OSDN Git Service

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