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