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