OSDN Git Service

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