hmp: gpa2hva and gpa2hpa hostaddr command
[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 TARGET_I386
978 qmp_unregister_command(&qmp_commands, "rtc-reset-reinjection");
979 #endif
980 #ifndef TARGET_S390X
981 qmp_unregister_command(&qmp_commands, "dump-skeys");
982 #endif
983 #ifndef TARGET_ARM
984 qmp_unregister_command(&qmp_commands, "query-gic-capabilities");
985 #endif
986 #if !defined(TARGET_S390X) && !defined(TARGET_I386)
987 qmp_unregister_command(&qmp_commands, "query-cpu-model-expansion");
988 #endif
989 #if !defined(TARGET_S390X)
990 qmp_unregister_command(&qmp_commands, "query-cpu-model-baseline");
991 qmp_unregister_command(&qmp_commands, "query-cpu-model-comparison");
992 #endif
993 #if !defined(TARGET_PPC) && !defined(TARGET_ARM) && !defined(TARGET_I386) \
994 && !defined(TARGET_S390X)
995 qmp_unregister_command(&qmp_commands, "query-cpu-definitions");
996 #endif
997 }
998
999 void monitor_init_qmp_commands(void)
1000 {
1001 /*
1002 * Two command lists:
1003 * - qmp_commands contains all QMP commands
1004 * - qmp_cap_negotiation_commands contains just
1005 * "qmp_capabilities", to enforce capability negotiation
1006 */
1007
1008 qmp_init_marshal(&qmp_commands);
1009
1010 qmp_register_command(&qmp_commands, "query-qmp-schema",
1011 qmp_query_qmp_schema,
1012 QCO_NO_OPTIONS);
1013 qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
1014 QCO_NO_OPTIONS);
1015 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1016 QCO_NO_OPTIONS);
1017
1018 qmp_unregister_commands_hack();
1019
1020 QTAILQ_INIT(&qmp_cap_negotiation_commands);
1021 qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
1022 qmp_marshal_qmp_capabilities, QCO_NO_OPTIONS);
1023 }
1024
1025 void qmp_qmp_capabilities(Error **errp)
1026 {
1027 if (cur_mon->qmp.commands == &qmp_commands) {
1028 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1029 "Capabilities negotiation is already complete, command "
1030 "ignored");
1031 return;
1032 }
1033
1034 cur_mon->qmp.commands = &qmp_commands;
1035 }
1036
1037 /* set the current CPU defined by the user */
1038 int monitor_set_cpu(int cpu_index)
1039 {
1040 CPUState *cpu;
1041
1042 cpu = qemu_get_cpu(cpu_index);
1043 if (cpu == NULL) {
1044 return -1;
1045 }
1046 cur_mon->mon_cpu = cpu;
1047 return 0;
1048 }
1049
1050 CPUState *mon_get_cpu(void)
1051 {
1052 if (!cur_mon->mon_cpu) {
1053 if (!first_cpu) {
1054 return NULL;
1055 }
1056 monitor_set_cpu(first_cpu->cpu_index);
1057 }
1058 cpu_synchronize_state(cur_mon->mon_cpu);
1059 return cur_mon->mon_cpu;
1060 }
1061
1062 CPUArchState *mon_get_cpu_env(void)
1063 {
1064 CPUState *cs = mon_get_cpu();
1065
1066 return cs ? cs->env_ptr : NULL;
1067 }
1068
1069 int monitor_get_cpu_index(void)
1070 {
1071 CPUState *cs = mon_get_cpu();
1072
1073 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1074 }
1075
1076 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1077 {
1078 CPUState *cs = mon_get_cpu();
1079
1080 if (!cs) {
1081 monitor_printf(mon, "No CPU available\n");
1082 return;
1083 }
1084 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1085 }
1086
1087 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1088 {
1089 dump_exec_info((FILE *)mon, monitor_fprintf);
1090 dump_drift_info((FILE *)mon, monitor_fprintf);
1091 }
1092
1093 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1094 {
1095 dump_opcount_info((FILE *)mon, monitor_fprintf);
1096 }
1097
1098 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1099 {
1100 int i;
1101 const char *str;
1102
1103 if (!mon->rs)
1104 return;
1105 i = 0;
1106 for(;;) {
1107 str = readline_get_history(mon->rs, i);
1108 if (!str)
1109 break;
1110 monitor_printf(mon, "%d: '%s'\n", i, str);
1111 i++;
1112 }
1113 }
1114
1115 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1116 {
1117 CPUState *cs = mon_get_cpu();
1118
1119 if (!cs) {
1120 monitor_printf(mon, "No CPU available\n");
1121 return;
1122 }
1123 cpu_dump_statistics(cs, (FILE *)mon, &monitor_fprintf, 0);
1124 }
1125
1126 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1127 {
1128 const char *name = qdict_get_try_str(qdict, "name");
1129 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1130 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1131 TraceEventInfoList *events;
1132 TraceEventInfoList *elem;
1133 Error *local_err = NULL;
1134
1135 if (name == NULL) {
1136 name = "*";
1137 }
1138 if (vcpu < 0) {
1139 monitor_printf(mon, "argument vcpu must be positive");
1140 return;
1141 }
1142
1143 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1144 if (local_err) {
1145 error_report_err(local_err);
1146 return;
1147 }
1148
1149 for (elem = events; elem != NULL; elem = elem->next) {
1150 monitor_printf(mon, "%s : state %u\n",
1151 elem->value->name,
1152 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1153 }
1154 qapi_free_TraceEventInfoList(events);
1155 }
1156
1157 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1158 bool has_port, int64_t port,
1159 bool has_tls_port, int64_t tls_port,
1160 bool has_cert_subject, const char *cert_subject,
1161 Error **errp)
1162 {
1163 if (strcmp(protocol, "spice") == 0) {
1164 if (!qemu_using_spice(errp)) {
1165 return;
1166 }
1167
1168 if (!has_port && !has_tls_port) {
1169 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1170 return;
1171 }
1172
1173 if (qemu_spice_migrate_info(hostname,
1174 has_port ? port : -1,
1175 has_tls_port ? tls_port : -1,
1176 cert_subject)) {
1177 error_setg(errp, QERR_UNDEFINED_ERROR);
1178 return;
1179 }
1180 return;
1181 }
1182
1183 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1184 }
1185
1186 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1187 {
1188 Error *err = NULL;
1189
1190 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1191 if (err) {
1192 error_report_err(err);
1193 }
1194 }
1195
1196 static void hmp_log(Monitor *mon, const QDict *qdict)
1197 {
1198 int mask;
1199 const char *items = qdict_get_str(qdict, "items");
1200
1201 if (!strcmp(items, "none")) {
1202 mask = 0;
1203 } else {
1204 mask = qemu_str_to_log_mask(items);
1205 if (!mask) {
1206 help_cmd(mon, "log");
1207 return;
1208 }
1209 }
1210 qemu_set_log(mask);
1211 }
1212
1213 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1214 {
1215 const char *option = qdict_get_try_str(qdict, "option");
1216 if (!option || !strcmp(option, "on")) {
1217 singlestep = 1;
1218 } else if (!strcmp(option, "off")) {
1219 singlestep = 0;
1220 } else {
1221 monitor_printf(mon, "unexpected option %s\n", option);
1222 }
1223 }
1224
1225 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1226 {
1227 const char *device = qdict_get_try_str(qdict, "device");
1228 if (!device)
1229 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1230 if (gdbserver_start(device) < 0) {
1231 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1232 device);
1233 } else if (strcmp(device, "none") == 0) {
1234 monitor_printf(mon, "Disabled gdbserver\n");
1235 } else {
1236 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1237 device);
1238 }
1239 }
1240
1241 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1242 {
1243 const char *action = qdict_get_str(qdict, "action");
1244 if (select_watchdog_action(action) == -1) {
1245 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1246 }
1247 }
1248
1249 static void monitor_printc(Monitor *mon, int c)
1250 {
1251 monitor_printf(mon, "'");
1252 switch(c) {
1253 case '\'':
1254 monitor_printf(mon, "\\'");
1255 break;
1256 case '\\':
1257 monitor_printf(mon, "\\\\");
1258 break;
1259 case '\n':
1260 monitor_printf(mon, "\\n");
1261 break;
1262 case '\r':
1263 monitor_printf(mon, "\\r");
1264 break;
1265 default:
1266 if (c >= 32 && c <= 126) {
1267 monitor_printf(mon, "%c", c);
1268 } else {
1269 monitor_printf(mon, "\\x%02x", c);
1270 }
1271 break;
1272 }
1273 monitor_printf(mon, "'");
1274 }
1275
1276 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1277 hwaddr addr, int is_physical)
1278 {
1279 int l, line_size, i, max_digits, len;
1280 uint8_t buf[16];
1281 uint64_t v;
1282 CPUState *cs = mon_get_cpu();
1283
1284 if (!cs && (format == 'i' || !is_physical)) {
1285 monitor_printf(mon, "Can not dump without CPU\n");
1286 return;
1287 }
1288
1289 if (format == 'i') {
1290 int flags = 0;
1291 #ifdef TARGET_I386
1292 CPUArchState *env = mon_get_cpu_env();
1293 if (wsize == 2) {
1294 flags = 1;
1295 } else if (wsize == 4) {
1296 flags = 0;
1297 } else {
1298 /* as default we use the current CS size */
1299 flags = 0;
1300 if (env) {
1301 #ifdef TARGET_X86_64
1302 if ((env->efer & MSR_EFER_LMA) &&
1303 (env->segs[R_CS].flags & DESC_L_MASK))
1304 flags = 2;
1305 else
1306 #endif
1307 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1308 flags = 1;
1309 }
1310 }
1311 #endif
1312 #ifdef TARGET_PPC
1313 CPUArchState *env = mon_get_cpu_env();
1314 flags = msr_le << 16;
1315 flags |= env->bfd_mach;
1316 #endif
1317 monitor_disas(mon, cs, addr, count, is_physical, flags);
1318 return;
1319 }
1320
1321 len = wsize * count;
1322 if (wsize == 1)
1323 line_size = 8;
1324 else
1325 line_size = 16;
1326 max_digits = 0;
1327
1328 switch(format) {
1329 case 'o':
1330 max_digits = (wsize * 8 + 2) / 3;
1331 break;
1332 default:
1333 case 'x':
1334 max_digits = (wsize * 8) / 4;
1335 break;
1336 case 'u':
1337 case 'd':
1338 max_digits = (wsize * 8 * 10 + 32) / 33;
1339 break;
1340 case 'c':
1341 wsize = 1;
1342 break;
1343 }
1344
1345 while (len > 0) {
1346 if (is_physical)
1347 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1348 else
1349 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1350 l = len;
1351 if (l > line_size)
1352 l = line_size;
1353 if (is_physical) {
1354 cpu_physical_memory_read(addr, buf, l);
1355 } else {
1356 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1357 monitor_printf(mon, " Cannot access memory\n");
1358 break;
1359 }
1360 }
1361 i = 0;
1362 while (i < l) {
1363 switch(wsize) {
1364 default:
1365 case 1:
1366 v = ldub_p(buf + i);
1367 break;
1368 case 2:
1369 v = lduw_p(buf + i);
1370 break;
1371 case 4:
1372 v = (uint32_t)ldl_p(buf + i);
1373 break;
1374 case 8:
1375 v = ldq_p(buf + i);
1376 break;
1377 }
1378 monitor_printf(mon, " ");
1379 switch(format) {
1380 case 'o':
1381 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1382 break;
1383 case 'x':
1384 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1385 break;
1386 case 'u':
1387 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1388 break;
1389 case 'd':
1390 monitor_printf(mon, "%*" PRId64, max_digits, v);
1391 break;
1392 case 'c':
1393 monitor_printc(mon, v);
1394 break;
1395 }
1396 i += wsize;
1397 }
1398 monitor_printf(mon, "\n");
1399 addr += l;
1400 len -= l;
1401 }
1402 }
1403
1404 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1405 {
1406 int count = qdict_get_int(qdict, "count");
1407 int format = qdict_get_int(qdict, "format");
1408 int size = qdict_get_int(qdict, "size");
1409 target_long addr = qdict_get_int(qdict, "addr");
1410
1411 memory_dump(mon, count, format, size, addr, 0);
1412 }
1413
1414 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1415 {
1416 int count = qdict_get_int(qdict, "count");
1417 int format = qdict_get_int(qdict, "format");
1418 int size = qdict_get_int(qdict, "size");
1419 hwaddr addr = qdict_get_int(qdict, "addr");
1420
1421 memory_dump(mon, count, format, size, addr, 1);
1422 }
1423
1424 static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
1425 {
1426 MemoryRegionSection mrs = memory_region_find(get_system_memory(),
1427 addr, 1);
1428
1429 if (!mrs.mr) {
1430 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1431 return NULL;
1432 }
1433
1434 if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
1435 error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
1436 memory_region_unref(mrs.mr);
1437 return NULL;
1438 }
1439
1440 *p_mr = mrs.mr;
1441 return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
1442 }
1443
1444 static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
1445 {
1446 hwaddr addr = qdict_get_int(qdict, "addr");
1447 Error *local_err = NULL;
1448 MemoryRegion *mr = NULL;
1449 void *ptr;
1450
1451 ptr = gpa2hva(&mr, addr, &local_err);
1452 if (local_err) {
1453 error_report_err(local_err);
1454 return;
1455 }
1456
1457 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1458 " (%s) is %p\n",
1459 addr, mr->name, ptr);
1460
1461 memory_region_unref(mr);
1462 }
1463
1464 #ifdef CONFIG_LINUX
1465 static uint64_t vtop(void *ptr, Error **errp)
1466 {
1467 uint64_t pinfo;
1468 uint64_t ret = -1;
1469 uintptr_t addr = (uintptr_t) ptr;
1470 uintptr_t pagesize = getpagesize();
1471 off_t offset = addr / pagesize * sizeof(pinfo);
1472 int fd;
1473
1474 fd = open("/proc/self/pagemap", O_RDONLY);
1475 if (fd == -1) {
1476 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1477 return -1;
1478 }
1479
1480 /* Force copy-on-write if necessary. */
1481 atomic_add((uint8_t *)ptr, 0);
1482
1483 if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
1484 error_setg_errno(errp, errno, "Cannot read pagemap");
1485 goto out;
1486 }
1487 if ((pinfo & (1ull << 63)) == 0) {
1488 error_setg(errp, "Page not present");
1489 goto out;
1490 }
1491 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1492
1493 out:
1494 close(fd);
1495 return ret;
1496 }
1497
1498 static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
1499 {
1500 hwaddr addr = qdict_get_int(qdict, "addr");
1501 Error *local_err = NULL;
1502 MemoryRegion *mr = NULL;
1503 void *ptr;
1504 uint64_t physaddr;
1505
1506 ptr = gpa2hva(&mr, addr, &local_err);
1507 if (local_err) {
1508 error_report_err(local_err);
1509 return;
1510 }
1511
1512 physaddr = vtop(ptr, &local_err);
1513 if (local_err) {
1514 error_report_err(local_err);
1515 } else {
1516 monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
1517 " (%s) is 0x%" PRIx64 "\n",
1518 addr, mr->name, (uint64_t) physaddr);
1519 }
1520
1521 memory_region_unref(mr);
1522 }
1523 #endif
1524
1525 static void do_print(Monitor *mon, const QDict *qdict)
1526 {
1527 int format = qdict_get_int(qdict, "format");
1528 hwaddr val = qdict_get_int(qdict, "val");
1529
1530 switch(format) {
1531 case 'o':
1532 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1533 break;
1534 case 'x':
1535 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1536 break;
1537 case 'u':
1538 monitor_printf(mon, "%" HWADDR_PRIu, val);
1539 break;
1540 default:
1541 case 'd':
1542 monitor_printf(mon, "%" HWADDR_PRId, val);
1543 break;
1544 case 'c':
1545 monitor_printc(mon, val);
1546 break;
1547 }
1548 monitor_printf(mon, "\n");
1549 }
1550
1551 static void hmp_sum(Monitor *mon, const QDict *qdict)
1552 {
1553 uint32_t addr;
1554 uint16_t sum;
1555 uint32_t start = qdict_get_int(qdict, "start");
1556 uint32_t size = qdict_get_int(qdict, "size");
1557
1558 sum = 0;
1559 for(addr = start; addr < (start + size); addr++) {
1560 uint8_t val = address_space_ldub(&address_space_memory, addr,
1561 MEMTXATTRS_UNSPECIFIED, NULL);
1562 /* BSD sum algorithm ('sum' Unix command) */
1563 sum = (sum >> 1) | (sum << 15);
1564 sum += val;
1565 }
1566 monitor_printf(mon, "%05d\n", sum);
1567 }
1568
1569 static int mouse_button_state;
1570
1571 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1572 {
1573 int dx, dy, dz, button;
1574 const char *dx_str = qdict_get_str(qdict, "dx_str");
1575 const char *dy_str = qdict_get_str(qdict, "dy_str");
1576 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1577
1578 dx = strtol(dx_str, NULL, 0);
1579 dy = strtol(dy_str, NULL, 0);
1580 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1581 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1582
1583 if (dz_str) {
1584 dz = strtol(dz_str, NULL, 0);
1585 if (dz != 0) {
1586 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1587 qemu_input_queue_btn(NULL, button, true);
1588 qemu_input_event_sync();
1589 qemu_input_queue_btn(NULL, button, false);
1590 }
1591 }
1592 qemu_input_event_sync();
1593 }
1594
1595 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1596 {
1597 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1598 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1599 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1600 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1601 };
1602 int button_state = qdict_get_int(qdict, "button_state");
1603
1604 if (mouse_button_state == button_state) {
1605 return;
1606 }
1607 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1608 qemu_input_event_sync();
1609 mouse_button_state = button_state;
1610 }
1611
1612 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1613 {
1614 int size = qdict_get_int(qdict, "size");
1615 int addr = qdict_get_int(qdict, "addr");
1616 int has_index = qdict_haskey(qdict, "index");
1617 uint32_t val;
1618 int suffix;
1619
1620 if (has_index) {
1621 int index = qdict_get_int(qdict, "index");
1622 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1623 addr++;
1624 }
1625 addr &= 0xffff;
1626
1627 switch(size) {
1628 default:
1629 case 1:
1630 val = cpu_inb(addr);
1631 suffix = 'b';
1632 break;
1633 case 2:
1634 val = cpu_inw(addr);
1635 suffix = 'w';
1636 break;
1637 case 4:
1638 val = cpu_inl(addr);
1639 suffix = 'l';
1640 break;
1641 }
1642 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1643 suffix, addr, size * 2, val);
1644 }
1645
1646 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1647 {
1648 int size = qdict_get_int(qdict, "size");
1649 int addr = qdict_get_int(qdict, "addr");
1650 int val = qdict_get_int(qdict, "val");
1651
1652 addr &= IOPORTS_MASK;
1653
1654 switch (size) {
1655 default:
1656 case 1:
1657 cpu_outb(addr, val);
1658 break;
1659 case 2:
1660 cpu_outw(addr, val);
1661 break;
1662 case 4:
1663 cpu_outl(addr, val);
1664 break;
1665 }
1666 }
1667
1668 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
1669 {
1670 Error *local_err = NULL;
1671 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1672
1673 qemu_boot_set(bootdevice, &local_err);
1674 if (local_err) {
1675 error_report_err(local_err);
1676 } else {
1677 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1678 }
1679 }
1680
1681 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
1682 {
1683 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
1684
1685 mtree_info((fprintf_function)monitor_printf, mon, flatview);
1686 }
1687
1688 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
1689 {
1690 int i;
1691 CPUState *cpu;
1692 uint64_t *node_mem;
1693
1694 node_mem = g_new0(uint64_t, nb_numa_nodes);
1695 query_numa_node_mem(node_mem);
1696 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1697 for (i = 0; i < nb_numa_nodes; i++) {
1698 monitor_printf(mon, "node %d cpus:", i);
1699 CPU_FOREACH(cpu) {
1700 if (cpu->numa_node == i) {
1701 monitor_printf(mon, " %d", cpu->cpu_index);
1702 }
1703 }
1704 monitor_printf(mon, "\n");
1705 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1706 node_mem[i] >> 20);
1707 }
1708 g_free(node_mem);
1709 }
1710
1711 #ifdef CONFIG_PROFILER
1712
1713 int64_t tcg_time;
1714 int64_t dev_time;
1715
1716 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1717 {
1718 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1719 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
1720 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1721 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
1722 tcg_time = 0;
1723 dev_time = 0;
1724 }
1725 #else
1726 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
1727 {
1728 monitor_printf(mon, "Internal profiler not compiled\n");
1729 }
1730 #endif
1731
1732 /* Capture support */
1733 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1734
1735 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
1736 {
1737 int i;
1738 CaptureState *s;
1739
1740 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1741 monitor_printf(mon, "[%d]: ", i);
1742 s->ops.info (s->opaque);
1743 }
1744 }
1745
1746 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
1747 {
1748 int i;
1749 int n = qdict_get_int(qdict, "n");
1750 CaptureState *s;
1751
1752 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1753 if (i == n) {
1754 s->ops.destroy (s->opaque);
1755 QLIST_REMOVE (s, entries);
1756 g_free (s);
1757 return;
1758 }
1759 }
1760 }
1761
1762 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
1763 {
1764 const char *path = qdict_get_str(qdict, "path");
1765 int has_freq = qdict_haskey(qdict, "freq");
1766 int freq = qdict_get_try_int(qdict, "freq", -1);
1767 int has_bits = qdict_haskey(qdict, "bits");
1768 int bits = qdict_get_try_int(qdict, "bits", -1);
1769 int has_channels = qdict_haskey(qdict, "nchannels");
1770 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1771 CaptureState *s;
1772
1773 s = g_malloc0 (sizeof (*s));
1774
1775 freq = has_freq ? freq : 44100;
1776 bits = has_bits ? bits : 16;
1777 nchannels = has_channels ? nchannels : 2;
1778
1779 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1780 monitor_printf(mon, "Failed to add wave capture\n");
1781 g_free (s);
1782 return;
1783 }
1784 QLIST_INSERT_HEAD (&capture_head, s, entries);
1785 }
1786
1787 static qemu_acl *find_acl(Monitor *mon, const char *name)
1788 {
1789 qemu_acl *acl = qemu_acl_find(name);
1790
1791 if (!acl) {
1792 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1793 }
1794 return acl;
1795 }
1796
1797 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
1798 {
1799 const char *aclname = qdict_get_str(qdict, "aclname");
1800 qemu_acl *acl = find_acl(mon, aclname);
1801 qemu_acl_entry *entry;
1802 int i = 0;
1803
1804 if (acl) {
1805 monitor_printf(mon, "policy: %s\n",
1806 acl->defaultDeny ? "deny" : "allow");
1807 QTAILQ_FOREACH(entry, &acl->entries, next) {
1808 i++;
1809 monitor_printf(mon, "%d: %s %s\n", i,
1810 entry->deny ? "deny" : "allow", entry->match);
1811 }
1812 }
1813 }
1814
1815 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
1816 {
1817 const char *aclname = qdict_get_str(qdict, "aclname");
1818 qemu_acl *acl = find_acl(mon, aclname);
1819
1820 if (acl) {
1821 qemu_acl_reset(acl);
1822 monitor_printf(mon, "acl: removed all rules\n");
1823 }
1824 }
1825
1826 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
1827 {
1828 const char *aclname = qdict_get_str(qdict, "aclname");
1829 const char *policy = qdict_get_str(qdict, "policy");
1830 qemu_acl *acl = find_acl(mon, aclname);
1831
1832 if (acl) {
1833 if (strcmp(policy, "allow") == 0) {
1834 acl->defaultDeny = 0;
1835 monitor_printf(mon, "acl: policy set to 'allow'\n");
1836 } else if (strcmp(policy, "deny") == 0) {
1837 acl->defaultDeny = 1;
1838 monitor_printf(mon, "acl: policy set to 'deny'\n");
1839 } else {
1840 monitor_printf(mon, "acl: unknown policy '%s', "
1841 "expected 'deny' or 'allow'\n", policy);
1842 }
1843 }
1844 }
1845
1846 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
1847 {
1848 const char *aclname = qdict_get_str(qdict, "aclname");
1849 const char *match = qdict_get_str(qdict, "match");
1850 const char *policy = qdict_get_str(qdict, "policy");
1851 int has_index = qdict_haskey(qdict, "index");
1852 int index = qdict_get_try_int(qdict, "index", -1);
1853 qemu_acl *acl = find_acl(mon, aclname);
1854 int deny, ret;
1855
1856 if (acl) {
1857 if (strcmp(policy, "allow") == 0) {
1858 deny = 0;
1859 } else if (strcmp(policy, "deny") == 0) {
1860 deny = 1;
1861 } else {
1862 monitor_printf(mon, "acl: unknown policy '%s', "
1863 "expected 'deny' or 'allow'\n", policy);
1864 return;
1865 }
1866 if (has_index)
1867 ret = qemu_acl_insert(acl, deny, match, index);
1868 else
1869 ret = qemu_acl_append(acl, deny, match);
1870 if (ret < 0)
1871 monitor_printf(mon, "acl: unable to add acl entry\n");
1872 else
1873 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1874 }
1875 }
1876
1877 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
1878 {
1879 const char *aclname = qdict_get_str(qdict, "aclname");
1880 const char *match = qdict_get_str(qdict, "match");
1881 qemu_acl *acl = find_acl(mon, aclname);
1882 int ret;
1883
1884 if (acl) {
1885 ret = qemu_acl_remove(acl, match);
1886 if (ret < 0)
1887 monitor_printf(mon, "acl: no matching acl entry\n");
1888 else
1889 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1890 }
1891 }
1892
1893 void qmp_getfd(const char *fdname, Error **errp)
1894 {
1895 mon_fd_t *monfd;
1896 int fd;
1897
1898 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
1899 if (fd == -1) {
1900 error_setg(errp, QERR_FD_NOT_SUPPLIED);
1901 return;
1902 }
1903
1904 if (qemu_isdigit(fdname[0])) {
1905 close(fd);
1906 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1907 "a name not starting with a digit");
1908 return;
1909 }
1910
1911 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1912 if (strcmp(monfd->name, fdname) != 0) {
1913 continue;
1914 }
1915
1916 close(monfd->fd);
1917 monfd->fd = fd;
1918 return;
1919 }
1920
1921 monfd = g_malloc0(sizeof(mon_fd_t));
1922 monfd->name = g_strdup(fdname);
1923 monfd->fd = fd;
1924
1925 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
1926 }
1927
1928 void qmp_closefd(const char *fdname, Error **errp)
1929 {
1930 mon_fd_t *monfd;
1931
1932 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
1933 if (strcmp(monfd->name, fdname) != 0) {
1934 continue;
1935 }
1936
1937 QLIST_REMOVE(monfd, next);
1938 close(monfd->fd);
1939 g_free(monfd->name);
1940 g_free(monfd);
1941 return;
1942 }
1943
1944 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
1945 }
1946
1947 static void hmp_loadvm(Monitor *mon, const QDict *qdict)
1948 {
1949 int saved_vm_running = runstate_is_running();
1950 const char *name = qdict_get_str(qdict, "name");
1951
1952 vm_stop(RUN_STATE_RESTORE_VM);
1953
1954 if (load_vmstate(name) == 0 && saved_vm_running) {
1955 vm_start();
1956 }
1957 }
1958
1959 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
1960 {
1961 mon_fd_t *monfd;
1962
1963 QLIST_FOREACH(monfd, &mon->fds, next) {
1964 int fd;
1965
1966 if (strcmp(monfd->name, fdname) != 0) {
1967 continue;
1968 }
1969
1970 fd = monfd->fd;
1971
1972 /* caller takes ownership of fd */
1973 QLIST_REMOVE(monfd, next);
1974 g_free(monfd->name);
1975 g_free(monfd);
1976
1977 return fd;
1978 }
1979
1980 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
1981 return -1;
1982 }
1983
1984 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1985 {
1986 MonFdsetFd *mon_fdset_fd;
1987 MonFdsetFd *mon_fdset_fd_next;
1988
1989 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
1990 if ((mon_fdset_fd->removed ||
1991 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1992 runstate_is_running()) {
1993 close(mon_fdset_fd->fd);
1994 g_free(mon_fdset_fd->opaque);
1995 QLIST_REMOVE(mon_fdset_fd, next);
1996 g_free(mon_fdset_fd);
1997 }
1998 }
1999
2000 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2001 QLIST_REMOVE(mon_fdset, next);
2002 g_free(mon_fdset);
2003 }
2004 }
2005
2006 static void monitor_fdsets_cleanup(void)
2007 {
2008 MonFdset *mon_fdset;
2009 MonFdset *mon_fdset_next;
2010
2011 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2012 monitor_fdset_cleanup(mon_fdset);
2013 }
2014 }
2015
2016 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2017 const char *opaque, Error **errp)
2018 {
2019 int fd;
2020 Monitor *mon = cur_mon;
2021 AddfdInfo *fdinfo;
2022
2023 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2024 if (fd == -1) {
2025 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2026 goto error;
2027 }
2028
2029 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2030 has_opaque, opaque, errp);
2031 if (fdinfo) {
2032 return fdinfo;
2033 }
2034
2035 error:
2036 if (fd != -1) {
2037 close(fd);
2038 }
2039 return NULL;
2040 }
2041
2042 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2043 {
2044 MonFdset *mon_fdset;
2045 MonFdsetFd *mon_fdset_fd;
2046 char fd_str[60];
2047
2048 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2049 if (mon_fdset->id != fdset_id) {
2050 continue;
2051 }
2052 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2053 if (has_fd) {
2054 if (mon_fdset_fd->fd != fd) {
2055 continue;
2056 }
2057 mon_fdset_fd->removed = true;
2058 break;
2059 } else {
2060 mon_fdset_fd->removed = true;
2061 }
2062 }
2063 if (has_fd && !mon_fdset_fd) {
2064 goto error;
2065 }
2066 monitor_fdset_cleanup(mon_fdset);
2067 return;
2068 }
2069
2070 error:
2071 if (has_fd) {
2072 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2073 fdset_id, fd);
2074 } else {
2075 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2076 }
2077 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2078 }
2079
2080 FdsetInfoList *qmp_query_fdsets(Error **errp)
2081 {
2082 MonFdset *mon_fdset;
2083 MonFdsetFd *mon_fdset_fd;
2084 FdsetInfoList *fdset_list = NULL;
2085
2086 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2087 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2088 FdsetFdInfoList *fdsetfd_list = NULL;
2089
2090 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2091 fdset_info->value->fdset_id = mon_fdset->id;
2092
2093 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2094 FdsetFdInfoList *fdsetfd_info;
2095
2096 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2097 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2098 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2099 if (mon_fdset_fd->opaque) {
2100 fdsetfd_info->value->has_opaque = true;
2101 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2102 } else {
2103 fdsetfd_info->value->has_opaque = false;
2104 }
2105
2106 fdsetfd_info->next = fdsetfd_list;
2107 fdsetfd_list = fdsetfd_info;
2108 }
2109
2110 fdset_info->value->fds = fdsetfd_list;
2111
2112 fdset_info->next = fdset_list;
2113 fdset_list = fdset_info;
2114 }
2115
2116 return fdset_list;
2117 }
2118
2119 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2120 bool has_opaque, const char *opaque,
2121 Error **errp)
2122 {
2123 MonFdset *mon_fdset = NULL;
2124 MonFdsetFd *mon_fdset_fd;
2125 AddfdInfo *fdinfo;
2126
2127 if (has_fdset_id) {
2128 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2129 /* Break if match found or match impossible due to ordering by ID */
2130 if (fdset_id <= mon_fdset->id) {
2131 if (fdset_id < mon_fdset->id) {
2132 mon_fdset = NULL;
2133 }
2134 break;
2135 }
2136 }
2137 }
2138
2139 if (mon_fdset == NULL) {
2140 int64_t fdset_id_prev = -1;
2141 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2142
2143 if (has_fdset_id) {
2144 if (fdset_id < 0) {
2145 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2146 "a non-negative value");
2147 return NULL;
2148 }
2149 /* Use specified fdset ID */
2150 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2151 mon_fdset_cur = mon_fdset;
2152 if (fdset_id < mon_fdset_cur->id) {
2153 break;
2154 }
2155 }
2156 } else {
2157 /* Use first available fdset ID */
2158 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2159 mon_fdset_cur = mon_fdset;
2160 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2161 fdset_id_prev = mon_fdset_cur->id;
2162 continue;
2163 }
2164 break;
2165 }
2166 }
2167
2168 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2169 if (has_fdset_id) {
2170 mon_fdset->id = fdset_id;
2171 } else {
2172 mon_fdset->id = fdset_id_prev + 1;
2173 }
2174
2175 /* The fdset list is ordered by fdset ID */
2176 if (!mon_fdset_cur) {
2177 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2178 } else if (mon_fdset->id < mon_fdset_cur->id) {
2179 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2180 } else {
2181 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2182 }
2183 }
2184
2185 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2186 mon_fdset_fd->fd = fd;
2187 mon_fdset_fd->removed = false;
2188 if (has_opaque) {
2189 mon_fdset_fd->opaque = g_strdup(opaque);
2190 }
2191 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2192
2193 fdinfo = g_malloc0(sizeof(*fdinfo));
2194 fdinfo->fdset_id = mon_fdset->id;
2195 fdinfo->fd = mon_fdset_fd->fd;
2196
2197 return fdinfo;
2198 }
2199
2200 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2201 {
2202 #ifndef _WIN32
2203 MonFdset *mon_fdset;
2204 MonFdsetFd *mon_fdset_fd;
2205 int mon_fd_flags;
2206
2207 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2208 if (mon_fdset->id != fdset_id) {
2209 continue;
2210 }
2211 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2212 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2213 if (mon_fd_flags == -1) {
2214 return -1;
2215 }
2216
2217 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2218 return mon_fdset_fd->fd;
2219 }
2220 }
2221 errno = EACCES;
2222 return -1;
2223 }
2224 #endif
2225
2226 errno = ENOENT;
2227 return -1;
2228 }
2229
2230 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2231 {
2232 MonFdset *mon_fdset;
2233 MonFdsetFd *mon_fdset_fd_dup;
2234
2235 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2236 if (mon_fdset->id != fdset_id) {
2237 continue;
2238 }
2239 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2240 if (mon_fdset_fd_dup->fd == dup_fd) {
2241 return -1;
2242 }
2243 }
2244 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2245 mon_fdset_fd_dup->fd = dup_fd;
2246 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2247 return 0;
2248 }
2249 return -1;
2250 }
2251
2252 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2253 {
2254 MonFdset *mon_fdset;
2255 MonFdsetFd *mon_fdset_fd_dup;
2256
2257 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2258 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2259 if (mon_fdset_fd_dup->fd == dup_fd) {
2260 if (remove) {
2261 QLIST_REMOVE(mon_fdset_fd_dup, next);
2262 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2263 monitor_fdset_cleanup(mon_fdset);
2264 }
2265 return -1;
2266 } else {
2267 return mon_fdset->id;
2268 }
2269 }
2270 }
2271 }
2272 return -1;
2273 }
2274
2275 int monitor_fdset_dup_fd_find(int dup_fd)
2276 {
2277 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2278 }
2279
2280 void monitor_fdset_dup_fd_remove(int dup_fd)
2281 {
2282 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2283 }
2284
2285 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2286 {
2287 int fd;
2288 Error *local_err = NULL;
2289
2290 if (!qemu_isdigit(fdname[0]) && mon) {
2291 fd = monitor_get_fd(mon, fdname, &local_err);
2292 } else {
2293 fd = qemu_parse_fd(fdname);
2294 if (fd == -1) {
2295 error_setg(&local_err, "Invalid file descriptor number '%s'",
2296 fdname);
2297 }
2298 }
2299 if (local_err) {
2300 error_propagate(errp, local_err);
2301 assert(fd == -1);
2302 } else {
2303 assert(fd != -1);
2304 }
2305
2306 return fd;
2307 }
2308
2309 /* Please update hmp-commands.hx when adding or changing commands */
2310 static mon_cmd_t info_cmds[] = {
2311 #include "hmp-commands-info.h"
2312 { NULL, NULL, },
2313 };
2314
2315 /* mon_cmds and info_cmds would be sorted at runtime */
2316 static mon_cmd_t mon_cmds[] = {
2317 #include "hmp-commands.h"
2318 { NULL, NULL, },
2319 };
2320
2321 /*******************************************************************/
2322
2323 static const char *pch;
2324 static sigjmp_buf expr_env;
2325
2326
2327 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2328 expr_error(Monitor *mon, const char *fmt, ...)
2329 {
2330 va_list ap;
2331 va_start(ap, fmt);
2332 monitor_vprintf(mon, fmt, ap);
2333 monitor_printf(mon, "\n");
2334 va_end(ap);
2335 siglongjmp(expr_env, 1);
2336 }
2337
2338 /* return 0 if OK, -1 if not found */
2339 static int get_monitor_def(target_long *pval, const char *name)
2340 {
2341 const MonitorDef *md = target_monitor_defs();
2342 CPUState *cs = mon_get_cpu();
2343 void *ptr;
2344 uint64_t tmp = 0;
2345 int ret;
2346
2347 if (cs == NULL || md == NULL) {
2348 return -1;
2349 }
2350
2351 for(; md->name != NULL; md++) {
2352 if (compare_cmd(name, md->name)) {
2353 if (md->get_value) {
2354 *pval = md->get_value(md, md->offset);
2355 } else {
2356 CPUArchState *env = mon_get_cpu_env();
2357 ptr = (uint8_t *)env + md->offset;
2358 switch(md->type) {
2359 case MD_I32:
2360 *pval = *(int32_t *)ptr;
2361 break;
2362 case MD_TLONG:
2363 *pval = *(target_long *)ptr;
2364 break;
2365 default:
2366 *pval = 0;
2367 break;
2368 }
2369 }
2370 return 0;
2371 }
2372 }
2373
2374 ret = target_get_monitor_def(cs, name, &tmp);
2375 if (!ret) {
2376 *pval = (target_long) tmp;
2377 }
2378
2379 return ret;
2380 }
2381
2382 static void next(void)
2383 {
2384 if (*pch != '\0') {
2385 pch++;
2386 while (qemu_isspace(*pch))
2387 pch++;
2388 }
2389 }
2390
2391 static int64_t expr_sum(Monitor *mon);
2392
2393 static int64_t expr_unary(Monitor *mon)
2394 {
2395 int64_t n;
2396 char *p;
2397 int ret;
2398
2399 switch(*pch) {
2400 case '+':
2401 next();
2402 n = expr_unary(mon);
2403 break;
2404 case '-':
2405 next();
2406 n = -expr_unary(mon);
2407 break;
2408 case '~':
2409 next();
2410 n = ~expr_unary(mon);
2411 break;
2412 case '(':
2413 next();
2414 n = expr_sum(mon);
2415 if (*pch != ')') {
2416 expr_error(mon, "')' expected");
2417 }
2418 next();
2419 break;
2420 case '\'':
2421 pch++;
2422 if (*pch == '\0')
2423 expr_error(mon, "character constant expected");
2424 n = *pch;
2425 pch++;
2426 if (*pch != '\'')
2427 expr_error(mon, "missing terminating \' character");
2428 next();
2429 break;
2430 case '$':
2431 {
2432 char buf[128], *q;
2433 target_long reg=0;
2434
2435 pch++;
2436 q = buf;
2437 while ((*pch >= 'a' && *pch <= 'z') ||
2438 (*pch >= 'A' && *pch <= 'Z') ||
2439 (*pch >= '0' && *pch <= '9') ||
2440 *pch == '_' || *pch == '.') {
2441 if ((q - buf) < sizeof(buf) - 1)
2442 *q++ = *pch;
2443 pch++;
2444 }
2445 while (qemu_isspace(*pch))
2446 pch++;
2447 *q = 0;
2448 ret = get_monitor_def(&reg, buf);
2449 if (ret < 0)
2450 expr_error(mon, "unknown register");
2451 n = reg;
2452 }
2453 break;
2454 case '\0':
2455 expr_error(mon, "unexpected end of expression");
2456 n = 0;
2457 break;
2458 default:
2459 errno = 0;
2460 n = strtoull(pch, &p, 0);
2461 if (errno == ERANGE) {
2462 expr_error(mon, "number too large");
2463 }
2464 if (pch == p) {
2465 expr_error(mon, "invalid char '%c' in expression", *p);
2466 }
2467 pch = p;
2468 while (qemu_isspace(*pch))
2469 pch++;
2470 break;
2471 }
2472 return n;
2473 }
2474
2475
2476 static int64_t expr_prod(Monitor *mon)
2477 {
2478 int64_t val, val2;
2479 int op;
2480
2481 val = expr_unary(mon);
2482 for(;;) {
2483 op = *pch;
2484 if (op != '*' && op != '/' && op != '%')
2485 break;
2486 next();
2487 val2 = expr_unary(mon);
2488 switch(op) {
2489 default:
2490 case '*':
2491 val *= val2;
2492 break;
2493 case '/':
2494 case '%':
2495 if (val2 == 0)
2496 expr_error(mon, "division by zero");
2497 if (op == '/')
2498 val /= val2;
2499 else
2500 val %= val2;
2501 break;
2502 }
2503 }
2504 return val;
2505 }
2506
2507 static int64_t expr_logic(Monitor *mon)
2508 {
2509 int64_t val, val2;
2510 int op;
2511
2512 val = expr_prod(mon);
2513 for(;;) {
2514 op = *pch;
2515 if (op != '&' && op != '|' && op != '^')
2516 break;
2517 next();
2518 val2 = expr_prod(mon);
2519 switch(op) {
2520 default:
2521 case '&':
2522 val &= val2;
2523 break;
2524 case '|':
2525 val |= val2;
2526 break;
2527 case '^':
2528 val ^= val2;
2529 break;
2530 }
2531 }
2532 return val;
2533 }
2534
2535 static int64_t expr_sum(Monitor *mon)
2536 {
2537 int64_t val, val2;
2538 int op;
2539
2540 val = expr_logic(mon);
2541 for(;;) {
2542 op = *pch;
2543 if (op != '+' && op != '-')
2544 break;
2545 next();
2546 val2 = expr_logic(mon);
2547 if (op == '+')
2548 val += val2;
2549 else
2550 val -= val2;
2551 }
2552 return val;
2553 }
2554
2555 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2556 {
2557 pch = *pp;
2558 if (sigsetjmp(expr_env, 0)) {
2559 *pp = pch;
2560 return -1;
2561 }
2562 while (qemu_isspace(*pch))
2563 pch++;
2564 *pval = expr_sum(mon);
2565 *pp = pch;
2566 return 0;
2567 }
2568
2569 static int get_double(Monitor *mon, double *pval, const char **pp)
2570 {
2571 const char *p = *pp;
2572 char *tailp;
2573 double d;
2574
2575 d = strtod(p, &tailp);
2576 if (tailp == p) {
2577 monitor_printf(mon, "Number expected\n");
2578 return -1;
2579 }
2580 if (d != d || d - d != 0) {
2581 /* NaN or infinity */
2582 monitor_printf(mon, "Bad number\n");
2583 return -1;
2584 }
2585 *pval = d;
2586 *pp = tailp;
2587 return 0;
2588 }
2589
2590 /*
2591 * Store the command-name in cmdname, and return a pointer to
2592 * the remaining of the command string.
2593 */
2594 static const char *get_command_name(const char *cmdline,
2595 char *cmdname, size_t nlen)
2596 {
2597 size_t len;
2598 const char *p, *pstart;
2599
2600 p = cmdline;
2601 while (qemu_isspace(*p))
2602 p++;
2603 if (*p == '\0')
2604 return NULL;
2605 pstart = p;
2606 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2607 p++;
2608 len = p - pstart;
2609 if (len > nlen - 1)
2610 len = nlen - 1;
2611 memcpy(cmdname, pstart, len);
2612 cmdname[len] = '\0';
2613 return p;
2614 }
2615
2616 /**
2617 * Read key of 'type' into 'key' and return the current
2618 * 'type' pointer.
2619 */
2620 static char *key_get_info(const char *type, char **key)
2621 {
2622 size_t len;
2623 char *p, *str;
2624
2625 if (*type == ',')
2626 type++;
2627
2628 p = strchr(type, ':');
2629 if (!p) {
2630 *key = NULL;
2631 return NULL;
2632 }
2633 len = p - type;
2634
2635 str = g_malloc(len + 1);
2636 memcpy(str, type, len);
2637 str[len] = '\0';
2638
2639 *key = str;
2640 return ++p;
2641 }
2642
2643 static int default_fmt_format = 'x';
2644 static int default_fmt_size = 4;
2645
2646 static int is_valid_option(const char *c, const char *typestr)
2647 {
2648 char option[3];
2649
2650 option[0] = '-';
2651 option[1] = *c;
2652 option[2] = '\0';
2653
2654 typestr = strstr(typestr, option);
2655 return (typestr != NULL);
2656 }
2657
2658 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2659 const char *cmdname)
2660 {
2661 const mon_cmd_t *cmd;
2662
2663 for (cmd = disp_table; cmd->name != NULL; cmd++) {
2664 if (compare_cmd(cmdname, cmd->name)) {
2665 return cmd;
2666 }
2667 }
2668
2669 return NULL;
2670 }
2671
2672 /*
2673 * Parse command name from @cmdp according to command table @table.
2674 * If blank, return NULL.
2675 * Else, if no valid command can be found, report to @mon, and return
2676 * NULL.
2677 * Else, change @cmdp to point right behind the name, and return its
2678 * command table entry.
2679 * Do not assume the return value points into @table! It doesn't when
2680 * the command is found in a sub-command table.
2681 */
2682 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2683 const char **cmdp,
2684 mon_cmd_t *table)
2685 {
2686 const char *p;
2687 const mon_cmd_t *cmd;
2688 char cmdname[256];
2689
2690 /* extract the command name */
2691 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
2692 if (!p)
2693 return NULL;
2694
2695 cmd = search_dispatch_table(table, cmdname);
2696 if (!cmd) {
2697 monitor_printf(mon, "unknown command: '%.*s'\n",
2698 (int)(p - *cmdp), *cmdp);
2699 return NULL;
2700 }
2701
2702 /* filter out following useless space */
2703 while (qemu_isspace(*p)) {
2704 p++;
2705 }
2706
2707 *cmdp = p;
2708 /* search sub command */
2709 if (cmd->sub_table != NULL && *p != '\0') {
2710 return monitor_parse_command(mon, cmdp, cmd->sub_table);
2711 }
2712
2713 return cmd;
2714 }
2715
2716 /*
2717 * Parse arguments for @cmd.
2718 * If it can't be parsed, report to @mon, and return NULL.
2719 * Else, insert command arguments into a QDict, and return it.
2720 * Note: On success, caller has to free the QDict structure.
2721 */
2722
2723 static QDict *monitor_parse_arguments(Monitor *mon,
2724 const char **endp,
2725 const mon_cmd_t *cmd)
2726 {
2727 const char *typestr;
2728 char *key;
2729 int c;
2730 const char *p = *endp;
2731 char buf[1024];
2732 QDict *qdict = qdict_new();
2733
2734 /* parse the parameters */
2735 typestr = cmd->args_type;
2736 for(;;) {
2737 typestr = key_get_info(typestr, &key);
2738 if (!typestr)
2739 break;
2740 c = *typestr;
2741 typestr++;
2742 switch(c) {
2743 case 'F':
2744 case 'B':
2745 case 's':
2746 {
2747 int ret;
2748
2749 while (qemu_isspace(*p))
2750 p++;
2751 if (*typestr == '?') {
2752 typestr++;
2753 if (*p == '\0') {
2754 /* no optional string: NULL argument */
2755 break;
2756 }
2757 }
2758 ret = get_str(buf, sizeof(buf), &p);
2759 if (ret < 0) {
2760 switch(c) {
2761 case 'F':
2762 monitor_printf(mon, "%s: filename expected\n",
2763 cmd->name);
2764 break;
2765 case 'B':
2766 monitor_printf(mon, "%s: block device name expected\n",
2767 cmd->name);
2768 break;
2769 default:
2770 monitor_printf(mon, "%s: string expected\n", cmd->name);
2771 break;
2772 }
2773 goto fail;
2774 }
2775 qdict_put(qdict, key, qstring_from_str(buf));
2776 }
2777 break;
2778 case 'O':
2779 {
2780 QemuOptsList *opts_list;
2781 QemuOpts *opts;
2782
2783 opts_list = qemu_find_opts(key);
2784 if (!opts_list || opts_list->desc->name) {
2785 goto bad_type;
2786 }
2787 while (qemu_isspace(*p)) {
2788 p++;
2789 }
2790 if (!*p)
2791 break;
2792 if (get_str(buf, sizeof(buf), &p) < 0) {
2793 goto fail;
2794 }
2795 opts = qemu_opts_parse_noisily(opts_list, buf, true);
2796 if (!opts) {
2797 goto fail;
2798 }
2799 qemu_opts_to_qdict(opts, qdict);
2800 qemu_opts_del(opts);
2801 }
2802 break;
2803 case '/':
2804 {
2805 int count, format, size;
2806
2807 while (qemu_isspace(*p))
2808 p++;
2809 if (*p == '/') {
2810 /* format found */
2811 p++;
2812 count = 1;
2813 if (qemu_isdigit(*p)) {
2814 count = 0;
2815 while (qemu_isdigit(*p)) {
2816 count = count * 10 + (*p - '0');
2817 p++;
2818 }
2819 }
2820 size = -1;
2821 format = -1;
2822 for(;;) {
2823 switch(*p) {
2824 case 'o':
2825 case 'd':
2826 case 'u':
2827 case 'x':
2828 case 'i':
2829 case 'c':
2830 format = *p++;
2831 break;
2832 case 'b':
2833 size = 1;
2834 p++;
2835 break;
2836 case 'h':
2837 size = 2;
2838 p++;
2839 break;
2840 case 'w':
2841 size = 4;
2842 p++;
2843 break;
2844 case 'g':
2845 case 'L':
2846 size = 8;
2847 p++;
2848 break;
2849 default:
2850 goto next;
2851 }
2852 }
2853 next:
2854 if (*p != '\0' && !qemu_isspace(*p)) {
2855 monitor_printf(mon, "invalid char in format: '%c'\n",
2856 *p);
2857 goto fail;
2858 }
2859 if (format < 0)
2860 format = default_fmt_format;
2861 if (format != 'i') {
2862 /* for 'i', not specifying a size gives -1 as size */
2863 if (size < 0)
2864 size = default_fmt_size;
2865 default_fmt_size = size;
2866 }
2867 default_fmt_format = format;
2868 } else {
2869 count = 1;
2870 format = default_fmt_format;
2871 if (format != 'i') {
2872 size = default_fmt_size;
2873 } else {
2874 size = -1;
2875 }
2876 }
2877 qdict_put(qdict, "count", qint_from_int(count));
2878 qdict_put(qdict, "format", qint_from_int(format));
2879 qdict_put(qdict, "size", qint_from_int(size));
2880 }
2881 break;
2882 case 'i':
2883 case 'l':
2884 case 'M':
2885 {
2886 int64_t val;
2887
2888 while (qemu_isspace(*p))
2889 p++;
2890 if (*typestr == '?' || *typestr == '.') {
2891 if (*typestr == '?') {
2892 if (*p == '\0') {
2893 typestr++;
2894 break;
2895 }
2896 } else {
2897 if (*p == '.') {
2898 p++;
2899 while (qemu_isspace(*p))
2900 p++;
2901 } else {
2902 typestr++;
2903 break;
2904 }
2905 }
2906 typestr++;
2907 }
2908 if (get_expr(mon, &val, &p))
2909 goto fail;
2910 /* Check if 'i' is greater than 32-bit */
2911 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2912 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
2913 monitor_printf(mon, "integer is for 32-bit values\n");
2914 goto fail;
2915 } else if (c == 'M') {
2916 if (val < 0) {
2917 monitor_printf(mon, "enter a positive value\n");
2918 goto fail;
2919 }
2920 val <<= 20;
2921 }
2922 qdict_put(qdict, key, qint_from_int(val));
2923 }
2924 break;
2925 case 'o':
2926 {
2927 int ret;
2928 uint64_t val;
2929 char *end;
2930
2931 while (qemu_isspace(*p)) {
2932 p++;
2933 }
2934 if (*typestr == '?') {
2935 typestr++;
2936 if (*p == '\0') {
2937 break;
2938 }
2939 }
2940 ret = qemu_strtosz_MiB(p, &end, &val);
2941 if (ret < 0 || val > INT64_MAX) {
2942 monitor_printf(mon, "invalid size\n");
2943 goto fail;
2944 }
2945 qdict_put(qdict, key, qint_from_int(val));
2946 p = end;
2947 }
2948 break;
2949 case 'T':
2950 {
2951 double val;
2952
2953 while (qemu_isspace(*p))
2954 p++;
2955 if (*typestr == '?') {
2956 typestr++;
2957 if (*p == '\0') {
2958 break;
2959 }
2960 }
2961 if (get_double(mon, &val, &p) < 0) {
2962 goto fail;
2963 }
2964 if (p[0] && p[1] == 's') {
2965 switch (*p) {
2966 case 'm':
2967 val /= 1e3; p += 2; break;
2968 case 'u':
2969 val /= 1e6; p += 2; break;
2970 case 'n':
2971 val /= 1e9; p += 2; break;
2972 }
2973 }
2974 if (*p && !qemu_isspace(*p)) {
2975 monitor_printf(mon, "Unknown unit suffix\n");
2976 goto fail;
2977 }
2978 qdict_put(qdict, key, qfloat_from_double(val));
2979 }
2980 break;
2981 case 'b':
2982 {
2983 const char *beg;
2984 bool val;
2985
2986 while (qemu_isspace(*p)) {
2987 p++;
2988 }
2989 beg = p;
2990 while (qemu_isgraph(*p)) {
2991 p++;
2992 }
2993 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
2994 val = true;
2995 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
2996 val = false;
2997 } else {
2998 monitor_printf(mon, "Expected 'on' or 'off'\n");
2999 goto fail;
3000 }
3001 qdict_put(qdict, key, qbool_from_bool(val));
3002 }
3003 break;
3004 case '-':
3005 {
3006 const char *tmp = p;
3007 int skip_key = 0;
3008 /* option */
3009
3010 c = *typestr++;
3011 if (c == '\0')
3012 goto bad_type;
3013 while (qemu_isspace(*p))
3014 p++;
3015 if (*p == '-') {
3016 p++;
3017 if(c != *p) {
3018 if(!is_valid_option(p, typestr)) {
3019
3020 monitor_printf(mon, "%s: unsupported option -%c\n",
3021 cmd->name, *p);
3022 goto fail;
3023 } else {
3024 skip_key = 1;
3025 }
3026 }
3027 if(skip_key) {
3028 p = tmp;
3029 } else {
3030 /* has option */
3031 p++;
3032 qdict_put(qdict, key, qbool_from_bool(true));
3033 }
3034 }
3035 }
3036 break;
3037 case 'S':
3038 {
3039 /* package all remaining string */
3040 int len;
3041
3042 while (qemu_isspace(*p)) {
3043 p++;
3044 }
3045 if (*typestr == '?') {
3046 typestr++;
3047 if (*p == '\0') {
3048 /* no remaining string: NULL argument */
3049 break;
3050 }
3051 }
3052 len = strlen(p);
3053 if (len <= 0) {
3054 monitor_printf(mon, "%s: string expected\n",
3055 cmd->name);
3056 goto fail;
3057 }
3058 qdict_put(qdict, key, qstring_from_str(p));
3059 p += len;
3060 }
3061 break;
3062 default:
3063 bad_type:
3064 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3065 goto fail;
3066 }
3067 g_free(key);
3068 key = NULL;
3069 }
3070 /* check that all arguments were parsed */
3071 while (qemu_isspace(*p))
3072 p++;
3073 if (*p != '\0') {
3074 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3075 cmd->name);
3076 goto fail;
3077 }
3078
3079 return qdict;
3080
3081 fail:
3082 QDECREF(qdict);
3083 g_free(key);
3084 return NULL;
3085 }
3086
3087 static void handle_hmp_command(Monitor *mon, const char *cmdline)
3088 {
3089 QDict *qdict;
3090 const mon_cmd_t *cmd;
3091
3092 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
3093 if (!cmd) {
3094 return;
3095 }
3096
3097 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
3098 if (!qdict) {
3099 monitor_printf(mon, "Try \"help %s\" for more information\n",
3100 cmd->name);
3101 return;
3102 }
3103
3104 cmd->cmd(mon, qdict);
3105 QDECREF(qdict);
3106 }
3107
3108 static void cmd_completion(Monitor *mon, const char *name, const char *list)
3109 {
3110 const char *p, *pstart;
3111 char cmd[128];
3112 int len;
3113
3114 p = list;
3115 for(;;) {
3116 pstart = p;
3117 p = strchr(p, '|');
3118 if (!p)
3119 p = pstart + strlen(pstart);
3120 len = p - pstart;
3121 if (len > sizeof(cmd) - 2)
3122 len = sizeof(cmd) - 2;
3123 memcpy(cmd, pstart, len);
3124 cmd[len] = '\0';
3125 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3126 readline_add_completion(mon->rs, cmd);
3127 }
3128 if (*p == '\0')
3129 break;
3130 p++;
3131 }
3132 }
3133
3134 static void file_completion(Monitor *mon, const char *input)
3135 {
3136 DIR *ffs;
3137 struct dirent *d;
3138 char path[1024];
3139 char file[1024], file_prefix[1024];
3140 int input_path_len;
3141 const char *p;
3142
3143 p = strrchr(input, '/');
3144 if (!p) {
3145 input_path_len = 0;
3146 pstrcpy(file_prefix, sizeof(file_prefix), input);
3147 pstrcpy(path, sizeof(path), ".");
3148 } else {
3149 input_path_len = p - input + 1;
3150 memcpy(path, input, input_path_len);
3151 if (input_path_len > sizeof(path) - 1)
3152 input_path_len = sizeof(path) - 1;
3153 path[input_path_len] = '\0';
3154 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3155 }
3156
3157 ffs = opendir(path);
3158 if (!ffs)
3159 return;
3160 for(;;) {
3161 struct stat sb;
3162 d = readdir(ffs);
3163 if (!d)
3164 break;
3165
3166 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3167 continue;
3168 }
3169
3170 if (strstart(d->d_name, file_prefix, NULL)) {
3171 memcpy(file, input, input_path_len);
3172 if (input_path_len < sizeof(file))
3173 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3174 d->d_name);
3175 /* stat the file to find out if it's a directory.
3176 * In that case add a slash to speed up typing long paths
3177 */
3178 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3179 pstrcat(file, sizeof(file), "/");
3180 }
3181 readline_add_completion(mon->rs, file);
3182 }
3183 }
3184 closedir(ffs);
3185 }
3186
3187 static const char *next_arg_type(const char *typestr)
3188 {
3189 const char *p = strchr(typestr, ':');
3190 return (p != NULL ? ++p : typestr);
3191 }
3192
3193 static void add_completion_option(ReadLineState *rs, const char *str,
3194 const char *option)
3195 {
3196 if (!str || !option) {
3197 return;
3198 }
3199 if (!strncmp(option, str, strlen(str))) {
3200 readline_add_completion(rs, option);
3201 }
3202 }
3203
3204 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3205 {
3206 size_t len;
3207 ChardevBackendInfoList *list, *start;
3208
3209 if (nb_args != 2) {
3210 return;
3211 }
3212 len = strlen(str);
3213 readline_set_completion_index(rs, len);
3214
3215 start = list = qmp_query_chardev_backends(NULL);
3216 while (list) {
3217 const char *chr_name = list->value->name;
3218
3219 if (!strncmp(chr_name, str, len)) {
3220 readline_add_completion(rs, chr_name);
3221 }
3222 list = list->next;
3223 }
3224 qapi_free_ChardevBackendInfoList(start);
3225 }
3226
3227 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3228 {
3229 size_t len;
3230 int i;
3231
3232 if (nb_args != 2) {
3233 return;
3234 }
3235 len = strlen(str);
3236 readline_set_completion_index(rs, len);
3237 for (i = 0; NetClientDriver_lookup[i]; i++) {
3238 add_completion_option(rs, str, NetClientDriver_lookup[i]);
3239 }
3240 }
3241
3242 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3243 {
3244 GSList *list, *elt;
3245 size_t len;
3246
3247 if (nb_args != 2) {
3248 return;
3249 }
3250
3251 len = strlen(str);
3252 readline_set_completion_index(rs, len);
3253 list = elt = object_class_get_list(TYPE_DEVICE, false);
3254 while (elt) {
3255 const char *name;
3256 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3257 TYPE_DEVICE);
3258 name = object_class_get_name(OBJECT_CLASS(dc));
3259
3260 if (!dc->cannot_instantiate_with_device_add_yet
3261 && !strncmp(name, str, len)) {
3262 readline_add_completion(rs, name);
3263 }
3264 elt = elt->next;
3265 }
3266 g_slist_free(list);
3267 }
3268
3269 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3270 {
3271 GSList *list, *elt;
3272 size_t len;
3273
3274 if (nb_args != 2) {
3275 return;
3276 }
3277
3278 len = strlen(str);
3279 readline_set_completion_index(rs, len);
3280 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3281 while (elt) {
3282 const char *name;
3283
3284 name = object_class_get_name(OBJECT_CLASS(elt->data));
3285 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3286 readline_add_completion(rs, name);
3287 }
3288 elt = elt->next;
3289 }
3290 g_slist_free(list);
3291 }
3292
3293 static void peripheral_device_del_completion(ReadLineState *rs,
3294 const char *str, size_t len)
3295 {
3296 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3297 GSList *list, *item;
3298
3299 list = qdev_build_hotpluggable_device_list(peripheral);
3300 if (!list) {
3301 return;
3302 }
3303
3304 for (item = list; item; item = g_slist_next(item)) {
3305 DeviceState *dev = item->data;
3306
3307 if (dev->id && !strncmp(str, dev->id, len)) {
3308 readline_add_completion(rs, dev->id);
3309 }
3310 }
3311
3312 g_slist_free(list);
3313 }
3314
3315 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3316 {
3317 size_t len;
3318 ChardevInfoList *list, *start;
3319
3320 if (nb_args != 2) {
3321 return;
3322 }
3323 len = strlen(str);
3324 readline_set_completion_index(rs, len);
3325
3326 start = list = qmp_query_chardev(NULL);
3327 while (list) {
3328 ChardevInfo *chr = list->value;
3329
3330 if (!strncmp(chr->label, str, len)) {
3331 readline_add_completion(rs, chr->label);
3332 }
3333 list = list->next;
3334 }
3335 qapi_free_ChardevInfoList(start);
3336 }
3337
3338 static void ringbuf_completion(ReadLineState *rs, const char *str)
3339 {
3340 size_t len;
3341 ChardevInfoList *list, *start;
3342
3343 len = strlen(str);
3344 readline_set_completion_index(rs, len);
3345
3346 start = list = qmp_query_chardev(NULL);
3347 while (list) {
3348 ChardevInfo *chr_info = list->value;
3349
3350 if (!strncmp(chr_info->label, str, len)) {
3351 Chardev *chr = qemu_chr_find(chr_info->label);
3352 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3353 readline_add_completion(rs, chr_info->label);
3354 }
3355 }
3356 list = list->next;
3357 }
3358 qapi_free_ChardevInfoList(start);
3359 }
3360
3361 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3362 {
3363 if (nb_args != 2) {
3364 return;
3365 }
3366 ringbuf_completion(rs, str);
3367 }
3368
3369 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3370 {
3371 size_t len;
3372
3373 if (nb_args != 2) {
3374 return;
3375 }
3376
3377 len = strlen(str);
3378 readline_set_completion_index(rs, len);
3379 peripheral_device_del_completion(rs, str, len);
3380 }
3381
3382 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3383 {
3384 ObjectPropertyInfoList *list, *start;
3385 size_t len;
3386
3387 if (nb_args != 2) {
3388 return;
3389 }
3390 len = strlen(str);
3391 readline_set_completion_index(rs, len);
3392
3393 start = list = qmp_qom_list("/objects", NULL);
3394 while (list) {
3395 ObjectPropertyInfo *info = list->value;
3396
3397 if (!strncmp(info->type, "child<", 5)
3398 && !strncmp(info->name, str, len)) {
3399 readline_add_completion(rs, info->name);
3400 }
3401 list = list->next;
3402 }
3403 qapi_free_ObjectPropertyInfoList(start);
3404 }
3405
3406 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3407 {
3408 int i;
3409 char *sep;
3410 size_t len;
3411
3412 if (nb_args != 2) {
3413 return;
3414 }
3415 sep = strrchr(str, '-');
3416 if (sep) {
3417 str = sep + 1;
3418 }
3419 len = strlen(str);
3420 readline_set_completion_index(rs, len);
3421 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3422 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3423 readline_add_completion(rs, QKeyCode_lookup[i]);
3424 }
3425 }
3426 }
3427
3428 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3429 {
3430 size_t len;
3431
3432 len = strlen(str);
3433 readline_set_completion_index(rs, len);
3434 if (nb_args == 2) {
3435 NetClientState *ncs[MAX_QUEUE_NUM];
3436 int count, i;
3437 count = qemu_find_net_clients_except(NULL, ncs,