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