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