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