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