]> git.proxmox.com Git - mirror_qemu.git/blob - monitor.c
monitor: use qmp_find_command() (using generated qapi code)
[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 CommandInfoList *qmp_query_commands(Error **errp)
961 {
962 CommandInfoList *info, *cmd_list = NULL;
963 const mon_cmd_t *cmd;
964
965 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
966 info = g_malloc0(sizeof(*info));
967 info->value = g_malloc0(sizeof(*info->value));
968 info->value->name = g_strdup(cmd->name);
969
970 info->next = cmd_list;
971 cmd_list = info;
972 }
973
974 return cmd_list;
975 }
976
977 EventInfoList *qmp_query_events(Error **errp)
978 {
979 EventInfoList *info, *ev_list = NULL;
980 QAPIEvent e;
981
982 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
983 const char *event_name = QAPIEvent_lookup[e];
984 assert(event_name != NULL);
985 info = g_malloc0(sizeof(*info));
986 info->value = g_malloc0(sizeof(*info->value));
987 info->value->name = g_strdup(event_name);
988
989 info->next = ev_list;
990 ev_list = info;
991 }
992
993 return ev_list;
994 }
995
996 /*
997 * Minor hack: generated marshalling suppressed for this command
998 * ('gen': false in the schema) so we can parse the JSON string
999 * directly into QObject instead of first parsing it with
1000 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
1001 * to QObject with generated output marshallers, every time. Instead,
1002 * we do it in test-qmp-input-visitor.c, just to make sure
1003 * qapi-introspect.py's output actually conforms to the schema.
1004 */
1005 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
1006 Error **errp)
1007 {
1008 *ret_data = qobject_from_json(qmp_schema_json);
1009 }
1010
1011 /*
1012 * We used to define commands in qmp-commands.hx in addition to the
1013 * QAPI schema. This permitted defining some of them only in certain
1014 * configurations. query-commands has always reflected that (good,
1015 * because it lets QMP clients figure out what's actually available),
1016 * while query-qmp-schema never did (not so good). This function is a
1017 * hack to keep the configuration-specific commands defined exactly as
1018 * before, even though qmp-commands.hx is gone.
1019 *
1020 * FIXME Educate the QAPI schema on configuration-specific commands,
1021 * and drop this hack.
1022 */
1023 static void qmp_unregister_commands_hack(void)
1024 {
1025 #ifndef CONFIG_SPICE
1026 qmp_unregister_command("query-spice");
1027 #endif
1028 #ifndef TARGET_I386
1029 qmp_unregister_command("rtc-reset-reinjection");
1030 #endif
1031 #ifndef TARGET_S390X
1032 qmp_unregister_command("dump-skeys");
1033 #endif
1034 #ifndef TARGET_ARM
1035 qmp_unregister_command("query-gic-capabilities");
1036 #endif
1037 }
1038
1039 static void qmp_init_marshal(void)
1040 {
1041 qmp_register_command("query-qmp-schema", qmp_query_qmp_schema,
1042 QCO_NO_OPTIONS);
1043 qmp_register_command("device_add", qmp_device_add,
1044 QCO_NO_OPTIONS);
1045 qmp_register_command("netdev_add", qmp_netdev_add,
1046 QCO_NO_OPTIONS);
1047
1048 /* call it after the rest of qapi_init() */
1049 register_module_init(qmp_unregister_commands_hack, MODULE_INIT_QAPI);
1050 }
1051
1052 qapi_init(qmp_init_marshal);
1053
1054 /* set the current CPU defined by the user */
1055 int monitor_set_cpu(int cpu_index)
1056 {
1057 CPUState *cpu;
1058
1059 cpu = qemu_get_cpu(cpu_index);
1060 if (cpu == NULL) {
1061 return -1;
1062 }
1063 cur_mon->mon_cpu = cpu;
1064 return 0;
1065 }
1066
1067 CPUState *mon_get_cpu(void)
1068 {
1069 if (!cur_mon->mon_cpu) {
1070 monitor_set_cpu(0);
1071 }
1072 cpu_synchronize_state(cur_mon->mon_cpu);
1073 return cur_mon->mon_cpu;
1074 }
1075
1076 CPUArchState *mon_get_cpu_env(void)
1077 {
1078 return mon_get_cpu()->env_ptr;
1079 }
1080
1081 int monitor_get_cpu_index(void)
1082 {
1083 return mon_get_cpu()->cpu_index;
1084 }
1085
1086 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1087 {
1088 cpu_dump_state(mon_get_cpu(), (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1089 }
1090
1091 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1092 {
1093 dump_exec_info((FILE *)mon, monitor_fprintf);
1094 dump_drift_info((FILE *)mon, monitor_fprintf);
1095 }
1096
1097 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1098 {
1099 dump_opcount_info((FILE *)mon, monitor_fprintf);
1100 }
1101
1102 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1103 {
1104 int i;
1105 const char *str;
1106
1107 if (!mon->rs)
1108 return;
1109 i = 0;
1110 for(;;) {
1111 str = readline_get_history(mon->rs, i);
1112 if (!str)
1113 break;
1114 monitor_printf(mon, "%d: '%s'\n", i, str);
1115 i++;
1116 }
1117 }
1118
1119 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1120 {
1121 cpu_dump_statistics(mon_get_cpu(), (FILE *)mon, &monitor_fprintf, 0);
1122 }
1123
1124 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1125 {
1126 const char *name = qdict_get_try_str(qdict, "name");
1127 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1128 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1129 TraceEventInfoList *events;
1130 TraceEventInfoList *elem;
1131 Error *local_err = NULL;
1132
1133 if (name == NULL) {
1134 name = "*";
1135 }
1136 if (vcpu < 0) {
1137 monitor_printf(mon, "argument vcpu must be positive");
1138 return;
1139 }
1140
1141 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1142 if (local_err) {
1143 error_report_err(local_err);
1144 return;
1145 }
1146
1147 for (elem = events; elem != NULL; elem = elem->next) {
1148 monitor_printf(mon, "%s : state %u\n",
1149 elem->value->name,
1150 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1151 }
1152 qapi_free_TraceEventInfoList(events);
1153 }
1154
1155 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1156 bool has_port, int64_t port,
1157 bool has_tls_port, int64_t tls_port,
1158 bool has_cert_subject, const char *cert_subject,
1159 Error **errp)
1160 {
1161 if (strcmp(protocol, "spice") == 0) {
1162 if (!qemu_using_spice(errp)) {
1163 return;
1164 }
1165
1166 if (!has_port && !has_tls_port) {
1167 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1168 return;
1169 }
1170
1171 if (qemu_spice_migrate_info(hostname,
1172 has_port ? port : -1,
1173 has_tls_port ? tls_port : -1,
1174 cert_subject)) {
1175 error_setg(errp, QERR_UNDEFINED_ERROR);
1176 return;
1177 }
1178 return;
1179 }
1180
1181 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1182 }
1183
1184 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1185 {
1186 Error *err = NULL;
1187
1188 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1189 if (err) {
1190 error_report_err(err);
1191 }
1192 }
1193
1194 static void hmp_log(Monitor *mon, const QDict *qdict)
1195 {
1196 int mask;
1197 const char *items = qdict_get_str(qdict, "items");
1198
1199 if (!strcmp(items, "none")) {
1200 mask = 0;
1201 } else {
1202 mask = qemu_str_to_log_mask(items);
1203 if (!mask) {
1204 help_cmd(mon, "log");
1205 return;
1206 }
1207 }
1208 qemu_set_log(mask);
1209 }
1210
1211 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1212 {
1213 const char *option = qdict_get_try_str(qdict, "option");
1214 if (!option || !strcmp(option, "on")) {
1215 singlestep = 1;
1216 } else if (!strcmp(option, "off")) {
1217 singlestep = 0;
1218 } else {
1219 monitor_printf(mon, "unexpected option %s\n", option);
1220 }
1221 }
1222
1223 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1224 {
1225 const char *device = qdict_get_try_str(qdict, "device");
1226 if (!device)
1227 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1228 if (gdbserver_start(device) < 0) {
1229 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1230 device);
1231 } else if (strcmp(device, "none") == 0) {
1232 monitor_printf(mon, "Disabled gdbserver\n");
1233 } else {
1234 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1235 device);
1236 }
1237 }
1238
1239 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1240 {
1241 const char *action = qdict_get_str(qdict, "action");
1242 if (select_watchdog_action(action) == -1) {
1243 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1244 }
1245 }
1246
1247 static void monitor_printc(Monitor *mon, int c)
1248 {
1249 monitor_printf(mon, "'");
1250 switch(c) {
1251 case '\'':
1252 monitor_printf(mon, "\\'");
1253 break;
1254 case '\\':
1255 monitor_printf(mon, "\\\\");
1256 break;
1257 case '\n':
1258 monitor_printf(mon, "\\n");
1259 break;
1260 case '\r':
1261 monitor_printf(mon, "\\r");
1262 break;
1263 default:
1264 if (c >= 32 && c <= 126) {
1265 monitor_printf(mon, "%c", c);
1266 } else {
1267 monitor_printf(mon, "\\x%02x", c);
1268 }
1269 break;
1270 }
1271 monitor_printf(mon, "'");
1272 }
1273
1274 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1275 hwaddr addr, int is_physical)
1276 {
1277 int l, line_size, i, max_digits, len;
1278 uint8_t buf[16];
1279 uint64_t v;
1280
1281 if (format == 'i') {
1282 int flags = 0;
1283 #ifdef TARGET_I386
1284 CPUArchState *env = mon_get_cpu_env();
1285 if (wsize == 2) {
1286 flags = 1;
1287 } else if (wsize == 4) {
1288 flags = 0;
1289 } else {
1290 /* as default we use the current CS size */
1291 flags = 0;
1292 if (env) {
1293 #ifdef TARGET_X86_64
1294 if ((env->efer & MSR_EFER_LMA) &&
1295 (env->segs[R_CS].flags & DESC_L_MASK))
1296 flags = 2;
1297 else
1298 #endif
1299 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1300 flags = 1;
1301 }
1302 }
1303 #endif
1304 #ifdef TARGET_PPC
1305 CPUArchState *env = mon_get_cpu_env();
1306 flags = msr_le << 16;
1307 flags |= env->bfd_mach;
1308 #endif
1309 monitor_disas(mon, mon_get_cpu(), addr, count, is_physical, flags);
1310 return;
1311 }
1312
1313 len = wsize * count;
1314 if (wsize == 1)
1315 line_size = 8;
1316 else
1317 line_size = 16;
1318 max_digits = 0;
1319
1320 switch(format) {
1321 case 'o':
1322 max_digits = (wsize * 8 + 2) / 3;
1323 break;
1324 default:
1325 case 'x':
1326 max_digits = (wsize * 8) / 4;
1327 break;
1328 case 'u':
1329 case 'd':
1330 max_digits = (wsize * 8 * 10 + 32) / 33;
1331 break;
1332 case 'c':
1333 wsize = 1;
1334 break;
1335 }
1336
1337 while (len > 0) {
1338 if (is_physical)
1339 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1340 else
1341 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1342 l = len;
1343 if (l > line_size)
1344 l = line_size;
1345 if (is_physical) {
1346 cpu_physical_memory_read(addr, buf, l);
1347 } else {
1348 if (cpu_memory_rw_debug(mon_get_cpu(), addr, buf, l, 0) < 0) {
1349 monitor_printf(mon, " Cannot access memory\n");
1350 break;
1351 }
1352 }
1353 i = 0;
1354 while (i < l) {
1355 switch(wsize) {
1356 default:
1357 case 1:
1358 v = ldub_p(buf + i);
1359 break;
1360 case 2:
1361 v = lduw_p(buf + i);
1362 break;
1363 case 4:
1364 v = (uint32_t)ldl_p(buf + i);
1365 break;
1366 case 8:
1367 v = ldq_p(buf + i);
1368 break;
1369 }
1370 monitor_printf(mon, " ");
1371 switch(format) {
1372 case 'o':
1373 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1374 break;
1375 case 'x':
1376 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1377 break;
1378 case 'u':
1379 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1380 break;
1381 case 'd':
1382 monitor_printf(mon, "%*" PRId64, max_digits, v);
1383 break;
1384 case 'c':
1385 monitor_printc(mon, v);
1386 break;
1387 }
1388 i += wsize;
1389 }
1390 monitor_printf(mon, "\n");
1391 addr += l;
1392 len -= l;
1393 }
1394 }
1395
1396 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1397 {
1398 int count = qdict_get_int(qdict, "count");
1399 int format = qdict_get_int(qdict, "format");
1400 int size = qdict_get_int(qdict, "size");
1401 target_long addr = qdict_get_int(qdict, "addr");
1402
1403 memory_dump(mon, count, format, size, addr, 0);
1404 }
1405
1406 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1407 {
1408 int count = qdict_get_int(qdict, "count");
1409 int format = qdict_get_int(qdict, "format");
1410 int size = qdict_get_int(qdict, "size");
1411 hwaddr addr = qdict_get_int(qdict, "addr");
1412
1413 memory_dump(mon, count, format, size, addr, 1);
1414 }
1415
1416 static void do_print(Monitor *mon, const QDict *qdict)
1417 {
1418 int format = qdict_get_int(qdict, "format");
1419 hwaddr val = qdict_get_int(qdict, "val");
1420
1421 switch(format) {
1422 case 'o':
1423 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1424 break;
1425 case 'x':
1426 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1427 break;
1428 case 'u':
1429 monitor_printf(mon, "%" HWADDR_PRIu, val);
1430 break;
1431 default:
1432 case 'd':
1433 monitor_printf(mon, "%" HWADDR_PRId, val);
1434 break;
1435 case 'c':
1436 monitor_printc(mon, val);
1437 break;
1438 }
1439 monitor_printf(mon, "\n");
1440 }
1441
1442 static void hmp_sum(Monitor *mon, const QDict *qdict)
1443 {
1444 uint32_t addr;
1445 uint16_t sum;
1446 uint32_t start = qdict_get_int(qdict, "start");
1447 uint32_t size = qdict_get_int(qdict, "size");
1448
1449 sum = 0;
1450 for(addr = start; addr < (start + size); addr++) {
1451 uint8_t val = address_space_ldub(&address_space_memory, addr,
1452 MEMTXATTRS_UNSPECIFIED, NULL);
1453 /* BSD sum algorithm ('sum' Unix command) */
1454 sum = (sum >> 1) | (sum << 15);
1455 sum += val;
1456 }
1457 monitor_printf(mon, "%05d\n", sum);
1458 }
1459
1460 static int mouse_button_state;
1461
1462 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1463 {
1464 int dx, dy, dz, button;
1465 const char *dx_str = qdict_get_str(qdict, "dx_str");
1466 const char *dy_str = qdict_get_str(qdict, "dy_str");
1467 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1468
1469 dx = strtol(dx_str, NULL, 0);
1470 dy = strtol(dy_str, NULL, 0);
1471 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1472 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1473
1474 if (dz_str) {
1475 dz = strtol(dz_str, NULL, 0);
1476 if (dz != 0) {
1477 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1478 qemu_input_queue_btn(NULL, button, true);
1479 qemu_input_event_sync();
1480 qemu_input_queue_btn(NULL, button, false);
1481 }
1482 }
1483 qemu_input_event_sync();
1484 }
1485
1486 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1487 {
1488 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1489 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1490 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1491 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1492 };
1493 int button_state = qdict_get_int(qdict, "button_state");
1494
1495 if (mouse_button_state == button_state) {
1496 return;
1497 }
1498 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1499 qemu_input_event_sync();
1500 mouse_button_state = button_state;
1501 }
1502
1503 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1504 {
1505 int size = qdict_get_int(qdict, "size");
1506 int addr = qdict_get_int(qdict, "addr");
1507 int has_index = qdict_haskey(qdict, "index");
1508 uint32_t val;
1509 int suffix;
1510
1511 if (has_index) {
1512 int index = qdict_get_int(qdict, "index");
1513 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1514 addr++;
1515 }
1516 addr &= 0xffff;
1517
1518 switch(size) {
1519 default:
1520 case 1:
1521 val = cpu_inb(addr);
1522 suffix = 'b';
1523 break;
1524 case 2:
1525 val = cpu_inw(addr);
1526 suffix = 'w';
1527 break;
1528 case 4:
1529 val = cpu_inl(addr);
1530 suffix = 'l';
1531 break;
1532 }
1533 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1534 suffix, addr, size * 2, val);
1535 }
1536
1537 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1538 {
1539 int size = qdict_get_int(qdict, "size");
1540 int addr = qdict_get_int(qdict, "addr");
1541 int val = qdict_get_int(qdict, "val");
1542
1543 addr &= IOPORTS_MASK;
1544
1545 switch (size) {
1546 default:
1547 case 1:
1548 cpu_outb(addr, val);
1549 break;
1550 case 2:
1551 cpu_outw(addr, val);
1552 break;
1553 case 4:
1554 cpu_outl(addr, val);
1555 break;
1556 }
1557 }
1558
1559 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1560 {
1561 Error *local_err = NULL;
1562 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1563
1564 qemu_boot_set(bootdevice, &local_err);
1565 if (local_err) {
1566 error_report_err(local_err);
1567 } else {
1568 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1569 }
1570 }
1571
1572 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1573 {
1574 mtree_info((fprintf_function)monitor_printf, mon);
1575 }
1576
1577 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1578 {
1579 int i;
1580 CPUState *cpu;
1581 uint64_t *node_mem;
1582
1583 node_mem = g_new0(uint64_t, nb_numa_nodes);
1584 query_numa_node_mem(node_mem);
1585 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1586 for (i = 0; i < nb_numa_nodes; i++) {
1587 monitor_printf(mon, "node %d cpus:", i);
1588 CPU_FOREACH(cpu) {
1589 if (cpu->numa_node == i) {
1590 monitor_printf(mon, " %d", cpu->cpu_index);
1591 }
1592 }
1593 monitor_printf(mon, "\n");
1594 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1595 node_mem[i] >> 20);
1596 }
1597 g_free(node_mem);
1598 }
1599
1600 #ifdef CONFIG_PROFILER
1601
1602 int64_t tcg_time;
1603 int64_t dev_time;
1604
1605 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1606 {
1607 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1608 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1609 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1610 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1611 tcg_time = 0;
1612 dev_time = 0;
1613 }
1614 #else
1615 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1616 {
1617 monitor_printf(mon, "Internal profiler not compiled\n");
1618 }
1619 #endif
1620
1621 /* Capture support */
1622 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1623
1624 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1625 {
1626 int i;
1627 CaptureState *s;
1628
1629 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1630 monitor_printf(mon, "[%d]: ", i);
1631 s->ops.info (s->opaque);
1632 }
1633 }
1634
1635 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1636 {
1637 int i;
1638 int n = qdict_get_int(qdict, "n");
1639 CaptureState *s;
1640
1641 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1642 if (i == n) {
1643 s->ops.destroy (s->opaque);
1644 QLIST_REMOVE (s, entries);
1645 g_free (s);
1646 return;
1647 }
1648 }
1649 }
1650
1651 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1652 {
1653 const char *path = qdict_get_str(qdict, "path");
1654 int has_freq = qdict_haskey(qdict, "freq");
1655 int freq = qdict_get_try_int(qdict, "freq", -1);
1656 int has_bits = qdict_haskey(qdict, "bits");
1657 int bits = qdict_get_try_int(qdict, "bits", -1);
1658 int has_channels = qdict_haskey(qdict, "nchannels");
1659 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1660 CaptureState *s;
1661
1662 s = g_malloc0 (sizeof (*s));
1663
1664 freq = has_freq ? freq : 44100;
1665 bits = has_bits ? bits : 16;
1666 nchannels = has_channels ? nchannels : 2;
1667
1668 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1669 monitor_printf(mon, "Failed to add wave capture\n");
1670 g_free (s);
1671 return;
1672 }
1673 QLIST_INSERT_HEAD (&capture_head, s, entries);
1674 }
1675
1676 static qemu_acl *find_acl(Monitor *mon, const char *name)
1677 {
1678 qemu_acl *acl = qemu_acl_find(name);
1679
1680 if (!acl) {
1681 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1682 }
1683 return acl;
1684 }
1685
1686 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1687 {
1688 const char *aclname = qdict_get_str(qdict, "aclname");
1689 qemu_acl *acl = find_acl(mon, aclname);
1690 qemu_acl_entry *entry;
1691 int i = 0;
1692
1693 if (acl) {
1694 monitor_printf(mon, "policy: %s\n",
1695 acl->defaultDeny ? "deny" : "allow");
1696 QTAILQ_FOREACH(entry, &acl->entries, next) {
1697 i++;
1698 monitor_printf(mon, "%d: %s %s\n", i,
1699 entry->deny ? "deny" : "allow", entry->match);
1700 }
1701 }
1702 }
1703
1704 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1705 {
1706 const char *aclname = qdict_get_str(qdict, "aclname");
1707 qemu_acl *acl = find_acl(mon, aclname);
1708
1709 if (acl) {
1710 qemu_acl_reset(acl);
1711 monitor_printf(mon, "acl: removed all rules\n");
1712 }
1713 }
1714
1715 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1716 {
1717 const char *aclname = qdict_get_str(qdict, "aclname");
1718 const char *policy = qdict_get_str(qdict, "policy");
1719 qemu_acl *acl = find_acl(mon, aclname);
1720
1721 if (acl) {
1722 if (strcmp(policy, "allow") == 0) {
1723 acl->defaultDeny = 0;
1724 monitor_printf(mon, "acl: policy set to 'allow'\n");
1725 } else if (strcmp(policy, "deny") == 0) {
1726 acl->defaultDeny = 1;
1727 monitor_printf(mon, "acl: policy set to 'deny'\n");
1728 } else {
1729 monitor_printf(mon, "acl: unknown policy '%s', "
1730 "expected 'deny' or 'allow'\n", policy);
1731 }
1732 }
1733 }
1734
1735 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1736 {
1737 const char *aclname = qdict_get_str(qdict, "aclname");
1738 const char *match = qdict_get_str(qdict, "match");
1739 const char *policy = qdict_get_str(qdict, "policy");
1740 int has_index = qdict_haskey(qdict, "index");
1741 int index = qdict_get_try_int(qdict, "index", -1);
1742 qemu_acl *acl = find_acl(mon, aclname);
1743 int deny, ret;
1744
1745 if (acl) {
1746 if (strcmp(policy, "allow") == 0) {
1747 deny = 0;
1748 } else if (strcmp(policy, "deny") == 0) {
1749 deny = 1;
1750 } else {
1751 monitor_printf(mon, "acl: unknown policy '%s', "
1752 "expected 'deny' or 'allow'\n", policy);
1753 return;
1754 }
1755 if (has_index)
1756 ret = qemu_acl_insert(acl, deny, match, index);
1757 else
1758 ret = qemu_acl_append(acl, deny, match);
1759 if (ret < 0)
1760 monitor_printf(mon, "acl: unable to add acl entry\n");
1761 else
1762 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1763 }
1764 }
1765
1766 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1767 {
1768 const char *aclname = qdict_get_str(qdict, "aclname");
1769 const char *match = qdict_get_str(qdict, "match");
1770 qemu_acl *acl = find_acl(mon, aclname);
1771 int ret;
1772
1773 if (acl) {
1774 ret = qemu_acl_remove(acl, match);
1775 if (ret < 0)
1776 monitor_printf(mon, "acl: no matching acl entry\n");
1777 else
1778 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1779 }
1780 }
1781
1782 void qmp_getfd(const char *fdname, Error **errp)
1783 {
1784 mon_fd_t *monfd;
1785 int fd;
1786
1787 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
1788 if (fd == -1) {
1789 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1790 return;
1791 }
1792
1793 if (qemu_isdigit(fdname[0])) {
1794 close(fd);
1795 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1796 "a name not starting with a digit");
1797 return;
1798 }
1799
1800 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1801 if (strcmp(monfd->name, fdname) != 0) {
1802 continue;
1803 }
1804
1805 close(monfd->fd);
1806 monfd->fd = fd;
1807 return;
1808 }
1809
1810 monfd = g_malloc0(sizeof(mon_fd_t));
1811 monfd->name = g_strdup(fdname);
1812 monfd->fd = fd;
1813
1814 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1815 }
1816
1817 void qmp_closefd(const char *fdname, Error **errp)
1818 {
1819 mon_fd_t *monfd;
1820
1821 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1822 if (strcmp(monfd->name, fdname) != 0) {
1823 continue;
1824 }
1825
1826 QLIST_REMOVE(monfd, next);
1827 close(monfd->fd);
1828 g_free(monfd->name);
1829 g_free(monfd);
1830 return;
1831 }
1832
1833 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1834 }
1835
1836 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1837 {
1838 int saved_vm_running = runstate_is_running();
1839 const char *name = qdict_get_str(qdict, "name");
1840
1841 vm_stop(RUN_STATE_RESTORE_VM);
1842
1843 if (load_vmstate(name) == 0 && saved_vm_running) {
1844 vm_start();
1845 }
1846 }
1847
1848 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1849 {
1850 mon_fd_t *monfd;
1851
1852 QLIST_FOREACH(monfd, &mon->fds, next) {
1853 int fd;
1854
1855 if (strcmp(monfd->name, fdname) != 0) {
1856 continue;
1857 }
1858
1859 fd = monfd->fd;
1860
1861 /* caller takes ownership of fd */
1862 QLIST_REMOVE(monfd, next);
1863 g_free(monfd->name);
1864 g_free(monfd);
1865
1866 return fd;
1867 }
1868
1869 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1870 return -1;
1871 }
1872
1873 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1874 {
1875 MonFdsetFd *mon_fdset_fd;
1876 MonFdsetFd *mon_fdset_fd_next;
1877
1878 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1879 if ((mon_fdset_fd->removed ||
1880 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1881 runstate_is_running()) {
1882 close(mon_fdset_fd->fd);
1883 g_free(mon_fdset_fd->opaque);
1884 QLIST_REMOVE(mon_fdset_fd, next);
1885 g_free(mon_fdset_fd);
1886 }
1887 }
1888
1889 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
1890 QLIST_REMOVE(mon_fdset, next);
1891 g_free(mon_fdset);
1892 }
1893 }
1894
1895 static void monitor_fdsets_cleanup(void)
1896 {
1897 MonFdset *mon_fdset;
1898 MonFdset *mon_fdset_next;
1899
1900 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
1901 monitor_fdset_cleanup(mon_fdset);
1902 }
1903 }
1904
1905 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
1906 const char *opaque, Error **errp)
1907 {
1908 int fd;
1909 Monitor *mon = cur_mon;
1910 AddfdInfo *fdinfo;
1911
1912 fd = qemu_chr_fe_get_msgfd(mon->chr);
1913 if (fd == -1) {
1914 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1915 goto error;
1916 }
1917
1918 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
1919 has_opaque, opaque, errp);
1920 if (fdinfo) {
1921 return fdinfo;
1922 }
1923
1924 error:
1925 if (fd != -1) {
1926 close(fd);
1927 }
1928 return NULL;
1929 }
1930
1931 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
1932 {
1933 MonFdset *mon_fdset;
1934 MonFdsetFd *mon_fdset_fd;
1935 char fd_str[60];
1936
1937 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1938 if (mon_fdset->id != fdset_id) {
1939 continue;
1940 }
1941 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1942 if (has_fd) {
1943 if (mon_fdset_fd->fd != fd) {
1944 continue;
1945 }
1946 mon_fdset_fd->removed = true;
1947 break;
1948 } else {
1949 mon_fdset_fd->removed = true;
1950 }
1951 }
1952 if (has_fd && !mon_fdset_fd) {
1953 goto error;
1954 }
1955 monitor_fdset_cleanup(mon_fdset);
1956 return;
1957 }
1958
1959 error:
1960 if (has_fd) {
1961 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
1962 fdset_id, fd);
1963 } else {
1964 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
1965 }
1966 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
1967 }
1968
1969 FdsetInfoList *qmp_query_fdsets(Error **errp)
1970 {
1971 MonFdset *mon_fdset;
1972 MonFdsetFd *mon_fdset_fd;
1973 FdsetInfoList *fdset_list = NULL;
1974
1975 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1976 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
1977 FdsetFdInfoList *fdsetfd_list = NULL;
1978
1979 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
1980 fdset_info->value->fdset_id = mon_fdset->id;
1981
1982 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1983 FdsetFdInfoList *fdsetfd_info;
1984
1985 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
1986 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
1987 fdsetfd_info->value->fd = mon_fdset_fd->fd;
1988 if (mon_fdset_fd->opaque) {
1989 fdsetfd_info->value->has_opaque = true;
1990 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
1991 } else {
1992 fdsetfd_info->value->has_opaque = false;
1993 }
1994
1995 fdsetfd_info->next = fdsetfd_list;
1996 fdsetfd_list = fdsetfd_info;
1997 }
1998
1999 fdset_info->value->fds = fdsetfd_list;
2000
2001 fdset_info->next = fdset_list;
2002 fdset_list = fdset_info;
2003 }
2004
2005 return fdset_list;
2006 }
2007
2008 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2009 bool has_opaque, const char *opaque,
2010 Error **errp)
2011 {
2012 MonFdset *mon_fdset = NULL;
2013 MonFdsetFd *mon_fdset_fd;
2014 AddfdInfo *fdinfo;
2015
2016 if (has_fdset_id) {
2017 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2018 /* Break if match found or match impossible due to ordering by ID */
2019 if (fdset_id <= mon_fdset->id) {
2020 if (fdset_id < mon_fdset->id) {
2021 mon_fdset = NULL;
2022 }
2023 break;
2024 }
2025 }
2026 }
2027
2028 if (mon_fdset == NULL) {
2029 int64_t fdset_id_prev = -1;
2030 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2031
2032 if (has_fdset_id) {
2033 if (fdset_id < 0) {
2034 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2035 "a non-negative value");
2036 return NULL;
2037 }
2038 /* Use specified fdset ID */
2039 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2040 mon_fdset_cur = mon_fdset;
2041 if (fdset_id < mon_fdset_cur->id) {
2042 break;
2043 }
2044 }
2045 } else {
2046 /* Use first available fdset ID */
2047 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2048 mon_fdset_cur = mon_fdset;
2049 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2050 fdset_id_prev = mon_fdset_cur->id;
2051 continue;
2052 }
2053 break;
2054 }
2055 }
2056
2057 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2058 if (has_fdset_id) {
2059 mon_fdset->id = fdset_id;
2060 } else {
2061 mon_fdset->id = fdset_id_prev + 1;
2062 }
2063
2064 /* The fdset list is ordered by fdset ID */
2065 if (!mon_fdset_cur) {
2066 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2067 } else if (mon_fdset->id < mon_fdset_cur->id) {
2068 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2069 } else {
2070 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2071 }
2072 }
2073
2074 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2075 mon_fdset_fd->fd = fd;
2076 mon_fdset_fd->removed = false;
2077 if (has_opaque) {
2078 mon_fdset_fd->opaque = g_strdup(opaque);
2079 }
2080 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2081
2082 fdinfo = g_malloc0(sizeof(*fdinfo));
2083 fdinfo->fdset_id = mon_fdset->id;
2084 fdinfo->fd = mon_fdset_fd->fd;
2085
2086 return fdinfo;
2087 }
2088
2089 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2090 {
2091 #ifndef _WIN32
2092 MonFdset *mon_fdset;
2093 MonFdsetFd *mon_fdset_fd;
2094 int mon_fd_flags;
2095
2096 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2097 if (mon_fdset->id != fdset_id) {
2098 continue;
2099 }
2100 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2101 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2102 if (mon_fd_flags == -1) {
2103 return -1;
2104 }
2105
2106 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2107 return mon_fdset_fd->fd;
2108 }
2109 }
2110 errno = EACCES;
2111 return -1;
2112 }
2113 #endif
2114
2115 errno = ENOENT;
2116 return -1;
2117 }
2118
2119 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2120 {
2121 MonFdset *mon_fdset;
2122 MonFdsetFd *mon_fdset_fd_dup;
2123
2124 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2125 if (mon_fdset->id != fdset_id) {
2126 continue;
2127 }
2128 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2129 if (mon_fdset_fd_dup->fd == dup_fd) {
2130 return -1;
2131 }
2132 }
2133 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2134 mon_fdset_fd_dup->fd = dup_fd;
2135 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2136 return 0;
2137 }
2138 return -1;
2139 }
2140
2141 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2142 {
2143 MonFdset *mon_fdset;
2144 MonFdsetFd *mon_fdset_fd_dup;
2145
2146 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2147 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2148 if (mon_fdset_fd_dup->fd == dup_fd) {
2149 if (remove) {
2150 QLIST_REMOVE(mon_fdset_fd_dup, next);
2151 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2152 monitor_fdset_cleanup(mon_fdset);
2153 }
2154 return -1;
2155 } else {
2156 return mon_fdset->id;
2157 }
2158 }
2159 }
2160 }
2161 return -1;
2162 }
2163
2164 int monitor_fdset_dup_fd_find(int dup_fd)
2165 {
2166 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2167 }
2168
2169 void monitor_fdset_dup_fd_remove(int dup_fd)
2170 {
2171 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2172 }
2173
2174 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2175 {
2176 int fd;
2177 Error *local_err = NULL;
2178
2179 if (!qemu_isdigit(fdname[0]) && mon) {
2180 fd = monitor_get_fd(mon, fdname, &local_err);
2181 } else {
2182 fd = qemu_parse_fd(fdname);
2183 if (fd == -1) {
2184 error_setg(&local_err, "Invalid file descriptor number '%s'",
2185 fdname);
2186 }
2187 }
2188 if (local_err) {
2189 error_propagate(errp, local_err);
2190 assert(fd == -1);
2191 } else {
2192 assert(fd != -1);
2193 }
2194
2195 return fd;
2196 }
2197
2198 /* Please update hmp-commands.hx when adding or changing commands */
2199 static mon_cmd_t info_cmds[] = {
2200 #include "hmp-commands-info.h"
2201 { NULL, NULL, },
2202 };
2203
2204 /* mon_cmds and info_cmds would be sorted at runtime */
2205 static mon_cmd_t mon_cmds[] = {
2206 #include "hmp-commands.h"
2207 { NULL, NULL, },
2208 };
2209
2210 static const mon_cmd_t qmp_cmds[] = {
2211 #include "qmp-commands-old.h"
2212 { /* NULL */ },
2213 };
2214
2215 /*******************************************************************/
2216
2217 static const char *pch;
2218 static sigjmp_buf expr_env;
2219
2220
2221 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2222 expr_error(Monitor *mon, const char *fmt, ...)
2223 {
2224 va_list ap;
2225 va_start(ap, fmt);
2226 monitor_vprintf(mon, fmt, ap);
2227 monitor_printf(mon, "\n");
2228 va_end(ap);
2229 siglongjmp(expr_env, 1);
2230 }
2231
2232 /* return 0 if OK, -1 if not found */
2233 static int get_monitor_def(target_long *pval, const char *name)
2234 {
2235 const MonitorDef *md = target_monitor_defs();
2236 void *ptr;
2237 uint64_t tmp = 0;
2238 int ret;
2239
2240 if (md == NULL) {
2241 return -1;
2242 }
2243
2244 for(; md->name != NULL; md++) {
2245 if (compare_cmd(name, md->name)) {
2246 if (md->get_value) {
2247 *pval = md->get_value(md, md->offset);
2248 } else {
2249 CPUArchState *env = mon_get_cpu_env();
2250 ptr = (uint8_t *)env + md->offset;
2251 switch(md->type) {
2252 case MD_I32:
2253 *pval = *(int32_t *)ptr;
2254 break;
2255 case MD_TLONG:
2256 *pval = *(target_long *)ptr;
2257 break;
2258 default:
2259 *pval = 0;
2260 break;
2261 }
2262 }
2263 return 0;
2264 }
2265 }
2266
2267 ret = target_get_monitor_def(mon_get_cpu(), name, &tmp);
2268 if (!ret) {
2269 *pval = (target_long) tmp;
2270 }
2271
2272 return ret;
2273 }
2274
2275 static void next(void)
2276 {
2277 if (*pch != '\0') {
2278 pch++;
2279 while (qemu_isspace(*pch))
2280 pch++;
2281 }
2282 }
2283
2284 static int64_t expr_sum(Monitor *mon);
2285
2286 static int64_t expr_unary(Monitor *mon)
2287 {
2288 int64_t n;
2289 char *p;
2290 int ret;
2291
2292 switch(*pch) {
2293 case '+':
2294 next();
2295 n = expr_unary(mon);
2296 break;
2297 case '-':
2298 next();
2299 n = -expr_unary(mon);
2300 break;
2301 case '~':
2302 next();
2303 n = ~expr_unary(mon);
2304 break;
2305 case '(':
2306 next();
2307 n = expr_sum(mon);
2308 if (*pch != ')') {
2309 expr_error(mon, "')' expected");
2310 }
2311 next();
2312 break;
2313 case '\'':
2314 pch++;
2315 if (*pch == '\0')
2316 expr_error(mon, "character constant expected");
2317 n = *pch;
2318 pch++;
2319 if (*pch != '\'')
2320 expr_error(mon, "missing terminating \' character");
2321 next();
2322 break;
2323 case '$':
2324 {
2325 char buf[128], *q;
2326 target_long reg=0;
2327
2328 pch++;
2329 q = buf;
2330 while ((*pch >= 'a' && *pch <= 'z') ||
2331 (*pch >= 'A' && *pch <= 'Z') ||
2332 (*pch >= '0' && *pch <= '9') ||
2333 *pch == '_' || *pch == '.') {
2334 if ((q - buf) < sizeof(buf) - 1)
2335 *q++ = *pch;
2336 pch++;
2337 }
2338 while (qemu_isspace(*pch))
2339 pch++;
2340 *q = 0;
2341 ret = get_monitor_def(&reg, buf);
2342 if (ret < 0)
2343 expr_error(mon, "unknown register");
2344 n = reg;
2345 }
2346 break;
2347 case '\0':
2348 expr_error(mon, "unexpected end of expression");
2349 n = 0;
2350 break;
2351 default:
2352 errno = 0;
2353 n = strtoull(pch, &p, 0);
2354 if (errno == ERANGE) {
2355 expr_error(mon, "number too large");
2356 }
2357 if (pch == p) {
2358 expr_error(mon, "invalid char '%c' in expression", *p);
2359 }
2360 pch = p;
2361 while (qemu_isspace(*pch))
2362 pch++;
2363 break;
2364 }
2365 return n;
2366 }
2367
2368
2369 static int64_t expr_prod(Monitor *mon)
2370 {
2371 int64_t val, val2;
2372 int op;
2373
2374 val = expr_unary(mon);
2375 for(;;) {
2376 op = *pch;
2377 if (op != '*' && op != '/' && op != '%')
2378 break;
2379 next();
2380 val2 = expr_unary(mon);
2381 switch(op) {
2382 default:
2383 case '*':
2384 val *= val2;
2385 break;
2386 case '/':
2387 case '%':
2388 if (val2 == 0)
2389 expr_error(mon, "division by zero");
2390 if (op == '/')
2391 val /= val2;
2392 else
2393 val %= val2;
2394 break;
2395 }
2396 }
2397 return val;
2398 }
2399
2400 static int64_t expr_logic(Monitor *mon)
2401 {
2402 int64_t val, val2;
2403 int op;
2404
2405 val = expr_prod(mon);
2406 for(;;) {
2407 op = *pch;
2408 if (op != '&' && op != '|' && op != '^')
2409 break;
2410 next();
2411 val2 = expr_prod(mon);
2412 switch(op) {
2413 default:
2414 case '&':
2415 val &= val2;
2416 break;
2417 case '|':
2418 val |= val2;
2419 break;
2420 case '^':
2421 val ^= val2;
2422 break;
2423 }
2424 }
2425 return val;
2426 }
2427
2428 static int64_t expr_sum(Monitor *mon)
2429 {
2430 int64_t val, val2;
2431 int op;
2432
2433 val = expr_logic(mon);
2434 for(;;) {
2435 op = *pch;
2436 if (op != '+' && op != '-')
2437 break;
2438 next();
2439 val2 = expr_logic(mon);
2440 if (op == '+')
2441 val += val2;
2442 else
2443 val -= val2;
2444 }
2445 return val;
2446 }
2447
2448 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2449 {
2450 pch = *pp;
2451 if (sigsetjmp(expr_env, 0)) {
2452 *pp = pch;
2453 return -1;
2454 }
2455 while (qemu_isspace(*pch))
2456 pch++;
2457 *pval = expr_sum(mon);
2458 *pp = pch;
2459 return 0;
2460 }
2461
2462 static int get_double(Monitor *mon, double *pval, const char **pp)
2463 {
2464 const char *p = *pp;
2465 char *tailp;
2466 double d;
2467
2468 d = strtod(p, &tailp);
2469 if (tailp == p) {
2470 monitor_printf(mon, "Number expected\n");
2471 return -1;
2472 }
2473 if (d != d || d - d != 0) {
2474 /* NaN or infinity */
2475 monitor_printf(mon, "Bad number\n");
2476 return -1;
2477 }
2478 *pval = d;
2479 *pp = tailp;
2480 return 0;
2481 }
2482
2483 /*
2484 * Store the command-name in cmdname, and return a pointer to
2485 * the remaining of the command string.
2486 */
2487 static const char *get_command_name(const char *cmdline,
2488 char *cmdname, size_t nlen)
2489 {
2490 size_t len;
2491 const char *p, *pstart;
2492
2493 p = cmdline;
2494 while (qemu_isspace(*p))
2495 p++;
2496 if (*p == '\0')
2497 return NULL;
2498 pstart = p;
2499 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2500 p++;
2501 len = p - pstart;
2502 if (len > nlen - 1)
2503 len = nlen - 1;
2504 memcpy(cmdname, pstart, len);
2505 cmdname[len] = '\0';
2506 return p;
2507 }
2508
2509 /**
2510 * Read key of 'type' into 'key' and return the current
2511 * 'type' pointer.
2512 */
2513 static char *key_get_info(const char *type, char **key)
2514 {
2515 size_t len;
2516 char *p, *str;
2517
2518 if (*type == ',')
2519 type++;
2520
2521 p = strchr(type, ':');
2522 if (!p) {
2523 *key = NULL;
2524 return NULL;
2525 }
2526 len = p - type;
2527
2528 str = g_malloc(len + 1);
2529 memcpy(str, type, len);
2530 str[len] = '\0';
2531
2532 *key = str;
2533 return ++p;
2534 }
2535
2536 static int default_fmt_format = 'x';
2537 static int default_fmt_size = 4;
2538
2539 static int is_valid_option(const char *c, const char *typestr)
2540 {
2541 char option[3];
2542
2543 option[0] = '-';
2544 option[1] = *c;
2545 option[2] = '\0';
2546
2547 typestr = strstr(typestr, option);
2548 return (typestr != NULL);
2549 }
2550
2551 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2552 const char *cmdname)
2553 {
2554 const mon_cmd_t *cmd;
2555
2556 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2557 if (compare_cmd(cmdname, cmd->name)) {
2558 return cmd;
2559 }
2560 }
2561
2562 return NULL;
2563 }
2564
2565 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
2566 {
2567 return search_dispatch_table(qmp_cmds, cmdname);
2568 }
2569
2570 /*
2571 * Parse command name from @cmdp according to command table @table.
2572 * If blank, return NULL.
2573 * Else, if no valid command can be found, report to @mon, and return
2574 * NULL.
2575 * Else, change @cmdp to point right behind the name, and return its
2576 * command table entry.
2577 * Do not assume the return value points into @table! It doesn't when
2578 * the command is found in a sub-command table.
2579 */
2580 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2581 const char **cmdp,
2582 mon_cmd_t *table)
2583 {
2584 const char *p;
2585 const mon_cmd_t *cmd;
2586 char cmdname[256];
2587
2588 /* extract the command name */
2589 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2590 if (!p)
2591 return NULL;
2592
2593 cmd = search_dispatch_table(table, cmdname);
2594 if (!cmd) {
2595 monitor_printf(mon, "unknown command: '%.*s'\n",
2596 (int)(p - *cmdp), *cmdp);
2597 return NULL;
2598 }
2599
2600 /* filter out following useless space */
2601 while (qemu_isspace(*p)) {
2602 p++;
2603 }
2604
2605 *cmdp = p;
2606 /* search sub command */
2607 if (cmd->sub_table != NULL && *p != '\0') {
2608 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2609 }
2610
2611 return cmd;
2612 }
2613
2614 /*
2615 * Parse arguments for @cmd.
2616 * If it can't be parsed, report to @mon, and return NULL.
2617 * Else, insert command arguments into a QDict, and return it.
2618 * Note: On success, caller has to free the QDict structure.
2619 */
2620
2621 static QDict *monitor_parse_arguments(Monitor *mon,
2622 const char **endp,
2623 const mon_cmd_t *cmd)
2624 {
2625 const char *typestr;
2626 char *key;
2627 int c;
2628 const char *p = *endp;
2629 char buf[1024];
2630 QDict *qdict = qdict_new();
2631
2632 /* parse the parameters */
2633 typestr = cmd->args_type;
2634 for(;;) {
2635 typestr = key_get_info(typestr, &key);
2636 if (!typestr)
2637 break;
2638 c = *typestr;
2639 typestr++;
2640 switch(c) {
2641 case 'F':
2642 case 'B':
2643 case 's':
2644 {
2645 int ret;
2646
2647 while (qemu_isspace(*p))
2648 p++;
2649 if (*typestr == '?') {
2650 typestr++;
2651 if (*p == '\0') {
2652 /* no optional string: NULL argument */
2653 break;
2654 }
2655 }
2656 ret = get_str(buf, sizeof(buf), &p);
2657 if (ret < 0) {
2658 switch(c) {
2659 case 'F':
2660 monitor_printf(mon, "%s: filename expected\n",
2661 cmd->name);
2662 break;
2663 case 'B':
2664 monitor_printf(mon, "%s: block device name expected\n",
2665 cmd->name);
2666 break;
2667 default:
2668 monitor_printf(mon, "%s: string expected\n", cmd->name);
2669 break;
2670 }
2671 goto fail;
2672 }
2673 qdict_put(qdict, key, qstring_from_str(buf));
2674 }
2675 break;
2676 case 'O':
2677 {
2678 QemuOptsList *opts_list;
2679 QemuOpts *opts;
2680
2681 opts_list = qemu_find_opts(key);
2682 if (!opts_list || opts_list->desc->name) {
2683 goto bad_type;
2684 }
2685 while (qemu_isspace(*p)) {
2686 p++;
2687 }
2688 if (!*p)
2689 break;
2690 if (get_str(buf, sizeof(buf), &p) < 0) {
2691 goto fail;
2692 }
2693 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2694 if (!opts) {
2695 goto fail;
2696 }
2697 qemu_opts_to_qdict(opts, qdict);
2698 qemu_opts_del(opts);
2699 }
2700 break;
2701 case '/':
2702 {
2703 int count, format, size;
2704
2705 while (qemu_isspace(*p))
2706 p++;
2707 if (*p == '/') {
2708 /* format found */
2709 p++;
2710 count = 1;
2711 if (qemu_isdigit(*p)) {
2712 count = 0;
2713 while (qemu_isdigit(*p)) {
2714 count = count * 10 + (*p - '0');
2715 p++;
2716 }
2717 }
2718 size = -1;
2719 format = -1;
2720 for(;;) {
2721 switch(*p) {
2722 case 'o':
2723 case 'd':
2724 case 'u':
2725 case 'x':
2726 case 'i':
2727 case 'c':
2728 format = *p++;
2729 break;
2730 case 'b':
2731 size = 1;
2732 p++;
2733 break;
2734 case 'h':
2735 size = 2;
2736 p++;
2737 break;
2738 case 'w':
2739 size = 4;
2740 p++;
2741 break;
2742 case 'g':
2743 case 'L':
2744 size = 8;
2745 p++;
2746 break;
2747 default:
2748 goto next;
2749 }
2750 }
2751 next:
2752 if (*p != '\0' && !qemu_isspace(*p)) {
2753 monitor_printf(mon, "invalid char in format: '%c'\n",
2754 *p);
2755 goto fail;
2756 }
2757 if (format < 0)
2758 format = default_fmt_format;
2759 if (format != 'i') {
2760 /* for 'i', not specifying a size gives -1 as size */
2761 if (size < 0)
2762 size = default_fmt_size;
2763 default_fmt_size = size;
2764 }
2765 default_fmt_format = format;
2766 } else {
2767 count = 1;
2768 format = default_fmt_format;
2769 if (format != 'i') {
2770 size = default_fmt_size;
2771 } else {
2772 size = -1;
2773 }
2774 }
2775 qdict_put(qdict, "count", qint_from_int(count));
2776 qdict_put(qdict, "format", qint_from_int(format));
2777 qdict_put(qdict, "size", qint_from_int(size));
2778 }
2779 break;
2780 case 'i':
2781 case 'l':
2782 case 'M':
2783 {
2784 int64_t val;
2785
2786 while (qemu_isspace(*p))
2787 p++;
2788 if (*typestr == '?' || *typestr == '.') {
2789 if (*typestr == '?') {
2790 if (*p == '\0') {
2791 typestr++;
2792 break;
2793 }
2794 } else {
2795 if (*p == '.') {
2796 p++;
2797 while (qemu_isspace(*p))
2798 p++;
2799 } else {
2800 typestr++;
2801 break;
2802 }
2803 }
2804 typestr++;
2805 }
2806 if (get_expr(mon, &val, &p))
2807 goto fail;
2808 /* Check if 'i' is greater than 32-bit */
2809 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2810 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2811 monitor_printf(mon, "integer is for 32-bit values\n");
2812 goto fail;
2813 } else if (c == 'M') {
2814 if (val < 0) {
2815 monitor_printf(mon, "enter a positive value\n");
2816 goto fail;
2817 }
2818 val <<= 20;
2819 }
2820 qdict_put(qdict, key, qint_from_int(val));
2821 }
2822 break;
2823 case 'o':
2824 {
2825 int64_t val;
2826 char *end;
2827
2828 while (qemu_isspace(*p)) {
2829 p++;
2830 }
2831 if (*typestr == '?') {
2832 typestr++;
2833 if (*p == '\0') {
2834 break;
2835 }
2836 }
2837 val = qemu_strtosz(p, &end);
2838 if (val < 0) {
2839 monitor_printf(mon, "invalid size\n");
2840 goto fail;
2841 }
2842 qdict_put(qdict, key, qint_from_int(val));
2843 p = end;
2844 }
2845 break;
2846 case 'T':
2847 {
2848 double val;
2849
2850 while (qemu_isspace(*p))
2851 p++;
2852 if (*typestr == '?') {
2853 typestr++;
2854 if (*p == '\0') {
2855 break;
2856 }
2857 }
2858 if (get_double(mon, &val, &p) < 0) {
2859 goto fail;
2860 }
2861 if (p[0] && p[1] == 's') {
2862 switch (*p) {
2863 case 'm':
2864 val /= 1e3; p += 2; break;
2865 case 'u':
2866 val /= 1e6; p += 2; break;
2867 case 'n':
2868 val /= 1e9; p += 2; break;
2869 }
2870 }
2871 if (*p && !qemu_isspace(*p)) {
2872 monitor_printf(mon, "Unknown unit suffix\n");
2873 goto fail;
2874 }
2875 qdict_put(qdict, key, qfloat_from_double(val));
2876 }
2877 break;
2878 case 'b':
2879 {
2880 const char *beg;
2881 bool val;
2882
2883 while (qemu_isspace(*p)) {
2884 p++;
2885 }
2886 beg = p;
2887 while (qemu_isgraph(*p)) {
2888 p++;
2889 }
2890 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2891 val = true;
2892 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
2893 val = false;
2894 } else {
2895 monitor_printf(mon, "Expected 'on' or 'off'\n");
2896 goto fail;
2897 }
2898 qdict_put(qdict, key, qbool_from_bool(val));
2899 }
2900 break;
2901 case '-':
2902 {
2903 const char *tmp = p;
2904 int skip_key = 0;
2905 /* option */
2906
2907 c = *typestr++;
2908 if (c == '\0')
2909 goto bad_type;
2910 while (qemu_isspace(*p))
2911 p++;
2912 if (*p == '-') {
2913 p++;
2914 if(c != *p) {
2915 if(!is_valid_option(p, typestr)) {
2916
2917 monitor_printf(mon, "%s: unsupported option -%c\n",
2918 cmd->name, *p);
2919 goto fail;
2920 } else {
2921 skip_key = 1;
2922 }
2923 }
2924 if(skip_key) {
2925 p = tmp;
2926 } else {
2927 /* has option */
2928 p++;
2929 qdict_put(qdict, key, qbool_from_bool(true));
2930 }
2931 }
2932 }
2933 break;
2934 case 'S':
2935 {
2936 /* package all remaining string */
2937 int len;
2938
2939 while (qemu_isspace(*p)) {
2940 p++;
2941 }
2942 if (*typestr == '?') {
2943 typestr++;
2944 if (*p == '\0') {
2945 /* no remaining string: NULL argument */
2946 break;
2947 }
2948 }
2949 len = strlen(p);
2950 if (len <= 0) {
2951 monitor_printf(mon, "%s: string expected\n",
2952 cmd->name);
2953 goto fail;
2954 }
2955 qdict_put(qdict, key, qstring_from_str(p));
2956 p += len;
2957 }
2958 break;
2959 default:
2960 bad_type:
2961 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
2962 goto fail;
2963 }
2964 g_free(key);
2965 key = NULL;
2966 }
2967 /* check that all arguments were parsed */
2968 while (qemu_isspace(*p))
2969 p++;
2970 if (*p != '\0') {
2971 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
2972 cmd->name);
2973 goto fail;
2974 }
2975
2976 return qdict;
2977
2978 fail:
2979 QDECREF(qdict);
2980 g_free(key);
2981 return NULL;
2982 }
2983
2984 static void handle_hmp_command(Monitor *mon, const char *cmdline)
2985 {
2986 QDict *qdict;
2987 const mon_cmd_t *cmd;
2988
2989 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
2990 if (!cmd) {
2991 return;
2992 }
2993
2994 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
2995 if (!qdict) {
2996 monitor_printf(mon, "Try \"help %s\" for more information\n",
2997 cmd->name);
2998 return;
2999 }
3000
3001 cmd->mhandler.cmd(mon, qdict);
3002 QDECREF(qdict);
3003 }
3004
3005 static void cmd_completion(Monitor *mon, const char *name, const char *list)
3006 {
3007 const char *p, *pstart;
3008 char cmd[128];
3009 int len;
3010
3011 p = list;
3012 for(;;) {
3013 pstart = p;
3014 p = strchr(p, '|');
3015 if (!p)
3016 p = pstart + strlen(pstart);
3017 len = p - pstart;
3018 if (len > sizeof(cmd) - 2)
3019 len = sizeof(cmd) - 2;
3020 memcpy(cmd, pstart, len);
3021 cmd[len] = '\0';
3022 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3023 readline_add_completion(mon->rs, cmd);
3024 }
3025 if (*p == '\0')
3026 break;
3027 p++;
3028 }
3029 }
3030
3031 static void file_completion(Monitor *mon, const char *input)
3032 {
3033 DIR *ffs;
3034 struct dirent *d;
3035 char path[1024];
3036 char file[1024], file_prefix[1024];
3037 int input_path_len;
3038 const char *p;
3039
3040 p = strrchr(input, '/');
3041 if (!p) {
3042 input_path_len = 0;
3043 pstrcpy(file_prefix, sizeof(file_prefix), input);
3044 pstrcpy(path, sizeof(path), ".");
3045 } else {
3046 input_path_len = p - input + 1;
3047 memcpy(path, input, input_path_len);
3048 if (input_path_len > sizeof(path) - 1)
3049 input_path_len = sizeof(path) - 1;
3050 path[input_path_len] = '\0';
3051 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3052 }
3053
3054 ffs = opendir(path);
3055 if (!ffs)
3056 return;
3057 for(;;) {
3058 struct stat sb;
3059 d = readdir(ffs);
3060 if (!d)
3061 break;
3062
3063 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3064 continue;
3065 }
3066
3067 if (strstart(d->d_name, file_prefix, NULL)) {
3068 memcpy(file, input, input_path_len);
3069 if (input_path_len < sizeof(file))
3070 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3071 d->d_name);
3072 /* stat the file to find out if it's a directory.
3073 * In that case add a slash to speed up typing long paths
3074 */
3075 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3076 pstrcat(file, sizeof(file), "/");
3077 }
3078 readline_add_completion(mon->rs, file);
3079 }
3080 }
3081 closedir(ffs);
3082 }
3083
3084 static const char *next_arg_type(const char *typestr)
3085 {
3086 const char *p = strchr(typestr, ':');
3087 return (p != NULL ? ++p : typestr);
3088 }
3089
3090 static void add_completion_option(ReadLineState *rs, const char *str,
3091 const char *option)
3092 {
3093 if (!str || !option) {
3094 return;
3095 }
3096 if (!strncmp(option, str, strlen(str))) {
3097 readline_add_completion(rs, option);
3098 }
3099 }
3100
3101 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3102 {
3103 size_t len;
3104 ChardevBackendInfoList *list, *start;
3105
3106 if (nb_args != 2) {
3107 return;
3108 }
3109 len = strlen(str);
3110 readline_set_completion_index(rs, len);
3111
3112 start = list = qmp_query_chardev_backends(NULL);
3113 while (list) {
3114 const char *chr_name = list->value->name;
3115
3116 if (!strncmp(chr_name, str, len)) {
3117 readline_add_completion(rs, chr_name);
3118 }
3119 list = list->next;
3120 }
3121 qapi_free_ChardevBackendInfoList(start);
3122 }
3123
3124 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3125 {
3126 size_t len;
3127 int i;
3128
3129 if (nb_args != 2) {
3130 return;
3131 }
3132 len = strlen(str);
3133 readline_set_completion_index(rs, len);
3134 for (i = 0; NetClientDriver_lookup[i]; i++) {
3135 add_completion_option(rs, str, NetClientDriver_lookup[i]);
3136 }
3137 }
3138
3139 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3140 {
3141 GSList *list, *elt;
3142 size_t len;
3143
3144 if (nb_args != 2) {
3145 return;
3146 }
3147
3148 len = strlen(str);
3149 readline_set_completion_index(rs, len);
3150 list = elt = object_class_get_list(TYPE_DEVICE, false);
3151 while (elt) {
3152 const char *name;
3153 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3154 TYPE_DEVICE);
3155 name = object_class_get_name(OBJECT_CLASS(dc));
3156
3157 if (!dc->cannot_instantiate_with_device_add_yet
3158 && !strncmp(name, str, len)) {
3159 readline_add_completion(rs, name);
3160 }
3161 elt = elt->next;
3162 }
3163 g_slist_free(list);
3164 }
3165
3166 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3167 {
3168 GSList *list, *elt;
3169 size_t len;
3170
3171 if (nb_args != 2) {
3172 return;
3173 }
3174
3175 len = strlen(str);
3176 readline_set_completion_index(rs, len);
3177 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3178 while (elt) {
3179 const char *name;
3180
3181 name = object_class_get_name(OBJECT_CLASS(elt->data));
3182 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3183 readline_add_completion(rs, name);
3184 }
3185 elt = elt->next;
3186 }
3187 g_slist_free(list);
3188 }
3189
3190 static void peripheral_device_del_completion(ReadLineState *rs,
3191 const char *str, size_t len)
3192 {
3193 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3194 GSList *list, *item;
3195
3196 list = qdev_build_hotpluggable_device_list(peripheral);
3197 if (!list) {
3198 return;
3199 }
3200
3201 for (item = list; item; item = g_slist_next(item)) {
3202 DeviceState *dev = item->data;
3203
3204 if (dev->id && !strncmp(str, dev->id, len)) {
3205 readline_add_completion(rs, dev->id);
3206 }
3207 }
3208
3209 g_slist_free(list);
3210 }
3211
3212 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3213 {
3214 size_t len;
3215 ChardevInfoList *list, *start;
3216
3217 if (nb_args != 2) {
3218 return;
3219 }
3220 len = strlen(str);
3221 readline_set_completion_index(rs, len);
3222
3223 start = list = qmp_query_chardev(NULL);
3224 while (list) {
3225 ChardevInfo *chr = list->value;
3226
3227 if (!strncmp(chr->label, str, len)) {
3228 readline_add_completion(rs, chr->label);
3229 }
3230 list = list->next;
3231 }
3232 qapi_free_ChardevInfoList(start);
3233 }
3234
3235 static void ringbuf_completion(ReadLineState *rs, const char *str)
3236 {
3237 size_t len;
3238 ChardevInfoList *list, *start;
3239
3240 len = strlen(str);
3241 readline_set_completion_index(rs, len);
3242
3243 start = list = qmp_query_chardev(NULL);
3244 while (list) {
3245 ChardevInfo *chr_info = list->value;
3246
3247 if (!strncmp(chr_info->label, str, len)) {
3248 CharDriverState *chr = qemu_chr_find(chr_info->label);
3249 if (chr && chr_is_ringbuf(chr)) {
3250 readline_add_completion(rs, chr_info->label);
3251 }
3252 }
3253 list = list->next;
3254 }
3255 qapi_free_ChardevInfoList(start);
3256 }
3257
3258 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3259 {
3260 if (nb_args != 2) {
3261 return;
3262 }
3263 ringbuf_completion(rs, str);
3264 }
3265
3266 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3267 {
3268 size_t len;
3269
3270 if (nb_args != 2) {
3271 return;
3272 }
3273
3274 len = strlen(str);
3275 readline_set_completion_index(rs, len);
3276 peripheral_device_del_completion(rs, str, len);
3277 }
3278
3279 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3280 {
3281 ObjectPropertyInfoList *list, *start;
3282 size_t len;
3283
3284 if (nb_args != 2) {
3285 return;
3286 }
3287 len = strlen(str);
3288 readline_set_completion_index(rs, len);
3289
3290 start = list = qmp_qom_list("/objects", NULL);
3291 while (list) {
3292 ObjectPropertyInfo *info = list->value;
3293
3294 if (!strncmp(info->type, "child<", 5)
3295 && !strncmp(info->name, str, len)) {
3296 readline_add_completion(rs, info->name);
3297 }
3298 list = list->next;
3299 }
3300 qapi_free_ObjectPropertyInfoList(start);
3301 }
3302
3303 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3304 {
3305 int i;
3306 char *sep;
3307 size_t len;
3308
3309 if (nb_args != 2) {
3310 return;
3311 }
3312 sep = strrchr(str, '-');
3313 if (sep) {
3314 str = sep + 1;
3315 }
3316 len = strlen(str);
3317 readline_set_completion_index(rs, len);
3318 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3319 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3320 readline_add_completion(rs, QKeyCode_lookup[i]);
3321 }
3322 }
3323 }
3324
3325 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3326 {
3327 size_t len;
3328
3329 len = strlen(str);
3330 readline_set_completion_index(rs, len);
3331 if (nb_args == 2) {
3332 NetClientState *ncs[MAX_QUEUE_NUM];
3333 int count, i;
3334 count = qemu_find_net_clients_except(NULL, ncs,
3335 NET_CLIENT_DRIVER_NONE,
3336 MAX_QUEUE_NUM);
3337 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3338 const char *name = ncs[i]->name;
3339 if (!strncmp(str, name, len)) {
3340 readline_add_completion(rs, name);
3341 }
3342 }
3343 } else if (nb_args == 3) {
3344 add_completion_option(rs, str, "on");
3345 add_completion_option(rs, str, "off");
3346 }
3347 }
3348
3349 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3350 {
3351 int len, count, i;
3352 NetClientState *ncs[MAX_QUEUE_NUM];
3353
3354 if (nb_args != 2) {
3355 return;
3356 }
3357
3358 len = strlen(str);
3359 readline_set_completion_index(rs, len);
3360 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3361 MAX_QUEUE_NUM);
3362 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3363 QemuOpts *opts;
3364 const char *name = ncs[i]->name;
3365 if (strncmp(str, name, len)) {
3366 continue;
3367 }
3368 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3369 if (opts) {
3370 readline_add_completion(rs, name);
3371 }
3372 }
3373 }
3374
3375 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3376 {
3377 size_t len;
3378
3379 len = strlen(str);
3380 readline_set_completion_index(rs, len);
3381 if (nb_args == 2) {
3382 TraceEventID id;
3383 for (id = 0; id < trace_event_count(); id++) {
3384 const char *event_name = trace_event_get_name(trace_event_id(id));
3385 if (!strncmp(str, event_name, len)) {
3386 readline_add_completion(rs, event_name);
3387 }
3388 }
3389 }
3390 }
3391
3392 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3393 {
3394 size_t len;
3395
3396 len = strlen(str);
3397 readline_set_completion_index(rs, len);
3398 if (nb_args == 2) {
3399 TraceEventID id;
3400 for (id = 0; id < trace_event_count(); id++) {
3401 const char *event_name = trace_event_get_name(trace_event_id(id));
3402 if (!strncmp(str, event_name, len)) {
3403 readline_add_completion(rs, event_name);
3404 }
3405 }
3406 } else if (nb_args == 3) {
3407 add_completion_option(rs, str, "on");
3408 add_completion_option(rs, str, "off");
3409 }
3410 }
3411
3412 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3413 {
3414 int i;
3415
3416 if (nb_args != 2) {
3417 return;
3418 }
3419 readline_set_completion_index(rs, strlen(str));
3420 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3421 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3422 }
3423 }
3424
3425 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3426 const char *str)
3427 {
3428 size_t len;
3429
3430 len = strlen(str);
3431 readline_set_completion_index(rs, len);
3432 if (nb_args == 2) {
3433 int i;
3434 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3435 const char *name = MigrationCapability_lookup[i];
3436 if (!strncmp(str, name, len)) {
3437 readline_add_completion(rs, name);
3438 }
3439 }
3440 } else if (nb_args == 3) {
3441 add_completion_option(rs, str, "on");
3442 add_completion_option(rs, str, "off");
3443 }
3444 }
3445
3446 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3447 const char *str)
3448 {
3449 size_t len;
3450
3451 len = strlen(str);
3452 readline_set_completion_index(rs, len);
3453 if (nb_args == 2) {
3454 int i;
3455 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3456 const char *name = MigrationParameter_lookup[i];
3457 if (!strncmp(str, name, len)) {
3458 readline_add_completion(rs, name);
3459 }
3460 }
3461 }
3462 }
3463
3464 void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3465 {
3466 int i;
3467 size_t len;
3468 if (nb_args != 2) {
3469 return;
3470 }
3471 len = strlen(str);
3472 readline_set_completion_index(rs, len);
3473 for (i = 0; host_net_devices[i]; i++) {
3474 if (!strncmp(host_net_devices[i], str, len)) {
3475 readline_add_completion(rs, host_net_devices[i]);
3476 }
3477 }
3478 }
3479
3480 void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3481 {
3482 NetClientState *ncs[MAX_QUEUE_NUM];
3483 int count, i, len;
3484
3485 len = strlen(str);
3486 readline_set_completion_index(rs, len);
3487 if (nb_args == 2) {
3488 count = qemu_find_net_clients_except(NULL, ncs,
3489 NET_CLIENT_DRIVER_NONE,
3490 MAX_QUEUE_NUM);
3491 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3492 int id;
3493 char name[16];
3494
3495 if (net_hub_id_for_client(ncs[i], &id)) {
3496 continue;
3497 }
3498 snprintf(name, sizeof(name), "%d", id);
3499 if (!strncmp(str, name, len)) {
3500 readline_add_completion(rs, name);
3501 }
3502 }
3503 return;
3504 } else if (nb_args == 3) {
3505 count = qemu_find_net_clients_except(NULL, ncs,
3506 NET_CLIENT_DRIVER_NIC,
3507 MAX_QUEUE_NUM);
3508 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3509 int id;
3510 const char *name;
3511
3512 if (ncs[i]->info->type == NET_CLIENT_DRIVER_HUBPORT ||
3513 net_hub_id_for_client(ncs[i], &id)) {
3514 continue;
3515 }
3516 name = ncs[i]->name;
3517 if (!strncmp(str, name, len)) {
3518 readline_add_completion(rs, name);
3519 }
3520 }
3521 return;
3522 }
3523 }
3524
3525 static void vm_completion(ReadLineState *rs, const char *str)
3526 {
3527 size_t len;
3528 BlockDriverState *bs;
3529 BdrvNextIterator it;
3530
3531 len = strlen(str);
3532 readline_set_completion_index(rs, len);
3533
3534 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3535 SnapshotInfoList *snapshots, *snapshot;
3536 AioContext *ctx = bdrv_get_aio_context(bs);
3537 bool ok = false;
3538
3539 aio_context_acquire(ctx);
3540 if (bdrv_can_snapshot(bs)) {
3541 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3542 }
3543 aio_context_release(ctx);
3544 if (!ok) {
3545 continue;
3546 }
3547
3548 snapshot = snapshots;
3549 while (snapshot) {
3550 char *completion = snapshot->value->name;
3551 if (!strncmp(str, completion, len)) {
3552 readline_add_completion(rs, completion);
3553 }
3554 completion = snapshot->value->id;
3555 if (!strncmp(str, completion, len)) {
3556 readline_add_completion(rs, completion);
3557 }
3558 snapshot = snapshot->next;
3559 }
3560 qapi_free_SnapshotInfoList(snapshots);
3561 }
3562
3563 }
3564
3565 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3566 {
3567 if (nb_args == 2) {
3568 vm_completion(rs, str);
3569 }
3570 }
3571
3572 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3573 {
3574 if (nb_args == 2) {
3575 vm_completion(rs, str);
3576 }
3577 }
3578
3579 static void monitor_find_completion_by_table(Monitor *mon,
3580 const mon_cmd_t *cmd_table,
3581 char **args,
3582 int nb_args)
3583 {
3584 const char *cmdname;
3585 int i;
3586 const char *ptype, *str, *name;
3587 const mon_cmd_t *cmd;
3588 BlockBackend *blk = NULL;
3589
3590 if (nb_args <= 1) {
3591 /* command completion */
3592 if (nb_args == 0)
3593 cmdname = "";
3594 else
3595 cmdname = args[0];
3596 readline_set_completion_index(mon->rs, strlen(cmdname));
3597 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3598 cmd_completion(mon, cmdname, cmd->name);
3599 }
3600 } else {
3601 /* find the command */
3602 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
3603 if (compare_cmd(args[0], cmd->name)) {
3604 break;
3605 }
3606 }
3607 if (!cmd->name) {
3608 return;
3609 }
3610
3611 if (cmd->sub_table) {
3612 /* do the job again */
3613 monitor_find_completion_by_table(mon, cmd->sub_table,
3614 &args[1], nb_args - 1);
3615 return;
3616 }
3617 if (cmd->command_completion) {
3618 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3619 return;
3620 }
3621
3622 ptype = next_arg_type(cmd->args_type);
3623 for(i = 0; i < nb_args - 2; i++) {
3624 if (*ptype != '\0') {
3625 ptype = next_arg_type(ptype);
3626 while (*ptype == '?')
3627 ptype = next_arg_type(ptype);
3628 }
3629 }
3630 str = args[nb_args - 1];
3631 while (*ptype == '-' && ptype[1] != '\0') {
3632 ptype = next_arg_type(ptype);
3633 }
3634 switch(*ptype) {
3635 case 'F':
3636 /* file completion */
3637 readline_set_completion_index(mon->rs, strlen(str));
3638 file_completion(mon, str);
3639 break;
3640 case 'B':
3641 /* block device name completion */
3642 readline_set_completion_index(mon->rs, strlen(str));
3643 while ((blk = blk_next(blk)) != NULL) {
3644 name = blk_name(blk);
3645 if (str[0] == '\0' ||
3646 !strncmp(name, str, strlen(str))) {
3647 readline_add_completion(mon->rs, name);
3648 }
3649 }
3650 break;
3651 case 's':
3652 case 'S':
3653 if (!strcmp(cmd->name, "help|?")) {
3654 monitor_find_completion_by_table(mon, cmd_table,
3655 &args[1], nb_args - 1);
3656 }
3657 break;
3658 default:
3659 break;
3660 }
3661 }
3662 }
3663
3664 static void monitor_find_completion(void *opaque,
3665 const char *cmdline)
3666 {
3667 Monitor *mon = opaque;
3668 char *args[MAX_ARGS];
3669 int nb_args, len;
3670
3671 /* 1. parse the cmdline */
3672 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3673 return;
3674 }
3675
3676 /* if the line ends with a space, it means we want to complete the
3677 next arg */
3678 len = strlen(cmdline);
3679 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3680 if (nb_args >= MAX_ARGS) {
3681 goto cleanup;
3682 }
3683 args[nb_args++] = g_strdup("");
3684 }
3685
3686 /* 2. auto complete according to args */
3687 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
3688
3689 cleanup:
3690 free_cmdline_args(args, nb_args);
3691 }
3692
3693 static int monitor_can_read(void *opaque)
3694 {
3695 Monitor *mon = opaque;
3696
3697 return (mon->suspend_cnt == 0) ? 1 : 0;
3698 }
3699
3700 static bool invalid_qmp_mode(const Monitor *mon, const char *cmd,
3701 Error **errp)
3702 {
3703 bool is_cap = g_str_equal(cmd, "qmp_capabilities");
3704
3705 if (is_cap && mon->qmp.in_command_mode) {
3706 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3707 "Capabilities negotiation is already complete, command "
3708 "'%s' ignored", cmd);
3709 return true;
3710 }
3711 if (!is_cap && !mon->qmp.in_command_mode) {
3712 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3713 "Expecting capabilities negotiation with "
3714 "'qmp_capabilities' before command '%s'", cmd);
3715 return true;
3716 }
3717 return false;
3718 }
3719
3720 /*
3721 * Argument validation rules:
3722 *
3723 * 1. The argument must exist in cmd_args qdict
3724 * 2. The argument type must be the expected one
3725 *
3726 * Special case: If the argument doesn't exist in cmd_args and
3727 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
3728 * checking is skipped for it.
3729 */
3730 static void check_client_args_type(const QDict *client_args,
3731 const QDict *cmd_args, int flags,
3732 Error **errp)
3733 {
3734 const QDictEntry *ent;
3735
3736 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
3737 QObject *obj;
3738 QString *arg_type;
3739 const QObject *client_arg = qdict_entry_value(ent);
3740 const char *client_arg_name = qdict_entry_key(ent);
3741
3742 obj = qdict_get(cmd_args, client_arg_name);
3743 if (!obj) {
3744 if (flags & QMP_ACCEPT_UNKNOWNS) {
3745 /* handler accepts unknowns */
3746 continue;
3747 }
3748 /* client arg doesn't exist */
3749 error_setg(errp, QERR_INVALID_PARAMETER, client_arg_name);
3750 return;
3751 }
3752
3753 arg_type = qobject_to_qstring(obj);
3754 assert(arg_type != NULL);
3755
3756 /* check if argument's type is correct */
3757 switch (qstring_get_str(arg_type)[0]) {
3758 case 'F':
3759 case 'B':
3760 case 's':
3761 if (qobject_type(client_arg) != QTYPE_QSTRING) {
3762 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3763 client_arg_name, "string");
3764 return;
3765 }
3766 break;
3767 case 'i':
3768 case 'l':
3769 case 'M':
3770 case 'o':
3771 if (qobject_type(client_arg) != QTYPE_QINT) {
3772 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3773 client_arg_name, "int");
3774 return;
3775 }
3776 break;
3777 case 'T':
3778 if (qobject_type(client_arg) != QTYPE_QINT &&
3779 qobject_type(client_arg) != QTYPE_QFLOAT) {
3780 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3781 client_arg_name, "number");
3782 return;
3783 }
3784 break;
3785 case 'b':
3786 case '-':
3787 if (qobject_type(client_arg) != QTYPE_QBOOL) {
3788 error_setg(errp, QERR_INVALID_PARAMETER_TYPE,
3789 client_arg_name, "bool");
3790 return;
3791 }
3792 break;
3793 case 'O':
3794 assert(flags & QMP_ACCEPT_UNKNOWNS);
3795 break;
3796 case 'q':
3797 /* Any QObject can be passed. */
3798 break;
3799 case '/':
3800 case '.':
3801 /*
3802 * These types are not supported by QMP and thus are not
3803 * handled here. Fall through.
3804 */
3805 default:
3806 abort();
3807 }
3808 }
3809 }
3810
3811 /*
3812 * - Check if the client has passed all mandatory args
3813 * - Set special flags for argument validation
3814 */
3815 static void check_mandatory_args(const QDict *cmd_args,
3816 const QDict *client_args, int *flags,
3817 Error **errp)
3818 {
3819 const QDictEntry *ent;
3820
3821 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
3822 const char *cmd_arg_name = qdict_entry_key(ent);
3823 QString *type = qobject_to_qstring(qdict_entry_value(ent));
3824 assert(type != NULL);
3825
3826 if (qstring_get_str(type)[0] == 'O') {
3827 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
3828 *flags |= QMP_ACCEPT_UNKNOWNS;
3829 } else if (qstring_get_str(type)[0] != '-' &&
3830 qstring_get_str(type)[1] != '?' &&
3831 !qdict_haskey(client_args, cmd_arg_name)) {
3832 error_setg(errp, QERR_MISSING_PARAMETER, cmd_arg_name);
3833 return;
3834 }
3835 }
3836 }
3837
3838 static QDict *qdict_from_args_type(const char *args_type)
3839 {
3840 int i;
3841 QDict *qdict;
3842 QString *key, *type, *cur_qs;
3843
3844 assert(args_type != NULL);
3845
3846 qdict = qdict_new();
3847
3848 if (args_type == NULL || args_type[0] == '\0') {
3849 /* no args, empty qdict */
3850 goto out;
3851 }
3852
3853 key = qstring_new();
3854 type = qstring_new();
3855
3856 cur_qs = key;
3857
3858 for (i = 0;; i++) {
3859 switch (args_type[i]) {
3860 case ',':
3861 case '\0':
3862 qdict_put(qdict, qstring_get_str(key), type);
3863 QDECREF(key);
3864 if (args_type[i] == '\0') {
3865 goto out;
3866 }
3867 type = qstring_new(); /* qdict has ref */
3868 cur_qs = key = qstring_new();
3869 break;
3870 case ':':
3871 cur_qs = type;
3872 break;
3873 default:
3874 qstring_append_chr(cur_qs, args_type[i]);
3875 break;
3876 }
3877 }
3878
3879 out:
3880 return qdict;
3881 }
3882
3883 /*
3884 * Client argument checking rules:
3885 *
3886 * 1. Client must provide all mandatory arguments
3887 * 2. Each argument provided by the client must be expected
3888 * 3. Each argument provided by the client must have the type expected
3889 * by the command
3890 */
3891 static void qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args,
3892 Error **errp)
3893 {
3894 Error *err = NULL;
3895 int flags;
3896 QDict *cmd_args;
3897
3898 cmd_args = qdict_from_args_type(cmd->args_type);
3899
3900 flags = 0;
3901 check_mandatory_args(cmd_args, client_args, &flags, &err);
3902 if (err) {
3903 goto out;
3904 }
3905
3906 check_client_args_type(client_args, cmd_args, flags, &err);
3907
3908 out:
3909 error_propagate(errp, err);
3910 QDECREF(cmd_args);
3911 }
3912
3913 /*
3914 * Input object checking rules
3915 *
3916 * 1. Input object must be a dict
3917 * 2. The "execute" key must exist
3918 * 3. The "execute" key must be a string
3919 * 4. If the "arguments" key exists, it must be a dict
3920 * 5. If the "id" key exists, it can be anything (ie. json-value)
3921 * 6. Any argument not listed above is considered invalid
3922 */
3923 static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
3924 {
3925 const QDictEntry *ent;
3926 int has_exec_key = 0;
3927 QDict *input_dict;
3928
3929 if (qobject_type(input_obj) != QTYPE_QDICT) {
3930 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
3931 return NULL;
3932 }
3933
3934 input_dict = qobject_to_qdict(input_obj);
3935
3936 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
3937 const char *arg_name = qdict_entry_key(ent);
3938 const QObject *arg_obj = qdict_entry_value(ent);
3939
3940 if (!strcmp(arg_name, "execute")) {
3941 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
3942 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3943 "execute", "string");
3944 return NULL;
3945 }
3946 has_exec_key = 1;
3947 } else if (!strcmp(arg_name, "arguments")) {
3948 if (qobject_type(arg_obj) != QTYPE_QDICT) {
3949 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3950 "arguments", "object");
3951 return NULL;
3952 }
3953 } else if (!strcmp(arg_name, "id")) {
3954 /* Any string is acceptable as "id", so nothing to check */
3955 } else {
3956 error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
3957 return NULL;
3958 }
3959 }
3960
3961 if (!has_exec_key) {
3962 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
3963 return NULL;
3964 }
3965
3966 return input_dict;
3967 }
3968
3969 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
3970 {
3971 Error *local_err = NULL;
3972 QObject *obj, *data;
3973 QDict *input, *args;
3974 const mon_cmd_t *cmd;
3975 QmpCommand *qcmd;
3976 const char *cmd_name;
3977 Monitor *mon = cur_mon;
3978
3979 args = input = NULL;
3980 data = NULL;
3981
3982 obj = json_parser_parse(tokens, NULL);
3983 if (!obj) {
3984 // FIXME: should be triggered in json_parser_parse()
3985 error_setg(&local_err, QERR_JSON_PARSING);
3986 goto err_out;
3987 }
3988
3989 input = qmp_check_input_obj(obj, &local_err);
3990 if (!input) {
3991 qobject_decref(obj);
3992 goto err_out;
3993 }
3994
3995 mon->qmp.id = qdict_get(input, "id");
3996 qobject_incref(mon->qmp.id);
3997
3998 cmd_name = qdict_get_str(input, "execute");
3999 trace_handle_qmp_command(mon, cmd_name);
4000 cmd = qmp_find_cmd(cmd_name);
4001 qcmd = qmp_find_command(cmd_name);
4002 if (!qcmd || !cmd) {
4003 error_set(&local_err, ERROR_CLASS_COMMAND_NOT_FOUND,
4004 "The command %s has not been found", cmd_name);
4005 goto err_out;
4006 }
4007 if (invalid_qmp_mode(mon, cmd_name, &local_err)) {
4008 goto err_out;
4009 }
4010
4011 obj = qdict_get(input, "arguments");
4012 if (!obj) {
4013 args = qdict_new();
4014 } else {
4015 args = qobject_to_qdict(obj);
4016 QINCREF(args);
4017 }
4018
4019 qmp_check_client_args(cmd, args, &local_err);
4020 if (local_err) {
4021 goto err_out;
4022 }
4023
4024 qcmd->fn(args, &data, &local_err);
4025
4026 err_out:
4027 monitor_protocol_emitter(mon, data, local_err);
4028 qobject_decref(data);
4029 error_free(local_err);
4030 QDECREF(input);
4031 QDECREF(args);
4032 }
4033
4034 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
4035 {
4036 Monitor *old_mon = cur_mon;
4037
4038 cur_mon = opaque;
4039
4040 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
4041
4042 cur_mon = old_mon;
4043 }
4044
4045 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4046 {
4047 Monitor *old_mon = cur_mon;
4048 int i;
4049
4050 cur_mon = opaque;
4051
4052 if (cur_mon->rs) {
4053 for (i = 0; i < size; i++)
4054 readline_handle_byte(cur_mon->rs, buf[i]);
4055 } else {
4056 if (size == 0 || buf[size - 1] != 0)
4057 monitor_printf(cur_mon, "corrupted command\n");
4058 else
4059 handle_hmp_command(cur_mon, (char *)buf);
4060 }
4061
4062 cur_mon = old_mon;
4063 }
4064
4065 static void monitor_command_cb(void *opaque, const char *cmdline,
4066 void *readline_opaque)
4067 {
4068 Monitor *mon = opaque;
4069
4070 monitor_suspend(mon);
4071 handle_hmp_command(mon, cmdline);
4072 monitor_resume(mon);
4073 }
4074
4075 int monitor_suspend(Monitor *mon)
4076 {
4077 if (!mon->rs)
4078 return -ENOTTY;
4079 mon->suspend_cnt++;
4080 return 0;
4081 }
4082
4083 void monitor_resume(Monitor *mon)
4084 {
4085 if (!mon->rs)
4086 return;
4087 if (--mon->suspend_cnt == 0)
4088 readline_show_prompt(mon->rs);
4089 }
4090
4091 static QObject *get_qmp_greeting(void)
4092 {
4093 QObject *ver = NULL;
4094
4095 qmp_marshal_query_version(NULL, &ver, NULL);
4096
4097 return qobject_from_jsonf("{'QMP': {'version': %p, 'capabilities': []}}",
4098 ver);
4099 }
4100
4101 static void monitor_qmp_event(void *opaque, int event)
4102 {
4103 QObject *data;
4104 Monitor *mon = opaque;
4105
4106 switch (event) {
4107 case CHR_EVENT_OPENED:
4108 mon->qmp.in_command_mode = false;
4109 data = get_qmp_greeting();
4110 monitor_json_emitter(mon, data);
4111 qobject_decref(data);
4112 mon_refcount++;
4113 break;
4114 case CHR_EVENT_CLOSED:
4115 json_message_parser_destroy(&mon->qmp.parser);
4116 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4117 mon_refcount--;
4118 monitor_fdsets_cleanup();
4119 break;
4120 }
4121 }
4122
4123 static void monitor_event(void *opaque, int event)
4124 {
4125 Monitor *mon = opaque;
4126
4127 switch (event) {
4128 case CHR_EVENT_MUX_IN:
4129 qemu_mutex_lock(&mon->out_lock);
4130 mon->mux_out = 0;
4131 qemu_mutex_unlock(&mon->out_lock);
4132 if (mon->reset_seen) {
4133 readline_restart(mon->rs);
4134 monitor_resume(mon);
4135 monitor_flush(mon);
4136 } else {
4137 mon->suspend_cnt = 0;
4138 }
4139 break;
4140
4141 case CHR_EVENT_MUX_OUT:
4142 if (mon->reset_seen) {
4143 if (mon->suspend_cnt == 0) {
4144 monitor_printf(mon, "\n");
4145 }
4146 monitor_flush(mon);
4147 monitor_suspend(mon);
4148 } else {
4149 mon->suspend_cnt++;
4150 }
4151 qemu_mutex_lock(&mon->out_lock);
4152 mon->mux_out = 1;
4153 qemu_mutex_unlock(&mon->out_lock);
4154 break;
4155
4156 case CHR_EVENT_OPENED:
4157 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4158 "information\n", QEMU_VERSION);
4159 if (!mon->mux_out) {
4160 readline_restart(mon->rs);
4161 readline_show_prompt(mon->rs);
4162 }
4163 mon->reset_seen = 1;
4164 mon_refcount++;
4165 break;
4166
4167 case CHR_EVENT_CLOSED:
4168 mon_refcount--;
4169 monitor_fdsets_cleanup();
4170 break;
4171 }
4172 }
4173
4174 static int
4175 compare_mon_cmd(const void *a, const void *b)
4176 {
4177 return strcmp(((const mon_cmd_t *)a)->name,
4178 ((const mon_cmd_t *)b)->name);
4179 }
4180
4181 static void sortcmdlist(void)
4182 {
4183 int array_num;
4184 int elem_size = sizeof(mon_cmd_t);
4185
4186 array_num = sizeof(mon_cmds)/elem_size-1;
4187 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4188
4189 array_num = sizeof(info_cmds)/elem_size-1;
4190 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4191 }
4192
4193 /* These functions just adapt the readline interface in a typesafe way. We
4194 * could cast function pointers but that discards compiler checks.
4195 */
4196 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4197 const char *fmt, ...)
4198 {
4199 va_list ap;
4200 va_start(ap, fmt);
4201 monitor_vprintf(opaque, fmt, ap);
4202 va_end(ap);
4203 }
4204
4205 static void monitor_readline_flush(void *opaque)
4206 {
4207 monitor_flush(opaque);
4208 }
4209
4210 static void __attribute__((constructor)) monitor_lock_init(void)
4211 {
4212 qemu_mutex_init(&monitor_lock);
4213 }
4214
4215 void monitor_init(CharDriverState *chr, int flags)
4216 {
4217 static int is_first_init = 1;
4218 Monitor *mon;
4219
4220 if (is_first_init) {
4221 monitor_qapi_event_init();
4222 sortcmdlist();
4223 is_first_init = 0;
4224 }
4225
4226 mon = g_malloc(sizeof(*mon));
4227 monitor_data_init(mon);
4228
4229 mon->chr = chr;
4230 mon->flags = flags;
4231 if (flags & MONITOR_USE_READLINE) {
4232 mon->rs = readline_init(monitor_readline_printf,
4233 monitor_readline_flush,
4234 mon,
4235 monitor_find_completion);
4236 monitor_read_command(mon, 0);
4237 }
4238
4239 if (monitor_is_qmp(mon)) {
4240 qemu_chr_add_handlers(chr, monitor_can_read, monitor_qmp_read,
4241 monitor_qmp_event, mon);
4242 qemu_chr_fe_set_echo(chr, true);
4243 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4244 } else {
4245 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4246 monitor_event, mon);
4247 }
4248
4249 qemu_mutex_lock(&monitor_lock);
4250 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4251 qemu_mutex_unlock(&monitor_lock);
4252 }
4253
4254 void monitor_cleanup(void)
4255 {
4256 Monitor *mon, *next;
4257
4258 qemu_mutex_lock(&monitor_lock);
4259 QLIST_FOREACH_SAFE(mon, &mon_list, entry, next) {
4260 QLIST_REMOVE(mon, entry);
4261 monitor_data_destroy(mon);
4262 g_free(mon);
4263 }
4264 qemu_mutex_unlock(&monitor_lock);
4265 }
4266
4267 static void bdrv_password_cb(void *opaque, const char *password,
4268 void *readline_opaque)
4269 {
4270 Monitor *mon = opaque;
4271 BlockDriverState *bs = readline_opaque;
4272 int ret = 0;
4273 Error *local_err = NULL;
4274
4275 bdrv_add_key(bs, password, &local_err);
4276 if (local_err) {
4277 error_report_err(local_err);
4278 ret = -EPERM;
4279 }
4280 if (mon->password_completion_cb)
4281 mon->password_completion_cb(mon->password_opaque, ret);
4282
4283 monitor_read_command(mon, 1);
4284 }
4285
4286 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4287 BlockCompletionFunc *completion_cb,
4288 void *opaque)
4289 {
4290 int err;
4291
4292 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4293 bdrv_get_encrypted_filename(bs));
4294
4295 mon->password_completion_cb = completion_cb;
4296 mon->password_opaque = opaque;
4297
4298 err = monitor_read_password(mon, bdrv_password_cb, bs);
4299
4300 if (err && completion_cb)
4301 completion_cb(opaque, err);
4302
4303 return err;
4304 }
4305
4306 int monitor_read_block_device_key(Monitor *mon, const char *device,
4307 BlockCompletionFunc *completion_cb,
4308 void *opaque)
4309 {
4310 Error *err = NULL;
4311 BlockBackend *blk;
4312
4313 blk = blk_by_name(device);
4314 if (!blk) {
4315 monitor_printf(mon, "Device not found %s\n", device);
4316 return -1;
4317 }
4318 if (!blk_bs(blk)) {
4319 monitor_printf(mon, "Device '%s' has no medium\n", device);
4320 return -1;
4321 }
4322
4323 bdrv_add_key(blk_bs(blk), NULL, &err);
4324 if (err) {
4325 error_free(err);
4326 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
4327 }
4328
4329 if (completion_cb) {
4330 completion_cb(opaque, 0);
4331 }
4332 return 0;
4333 }
4334
4335 QemuOptsList qemu_mon_opts = {
4336 .name = "mon",
4337 .implied_opt_name = "chardev",
4338 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4339 .desc = {
4340 {
4341 .name = "mode",
4342 .type = QEMU_OPT_STRING,
4343 },{
4344 .name = "chardev",
4345 .type = QEMU_OPT_STRING,
4346 },{
4347 .name = "default",
4348 .type = QEMU_OPT_BOOL,
4349 },{
4350 .name = "pretty",
4351 .type = QEMU_OPT_BOOL,
4352 },
4353 { /* end of list */ }
4354 },
4355 };
4356
4357 #ifndef TARGET_I386
4358 void qmp_rtc_reset_reinjection(Error **errp)
4359 {
4360 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4361 }
4362 #endif
4363
4364 #ifndef TARGET_S390X
4365 void qmp_dump_skeys(const char *filename, Error **errp)
4366 {
4367 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4368 }
4369 #endif
4370
4371 #ifndef TARGET_ARM
4372 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4373 {
4374 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4375 return NULL;
4376 }
4377 #endif
4378
4379 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4380 {
4381 MachineState *ms = MACHINE(qdev_get_machine());
4382 MachineClass *mc = MACHINE_GET_CLASS(ms);
4383
4384 if (!mc->query_hotpluggable_cpus) {
4385 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4386 return NULL;
4387 }
4388
4389 return mc->query_hotpluggable_cpus(ms);
4390 }