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