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