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