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