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