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