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