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