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