OSDN Git Service

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