]> Git Repo - qemu.git/blob - monitor.c
monitor: Introduce 'info commands'
[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 "qemu-char.h"
36 #include "sysemu.h"
37 #include "monitor.h"
38 #include "readline.h"
39 #include "console.h"
40 #include "block.h"
41 #include "audio/audio.h"
42 #include "disas.h"
43 #include "balloon.h"
44 #include "qemu-timer.h"
45 #include "migration.h"
46 #include "kvm.h"
47 #include "acl.h"
48 #include "qint.h"
49 #include "qlist.h"
50 #include "qdict.h"
51 #include "qstring.h"
52 #include "qerror.h"
53
54 //#define DEBUG
55 //#define DEBUG_COMPLETION
56
57 /*
58  * Supported types:
59  *
60  * 'F'          filename
61  * 'B'          block device name
62  * 's'          string (accept optional quote)
63  * 'i'          32 bit integer
64  * 'l'          target long (32 or 64 bit)
65  * '/'          optional gdb-like print format (like "/10x")
66  *
67  * '?'          optional type (for all types, except '/')
68  * '.'          other form of optional type (for 'i' and 'l')
69  * '-'          optional parameter (eg. '-f')
70  *
71  */
72
73 typedef struct mon_cmd_t {
74     const char *name;
75     const char *args_type;
76     const char *params;
77     const char *help;
78     void (*user_print)(Monitor *mon, const QObject *data);
79     union {
80         void (*info)(Monitor *mon);
81         void (*info_new)(Monitor *mon, QObject **ret_data);
82         void (*cmd)(Monitor *mon, const QDict *qdict);
83         void (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data);
84     } mhandler;
85 } mon_cmd_t;
86
87 /* file descriptors passed via SCM_RIGHTS */
88 typedef struct mon_fd_t mon_fd_t;
89 struct mon_fd_t {
90     char *name;
91     int fd;
92     QLIST_ENTRY(mon_fd_t) next;
93 };
94
95 struct Monitor {
96     CharDriverState *chr;
97     int mux_out;
98     int reset_seen;
99     int flags;
100     int suspend_cnt;
101     uint8_t outbuf[1024];
102     int outbuf_index;
103     ReadLineState *rs;
104     CPUState *mon_cpu;
105     BlockDriverCompletionFunc *password_completion_cb;
106     void *password_opaque;
107     QError *error;
108     QLIST_HEAD(,mon_fd_t) fds;
109     QLIST_ENTRY(Monitor) entry;
110 };
111
112 static QLIST_HEAD(mon_list, Monitor) mon_list;
113
114 static const mon_cmd_t mon_cmds[];
115 static const mon_cmd_t info_cmds[];
116
117 Monitor *cur_mon = NULL;
118
119 static void monitor_command_cb(Monitor *mon, const char *cmdline,
120                                void *opaque);
121
122 /* Return true if in control mode, false otherwise */
123 static inline int monitor_ctrl_mode(const Monitor *mon)
124 {
125     return (mon->flags & MONITOR_USE_CONTROL);
126 }
127
128 static void monitor_read_command(Monitor *mon, int show_prompt)
129 {
130     readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
131     if (show_prompt)
132         readline_show_prompt(mon->rs);
133 }
134
135 static int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
136                                  void *opaque)
137 {
138     if (mon->rs) {
139         readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
140         /* prompt is printed on return from the command handler */
141         return 0;
142     } else {
143         monitor_printf(mon, "terminal does not support password prompting\n");
144         return -ENOTTY;
145     }
146 }
147
148 void monitor_flush(Monitor *mon)
149 {
150     if (mon && mon->outbuf_index != 0 && !mon->mux_out) {
151         qemu_chr_write(mon->chr, mon->outbuf, mon->outbuf_index);
152         mon->outbuf_index = 0;
153     }
154 }
155
156 /* flush at every end of line or if the buffer is full */
157 static void monitor_puts(Monitor *mon, const char *str)
158 {
159     char c;
160
161     if (!mon)
162         return;
163
164     for(;;) {
165         c = *str++;
166         if (c == '\0')
167             break;
168         if (c == '\n')
169             mon->outbuf[mon->outbuf_index++] = '\r';
170         mon->outbuf[mon->outbuf_index++] = c;
171         if (mon->outbuf_index >= (sizeof(mon->outbuf) - 1)
172             || c == '\n')
173             monitor_flush(mon);
174     }
175 }
176
177 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
178 {
179     char buf[4096];
180     vsnprintf(buf, sizeof(buf), fmt, ap);
181     monitor_puts(mon, buf);
182 }
183
184 void monitor_printf(Monitor *mon, const char *fmt, ...)
185 {
186     va_list ap;
187     va_start(ap, fmt);
188     monitor_vprintf(mon, fmt, ap);
189     va_end(ap);
190 }
191
192 void monitor_print_filename(Monitor *mon, const char *filename)
193 {
194     int i;
195
196     for (i = 0; filename[i]; i++) {
197         switch (filename[i]) {
198         case ' ':
199         case '"':
200         case '\\':
201             monitor_printf(mon, "\\%c", filename[i]);
202             break;
203         case '\t':
204             monitor_printf(mon, "\\t");
205             break;
206         case '\r':
207             monitor_printf(mon, "\\r");
208             break;
209         case '\n':
210             monitor_printf(mon, "\\n");
211             break;
212         default:
213             monitor_printf(mon, "%c", filename[i]);
214             break;
215         }
216     }
217 }
218
219 static int monitor_fprintf(FILE *stream, const char *fmt, ...)
220 {
221     va_list ap;
222     va_start(ap, fmt);
223     monitor_vprintf((Monitor *)stream, fmt, ap);
224     va_end(ap);
225     return 0;
226 }
227
228 static void monitor_user_noop(Monitor *mon, const QObject *data) { }
229
230 static inline int monitor_handler_ported(const mon_cmd_t *cmd)
231 {
232     return cmd->user_print != NULL;
233 }
234
235 static inline int monitor_has_error(const Monitor *mon)
236 {
237     return mon->error != NULL;
238 }
239
240 static void monitor_print_qobject(Monitor *mon, const QObject *data)
241 {
242     switch (qobject_type(data)) {
243         case QTYPE_QSTRING:
244             monitor_printf(mon, "%s",qstring_get_str(qobject_to_qstring(data)));
245             break;
246         case QTYPE_QINT:
247             monitor_printf(mon, "%" PRId64,qint_get_int(qobject_to_qint(data)));
248             break;
249         default:
250             monitor_printf(mon, "ERROR: unsupported type: %d",
251                                                         qobject_type(data));
252             break;
253     }
254
255     monitor_puts(mon, "\n");
256 }
257
258 static int compare_cmd(const char *name, const char *list)
259 {
260     const char *p, *pstart;
261     int len;
262     len = strlen(name);
263     p = list;
264     for(;;) {
265         pstart = p;
266         p = strchr(p, '|');
267         if (!p)
268             p = pstart + strlen(pstart);
269         if ((p - pstart) == len && !memcmp(pstart, name, len))
270             return 1;
271         if (*p == '\0')
272             break;
273         p++;
274     }
275     return 0;
276 }
277
278 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
279                           const char *prefix, const char *name)
280 {
281     const mon_cmd_t *cmd;
282
283     for(cmd = cmds; cmd->name != NULL; cmd++) {
284         if (!name || !strcmp(name, cmd->name))
285             monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
286                            cmd->params, cmd->help);
287     }
288 }
289
290 static void help_cmd(Monitor *mon, const char *name)
291 {
292     if (name && !strcmp(name, "info")) {
293         help_cmd_dump(mon, info_cmds, "info ", NULL);
294     } else {
295         help_cmd_dump(mon, mon_cmds, "", name);
296         if (name && !strcmp(name, "log")) {
297             const CPULogItem *item;
298             monitor_printf(mon, "Log items (comma separated):\n");
299             monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
300             for(item = cpu_log_items; item->mask != 0; item++) {
301                 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
302             }
303         }
304     }
305 }
306
307 static void do_help_cmd(Monitor *mon, const QDict *qdict)
308 {
309     help_cmd(mon, qdict_get_try_str(qdict, "name"));
310 }
311
312 static void do_commit(Monitor *mon, const QDict *qdict)
313 {
314     int all_devices;
315     DriveInfo *dinfo;
316     const char *device = qdict_get_str(qdict, "device");
317
318     all_devices = !strcmp(device, "all");
319     QTAILQ_FOREACH(dinfo, &drives, next) {
320         if (!all_devices)
321             if (strcmp(bdrv_get_device_name(dinfo->bdrv), device))
322                 continue;
323         bdrv_commit(dinfo->bdrv);
324     }
325 }
326
327 static void do_info(Monitor *mon, const QDict *qdict, QObject **ret_data)
328 {
329     const mon_cmd_t *cmd;
330     const char *item = qdict_get_try_str(qdict, "item");
331
332     if (!item)
333         goto help;
334
335     for (cmd = info_cmds; cmd->name != NULL; cmd++) {
336         if (compare_cmd(item, cmd->name))
337             break;
338     }
339
340     if (cmd->name == NULL)
341         goto help;
342
343     if (monitor_handler_ported(cmd)) {
344         cmd->mhandler.info_new(mon, ret_data);
345         if (*ret_data)
346             cmd->user_print(mon, *ret_data);
347     } else {
348         cmd->mhandler.info(mon);
349     }
350
351     return;
352
353 help:
354     help_cmd(mon, "info");
355 }
356
357 /**
358  * do_info_version(): Show QEMU version
359  */
360 static void do_info_version(Monitor *mon, QObject **ret_data)
361 {
362     *ret_data = QOBJECT(qstring_from_str(QEMU_VERSION QEMU_PKGVERSION));
363 }
364
365 static void do_info_name(Monitor *mon)
366 {
367     if (qemu_name)
368         monitor_printf(mon, "%s\n", qemu_name);
369 }
370
371 /**
372  * do_info_commands(): List QMP available commands
373  *
374  * Return a QList of QStrings.
375  */
376 static void do_info_commands(Monitor *mon, QObject **ret_data)
377 {
378     QList *cmd_list;
379     const mon_cmd_t *cmd;
380
381     cmd_list = qlist_new();
382
383     for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
384         if (monitor_handler_ported(cmd) && !compare_cmd(cmd->name, "info")) {
385             qlist_append(cmd_list, qstring_from_str(cmd->name));
386         }
387     }
388
389     for (cmd = info_cmds; cmd->name != NULL; cmd++) {
390         if (monitor_handler_ported(cmd)) {
391             char buf[128];
392             snprintf(buf, sizeof(buf), "query-%s", cmd->name);
393             qlist_append(cmd_list, qstring_from_str(buf));
394         }
395     }
396
397     *ret_data = QOBJECT(cmd_list);
398 }
399
400 #if defined(TARGET_I386)
401 static void do_info_hpet(Monitor *mon)
402 {
403     monitor_printf(mon, "HPET is %s by QEMU\n",
404                    (no_hpet) ? "disabled" : "enabled");
405 }
406 #endif
407
408 static void do_info_uuid(Monitor *mon)
409 {
410     monitor_printf(mon, UUID_FMT "\n", qemu_uuid[0], qemu_uuid[1],
411                    qemu_uuid[2], qemu_uuid[3], qemu_uuid[4], qemu_uuid[5],
412                    qemu_uuid[6], qemu_uuid[7], qemu_uuid[8], qemu_uuid[9],
413                    qemu_uuid[10], qemu_uuid[11], qemu_uuid[12], qemu_uuid[13],
414                    qemu_uuid[14], qemu_uuid[15]);
415 }
416
417 /* get the current CPU defined by the user */
418 static int mon_set_cpu(int cpu_index)
419 {
420     CPUState *env;
421
422     for(env = first_cpu; env != NULL; env = env->next_cpu) {
423         if (env->cpu_index == cpu_index) {
424             cur_mon->mon_cpu = env;
425             return 0;
426         }
427     }
428     return -1;
429 }
430
431 static CPUState *mon_get_cpu(void)
432 {
433     if (!cur_mon->mon_cpu) {
434         mon_set_cpu(0);
435     }
436     cpu_synchronize_state(cur_mon->mon_cpu);
437     return cur_mon->mon_cpu;
438 }
439
440 static void do_info_registers(Monitor *mon)
441 {
442     CPUState *env;
443     env = mon_get_cpu();
444     if (!env)
445         return;
446 #ifdef TARGET_I386
447     cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
448                    X86_DUMP_FPU);
449 #else
450     cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
451                    0);
452 #endif
453 }
454
455 static void print_cpu_iter(QObject *obj, void *opaque)
456 {
457     QDict *cpu;
458     int active = ' ';
459     Monitor *mon = opaque;
460
461     assert(qobject_type(obj) == QTYPE_QDICT);
462     cpu = qobject_to_qdict(obj);
463
464     if (strcmp(qdict_get_str(cpu, "current"), "yes") == 0)
465         active = '*';
466
467     monitor_printf(mon, "%c CPU #%d: ", active, (int)qdict_get_int(cpu, "CPU"));
468
469 #if defined(TARGET_I386)
470     monitor_printf(mon, "pc=0x" TARGET_FMT_lx,
471                    (target_ulong) qdict_get_int(cpu, "pc"));
472 #elif defined(TARGET_PPC)
473     monitor_printf(mon, "nip=0x" TARGET_FMT_lx,
474                    (target_long) qdict_get_int(cpu, "nip"));
475 #elif defined(TARGET_SPARC)
476     monitor_printf(mon, "pc=0x " TARGET_FMT_lx,
477                    (target_long) qdict_get_int(cpu, "pc"));
478     monitor_printf(mon, "npc=0x" TARGET_FMT_lx,
479                    (target_long) qdict_get_int(cpu, "npc"));
480 #elif defined(TARGET_MIPS)
481     monitor_printf(mon, "PC=0x" TARGET_FMT_lx,
482                    (target_long) qdict_get_int(cpu, "PC"));
483 #endif
484
485     if (strcmp(qdict_get_str(cpu, "halted"), "yes") == 0)
486         monitor_printf(mon, " (halted)");
487
488     monitor_printf(mon, "\n");
489 }
490
491 static void monitor_print_cpus(Monitor *mon, const QObject *data)
492 {
493     QList *cpu_list;
494
495     assert(qobject_type(data) == QTYPE_QLIST);
496     cpu_list = qobject_to_qlist(data);
497     qlist_iter(cpu_list, print_cpu_iter, mon);
498 }
499
500 /**
501  * do_info_cpus(): Show CPU information
502  *
503  * Return a QList with a QDict for each CPU.
504  *
505  * For example:
506  *
507  * [ { "CPU": 0, "current": "yes", "pc": 0x..., "halted": "no" },
508  *   { "CPU": 1, "current": "no",  "pc": 0x..., "halted": "yes" } ]
509  */
510 static void do_info_cpus(Monitor *mon, QObject **ret_data)
511 {
512     CPUState *env;
513     QList *cpu_list;
514
515     cpu_list = qlist_new();
516
517     /* just to set the default cpu if not already done */
518     mon_get_cpu();
519
520     for(env = first_cpu; env != NULL; env = env->next_cpu) {
521         const char *answer;
522         QDict *cpu = qdict_new();
523
524         cpu_synchronize_state(env);
525
526         qdict_put(cpu, "CPU", qint_from_int(env->cpu_index));
527         answer = (env == mon->mon_cpu) ? "yes" : "no";
528         qdict_put(cpu, "current", qstring_from_str(answer));
529
530 #if defined(TARGET_I386)
531         qdict_put(cpu, "pc", qint_from_int(env->eip + env->segs[R_CS].base));
532 #elif defined(TARGET_PPC)
533         qdict_put(cpu, "nip", qint_from_int(env->nip));
534 #elif defined(TARGET_SPARC)
535         qdict_put(cpu, "pc", qint_from_int(env->pc));
536         qdict_put(cpu, "npc", qint_from_int(env->npc));
537 #elif defined(TARGET_MIPS)
538         qdict_put(cpu, "PC", qint_from_int(env->active_tc.PC));
539 #endif
540         answer = env->halted ? "yes" : "no";
541         qdict_put(cpu, "halted", qstring_from_str(answer));
542
543         qlist_append(cpu_list, cpu);
544     }
545
546     *ret_data = QOBJECT(cpu_list);
547 }
548
549 static void do_cpu_set(Monitor *mon, const QDict *qdict)
550 {
551     int index = qdict_get_int(qdict, "index");
552     if (mon_set_cpu(index) < 0)
553         monitor_printf(mon, "Invalid CPU index\n");
554 }
555
556 static void do_info_jit(Monitor *mon)
557 {
558     dump_exec_info((FILE *)mon, monitor_fprintf);
559 }
560
561 static void do_info_history(Monitor *mon)
562 {
563     int i;
564     const char *str;
565
566     if (!mon->rs)
567         return;
568     i = 0;
569     for(;;) {
570         str = readline_get_history(mon->rs, i);
571         if (!str)
572             break;
573         monitor_printf(mon, "%d: '%s'\n", i, str);
574         i++;
575     }
576 }
577
578 #if defined(TARGET_PPC)
579 /* XXX: not implemented in other targets */
580 static void do_info_cpu_stats(Monitor *mon)
581 {
582     CPUState *env;
583
584     env = mon_get_cpu();
585     cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
586 }
587 #endif
588
589 /**
590  * do_quit(): Quit QEMU execution
591  */
592 static void do_quit(Monitor *mon, const QDict *qdict, QObject **ret_data)
593 {
594     exit(0);
595 }
596
597 static int eject_device(Monitor *mon, BlockDriverState *bs, int force)
598 {
599     if (bdrv_is_inserted(bs)) {
600         if (!force) {
601             if (!bdrv_is_removable(bs)) {
602                 monitor_printf(mon, "device is not removable\n");
603                 return -1;
604             }
605             if (bdrv_is_locked(bs)) {
606                 monitor_printf(mon, "device is locked\n");
607                 return -1;
608             }
609         }
610         bdrv_close(bs);
611     }
612     return 0;
613 }
614
615 static void do_eject(Monitor *mon, const QDict *qdict, QObject **ret_data)
616 {
617     BlockDriverState *bs;
618     int force = qdict_get_int(qdict, "force");
619     const char *filename = qdict_get_str(qdict, "filename");
620
621     bs = bdrv_find(filename);
622     if (!bs) {
623         monitor_printf(mon, "device not found\n");
624         return;
625     }
626     eject_device(mon, bs, force);
627 }
628
629 static void do_change_block(Monitor *mon, const char *device,
630                             const char *filename, const char *fmt)
631 {
632     BlockDriverState *bs;
633     BlockDriver *drv = NULL;
634
635     bs = bdrv_find(device);
636     if (!bs) {
637         monitor_printf(mon, "device not found\n");
638         return;
639     }
640     if (fmt) {
641         drv = bdrv_find_whitelisted_format(fmt);
642         if (!drv) {
643             monitor_printf(mon, "invalid format %s\n", fmt);
644             return;
645         }
646     }
647     if (eject_device(mon, bs, 0) < 0)
648         return;
649     bdrv_open2(bs, filename, 0, drv);
650     monitor_read_bdrv_key_start(mon, bs, NULL, NULL);
651 }
652
653 static void change_vnc_password_cb(Monitor *mon, const char *password,
654                                    void *opaque)
655 {
656     if (vnc_display_password(NULL, password) < 0)
657         monitor_printf(mon, "could not set VNC server password\n");
658
659     monitor_read_command(mon, 1);
660 }
661
662 static void do_change_vnc(Monitor *mon, const char *target, const char *arg)
663 {
664     if (strcmp(target, "passwd") == 0 ||
665         strcmp(target, "password") == 0) {
666         if (arg) {
667             char password[9];
668             strncpy(password, arg, sizeof(password));
669             password[sizeof(password) - 1] = '\0';
670             change_vnc_password_cb(mon, password, NULL);
671         } else {
672             monitor_read_password(mon, change_vnc_password_cb, NULL);
673         }
674     } else {
675         if (vnc_display_open(NULL, target) < 0)
676             monitor_printf(mon, "could not start VNC server on %s\n", target);
677     }
678 }
679
680 static void do_change(Monitor *mon, const QDict *qdict)
681 {
682     const char *device = qdict_get_str(qdict, "device");
683     const char *target = qdict_get_str(qdict, "target");
684     const char *arg = qdict_get_try_str(qdict, "arg");
685     if (strcmp(device, "vnc") == 0) {
686         do_change_vnc(mon, target, arg);
687     } else {
688         do_change_block(mon, device, target, arg);
689     }
690 }
691
692 static void do_screen_dump(Monitor *mon, const QDict *qdict)
693 {
694     vga_hw_screen_dump(qdict_get_str(qdict, "filename"));
695 }
696
697 static void do_logfile(Monitor *mon, const QDict *qdict)
698 {
699     cpu_set_log_filename(qdict_get_str(qdict, "filename"));
700 }
701
702 static void do_log(Monitor *mon, const QDict *qdict)
703 {
704     int mask;
705     const char *items = qdict_get_str(qdict, "items");
706
707     if (!strcmp(items, "none")) {
708         mask = 0;
709     } else {
710         mask = cpu_str_to_log_mask(items);
711         if (!mask) {
712             help_cmd(mon, "log");
713             return;
714         }
715     }
716     cpu_set_log(mask);
717 }
718
719 static void do_singlestep(Monitor *mon, const QDict *qdict)
720 {
721     const char *option = qdict_get_try_str(qdict, "option");
722     if (!option || !strcmp(option, "on")) {
723         singlestep = 1;
724     } else if (!strcmp(option, "off")) {
725         singlestep = 0;
726     } else {
727         monitor_printf(mon, "unexpected option %s\n", option);
728     }
729 }
730
731 /**
732  * do_stop(): Stop VM execution
733  */
734 static void do_stop(Monitor *mon, const QDict *qdict, QObject **ret_data)
735 {
736     vm_stop(EXCP_INTERRUPT);
737 }
738
739 static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs);
740
741 struct bdrv_iterate_context {
742     Monitor *mon;
743     int err;
744 };
745
746 /**
747  * do_cont(): Resume emulation.
748  */
749 static void do_cont(Monitor *mon, const QDict *qdict, QObject **ret_data)
750 {
751     struct bdrv_iterate_context context = { mon, 0 };
752
753     bdrv_iterate(encrypted_bdrv_it, &context);
754     /* only resume the vm if all keys are set and valid */
755     if (!context.err)
756         vm_start();
757 }
758
759 static void bdrv_key_cb(void *opaque, int err)
760 {
761     Monitor *mon = opaque;
762
763     /* another key was set successfully, retry to continue */
764     if (!err)
765         do_cont(mon, NULL, NULL);
766 }
767
768 static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs)
769 {
770     struct bdrv_iterate_context *context = opaque;
771
772     if (!context->err && bdrv_key_required(bs)) {
773         context->err = -EBUSY;
774         monitor_read_bdrv_key_start(context->mon, bs, bdrv_key_cb,
775                                     context->mon);
776     }
777 }
778
779 static void do_gdbserver(Monitor *mon, const QDict *qdict)
780 {
781     const char *device = qdict_get_try_str(qdict, "device");
782     if (!device)
783         device = "tcp::" DEFAULT_GDBSTUB_PORT;
784     if (gdbserver_start(device) < 0) {
785         monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
786                        device);
787     } else if (strcmp(device, "none") == 0) {
788         monitor_printf(mon, "Disabled gdbserver\n");
789     } else {
790         monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
791                        device);
792     }
793 }
794
795 static void do_watchdog_action(Monitor *mon, const QDict *qdict)
796 {
797     const char *action = qdict_get_str(qdict, "action");
798     if (select_watchdog_action(action) == -1) {
799         monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
800     }
801 }
802
803 static void monitor_printc(Monitor *mon, int c)
804 {
805     monitor_printf(mon, "'");
806     switch(c) {
807     case '\'':
808         monitor_printf(mon, "\\'");
809         break;
810     case '\\':
811         monitor_printf(mon, "\\\\");
812         break;
813     case '\n':
814         monitor_printf(mon, "\\n");
815         break;
816     case '\r':
817         monitor_printf(mon, "\\r");
818         break;
819     default:
820         if (c >= 32 && c <= 126) {
821             monitor_printf(mon, "%c", c);
822         } else {
823             monitor_printf(mon, "\\x%02x", c);
824         }
825         break;
826     }
827     monitor_printf(mon, "'");
828 }
829
830 static void memory_dump(Monitor *mon, int count, int format, int wsize,
831                         target_phys_addr_t addr, int is_physical)
832 {
833     CPUState *env;
834     int nb_per_line, l, line_size, i, max_digits, len;
835     uint8_t buf[16];
836     uint64_t v;
837
838     if (format == 'i') {
839         int flags;
840         flags = 0;
841         env = mon_get_cpu();
842         if (!env && !is_physical)
843             return;
844 #ifdef TARGET_I386
845         if (wsize == 2) {
846             flags = 1;
847         } else if (wsize == 4) {
848             flags = 0;
849         } else {
850             /* as default we use the current CS size */
851             flags = 0;
852             if (env) {
853 #ifdef TARGET_X86_64
854                 if ((env->efer & MSR_EFER_LMA) &&
855                     (env->segs[R_CS].flags & DESC_L_MASK))
856                     flags = 2;
857                 else
858 #endif
859                 if (!(env->segs[R_CS].flags & DESC_B_MASK))
860                     flags = 1;
861             }
862         }
863 #endif
864         monitor_disas(mon, env, addr, count, is_physical, flags);
865         return;
866     }
867
868     len = wsize * count;
869     if (wsize == 1)
870         line_size = 8;
871     else
872         line_size = 16;
873     nb_per_line = line_size / wsize;
874     max_digits = 0;
875
876     switch(format) {
877     case 'o':
878         max_digits = (wsize * 8 + 2) / 3;
879         break;
880     default:
881     case 'x':
882         max_digits = (wsize * 8) / 4;
883         break;
884     case 'u':
885     case 'd':
886         max_digits = (wsize * 8 * 10 + 32) / 33;
887         break;
888     case 'c':
889         wsize = 1;
890         break;
891     }
892
893     while (len > 0) {
894         if (is_physical)
895             monitor_printf(mon, TARGET_FMT_plx ":", addr);
896         else
897             monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
898         l = len;
899         if (l > line_size)
900             l = line_size;
901         if (is_physical) {
902             cpu_physical_memory_rw(addr, buf, l, 0);
903         } else {
904             env = mon_get_cpu();
905             if (!env)
906                 break;
907             if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {
908                 monitor_printf(mon, " Cannot access memory\n");
909                 break;
910             }
911         }
912         i = 0;
913         while (i < l) {
914             switch(wsize) {
915             default:
916             case 1:
917                 v = ldub_raw(buf + i);
918                 break;
919             case 2:
920                 v = lduw_raw(buf + i);
921                 break;
922             case 4:
923                 v = (uint32_t)ldl_raw(buf + i);
924                 break;
925             case 8:
926                 v = ldq_raw(buf + i);
927                 break;
928             }
929             monitor_printf(mon, " ");
930             switch(format) {
931             case 'o':
932                 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
933                 break;
934             case 'x':
935                 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
936                 break;
937             case 'u':
938                 monitor_printf(mon, "%*" PRIu64, max_digits, v);
939                 break;
940             case 'd':
941                 monitor_printf(mon, "%*" PRId64, max_digits, v);
942                 break;
943             case 'c':
944                 monitor_printc(mon, v);
945                 break;
946             }
947             i += wsize;
948         }
949         monitor_printf(mon, "\n");
950         addr += l;
951         len -= l;
952     }
953 }
954
955 static void do_memory_dump(Monitor *mon, const QDict *qdict)
956 {
957     int count = qdict_get_int(qdict, "count");
958     int format = qdict_get_int(qdict, "format");
959     int size = qdict_get_int(qdict, "size");
960     target_long addr = qdict_get_int(qdict, "addr");
961
962     memory_dump(mon, count, format, size, addr, 0);
963 }
964
965 static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
966 {
967     int count = qdict_get_int(qdict, "count");
968     int format = qdict_get_int(qdict, "format");
969     int size = qdict_get_int(qdict, "size");
970     target_phys_addr_t addr = qdict_get_int(qdict, "addr");
971
972     memory_dump(mon, count, format, size, addr, 1);
973 }
974
975 static void do_print(Monitor *mon, const QDict *qdict)
976 {
977     int format = qdict_get_int(qdict, "format");
978     target_phys_addr_t val = qdict_get_int(qdict, "val");
979
980 #if TARGET_PHYS_ADDR_BITS == 32
981     switch(format) {
982     case 'o':
983         monitor_printf(mon, "%#o", val);
984         break;
985     case 'x':
986         monitor_printf(mon, "%#x", val);
987         break;
988     case 'u':
989         monitor_printf(mon, "%u", val);
990         break;
991     default:
992     case 'd':
993         monitor_printf(mon, "%d", val);
994         break;
995     case 'c':
996         monitor_printc(mon, val);
997         break;
998     }
999 #else
1000     switch(format) {
1001     case 'o':
1002         monitor_printf(mon, "%#" PRIo64, val);
1003         break;
1004     case 'x':
1005         monitor_printf(mon, "%#" PRIx64, val);
1006         break;
1007     case 'u':
1008         monitor_printf(mon, "%" PRIu64, val);
1009         break;
1010     default:
1011     case 'd':
1012         monitor_printf(mon, "%" PRId64, val);
1013         break;
1014     case 'c':
1015         monitor_printc(mon, val);
1016         break;
1017     }
1018 #endif
1019     monitor_printf(mon, "\n");
1020 }
1021
1022 static void do_memory_save(Monitor *mon, const QDict *qdict, QObject **ret_data)
1023 {
1024     FILE *f;
1025     uint32_t size = qdict_get_int(qdict, "size");
1026     const char *filename = qdict_get_str(qdict, "filename");
1027     target_long addr = qdict_get_int(qdict, "val");
1028     uint32_t l;
1029     CPUState *env;
1030     uint8_t buf[1024];
1031
1032     env = mon_get_cpu();
1033     if (!env)
1034         return;
1035
1036     f = fopen(filename, "wb");
1037     if (!f) {
1038         monitor_printf(mon, "could not open '%s'\n", filename);
1039         return;
1040     }
1041     while (size != 0) {
1042         l = sizeof(buf);
1043         if (l > size)
1044             l = size;
1045         cpu_memory_rw_debug(env, addr, buf, l, 0);
1046         fwrite(buf, 1, l, f);
1047         addr += l;
1048         size -= l;
1049     }
1050     fclose(f);
1051 }
1052
1053 static void do_physical_memory_save(Monitor *mon, const QDict *qdict,
1054                                     QObject **ret_data)
1055 {
1056     FILE *f;
1057     uint32_t l;
1058     uint8_t buf[1024];
1059     uint32_t size = qdict_get_int(qdict, "size");
1060     const char *filename = qdict_get_str(qdict, "filename");
1061     target_phys_addr_t addr = qdict_get_int(qdict, "val");
1062
1063     f = fopen(filename, "wb");
1064     if (!f) {
1065         monitor_printf(mon, "could not open '%s'\n", filename);
1066         return;
1067     }
1068     while (size != 0) {
1069         l = sizeof(buf);
1070         if (l > size)
1071             l = size;
1072         cpu_physical_memory_rw(addr, buf, l, 0);
1073         fwrite(buf, 1, l, f);
1074         fflush(f);
1075         addr += l;
1076         size -= l;
1077     }
1078     fclose(f);
1079 }
1080
1081 static void do_sum(Monitor *mon, const QDict *qdict)
1082 {
1083     uint32_t addr;
1084     uint8_t buf[1];
1085     uint16_t sum;
1086     uint32_t start = qdict_get_int(qdict, "start");
1087     uint32_t size = qdict_get_int(qdict, "size");
1088
1089     sum = 0;
1090     for(addr = start; addr < (start + size); addr++) {
1091         cpu_physical_memory_rw(addr, buf, 1, 0);
1092         /* BSD sum algorithm ('sum' Unix command) */
1093         sum = (sum >> 1) | (sum << 15);
1094         sum += buf[0];
1095     }
1096     monitor_printf(mon, "%05d\n", sum);
1097 }
1098
1099 typedef struct {
1100     int keycode;
1101     const char *name;
1102 } KeyDef;
1103
1104 static const KeyDef key_defs[] = {
1105     { 0x2a, "shift" },
1106     { 0x36, "shift_r" },
1107
1108     { 0x38, "alt" },
1109     { 0xb8, "alt_r" },
1110     { 0x64, "altgr" },
1111     { 0xe4, "altgr_r" },
1112     { 0x1d, "ctrl" },
1113     { 0x9d, "ctrl_r" },
1114
1115     { 0xdd, "menu" },
1116
1117     { 0x01, "esc" },
1118
1119     { 0x02, "1" },
1120     { 0x03, "2" },
1121     { 0x04, "3" },
1122     { 0x05, "4" },
1123     { 0x06, "5" },
1124     { 0x07, "6" },
1125     { 0x08, "7" },
1126     { 0x09, "8" },
1127     { 0x0a, "9" },
1128     { 0x0b, "0" },
1129     { 0x0c, "minus" },
1130     { 0x0d, "equal" },
1131     { 0x0e, "backspace" },
1132
1133     { 0x0f, "tab" },
1134     { 0x10, "q" },
1135     { 0x11, "w" },
1136     { 0x12, "e" },
1137     { 0x13, "r" },
1138     { 0x14, "t" },
1139     { 0x15, "y" },
1140     { 0x16, "u" },
1141     { 0x17, "i" },
1142     { 0x18, "o" },
1143     { 0x19, "p" },
1144
1145     { 0x1c, "ret" },
1146
1147     { 0x1e, "a" },
1148     { 0x1f, "s" },
1149     { 0x20, "d" },
1150     { 0x21, "f" },
1151     { 0x22, "g" },
1152     { 0x23, "h" },
1153     { 0x24, "j" },
1154     { 0x25, "k" },
1155     { 0x26, "l" },
1156
1157     { 0x2c, "z" },
1158     { 0x2d, "x" },
1159     { 0x2e, "c" },
1160     { 0x2f, "v" },
1161     { 0x30, "b" },
1162     { 0x31, "n" },
1163     { 0x32, "m" },
1164     { 0x33, "comma" },
1165     { 0x34, "dot" },
1166     { 0x35, "slash" },
1167
1168     { 0x37, "asterisk" },
1169
1170     { 0x39, "spc" },
1171     { 0x3a, "caps_lock" },
1172     { 0x3b, "f1" },
1173     { 0x3c, "f2" },
1174     { 0x3d, "f3" },
1175     { 0x3e, "f4" },
1176     { 0x3f, "f5" },
1177     { 0x40, "f6" },
1178     { 0x41, "f7" },
1179     { 0x42, "f8" },
1180     { 0x43, "f9" },
1181     { 0x44, "f10" },
1182     { 0x45, "num_lock" },
1183     { 0x46, "scroll_lock" },
1184
1185     { 0xb5, "kp_divide" },
1186     { 0x37, "kp_multiply" },
1187     { 0x4a, "kp_subtract" },
1188     { 0x4e, "kp_add" },
1189     { 0x9c, "kp_enter" },
1190     { 0x53, "kp_decimal" },
1191     { 0x54, "sysrq" },
1192
1193     { 0x52, "kp_0" },
1194     { 0x4f, "kp_1" },
1195     { 0x50, "kp_2" },
1196     { 0x51, "kp_3" },
1197     { 0x4b, "kp_4" },
1198     { 0x4c, "kp_5" },
1199     { 0x4d, "kp_6" },
1200     { 0x47, "kp_7" },
1201     { 0x48, "kp_8" },
1202     { 0x49, "kp_9" },
1203
1204     { 0x56, "<" },
1205
1206     { 0x57, "f11" },
1207     { 0x58, "f12" },
1208
1209     { 0xb7, "print" },
1210
1211     { 0xc7, "home" },
1212     { 0xc9, "pgup" },
1213     { 0xd1, "pgdn" },
1214     { 0xcf, "end" },
1215
1216     { 0xcb, "left" },
1217     { 0xc8, "up" },
1218     { 0xd0, "down" },
1219     { 0xcd, "right" },
1220
1221     { 0xd2, "insert" },
1222     { 0xd3, "delete" },
1223 #if defined(TARGET_SPARC) && !defined(TARGET_SPARC64)
1224     { 0xf0, "stop" },
1225     { 0xf1, "again" },
1226     { 0xf2, "props" },
1227     { 0xf3, "undo" },
1228     { 0xf4, "front" },
1229     { 0xf5, "copy" },
1230     { 0xf6, "open" },
1231     { 0xf7, "paste" },
1232     { 0xf8, "find" },
1233     { 0xf9, "cut" },
1234     { 0xfa, "lf" },
1235     { 0xfb, "help" },
1236     { 0xfc, "meta_l" },
1237     { 0xfd, "meta_r" },
1238     { 0xfe, "compose" },
1239 #endif
1240     { 0, NULL },
1241 };
1242
1243 static int get_keycode(const char *key)
1244 {
1245     const KeyDef *p;
1246     char *endp;
1247     int ret;
1248
1249     for(p = key_defs; p->name != NULL; p++) {
1250         if (!strcmp(key, p->name))
1251             return p->keycode;
1252     }
1253     if (strstart(key, "0x", NULL)) {
1254         ret = strtoul(key, &endp, 0);
1255         if (*endp == '\0' && ret >= 0x01 && ret <= 0xff)
1256             return ret;
1257     }
1258     return -1;
1259 }
1260
1261 #define MAX_KEYCODES 16
1262 static uint8_t keycodes[MAX_KEYCODES];
1263 static int nb_pending_keycodes;
1264 static QEMUTimer *key_timer;
1265
1266 static void release_keys(void *opaque)
1267 {
1268     int keycode;
1269
1270     while (nb_pending_keycodes > 0) {
1271         nb_pending_keycodes--;
1272         keycode = keycodes[nb_pending_keycodes];
1273         if (keycode & 0x80)
1274             kbd_put_keycode(0xe0);
1275         kbd_put_keycode(keycode | 0x80);
1276     }
1277 }
1278
1279 static void do_sendkey(Monitor *mon, const QDict *qdict)
1280 {
1281     char keyname_buf[16];
1282     char *separator;
1283     int keyname_len, keycode, i;
1284     const char *string = qdict_get_str(qdict, "string");
1285     int has_hold_time = qdict_haskey(qdict, "hold_time");
1286     int hold_time = qdict_get_try_int(qdict, "hold_time", -1);
1287
1288     if (nb_pending_keycodes > 0) {
1289         qemu_del_timer(key_timer);
1290         release_keys(NULL);
1291     }
1292     if (!has_hold_time)
1293         hold_time = 100;
1294     i = 0;
1295     while (1) {
1296         separator = strchr(string, '-');
1297         keyname_len = separator ? separator - string : strlen(string);
1298         if (keyname_len > 0) {
1299             pstrcpy(keyname_buf, sizeof(keyname_buf), string);
1300             if (keyname_len > sizeof(keyname_buf) - 1) {
1301                 monitor_printf(mon, "invalid key: '%s...'\n", keyname_buf);
1302                 return;
1303             }
1304             if (i == MAX_KEYCODES) {
1305                 monitor_printf(mon, "too many keys\n");
1306                 return;
1307             }
1308             keyname_buf[keyname_len] = 0;
1309             keycode = get_keycode(keyname_buf);
1310             if (keycode < 0) {
1311                 monitor_printf(mon, "unknown key: '%s'\n", keyname_buf);
1312                 return;
1313             }
1314             keycodes[i++] = keycode;
1315         }
1316         if (!separator)
1317             break;
1318         string = separator + 1;
1319     }
1320     nb_pending_keycodes = i;
1321     /* key down events */
1322     for (i = 0; i < nb_pending_keycodes; i++) {
1323         keycode = keycodes[i];
1324         if (keycode & 0x80)
1325             kbd_put_keycode(0xe0);
1326         kbd_put_keycode(keycode & 0x7f);
1327     }
1328     /* delayed key up events */
1329     qemu_mod_timer(key_timer, qemu_get_clock(vm_clock) +
1330                    muldiv64(get_ticks_per_sec(), hold_time, 1000));
1331 }
1332
1333 static int mouse_button_state;
1334
1335 static void do_mouse_move(Monitor *mon, const QDict *qdict)
1336 {
1337     int dx, dy, dz;
1338     const char *dx_str = qdict_get_str(qdict, "dx_str");
1339     const char *dy_str = qdict_get_str(qdict, "dy_str");
1340     const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1341     dx = strtol(dx_str, NULL, 0);
1342     dy = strtol(dy_str, NULL, 0);
1343     dz = 0;
1344     if (dz_str)
1345         dz = strtol(dz_str, NULL, 0);
1346     kbd_mouse_event(dx, dy, dz, mouse_button_state);
1347 }
1348
1349 static void do_mouse_button(Monitor *mon, const QDict *qdict)
1350 {
1351     int button_state = qdict_get_int(qdict, "button_state");
1352     mouse_button_state = button_state;
1353     kbd_mouse_event(0, 0, 0, mouse_button_state);
1354 }
1355
1356 static void do_ioport_read(Monitor *mon, const QDict *qdict)
1357 {
1358     int size = qdict_get_int(qdict, "size");
1359     int addr = qdict_get_int(qdict, "addr");
1360     int has_index = qdict_haskey(qdict, "index");
1361     uint32_t val;
1362     int suffix;
1363
1364     if (has_index) {
1365         int index = qdict_get_int(qdict, "index");
1366         cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1367         addr++;
1368     }
1369     addr &= 0xffff;
1370
1371     switch(size) {
1372     default:
1373     case 1:
1374         val = cpu_inb(addr);
1375         suffix = 'b';
1376         break;
1377     case 2:
1378         val = cpu_inw(addr);
1379         suffix = 'w';
1380         break;
1381     case 4:
1382         val = cpu_inl(addr);
1383         suffix = 'l';
1384         break;
1385     }
1386     monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1387                    suffix, addr, size * 2, val);
1388 }
1389
1390 static void do_ioport_write(Monitor *mon, const QDict *qdict)
1391 {
1392     int size = qdict_get_int(qdict, "size");
1393     int addr = qdict_get_int(qdict, "addr");
1394     int val = qdict_get_int(qdict, "val");
1395
1396     addr &= IOPORTS_MASK;
1397
1398     switch (size) {
1399     default:
1400     case 1:
1401         cpu_outb(addr, val);
1402         break;
1403     case 2:
1404         cpu_outw(addr, val);
1405         break;
1406     case 4:
1407         cpu_outl(addr, val);
1408         break;
1409     }
1410 }
1411
1412 static void do_boot_set(Monitor *mon, const QDict *qdict)
1413 {
1414     int res;
1415     const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1416
1417     res = qemu_boot_set(bootdevice);
1418     if (res == 0) {
1419         monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1420     } else if (res > 0) {
1421         monitor_printf(mon, "setting boot device list failed\n");
1422     } else {
1423         monitor_printf(mon, "no function defined to set boot device list for "
1424                        "this architecture\n");
1425     }
1426 }
1427
1428 /**
1429  * do_system_reset(): Issue a machine reset
1430  */
1431 static void do_system_reset(Monitor *mon, const QDict *qdict,
1432                             QObject **ret_data)
1433 {
1434     qemu_system_reset_request();
1435 }
1436
1437 /**
1438  * do_system_powerdown(): Issue a machine powerdown
1439  */
1440 static void do_system_powerdown(Monitor *mon, const QDict *qdict,
1441                                 QObject **ret_data)
1442 {
1443     qemu_system_powerdown_request();
1444 }
1445
1446 #if defined(TARGET_I386)
1447 static void print_pte(Monitor *mon, uint32_t addr, uint32_t pte, uint32_t mask)
1448 {
1449     monitor_printf(mon, "%08x: %08x %c%c%c%c%c%c%c%c\n",
1450                    addr,
1451                    pte & mask,
1452                    pte & PG_GLOBAL_MASK ? 'G' : '-',
1453                    pte & PG_PSE_MASK ? 'P' : '-',
1454                    pte & PG_DIRTY_MASK ? 'D' : '-',
1455                    pte & PG_ACCESSED_MASK ? 'A' : '-',
1456                    pte & PG_PCD_MASK ? 'C' : '-',
1457                    pte & PG_PWT_MASK ? 'T' : '-',
1458                    pte & PG_USER_MASK ? 'U' : '-',
1459                    pte & PG_RW_MASK ? 'W' : '-');
1460 }
1461
1462 static void tlb_info(Monitor *mon)
1463 {
1464     CPUState *env;
1465     int l1, l2;
1466     uint32_t pgd, pde, pte;
1467
1468     env = mon_get_cpu();
1469     if (!env)
1470         return;
1471
1472     if (!(env->cr[0] & CR0_PG_MASK)) {
1473         monitor_printf(mon, "PG disabled\n");
1474         return;
1475     }
1476     pgd = env->cr[3] & ~0xfff;
1477     for(l1 = 0; l1 < 1024; l1++) {
1478         cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1479         pde = le32_to_cpu(pde);
1480         if (pde & PG_PRESENT_MASK) {
1481             if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1482                 print_pte(mon, (l1 << 22), pde, ~((1 << 20) - 1));
1483             } else {
1484                 for(l2 = 0; l2 < 1024; l2++) {
1485                     cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1486                                              (uint8_t *)&pte, 4);
1487                     pte = le32_to_cpu(pte);
1488                     if (pte & PG_PRESENT_MASK) {
1489                         print_pte(mon, (l1 << 22) + (l2 << 12),
1490                                   pte & ~PG_PSE_MASK,
1491                                   ~0xfff);
1492                     }
1493                 }
1494             }
1495         }
1496     }
1497 }
1498
1499 static void mem_print(Monitor *mon, uint32_t *pstart, int *plast_prot,
1500                       uint32_t end, int prot)
1501 {
1502     int prot1;
1503     prot1 = *plast_prot;
1504     if (prot != prot1) {
1505         if (*pstart != -1) {
1506             monitor_printf(mon, "%08x-%08x %08x %c%c%c\n",
1507                            *pstart, end, end - *pstart,
1508                            prot1 & PG_USER_MASK ? 'u' : '-',
1509                            'r',
1510                            prot1 & PG_RW_MASK ? 'w' : '-');
1511         }
1512         if (prot != 0)
1513             *pstart = end;
1514         else
1515             *pstart = -1;
1516         *plast_prot = prot;
1517     }
1518 }
1519
1520 static void mem_info(Monitor *mon)
1521 {
1522     CPUState *env;
1523     int l1, l2, prot, last_prot;
1524     uint32_t pgd, pde, pte, start, end;
1525
1526     env = mon_get_cpu();
1527     if (!env)
1528         return;
1529
1530     if (!(env->cr[0] & CR0_PG_MASK)) {
1531         monitor_printf(mon, "PG disabled\n");
1532         return;
1533     }
1534     pgd = env->cr[3] & ~0xfff;
1535     last_prot = 0;
1536     start = -1;
1537     for(l1 = 0; l1 < 1024; l1++) {
1538         cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1539         pde = le32_to_cpu(pde);
1540         end = l1 << 22;
1541         if (pde & PG_PRESENT_MASK) {
1542             if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1543                 prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1544                 mem_print(mon, &start, &last_prot, end, prot);
1545             } else {
1546                 for(l2 = 0; l2 < 1024; l2++) {
1547                     cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1548                                              (uint8_t *)&pte, 4);
1549                     pte = le32_to_cpu(pte);
1550                     end = (l1 << 22) + (l2 << 12);
1551                     if (pte & PG_PRESENT_MASK) {
1552                         prot = pte & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1553                     } else {
1554                         prot = 0;
1555                     }
1556                     mem_print(mon, &start, &last_prot, end, prot);
1557                 }
1558             }
1559         } else {
1560             prot = 0;
1561             mem_print(mon, &start, &last_prot, end, prot);
1562         }
1563     }
1564 }
1565 #endif
1566
1567 #if defined(TARGET_SH4)
1568
1569 static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1570 {
1571     monitor_printf(mon, " tlb%i:\t"
1572                    "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1573                    "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1574                    "dirty=%hhu writethrough=%hhu\n",
1575                    idx,
1576                    tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1577                    tlb->v, tlb->sh, tlb->c, tlb->pr,
1578                    tlb->d, tlb->wt);
1579 }
1580
1581 static void tlb_info(Monitor *mon)
1582 {
1583     CPUState *env = mon_get_cpu();
1584     int i;
1585
1586     monitor_printf (mon, "ITLB:\n");
1587     for (i = 0 ; i < ITLB_SIZE ; i++)
1588         print_tlb (mon, i, &env->itlb[i]);
1589     monitor_printf (mon, "UTLB:\n");
1590     for (i = 0 ; i < UTLB_SIZE ; i++)
1591         print_tlb (mon, i, &env->utlb[i]);
1592 }
1593
1594 #endif
1595
1596 static void do_info_kvm(Monitor *mon)
1597 {
1598 #ifdef CONFIG_KVM
1599     monitor_printf(mon, "kvm support: ");
1600     if (kvm_enabled())
1601         monitor_printf(mon, "enabled\n");
1602     else
1603         monitor_printf(mon, "disabled\n");
1604 #else
1605     monitor_printf(mon, "kvm support: not compiled\n");
1606 #endif
1607 }
1608
1609 static void do_info_numa(Monitor *mon)
1610 {
1611     int i;
1612     CPUState *env;
1613
1614     monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1615     for (i = 0; i < nb_numa_nodes; i++) {
1616         monitor_printf(mon, "node %d cpus:", i);
1617         for (env = first_cpu; env != NULL; env = env->next_cpu) {
1618             if (env->numa_node == i) {
1619                 monitor_printf(mon, " %d", env->cpu_index);
1620             }
1621         }
1622         monitor_printf(mon, "\n");
1623         monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1624             node_mem[i] >> 20);
1625     }
1626 }
1627
1628 #ifdef CONFIG_PROFILER
1629
1630 int64_t qemu_time;
1631 int64_t dev_time;
1632
1633 static void do_info_profile(Monitor *mon)
1634 {
1635     int64_t total;
1636     total = qemu_time;
1637     if (total == 0)
1638         total = 1;
1639     monitor_printf(mon, "async time  %" PRId64 " (%0.3f)\n",
1640                    dev_time, dev_time / (double)get_ticks_per_sec());
1641     monitor_printf(mon, "qemu time   %" PRId64 " (%0.3f)\n",
1642                    qemu_time, qemu_time / (double)get_ticks_per_sec());
1643     qemu_time = 0;
1644     dev_time = 0;
1645 }
1646 #else
1647 static void do_info_profile(Monitor *mon)
1648 {
1649     monitor_printf(mon, "Internal profiler not compiled\n");
1650 }
1651 #endif
1652
1653 /* Capture support */
1654 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1655
1656 static void do_info_capture(Monitor *mon)
1657 {
1658     int i;
1659     CaptureState *s;
1660
1661     for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1662         monitor_printf(mon, "[%d]: ", i);
1663         s->ops.info (s->opaque);
1664     }
1665 }
1666
1667 #ifdef HAS_AUDIO
1668 static void do_stop_capture(Monitor *mon, const QDict *qdict)
1669 {
1670     int i;
1671     int n = qdict_get_int(qdict, "n");
1672     CaptureState *s;
1673
1674     for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1675         if (i == n) {
1676             s->ops.destroy (s->opaque);
1677             QLIST_REMOVE (s, entries);
1678             qemu_free (s);
1679             return;
1680         }
1681     }
1682 }
1683
1684 static void do_wav_capture(Monitor *mon, const QDict *qdict)
1685 {
1686     const char *path = qdict_get_str(qdict, "path");
1687     int has_freq = qdict_haskey(qdict, "freq");
1688     int freq = qdict_get_try_int(qdict, "freq", -1);
1689     int has_bits = qdict_haskey(qdict, "bits");
1690     int bits = qdict_get_try_int(qdict, "bits", -1);
1691     int has_channels = qdict_haskey(qdict, "nchannels");
1692     int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1693     CaptureState *s;
1694
1695     s = qemu_mallocz (sizeof (*s));
1696
1697     freq = has_freq ? freq : 44100;
1698     bits = has_bits ? bits : 16;
1699     nchannels = has_channels ? nchannels : 2;
1700
1701     if (wav_start_capture (s, path, freq, bits, nchannels)) {
1702         monitor_printf(mon, "Faied to add wave capture\n");
1703         qemu_free (s);
1704     }
1705     QLIST_INSERT_HEAD (&capture_head, s, entries);
1706 }
1707 #endif
1708
1709 #if defined(TARGET_I386)
1710 static void do_inject_nmi(Monitor *mon, const QDict *qdict)
1711 {
1712     CPUState *env;
1713     int cpu_index = qdict_get_int(qdict, "cpu_index");
1714
1715     for (env = first_cpu; env != NULL; env = env->next_cpu)
1716         if (env->cpu_index == cpu_index) {
1717             cpu_interrupt(env, CPU_INTERRUPT_NMI);
1718             break;
1719         }
1720 }
1721 #endif
1722
1723 static void do_info_status(Monitor *mon)
1724 {
1725     if (vm_running) {
1726         if (singlestep) {
1727             monitor_printf(mon, "VM status: running (single step mode)\n");
1728         } else {
1729             monitor_printf(mon, "VM status: running\n");
1730         }
1731     } else
1732        monitor_printf(mon, "VM status: paused\n");
1733 }
1734
1735 /**
1736  * do_balloon(): Request VM to change its memory allocation
1737  */
1738 static void do_balloon(Monitor *mon, const QDict *qdict, QObject **ret_data)
1739 {
1740     int value = qdict_get_int(qdict, "value");
1741     ram_addr_t target = value;
1742     qemu_balloon(target << 20);
1743 }
1744
1745 static void monitor_print_balloon(Monitor *mon, const QObject *data)
1746 {
1747     monitor_printf(mon, "balloon: actual=%d\n",
1748                                      (int)qint_get_int(qobject_to_qint(data)));
1749 }
1750
1751 /**
1752  * do_info_balloon(): Balloon information
1753  */
1754 static void do_info_balloon(Monitor *mon, QObject **ret_data)
1755 {
1756     ram_addr_t actual;
1757
1758     actual = qemu_balloon_status();
1759     if (kvm_enabled() && !kvm_has_sync_mmu())
1760         qemu_error_new(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
1761     else if (actual == 0)
1762         qemu_error_new(QERR_DEVICE_NOT_ACTIVE, "balloon");
1763     else
1764         *ret_data = QOBJECT(qint_from_int((int)(actual >> 20)));
1765 }
1766
1767 static qemu_acl *find_acl(Monitor *mon, const char *name)
1768 {
1769     qemu_acl *acl = qemu_acl_find(name);
1770
1771     if (!acl) {
1772         monitor_printf(mon, "acl: unknown list '%s'\n", name);
1773     }
1774     return acl;
1775 }
1776
1777 static void do_acl_show(Monitor *mon, const QDict *qdict)
1778 {
1779     const char *aclname = qdict_get_str(qdict, "aclname");
1780     qemu_acl *acl = find_acl(mon, aclname);
1781     qemu_acl_entry *entry;
1782     int i = 0;
1783
1784     if (acl) {
1785         monitor_printf(mon, "policy: %s\n",
1786                        acl->defaultDeny ? "deny" : "allow");
1787         QTAILQ_FOREACH(entry, &acl->entries, next) {
1788             i++;
1789             monitor_printf(mon, "%d: %s %s\n", i,
1790                            entry->deny ? "deny" : "allow", entry->match);
1791         }
1792     }
1793 }
1794
1795 static void do_acl_reset(Monitor *mon, const QDict *qdict)
1796 {
1797     const char *aclname = qdict_get_str(qdict, "aclname");
1798     qemu_acl *acl = find_acl(mon, aclname);
1799
1800     if (acl) {
1801         qemu_acl_reset(acl);
1802         monitor_printf(mon, "acl: removed all rules\n");
1803     }
1804 }
1805
1806 static void do_acl_policy(Monitor *mon, const QDict *qdict)
1807 {
1808     const char *aclname = qdict_get_str(qdict, "aclname");
1809     const char *policy = qdict_get_str(qdict, "policy");
1810     qemu_acl *acl = find_acl(mon, aclname);
1811
1812     if (acl) {
1813         if (strcmp(policy, "allow") == 0) {
1814             acl->defaultDeny = 0;
1815             monitor_printf(mon, "acl: policy set to 'allow'\n");
1816         } else if (strcmp(policy, "deny") == 0) {
1817             acl->defaultDeny = 1;
1818             monitor_printf(mon, "acl: policy set to 'deny'\n");
1819         } else {
1820             monitor_printf(mon, "acl: unknown policy '%s', "
1821                            "expected 'deny' or 'allow'\n", policy);
1822         }
1823     }
1824 }
1825
1826 static void do_acl_add(Monitor *mon, const QDict *qdict)
1827 {
1828     const char *aclname = qdict_get_str(qdict, "aclname");
1829     const char *match = qdict_get_str(qdict, "match");
1830     const char *policy = qdict_get_str(qdict, "policy");
1831     int has_index = qdict_haskey(qdict, "index");
1832     int index = qdict_get_try_int(qdict, "index", -1);
1833     qemu_acl *acl = find_acl(mon, aclname);
1834     int deny, ret;
1835
1836     if (acl) {
1837         if (strcmp(policy, "allow") == 0) {
1838             deny = 0;
1839         } else if (strcmp(policy, "deny") == 0) {
1840             deny = 1;
1841         } else {
1842             monitor_printf(mon, "acl: unknown policy '%s', "
1843                            "expected 'deny' or 'allow'\n", policy);
1844             return;
1845         }
1846         if (has_index)
1847             ret = qemu_acl_insert(acl, deny, match, index);
1848         else
1849             ret = qemu_acl_append(acl, deny, match);
1850         if (ret < 0)
1851             monitor_printf(mon, "acl: unable to add acl entry\n");
1852         else
1853             monitor_printf(mon, "acl: added rule at position %d\n", ret);
1854     }
1855 }
1856
1857 static void do_acl_remove(Monitor *mon, const QDict *qdict)
1858 {
1859     const char *aclname = qdict_get_str(qdict, "aclname");
1860     const char *match = qdict_get_str(qdict, "match");
1861     qemu_acl *acl = find_acl(mon, aclname);
1862     int ret;
1863
1864     if (acl) {
1865         ret = qemu_acl_remove(acl, match);
1866         if (ret < 0)
1867             monitor_printf(mon, "acl: no matching acl entry\n");
1868         else
1869             monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1870     }
1871 }
1872
1873 #if defined(TARGET_I386)
1874 static void do_inject_mce(Monitor *mon, const QDict *qdict)
1875 {
1876     CPUState *cenv;
1877     int cpu_index = qdict_get_int(qdict, "cpu_index");
1878     int bank = qdict_get_int(qdict, "bank");
1879     uint64_t status = qdict_get_int(qdict, "status");
1880     uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
1881     uint64_t addr = qdict_get_int(qdict, "addr");
1882     uint64_t misc = qdict_get_int(qdict, "misc");
1883
1884     for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu)
1885         if (cenv->cpu_index == cpu_index && cenv->mcg_cap) {
1886             cpu_inject_x86_mce(cenv, bank, status, mcg_status, addr, misc);
1887             break;
1888         }
1889 }
1890 #endif
1891
1892 static void do_getfd(Monitor *mon, const QDict *qdict, QObject **ret_data)
1893 {
1894     const char *fdname = qdict_get_str(qdict, "fdname");
1895     mon_fd_t *monfd;
1896     int fd;
1897
1898     fd = qemu_chr_get_msgfd(mon->chr);
1899     if (fd == -1) {
1900         monitor_printf(mon, "getfd: no file descriptor supplied via SCM_RIGHTS\n");
1901         return;
1902     }
1903
1904     if (qemu_isdigit(fdname[0])) {
1905         monitor_printf(mon, "getfd: monitor names may not begin with a number\n");
1906         return;
1907     }
1908
1909     fd = dup(fd);
1910     if (fd == -1) {
1911         monitor_printf(mon, "Failed to dup() file descriptor: %s\n",
1912                        strerror(errno));
1913         return;
1914     }
1915
1916     QLIST_FOREACH(monfd, &mon->fds, next) {
1917         if (strcmp(monfd->name, fdname) != 0) {
1918             continue;
1919         }
1920
1921         close(monfd->fd);
1922         monfd->fd = fd;
1923         return;
1924     }
1925
1926     monfd = qemu_mallocz(sizeof(mon_fd_t));
1927     monfd->name = qemu_strdup(fdname);
1928     monfd->fd = fd;
1929
1930     QLIST_INSERT_HEAD(&mon->fds, monfd, next);
1931 }
1932
1933 static void do_closefd(Monitor *mon, const QDict *qdict, QObject **ret_data)
1934 {
1935     const char *fdname = qdict_get_str(qdict, "fdname");
1936     mon_fd_t *monfd;
1937
1938     QLIST_FOREACH(monfd, &mon->fds, next) {
1939         if (strcmp(monfd->name, fdname) != 0) {
1940             continue;
1941         }
1942
1943         QLIST_REMOVE(monfd, next);
1944         close(monfd->fd);
1945         qemu_free(monfd->name);
1946         qemu_free(monfd);
1947         return;
1948     }
1949
1950     monitor_printf(mon, "Failed to find file descriptor named %s\n",
1951                    fdname);
1952 }
1953
1954 static void do_loadvm(Monitor *mon, const QDict *qdict)
1955 {
1956     int saved_vm_running  = vm_running;
1957     const char *name = qdict_get_str(qdict, "name");
1958
1959     vm_stop(0);
1960
1961     if (load_vmstate(mon, name) >= 0 && saved_vm_running)
1962         vm_start();
1963 }
1964
1965 int monitor_get_fd(Monitor *mon, const char *fdname)
1966 {
1967     mon_fd_t *monfd;
1968
1969     QLIST_FOREACH(monfd, &mon->fds, next) {
1970         int fd;
1971
1972         if (strcmp(monfd->name, fdname) != 0) {
1973             continue;
1974         }
1975
1976         fd = monfd->fd;
1977
1978         /* caller takes ownership of fd */
1979         QLIST_REMOVE(monfd, next);
1980         qemu_free(monfd->name);
1981         qemu_free(monfd);
1982
1983         return fd;
1984     }
1985
1986     return -1;
1987 }
1988
1989 static const mon_cmd_t mon_cmds[] = {
1990 #include "qemu-monitor.h"
1991     { NULL, NULL, },
1992 };
1993
1994 /* Please update qemu-monitor.hx when adding or changing commands */
1995 static const mon_cmd_t info_cmds[] = {
1996     {
1997         .name       = "version",
1998         .args_type  = "",
1999         .params     = "",
2000         .help       = "show the version of QEMU",
2001         .user_print = monitor_print_qobject,
2002         .mhandler.info_new = do_info_version,
2003     },
2004     {
2005         .name       = "commands",
2006         .args_type  = "",
2007         .params     = "",
2008         .help       = "list QMP available commands",
2009         .user_print = monitor_user_noop,
2010         .mhandler.info_new = do_info_commands,
2011     },
2012     {
2013         .name       = "network",
2014         .args_type  = "",
2015         .params     = "",
2016         .help       = "show the network state",
2017         .mhandler.info = do_info_network,
2018     },
2019     {
2020         .name       = "chardev",
2021         .args_type  = "",
2022         .params     = "",
2023         .help       = "show the character devices",
2024         .mhandler.info = qemu_chr_info,
2025     },
2026     {
2027         .name       = "block",
2028         .args_type  = "",
2029         .params     = "",
2030         .help       = "show the block devices",
2031         .mhandler.info = bdrv_info,
2032     },
2033     {
2034         .name       = "blockstats",
2035         .args_type  = "",
2036         .params     = "",
2037         .help       = "show block device statistics",
2038         .mhandler.info = bdrv_info_stats,
2039     },
2040     {
2041         .name       = "registers",
2042         .args_type  = "",
2043         .params     = "",
2044         .help       = "show the cpu registers",
2045         .mhandler.info = do_info_registers,
2046     },
2047     {
2048         .name       = "cpus",
2049         .args_type  = "",
2050         .params     = "",
2051         .help       = "show infos for each CPU",
2052         .user_print = monitor_print_cpus,
2053         .mhandler.info_new = do_info_cpus,
2054     },
2055     {
2056         .name       = "history",
2057         .args_type  = "",
2058         .params     = "",
2059         .help       = "show the command line history",
2060         .mhandler.info = do_info_history,
2061     },
2062     {
2063         .name       = "irq",
2064         .args_type  = "",
2065         .params     = "",
2066         .help       = "show the interrupts statistics (if available)",
2067         .mhandler.info = irq_info,
2068     },
2069     {
2070         .name       = "pic",
2071         .args_type  = "",
2072         .params     = "",
2073         .help       = "show i8259 (PIC) state",
2074         .mhandler.info = pic_info,
2075     },
2076     {
2077         .name       = "pci",
2078         .args_type  = "",
2079         .params     = "",
2080         .help       = "show PCI info",
2081         .mhandler.info = pci_info,
2082     },
2083 #if defined(TARGET_I386) || defined(TARGET_SH4)
2084     {
2085         .name       = "tlb",
2086         .args_type  = "",
2087         .params     = "",
2088         .help       = "show virtual to physical memory mappings",
2089         .mhandler.info = tlb_info,
2090     },
2091 #endif
2092 #if defined(TARGET_I386)
2093     {
2094         .name       = "mem",
2095         .args_type  = "",
2096         .params     = "",
2097         .help       = "show the active virtual memory mappings",
2098         .mhandler.info = mem_info,
2099     },
2100     {
2101         .name       = "hpet",
2102         .args_type  = "",
2103         .params     = "",
2104         .help       = "show state of HPET",
2105         .mhandler.info = do_info_hpet,
2106     },
2107 #endif
2108     {
2109         .name       = "jit",
2110         .args_type  = "",
2111         .params     = "",
2112         .help       = "show dynamic compiler info",
2113         .mhandler.info = do_info_jit,
2114     },
2115     {
2116         .name       = "kvm",
2117         .args_type  = "",
2118         .params     = "",
2119         .help       = "show KVM information",
2120         .mhandler.info = do_info_kvm,
2121     },
2122     {
2123         .name       = "numa",
2124         .args_type  = "",
2125         .params     = "",
2126         .help       = "show NUMA information",
2127         .mhandler.info = do_info_numa,
2128     },
2129     {
2130         .name       = "usb",
2131         .args_type  = "",
2132         .params     = "",
2133         .help       = "show guest USB devices",
2134         .mhandler.info = usb_info,
2135     },
2136     {
2137         .name       = "usbhost",
2138         .args_type  = "",
2139         .params     = "",
2140         .help       = "show host USB devices",
2141         .mhandler.info = usb_host_info,
2142     },
2143     {
2144         .name       = "profile",
2145         .args_type  = "",
2146         .params     = "",
2147         .help       = "show profiling information",
2148         .mhandler.info = do_info_profile,
2149     },
2150     {
2151         .name       = "capture",
2152         .args_type  = "",
2153         .params     = "",
2154         .help       = "show capture information",
2155         .mhandler.info = do_info_capture,
2156     },
2157     {
2158         .name       = "snapshots",
2159         .args_type  = "",
2160         .params     = "",
2161         .help       = "show the currently saved VM snapshots",
2162         .mhandler.info = do_info_snapshots,
2163     },
2164     {
2165         .name       = "status",
2166         .args_type  = "",
2167         .params     = "",
2168         .help       = "show the current VM status (running|paused)",
2169         .mhandler.info = do_info_status,
2170     },
2171     {
2172         .name       = "pcmcia",
2173         .args_type  = "",
2174         .params     = "",
2175         .help       = "show guest PCMCIA status",
2176         .mhandler.info = pcmcia_info,
2177     },
2178     {
2179         .name       = "mice",
2180         .args_type  = "",
2181         .params     = "",
2182         .help       = "show which guest mouse is receiving events",
2183         .mhandler.info = do_info_mice,
2184     },
2185     {
2186         .name       = "vnc",
2187         .args_type  = "",
2188         .params     = "",
2189         .help       = "show the vnc server status",
2190         .mhandler.info = do_info_vnc,
2191     },
2192     {
2193         .name       = "name",
2194         .args_type  = "",
2195         .params     = "",
2196         .help       = "show the current VM name",
2197         .mhandler.info = do_info_name,
2198     },
2199     {
2200         .name       = "uuid",
2201         .args_type  = "",
2202         .params     = "",
2203         .help       = "show the current VM UUID",
2204         .mhandler.info = do_info_uuid,
2205     },
2206 #if defined(TARGET_PPC)
2207     {
2208         .name       = "cpustats",
2209         .args_type  = "",
2210         .params     = "",
2211         .help       = "show CPU statistics",
2212         .mhandler.info = do_info_cpu_stats,
2213     },
2214 #endif
2215 #if defined(CONFIG_SLIRP)
2216     {
2217         .name       = "usernet",
2218         .args_type  = "",
2219         .params     = "",
2220         .help       = "show user network stack connection states",
2221         .mhandler.info = do_info_usernet,
2222     },
2223 #endif
2224     {
2225         .name       = "migrate",
2226         .args_type  = "",
2227         .params     = "",
2228         .help       = "show migration status",
2229         .mhandler.info = do_info_migrate,
2230     },
2231     {
2232         .name       = "balloon",
2233         .args_type  = "",
2234         .params     = "",
2235         .help       = "show balloon information",
2236         .user_print = monitor_print_balloon,
2237         .mhandler.info_new = do_info_balloon,
2238     },
2239     {
2240         .name       = "qtree",
2241         .args_type  = "",
2242         .params     = "",
2243         .help       = "show device tree",
2244         .mhandler.info = do_info_qtree,
2245     },
2246     {
2247         .name       = "qdm",
2248         .args_type  = "",
2249         .params     = "",
2250         .help       = "show qdev device model list",
2251         .mhandler.info = do_info_qdm,
2252     },
2253     {
2254         .name       = "roms",
2255         .args_type  = "",
2256         .params     = "",
2257         .help       = "show roms",
2258         .mhandler.info = do_info_roms,
2259     },
2260     {
2261         .name       = NULL,
2262     },
2263 };
2264
2265 /*******************************************************************/
2266
2267 static const char *pch;
2268 static jmp_buf expr_env;
2269
2270 #define MD_TLONG 0
2271 #define MD_I32   1
2272
2273 typedef struct MonitorDef {
2274     const char *name;
2275     int offset;
2276     target_long (*get_value)(const struct MonitorDef *md, int val);
2277     int type;
2278 } MonitorDef;
2279
2280 #if defined(TARGET_I386)
2281 static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2282 {
2283     CPUState *env = mon_get_cpu();
2284     if (!env)
2285         return 0;
2286     return env->eip + env->segs[R_CS].base;
2287 }
2288 #endif
2289
2290 #if defined(TARGET_PPC)
2291 static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2292 {
2293     CPUState *env = mon_get_cpu();
2294     unsigned int u;
2295     int i;
2296
2297     if (!env)
2298         return 0;
2299
2300     u = 0;
2301     for (i = 0; i < 8; i++)
2302         u |= env->crf[i] << (32 - (4 * i));
2303
2304     return u;
2305 }
2306
2307 static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2308 {
2309     CPUState *env = mon_get_cpu();
2310     if (!env)
2311         return 0;
2312     return env->msr;
2313 }
2314
2315 static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2316 {
2317     CPUState *env = mon_get_cpu();
2318     if (!env)
2319         return 0;
2320     return env->xer;
2321 }
2322
2323 static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2324 {
2325     CPUState *env = mon_get_cpu();
2326     if (!env)
2327         return 0;
2328     return cpu_ppc_load_decr(env);
2329 }
2330
2331 static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2332 {
2333     CPUState *env = mon_get_cpu();
2334     if (!env)
2335         return 0;
2336     return cpu_ppc_load_tbu(env);
2337 }
2338
2339 static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2340 {
2341     CPUState *env = mon_get_cpu();
2342     if (!env)
2343         return 0;
2344     return cpu_ppc_load_tbl(env);
2345 }
2346 #endif
2347
2348 #if defined(TARGET_SPARC)
2349 #ifndef TARGET_SPARC64
2350 static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2351 {
2352     CPUState *env = mon_get_cpu();
2353     if (!env)
2354         return 0;
2355     return GET_PSR(env);
2356 }
2357 #endif
2358
2359 static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2360 {
2361     CPUState *env = mon_get_cpu();
2362     if (!env)
2363         return 0;
2364     return env->regwptr[val];
2365 }
2366 #endif
2367
2368 static const MonitorDef monitor_defs[] = {
2369 #ifdef TARGET_I386
2370
2371 #define SEG(name, seg) \
2372     { name, offsetof(CPUState, segs[seg].selector), NULL, MD_I32 },\
2373     { name ".base", offsetof(CPUState, segs[seg].base) },\
2374     { name ".limit", offsetof(CPUState, segs[seg].limit), NULL, MD_I32 },
2375
2376     { "eax", offsetof(CPUState, regs[0]) },
2377     { "ecx", offsetof(CPUState, regs[1]) },
2378     { "edx", offsetof(CPUState, regs[2]) },
2379     { "ebx", offsetof(CPUState, regs[3]) },
2380     { "esp|sp", offsetof(CPUState, regs[4]) },
2381     { "ebp|fp", offsetof(CPUState, regs[5]) },
2382     { "esi", offsetof(CPUState, regs[6]) },
2383     { "edi", offsetof(CPUState, regs[7]) },
2384 #ifdef TARGET_X86_64
2385     { "r8", offsetof(CPUState, regs[8]) },
2386     { "r9", offsetof(CPUState, regs[9]) },
2387     { "r10", offsetof(CPUState, regs[10]) },
2388     { "r11", offsetof(CPUState, regs[11]) },
2389     { "r12", offsetof(CPUState, regs[12]) },
2390     { "r13", offsetof(CPUState, regs[13]) },
2391     { "r14", offsetof(CPUState, regs[14]) },
2392     { "r15", offsetof(CPUState, regs[15]) },
2393 #endif
2394     { "eflags", offsetof(CPUState, eflags) },
2395     { "eip", offsetof(CPUState, eip) },
2396     SEG("cs", R_CS)
2397     SEG("ds", R_DS)
2398     SEG("es", R_ES)
2399     SEG("ss", R_SS)
2400     SEG("fs", R_FS)
2401     SEG("gs", R_GS)
2402     { "pc", 0, monitor_get_pc, },
2403 #elif defined(TARGET_PPC)
2404     /* General purpose registers */
2405     { "r0", offsetof(CPUState, gpr[0]) },
2406     { "r1", offsetof(CPUState, gpr[1]) },
2407     { "r2", offsetof(CPUState, gpr[2]) },
2408     { "r3", offsetof(CPUState, gpr[3]) },
2409     { "r4", offsetof(CPUState, gpr[4]) },
2410     { "r5", offsetof(CPUState, gpr[5]) },
2411     { "r6", offsetof(CPUState, gpr[6]) },
2412     { "r7", offsetof(CPUState, gpr[7]) },
2413     { "r8", offsetof(CPUState, gpr[8]) },
2414     { "r9", offsetof(CPUState, gpr[9]) },
2415     { "r10", offsetof(CPUState, gpr[10]) },
2416     { "r11", offsetof(CPUState, gpr[11]) },
2417     { "r12", offsetof(CPUState, gpr[12]) },
2418     { "r13", offsetof(CPUState, gpr[13]) },
2419     { "r14", offsetof(CPUState, gpr[14]) },
2420     { "r15", offsetof(CPUState, gpr[15]) },
2421     { "r16", offsetof(CPUState, gpr[16]) },
2422     { "r17", offsetof(CPUState, gpr[17]) },
2423     { "r18", offsetof(CPUState, gpr[18]) },
2424     { "r19", offsetof(CPUState, gpr[19]) },
2425     { "r20", offsetof(CPUState, gpr[20]) },
2426     { "r21", offsetof(CPUState, gpr[21]) },
2427     { "r22", offsetof(CPUState, gpr[22]) },
2428     { "r23", offsetof(CPUState, gpr[23]) },
2429     { "r24", offsetof(CPUState, gpr[24]) },
2430     { "r25", offsetof(CPUState, gpr[25]) },
2431     { "r26", offsetof(CPUState, gpr[26]) },
2432     { "r27", offsetof(CPUState, gpr[27]) },
2433     { "r28", offsetof(CPUState, gpr[28]) },
2434     { "r29", offsetof(CPUState, gpr[29]) },
2435     { "r30", offsetof(CPUState, gpr[30]) },
2436     { "r31", offsetof(CPUState, gpr[31]) },
2437     /* Floating point registers */
2438     { "f0", offsetof(CPUState, fpr[0]) },
2439     { "f1", offsetof(CPUState, fpr[1]) },
2440     { "f2", offsetof(CPUState, fpr[2]) },
2441     { "f3", offsetof(CPUState, fpr[3]) },
2442     { "f4", offsetof(CPUState, fpr[4]) },
2443     { "f5", offsetof(CPUState, fpr[5]) },
2444     { "f6", offsetof(CPUState, fpr[6]) },
2445     { "f7", offsetof(CPUState, fpr[7]) },
2446     { "f8", offsetof(CPUState, fpr[8]) },
2447     { "f9", offsetof(CPUState, fpr[9]) },
2448     { "f10", offsetof(CPUState, fpr[10]) },
2449     { "f11", offsetof(CPUState, fpr[11]) },
2450     { "f12", offsetof(CPUState, fpr[12]) },
2451     { "f13", offsetof(CPUState, fpr[13]) },
2452     { "f14", offsetof(CPUState, fpr[14]) },
2453     { "f15", offsetof(CPUState, fpr[15]) },
2454     { "f16", offsetof(CPUState, fpr[16]) },
2455     { "f17", offsetof(CPUState, fpr[17]) },
2456     { "f18", offsetof(CPUState, fpr[18]) },
2457     { "f19", offsetof(CPUState, fpr[19]) },
2458     { "f20", offsetof(CPUState, fpr[20]) },
2459     { "f21", offsetof(CPUState, fpr[21]) },
2460     { "f22", offsetof(CPUState, fpr[22]) },
2461     { "f23", offsetof(CPUState, fpr[23]) },
2462     { "f24", offsetof(CPUState, fpr[24]) },
2463     { "f25", offsetof(CPUState, fpr[25]) },
2464     { "f26", offsetof(CPUState, fpr[26]) },
2465     { "f27", offsetof(CPUState, fpr[27]) },
2466     { "f28", offsetof(CPUState, fpr[28]) },
2467     { "f29", offsetof(CPUState, fpr[29]) },
2468     { "f30", offsetof(CPUState, fpr[30]) },
2469     { "f31", offsetof(CPUState, fpr[31]) },
2470     { "fpscr", offsetof(CPUState, fpscr) },
2471     /* Next instruction pointer */
2472     { "nip|pc", offsetof(CPUState, nip) },
2473     { "lr", offsetof(CPUState, lr) },
2474     { "ctr", offsetof(CPUState, ctr) },
2475     { "decr", 0, &monitor_get_decr, },
2476     { "ccr", 0, &monitor_get_ccr, },
2477     /* Machine state register */
2478     { "msr", 0, &monitor_get_msr, },
2479     { "xer", 0, &monitor_get_xer, },
2480     { "tbu", 0, &monitor_get_tbu, },
2481     { "tbl", 0, &monitor_get_tbl, },
2482 #if defined(TARGET_PPC64)
2483     /* Address space register */
2484     { "asr", offsetof(CPUState, asr) },
2485 #endif
2486     /* Segment registers */
2487     { "sdr1", offsetof(CPUState, sdr1) },
2488     { "sr0", offsetof(CPUState, sr[0]) },
2489     { "sr1", offsetof(CPUState, sr[1]) },
2490     { "sr2", offsetof(CPUState, sr[2]) },
2491     { "sr3", offsetof(CPUState, sr[3]) },
2492     { "sr4", offsetof(CPUState, sr[4]) },
2493     { "sr5", offsetof(CPUState, sr[5]) },
2494     { "sr6", offsetof(CPUState, sr[6]) },
2495     { "sr7", offsetof(CPUState, sr[7]) },
2496     { "sr8", offsetof(CPUState, sr[8]) },
2497     { "sr9", offsetof(CPUState, sr[9]) },
2498     { "sr10", offsetof(CPUState, sr[10]) },
2499     { "sr11", offsetof(CPUState, sr[11]) },
2500     { "sr12", offsetof(CPUState, sr[12]) },
2501     { "sr13", offsetof(CPUState, sr[13]) },
2502     { "sr14", offsetof(CPUState, sr[14]) },
2503     { "sr15", offsetof(CPUState, sr[15]) },
2504     /* Too lazy to put BATs and SPRs ... */
2505 #elif defined(TARGET_SPARC)
2506     { "g0", offsetof(CPUState, gregs[0]) },
2507     { "g1", offsetof(CPUState, gregs[1]) },
2508     { "g2", offsetof(CPUState, gregs[2]) },
2509     { "g3", offsetof(CPUState, gregs[3]) },
2510     { "g4", offsetof(CPUState, gregs[4]) },
2511     { "g5", offsetof(CPUState, gregs[5]) },
2512     { "g6", offsetof(CPUState, gregs[6]) },
2513     { "g7", offsetof(CPUState, gregs[7]) },
2514     { "o0", 0, monitor_get_reg },
2515     { "o1", 1, monitor_get_reg },
2516     { "o2", 2, monitor_get_reg },
2517     { "o3", 3, monitor_get_reg },
2518     { "o4", 4, monitor_get_reg },
2519     { "o5", 5, monitor_get_reg },
2520     { "o6", 6, monitor_get_reg },
2521     { "o7", 7, monitor_get_reg },
2522     { "l0", 8, monitor_get_reg },
2523     { "l1", 9, monitor_get_reg },
2524     { "l2", 10, monitor_get_reg },
2525     { "l3", 11, monitor_get_reg },
2526     { "l4", 12, monitor_get_reg },
2527     { "l5", 13, monitor_get_reg },
2528     { "l6", 14, monitor_get_reg },
2529     { "l7", 15, monitor_get_reg },
2530     { "i0", 16, monitor_get_reg },
2531     { "i1", 17, monitor_get_reg },
2532     { "i2", 18, monitor_get_reg },
2533     { "i3", 19, monitor_get_reg },
2534     { "i4", 20, monitor_get_reg },
2535     { "i5", 21, monitor_get_reg },
2536     { "i6", 22, monitor_get_reg },
2537     { "i7", 23, monitor_get_reg },
2538     { "pc", offsetof(CPUState, pc) },
2539     { "npc", offsetof(CPUState, npc) },
2540     { "y", offsetof(CPUState, y) },
2541 #ifndef TARGET_SPARC64
2542     { "psr", 0, &monitor_get_psr, },
2543     { "wim", offsetof(CPUState, wim) },
2544 #endif
2545     { "tbr", offsetof(CPUState, tbr) },
2546     { "fsr", offsetof(CPUState, fsr) },
2547     { "f0", offsetof(CPUState, fpr[0]) },
2548     { "f1", offsetof(CPUState, fpr[1]) },
2549     { "f2", offsetof(CPUState, fpr[2]) },
2550     { "f3", offsetof(CPUState, fpr[3]) },
2551     { "f4", offsetof(CPUState, fpr[4]) },
2552     { "f5", offsetof(CPUState, fpr[5]) },
2553     { "f6", offsetof(CPUState, fpr[6]) },
2554     { "f7", offsetof(CPUState, fpr[7]) },
2555     { "f8", offsetof(CPUState, fpr[8]) },
2556     { "f9", offsetof(CPUState, fpr[9]) },
2557     { "f10", offsetof(CPUState, fpr[10]) },
2558     { "f11", offsetof(CPUState, fpr[11]) },
2559     { "f12", offsetof(CPUState, fpr[12]) },
2560     { "f13", offsetof(CPUState, fpr[13]) },
2561     { "f14", offsetof(CPUState, fpr[14]) },
2562     { "f15", offsetof(CPUState, fpr[15]) },
2563     { "f16", offsetof(CPUState, fpr[16]) },
2564     { "f17", offsetof(CPUState, fpr[17]) },
2565     { "f18", offsetof(CPUState, fpr[18]) },
2566     { "f19", offsetof(CPUState, fpr[19]) },
2567     { "f20", offsetof(CPUState, fpr[20]) },
2568     { "f21", offsetof(CPUState, fpr[21]) },
2569     { "f22", offsetof(CPUState, fpr[22]) },
2570     { "f23", offsetof(CPUState, fpr[23]) },
2571     { "f24", offsetof(CPUState, fpr[24]) },
2572     { "f25", offsetof(CPUState, fpr[25]) },
2573     { "f26", offsetof(CPUState, fpr[26]) },
2574     { "f27", offsetof(CPUState, fpr[27]) },
2575     { "f28", offsetof(CPUState, fpr[28]) },
2576     { "f29", offsetof(CPUState, fpr[29]) },
2577     { "f30", offsetof(CPUState, fpr[30]) },
2578     { "f31", offsetof(CPUState, fpr[31]) },
2579 #ifdef TARGET_SPARC64
2580     { "f32", offsetof(CPUState, fpr[32]) },
2581     { "f34", offsetof(CPUState, fpr[34]) },
2582     { "f36", offsetof(CPUState, fpr[36]) },
2583     { "f38", offsetof(CPUState, fpr[38]) },
2584     { "f40", offsetof(CPUState, fpr[40]) },
2585     { "f42", offsetof(CPUState, fpr[42]) },
2586     { "f44", offsetof(CPUState, fpr[44]) },
2587     { "f46", offsetof(CPUState, fpr[46]) },
2588     { "f48", offsetof(CPUState, fpr[48]) },
2589     { "f50", offsetof(CPUState, fpr[50]) },
2590     { "f52", offsetof(CPUState, fpr[52]) },
2591     { "f54", offsetof(CPUState, fpr[54]) },
2592     { "f56", offsetof(CPUState, fpr[56]) },
2593     { "f58", offsetof(CPUState, fpr[58]) },
2594     { "f60", offsetof(CPUState, fpr[60]) },
2595     { "f62", offsetof(CPUState, fpr[62]) },
2596     { "asi", offsetof(CPUState, asi) },
2597     { "pstate", offsetof(CPUState, pstate) },
2598     { "cansave", offsetof(CPUState, cansave) },
2599     { "canrestore", offsetof(CPUState, canrestore) },
2600     { "otherwin", offsetof(CPUState, otherwin) },
2601     { "wstate", offsetof(CPUState, wstate) },
2602     { "cleanwin", offsetof(CPUState, cleanwin) },
2603     { "fprs", offsetof(CPUState, fprs) },
2604 #endif
2605 #endif
2606     { NULL },
2607 };
2608
2609 static void expr_error(Monitor *mon, const char *msg)
2610 {
2611     monitor_printf(mon, "%s\n", msg);
2612     longjmp(expr_env, 1);
2613 }
2614
2615 /* return 0 if OK, -1 if not found, -2 if no CPU defined */
2616 static int get_monitor_def(target_long *pval, const char *name)
2617 {
2618     const MonitorDef *md;
2619     void *ptr;
2620
2621     for(md = monitor_defs; md->name != NULL; md++) {
2622         if (compare_cmd(name, md->name)) {
2623             if (md->get_value) {
2624                 *pval = md->get_value(md, md->offset);
2625             } else {
2626                 CPUState *env = mon_get_cpu();
2627                 if (!env)
2628                     return -2;
2629                 ptr = (uint8_t *)env + md->offset;
2630                 switch(md->type) {
2631                 case MD_I32:
2632                     *pval = *(int32_t *)ptr;
2633                     break;
2634                 case MD_TLONG:
2635                     *pval = *(target_long *)ptr;
2636                     break;
2637                 default:
2638                     *pval = 0;
2639                     break;
2640                 }
2641             }
2642             return 0;
2643         }
2644     }
2645     return -1;
2646 }
2647
2648 static void next(void)
2649 {
2650     if (*pch != '\0') {
2651         pch++;
2652         while (qemu_isspace(*pch))
2653             pch++;
2654     }
2655 }
2656
2657 static int64_t expr_sum(Monitor *mon);
2658
2659 static int64_t expr_unary(Monitor *mon)
2660 {
2661     int64_t n;
2662     char *p;
2663     int ret;
2664
2665     switch(*pch) {
2666     case '+':
2667         next();
2668         n = expr_unary(mon);
2669         break;
2670     case '-':
2671         next();
2672         n = -expr_unary(mon);
2673         break;
2674     case '~':
2675         next();
2676         n = ~expr_unary(mon);
2677         break;
2678     case '(':
2679         next();
2680         n = expr_sum(mon);
2681         if (*pch != ')') {
2682             expr_error(mon, "')' expected");
2683         }
2684         next();
2685         break;
2686     case '\'':
2687         pch++;
2688         if (*pch == '\0')
2689             expr_error(mon, "character constant expected");
2690         n = *pch;
2691         pch++;
2692         if (*pch != '\'')
2693             expr_error(mon, "missing terminating \' character");
2694         next();
2695         break;
2696     case '$':
2697         {
2698             char buf[128], *q;
2699             target_long reg=0;
2700
2701             pch++;
2702             q = buf;
2703             while ((*pch >= 'a' && *pch <= 'z') ||
2704                    (*pch >= 'A' && *pch <= 'Z') ||
2705                    (*pch >= '0' && *pch <= '9') ||
2706                    *pch == '_' || *pch == '.') {
2707                 if ((q - buf) < sizeof(buf) - 1)
2708                     *q++ = *pch;
2709                 pch++;
2710             }
2711             while (qemu_isspace(*pch))
2712                 pch++;
2713             *q = 0;
2714             ret = get_monitor_def(&reg, buf);
2715             if (ret == -1)
2716                 expr_error(mon, "unknown register");
2717             else if (ret == -2)
2718                 expr_error(mon, "no cpu defined");
2719             n = reg;
2720         }
2721         break;
2722     case '\0':
2723         expr_error(mon, "unexpected end of expression");
2724         n = 0;
2725         break;
2726     default:
2727 #if TARGET_PHYS_ADDR_BITS > 32
2728         n = strtoull(pch, &p, 0);
2729 #else
2730         n = strtoul(pch, &p, 0);
2731 #endif
2732         if (pch == p) {
2733             expr_error(mon, "invalid char in expression");
2734         }
2735         pch = p;
2736         while (qemu_isspace(*pch))
2737             pch++;
2738         break;
2739     }
2740     return n;
2741 }
2742
2743
2744 static int64_t expr_prod(Monitor *mon)
2745 {
2746     int64_t val, val2;
2747     int op;
2748
2749     val = expr_unary(mon);
2750     for(;;) {
2751         op = *pch;
2752         if (op != '*' && op != '/' && op != '%')
2753             break;
2754         next();
2755         val2 = expr_unary(mon);
2756         switch(op) {
2757         default:
2758         case '*':
2759             val *= val2;
2760             break;
2761         case '/':
2762         case '%':
2763             if (val2 == 0)
2764                 expr_error(mon, "division by zero");
2765             if (op == '/')
2766                 val /= val2;
2767             else
2768                 val %= val2;
2769             break;
2770         }
2771     }
2772     return val;
2773 }
2774
2775 static int64_t expr_logic(Monitor *mon)
2776 {
2777     int64_t val, val2;
2778     int op;
2779
2780     val = expr_prod(mon);
2781     for(;;) {
2782         op = *pch;
2783         if (op != '&' && op != '|' && op != '^')
2784             break;
2785         next();
2786         val2 = expr_prod(mon);
2787         switch(op) {
2788         default:
2789         case '&':
2790             val &= val2;
2791             break;
2792         case '|':
2793             val |= val2;
2794             break;
2795         case '^':
2796             val ^= val2;
2797             break;
2798         }
2799     }
2800     return val;
2801 }
2802
2803 static int64_t expr_sum(Monitor *mon)
2804 {
2805     int64_t val, val2;
2806     int op;
2807
2808     val = expr_logic(mon);
2809     for(;;) {
2810         op = *pch;
2811         if (op != '+' && op != '-')
2812             break;
2813         next();
2814         val2 = expr_logic(mon);
2815         if (op == '+')
2816             val += val2;
2817         else
2818             val -= val2;
2819     }
2820     return val;
2821 }
2822
2823 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2824 {
2825     pch = *pp;
2826     if (setjmp(expr_env)) {
2827         *pp = pch;
2828         return -1;
2829     }
2830     while (qemu_isspace(*pch))
2831         pch++;
2832     *pval = expr_sum(mon);
2833     *pp = pch;
2834     return 0;
2835 }
2836
2837 static int get_str(char *buf, int buf_size, const char **pp)
2838 {
2839     const char *p;
2840     char *q;
2841     int c;
2842
2843     q = buf;
2844     p = *pp;
2845     while (qemu_isspace(*p))
2846         p++;
2847     if (*p == '\0') {
2848     fail:
2849         *q = '\0';
2850         *pp = p;
2851         return -1;
2852     }
2853     if (*p == '\"') {
2854         p++;
2855         while (*p != '\0' && *p != '\"') {
2856             if (*p == '\\') {
2857                 p++;
2858                 c = *p++;
2859                 switch(c) {
2860                 case 'n':
2861                     c = '\n';
2862                     break;
2863                 case 'r':
2864                     c = '\r';
2865                     break;
2866                 case '\\':
2867                 case '\'':
2868                 case '\"':
2869                     break;
2870                 default:
2871                     qemu_printf("unsupported escape code: '\\%c'\n", c);
2872                     goto fail;
2873                 }
2874                 if ((q - buf) < buf_size - 1) {
2875                     *q++ = c;
2876                 }
2877             } else {
2878                 if ((q - buf) < buf_size - 1) {
2879                     *q++ = *p;
2880                 }
2881                 p++;
2882             }
2883         }
2884         if (*p != '\"') {
2885             qemu_printf("unterminated string\n");
2886             goto fail;
2887         }
2888         p++;
2889     } else {
2890         while (*p != '\0' && !qemu_isspace(*p)) {
2891             if ((q - buf) < buf_size - 1) {
2892                 *q++ = *p;
2893             }
2894             p++;
2895         }
2896     }
2897     *q = '\0';
2898     *pp = p;
2899     return 0;
2900 }
2901
2902 /*
2903  * Store the command-name in cmdname, and return a pointer to
2904  * the remaining of the command string.
2905  */
2906 static const char *get_command_name(const char *cmdline,
2907                                     char *cmdname, size_t nlen)
2908 {
2909     size_t len;
2910     const char *p, *pstart;
2911
2912     p = cmdline;
2913     while (qemu_isspace(*p))
2914         p++;
2915     if (*p == '\0')
2916         return NULL;
2917     pstart = p;
2918     while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2919         p++;
2920     len = p - pstart;
2921     if (len > nlen - 1)
2922         len = nlen - 1;
2923     memcpy(cmdname, pstart, len);
2924     cmdname[len] = '\0';
2925     return p;
2926 }
2927
2928 /**
2929  * Read key of 'type' into 'key' and return the current
2930  * 'type' pointer.
2931  */
2932 static char *key_get_info(const char *type, char **key)
2933 {
2934     size_t len;
2935     char *p, *str;
2936
2937     if (*type == ',')
2938         type++;
2939
2940     p = strchr(type, ':');
2941     if (!p) {
2942         *key = NULL;
2943         return NULL;
2944     }
2945     len = p - type;
2946
2947     str = qemu_malloc(len + 1);
2948     memcpy(str, type, len);
2949     str[len] = '\0';
2950
2951     *key = str;
2952     return ++p;
2953 }
2954
2955 static int default_fmt_format = 'x';
2956 static int default_fmt_size = 4;
2957
2958 #define MAX_ARGS 16
2959
2960 static int is_valid_option(const char *c, const char *typestr)
2961 {
2962     char option[3];
2963   
2964     option[0] = '-';
2965     option[1] = *c;
2966     option[2] = '\0';
2967   
2968     typestr = strstr(typestr, option);
2969     return (typestr != NULL);
2970 }
2971
2972 static const mon_cmd_t *monitor_find_command(const char *cmdname)
2973 {
2974     const mon_cmd_t *cmd;
2975
2976     for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
2977         if (compare_cmd(cmdname, cmd->name)) {
2978             return cmd;
2979         }
2980     }
2981
2982     return NULL;
2983 }
2984
2985 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2986                                               const char *cmdline,
2987                                               QDict *qdict)
2988 {
2989     const char *p, *typestr;
2990     int c;
2991     const mon_cmd_t *cmd;
2992     char cmdname[256];
2993     char buf[1024];
2994     char *key;
2995
2996 #ifdef DEBUG
2997     monitor_printf(mon, "command='%s'\n", cmdline);
2998 #endif
2999
3000     /* extract the command name */
3001     p = get_command_name(cmdline, cmdname, sizeof(cmdname));
3002     if (!p)
3003         return NULL;
3004
3005     cmd = monitor_find_command(cmdname);
3006     if (!cmd) {
3007         monitor_printf(mon, "unknown command: '%s'\n", cmdname);
3008         return NULL;
3009     }
3010
3011     /* parse the parameters */
3012     typestr = cmd->args_type;
3013     for(;;) {
3014         typestr = key_get_info(typestr, &key);
3015         if (!typestr)
3016             break;
3017         c = *typestr;
3018         typestr++;
3019         switch(c) {
3020         case 'F':
3021         case 'B':
3022         case 's':
3023             {
3024                 int ret;
3025
3026                 while (qemu_isspace(*p))
3027                     p++;
3028                 if (*typestr == '?') {
3029                     typestr++;
3030                     if (*p == '\0') {
3031                         /* no optional string: NULL argument */
3032                         break;
3033                     }
3034                 }
3035                 ret = get_str(buf, sizeof(buf), &p);
3036                 if (ret < 0) {
3037                     switch(c) {
3038                     case 'F':
3039                         monitor_printf(mon, "%s: filename expected\n",
3040                                        cmdname);
3041                         break;
3042                     case 'B':
3043                         monitor_printf(mon, "%s: block device name expected\n",
3044                                        cmdname);
3045                         break;
3046                     default:
3047                         monitor_printf(mon, "%s: string expected\n", cmdname);
3048                         break;
3049                     }
3050                     goto fail;
3051                 }
3052                 qdict_put(qdict, key, qstring_from_str(buf));
3053             }
3054             break;
3055         case '/':
3056             {
3057                 int count, format, size;
3058
3059                 while (qemu_isspace(*p))
3060                     p++;
3061                 if (*p == '/') {
3062                     /* format found */
3063                     p++;
3064                     count = 1;
3065                     if (qemu_isdigit(*p)) {
3066                         count = 0;
3067                         while (qemu_isdigit(*p)) {
3068                             count = count * 10 + (*p - '0');
3069                             p++;
3070                         }
3071                     }
3072                     size = -1;
3073                     format = -1;
3074                     for(;;) {
3075                         switch(*p) {
3076                         case 'o':
3077                         case 'd':
3078                         case 'u':
3079                         case 'x':
3080                         case 'i':
3081                         case 'c':
3082                             format = *p++;
3083                             break;
3084                         case 'b':
3085                             size = 1;
3086                             p++;
3087                             break;
3088                         case 'h':
3089                             size = 2;
3090                             p++;
3091                             break;
3092                         case 'w':
3093                             size = 4;
3094                             p++;
3095                             break;
3096                         case 'g':
3097                         case 'L':
3098                             size = 8;
3099                             p++;
3100                             break;
3101                         default:
3102                             goto next;
3103                         }
3104                     }
3105                 next:
3106                     if (*p != '\0' && !qemu_isspace(*p)) {
3107                         monitor_printf(mon, "invalid char in format: '%c'\n",
3108                                        *p);
3109                         goto fail;
3110                     }
3111                     if (format < 0)
3112                         format = default_fmt_format;
3113                     if (format != 'i') {
3114                         /* for 'i', not specifying a size gives -1 as size */
3115                         if (size < 0)
3116                             size = default_fmt_size;
3117                         default_fmt_size = size;
3118                     }
3119                     default_fmt_format = format;
3120                 } else {
3121                     count = 1;
3122                     format = default_fmt_format;
3123                     if (format != 'i') {
3124                         size = default_fmt_size;
3125                     } else {
3126                         size = -1;
3127                     }
3128                 }
3129                 qdict_put(qdict, "count", qint_from_int(count));
3130                 qdict_put(qdict, "format", qint_from_int(format));
3131                 qdict_put(qdict, "size", qint_from_int(size));
3132             }
3133             break;
3134         case 'i':
3135         case 'l':
3136             {
3137                 int64_t val;
3138
3139                 while (qemu_isspace(*p))
3140                     p++;
3141                 if (*typestr == '?' || *typestr == '.') {
3142                     if (*typestr == '?') {
3143                         if (*p == '\0') {
3144                             typestr++;
3145                             break;
3146                         }
3147                     } else {
3148                         if (*p == '.') {
3149                             p++;
3150                             while (qemu_isspace(*p))
3151                                 p++;
3152                         } else {
3153                             typestr++;
3154                             break;
3155                         }
3156                     }
3157                     typestr++;
3158                 }
3159                 if (get_expr(mon, &val, &p))
3160                     goto fail;
3161                 /* Check if 'i' is greater than 32-bit */
3162                 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3163                     monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3164                     monitor_printf(mon, "integer is for 32-bit values\n");
3165                     goto fail;
3166                 }
3167                 qdict_put(qdict, key, qint_from_int(val));
3168             }
3169             break;
3170         case '-':
3171             {
3172                 const char *tmp = p;
3173                 int has_option, skip_key = 0;
3174                 /* option */
3175
3176                 c = *typestr++;
3177                 if (c == '\0')
3178                     goto bad_type;
3179                 while (qemu_isspace(*p))
3180                     p++;
3181                 has_option = 0;
3182                 if (*p == '-') {
3183                     p++;
3184                     if(c != *p) {
3185                         if(!is_valid_option(p, typestr)) {
3186                   
3187                             monitor_printf(mon, "%s: unsupported option -%c\n",
3188                                            cmdname, *p);
3189                             goto fail;
3190                         } else {
3191                             skip_key = 1;
3192                         }
3193                     }
3194                     if(skip_key) {
3195                         p = tmp;
3196                     } else {
3197                         p++;
3198                         has_option = 1;
3199                     }
3200                 }
3201                 qdict_put(qdict, key, qint_from_int(has_option));
3202             }
3203             break;
3204         default:
3205         bad_type:
3206             monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
3207             goto fail;
3208         }
3209         qemu_free(key);
3210         key = NULL;
3211     }
3212     /* check that all arguments were parsed */
3213     while (qemu_isspace(*p))
3214         p++;
3215     if (*p != '\0') {
3216         monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3217                        cmdname);
3218         goto fail;
3219     }
3220
3221     return cmd;
3222
3223 fail:
3224     qemu_free(key);
3225     return NULL;
3226 }
3227
3228 static void monitor_print_error(Monitor *mon)
3229 {
3230     qerror_print(mon->error);
3231     QDECREF(mon->error);
3232     mon->error = NULL;
3233 }
3234
3235 static void monitor_call_handler(Monitor *mon, const mon_cmd_t *cmd,
3236                                  const QDict *params)
3237 {
3238     QObject *data = NULL;
3239
3240     cmd->mhandler.cmd_new(mon, params, &data);
3241     if (data)
3242         cmd->user_print(mon, data);
3243
3244     qobject_decref(data);
3245 }
3246
3247 static void handle_user_command(Monitor *mon, const char *cmdline)
3248 {
3249     QDict *qdict;
3250     const mon_cmd_t *cmd;
3251
3252     qdict = qdict_new();
3253
3254     cmd = monitor_parse_command(mon, cmdline, qdict);
3255     if (!cmd)
3256         goto out;
3257
3258     qemu_errors_to_mon(mon);
3259
3260     if (monitor_handler_ported(cmd)) {
3261         monitor_call_handler(mon, cmd, qdict);
3262     } else {
3263         cmd->mhandler.cmd(mon, qdict);
3264     }
3265
3266     if (monitor_has_error(mon))
3267         monitor_print_error(mon);
3268
3269     qemu_errors_to_previous();
3270
3271 out:
3272     QDECREF(qdict);
3273 }
3274
3275 static void cmd_completion(const char *name, const char *list)
3276 {
3277     const char *p, *pstart;
3278     char cmd[128];
3279     int len;
3280
3281     p = list;
3282     for(;;) {
3283         pstart = p;
3284         p = strchr(p, '|');
3285         if (!p)
3286             p = pstart + strlen(pstart);
3287         len = p - pstart;
3288         if (len > sizeof(cmd) - 2)
3289             len = sizeof(cmd) - 2;
3290         memcpy(cmd, pstart, len);
3291         cmd[len] = '\0';
3292         if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3293             readline_add_completion(cur_mon->rs, cmd);
3294         }
3295         if (*p == '\0')
3296             break;
3297         p++;
3298     }
3299 }
3300
3301 static void file_completion(const char *input)
3302 {
3303     DIR *ffs;
3304     struct dirent *d;
3305     char path[1024];
3306     char file[1024], file_prefix[1024];
3307     int input_path_len;
3308     const char *p;
3309
3310     p = strrchr(input, '/');
3311     if (!p) {
3312         input_path_len = 0;
3313         pstrcpy(file_prefix, sizeof(file_prefix), input);
3314         pstrcpy(path, sizeof(path), ".");
3315     } else {
3316         input_path_len = p - input + 1;
3317         memcpy(path, input, input_path_len);
3318         if (input_path_len > sizeof(path) - 1)
3319             input_path_len = sizeof(path) - 1;
3320         path[input_path_len] = '\0';
3321         pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3322     }
3323 #ifdef DEBUG_COMPLETION
3324     monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
3325                    input, path, file_prefix);
3326 #endif
3327     ffs = opendir(path);
3328     if (!ffs)
3329         return;
3330     for(;;) {
3331         struct stat sb;
3332         d = readdir(ffs);
3333         if (!d)
3334             break;
3335         if (strstart(d->d_name, file_prefix, NULL)) {
3336             memcpy(file, input, input_path_len);
3337             if (input_path_len < sizeof(file))
3338                 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3339                         d->d_name);
3340             /* stat the file to find out if it's a directory.
3341              * In that case add a slash to speed up typing long paths
3342              */
3343             stat(file, &sb);
3344             if(S_ISDIR(sb.st_mode))
3345                 pstrcat(file, sizeof(file), "/");
3346             readline_add_completion(cur_mon->rs, file);
3347         }
3348     }
3349     closedir(ffs);
3350 }
3351
3352 static void block_completion_it(void *opaque, BlockDriverState *bs)
3353 {
3354     const char *name = bdrv_get_device_name(bs);
3355     const char *input = opaque;
3356
3357     if (input[0] == '\0' ||
3358         !strncmp(name, (char *)input, strlen(input))) {
3359         readline_add_completion(cur_mon->rs, name);
3360     }
3361 }
3362
3363 /* NOTE: this parser is an approximate form of the real command parser */
3364 static void parse_cmdline(const char *cmdline,
3365                          int *pnb_args, char **args)
3366 {
3367     const char *p;
3368     int nb_args, ret;
3369     char buf[1024];
3370
3371     p = cmdline;
3372     nb_args = 0;
3373     for(;;) {
3374         while (qemu_isspace(*p))
3375             p++;
3376         if (*p == '\0')
3377             break;
3378         if (nb_args >= MAX_ARGS)
3379             break;
3380         ret = get_str(buf, sizeof(buf), &p);
3381         args[nb_args] = qemu_strdup(buf);
3382         nb_args++;
3383         if (ret < 0)
3384             break;
3385     }
3386     *pnb_args = nb_args;
3387 }
3388
3389 static const char *next_arg_type(const char *typestr)
3390 {
3391     const char *p = strchr(typestr, ':');
3392     return (p != NULL ? ++p : typestr);
3393 }
3394
3395 static void monitor_find_completion(const char *cmdline)
3396 {
3397     const char *cmdname;
3398     char *args[MAX_ARGS];
3399     int nb_args, i, len;
3400     const char *ptype, *str;
3401     const mon_cmd_t *cmd;
3402     const KeyDef *key;
3403
3404     parse_cmdline(cmdline, &nb_args, args);
3405 #ifdef DEBUG_COMPLETION
3406     for(i = 0; i < nb_args; i++) {
3407         monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
3408     }
3409 #endif
3410
3411     /* if the line ends with a space, it means we want to complete the
3412        next arg */
3413     len = strlen(cmdline);
3414     if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3415         if (nb_args >= MAX_ARGS)
3416             return;
3417         args[nb_args++] = qemu_strdup("");
3418     }
3419     if (nb_args <= 1) {
3420         /* command completion */
3421         if (nb_args == 0)
3422             cmdname = "";
3423         else
3424             cmdname = args[0];
3425         readline_set_completion_index(cur_mon->rs, strlen(cmdname));
3426         for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
3427             cmd_completion(cmdname, cmd->name);
3428         }
3429     } else {
3430         /* find the command */
3431         for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
3432             if (compare_cmd(args[0], cmd->name))
3433                 goto found;
3434         }
3435         return;
3436     found:
3437         ptype = next_arg_type(cmd->args_type);
3438         for(i = 0; i < nb_args - 2; i++) {
3439             if (*ptype != '\0') {
3440                 ptype = next_arg_type(ptype);
3441                 while (*ptype == '?')
3442                     ptype = next_arg_type(ptype);
3443             }
3444         }
3445         str = args[nb_args - 1];
3446         if (*ptype == '-' && ptype[1] != '\0') {
3447             ptype += 2;
3448         }
3449         switch(*ptype) {
3450         case 'F':
3451             /* file completion */
3452             readline_set_completion_index(cur_mon->rs, strlen(str));
3453             file_completion(str);
3454             break;
3455         case 'B':
3456             /* block device name completion */
3457             readline_set_completion_index(cur_mon->rs, strlen(str));
3458             bdrv_iterate(block_completion_it, (void *)str);
3459             break;
3460         case 's':
3461             /* XXX: more generic ? */
3462             if (!strcmp(cmd->name, "info")) {
3463                 readline_set_completion_index(cur_mon->rs, strlen(str));
3464                 for(cmd = info_cmds; cmd->name != NULL; cmd++) {
3465                     cmd_completion(str, cmd->name);
3466                 }
3467             } else if (!strcmp(cmd->name, "sendkey")) {
3468                 char *sep = strrchr(str, '-');
3469                 if (sep)
3470                     str = sep + 1;
3471                 readline_set_completion_index(cur_mon->rs, strlen(str));
3472                 for(key = key_defs; key->name != NULL; key++) {
3473                     cmd_completion(str, key->name);
3474                 }
3475             } else if (!strcmp(cmd->name, "help|?")) {
3476                 readline_set_completion_index(cur_mon->rs, strlen(str));
3477                 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
3478                     cmd_completion(str, cmd->name);
3479                 }
3480             }
3481             break;
3482         default:
3483             break;
3484         }
3485     }
3486     for(i = 0; i < nb_args; i++)
3487         qemu_free(args[i]);
3488 }
3489
3490 static int monitor_can_read(void *opaque)
3491 {
3492     Monitor *mon = opaque;
3493
3494     return (mon->suspend_cnt == 0) ? 128 : 0;
3495 }
3496
3497 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3498 {
3499     Monitor *old_mon = cur_mon;
3500     int i;
3501
3502     cur_mon = opaque;
3503
3504     if (cur_mon->rs) {
3505         for (i = 0; i < size; i++)
3506             readline_handle_byte(cur_mon->rs, buf[i]);
3507     } else {
3508         if (size == 0 || buf[size - 1] != 0)
3509             monitor_printf(cur_mon, "corrupted command\n");
3510         else
3511             handle_user_command(cur_mon, (char *)buf);
3512     }
3513
3514     cur_mon = old_mon;
3515 }
3516
3517 static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
3518 {
3519     monitor_suspend(mon);
3520     handle_user_command(mon, cmdline);
3521     monitor_resume(mon);
3522 }
3523
3524 int monitor_suspend(Monitor *mon)
3525 {
3526     if (!mon->rs)
3527         return -ENOTTY;
3528     mon->suspend_cnt++;
3529     return 0;
3530 }
3531
3532 void monitor_resume(Monitor *mon)
3533 {
3534     if (!mon->rs)
3535         return;
3536     if (--mon->suspend_cnt == 0)
3537         readline_show_prompt(mon->rs);
3538 }
3539
3540 static void monitor_event(void *opaque, int event)
3541 {
3542     Monitor *mon = opaque;
3543
3544     switch (event) {
3545     case CHR_EVENT_MUX_IN:
3546         mon->mux_out = 0;
3547         if (mon->reset_seen) {
3548             readline_restart(mon->rs);
3549             monitor_resume(mon);
3550             monitor_flush(mon);
3551         } else {
3552             mon->suspend_cnt = 0;
3553         }
3554         break;
3555
3556     case CHR_EVENT_MUX_OUT:
3557         if (mon->reset_seen) {
3558             if (mon->suspend_cnt == 0) {
3559                 monitor_printf(mon, "\n");
3560             }
3561             monitor_flush(mon);
3562             monitor_suspend(mon);
3563         } else {
3564             mon->suspend_cnt++;
3565         }
3566         mon->mux_out = 1;
3567         break;
3568
3569     case CHR_EVENT_OPENED:
3570         monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
3571                        "information\n", QEMU_VERSION);
3572         if (!mon->mux_out) {
3573             readline_show_prompt(mon->rs);
3574         }
3575         mon->reset_seen = 1;
3576         break;
3577     }
3578 }
3579
3580
3581 /*
3582  * Local variables:
3583  *  c-indent-level: 4
3584  *  c-basic-offset: 4
3585  *  tab-width: 8
3586  * End:
3587  */
3588
3589 const char *monitor_cmdline_parse(const char *cmdline, int *flags)
3590 {
3591     const char *dev;
3592
3593     if (strstart(cmdline, "control,", &dev)) {
3594         if (strstart(dev, "vc", NULL)) {
3595             fprintf(stderr, "qemu: control mode is for low-level interaction ");
3596             fprintf(stderr, "cannot be used with device 'vc'\n");
3597             exit(1);
3598         }
3599         *flags &= ~MONITOR_USE_READLINE;
3600         *flags |= MONITOR_USE_CONTROL;
3601         return dev;
3602     }
3603
3604     return cmdline;
3605 }
3606
3607 void monitor_init(CharDriverState *chr, int flags)
3608 {
3609     static int is_first_init = 1;
3610     Monitor *mon;
3611
3612     if (is_first_init) {
3613         key_timer = qemu_new_timer(vm_clock, release_keys, NULL);
3614         is_first_init = 0;
3615     }
3616
3617     mon = qemu_mallocz(sizeof(*mon));
3618
3619     mon->chr = chr;
3620     mon->flags = flags;
3621     if (flags & MONITOR_USE_READLINE) {
3622         mon->rs = readline_init(mon, monitor_find_completion);
3623         monitor_read_command(mon, 0);
3624     }
3625
3626     qemu_chr_add_handlers(chr, monitor_can_read, monitor_read, monitor_event,
3627                           mon);
3628
3629     QLIST_INSERT_HEAD(&mon_list, mon, entry);
3630     if (!cur_mon || (flags & MONITOR_IS_DEFAULT))
3631         cur_mon = mon;
3632 }
3633
3634 static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
3635 {
3636     BlockDriverState *bs = opaque;
3637     int ret = 0;
3638
3639     if (bdrv_set_key(bs, password) != 0) {
3640         monitor_printf(mon, "invalid password\n");
3641         ret = -EPERM;
3642     }
3643     if (mon->password_completion_cb)
3644         mon->password_completion_cb(mon->password_opaque, ret);
3645
3646     monitor_read_command(mon, 1);
3647 }
3648
3649 void monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
3650                                  BlockDriverCompletionFunc *completion_cb,
3651                                  void *opaque)
3652 {
3653     int err;
3654
3655     if (!bdrv_key_required(bs)) {
3656         if (completion_cb)
3657             completion_cb(opaque, 0);
3658         return;
3659     }
3660
3661     monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
3662                    bdrv_get_encrypted_filename(bs));
3663
3664     mon->password_completion_cb = completion_cb;
3665     mon->password_opaque = opaque;
3666
3667     err = monitor_read_password(mon, bdrv_password_cb, bs);
3668
3669     if (err && completion_cb)
3670         completion_cb(opaque, err);
3671 }
3672
3673 typedef struct QemuErrorSink QemuErrorSink;
3674 struct QemuErrorSink {
3675     enum {
3676         ERR_SINK_FILE,
3677         ERR_SINK_MONITOR,
3678     } dest;
3679     union {
3680         FILE    *fp;
3681         Monitor *mon;
3682     };
3683     QemuErrorSink *previous;
3684 };
3685
3686 static QemuErrorSink *qemu_error_sink;
3687
3688 void qemu_errors_to_file(FILE *fp)
3689 {
3690     QemuErrorSink *sink;
3691
3692     sink = qemu_mallocz(sizeof(*sink));
3693     sink->dest = ERR_SINK_FILE;
3694     sink->fp = fp;
3695     sink->previous = qemu_error_sink;
3696     qemu_error_sink = sink;
3697 }
3698
3699 void qemu_errors_to_mon(Monitor *mon)
3700 {
3701     QemuErrorSink *sink;
3702
3703     sink = qemu_mallocz(sizeof(*sink));
3704     sink->dest = ERR_SINK_MONITOR;
3705     sink->mon = mon;
3706     sink->previous = qemu_error_sink;
3707     qemu_error_sink = sink;
3708 }
3709
3710 void qemu_errors_to_previous(void)
3711 {
3712     QemuErrorSink *sink;
3713
3714     assert(qemu_error_sink != NULL);
3715     sink = qemu_error_sink;
3716     qemu_error_sink = sink->previous;
3717     qemu_free(sink);
3718 }
3719
3720 void qemu_error(const char *fmt, ...)
3721 {
3722     va_list args;
3723
3724     assert(qemu_error_sink != NULL);
3725     switch (qemu_error_sink->dest) {
3726     case ERR_SINK_FILE:
3727         va_start(args, fmt);
3728         vfprintf(qemu_error_sink->fp, fmt, args);
3729         va_end(args);
3730         break;
3731     case ERR_SINK_MONITOR:
3732         va_start(args, fmt);
3733         monitor_vprintf(qemu_error_sink->mon, fmt, args);
3734         va_end(args);
3735         break;
3736     }
3737 }
3738
3739 void qemu_error_internal(const char *file, int linenr, const char *func,
3740                          const char *fmt, ...)
3741 {
3742     va_list va;
3743     QError *qerror;
3744
3745     assert(qemu_error_sink != NULL);
3746
3747     va_start(va, fmt);
3748     qerror = qerror_from_info(file, linenr, func, fmt, &va);
3749     va_end(va);
3750
3751     switch (qemu_error_sink->dest) {
3752     case ERR_SINK_FILE:
3753         qerror_print(qerror);
3754         QDECREF(qerror);
3755         break;
3756     case ERR_SINK_MONITOR:
3757         assert(qemu_error_sink->mon->error == NULL);
3758         qemu_error_sink->mon->error = qerror;
3759         break;
3760     }
3761 }
This page took 0.220256 seconds and 4 git commands to generate.