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