qemu-guest-agent: freeze-hook to ignore dpkg files as well
[qemu/ar7.git] / monitor.c
blob94f673511b95198e584ca9fe37b63f87bb97349c
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.
25 #include "qemu/osdep.h"
26 #include "qemu/units.h"
27 #include <dirent.h>
28 #include "cpu.h"
29 #include "hw/hw.h"
30 #include "monitor/qdev.h"
31 #include "hw/usb.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 "chardev/char-fe.h"
39 #include "chardev/char-io.h"
40 #include "chardev/char-mux.h"
41 #include "ui/qemu-spice.h"
42 #include "sysemu/numa.h"
43 #include "monitor/monitor.h"
44 #include "qemu/config-file.h"
45 #include "qemu/readline.h"
46 #include "ui/console.h"
47 #include "ui/input.h"
48 #include "sysemu/block-backend.h"
49 #include "audio/audio.h"
50 #include "disas/disas.h"
51 #include "sysemu/balloon.h"
52 #include "qemu/timer.h"
53 #include "sysemu/hw_accel.h"
54 #include "qemu/acl.h"
55 #include "sysemu/tpm.h"
56 #include "qapi/qmp/qdict.h"
57 #include "qapi/qmp/qerror.h"
58 #include "qapi/qmp/qnum.h"
59 #include "qapi/qmp/qstring.h"
60 #include "qapi/qmp/qjson.h"
61 #include "qapi/qmp/json-streamer.h"
62 #include "qapi/qmp/json-parser.h"
63 #include "qapi/qmp/qlist.h"
64 #include "qom/object_interfaces.h"
65 #include "trace-root.h"
66 #include "trace/control.h"
67 #include "monitor/hmp-target.h"
68 #ifdef CONFIG_TRACE_SIMPLE
69 #include "trace/simple.h"
70 #endif
71 #include "exec/memory.h"
72 #include "exec/exec-all.h"
73 #include "qemu/log.h"
74 #include "qemu/option.h"
75 #include "hmp.h"
76 #include "qemu/thread.h"
77 #include "block/qapi.h"
78 #include "qapi/qapi-commands.h"
79 #include "qapi/qapi-events.h"
80 #include "qapi/error.h"
81 #include "qapi/qmp-event.h"
82 #include "qapi/qapi-introspect.h"
83 #include "sysemu/qtest.h"
84 #include "sysemu/cpus.h"
85 #include "sysemu/iothread.h"
86 #include "qemu/cutils.h"
88 #if defined(TARGET_S390X)
89 #include "hw/s390x/storage-keys.h"
90 #include "hw/s390x/storage-attributes.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 const char *flags; /* p=preconfig */
133 void (*cmd)(Monitor *mon, const QDict *qdict);
134 /* @sub_table is a list of 2nd level of commands. If it does not exist,
135 * cmd should be used. If it exists, sub_table[?].cmd should be
136 * used, and cmd of 1st level plays the role of help function.
138 struct mon_cmd_t *sub_table;
139 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
140 } mon_cmd_t;
142 /* file descriptors passed via SCM_RIGHTS */
143 typedef struct mon_fd_t mon_fd_t;
144 struct mon_fd_t {
145 char *name;
146 int fd;
147 QLIST_ENTRY(mon_fd_t) next;
150 /* file descriptor associated with a file descriptor set */
151 typedef struct MonFdsetFd MonFdsetFd;
152 struct MonFdsetFd {
153 int fd;
154 bool removed;
155 char *opaque;
156 QLIST_ENTRY(MonFdsetFd) next;
159 /* file descriptor set containing fds passed via SCM_RIGHTS */
160 typedef struct MonFdset MonFdset;
161 struct MonFdset {
162 int64_t id;
163 QLIST_HEAD(, MonFdsetFd) fds;
164 QLIST_HEAD(, MonFdsetFd) dup_fds;
165 QLIST_ENTRY(MonFdset) next;
168 typedef struct {
169 JSONMessageParser parser;
171 * When a client connects, we're in capabilities negotiation mode.
172 * @commands is &qmp_cap_negotiation_commands then. When command
173 * qmp_capabilities succeeds, we go into command mode, and
174 * @command becomes &qmp_commands.
176 QmpCommandList *commands;
177 bool capab_offered[QMP_CAPABILITY__MAX]; /* capabilities offered */
178 bool capab[QMP_CAPABILITY__MAX]; /* offered and accepted */
180 * Protects qmp request/response queue.
181 * Take monitor_lock first when you need both.
183 QemuMutex qmp_queue_lock;
184 /* Input queue that holds all the parsed QMP requests */
185 GQueue *qmp_requests;
186 /* Output queue contains all the QMP responses in order */
187 GQueue *qmp_responses;
188 } MonitorQMP;
191 * To prevent flooding clients, events can be throttled. The
192 * throttling is calculated globally, rather than per-Monitor
193 * instance.
195 typedef struct MonitorQAPIEventState {
196 QAPIEvent event; /* Throttling state for this event type and... */
197 QDict *data; /* ... data, see qapi_event_throttle_equal() */
198 QEMUTimer *timer; /* Timer for handling delayed events */
199 QDict *qdict; /* Delayed event (if any) */
200 } MonitorQAPIEventState;
202 typedef struct {
203 int64_t rate; /* Minimum time (in ns) between two events */
204 } MonitorQAPIEventConf;
206 struct Monitor {
207 CharBackend chr;
208 int reset_seen;
209 int flags;
210 int suspend_cnt; /* Needs to be accessed atomically */
211 bool skip_flush;
212 bool use_io_thread;
215 * State used only in the thread "owning" the monitor.
216 * If @use_io_thread, this is @mon_iothread.
217 * Else, it's the main thread.
218 * These members can be safely accessed without locks.
220 ReadLineState *rs;
222 MonitorQMP qmp;
223 gchar *mon_cpu_path;
224 BlockCompletionFunc *password_completion_cb;
225 void *password_opaque;
226 mon_cmd_t *cmd_table;
227 QTAILQ_ENTRY(Monitor) entry;
230 * The per-monitor lock. We can't access guest memory when holding
231 * the lock.
233 QemuMutex mon_lock;
236 * Members that are protected by the per-monitor lock
238 QLIST_HEAD(, mon_fd_t) fds;
239 QString *outbuf;
240 guint out_watch;
241 /* Read under either BQL or mon_lock, written with BQL+mon_lock. */
242 int mux_out;
245 /* Shared monitor I/O thread */
246 IOThread *mon_iothread;
248 /* Bottom half to dispatch the requests received from I/O thread */
249 QEMUBH *qmp_dispatcher_bh;
251 /* Bottom half to deliver the responses back to clients */
252 QEMUBH *qmp_respond_bh;
254 struct QMPRequest {
255 /* Owner of the request */
256 Monitor *mon;
257 /* "id" field of the request */
258 QObject *id;
260 * Request object to be handled or Error to be reported
261 * (exactly one of them is non-null)
263 QObject *req;
264 Error *err;
266 * Whether we need to resume the monitor afterward. This flag is
267 * used to emulate the old QMP server behavior that the current
268 * command must be completed before execution of the next one.
270 bool need_resume;
272 typedef struct QMPRequest QMPRequest;
274 /* QMP checker flags */
275 #define QMP_ACCEPT_UNKNOWNS 1
277 /* Protects mon_list, monitor_qapi_event_state. */
278 static QemuMutex monitor_lock;
279 static GHashTable *monitor_qapi_event_state;
280 static QTAILQ_HEAD(mon_list, Monitor) mon_list;
282 /* Protects mon_fdsets */
283 static QemuMutex mon_fdsets_lock;
284 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
286 static int mon_refcount;
288 static mon_cmd_t mon_cmds[];
289 static mon_cmd_t info_cmds[];
291 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
293 __thread Monitor *cur_mon;
295 static void monitor_command_cb(void *opaque, const char *cmdline,
296 void *readline_opaque);
299 * Is @mon a QMP monitor?
301 static inline bool monitor_is_qmp(const Monitor *mon)
303 return (mon->flags & MONITOR_USE_CONTROL);
307 * Is @mon is using readline?
308 * Note: not all HMP monitors use readline, e.g., gdbserver has a
309 * non-interactive HMP monitor, so readline is not used there.
311 static inline bool monitor_uses_readline(const Monitor *mon)
313 return mon->flags & MONITOR_USE_READLINE;
316 static inline bool monitor_is_hmp_non_interactive(const Monitor *mon)
318 return !monitor_is_qmp(mon) && !monitor_uses_readline(mon);
322 * Return the clock to use for recording an event's time.
323 * It's QEMU_CLOCK_REALTIME, except for qtests it's
324 * QEMU_CLOCK_VIRTUAL, to support testing rate limits.
325 * Beware: result is invalid before configure_accelerator().
327 static inline QEMUClockType monitor_get_event_clock(void)
329 return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME;
333 * Is the current monitor, if any, a QMP monitor?
335 bool monitor_cur_is_qmp(void)
337 return cur_mon && monitor_is_qmp(cur_mon);
340 void monitor_read_command(Monitor *mon, int show_prompt)
342 if (!mon->rs)
343 return;
345 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
346 if (show_prompt)
347 readline_show_prompt(mon->rs);
350 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
351 void *opaque)
353 if (mon->rs) {
354 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
355 /* prompt is printed on return from the command handler */
356 return 0;
357 } else {
358 monitor_printf(mon, "terminal does not support password prompting\n");
359 return -ENOTTY;
363 static void qmp_request_free(QMPRequest *req)
365 qobject_unref(req->id);
366 qobject_unref(req->req);
367 error_free(req->err);
368 g_free(req);
371 /* Caller must hold mon->qmp.qmp_queue_lock */
372 static void monitor_qmp_cleanup_req_queue_locked(Monitor *mon)
374 while (!g_queue_is_empty(mon->qmp.qmp_requests)) {
375 qmp_request_free(g_queue_pop_head(mon->qmp.qmp_requests));
379 /* Caller must hold the mon->qmp.qmp_queue_lock */
380 static void monitor_qmp_cleanup_resp_queue_locked(Monitor *mon)
382 while (!g_queue_is_empty(mon->qmp.qmp_responses)) {
383 qobject_unref((QDict *)g_queue_pop_head(mon->qmp.qmp_responses));
387 static void monitor_qmp_cleanup_queues(Monitor *mon)
389 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
390 monitor_qmp_cleanup_req_queue_locked(mon);
391 monitor_qmp_cleanup_resp_queue_locked(mon);
392 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
396 static void monitor_flush_locked(Monitor *mon);
398 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
399 void *opaque)
401 Monitor *mon = opaque;
403 qemu_mutex_lock(&mon->mon_lock);
404 mon->out_watch = 0;
405 monitor_flush_locked(mon);
406 qemu_mutex_unlock(&mon->mon_lock);
407 return FALSE;
410 /* Caller must hold mon->mon_lock */
411 static void monitor_flush_locked(Monitor *mon)
413 int rc;
414 size_t len;
415 const char *buf;
417 if (mon->skip_flush) {
418 return;
421 buf = qstring_get_str(mon->outbuf);
422 len = qstring_get_length(mon->outbuf);
424 if (len && !mon->mux_out) {
425 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
426 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
427 /* all flushed or error */
428 qobject_unref(mon->outbuf);
429 mon->outbuf = qstring_new();
430 return;
432 if (rc > 0) {
433 /* partial write */
434 QString *tmp = qstring_from_str(buf + rc);
435 qobject_unref(mon->outbuf);
436 mon->outbuf = tmp;
438 if (mon->out_watch == 0) {
439 mon->out_watch =
440 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
441 monitor_unblocked, mon);
446 void monitor_flush(Monitor *mon)
448 qemu_mutex_lock(&mon->mon_lock);
449 monitor_flush_locked(mon);
450 qemu_mutex_unlock(&mon->mon_lock);
453 /* flush at every end of line */
454 static void monitor_puts(Monitor *mon, const char *str)
456 char c;
458 qemu_mutex_lock(&mon->mon_lock);
459 for(;;) {
460 c = *str++;
461 if (c == '\0')
462 break;
463 if (c == '\n') {
464 qstring_append_chr(mon->outbuf, '\r');
466 qstring_append_chr(mon->outbuf, c);
467 if (c == '\n') {
468 monitor_flush_locked(mon);
471 qemu_mutex_unlock(&mon->mon_lock);
474 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
476 char *buf;
478 if (!mon)
479 return;
481 if (monitor_is_qmp(mon)) {
482 return;
485 buf = g_strdup_vprintf(fmt, ap);
486 monitor_puts(mon, buf);
487 g_free(buf);
490 void monitor_printf(Monitor *mon, const char *fmt, ...)
492 va_list ap;
493 va_start(ap, fmt);
494 monitor_vprintf(mon, fmt, ap);
495 va_end(ap);
498 int monitor_fprintf(FILE *stream, const char *fmt, ...)
500 va_list ap;
501 va_start(ap, fmt);
502 monitor_vprintf((Monitor *)stream, fmt, ap);
503 va_end(ap);
504 return 0;
507 static void qmp_send_response(Monitor *mon, QDict *rsp)
509 QObject *data = QOBJECT(rsp);
510 QString *json;
512 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
513 qobject_to_json(data);
514 assert(json != NULL);
516 qstring_append_chr(json, '\n');
517 monitor_puts(mon, qstring_get_str(json));
519 qobject_unref(json);
522 static void qmp_queue_response(Monitor *mon, QDict *rsp)
524 if (mon->use_io_thread) {
526 * Push a reference to the response queue. The I/O thread
527 * drains that queue and emits.
529 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
530 g_queue_push_tail(mon->qmp.qmp_responses, qobject_ref(rsp));
531 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
532 qemu_bh_schedule(qmp_respond_bh);
533 } else {
535 * Not using monitor I/O thread, i.e. we are in the main thread.
536 * Emit right away.
538 qmp_send_response(mon, rsp);
542 struct QMPResponse {
543 Monitor *mon;
544 QDict *data;
546 typedef struct QMPResponse QMPResponse;
548 static QDict *monitor_qmp_response_pop_one(Monitor *mon)
550 QDict *data;
552 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
553 data = g_queue_pop_head(mon->qmp.qmp_responses);
554 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
556 return data;
559 static void monitor_qmp_response_flush(Monitor *mon)
561 QDict *data;
563 while ((data = monitor_qmp_response_pop_one(mon))) {
564 qmp_send_response(mon, data);
565 qobject_unref(data);
570 * Pop a QMPResponse from any monitor's response queue into @response.
571 * Return false if all the queues are empty; else true.
573 static bool monitor_qmp_response_pop_any(QMPResponse *response)
575 Monitor *mon;
576 QDict *data = NULL;
578 qemu_mutex_lock(&monitor_lock);
579 QTAILQ_FOREACH(mon, &mon_list, entry) {
580 data = monitor_qmp_response_pop_one(mon);
581 if (data) {
582 response->mon = mon;
583 response->data = data;
584 break;
587 qemu_mutex_unlock(&monitor_lock);
588 return data != NULL;
591 static void monitor_qmp_bh_responder(void *opaque)
593 QMPResponse response;
595 while (monitor_qmp_response_pop_any(&response)) {
596 qmp_send_response(response.mon, response.data);
597 qobject_unref(response.data);
601 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
602 /* Limit guest-triggerable events to 1 per second */
603 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
604 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
605 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
606 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
607 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
608 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
612 * Broadcast an event to all monitors.
613 * @qdict is the event object. Its member "event" must match @event.
614 * Caller must hold monitor_lock.
616 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
618 Monitor *mon;
620 trace_monitor_protocol_event_emit(event, qdict);
621 QTAILQ_FOREACH(mon, &mon_list, entry) {
622 if (monitor_is_qmp(mon)
623 && mon->qmp.commands != &qmp_cap_negotiation_commands) {
624 qmp_queue_response(mon, qdict);
629 static void monitor_qapi_event_handler(void *opaque);
632 * Queue a new event for emission to Monitor instances,
633 * applying any rate limiting if required.
635 static void
636 monitor_qapi_event_queue_no_reenter(QAPIEvent event, QDict *qdict)
638 MonitorQAPIEventConf *evconf;
639 MonitorQAPIEventState *evstate;
641 assert(event < QAPI_EVENT__MAX);
642 evconf = &monitor_qapi_event_conf[event];
643 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
645 qemu_mutex_lock(&monitor_lock);
647 if (!evconf->rate) {
648 /* Unthrottled event */
649 monitor_qapi_event_emit(event, qdict);
650 } else {
651 QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
652 MonitorQAPIEventState key = { .event = event, .data = data };
654 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
655 assert(!evstate || timer_pending(evstate->timer));
657 if (evstate) {
659 * Timer is pending for (at least) evconf->rate ns after
660 * last send. Store event for sending when timer fires,
661 * replacing a prior stored event if any.
663 qobject_unref(evstate->qdict);
664 evstate->qdict = qobject_ref(qdict);
665 } else {
667 * Last send was (at least) evconf->rate ns ago.
668 * Send immediately, and arm the timer to call
669 * monitor_qapi_event_handler() in evconf->rate ns. Any
670 * events arriving before then will be delayed until then.
672 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
674 monitor_qapi_event_emit(event, qdict);
676 evstate = g_new(MonitorQAPIEventState, 1);
677 evstate->event = event;
678 evstate->data = qobject_ref(data);
679 evstate->qdict = NULL;
680 evstate->timer = timer_new_ns(monitor_get_event_clock(),
681 monitor_qapi_event_handler,
682 evstate);
683 g_hash_table_add(monitor_qapi_event_state, evstate);
684 timer_mod_ns(evstate->timer, now + evconf->rate);
688 qemu_mutex_unlock(&monitor_lock);
691 static void
692 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
695 * monitor_qapi_event_queue_no_reenter() is not reentrant: it
696 * would deadlock on monitor_lock. Work around by queueing
697 * events in thread-local storage.
698 * TODO: remove this, make it re-enter safe.
700 typedef struct MonitorQapiEvent {
701 QAPIEvent event;
702 QDict *qdict;
703 QSIMPLEQ_ENTRY(MonitorQapiEvent) entry;
704 } MonitorQapiEvent;
705 static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue;
706 static __thread bool reentered;
707 MonitorQapiEvent *ev;
709 if (!reentered) {
710 QSIMPLEQ_INIT(&event_queue);
713 ev = g_new(MonitorQapiEvent, 1);
714 ev->qdict = qobject_ref(qdict);
715 ev->event = event;
716 QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry);
717 if (reentered) {
718 return;
721 reentered = true;
723 while ((ev = QSIMPLEQ_FIRST(&event_queue)) != NULL) {
724 QSIMPLEQ_REMOVE_HEAD(&event_queue, entry);
725 monitor_qapi_event_queue_no_reenter(ev->event, ev->qdict);
726 qobject_unref(ev->qdict);
727 g_free(ev);
730 reentered = false;
734 * This function runs evconf->rate ns after sending a throttled
735 * event.
736 * If another event has since been stored, send it.
738 static void monitor_qapi_event_handler(void *opaque)
740 MonitorQAPIEventState *evstate = opaque;
741 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
743 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
744 qemu_mutex_lock(&monitor_lock);
746 if (evstate->qdict) {
747 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
749 monitor_qapi_event_emit(evstate->event, evstate->qdict);
750 qobject_unref(evstate->qdict);
751 evstate->qdict = NULL;
752 timer_mod_ns(evstate->timer, now + evconf->rate);
753 } else {
754 g_hash_table_remove(monitor_qapi_event_state, evstate);
755 qobject_unref(evstate->data);
756 timer_free(evstate->timer);
757 g_free(evstate);
760 qemu_mutex_unlock(&monitor_lock);
763 static unsigned int qapi_event_throttle_hash(const void *key)
765 const MonitorQAPIEventState *evstate = key;
766 unsigned int hash = evstate->event * 255;
768 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
769 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
772 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
773 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
776 return hash;
779 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
781 const MonitorQAPIEventState *eva = a;
782 const MonitorQAPIEventState *evb = b;
784 if (eva->event != evb->event) {
785 return FALSE;
788 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
789 return !strcmp(qdict_get_str(eva->data, "id"),
790 qdict_get_str(evb->data, "id"));
793 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
794 return !strcmp(qdict_get_str(eva->data, "node-name"),
795 qdict_get_str(evb->data, "node-name"));
798 return TRUE;
801 static void monitor_qapi_event_init(void)
803 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
804 qapi_event_throttle_equal);
805 qmp_event_set_func_emit(monitor_qapi_event_queue);
808 static void handle_hmp_command(Monitor *mon, const char *cmdline);
810 static void monitor_data_init(Monitor *mon, bool skip_flush,
811 bool use_io_thread)
813 memset(mon, 0, sizeof(Monitor));
814 qemu_mutex_init(&mon->mon_lock);
815 qemu_mutex_init(&mon->qmp.qmp_queue_lock);
816 mon->outbuf = qstring_new();
817 /* Use *mon_cmds by default. */
818 mon->cmd_table = mon_cmds;
819 mon->skip_flush = skip_flush;
820 mon->use_io_thread = use_io_thread;
821 mon->qmp.qmp_requests = g_queue_new();
822 mon->qmp.qmp_responses = g_queue_new();
825 static void monitor_data_destroy(Monitor *mon)
827 g_free(mon->mon_cpu_path);
828 qemu_chr_fe_deinit(&mon->chr, false);
829 if (monitor_is_qmp(mon)) {
830 json_message_parser_destroy(&mon->qmp.parser);
832 readline_free(mon->rs);
833 qobject_unref(mon->outbuf);
834 qemu_mutex_destroy(&mon->mon_lock);
835 qemu_mutex_destroy(&mon->qmp.qmp_queue_lock);
836 monitor_qmp_cleanup_req_queue_locked(mon);
837 monitor_qmp_cleanup_resp_queue_locked(mon);
838 g_queue_free(mon->qmp.qmp_requests);
839 g_queue_free(mon->qmp.qmp_responses);
842 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
843 int64_t cpu_index, Error **errp)
845 char *output = NULL;
846 Monitor *old_mon, hmp;
848 monitor_data_init(&hmp, true, false);
850 old_mon = cur_mon;
851 cur_mon = &hmp;
853 if (has_cpu_index) {
854 int ret = monitor_set_cpu(cpu_index);
855 if (ret < 0) {
856 cur_mon = old_mon;
857 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
858 "a CPU number");
859 goto out;
863 handle_hmp_command(&hmp, command_line);
864 cur_mon = old_mon;
866 qemu_mutex_lock(&hmp.mon_lock);
867 if (qstring_get_length(hmp.outbuf) > 0) {
868 output = g_strdup(qstring_get_str(hmp.outbuf));
869 } else {
870 output = g_strdup("");
872 qemu_mutex_unlock(&hmp.mon_lock);
874 out:
875 monitor_data_destroy(&hmp);
876 return output;
879 static int compare_cmd(const char *name, const char *list)
881 const char *p, *pstart;
882 int len;
883 len = strlen(name);
884 p = list;
885 for(;;) {
886 pstart = p;
887 p = qemu_strchrnul(p, '|');
888 if ((p - pstart) == len && !memcmp(pstart, name, len))
889 return 1;
890 if (*p == '\0')
891 break;
892 p++;
894 return 0;
897 static int get_str(char *buf, int buf_size, const char **pp)
899 const char *p;
900 char *q;
901 int c;
903 q = buf;
904 p = *pp;
905 while (qemu_isspace(*p)) {
906 p++;
908 if (*p == '\0') {
909 fail:
910 *q = '\0';
911 *pp = p;
912 return -1;
914 if (*p == '\"') {
915 p++;
916 while (*p != '\0' && *p != '\"') {
917 if (*p == '\\') {
918 p++;
919 c = *p++;
920 switch (c) {
921 case 'n':
922 c = '\n';
923 break;
924 case 'r':
925 c = '\r';
926 break;
927 case '\\':
928 case '\'':
929 case '\"':
930 break;
931 default:
932 printf("unsupported escape code: '\\%c'\n", c);
933 goto fail;
935 if ((q - buf) < buf_size - 1) {
936 *q++ = c;
938 } else {
939 if ((q - buf) < buf_size - 1) {
940 *q++ = *p;
942 p++;
945 if (*p != '\"') {
946 printf("unterminated string\n");
947 goto fail;
949 p++;
950 } else {
951 while (*p != '\0' && !qemu_isspace(*p)) {
952 if ((q - buf) < buf_size - 1) {
953 *q++ = *p;
955 p++;
958 *q = '\0';
959 *pp = p;
960 return 0;
963 #define MAX_ARGS 16
965 static void free_cmdline_args(char **args, int nb_args)
967 int i;
969 assert(nb_args <= MAX_ARGS);
971 for (i = 0; i < nb_args; i++) {
972 g_free(args[i]);
978 * Parse the command line to get valid args.
979 * @cmdline: command line to be parsed.
980 * @pnb_args: location to store the number of args, must NOT be NULL.
981 * @args: location to store the args, which should be freed by caller, must
982 * NOT be NULL.
984 * Returns 0 on success, negative on failure.
986 * NOTE: this parser is an approximate form of the real command parser. Number
987 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
988 * return with failure.
990 static int parse_cmdline(const char *cmdline,
991 int *pnb_args, char **args)
993 const char *p;
994 int nb_args, ret;
995 char buf[1024];
997 p = cmdline;
998 nb_args = 0;
999 for (;;) {
1000 while (qemu_isspace(*p)) {
1001 p++;
1003 if (*p == '\0') {
1004 break;
1006 if (nb_args >= MAX_ARGS) {
1007 goto fail;
1009 ret = get_str(buf, sizeof(buf), &p);
1010 if (ret < 0) {
1011 goto fail;
1013 args[nb_args] = g_strdup(buf);
1014 nb_args++;
1016 *pnb_args = nb_args;
1017 return 0;
1019 fail:
1020 free_cmdline_args(args, nb_args);
1021 return -1;
1025 * Can command @cmd be executed in preconfig state?
1027 static bool cmd_can_preconfig(const mon_cmd_t *cmd)
1029 if (!cmd->flags) {
1030 return false;
1033 return strchr(cmd->flags, 'p');
1036 static void help_cmd_dump_one(Monitor *mon,
1037 const mon_cmd_t *cmd,
1038 char **prefix_args,
1039 int prefix_args_nb)
1041 int i;
1043 if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
1044 return;
1047 for (i = 0; i < prefix_args_nb; i++) {
1048 monitor_printf(mon, "%s ", prefix_args[i]);
1050 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
1053 /* @args[@arg_index] is the valid command need to find in @cmds */
1054 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
1055 char **args, int nb_args, int arg_index)
1057 const mon_cmd_t *cmd;
1059 /* No valid arg need to compare with, dump all in *cmds */
1060 if (arg_index >= nb_args) {
1061 for (cmd = cmds; cmd->name != NULL; cmd++) {
1062 help_cmd_dump_one(mon, cmd, args, arg_index);
1064 return;
1067 /* Find one entry to dump */
1068 for (cmd = cmds; cmd->name != NULL; cmd++) {
1069 if (compare_cmd(args[arg_index], cmd->name) &&
1070 ((!runstate_check(RUN_STATE_PRECONFIG) ||
1071 cmd_can_preconfig(cmd)))) {
1072 if (cmd->sub_table) {
1073 /* continue with next arg */
1074 help_cmd_dump(mon, cmd->sub_table,
1075 args, nb_args, arg_index + 1);
1076 } else {
1077 help_cmd_dump_one(mon, cmd, args, arg_index);
1079 break;
1084 static void help_cmd(Monitor *mon, const char *name)
1086 char *args[MAX_ARGS];
1087 int nb_args = 0;
1089 /* 1. parse user input */
1090 if (name) {
1091 /* special case for log, directly dump and return */
1092 if (!strcmp(name, "log")) {
1093 const QEMULogItem *item;
1094 monitor_printf(mon, "Log items (comma separated):\n");
1095 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
1096 for (item = qemu_log_items; item->mask != 0; item++) {
1097 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
1099 return;
1102 if (parse_cmdline(name, &nb_args, args) < 0) {
1103 return;
1107 /* 2. dump the contents according to parsed args */
1108 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
1110 free_cmdline_args(args, nb_args);
1113 static void do_help_cmd(Monitor *mon, const QDict *qdict)
1115 help_cmd(mon, qdict_get_try_str(qdict, "name"));
1118 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
1120 const char *tp_name = qdict_get_str(qdict, "name");
1121 bool new_state = qdict_get_bool(qdict, "option");
1122 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1123 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1124 Error *local_err = NULL;
1126 if (vcpu < 0) {
1127 monitor_printf(mon, "argument vcpu must be positive");
1128 return;
1131 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
1132 if (local_err) {
1133 error_report_err(local_err);
1137 #ifdef CONFIG_TRACE_SIMPLE
1138 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
1140 const char *op = qdict_get_try_str(qdict, "op");
1141 const char *arg = qdict_get_try_str(qdict, "arg");
1143 if (!op) {
1144 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
1145 } else if (!strcmp(op, "on")) {
1146 st_set_trace_file_enabled(true);
1147 } else if (!strcmp(op, "off")) {
1148 st_set_trace_file_enabled(false);
1149 } else if (!strcmp(op, "flush")) {
1150 st_flush_trace_buffer();
1151 } else if (!strcmp(op, "set")) {
1152 if (arg) {
1153 st_set_trace_file(arg);
1155 } else {
1156 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
1157 help_cmd(mon, "trace-file");
1160 #endif
1162 static void hmp_info_help(Monitor *mon, const QDict *qdict)
1164 help_cmd(mon, "info");
1167 static void query_commands_cb(QmpCommand *cmd, void *opaque)
1169 CommandInfoList *info, **list = opaque;
1171 if (!cmd->enabled) {
1172 return;
1175 info = g_malloc0(sizeof(*info));
1176 info->value = g_malloc0(sizeof(*info->value));
1177 info->value->name = g_strdup(cmd->name);
1178 info->next = *list;
1179 *list = info;
1182 CommandInfoList *qmp_query_commands(Error **errp)
1184 CommandInfoList *list = NULL;
1186 qmp_for_each_command(cur_mon->qmp.commands, query_commands_cb, &list);
1188 return list;
1191 EventInfoList *qmp_query_events(Error **errp)
1193 EventInfoList *info, *ev_list = NULL;
1194 QAPIEvent e;
1196 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
1197 const char *event_name = QAPIEvent_str(e);
1198 assert(event_name != NULL);
1199 info = g_malloc0(sizeof(*info));
1200 info->value = g_malloc0(sizeof(*info->value));
1201 info->value->name = g_strdup(event_name);
1203 info->next = ev_list;
1204 ev_list = info;
1207 return ev_list;
1211 * Minor hack: generated marshalling suppressed for this command
1212 * ('gen': false in the schema) so we can parse the JSON string
1213 * directly into QObject instead of first parsing it with
1214 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
1215 * to QObject with generated output marshallers, every time. Instead,
1216 * we do it in test-qobject-input-visitor.c, just to make sure
1217 * qapi-gen.py's output actually conforms to the schema.
1219 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
1220 Error **errp)
1222 *ret_data = qobject_from_qlit(&qmp_schema_qlit);
1226 * We used to define commands in qmp-commands.hx in addition to the
1227 * QAPI schema. This permitted defining some of them only in certain
1228 * configurations. query-commands has always reflected that (good,
1229 * because it lets QMP clients figure out what's actually available),
1230 * while query-qmp-schema never did (not so good). This function is a
1231 * hack to keep the configuration-specific commands defined exactly as
1232 * before, even though qmp-commands.hx is gone.
1234 * FIXME Educate the QAPI schema on configuration-specific commands,
1235 * and drop this hack.
1237 static void qmp_unregister_commands_hack(void)
1239 #ifndef CONFIG_REPLICATION
1240 qmp_unregister_command(&qmp_commands, "xen-set-replication");
1241 qmp_unregister_command(&qmp_commands, "query-xen-replication-status");
1242 qmp_unregister_command(&qmp_commands, "xen-colo-do-checkpoint");
1243 #endif
1244 #ifndef TARGET_I386
1245 qmp_unregister_command(&qmp_commands, "rtc-reset-reinjection");
1246 qmp_unregister_command(&qmp_commands, "query-sev");
1247 qmp_unregister_command(&qmp_commands, "query-sev-launch-measure");
1248 qmp_unregister_command(&qmp_commands, "query-sev-capabilities");
1249 #endif
1250 #ifndef TARGET_S390X
1251 qmp_unregister_command(&qmp_commands, "dump-skeys");
1252 #endif
1253 #ifndef TARGET_ARM
1254 qmp_unregister_command(&qmp_commands, "query-gic-capabilities");
1255 #endif
1256 #if !defined(TARGET_S390X) && !defined(TARGET_I386)
1257 qmp_unregister_command(&qmp_commands, "query-cpu-model-expansion");
1258 #endif
1259 #if !defined(TARGET_S390X)
1260 qmp_unregister_command(&qmp_commands, "query-cpu-model-baseline");
1261 qmp_unregister_command(&qmp_commands, "query-cpu-model-comparison");
1262 #endif
1263 #if !defined(TARGET_PPC) && !defined(TARGET_ARM) && !defined(TARGET_I386) \
1264 && !defined(TARGET_S390X)
1265 qmp_unregister_command(&qmp_commands, "query-cpu-definitions");
1266 #endif
1269 static void monitor_init_qmp_commands(void)
1272 * Two command lists:
1273 * - qmp_commands contains all QMP commands
1274 * - qmp_cap_negotiation_commands contains just
1275 * "qmp_capabilities", to enforce capability negotiation
1278 qmp_init_marshal(&qmp_commands);
1280 qmp_register_command(&qmp_commands, "query-qmp-schema",
1281 qmp_query_qmp_schema, QCO_ALLOW_PRECONFIG);
1282 qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
1283 QCO_NO_OPTIONS);
1284 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1285 QCO_NO_OPTIONS);
1287 qmp_unregister_commands_hack();
1289 QTAILQ_INIT(&qmp_cap_negotiation_commands);
1290 qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
1291 qmp_marshal_qmp_capabilities, QCO_ALLOW_PRECONFIG);
1294 static bool qmp_oob_enabled(Monitor *mon)
1296 return mon->qmp.capab[QMP_CAPABILITY_OOB];
1299 static void monitor_qmp_caps_reset(Monitor *mon)
1301 memset(mon->qmp.capab_offered, 0, sizeof(mon->qmp.capab_offered));
1302 memset(mon->qmp.capab, 0, sizeof(mon->qmp.capab));
1303 mon->qmp.capab_offered[QMP_CAPABILITY_OOB] = mon->use_io_thread;
1307 * Accept QMP capabilities in @list for @mon.
1308 * On success, set mon->qmp.capab[], and return true.
1309 * On error, set @errp, and return false.
1311 static bool qmp_caps_accept(Monitor *mon, QMPCapabilityList *list,
1312 Error **errp)
1314 GString *unavailable = NULL;
1315 bool capab[QMP_CAPABILITY__MAX];
1317 memset(capab, 0, sizeof(capab));
1319 for (; list; list = list->next) {
1320 if (!mon->qmp.capab_offered[list->value]) {
1321 if (!unavailable) {
1322 unavailable = g_string_new(QMPCapability_str(list->value));
1323 } else {
1324 g_string_append_printf(unavailable, ", %s",
1325 QMPCapability_str(list->value));
1328 capab[list->value] = true;
1331 if (unavailable) {
1332 error_setg(errp, "Capability %s not available", unavailable->str);
1333 g_string_free(unavailable, true);
1334 return false;
1337 memcpy(mon->qmp.capab, capab, sizeof(capab));
1338 return true;
1341 void qmp_qmp_capabilities(bool has_enable, QMPCapabilityList *enable,
1342 Error **errp)
1344 if (cur_mon->qmp.commands == &qmp_commands) {
1345 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1346 "Capabilities negotiation is already complete, command "
1347 "ignored");
1348 return;
1351 if (!qmp_caps_accept(cur_mon, enable, errp)) {
1352 return;
1355 cur_mon->qmp.commands = &qmp_commands;
1358 /* Set the current CPU defined by the user. Callers must hold BQL. */
1359 int monitor_set_cpu(int cpu_index)
1361 CPUState *cpu;
1363 cpu = qemu_get_cpu(cpu_index);
1364 if (cpu == NULL) {
1365 return -1;
1367 g_free(cur_mon->mon_cpu_path);
1368 cur_mon->mon_cpu_path = object_get_canonical_path(OBJECT(cpu));
1369 return 0;
1372 /* Callers must hold BQL. */
1373 static CPUState *mon_get_cpu_sync(bool synchronize)
1375 CPUState *cpu;
1377 if (cur_mon->mon_cpu_path) {
1378 cpu = (CPUState *) object_resolve_path_type(cur_mon->mon_cpu_path,
1379 TYPE_CPU, NULL);
1380 if (!cpu) {
1381 g_free(cur_mon->mon_cpu_path);
1382 cur_mon->mon_cpu_path = NULL;
1385 if (!cur_mon->mon_cpu_path) {
1386 if (!first_cpu) {
1387 return NULL;
1389 monitor_set_cpu(first_cpu->cpu_index);
1390 cpu = first_cpu;
1392 if (synchronize) {
1393 cpu_synchronize_state(cpu);
1395 return cpu;
1398 CPUState *mon_get_cpu(void)
1400 return mon_get_cpu_sync(true);
1403 CPUArchState *mon_get_cpu_env(void)
1405 CPUState *cs = mon_get_cpu();
1407 return cs ? cs->env_ptr : NULL;
1410 int monitor_get_cpu_index(void)
1412 CPUState *cs = mon_get_cpu_sync(false);
1414 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1417 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1419 bool all_cpus = qdict_get_try_bool(qdict, "cpustate_all", false);
1420 CPUState *cs;
1422 if (all_cpus) {
1423 CPU_FOREACH(cs) {
1424 monitor_printf(mon, "\nCPU#%d\n", cs->cpu_index);
1425 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1427 } else {
1428 cs = mon_get_cpu();
1430 if (!cs) {
1431 monitor_printf(mon, "No CPU available\n");
1432 return;
1435 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1439 #ifdef CONFIG_TCG
1440 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1442 if (!tcg_enabled()) {
1443 error_report("JIT information is only available with accel=tcg");
1444 return;
1447 dump_exec_info((FILE *)mon, monitor_fprintf);
1448 dump_drift_info((FILE *)mon, monitor_fprintf);
1451 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1453 dump_opcount_info((FILE *)mon, monitor_fprintf);
1455 #endif
1457 static void hmp_info_sync_profile(Monitor *mon, const QDict *qdict)
1459 int64_t max = qdict_get_try_int(qdict, "max", 10);
1460 bool mean = qdict_get_try_bool(qdict, "mean", false);
1461 bool coalesce = !qdict_get_try_bool(qdict, "no_coalesce", false);
1462 enum QSPSortBy sort_by;
1464 sort_by = mean ? QSP_SORT_BY_AVG_WAIT_TIME : QSP_SORT_BY_TOTAL_WAIT_TIME;
1465 qsp_report((FILE *)mon, monitor_fprintf, max, sort_by, coalesce);
1468 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1470 int i;
1471 const char *str;
1473 if (!mon->rs)
1474 return;
1475 i = 0;
1476 for(;;) {
1477 str = readline_get_history(mon->rs, i);
1478 if (!str)
1479 break;
1480 monitor_printf(mon, "%d: '%s'\n", i, str);
1481 i++;
1485 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1487 CPUState *cs = mon_get_cpu();
1489 if (!cs) {
1490 monitor_printf(mon, "No CPU available\n");
1491 return;
1493 cpu_dump_statistics(cs, (FILE *)mon, &monitor_fprintf, 0);
1496 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1498 const char *name = qdict_get_try_str(qdict, "name");
1499 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1500 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1501 TraceEventInfoList *events;
1502 TraceEventInfoList *elem;
1503 Error *local_err = NULL;
1505 if (name == NULL) {
1506 name = "*";
1508 if (vcpu < 0) {
1509 monitor_printf(mon, "argument vcpu must be positive");
1510 return;
1513 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1514 if (local_err) {
1515 error_report_err(local_err);
1516 return;
1519 for (elem = events; elem != NULL; elem = elem->next) {
1520 monitor_printf(mon, "%s : state %u\n",
1521 elem->value->name,
1522 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1524 qapi_free_TraceEventInfoList(events);
1527 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1528 bool has_port, int64_t port,
1529 bool has_tls_port, int64_t tls_port,
1530 bool has_cert_subject, const char *cert_subject,
1531 Error **errp)
1533 if (strcmp(protocol, "spice") == 0) {
1534 if (!qemu_using_spice(errp)) {
1535 return;
1538 if (!has_port && !has_tls_port) {
1539 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1540 return;
1543 if (qemu_spice_migrate_info(hostname,
1544 has_port ? port : -1,
1545 has_tls_port ? tls_port : -1,
1546 cert_subject)) {
1547 error_setg(errp, QERR_UNDEFINED_ERROR);
1548 return;
1550 return;
1553 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1556 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1558 Error *err = NULL;
1560 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1561 if (err) {
1562 error_report_err(err);
1566 static void hmp_log(Monitor *mon, const QDict *qdict)
1568 int mask;
1569 const char *items = qdict_get_str(qdict, "items");
1571 if (!strcmp(items, "none")) {
1572 mask = 0;
1573 } else {
1574 mask = qemu_str_to_log_mask(items);
1575 if (!mask) {
1576 help_cmd(mon, "log");
1577 return;
1580 qemu_set_log(mask);
1583 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1585 const char *option = qdict_get_try_str(qdict, "option");
1586 if (!option || !strcmp(option, "on")) {
1587 singlestep = 1;
1588 } else if (!strcmp(option, "off")) {
1589 singlestep = 0;
1590 } else {
1591 monitor_printf(mon, "unexpected option %s\n", option);
1595 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1597 const char *device = qdict_get_try_str(qdict, "device");
1598 if (!device)
1599 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1600 if (gdbserver_start(device) < 0) {
1601 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1602 device);
1603 } else if (strcmp(device, "none") == 0) {
1604 monitor_printf(mon, "Disabled gdbserver\n");
1605 } else {
1606 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1607 device);
1611 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1613 const char *action = qdict_get_str(qdict, "action");
1614 if (select_watchdog_action(action) == -1) {
1615 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1619 static void monitor_printc(Monitor *mon, int c)
1621 monitor_printf(mon, "'");
1622 switch(c) {
1623 case '\'':
1624 monitor_printf(mon, "\\'");
1625 break;
1626 case '\\':
1627 monitor_printf(mon, "\\\\");
1628 break;
1629 case '\n':
1630 monitor_printf(mon, "\\n");
1631 break;
1632 case '\r':
1633 monitor_printf(mon, "\\r");
1634 break;
1635 default:
1636 if (c >= 32 && c <= 126) {
1637 monitor_printf(mon, "%c", c);
1638 } else {
1639 monitor_printf(mon, "\\x%02x", c);
1641 break;
1643 monitor_printf(mon, "'");
1646 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1647 hwaddr addr, int is_physical)
1649 int l, line_size, i, max_digits, len;
1650 uint8_t buf[16];
1651 uint64_t v;
1652 CPUState *cs = mon_get_cpu();
1654 if (!cs && (format == 'i' || !is_physical)) {
1655 monitor_printf(mon, "Can not dump without CPU\n");
1656 return;
1659 if (format == 'i') {
1660 monitor_disas(mon, cs, addr, count, is_physical);
1661 return;
1664 len = wsize * count;
1665 if (wsize == 1)
1666 line_size = 8;
1667 else
1668 line_size = 16;
1669 max_digits = 0;
1671 switch(format) {
1672 case 'o':
1673 max_digits = DIV_ROUND_UP(wsize * 8, 3);
1674 break;
1675 default:
1676 case 'x':
1677 max_digits = (wsize * 8) / 4;
1678 break;
1679 case 'u':
1680 case 'd':
1681 max_digits = DIV_ROUND_UP(wsize * 8 * 10, 33);
1682 break;
1683 case 'c':
1684 wsize = 1;
1685 break;
1688 while (len > 0) {
1689 if (is_physical)
1690 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1691 else
1692 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1693 l = len;
1694 if (l > line_size)
1695 l = line_size;
1696 if (is_physical) {
1697 cpu_physical_memory_read(addr, buf, l);
1698 } else {
1699 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1700 monitor_printf(mon, " Cannot access memory\n");
1701 break;
1704 i = 0;
1705 while (i < l) {
1706 switch(wsize) {
1707 default:
1708 case 1:
1709 v = ldub_p(buf + i);
1710 break;
1711 case 2:
1712 v = lduw_p(buf + i);
1713 break;
1714 case 4:
1715 v = (uint32_t)ldl_p(buf + i);
1716 break;
1717 case 8:
1718 v = ldq_p(buf + i);
1719 break;
1721 monitor_printf(mon, " ");
1722 switch(format) {
1723 case 'o':
1724 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1725 break;
1726 case 'x':
1727 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1728 break;
1729 case 'u':
1730 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1731 break;
1732 case 'd':
1733 monitor_printf(mon, "%*" PRId64, max_digits, v);
1734 break;
1735 case 'c':
1736 monitor_printc(mon, v);
1737 break;
1739 i += wsize;
1741 monitor_printf(mon, "\n");
1742 addr += l;
1743 len -= l;
1747 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1749 int count = qdict_get_int(qdict, "count");
1750 int format = qdict_get_int(qdict, "format");
1751 int size = qdict_get_int(qdict, "size");
1752 target_long addr = qdict_get_int(qdict, "addr");
1754 memory_dump(mon, count, format, size, addr, 0);
1757 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1759 int count = qdict_get_int(qdict, "count");
1760 int format = qdict_get_int(qdict, "format");
1761 int size = qdict_get_int(qdict, "size");
1762 hwaddr addr = qdict_get_int(qdict, "addr");
1764 memory_dump(mon, count, format, size, addr, 1);
1767 static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
1769 MemoryRegionSection mrs = memory_region_find(get_system_memory(),
1770 addr, 1);
1772 if (!mrs.mr) {
1773 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1774 return NULL;
1777 if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
1778 error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
1779 memory_region_unref(mrs.mr);
1780 return NULL;
1783 *p_mr = mrs.mr;
1784 return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
1787 static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
1789 hwaddr addr = qdict_get_int(qdict, "addr");
1790 Error *local_err = NULL;
1791 MemoryRegion *mr = NULL;
1792 void *ptr;
1794 ptr = gpa2hva(&mr, addr, &local_err);
1795 if (local_err) {
1796 error_report_err(local_err);
1797 return;
1800 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1801 " (%s) is %p\n",
1802 addr, mr->name, ptr);
1804 memory_region_unref(mr);
1807 #ifdef CONFIG_LINUX
1808 static uint64_t vtop(void *ptr, Error **errp)
1810 uint64_t pinfo;
1811 uint64_t ret = -1;
1812 uintptr_t addr = (uintptr_t) ptr;
1813 uintptr_t pagesize = getpagesize();
1814 off_t offset = addr / pagesize * sizeof(pinfo);
1815 int fd;
1817 fd = open("/proc/self/pagemap", O_RDONLY);
1818 if (fd == -1) {
1819 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1820 return -1;
1823 /* Force copy-on-write if necessary. */
1824 atomic_add((uint8_t *)ptr, 0);
1826 if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
1827 error_setg_errno(errp, errno, "Cannot read pagemap");
1828 goto out;
1830 if ((pinfo & (1ull << 63)) == 0) {
1831 error_setg(errp, "Page not present");
1832 goto out;
1834 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1836 out:
1837 close(fd);
1838 return ret;
1841 static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
1843 hwaddr addr = qdict_get_int(qdict, "addr");
1844 Error *local_err = NULL;
1845 MemoryRegion *mr = NULL;
1846 void *ptr;
1847 uint64_t physaddr;
1849 ptr = gpa2hva(&mr, addr, &local_err);
1850 if (local_err) {
1851 error_report_err(local_err);
1852 return;
1855 physaddr = vtop(ptr, &local_err);
1856 if (local_err) {
1857 error_report_err(local_err);
1858 } else {
1859 monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
1860 " (%s) is 0x%" PRIx64 "\n",
1861 addr, mr->name, (uint64_t) physaddr);
1864 memory_region_unref(mr);
1866 #endif
1868 static void do_print(Monitor *mon, const QDict *qdict)
1870 int format = qdict_get_int(qdict, "format");
1871 hwaddr val = qdict_get_int(qdict, "val");
1873 switch(format) {
1874 case 'o':
1875 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1876 break;
1877 case 'x':
1878 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1879 break;
1880 case 'u':
1881 monitor_printf(mon, "%" HWADDR_PRIu, val);
1882 break;
1883 default:
1884 case 'd':
1885 monitor_printf(mon, "%" HWADDR_PRId, val);
1886 break;
1887 case 'c':
1888 monitor_printc(mon, val);
1889 break;
1891 monitor_printf(mon, "\n");
1894 static void hmp_sum(Monitor *mon, const QDict *qdict)
1896 uint32_t addr;
1897 uint16_t sum;
1898 uint32_t start = qdict_get_int(qdict, "start");
1899 uint32_t size = qdict_get_int(qdict, "size");
1901 sum = 0;
1902 for(addr = start; addr < (start + size); addr++) {
1903 uint8_t val = address_space_ldub(&address_space_memory, addr,
1904 MEMTXATTRS_UNSPECIFIED, NULL);
1905 /* BSD sum algorithm ('sum' Unix command) */
1906 sum = (sum >> 1) | (sum << 15);
1907 sum += val;
1909 monitor_printf(mon, "%05d\n", sum);
1912 static int mouse_button_state;
1914 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1916 int dx, dy, dz, button;
1917 const char *dx_str = qdict_get_str(qdict, "dx_str");
1918 const char *dy_str = qdict_get_str(qdict, "dy_str");
1919 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1921 dx = strtol(dx_str, NULL, 0);
1922 dy = strtol(dy_str, NULL, 0);
1923 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1924 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1926 if (dz_str) {
1927 dz = strtol(dz_str, NULL, 0);
1928 if (dz != 0) {
1929 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1930 qemu_input_queue_btn(NULL, button, true);
1931 qemu_input_event_sync();
1932 qemu_input_queue_btn(NULL, button, false);
1935 qemu_input_event_sync();
1938 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1940 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1941 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1942 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1943 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1945 int button_state = qdict_get_int(qdict, "button_state");
1947 if (mouse_button_state == button_state) {
1948 return;
1950 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1951 qemu_input_event_sync();
1952 mouse_button_state = button_state;
1955 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1957 int size = qdict_get_int(qdict, "size");
1958 int addr = qdict_get_int(qdict, "addr");
1959 int has_index = qdict_haskey(qdict, "index");
1960 uint32_t val;
1961 int suffix;
1963 if (has_index) {
1964 int index = qdict_get_int(qdict, "index");
1965 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1966 addr++;
1968 addr &= 0xffff;
1970 switch(size) {
1971 default:
1972 case 1:
1973 val = cpu_inb(addr);
1974 suffix = 'b';
1975 break;
1976 case 2:
1977 val = cpu_inw(addr);
1978 suffix = 'w';
1979 break;
1980 case 4:
1981 val = cpu_inl(addr);
1982 suffix = 'l';
1983 break;
1985 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1986 suffix, addr, size * 2, val);
1989 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1991 int size = qdict_get_int(qdict, "size");
1992 int addr = qdict_get_int(qdict, "addr");
1993 int val = qdict_get_int(qdict, "val");
1995 addr &= IOPORTS_MASK;
1997 switch (size) {
1998 default:
1999 case 1:
2000 cpu_outb(addr, val);
2001 break;
2002 case 2:
2003 cpu_outw(addr, val);
2004 break;
2005 case 4:
2006 cpu_outl(addr, val);
2007 break;
2011 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
2013 Error *local_err = NULL;
2014 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
2016 qemu_boot_set(bootdevice, &local_err);
2017 if (local_err) {
2018 error_report_err(local_err);
2019 } else {
2020 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
2024 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
2026 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
2027 bool dispatch_tree = qdict_get_try_bool(qdict, "dispatch_tree", false);
2028 bool owner = qdict_get_try_bool(qdict, "owner", false);
2030 mtree_info((fprintf_function)monitor_printf, mon, flatview, dispatch_tree,
2031 owner);
2034 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
2036 int i;
2037 NumaNodeMem *node_mem;
2038 CpuInfoList *cpu_list, *cpu;
2040 cpu_list = qmp_query_cpus(&error_abort);
2041 node_mem = g_new0(NumaNodeMem, nb_numa_nodes);
2043 query_numa_node_mem(node_mem);
2044 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
2045 for (i = 0; i < nb_numa_nodes; i++) {
2046 monitor_printf(mon, "node %d cpus:", i);
2047 for (cpu = cpu_list; cpu; cpu = cpu->next) {
2048 if (cpu->value->has_props && cpu->value->props->has_node_id &&
2049 cpu->value->props->node_id == i) {
2050 monitor_printf(mon, " %" PRIi64, cpu->value->CPU);
2053 monitor_printf(mon, "\n");
2054 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
2055 node_mem[i].node_mem >> 20);
2056 monitor_printf(mon, "node %d plugged: %" PRId64 " MB\n", i,
2057 node_mem[i].node_plugged_mem >> 20);
2059 qapi_free_CpuInfoList(cpu_list);
2060 g_free(node_mem);
2063 #ifdef CONFIG_PROFILER
2065 int64_t tcg_time;
2066 int64_t dev_time;
2068 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
2070 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
2071 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
2072 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
2073 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
2074 tcg_time = 0;
2075 dev_time = 0;
2077 #else
2078 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
2080 monitor_printf(mon, "Internal profiler not compiled\n");
2082 #endif
2084 /* Capture support */
2085 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2087 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
2089 int i;
2090 CaptureState *s;
2092 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2093 monitor_printf(mon, "[%d]: ", i);
2094 s->ops.info (s->opaque);
2098 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
2100 int i;
2101 int n = qdict_get_int(qdict, "n");
2102 CaptureState *s;
2104 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2105 if (i == n) {
2106 s->ops.destroy (s->opaque);
2107 QLIST_REMOVE (s, entries);
2108 g_free (s);
2109 return;
2114 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
2116 const char *path = qdict_get_str(qdict, "path");
2117 int has_freq = qdict_haskey(qdict, "freq");
2118 int freq = qdict_get_try_int(qdict, "freq", -1);
2119 int has_bits = qdict_haskey(qdict, "bits");
2120 int bits = qdict_get_try_int(qdict, "bits", -1);
2121 int has_channels = qdict_haskey(qdict, "nchannels");
2122 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2123 CaptureState *s;
2125 s = g_malloc0 (sizeof (*s));
2127 freq = has_freq ? freq : 44100;
2128 bits = has_bits ? bits : 16;
2129 nchannels = has_channels ? nchannels : 2;
2131 if (wav_start_capture (s, path, freq, bits, nchannels)) {
2132 monitor_printf(mon, "Failed to add wave capture\n");
2133 g_free (s);
2134 return;
2136 QLIST_INSERT_HEAD (&capture_head, s, entries);
2139 static qemu_acl *find_acl(Monitor *mon, const char *name)
2141 qemu_acl *acl = qemu_acl_find(name);
2143 if (!acl) {
2144 monitor_printf(mon, "acl: unknown list '%s'\n", name);
2146 return acl;
2149 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
2151 const char *aclname = qdict_get_str(qdict, "aclname");
2152 qemu_acl *acl = find_acl(mon, aclname);
2153 qemu_acl_entry *entry;
2154 int i = 0;
2156 if (acl) {
2157 monitor_printf(mon, "policy: %s\n",
2158 acl->defaultDeny ? "deny" : "allow");
2159 QTAILQ_FOREACH(entry, &acl->entries, next) {
2160 i++;
2161 monitor_printf(mon, "%d: %s %s\n", i,
2162 entry->deny ? "deny" : "allow", entry->match);
2167 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
2169 const char *aclname = qdict_get_str(qdict, "aclname");
2170 qemu_acl *acl = find_acl(mon, aclname);
2172 if (acl) {
2173 qemu_acl_reset(acl);
2174 monitor_printf(mon, "acl: removed all rules\n");
2178 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
2180 const char *aclname = qdict_get_str(qdict, "aclname");
2181 const char *policy = qdict_get_str(qdict, "policy");
2182 qemu_acl *acl = find_acl(mon, aclname);
2184 if (acl) {
2185 if (strcmp(policy, "allow") == 0) {
2186 acl->defaultDeny = 0;
2187 monitor_printf(mon, "acl: policy set to 'allow'\n");
2188 } else if (strcmp(policy, "deny") == 0) {
2189 acl->defaultDeny = 1;
2190 monitor_printf(mon, "acl: policy set to 'deny'\n");
2191 } else {
2192 monitor_printf(mon, "acl: unknown policy '%s', "
2193 "expected 'deny' or 'allow'\n", policy);
2198 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
2200 const char *aclname = qdict_get_str(qdict, "aclname");
2201 const char *match = qdict_get_str(qdict, "match");
2202 const char *policy = qdict_get_str(qdict, "policy");
2203 int has_index = qdict_haskey(qdict, "index");
2204 int index = qdict_get_try_int(qdict, "index", -1);
2205 qemu_acl *acl = find_acl(mon, aclname);
2206 int deny, ret;
2208 if (acl) {
2209 if (strcmp(policy, "allow") == 0) {
2210 deny = 0;
2211 } else if (strcmp(policy, "deny") == 0) {
2212 deny = 1;
2213 } else {
2214 monitor_printf(mon, "acl: unknown policy '%s', "
2215 "expected 'deny' or 'allow'\n", policy);
2216 return;
2218 if (has_index)
2219 ret = qemu_acl_insert(acl, deny, match, index);
2220 else
2221 ret = qemu_acl_append(acl, deny, match);
2222 if (ret < 0)
2223 monitor_printf(mon, "acl: unable to add acl entry\n");
2224 else
2225 monitor_printf(mon, "acl: added rule at position %d\n", ret);
2229 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
2231 const char *aclname = qdict_get_str(qdict, "aclname");
2232 const char *match = qdict_get_str(qdict, "match");
2233 qemu_acl *acl = find_acl(mon, aclname);
2234 int ret;
2236 if (acl) {
2237 ret = qemu_acl_remove(acl, match);
2238 if (ret < 0)
2239 monitor_printf(mon, "acl: no matching acl entry\n");
2240 else
2241 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2245 void qmp_getfd(const char *fdname, Error **errp)
2247 mon_fd_t *monfd;
2248 int fd, tmp_fd;
2250 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
2251 if (fd == -1) {
2252 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2253 return;
2256 if (qemu_isdigit(fdname[0])) {
2257 close(fd);
2258 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2259 "a name not starting with a digit");
2260 return;
2263 qemu_mutex_lock(&cur_mon->mon_lock);
2264 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2265 if (strcmp(monfd->name, fdname) != 0) {
2266 continue;
2269 tmp_fd = monfd->fd;
2270 monfd->fd = fd;
2271 qemu_mutex_unlock(&cur_mon->mon_lock);
2272 /* Make sure close() is outside critical section */
2273 close(tmp_fd);
2274 return;
2277 monfd = g_malloc0(sizeof(mon_fd_t));
2278 monfd->name = g_strdup(fdname);
2279 monfd->fd = fd;
2281 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2282 qemu_mutex_unlock(&cur_mon->mon_lock);
2285 void qmp_closefd(const char *fdname, Error **errp)
2287 mon_fd_t *monfd;
2288 int tmp_fd;
2290 qemu_mutex_lock(&cur_mon->mon_lock);
2291 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2292 if (strcmp(monfd->name, fdname) != 0) {
2293 continue;
2296 QLIST_REMOVE(monfd, next);
2297 tmp_fd = monfd->fd;
2298 g_free(monfd->name);
2299 g_free(monfd);
2300 qemu_mutex_unlock(&cur_mon->mon_lock);
2301 /* Make sure close() is outside critical section */
2302 close(tmp_fd);
2303 return;
2306 qemu_mutex_unlock(&cur_mon->mon_lock);
2307 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
2310 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2312 mon_fd_t *monfd;
2314 qemu_mutex_lock(&mon->mon_lock);
2315 QLIST_FOREACH(monfd, &mon->fds, next) {
2316 int fd;
2318 if (strcmp(monfd->name, fdname) != 0) {
2319 continue;
2322 fd = monfd->fd;
2324 /* caller takes ownership of fd */
2325 QLIST_REMOVE(monfd, next);
2326 g_free(monfd->name);
2327 g_free(monfd);
2328 qemu_mutex_unlock(&mon->mon_lock);
2330 return fd;
2333 qemu_mutex_unlock(&mon->mon_lock);
2334 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2335 return -1;
2338 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2340 MonFdsetFd *mon_fdset_fd;
2341 MonFdsetFd *mon_fdset_fd_next;
2343 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2344 if ((mon_fdset_fd->removed ||
2345 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2346 runstate_is_running()) {
2347 close(mon_fdset_fd->fd);
2348 g_free(mon_fdset_fd->opaque);
2349 QLIST_REMOVE(mon_fdset_fd, next);
2350 g_free(mon_fdset_fd);
2354 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2355 QLIST_REMOVE(mon_fdset, next);
2356 g_free(mon_fdset);
2360 static void monitor_fdsets_cleanup(void)
2362 MonFdset *mon_fdset;
2363 MonFdset *mon_fdset_next;
2365 qemu_mutex_lock(&mon_fdsets_lock);
2366 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2367 monitor_fdset_cleanup(mon_fdset);
2369 qemu_mutex_unlock(&mon_fdsets_lock);
2372 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2373 const char *opaque, Error **errp)
2375 int fd;
2376 Monitor *mon = cur_mon;
2377 AddfdInfo *fdinfo;
2379 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2380 if (fd == -1) {
2381 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2382 goto error;
2385 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2386 has_opaque, opaque, errp);
2387 if (fdinfo) {
2388 return fdinfo;
2391 error:
2392 if (fd != -1) {
2393 close(fd);
2395 return NULL;
2398 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2400 MonFdset *mon_fdset;
2401 MonFdsetFd *mon_fdset_fd;
2402 char fd_str[60];
2404 qemu_mutex_lock(&mon_fdsets_lock);
2405 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2406 if (mon_fdset->id != fdset_id) {
2407 continue;
2409 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2410 if (has_fd) {
2411 if (mon_fdset_fd->fd != fd) {
2412 continue;
2414 mon_fdset_fd->removed = true;
2415 break;
2416 } else {
2417 mon_fdset_fd->removed = true;
2420 if (has_fd && !mon_fdset_fd) {
2421 goto error;
2423 monitor_fdset_cleanup(mon_fdset);
2424 qemu_mutex_unlock(&mon_fdsets_lock);
2425 return;
2428 error:
2429 qemu_mutex_unlock(&mon_fdsets_lock);
2430 if (has_fd) {
2431 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2432 fdset_id, fd);
2433 } else {
2434 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2436 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2439 FdsetInfoList *qmp_query_fdsets(Error **errp)
2441 MonFdset *mon_fdset;
2442 MonFdsetFd *mon_fdset_fd;
2443 FdsetInfoList *fdset_list = NULL;
2445 qemu_mutex_lock(&mon_fdsets_lock);
2446 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2447 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2448 FdsetFdInfoList *fdsetfd_list = NULL;
2450 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2451 fdset_info->value->fdset_id = mon_fdset->id;
2453 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2454 FdsetFdInfoList *fdsetfd_info;
2456 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2457 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2458 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2459 if (mon_fdset_fd->opaque) {
2460 fdsetfd_info->value->has_opaque = true;
2461 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2462 } else {
2463 fdsetfd_info->value->has_opaque = false;
2466 fdsetfd_info->next = fdsetfd_list;
2467 fdsetfd_list = fdsetfd_info;
2470 fdset_info->value->fds = fdsetfd_list;
2472 fdset_info->next = fdset_list;
2473 fdset_list = fdset_info;
2475 qemu_mutex_unlock(&mon_fdsets_lock);
2477 return fdset_list;
2480 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2481 bool has_opaque, const char *opaque,
2482 Error **errp)
2484 MonFdset *mon_fdset = NULL;
2485 MonFdsetFd *mon_fdset_fd;
2486 AddfdInfo *fdinfo;
2488 qemu_mutex_lock(&mon_fdsets_lock);
2489 if (has_fdset_id) {
2490 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2491 /* Break if match found or match impossible due to ordering by ID */
2492 if (fdset_id <= mon_fdset->id) {
2493 if (fdset_id < mon_fdset->id) {
2494 mon_fdset = NULL;
2496 break;
2501 if (mon_fdset == NULL) {
2502 int64_t fdset_id_prev = -1;
2503 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2505 if (has_fdset_id) {
2506 if (fdset_id < 0) {
2507 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2508 "a non-negative value");
2509 qemu_mutex_unlock(&mon_fdsets_lock);
2510 return NULL;
2512 /* Use specified fdset ID */
2513 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2514 mon_fdset_cur = mon_fdset;
2515 if (fdset_id < mon_fdset_cur->id) {
2516 break;
2519 } else {
2520 /* Use first available fdset ID */
2521 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2522 mon_fdset_cur = mon_fdset;
2523 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2524 fdset_id_prev = mon_fdset_cur->id;
2525 continue;
2527 break;
2531 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2532 if (has_fdset_id) {
2533 mon_fdset->id = fdset_id;
2534 } else {
2535 mon_fdset->id = fdset_id_prev + 1;
2538 /* The fdset list is ordered by fdset ID */
2539 if (!mon_fdset_cur) {
2540 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2541 } else if (mon_fdset->id < mon_fdset_cur->id) {
2542 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2543 } else {
2544 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2548 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2549 mon_fdset_fd->fd = fd;
2550 mon_fdset_fd->removed = false;
2551 if (has_opaque) {
2552 mon_fdset_fd->opaque = g_strdup(opaque);
2554 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2556 fdinfo = g_malloc0(sizeof(*fdinfo));
2557 fdinfo->fdset_id = mon_fdset->id;
2558 fdinfo->fd = mon_fdset_fd->fd;
2560 qemu_mutex_unlock(&mon_fdsets_lock);
2561 return fdinfo;
2564 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2566 #ifdef _WIN32
2567 return -ENOENT;
2568 #else
2569 MonFdset *mon_fdset;
2570 MonFdsetFd *mon_fdset_fd;
2571 int mon_fd_flags;
2572 int ret;
2574 qemu_mutex_lock(&mon_fdsets_lock);
2575 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2576 if (mon_fdset->id != fdset_id) {
2577 continue;
2579 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2580 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2581 if (mon_fd_flags == -1) {
2582 ret = -errno;
2583 goto out;
2586 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2587 ret = mon_fdset_fd->fd;
2588 goto out;
2591 ret = -EACCES;
2592 goto out;
2594 ret = -ENOENT;
2596 out:
2597 qemu_mutex_unlock(&mon_fdsets_lock);
2598 return ret;
2599 #endif
2602 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2604 MonFdset *mon_fdset;
2605 MonFdsetFd *mon_fdset_fd_dup;
2607 qemu_mutex_lock(&mon_fdsets_lock);
2608 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2609 if (mon_fdset->id != fdset_id) {
2610 continue;
2612 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2613 if (mon_fdset_fd_dup->fd == dup_fd) {
2614 goto err;
2617 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2618 mon_fdset_fd_dup->fd = dup_fd;
2619 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2620 qemu_mutex_unlock(&mon_fdsets_lock);
2621 return 0;
2624 err:
2625 qemu_mutex_unlock(&mon_fdsets_lock);
2626 return -1;
2629 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2631 MonFdset *mon_fdset;
2632 MonFdsetFd *mon_fdset_fd_dup;
2634 qemu_mutex_lock(&mon_fdsets_lock);
2635 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2636 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2637 if (mon_fdset_fd_dup->fd == dup_fd) {
2638 if (remove) {
2639 QLIST_REMOVE(mon_fdset_fd_dup, next);
2640 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2641 monitor_fdset_cleanup(mon_fdset);
2643 goto err;
2644 } else {
2645 qemu_mutex_unlock(&mon_fdsets_lock);
2646 return mon_fdset->id;
2652 err:
2653 qemu_mutex_unlock(&mon_fdsets_lock);
2654 return -1;
2657 int monitor_fdset_dup_fd_find(int dup_fd)
2659 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2662 void monitor_fdset_dup_fd_remove(int dup_fd)
2664 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2667 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2669 int fd;
2670 Error *local_err = NULL;
2672 if (!qemu_isdigit(fdname[0]) && mon) {
2673 fd = monitor_get_fd(mon, fdname, &local_err);
2674 } else {
2675 fd = qemu_parse_fd(fdname);
2676 if (fd == -1) {
2677 error_setg(&local_err, "Invalid file descriptor number '%s'",
2678 fdname);
2681 if (local_err) {
2682 error_propagate(errp, local_err);
2683 assert(fd == -1);
2684 } else {
2685 assert(fd != -1);
2688 return fd;
2691 /* Please update hmp-commands.hx when adding or changing commands */
2692 static mon_cmd_t info_cmds[] = {
2693 #include "hmp-commands-info.h"
2694 { NULL, NULL, },
2697 /* mon_cmds and info_cmds would be sorted at runtime */
2698 static mon_cmd_t mon_cmds[] = {
2699 #include "hmp-commands.h"
2700 { NULL, NULL, },
2703 /*******************************************************************/
2705 static const char *pch;
2706 static sigjmp_buf expr_env;
2709 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2710 expr_error(Monitor *mon, const char *fmt, ...)
2712 va_list ap;
2713 va_start(ap, fmt);
2714 monitor_vprintf(mon, fmt, ap);
2715 monitor_printf(mon, "\n");
2716 va_end(ap);
2717 siglongjmp(expr_env, 1);
2720 /* return 0 if OK, -1 if not found */
2721 static int get_monitor_def(target_long *pval, const char *name)
2723 const MonitorDef *md = target_monitor_defs();
2724 CPUState *cs = mon_get_cpu();
2725 void *ptr;
2726 uint64_t tmp = 0;
2727 int ret;
2729 if (cs == NULL || md == NULL) {
2730 return -1;
2733 for(; md->name != NULL; md++) {
2734 if (compare_cmd(name, md->name)) {
2735 if (md->get_value) {
2736 *pval = md->get_value(md, md->offset);
2737 } else {
2738 CPUArchState *env = mon_get_cpu_env();
2739 ptr = (uint8_t *)env + md->offset;
2740 switch(md->type) {
2741 case MD_I32:
2742 *pval = *(int32_t *)ptr;
2743 break;
2744 case MD_TLONG:
2745 *pval = *(target_long *)ptr;
2746 break;
2747 default:
2748 *pval = 0;
2749 break;
2752 return 0;
2756 ret = target_get_monitor_def(cs, name, &tmp);
2757 if (!ret) {
2758 *pval = (target_long) tmp;
2761 return ret;
2764 static void next(void)
2766 if (*pch != '\0') {
2767 pch++;
2768 while (qemu_isspace(*pch))
2769 pch++;
2773 static int64_t expr_sum(Monitor *mon);
2775 static int64_t expr_unary(Monitor *mon)
2777 int64_t n;
2778 char *p;
2779 int ret;
2781 switch(*pch) {
2782 case '+':
2783 next();
2784 n = expr_unary(mon);
2785 break;
2786 case '-':
2787 next();
2788 n = -expr_unary(mon);
2789 break;
2790 case '~':
2791 next();
2792 n = ~expr_unary(mon);
2793 break;
2794 case '(':
2795 next();
2796 n = expr_sum(mon);
2797 if (*pch != ')') {
2798 expr_error(mon, "')' expected");
2800 next();
2801 break;
2802 case '\'':
2803 pch++;
2804 if (*pch == '\0')
2805 expr_error(mon, "character constant expected");
2806 n = *pch;
2807 pch++;
2808 if (*pch != '\'')
2809 expr_error(mon, "missing terminating \' character");
2810 next();
2811 break;
2812 case '$':
2814 char buf[128], *q;
2815 target_long reg=0;
2817 pch++;
2818 q = buf;
2819 while ((*pch >= 'a' && *pch <= 'z') ||
2820 (*pch >= 'A' && *pch <= 'Z') ||
2821 (*pch >= '0' && *pch <= '9') ||
2822 *pch == '_' || *pch == '.') {
2823 if ((q - buf) < sizeof(buf) - 1)
2824 *q++ = *pch;
2825 pch++;
2827 while (qemu_isspace(*pch))
2828 pch++;
2829 *q = 0;
2830 ret = get_monitor_def(&reg, buf);
2831 if (ret < 0)
2832 expr_error(mon, "unknown register");
2833 n = reg;
2835 break;
2836 case '\0':
2837 expr_error(mon, "unexpected end of expression");
2838 n = 0;
2839 break;
2840 default:
2841 errno = 0;
2842 n = strtoull(pch, &p, 0);
2843 if (errno == ERANGE) {
2844 expr_error(mon, "number too large");
2846 if (pch == p) {
2847 expr_error(mon, "invalid char '%c' in expression", *p);
2849 pch = p;
2850 while (qemu_isspace(*pch))
2851 pch++;
2852 break;
2854 return n;
2858 static int64_t expr_prod(Monitor *mon)
2860 int64_t val, val2;
2861 int op;
2863 val = expr_unary(mon);
2864 for(;;) {
2865 op = *pch;
2866 if (op != '*' && op != '/' && op != '%')
2867 break;
2868 next();
2869 val2 = expr_unary(mon);
2870 switch(op) {
2871 default:
2872 case '*':
2873 val *= val2;
2874 break;
2875 case '/':
2876 case '%':
2877 if (val2 == 0)
2878 expr_error(mon, "division by zero");
2879 if (op == '/')
2880 val /= val2;
2881 else
2882 val %= val2;
2883 break;
2886 return val;
2889 static int64_t expr_logic(Monitor *mon)
2891 int64_t val, val2;
2892 int op;
2894 val = expr_prod(mon);
2895 for(;;) {
2896 op = *pch;
2897 if (op != '&' && op != '|' && op != '^')
2898 break;
2899 next();
2900 val2 = expr_prod(mon);
2901 switch(op) {
2902 default:
2903 case '&':
2904 val &= val2;
2905 break;
2906 case '|':
2907 val |= val2;
2908 break;
2909 case '^':
2910 val ^= val2;
2911 break;
2914 return val;
2917 static int64_t expr_sum(Monitor *mon)
2919 int64_t val, val2;
2920 int op;
2922 val = expr_logic(mon);
2923 for(;;) {
2924 op = *pch;
2925 if (op != '+' && op != '-')
2926 break;
2927 next();
2928 val2 = expr_logic(mon);
2929 if (op == '+')
2930 val += val2;
2931 else
2932 val -= val2;
2934 return val;
2937 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2939 pch = *pp;
2940 if (sigsetjmp(expr_env, 0)) {
2941 *pp = pch;
2942 return -1;
2944 while (qemu_isspace(*pch))
2945 pch++;
2946 *pval = expr_sum(mon);
2947 *pp = pch;
2948 return 0;
2951 static int get_double(Monitor *mon, double *pval, const char **pp)
2953 const char *p = *pp;
2954 char *tailp;
2955 double d;
2957 d = strtod(p, &tailp);
2958 if (tailp == p) {
2959 monitor_printf(mon, "Number expected\n");
2960 return -1;
2962 if (d != d || d - d != 0) {
2963 /* NaN or infinity */
2964 monitor_printf(mon, "Bad number\n");
2965 return -1;
2967 *pval = d;
2968 *pp = tailp;
2969 return 0;
2973 * Store the command-name in cmdname, and return a pointer to
2974 * the remaining of the command string.
2976 static const char *get_command_name(const char *cmdline,
2977 char *cmdname, size_t nlen)
2979 size_t len;
2980 const char *p, *pstart;
2982 p = cmdline;
2983 while (qemu_isspace(*p))
2984 p++;
2985 if (*p == '\0')
2986 return NULL;
2987 pstart = p;
2988 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2989 p++;
2990 len = p - pstart;
2991 if (len > nlen - 1)
2992 len = nlen - 1;
2993 memcpy(cmdname, pstart, len);
2994 cmdname[len] = '\0';
2995 return p;
2999 * Read key of 'type' into 'key' and return the current
3000 * 'type' pointer.
3002 static char *key_get_info(const char *type, char **key)
3004 size_t len;
3005 char *p, *str;
3007 if (*type == ',')
3008 type++;
3010 p = strchr(type, ':');
3011 if (!p) {
3012 *key = NULL;
3013 return NULL;
3015 len = p - type;
3017 str = g_malloc(len + 1);
3018 memcpy(str, type, len);
3019 str[len] = '\0';
3021 *key = str;
3022 return ++p;
3025 static int default_fmt_format = 'x';
3026 static int default_fmt_size = 4;
3028 static int is_valid_option(const char *c, const char *typestr)
3030 char option[3];
3032 option[0] = '-';
3033 option[1] = *c;
3034 option[2] = '\0';
3036 typestr = strstr(typestr, option);
3037 return (typestr != NULL);
3040 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3041 const char *cmdname)
3043 const mon_cmd_t *cmd;
3045 for (cmd = disp_table; cmd->name != NULL; cmd++) {
3046 if (compare_cmd(cmdname, cmd->name)) {
3047 return cmd;
3051 return NULL;
3055 * Parse command name from @cmdp according to command table @table.
3056 * If blank, return NULL.
3057 * Else, if no valid command can be found, report to @mon, and return
3058 * NULL.
3059 * Else, change @cmdp to point right behind the name, and return its
3060 * command table entry.
3061 * Do not assume the return value points into @table! It doesn't when
3062 * the command is found in a sub-command table.
3064 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3065 const char *cmdp_start,
3066 const char **cmdp,
3067 mon_cmd_t *table)
3069 const char *p;
3070 const mon_cmd_t *cmd;
3071 char cmdname[256];
3073 /* extract the command name */
3074 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
3075 if (!p)
3076 return NULL;
3078 cmd = search_dispatch_table(table, cmdname);
3079 if (!cmd) {
3080 monitor_printf(mon, "unknown command: '%.*s'\n",
3081 (int)(p - cmdp_start), cmdp_start);
3082 return NULL;
3084 if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
3085 monitor_printf(mon, "Command '%.*s' not available with -preconfig "
3086 "until after exit_preconfig.\n",
3087 (int)(p - cmdp_start), cmdp_start);
3088 return NULL;
3091 /* filter out following useless space */
3092 while (qemu_isspace(*p)) {
3093 p++;
3096 *cmdp = p;
3097 /* search sub command */
3098 if (cmd->sub_table != NULL && *p != '\0') {
3099 return monitor_parse_command(mon, cmdp_start, cmdp, cmd->sub_table);
3102 return cmd;
3106 * Parse arguments for @cmd.
3107 * If it can't be parsed, report to @mon, and return NULL.
3108 * Else, insert command arguments into a QDict, and return it.
3109 * Note: On success, caller has to free the QDict structure.
3112 static QDict *monitor_parse_arguments(Monitor *mon,
3113 const char **endp,
3114 const mon_cmd_t *cmd)
3116 const char *typestr;
3117 char *key;
3118 int c;
3119 const char *p = *endp;
3120 char buf[1024];
3121 QDict *qdict = qdict_new();
3123 /* parse the parameters */
3124 typestr = cmd->args_type;
3125 for(;;) {
3126 typestr = key_get_info(typestr, &key);
3127 if (!typestr)
3128 break;
3129 c = *typestr;
3130 typestr++;
3131 switch(c) {
3132 case 'F':
3133 case 'B':
3134 case 's':
3136 int ret;
3138 while (qemu_isspace(*p))
3139 p++;
3140 if (*typestr == '?') {
3141 typestr++;
3142 if (*p == '\0') {
3143 /* no optional string: NULL argument */
3144 break;
3147 ret = get_str(buf, sizeof(buf), &p);
3148 if (ret < 0) {
3149 switch(c) {
3150 case 'F':
3151 monitor_printf(mon, "%s: filename expected\n",
3152 cmd->name);
3153 break;
3154 case 'B':
3155 monitor_printf(mon, "%s: block device name expected\n",
3156 cmd->name);
3157 break;
3158 default:
3159 monitor_printf(mon, "%s: string expected\n", cmd->name);
3160 break;
3162 goto fail;
3164 qdict_put_str(qdict, key, buf);
3166 break;
3167 case 'O':
3169 QemuOptsList *opts_list;
3170 QemuOpts *opts;
3172 opts_list = qemu_find_opts(key);
3173 if (!opts_list || opts_list->desc->name) {
3174 goto bad_type;
3176 while (qemu_isspace(*p)) {
3177 p++;
3179 if (!*p)
3180 break;
3181 if (get_str(buf, sizeof(buf), &p) < 0) {
3182 goto fail;
3184 opts = qemu_opts_parse_noisily(opts_list, buf, true);
3185 if (!opts) {
3186 goto fail;
3188 qemu_opts_to_qdict(opts, qdict);
3189 qemu_opts_del(opts);
3191 break;
3192 case '/':
3194 int count, format, size;
3196 while (qemu_isspace(*p))
3197 p++;
3198 if (*p == '/') {
3199 /* format found */
3200 p++;
3201 count = 1;
3202 if (qemu_isdigit(*p)) {
3203 count = 0;
3204 while (qemu_isdigit(*p)) {
3205 count = count * 10 + (*p - '0');
3206 p++;
3209 size = -1;
3210 format = -1;
3211 for(;;) {
3212 switch(*p) {
3213 case 'o':
3214 case 'd':
3215 case 'u':
3216 case 'x':
3217 case 'i':
3218 case 'c':
3219 format = *p++;
3220 break;
3221 case 'b':
3222 size = 1;
3223 p++;
3224 break;
3225 case 'h':
3226 size = 2;
3227 p++;
3228 break;
3229 case 'w':
3230 size = 4;
3231 p++;
3232 break;
3233 case 'g':
3234 case 'L':
3235 size = 8;
3236 p++;
3237 break;
3238 default:
3239 goto next;
3242 next:
3243 if (*p != '\0' && !qemu_isspace(*p)) {
3244 monitor_printf(mon, "invalid char in format: '%c'\n",
3245 *p);
3246 goto fail;
3248 if (format < 0)
3249 format = default_fmt_format;
3250 if (format != 'i') {
3251 /* for 'i', not specifying a size gives -1 as size */
3252 if (size < 0)
3253 size = default_fmt_size;
3254 default_fmt_size = size;
3256 default_fmt_format = format;
3257 } else {
3258 count = 1;
3259 format = default_fmt_format;
3260 if (format != 'i') {
3261 size = default_fmt_size;
3262 } else {
3263 size = -1;
3266 qdict_put_int(qdict, "count", count);
3267 qdict_put_int(qdict, "format", format);
3268 qdict_put_int(qdict, "size", size);
3270 break;
3271 case 'i':
3272 case 'l':
3273 case 'M':
3275 int64_t val;
3277 while (qemu_isspace(*p))
3278 p++;
3279 if (*typestr == '?' || *typestr == '.') {
3280 if (*typestr == '?') {
3281 if (*p == '\0') {
3282 typestr++;
3283 break;
3285 } else {
3286 if (*p == '.') {
3287 p++;
3288 while (qemu_isspace(*p))
3289 p++;
3290 } else {
3291 typestr++;
3292 break;
3295 typestr++;
3297 if (get_expr(mon, &val, &p))
3298 goto fail;
3299 /* Check if 'i' is greater than 32-bit */
3300 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3301 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
3302 monitor_printf(mon, "integer is for 32-bit values\n");
3303 goto fail;
3304 } else if (c == 'M') {
3305 if (val < 0) {
3306 monitor_printf(mon, "enter a positive value\n");
3307 goto fail;
3309 val *= MiB;
3311 qdict_put_int(qdict, key, val);
3313 break;
3314 case 'o':
3316 int ret;
3317 uint64_t val;
3318 char *end;
3320 while (qemu_isspace(*p)) {
3321 p++;
3323 if (*typestr == '?') {
3324 typestr++;
3325 if (*p == '\0') {
3326 break;
3329 ret = qemu_strtosz_MiB(p, &end, &val);
3330 if (ret < 0 || val > INT64_MAX) {
3331 monitor_printf(mon, "invalid size\n");
3332 goto fail;
3334 qdict_put_int(qdict, key, val);
3335 p = end;
3337 break;
3338 case 'T':
3340 double val;
3342 while (qemu_isspace(*p))
3343 p++;
3344 if (*typestr == '?') {
3345 typestr++;
3346 if (*p == '\0') {
3347 break;
3350 if (get_double(mon, &val, &p) < 0) {
3351 goto fail;
3353 if (p[0] && p[1] == 's') {
3354 switch (*p) {
3355 case 'm':
3356 val /= 1e3; p += 2; break;
3357 case 'u':
3358 val /= 1e6; p += 2; break;
3359 case 'n':
3360 val /= 1e9; p += 2; break;
3363 if (*p && !qemu_isspace(*p)) {
3364 monitor_printf(mon, "Unknown unit suffix\n");
3365 goto fail;
3367 qdict_put(qdict, key, qnum_from_double(val));
3369 break;
3370 case 'b':
3372 const char *beg;
3373 bool val;
3375 while (qemu_isspace(*p)) {
3376 p++;
3378 beg = p;
3379 while (qemu_isgraph(*p)) {
3380 p++;
3382 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3383 val = true;
3384 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3385 val = false;
3386 } else {
3387 monitor_printf(mon, "Expected 'on' or 'off'\n");
3388 goto fail;
3390 qdict_put_bool(qdict, key, val);
3392 break;
3393 case '-':
3395 const char *tmp = p;
3396 int skip_key = 0;
3397 /* option */
3399 c = *typestr++;
3400 if (c == '\0')
3401 goto bad_type;
3402 while (qemu_isspace(*p))
3403 p++;
3404 if (*p == '-') {
3405 p++;
3406 if(c != *p) {
3407 if(!is_valid_option(p, typestr)) {
3409 monitor_printf(mon, "%s: unsupported option -%c\n",
3410 cmd->name, *p);
3411 goto fail;
3412 } else {
3413 skip_key = 1;
3416 if(skip_key) {
3417 p = tmp;
3418 } else {
3419 /* has option */
3420 p++;
3421 qdict_put_bool(qdict, key, true);
3425 break;
3426 case 'S':
3428 /* package all remaining string */
3429 int len;
3431 while (qemu_isspace(*p)) {
3432 p++;
3434 if (*typestr == '?') {
3435 typestr++;
3436 if (*p == '\0') {
3437 /* no remaining string: NULL argument */
3438 break;
3441 len = strlen(p);
3442 if (len <= 0) {
3443 monitor_printf(mon, "%s: string expected\n",
3444 cmd->name);
3445 goto fail;
3447 qdict_put_str(qdict, key, p);
3448 p += len;
3450 break;
3451 default:
3452 bad_type:
3453 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3454 goto fail;
3456 g_free(key);
3457 key = NULL;
3459 /* check that all arguments were parsed */
3460 while (qemu_isspace(*p))
3461 p++;
3462 if (*p != '\0') {
3463 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3464 cmd->name);
3465 goto fail;
3468 return qdict;
3470 fail:
3471 qobject_unref(qdict);
3472 g_free(key);
3473 return NULL;
3476 static void handle_hmp_command(Monitor *mon, const char *cmdline)
3478 QDict *qdict;
3479 const mon_cmd_t *cmd;
3480 const char *cmd_start = cmdline;
3482 trace_handle_hmp_command(mon, cmdline);
3484 cmd = monitor_parse_command(mon, cmdline, &cmdline, mon->cmd_table);
3485 if (!cmd) {
3486 return;
3489 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
3490 if (!qdict) {
3491 while (cmdline > cmd_start && qemu_isspace(cmdline[-1])) {
3492 cmdline--;
3494 monitor_printf(mon, "Try \"help %.*s\" for more information\n",
3495 (int)(cmdline - cmd_start), cmd_start);
3496 return;
3499 cmd->cmd(mon, qdict);
3500 qobject_unref(qdict);
3503 static void cmd_completion(Monitor *mon, const char *name, const char *list)
3505 const char *p, *pstart;
3506 char cmd[128];
3507 int len;
3509 p = list;
3510 for(;;) {
3511 pstart = p;
3512 p = qemu_strchrnul(p, '|');
3513 len = p - pstart;
3514 if (len > sizeof(cmd) - 2)
3515 len = sizeof(cmd) - 2;
3516 memcpy(cmd, pstart, len);
3517 cmd[len] = '\0';
3518 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3519 readline_add_completion(mon->rs, cmd);
3521 if (*p == '\0')
3522 break;
3523 p++;
3527 static void file_completion(Monitor *mon, const char *input)
3529 DIR *ffs;
3530 struct dirent *d;
3531 char path[1024];
3532 char file[1024], file_prefix[1024];
3533 int input_path_len;
3534 const char *p;
3536 p = strrchr(input, '/');
3537 if (!p) {
3538 input_path_len = 0;
3539 pstrcpy(file_prefix, sizeof(file_prefix), input);
3540 pstrcpy(path, sizeof(path), ".");
3541 } else {
3542 input_path_len = p - input + 1;
3543 memcpy(path, input, input_path_len);
3544 if (input_path_len > sizeof(path) - 1)
3545 input_path_len = sizeof(path) - 1;
3546 path[input_path_len] = '\0';
3547 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3550 ffs = opendir(path);
3551 if (!ffs)
3552 return;
3553 for(;;) {
3554 struct stat sb;
3555 d = readdir(ffs);
3556 if (!d)
3557 break;
3559 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3560 continue;
3563 if (strstart(d->d_name, file_prefix, NULL)) {
3564 memcpy(file, input, input_path_len);
3565 if (input_path_len < sizeof(file))
3566 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3567 d->d_name);
3568 /* stat the file to find out if it's a directory.
3569 * In that case add a slash to speed up typing long paths
3571 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3572 pstrcat(file, sizeof(file), "/");
3574 readline_add_completion(mon->rs, file);
3577 closedir(ffs);
3580 static const char *next_arg_type(const char *typestr)
3582 const char *p = strchr(typestr, ':');
3583 return (p != NULL ? ++p : typestr);
3586 static void add_completion_option(ReadLineState *rs, const char *str,
3587 const char *option)
3589 if (!str || !option) {
3590 return;
3592 if (!strncmp(option, str, strlen(str))) {
3593 readline_add_completion(rs, option);
3597 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3599 size_t len;
3600 ChardevBackendInfoList *list, *start;
3602 if (nb_args != 2) {
3603 return;
3605 len = strlen(str);
3606 readline_set_completion_index(rs, len);
3608 start = list = qmp_query_chardev_backends(NULL);
3609 while (list) {
3610 const char *chr_name = list->value->name;
3612 if (!strncmp(chr_name, str, len)) {
3613 readline_add_completion(rs, chr_name);
3615 list = list->next;
3617 qapi_free_ChardevBackendInfoList(start);
3620 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3622 size_t len;
3623 int i;
3625 if (nb_args != 2) {
3626 return;
3628 len = strlen(str);
3629 readline_set_completion_index(rs, len);
3630 for (i = 0; i < NET_CLIENT_DRIVER__MAX; i++) {
3631 add_completion_option(rs, str, NetClientDriver_str(i));
3635 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3637 GSList *list, *elt;
3638 size_t len;
3640 if (nb_args != 2) {
3641 return;
3644 len = strlen(str);
3645 readline_set_completion_index(rs, len);
3646 list = elt = object_class_get_list(TYPE_DEVICE, false);
3647 while (elt) {
3648 const char *name;
3649 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3650 TYPE_DEVICE);
3651 name = object_class_get_name(OBJECT_CLASS(dc));
3653 if (dc->user_creatable
3654 && !strncmp(name, str, len)) {
3655 readline_add_completion(rs, name);
3657 elt = elt->next;
3659 g_slist_free(list);
3662 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3664 GSList *list, *elt;
3665 size_t len;
3667 if (nb_args != 2) {
3668 return;
3671 len = strlen(str);
3672 readline_set_completion_index(rs, len);
3673 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3674 while (elt) {
3675 const char *name;
3677 name = object_class_get_name(OBJECT_CLASS(elt->data));
3678 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3679 readline_add_completion(rs, name);
3681 elt = elt->next;
3683 g_slist_free(list);
3686 static void peripheral_device_del_completion(ReadLineState *rs,
3687 const char *str, size_t len)
3689 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3690 GSList *list, *item;
3692 list = qdev_build_hotpluggable_device_list(peripheral);
3693 if (!list) {
3694 return;
3697 for (item = list; item; item = g_slist_next(item)) {
3698 DeviceState *dev = item->data;
3700 if (dev->id && !strncmp(str, dev->id, len)) {
3701 readline_add_completion(rs, dev->id);
3705 g_slist_free(list);
3708 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3710 size_t len;
3711 ChardevInfoList *list, *start;
3713 if (nb_args != 2) {
3714 return;
3716 len = strlen(str);
3717 readline_set_completion_index(rs, len);
3719 start = list = qmp_query_chardev(NULL);
3720 while (list) {
3721 ChardevInfo *chr = list->value;
3723 if (!strncmp(chr->label, str, len)) {
3724 readline_add_completion(rs, chr->label);
3726 list = list->next;
3728 qapi_free_ChardevInfoList(start);
3731 static void ringbuf_completion(ReadLineState *rs, const char *str)
3733 size_t len;
3734 ChardevInfoList *list, *start;
3736 len = strlen(str);
3737 readline_set_completion_index(rs, len);
3739 start = list = qmp_query_chardev(NULL);
3740 while (list) {
3741 ChardevInfo *chr_info = list->value;
3743 if (!strncmp(chr_info->label, str, len)) {
3744 Chardev *chr = qemu_chr_find(chr_info->label);
3745 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3746 readline_add_completion(rs, chr_info->label);
3749 list = list->next;
3751 qapi_free_ChardevInfoList(start);
3754 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3756 if (nb_args != 2) {
3757 return;
3759 ringbuf_completion(rs, str);
3762 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3764 size_t len;
3766 if (nb_args != 2) {
3767 return;
3770 len = strlen(str);
3771 readline_set_completion_index(rs, len);
3772 peripheral_device_del_completion(rs, str, len);
3775 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3777 ObjectPropertyInfoList *list, *start;
3778 size_t len;
3780 if (nb_args != 2) {
3781 return;
3783 len = strlen(str);
3784 readline_set_completion_index(rs, len);
3786 start = list = qmp_qom_list("/objects", NULL);
3787 while (list) {
3788 ObjectPropertyInfo *info = list->value;
3790 if (!strncmp(info->type, "child<", 5)
3791 && !strncmp(info->name, str, len)) {
3792 readline_add_completion(rs, info->name);
3794 list = list->next;
3796 qapi_free_ObjectPropertyInfoList(start);
3799 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3801 int i;
3802 char *sep;
3803 size_t len;
3805 if (nb_args != 2) {
3806 return;
3808 sep = strrchr(str, '-');
3809 if (sep) {
3810 str = sep + 1;
3812 len = strlen(str);
3813 readline_set_completion_index(rs, len);
3814 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3815 if (!strncmp(str, QKeyCode_str(i), len)) {
3816 readline_add_completion(rs, QKeyCode_str(i));
3821 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3823 size_t len;
3825 len = strlen(str);
3826 readline_set_completion_index(rs, len);
3827 if (nb_args == 2) {
3828 NetClientState *ncs[MAX_QUEUE_NUM];
3829 int count, i;
3830 count = qemu_find_net_clients_except(NULL, ncs,
3831 NET_CLIENT_DRIVER_NONE,
3832 MAX_QUEUE_NUM);
3833 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3834 const char *name = ncs[i]->name;
3835 if (!strncmp(str, name, len)) {
3836 readline_add_completion(rs, name);
3839 } else if (nb_args == 3) {
3840 add_completion_option(rs, str, "on");
3841 add_completion_option(rs, str, "off");
3845 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3847 int len, count, i;
3848 NetClientState *ncs[MAX_QUEUE_NUM];
3850 if (nb_args != 2) {
3851 return;
3854 len = strlen(str);
3855 readline_set_completion_index(rs, len);
3856 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3857 MAX_QUEUE_NUM);
3858 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3859 QemuOpts *opts;
3860 const char *name = ncs[i]->name;
3861 if (strncmp(str, name, len)) {
3862 continue;
3864 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3865 if (opts) {
3866 readline_add_completion(rs, name);
3871 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3873 size_t len;
3875 len = strlen(str);
3876 readline_set_completion_index(rs, len);
3877 if (nb_args == 2) {
3878 TraceEventIter iter;
3879 TraceEvent *ev;
3880 char *pattern = g_strdup_printf("%s*", str);
3881 trace_event_iter_init(&iter, pattern);
3882 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3883 readline_add_completion(rs, trace_event_get_name(ev));
3885 g_free(pattern);
3889 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3891 size_t len;
3893 len = strlen(str);
3894 readline_set_completion_index(rs, len);
3895 if (nb_args == 2) {
3896 TraceEventIter iter;
3897 TraceEvent *ev;
3898 char *pattern = g_strdup_printf("%s*", str);
3899 trace_event_iter_init(&iter, pattern);
3900 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3901 readline_add_completion(rs, trace_event_get_name(ev));
3903 g_free(pattern);
3904 } else if (nb_args == 3) {
3905 add_completion_option(rs, str, "on");
3906 add_completion_option(rs, str, "off");
3910 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3912 int i;
3914 if (nb_args != 2) {
3915 return;
3917 readline_set_completion_index(rs, strlen(str));
3918 for (i = 0; i < WATCHDOG_ACTION__MAX; i++) {
3919 add_completion_option(rs, str, WatchdogAction_str(i));
3923 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3924 const char *str)
3926 size_t len;
3928 len = strlen(str);
3929 readline_set_completion_index(rs, len);
3930 if (nb_args == 2) {
3931 int i;
3932 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3933 const char *name = MigrationCapability_str(i);
3934 if (!strncmp(str, name, len)) {
3935 readline_add_completion(rs, name);
3938 } else if (nb_args == 3) {
3939 add_completion_option(rs, str, "on");
3940 add_completion_option(rs, str, "off");
3944 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3945 const char *str)
3947 size_t len;
3949 len = strlen(str);
3950 readline_set_completion_index(rs, len);
3951 if (nb_args == 2) {
3952 int i;
3953 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3954 const char *name = MigrationParameter_str(i);
3955 if (!strncmp(str, name, len)) {
3956 readline_add_completion(rs, name);
3962 static void vm_completion(ReadLineState *rs, const char *str)
3964 size_t len;
3965 BlockDriverState *bs;
3966 BdrvNextIterator it;
3968 len = strlen(str);
3969 readline_set_completion_index(rs, len);
3971 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3972 SnapshotInfoList *snapshots, *snapshot;
3973 AioContext *ctx = bdrv_get_aio_context(bs);
3974 bool ok = false;
3976 aio_context_acquire(ctx);
3977 if (bdrv_can_snapshot(bs)) {
3978 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3980 aio_context_release(ctx);
3981 if (!ok) {
3982 continue;
3985 snapshot = snapshots;
3986 while (snapshot) {
3987 char *completion = snapshot->value->name;
3988 if (!strncmp(str, completion, len)) {
3989 readline_add_completion(rs, completion);
3991 completion = snapshot->value->id;
3992 if (!strncmp(str, completion, len)) {
3993 readline_add_completion(rs, completion);
3995 snapshot = snapshot->next;
3997 qapi_free_SnapshotInfoList(snapshots);
4002 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
4004 if (nb_args == 2) {
4005 vm_completion(rs, str);
4009 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
4011 if (nb_args == 2) {
4012 vm_completion(rs, str);
4016 static void monitor_find_completion_by_table(Monitor *mon,
4017 const mon_cmd_t *cmd_table,
4018 char **args,
4019 int nb_args)
4021 const char *cmdname;
4022 int i;
4023 const char *ptype, *old_ptype, *str, *name;
4024 const mon_cmd_t *cmd;
4025 BlockBackend *blk = NULL;
4027 if (nb_args <= 1) {
4028 /* command completion */
4029 if (nb_args == 0)
4030 cmdname = "";
4031 else
4032 cmdname = args[0];
4033 readline_set_completion_index(mon->rs, strlen(cmdname));
4034 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4035 if (!runstate_check(RUN_STATE_PRECONFIG) ||
4036 cmd_can_preconfig(cmd)) {
4037 cmd_completion(mon, cmdname, cmd->name);
4040 } else {
4041 /* find the command */
4042 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4043 if (compare_cmd(args[0], cmd->name) &&
4044 (!runstate_check(RUN_STATE_PRECONFIG) ||
4045 cmd_can_preconfig(cmd))) {
4046 break;
4049 if (!cmd->name) {
4050 return;
4053 if (cmd->sub_table) {
4054 /* do the job again */
4055 monitor_find_completion_by_table(mon, cmd->sub_table,
4056 &args[1], nb_args - 1);
4057 return;
4059 if (cmd->command_completion) {
4060 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
4061 return;
4064 ptype = next_arg_type(cmd->args_type);
4065 for(i = 0; i < nb_args - 2; i++) {
4066 if (*ptype != '\0') {
4067 ptype = next_arg_type(ptype);
4068 while (*ptype == '?')
4069 ptype = next_arg_type(ptype);
4072 str = args[nb_args - 1];
4073 old_ptype = NULL;
4074 while (*ptype == '-' && old_ptype != ptype) {
4075 old_ptype = ptype;
4076 ptype = next_arg_type(ptype);
4078 switch(*ptype) {
4079 case 'F':
4080 /* file completion */
4081 readline_set_completion_index(mon->rs, strlen(str));
4082 file_completion(mon, str);
4083 break;
4084 case 'B':
4085 /* block device name completion */
4086 readline_set_completion_index(mon->rs, strlen(str));
4087 while ((blk = blk_next(blk)) != NULL) {
4088 name = blk_name(blk);
4089 if (str[0] == '\0' ||
4090 !strncmp(name, str, strlen(str))) {
4091 readline_add_completion(mon->rs, name);
4094 break;
4095 case 's':
4096 case 'S':
4097 if (!strcmp(cmd->name, "help|?")) {
4098 monitor_find_completion_by_table(mon, cmd_table,
4099 &args[1], nb_args - 1);
4101 break;
4102 default:
4103 break;
4108 static void monitor_find_completion(void *opaque,
4109 const char *cmdline)
4111 Monitor *mon = opaque;
4112 char *args[MAX_ARGS];
4113 int nb_args, len;
4115 /* 1. parse the cmdline */
4116 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
4117 return;
4120 /* if the line ends with a space, it means we want to complete the
4121 next arg */
4122 len = strlen(cmdline);
4123 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4124 if (nb_args >= MAX_ARGS) {
4125 goto cleanup;
4127 args[nb_args++] = g_strdup("");
4130 /* 2. auto complete according to args */
4131 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
4133 cleanup:
4134 free_cmdline_args(args, nb_args);
4137 static int monitor_can_read(void *opaque)
4139 Monitor *mon = opaque;
4141 return !atomic_mb_read(&mon->suspend_cnt);
4145 * Emit QMP response @rsp with ID @id to @mon.
4146 * Null @rsp can only happen for commands with QCO_NO_SUCCESS_RESP.
4147 * Nothing is emitted then.
4149 static void monitor_qmp_respond(Monitor *mon, QDict *rsp, QObject *id)
4151 if (rsp) {
4152 if (id) {
4153 qdict_put_obj(rsp, "id", qobject_ref(id));
4156 qmp_queue_response(mon, rsp);
4160 static void monitor_qmp_dispatch(Monitor *mon, QObject *req, QObject *id)
4162 Monitor *old_mon;
4163 QDict *rsp;
4164 QDict *error;
4166 old_mon = cur_mon;
4167 cur_mon = mon;
4169 rsp = qmp_dispatch(mon->qmp.commands, req, qmp_oob_enabled(mon));
4171 cur_mon = old_mon;
4173 if (mon->qmp.commands == &qmp_cap_negotiation_commands) {
4174 error = qdict_get_qdict(rsp, "error");
4175 if (error
4176 && !g_strcmp0(qdict_get_try_str(error, "class"),
4177 QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
4178 /* Provide a more useful error message */
4179 qdict_del(error, "desc");
4180 qdict_put_str(error, "desc", "Expecting capabilities negotiation"
4181 " with 'qmp_capabilities'");
4185 monitor_qmp_respond(mon, rsp, id);
4186 qobject_unref(rsp);
4190 * Pop a QMP request from a monitor request queue.
4191 * Return the request, or NULL all request queues are empty.
4192 * We are using round-robin fashion to pop the request, to avoid
4193 * processing commands only on a very busy monitor. To achieve that,
4194 * when we process one request on a specific monitor, we put that
4195 * monitor to the end of mon_list queue.
4197 static QMPRequest *monitor_qmp_requests_pop_any(void)
4199 QMPRequest *req_obj = NULL;
4200 Monitor *mon;
4202 qemu_mutex_lock(&monitor_lock);
4204 QTAILQ_FOREACH(mon, &mon_list, entry) {
4205 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
4206 req_obj = g_queue_pop_head(mon->qmp.qmp_requests);
4207 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
4208 if (req_obj) {
4209 break;
4213 if (req_obj) {
4215 * We found one request on the monitor. Degrade this monitor's
4216 * priority to lowest by re-inserting it to end of queue.
4218 QTAILQ_REMOVE(&mon_list, mon, entry);
4219 QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
4222 qemu_mutex_unlock(&monitor_lock);
4224 return req_obj;
4227 static void monitor_qmp_bh_dispatcher(void *data)
4229 QMPRequest *req_obj = monitor_qmp_requests_pop_any();
4230 QDict *rsp;
4232 if (!req_obj) {
4233 return;
4236 if (req_obj->req) {
4237 trace_monitor_qmp_cmd_in_band(qobject_get_try_str(req_obj->id) ?: "");
4238 monitor_qmp_dispatch(req_obj->mon, req_obj->req, req_obj->id);
4239 } else {
4240 assert(req_obj->err);
4241 rsp = qmp_error_response(req_obj->err);
4242 req_obj->err = NULL;
4243 monitor_qmp_respond(req_obj->mon, rsp, NULL);
4244 qobject_unref(rsp);
4247 if (req_obj->need_resume) {
4248 /* Pairs with the monitor_suspend() in handle_qmp_command() */
4249 monitor_resume(req_obj->mon);
4251 qmp_request_free(req_obj);
4253 /* Reschedule instead of looping so the main loop stays responsive */
4254 qemu_bh_schedule(qmp_dispatcher_bh);
4257 #define QMP_REQ_QUEUE_LEN_MAX (8)
4259 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
4261 QObject *req, *id = NULL;
4262 QDict *qdict;
4263 MonitorQMP *mon_qmp = container_of(parser, MonitorQMP, parser);
4264 Monitor *mon = container_of(mon_qmp, Monitor, qmp);
4265 Error *err = NULL;
4266 QMPRequest *req_obj;
4268 req = json_parser_parse_err(tokens, NULL, &err);
4269 if (!req && !err) {
4270 /* json_parser_parse_err() sucks: can fail without setting @err */
4271 error_setg(&err, QERR_JSON_PARSING);
4274 qdict = qobject_to(QDict, req);
4275 if (qdict) {
4276 id = qobject_ref(qdict_get(qdict, "id"));
4277 qdict_del(qdict, "id");
4278 } /* else will fail qmp_dispatch() */
4280 if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
4281 QString *req_json = qobject_to_json(req);
4282 trace_handle_qmp_command(mon, qstring_get_str(req_json));
4283 qobject_unref(req_json);
4286 if (qdict && qmp_is_oob(qdict)) {
4287 /* OOB commands are executed immediately */
4288 trace_monitor_qmp_cmd_out_of_band(qobject_get_try_str(id)
4289 ?: "");
4290 monitor_qmp_dispatch(mon, req, id);
4291 qobject_unref(req);
4292 qobject_unref(id);
4293 return;
4296 req_obj = g_new0(QMPRequest, 1);
4297 req_obj->mon = mon;
4298 req_obj->id = id;
4299 req_obj->req = req;
4300 req_obj->err = err;
4301 req_obj->need_resume = false;
4303 /* Protect qmp_requests and fetching its length. */
4304 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
4307 * If OOB is not enabled on the current monitor, we'll emulate the
4308 * old behavior that we won't process the current monitor any more
4309 * until it has responded. This helps make sure that as long as
4310 * OOB is not enabled, the server will never drop any command.
4312 if (!qmp_oob_enabled(mon)) {
4313 monitor_suspend(mon);
4314 req_obj->need_resume = true;
4315 } else {
4316 /* Drop the request if queue is full. */
4317 if (mon->qmp.qmp_requests->length >= QMP_REQ_QUEUE_LEN_MAX) {
4318 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
4320 * FIXME @id's scope is just @mon, and broadcasting it is
4321 * wrong. If another monitor's client has a command with
4322 * the same ID in flight, the event will incorrectly claim
4323 * that command was dropped.
4325 qapi_event_send_command_dropped(id,
4326 COMMAND_DROP_REASON_QUEUE_FULL,
4327 &error_abort);
4328 qmp_request_free(req_obj);
4329 return;
4334 * Put the request to the end of queue so that requests will be
4335 * handled in time order. Ownership for req_obj, req, id,
4336 * etc. will be delivered to the handler side.
4338 g_queue_push_tail(mon->qmp.qmp_requests, req_obj);
4339 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
4341 /* Kick the dispatcher routine */
4342 qemu_bh_schedule(qmp_dispatcher_bh);
4345 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
4347 Monitor *mon = opaque;
4349 json_message_parser_feed(&mon->qmp.parser, (const char *) buf, size);
4352 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4354 Monitor *old_mon = cur_mon;
4355 int i;
4357 cur_mon = opaque;
4359 if (cur_mon->rs) {
4360 for (i = 0; i < size; i++)
4361 readline_handle_byte(cur_mon->rs, buf[i]);
4362 } else {
4363 if (size == 0 || buf[size - 1] != 0)
4364 monitor_printf(cur_mon, "corrupted command\n");
4365 else
4366 handle_hmp_command(cur_mon, (char *)buf);
4369 cur_mon = old_mon;
4372 static void monitor_command_cb(void *opaque, const char *cmdline,
4373 void *readline_opaque)
4375 Monitor *mon = opaque;
4377 monitor_suspend(mon);
4378 handle_hmp_command(mon, cmdline);
4379 monitor_resume(mon);
4382 int monitor_suspend(Monitor *mon)
4384 if (monitor_is_hmp_non_interactive(mon)) {
4385 return -ENOTTY;
4388 atomic_inc(&mon->suspend_cnt);
4390 if (monitor_is_qmp(mon)) {
4392 * Kick I/O thread to make sure this takes effect. It'll be
4393 * evaluated again in prepare() of the watch object.
4395 aio_notify(iothread_get_aio_context(mon_iothread));
4398 trace_monitor_suspend(mon, 1);
4399 return 0;
4402 void monitor_resume(Monitor *mon)
4404 if (monitor_is_hmp_non_interactive(mon)) {
4405 return;
4408 if (atomic_dec_fetch(&mon->suspend_cnt) == 0) {
4409 if (monitor_is_qmp(mon)) {
4411 * For QMP monitors that are running in the I/O thread,
4412 * let's kick the thread in case it's sleeping.
4414 if (mon->use_io_thread) {
4415 aio_notify(iothread_get_aio_context(mon_iothread));
4417 } else {
4418 assert(mon->rs);
4419 readline_show_prompt(mon->rs);
4422 trace_monitor_suspend(mon, -1);
4425 static QDict *qmp_greeting(Monitor *mon)
4427 QList *cap_list = qlist_new();
4428 QObject *ver = NULL;
4429 QMPCapability cap;
4431 qmp_marshal_query_version(NULL, &ver, NULL);
4433 for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
4434 if (mon->qmp.capab_offered[cap]) {
4435 qlist_append_str(cap_list, QMPCapability_str(cap));
4439 return qdict_from_jsonf_nofail(
4440 "{'QMP': {'version': %p, 'capabilities': %p}}",
4441 ver, cap_list);
4444 static void monitor_qmp_event(void *opaque, int event)
4446 QDict *data;
4447 Monitor *mon = opaque;
4449 switch (event) {
4450 case CHR_EVENT_OPENED:
4451 mon->qmp.commands = &qmp_cap_negotiation_commands;
4452 monitor_qmp_caps_reset(mon);
4453 data = qmp_greeting(mon);
4454 qmp_queue_response(mon, data);
4455 qobject_unref(data);
4456 mon_refcount++;
4457 break;
4458 case CHR_EVENT_CLOSED:
4460 * Note: this is only useful when the output of the chardev
4461 * backend is still open. For example, when the backend is
4462 * stdio, it's possible that stdout is still open when stdin
4463 * is closed.
4465 monitor_qmp_response_flush(mon);
4466 monitor_qmp_cleanup_queues(mon);
4467 json_message_parser_destroy(&mon->qmp.parser);
4468 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4469 mon_refcount--;
4470 monitor_fdsets_cleanup();
4471 break;
4475 static void monitor_event(void *opaque, int event)
4477 Monitor *mon = opaque;
4479 switch (event) {
4480 case CHR_EVENT_MUX_IN:
4481 qemu_mutex_lock(&mon->mon_lock);
4482 mon->mux_out = 0;
4483 qemu_mutex_unlock(&mon->mon_lock);
4484 if (mon->reset_seen) {
4485 readline_restart(mon->rs);
4486 monitor_resume(mon);
4487 monitor_flush(mon);
4488 } else {
4489 atomic_mb_set(&mon->suspend_cnt, 0);
4491 break;
4493 case CHR_EVENT_MUX_OUT:
4494 if (mon->reset_seen) {
4495 if (atomic_mb_read(&mon->suspend_cnt) == 0) {
4496 monitor_printf(mon, "\n");
4498 monitor_flush(mon);
4499 monitor_suspend(mon);
4500 } else {
4501 atomic_inc(&mon->suspend_cnt);
4503 qemu_mutex_lock(&mon->mon_lock);
4504 mon->mux_out = 1;
4505 qemu_mutex_unlock(&mon->mon_lock);
4506 break;
4508 case CHR_EVENT_OPENED:
4509 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4510 "information\n", QEMU_VERSION);
4511 if (!mon->mux_out) {
4512 readline_restart(mon->rs);
4513 readline_show_prompt(mon->rs);
4515 mon->reset_seen = 1;
4516 mon_refcount++;
4517 break;
4519 case CHR_EVENT_CLOSED:
4520 mon_refcount--;
4521 monitor_fdsets_cleanup();
4522 break;
4526 static int
4527 compare_mon_cmd(const void *a, const void *b)
4529 return strcmp(((const mon_cmd_t *)a)->name,
4530 ((const mon_cmd_t *)b)->name);
4533 static void sortcmdlist(void)
4535 int array_num;
4536 int elem_size = sizeof(mon_cmd_t);
4538 array_num = sizeof(mon_cmds)/elem_size-1;
4539 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4541 array_num = sizeof(info_cmds)/elem_size-1;
4542 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4545 static GMainContext *monitor_get_io_context(void)
4547 return iothread_get_g_main_context(mon_iothread);
4550 static AioContext *monitor_get_aio_context(void)
4552 return iothread_get_aio_context(mon_iothread);
4555 static void monitor_iothread_init(void)
4557 mon_iothread = iothread_create("mon_iothread", &error_abort);
4560 * The dispatcher BH must run in the main loop thread, since we
4561 * have commands assuming that context. It would be nice to get
4562 * rid of those assumptions.
4564 qmp_dispatcher_bh = aio_bh_new(iohandler_get_aio_context(),
4565 monitor_qmp_bh_dispatcher,
4566 NULL);
4569 * The responder BH must be run in the monitor I/O thread, so that
4570 * monitors that are using the I/O thread have their output
4571 * written by the I/O thread.
4573 qmp_respond_bh = aio_bh_new(monitor_get_aio_context(),
4574 monitor_qmp_bh_responder,
4575 NULL);
4578 void monitor_init_globals(void)
4580 monitor_init_qmp_commands();
4581 monitor_qapi_event_init();
4582 sortcmdlist();
4583 qemu_mutex_init(&monitor_lock);
4584 qemu_mutex_init(&mon_fdsets_lock);
4585 monitor_iothread_init();
4588 /* These functions just adapt the readline interface in a typesafe way. We
4589 * could cast function pointers but that discards compiler checks.
4591 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4592 const char *fmt, ...)
4594 va_list ap;
4595 va_start(ap, fmt);
4596 monitor_vprintf(opaque, fmt, ap);
4597 va_end(ap);
4600 static void monitor_readline_flush(void *opaque)
4602 monitor_flush(opaque);
4606 * Print to current monitor if we have one, else to stderr.
4607 * TODO should return int, so callers can calculate width, but that
4608 * requires surgery to monitor_vprintf(). Left for another day.
4610 void error_vprintf(const char *fmt, va_list ap)
4612 if (cur_mon && !monitor_cur_is_qmp()) {
4613 monitor_vprintf(cur_mon, fmt, ap);
4614 } else {
4615 vfprintf(stderr, fmt, ap);
4619 void error_vprintf_unless_qmp(const char *fmt, va_list ap)
4621 if (cur_mon && !monitor_cur_is_qmp()) {
4622 monitor_vprintf(cur_mon, fmt, ap);
4623 } else if (!cur_mon) {
4624 vfprintf(stderr, fmt, ap);
4628 static void monitor_list_append(Monitor *mon)
4630 qemu_mutex_lock(&monitor_lock);
4631 QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
4632 qemu_mutex_unlock(&monitor_lock);
4635 static void monitor_qmp_setup_handlers_bh(void *opaque)
4637 Monitor *mon = opaque;
4638 GMainContext *context;
4640 if (mon->use_io_thread) {
4641 /* Use @mon_iothread context */
4642 context = monitor_get_io_context();
4643 assert(context);
4644 } else {
4645 /* Use default main loop context */
4646 context = NULL;
4649 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
4650 monitor_qmp_event, NULL, mon, context, true);
4651 monitor_list_append(mon);
4654 void monitor_init(Chardev *chr, int flags)
4656 Monitor *mon = g_malloc(sizeof(*mon));
4657 bool use_readline = flags & MONITOR_USE_READLINE;
4658 bool use_oob = flags & MONITOR_USE_OOB;
4660 if (use_oob) {
4661 if (CHARDEV_IS_MUX(chr)) {
4662 error_report("Monitor out-of-band is not supported with "
4663 "MUX typed chardev backend");
4664 exit(1);
4666 if (use_readline) {
4667 error_report("Monitor out-of-band is only supported by QMP");
4668 exit(1);
4672 monitor_data_init(mon, false, use_oob);
4674 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
4675 mon->flags = flags;
4676 if (use_readline) {
4677 mon->rs = readline_init(monitor_readline_printf,
4678 monitor_readline_flush,
4679 mon,
4680 monitor_find_completion);
4681 monitor_read_command(mon, 0);
4684 if (monitor_is_qmp(mon)) {
4685 qemu_chr_fe_set_echo(&mon->chr, true);
4686 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4687 if (mon->use_io_thread) {
4689 * Make sure the old iowatch is gone. It's possible when
4690 * e.g. the chardev is in client mode, with wait=on.
4692 remove_fd_in_watch(chr);
4694 * We can't call qemu_chr_fe_set_handlers() directly here
4695 * since chardev might be running in the monitor I/O
4696 * thread. Schedule a bottom half.
4698 aio_bh_schedule_oneshot(monitor_get_aio_context(),
4699 monitor_qmp_setup_handlers_bh, mon);
4700 /* The bottom half will add @mon to @mon_list */
4701 return;
4702 } else {
4703 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read,
4704 monitor_qmp_read, monitor_qmp_event,
4705 NULL, mon, NULL, true);
4707 } else {
4708 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
4709 monitor_event, NULL, mon, NULL, true);
4712 monitor_list_append(mon);
4715 void monitor_cleanup(void)
4717 Monitor *mon, *next;
4720 * We need to explicitly stop the I/O thread (but not destroy it),
4721 * clean up the monitor resources, then destroy the I/O thread since
4722 * we need to unregister from chardev below in
4723 * monitor_data_destroy(), and chardev is not thread-safe yet
4725 iothread_stop(mon_iothread);
4728 * Flush all response queues. Note that even after this flush,
4729 * data may remain in output buffers.
4731 monitor_qmp_bh_responder(NULL);
4733 /* Flush output buffers and destroy monitors */
4734 qemu_mutex_lock(&monitor_lock);
4735 QTAILQ_FOREACH_SAFE(mon, &mon_list, entry, next) {
4736 QTAILQ_REMOVE(&mon_list, mon, entry);
4737 monitor_flush(mon);
4738 monitor_data_destroy(mon);
4739 g_free(mon);
4741 qemu_mutex_unlock(&monitor_lock);
4743 /* QEMUBHs needs to be deleted before destroying the I/O thread */
4744 qemu_bh_delete(qmp_dispatcher_bh);
4745 qmp_dispatcher_bh = NULL;
4746 qemu_bh_delete(qmp_respond_bh);
4747 qmp_respond_bh = NULL;
4749 iothread_destroy(mon_iothread);
4750 mon_iothread = NULL;
4753 QemuOptsList qemu_mon_opts = {
4754 .name = "mon",
4755 .implied_opt_name = "chardev",
4756 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4757 .desc = {
4759 .name = "mode",
4760 .type = QEMU_OPT_STRING,
4762 .name = "chardev",
4763 .type = QEMU_OPT_STRING,
4765 .name = "pretty",
4766 .type = QEMU_OPT_BOOL,
4768 .name = "x-oob",
4769 .type = QEMU_OPT_BOOL,
4771 { /* end of list */ }
4775 #ifndef TARGET_I386
4776 void qmp_rtc_reset_reinjection(Error **errp)
4778 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4781 SevInfo *qmp_query_sev(Error **errp)
4783 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev");
4784 return NULL;
4787 SevLaunchMeasureInfo *qmp_query_sev_launch_measure(Error **errp)
4789 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev-launch-measure");
4790 return NULL;
4793 SevCapability *qmp_query_sev_capabilities(Error **errp)
4795 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev-capabilities");
4796 return NULL;
4798 #endif
4800 #ifndef TARGET_S390X
4801 void qmp_dump_skeys(const char *filename, Error **errp)
4803 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4805 #endif
4807 #ifndef TARGET_ARM
4808 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4810 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4811 return NULL;
4813 #endif
4815 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4817 MachineState *ms = MACHINE(qdev_get_machine());
4818 MachineClass *mc = MACHINE_GET_CLASS(ms);
4820 if (!mc->has_hotpluggable_cpus) {
4821 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4822 return NULL;
4825 return machine_query_hotpluggable_cpus(ms);