e605822445cfcfccce08fd5bf42c9c24e3012d4d
[sdk/emulator/qemu.git] / monitor.c
1 /*
2  * QEMU monitor
3  *
4  * Copyright (c) 2003-2004 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include <dirent.h>
25 #include "hw/hw.h"
26 #include "monitor/qdev.h"
27 #include "hw/usb.h"
28 #include "hw/pcmcia.h"
29 #include "hw/i386/pc.h"
30 #include "hw/pci/pci.h"
31 #include "sysemu/watchdog.h"
32 #include "hw/loader.h"
33 #include "exec/gdbstub.h"
34 #include "net/net.h"
35 #include "net/slirp.h"
36 #include "char/char.h"
37 #include "ui/qemu-spice.h"
38 #include "sysemu/sysemu.h"
39 #include "monitor/monitor.h"
40 #include "monitor/readline.h"
41 #include "ui/console.h"
42 #include "sysemu/blockdev.h"
43 #include "audio/audio.h"
44 #include "disas/disas.h"
45 #include "sysemu/balloon.h"
46 #include "qemu/timer.h"
47 #include "migration/migration.h"
48 #include "sysemu/kvm.h"
49 #include "qemu/acl.h"
50 #include "sysemu/tpm.h"
51 #include "qapi/qmp/qint.h"
52 #include "qapi/qmp/qfloat.h"
53 #include "qapi/qmp/qlist.h"
54 #include "qapi/qmp/qbool.h"
55 #include "qapi/qmp/qstring.h"
56 #include "qapi/qmp/qjson.h"
57 #include "qapi/qmp/json-streamer.h"
58 #include "qapi/qmp/json-parser.h"
59 #include "qemu/osdep.h"
60 #include "cpu.h"
61 #include "trace.h"
62 #include "trace/control.h"
63 #ifdef CONFIG_TRACE_SIMPLE
64 #include "trace/simple.h"
65 #endif
66 #include "ui/qemu-spice.h"
67 #include "exec/memory.h"
68 #include "qmp-commands.h"
69 #include "hmp.h"
70 #include "qemu/thread.h"
71
72 /* for pic/irq_info */
73 #if defined(TARGET_SPARC)
74 #include "hw/sparc/sun4m.h"
75 #endif
76 #include "hw/lm32/lm32_pic.h"
77
78 //#define DEBUG
79 //#define DEBUG_COMPLETION
80
81 /*
82  * Supported types:
83  *
84  * 'F'          filename
85  * 'B'          block device name
86  * 's'          string (accept optional quote)
87  * 'O'          option string of the form NAME=VALUE,...
88  *              parsed according to QemuOptsList given by its name
89  *              Example: 'device:O' uses qemu_device_opts.
90  *              Restriction: only lists with empty desc are supported
91  *              TODO lift the restriction
92  * 'i'          32 bit integer
93  * 'l'          target long (32 or 64 bit)
94  * 'M'          Non-negative target long (32 or 64 bit), in user mode the
95  *              value is multiplied by 2^20 (think Mebibyte)
96  * 'o'          octets (aka bytes)
97  *              user mode accepts an optional T, t, G, g, M, m, K, k
98  *              suffix, which multiplies the value by 2^40 for
99  *              suffixes T and t, 2^30 for suffixes G and g, 2^20 for
100  *              M and m, 2^10 for K and k
101  * 'T'          double
102  *              user mode accepts an optional ms, us, ns suffix,
103  *              which divides the value by 1e3, 1e6, 1e9, respectively
104  * '/'          optional gdb-like print format (like "/10x")
105  *
106  * '?'          optional type (for all types, except '/')
107  * '.'          other form of optional type (for 'i' and 'l')
108  * 'b'          boolean
109  *              user mode accepts "on" or "off"
110  * '-'          optional parameter (eg. '-f')
111  *
112  */
113
114 typedef struct MonitorCompletionData MonitorCompletionData;
115 struct MonitorCompletionData {
116     Monitor *mon;
117     void (*user_print)(Monitor *mon, const QObject *data);
118 };
119
120 typedef struct mon_cmd_t {
121     const char *name;
122     const char *args_type;
123     const char *params;
124     const char *help;
125     void (*user_print)(Monitor *mon, const QObject *data);
126     union {
127         void (*cmd)(Monitor *mon, const QDict *qdict);
128         int  (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data);
129         int  (*cmd_async)(Monitor *mon, const QDict *params,
130                           MonitorCompletion *cb, void *opaque);
131     } mhandler;
132     int flags;
133     /* @sub_table is a list of 2nd level of commands. If it do not exist,
134      * mhandler should be used. If it exist, sub_table[?].mhandler should be
135      * used, and mhandler of 1st level plays the role of help function.
136      */
137     struct mon_cmd_t *sub_table;
138 } mon_cmd_t;
139
140 /* file descriptors passed via SCM_RIGHTS */
141 typedef struct mon_fd_t mon_fd_t;
142 struct mon_fd_t {
143     char *name;
144     int fd;
145     QLIST_ENTRY(mon_fd_t) next;
146 };
147
148 /* file descriptor associated with a file descriptor set */
149 typedef struct MonFdsetFd MonFdsetFd;
150 struct MonFdsetFd {
151     int fd;
152     bool removed;
153     char *opaque;
154     QLIST_ENTRY(MonFdsetFd) next;
155 };
156
157 /* file descriptor set containing fds passed via SCM_RIGHTS */
158 typedef struct MonFdset MonFdset;
159 struct MonFdset {
160     int64_t id;
161     QLIST_HEAD(, MonFdsetFd) fds;
162     QLIST_HEAD(, MonFdsetFd) dup_fds;
163     QLIST_ENTRY(MonFdset) next;
164 };
165
166 typedef struct MonitorControl {
167     QObject *id;
168     JSONMessageParser parser;
169     int command_mode;
170 } MonitorControl;
171
172 /*
173  * To prevent flooding clients, events can be throttled. The
174  * throttling is calculated globally, rather than per-Monitor
175  * instance.
176  */
177 typedef struct MonitorEventState {
178     MonitorEvent event; /* Event being tracked */
179     int64_t rate;       /* Period over which to throttle. 0 to disable */
180     int64_t last;       /* Time at which event was last emitted */
181     QEMUTimer *timer;   /* Timer for handling delayed events */
182     QObject *data;      /* Event pending delayed dispatch */
183 } MonitorEventState;
184
185 struct Monitor {
186     CharDriverState *chr;
187     int mux_out;
188     int reset_seen;
189     int flags;
190     int suspend_cnt;
191     bool skip_flush;
192     QString *outbuf;
193     ReadLineState *rs;
194     MonitorControl *mc;
195     CPUArchState *mon_cpu;
196     BlockDriverCompletionFunc *password_completion_cb;
197     void *password_opaque;
198     QError *error;
199     QLIST_HEAD(,mon_fd_t) fds;
200     QLIST_ENTRY(Monitor) entry;
201 };
202
203 /* QMP checker flags */
204 #define QMP_ACCEPT_UNKNOWNS 1
205
206 static QLIST_HEAD(mon_list, Monitor) mon_list;
207 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
208 static int mon_refcount;
209
210 static mon_cmd_t mon_cmds[];
211 static mon_cmd_t info_cmds[];
212
213 static const mon_cmd_t qmp_cmds[];
214
215 Monitor *cur_mon;
216 Monitor *default_mon;
217
218 static void monitor_command_cb(Monitor *mon, const char *cmdline,
219                                void *opaque);
220
221 static inline int qmp_cmd_mode(const Monitor *mon)
222 {
223     return (mon->mc ? mon->mc->command_mode : 0);
224 }
225
226 /* Return true if in control mode, false otherwise */
227 static inline int monitor_ctrl_mode(const Monitor *mon)
228 {
229     return (mon->flags & MONITOR_USE_CONTROL);
230 }
231
232 /* Return non-zero iff we have a current monitor, and it is in QMP mode.  */
233 int monitor_cur_is_qmp(void)
234 {
235     return cur_mon && monitor_ctrl_mode(cur_mon);
236 }
237
238 void monitor_read_command(Monitor *mon, int show_prompt)
239 {
240     if (!mon->rs)
241         return;
242
243     readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
244     if (show_prompt)
245         readline_show_prompt(mon->rs);
246 }
247
248 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
249                           void *opaque)
250 {
251     if (monitor_ctrl_mode(mon)) {
252         qerror_report(QERR_MISSING_PARAMETER, "password");
253         return -EINVAL;
254     } else if (mon->rs) {
255         readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
256         /* prompt is printed on return from the command handler */
257         return 0;
258     } else {
259         monitor_printf(mon, "terminal does not support password prompting\n");
260         return -ENOTTY;
261     }
262 }
263
264 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
265                                   void *opaque)
266 {
267     monitor_flush(opaque);
268     return FALSE;
269 }
270
271 void monitor_flush(Monitor *mon)
272 {
273     int rc;
274     size_t len;
275     const char *buf;
276
277     if (mon->skip_flush) {
278         return;
279     }
280
281     buf = qstring_get_str(mon->outbuf);
282     len = qstring_get_length(mon->outbuf);
283
284     if (mon && len && !mon->mux_out) {
285         rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
286         if (rc == len) {
287             /* all flushed */
288             QDECREF(mon->outbuf);
289             mon->outbuf = qstring_new();
290             return;
291         }
292         if (rc > 0) {
293             /* partinal write */
294             QString *tmp = qstring_from_str(buf + rc);
295             QDECREF(mon->outbuf);
296             mon->outbuf = tmp;
297         }
298         qemu_chr_fe_add_watch(mon->chr, G_IO_OUT, monitor_unblocked, mon);
299     }
300 }
301
302 /* flush at every end of line */
303 static void monitor_puts(Monitor *mon, const char *str)
304 {
305     char c;
306
307     for(;;) {
308         c = *str++;
309         if (c == '\0')
310             break;
311         if (c == '\n') {
312             qstring_append_chr(mon->outbuf, '\r');
313         }
314         qstring_append_chr(mon->outbuf, c);
315         if (c == '\n') {
316             monitor_flush(mon);
317         }
318     }
319 }
320
321 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
322 {
323     char *buf;
324
325     if (!mon)
326         return;
327
328     if (monitor_ctrl_mode(mon)) {
329         return;
330     }
331
332     buf = g_strdup_vprintf(fmt, ap);
333     monitor_puts(mon, buf);
334     g_free(buf);
335 }
336
337 void monitor_printf(Monitor *mon, const char *fmt, ...)
338 {
339     va_list ap;
340     va_start(ap, fmt);
341     monitor_vprintf(mon, fmt, ap);
342     va_end(ap);
343 }
344
345 void monitor_print_filename(Monitor *mon, const char *filename)
346 {
347     int i;
348
349     for (i = 0; filename[i]; i++) {
350         switch (filename[i]) {
351         case ' ':
352         case '"':
353         case '\\':
354             monitor_printf(mon, "\\%c", filename[i]);
355             break;
356         case '\t':
357             monitor_printf(mon, "\\t");
358             break;
359         case '\r':
360             monitor_printf(mon, "\\r");
361             break;
362         case '\n':
363             monitor_printf(mon, "\\n");
364             break;
365         default:
366             monitor_printf(mon, "%c", filename[i]);
367             break;
368         }
369     }
370 }
371
372 static int GCC_FMT_ATTR(2, 3) monitor_fprintf(FILE *stream,
373                                               const char *fmt, ...)
374 {
375     va_list ap;
376     va_start(ap, fmt);
377     monitor_vprintf((Monitor *)stream, fmt, ap);
378     va_end(ap);
379     return 0;
380 }
381
382 static void monitor_user_noop(Monitor *mon, const QObject *data) { }
383
384 static inline int handler_is_qobject(const mon_cmd_t *cmd)
385 {
386     return cmd->user_print != NULL;
387 }
388
389 static inline bool handler_is_async(const mon_cmd_t *cmd)
390 {
391     return cmd->flags & MONITOR_CMD_ASYNC;
392 }
393
394 static inline int monitor_has_error(const Monitor *mon)
395 {
396     return mon->error != NULL;
397 }
398
399 static void monitor_json_emitter(Monitor *mon, const QObject *data)
400 {
401     QString *json;
402
403     json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
404                                              qobject_to_json(data);
405     assert(json != NULL);
406
407     qstring_append_chr(json, '\n');
408     monitor_puts(mon, qstring_get_str(json));
409
410     QDECREF(json);
411 }
412
413 static QDict *build_qmp_error_dict(const QError *err)
414 {
415     QObject *obj;
416
417     obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %p } }",
418                              ErrorClass_lookup[err->err_class],
419                              qerror_human(err));
420
421     return qobject_to_qdict(obj);
422 }
423
424 static void monitor_protocol_emitter(Monitor *mon, QObject *data)
425 {
426     QDict *qmp;
427
428     trace_monitor_protocol_emitter(mon);
429
430     if (!monitor_has_error(mon)) {
431         /* success response */
432         qmp = qdict_new();
433         if (data) {
434             qobject_incref(data);
435             qdict_put_obj(qmp, "return", data);
436         } else {
437             /* return an empty QDict by default */
438             qdict_put(qmp, "return", qdict_new());
439         }
440     } else {
441         /* error response */
442         qmp = build_qmp_error_dict(mon->error);
443         QDECREF(mon->error);
444         mon->error = NULL;
445     }
446
447     if (mon->mc->id) {
448         qdict_put_obj(qmp, "id", mon->mc->id);
449         mon->mc->id = NULL;
450     }
451
452     monitor_json_emitter(mon, QOBJECT(qmp));
453     QDECREF(qmp);
454 }
455
456 static void timestamp_put(QDict *qdict)
457 {
458     int err;
459     QObject *obj;
460     qemu_timeval tv;
461
462     err = qemu_gettimeofday(&tv);
463     if (err < 0)
464         return;
465
466     obj = qobject_from_jsonf("{ 'seconds': %" PRId64 ", "
467                                 "'microseconds': %" PRId64 " }",
468                                 (int64_t) tv.tv_sec, (int64_t) tv.tv_usec);
469     qdict_put_obj(qdict, "timestamp", obj);
470 }
471
472
473 static const char *monitor_event_names[] = {
474     [QEVENT_SHUTDOWN] = "SHUTDOWN",
475     [QEVENT_RESET] = "RESET",
476     [QEVENT_POWERDOWN] = "POWERDOWN",
477     [QEVENT_STOP] = "STOP",
478     [QEVENT_RESUME] = "RESUME",
479     [QEVENT_VNC_CONNECTED] = "VNC_CONNECTED",
480     [QEVENT_VNC_INITIALIZED] = "VNC_INITIALIZED",
481     [QEVENT_VNC_DISCONNECTED] = "VNC_DISCONNECTED",
482     [QEVENT_BLOCK_IO_ERROR] = "BLOCK_IO_ERROR",
483     [QEVENT_RTC_CHANGE] = "RTC_CHANGE",
484     [QEVENT_WATCHDOG] = "WATCHDOG",
485     [QEVENT_SPICE_CONNECTED] = "SPICE_CONNECTED",
486     [QEVENT_SPICE_INITIALIZED] = "SPICE_INITIALIZED",
487     [QEVENT_SPICE_DISCONNECTED] = "SPICE_DISCONNECTED",
488     [QEVENT_BLOCK_JOB_COMPLETED] = "BLOCK_JOB_COMPLETED",
489     [QEVENT_BLOCK_JOB_CANCELLED] = "BLOCK_JOB_CANCELLED",
490     [QEVENT_BLOCK_JOB_ERROR] = "BLOCK_JOB_ERROR",
491     [QEVENT_BLOCK_JOB_READY] = "BLOCK_JOB_READY",
492     [QEVENT_DEVICE_DELETED] = "DEVICE_DELETED",
493     [QEVENT_DEVICE_TRAY_MOVED] = "DEVICE_TRAY_MOVED",
494     [QEVENT_SUSPEND] = "SUSPEND",
495     [QEVENT_SUSPEND_DISK] = "SUSPEND_DISK",
496     [QEVENT_WAKEUP] = "WAKEUP",
497     [QEVENT_BALLOON_CHANGE] = "BALLOON_CHANGE",
498     [QEVENT_SPICE_MIGRATE_COMPLETED] = "SPICE_MIGRATE_COMPLETED",
499 };
500 QEMU_BUILD_BUG_ON(ARRAY_SIZE(monitor_event_names) != QEVENT_MAX)
501
502 MonitorEventState monitor_event_state[QEVENT_MAX];
503 QemuMutex monitor_event_state_lock;
504
505 /*
506  * Emits the event to every monitor instance
507  */
508 static void
509 monitor_protocol_event_emit(MonitorEvent event,
510                             QObject *data)
511 {
512     Monitor *mon;
513
514     trace_monitor_protocol_event_emit(event, data);
515     QLIST_FOREACH(mon, &mon_list, entry) {
516         if (monitor_ctrl_mode(mon) && qmp_cmd_mode(mon)) {
517             monitor_json_emitter(mon, data);
518         }
519     }
520 }
521
522
523 /*
524  * Queue a new event for emission to Monitor instances,
525  * applying any rate limiting if required.
526  */
527 static void
528 monitor_protocol_event_queue(MonitorEvent event,
529                              QObject *data)
530 {
531     MonitorEventState *evstate;
532     int64_t now = qemu_get_clock_ns(rt_clock);
533     assert(event < QEVENT_MAX);
534
535     qemu_mutex_lock(&monitor_event_state_lock);
536     evstate = &(monitor_event_state[event]);
537     trace_monitor_protocol_event_queue(event,
538                                        data,
539                                        evstate->rate,
540                                        evstate->last,
541                                        now);
542
543     /* Rate limit of 0 indicates no throttling */
544     if (!evstate->rate) {
545         monitor_protocol_event_emit(event, data);
546         evstate->last = now;
547     } else {
548         int64_t delta = now - evstate->last;
549         if (evstate->data ||
550             delta < evstate->rate) {
551             /* If there's an existing event pending, replace
552              * it with the new event, otherwise schedule a
553              * timer for delayed emission
554              */
555             if (evstate->data) {
556                 qobject_decref(evstate->data);
557             } else {
558                 int64_t then = evstate->last + evstate->rate;
559                 qemu_mod_timer_ns(evstate->timer, then);
560             }
561             evstate->data = data;
562             qobject_incref(evstate->data);
563         } else {
564             monitor_protocol_event_emit(event, data);
565             evstate->last = now;
566         }
567     }
568     qemu_mutex_unlock(&monitor_event_state_lock);
569 }
570
571
572 /*
573  * The callback invoked by QemuTimer when a delayed
574  * event is ready to be emitted
575  */
576 static void monitor_protocol_event_handler(void *opaque)
577 {
578     MonitorEventState *evstate = opaque;
579     int64_t now = qemu_get_clock_ns(rt_clock);
580
581     qemu_mutex_lock(&monitor_event_state_lock);
582
583     trace_monitor_protocol_event_handler(evstate->event,
584                                          evstate->data,
585                                          evstate->last,
586                                          now);
587     if (evstate->data) {
588         monitor_protocol_event_emit(evstate->event, evstate->data);
589         qobject_decref(evstate->data);
590         evstate->data = NULL;
591     }
592     evstate->last = now;
593     qemu_mutex_unlock(&monitor_event_state_lock);
594 }
595
596
597 /*
598  * @event: the event ID to be limited
599  * @rate: the rate limit in milliseconds
600  *
601  * Sets a rate limit on a particular event, so no
602  * more than 1 event will be emitted within @rate
603  * milliseconds
604  */
605 static void
606 monitor_protocol_event_throttle(MonitorEvent event,
607                                 int64_t rate)
608 {
609     MonitorEventState *evstate;
610     assert(event < QEVENT_MAX);
611
612     evstate = &(monitor_event_state[event]);
613
614     trace_monitor_protocol_event_throttle(event, rate);
615     evstate->event = event;
616     evstate->rate = rate * SCALE_MS;
617     evstate->timer = qemu_new_timer(rt_clock,
618                                     SCALE_MS,
619                                     monitor_protocol_event_handler,
620                                     evstate);
621     evstate->last = 0;
622     evstate->data = NULL;
623 }
624
625
626 /* Global, one-time initializer to configure the rate limiting
627  * and initialize state */
628 static void monitor_protocol_event_init(void)
629 {
630     qemu_mutex_init(&monitor_event_state_lock);
631     /* Limit RTC & BALLOON events to 1 per second */
632     monitor_protocol_event_throttle(QEVENT_RTC_CHANGE, 1000);
633     monitor_protocol_event_throttle(QEVENT_BALLOON_CHANGE, 1000);
634     monitor_protocol_event_throttle(QEVENT_WATCHDOG, 1000);
635 }
636
637 /**
638  * monitor_protocol_event(): Generate a Monitor event
639  *
640  * Event-specific data can be emitted through the (optional) 'data' parameter.
641  */
642 void monitor_protocol_event(MonitorEvent event, QObject *data)
643 {
644     QDict *qmp;
645     const char *event_name;
646
647     assert(event < QEVENT_MAX);
648
649     event_name = monitor_event_names[event];
650     assert(event_name != NULL);
651
652     qmp = qdict_new();
653     timestamp_put(qmp);
654     qdict_put(qmp, "event", qstring_from_str(event_name));
655     if (data) {
656         qobject_incref(data);
657         qdict_put_obj(qmp, "data", data);
658     }
659
660     trace_monitor_protocol_event(event, event_name, qmp);
661     monitor_protocol_event_queue(event, QOBJECT(qmp));
662     QDECREF(qmp);
663 }
664
665 static int do_qmp_capabilities(Monitor *mon, const QDict *params,
666                                QObject **ret_data)
667 {
668     /* Will setup QMP capabilities in the future */
669     if (monitor_ctrl_mode(mon)) {
670         mon->mc->command_mode = 1;
671     }
672
673     return 0;
674 }
675
676 static void handle_user_command(Monitor *mon, const char *cmdline);
677
678 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
679                                 int64_t cpu_index, Error **errp)
680 {
681     char *output = NULL;
682     Monitor *old_mon, hmp;
683
684     memset(&hmp, 0, sizeof(hmp));
685     hmp.outbuf = qstring_new();
686     hmp.skip_flush = true;
687
688     old_mon = cur_mon;
689     cur_mon = &hmp;
690
691     if (has_cpu_index) {
692         int ret = monitor_set_cpu(cpu_index);
693         if (ret < 0) {
694             cur_mon = old_mon;
695             error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
696                       "a CPU number");
697             goto out;
698         }
699     }
700
701     handle_user_command(&hmp, command_line);
702     cur_mon = old_mon;
703
704     if (qstring_get_length(hmp.outbuf) > 0) {
705         output = g_strdup(qstring_get_str(hmp.outbuf));
706     } else {
707         output = g_strdup("");
708     }
709
710 out:
711     QDECREF(hmp.outbuf);
712     return output;
713 }
714
715 static int compare_cmd(const char *name, const char *list)
716 {
717     const char *p, *pstart;
718     int len;
719     len = strlen(name);
720     p = list;
721     for(;;) {
722         pstart = p;
723         p = strchr(p, '|');
724         if (!p)
725             p = pstart + strlen(pstart);
726         if ((p - pstart) == len && !memcmp(pstart, name, len))
727             return 1;
728         if (*p == '\0')
729             break;
730         p++;
731     }
732     return 0;
733 }
734
735 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
736                           const char *prefix, const char *name)
737 {
738     const mon_cmd_t *cmd;
739
740     for(cmd = cmds; cmd->name != NULL; cmd++) {
741         if (!name || !strcmp(name, cmd->name))
742             monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
743                            cmd->params, cmd->help);
744     }
745 }
746
747 static void help_cmd(Monitor *mon, const char *name)
748 {
749     if (name && !strcmp(name, "info")) {
750         help_cmd_dump(mon, info_cmds, "info ", NULL);
751     } else {
752         help_cmd_dump(mon, mon_cmds, "", name);
753         if (name && !strcmp(name, "log")) {
754             const QEMULogItem *item;
755             monitor_printf(mon, "Log items (comma separated):\n");
756             monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
757             for (item = qemu_log_items; item->mask != 0; item++) {
758                 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
759             }
760         }
761     }
762 }
763
764 static void do_help_cmd(Monitor *mon, const QDict *qdict)
765 {
766     help_cmd(mon, qdict_get_try_str(qdict, "name"));
767 }
768
769 static void do_trace_event_set_state(Monitor *mon, const QDict *qdict)
770 {
771     const char *tp_name = qdict_get_str(qdict, "name");
772     bool new_state = qdict_get_bool(qdict, "option");
773
774     bool found = false;
775     TraceEvent *ev = NULL;
776     while ((ev = trace_event_pattern(tp_name, ev)) != NULL) {
777         found = true;
778         if (!trace_event_get_state_static(ev)) {
779             monitor_printf(mon, "event \"%s\" is not traceable\n", tp_name);
780         } else {
781             trace_event_set_state_dynamic(ev, new_state);
782         }
783     }
784     if (!trace_event_is_pattern(tp_name) && !found) {
785         monitor_printf(mon, "unknown event name \"%s\"\n", tp_name);
786     }
787 }
788
789 #ifdef CONFIG_TRACE_SIMPLE
790 static void do_trace_file(Monitor *mon, const QDict *qdict)
791 {
792     const char *op = qdict_get_try_str(qdict, "op");
793     const char *arg = qdict_get_try_str(qdict, "arg");
794
795     if (!op) {
796         st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
797     } else if (!strcmp(op, "on")) {
798         st_set_trace_file_enabled(true);
799     } else if (!strcmp(op, "off")) {
800         st_set_trace_file_enabled(false);
801     } else if (!strcmp(op, "flush")) {
802         st_flush_trace_buffer();
803     } else if (!strcmp(op, "set")) {
804         if (arg) {
805             st_set_trace_file(arg);
806         }
807     } else {
808         monitor_printf(mon, "unexpected argument \"%s\"\n", op);
809         help_cmd(mon, "trace-file");
810     }
811 }
812 #endif
813
814 static void user_monitor_complete(void *opaque, QObject *ret_data)
815 {
816     MonitorCompletionData *data = (MonitorCompletionData *)opaque; 
817
818     if (ret_data) {
819         data->user_print(data->mon, ret_data);
820     }
821     monitor_resume(data->mon);
822     g_free(data);
823 }
824
825 static void qmp_monitor_complete(void *opaque, QObject *ret_data)
826 {
827     monitor_protocol_emitter(opaque, ret_data);
828 }
829
830 static int qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
831                                  const QDict *params)
832 {
833     return cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);
834 }
835
836 static void user_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
837                                    const QDict *params)
838 {
839     int ret;
840
841     MonitorCompletionData *cb_data = g_malloc(sizeof(*cb_data));
842     cb_data->mon = mon;
843     cb_data->user_print = cmd->user_print;
844     monitor_suspend(mon);
845     ret = cmd->mhandler.cmd_async(mon, params,
846                                   user_monitor_complete, cb_data);
847     if (ret < 0) {
848         monitor_resume(mon);
849         g_free(cb_data);
850     }
851 }
852
853 static void do_info_help(Monitor *mon, const QDict *qdict)
854 {
855     help_cmd(mon, "info");
856 }
857
858 CommandInfoList *qmp_query_commands(Error **errp)
859 {
860     CommandInfoList *info, *cmd_list = NULL;
861     const mon_cmd_t *cmd;
862
863     for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
864         info = g_malloc0(sizeof(*info));
865         info->value = g_malloc0(sizeof(*info->value));
866         info->value->name = g_strdup(cmd->name);
867
868         info->next = cmd_list;
869         cmd_list = info;
870     }
871
872     return cmd_list;
873 }
874
875 EventInfoList *qmp_query_events(Error **errp)
876 {
877     EventInfoList *info, *ev_list = NULL;
878     MonitorEvent e;
879
880     for (e = 0 ; e < QEVENT_MAX ; e++) {
881         const char *event_name = monitor_event_names[e];
882         assert(event_name != NULL);
883         info = g_malloc0(sizeof(*info));
884         info->value = g_malloc0(sizeof(*info->value));
885         info->value->name = g_strdup(event_name);
886
887         info->next = ev_list;
888         ev_list = info;
889     }
890
891     return ev_list;
892 }
893
894 /* set the current CPU defined by the user */
895 int monitor_set_cpu(int cpu_index)
896 {
897     CPUState *cpu;
898
899     cpu = qemu_get_cpu(cpu_index);
900     if (cpu == NULL) {
901         return -1;
902     }
903     cur_mon->mon_cpu = cpu->env_ptr;
904     return 0;
905 }
906
907 static CPUArchState *mon_get_cpu(void)
908 {
909     if (!cur_mon->mon_cpu) {
910         monitor_set_cpu(0);
911     }
912     cpu_synchronize_state(cur_mon->mon_cpu);
913     return cur_mon->mon_cpu;
914 }
915
916 int monitor_get_cpu_index(void)
917 {
918     CPUState *cpu = ENV_GET_CPU(mon_get_cpu());
919     return cpu->cpu_index;
920 }
921
922 static void do_info_registers(Monitor *mon, const QDict *qdict)
923 {
924     CPUArchState *env;
925     env = mon_get_cpu();
926     cpu_dump_state(env, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
927 }
928
929 static void do_info_jit(Monitor *mon, const QDict *qdict)
930 {
931     dump_exec_info((FILE *)mon, monitor_fprintf);
932 }
933
934 static void do_info_history(Monitor *mon, const QDict *qdict)
935 {
936     int i;
937     const char *str;
938
939     if (!mon->rs)
940         return;
941     i = 0;
942     for(;;) {
943         str = readline_get_history(mon->rs, i);
944         if (!str)
945             break;
946         monitor_printf(mon, "%d: '%s'\n", i, str);
947         i++;
948     }
949 }
950
951 #if defined(TARGET_PPC)
952 /* XXX: not implemented in other targets */
953 static void do_info_cpu_stats(Monitor *mon, const QDict *qdict)
954 {
955     CPUArchState *env;
956
957     env = mon_get_cpu();
958     cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
959 }
960 #endif
961
962 static void do_trace_print_events(Monitor *mon, const QDict *qdict)
963 {
964     trace_print_events((FILE *)mon, &monitor_fprintf);
965 }
966
967 static int client_migrate_info(Monitor *mon, const QDict *qdict,
968                                MonitorCompletion cb, void *opaque)
969 {
970     const char *protocol = qdict_get_str(qdict, "protocol");
971     const char *hostname = qdict_get_str(qdict, "hostname");
972     const char *subject  = qdict_get_try_str(qdict, "cert-subject");
973     int port             = qdict_get_try_int(qdict, "port", -1);
974     int tls_port         = qdict_get_try_int(qdict, "tls-port", -1);
975     int ret;
976
977     if (strcmp(protocol, "spice") == 0) {
978         if (!using_spice) {
979             qerror_report(QERR_DEVICE_NOT_ACTIVE, "spice");
980             return -1;
981         }
982
983         if (port == -1 && tls_port == -1) {
984             qerror_report(QERR_MISSING_PARAMETER, "port/tls-port");
985             return -1;
986         }
987
988         ret = qemu_spice_migrate_info(hostname, port, tls_port, subject,
989                                       cb, opaque);
990         if (ret != 0) {
991             qerror_report(QERR_UNDEFINED_ERROR);
992             return -1;
993         }
994         return 0;
995     }
996
997     qerror_report(QERR_INVALID_PARAMETER, "protocol");
998     return -1;
999 }
1000
1001 static void do_logfile(Monitor *mon, const QDict *qdict)
1002 {
1003     qemu_set_log_filename(qdict_get_str(qdict, "filename"));
1004 }
1005
1006 static void do_log(Monitor *mon, const QDict *qdict)
1007 {
1008     int mask;
1009     const char *items = qdict_get_str(qdict, "items");
1010
1011     if (!strcmp(items, "none")) {
1012         mask = 0;
1013     } else {
1014         mask = qemu_str_to_log_mask(items);
1015         if (!mask) {
1016             help_cmd(mon, "log");
1017             return;
1018         }
1019     }
1020     qemu_set_log(mask);
1021 }
1022
1023 static void do_singlestep(Monitor *mon, const QDict *qdict)
1024 {
1025     const char *option = qdict_get_try_str(qdict, "option");
1026     if (!option || !strcmp(option, "on")) {
1027         singlestep = 1;
1028     } else if (!strcmp(option, "off")) {
1029         singlestep = 0;
1030     } else {
1031         monitor_printf(mon, "unexpected option %s\n", option);
1032     }
1033 }
1034
1035 static void do_gdbserver(Monitor *mon, const QDict *qdict)
1036 {
1037     const char *device = qdict_get_try_str(qdict, "device");
1038     if (!device)
1039         device = "tcp::" DEFAULT_GDBSTUB_PORT;
1040     if (gdbserver_start(device) < 0) {
1041         monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1042                        device);
1043     } else if (strcmp(device, "none") == 0) {
1044         monitor_printf(mon, "Disabled gdbserver\n");
1045     } else {
1046         monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1047                        device);
1048     }
1049 }
1050
1051 static void do_watchdog_action(Monitor *mon, const QDict *qdict)
1052 {
1053     const char *action = qdict_get_str(qdict, "action");
1054     if (select_watchdog_action(action) == -1) {
1055         monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1056     }
1057 }
1058
1059 static void monitor_printc(Monitor *mon, int c)
1060 {
1061     monitor_printf(mon, "'");
1062     switch(c) {
1063     case '\'':
1064         monitor_printf(mon, "\\'");
1065         break;
1066     case '\\':
1067         monitor_printf(mon, "\\\\");
1068         break;
1069     case '\n':
1070         monitor_printf(mon, "\\n");
1071         break;
1072     case '\r':
1073         monitor_printf(mon, "\\r");
1074         break;
1075     default:
1076         if (c >= 32 && c <= 126) {
1077             monitor_printf(mon, "%c", c);
1078         } else {
1079             monitor_printf(mon, "\\x%02x", c);
1080         }
1081         break;
1082     }
1083     monitor_printf(mon, "'");
1084 }
1085
1086 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1087                         hwaddr addr, int is_physical)
1088 {
1089     CPUArchState *env;
1090     int l, line_size, i, max_digits, len;
1091     uint8_t buf[16];
1092     uint64_t v;
1093
1094     if (format == 'i') {
1095         int flags;
1096         flags = 0;
1097         env = mon_get_cpu();
1098 #ifdef TARGET_I386
1099         if (wsize == 2) {
1100             flags = 1;
1101         } else if (wsize == 4) {
1102             flags = 0;
1103         } else {
1104             /* as default we use the current CS size */
1105             flags = 0;
1106             if (env) {
1107 #ifdef TARGET_X86_64
1108                 if ((env->efer & MSR_EFER_LMA) &&
1109                     (env->segs[R_CS].flags & DESC_L_MASK))
1110                     flags = 2;
1111                 else
1112 #endif
1113                 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1114                     flags = 1;
1115             }
1116         }
1117 #endif
1118         monitor_disas(mon, env, addr, count, is_physical, flags);
1119         return;
1120     }
1121
1122     len = wsize * count;
1123     if (wsize == 1)
1124         line_size = 8;
1125     else
1126         line_size = 16;
1127     max_digits = 0;
1128
1129     switch(format) {
1130     case 'o':
1131         max_digits = (wsize * 8 + 2) / 3;
1132         break;
1133     default:
1134     case 'x':
1135         max_digits = (wsize * 8) / 4;
1136         break;
1137     case 'u':
1138     case 'd':
1139         max_digits = (wsize * 8 * 10 + 32) / 33;
1140         break;
1141     case 'c':
1142         wsize = 1;
1143         break;
1144     }
1145
1146     while (len > 0) {
1147         if (is_physical)
1148             monitor_printf(mon, TARGET_FMT_plx ":", addr);
1149         else
1150             monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1151         l = len;
1152         if (l > line_size)
1153             l = line_size;
1154         if (is_physical) {
1155             cpu_physical_memory_read(addr, buf, l);
1156         } else {
1157             env = mon_get_cpu();
1158             if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {
1159                 monitor_printf(mon, " Cannot access memory\n");
1160                 break;
1161             }
1162         }
1163         i = 0;
1164         while (i < l) {
1165             switch(wsize) {
1166             default:
1167             case 1:
1168                 v = ldub_raw(buf + i);
1169                 break;
1170             case 2:
1171                 v = lduw_raw(buf + i);
1172                 break;
1173             case 4:
1174                 v = (uint32_t)ldl_raw(buf + i);
1175                 break;
1176             case 8:
1177                 v = ldq_raw(buf + i);
1178                 break;
1179             }
1180             monitor_printf(mon, " ");
1181             switch(format) {
1182             case 'o':
1183                 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1184                 break;
1185             case 'x':
1186                 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1187                 break;
1188             case 'u':
1189                 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1190                 break;
1191             case 'd':
1192                 monitor_printf(mon, "%*" PRId64, max_digits, v);
1193                 break;
1194             case 'c':
1195                 monitor_printc(mon, v);
1196                 break;
1197             }
1198             i += wsize;
1199         }
1200         monitor_printf(mon, "\n");
1201         addr += l;
1202         len -= l;
1203     }
1204 }
1205
1206 static void do_memory_dump(Monitor *mon, const QDict *qdict)
1207 {
1208     int count = qdict_get_int(qdict, "count");
1209     int format = qdict_get_int(qdict, "format");
1210     int size = qdict_get_int(qdict, "size");
1211     target_long addr = qdict_get_int(qdict, "addr");
1212
1213     memory_dump(mon, count, format, size, addr, 0);
1214 }
1215
1216 static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
1217 {
1218     int count = qdict_get_int(qdict, "count");
1219     int format = qdict_get_int(qdict, "format");
1220     int size = qdict_get_int(qdict, "size");
1221     hwaddr addr = qdict_get_int(qdict, "addr");
1222
1223     memory_dump(mon, count, format, size, addr, 1);
1224 }
1225
1226 static void do_print(Monitor *mon, const QDict *qdict)
1227 {
1228     int format = qdict_get_int(qdict, "format");
1229     hwaddr val = qdict_get_int(qdict, "val");
1230
1231     switch(format) {
1232     case 'o':
1233         monitor_printf(mon, "%#" HWADDR_PRIo, val);
1234         break;
1235     case 'x':
1236         monitor_printf(mon, "%#" HWADDR_PRIx, val);
1237         break;
1238     case 'u':
1239         monitor_printf(mon, "%" HWADDR_PRIu, val);
1240         break;
1241     default:
1242     case 'd':
1243         monitor_printf(mon, "%" HWADDR_PRId, val);
1244         break;
1245     case 'c':
1246         monitor_printc(mon, val);
1247         break;
1248     }
1249     monitor_printf(mon, "\n");
1250 }
1251
1252 static void do_sum(Monitor *mon, const QDict *qdict)
1253 {
1254     uint32_t addr;
1255     uint16_t sum;
1256     uint32_t start = qdict_get_int(qdict, "start");
1257     uint32_t size = qdict_get_int(qdict, "size");
1258
1259     sum = 0;
1260     for(addr = start; addr < (start + size); addr++) {
1261         uint8_t val = ldub_phys(addr);
1262         /* BSD sum algorithm ('sum' Unix command) */
1263         sum = (sum >> 1) | (sum << 15);
1264         sum += val;
1265     }
1266     monitor_printf(mon, "%05d\n", sum);
1267 }
1268
1269 static int mouse_button_state;
1270
1271 static void do_mouse_move(Monitor *mon, const QDict *qdict)
1272 {
1273     int dx, dy, dz;
1274     const char *dx_str = qdict_get_str(qdict, "dx_str");
1275     const char *dy_str = qdict_get_str(qdict, "dy_str");
1276     const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1277     dx = strtol(dx_str, NULL, 0);
1278     dy = strtol(dy_str, NULL, 0);
1279     dz = 0;
1280     if (dz_str)
1281         dz = strtol(dz_str, NULL, 0);
1282     kbd_mouse_event(dx, dy, dz, mouse_button_state);
1283 }
1284
1285 static void do_mouse_button(Monitor *mon, const QDict *qdict)
1286 {
1287     int button_state = qdict_get_int(qdict, "button_state");
1288     mouse_button_state = button_state;
1289     kbd_mouse_event(0, 0, 0, mouse_button_state);
1290 }
1291
1292 static void do_ioport_read(Monitor *mon, const QDict *qdict)
1293 {
1294     int size = qdict_get_int(qdict, "size");
1295     int addr = qdict_get_int(qdict, "addr");
1296     int has_index = qdict_haskey(qdict, "index");
1297     uint32_t val;
1298     int suffix;
1299
1300     if (has_index) {
1301         int index = qdict_get_int(qdict, "index");
1302         cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1303         addr++;
1304     }
1305     addr &= 0xffff;
1306
1307     switch(size) {
1308     default:
1309     case 1:
1310         val = cpu_inb(addr);
1311         suffix = 'b';
1312         break;
1313     case 2:
1314         val = cpu_inw(addr);
1315         suffix = 'w';
1316         break;
1317     case 4:
1318         val = cpu_inl(addr);
1319         suffix = 'l';
1320         break;
1321     }
1322     monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1323                    suffix, addr, size * 2, val);
1324 }
1325
1326 static void do_ioport_write(Monitor *mon, const QDict *qdict)
1327 {
1328     int size = qdict_get_int(qdict, "size");
1329     int addr = qdict_get_int(qdict, "addr");
1330     int val = qdict_get_int(qdict, "val");
1331
1332     addr &= IOPORTS_MASK;
1333
1334     switch (size) {
1335     default:
1336     case 1:
1337         cpu_outb(addr, val);
1338         break;
1339     case 2:
1340         cpu_outw(addr, val);
1341         break;
1342     case 4:
1343         cpu_outl(addr, val);
1344         break;
1345     }
1346 }
1347
1348 static void do_boot_set(Monitor *mon, const QDict *qdict)
1349 {
1350     int res;
1351     const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1352
1353     res = qemu_boot_set(bootdevice);
1354     if (res == 0) {
1355         monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1356     } else if (res > 0) {
1357         monitor_printf(mon, "setting boot device list failed\n");
1358     } else {
1359         monitor_printf(mon, "no function defined to set boot device list for "
1360                        "this architecture\n");
1361     }
1362 }
1363
1364 #if defined(TARGET_I386)
1365 static void print_pte(Monitor *mon, hwaddr addr,
1366                       hwaddr pte,
1367                       hwaddr mask)
1368 {
1369 #ifdef TARGET_X86_64
1370     if (addr & (1ULL << 47)) {
1371         addr |= -1LL << 48;
1372     }
1373 #endif
1374     monitor_printf(mon, TARGET_FMT_plx ": " TARGET_FMT_plx
1375                    " %c%c%c%c%c%c%c%c%c\n",
1376                    addr,
1377                    pte & mask,
1378                    pte & PG_NX_MASK ? 'X' : '-',
1379                    pte & PG_GLOBAL_MASK ? 'G' : '-',
1380                    pte & PG_PSE_MASK ? 'P' : '-',
1381                    pte & PG_DIRTY_MASK ? 'D' : '-',
1382                    pte & PG_ACCESSED_MASK ? 'A' : '-',
1383                    pte & PG_PCD_MASK ? 'C' : '-',
1384                    pte & PG_PWT_MASK ? 'T' : '-',
1385                    pte & PG_USER_MASK ? 'U' : '-',
1386                    pte & PG_RW_MASK ? 'W' : '-');
1387 }
1388
1389 static void tlb_info_32(Monitor *mon, CPUArchState *env)
1390 {
1391     unsigned int l1, l2;
1392     uint32_t pgd, pde, pte;
1393
1394     pgd = env->cr[3] & ~0xfff;
1395     for(l1 = 0; l1 < 1024; l1++) {
1396         cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
1397         pde = le32_to_cpu(pde);
1398         if (pde & PG_PRESENT_MASK) {
1399             if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1400                 /* 4M pages */
1401                 print_pte(mon, (l1 << 22), pde, ~((1 << 21) - 1));
1402             } else {
1403                 for(l2 = 0; l2 < 1024; l2++) {
1404                     cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
1405                     pte = le32_to_cpu(pte);
1406                     if (pte & PG_PRESENT_MASK) {
1407                         print_pte(mon, (l1 << 22) + (l2 << 12),
1408                                   pte & ~PG_PSE_MASK,
1409                                   ~0xfff);
1410                     }
1411                 }
1412             }
1413         }
1414     }
1415 }
1416
1417 static void tlb_info_pae32(Monitor *mon, CPUArchState *env)
1418 {
1419     unsigned int l1, l2, l3;
1420     uint64_t pdpe, pde, pte;
1421     uint64_t pdp_addr, pd_addr, pt_addr;
1422
1423     pdp_addr = env->cr[3] & ~0x1f;
1424     for (l1 = 0; l1 < 4; l1++) {
1425         cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
1426         pdpe = le64_to_cpu(pdpe);
1427         if (pdpe & PG_PRESENT_MASK) {
1428             pd_addr = pdpe & 0x3fffffffff000ULL;
1429             for (l2 = 0; l2 < 512; l2++) {
1430                 cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
1431                 pde = le64_to_cpu(pde);
1432                 if (pde & PG_PRESENT_MASK) {
1433                     if (pde & PG_PSE_MASK) {
1434                         /* 2M pages with PAE, CR4.PSE is ignored */
1435                         print_pte(mon, (l1 << 30 ) + (l2 << 21), pde,
1436                                   ~((hwaddr)(1 << 20) - 1));
1437                     } else {
1438                         pt_addr = pde & 0x3fffffffff000ULL;
1439                         for (l3 = 0; l3 < 512; l3++) {
1440                             cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
1441                             pte = le64_to_cpu(pte);
1442                             if (pte & PG_PRESENT_MASK) {
1443                                 print_pte(mon, (l1 << 30 ) + (l2 << 21)
1444                                           + (l3 << 12),
1445                                           pte & ~PG_PSE_MASK,
1446                                           ~(hwaddr)0xfff);
1447                             }
1448                         }
1449                     }
1450                 }
1451             }
1452         }
1453     }
1454 }
1455
1456 #ifdef TARGET_X86_64
1457 static void tlb_info_64(Monitor *mon, CPUArchState *env)
1458 {
1459     uint64_t l1, l2, l3, l4;
1460     uint64_t pml4e, pdpe, pde, pte;
1461     uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr;
1462
1463     pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
1464     for (l1 = 0; l1 < 512; l1++) {
1465         cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
1466         pml4e = le64_to_cpu(pml4e);
1467         if (pml4e & PG_PRESENT_MASK) {
1468             pdp_addr = pml4e & 0x3fffffffff000ULL;
1469             for (l2 = 0; l2 < 512; l2++) {
1470                 cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
1471                 pdpe = le64_to_cpu(pdpe);
1472                 if (pdpe & PG_PRESENT_MASK) {
1473                     if (pdpe & PG_PSE_MASK) {
1474                         /* 1G pages, CR4.PSE is ignored */
1475                         print_pte(mon, (l1 << 39) + (l2 << 30), pdpe,
1476                                   0x3ffffc0000000ULL);
1477                     } else {
1478                         pd_addr = pdpe & 0x3fffffffff000ULL;
1479                         for (l3 = 0; l3 < 512; l3++) {
1480                             cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
1481                             pde = le64_to_cpu(pde);
1482                             if (pde & PG_PRESENT_MASK) {
1483                                 if (pde & PG_PSE_MASK) {
1484                                     /* 2M pages, CR4.PSE is ignored */
1485                                     print_pte(mon, (l1 << 39) + (l2 << 30) +
1486                                               (l3 << 21), pde,
1487                                               0x3ffffffe00000ULL);
1488                                 } else {
1489                                     pt_addr = pde & 0x3fffffffff000ULL;
1490                                     for (l4 = 0; l4 < 512; l4++) {
1491                                         cpu_physical_memory_read(pt_addr
1492                                                                  + l4 * 8,
1493                                                                  &pte, 8);
1494                                         pte = le64_to_cpu(pte);
1495                                         if (pte & PG_PRESENT_MASK) {
1496                                             print_pte(mon, (l1 << 39) +
1497                                                       (l2 << 30) +
1498                                                       (l3 << 21) + (l4 << 12),
1499                                                       pte & ~PG_PSE_MASK,
1500                                                       0x3fffffffff000ULL);
1501                                         }
1502                                     }
1503                                 }
1504                             }
1505                         }
1506                     }
1507                 }
1508             }
1509         }
1510     }
1511 }
1512 #endif
1513
1514 static void tlb_info(Monitor *mon, const QDict *qdict)
1515 {
1516     CPUArchState *env;
1517
1518     env = mon_get_cpu();
1519
1520     if (!(env->cr[0] & CR0_PG_MASK)) {
1521         monitor_printf(mon, "PG disabled\n");
1522         return;
1523     }
1524     if (env->cr[4] & CR4_PAE_MASK) {
1525 #ifdef TARGET_X86_64
1526         if (env->hflags & HF_LMA_MASK) {
1527             tlb_info_64(mon, env);
1528         } else
1529 #endif
1530         {
1531             tlb_info_pae32(mon, env);
1532         }
1533     } else {
1534         tlb_info_32(mon, env);
1535     }
1536 }
1537
1538 static void mem_print(Monitor *mon, hwaddr *pstart,
1539                       int *plast_prot,
1540                       hwaddr end, int prot)
1541 {
1542     int prot1;
1543     prot1 = *plast_prot;
1544     if (prot != prot1) {
1545         if (*pstart != -1) {
1546             monitor_printf(mon, TARGET_FMT_plx "-" TARGET_FMT_plx " "
1547                            TARGET_FMT_plx " %c%c%c\n",
1548                            *pstart, end, end - *pstart,
1549                            prot1 & PG_USER_MASK ? 'u' : '-',
1550                            'r',
1551                            prot1 & PG_RW_MASK ? 'w' : '-');
1552         }
1553         if (prot != 0)
1554             *pstart = end;
1555         else
1556             *pstart = -1;
1557         *plast_prot = prot;
1558     }
1559 }
1560
1561 static void mem_info_32(Monitor *mon, CPUArchState *env)
1562 {
1563     unsigned int l1, l2;
1564     int prot, last_prot;
1565     uint32_t pgd, pde, pte;
1566     hwaddr start, end;
1567
1568     pgd = env->cr[3] & ~0xfff;
1569     last_prot = 0;
1570     start = -1;
1571     for(l1 = 0; l1 < 1024; l1++) {
1572         cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
1573         pde = le32_to_cpu(pde);
1574         end = l1 << 22;
1575         if (pde & PG_PRESENT_MASK) {
1576             if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1577                 prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1578                 mem_print(mon, &start, &last_prot, end, prot);
1579             } else {
1580                 for(l2 = 0; l2 < 1024; l2++) {
1581                     cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
1582                     pte = le32_to_cpu(pte);
1583                     end = (l1 << 22) + (l2 << 12);
1584                     if (pte & PG_PRESENT_MASK) {
1585                         prot = pte & pde &
1586                             (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1587                     } else {
1588                         prot = 0;
1589                     }
1590                     mem_print(mon, &start, &last_prot, end, prot);
1591                 }
1592             }
1593         } else {
1594             prot = 0;
1595             mem_print(mon, &start, &last_prot, end, prot);
1596         }
1597     }
1598     /* Flush last range */
1599     mem_print(mon, &start, &last_prot, (hwaddr)1 << 32, 0);
1600 }
1601
1602 static void mem_info_pae32(Monitor *mon, CPUArchState *env)
1603 {
1604     unsigned int l1, l2, l3;
1605     int prot, last_prot;
1606     uint64_t pdpe, pde, pte;
1607     uint64_t pdp_addr, pd_addr, pt_addr;
1608     hwaddr start, end;
1609
1610     pdp_addr = env->cr[3] & ~0x1f;
1611     last_prot = 0;
1612     start = -1;
1613     for (l1 = 0; l1 < 4; l1++) {
1614         cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
1615         pdpe = le64_to_cpu(pdpe);
1616         end = l1 << 30;
1617         if (pdpe & PG_PRESENT_MASK) {
1618             pd_addr = pdpe & 0x3fffffffff000ULL;
1619             for (l2 = 0; l2 < 512; l2++) {
1620                 cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
1621                 pde = le64_to_cpu(pde);
1622                 end = (l1 << 30) + (l2 << 21);
1623                 if (pde & PG_PRESENT_MASK) {
1624                     if (pde & PG_PSE_MASK) {
1625                         prot = pde & (PG_USER_MASK | PG_RW_MASK |
1626                                       PG_PRESENT_MASK);
1627                         mem_print(mon, &start, &last_prot, end, prot);
1628                     } else {
1629                         pt_addr = pde & 0x3fffffffff000ULL;
1630                         for (l3 = 0; l3 < 512; l3++) {
1631                             cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
1632                             pte = le64_to_cpu(pte);
1633                             end = (l1 << 30) + (l2 << 21) + (l3 << 12);
1634                             if (pte & PG_PRESENT_MASK) {
1635                                 prot = pte & pde & (PG_USER_MASK | PG_RW_MASK |
1636                                                     PG_PRESENT_MASK);
1637                             } else {
1638                                 prot = 0;
1639                             }
1640                             mem_print(mon, &start, &last_prot, end, prot);
1641                         }
1642                     }
1643                 } else {
1644                     prot = 0;
1645                     mem_print(mon, &start, &last_prot, end, prot);
1646                 }
1647             }
1648         } else {
1649             prot = 0;
1650             mem_print(mon, &start, &last_prot, end, prot);
1651         }
1652     }
1653     /* Flush last range */
1654     mem_print(mon, &start, &last_prot, (hwaddr)1 << 32, 0);
1655 }
1656
1657
1658 #ifdef TARGET_X86_64
1659 static void mem_info_64(Monitor *mon, CPUArchState *env)
1660 {
1661     int prot, last_prot;
1662     uint64_t l1, l2, l3, l4;
1663     uint64_t pml4e, pdpe, pde, pte;
1664     uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr, start, end;
1665
1666     pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
1667     last_prot = 0;
1668     start = -1;
1669     for (l1 = 0; l1 < 512; l1++) {
1670         cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
1671         pml4e = le64_to_cpu(pml4e);
1672         end = l1 << 39;
1673         if (pml4e & PG_PRESENT_MASK) {
1674             pdp_addr = pml4e & 0x3fffffffff000ULL;
1675             for (l2 = 0; l2 < 512; l2++) {
1676                 cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
1677                 pdpe = le64_to_cpu(pdpe);
1678                 end = (l1 << 39) + (l2 << 30);
1679                 if (pdpe & PG_PRESENT_MASK) {
1680                     if (pdpe & PG_PSE_MASK) {
1681                         prot = pdpe & (PG_USER_MASK | PG_RW_MASK |
1682                                        PG_PRESENT_MASK);
1683                         prot &= pml4e;
1684                         mem_print(mon, &start, &last_prot, end, prot);
1685                     } else {
1686                         pd_addr = pdpe & 0x3fffffffff000ULL;
1687                         for (l3 = 0; l3 < 512; l3++) {
1688                             cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
1689                             pde = le64_to_cpu(pde);
1690                             end = (l1 << 39) + (l2 << 30) + (l3 << 21);
1691                             if (pde & PG_PRESENT_MASK) {
1692                                 if (pde & PG_PSE_MASK) {
1693                                     prot = pde & (PG_USER_MASK | PG_RW_MASK |
1694                                                   PG_PRESENT_MASK);
1695                                     prot &= pml4e & pdpe;
1696                                     mem_print(mon, &start, &last_prot, end, prot);
1697                                 } else {
1698                                     pt_addr = pde & 0x3fffffffff000ULL;
1699                                     for (l4 = 0; l4 < 512; l4++) {
1700                                         cpu_physical_memory_read(pt_addr
1701                                                                  + l4 * 8,
1702                                                                  &pte, 8);
1703                                         pte = le64_to_cpu(pte);
1704                                         end = (l1 << 39) + (l2 << 30) +
1705                                             (l3 << 21) + (l4 << 12);
1706                                         if (pte & PG_PRESENT_MASK) {
1707                                             prot = pte & (PG_USER_MASK | PG_RW_MASK |
1708                                                           PG_PRESENT_MASK);
1709                                             prot &= pml4e & pdpe & pde;
1710                                         } else {
1711                                             prot = 0;
1712                                         }
1713                                         mem_print(mon, &start, &last_prot, end, prot);
1714                                     }
1715                                 }
1716                             } else {
1717                                 prot = 0;
1718                                 mem_print(mon, &start, &last_prot, end, prot);
1719                             }
1720                         }
1721                     }
1722                 } else {
1723                     prot = 0;
1724                     mem_print(mon, &start, &last_prot, end, prot);
1725                 }
1726             }
1727         } else {
1728             prot = 0;
1729             mem_print(mon, &start, &last_prot, end, prot);
1730         }
1731     }
1732     /* Flush last range */
1733     mem_print(mon, &start, &last_prot, (hwaddr)1 << 48, 0);
1734 }
1735 #endif
1736
1737 static void mem_info(Monitor *mon, const QDict *qdict)
1738 {
1739     CPUArchState *env;
1740
1741     env = mon_get_cpu();
1742
1743     if (!(env->cr[0] & CR0_PG_MASK)) {
1744         monitor_printf(mon, "PG disabled\n");
1745         return;
1746     }
1747     if (env->cr[4] & CR4_PAE_MASK) {
1748 #ifdef TARGET_X86_64
1749         if (env->hflags & HF_LMA_MASK) {
1750             mem_info_64(mon, env);
1751         } else
1752 #endif
1753         {
1754             mem_info_pae32(mon, env);
1755         }
1756     } else {
1757         mem_info_32(mon, env);
1758     }
1759 }
1760 #endif
1761
1762 #if defined(TARGET_SH4)
1763
1764 static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1765 {
1766     monitor_printf(mon, " tlb%i:\t"
1767                    "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1768                    "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1769                    "dirty=%hhu writethrough=%hhu\n",
1770                    idx,
1771                    tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1772                    tlb->v, tlb->sh, tlb->c, tlb->pr,
1773                    tlb->d, tlb->wt);
1774 }
1775
1776 static void tlb_info(Monitor *mon, const QDict *qdict)
1777 {
1778     CPUArchState *env = mon_get_cpu();
1779     int i;
1780
1781     monitor_printf (mon, "ITLB:\n");
1782     for (i = 0 ; i < ITLB_SIZE ; i++)
1783         print_tlb (mon, i, &env->itlb[i]);
1784     monitor_printf (mon, "UTLB:\n");
1785     for (i = 0 ; i < UTLB_SIZE ; i++)
1786         print_tlb (mon, i, &env->utlb[i]);
1787 }
1788
1789 #endif
1790
1791 #if defined(TARGET_SPARC) || defined(TARGET_PPC) || defined(TARGET_XTENSA)
1792 static void tlb_info(Monitor *mon, const QDict *qdict)
1793 {
1794     CPUArchState *env1 = mon_get_cpu();
1795
1796     dump_mmu((FILE*)mon, (fprintf_function)monitor_printf, env1);
1797 }
1798 #endif
1799
1800 static void do_info_mtree(Monitor *mon, const QDict *qdict)
1801 {
1802     mtree_info((fprintf_function)monitor_printf, mon);
1803 }
1804
1805 static void do_info_numa(Monitor *mon, const QDict *qdict)
1806 {
1807     int i;
1808     CPUArchState *env;
1809     CPUState *cpu;
1810
1811     monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1812     for (i = 0; i < nb_numa_nodes; i++) {
1813         monitor_printf(mon, "node %d cpus:", i);
1814         for (env = first_cpu; env != NULL; env = env->next_cpu) {
1815             cpu = ENV_GET_CPU(env);
1816             if (cpu->numa_node == i) {
1817                 monitor_printf(mon, " %d", cpu->cpu_index);
1818             }
1819         }
1820         monitor_printf(mon, "\n");
1821         monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1822             node_mem[i] >> 20);
1823     }
1824 }
1825
1826 #ifdef CONFIG_PROFILER
1827
1828 int64_t qemu_time;
1829 int64_t dev_time;
1830
1831 static void do_info_profile(Monitor *mon, const QDict *qdict)
1832 {
1833     int64_t total;
1834     total = qemu_time;
1835     if (total == 0)
1836         total = 1;
1837     monitor_printf(mon, "async time  %" PRId64 " (%0.3f)\n",
1838                    dev_time, dev_time / (double)get_ticks_per_sec());
1839     monitor_printf(mon, "qemu time   %" PRId64 " (%0.3f)\n",
1840                    qemu_time, qemu_time / (double)get_ticks_per_sec());
1841     qemu_time = 0;
1842     dev_time = 0;
1843 }
1844 #else
1845 static void do_info_profile(Monitor *mon, const QDict *qdict)
1846 {
1847     monitor_printf(mon, "Internal profiler not compiled\n");
1848 }
1849 #endif
1850
1851 /* Capture support */
1852 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1853
1854 static void do_info_capture(Monitor *mon, const QDict *qdict)
1855 {
1856     int i;
1857     CaptureState *s;
1858
1859     for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1860         monitor_printf(mon, "[%d]: ", i);
1861         s->ops.info (s->opaque);
1862     }
1863 }
1864
1865 #ifdef HAS_AUDIO
1866 static void do_stop_capture(Monitor *mon, const QDict *qdict)
1867 {
1868     int i;
1869     int n = qdict_get_int(qdict, "n");
1870     CaptureState *s;
1871
1872     for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1873         if (i == n) {
1874             s->ops.destroy (s->opaque);
1875             QLIST_REMOVE (s, entries);
1876             g_free (s);
1877             return;
1878         }
1879     }
1880 }
1881
1882 static void do_wav_capture(Monitor *mon, const QDict *qdict)
1883 {
1884     const char *path = qdict_get_str(qdict, "path");
1885     int has_freq = qdict_haskey(qdict, "freq");
1886     int freq = qdict_get_try_int(qdict, "freq", -1);
1887     int has_bits = qdict_haskey(qdict, "bits");
1888     int bits = qdict_get_try_int(qdict, "bits", -1);
1889     int has_channels = qdict_haskey(qdict, "nchannels");
1890     int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1891     CaptureState *s;
1892
1893     s = g_malloc0 (sizeof (*s));
1894
1895     freq = has_freq ? freq : 44100;
1896     bits = has_bits ? bits : 16;
1897     nchannels = has_channels ? nchannels : 2;
1898
1899     if (wav_start_capture (s, path, freq, bits, nchannels)) {
1900         monitor_printf(mon, "Failed to add wave capture\n");
1901         g_free (s);
1902         return;
1903     }
1904     QLIST_INSERT_HEAD (&capture_head, s, entries);
1905 }
1906 #endif
1907
1908 static qemu_acl *find_acl(Monitor *mon, const char *name)
1909 {
1910     qemu_acl *acl = qemu_acl_find(name);
1911
1912     if (!acl) {
1913         monitor_printf(mon, "acl: unknown list '%s'\n", name);
1914     }
1915     return acl;
1916 }
1917
1918 static void do_acl_show(Monitor *mon, const QDict *qdict)
1919 {
1920     const char *aclname = qdict_get_str(qdict, "aclname");
1921     qemu_acl *acl = find_acl(mon, aclname);
1922     qemu_acl_entry *entry;
1923     int i = 0;
1924
1925     if (acl) {
1926         monitor_printf(mon, "policy: %s\n",
1927                        acl->defaultDeny ? "deny" : "allow");
1928         QTAILQ_FOREACH(entry, &acl->entries, next) {
1929             i++;
1930             monitor_printf(mon, "%d: %s %s\n", i,
1931                            entry->deny ? "deny" : "allow", entry->match);
1932         }
1933     }
1934 }
1935
1936 static void do_acl_reset(Monitor *mon, const QDict *qdict)
1937 {
1938     const char *aclname = qdict_get_str(qdict, "aclname");
1939     qemu_acl *acl = find_acl(mon, aclname);
1940
1941     if (acl) {
1942         qemu_acl_reset(acl);
1943         monitor_printf(mon, "acl: removed all rules\n");
1944     }
1945 }
1946
1947 static void do_acl_policy(Monitor *mon, const QDict *qdict)
1948 {
1949     const char *aclname = qdict_get_str(qdict, "aclname");
1950     const char *policy = qdict_get_str(qdict, "policy");
1951     qemu_acl *acl = find_acl(mon, aclname);
1952
1953     if (acl) {
1954         if (strcmp(policy, "allow") == 0) {
1955             acl->defaultDeny = 0;
1956             monitor_printf(mon, "acl: policy set to 'allow'\n");
1957         } else if (strcmp(policy, "deny") == 0) {
1958             acl->defaultDeny = 1;
1959             monitor_printf(mon, "acl: policy set to 'deny'\n");
1960         } else {
1961             monitor_printf(mon, "acl: unknown policy '%s', "
1962                            "expected 'deny' or 'allow'\n", policy);
1963         }
1964     }
1965 }
1966
1967 static void do_acl_add(Monitor *mon, const QDict *qdict)
1968 {
1969     const char *aclname = qdict_get_str(qdict, "aclname");
1970     const char *match = qdict_get_str(qdict, "match");
1971     const char *policy = qdict_get_str(qdict, "policy");
1972     int has_index = qdict_haskey(qdict, "index");
1973     int index = qdict_get_try_int(qdict, "index", -1);
1974     qemu_acl *acl = find_acl(mon, aclname);
1975     int deny, ret;
1976
1977     if (acl) {
1978         if (strcmp(policy, "allow") == 0) {
1979             deny = 0;
1980         } else if (strcmp(policy, "deny") == 0) {
1981             deny = 1;
1982         } else {
1983             monitor_printf(mon, "acl: unknown policy '%s', "
1984                            "expected 'deny' or 'allow'\n", policy);
1985             return;
1986         }
1987         if (has_index)
1988             ret = qemu_acl_insert(acl, deny, match, index);
1989         else
1990             ret = qemu_acl_append(acl, deny, match);
1991         if (ret < 0)
1992             monitor_printf(mon, "acl: unable to add acl entry\n");
1993         else
1994             monitor_printf(mon, "acl: added rule at position %d\n", ret);
1995     }
1996 }
1997
1998 static void do_acl_remove(Monitor *mon, const QDict *qdict)
1999 {
2000     const char *aclname = qdict_get_str(qdict, "aclname");
2001     const char *match = qdict_get_str(qdict, "match");
2002     qemu_acl *acl = find_acl(mon, aclname);
2003     int ret;
2004
2005     if (acl) {
2006         ret = qemu_acl_remove(acl, match);
2007         if (ret < 0)
2008             monitor_printf(mon, "acl: no matching acl entry\n");
2009         else
2010             monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2011     }
2012 }
2013
2014 #if defined(TARGET_I386)
2015 static void do_inject_mce(Monitor *mon, const QDict *qdict)
2016 {
2017     X86CPU *cpu;
2018     CPUX86State *cenv;
2019     CPUState *cs;
2020     int cpu_index = qdict_get_int(qdict, "cpu_index");
2021     int bank = qdict_get_int(qdict, "bank");
2022     uint64_t status = qdict_get_int(qdict, "status");
2023     uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2024     uint64_t addr = qdict_get_int(qdict, "addr");
2025     uint64_t misc = qdict_get_int(qdict, "misc");
2026     int flags = MCE_INJECT_UNCOND_AO;
2027
2028     if (qdict_get_try_bool(qdict, "broadcast", 0)) {
2029         flags |= MCE_INJECT_BROADCAST;
2030     }
2031     for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu) {
2032         cpu = x86_env_get_cpu(cenv);
2033         cs = CPU(cpu);
2034         if (cs->cpu_index == cpu_index) {
2035             cpu_x86_inject_mce(mon, cpu, bank, status, mcg_status, addr, misc,
2036                                flags);
2037             break;
2038         }
2039     }
2040 }
2041 #endif
2042
2043 void qmp_getfd(const char *fdname, Error **errp)
2044 {
2045     mon_fd_t *monfd;
2046     int fd;
2047
2048     fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
2049     if (fd == -1) {
2050         error_set(errp, QERR_FD_NOT_SUPPLIED);
2051         return;
2052     }
2053
2054     if (qemu_isdigit(fdname[0])) {
2055         error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2056                   "a name not starting with a digit");
2057         return;
2058     }
2059
2060     QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2061         if (strcmp(monfd->name, fdname) != 0) {
2062             continue;
2063         }
2064
2065         close(monfd->fd);
2066         monfd->fd = fd;
2067         return;
2068     }
2069
2070     monfd = g_malloc0(sizeof(mon_fd_t));
2071     monfd->name = g_strdup(fdname);
2072     monfd->fd = fd;
2073
2074     QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2075 }
2076
2077 void qmp_closefd(const char *fdname, Error **errp)
2078 {
2079     mon_fd_t *monfd;
2080
2081     QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2082         if (strcmp(monfd->name, fdname) != 0) {
2083             continue;
2084         }
2085
2086         QLIST_REMOVE(monfd, next);
2087         close(monfd->fd);
2088         g_free(monfd->name);
2089         g_free(monfd);
2090         return;
2091     }
2092
2093     error_set(errp, QERR_FD_NOT_FOUND, fdname);
2094 }
2095
2096 static void do_loadvm(Monitor *mon, const QDict *qdict)
2097 {
2098     int saved_vm_running  = runstate_is_running();
2099     const char *name = qdict_get_str(qdict, "name");
2100
2101     vm_stop(RUN_STATE_RESTORE_VM);
2102
2103     if (load_vmstate(name) == 0 && saved_vm_running) {
2104         vm_start();
2105     }
2106 }
2107
2108 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2109 {
2110     mon_fd_t *monfd;
2111
2112     QLIST_FOREACH(monfd, &mon->fds, next) {
2113         int fd;
2114
2115         if (strcmp(monfd->name, fdname) != 0) {
2116             continue;
2117         }
2118
2119         fd = monfd->fd;
2120
2121         /* caller takes ownership of fd */
2122         QLIST_REMOVE(monfd, next);
2123         g_free(monfd->name);
2124         g_free(monfd);
2125
2126         return fd;
2127     }
2128
2129     error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2130     return -1;
2131 }
2132
2133 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2134 {
2135     MonFdsetFd *mon_fdset_fd;
2136     MonFdsetFd *mon_fdset_fd_next;
2137
2138     QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2139         if ((mon_fdset_fd->removed ||
2140                 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2141                 runstate_is_running()) {
2142             close(mon_fdset_fd->fd);
2143             g_free(mon_fdset_fd->opaque);
2144             QLIST_REMOVE(mon_fdset_fd, next);
2145             g_free(mon_fdset_fd);
2146         }
2147     }
2148
2149     if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2150         QLIST_REMOVE(mon_fdset, next);
2151         g_free(mon_fdset);
2152     }
2153 }
2154
2155 static void monitor_fdsets_cleanup(void)
2156 {
2157     MonFdset *mon_fdset;
2158     MonFdset *mon_fdset_next;
2159
2160     QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2161         monitor_fdset_cleanup(mon_fdset);
2162     }
2163 }
2164
2165 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2166                       const char *opaque, Error **errp)
2167 {
2168     int fd;
2169     Monitor *mon = cur_mon;
2170     AddfdInfo *fdinfo;
2171
2172     fd = qemu_chr_fe_get_msgfd(mon->chr);
2173     if (fd == -1) {
2174         error_set(errp, QERR_FD_NOT_SUPPLIED);
2175         goto error;
2176     }
2177
2178     fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2179                                   has_opaque, opaque, errp);
2180     if (fdinfo) {
2181         return fdinfo;
2182     }
2183
2184 error:
2185     if (fd != -1) {
2186         close(fd);
2187     }
2188     return NULL;
2189 }
2190
2191 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2192 {
2193     MonFdset *mon_fdset;
2194     MonFdsetFd *mon_fdset_fd;
2195     char fd_str[60];
2196
2197     QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2198         if (mon_fdset->id != fdset_id) {
2199             continue;
2200         }
2201         QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2202             if (has_fd) {
2203                 if (mon_fdset_fd->fd != fd) {
2204                     continue;
2205                 }
2206                 mon_fdset_fd->removed = true;
2207                 break;
2208             } else {
2209                 mon_fdset_fd->removed = true;
2210             }
2211         }
2212         if (has_fd && !mon_fdset_fd) {
2213             goto error;
2214         }
2215         monitor_fdset_cleanup(mon_fdset);
2216         return;
2217     }
2218
2219 error:
2220     if (has_fd) {
2221         snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2222                  fdset_id, fd);
2223     } else {
2224         snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2225     }
2226     error_set(errp, QERR_FD_NOT_FOUND, fd_str);
2227 }
2228
2229 FdsetInfoList *qmp_query_fdsets(Error **errp)
2230 {
2231     MonFdset *mon_fdset;
2232     MonFdsetFd *mon_fdset_fd;
2233     FdsetInfoList *fdset_list = NULL;
2234
2235     QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2236         FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2237         FdsetFdInfoList *fdsetfd_list = NULL;
2238
2239         fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2240         fdset_info->value->fdset_id = mon_fdset->id;
2241
2242         QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2243             FdsetFdInfoList *fdsetfd_info;
2244
2245             fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2246             fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2247             fdsetfd_info->value->fd = mon_fdset_fd->fd;
2248             if (mon_fdset_fd->opaque) {
2249                 fdsetfd_info->value->has_opaque = true;
2250                 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2251             } else {
2252                 fdsetfd_info->value->has_opaque = false;
2253             }
2254
2255             fdsetfd_info->next = fdsetfd_list;
2256             fdsetfd_list = fdsetfd_info;
2257         }
2258
2259         fdset_info->value->fds = fdsetfd_list;
2260
2261         fdset_info->next = fdset_list;
2262         fdset_list = fdset_info;
2263     }
2264
2265     return fdset_list;
2266 }
2267
2268 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2269                                 bool has_opaque, const char *opaque,
2270                                 Error **errp)
2271 {
2272     MonFdset *mon_fdset = NULL;
2273     MonFdsetFd *mon_fdset_fd;
2274     AddfdInfo *fdinfo;
2275
2276     if (has_fdset_id) {
2277         QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2278             /* Break if match found or match impossible due to ordering by ID */
2279             if (fdset_id <= mon_fdset->id) {
2280                 if (fdset_id < mon_fdset->id) {
2281                     mon_fdset = NULL;
2282                 }
2283                 break;
2284             }
2285         }
2286     }
2287
2288     if (mon_fdset == NULL) {
2289         int64_t fdset_id_prev = -1;
2290         MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2291
2292         if (has_fdset_id) {
2293             if (fdset_id < 0) {
2294                 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2295                           "a non-negative value");
2296                 return NULL;
2297             }
2298             /* Use specified fdset ID */
2299             QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2300                 mon_fdset_cur = mon_fdset;
2301                 if (fdset_id < mon_fdset_cur->id) {
2302                     break;
2303                 }
2304             }
2305         } else {
2306             /* Use first available fdset ID */
2307             QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2308                 mon_fdset_cur = mon_fdset;
2309                 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2310                     fdset_id_prev = mon_fdset_cur->id;
2311                     continue;
2312                 }
2313                 break;
2314             }
2315         }
2316
2317         mon_fdset = g_malloc0(sizeof(*mon_fdset));
2318         if (has_fdset_id) {
2319             mon_fdset->id = fdset_id;
2320         } else {
2321             mon_fdset->id = fdset_id_prev + 1;
2322         }
2323
2324         /* The fdset list is ordered by fdset ID */
2325         if (!mon_fdset_cur) {
2326             QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2327         } else if (mon_fdset->id < mon_fdset_cur->id) {
2328             QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2329         } else {
2330             QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2331         }
2332     }
2333
2334     mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2335     mon_fdset_fd->fd = fd;
2336     mon_fdset_fd->removed = false;
2337     if (has_opaque) {
2338         mon_fdset_fd->opaque = g_strdup(opaque);
2339     }
2340     QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2341
2342     fdinfo = g_malloc0(sizeof(*fdinfo));
2343     fdinfo->fdset_id = mon_fdset->id;
2344     fdinfo->fd = mon_fdset_fd->fd;
2345
2346     return fdinfo;
2347 }
2348
2349 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2350 {
2351 #ifndef _WIN32
2352     MonFdset *mon_fdset;
2353     MonFdsetFd *mon_fdset_fd;
2354     int mon_fd_flags;
2355
2356     QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2357         if (mon_fdset->id != fdset_id) {
2358             continue;
2359         }
2360         QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2361             mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2362             if (mon_fd_flags == -1) {
2363                 return -1;
2364             }
2365
2366             if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2367                 return mon_fdset_fd->fd;
2368             }
2369         }
2370         errno = EACCES;
2371         return -1;
2372     }
2373 #endif
2374
2375     errno = ENOENT;
2376     return -1;
2377 }
2378
2379 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2380 {
2381     MonFdset *mon_fdset;
2382     MonFdsetFd *mon_fdset_fd_dup;
2383
2384     QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2385         if (mon_fdset->id != fdset_id) {
2386             continue;
2387         }
2388         QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2389             if (mon_fdset_fd_dup->fd == dup_fd) {
2390                 return -1;
2391             }
2392         }
2393         mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2394         mon_fdset_fd_dup->fd = dup_fd;
2395         QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2396         return 0;
2397     }
2398     return -1;
2399 }
2400
2401 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2402 {
2403     MonFdset *mon_fdset;
2404     MonFdsetFd *mon_fdset_fd_dup;
2405
2406     QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2407         QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2408             if (mon_fdset_fd_dup->fd == dup_fd) {
2409                 if (remove) {
2410                     QLIST_REMOVE(mon_fdset_fd_dup, next);
2411                     if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2412                         monitor_fdset_cleanup(mon_fdset);
2413                     }
2414                 }
2415                 return mon_fdset->id;
2416             }
2417         }
2418     }
2419     return -1;
2420 }
2421
2422 int monitor_fdset_dup_fd_find(int dup_fd)
2423 {
2424     return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2425 }
2426
2427 int monitor_fdset_dup_fd_remove(int dup_fd)
2428 {
2429     return monitor_fdset_dup_fd_find_remove(dup_fd, true);
2430 }
2431
2432 int monitor_handle_fd_param(Monitor *mon, const char *fdname)
2433 {
2434     int fd;
2435     Error *local_err = NULL;
2436
2437     if (!qemu_isdigit(fdname[0]) && mon) {
2438
2439         fd = monitor_get_fd(mon, fdname, &local_err);
2440         if (fd == -1) {
2441             qerror_report_err(local_err);
2442             error_free(local_err);
2443             return -1;
2444         }
2445     } else {
2446         fd = qemu_parse_fd(fdname);
2447     }
2448
2449     return fd;
2450 }
2451
2452 /* Please update hmp-commands.hx when adding or changing commands */
2453 static mon_cmd_t info_cmds[] = {
2454     {
2455         .name       = "version",
2456         .args_type  = "",
2457         .params     = "",
2458         .help       = "show the version of QEMU",
2459         .mhandler.cmd = hmp_info_version,
2460     },
2461     {
2462         .name       = "network",
2463         .args_type  = "",
2464         .params     = "",
2465         .help       = "show the network state",
2466         .mhandler.cmd = do_info_network,
2467     },
2468     {
2469         .name       = "chardev",
2470         .args_type  = "",
2471         .params     = "",
2472         .help       = "show the character devices",
2473         .mhandler.cmd = hmp_info_chardev,
2474     },
2475     {
2476         .name       = "block",
2477         .args_type  = "",
2478         .params     = "",
2479         .help       = "show the block devices",
2480         .mhandler.cmd = hmp_info_block,
2481     },
2482     {
2483         .name       = "blockstats",
2484         .args_type  = "",
2485         .params     = "",
2486         .help       = "show block device statistics",
2487         .mhandler.cmd = hmp_info_blockstats,
2488     },
2489     {
2490         .name       = "block-jobs",
2491         .args_type  = "",
2492         .params     = "",
2493         .help       = "show progress of ongoing block device operations",
2494         .mhandler.cmd = hmp_info_block_jobs,
2495     },
2496     {
2497         .name       = "registers",
2498         .args_type  = "",
2499         .params     = "",
2500         .help       = "show the cpu registers",
2501         .mhandler.cmd = do_info_registers,
2502     },
2503     {
2504         .name       = "cpus",
2505         .args_type  = "",
2506         .params     = "",
2507         .help       = "show infos for each CPU",
2508         .mhandler.cmd = hmp_info_cpus,
2509     },
2510     {
2511         .name       = "history",
2512         .args_type  = "",
2513         .params     = "",
2514         .help       = "show the command line history",
2515         .mhandler.cmd = do_info_history,
2516     },
2517 #if defined(TARGET_I386) || defined(TARGET_PPC) || defined(TARGET_MIPS) || \
2518     defined(TARGET_LM32) || (defined(TARGET_SPARC) && !defined(TARGET_SPARC64))
2519     {
2520         .name       = "irq",
2521         .args_type  = "",
2522         .params     = "",
2523         .help       = "show the interrupts statistics (if available)",
2524 #ifdef TARGET_SPARC
2525         .mhandler.cmd = sun4m_irq_info,
2526 #elif defined(TARGET_LM32)
2527         .mhandler.cmd = lm32_irq_info,
2528 #else
2529         .mhandler.cmd = irq_info,
2530 #endif
2531     },
2532     {
2533         .name       = "pic",
2534         .args_type  = "",
2535         .params     = "",
2536         .help       = "show i8259 (PIC) state",
2537 #ifdef TARGET_SPARC
2538         .mhandler.cmd = sun4m_pic_info,
2539 #elif defined(TARGET_LM32)
2540         .mhandler.cmd = lm32_do_pic_info,
2541 #else
2542         .mhandler.cmd = pic_info,
2543 #endif
2544     },
2545 #endif
2546     {
2547         .name       = "pci",
2548         .args_type  = "",
2549         .params     = "",
2550         .help       = "show PCI info",
2551         .mhandler.cmd = hmp_info_pci,
2552     },
2553 #if defined(TARGET_I386) || defined(TARGET_SH4) || defined(TARGET_SPARC) || \
2554     defined(TARGET_PPC) || defined(TARGET_XTENSA)
2555     {
2556         .name       = "tlb",
2557         .args_type  = "",
2558         .params     = "",
2559         .help       = "show virtual to physical memory mappings",
2560         .mhandler.cmd = tlb_info,
2561     },
2562 #endif
2563 #if defined(TARGET_I386)
2564     {
2565         .name       = "mem",
2566         .args_type  = "",
2567         .params     = "",
2568         .help       = "show the active virtual memory mappings",
2569         .mhandler.cmd = mem_info,
2570     },
2571 #endif
2572     {
2573         .name       = "mtree",
2574         .args_type  = "",
2575         .params     = "",
2576         .help       = "show memory tree",
2577         .mhandler.cmd = do_info_mtree,
2578     },
2579     {
2580         .name       = "jit",
2581         .args_type  = "",
2582         .params     = "",
2583         .help       = "show dynamic compiler info",
2584         .mhandler.cmd = do_info_jit,
2585     },
2586     {
2587         .name       = "kvm",
2588         .args_type  = "",
2589         .params     = "",
2590         .help       = "show KVM information",
2591         .mhandler.cmd = hmp_info_kvm,
2592     },
2593     {
2594         .name       = "numa",
2595         .args_type  = "",
2596         .params     = "",
2597         .help       = "show NUMA information",
2598         .mhandler.cmd = do_info_numa,
2599     },
2600     {
2601         .name       = "usb",
2602         .args_type  = "",
2603         .params     = "",
2604         .help       = "show guest USB devices",
2605         .mhandler.cmd = usb_info,
2606     },
2607     {
2608         .name       = "usbhost",
2609         .args_type  = "",
2610         .params     = "",
2611         .help       = "show host USB devices",
2612         .mhandler.cmd = usb_host_info,
2613     },
2614     {
2615         .name       = "profile",
2616         .args_type  = "",
2617         .params     = "",
2618         .help       = "show profiling information",
2619         .mhandler.cmd = do_info_profile,
2620     },
2621     {
2622         .name       = "capture",
2623         .args_type  = "",
2624         .params     = "",
2625         .help       = "show capture information",
2626         .mhandler.cmd = do_info_capture,
2627     },
2628     {
2629         .name       = "snapshots",
2630         .args_type  = "",
2631         .params     = "",
2632         .help       = "show the currently saved VM snapshots",
2633         .mhandler.cmd = do_info_snapshots,
2634     },
2635     {
2636         .name       = "status",
2637         .args_type  = "",
2638         .params     = "",
2639         .help       = "show the current VM status (running|paused)",
2640         .mhandler.cmd = hmp_info_status,
2641     },
2642     {
2643         .name       = "pcmcia",
2644         .args_type  = "",
2645         .params     = "",
2646         .help       = "show guest PCMCIA status",
2647         .mhandler.cmd = pcmcia_info,
2648     },
2649     {
2650         .name       = "mice",
2651         .args_type  = "",
2652         .params     = "",
2653         .help       = "show which guest mouse is receiving events",
2654         .mhandler.cmd = hmp_info_mice,
2655     },
2656     {
2657         .name       = "vnc",
2658         .args_type  = "",
2659         .params     = "",
2660         .help       = "show the vnc server status",
2661         .mhandler.cmd = hmp_info_vnc,
2662     },
2663 #if defined(CONFIG_SPICE)
2664     {
2665         .name       = "spice",
2666         .args_type  = "",
2667         .params     = "",
2668         .help       = "show the spice server status",
2669         .mhandler.cmd = hmp_info_spice,
2670     },
2671 #endif
2672     {
2673         .name       = "name",
2674         .args_type  = "",
2675         .params     = "",
2676         .help       = "show the current VM name",
2677         .mhandler.cmd = hmp_info_name,
2678     },
2679     {
2680         .name       = "uuid",
2681         .args_type  = "",
2682         .params     = "",
2683         .help       = "show the current VM UUID",
2684         .mhandler.cmd = hmp_info_uuid,
2685     },
2686 #if defined(TARGET_PPC)
2687     {
2688         .name       = "cpustats",
2689         .args_type  = "",
2690         .params     = "",
2691         .help       = "show CPU statistics",
2692         .mhandler.cmd = do_info_cpu_stats,
2693     },
2694 #endif
2695 #if defined(CONFIG_SLIRP)
2696     {
2697         .name       = "usernet",
2698         .args_type  = "",
2699         .params     = "",
2700         .help       = "show user network stack connection states",
2701         .mhandler.cmd = do_info_usernet,
2702     },
2703 #endif
2704     {
2705         .name       = "migrate",
2706         .args_type  = "",
2707         .params     = "",
2708         .help       = "show migration status",
2709         .mhandler.cmd = hmp_info_migrate,
2710     },
2711     {
2712         .name       = "migrate_capabilities",
2713         .args_type  = "",
2714         .params     = "",
2715         .help       = "show current migration capabilities",
2716         .mhandler.cmd = hmp_info_migrate_capabilities,
2717     },
2718     {
2719         .name       = "migrate_cache_size",
2720         .args_type  = "",
2721         .params     = "",
2722         .help       = "show current migration xbzrle cache size",
2723         .mhandler.cmd = hmp_info_migrate_cache_size,
2724     },
2725     {
2726         .name       = "balloon",
2727         .args_type  = "",
2728         .params     = "",
2729         .help       = "show balloon information",
2730         .mhandler.cmd = hmp_info_balloon,
2731     },
2732     {
2733         .name       = "qtree",
2734         .args_type  = "",
2735         .params     = "",
2736         .help       = "show device tree",
2737         .mhandler.cmd = do_info_qtree,
2738     },
2739     {
2740         .name       = "qdm",
2741         .args_type  = "",
2742         .params     = "",
2743         .help       = "show qdev device model list",
2744         .mhandler.cmd = do_info_qdm,
2745     },
2746     {
2747         .name       = "roms",
2748         .args_type  = "",
2749         .params     = "",
2750         .help       = "show roms",
2751         .mhandler.cmd = do_info_roms,
2752     },
2753     {
2754         .name       = "trace-events",
2755         .args_type  = "",
2756         .params     = "",
2757         .help       = "show available trace-events & their state",
2758         .mhandler.cmd = do_trace_print_events,
2759     },
2760     {
2761         .name       = "tpm",
2762         .args_type  = "",
2763         .params     = "",
2764         .help       = "show the TPM device",
2765         .mhandler.cmd = hmp_info_tpm,
2766     },
2767     {
2768         .name       = "cpu_max",
2769         .args_type  = "",
2770         .params     = "",
2771         .help       = "Get maximum number of VCPUs supported by machine",
2772         .mhandler.cmd = hmp_query_cpu_max,
2773     },
2774     {
2775         .name       = NULL,
2776     },
2777 };
2778
2779 /* mon_cmds and info_cmds would be sorted at runtime */
2780 static mon_cmd_t mon_cmds[] = {
2781 #include "hmp-commands.h"
2782     { NULL, NULL, },
2783 };
2784
2785 static const mon_cmd_t qmp_cmds[] = {
2786 #include "qmp-commands-old.h"
2787     { /* NULL */ },
2788 };
2789
2790 /*******************************************************************/
2791
2792 static const char *pch;
2793 static sigjmp_buf expr_env;
2794
2795 #define MD_TLONG 0
2796 #define MD_I32   1
2797
2798 typedef struct MonitorDef {
2799     const char *name;
2800     int offset;
2801     target_long (*get_value)(const struct MonitorDef *md, int val);
2802     int type;
2803 } MonitorDef;
2804
2805 #if defined(TARGET_I386)
2806 static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2807 {
2808     CPUArchState *env = mon_get_cpu();
2809     return env->eip + env->segs[R_CS].base;
2810 }
2811 #endif
2812
2813 #if defined(TARGET_PPC)
2814 static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2815 {
2816     CPUArchState *env = mon_get_cpu();
2817     unsigned int u;
2818     int i;
2819
2820     u = 0;
2821     for (i = 0; i < 8; i++)
2822         u |= env->crf[i] << (32 - (4 * i));
2823
2824     return u;
2825 }
2826
2827 static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2828 {
2829     CPUArchState *env = mon_get_cpu();
2830     return env->msr;
2831 }
2832
2833 static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2834 {
2835     CPUArchState *env = mon_get_cpu();
2836     return env->xer;
2837 }
2838
2839 static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2840 {
2841     CPUArchState *env = mon_get_cpu();
2842     return cpu_ppc_load_decr(env);
2843 }
2844
2845 static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2846 {
2847     CPUArchState *env = mon_get_cpu();
2848     return cpu_ppc_load_tbu(env);
2849 }
2850
2851 static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2852 {
2853     CPUArchState *env = mon_get_cpu();
2854     return cpu_ppc_load_tbl(env);
2855 }
2856 #endif
2857
2858 #if defined(TARGET_SPARC)
2859 #ifndef TARGET_SPARC64
2860 static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2861 {
2862     CPUArchState *env = mon_get_cpu();
2863
2864     return cpu_get_psr(env);
2865 }
2866 #endif
2867
2868 static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2869 {
2870     CPUArchState *env = mon_get_cpu();
2871     return env->regwptr[val];
2872 }
2873 #endif
2874
2875 static const MonitorDef monitor_defs[] = {
2876 #ifdef TARGET_I386
2877
2878 #define SEG(name, seg) \
2879     { name, offsetof(CPUX86State, segs[seg].selector), NULL, MD_I32 },\
2880     { name ".base", offsetof(CPUX86State, segs[seg].base) },\
2881     { name ".limit", offsetof(CPUX86State, segs[seg].limit), NULL, MD_I32 },
2882
2883     { "eax", offsetof(CPUX86State, regs[0]) },
2884     { "ecx", offsetof(CPUX86State, regs[1]) },
2885     { "edx", offsetof(CPUX86State, regs[2]) },
2886     { "ebx", offsetof(CPUX86State, regs[3]) },
2887     { "esp|sp", offsetof(CPUX86State, regs[4]) },
2888     { "ebp|fp", offsetof(CPUX86State, regs[5]) },
2889     { "esi", offsetof(CPUX86State, regs[6]) },
2890     { "edi", offsetof(CPUX86State, regs[7]) },
2891 #ifdef TARGET_X86_64
2892     { "r8", offsetof(CPUX86State, regs[8]) },
2893     { "r9", offsetof(CPUX86State, regs[9]) },
2894     { "r10", offsetof(CPUX86State, regs[10]) },
2895     { "r11", offsetof(CPUX86State, regs[11]) },
2896     { "r12", offsetof(CPUX86State, regs[12]) },
2897     { "r13", offsetof(CPUX86State, regs[13]) },
2898     { "r14", offsetof(CPUX86State, regs[14]) },
2899     { "r15", offsetof(CPUX86State, regs[15]) },
2900 #endif
2901     { "eflags", offsetof(CPUX86State, eflags) },
2902     { "eip", offsetof(CPUX86State, eip) },
2903     SEG("cs", R_CS)
2904     SEG("ds", R_DS)
2905     SEG("es", R_ES)
2906     SEG("ss", R_SS)
2907     SEG("fs", R_FS)
2908     SEG("gs", R_GS)
2909     { "pc", 0, monitor_get_pc, },
2910 #elif defined(TARGET_PPC)
2911     /* General purpose registers */
2912     { "r0", offsetof(CPUPPCState, gpr[0]) },
2913     { "r1", offsetof(CPUPPCState, gpr[1]) },
2914     { "r2", offsetof(CPUPPCState, gpr[2]) },
2915     { "r3", offsetof(CPUPPCState, gpr[3]) },
2916     { "r4", offsetof(CPUPPCState, gpr[4]) },
2917     { "r5", offsetof(CPUPPCState, gpr[5]) },
2918     { "r6", offsetof(CPUPPCState, gpr[6]) },
2919     { "r7", offsetof(CPUPPCState, gpr[7]) },
2920     { "r8", offsetof(CPUPPCState, gpr[8]) },
2921     { "r9", offsetof(CPUPPCState, gpr[9]) },
2922     { "r10", offsetof(CPUPPCState, gpr[10]) },
2923     { "r11", offsetof(CPUPPCState, gpr[11]) },
2924     { "r12", offsetof(CPUPPCState, gpr[12]) },
2925     { "r13", offsetof(CPUPPCState, gpr[13]) },
2926     { "r14", offsetof(CPUPPCState, gpr[14]) },
2927     { "r15", offsetof(CPUPPCState, gpr[15]) },
2928     { "r16", offsetof(CPUPPCState, gpr[16]) },
2929     { "r17", offsetof(CPUPPCState, gpr[17]) },
2930     { "r18", offsetof(CPUPPCState, gpr[18]) },
2931     { "r19", offsetof(CPUPPCState, gpr[19]) },
2932     { "r20", offsetof(CPUPPCState, gpr[20]) },
2933     { "r21", offsetof(CPUPPCState, gpr[21]) },
2934     { "r22", offsetof(CPUPPCState, gpr[22]) },
2935     { "r23", offsetof(CPUPPCState, gpr[23]) },
2936     { "r24", offsetof(CPUPPCState, gpr[24]) },
2937     { "r25", offsetof(CPUPPCState, gpr[25]) },
2938     { "r26", offsetof(CPUPPCState, gpr[26]) },
2939     { "r27", offsetof(CPUPPCState, gpr[27]) },
2940     { "r28", offsetof(CPUPPCState, gpr[28]) },
2941     { "r29", offsetof(CPUPPCState, gpr[29]) },
2942     { "r30", offsetof(CPUPPCState, gpr[30]) },
2943     { "r31", offsetof(CPUPPCState, gpr[31]) },
2944     /* Floating point registers */
2945     { "f0", offsetof(CPUPPCState, fpr[0]) },
2946     { "f1", offsetof(CPUPPCState, fpr[1]) },
2947     { "f2", offsetof(CPUPPCState, fpr[2]) },
2948     { "f3", offsetof(CPUPPCState, fpr[3]) },
2949     { "f4", offsetof(CPUPPCState, fpr[4]) },
2950     { "f5", offsetof(CPUPPCState, fpr[5]) },
2951     { "f6", offsetof(CPUPPCState, fpr[6]) },
2952     { "f7", offsetof(CPUPPCState, fpr[7]) },
2953     { "f8", offsetof(CPUPPCState, fpr[8]) },
2954     { "f9", offsetof(CPUPPCState, fpr[9]) },
2955     { "f10", offsetof(CPUPPCState, fpr[10]) },
2956     { "f11", offsetof(CPUPPCState, fpr[11]) },
2957     { "f12", offsetof(CPUPPCState, fpr[12]) },
2958     { "f13", offsetof(CPUPPCState, fpr[13]) },
2959     { "f14", offsetof(CPUPPCState, fpr[14]) },
2960     { "f15", offsetof(CPUPPCState, fpr[15]) },
2961     { "f16", offsetof(CPUPPCState, fpr[16]) },
2962     { "f17", offsetof(CPUPPCState, fpr[17]) },
2963     { "f18", offsetof(CPUPPCState, fpr[18]) },
2964     { "f19", offsetof(CPUPPCState, fpr[19]) },
2965     { "f20", offsetof(CPUPPCState, fpr[20]) },
2966     { "f21", offsetof(CPUPPCState, fpr[21]) },
2967     { "f22", offsetof(CPUPPCState, fpr[22]) },
2968     { "f23", offsetof(CPUPPCState, fpr[23]) },
2969     { "f24", offsetof(CPUPPCState, fpr[24]) },
2970     { "f25", offsetof(CPUPPCState, fpr[25]) },
2971     { "f26", offsetof(CPUPPCState, fpr[26]) },
2972     { "f27", offsetof(CPUPPCState, fpr[27]) },
2973     { "f28", offsetof(CPUPPCState, fpr[28]) },
2974     { "f29", offsetof(CPUPPCState, fpr[29]) },
2975     { "f30", offsetof(CPUPPCState, fpr[30]) },
2976     { "f31", offsetof(CPUPPCState, fpr[31]) },
2977     { "fpscr", offsetof(CPUPPCState, fpscr) },
2978     /* Next instruction pointer */
2979     { "nip|pc", offsetof(CPUPPCState, nip) },
2980     { "lr", offsetof(CPUPPCState, lr) },
2981     { "ctr", offsetof(CPUPPCState, ctr) },
2982     { "decr", 0, &monitor_get_decr, },
2983     { "ccr", 0, &monitor_get_ccr, },
2984     /* Machine state register */
2985     { "msr", 0, &monitor_get_msr, },
2986     { "xer", 0, &monitor_get_xer, },
2987     { "tbu", 0, &monitor_get_tbu, },
2988     { "tbl", 0, &monitor_get_tbl, },
2989     /* Segment registers */
2990     { "sdr1", offsetof(CPUPPCState, spr[SPR_SDR1]) },
2991     { "sr0", offsetof(CPUPPCState, sr[0]) },
2992     { "sr1", offsetof(CPUPPCState, sr[1]) },
2993     { "sr2", offsetof(CPUPPCState, sr[2]) },
2994     { "sr3", offsetof(CPUPPCState, sr[3]) },
2995     { "sr4", offsetof(CPUPPCState, sr[4]) },
2996     { "sr5", offsetof(CPUPPCState, sr[5]) },
2997     { "sr6", offsetof(CPUPPCState, sr[6]) },
2998     { "sr7", offsetof(CPUPPCState, sr[7]) },
2999     { "sr8", offsetof(CPUPPCState, sr[8]) },
3000     { "sr9", offsetof(CPUPPCState, sr[9]) },
3001     { "sr10", offsetof(CPUPPCState, sr[10]) },
3002     { "sr11", offsetof(CPUPPCState, sr[11]) },
3003     { "sr12", offsetof(CPUPPCState, sr[12]) },
3004     { "sr13", offsetof(CPUPPCState, sr[13]) },
3005     { "sr14", offsetof(CPUPPCState, sr[14]) },
3006     { "sr15", offsetof(CPUPPCState, sr[15]) },
3007     /* Too lazy to put BATs... */
3008     { "pvr", offsetof(CPUPPCState, spr[SPR_PVR]) },
3009
3010     { "srr0", offsetof(CPUPPCState, spr[SPR_SRR0]) },
3011     { "srr1", offsetof(CPUPPCState, spr[SPR_SRR1]) },
3012     { "sprg0", offsetof(CPUPPCState, spr[SPR_SPRG0]) },
3013     { "sprg1", offsetof(CPUPPCState, spr[SPR_SPRG1]) },
3014     { "sprg2", offsetof(CPUPPCState, spr[SPR_SPRG2]) },
3015     { "sprg3", offsetof(CPUPPCState, spr[SPR_SPRG3]) },
3016     { "sprg4", offsetof(CPUPPCState, spr[SPR_SPRG4]) },
3017     { "sprg5", offsetof(CPUPPCState, spr[SPR_SPRG5]) },
3018     { "sprg6", offsetof(CPUPPCState, spr[SPR_SPRG6]) },
3019     { "sprg7", offsetof(CPUPPCState, spr[SPR_SPRG7]) },
3020     { "pid", offsetof(CPUPPCState, spr[SPR_BOOKE_PID]) },
3021     { "csrr0", offsetof(CPUPPCState, spr[SPR_BOOKE_CSRR0]) },
3022     { "csrr1", offsetof(CPUPPCState, spr[SPR_BOOKE_CSRR1]) },
3023     { "esr", offsetof(CPUPPCState, spr[SPR_BOOKE_ESR]) },
3024     { "dear", offsetof(CPUPPCState, spr[SPR_BOOKE_DEAR]) },
3025     { "mcsr", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSR]) },
3026     { "tsr", offsetof(CPUPPCState, spr[SPR_BOOKE_TSR]) },
3027     { "tcr", offsetof(CPUPPCState, spr[SPR_BOOKE_TCR]) },
3028     { "vrsave", offsetof(CPUPPCState, spr[SPR_VRSAVE]) },
3029     { "pir", offsetof(CPUPPCState, spr[SPR_BOOKE_PIR]) },
3030     { "mcsrr0", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSRR0]) },
3031     { "mcsrr1", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSRR1]) },
3032     { "decar", offsetof(CPUPPCState, spr[SPR_BOOKE_DECAR]) },
3033     { "ivpr", offsetof(CPUPPCState, spr[SPR_BOOKE_IVPR]) },
3034     { "epcr", offsetof(CPUPPCState, spr[SPR_BOOKE_EPCR]) },
3035     { "sprg8", offsetof(CPUPPCState, spr[SPR_BOOKE_SPRG8]) },
3036     { "ivor0", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR0]) },
3037     { "ivor1", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR1]) },
3038     { "ivor2", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR2]) },
3039     { "ivor3", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR3]) },
3040     { "ivor4", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR4]) },
3041     { "ivor5", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR5]) },
3042     { "ivor6", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR6]) },
3043     { "ivor7", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR7]) },
3044     { "ivor8", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR8]) },
3045     { "ivor9", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR9]) },
3046     { "ivor10", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR10]) },
3047     { "ivor11", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR11]) },
3048     { "ivor12", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR12]) },
3049     { "ivor13", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR13]) },
3050     { "ivor14", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR14]) },
3051     { "ivor15", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR15]) },
3052     { "ivor32", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR32]) },
3053     { "ivor33", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR33]) },
3054     { "ivor34", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR34]) },
3055     { "ivor35", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR35]) },
3056     { "ivor36", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR36]) },
3057     { "ivor37", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR37]) },
3058     { "mas0", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS0]) },
3059     { "mas1", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS1]) },
3060     { "mas2", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS2]) },
3061     { "mas3", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS3]) },
3062     { "mas4", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS4]) },
3063     { "mas6", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS6]) },
3064     { "mas7", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS7]) },
3065     { "mmucfg", offsetof(CPUPPCState, spr[SPR_MMUCFG]) },
3066     { "tlb0cfg", offsetof(CPUPPCState, spr[SPR_BOOKE_TLB0CFG]) },
3067     { "tlb1cfg", offsetof(CPUPPCState, spr[SPR_BOOKE_TLB1CFG]) },
3068     { "epr", offsetof(CPUPPCState, spr[SPR_BOOKE_EPR]) },
3069     { "eplc", offsetof(CPUPPCState, spr[SPR_BOOKE_EPLC]) },
3070     { "epsc", offsetof(CPUPPCState, spr[SPR_BOOKE_EPSC]) },
3071     { "svr", offsetof(CPUPPCState, spr[SPR_E500_SVR]) },
3072     { "mcar", offsetof(CPUPPCState, spr[SPR_Exxx_MCAR]) },
3073     { "pid1", offsetof(CPUPPCState, spr[SPR_BOOKE_PID1]) },
3074     { "pid2", offsetof(CPUPPCState, spr[SPR_BOOKE_PID2]) },
3075     { "hid0", offsetof(CPUPPCState, spr[SPR_HID0]) },
3076
3077 #elif defined(TARGET_SPARC)
3078     { "g0", offsetof(CPUSPARCState, gregs[0]) },
3079     { "g1", offsetof(CPUSPARCState, gregs[1]) },
3080     { "g2", offsetof(CPUSPARCState, gregs[2]) },
3081     { "g3", offsetof(CPUSPARCState, gregs[3]) },
3082     { "g4", offsetof(CPUSPARCState, gregs[4]) },
3083     { "g5", offsetof(CPUSPARCState, gregs[5]) },
3084     { "g6", offsetof(CPUSPARCState, gregs[6]) },
3085     { "g7", offsetof(CPUSPARCState, gregs[7]) },
3086     { "o0", 0, monitor_get_reg },
3087     { "o1", 1, monitor_get_reg },
3088     { "o2", 2, monitor_get_reg },
3089     { "o3", 3, monitor_get_reg },
3090     { "o4", 4, monitor_get_reg },
3091     { "o5", 5, monitor_get_reg },
3092     { "o6", 6, monitor_get_reg },
3093     { "o7", 7, monitor_get_reg },
3094     { "l0", 8, monitor_get_reg },
3095     { "l1", 9, monitor_get_reg },
3096     { "l2", 10, monitor_get_reg },
3097     { "l3", 11, monitor_get_reg },
3098     { "l4", 12, monitor_get_reg },
3099     { "l5", 13, monitor_get_reg },
3100     { "l6", 14, monitor_get_reg },
3101     { "l7", 15, monitor_get_reg },
3102     { "i0", 16, monitor_get_reg },
3103     { "i1", 17, monitor_get_reg },
3104     { "i2", 18, monitor_get_reg },
3105     { "i3", 19, monitor_get_reg },
3106     { "i4", 20, monitor_get_reg },
3107     { "i5", 21, monitor_get_reg },
3108     { "i6", 22, monitor_get_reg },
3109     { "i7", 23, monitor_get_reg },
3110     { "pc", offsetof(CPUSPARCState, pc) },
3111     { "npc", offsetof(CPUSPARCState, npc) },
3112     { "y", offsetof(CPUSPARCState, y) },
3113 #ifndef TARGET_SPARC64
3114     { "psr", 0, &monitor_get_psr, },
3115     { "wim", offsetof(CPUSPARCState, wim) },
3116 #endif
3117     { "tbr", offsetof(CPUSPARCState, tbr) },
3118     { "fsr", offsetof(CPUSPARCState, fsr) },
3119     { "f0", offsetof(CPUSPARCState, fpr[0].l.upper) },
3120     { "f1", offsetof(CPUSPARCState, fpr[0].l.lower) },
3121     { "f2", offsetof(CPUSPARCState, fpr[1].l.upper) },
3122     { "f3", offsetof(CPUSPARCState, fpr[1].l.lower) },
3123     { "f4", offsetof(CPUSPARCState, fpr[2].l.upper) },
3124     { "f5", offsetof(CPUSPARCState, fpr[2].l.lower) },
3125     { "f6", offsetof(CPUSPARCState, fpr[3].l.upper) },
3126     { "f7", offsetof(CPUSPARCState, fpr[3].l.lower) },
3127     { "f8", offsetof(CPUSPARCState, fpr[4].l.upper) },
3128     { "f9", offsetof(CPUSPARCState, fpr[4].l.lower) },
3129     { "f10", offsetof(CPUSPARCState, fpr[5].l.upper) },
3130     { "f11", offsetof(CPUSPARCState, fpr[5].l.lower) },
3131     { "f12", offsetof(CPUSPARCState, fpr[6].l.upper) },
3132     { "f13", offsetof(CPUSPARCState, fpr[6].l.lower) },
3133     { "f14", offsetof(CPUSPARCState, fpr[7].l.upper) },
3134     { "f15", offsetof(CPUSPARCState, fpr[7].l.lower) },
3135     { "f16", offsetof(CPUSPARCState, fpr[8].l.upper) },
3136     { "f17", offsetof(CPUSPARCState, fpr[8].l.lower) },
3137     { "f18", offsetof(CPUSPARCState, fpr[9].l.upper) },
3138     { "f19", offsetof(CPUSPARCState, fpr[9].l.lower) },
3139     { "f20", offsetof(CPUSPARCState, fpr[10].l.upper) },
3140     { "f21", offsetof(CPUSPARCState, fpr[10].l.lower) },
3141     { "f22", offsetof(CPUSPARCState, fpr[11].l.upper) },
3142     { "f23", offsetof(CPUSPARCState, fpr[11].l.lower) },
3143     { "f24", offsetof(CPUSPARCState, fpr[12].l.upper) },
3144     { "f25", offsetof(CPUSPARCState, fpr[12].l.lower) },
3145     { "f26", offsetof(CPUSPARCState, fpr[13].l.upper) },
3146     { "f27", offsetof(CPUSPARCState, fpr[13].l.lower) },
3147     { "f28", offsetof(CPUSPARCState, fpr[14].l.upper) },
3148     { "f29", offsetof(CPUSPARCState, fpr[14].l.lower) },
3149     { "f30", offsetof(CPUSPARCState, fpr[15].l.upper) },
3150     { "f31", offsetof(CPUSPARCState, fpr[15].l.lower) },
3151 #ifdef TARGET_SPARC64
3152     { "f32", offsetof(CPUSPARCState, fpr[16]) },
3153     { "f34", offsetof(CPUSPARCState, fpr[17]) },
3154     { "f36", offsetof(CPUSPARCState, fpr[18]) },
3155     { "f38", offsetof(CPUSPARCState, fpr[19]) },
3156     { "f40", offsetof(CPUSPARCState, fpr[20]) },
3157     { "f42", offsetof(CPUSPARCState, fpr[21]) },
3158     { "f44", offsetof(CPUSPARCState, fpr[22]) },
3159     { "f46", offsetof(CPUSPARCState, fpr[23]) },
3160     { "f48", offsetof(CPUSPARCState, fpr[24]) },
3161     { "f50", offsetof(CPUSPARCState, fpr[25]) },
3162     { "f52", offsetof(CPUSPARCState, fpr[26]) },
3163     { "f54", offsetof(CPUSPARCState, fpr[27]) },
3164     { "f56", offsetof(CPUSPARCState, fpr[28]) },
3165     { "f58", offsetof(CPUSPARCState, fpr[29]) },
3166     { "f60", offsetof(CPUSPARCState, fpr[30]) },
3167     { "f62", offsetof(CPUSPARCState, fpr[31]) },
3168     { "asi", offsetof(CPUSPARCState, asi) },
3169     { "pstate", offsetof(CPUSPARCState, pstate) },
3170     { "cansave", offsetof(CPUSPARCState, cansave) },
3171     { "canrestore", offsetof(CPUSPARCState, canrestore) },
3172     { "otherwin", offsetof(CPUSPARCState, otherwin) },
3173     { "wstate", offsetof(CPUSPARCState, wstate) },
3174     { "cleanwin", offsetof(CPUSPARCState, cleanwin) },
3175     { "fprs", offsetof(CPUSPARCState, fprs) },
3176 #endif
3177 #endif
3178     { NULL },
3179 };
3180
3181 static void expr_error(Monitor *mon, const char *msg)
3182 {
3183     monitor_printf(mon, "%s\n", msg);
3184     siglongjmp(expr_env, 1);
3185 }
3186
3187 /* return 0 if OK, -1 if not found */
3188 static int get_monitor_def(target_long *pval, const char *name)
3189 {
3190     const MonitorDef *md;
3191     void *ptr;
3192
3193     for(md = monitor_defs; md->name != NULL; md++) {
3194         if (compare_cmd(name, md->name)) {
3195             if (md->get_value) {
3196                 *pval = md->get_value(md, md->offset);
3197             } else {
3198                 CPUArchState *env = mon_get_cpu();
3199                 ptr = (uint8_t *)env + md->offset;
3200                 switch(md->type) {
3201                 case MD_I32:
3202                     *pval = *(int32_t *)ptr;
3203                     break;
3204                 case MD_TLONG:
3205                     *pval = *(target_long *)ptr;
3206                     break;
3207                 default:
3208                     *pval = 0;
3209                     break;
3210                 }
3211             }
3212             return 0;
3213         }
3214     }
3215     return -1;
3216 }
3217
3218 static void next(void)
3219 {
3220     if (*pch != '\0') {
3221         pch++;
3222         while (qemu_isspace(*pch))
3223             pch++;
3224     }
3225 }
3226
3227 static int64_t expr_sum(Monitor *mon);
3228
3229 static int64_t expr_unary(Monitor *mon)
3230 {
3231     int64_t n;
3232     char *p;
3233     int ret;
3234
3235     switch(*pch) {
3236     case '+':
3237         next();
3238         n = expr_unary(mon);
3239         break;
3240     case '-':
3241         next();
3242         n = -expr_unary(mon);
3243         break;
3244     case '~':
3245         next();
3246         n = ~expr_unary(mon);
3247         break;
3248     case '(':
3249         next();
3250         n = expr_sum(mon);
3251         if (*pch != ')') {
3252             expr_error(mon, "')' expected");
3253         }
3254         next();
3255         break;
3256     case '\'':
3257         pch++;
3258         if (*pch == '\0')
3259             expr_error(mon, "character constant expected");
3260         n = *pch;
3261         pch++;
3262         if (*pch != '\'')
3263             expr_error(mon, "missing terminating \' character");
3264         next();
3265         break;
3266     case '$':
3267         {
3268             char buf[128], *q;
3269             target_long reg=0;
3270
3271             pch++;
3272             q = buf;
3273             while ((*pch >= 'a' && *pch <= 'z') ||
3274                    (*pch >= 'A' && *pch <= 'Z') ||
3275                    (*pch >= '0' && *pch <= '9') ||
3276                    *pch == '_' || *pch == '.') {
3277                 if ((q - buf) < sizeof(buf) - 1)
3278                     *q++ = *pch;
3279                 pch++;
3280             }
3281             while (qemu_isspace(*pch))
3282                 pch++;
3283             *q = 0;
3284             ret = get_monitor_def(&reg, buf);
3285             if (ret < 0)
3286                 expr_error(mon, "unknown register");
3287             n = reg;
3288         }
3289         break;
3290     case '\0':
3291         expr_error(mon, "unexpected end of expression");
3292         n = 0;
3293         break;
3294     default:
3295         errno = 0;
3296         n = strtoull(pch, &p, 0);
3297         if (errno == ERANGE) {
3298             expr_error(mon, "number too large");
3299         }
3300         if (pch == p) {
3301             expr_error(mon, "invalid char in expression");
3302         }
3303         pch = p;
3304         while (qemu_isspace(*pch))
3305             pch++;
3306         break;
3307     }
3308     return n;
3309 }
3310
3311
3312 static int64_t expr_prod(Monitor *mon)
3313 {
3314     int64_t val, val2;
3315     int op;
3316
3317     val = expr_unary(mon);
3318     for(;;) {
3319         op = *pch;
3320         if (op != '*' && op != '/' && op != '%')
3321             break;
3322         next();
3323         val2 = expr_unary(mon);
3324         switch(op) {
3325         default:
3326         case '*':
3327             val *= val2;
3328             break;
3329         case '/':
3330         case '%':
3331             if (val2 == 0)
3332                 expr_error(mon, "division by zero");
3333             if (op == '/')
3334                 val /= val2;
3335             else
3336                 val %= val2;
3337             break;
3338         }
3339     }
3340     return val;
3341 }
3342
3343 static int64_t expr_logic(Monitor *mon)
3344 {
3345     int64_t val, val2;
3346     int op;
3347
3348     val = expr_prod(mon);
3349     for(;;) {
3350         op = *pch;
3351         if (op != '&' && op != '|' && op != '^')
3352             break;
3353         next();
3354         val2 = expr_prod(mon);
3355         switch(op) {
3356         default:
3357         case '&':
3358             val &= val2;
3359             break;
3360         case '|':
3361             val |= val2;
3362             break;
3363         case '^':
3364             val ^= val2;
3365             break;
3366         }
3367     }
3368     return val;
3369 }
3370
3371 static int64_t expr_sum(Monitor *mon)
3372 {
3373     int64_t val, val2;
3374     int op;
3375
3376     val = expr_logic(mon);
3377     for(;;) {
3378         op = *pch;
3379         if (op != '+' && op != '-')
3380             break;
3381         next();
3382         val2 = expr_logic(mon);
3383         if (op == '+')
3384             val += val2;
3385         else
3386             val -= val2;
3387     }
3388     return val;
3389 }
3390
3391 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3392 {
3393     pch = *pp;
3394     if (sigsetjmp(expr_env, 0)) {
3395         *pp = pch;
3396         return -1;
3397     }
3398     while (qemu_isspace(*pch))
3399         pch++;
3400     *pval = expr_sum(mon);
3401     *pp = pch;
3402     return 0;
3403 }
3404
3405 static int get_double(Monitor *mon, double *pval, const char **pp)
3406 {
3407     const char *p = *pp;
3408     char *tailp;
3409     double d;
3410
3411     d = strtod(p, &tailp);
3412     if (tailp == p) {
3413         monitor_printf(mon, "Number expected\n");
3414         return -1;
3415     }
3416     if (d != d || d - d != 0) {
3417         /* NaN or infinity */
3418         monitor_printf(mon, "Bad number\n");
3419         return -1;
3420     }
3421     *pval = d;
3422     *pp = tailp;
3423     return 0;
3424 }
3425
3426 static int get_str(char *buf, int buf_size, const char **pp)
3427 {
3428     const char *p;
3429     char *q;
3430     int c;
3431
3432     q = buf;
3433     p = *pp;
3434     while (qemu_isspace(*p))
3435         p++;
3436     if (*p == '\0') {
3437     fail:
3438         *q = '\0';
3439         *pp = p;
3440         return -1;
3441     }
3442     if (*p == '\"') {
3443         p++;
3444         while (*p != '\0' && *p != '\"') {
3445             if (*p == '\\') {
3446                 p++;
3447                 c = *p++;
3448                 switch(c) {
3449                 case 'n':
3450                     c = '\n';
3451                     break;
3452                 case 'r':
3453                     c = '\r';
3454                     break;
3455                 case '\\':
3456                 case '\'':
3457                 case '\"':
3458                     break;
3459                 default:
3460                     qemu_printf("unsupported escape code: '\\%c'\n", c);
3461                     goto fail;
3462                 }
3463                 if ((q - buf) < buf_size - 1) {
3464                     *q++ = c;
3465                 }
3466             } else {
3467                 if ((q - buf) < buf_size - 1) {
3468                     *q++ = *p;
3469                 }
3470                 p++;
3471             }
3472         }
3473         if (*p != '\"') {
3474             qemu_printf("unterminated string\n");
3475             goto fail;
3476         }
3477         p++;
3478     } else {
3479         while (*p != '\0' && !qemu_isspace(*p)) {
3480             if ((q - buf) < buf_size - 1) {
3481                 *q++ = *p;
3482             }
3483             p++;
3484         }
3485     }
3486     *q = '\0';
3487     *pp = p;
3488     return 0;
3489 }
3490
3491 /*
3492  * Store the command-name in cmdname, and return a pointer to
3493  * the remaining of the command string.
3494  */
3495 static const char *get_command_name(const char *cmdline,
3496                                     char *cmdname, size_t nlen)
3497 {
3498     size_t len;
3499     const char *p, *pstart;
3500
3501     p = cmdline;
3502     while (qemu_isspace(*p))
3503         p++;
3504     if (*p == '\0')
3505         return NULL;
3506     pstart = p;
3507     while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3508         p++;
3509     len = p - pstart;
3510     if (len > nlen - 1)
3511         len = nlen - 1;
3512     memcpy(cmdname, pstart, len);
3513     cmdname[len] = '\0';
3514     return p;
3515 }
3516
3517 /**
3518  * Read key of 'type' into 'key' and return the current
3519  * 'type' pointer.
3520  */
3521 static char *key_get_info(const char *type, char **key)
3522 {
3523     size_t len;
3524     char *p, *str;
3525
3526     if (*type == ',')
3527         type++;
3528
3529     p = strchr(type, ':');
3530     if (!p) {
3531         *key = NULL;
3532         return NULL;
3533     }
3534     len = p - type;
3535
3536     str = g_malloc(len + 1);
3537     memcpy(str, type, len);
3538     str[len] = '\0';
3539
3540     *key = str;
3541     return ++p;
3542 }
3543
3544 static int default_fmt_format = 'x';
3545 static int default_fmt_size = 4;
3546
3547 #define MAX_ARGS 16
3548
3549 static int is_valid_option(const char *c, const char *typestr)
3550 {
3551     char option[3];
3552   
3553     option[0] = '-';
3554     option[1] = *c;
3555     option[2] = '\0';
3556   
3557     typestr = strstr(typestr, option);
3558     return (typestr != NULL);
3559 }
3560
3561 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3562                                               const char *cmdname)
3563 {
3564     const mon_cmd_t *cmd;
3565
3566     for (cmd = disp_table; cmd->name != NULL; cmd++) {
3567         if (compare_cmd(cmdname, cmd->name)) {
3568             return cmd;
3569         }
3570     }
3571
3572     return NULL;
3573 }
3574
3575 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
3576 {
3577     return search_dispatch_table(qmp_cmds, cmdname);
3578 }
3579
3580 /*
3581  * Parse @cmdline according to command table @table.
3582  * If @cmdline is blank, return NULL.
3583  * If it can't be parsed, report to @mon, and return NULL.
3584  * Else, insert command arguments into @qdict, and return the command.
3585  * If a sub-command table exists, and if @cmdline contains an additional string
3586  * for a sub-command, this function will try to search the sub-command table.
3587  * If no additional string for a sub-command is present, this function will
3588  * return the command found in @table.
3589  * Do not assume the returned command points into @table!  It doesn't
3590  * when the command is a sub-command.
3591  */
3592 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3593                                               const char *cmdline,
3594                                               int start,
3595                                               mon_cmd_t *table,
3596                                               QDict *qdict)
3597 {
3598     const char *p, *typestr;
3599     int c;
3600     const mon_cmd_t *cmd;
3601     char cmdname[256];
3602     char buf[1024];
3603     char *key;
3604
3605 #ifdef DEBUG
3606     monitor_printf(mon, "command='%s', start='%d'\n", cmdline, start);
3607 #endif
3608
3609     /* extract the command name */
3610     p = get_command_name(cmdline + start, cmdname, sizeof(cmdname));
3611     if (!p)
3612         return NULL;
3613
3614     cmd = search_dispatch_table(table, cmdname);
3615     if (!cmd) {
3616         monitor_printf(mon, "unknown command: '%.*s'\n",
3617                        (int)(p - cmdline), cmdline);
3618         return NULL;
3619     }
3620
3621     /* filter out following useless space */
3622     while (qemu_isspace(*p)) {
3623         p++;
3624     }
3625     /* search sub command */
3626     if (cmd->sub_table != NULL) {
3627         /* check if user set additional command */
3628         if (*p == '\0') {
3629             return cmd;
3630         }
3631         return monitor_parse_command(mon, cmdline, p - cmdline,
3632                                      cmd->sub_table, qdict);
3633     }
3634
3635     /* parse the parameters */
3636     typestr = cmd->args_type;
3637     for(;;) {
3638         typestr = key_get_info(typestr, &key);
3639         if (!typestr)
3640             break;
3641         c = *typestr;
3642         typestr++;
3643         switch(c) {
3644         case 'F':
3645         case 'B':
3646         case 's':
3647             {
3648                 int ret;
3649
3650                 while (qemu_isspace(*p))
3651                     p++;
3652                 if (*typestr == '?') {
3653                     typestr++;
3654                     if (*p == '\0') {
3655                         /* no optional string: NULL argument */
3656                         break;
3657                     }
3658                 }
3659                 ret = get_str(buf, sizeof(buf), &p);
3660                 if (ret < 0) {
3661                     switch(c) {
3662                     case 'F':
3663                         monitor_printf(mon, "%s: filename expected\n",
3664                                        cmdname);
3665                         break;
3666                     case 'B':
3667                         monitor_printf(mon, "%s: block device name expected\n",
3668                                        cmdname);
3669                         break;
3670                     default:
3671                         monitor_printf(mon, "%s: string expected\n", cmdname);
3672                         break;
3673                     }
3674                     goto fail;
3675                 }
3676                 qdict_put(qdict, key, qstring_from_str(buf));
3677             }
3678             break;
3679         case 'O':
3680             {
3681                 QemuOptsList *opts_list;
3682                 QemuOpts *opts;
3683
3684                 opts_list = qemu_find_opts(key);
3685                 if (!opts_list || opts_list->desc->name) {
3686                     goto bad_type;
3687                 }
3688                 while (qemu_isspace(*p)) {
3689                     p++;
3690                 }
3691                 if (!*p)
3692                     break;
3693                 if (get_str(buf, sizeof(buf), &p) < 0) {
3694                     goto fail;
3695                 }
3696                 opts = qemu_opts_parse(opts_list, buf, 1);
3697                 if (!opts) {
3698                     goto fail;
3699                 }
3700                 qemu_opts_to_qdict(opts, qdict);
3701                 qemu_opts_del(opts);
3702             }
3703             break;
3704         case '/':
3705             {
3706                 int count, format, size;
3707
3708                 while (qemu_isspace(*p))
3709                     p++;
3710                 if (*p == '/') {
3711                     /* format found */
3712                     p++;
3713                     count = 1;
3714                     if (qemu_isdigit(*p)) {
3715                         count = 0;
3716                         while (qemu_isdigit(*p)) {
3717                             count = count * 10 + (*p - '0');
3718                             p++;
3719                         }
3720                     }
3721                     size = -1;
3722                     format = -1;
3723                     for(;;) {
3724                         switch(*p) {
3725                         case 'o':
3726                         case 'd':
3727                         case 'u':
3728                         case 'x':
3729                         case 'i':
3730                         case 'c':
3731                             format = *p++;
3732                             break;
3733                         case 'b':
3734                             size = 1;
3735                             p++;
3736                             break;
3737                         case 'h':
3738                             size = 2;
3739                             p++;
3740                             break;
3741                         case 'w':
3742                             size = 4;
3743                             p++;
3744                             break;
3745                         case 'g':
3746                         case 'L':
3747                             size = 8;
3748                             p++;
3749                             break;
3750                         default:
3751                             goto next;
3752                         }
3753                     }
3754                 next:
3755                     if (*p != '\0' && !qemu_isspace(*p)) {
3756                         monitor_printf(mon, "invalid char in format: '%c'\n",
3757                                        *p);
3758                         goto fail;
3759                     }
3760                     if (format < 0)
3761                         format = default_fmt_format;
3762                     if (format != 'i') {
3763                         /* for 'i', not specifying a size gives -1 as size */
3764                         if (size < 0)
3765                             size = default_fmt_size;
3766                         default_fmt_size = size;
3767                     }
3768                     default_fmt_format = format;
3769                 } else {
3770                     count = 1;
3771                     format = default_fmt_format;
3772                     if (format != 'i') {
3773                         size = default_fmt_size;
3774                     } else {
3775                         size = -1;
3776                     }
3777                 }
3778                 qdict_put(qdict, "count", qint_from_int(count));
3779                 qdict_put(qdict, "format", qint_from_int(format));
3780                 qdict_put(qdict, "size", qint_from_int(size));
3781             }
3782             break;
3783         case 'i':
3784         case 'l':
3785         case 'M':
3786             {
3787                 int64_t val;
3788
3789                 while (qemu_isspace(*p))
3790                     p++;
3791                 if (*typestr == '?' || *typestr == '.') {
3792                     if (*typestr == '?') {
3793                         if (*p == '\0') {
3794                             typestr++;
3795                             break;
3796                         }
3797                     } else {
3798                         if (*p == '.') {
3799                             p++;
3800                             while (qemu_isspace(*p))
3801                                 p++;
3802                         } else {
3803                             typestr++;
3804                             break;
3805                         }
3806                     }
3807                     typestr++;
3808                 }
3809                 if (get_expr(mon, &val, &p))
3810                     goto fail;
3811                 /* Check if 'i' is greater than 32-bit */
3812                 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3813                     monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3814                     monitor_printf(mon, "integer is for 32-bit values\n");
3815                     goto fail;
3816                 } else if (c == 'M') {
3817                     if (val < 0) {
3818                         monitor_printf(mon, "enter a positive value\n");
3819                         goto fail;
3820                     }
3821                     val <<= 20;
3822                 }
3823                 qdict_put(qdict, key, qint_from_int(val));
3824             }
3825             break;
3826         case 'o':
3827             {
3828                 int64_t val;
3829                 char *end;
3830
3831                 while (qemu_isspace(*p)) {
3832                     p++;
3833                 }
3834                 if (*typestr == '?') {
3835                     typestr++;
3836                     if (*p == '\0') {
3837                         break;
3838                     }
3839                 }
3840                 val = strtosz(p, &end);
3841                 if (val < 0) {
3842                     monitor_printf(mon, "invalid size\n");
3843                     goto fail;
3844                 }
3845                 qdict_put(qdict, key, qint_from_int(val));
3846                 p = end;
3847             }
3848             break;
3849         case 'T':
3850             {
3851                 double val;
3852
3853                 while (qemu_isspace(*p))
3854                     p++;
3855                 if (*typestr == '?') {
3856                     typestr++;
3857                     if (*p == '\0') {
3858                         break;
3859                     }
3860                 }
3861                 if (get_double(mon, &val, &p) < 0) {
3862                     goto fail;
3863                 }
3864                 if (p[0] && p[1] == 's') {
3865                     switch (*p) {
3866                     case 'm':
3867                         val /= 1e3; p += 2; break;
3868                     case 'u':
3869                         val /= 1e6; p += 2; break;
3870                     case 'n':
3871                         val /= 1e9; p += 2; break;
3872                     }
3873                 }
3874                 if (*p && !qemu_isspace(*p)) {
3875                     monitor_printf(mon, "Unknown unit suffix\n");
3876                     goto fail;
3877                 }
3878                 qdict_put(qdict, key, qfloat_from_double(val));
3879             }
3880             break;
3881         case 'b':
3882             {
3883                 const char *beg;
3884                 int val;
3885
3886                 while (qemu_isspace(*p)) {
3887                     p++;
3888                 }
3889                 beg = p;
3890                 while (qemu_isgraph(*p)) {
3891                     p++;
3892                 }
3893                 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3894                     val = 1;
3895                 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3896                     val = 0;
3897                 } else {
3898                     monitor_printf(mon, "Expected 'on' or 'off'\n");
3899                     goto fail;
3900                 }
3901                 qdict_put(qdict, key, qbool_from_int(val));
3902             }
3903             break;
3904         case '-':
3905             {
3906                 const char *tmp = p;
3907                 int skip_key = 0;
3908                 /* option */
3909
3910                 c = *typestr++;
3911                 if (c == '\0')
3912                     goto bad_type;
3913                 while (qemu_isspace(*p))
3914                     p++;
3915                 if (*p == '-') {
3916                     p++;
3917                     if(c != *p) {
3918                         if(!is_valid_option(p, typestr)) {
3919                   
3920                             monitor_printf(mon, "%s: unsupported option -%c\n",
3921                                            cmdname, *p);
3922                             goto fail;
3923                         } else {
3924                             skip_key = 1;
3925                         }
3926                     }
3927                     if(skip_key) {
3928                         p = tmp;
3929                     } else {
3930                         /* has option */
3931                         p++;
3932                         qdict_put(qdict, key, qbool_from_int(1));
3933                     }
3934                 }
3935             }
3936             break;
3937         default:
3938         bad_type:
3939             monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
3940             goto fail;
3941         }
3942         g_free(key);
3943         key = NULL;
3944     }
3945     /* check that all arguments were parsed */
3946     while (qemu_isspace(*p))
3947         p++;
3948     if (*p != '\0') {
3949         monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3950                        cmdname);
3951         goto fail;
3952     }
3953
3954     return cmd;
3955
3956 fail:
3957     g_free(key);
3958     return NULL;
3959 }
3960
3961 void monitor_set_error(Monitor *mon, QError *qerror)
3962 {
3963     /* report only the first error */
3964     if (!mon->error) {
3965         mon->error = qerror;
3966     } else {
3967         QDECREF(qerror);
3968     }
3969 }
3970
3971 static void handler_audit(Monitor *mon, const mon_cmd_t *cmd, int ret)
3972 {
3973     if (ret && !monitor_has_error(mon)) {
3974         /*
3975          * If it returns failure, it must have passed on error.
3976          *
3977          * Action: Report an internal error to the client if in QMP.
3978          */
3979         qerror_report(QERR_UNDEFINED_ERROR);
3980     }
3981 }
3982
3983 static void handle_user_command(Monitor *mon, const char *cmdline)
3984 {
3985     QDict *qdict;
3986     const mon_cmd_t *cmd;
3987
3988     qdict = qdict_new();
3989
3990     cmd = monitor_parse_command(mon, cmdline, 0, mon_cmds, qdict);
3991     if (!cmd)
3992         goto out;
3993
3994     if (handler_is_async(cmd)) {
3995         user_async_cmd_handler(mon, cmd, qdict);
3996     } else if (handler_is_qobject(cmd)) {
3997         QObject *data = NULL;
3998
3999         /* XXX: ignores the error code */
4000         cmd->mhandler.cmd_new(mon, qdict, &data);
4001         assert(!monitor_has_error(mon));
4002         if (data) {
4003             cmd->user_print(mon, data);
4004             qobject_decref(data);
4005         }
4006     } else {
4007         cmd->mhandler.cmd(mon, qdict);
4008     }
4009
4010 out:
4011     QDECREF(qdict);
4012 }
4013
4014 static void cmd_completion(const char *name, const char *list)
4015 {
4016     const char *p, *pstart;
4017     char cmd[128];
4018     int len;
4019
4020     p = list;
4021     for(;;) {
4022         pstart = p;
4023         p = strchr(p, '|');
4024         if (!p)
4025             p = pstart + strlen(pstart);
4026         len = p - pstart;
4027         if (len > sizeof(cmd) - 2)
4028             len = sizeof(cmd) - 2;
4029         memcpy(cmd, pstart, len);
4030         cmd[len] = '\0';
4031         if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
4032             readline_add_completion(cur_mon->rs, cmd);
4033         }
4034         if (*p == '\0')
4035             break;
4036         p++;
4037     }
4038 }
4039
4040 static void file_completion(const char *input)
4041 {
4042     DIR *ffs;
4043     struct dirent *d;
4044     char path[1024];
4045     char file[1024], file_prefix[1024];
4046     int input_path_len;
4047     const char *p;
4048
4049     p = strrchr(input, '/');
4050     if (!p) {
4051         input_path_len = 0;
4052         pstrcpy(file_prefix, sizeof(file_prefix), input);
4053         pstrcpy(path, sizeof(path), ".");
4054     } else {
4055         input_path_len = p - input + 1;
4056         memcpy(path, input, input_path_len);
4057         if (input_path_len > sizeof(path) - 1)
4058             input_path_len = sizeof(path) - 1;
4059         path[input_path_len] = '\0';
4060         pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
4061     }
4062 #ifdef DEBUG_COMPLETION
4063     monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
4064                    input, path, file_prefix);
4065 #endif
4066     ffs = opendir(path);
4067     if (!ffs)
4068         return;
4069     for(;;) {
4070         struct stat sb;
4071         d = readdir(ffs);
4072         if (!d)
4073             break;
4074
4075         if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
4076             continue;
4077         }
4078
4079         if (strstart(d->d_name, file_prefix, NULL)) {
4080             memcpy(file, input, input_path_len);
4081             if (input_path_len < sizeof(file))
4082                 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
4083                         d->d_name);
4084             /* stat the file to find out if it's a directory.
4085              * In that case add a slash to speed up typing long paths
4086              */
4087             if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
4088                 pstrcat(file, sizeof(file), "/");
4089             }
4090             readline_add_completion(cur_mon->rs, file);
4091         }
4092     }
4093     closedir(ffs);
4094 }
4095
4096 static void block_completion_it(void *opaque, BlockDriverState *bs)
4097 {
4098     const char *name = bdrv_get_device_name(bs);
4099     const char *input = opaque;
4100
4101     if (input[0] == '\0' ||
4102         !strncmp(name, (char *)input, strlen(input))) {
4103         readline_add_completion(cur_mon->rs, name);
4104     }
4105 }
4106
4107 /* NOTE: this parser is an approximate form of the real command parser */
4108 static void parse_cmdline(const char *cmdline,
4109                          int *pnb_args, char **args)
4110 {
4111     const char *p;
4112     int nb_args, ret;
4113     char buf[1024];
4114
4115     p = cmdline;
4116     nb_args = 0;
4117     for(;;) {
4118         while (qemu_isspace(*p))
4119             p++;
4120         if (*p == '\0')
4121             break;
4122         if (nb_args >= MAX_ARGS)
4123             break;
4124         ret = get_str(buf, sizeof(buf), &p);
4125         args[nb_args] = g_strdup(buf);
4126         nb_args++;
4127         if (ret < 0)
4128             break;
4129     }
4130     *pnb_args = nb_args;
4131 }
4132
4133 static const char *next_arg_type(const char *typestr)
4134 {
4135     const char *p = strchr(typestr, ':');
4136     return (p != NULL ? ++p : typestr);
4137 }
4138
4139 static void monitor_find_completion(const char *cmdline)
4140 {
4141     const char *cmdname;
4142     char *args[MAX_ARGS];
4143     int nb_args, i, len;
4144     const char *ptype, *str;
4145     const mon_cmd_t *cmd;
4146
4147     parse_cmdline(cmdline, &nb_args, args);
4148 #ifdef DEBUG_COMPLETION
4149     for(i = 0; i < nb_args; i++) {
4150         monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
4151     }
4152 #endif
4153
4154     /* if the line ends with a space, it means we want to complete the
4155        next arg */
4156     len = strlen(cmdline);
4157     if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4158         if (nb_args >= MAX_ARGS) {
4159             goto cleanup;
4160         }
4161         args[nb_args++] = g_strdup("");
4162     }
4163     if (nb_args <= 1) {
4164         /* command completion */
4165         if (nb_args == 0)
4166             cmdname = "";
4167         else
4168             cmdname = args[0];
4169         readline_set_completion_index(cur_mon->rs, strlen(cmdname));
4170         for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
4171             cmd_completion(cmdname, cmd->name);
4172         }
4173     } else {
4174         /* find the command */
4175         for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4176             if (compare_cmd(args[0], cmd->name)) {
4177                 break;
4178             }
4179         }
4180         if (!cmd->name) {
4181             goto cleanup;
4182         }
4183
4184         ptype = next_arg_type(cmd->args_type);
4185         for(i = 0; i < nb_args - 2; i++) {
4186             if (*ptype != '\0') {
4187                 ptype = next_arg_type(ptype);
4188                 while (*ptype == '?')
4189                     ptype = next_arg_type(ptype);
4190             }
4191         }
4192         str = args[nb_args - 1];
4193         if (*ptype == '-' && ptype[1] != '\0') {
4194             ptype = next_arg_type(ptype);
4195         }
4196         switch(*ptype) {
4197         case 'F':
4198             /* file completion */
4199             readline_set_completion_index(cur_mon->rs, strlen(str));
4200             file_completion(str);
4201             break;
4202         case 'B':
4203             /* block device name completion */
4204             readline_set_completion_index(cur_mon->rs, strlen(str));
4205             bdrv_iterate(block_completion_it, (void *)str);
4206             break;
4207         case 's':
4208             /* XXX: more generic ? */
4209             if (!strcmp(cmd->name, "info")) {
4210                 readline_set_completion_index(cur_mon->rs, strlen(str));
4211                 for(cmd = info_cmds; cmd->name != NULL; cmd++) {
4212                     cmd_completion(str, cmd->name);
4213                 }
4214             } else if (!strcmp(cmd->name, "sendkey")) {
4215                 char *sep = strrchr(str, '-');
4216                 if (sep)
4217                     str = sep + 1;
4218                 readline_set_completion_index(cur_mon->rs, strlen(str));
4219                 for (i = 0; i < Q_KEY_CODE_MAX; i++) {
4220                     cmd_completion(str, QKeyCode_lookup[i]);
4221                 }
4222             } else if (!strcmp(cmd->name, "help|?")) {
4223                 readline_set_completion_index(cur_mon->rs, strlen(str));
4224                 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4225                     cmd_completion(str, cmd->name);
4226                 }
4227             }
4228             break;
4229         default:
4230             break;
4231         }
4232     }
4233
4234 cleanup:
4235     for (i = 0; i < nb_args; i++) {
4236         g_free(args[i]);
4237     }
4238 }
4239
4240 static int monitor_can_read(void *opaque)
4241 {
4242     Monitor *mon = opaque;
4243
4244     return (mon->suspend_cnt == 0) ? 1 : 0;
4245 }
4246
4247 static int invalid_qmp_mode(const Monitor *mon, const char *cmd_name)
4248 {
4249     int is_cap = compare_cmd(cmd_name, "qmp_capabilities");
4250     return (qmp_cmd_mode(mon) ? is_cap : !is_cap);
4251 }
4252
4253 /*
4254  * Argument validation rules:
4255  *
4256  * 1. The argument must exist in cmd_args qdict
4257  * 2. The argument type must be the expected one
4258  *
4259  * Special case: If the argument doesn't exist in cmd_args and
4260  *               the QMP_ACCEPT_UNKNOWNS flag is set, then the
4261  *               checking is skipped for it.
4262  */
4263 static int check_client_args_type(const QDict *client_args,
4264                                   const QDict *cmd_args, int flags)
4265 {
4266     const QDictEntry *ent;
4267
4268     for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
4269         QObject *obj;
4270         QString *arg_type;
4271         const QObject *client_arg = qdict_entry_value(ent);
4272         const char *client_arg_name = qdict_entry_key(ent);
4273
4274         obj = qdict_get(cmd_args, client_arg_name);
4275         if (!obj) {
4276             if (flags & QMP_ACCEPT_UNKNOWNS) {
4277                 /* handler accepts unknowns */
4278                 continue;
4279             }
4280             /* client arg doesn't exist */
4281             qerror_report(QERR_INVALID_PARAMETER, client_arg_name);
4282             return -1;
4283         }
4284
4285         arg_type = qobject_to_qstring(obj);
4286         assert(arg_type != NULL);
4287
4288         /* check if argument's type is correct */
4289         switch (qstring_get_str(arg_type)[0]) {
4290         case 'F':
4291         case 'B':
4292         case 's':
4293             if (qobject_type(client_arg) != QTYPE_QSTRING) {
4294                 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4295                               "string");
4296                 return -1;
4297             }
4298         break;
4299         case 'i':
4300         case 'l':
4301         case 'M':
4302         case 'o':
4303             if (qobject_type(client_arg) != QTYPE_QINT) {
4304                 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4305                               "int");
4306                 return -1; 
4307             }
4308             break;
4309         case 'T':
4310             if (qobject_type(client_arg) != QTYPE_QINT &&
4311                 qobject_type(client_arg) != QTYPE_QFLOAT) {
4312                 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4313                               "number");
4314                return -1; 
4315             }
4316             break;
4317         case 'b':
4318         case '-':
4319             if (qobject_type(client_arg) != QTYPE_QBOOL) {
4320                 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4321                               "bool");
4322                return -1; 
4323             }
4324             break;
4325         case 'O':
4326             assert(flags & QMP_ACCEPT_UNKNOWNS);
4327             break;
4328         case 'q':
4329             /* Any QObject can be passed.  */
4330             break;
4331         case '/':
4332         case '.':
4333             /*
4334              * These types are not supported by QMP and thus are not
4335              * handled here. Fall through.
4336              */
4337         default:
4338             abort();
4339         }
4340     }
4341
4342     return 0;
4343 }
4344
4345 /*
4346  * - Check if the client has passed all mandatory args
4347  * - Set special flags for argument validation
4348  */
4349 static int check_mandatory_args(const QDict *cmd_args,
4350                                 const QDict *client_args, int *flags)
4351 {
4352     const QDictEntry *ent;
4353
4354     for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
4355         const char *cmd_arg_name = qdict_entry_key(ent);
4356         QString *type = qobject_to_qstring(qdict_entry_value(ent));
4357         assert(type != NULL);
4358
4359         if (qstring_get_str(type)[0] == 'O') {
4360             assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
4361             *flags |= QMP_ACCEPT_UNKNOWNS;
4362         } else if (qstring_get_str(type)[0] != '-' &&
4363                    qstring_get_str(type)[1] != '?' &&
4364                    !qdict_haskey(client_args, cmd_arg_name)) {
4365             qerror_report(QERR_MISSING_PARAMETER, cmd_arg_name);
4366             return -1;
4367         }
4368     }
4369
4370     return 0;
4371 }
4372
4373 static QDict *qdict_from_args_type(const char *args_type)
4374 {
4375     int i;
4376     QDict *qdict;
4377     QString *key, *type, *cur_qs;
4378
4379     assert(args_type != NULL);
4380
4381     qdict = qdict_new();
4382
4383     if (args_type == NULL || args_type[0] == '\0') {
4384         /* no args, empty qdict */
4385         goto out;
4386     }
4387
4388     key = qstring_new();
4389     type = qstring_new();
4390
4391     cur_qs = key;
4392
4393     for (i = 0;; i++) {
4394         switch (args_type[i]) {
4395             case ',':
4396             case '\0':
4397                 qdict_put(qdict, qstring_get_str(key), type);
4398                 QDECREF(key);
4399                 if (args_type[i] == '\0') {
4400                     goto out;
4401                 }
4402                 type = qstring_new(); /* qdict has ref */
4403                 cur_qs = key = qstring_new();
4404                 break;
4405             case ':':
4406                 cur_qs = type;
4407                 break;
4408             default:
4409                 qstring_append_chr(cur_qs, args_type[i]);
4410                 break;
4411         }
4412     }
4413
4414 out:
4415     return qdict;
4416 }
4417
4418 /*
4419  * Client argument checking rules:
4420  *
4421  * 1. Client must provide all mandatory arguments
4422  * 2. Each argument provided by the client must be expected
4423  * 3. Each argument provided by the client must have the type expected
4424  *    by the command
4425  */
4426 static int qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args)
4427 {
4428     int flags, err;
4429     QDict *cmd_args;
4430
4431     cmd_args = qdict_from_args_type(cmd->args_type);
4432
4433     flags = 0;
4434     err = check_mandatory_args(cmd_args, client_args, &flags);
4435     if (err) {
4436         goto out;
4437     }
4438
4439     err = check_client_args_type(client_args, cmd_args, flags);
4440
4441 out:
4442     QDECREF(cmd_args);
4443     return err;
4444 }
4445
4446 /*
4447  * Input object checking rules
4448  *
4449  * 1. Input object must be a dict
4450  * 2. The "execute" key must exist
4451  * 3. The "execute" key must be a string
4452  * 4. If the "arguments" key exists, it must be a dict
4453  * 5. If the "id" key exists, it can be anything (ie. json-value)
4454  * 6. Any argument not listed above is considered invalid
4455  */
4456 static QDict *qmp_check_input_obj(QObject *input_obj)
4457 {
4458     const QDictEntry *ent;
4459     int has_exec_key = 0;
4460     QDict *input_dict;
4461
4462     if (qobject_type(input_obj) != QTYPE_QDICT) {
4463         qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "object");
4464         return NULL;
4465     }
4466
4467     input_dict = qobject_to_qdict(input_obj);
4468
4469     for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
4470         const char *arg_name = qdict_entry_key(ent);
4471         const QObject *arg_obj = qdict_entry_value(ent);
4472
4473         if (!strcmp(arg_name, "execute")) {
4474             if (qobject_type(arg_obj) != QTYPE_QSTRING) {
4475                 qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "execute",
4476                               "string");
4477                 return NULL;
4478             }
4479             has_exec_key = 1;
4480         } else if (!strcmp(arg_name, "arguments")) {
4481             if (qobject_type(arg_obj) != QTYPE_QDICT) {
4482                 qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "arguments",
4483                               "object");
4484                 return NULL;
4485             }
4486         } else if (!strcmp(arg_name, "id")) {
4487             /* FIXME: check duplicated IDs for async commands */
4488         } else {
4489             qerror_report(QERR_QMP_EXTRA_MEMBER, arg_name);
4490             return NULL;
4491         }
4492     }
4493
4494     if (!has_exec_key) {
4495         qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4496         return NULL;
4497     }
4498
4499     return input_dict;
4500 }
4501
4502 static void qmp_call_cmd(Monitor *mon, const mon_cmd_t *cmd,
4503                          const QDict *params)
4504 {
4505     int ret;
4506     QObject *data = NULL;
4507
4508     ret = cmd->mhandler.cmd_new(mon, params, &data);
4509     handler_audit(mon, cmd, ret);
4510     monitor_protocol_emitter(mon, data);
4511     qobject_decref(data);
4512 }
4513
4514 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
4515 {
4516     int err;
4517     QObject *obj;
4518     QDict *input, *args;
4519     const mon_cmd_t *cmd;
4520     const char *cmd_name;
4521     Monitor *mon = cur_mon;
4522
4523     args = input = NULL;
4524
4525     obj = json_parser_parse(tokens, NULL);
4526     if (!obj) {
4527         // FIXME: should be triggered in json_parser_parse()
4528         qerror_report(QERR_JSON_PARSING);
4529         goto err_out;
4530     }
4531
4532     input = qmp_check_input_obj(obj);
4533     if (!input) {
4534         qobject_decref(obj);
4535         goto err_out;
4536     }
4537
4538     mon->mc->id = qdict_get(input, "id");
4539     qobject_incref(mon->mc->id);
4540
4541     cmd_name = qdict_get_str(input, "execute");
4542     trace_handle_qmp_command(mon, cmd_name);
4543     if (invalid_qmp_mode(mon, cmd_name)) {
4544         qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
4545         goto err_out;
4546     }
4547
4548     cmd = qmp_find_cmd(cmd_name);
4549     if (!cmd) {
4550         qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
4551         goto err_out;
4552     }
4553
4554     obj = qdict_get(input, "arguments");
4555     if (!obj) {
4556         args = qdict_new();
4557     } else {
4558         args = qobject_to_qdict(obj);
4559         QINCREF(args);
4560     }
4561
4562     err = qmp_check_client_args(cmd, args);
4563     if (err < 0) {
4564         goto err_out;
4565     }
4566
4567     if (handler_is_async(cmd)) {
4568         err = qmp_async_cmd_handler(mon, cmd, args);
4569         if (err) {
4570             /* emit the error response */
4571             goto err_out;
4572         }
4573     } else {
4574         qmp_call_cmd(mon, cmd, args);
4575     }
4576
4577     goto out;
4578
4579 err_out:
4580     monitor_protocol_emitter(mon, NULL);
4581 out:
4582     QDECREF(input);
4583     QDECREF(args);
4584 }
4585
4586 /**
4587  * monitor_control_read(): Read and handle QMP input
4588  */
4589 static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
4590 {
4591     Monitor *old_mon = cur_mon;
4592
4593     cur_mon = opaque;
4594
4595     json_message_parser_feed(&cur_mon->mc->parser, (const char *) buf, size);
4596
4597     cur_mon = old_mon;
4598 }
4599
4600 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4601 {
4602     Monitor *old_mon = cur_mon;
4603     int i;
4604
4605     cur_mon = opaque;
4606
4607     if (cur_mon->rs) {
4608         for (i = 0; i < size; i++)
4609             readline_handle_byte(cur_mon->rs, buf[i]);
4610     } else {
4611         if (size == 0 || buf[size - 1] != 0)
4612             monitor_printf(cur_mon, "corrupted command\n");
4613         else
4614             handle_user_command(cur_mon, (char *)buf);
4615     }
4616
4617     cur_mon = old_mon;
4618 }
4619
4620 static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
4621 {
4622     monitor_suspend(mon);
4623     handle_user_command(mon, cmdline);
4624     monitor_resume(mon);
4625 }
4626
4627 int monitor_suspend(Monitor *mon)
4628 {
4629     if (!mon->rs)
4630         return -ENOTTY;
4631     mon->suspend_cnt++;
4632     return 0;
4633 }
4634
4635 void monitor_resume(Monitor *mon)
4636 {
4637     if (!mon->rs)
4638         return;
4639     if (--mon->suspend_cnt == 0)
4640         readline_show_prompt(mon->rs);
4641 }
4642
4643 static QObject *get_qmp_greeting(void)
4644 {
4645     QObject *ver = NULL;
4646
4647     qmp_marshal_input_query_version(NULL, NULL, &ver);
4648     return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
4649 }
4650
4651 /**
4652  * monitor_control_event(): Print QMP gretting
4653  */
4654 static void monitor_control_event(void *opaque, int event)
4655 {
4656     QObject *data;
4657     Monitor *mon = opaque;
4658
4659     switch (event) {
4660     case CHR_EVENT_OPENED:
4661         mon->mc->command_mode = 0;
4662         data = get_qmp_greeting();
4663         monitor_json_emitter(mon, data);
4664         qobject_decref(data);
4665         mon_refcount++;
4666         break;
4667     case CHR_EVENT_CLOSED:
4668         json_message_parser_destroy(&mon->mc->parser);
4669         json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4670         mon_refcount--;
4671         monitor_fdsets_cleanup();
4672         break;
4673     }
4674 }
4675
4676 static void monitor_event(void *opaque, int event)
4677 {
4678     Monitor *mon = opaque;
4679
4680     switch (event) {
4681     case CHR_EVENT_MUX_IN:
4682         mon->mux_out = 0;
4683         if (mon->reset_seen) {
4684             readline_restart(mon->rs);
4685             monitor_resume(mon);
4686             monitor_flush(mon);
4687         } else {
4688             mon->suspend_cnt = 0;
4689         }
4690         break;
4691
4692     case CHR_EVENT_MUX_OUT:
4693         if (mon->reset_seen) {
4694             if (mon->suspend_cnt == 0) {
4695                 monitor_printf(mon, "\n");
4696             }
4697             monitor_flush(mon);
4698             monitor_suspend(mon);
4699         } else {
4700             mon->suspend_cnt++;
4701         }
4702         mon->mux_out = 1;
4703         break;
4704
4705     case CHR_EVENT_OPENED:
4706         monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4707                        "information\n", QEMU_VERSION);
4708         if (!mon->mux_out) {
4709             readline_show_prompt(mon->rs);
4710         }
4711         mon->reset_seen = 1;
4712         mon_refcount++;
4713         break;
4714
4715     case CHR_EVENT_CLOSED:
4716         mon_refcount--;
4717         monitor_fdsets_cleanup();
4718         break;
4719     }
4720 }
4721
4722 static int
4723 compare_mon_cmd(const void *a, const void *b)
4724 {
4725     return strcmp(((const mon_cmd_t *)a)->name,
4726             ((const mon_cmd_t *)b)->name);
4727 }
4728
4729 static void sortcmdlist(void)
4730 {
4731     int array_num;
4732     int elem_size = sizeof(mon_cmd_t);
4733
4734     array_num = sizeof(mon_cmds)/elem_size-1;
4735     qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4736
4737     array_num = sizeof(info_cmds)/elem_size-1;
4738     qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4739 }
4740
4741
4742 /*
4743  * Local variables:
4744  *  c-indent-level: 4
4745  *  c-basic-offset: 4
4746  *  tab-width: 8
4747  * End:
4748  */
4749
4750 void monitor_init(CharDriverState *chr, int flags)
4751 {
4752     static int is_first_init = 1;
4753     Monitor *mon;
4754
4755     if (is_first_init) {
4756         monitor_protocol_event_init();
4757         is_first_init = 0;
4758     }
4759
4760     mon = g_malloc0(sizeof(*mon));
4761     mon->outbuf = qstring_new();
4762
4763     mon->chr = chr;
4764     mon->flags = flags;
4765     if (flags & MONITOR_USE_READLINE) {
4766         mon->rs = readline_init(mon, monitor_find_completion);
4767         monitor_read_command(mon, 0);
4768     }
4769
4770     if (monitor_ctrl_mode(mon)) {
4771         mon->mc = g_malloc0(sizeof(MonitorControl));
4772         /* Control mode requires special handlers */
4773         qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
4774                               monitor_control_event, mon);
4775         qemu_chr_fe_set_echo(chr, true);
4776
4777         json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4778     } else {
4779         qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4780                               monitor_event, mon);
4781     }
4782
4783     QLIST_INSERT_HEAD(&mon_list, mon, entry);
4784     if (!default_mon || (flags & MONITOR_IS_DEFAULT))
4785         default_mon = mon;
4786
4787     sortcmdlist();
4788 }
4789
4790 static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
4791 {
4792     BlockDriverState *bs = opaque;
4793     int ret = 0;
4794
4795     if (bdrv_set_key(bs, password) != 0) {
4796         monitor_printf(mon, "invalid password\n");
4797         ret = -EPERM;
4798     }
4799     if (mon->password_completion_cb)
4800         mon->password_completion_cb(mon->password_opaque, ret);
4801
4802     monitor_read_command(mon, 1);
4803 }
4804
4805 ReadLineState *monitor_get_rs(Monitor *mon)
4806 {
4807     return mon->rs;
4808 }
4809
4810 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4811                                 BlockDriverCompletionFunc *completion_cb,
4812                                 void *opaque)
4813 {
4814     int err;
4815
4816     if (!bdrv_key_required(bs)) {
4817         if (completion_cb)
4818             completion_cb(opaque, 0);
4819         return 0;
4820     }
4821
4822     if (monitor_ctrl_mode(mon)) {
4823         qerror_report(QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
4824                       bdrv_get_encrypted_filename(bs));
4825         return -1;
4826     }
4827
4828     monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4829                    bdrv_get_encrypted_filename(bs));
4830
4831     mon->password_completion_cb = completion_cb;
4832     mon->password_opaque = opaque;
4833
4834     err = monitor_read_password(mon, bdrv_password_cb, bs);
4835
4836     if (err && completion_cb)
4837         completion_cb(opaque, err);
4838
4839     return err;
4840 }
4841
4842 int monitor_read_block_device_key(Monitor *mon, const char *device,
4843                                   BlockDriverCompletionFunc *completion_cb,
4844                                   void *opaque)
4845 {
4846     BlockDriverState *bs;
4847
4848     bs = bdrv_find(device);
4849     if (!bs) {
4850         monitor_printf(mon, "Device not found %s\n", device);
4851         return -1;
4852     }
4853
4854     return monitor_read_bdrv_key_start(mon, bs, completion_cb, opaque);
4855 }
4856
4857 QemuOptsList qemu_mon_opts = {
4858     .name = "mon",
4859     .implied_opt_name = "chardev",
4860     .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4861     .desc = {
4862         {
4863             .name = "mode",
4864             .type = QEMU_OPT_STRING,
4865         },{
4866             .name = "chardev",
4867             .type = QEMU_OPT_STRING,
4868         },{
4869             .name = "default",
4870             .type = QEMU_OPT_BOOL,
4871         },{
4872             .name = "pretty",
4873             .type = QEMU_OPT_BOOL,
4874         },
4875         { /* end of list */ }
4876     },
4877 };