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