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