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