]> git.proxmox.com Git - mirror_qemu.git/blob - monitor/misc.c
Move monitor.c to monitor/misc.c
[mirror_qemu.git] / monitor / misc.c
1 /*
2 * QEMU monitor
3 *
4 * Copyright (c) 2003-2004 Fabrice Bellard
5 *
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:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
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.
23 */
24
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/ctype.h"
46 #include "qemu/readline.h"
47 #include "ui/console.h"
48 #include "ui/input.h"
49 #include "sysemu/block-backend.h"
50 #include "audio/audio.h"
51 #include "disas/disas.h"
52 #include "sysemu/balloon.h"
53 #include "qemu/timer.h"
54 #include "sysemu/hw_accel.h"
55 #include "authz/list.h"
56 #include "qapi/util.h"
57 #include "sysemu/tcg.h"
58 #include "sysemu/tpm.h"
59 #include "qapi/qmp/qdict.h"
60 #include "qapi/qmp/qerror.h"
61 #include "qapi/qmp/qnum.h"
62 #include "qapi/qmp/qstring.h"
63 #include "qapi/qmp/qjson.h"
64 #include "qapi/qmp/json-parser.h"
65 #include "qapi/qmp/qlist.h"
66 #include "qom/object_interfaces.h"
67 #include "trace.h"
68 #include "trace/control.h"
69 #include "monitor/hmp-target.h"
70 #ifdef CONFIG_TRACE_SIMPLE
71 #include "trace/simple.h"
72 #endif
73 #include "exec/memory.h"
74 #include "exec/exec-all.h"
75 #include "qemu/log.h"
76 #include "qemu/option.h"
77 #include "hmp.h"
78 #include "qemu/thread.h"
79 #include "block/qapi.h"
80 #include "qapi/qapi-commands.h"
81 #include "qapi/qapi-emit-events.h"
82 #include "qapi/error.h"
83 #include "qapi/qmp-event.h"
84 #include "qapi/qapi-introspect.h"
85 #include "sysemu/qtest.h"
86 #include "sysemu/cpus.h"
87 #include "sysemu/iothread.h"
88 #include "qemu/cutils.h"
89 #include "tcg/tcg.h"
90
91 #if defined(TARGET_S390X)
92 #include "hw/s390x/storage-keys.h"
93 #include "hw/s390x/storage-attributes.h"
94 #endif
95
96 /*
97 * Supported types:
98 *
99 * 'F' filename
100 * 'B' block device name
101 * 's' string (accept optional quote)
102 * 'S' it just appends the rest of the string (accept optional quote)
103 * 'O' option string of the form NAME=VALUE,...
104 * parsed according to QemuOptsList given by its name
105 * Example: 'device:O' uses qemu_device_opts.
106 * Restriction: only lists with empty desc are supported
107 * TODO lift the restriction
108 * 'i' 32 bit integer
109 * 'l' target long (32 or 64 bit)
110 * 'M' Non-negative target long (32 or 64 bit), in user mode the
111 * value is multiplied by 2^20 (think Mebibyte)
112 * 'o' octets (aka bytes)
113 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
114 * K, k suffix, which multiplies the value by 2^60 for suffixes E
115 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
116 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
117 * 'T' double
118 * user mode accepts an optional ms, us, ns suffix,
119 * which divides the value by 1e3, 1e6, 1e9, respectively
120 * '/' optional gdb-like print format (like "/10x")
121 *
122 * '?' optional type (for all types, except '/')
123 * '.' other form of optional type (for 'i' and 'l')
124 * 'b' boolean
125 * user mode accepts "on" or "off"
126 * '-' optional parameter (eg. '-f')
127 *
128 */
129
130 typedef struct HMPCommand {
131 const char *name;
132 const char *args_type;
133 const char *params;
134 const char *help;
135 const char *flags; /* p=preconfig */
136 void (*cmd)(Monitor *mon, const QDict *qdict);
137 /* @sub_table is a list of 2nd level of commands. If it does not exist,
138 * cmd should be used. If it exists, sub_table[?].cmd should be
139 * used, and cmd of 1st level plays the role of help function.
140 */
141 struct HMPCommand *sub_table;
142 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
143 } HMPCommand;
144
145 /* file descriptors passed via SCM_RIGHTS */
146 typedef struct mon_fd_t mon_fd_t;
147 struct mon_fd_t {
148 char *name;
149 int fd;
150 QLIST_ENTRY(mon_fd_t) next;
151 };
152
153 /* file descriptor associated with a file descriptor set */
154 typedef struct MonFdsetFd MonFdsetFd;
155 struct MonFdsetFd {
156 int fd;
157 bool removed;
158 char *opaque;
159 QLIST_ENTRY(MonFdsetFd) next;
160 };
161
162 /* file descriptor set containing fds passed via SCM_RIGHTS */
163 typedef struct MonFdset MonFdset;
164 struct MonFdset {
165 int64_t id;
166 QLIST_HEAD(, MonFdsetFd) fds;
167 QLIST_HEAD(, MonFdsetFd) dup_fds;
168 QLIST_ENTRY(MonFdset) next;
169 };
170
171 /*
172 * To prevent flooding clients, events can be throttled. The
173 * throttling is calculated globally, rather than per-Monitor
174 * instance.
175 */
176 typedef struct MonitorQAPIEventState {
177 QAPIEvent event; /* Throttling state for this event type and... */
178 QDict *data; /* ... data, see qapi_event_throttle_equal() */
179 QEMUTimer *timer; /* Timer for handling delayed events */
180 QDict *qdict; /* Delayed event (if any) */
181 } MonitorQAPIEventState;
182
183 typedef struct {
184 int64_t rate; /* Minimum time (in ns) between two events */
185 } MonitorQAPIEventConf;
186
187 struct Monitor {
188 CharBackend chr;
189 int reset_seen;
190 int flags;
191 int suspend_cnt; /* Needs to be accessed atomically */
192 bool skip_flush;
193 bool use_io_thread;
194
195 gchar *mon_cpu_path;
196 QTAILQ_ENTRY(Monitor) entry;
197
198 /*
199 * The per-monitor lock. We can't access guest memory when holding
200 * the lock.
201 */
202 QemuMutex mon_lock;
203
204 /*
205 * Members that are protected by the per-monitor lock
206 */
207 QLIST_HEAD(, mon_fd_t) fds;
208 QString *outbuf;
209 guint out_watch;
210 /* Read under either BQL or mon_lock, written with BQL+mon_lock. */
211 int mux_out;
212 };
213
214 struct MonitorHMP {
215 Monitor common;
216 /*
217 * State used only in the thread "owning" the monitor.
218 * If @use_io_thread, this is @mon_iothread. (This does not actually happen
219 * in the current state of the code.)
220 * Else, it's the main thread.
221 * These members can be safely accessed without locks.
222 */
223 ReadLineState *rs;
224 };
225
226 typedef struct {
227 Monitor common;
228 JSONMessageParser parser;
229 /*
230 * When a client connects, we're in capabilities negotiation mode.
231 * @commands is &qmp_cap_negotiation_commands then. When command
232 * qmp_capabilities succeeds, we go into command mode, and
233 * @command becomes &qmp_commands.
234 */
235 QmpCommandList *commands;
236 bool capab_offered[QMP_CAPABILITY__MAX]; /* capabilities offered */
237 bool capab[QMP_CAPABILITY__MAX]; /* offered and accepted */
238 /*
239 * Protects qmp request/response queue.
240 * Take monitor_lock first when you need both.
241 */
242 QemuMutex qmp_queue_lock;
243 /* Input queue that holds all the parsed QMP requests */
244 GQueue *qmp_requests;
245 } MonitorQMP;
246
247 /* Shared monitor I/O thread */
248 IOThread *mon_iothread;
249
250 /* Bottom half to dispatch the requests received from I/O thread */
251 QEMUBH *qmp_dispatcher_bh;
252
253 struct QMPRequest {
254 /* Owner of the request */
255 MonitorQMP *mon;
256 /*
257 * Request object to be handled or Error to be reported
258 * (exactly one of them is non-null)
259 */
260 QObject *req;
261 Error *err;
262 };
263 typedef struct QMPRequest QMPRequest;
264
265 /* QMP checker flags */
266 #define QMP_ACCEPT_UNKNOWNS 1
267
268 /* Protects mon_list, monitor_qapi_event_state, monitor_destroyed. */
269 static QemuMutex monitor_lock;
270 static GHashTable *monitor_qapi_event_state;
271 static QTAILQ_HEAD(, Monitor) mon_list;
272 static bool monitor_destroyed;
273
274 /* Protects mon_fdsets */
275 static QemuMutex mon_fdsets_lock;
276 static QLIST_HEAD(, MonFdset) mon_fdsets;
277
278 static int mon_refcount;
279
280 static HMPCommand hmp_cmds[];
281 static HMPCommand hmp_info_cmds[];
282
283 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
284
285 __thread Monitor *cur_mon;
286
287 static void monitor_command_cb(void *opaque, const char *cmdline,
288 void *readline_opaque);
289
290 /**
291 * Is @mon a QMP monitor?
292 */
293 static inline bool monitor_is_qmp(const Monitor *mon)
294 {
295 return (mon->flags & MONITOR_USE_CONTROL);
296 }
297
298 /**
299 * Is @mon is using readline?
300 * Note: not all HMP monitors use readline, e.g., gdbserver has a
301 * non-interactive HMP monitor, so readline is not used there.
302 */
303 static inline bool monitor_uses_readline(const Monitor *mon)
304 {
305 return mon->flags & MONITOR_USE_READLINE;
306 }
307
308 static inline bool monitor_is_hmp_non_interactive(const Monitor *mon)
309 {
310 return !monitor_is_qmp(mon) && !monitor_uses_readline(mon);
311 }
312
313 /*
314 * Return the clock to use for recording an event's time.
315 * It's QEMU_CLOCK_REALTIME, except for qtests it's
316 * QEMU_CLOCK_VIRTUAL, to support testing rate limits.
317 * Beware: result is invalid before configure_accelerator().
318 */
319 static inline QEMUClockType monitor_get_event_clock(void)
320 {
321 return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME;
322 }
323
324 /**
325 * Is the current monitor, if any, a QMP monitor?
326 */
327 bool monitor_cur_is_qmp(void)
328 {
329 return cur_mon && monitor_is_qmp(cur_mon);
330 }
331
332 void monitor_read_command(MonitorHMP *mon, int show_prompt)
333 {
334 if (!mon->rs)
335 return;
336
337 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
338 if (show_prompt)
339 readline_show_prompt(mon->rs);
340 }
341
342 int monitor_read_password(MonitorHMP *mon, ReadLineFunc *readline_func,
343 void *opaque)
344 {
345 if (mon->rs) {
346 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
347 /* prompt is printed on return from the command handler */
348 return 0;
349 } else {
350 monitor_printf(&mon->common,
351 "terminal does not support password prompting\n");
352 return -ENOTTY;
353 }
354 }
355
356 static void qmp_request_free(QMPRequest *req)
357 {
358 qobject_unref(req->req);
359 error_free(req->err);
360 g_free(req);
361 }
362
363 /* Caller must hold mon->qmp.qmp_queue_lock */
364 static void monitor_qmp_cleanup_req_queue_locked(MonitorQMP *mon)
365 {
366 while (!g_queue_is_empty(mon->qmp_requests)) {
367 qmp_request_free(g_queue_pop_head(mon->qmp_requests));
368 }
369 }
370
371 static void monitor_qmp_cleanup_queues(MonitorQMP *mon)
372 {
373 qemu_mutex_lock(&mon->qmp_queue_lock);
374 monitor_qmp_cleanup_req_queue_locked(mon);
375 qemu_mutex_unlock(&mon->qmp_queue_lock);
376 }
377
378
379 static void monitor_flush_locked(Monitor *mon);
380
381 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
382 void *opaque)
383 {
384 Monitor *mon = opaque;
385
386 qemu_mutex_lock(&mon->mon_lock);
387 mon->out_watch = 0;
388 monitor_flush_locked(mon);
389 qemu_mutex_unlock(&mon->mon_lock);
390 return FALSE;
391 }
392
393 /* Caller must hold mon->mon_lock */
394 static void monitor_flush_locked(Monitor *mon)
395 {
396 int rc;
397 size_t len;
398 const char *buf;
399
400 if (mon->skip_flush) {
401 return;
402 }
403
404 buf = qstring_get_str(mon->outbuf);
405 len = qstring_get_length(mon->outbuf);
406
407 if (len && !mon->mux_out) {
408 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
409 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
410 /* all flushed or error */
411 qobject_unref(mon->outbuf);
412 mon->outbuf = qstring_new();
413 return;
414 }
415 if (rc > 0) {
416 /* partial write */
417 QString *tmp = qstring_from_str(buf + rc);
418 qobject_unref(mon->outbuf);
419 mon->outbuf = tmp;
420 }
421 if (mon->out_watch == 0) {
422 mon->out_watch =
423 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
424 monitor_unblocked, mon);
425 }
426 }
427 }
428
429 void monitor_flush(Monitor *mon)
430 {
431 qemu_mutex_lock(&mon->mon_lock);
432 monitor_flush_locked(mon);
433 qemu_mutex_unlock(&mon->mon_lock);
434 }
435
436 /* flush at every end of line */
437 static int monitor_puts(Monitor *mon, const char *str)
438 {
439 int i;
440 char c;
441
442 qemu_mutex_lock(&mon->mon_lock);
443 for (i = 0; str[i]; i++) {
444 c = str[i];
445 if (c == '\n') {
446 qstring_append_chr(mon->outbuf, '\r');
447 }
448 qstring_append_chr(mon->outbuf, c);
449 if (c == '\n') {
450 monitor_flush_locked(mon);
451 }
452 }
453 qemu_mutex_unlock(&mon->mon_lock);
454
455 return i;
456 }
457
458 int monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
459 {
460 char *buf;
461 int n;
462
463 if (!mon)
464 return -1;
465
466 if (monitor_is_qmp(mon)) {
467 return -1;
468 }
469
470 buf = g_strdup_vprintf(fmt, ap);
471 n = monitor_puts(mon, buf);
472 g_free(buf);
473 return n;
474 }
475
476 int monitor_printf(Monitor *mon, const char *fmt, ...)
477 {
478 int ret;
479
480 va_list ap;
481 va_start(ap, fmt);
482 ret = monitor_vprintf(mon, fmt, ap);
483 va_end(ap);
484 return ret;
485 }
486
487 static void qmp_send_response(MonitorQMP *mon, const QDict *rsp)
488 {
489 const QObject *data = QOBJECT(rsp);
490 QString *json;
491
492 json = mon->common.flags & MONITOR_USE_PRETTY ?
493 qobject_to_json_pretty(data) : qobject_to_json(data);
494 assert(json != NULL);
495
496 qstring_append_chr(json, '\n');
497 monitor_puts(&mon->common, qstring_get_str(json));
498
499 qobject_unref(json);
500 }
501
502 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
503 /* Limit guest-triggerable events to 1 per second */
504 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
505 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
506 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
507 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
508 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
509 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
510 };
511
512 /*
513 * Broadcast an event to all monitors.
514 * @qdict is the event object. Its member "event" must match @event.
515 * Caller must hold monitor_lock.
516 */
517 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
518 {
519 Monitor *mon;
520 MonitorQMP *qmp_mon;
521
522 trace_monitor_protocol_event_emit(event, qdict);
523 QTAILQ_FOREACH(mon, &mon_list, entry) {
524 if (!monitor_is_qmp(mon)) {
525 continue;
526 }
527
528 qmp_mon = container_of(mon, MonitorQMP, common);
529 if (qmp_mon->commands != &qmp_cap_negotiation_commands) {
530 qmp_send_response(qmp_mon, qdict);
531 }
532 }
533 }
534
535 static void monitor_qapi_event_handler(void *opaque);
536
537 /*
538 * Queue a new event for emission to Monitor instances,
539 * applying any rate limiting if required.
540 */
541 static void
542 monitor_qapi_event_queue_no_reenter(QAPIEvent event, QDict *qdict)
543 {
544 MonitorQAPIEventConf *evconf;
545 MonitorQAPIEventState *evstate;
546
547 assert(event < QAPI_EVENT__MAX);
548 evconf = &monitor_qapi_event_conf[event];
549 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
550
551 qemu_mutex_lock(&monitor_lock);
552
553 if (!evconf->rate) {
554 /* Unthrottled event */
555 monitor_qapi_event_emit(event, qdict);
556 } else {
557 QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
558 MonitorQAPIEventState key = { .event = event, .data = data };
559
560 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
561 assert(!evstate || timer_pending(evstate->timer));
562
563 if (evstate) {
564 /*
565 * Timer is pending for (at least) evconf->rate ns after
566 * last send. Store event for sending when timer fires,
567 * replacing a prior stored event if any.
568 */
569 qobject_unref(evstate->qdict);
570 evstate->qdict = qobject_ref(qdict);
571 } else {
572 /*
573 * Last send was (at least) evconf->rate ns ago.
574 * Send immediately, and arm the timer to call
575 * monitor_qapi_event_handler() in evconf->rate ns. Any
576 * events arriving before then will be delayed until then.
577 */
578 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
579
580 monitor_qapi_event_emit(event, qdict);
581
582 evstate = g_new(MonitorQAPIEventState, 1);
583 evstate->event = event;
584 evstate->data = qobject_ref(data);
585 evstate->qdict = NULL;
586 evstate->timer = timer_new_ns(monitor_get_event_clock(),
587 monitor_qapi_event_handler,
588 evstate);
589 g_hash_table_add(monitor_qapi_event_state, evstate);
590 timer_mod_ns(evstate->timer, now + evconf->rate);
591 }
592 }
593
594 qemu_mutex_unlock(&monitor_lock);
595 }
596
597 void qapi_event_emit(QAPIEvent event, QDict *qdict)
598 {
599 /*
600 * monitor_qapi_event_queue_no_reenter() is not reentrant: it
601 * would deadlock on monitor_lock. Work around by queueing
602 * events in thread-local storage.
603 * TODO: remove this, make it re-enter safe.
604 */
605 typedef struct MonitorQapiEvent {
606 QAPIEvent event;
607 QDict *qdict;
608 QSIMPLEQ_ENTRY(MonitorQapiEvent) entry;
609 } MonitorQapiEvent;
610 static __thread QSIMPLEQ_HEAD(, MonitorQapiEvent) event_queue;
611 static __thread bool reentered;
612 MonitorQapiEvent *ev;
613
614 if (!reentered) {
615 QSIMPLEQ_INIT(&event_queue);
616 }
617
618 ev = g_new(MonitorQapiEvent, 1);
619 ev->qdict = qobject_ref(qdict);
620 ev->event = event;
621 QSIMPLEQ_INSERT_TAIL(&event_queue, ev, entry);
622 if (reentered) {
623 return;
624 }
625
626 reentered = true;
627
628 while ((ev = QSIMPLEQ_FIRST(&event_queue)) != NULL) {
629 QSIMPLEQ_REMOVE_HEAD(&event_queue, entry);
630 monitor_qapi_event_queue_no_reenter(ev->event, ev->qdict);
631 qobject_unref(ev->qdict);
632 g_free(ev);
633 }
634
635 reentered = false;
636 }
637
638 /*
639 * This function runs evconf->rate ns after sending a throttled
640 * event.
641 * If another event has since been stored, send it.
642 */
643 static void monitor_qapi_event_handler(void *opaque)
644 {
645 MonitorQAPIEventState *evstate = opaque;
646 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
647
648 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
649 qemu_mutex_lock(&monitor_lock);
650
651 if (evstate->qdict) {
652 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
653
654 monitor_qapi_event_emit(evstate->event, evstate->qdict);
655 qobject_unref(evstate->qdict);
656 evstate->qdict = NULL;
657 timer_mod_ns(evstate->timer, now + evconf->rate);
658 } else {
659 g_hash_table_remove(monitor_qapi_event_state, evstate);
660 qobject_unref(evstate->data);
661 timer_free(evstate->timer);
662 g_free(evstate);
663 }
664
665 qemu_mutex_unlock(&monitor_lock);
666 }
667
668 static unsigned int qapi_event_throttle_hash(const void *key)
669 {
670 const MonitorQAPIEventState *evstate = key;
671 unsigned int hash = evstate->event * 255;
672
673 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
674 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
675 }
676
677 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
678 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
679 }
680
681 return hash;
682 }
683
684 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
685 {
686 const MonitorQAPIEventState *eva = a;
687 const MonitorQAPIEventState *evb = b;
688
689 if (eva->event != evb->event) {
690 return FALSE;
691 }
692
693 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
694 return !strcmp(qdict_get_str(eva->data, "id"),
695 qdict_get_str(evb->data, "id"));
696 }
697
698 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
699 return !strcmp(qdict_get_str(eva->data, "node-name"),
700 qdict_get_str(evb->data, "node-name"));
701 }
702
703 return TRUE;
704 }
705
706 static void monitor_qapi_event_init(void)
707 {
708 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
709 qapi_event_throttle_equal);
710 }
711
712 static void handle_hmp_command(MonitorHMP *mon, const char *cmdline);
713
714 static void monitor_iothread_init(void);
715
716 static void monitor_data_init(Monitor *mon, int flags, bool skip_flush,
717 bool use_io_thread)
718 {
719 if (use_io_thread && !mon_iothread) {
720 monitor_iothread_init();
721 }
722 qemu_mutex_init(&mon->mon_lock);
723 mon->outbuf = qstring_new();
724 mon->skip_flush = skip_flush;
725 mon->use_io_thread = use_io_thread;
726 mon->flags = flags;
727 }
728
729 static void monitor_data_destroy_qmp(MonitorQMP *mon)
730 {
731 json_message_parser_destroy(&mon->parser);
732 qemu_mutex_destroy(&mon->qmp_queue_lock);
733 monitor_qmp_cleanup_req_queue_locked(mon);
734 g_queue_free(mon->qmp_requests);
735 }
736
737 static void monitor_data_destroy(Monitor *mon)
738 {
739 g_free(mon->mon_cpu_path);
740 qemu_chr_fe_deinit(&mon->chr, false);
741 if (monitor_is_qmp(mon)) {
742 monitor_data_destroy_qmp(container_of(mon, MonitorQMP, common));
743 } else {
744 readline_free(container_of(mon, MonitorHMP, common)->rs);
745 }
746 qobject_unref(mon->outbuf);
747 qemu_mutex_destroy(&mon->mon_lock);
748 }
749
750 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
751 int64_t cpu_index, Error **errp)
752 {
753 char *output = NULL;
754 Monitor *old_mon;
755 MonitorHMP hmp = {};
756
757 monitor_data_init(&hmp.common, 0, true, false);
758
759 old_mon = cur_mon;
760 cur_mon = &hmp.common;
761
762 if (has_cpu_index) {
763 int ret = monitor_set_cpu(cpu_index);
764 if (ret < 0) {
765 cur_mon = old_mon;
766 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
767 "a CPU number");
768 goto out;
769 }
770 }
771
772 handle_hmp_command(&hmp, command_line);
773 cur_mon = old_mon;
774
775 qemu_mutex_lock(&hmp.common.mon_lock);
776 if (qstring_get_length(hmp.common.outbuf) > 0) {
777 output = g_strdup(qstring_get_str(hmp.common.outbuf));
778 } else {
779 output = g_strdup("");
780 }
781 qemu_mutex_unlock(&hmp.common.mon_lock);
782
783 out:
784 monitor_data_destroy(&hmp.common);
785 return output;
786 }
787
788 static int compare_cmd(const char *name, const char *list)
789 {
790 const char *p, *pstart;
791 int len;
792 len = strlen(name);
793 p = list;
794 for(;;) {
795 pstart = p;
796 p = qemu_strchrnul(p, '|');
797 if ((p - pstart) == len && !memcmp(pstart, name, len))
798 return 1;
799 if (*p == '\0')
800 break;
801 p++;
802 }
803 return 0;
804 }
805
806 static int get_str(char *buf, int buf_size, const char **pp)
807 {
808 const char *p;
809 char *q;
810 int c;
811
812 q = buf;
813 p = *pp;
814 while (qemu_isspace(*p)) {
815 p++;
816 }
817 if (*p == '\0') {
818 fail:
819 *q = '\0';
820 *pp = p;
821 return -1;
822 }
823 if (*p == '\"') {
824 p++;
825 while (*p != '\0' && *p != '\"') {
826 if (*p == '\\') {
827 p++;
828 c = *p++;
829 switch (c) {
830 case 'n':
831 c = '\n';
832 break;
833 case 'r':
834 c = '\r';
835 break;
836 case '\\':
837 case '\'':
838 case '\"':
839 break;
840 default:
841 printf("unsupported escape code: '\\%c'\n", c);
842 goto fail;
843 }
844 if ((q - buf) < buf_size - 1) {
845 *q++ = c;
846 }
847 } else {
848 if ((q - buf) < buf_size - 1) {
849 *q++ = *p;
850 }
851 p++;
852 }
853 }
854 if (*p != '\"') {
855 printf("unterminated string\n");
856 goto fail;
857 }
858 p++;
859 } else {
860 while (*p != '\0' && !qemu_isspace(*p)) {
861 if ((q - buf) < buf_size - 1) {
862 *q++ = *p;
863 }
864 p++;
865 }
866 }
867 *q = '\0';
868 *pp = p;
869 return 0;
870 }
871
872 #define MAX_ARGS 16
873
874 static void free_cmdline_args(char **args, int nb_args)
875 {
876 int i;
877
878 assert(nb_args <= MAX_ARGS);
879
880 for (i = 0; i < nb_args; i++) {
881 g_free(args[i]);
882 }
883
884 }
885
886 /*
887 * Parse the command line to get valid args.
888 * @cmdline: command line to be parsed.
889 * @pnb_args: location to store the number of args, must NOT be NULL.
890 * @args: location to store the args, which should be freed by caller, must
891 * NOT be NULL.
892 *
893 * Returns 0 on success, negative on failure.
894 *
895 * NOTE: this parser is an approximate form of the real command parser. Number
896 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
897 * return with failure.
898 */
899 static int parse_cmdline(const char *cmdline,
900 int *pnb_args, char **args)
901 {
902 const char *p;
903 int nb_args, ret;
904 char buf[1024];
905
906 p = cmdline;
907 nb_args = 0;
908 for (;;) {
909 while (qemu_isspace(*p)) {
910 p++;
911 }
912 if (*p == '\0') {
913 break;
914 }
915 if (nb_args >= MAX_ARGS) {
916 goto fail;
917 }
918 ret = get_str(buf, sizeof(buf), &p);
919 if (ret < 0) {
920 goto fail;
921 }
922 args[nb_args] = g_strdup(buf);
923 nb_args++;
924 }
925 *pnb_args = nb_args;
926 return 0;
927
928 fail:
929 free_cmdline_args(args, nb_args);
930 return -1;
931 }
932
933 /*
934 * Can command @cmd be executed in preconfig state?
935 */
936 static bool cmd_can_preconfig(const HMPCommand *cmd)
937 {
938 if (!cmd->flags) {
939 return false;
940 }
941
942 return strchr(cmd->flags, 'p');
943 }
944
945 static void help_cmd_dump_one(Monitor *mon,
946 const HMPCommand *cmd,
947 char **prefix_args,
948 int prefix_args_nb)
949 {
950 int i;
951
952 if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
953 return;
954 }
955
956 for (i = 0; i < prefix_args_nb; i++) {
957 monitor_printf(mon, "%s ", prefix_args[i]);
958 }
959 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
960 }
961
962 /* @args[@arg_index] is the valid command need to find in @cmds */
963 static void help_cmd_dump(Monitor *mon, const HMPCommand *cmds,
964 char **args, int nb_args, int arg_index)
965 {
966 const HMPCommand *cmd;
967 size_t i;
968
969 /* No valid arg need to compare with, dump all in *cmds */
970 if (arg_index >= nb_args) {
971 for (cmd = cmds; cmd->name != NULL; cmd++) {
972 help_cmd_dump_one(mon, cmd, args, arg_index);
973 }
974 return;
975 }
976
977 /* Find one entry to dump */
978 for (cmd = cmds; cmd->name != NULL; cmd++) {
979 if (compare_cmd(args[arg_index], cmd->name) &&
980 ((!runstate_check(RUN_STATE_PRECONFIG) ||
981 cmd_can_preconfig(cmd)))) {
982 if (cmd->sub_table) {
983 /* continue with next arg */
984 help_cmd_dump(mon, cmd->sub_table,
985 args, nb_args, arg_index + 1);
986 } else {
987 help_cmd_dump_one(mon, cmd, args, arg_index);
988 }
989 return;
990 }
991 }
992
993 /* Command not found */
994 monitor_printf(mon, "unknown command: '");
995 for (i = 0; i <= arg_index; i++) {
996 monitor_printf(mon, "%s%s", args[i], i == arg_index ? "'\n" : " ");
997 }
998 }
999
1000 static void help_cmd(Monitor *mon, const char *name)
1001 {
1002 char *args[MAX_ARGS];
1003 int nb_args = 0;
1004
1005 /* 1. parse user input */
1006 if (name) {
1007 /* special case for log, directly dump and return */
1008 if (!strcmp(name, "log")) {
1009 const QEMULogItem *item;
1010 monitor_printf(mon, "Log items (comma separated):\n");
1011 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
1012 for (item = qemu_log_items; item->mask != 0; item++) {
1013 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
1014 }
1015 return;
1016 }
1017
1018 if (parse_cmdline(name, &nb_args, args) < 0) {
1019 return;
1020 }
1021 }
1022
1023 /* 2. dump the contents according to parsed args */
1024 help_cmd_dump(mon, hmp_cmds, args, nb_args, 0);
1025
1026 free_cmdline_args(args, nb_args);
1027 }
1028
1029 static void do_help_cmd(Monitor *mon, const QDict *qdict)
1030 {
1031 help_cmd(mon, qdict_get_try_str(qdict, "name"));
1032 }
1033
1034 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
1035 {
1036 const char *tp_name = qdict_get_str(qdict, "name");
1037 bool new_state = qdict_get_bool(qdict, "option");
1038 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1039 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1040 Error *local_err = NULL;
1041
1042 if (vcpu < 0) {
1043 monitor_printf(mon, "argument vcpu must be positive");
1044 return;
1045 }
1046
1047 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
1048 if (local_err) {
1049 error_report_err(local_err);
1050 }
1051 }
1052
1053 #ifdef CONFIG_TRACE_SIMPLE
1054 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
1055 {
1056 const char *op = qdict_get_try_str(qdict, "op");
1057 const char *arg = qdict_get_try_str(qdict, "arg");
1058
1059 if (!op) {
1060 st_print_trace_file_status();
1061 } else if (!strcmp(op, "on")) {
1062 st_set_trace_file_enabled(true);
1063 } else if (!strcmp(op, "off")) {
1064 st_set_trace_file_enabled(false);
1065 } else if (!strcmp(op, "flush")) {
1066 st_flush_trace_buffer();
1067 } else if (!strcmp(op, "set")) {
1068 if (arg) {
1069 st_set_trace_file(arg);
1070 }
1071 } else {
1072 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
1073 help_cmd(mon, "trace-file");
1074 }
1075 }
1076 #endif
1077
1078 static void hmp_info_help(Monitor *mon, const QDict *qdict)
1079 {
1080 help_cmd(mon, "info");
1081 }
1082
1083 static void query_commands_cb(QmpCommand *cmd, void *opaque)
1084 {
1085 CommandInfoList *info, **list = opaque;
1086
1087 if (!cmd->enabled) {
1088 return;
1089 }
1090
1091 info = g_malloc0(sizeof(*info));
1092 info->value = g_malloc0(sizeof(*info->value));
1093 info->value->name = g_strdup(cmd->name);
1094 info->next = *list;
1095 *list = info;
1096 }
1097
1098 CommandInfoList *qmp_query_commands(Error **errp)
1099 {
1100 CommandInfoList *list = NULL;
1101 MonitorQMP *mon;
1102
1103 assert(monitor_is_qmp(cur_mon));
1104 mon = container_of(cur_mon, MonitorQMP, common);
1105
1106 qmp_for_each_command(mon->commands, query_commands_cb, &list);
1107
1108 return list;
1109 }
1110
1111 EventInfoList *qmp_query_events(Error **errp)
1112 {
1113 /*
1114 * TODO This deprecated command is the only user of
1115 * QAPIEvent_str() and QAPIEvent_lookup[]. When the command goes,
1116 * they should go, too.
1117 */
1118 EventInfoList *info, *ev_list = NULL;
1119 QAPIEvent e;
1120
1121 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
1122 const char *event_name = QAPIEvent_str(e);
1123 assert(event_name != NULL);
1124 info = g_malloc0(sizeof(*info));
1125 info->value = g_malloc0(sizeof(*info->value));
1126 info->value->name = g_strdup(event_name);
1127
1128 info->next = ev_list;
1129 ev_list = info;
1130 }
1131
1132 return ev_list;
1133 }
1134
1135 /*
1136 * Minor hack: generated marshalling suppressed for this command
1137 * ('gen': false in the schema) so we can parse the JSON string
1138 * directly into QObject instead of first parsing it with
1139 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
1140 * to QObject with generated output marshallers, every time. Instead,
1141 * we do it in test-qobject-input-visitor.c, just to make sure
1142 * qapi-gen.py's output actually conforms to the schema.
1143 */
1144 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
1145 Error **errp)
1146 {
1147 *ret_data = qobject_from_qlit(&qmp_schema_qlit);
1148 }
1149
1150 static void monitor_init_qmp_commands(void)
1151 {
1152 /*
1153 * Two command lists:
1154 * - qmp_commands contains all QMP commands
1155 * - qmp_cap_negotiation_commands contains just
1156 * "qmp_capabilities", to enforce capability negotiation
1157 */
1158
1159 qmp_init_marshal(&qmp_commands);
1160
1161 qmp_register_command(&qmp_commands, "query-qmp-schema",
1162 qmp_query_qmp_schema, QCO_ALLOW_PRECONFIG);
1163 qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
1164 QCO_NO_OPTIONS);
1165 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1166 QCO_NO_OPTIONS);
1167
1168 QTAILQ_INIT(&qmp_cap_negotiation_commands);
1169 qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
1170 qmp_marshal_qmp_capabilities, QCO_ALLOW_PRECONFIG);
1171 }
1172
1173 static bool qmp_oob_enabled(MonitorQMP *mon)
1174 {
1175 return mon->capab[QMP_CAPABILITY_OOB];
1176 }
1177
1178 static void monitor_qmp_caps_reset(MonitorQMP *mon)
1179 {
1180 memset(mon->capab_offered, 0, sizeof(mon->capab_offered));
1181 memset(mon->capab, 0, sizeof(mon->capab));
1182 mon->capab_offered[QMP_CAPABILITY_OOB] = mon->common.use_io_thread;
1183 }
1184
1185 /*
1186 * Accept QMP capabilities in @list for @mon.
1187 * On success, set mon->qmp.capab[], and return true.
1188 * On error, set @errp, and return false.
1189 */
1190 static bool qmp_caps_accept(MonitorQMP *mon, QMPCapabilityList *list,
1191 Error **errp)
1192 {
1193 GString *unavailable = NULL;
1194 bool capab[QMP_CAPABILITY__MAX];
1195
1196 memset(capab, 0, sizeof(capab));
1197
1198 for (; list; list = list->next) {
1199 if (!mon->capab_offered[list->value]) {
1200 if (!unavailable) {
1201 unavailable = g_string_new(QMPCapability_str(list->value));
1202 } else {
1203 g_string_append_printf(unavailable, ", %s",
1204 QMPCapability_str(list->value));
1205 }
1206 }
1207 capab[list->value] = true;
1208 }
1209
1210 if (unavailable) {
1211 error_setg(errp, "Capability %s not available", unavailable->str);
1212 g_string_free(unavailable, true);
1213 return false;
1214 }
1215
1216 memcpy(mon->capab, capab, sizeof(capab));
1217 return true;
1218 }
1219
1220 void qmp_qmp_capabilities(bool has_enable, QMPCapabilityList *enable,
1221 Error **errp)
1222 {
1223 MonitorQMP *mon;
1224
1225 assert(monitor_is_qmp(cur_mon));
1226 mon = container_of(cur_mon, MonitorQMP, common);
1227
1228 if (mon->commands == &qmp_commands) {
1229 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1230 "Capabilities negotiation is already complete, command "
1231 "ignored");
1232 return;
1233 }
1234
1235 if (!qmp_caps_accept(mon, enable, errp)) {
1236 return;
1237 }
1238
1239 mon->commands = &qmp_commands;
1240 }
1241
1242 /* Set the current CPU defined by the user. Callers must hold BQL. */
1243 int monitor_set_cpu(int cpu_index)
1244 {
1245 CPUState *cpu;
1246
1247 cpu = qemu_get_cpu(cpu_index);
1248 if (cpu == NULL) {
1249 return -1;
1250 }
1251 g_free(cur_mon->mon_cpu_path);
1252 cur_mon->mon_cpu_path = object_get_canonical_path(OBJECT(cpu));
1253 return 0;
1254 }
1255
1256 /* Callers must hold BQL. */
1257 static CPUState *mon_get_cpu_sync(bool synchronize)
1258 {
1259 CPUState *cpu;
1260
1261 if (cur_mon->mon_cpu_path) {
1262 cpu = (CPUState *) object_resolve_path_type(cur_mon->mon_cpu_path,
1263 TYPE_CPU, NULL);
1264 if (!cpu) {
1265 g_free(cur_mon->mon_cpu_path);
1266 cur_mon->mon_cpu_path = NULL;
1267 }
1268 }
1269 if (!cur_mon->mon_cpu_path) {
1270 if (!first_cpu) {
1271 return NULL;
1272 }
1273 monitor_set_cpu(first_cpu->cpu_index);
1274 cpu = first_cpu;
1275 }
1276 if (synchronize) {
1277 cpu_synchronize_state(cpu);
1278 }
1279 return cpu;
1280 }
1281
1282 CPUState *mon_get_cpu(void)
1283 {
1284 return mon_get_cpu_sync(true);
1285 }
1286
1287 CPUArchState *mon_get_cpu_env(void)
1288 {
1289 CPUState *cs = mon_get_cpu();
1290
1291 return cs ? cs->env_ptr : NULL;
1292 }
1293
1294 int monitor_get_cpu_index(void)
1295 {
1296 CPUState *cs = mon_get_cpu_sync(false);
1297
1298 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1299 }
1300
1301 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1302 {
1303 bool all_cpus = qdict_get_try_bool(qdict, "cpustate_all", false);
1304 CPUState *cs;
1305
1306 if (all_cpus) {
1307 CPU_FOREACH(cs) {
1308 monitor_printf(mon, "\nCPU#%d\n", cs->cpu_index);
1309 cpu_dump_state(cs, NULL, CPU_DUMP_FPU);
1310 }
1311 } else {
1312 cs = mon_get_cpu();
1313
1314 if (!cs) {
1315 monitor_printf(mon, "No CPU available\n");
1316 return;
1317 }
1318
1319 cpu_dump_state(cs, NULL, CPU_DUMP_FPU);
1320 }
1321 }
1322
1323 #ifdef CONFIG_TCG
1324 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1325 {
1326 if (!tcg_enabled()) {
1327 error_report("JIT information is only available with accel=tcg");
1328 return;
1329 }
1330
1331 dump_exec_info();
1332 dump_drift_info();
1333 }
1334
1335 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1336 {
1337 dump_opcount_info();
1338 }
1339 #endif
1340
1341 static void hmp_info_sync_profile(Monitor *mon, const QDict *qdict)
1342 {
1343 int64_t max = qdict_get_try_int(qdict, "max", 10);
1344 bool mean = qdict_get_try_bool(qdict, "mean", false);
1345 bool coalesce = !qdict_get_try_bool(qdict, "no_coalesce", false);
1346 enum QSPSortBy sort_by;
1347
1348 sort_by = mean ? QSP_SORT_BY_AVG_WAIT_TIME : QSP_SORT_BY_TOTAL_WAIT_TIME;
1349 qsp_report(max, sort_by, coalesce);
1350 }
1351
1352 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1353 {
1354 MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
1355 int i;
1356 const char *str;
1357
1358 if (!hmp_mon->rs) {
1359 return;
1360 }
1361 i = 0;
1362 for(;;) {
1363 str = readline_get_history(hmp_mon->rs, i);
1364 if (!str) {
1365 break;
1366 }
1367 monitor_printf(mon, "%d: '%s'\n", i, str);
1368 i++;
1369 }
1370 }
1371
1372 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1373 {
1374 CPUState *cs = mon_get_cpu();
1375
1376 if (!cs) {
1377 monitor_printf(mon, "No CPU available\n");
1378 return;
1379 }
1380 cpu_dump_statistics(cs, 0);
1381 }
1382
1383 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1384 {
1385 const char *name = qdict_get_try_str(qdict, "name");
1386 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1387 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1388 TraceEventInfoList *events;
1389 TraceEventInfoList *elem;
1390 Error *local_err = NULL;
1391
1392 if (name == NULL) {
1393 name = "*";
1394 }
1395 if (vcpu < 0) {
1396 monitor_printf(mon, "argument vcpu must be positive");
1397 return;
1398 }
1399
1400 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1401 if (local_err) {
1402 error_report_err(local_err);
1403 return;
1404 }
1405
1406 for (elem = events; elem != NULL; elem = elem->next) {
1407 monitor_printf(mon, "%s : state %u\n",
1408 elem->value->name,
1409 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1410 }
1411 qapi_free_TraceEventInfoList(events);
1412 }
1413
1414 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1415 bool has_port, int64_t port,
1416 bool has_tls_port, int64_t tls_port,
1417 bool has_cert_subject, const char *cert_subject,
1418 Error **errp)
1419 {
1420 if (strcmp(protocol, "spice") == 0) {
1421 if (!qemu_using_spice(errp)) {
1422 return;
1423 }
1424
1425 if (!has_port && !has_tls_port) {
1426 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1427 return;
1428 }
1429
1430 if (qemu_spice_migrate_info(hostname,
1431 has_port ? port : -1,
1432 has_tls_port ? tls_port : -1,
1433 cert_subject)) {
1434 error_setg(errp, QERR_UNDEFINED_ERROR);
1435 return;
1436 }
1437 return;
1438 }
1439
1440 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1441 }
1442
1443 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1444 {
1445 Error *err = NULL;
1446
1447 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1448 if (err) {
1449 error_report_err(err);
1450 }
1451 }
1452
1453 static void hmp_log(Monitor *mon, const QDict *qdict)
1454 {
1455 int mask;
1456 const char *items = qdict_get_str(qdict, "items");
1457
1458 if (!strcmp(items, "none")) {
1459 mask = 0;
1460 } else {
1461 mask = qemu_str_to_log_mask(items);
1462 if (!mask) {
1463 help_cmd(mon, "log");
1464 return;
1465 }
1466 }
1467 qemu_set_log(mask);
1468 }
1469
1470 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1471 {
1472 const char *option = qdict_get_try_str(qdict, "option");
1473 if (!option || !strcmp(option, "on")) {
1474 singlestep = 1;
1475 } else if (!strcmp(option, "off")) {
1476 singlestep = 0;
1477 } else {
1478 monitor_printf(mon, "unexpected option %s\n", option);
1479 }
1480 }
1481
1482 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1483 {
1484 const char *device = qdict_get_try_str(qdict, "device");
1485 if (!device)
1486 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1487 if (gdbserver_start(device) < 0) {
1488 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1489 device);
1490 } else if (strcmp(device, "none") == 0) {
1491 monitor_printf(mon, "Disabled gdbserver\n");
1492 } else {
1493 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1494 device);
1495 }
1496 }
1497
1498 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1499 {
1500 const char *action = qdict_get_str(qdict, "action");
1501 if (select_watchdog_action(action) == -1) {
1502 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1503 }
1504 }
1505
1506 static void monitor_printc(Monitor *mon, int c)
1507 {
1508 monitor_printf(mon, "'");
1509 switch(c) {
1510 case '\'':
1511 monitor_printf(mon, "\\'");
1512 break;
1513 case '\\':
1514 monitor_printf(mon, "\\\\");
1515 break;
1516 case '\n':
1517 monitor_printf(mon, "\\n");
1518 break;
1519 case '\r':
1520 monitor_printf(mon, "\\r");
1521 break;
1522 default:
1523 if (c >= 32 && c <= 126) {
1524 monitor_printf(mon, "%c", c);
1525 } else {
1526 monitor_printf(mon, "\\x%02x", c);
1527 }
1528 break;
1529 }
1530 monitor_printf(mon, "'");
1531 }
1532
1533 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1534 hwaddr addr, int is_physical)
1535 {
1536 int l, line_size, i, max_digits, len;
1537 uint8_t buf[16];
1538 uint64_t v;
1539 CPUState *cs = mon_get_cpu();
1540
1541 if (!cs && (format == 'i' || !is_physical)) {
1542 monitor_printf(mon, "Can not dump without CPU\n");
1543 return;
1544 }
1545
1546 if (format == 'i') {
1547 monitor_disas(mon, cs, addr, count, is_physical);
1548 return;
1549 }
1550
1551 len = wsize * count;
1552 if (wsize == 1)
1553 line_size = 8;
1554 else
1555 line_size = 16;
1556 max_digits = 0;
1557
1558 switch(format) {
1559 case 'o':
1560 max_digits = DIV_ROUND_UP(wsize * 8, 3);
1561 break;
1562 default:
1563 case 'x':
1564 max_digits = (wsize * 8) / 4;
1565 break;
1566 case 'u':
1567 case 'd':
1568 max_digits = DIV_ROUND_UP(wsize * 8 * 10, 33);
1569 break;
1570 case 'c':
1571 wsize = 1;
1572 break;
1573 }
1574
1575 while (len > 0) {
1576 if (is_physical)
1577 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1578 else
1579 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1580 l = len;
1581 if (l > line_size)
1582 l = line_size;
1583 if (is_physical) {
1584 AddressSpace *as = cs ? cs->as : &address_space_memory;
1585 MemTxResult r = address_space_read(as, addr,
1586 MEMTXATTRS_UNSPECIFIED, buf, l);
1587 if (r != MEMTX_OK) {
1588 monitor_printf(mon, " Cannot access memory\n");
1589 break;
1590 }
1591 } else {
1592 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1593 monitor_printf(mon, " Cannot access memory\n");
1594 break;
1595 }
1596 }
1597 i = 0;
1598 while (i < l) {
1599 switch(wsize) {
1600 default:
1601 case 1:
1602 v = ldub_p(buf + i);
1603 break;
1604 case 2:
1605 v = lduw_p(buf + i);
1606 break;
1607 case 4:
1608 v = (uint32_t)ldl_p(buf + i);
1609 break;
1610 case 8:
1611 v = ldq_p(buf + i);
1612 break;
1613 }
1614 monitor_printf(mon, " ");
1615 switch(format) {
1616 case 'o':
1617 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1618 break;
1619 case 'x':
1620 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1621 break;
1622 case 'u':
1623 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1624 break;
1625 case 'd':
1626 monitor_printf(mon, "%*" PRId64, max_digits, v);
1627 break;
1628 case 'c':
1629 monitor_printc(mon, v);
1630 break;
1631 }
1632 i += wsize;
1633 }
1634 monitor_printf(mon, "\n");
1635 addr += l;
1636 len -= l;
1637 }
1638 }
1639
1640 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1641 {
1642 int count = qdict_get_int(qdict, "count");
1643 int format = qdict_get_int(qdict, "format");
1644 int size = qdict_get_int(qdict, "size");
1645 target_long addr = qdict_get_int(qdict, "addr");
1646
1647 memory_dump(mon, count, format, size, addr, 0);
1648 }
1649
1650 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1651 {
1652 int count = qdict_get_int(qdict, "count");
1653 int format = qdict_get_int(qdict, "format");
1654 int size = qdict_get_int(qdict, "size");
1655 hwaddr addr = qdict_get_int(qdict, "addr");
1656
1657 memory_dump(mon, count, format, size, addr, 1);
1658 }
1659
1660 static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
1661 {
1662 MemoryRegionSection mrs = memory_region_find(get_system_memory(),
1663 addr, 1);
1664
1665 if (!mrs.mr) {
1666 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1667 return NULL;
1668 }
1669
1670 if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
1671 error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
1672 memory_region_unref(mrs.mr);
1673 return NULL;
1674 }
1675
1676 *p_mr = mrs.mr;
1677 return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
1678 }
1679
1680 static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
1681 {
1682 hwaddr addr = qdict_get_int(qdict, "addr");
1683 Error *local_err = NULL;
1684 MemoryRegion *mr = NULL;
1685 void *ptr;
1686
1687 ptr = gpa2hva(&mr, addr, &local_err);
1688 if (local_err) {
1689 error_report_err(local_err);
1690 return;
1691 }
1692
1693 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1694 " (%s) is %p\n",
1695 addr, mr->name, ptr);
1696
1697 memory_region_unref(mr);
1698 }
1699
1700 static void hmp_gva2gpa(Monitor *mon, const QDict *qdict)
1701 {
1702 target_ulong addr = qdict_get_int(qdict, "addr");
1703 MemTxAttrs attrs;
1704 CPUState *cs = mon_get_cpu();
1705 hwaddr gpa;
1706
1707 if (!cs) {
1708 monitor_printf(mon, "No cpu\n");
1709 return;
1710 }
1711
1712 gpa = cpu_get_phys_page_attrs_debug(cs, addr & TARGET_PAGE_MASK, &attrs);
1713 if (gpa == -1) {
1714 monitor_printf(mon, "Unmapped\n");
1715 } else {
1716 monitor_printf(mon, "gpa: %#" HWADDR_PRIx "\n",
1717 gpa + (addr & ~TARGET_PAGE_MASK));
1718 }
1719 }
1720
1721 #ifdef CONFIG_LINUX
1722 static uint64_t vtop(void *ptr, Error **errp)
1723 {
1724 uint64_t pinfo;
1725 uint64_t ret = -1;
1726 uintptr_t addr = (uintptr_t) ptr;
1727 uintptr_t pagesize = getpagesize();
1728 off_t offset = addr / pagesize * sizeof(pinfo);
1729 int fd;
1730
1731 fd = open("/proc/self/pagemap", O_RDONLY);
1732 if (fd == -1) {
1733 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1734 return -1;
1735 }
1736
1737 /* Force copy-on-write if necessary. */
1738 atomic_add((uint8_t *)ptr, 0);
1739
1740 if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
1741 error_setg_errno(errp, errno, "Cannot read pagemap");
1742 goto out;
1743 }
1744 if ((pinfo & (1ull << 63)) == 0) {
1745 error_setg(errp, "Page not present");
1746 goto out;
1747 }
1748 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1749
1750 out:
1751 close(fd);
1752 return ret;
1753 }
1754
1755 static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
1756 {
1757 hwaddr addr = qdict_get_int(qdict, "addr");
1758 Error *local_err = NULL;
1759 MemoryRegion *mr = NULL;
1760 void *ptr;
1761 uint64_t physaddr;
1762
1763 ptr = gpa2hva(&mr, addr, &local_err);
1764 if (local_err) {
1765 error_report_err(local_err);
1766 return;
1767 }
1768
1769 physaddr = vtop(ptr, &local_err);
1770 if (local_err) {
1771 error_report_err(local_err);
1772 } else {
1773 monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
1774 " (%s) is 0x%" PRIx64 "\n",
1775 addr, mr->name, (uint64_t) physaddr);
1776 }
1777
1778 memory_region_unref(mr);
1779 }
1780 #endif
1781
1782 static void do_print(Monitor *mon, const QDict *qdict)
1783 {
1784 int format = qdict_get_int(qdict, "format");
1785 hwaddr val = qdict_get_int(qdict, "val");
1786
1787 switch(format) {
1788 case 'o':
1789 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1790 break;
1791 case 'x':
1792 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1793 break;
1794 case 'u':
1795 monitor_printf(mon, "%" HWADDR_PRIu, val);
1796 break;
1797 default:
1798 case 'd':
1799 monitor_printf(mon, "%" HWADDR_PRId, val);
1800 break;
1801 case 'c':
1802 monitor_printc(mon, val);
1803 break;
1804 }
1805 monitor_printf(mon, "\n");
1806 }
1807
1808 static void hmp_sum(Monitor *mon, const QDict *qdict)
1809 {
1810 uint32_t addr;
1811 uint16_t sum;
1812 uint32_t start = qdict_get_int(qdict, "start");
1813 uint32_t size = qdict_get_int(qdict, "size");
1814
1815 sum = 0;
1816 for(addr = start; addr < (start + size); addr++) {
1817 uint8_t val = address_space_ldub(&address_space_memory, addr,
1818 MEMTXATTRS_UNSPECIFIED, NULL);
1819 /* BSD sum algorithm ('sum' Unix command) */
1820 sum = (sum >> 1) | (sum << 15);
1821 sum += val;
1822 }
1823 monitor_printf(mon, "%05d\n", sum);
1824 }
1825
1826 static int mouse_button_state;
1827
1828 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1829 {
1830 int dx, dy, dz, button;
1831 const char *dx_str = qdict_get_str(qdict, "dx_str");
1832 const char *dy_str = qdict_get_str(qdict, "dy_str");
1833 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1834
1835 dx = strtol(dx_str, NULL, 0);
1836 dy = strtol(dy_str, NULL, 0);
1837 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1838 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1839
1840 if (dz_str) {
1841 dz = strtol(dz_str, NULL, 0);
1842 if (dz != 0) {
1843 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1844 qemu_input_queue_btn(NULL, button, true);
1845 qemu_input_event_sync();
1846 qemu_input_queue_btn(NULL, button, false);
1847 }
1848 }
1849 qemu_input_event_sync();
1850 }
1851
1852 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1853 {
1854 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1855 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1856 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1857 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1858 };
1859 int button_state = qdict_get_int(qdict, "button_state");
1860
1861 if (mouse_button_state == button_state) {
1862 return;
1863 }
1864 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1865 qemu_input_event_sync();
1866 mouse_button_state = button_state;
1867 }
1868
1869 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1870 {
1871 int size = qdict_get_int(qdict, "size");
1872 int addr = qdict_get_int(qdict, "addr");
1873 int has_index = qdict_haskey(qdict, "index");
1874 uint32_t val;
1875 int suffix;
1876
1877 if (has_index) {
1878 int index = qdict_get_int(qdict, "index");
1879 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1880 addr++;
1881 }
1882 addr &= 0xffff;
1883
1884 switch(size) {
1885 default:
1886 case 1:
1887 val = cpu_inb(addr);
1888 suffix = 'b';
1889 break;
1890 case 2:
1891 val = cpu_inw(addr);
1892 suffix = 'w';
1893 break;
1894 case 4:
1895 val = cpu_inl(addr);
1896 suffix = 'l';
1897 break;
1898 }
1899 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1900 suffix, addr, size * 2, val);
1901 }
1902
1903 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1904 {
1905 int size = qdict_get_int(qdict, "size");
1906 int addr = qdict_get_int(qdict, "addr");
1907 int val = qdict_get_int(qdict, "val");
1908
1909 addr &= IOPORTS_MASK;
1910
1911 switch (size) {
1912 default:
1913 case 1:
1914 cpu_outb(addr, val);
1915 break;
1916 case 2:
1917 cpu_outw(addr, val);
1918 break;
1919 case 4:
1920 cpu_outl(addr, val);
1921 break;
1922 }
1923 }
1924
1925 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1926 {
1927 Error *local_err = NULL;
1928 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1929
1930 qemu_boot_set(bootdevice, &local_err);
1931 if (local_err) {
1932 error_report_err(local_err);
1933 } else {
1934 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1935 }
1936 }
1937
1938 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1939 {
1940 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
1941 bool dispatch_tree = qdict_get_try_bool(qdict, "dispatch_tree", false);
1942 bool owner = qdict_get_try_bool(qdict, "owner", false);
1943
1944 mtree_info(flatview, dispatch_tree, owner);
1945 }
1946
1947 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1948 {
1949 int i;
1950 NumaNodeMem *node_mem;
1951 CpuInfoList *cpu_list, *cpu;
1952
1953 cpu_list = qmp_query_cpus(&error_abort);
1954 node_mem = g_new0(NumaNodeMem, nb_numa_nodes);
1955
1956 query_numa_node_mem(node_mem);
1957 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1958 for (i = 0; i < nb_numa_nodes; i++) {
1959 monitor_printf(mon, "node %d cpus:", i);
1960 for (cpu = cpu_list; cpu; cpu = cpu->next) {
1961 if (cpu->value->has_props && cpu->value->props->has_node_id &&
1962 cpu->value->props->node_id == i) {
1963 monitor_printf(mon, " %" PRIi64, cpu->value->CPU);
1964 }
1965 }
1966 monitor_printf(mon, "\n");
1967 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1968 node_mem[i].node_mem >> 20);
1969 monitor_printf(mon, "node %d plugged: %" PRId64 " MB\n", i,
1970 node_mem[i].node_plugged_mem >> 20);
1971 }
1972 qapi_free_CpuInfoList(cpu_list);
1973 g_free(node_mem);
1974 }
1975
1976 #ifdef CONFIG_PROFILER
1977
1978 int64_t dev_time;
1979
1980 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1981 {
1982 static int64_t last_cpu_exec_time;
1983 int64_t cpu_exec_time;
1984 int64_t delta;
1985
1986 cpu_exec_time = tcg_cpu_exec_time();
1987 delta = cpu_exec_time - last_cpu_exec_time;
1988
1989 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1990 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1991 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1992 delta, delta / (double)NANOSECONDS_PER_SECOND);
1993 last_cpu_exec_time = cpu_exec_time;
1994 dev_time = 0;
1995 }
1996 #else
1997 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1998 {
1999 monitor_printf(mon, "Internal profiler not compiled\n");
2000 }
2001 #endif
2002
2003 /* Capture support */
2004 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2005
2006 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
2007 {
2008 int i;
2009 CaptureState *s;
2010
2011 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2012 monitor_printf(mon, "[%d]: ", i);
2013 s->ops.info (s->opaque);
2014 }
2015 }
2016
2017 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
2018 {
2019 int i;
2020 int n = qdict_get_int(qdict, "n");
2021 CaptureState *s;
2022
2023 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2024 if (i == n) {
2025 s->ops.destroy (s->opaque);
2026 QLIST_REMOVE (s, entries);
2027 g_free (s);
2028 return;
2029 }
2030 }
2031 }
2032
2033 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
2034 {
2035 const char *path = qdict_get_str(qdict, "path");
2036 int has_freq = qdict_haskey(qdict, "freq");
2037 int freq = qdict_get_try_int(qdict, "freq", -1);
2038 int has_bits = qdict_haskey(qdict, "bits");
2039 int bits = qdict_get_try_int(qdict, "bits", -1);
2040 int has_channels = qdict_haskey(qdict, "nchannels");
2041 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2042 CaptureState *s;
2043
2044 s = g_malloc0 (sizeof (*s));
2045
2046 freq = has_freq ? freq : 44100;
2047 bits = has_bits ? bits : 16;
2048 nchannels = has_channels ? nchannels : 2;
2049
2050 if (wav_start_capture (s, path, freq, bits, nchannels)) {
2051 monitor_printf(mon, "Failed to add wave capture\n");
2052 g_free (s);
2053 return;
2054 }
2055 QLIST_INSERT_HEAD (&capture_head, s, entries);
2056 }
2057
2058 static QAuthZList *find_auth(Monitor *mon, const char *name)
2059 {
2060 Object *obj;
2061 Object *container;
2062
2063 container = object_get_objects_root();
2064 obj = object_resolve_path_component(container, name);
2065 if (!obj) {
2066 monitor_printf(mon, "acl: unknown list '%s'\n", name);
2067 return NULL;
2068 }
2069
2070 return QAUTHZ_LIST(obj);
2071 }
2072
2073 static bool warn_acl;
2074 static void hmp_warn_acl(void)
2075 {
2076 if (warn_acl) {
2077 return;
2078 }
2079 error_report("The acl_show, acl_reset, acl_policy, acl_add, acl_remove "
2080 "commands are deprecated with no replacement. Authorization "
2081 "for VNC should be performed using the pluggable QAuthZ "
2082 "objects");
2083 warn_acl = true;
2084 }
2085
2086 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
2087 {
2088 const char *aclname = qdict_get_str(qdict, "aclname");
2089 QAuthZList *auth = find_auth(mon, aclname);
2090 QAuthZListRuleList *rules;
2091 size_t i = 0;
2092
2093 hmp_warn_acl();
2094
2095 if (!auth) {
2096 return;
2097 }
2098
2099 monitor_printf(mon, "policy: %s\n",
2100 QAuthZListPolicy_str(auth->policy));
2101
2102 rules = auth->rules;
2103 while (rules) {
2104 QAuthZListRule *rule = rules->value;
2105 i++;
2106 monitor_printf(mon, "%zu: %s %s\n", i,
2107 QAuthZListPolicy_str(rule->policy),
2108 rule->match);
2109 rules = rules->next;
2110 }
2111 }
2112
2113 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
2114 {
2115 const char *aclname = qdict_get_str(qdict, "aclname");
2116 QAuthZList *auth = find_auth(mon, aclname);
2117
2118 hmp_warn_acl();
2119
2120 if (!auth) {
2121 return;
2122 }
2123
2124 auth->policy = QAUTHZ_LIST_POLICY_DENY;
2125 qapi_free_QAuthZListRuleList(auth->rules);
2126 auth->rules = NULL;
2127 monitor_printf(mon, "acl: removed all rules\n");
2128 }
2129
2130 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
2131 {
2132 const char *aclname = qdict_get_str(qdict, "aclname");
2133 const char *policy = qdict_get_str(qdict, "policy");
2134 QAuthZList *auth = find_auth(mon, aclname);
2135 int val;
2136 Error *err = NULL;
2137
2138 hmp_warn_acl();
2139
2140 if (!auth) {
2141 return;
2142 }
2143
2144 val = qapi_enum_parse(&QAuthZListPolicy_lookup,
2145 policy,
2146 QAUTHZ_LIST_POLICY_DENY,
2147 &err);
2148 if (err) {
2149 error_free(err);
2150 monitor_printf(mon, "acl: unknown policy '%s', "
2151 "expected 'deny' or 'allow'\n", policy);
2152 } else {
2153 auth->policy = val;
2154 if (auth->policy == QAUTHZ_LIST_POLICY_ALLOW) {
2155 monitor_printf(mon, "acl: policy set to 'allow'\n");
2156 } else {
2157 monitor_printf(mon, "acl: policy set to 'deny'\n");
2158 }
2159 }
2160 }
2161
2162 static QAuthZListFormat hmp_acl_get_format(const char *match)
2163 {
2164 if (strchr(match, '*')) {
2165 return QAUTHZ_LIST_FORMAT_GLOB;
2166 } else {
2167 return QAUTHZ_LIST_FORMAT_EXACT;
2168 }
2169 }
2170
2171 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
2172 {
2173 const char *aclname = qdict_get_str(qdict, "aclname");
2174 const char *match = qdict_get_str(qdict, "match");
2175 const char *policystr = qdict_get_str(qdict, "policy");
2176 int has_index = qdict_haskey(qdict, "index");
2177 int index = qdict_get_try_int(qdict, "index", -1);
2178 QAuthZList *auth = find_auth(mon, aclname);
2179 Error *err = NULL;
2180 QAuthZListPolicy policy;
2181 QAuthZListFormat format;
2182 size_t i = 0;
2183
2184 hmp_warn_acl();
2185
2186 if (!auth) {
2187 return;
2188 }
2189
2190 policy = qapi_enum_parse(&QAuthZListPolicy_lookup,
2191 policystr,
2192 QAUTHZ_LIST_POLICY_DENY,
2193 &err);
2194 if (err) {
2195 error_free(err);
2196 monitor_printf(mon, "acl: unknown policy '%s', "
2197 "expected 'deny' or 'allow'\n", policystr);
2198 return;
2199 }
2200
2201 format = hmp_acl_get_format(match);
2202
2203 if (has_index && index == 0) {
2204 monitor_printf(mon, "acl: unable to add acl entry\n");
2205 return;
2206 }
2207
2208 if (has_index) {
2209 i = qauthz_list_insert_rule(auth, match, policy,
2210 format, index - 1, &err);
2211 } else {
2212 i = qauthz_list_append_rule(auth, match, policy,
2213 format, &err);
2214 }
2215 if (err) {
2216 monitor_printf(mon, "acl: unable to add rule: %s",
2217 error_get_pretty(err));
2218 error_free(err);
2219 } else {
2220 monitor_printf(mon, "acl: added rule at position %zu\n", i + 1);
2221 }
2222 }
2223
2224 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
2225 {
2226 const char *aclname = qdict_get_str(qdict, "aclname");
2227 const char *match = qdict_get_str(qdict, "match");
2228 QAuthZList *auth = find_auth(mon, aclname);
2229 ssize_t i = 0;
2230
2231 hmp_warn_acl();
2232
2233 if (!auth) {
2234 return;
2235 }
2236
2237 i = qauthz_list_delete_rule(auth, match);
2238 if (i >= 0) {
2239 monitor_printf(mon, "acl: removed rule at position %zu\n", i + 1);
2240 } else {
2241 monitor_printf(mon, "acl: no matching acl entry\n");
2242 }
2243 }
2244
2245 void qmp_getfd(const char *fdname, Error **errp)
2246 {
2247 mon_fd_t *monfd;
2248 int fd, tmp_fd;
2249
2250 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
2251 if (fd == -1) {
2252 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2253 return;
2254 }
2255
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;
2261 }
2262
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;
2267 }
2268
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;
2275 }
2276
2277 monfd = g_malloc0(sizeof(mon_fd_t));
2278 monfd->name = g_strdup(fdname);
2279 monfd->fd = fd;
2280
2281 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2282 qemu_mutex_unlock(&cur_mon->mon_lock);
2283 }
2284
2285 void qmp_closefd(const char *fdname, Error **errp)
2286 {
2287 mon_fd_t *monfd;
2288 int tmp_fd;
2289
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;
2294 }
2295
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;
2304 }
2305
2306 qemu_mutex_unlock(&cur_mon->mon_lock);
2307 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
2308 }
2309
2310 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2311 {
2312 mon_fd_t *monfd;
2313
2314 qemu_mutex_lock(&mon->mon_lock);
2315 QLIST_FOREACH(monfd, &mon->fds, next) {
2316 int fd;
2317
2318 if (strcmp(monfd->name, fdname) != 0) {
2319 continue;
2320 }
2321
2322 fd = monfd->fd;
2323
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);
2329
2330 return fd;
2331 }
2332
2333 qemu_mutex_unlock(&mon->mon_lock);
2334 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2335 return -1;
2336 }
2337
2338 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2339 {
2340 MonFdsetFd *mon_fdset_fd;
2341 MonFdsetFd *mon_fdset_fd_next;
2342
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);
2351 }
2352 }
2353
2354 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2355 QLIST_REMOVE(mon_fdset, next);
2356 g_free(mon_fdset);
2357 }
2358 }
2359
2360 static void monitor_fdsets_cleanup(void)
2361 {
2362 MonFdset *mon_fdset;
2363 MonFdset *mon_fdset_next;
2364
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);
2368 }
2369 qemu_mutex_unlock(&mon_fdsets_lock);
2370 }
2371
2372 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2373 const char *opaque, Error **errp)
2374 {
2375 int fd;
2376 Monitor *mon = cur_mon;
2377 AddfdInfo *fdinfo;
2378
2379 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2380 if (fd == -1) {
2381 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2382 goto error;
2383 }
2384
2385 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2386 has_opaque, opaque, errp);
2387 if (fdinfo) {
2388 return fdinfo;
2389 }
2390
2391 error:
2392 if (fd != -1) {
2393 close(fd);
2394 }
2395 return NULL;
2396 }
2397
2398 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2399 {
2400 MonFdset *mon_fdset;
2401 MonFdsetFd *mon_fdset_fd;
2402 char fd_str[60];
2403
2404 qemu_mutex_lock(&mon_fdsets_lock);
2405 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2406 if (mon_fdset->id != fdset_id) {
2407 continue;
2408 }
2409 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2410 if (has_fd) {
2411 if (mon_fdset_fd->fd != fd) {
2412 continue;
2413 }
2414 mon_fdset_fd->removed = true;
2415 break;
2416 } else {
2417 mon_fdset_fd->removed = true;
2418 }
2419 }
2420 if (has_fd && !mon_fdset_fd) {
2421 goto error;
2422 }
2423 monitor_fdset_cleanup(mon_fdset);
2424 qemu_mutex_unlock(&mon_fdsets_lock);
2425 return;
2426 }
2427
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);
2435 }
2436 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2437 }
2438
2439 FdsetInfoList *qmp_query_fdsets(Error **errp)
2440 {
2441 MonFdset *mon_fdset;
2442 MonFdsetFd *mon_fdset_fd;
2443 FdsetInfoList *fdset_list = NULL;
2444
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;
2449
2450 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2451 fdset_info->value->fdset_id = mon_fdset->id;
2452
2453 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2454 FdsetFdInfoList *fdsetfd_info;
2455
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;
2464 }
2465
2466 fdsetfd_info->next = fdsetfd_list;
2467 fdsetfd_list = fdsetfd_info;
2468 }
2469
2470 fdset_info->value->fds = fdsetfd_list;
2471
2472 fdset_info->next = fdset_list;
2473 fdset_list = fdset_info;
2474 }
2475 qemu_mutex_unlock(&mon_fdsets_lock);
2476
2477 return fdset_list;
2478 }
2479
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)
2483 {
2484 MonFdset *mon_fdset = NULL;
2485 MonFdsetFd *mon_fdset_fd;
2486 AddfdInfo *fdinfo;
2487
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;
2495 }
2496 break;
2497 }
2498 }
2499 }
2500
2501 if (mon_fdset == NULL) {
2502 int64_t fdset_id_prev = -1;
2503 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2504
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;
2511 }
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;
2517 }
2518 }
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;
2526 }
2527 break;
2528 }
2529 }
2530
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;
2536 }
2537
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);
2545 }
2546 }
2547
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);
2553 }
2554 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2555
2556 fdinfo = g_malloc0(sizeof(*fdinfo));
2557 fdinfo->fdset_id = mon_fdset->id;
2558 fdinfo->fd = mon_fdset_fd->fd;
2559
2560 qemu_mutex_unlock(&mon_fdsets_lock);
2561 return fdinfo;
2562 }
2563
2564 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2565 {
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;
2573
2574 qemu_mutex_lock(&mon_fdsets_lock);
2575 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2576 if (mon_fdset->id != fdset_id) {
2577 continue;
2578 }
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;
2584 }
2585
2586 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2587 ret = mon_fdset_fd->fd;
2588 goto out;
2589 }
2590 }
2591 ret = -EACCES;
2592 goto out;
2593 }
2594 ret = -ENOENT;
2595
2596 out:
2597 qemu_mutex_unlock(&mon_fdsets_lock);
2598 return ret;
2599 #endif
2600 }
2601
2602 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2603 {
2604 MonFdset *mon_fdset;
2605 MonFdsetFd *mon_fdset_fd_dup;
2606
2607 qemu_mutex_lock(&mon_fdsets_lock);
2608 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2609 if (mon_fdset->id != fdset_id) {
2610 continue;
2611 }
2612 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2613 if (mon_fdset_fd_dup->fd == dup_fd) {
2614 goto err;
2615 }
2616 }
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;
2622 }
2623
2624 err:
2625 qemu_mutex_unlock(&mon_fdsets_lock);
2626 return -1;
2627 }
2628
2629 static int64_t monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2630 {
2631 MonFdset *mon_fdset;
2632 MonFdsetFd *mon_fdset_fd_dup;
2633
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);
2642 }
2643 goto err;
2644 } else {
2645 qemu_mutex_unlock(&mon_fdsets_lock);
2646 return mon_fdset->id;
2647 }
2648 }
2649 }
2650 }
2651
2652 err:
2653 qemu_mutex_unlock(&mon_fdsets_lock);
2654 return -1;
2655 }
2656
2657 int64_t monitor_fdset_dup_fd_find(int dup_fd)
2658 {
2659 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2660 }
2661
2662 void monitor_fdset_dup_fd_remove(int dup_fd)
2663 {
2664 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2665 }
2666
2667 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2668 {
2669 int fd;
2670 Error *local_err = NULL;
2671
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);
2679 }
2680 }
2681 if (local_err) {
2682 error_propagate(errp, local_err);
2683 assert(fd == -1);
2684 } else {
2685 assert(fd != -1);
2686 }
2687
2688 return fd;
2689 }
2690
2691 /* Please update hmp-commands.hx when adding or changing commands */
2692 static HMPCommand hmp_info_cmds[] = {
2693 #include "hmp-commands-info.h"
2694 { NULL, NULL, },
2695 };
2696
2697 /* hmp_cmds and hmp_info_cmds would be sorted at runtime */
2698 static HMPCommand hmp_cmds[] = {
2699 #include "hmp-commands.h"
2700 { NULL, NULL, },
2701 };
2702
2703 /*******************************************************************/
2704
2705 static const char *pch;
2706 static sigjmp_buf expr_env;
2707
2708
2709 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2710 expr_error(Monitor *mon, const char *fmt, ...)
2711 {
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);
2718 }
2719
2720 /* return 0 if OK, -1 if not found */
2721 static int get_monitor_def(target_long *pval, const char *name)
2722 {
2723 const MonitorDef *md = target_monitor_defs();
2724 CPUState *cs = mon_get_cpu();
2725 void *ptr;
2726 uint64_t tmp = 0;
2727 int ret;
2728
2729 if (cs == NULL || md == NULL) {
2730 return -1;
2731 }
2732
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;
2750 }
2751 }
2752 return 0;
2753 }
2754 }
2755
2756 ret = target_get_monitor_def(cs, name, &tmp);
2757 if (!ret) {
2758 *pval = (target_long) tmp;
2759 }
2760
2761 return ret;
2762 }
2763
2764 static void next(void)
2765 {
2766 if (*pch != '\0') {
2767 pch++;
2768 while (qemu_isspace(*pch))
2769 pch++;
2770 }
2771 }
2772
2773 static int64_t expr_sum(Monitor *mon);
2774
2775 static int64_t expr_unary(Monitor *mon)
2776 {
2777 int64_t n;
2778 char *p;
2779 int ret;
2780
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");
2799 }
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 '$':
2813 {
2814 char buf[128], *q;
2815 target_long reg=0;
2816
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++;
2826 }
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;
2834 }
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");
2845 }
2846 if (pch == p) {
2847 expr_error(mon, "invalid char '%c' in expression", *p);
2848 }
2849 pch = p;
2850 while (qemu_isspace(*pch))
2851 pch++;
2852 break;
2853 }
2854 return n;
2855 }
2856
2857
2858 static int64_t expr_prod(Monitor *mon)
2859 {
2860 int64_t val, val2;
2861 int op;
2862
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;
2884 }
2885 }
2886 return val;
2887 }
2888
2889 static int64_t expr_logic(Monitor *mon)
2890 {
2891 int64_t val, val2;
2892 int op;
2893
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;
2912 }
2913 }
2914 return val;
2915 }
2916
2917 static int64_t expr_sum(Monitor *mon)
2918 {
2919 int64_t val, val2;
2920 int op;
2921
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;
2933 }
2934 return val;
2935 }
2936
2937 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2938 {
2939 pch = *pp;
2940 if (sigsetjmp(expr_env, 0)) {
2941 *pp = pch;
2942 return -1;
2943 }
2944 while (qemu_isspace(*pch))
2945 pch++;
2946 *pval = expr_sum(mon);
2947 *pp = pch;
2948 return 0;
2949 }
2950
2951 static int get_double(Monitor *mon, double *pval, const char **pp)
2952 {
2953 const char *p = *pp;
2954 char *tailp;
2955 double d;
2956
2957 d = strtod(p, &tailp);
2958 if (tailp == p) {
2959 monitor_printf(mon, "Number expected\n");
2960 return -1;
2961 }
2962 if (d != d || d - d != 0) {
2963 /* NaN or infinity */
2964 monitor_printf(mon, "Bad number\n");
2965 return -1;
2966 }
2967 *pval = d;
2968 *pp = tailp;
2969 return 0;
2970 }
2971
2972 /*
2973 * Store the command-name in cmdname, and return a pointer to
2974 * the remaining of the command string.
2975 */
2976 static const char *get_command_name(const char *cmdline,
2977 char *cmdname, size_t nlen)
2978 {
2979 size_t len;
2980 const char *p, *pstart;
2981
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;
2996 }
2997
2998 /**
2999 * Read key of 'type' into 'key' and return the current
3000 * 'type' pointer.
3001 */
3002 static char *key_get_info(const char *type, char **key)
3003 {
3004 size_t len;
3005 char *p, *str;
3006
3007 if (*type == ',')
3008 type++;
3009
3010 p = strchr(type, ':');
3011 if (!p) {
3012 *key = NULL;
3013 return NULL;
3014 }
3015 len = p - type;
3016
3017 str = g_malloc(len + 1);
3018 memcpy(str, type, len);
3019 str[len] = '\0';
3020
3021 *key = str;
3022 return ++p;
3023 }
3024
3025 static int default_fmt_format = 'x';
3026 static int default_fmt_size = 4;
3027
3028 static int is_valid_option(const char *c, const char *typestr)
3029 {
3030 char option[3];
3031
3032 option[0] = '-';
3033 option[1] = *c;
3034 option[2] = '\0';
3035
3036 typestr = strstr(typestr, option);
3037 return (typestr != NULL);
3038 }
3039
3040 static const HMPCommand *search_dispatch_table(const HMPCommand *disp_table,
3041 const char *cmdname)
3042 {
3043 const HMPCommand *cmd;
3044
3045 for (cmd = disp_table; cmd->name != NULL; cmd++) {
3046 if (compare_cmd(cmdname, cmd->name)) {
3047 return cmd;
3048 }
3049 }
3050
3051 return NULL;
3052 }
3053
3054 /*
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.
3063 */
3064 static const HMPCommand *monitor_parse_command(MonitorHMP *hmp_mon,
3065 const char *cmdp_start,
3066 const char **cmdp,
3067 HMPCommand *table)
3068 {
3069 Monitor *mon = &hmp_mon->common;
3070 const char *p;
3071 const HMPCommand *cmd;
3072 char cmdname[256];
3073
3074 /* extract the command name */
3075 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
3076 if (!p)
3077 return NULL;
3078
3079 cmd = search_dispatch_table(table, cmdname);
3080 if (!cmd) {
3081 monitor_printf(mon, "unknown command: '%.*s'\n",
3082 (int)(p - cmdp_start), cmdp_start);
3083 return NULL;
3084 }
3085 if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
3086 monitor_printf(mon, "Command '%.*s' not available with -preconfig "
3087 "until after exit_preconfig.\n",
3088 (int)(p - cmdp_start), cmdp_start);
3089 return NULL;
3090 }
3091
3092 /* filter out following useless space */
3093 while (qemu_isspace(*p)) {
3094 p++;
3095 }
3096
3097 *cmdp = p;
3098 /* search sub command */
3099 if (cmd->sub_table != NULL && *p != '\0') {
3100 return monitor_parse_command(hmp_mon, cmdp_start, cmdp, cmd->sub_table);
3101 }
3102
3103 return cmd;
3104 }
3105
3106 /*
3107 * Parse arguments for @cmd.
3108 * If it can't be parsed, report to @mon, and return NULL.
3109 * Else, insert command arguments into a QDict, and return it.
3110 * Note: On success, caller has to free the QDict structure.
3111 */
3112
3113 static QDict *monitor_parse_arguments(Monitor *mon,
3114 const char **endp,
3115 const HMPCommand *cmd)
3116 {
3117 const char *typestr;
3118 char *key;
3119 int c;
3120 const char *p = *endp;
3121 char buf[1024];
3122 QDict *qdict = qdict_new();
3123
3124 /* parse the parameters */
3125 typestr = cmd->args_type;
3126 for(;;) {
3127 typestr = key_get_info(typestr, &key);
3128 if (!typestr)
3129 break;
3130 c = *typestr;
3131 typestr++;
3132 switch(c) {
3133 case 'F':
3134 case 'B':
3135 case 's':
3136 {
3137 int ret;
3138
3139 while (qemu_isspace(*p))
3140 p++;
3141 if (*typestr == '?') {
3142 typestr++;
3143 if (*p == '\0') {
3144 /* no optional string: NULL argument */
3145 break;
3146 }
3147 }
3148 ret = get_str(buf, sizeof(buf), &p);
3149 if (ret < 0) {
3150 switch(c) {
3151 case 'F':
3152 monitor_printf(mon, "%s: filename expected\n",
3153 cmd->name);
3154 break;
3155 case 'B':
3156 monitor_printf(mon, "%s: block device name expected\n",
3157 cmd->name);
3158 break;
3159 default:
3160 monitor_printf(mon, "%s: string expected\n", cmd->name);
3161 break;
3162 }
3163 goto fail;
3164 }
3165 qdict_put_str(qdict, key, buf);
3166 }
3167 break;
3168 case 'O':
3169 {
3170 QemuOptsList *opts_list;
3171 QemuOpts *opts;
3172
3173 opts_list = qemu_find_opts(key);
3174 if (!opts_list || opts_list->desc->name) {
3175 goto bad_type;
3176 }
3177 while (qemu_isspace(*p)) {
3178 p++;
3179 }
3180 if (!*p)
3181 break;
3182 if (get_str(buf, sizeof(buf), &p) < 0) {
3183 goto fail;
3184 }
3185 opts = qemu_opts_parse_noisily(opts_list, buf, true);
3186 if (!opts) {
3187 goto fail;
3188 }
3189 qemu_opts_to_qdict(opts, qdict);
3190 qemu_opts_del(opts);
3191 }
3192 break;
3193 case '/':
3194 {
3195 int count, format, size;
3196
3197 while (qemu_isspace(*p))
3198 p++;
3199 if (*p == '/') {
3200 /* format found */
3201 p++;
3202 count = 1;
3203 if (qemu_isdigit(*p)) {
3204 count = 0;
3205 while (qemu_isdigit(*p)) {
3206 count = count * 10 + (*p - '0');
3207 p++;
3208 }
3209 }
3210 size = -1;
3211 format = -1;
3212 for(;;) {
3213 switch(*p) {
3214 case 'o':
3215 case 'd':
3216 case 'u':
3217 case 'x':
3218 case 'i':
3219 case 'c':
3220 format = *p++;
3221 break;
3222 case 'b':
3223 size = 1;
3224 p++;
3225 break;
3226 case 'h':
3227 size = 2;
3228 p++;
3229 break;
3230 case 'w':
3231 size = 4;
3232 p++;
3233 break;
3234 case 'g':
3235 case 'L':
3236 size = 8;
3237 p++;
3238 break;
3239 default:
3240 goto next;
3241 }
3242 }
3243 next:
3244 if (*p != '\0' && !qemu_isspace(*p)) {
3245 monitor_printf(mon, "invalid char in format: '%c'\n",
3246 *p);
3247 goto fail;
3248 }
3249 if (format < 0)
3250 format = default_fmt_format;
3251 if (format != 'i') {
3252 /* for 'i', not specifying a size gives -1 as size */
3253 if (size < 0)
3254 size = default_fmt_size;
3255 default_fmt_size = size;
3256 }
3257 default_fmt_format = format;
3258 } else {
3259 count = 1;
3260 format = default_fmt_format;
3261 if (format != 'i') {
3262 size = default_fmt_size;
3263 } else {
3264 size = -1;
3265 }
3266 }
3267 qdict_put_int(qdict, "count", count);
3268 qdict_put_int(qdict, "format", format);
3269 qdict_put_int(qdict, "size", size);
3270 }
3271 break;
3272 case 'i':
3273 case 'l':
3274 case 'M':
3275 {
3276 int64_t val;
3277
3278 while (qemu_isspace(*p))
3279 p++;
3280 if (*typestr == '?' || *typestr == '.') {
3281 if (*typestr == '?') {
3282 if (*p == '\0') {
3283 typestr++;
3284 break;
3285 }
3286 } else {
3287 if (*p == '.') {
3288 p++;
3289 while (qemu_isspace(*p))
3290 p++;
3291 } else {
3292 typestr++;
3293 break;
3294 }
3295 }
3296 typestr++;
3297 }
3298 if (get_expr(mon, &val, &p))
3299 goto fail;
3300 /* Check if 'i' is greater than 32-bit */
3301 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3302 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
3303 monitor_printf(mon, "integer is for 32-bit values\n");
3304 goto fail;
3305 } else if (c == 'M') {
3306 if (val < 0) {
3307 monitor_printf(mon, "enter a positive value\n");
3308 goto fail;
3309 }
3310 val *= MiB;
3311 }
3312 qdict_put_int(qdict, key, val);
3313 }
3314 break;
3315 case 'o':
3316 {
3317 int ret;
3318 uint64_t val;
3319 const char *end;
3320
3321 while (qemu_isspace(*p)) {
3322 p++;
3323 }
3324 if (*typestr == '?') {
3325 typestr++;
3326 if (*p == '\0') {
3327 break;
3328 }
3329 }
3330 ret = qemu_strtosz_MiB(p, &end, &val);
3331 if (ret < 0 || val > INT64_MAX) {
3332 monitor_printf(mon, "invalid size\n");
3333 goto fail;
3334 }
3335 qdict_put_int(qdict, key, val);
3336 p = end;
3337 }
3338 break;
3339 case 'T':
3340 {
3341 double val;
3342
3343 while (qemu_isspace(*p))
3344 p++;
3345 if (*typestr == '?') {
3346 typestr++;
3347 if (*p == '\0') {
3348 break;
3349 }
3350 }
3351 if (get_double(mon, &val, &p) < 0) {
3352 goto fail;
3353 }
3354 if (p[0] && p[1] == 's') {
3355 switch (*p) {
3356 case 'm':
3357 val /= 1e3; p += 2; break;
3358 case 'u':
3359 val /= 1e6; p += 2; break;
3360 case 'n':
3361 val /= 1e9; p += 2; break;
3362 }
3363 }
3364 if (*p && !qemu_isspace(*p)) {
3365 monitor_printf(mon, "Unknown unit suffix\n");
3366 goto fail;
3367 }
3368 qdict_put(qdict, key, qnum_from_double(val));
3369 }
3370 break;
3371 case 'b':
3372 {
3373 const char *beg;
3374 bool val;
3375
3376 while (qemu_isspace(*p)) {
3377 p++;
3378 }
3379 beg = p;
3380 while (qemu_isgraph(*p)) {
3381 p++;
3382 }
3383 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3384 val = true;
3385 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3386 val = false;
3387 } else {
3388 monitor_printf(mon, "Expected 'on' or 'off'\n");
3389 goto fail;
3390 }
3391 qdict_put_bool(qdict, key, val);
3392 }
3393 break;
3394 case '-':
3395 {
3396 const char *tmp = p;
3397 int skip_key = 0;
3398 /* option */
3399
3400 c = *typestr++;
3401 if (c == '\0')
3402 goto bad_type;
3403 while (qemu_isspace(*p))
3404 p++;
3405 if (*p == '-') {
3406 p++;
3407 if(c != *p) {
3408 if(!is_valid_option(p, typestr)) {
3409
3410 monitor_printf(mon, "%s: unsupported option -%c\n",
3411 cmd->name, *p);
3412 goto fail;
3413 } else {
3414 skip_key = 1;
3415 }
3416 }
3417 if(skip_key) {
3418 p = tmp;
3419 } else {
3420 /* has option */
3421 p++;
3422 qdict_put_bool(qdict, key, true);
3423 }
3424 }
3425 }
3426 break;
3427 case 'S':
3428 {
3429 /* package all remaining string */
3430 int len;
3431
3432 while (qemu_isspace(*p)) {
3433 p++;
3434 }
3435 if (*typestr == '?') {
3436 typestr++;
3437 if (*p == '\0') {
3438 /* no remaining string: NULL argument */
3439 break;
3440 }
3441 }
3442 len = strlen(p);
3443 if (len <= 0) {
3444 monitor_printf(mon, "%s: string expected\n",
3445 cmd->name);
3446 goto fail;
3447 }
3448 qdict_put_str(qdict, key, p);
3449 p += len;
3450 }
3451 break;
3452 default:
3453 bad_type:
3454 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3455 goto fail;
3456 }
3457 g_free(key);
3458 key = NULL;
3459 }
3460 /* check that all arguments were parsed */
3461 while (qemu_isspace(*p))
3462 p++;
3463 if (*p != '\0') {
3464 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3465 cmd->name);
3466 goto fail;
3467 }
3468
3469 return qdict;
3470
3471 fail:
3472 qobject_unref(qdict);
3473 g_free(key);
3474 return NULL;
3475 }
3476
3477 static void handle_hmp_command(MonitorHMP *mon, const char *cmdline)
3478 {
3479 QDict *qdict;
3480 const HMPCommand *cmd;
3481 const char *cmd_start = cmdline;
3482
3483 trace_handle_hmp_command(mon, cmdline);
3484
3485 cmd = monitor_parse_command(mon, cmdline, &cmdline, hmp_cmds);
3486 if (!cmd) {
3487 return;
3488 }
3489
3490 qdict = monitor_parse_arguments(&mon->common, &cmdline, cmd);
3491 if (!qdict) {
3492 while (cmdline > cmd_start && qemu_isspace(cmdline[-1])) {
3493 cmdline--;
3494 }
3495 monitor_printf(&mon->common, "Try \"help %.*s\" for more information\n",
3496 (int)(cmdline - cmd_start), cmd_start);
3497 return;
3498 }
3499
3500 cmd->cmd(&mon->common, qdict);
3501 qobject_unref(qdict);
3502 }
3503
3504 static void cmd_completion(MonitorHMP *mon, const char *name, const char *list)
3505 {
3506 const char *p, *pstart;
3507 char cmd[128];
3508 int len;
3509
3510 p = list;
3511 for(;;) {
3512 pstart = p;
3513 p = qemu_strchrnul(p, '|');
3514 len = p - pstart;
3515 if (len > sizeof(cmd) - 2)
3516 len = sizeof(cmd) - 2;
3517 memcpy(cmd, pstart, len);
3518 cmd[len] = '\0';
3519 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3520 readline_add_completion(mon->rs, cmd);
3521 }
3522 if (*p == '\0')
3523 break;
3524 p++;
3525 }
3526 }
3527
3528 static void file_completion(MonitorHMP *mon, const char *input)
3529 {
3530 DIR *ffs;
3531 struct dirent *d;
3532 char path[1024];
3533 char file[1024], file_prefix[1024];
3534 int input_path_len;
3535 const char *p;
3536
3537 p = strrchr(input, '/');
3538 if (!p) {
3539 input_path_len = 0;
3540 pstrcpy(file_prefix, sizeof(file_prefix), input);
3541 pstrcpy(path, sizeof(path), ".");
3542 } else {
3543 input_path_len = p - input + 1;
3544 memcpy(path, input, input_path_len);
3545 if (input_path_len > sizeof(path) - 1)
3546 input_path_len = sizeof(path) - 1;
3547 path[input_path_len] = '\0';
3548 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3549 }
3550
3551 ffs = opendir(path);
3552 if (!ffs)
3553 return;
3554 for(;;) {
3555 struct stat sb;
3556 d = readdir(ffs);
3557 if (!d)
3558 break;
3559
3560 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3561 continue;
3562 }
3563
3564 if (strstart(d->d_name, file_prefix, NULL)) {
3565 memcpy(file, input, input_path_len);
3566 if (input_path_len < sizeof(file))
3567 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3568 d->d_name);
3569 /* stat the file to find out if it's a directory.
3570 * In that case add a slash to speed up typing long paths
3571 */
3572 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3573 pstrcat(file, sizeof(file), "/");
3574 }
3575 readline_add_completion(mon->rs, file);
3576 }
3577 }
3578 closedir(ffs);
3579 }
3580
3581 static const char *next_arg_type(const char *typestr)
3582 {
3583 const char *p = strchr(typestr, ':');
3584 return (p != NULL ? ++p : typestr);
3585 }
3586
3587 static void add_completion_option(ReadLineState *rs, const char *str,
3588 const char *option)
3589 {
3590 if (!str || !option) {
3591 return;
3592 }
3593 if (!strncmp(option, str, strlen(str))) {
3594 readline_add_completion(rs, option);
3595 }
3596 }
3597
3598 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3599 {
3600 size_t len;
3601 ChardevBackendInfoList *list, *start;
3602
3603 if (nb_args != 2) {
3604 return;
3605 }
3606 len = strlen(str);
3607 readline_set_completion_index(rs, len);
3608
3609 start = list = qmp_query_chardev_backends(NULL);
3610 while (list) {
3611 const char *chr_name = list->value->name;
3612
3613 if (!strncmp(chr_name, str, len)) {
3614 readline_add_completion(rs, chr_name);
3615 }
3616 list = list->next;
3617 }
3618 qapi_free_ChardevBackendInfoList(start);
3619 }
3620
3621 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3622 {
3623 size_t len;
3624 int i;
3625
3626 if (nb_args != 2) {
3627 return;
3628 }
3629 len = strlen(str);
3630 readline_set_completion_index(rs, len);
3631 for (i = 0; i < NET_CLIENT_DRIVER__MAX; i++) {
3632 add_completion_option(rs, str, NetClientDriver_str(i));
3633 }
3634 }
3635
3636 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3637 {
3638 GSList *list, *elt;
3639 size_t len;
3640
3641 if (nb_args != 2) {
3642 return;
3643 }
3644
3645 len = strlen(str);
3646 readline_set_completion_index(rs, len);
3647 list = elt = object_class_get_list(TYPE_DEVICE, false);
3648 while (elt) {
3649 const char *name;
3650 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3651 TYPE_DEVICE);
3652 name = object_class_get_name(OBJECT_CLASS(dc));
3653
3654 if (dc->user_creatable
3655 && !strncmp(name, str, len)) {
3656 readline_add_completion(rs, name);
3657 }
3658 elt = elt->next;
3659 }
3660 g_slist_free(list);
3661 }
3662
3663 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3664 {
3665 GSList *list, *elt;
3666 size_t len;
3667
3668 if (nb_args != 2) {
3669 return;
3670 }
3671
3672 len = strlen(str);
3673 readline_set_completion_index(rs, len);
3674 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3675 while (elt) {
3676 const char *name;
3677
3678 name = object_class_get_name(OBJECT_CLASS(elt->data));
3679 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3680 readline_add_completion(rs, name);
3681 }
3682 elt = elt->next;
3683 }
3684 g_slist_free(list);
3685 }
3686
3687 static void peripheral_device_del_completion(ReadLineState *rs,
3688 const char *str, size_t len)
3689 {
3690 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3691 GSList *list, *item;
3692
3693 list = qdev_build_hotpluggable_device_list(peripheral);
3694 if (!list) {
3695 return;
3696 }
3697
3698 for (item = list; item; item = g_slist_next(item)) {
3699 DeviceState *dev = item->data;
3700
3701 if (dev->id && !strncmp(str, dev->id, len)) {
3702 readline_add_completion(rs, dev->id);
3703 }
3704 }
3705
3706 g_slist_free(list);
3707 }
3708
3709 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3710 {
3711 size_t len;
3712 ChardevInfoList *list, *start;
3713
3714 if (nb_args != 2) {
3715 return;
3716 }
3717 len = strlen(str);
3718 readline_set_completion_index(rs, len);
3719
3720 start = list = qmp_query_chardev(NULL);
3721 while (list) {
3722 ChardevInfo *chr = list->value;
3723
3724 if (!strncmp(chr->label, str, len)) {
3725 readline_add_completion(rs, chr->label);
3726 }
3727 list = list->next;
3728 }
3729 qapi_free_ChardevInfoList(start);
3730 }
3731
3732 static void ringbuf_completion(ReadLineState *rs, const char *str)
3733 {
3734 size_t len;
3735 ChardevInfoList *list, *start;
3736
3737 len = strlen(str);
3738 readline_set_completion_index(rs, len);
3739
3740 start = list = qmp_query_chardev(NULL);
3741 while (list) {
3742 ChardevInfo *chr_info = list->value;
3743
3744 if (!strncmp(chr_info->label, str, len)) {
3745 Chardev *chr = qemu_chr_find(chr_info->label);
3746 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3747 readline_add_completion(rs, chr_info->label);
3748 }
3749 }
3750 list = list->next;
3751 }
3752 qapi_free_ChardevInfoList(start);
3753 }
3754
3755 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3756 {
3757 if (nb_args != 2) {
3758 return;
3759 }
3760 ringbuf_completion(rs, str);
3761 }
3762
3763 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3764 {
3765 size_t len;
3766
3767 if (nb_args != 2) {
3768 return;
3769 }
3770
3771 len = strlen(str);
3772 readline_set_completion_index(rs, len);
3773 peripheral_device_del_completion(rs, str, len);
3774 }
3775
3776 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3777 {
3778 ObjectPropertyInfoList *list, *start;
3779 size_t len;
3780
3781 if (nb_args != 2) {
3782 return;
3783 }
3784 len = strlen(str);
3785 readline_set_completion_index(rs, len);
3786
3787 start = list = qmp_qom_list("/objects", NULL);
3788 while (list) {
3789 ObjectPropertyInfo *info = list->value;
3790
3791 if (!strncmp(info->type, "child<", 5)
3792 && !strncmp(info->name, str, len)) {
3793 readline_add_completion(rs, info->name);
3794 }
3795 list = list->next;
3796 }
3797 qapi_free_ObjectPropertyInfoList(start);
3798 }
3799
3800 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3801 {
3802 int i;
3803 char *sep;
3804 size_t len;
3805
3806 if (nb_args != 2) {
3807 return;
3808 }
3809 sep = strrchr(str, '-');
3810 if (sep) {
3811 str = sep + 1;
3812 }
3813 len = strlen(str);
3814 readline_set_completion_index(rs, len);
3815 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3816 if (!strncmp(str, QKeyCode_str(i), len)) {
3817 readline_add_completion(rs, QKeyCode_str(i));
3818 }
3819 }
3820 }
3821
3822 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3823 {
3824 size_t len;
3825
3826 len = strlen(str);
3827 readline_set_completion_index(rs, len);
3828 if (nb_args == 2) {
3829 NetClientState *ncs[MAX_QUEUE_NUM];
3830 int count, i;
3831 count = qemu_find_net_clients_except(NULL, ncs,
3832 NET_CLIENT_DRIVER_NONE,
3833 MAX_QUEUE_NUM);
3834 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3835 const char *name = ncs[i]->name;
3836 if (!strncmp(str, name, len)) {
3837 readline_add_completion(rs, name);
3838 }
3839 }
3840 } else if (nb_args == 3) {
3841 add_completion_option(rs, str, "on");
3842 add_completion_option(rs, str, "off");
3843 }
3844 }
3845
3846 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3847 {
3848 int len, count, i;
3849 NetClientState *ncs[MAX_QUEUE_NUM];
3850
3851 if (nb_args != 2) {
3852 return;
3853 }
3854
3855 len = strlen(str);
3856 readline_set_completion_index(rs, len);
3857 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3858 MAX_QUEUE_NUM);
3859 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3860 QemuOpts *opts;
3861 const char *name = ncs[i]->name;
3862 if (strncmp(str, name, len)) {
3863 continue;
3864 }
3865 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3866 if (opts) {
3867 readline_add_completion(rs, name);
3868 }
3869 }
3870 }
3871
3872 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3873 {
3874 size_t len;
3875
3876 len = strlen(str);
3877 readline_set_completion_index(rs, len);
3878 if (nb_args == 2) {
3879 TraceEventIter iter;
3880 TraceEvent *ev;
3881 char *pattern = g_strdup_printf("%s*", str);
3882 trace_event_iter_init(&iter, pattern);
3883 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3884 readline_add_completion(rs, trace_event_get_name(ev));
3885 }
3886 g_free(pattern);
3887 }
3888 }
3889
3890 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3891 {
3892 size_t len;
3893
3894 len = strlen(str);
3895 readline_set_completion_index(rs, len);
3896 if (nb_args == 2) {
3897 TraceEventIter iter;
3898 TraceEvent *ev;
3899 char *pattern = g_strdup_printf("%s*", str);
3900 trace_event_iter_init(&iter, pattern);
3901 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3902 readline_add_completion(rs, trace_event_get_name(ev));
3903 }
3904 g_free(pattern);
3905 } else if (nb_args == 3) {
3906 add_completion_option(rs, str, "on");
3907 add_completion_option(rs, str, "off");
3908 }
3909 }
3910
3911 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3912 {
3913 int i;
3914
3915 if (nb_args != 2) {
3916 return;
3917 }
3918 readline_set_completion_index(rs, strlen(str));
3919 for (i = 0; i < WATCHDOG_ACTION__MAX; i++) {
3920 add_completion_option(rs, str, WatchdogAction_str(i));
3921 }
3922 }
3923
3924 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3925 const char *str)
3926 {
3927 size_t len;
3928
3929 len = strlen(str);
3930 readline_set_completion_index(rs, len);
3931 if (nb_args == 2) {
3932 int i;
3933 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3934 const char *name = MigrationCapability_str(i);
3935 if (!strncmp(str, name, len)) {
3936 readline_add_completion(rs, name);
3937 }
3938 }
3939 } else if (nb_args == 3) {
3940 add_completion_option(rs, str, "on");
3941 add_completion_option(rs, str, "off");
3942 }
3943 }
3944
3945 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3946 const char *str)
3947 {
3948 size_t len;
3949
3950 len = strlen(str);
3951 readline_set_completion_index(rs, len);
3952 if (nb_args == 2) {
3953 int i;
3954 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3955 const char *name = MigrationParameter_str(i);
3956 if (!strncmp(str, name, len)) {
3957 readline_add_completion(rs, name);
3958 }
3959 }
3960 }
3961 }
3962
3963 static void vm_completion(ReadLineState *rs, const char *str)
3964 {
3965 size_t len;
3966 BlockDriverState *bs;
3967 BdrvNextIterator it;
3968
3969 len = strlen(str);
3970 readline_set_completion_index(rs, len);
3971
3972 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3973 SnapshotInfoList *snapshots, *snapshot;
3974 AioContext *ctx = bdrv_get_aio_context(bs);
3975 bool ok = false;
3976
3977 aio_context_acquire(ctx);
3978 if (bdrv_can_snapshot(bs)) {
3979 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3980 }
3981 aio_context_release(ctx);
3982 if (!ok) {
3983 continue;
3984 }
3985
3986 snapshot = snapshots;
3987 while (snapshot) {
3988 char *completion = snapshot->value->name;
3989 if (!strncmp(str, completion, len)) {
3990 readline_add_completion(rs, completion);
3991 }
3992 completion = snapshot->value->id;
3993 if (!strncmp(str, completion, len)) {
3994 readline_add_completion(rs, completion);
3995 }
3996 snapshot = snapshot->next;
3997 }
3998 qapi_free_SnapshotInfoList(snapshots);
3999 }
4000
4001 }
4002
4003 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
4004 {
4005 if (nb_args == 2) {
4006 vm_completion(rs, str);
4007 }
4008 }
4009
4010 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
4011 {
4012 if (nb_args == 2) {
4013 vm_completion(rs, str);
4014 }
4015 }
4016
4017 static void monitor_find_completion_by_table(MonitorHMP *mon,
4018 const HMPCommand *cmd_table,
4019 char **args,
4020 int nb_args)
4021 {
4022 const char *cmdname;
4023 int i;
4024 const char *ptype, *old_ptype, *str, *name;
4025 const HMPCommand *cmd;
4026 BlockBackend *blk = NULL;
4027
4028 if (nb_args <= 1) {
4029 /* command completion */
4030 if (nb_args == 0)
4031 cmdname = "";
4032 else
4033 cmdname = args[0];
4034 readline_set_completion_index(mon->rs, strlen(cmdname));
4035 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4036 if (!runstate_check(RUN_STATE_PRECONFIG) ||
4037 cmd_can_preconfig(cmd)) {
4038 cmd_completion(mon, cmdname, cmd->name);
4039 }
4040 }
4041 } else {
4042 /* find the command */
4043 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4044 if (compare_cmd(args[0], cmd->name) &&
4045 (!runstate_check(RUN_STATE_PRECONFIG) ||
4046 cmd_can_preconfig(cmd))) {
4047 break;
4048 }
4049 }
4050 if (!cmd->name) {
4051 return;
4052 }
4053
4054 if (cmd->sub_table) {
4055 /* do the job again */
4056 monitor_find_completion_by_table(mon, cmd->sub_table,
4057 &args[1], nb_args - 1);
4058 return;
4059 }
4060 if (cmd->command_completion) {
4061 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
4062 return;
4063 }
4064
4065 ptype = next_arg_type(cmd->args_type);
4066 for(i = 0; i < nb_args - 2; i++) {
4067 if (*ptype != '\0') {
4068 ptype = next_arg_type(ptype);
4069 while (*ptype == '?')
4070 ptype = next_arg_type(ptype);
4071 }
4072 }
4073 str = args[nb_args - 1];
4074 old_ptype = NULL;
4075 while (*ptype == '-' && old_ptype != ptype) {
4076 old_ptype = ptype;
4077 ptype = next_arg_type(ptype);
4078 }
4079 switch(*ptype) {
4080 case 'F':
4081 /* file completion */
4082 readline_set_completion_index(mon->rs, strlen(str));
4083 file_completion(mon, str);
4084 break;
4085 case 'B':
4086 /* block device name completion */
4087 readline_set_completion_index(mon->rs, strlen(str));
4088 while ((blk = blk_next(blk)) != NULL) {
4089 name = blk_name(blk);
4090 if (str[0] == '\0' ||
4091 !strncmp(name, str, strlen(str))) {
4092 readline_add_completion(mon->rs, name);
4093 }
4094 }
4095 break;
4096 case 's':
4097 case 'S':
4098 if (!strcmp(cmd->name, "help|?")) {
4099 monitor_find_completion_by_table(mon, cmd_table,
4100 &args[1], nb_args - 1);
4101 }
4102 break;
4103 default:
4104 break;
4105 }
4106 }
4107 }
4108
4109 static void monitor_find_completion(void *opaque,
4110 const char *cmdline)
4111 {
4112 MonitorHMP *mon = opaque;
4113 char *args[MAX_ARGS];
4114 int nb_args, len;
4115
4116 /* 1. parse the cmdline */
4117 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
4118 return;
4119 }
4120
4121 /* if the line ends with a space, it means we want to complete the
4122 next arg */
4123 len = strlen(cmdline);
4124 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4125 if (nb_args >= MAX_ARGS) {
4126 goto cleanup;
4127 }
4128 args[nb_args++] = g_strdup("");
4129 }
4130
4131 /* 2. auto complete according to args */
4132 monitor_find_completion_by_table(mon, hmp_cmds, args, nb_args);
4133
4134 cleanup:
4135 free_cmdline_args(args, nb_args);
4136 }
4137
4138 static int monitor_can_read(void *opaque)
4139 {
4140 Monitor *mon = opaque;
4141
4142 return !atomic_mb_read(&mon->suspend_cnt);
4143 }
4144
4145 /*
4146 * Emit QMP response @rsp with ID @id to @mon.
4147 * Null @rsp can only happen for commands with QCO_NO_SUCCESS_RESP.
4148 * Nothing is emitted then.
4149 */
4150 static void monitor_qmp_respond(MonitorQMP *mon, QDict *rsp)
4151 {
4152 if (rsp) {
4153 qmp_send_response(mon, rsp);
4154 }
4155 }
4156
4157 static void monitor_qmp_dispatch(MonitorQMP *mon, QObject *req)
4158 {
4159 Monitor *old_mon;
4160 QDict *rsp;
4161 QDict *error;
4162
4163 old_mon = cur_mon;
4164 cur_mon = &mon->common;
4165
4166 rsp = qmp_dispatch(mon->commands, req, qmp_oob_enabled(mon));
4167
4168 cur_mon = old_mon;
4169
4170 if (mon->commands == &qmp_cap_negotiation_commands) {
4171 error = qdict_get_qdict(rsp, "error");
4172 if (error
4173 && !g_strcmp0(qdict_get_try_str(error, "class"),
4174 QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
4175 /* Provide a more useful error message */
4176 qdict_del(error, "desc");
4177 qdict_put_str(error, "desc", "Expecting capabilities negotiation"
4178 " with 'qmp_capabilities'");
4179 }
4180 }
4181
4182 monitor_qmp_respond(mon, rsp);
4183 qobject_unref(rsp);
4184 }
4185
4186 /*
4187 * Pop a QMP request from a monitor request queue.
4188 * Return the request, or NULL all request queues are empty.
4189 * We are using round-robin fashion to pop the request, to avoid
4190 * processing commands only on a very busy monitor. To achieve that,
4191 * when we process one request on a specific monitor, we put that
4192 * monitor to the end of mon_list queue.
4193 *
4194 * Note: if the function returned with non-NULL, then the caller will
4195 * be with qmp_mon->qmp_queue_lock held, and the caller is responsible
4196 * to release it.
4197 */
4198 static QMPRequest *monitor_qmp_requests_pop_any_with_lock(void)
4199 {
4200 QMPRequest *req_obj = NULL;
4201 Monitor *mon;
4202 MonitorQMP *qmp_mon;
4203
4204 qemu_mutex_lock(&monitor_lock);
4205
4206 QTAILQ_FOREACH(mon, &mon_list, entry) {
4207 if (!monitor_is_qmp(mon)) {
4208 continue;
4209 }
4210
4211 qmp_mon = container_of(mon, MonitorQMP, common);
4212 qemu_mutex_lock(&qmp_mon->qmp_queue_lock);
4213 req_obj = g_queue_pop_head(qmp_mon->qmp_requests);
4214 if (req_obj) {
4215 /* With the lock of corresponding queue held */
4216 break;
4217 }
4218 qemu_mutex_unlock(&qmp_mon->qmp_queue_lock);
4219 }
4220
4221 if (req_obj) {
4222 /*
4223 * We found one request on the monitor. Degrade this monitor's
4224 * priority to lowest by re-inserting it to end of queue.
4225 */
4226 QTAILQ_REMOVE(&mon_list, mon, entry);
4227 QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
4228 }
4229
4230 qemu_mutex_unlock(&monitor_lock);
4231
4232 return req_obj;
4233 }
4234
4235 static void monitor_qmp_bh_dispatcher(void *data)
4236 {
4237 QMPRequest *req_obj = monitor_qmp_requests_pop_any_with_lock();
4238 QDict *rsp;
4239 bool need_resume;
4240 MonitorQMP *mon;
4241
4242 if (!req_obj) {
4243 return;
4244 }
4245
4246 mon = req_obj->mon;
4247 /* qmp_oob_enabled() might change after "qmp_capabilities" */
4248 need_resume = !qmp_oob_enabled(mon) ||
4249 mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1;
4250 qemu_mutex_unlock(&mon->qmp_queue_lock);
4251 if (req_obj->req) {
4252 QDict *qdict = qobject_to(QDict, req_obj->req);
4253 QObject *id = qdict ? qdict_get(qdict, "id") : NULL;
4254 trace_monitor_qmp_cmd_in_band(qobject_get_try_str(id) ?: "");
4255 monitor_qmp_dispatch(mon, req_obj->req);
4256 } else {
4257 assert(req_obj->err);
4258 rsp = qmp_error_response(req_obj->err);
4259 req_obj->err = NULL;
4260 monitor_qmp_respond(mon, rsp);
4261 qobject_unref(rsp);
4262 }
4263
4264 if (need_resume) {
4265 /* Pairs with the monitor_suspend() in handle_qmp_command() */
4266 monitor_resume(&mon->common);
4267 }
4268 qmp_request_free(req_obj);
4269
4270 /* Reschedule instead of looping so the main loop stays responsive */
4271 qemu_bh_schedule(qmp_dispatcher_bh);
4272 }
4273
4274 static void handle_qmp_command(void *opaque, QObject *req, Error *err)
4275 {
4276 MonitorQMP *mon = opaque;
4277 QObject *id = NULL;
4278 QDict *qdict;
4279 QMPRequest *req_obj;
4280
4281 assert(!req != !err);
4282
4283 qdict = qobject_to(QDict, req);
4284 if (qdict) {
4285 id = qdict_get(qdict, "id");
4286 } /* else will fail qmp_dispatch() */
4287
4288 if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
4289 QString *req_json = qobject_to_json(req);
4290 trace_handle_qmp_command(mon, qstring_get_str(req_json));
4291 qobject_unref(req_json);
4292 }
4293
4294 if (qdict && qmp_is_oob(qdict)) {
4295 /* OOB commands are executed immediately */
4296 trace_monitor_qmp_cmd_out_of_band(qobject_get_try_str(id) ?: "");
4297 monitor_qmp_dispatch(mon, req);
4298 qobject_unref(req);
4299 return;
4300 }
4301
4302 req_obj = g_new0(QMPRequest, 1);
4303 req_obj->mon = mon;
4304 req_obj->req = req;
4305 req_obj->err = err;
4306
4307 /* Protect qmp_requests and fetching its length. */
4308 qemu_mutex_lock(&mon->qmp_queue_lock);
4309
4310 /*
4311 * Suspend the monitor when we can't queue more requests after
4312 * this one. Dequeuing in monitor_qmp_bh_dispatcher() will resume
4313 * it. Note that when OOB is disabled, we queue at most one
4314 * command, for backward compatibility.
4315 */
4316 if (!qmp_oob_enabled(mon) ||
4317 mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
4318 monitor_suspend(&mon->common);
4319 }
4320
4321 /*
4322 * Put the request to the end of queue so that requests will be
4323 * handled in time order. Ownership for req_obj, req,
4324 * etc. will be delivered to the handler side.
4325 */
4326 assert(mon->qmp_requests->length < QMP_REQ_QUEUE_LEN_MAX);
4327 g_queue_push_tail(mon->qmp_requests, req_obj);
4328 qemu_mutex_unlock(&mon->qmp_queue_lock);
4329
4330 /* Kick the dispatcher routine */
4331 qemu_bh_schedule(qmp_dispatcher_bh);
4332 }
4333
4334 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
4335 {
4336 MonitorQMP *mon = opaque;
4337
4338 json_message_parser_feed(&mon->parser, (const char *) buf, size);
4339 }
4340
4341 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4342 {
4343 MonitorHMP *mon;
4344 Monitor *old_mon = cur_mon;
4345 int i;
4346
4347 cur_mon = opaque;
4348 mon = container_of(cur_mon, MonitorHMP, common);
4349
4350 if (mon->rs) {
4351 for (i = 0; i < size; i++)
4352 readline_handle_byte(mon->rs, buf[i]);
4353 } else {
4354 if (size == 0 || buf[size - 1] != 0)
4355 monitor_printf(cur_mon, "corrupted command\n");
4356 else
4357 handle_hmp_command(mon, (char *)buf);
4358 }
4359
4360 cur_mon = old_mon;
4361 }
4362
4363 static void monitor_command_cb(void *opaque, const char *cmdline,
4364 void *readline_opaque)
4365 {
4366 MonitorHMP *mon = opaque;
4367
4368 monitor_suspend(&mon->common);
4369 handle_hmp_command(mon, cmdline);
4370 monitor_resume(&mon->common);
4371 }
4372
4373 int monitor_suspend(Monitor *mon)
4374 {
4375 if (monitor_is_hmp_non_interactive(mon)) {
4376 return -ENOTTY;
4377 }
4378
4379 atomic_inc(&mon->suspend_cnt);
4380
4381 if (mon->use_io_thread) {
4382 /*
4383 * Kick I/O thread to make sure this takes effect. It'll be
4384 * evaluated again in prepare() of the watch object.
4385 */
4386 aio_notify(iothread_get_aio_context(mon_iothread));
4387 }
4388
4389 trace_monitor_suspend(mon, 1);
4390 return 0;
4391 }
4392
4393 static void monitor_accept_input(void *opaque)
4394 {
4395 Monitor *mon = opaque;
4396
4397 qemu_chr_fe_accept_input(&mon->chr);
4398 }
4399
4400 void monitor_resume(Monitor *mon)
4401 {
4402 if (monitor_is_hmp_non_interactive(mon)) {
4403 return;
4404 }
4405
4406 if (atomic_dec_fetch(&mon->suspend_cnt) == 0) {
4407 AioContext *ctx;
4408
4409 if (mon->use_io_thread) {
4410 ctx = iothread_get_aio_context(mon_iothread);
4411 } else {
4412 ctx = qemu_get_aio_context();
4413 }
4414
4415 if (!monitor_is_qmp(mon)) {
4416 MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
4417 assert(hmp_mon->rs);
4418 readline_show_prompt(hmp_mon->rs);
4419 }
4420
4421 aio_bh_schedule_oneshot(ctx, monitor_accept_input, mon);
4422 }
4423
4424 trace_monitor_suspend(mon, -1);
4425 }
4426
4427 static QDict *qmp_greeting(MonitorQMP *mon)
4428 {
4429 QList *cap_list = qlist_new();
4430 QObject *ver = NULL;
4431 QMPCapability cap;
4432
4433 qmp_marshal_query_version(NULL, &ver, NULL);
4434
4435 for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
4436 if (mon->capab_offered[cap]) {
4437 qlist_append_str(cap_list, QMPCapability_str(cap));
4438 }
4439 }
4440
4441 return qdict_from_jsonf_nofail(
4442 "{'QMP': {'version': %p, 'capabilities': %p}}",
4443 ver, cap_list);
4444 }
4445
4446 static void monitor_qmp_event(void *opaque, int event)
4447 {
4448 QDict *data;
4449 MonitorQMP *mon = opaque;
4450
4451 switch (event) {
4452 case CHR_EVENT_OPENED:
4453 mon->commands = &qmp_cap_negotiation_commands;
4454 monitor_qmp_caps_reset(mon);
4455 data = qmp_greeting(mon);
4456 qmp_send_response(mon, data);
4457 qobject_unref(data);
4458 mon_refcount++;
4459 break;
4460 case CHR_EVENT_CLOSED:
4461 /*
4462 * Note: this is only useful when the output of the chardev
4463 * backend is still open. For example, when the backend is
4464 * stdio, it's possible that stdout is still open when stdin
4465 * is closed.
4466 */
4467 monitor_qmp_cleanup_queues(mon);
4468 json_message_parser_destroy(&mon->parser);
4469 json_message_parser_init(&mon->parser, handle_qmp_command,
4470 mon, NULL);
4471 mon_refcount--;
4472 monitor_fdsets_cleanup();
4473 break;
4474 }
4475 }
4476
4477 static void monitor_event(void *opaque, int event)
4478 {
4479 Monitor *mon = opaque;
4480 MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
4481
4482 switch (event) {
4483 case CHR_EVENT_MUX_IN:
4484 qemu_mutex_lock(&mon->mon_lock);
4485 mon->mux_out = 0;
4486 qemu_mutex_unlock(&mon->mon_lock);
4487 if (mon->reset_seen) {
4488 readline_restart(hmp_mon->rs);
4489 monitor_resume(mon);
4490 monitor_flush(mon);
4491 } else {
4492 atomic_mb_set(&mon->suspend_cnt, 0);
4493 }
4494 break;
4495
4496 case CHR_EVENT_MUX_OUT:
4497 if (mon->reset_seen) {
4498 if (atomic_mb_read(&mon->suspend_cnt) == 0) {
4499 monitor_printf(mon, "\n");
4500 }
4501 monitor_flush(mon);
4502 monitor_suspend(mon);
4503 } else {
4504 atomic_inc(&mon->suspend_cnt);
4505 }
4506 qemu_mutex_lock(&mon->mon_lock);
4507 mon->mux_out = 1;
4508 qemu_mutex_unlock(&mon->mon_lock);
4509 break;
4510
4511 case CHR_EVENT_OPENED:
4512 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4513 "information\n", QEMU_VERSION);
4514 if (!mon->mux_out) {
4515 readline_restart(hmp_mon->rs);
4516 readline_show_prompt(hmp_mon->rs);
4517 }
4518 mon->reset_seen = 1;
4519 mon_refcount++;
4520 break;
4521
4522 case CHR_EVENT_CLOSED:
4523 mon_refcount--;
4524 monitor_fdsets_cleanup();
4525 break;
4526 }
4527 }
4528
4529 static int
4530 compare_mon_cmd(const void *a, const void *b)
4531 {
4532 return strcmp(((const HMPCommand *)a)->name,
4533 ((const HMPCommand *)b)->name);
4534 }
4535
4536 static void sortcmdlist(void)
4537 {
4538 qsort(hmp_cmds, ARRAY_SIZE(hmp_cmds) - 1,
4539 sizeof(*hmp_cmds),
4540 compare_mon_cmd);
4541 qsort(hmp_info_cmds, ARRAY_SIZE(hmp_info_cmds) - 1,
4542 sizeof(*hmp_info_cmds),
4543 compare_mon_cmd);
4544 }
4545
4546 static void monitor_iothread_init(void)
4547 {
4548 mon_iothread = iothread_create("mon_iothread", &error_abort);
4549 }
4550
4551 void monitor_init_globals(void)
4552 {
4553 monitor_init_qmp_commands();
4554 monitor_qapi_event_init();
4555 sortcmdlist();
4556 qemu_mutex_init(&monitor_lock);
4557 qemu_mutex_init(&mon_fdsets_lock);
4558
4559 /*
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.
4563 */
4564 qmp_dispatcher_bh = aio_bh_new(iohandler_get_aio_context(),
4565 monitor_qmp_bh_dispatcher,
4566 NULL);
4567 }
4568
4569 /* These functions just adapt the readline interface in a typesafe way. We
4570 * could cast function pointers but that discards compiler checks.
4571 */
4572 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4573 const char *fmt, ...)
4574 {
4575 MonitorHMP *mon = opaque;
4576 va_list ap;
4577 va_start(ap, fmt);
4578 monitor_vprintf(&mon->common, fmt, ap);
4579 va_end(ap);
4580 }
4581
4582 static void monitor_readline_flush(void *opaque)
4583 {
4584 MonitorHMP *mon = opaque;
4585 monitor_flush(&mon->common);
4586 }
4587
4588 /*
4589 * Print to current monitor if we have one, else to stderr.
4590 */
4591 int error_vprintf(const char *fmt, va_list ap)
4592 {
4593 if (cur_mon && !monitor_cur_is_qmp()) {
4594 return monitor_vprintf(cur_mon, fmt, ap);
4595 }
4596 return vfprintf(stderr, fmt, ap);
4597 }
4598
4599 int error_vprintf_unless_qmp(const char *fmt, va_list ap)
4600 {
4601 if (!cur_mon) {
4602 return vfprintf(stderr, fmt, ap);
4603 }
4604 if (!monitor_cur_is_qmp()) {
4605 return monitor_vprintf(cur_mon, fmt, ap);
4606 }
4607 return -1;
4608 }
4609
4610 static void monitor_list_append(Monitor *mon)
4611 {
4612 qemu_mutex_lock(&monitor_lock);
4613 /*
4614 * This prevents inserting new monitors during monitor_cleanup().
4615 * A cleaner solution would involve the main thread telling other
4616 * threads to terminate, waiting for their termination.
4617 */
4618 if (!monitor_destroyed) {
4619 QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
4620 mon = NULL;
4621 }
4622 qemu_mutex_unlock(&monitor_lock);
4623
4624 if (mon) {
4625 monitor_data_destroy(mon);
4626 g_free(mon);
4627 }
4628 }
4629
4630 static void monitor_qmp_setup_handlers_bh(void *opaque)
4631 {
4632 MonitorQMP *mon = opaque;
4633 GMainContext *context;
4634
4635 assert(mon->common.use_io_thread);
4636 context = iothread_get_g_main_context(mon_iothread);
4637 assert(context);
4638 qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
4639 monitor_qmp_read, monitor_qmp_event,
4640 NULL, &mon->common, context, true);
4641 monitor_list_append(&mon->common);
4642 }
4643
4644 static void monitor_init_qmp(Chardev *chr, int flags)
4645 {
4646 MonitorQMP *mon = g_new0(MonitorQMP, 1);
4647
4648 /* Only HMP supports readline */
4649 assert(!(flags & MONITOR_USE_READLINE));
4650
4651 /* Note: we run QMP monitor in I/O thread when @chr supports that */
4652 monitor_data_init(&mon->common, flags, false,
4653 qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT));
4654
4655 qemu_mutex_init(&mon->qmp_queue_lock);
4656 mon->qmp_requests = g_queue_new();
4657
4658 qemu_chr_fe_init(&mon->common.chr, chr, &error_abort);
4659 qemu_chr_fe_set_echo(&mon->common.chr, true);
4660
4661 json_message_parser_init(&mon->parser, handle_qmp_command, mon, NULL);
4662 if (mon->common.use_io_thread) {
4663 /*
4664 * Make sure the old iowatch is gone. It's possible when
4665 * e.g. the chardev is in client mode, with wait=on.
4666 */
4667 remove_fd_in_watch(chr);
4668 /*
4669 * We can't call qemu_chr_fe_set_handlers() directly here
4670 * since chardev might be running in the monitor I/O
4671 * thread. Schedule a bottom half.
4672 */
4673 aio_bh_schedule_oneshot(iothread_get_aio_context(mon_iothread),
4674 monitor_qmp_setup_handlers_bh, mon);
4675 /* The bottom half will add @mon to @mon_list */
4676 } else {
4677 qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
4678 monitor_qmp_read, monitor_qmp_event,
4679 NULL, &mon->common, NULL, true);
4680 monitor_list_append(&mon->common);
4681 }
4682 }
4683
4684 static void monitor_init_hmp(Chardev *chr, int flags)
4685 {
4686 MonitorHMP *mon = g_new0(MonitorHMP, 1);
4687 bool use_readline = flags & MONITOR_USE_READLINE;
4688
4689 monitor_data_init(&mon->common, flags, false, false);
4690 qemu_chr_fe_init(&mon->common.chr, chr, &error_abort);
4691
4692 if (use_readline) {
4693 mon->rs = readline_init(monitor_readline_printf,
4694 monitor_readline_flush,
4695 mon,
4696 monitor_find_completion);
4697 monitor_read_command(mon, 0);
4698 }
4699
4700 qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read, monitor_read,
4701 monitor_event, NULL, &mon->common, NULL, true);
4702 monitor_list_append(&mon->common);
4703 }
4704
4705 void monitor_init(Chardev *chr, int flags)
4706 {
4707 if (flags & MONITOR_USE_CONTROL) {
4708 monitor_init_qmp(chr, flags);
4709 } else {
4710 monitor_init_hmp(chr, flags);
4711 }
4712 }
4713
4714 void monitor_cleanup(void)
4715 {
4716 /*
4717 * We need to explicitly stop the I/O thread (but not destroy it),
4718 * clean up the monitor resources, then destroy the I/O thread since
4719 * we need to unregister from chardev below in
4720 * monitor_data_destroy(), and chardev is not thread-safe yet
4721 */
4722 if (mon_iothread) {
4723 iothread_stop(mon_iothread);
4724 }
4725
4726 /* Flush output buffers and destroy monitors */
4727 qemu_mutex_lock(&monitor_lock);
4728 monitor_destroyed = true;
4729 while (!QTAILQ_EMPTY(&mon_list)) {
4730 Monitor *mon = QTAILQ_FIRST(&mon_list);
4731 QTAILQ_REMOVE(&mon_list, mon, entry);
4732 /* Permit QAPI event emission from character frontend release */
4733 qemu_mutex_unlock(&monitor_lock);
4734 monitor_flush(mon);
4735 monitor_data_destroy(mon);
4736 qemu_mutex_lock(&monitor_lock);
4737 g_free(mon);
4738 }
4739 qemu_mutex_unlock(&monitor_lock);
4740
4741 /* QEMUBHs needs to be deleted before destroying the I/O thread */
4742 qemu_bh_delete(qmp_dispatcher_bh);
4743 qmp_dispatcher_bh = NULL;
4744 if (mon_iothread) {
4745 iothread_destroy(mon_iothread);
4746 mon_iothread = NULL;
4747 }
4748 }
4749
4750 QemuOptsList qemu_mon_opts = {
4751 .name = "mon",
4752 .implied_opt_name = "chardev",
4753 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4754 .desc = {
4755 {
4756 .name = "mode",
4757 .type = QEMU_OPT_STRING,
4758 },{
4759 .name = "chardev",
4760 .type = QEMU_OPT_STRING,
4761 },{
4762 .name = "pretty",
4763 .type = QEMU_OPT_BOOL,
4764 },
4765 { /* end of list */ }
4766 },
4767 };
4768
4769 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4770 {
4771 MachineState *ms = MACHINE(qdev_get_machine());
4772 MachineClass *mc = MACHINE_GET_CLASS(ms);
4773
4774 if (!mc->has_hotpluggable_cpus) {
4775 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4776 return NULL;
4777 }
4778
4779 return machine_query_hotpluggable_cpus(ms);
4780 }