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