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