monitor: Rework API (Jan Kiszka)
[qemu] / 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 "hw/hw.h"
25 #include "hw/usb.h"
26 #include "hw/pcmcia.h"
27 #include "hw/pc.h"
28 #include "hw/pci.h"
29 #include "gdbstub.h"
30 #include "net.h"
31 #include "qemu-char.h"
32 #include "sysemu.h"
33 #include "monitor.h"
34 #include "readline.h"
35 #include "console.h"
36 #include "block.h"
37 #include "audio/audio.h"
38 #include "disas.h"
39 #include "balloon.h"
40 #include <dirent.h>
41 #include "qemu-timer.h"
42 #include "migration.h"
43 #include "kvm.h"
44
45 //#define DEBUG
46 //#define DEBUG_COMPLETION
47
48 /*
49  * Supported types:
50  *
51  * 'F'          filename
52  * 'B'          block device name
53  * 's'          string (accept optional quote)
54  * 'i'          32 bit integer
55  * 'l'          target long (32 or 64 bit)
56  * '/'          optional gdb-like print format (like "/10x")
57  *
58  * '?'          optional type (for 'F', 's' and 'i')
59  *
60  */
61
62 typedef struct mon_cmd_t {
63     const char *name;
64     const char *args_type;
65     void *handler;
66     const char *params;
67     const char *help;
68 } mon_cmd_t;
69
70 #define MAX_MON 4
71 static CharDriverState *monitor_hd[MAX_MON];
72 static int hide_banner;
73
74 static const mon_cmd_t mon_cmds[];
75 static const mon_cmd_t info_cmds[];
76
77 static uint8_t term_outbuf[1024];
78 static int term_outbuf_index;
79 static BlockDriverCompletionFunc *password_completion_cb;
80 static void *password_opaque;
81
82 Monitor *cur_mon;
83
84 static void monitor_start_input(void);
85
86 static CPUState *mon_cpu = NULL;
87
88 static void monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
89                                   void *opaque)
90 {
91     readline_start("Password: ", 1, readline_func, opaque);
92 }
93
94 void monitor_flush(Monitor *mon)
95 {
96     int i;
97     if (term_outbuf_index > 0) {
98         for (i = 0; i < MAX_MON; i++)
99             if (monitor_hd[i] && monitor_hd[i]->focus == 0)
100                 qemu_chr_write(monitor_hd[i], term_outbuf, term_outbuf_index);
101         term_outbuf_index = 0;
102     }
103 }
104
105 /* flush at every end of line or if the buffer is full */
106 static void monitor_puts(Monitor *mon, const char *str)
107 {
108     char c;
109     for(;;) {
110         c = *str++;
111         if (c == '\0')
112             break;
113         if (c == '\n')
114             term_outbuf[term_outbuf_index++] = '\r';
115         term_outbuf[term_outbuf_index++] = c;
116         if (term_outbuf_index >= (sizeof(term_outbuf) - 1) ||
117             c == '\n')
118             monitor_flush(mon);
119     }
120 }
121
122 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
123 {
124     char buf[4096];
125     vsnprintf(buf, sizeof(buf), fmt, ap);
126     monitor_puts(mon, buf);
127 }
128
129 void monitor_printf(Monitor *mon, const char *fmt, ...)
130 {
131     va_list ap;
132     va_start(ap, fmt);
133     monitor_vprintf(mon, fmt, ap);
134     va_end(ap);
135 }
136
137 void monitor_print_filename(Monitor *mon, const char *filename)
138 {
139     int i;
140
141     for (i = 0; filename[i]; i++) {
142         switch (filename[i]) {
143         case ' ':
144         case '"':
145         case '\\':
146             monitor_printf(mon, "\\%c", filename[i]);
147             break;
148         case '\t':
149             monitor_printf(mon, "\\t");
150             break;
151         case '\r':
152             monitor_printf(mon, "\\r");
153             break;
154         case '\n':
155             monitor_printf(mon, "\\n");
156             break;
157         default:
158             monitor_printf(mon, "%c", filename[i]);
159             break;
160         }
161     }
162 }
163
164 static int monitor_fprintf(FILE *stream, const char *fmt, ...)
165 {
166     va_list ap;
167     va_start(ap, fmt);
168     monitor_vprintf((Monitor *)stream, fmt, ap);
169     va_end(ap);
170     return 0;
171 }
172
173 static int compare_cmd(const char *name, const char *list)
174 {
175     const char *p, *pstart;
176     int len;
177     len = strlen(name);
178     p = list;
179     for(;;) {
180         pstart = p;
181         p = strchr(p, '|');
182         if (!p)
183             p = pstart + strlen(pstart);
184         if ((p - pstart) == len && !memcmp(pstart, name, len))
185             return 1;
186         if (*p == '\0')
187             break;
188         p++;
189     }
190     return 0;
191 }
192
193 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
194                           const char *prefix, const char *name)
195 {
196     const mon_cmd_t *cmd;
197
198     for(cmd = cmds; cmd->name != NULL; cmd++) {
199         if (!name || !strcmp(name, cmd->name))
200             monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
201                            cmd->params, cmd->help);
202     }
203 }
204
205 static void help_cmd(Monitor *mon, const char *name)
206 {
207     if (name && !strcmp(name, "info")) {
208         help_cmd_dump(mon, info_cmds, "info ", NULL);
209     } else {
210         help_cmd_dump(mon, mon_cmds, "", name);
211         if (name && !strcmp(name, "log")) {
212             const CPULogItem *item;
213             monitor_printf(mon, "Log items (comma separated):\n");
214             monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
215             for(item = cpu_log_items; item->mask != 0; item++) {
216                 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
217             }
218         }
219     }
220 }
221
222 static void do_commit(Monitor *mon, const char *device)
223 {
224     int i, all_devices;
225
226     all_devices = !strcmp(device, "all");
227     for (i = 0; i < nb_drives; i++) {
228             if (all_devices ||
229                 !strcmp(bdrv_get_device_name(drives_table[i].bdrv), device))
230                 bdrv_commit(drives_table[i].bdrv);
231     }
232 }
233
234 static void do_info(Monitor *mon, const char *item)
235 {
236     const mon_cmd_t *cmd;
237     void (*handler)(Monitor *);
238
239     if (!item)
240         goto help;
241     for(cmd = info_cmds; cmd->name != NULL; cmd++) {
242         if (compare_cmd(item, cmd->name))
243             goto found;
244     }
245  help:
246     help_cmd(mon, "info");
247     return;
248  found:
249     handler = cmd->handler;
250     handler(mon);
251 }
252
253 static void do_info_version(Monitor *mon)
254 {
255     monitor_printf(mon, "%s\n", QEMU_VERSION);
256 }
257
258 static void do_info_name(Monitor *mon)
259 {
260     if (qemu_name)
261         monitor_printf(mon, "%s\n", qemu_name);
262 }
263
264 #if defined(TARGET_I386)
265 static void do_info_hpet(Monitor *mon)
266 {
267     monitor_printf(mon, "HPET is %s by QEMU\n",
268                    (no_hpet) ? "disabled" : "enabled");
269 }
270 #endif
271
272 static void do_info_uuid(Monitor *mon)
273 {
274     monitor_printf(mon, UUID_FMT "\n", qemu_uuid[0], qemu_uuid[1],
275                    qemu_uuid[2], qemu_uuid[3], qemu_uuid[4], qemu_uuid[5],
276                    qemu_uuid[6], qemu_uuid[7], qemu_uuid[8], qemu_uuid[9],
277                    qemu_uuid[10], qemu_uuid[11], qemu_uuid[12], qemu_uuid[13],
278                    qemu_uuid[14], qemu_uuid[15]);
279 }
280
281 /* get the current CPU defined by the user */
282 static int mon_set_cpu(int cpu_index)
283 {
284     CPUState *env;
285
286     for(env = first_cpu; env != NULL; env = env->next_cpu) {
287         if (env->cpu_index == cpu_index) {
288             mon_cpu = env;
289             return 0;
290         }
291     }
292     return -1;
293 }
294
295 static CPUState *mon_get_cpu(void)
296 {
297     if (!mon_cpu) {
298         mon_set_cpu(0);
299     }
300     return mon_cpu;
301 }
302
303 static void do_info_registers(Monitor *mon)
304 {
305     CPUState *env;
306     env = mon_get_cpu();
307     if (!env)
308         return;
309 #ifdef TARGET_I386
310     cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
311                    X86_DUMP_FPU);
312 #else
313     cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
314                    0);
315 #endif
316 }
317
318 static void do_info_cpus(Monitor *mon)
319 {
320     CPUState *env;
321
322     /* just to set the default cpu if not already done */
323     mon_get_cpu();
324
325     for(env = first_cpu; env != NULL; env = env->next_cpu) {
326         monitor_printf(mon, "%c CPU #%d:",
327                        (env == mon_cpu) ? '*' : ' ',
328                        env->cpu_index);
329 #if defined(TARGET_I386)
330         monitor_printf(mon, " pc=0x" TARGET_FMT_lx,
331                        env->eip + env->segs[R_CS].base);
332 #elif defined(TARGET_PPC)
333         monitor_printf(mon, " nip=0x" TARGET_FMT_lx, env->nip);
334 #elif defined(TARGET_SPARC)
335         monitor_printf(mon, " pc=0x" TARGET_FMT_lx " npc=0x" TARGET_FMT_lx,
336                        env->pc, env->npc);
337 #elif defined(TARGET_MIPS)
338         monitor_printf(mon, " PC=0x" TARGET_FMT_lx, env->active_tc.PC);
339 #endif
340         if (env->halted)
341             monitor_printf(mon, " (halted)");
342         monitor_printf(mon, "\n");
343     }
344 }
345
346 static void do_cpu_set(Monitor *mon, int index)
347 {
348     if (mon_set_cpu(index) < 0)
349         monitor_printf(mon, "Invalid CPU index\n");
350 }
351
352 static void do_info_jit(Monitor *mon)
353 {
354     dump_exec_info((FILE *)mon, monitor_fprintf);
355 }
356
357 static void do_info_history(Monitor *mon)
358 {
359     int i;
360     const char *str;
361
362     i = 0;
363     for(;;) {
364         str = readline_get_history(i);
365         if (!str)
366             break;
367         monitor_printf(mon, "%d: '%s'\n", i, str);
368         i++;
369     }
370 }
371
372 #if defined(TARGET_PPC)
373 /* XXX: not implemented in other targets */
374 static void do_info_cpu_stats(Monitor *mon)
375 {
376     CPUState *env;
377
378     env = mon_get_cpu();
379     cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
380 }
381 #endif
382
383 static void do_quit(Monitor *mon)
384 {
385     exit(0);
386 }
387
388 static int eject_device(Monitor *mon, BlockDriverState *bs, int force)
389 {
390     if (bdrv_is_inserted(bs)) {
391         if (!force) {
392             if (!bdrv_is_removable(bs)) {
393                 monitor_printf(mon, "device is not removable\n");
394                 return -1;
395             }
396             if (bdrv_is_locked(bs)) {
397                 monitor_printf(mon, "device is locked\n");
398                 return -1;
399             }
400         }
401         bdrv_close(bs);
402     }
403     return 0;
404 }
405
406 static void do_eject(Monitor *mon, int force, const char *filename)
407 {
408     BlockDriverState *bs;
409
410     bs = bdrv_find(filename);
411     if (!bs) {
412         monitor_printf(mon, "device not found\n");
413         return;
414     }
415     eject_device(mon, bs, force);
416 }
417
418 static void do_change_block(Monitor *mon, const char *device,
419                             const char *filename, const char *fmt)
420 {
421     BlockDriverState *bs;
422     BlockDriver *drv = NULL;
423
424     bs = bdrv_find(device);
425     if (!bs) {
426         monitor_printf(mon, "device not found\n");
427         return;
428     }
429     if (fmt) {
430         drv = bdrv_find_format(fmt);
431         if (!drv) {
432             monitor_printf(mon, "invalid format %s\n", fmt);
433             return;
434         }
435     }
436     if (eject_device(mon, bs, 0) < 0)
437         return;
438     bdrv_open2(bs, filename, 0, drv);
439     monitor_read_bdrv_key_start(mon, bs, NULL, NULL);
440 }
441
442 static void change_vnc_password_cb(Monitor *mon, const char *password,
443                                    void *opaque)
444 {
445     if (vnc_display_password(NULL, password) < 0)
446         monitor_printf(mon, "could not set VNC server password\n");
447
448     monitor_start_input();
449 }
450
451 static void do_change_vnc(Monitor *mon, const char *target, const char *arg)
452 {
453     if (strcmp(target, "passwd") == 0 ||
454         strcmp(target, "password") == 0) {
455         if (arg) {
456             char password[9];
457             strncpy(password, arg, sizeof(password));
458             password[sizeof(password) - 1] = '\0';
459             change_vnc_password_cb(mon, password, NULL);
460         } else {
461             monitor_read_password(mon, change_vnc_password_cb, NULL);
462         }
463     } else {
464         if (vnc_display_open(NULL, target) < 0)
465             monitor_printf(mon, "could not start VNC server on %s\n", target);
466     }
467 }
468
469 static void do_change(Monitor *mon, const char *device, const char *target,
470                       const char *arg)
471 {
472     if (strcmp(device, "vnc") == 0) {
473         do_change_vnc(mon, target, arg);
474     } else {
475         do_change_block(mon, device, target, arg);
476     }
477 }
478
479 static void do_screen_dump(Monitor *mon, const char *filename)
480 {
481     vga_hw_screen_dump(filename);
482 }
483
484 static void do_logfile(Monitor *mon, const char *filename)
485 {
486     cpu_set_log_filename(filename);
487 }
488
489 static void do_log(Monitor *mon, const char *items)
490 {
491     int mask;
492
493     if (!strcmp(items, "none")) {
494         mask = 0;
495     } else {
496         mask = cpu_str_to_log_mask(items);
497         if (!mask) {
498             help_cmd(mon, "log");
499             return;
500         }
501     }
502     cpu_set_log(mask);
503 }
504
505 static void do_stop(Monitor *mon)
506 {
507     vm_stop(EXCP_INTERRUPT);
508 }
509
510 static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs);
511
512 struct bdrv_iterate_context {
513     Monitor *mon;
514     int err;
515 };
516
517 static void do_cont(Monitor *mon)
518 {
519     struct bdrv_iterate_context context = { mon, 0 };
520
521     bdrv_iterate(encrypted_bdrv_it, &context);
522     /* only resume the vm if all keys are set and valid */
523     if (!context.err)
524         vm_start();
525 }
526
527 static void bdrv_key_cb(void *opaque, int err)
528 {
529     Monitor *mon = opaque;
530
531     /* another key was set successfully, retry to continue */
532     if (!err)
533         do_cont(mon);
534 }
535
536 static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs)
537 {
538     struct bdrv_iterate_context *context = opaque;
539
540     if (!context->err && bdrv_key_required(bs)) {
541         context->err = -EBUSY;
542         monitor_read_bdrv_key_start(context->mon, bs, bdrv_key_cb,
543                                     context->mon);
544     }
545 }
546
547 #ifdef CONFIG_GDBSTUB
548 static void do_gdbserver(Monitor *mon, const char *port)
549 {
550     if (!port)
551         port = DEFAULT_GDBSTUB_PORT;
552     if (gdbserver_start(port) < 0) {
553         monitor_printf(mon, "Could not open gdbserver socket on port '%s'\n",
554                        port);
555     } else {
556         monitor_printf(mon, "Waiting gdb connection on port '%s'\n", port);
557     }
558 }
559 #endif
560
561 static void monitor_printc(Monitor *mon, int c)
562 {
563     monitor_printf(mon, "'");
564     switch(c) {
565     case '\'':
566         monitor_printf(mon, "\\'");
567         break;
568     case '\\':
569         monitor_printf(mon, "\\\\");
570         break;
571     case '\n':
572         monitor_printf(mon, "\\n");
573         break;
574     case '\r':
575         monitor_printf(mon, "\\r");
576         break;
577     default:
578         if (c >= 32 && c <= 126) {
579             monitor_printf(mon, "%c", c);
580         } else {
581             monitor_printf(mon, "\\x%02x", c);
582         }
583         break;
584     }
585     monitor_printf(mon, "'");
586 }
587
588 static void memory_dump(Monitor *mon, int count, int format, int wsize,
589                         target_phys_addr_t addr, int is_physical)
590 {
591     CPUState *env;
592     int nb_per_line, l, line_size, i, max_digits, len;
593     uint8_t buf[16];
594     uint64_t v;
595
596     if (format == 'i') {
597         int flags;
598         flags = 0;
599         env = mon_get_cpu();
600         if (!env && !is_physical)
601             return;
602 #ifdef TARGET_I386
603         if (wsize == 2) {
604             flags = 1;
605         } else if (wsize == 4) {
606             flags = 0;
607         } else {
608             /* as default we use the current CS size */
609             flags = 0;
610             if (env) {
611 #ifdef TARGET_X86_64
612                 if ((env->efer & MSR_EFER_LMA) &&
613                     (env->segs[R_CS].flags & DESC_L_MASK))
614                     flags = 2;
615                 else
616 #endif
617                 if (!(env->segs[R_CS].flags & DESC_B_MASK))
618                     flags = 1;
619             }
620         }
621 #endif
622         monitor_disas(mon, env, addr, count, is_physical, flags);
623         return;
624     }
625
626     len = wsize * count;
627     if (wsize == 1)
628         line_size = 8;
629     else
630         line_size = 16;
631     nb_per_line = line_size / wsize;
632     max_digits = 0;
633
634     switch(format) {
635     case 'o':
636         max_digits = (wsize * 8 + 2) / 3;
637         break;
638     default:
639     case 'x':
640         max_digits = (wsize * 8) / 4;
641         break;
642     case 'u':
643     case 'd':
644         max_digits = (wsize * 8 * 10 + 32) / 33;
645         break;
646     case 'c':
647         wsize = 1;
648         break;
649     }
650
651     while (len > 0) {
652         if (is_physical)
653             monitor_printf(mon, TARGET_FMT_plx ":", addr);
654         else
655             monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
656         l = len;
657         if (l > line_size)
658             l = line_size;
659         if (is_physical) {
660             cpu_physical_memory_rw(addr, buf, l, 0);
661         } else {
662             env = mon_get_cpu();
663             if (!env)
664                 break;
665             if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {
666                 monitor_printf(mon, " Cannot access memory\n");
667                 break;
668             }
669         }
670         i = 0;
671         while (i < l) {
672             switch(wsize) {
673             default:
674             case 1:
675                 v = ldub_raw(buf + i);
676                 break;
677             case 2:
678                 v = lduw_raw(buf + i);
679                 break;
680             case 4:
681                 v = (uint32_t)ldl_raw(buf + i);
682                 break;
683             case 8:
684                 v = ldq_raw(buf + i);
685                 break;
686             }
687             monitor_printf(mon, " ");
688             switch(format) {
689             case 'o':
690                 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
691                 break;
692             case 'x':
693                 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
694                 break;
695             case 'u':
696                 monitor_printf(mon, "%*" PRIu64, max_digits, v);
697                 break;
698             case 'd':
699                 monitor_printf(mon, "%*" PRId64, max_digits, v);
700                 break;
701             case 'c':
702                 monitor_printc(mon, v);
703                 break;
704             }
705             i += wsize;
706         }
707         monitor_printf(mon, "\n");
708         addr += l;
709         len -= l;
710     }
711 }
712
713 #if TARGET_LONG_BITS == 64
714 #define GET_TLONG(h, l) (((uint64_t)(h) << 32) | (l))
715 #else
716 #define GET_TLONG(h, l) (l)
717 #endif
718
719 static void do_memory_dump(Monitor *mon, int count, int format, int size,
720                            uint32_t addrh, uint32_t addrl)
721 {
722     target_long addr = GET_TLONG(addrh, addrl);
723     memory_dump(mon, count, format, size, addr, 0);
724 }
725
726 #if TARGET_PHYS_ADDR_BITS > 32
727 #define GET_TPHYSADDR(h, l) (((uint64_t)(h) << 32) | (l))
728 #else
729 #define GET_TPHYSADDR(h, l) (l)
730 #endif
731
732 static void do_physical_memory_dump(Monitor *mon, int count, int format,
733                                     int size, uint32_t addrh, uint32_t addrl)
734
735 {
736     target_phys_addr_t addr = GET_TPHYSADDR(addrh, addrl);
737     memory_dump(mon, count, format, size, addr, 1);
738 }
739
740 static void do_print(Monitor *mon, int count, int format, int size,
741                      unsigned int valh, unsigned int vall)
742 {
743     target_phys_addr_t val = GET_TPHYSADDR(valh, vall);
744 #if TARGET_PHYS_ADDR_BITS == 32
745     switch(format) {
746     case 'o':
747         monitor_printf(mon, "%#o", val);
748         break;
749     case 'x':
750         monitor_printf(mon, "%#x", val);
751         break;
752     case 'u':
753         monitor_printf(mon, "%u", val);
754         break;
755     default:
756     case 'd':
757         monitor_printf(mon, "%d", val);
758         break;
759     case 'c':
760         monitor_printc(mon, val);
761         break;
762     }
763 #else
764     switch(format) {
765     case 'o':
766         monitor_printf(mon, "%#" PRIo64, val);
767         break;
768     case 'x':
769         monitor_printf(mon, "%#" PRIx64, val);
770         break;
771     case 'u':
772         monitor_printf(mon, "%" PRIu64, val);
773         break;
774     default:
775     case 'd':
776         monitor_printf(mon, "%" PRId64, val);
777         break;
778     case 'c':
779         monitor_printc(mon, val);
780         break;
781     }
782 #endif
783     monitor_printf(mon, "\n");
784 }
785
786 static void do_memory_save(Monitor *mon, unsigned int valh, unsigned int vall,
787                            uint32_t size, const char *filename)
788 {
789     FILE *f;
790     target_long addr = GET_TLONG(valh, vall);
791     uint32_t l;
792     CPUState *env;
793     uint8_t buf[1024];
794
795     env = mon_get_cpu();
796     if (!env)
797         return;
798
799     f = fopen(filename, "wb");
800     if (!f) {
801         monitor_printf(mon, "could not open '%s'\n", filename);
802         return;
803     }
804     while (size != 0) {
805         l = sizeof(buf);
806         if (l > size)
807             l = size;
808         cpu_memory_rw_debug(env, addr, buf, l, 0);
809         fwrite(buf, 1, l, f);
810         addr += l;
811         size -= l;
812     }
813     fclose(f);
814 }
815
816 static void do_physical_memory_save(Monitor *mon, unsigned int valh,
817                                     unsigned int vall, uint32_t size,
818                                     const char *filename)
819 {
820     FILE *f;
821     uint32_t l;
822     uint8_t buf[1024];
823     target_phys_addr_t addr = GET_TPHYSADDR(valh, vall); 
824
825     f = fopen(filename, "wb");
826     if (!f) {
827         monitor_printf(mon, "could not open '%s'\n", filename);
828         return;
829     }
830     while (size != 0) {
831         l = sizeof(buf);
832         if (l > size)
833             l = size;
834         cpu_physical_memory_rw(addr, buf, l, 0);
835         fwrite(buf, 1, l, f);
836         fflush(f);
837         addr += l;
838         size -= l;
839     }
840     fclose(f);
841 }
842
843 static void do_sum(Monitor *mon, uint32_t start, uint32_t size)
844 {
845     uint32_t addr;
846     uint8_t buf[1];
847     uint16_t sum;
848
849     sum = 0;
850     for(addr = start; addr < (start + size); addr++) {
851         cpu_physical_memory_rw(addr, buf, 1, 0);
852         /* BSD sum algorithm ('sum' Unix command) */
853         sum = (sum >> 1) | (sum << 15);
854         sum += buf[0];
855     }
856     monitor_printf(mon, "%05d\n", sum);
857 }
858
859 typedef struct {
860     int keycode;
861     const char *name;
862 } KeyDef;
863
864 static const KeyDef key_defs[] = {
865     { 0x2a, "shift" },
866     { 0x36, "shift_r" },
867
868     { 0x38, "alt" },
869     { 0xb8, "alt_r" },
870     { 0x64, "altgr" },
871     { 0xe4, "altgr_r" },
872     { 0x1d, "ctrl" },
873     { 0x9d, "ctrl_r" },
874
875     { 0xdd, "menu" },
876
877     { 0x01, "esc" },
878
879     { 0x02, "1" },
880     { 0x03, "2" },
881     { 0x04, "3" },
882     { 0x05, "4" },
883     { 0x06, "5" },
884     { 0x07, "6" },
885     { 0x08, "7" },
886     { 0x09, "8" },
887     { 0x0a, "9" },
888     { 0x0b, "0" },
889     { 0x0c, "minus" },
890     { 0x0d, "equal" },
891     { 0x0e, "backspace" },
892
893     { 0x0f, "tab" },
894     { 0x10, "q" },
895     { 0x11, "w" },
896     { 0x12, "e" },
897     { 0x13, "r" },
898     { 0x14, "t" },
899     { 0x15, "y" },
900     { 0x16, "u" },
901     { 0x17, "i" },
902     { 0x18, "o" },
903     { 0x19, "p" },
904
905     { 0x1c, "ret" },
906
907     { 0x1e, "a" },
908     { 0x1f, "s" },
909     { 0x20, "d" },
910     { 0x21, "f" },
911     { 0x22, "g" },
912     { 0x23, "h" },
913     { 0x24, "j" },
914     { 0x25, "k" },
915     { 0x26, "l" },
916
917     { 0x2c, "z" },
918     { 0x2d, "x" },
919     { 0x2e, "c" },
920     { 0x2f, "v" },
921     { 0x30, "b" },
922     { 0x31, "n" },
923     { 0x32, "m" },
924     { 0x33, "comma" },
925     { 0x34, "dot" },
926     { 0x35, "slash" },
927
928     { 0x37, "asterisk" },
929
930     { 0x39, "spc" },
931     { 0x3a, "caps_lock" },
932     { 0x3b, "f1" },
933     { 0x3c, "f2" },
934     { 0x3d, "f3" },
935     { 0x3e, "f4" },
936     { 0x3f, "f5" },
937     { 0x40, "f6" },
938     { 0x41, "f7" },
939     { 0x42, "f8" },
940     { 0x43, "f9" },
941     { 0x44, "f10" },
942     { 0x45, "num_lock" },
943     { 0x46, "scroll_lock" },
944
945     { 0xb5, "kp_divide" },
946     { 0x37, "kp_multiply" },
947     { 0x4a, "kp_subtract" },
948     { 0x4e, "kp_add" },
949     { 0x9c, "kp_enter" },
950     { 0x53, "kp_decimal" },
951     { 0x54, "sysrq" },
952
953     { 0x52, "kp_0" },
954     { 0x4f, "kp_1" },
955     { 0x50, "kp_2" },
956     { 0x51, "kp_3" },
957     { 0x4b, "kp_4" },
958     { 0x4c, "kp_5" },
959     { 0x4d, "kp_6" },
960     { 0x47, "kp_7" },
961     { 0x48, "kp_8" },
962     { 0x49, "kp_9" },
963
964     { 0x56, "<" },
965
966     { 0x57, "f11" },
967     { 0x58, "f12" },
968
969     { 0xb7, "print" },
970
971     { 0xc7, "home" },
972     { 0xc9, "pgup" },
973     { 0xd1, "pgdn" },
974     { 0xcf, "end" },
975
976     { 0xcb, "left" },
977     { 0xc8, "up" },
978     { 0xd0, "down" },
979     { 0xcd, "right" },
980
981     { 0xd2, "insert" },
982     { 0xd3, "delete" },
983 #if defined(TARGET_SPARC) && !defined(TARGET_SPARC64)
984     { 0xf0, "stop" },
985     { 0xf1, "again" },
986     { 0xf2, "props" },
987     { 0xf3, "undo" },
988     { 0xf4, "front" },
989     { 0xf5, "copy" },
990     { 0xf6, "open" },
991     { 0xf7, "paste" },
992     { 0xf8, "find" },
993     { 0xf9, "cut" },
994     { 0xfa, "lf" },
995     { 0xfb, "help" },
996     { 0xfc, "meta_l" },
997     { 0xfd, "meta_r" },
998     { 0xfe, "compose" },
999 #endif
1000     { 0, NULL },
1001 };
1002
1003 static int get_keycode(const char *key)
1004 {
1005     const KeyDef *p;
1006     char *endp;
1007     int ret;
1008
1009     for(p = key_defs; p->name != NULL; p++) {
1010         if (!strcmp(key, p->name))
1011             return p->keycode;
1012     }
1013     if (strstart(key, "0x", NULL)) {
1014         ret = strtoul(key, &endp, 0);
1015         if (*endp == '\0' && ret >= 0x01 && ret <= 0xff)
1016             return ret;
1017     }
1018     return -1;
1019 }
1020
1021 #define MAX_KEYCODES 16
1022 static uint8_t keycodes[MAX_KEYCODES];
1023 static int nb_pending_keycodes;
1024 static QEMUTimer *key_timer;
1025
1026 static void release_keys(void *opaque)
1027 {
1028     int keycode;
1029
1030     while (nb_pending_keycodes > 0) {
1031         nb_pending_keycodes--;
1032         keycode = keycodes[nb_pending_keycodes];
1033         if (keycode & 0x80)
1034             kbd_put_keycode(0xe0);
1035         kbd_put_keycode(keycode | 0x80);
1036     }
1037 }
1038
1039 static void do_sendkey(Monitor *mon, const char *string, int has_hold_time,
1040                        int hold_time)
1041 {
1042     char keyname_buf[16];
1043     char *separator;
1044     int keyname_len, keycode, i;
1045
1046     if (nb_pending_keycodes > 0) {
1047         qemu_del_timer(key_timer);
1048         release_keys(NULL);
1049     }
1050     if (!has_hold_time)
1051         hold_time = 100;
1052     i = 0;
1053     while (1) {
1054         separator = strchr(string, '-');
1055         keyname_len = separator ? separator - string : strlen(string);
1056         if (keyname_len > 0) {
1057             pstrcpy(keyname_buf, sizeof(keyname_buf), string);
1058             if (keyname_len > sizeof(keyname_buf) - 1) {
1059                 monitor_printf(mon, "invalid key: '%s...'\n", keyname_buf);
1060                 return;
1061             }
1062             if (i == MAX_KEYCODES) {
1063                 monitor_printf(mon, "too many keys\n");
1064                 return;
1065             }
1066             keyname_buf[keyname_len] = 0;
1067             keycode = get_keycode(keyname_buf);
1068             if (keycode < 0) {
1069                 monitor_printf(mon, "unknown key: '%s'\n", keyname_buf);
1070                 return;
1071             }
1072             keycodes[i++] = keycode;
1073         }
1074         if (!separator)
1075             break;
1076         string = separator + 1;
1077     }
1078     nb_pending_keycodes = i;
1079     /* key down events */
1080     for (i = 0; i < nb_pending_keycodes; i++) {
1081         keycode = keycodes[i];
1082         if (keycode & 0x80)
1083             kbd_put_keycode(0xe0);
1084         kbd_put_keycode(keycode & 0x7f);
1085     }
1086     /* delayed key up events */
1087     qemu_mod_timer(key_timer, qemu_get_clock(vm_clock) +
1088                     muldiv64(ticks_per_sec, hold_time, 1000));
1089 }
1090
1091 static int mouse_button_state;
1092
1093 static void do_mouse_move(Monitor *mon, const char *dx_str, const char *dy_str,
1094                           const char *dz_str)
1095 {
1096     int dx, dy, dz;
1097     dx = strtol(dx_str, NULL, 0);
1098     dy = strtol(dy_str, NULL, 0);
1099     dz = 0;
1100     if (dz_str)
1101         dz = strtol(dz_str, NULL, 0);
1102     kbd_mouse_event(dx, dy, dz, mouse_button_state);
1103 }
1104
1105 static void do_mouse_button(Monitor *mon, int button_state)
1106 {
1107     mouse_button_state = button_state;
1108     kbd_mouse_event(0, 0, 0, mouse_button_state);
1109 }
1110
1111 static void do_ioport_read(Monitor *mon, int count, int format, int size,
1112                            int addr, int has_index, int index)
1113 {
1114     uint32_t val;
1115     int suffix;
1116
1117     if (has_index) {
1118         cpu_outb(NULL, addr & 0xffff, index & 0xff);
1119         addr++;
1120     }
1121     addr &= 0xffff;
1122
1123     switch(size) {
1124     default:
1125     case 1:
1126         val = cpu_inb(NULL, addr);
1127         suffix = 'b';
1128         break;
1129     case 2:
1130         val = cpu_inw(NULL, addr);
1131         suffix = 'w';
1132         break;
1133     case 4:
1134         val = cpu_inl(NULL, addr);
1135         suffix = 'l';
1136         break;
1137     }
1138     monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1139                    suffix, addr, size * 2, val);
1140 }
1141
1142 /* boot_set handler */
1143 static QEMUBootSetHandler *qemu_boot_set_handler = NULL;
1144 static void *boot_opaque;
1145
1146 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1147 {
1148     qemu_boot_set_handler = func;
1149     boot_opaque = opaque;
1150 }
1151
1152 static void do_boot_set(Monitor *mon, const char *bootdevice)
1153 {
1154     int res;
1155
1156     if (qemu_boot_set_handler)  {
1157         res = qemu_boot_set_handler(boot_opaque, bootdevice);
1158         if (res == 0)
1159             monitor_printf(mon, "boot device list now set to %s\n",
1160                            bootdevice);
1161         else
1162             monitor_printf(mon, "setting boot device list failed with "
1163                            "error %i\n", res);
1164     } else {
1165         monitor_printf(mon, "no function defined to set boot device list for "
1166                        "this architecture\n");
1167     }
1168 }
1169
1170 static void do_system_reset(Monitor *mon)
1171 {
1172     qemu_system_reset_request();
1173 }
1174
1175 static void do_system_powerdown(Monitor *mon)
1176 {
1177     qemu_system_powerdown_request();
1178 }
1179
1180 #if defined(TARGET_I386)
1181 static void print_pte(Monitor *mon, uint32_t addr, uint32_t pte, uint32_t mask)
1182 {
1183     monitor_printf(mon, "%08x: %08x %c%c%c%c%c%c%c%c\n",
1184                    addr,
1185                    pte & mask,
1186                    pte & PG_GLOBAL_MASK ? 'G' : '-',
1187                    pte & PG_PSE_MASK ? 'P' : '-',
1188                    pte & PG_DIRTY_MASK ? 'D' : '-',
1189                    pte & PG_ACCESSED_MASK ? 'A' : '-',
1190                    pte & PG_PCD_MASK ? 'C' : '-',
1191                    pte & PG_PWT_MASK ? 'T' : '-',
1192                    pte & PG_USER_MASK ? 'U' : '-',
1193                    pte & PG_RW_MASK ? 'W' : '-');
1194 }
1195
1196 static void tlb_info(Monitor *mon)
1197 {
1198     CPUState *env;
1199     int l1, l2;
1200     uint32_t pgd, pde, pte;
1201
1202     env = mon_get_cpu();
1203     if (!env)
1204         return;
1205
1206     if (!(env->cr[0] & CR0_PG_MASK)) {
1207         monitor_printf(mon, "PG disabled\n");
1208         return;
1209     }
1210     pgd = env->cr[3] & ~0xfff;
1211     for(l1 = 0; l1 < 1024; l1++) {
1212         cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1213         pde = le32_to_cpu(pde);
1214         if (pde & PG_PRESENT_MASK) {
1215             if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1216                 print_pte(mon, (l1 << 22), pde, ~((1 << 20) - 1));
1217             } else {
1218                 for(l2 = 0; l2 < 1024; l2++) {
1219                     cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1220                                              (uint8_t *)&pte, 4);
1221                     pte = le32_to_cpu(pte);
1222                     if (pte & PG_PRESENT_MASK) {
1223                         print_pte(mon, (l1 << 22) + (l2 << 12),
1224                                   pte & ~PG_PSE_MASK,
1225                                   ~0xfff);
1226                     }
1227                 }
1228             }
1229         }
1230     }
1231 }
1232
1233 static void mem_print(Monitor *mon, uint32_t *pstart, int *plast_prot,
1234                       uint32_t end, int prot)
1235 {
1236     int prot1;
1237     prot1 = *plast_prot;
1238     if (prot != prot1) {
1239         if (*pstart != -1) {
1240             monitor_printf(mon, "%08x-%08x %08x %c%c%c\n",
1241                            *pstart, end, end - *pstart,
1242                            prot1 & PG_USER_MASK ? 'u' : '-',
1243                            'r',
1244                            prot1 & PG_RW_MASK ? 'w' : '-');
1245         }
1246         if (prot != 0)
1247             *pstart = end;
1248         else
1249             *pstart = -1;
1250         *plast_prot = prot;
1251     }
1252 }
1253
1254 static void mem_info(Monitor *mon)
1255 {
1256     CPUState *env;
1257     int l1, l2, prot, last_prot;
1258     uint32_t pgd, pde, pte, start, end;
1259
1260     env = mon_get_cpu();
1261     if (!env)
1262         return;
1263
1264     if (!(env->cr[0] & CR0_PG_MASK)) {
1265         monitor_printf(mon, "PG disabled\n");
1266         return;
1267     }
1268     pgd = env->cr[3] & ~0xfff;
1269     last_prot = 0;
1270     start = -1;
1271     for(l1 = 0; l1 < 1024; l1++) {
1272         cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1273         pde = le32_to_cpu(pde);
1274         end = l1 << 22;
1275         if (pde & PG_PRESENT_MASK) {
1276             if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1277                 prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1278                 mem_print(mon, &start, &last_prot, end, prot);
1279             } else {
1280                 for(l2 = 0; l2 < 1024; l2++) {
1281                     cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1282                                              (uint8_t *)&pte, 4);
1283                     pte = le32_to_cpu(pte);
1284                     end = (l1 << 22) + (l2 << 12);
1285                     if (pte & PG_PRESENT_MASK) {
1286                         prot = pte & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1287                     } else {
1288                         prot = 0;
1289                     }
1290                     mem_print(mon, &start, &last_prot, end, prot);
1291                 }
1292             }
1293         } else {
1294             prot = 0;
1295             mem_print(mon, &start, &last_prot, end, prot);
1296         }
1297     }
1298 }
1299 #endif
1300
1301 #if defined(TARGET_SH4)
1302
1303 static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1304 {
1305     monitor_printf(mon, " tlb%i:\t"
1306                    "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1307                    "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1308                    "dirty=%hhu writethrough=%hhu\n",
1309                    idx,
1310                    tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1311                    tlb->v, tlb->sh, tlb->c, tlb->pr,
1312                    tlb->d, tlb->wt);
1313 }
1314
1315 static void tlb_info(Monitor *mon)
1316 {
1317     CPUState *env = mon_get_cpu();
1318     int i;
1319
1320     monitor_printf (mon, "ITLB:\n");
1321     for (i = 0 ; i < ITLB_SIZE ; i++)
1322         print_tlb (mon, i, &env->itlb[i]);
1323     monitor_printf (mon, "UTLB:\n");
1324     for (i = 0 ; i < UTLB_SIZE ; i++)
1325         print_tlb (mon, i, &env->utlb[i]);
1326 }
1327
1328 #endif
1329
1330 static void do_info_kqemu(Monitor *mon)
1331 {
1332 #ifdef USE_KQEMU
1333     CPUState *env;
1334     int val;
1335     val = 0;
1336     env = mon_get_cpu();
1337     if (!env) {
1338         monitor_printf(mon, "No cpu initialized yet");
1339         return;
1340     }
1341     val = env->kqemu_enabled;
1342     monitor_printf(mon, "kqemu support: ");
1343     switch(val) {
1344     default:
1345     case 0:
1346         monitor_printf(mon, "disabled\n");
1347         break;
1348     case 1:
1349         monitor_printf(mon, "enabled for user code\n");
1350         break;
1351     case 2:
1352         monitor_printf(mon, "enabled for user and kernel code\n");
1353         break;
1354     }
1355 #else
1356     monitor_printf(mon, "kqemu support: not compiled\n");
1357 #endif
1358 }
1359
1360 static void do_info_kvm(Monitor *mon)
1361 {
1362 #ifdef CONFIG_KVM
1363     monitor_printf(mon, "kvm support: ");
1364     if (kvm_enabled())
1365         monitor_printf(mon, "enabled\n");
1366     else
1367         monitor_printf(mon, "disabled\n");
1368 #else
1369     monitor_printf(mon, "kvm support: not compiled\n");
1370 #endif
1371 }
1372
1373 #ifdef CONFIG_PROFILER
1374
1375 int64_t kqemu_time;
1376 int64_t qemu_time;
1377 int64_t kqemu_exec_count;
1378 int64_t dev_time;
1379 int64_t kqemu_ret_int_count;
1380 int64_t kqemu_ret_excp_count;
1381 int64_t kqemu_ret_intr_count;
1382
1383 static void do_info_profile(Monitor *mon)
1384 {
1385     int64_t total;
1386     total = qemu_time;
1387     if (total == 0)
1388         total = 1;
1389     monitor_printf(mon, "async time  %" PRId64 " (%0.3f)\n",
1390                    dev_time, dev_time / (double)ticks_per_sec);
1391     monitor_printf(mon, "qemu time   %" PRId64 " (%0.3f)\n",
1392                    qemu_time, qemu_time / (double)ticks_per_sec);
1393     monitor_printf(mon, "kqemu time  %" PRId64 " (%0.3f %0.1f%%) count=%"
1394                         PRId64 " int=%" PRId64 " excp=%" PRId64 " intr=%"
1395                         PRId64 "\n",
1396                    kqemu_time, kqemu_time / (double)ticks_per_sec,
1397                    kqemu_time / (double)total * 100.0,
1398                    kqemu_exec_count,
1399                    kqemu_ret_int_count,
1400                    kqemu_ret_excp_count,
1401                    kqemu_ret_intr_count);
1402     qemu_time = 0;
1403     kqemu_time = 0;
1404     kqemu_exec_count = 0;
1405     dev_time = 0;
1406     kqemu_ret_int_count = 0;
1407     kqemu_ret_excp_count = 0;
1408     kqemu_ret_intr_count = 0;
1409 #ifdef USE_KQEMU
1410     kqemu_record_dump();
1411 #endif
1412 }
1413 #else
1414 static void do_info_profile(Monitor *mon)
1415 {
1416     monitor_printf(mon, "Internal profiler not compiled\n");
1417 }
1418 #endif
1419
1420 /* Capture support */
1421 static LIST_HEAD (capture_list_head, CaptureState) capture_head;
1422
1423 static void do_info_capture(Monitor *mon)
1424 {
1425     int i;
1426     CaptureState *s;
1427
1428     for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1429         monitor_printf(mon, "[%d]: ", i);
1430         s->ops.info (s->opaque);
1431     }
1432 }
1433
1434 static void do_stop_capture(Monitor *mon, int n)
1435 {
1436     int i;
1437     CaptureState *s;
1438
1439     for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1440         if (i == n) {
1441             s->ops.destroy (s->opaque);
1442             LIST_REMOVE (s, entries);
1443             qemu_free (s);
1444             return;
1445         }
1446     }
1447 }
1448
1449 #ifdef HAS_AUDIO
1450 static void do_wav_capture(Monitor *mon, const char *path,
1451                            int has_freq, int freq,
1452                            int has_bits, int bits,
1453                            int has_channels, int nchannels)
1454 {
1455     CaptureState *s;
1456
1457     s = qemu_mallocz (sizeof (*s));
1458
1459     freq = has_freq ? freq : 44100;
1460     bits = has_bits ? bits : 16;
1461     nchannels = has_channels ? nchannels : 2;
1462
1463     if (wav_start_capture (s, path, freq, bits, nchannels)) {
1464         monitor_printf(mon, "Faied to add wave capture\n");
1465         qemu_free (s);
1466     }
1467     LIST_INSERT_HEAD (&capture_head, s, entries);
1468 }
1469 #endif
1470
1471 #if defined(TARGET_I386)
1472 static void do_inject_nmi(Monitor *mon, int cpu_index)
1473 {
1474     CPUState *env;
1475
1476     for (env = first_cpu; env != NULL; env = env->next_cpu)
1477         if (env->cpu_index == cpu_index) {
1478             cpu_interrupt(env, CPU_INTERRUPT_NMI);
1479             break;
1480         }
1481 }
1482 #endif
1483
1484 static void do_info_status(Monitor *mon)
1485 {
1486     if (vm_running)
1487        monitor_printf(mon, "VM status: running\n");
1488     else
1489        monitor_printf(mon, "VM status: paused\n");
1490 }
1491
1492
1493 static void do_balloon(Monitor *mon, int value)
1494 {
1495     ram_addr_t target = value;
1496     qemu_balloon(target << 20);
1497 }
1498
1499 static void do_info_balloon(Monitor *mon)
1500 {
1501     ram_addr_t actual;
1502
1503     actual = qemu_balloon_status();
1504     if (kvm_enabled() && !kvm_has_sync_mmu())
1505         monitor_printf(mon, "Using KVM without synchronous MMU, "
1506                        "ballooning disabled\n");
1507     else if (actual == 0)
1508         monitor_printf(mon, "Ballooning not activated in VM\n");
1509     else
1510         monitor_printf(mon, "balloon: actual=%d\n", (int)(actual >> 20));
1511 }
1512
1513 /* Please update qemu-doc.texi when adding or changing commands */
1514 static const mon_cmd_t mon_cmds[] = {
1515     { "help|?", "s?", help_cmd,
1516       "[cmd]", "show the help" },
1517     { "commit", "s", do_commit,
1518       "device|all", "commit changes to the disk images (if -snapshot is used) or backing files" },
1519     { "info", "s?", do_info,
1520       "subcommand", "show various information about the system state" },
1521     { "q|quit", "", do_quit,
1522       "", "quit the emulator" },
1523     { "eject", "-fB", do_eject,
1524       "[-f] device", "eject a removable medium (use -f to force it)" },
1525     { "change", "BFs?", do_change,
1526       "device filename [format]", "change a removable medium, optional format" },
1527     { "screendump", "F", do_screen_dump,
1528       "filename", "save screen into PPM image 'filename'" },
1529     { "logfile", "F", do_logfile,
1530       "filename", "output logs to 'filename'" },
1531     { "log", "s", do_log,
1532       "item1[,...]", "activate logging of the specified items to '/tmp/qemu.log'" },
1533     { "savevm", "s?", do_savevm,
1534       "tag|id", "save a VM snapshot. If no tag or id are provided, a new snapshot is created" },
1535     { "loadvm", "s", do_loadvm,
1536       "tag|id", "restore a VM snapshot from its tag or id" },
1537     { "delvm", "s", do_delvm,
1538       "tag|id", "delete a VM snapshot from its tag or id" },
1539     { "stop", "", do_stop,
1540       "", "stop emulation", },
1541     { "c|cont", "", do_cont,
1542       "", "resume emulation", },
1543 #ifdef CONFIG_GDBSTUB
1544     { "gdbserver", "s?", do_gdbserver,
1545       "[port]", "start gdbserver session (default port=1234)", },
1546 #endif
1547     { "x", "/l", do_memory_dump,
1548       "/fmt addr", "virtual memory dump starting at 'addr'", },
1549     { "xp", "/l", do_physical_memory_dump,
1550       "/fmt addr", "physical memory dump starting at 'addr'", },
1551     { "p|print", "/l", do_print,
1552       "/fmt expr", "print expression value (use $reg for CPU register access)", },
1553     { "i", "/ii.", do_ioport_read,
1554       "/fmt addr", "I/O port read" },
1555
1556     { "sendkey", "si?", do_sendkey,
1557       "keys [hold_ms]", "send keys to the VM (e.g. 'sendkey ctrl-alt-f1', default hold time=100 ms)" },
1558     { "system_reset", "", do_system_reset,
1559       "", "reset the system" },
1560     { "system_powerdown", "", do_system_powerdown,
1561       "", "send system power down event" },
1562     { "sum", "ii", do_sum,
1563       "addr size", "compute the checksum of a memory region" },
1564     { "usb_add", "s", do_usb_add,
1565       "device", "add USB device (e.g. 'host:bus.addr' or 'host:vendor_id:product_id')" },
1566     { "usb_del", "s", do_usb_del,
1567       "device", "remove USB device 'bus.addr'" },
1568     { "cpu", "i", do_cpu_set,
1569       "index", "set the default CPU" },
1570     { "mouse_move", "sss?", do_mouse_move,
1571       "dx dy [dz]", "send mouse move events" },
1572     { "mouse_button", "i", do_mouse_button,
1573       "state", "change mouse button state (1=L, 2=M, 4=R)" },
1574     { "mouse_set", "i", do_mouse_set,
1575       "index", "set which mouse device receives events" },
1576 #ifdef HAS_AUDIO
1577     { "wavcapture", "si?i?i?", do_wav_capture,
1578       "path [frequency bits channels]",
1579       "capture audio to a wave file (default frequency=44100 bits=16 channels=2)" },
1580 #endif
1581     { "stopcapture", "i", do_stop_capture,
1582       "capture index", "stop capture" },
1583     { "memsave", "lis", do_memory_save,
1584       "addr size file", "save to disk virtual memory dump starting at 'addr' of size 'size'", },
1585     { "pmemsave", "lis", do_physical_memory_save,
1586       "addr size file", "save to disk physical memory dump starting at 'addr' of size 'size'", },
1587     { "boot_set", "s", do_boot_set,
1588       "bootdevice", "define new values for the boot device list" },
1589 #if defined(TARGET_I386)
1590     { "nmi", "i", do_inject_nmi,
1591       "cpu", "inject an NMI on the given CPU", },
1592 #endif
1593     { "migrate", "-ds", do_migrate,
1594       "[-d] uri", "migrate to URI (using -d to not wait for completion)" },
1595     { "migrate_cancel", "", do_migrate_cancel,
1596       "", "cancel the current VM migration" },
1597     { "migrate_set_speed", "s", do_migrate_set_speed,
1598       "value", "set maximum speed (in bytes) for migrations" },
1599 #if defined(TARGET_I386)
1600     { "drive_add", "ss", drive_hot_add, "pci_addr=[[<domain>:]<bus>:]<slot>\n"
1601                                          "[file=file][,if=type][,bus=n]\n"
1602                                         "[,unit=m][,media=d][index=i]\n"
1603                                         "[,cyls=c,heads=h,secs=s[,trans=t]]\n"
1604                                         "[snapshot=on|off][,cache=on|off]",
1605                                         "add drive to PCI storage controller" },
1606     { "pci_add", "sss", pci_device_hot_add, "pci_addr=auto|[[<domain>:]<bus>:]<slot> nic|storage [[vlan=n][,macaddr=addr][,model=type]] [file=file][,if=type][,bus=nr]...", "hot-add PCI device" },
1607     { "pci_del", "s", pci_device_hot_remove, "pci_addr=[[<domain>:]<bus>:]<slot>", "hot remove PCI device" },
1608     { "host_net_add", "ss", net_host_device_add,
1609       "[tap,user,socket,vde] options", "add host VLAN client" },
1610     { "host_net_remove", "is", net_host_device_remove,
1611       "vlan_id name", "remove host VLAN client" },
1612 #endif
1613     { "balloon", "i", do_balloon,
1614       "target", "request VM to change it's memory allocation (in MB)" },
1615     { "set_link", "ss", do_set_link,
1616       "name [up|down]", "change the link status of a network adapter" },
1617     { NULL, NULL, },
1618 };
1619
1620 /* Please update qemu-doc.texi when adding or changing commands */
1621 static const mon_cmd_t info_cmds[] = {
1622     { "version", "", do_info_version,
1623       "", "show the version of QEMU" },
1624     { "network", "", do_info_network,
1625       "", "show the network state" },
1626     { "chardev", "", qemu_chr_info,
1627       "", "show the character devices" },
1628     { "block", "", bdrv_info,
1629       "", "show the block devices" },
1630     { "blockstats", "", bdrv_info_stats,
1631       "", "show block device statistics" },
1632     { "registers", "", do_info_registers,
1633       "", "show the cpu registers" },
1634     { "cpus", "", do_info_cpus,
1635       "", "show infos for each CPU" },
1636     { "history", "", do_info_history,
1637       "", "show the command line history", },
1638     { "irq", "", irq_info,
1639       "", "show the interrupts statistics (if available)", },
1640     { "pic", "", pic_info,
1641       "", "show i8259 (PIC) state", },
1642     { "pci", "", pci_info,
1643       "", "show PCI info", },
1644 #if defined(TARGET_I386) || defined(TARGET_SH4)
1645     { "tlb", "", tlb_info,
1646       "", "show virtual to physical memory mappings", },
1647 #endif
1648 #if defined(TARGET_I386)
1649     { "mem", "", mem_info,
1650       "", "show the active virtual memory mappings", },
1651     { "hpet", "", do_info_hpet,
1652       "", "show state of HPET", },
1653 #endif
1654     { "jit", "", do_info_jit,
1655       "", "show dynamic compiler info", },
1656     { "kqemu", "", do_info_kqemu,
1657       "", "show KQEMU information", },
1658     { "kvm", "", do_info_kvm,
1659       "", "show KVM information", },
1660     { "usb", "", usb_info,
1661       "", "show guest USB devices", },
1662     { "usbhost", "", usb_host_info,
1663       "", "show host USB devices", },
1664     { "profile", "", do_info_profile,
1665       "", "show profiling information", },
1666     { "capture", "", do_info_capture,
1667       "", "show capture information" },
1668     { "snapshots", "", do_info_snapshots,
1669       "", "show the currently saved VM snapshots" },
1670     { "status", "", do_info_status,
1671       "", "show the current VM status (running|paused)" },
1672     { "pcmcia", "", pcmcia_info,
1673       "", "show guest PCMCIA status" },
1674     { "mice", "", do_info_mice,
1675       "", "show which guest mouse is receiving events" },
1676     { "vnc", "", do_info_vnc,
1677       "", "show the vnc server status"},
1678     { "name", "", do_info_name,
1679       "", "show the current VM name" },
1680     { "uuid", "", do_info_uuid,
1681       "", "show the current VM UUID" },
1682 #if defined(TARGET_PPC)
1683     { "cpustats", "", do_info_cpu_stats,
1684       "", "show CPU statistics", },
1685 #endif
1686 #if defined(CONFIG_SLIRP)
1687     { "slirp", "", do_info_slirp,
1688       "", "show SLIRP statistics", },
1689 #endif
1690     { "migrate", "", do_info_migrate, "", "show migration status" },
1691     { "balloon", "", do_info_balloon,
1692       "", "show balloon information" },
1693     { NULL, NULL, },
1694 };
1695
1696 /*******************************************************************/
1697
1698 static const char *pch;
1699 static jmp_buf expr_env;
1700
1701 #define MD_TLONG 0
1702 #define MD_I32   1
1703
1704 typedef struct MonitorDef {
1705     const char *name;
1706     int offset;
1707     target_long (*get_value)(const struct MonitorDef *md, int val);
1708     int type;
1709 } MonitorDef;
1710
1711 #if defined(TARGET_I386)
1712 static target_long monitor_get_pc (const struct MonitorDef *md, int val)
1713 {
1714     CPUState *env = mon_get_cpu();
1715     if (!env)
1716         return 0;
1717     return env->eip + env->segs[R_CS].base;
1718 }
1719 #endif
1720
1721 #if defined(TARGET_PPC)
1722 static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
1723 {
1724     CPUState *env = mon_get_cpu();
1725     unsigned int u;
1726     int i;
1727
1728     if (!env)
1729         return 0;
1730
1731     u = 0;
1732     for (i = 0; i < 8; i++)
1733         u |= env->crf[i] << (32 - (4 * i));
1734
1735     return u;
1736 }
1737
1738 static target_long monitor_get_msr (const struct MonitorDef *md, int val)
1739 {
1740     CPUState *env = mon_get_cpu();
1741     if (!env)
1742         return 0;
1743     return env->msr;
1744 }
1745
1746 static target_long monitor_get_xer (const struct MonitorDef *md, int val)
1747 {
1748     CPUState *env = mon_get_cpu();
1749     if (!env)
1750         return 0;
1751     return env->xer;
1752 }
1753
1754 static target_long monitor_get_decr (const struct MonitorDef *md, int val)
1755 {
1756     CPUState *env = mon_get_cpu();
1757     if (!env)
1758         return 0;
1759     return cpu_ppc_load_decr(env);
1760 }
1761
1762 static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
1763 {
1764     CPUState *env = mon_get_cpu();
1765     if (!env)
1766         return 0;
1767     return cpu_ppc_load_tbu(env);
1768 }
1769
1770 static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
1771 {
1772     CPUState *env = mon_get_cpu();
1773     if (!env)
1774         return 0;
1775     return cpu_ppc_load_tbl(env);
1776 }
1777 #endif
1778
1779 #if defined(TARGET_SPARC)
1780 #ifndef TARGET_SPARC64
1781 static target_long monitor_get_psr (const struct MonitorDef *md, int val)
1782 {
1783     CPUState *env = mon_get_cpu();
1784     if (!env)
1785         return 0;
1786     return GET_PSR(env);
1787 }
1788 #endif
1789
1790 static target_long monitor_get_reg(const struct MonitorDef *md, int val)
1791 {
1792     CPUState *env = mon_get_cpu();
1793     if (!env)
1794         return 0;
1795     return env->regwptr[val];
1796 }
1797 #endif
1798
1799 static const MonitorDef monitor_defs[] = {
1800 #ifdef TARGET_I386
1801
1802 #define SEG(name, seg) \
1803     { name, offsetof(CPUState, segs[seg].selector), NULL, MD_I32 },\
1804     { name ".base", offsetof(CPUState, segs[seg].base) },\
1805     { name ".limit", offsetof(CPUState, segs[seg].limit), NULL, MD_I32 },
1806
1807     { "eax", offsetof(CPUState, regs[0]) },
1808     { "ecx", offsetof(CPUState, regs[1]) },
1809     { "edx", offsetof(CPUState, regs[2]) },
1810     { "ebx", offsetof(CPUState, regs[3]) },
1811     { "esp|sp", offsetof(CPUState, regs[4]) },
1812     { "ebp|fp", offsetof(CPUState, regs[5]) },
1813     { "esi", offsetof(CPUState, regs[6]) },
1814     { "edi", offsetof(CPUState, regs[7]) },
1815 #ifdef TARGET_X86_64
1816     { "r8", offsetof(CPUState, regs[8]) },
1817     { "r9", offsetof(CPUState, regs[9]) },
1818     { "r10", offsetof(CPUState, regs[10]) },
1819     { "r11", offsetof(CPUState, regs[11]) },
1820     { "r12", offsetof(CPUState, regs[12]) },
1821     { "r13", offsetof(CPUState, regs[13]) },
1822     { "r14", offsetof(CPUState, regs[14]) },
1823     { "r15", offsetof(CPUState, regs[15]) },
1824 #endif
1825     { "eflags", offsetof(CPUState, eflags) },
1826     { "eip", offsetof(CPUState, eip) },
1827     SEG("cs", R_CS)
1828     SEG("ds", R_DS)
1829     SEG("es", R_ES)
1830     SEG("ss", R_SS)
1831     SEG("fs", R_FS)
1832     SEG("gs", R_GS)
1833     { "pc", 0, monitor_get_pc, },
1834 #elif defined(TARGET_PPC)
1835     /* General purpose registers */
1836     { "r0", offsetof(CPUState, gpr[0]) },
1837     { "r1", offsetof(CPUState, gpr[1]) },
1838     { "r2", offsetof(CPUState, gpr[2]) },
1839     { "r3", offsetof(CPUState, gpr[3]) },
1840     { "r4", offsetof(CPUState, gpr[4]) },
1841     { "r5", offsetof(CPUState, gpr[5]) },
1842     { "r6", offsetof(CPUState, gpr[6]) },
1843     { "r7", offsetof(CPUState, gpr[7]) },
1844     { "r8", offsetof(CPUState, gpr[8]) },
1845     { "r9", offsetof(CPUState, gpr[9]) },
1846     { "r10", offsetof(CPUState, gpr[10]) },
1847     { "r11", offsetof(CPUState, gpr[11]) },
1848     { "r12", offsetof(CPUState, gpr[12]) },
1849     { "r13", offsetof(CPUState, gpr[13]) },
1850     { "r14", offsetof(CPUState, gpr[14]) },
1851     { "r15", offsetof(CPUState, gpr[15]) },
1852     { "r16", offsetof(CPUState, gpr[16]) },
1853     { "r17", offsetof(CPUState, gpr[17]) },
1854     { "r18", offsetof(CPUState, gpr[18]) },
1855     { "r19", offsetof(CPUState, gpr[19]) },
1856     { "r20", offsetof(CPUState, gpr[20]) },
1857     { "r21", offsetof(CPUState, gpr[21]) },
1858     { "r22", offsetof(CPUState, gpr[22]) },
1859     { "r23", offsetof(CPUState, gpr[23]) },
1860     { "r24", offsetof(CPUState, gpr[24]) },
1861     { "r25", offsetof(CPUState, gpr[25]) },
1862     { "r26", offsetof(CPUState, gpr[26]) },
1863     { "r27", offsetof(CPUState, gpr[27]) },
1864     { "r28", offsetof(CPUState, gpr[28]) },
1865     { "r29", offsetof(CPUState, gpr[29]) },
1866     { "r30", offsetof(CPUState, gpr[30]) },
1867     { "r31", offsetof(CPUState, gpr[31]) },
1868     /* Floating point registers */
1869     { "f0", offsetof(CPUState, fpr[0]) },
1870     { "f1", offsetof(CPUState, fpr[1]) },
1871     { "f2", offsetof(CPUState, fpr[2]) },
1872     { "f3", offsetof(CPUState, fpr[3]) },
1873     { "f4", offsetof(CPUState, fpr[4]) },
1874     { "f5", offsetof(CPUState, fpr[5]) },
1875     { "f6", offsetof(CPUState, fpr[6]) },
1876     { "f7", offsetof(CPUState, fpr[7]) },
1877     { "f8", offsetof(CPUState, fpr[8]) },
1878     { "f9", offsetof(CPUState, fpr[9]) },
1879     { "f10", offsetof(CPUState, fpr[10]) },
1880     { "f11", offsetof(CPUState, fpr[11]) },
1881     { "f12", offsetof(CPUState, fpr[12]) },
1882     { "f13", offsetof(CPUState, fpr[13]) },
1883     { "f14", offsetof(CPUState, fpr[14]) },
1884     { "f15", offsetof(CPUState, fpr[15]) },
1885     { "f16", offsetof(CPUState, fpr[16]) },
1886     { "f17", offsetof(CPUState, fpr[17]) },
1887     { "f18", offsetof(CPUState, fpr[18]) },
1888     { "f19", offsetof(CPUState, fpr[19]) },
1889     { "f20", offsetof(CPUState, fpr[20]) },
1890     { "f21", offsetof(CPUState, fpr[21]) },
1891     { "f22", offsetof(CPUState, fpr[22]) },
1892     { "f23", offsetof(CPUState, fpr[23]) },
1893     { "f24", offsetof(CPUState, fpr[24]) },
1894     { "f25", offsetof(CPUState, fpr[25]) },
1895     { "f26", offsetof(CPUState, fpr[26]) },
1896     { "f27", offsetof(CPUState, fpr[27]) },
1897     { "f28", offsetof(CPUState, fpr[28]) },
1898     { "f29", offsetof(CPUState, fpr[29]) },
1899     { "f30", offsetof(CPUState, fpr[30]) },
1900     { "f31", offsetof(CPUState, fpr[31]) },
1901     { "fpscr", offsetof(CPUState, fpscr) },
1902     /* Next instruction pointer */
1903     { "nip|pc", offsetof(CPUState, nip) },
1904     { "lr", offsetof(CPUState, lr) },
1905     { "ctr", offsetof(CPUState, ctr) },
1906     { "decr", 0, &monitor_get_decr, },
1907     { "ccr", 0, &monitor_get_ccr, },
1908     /* Machine state register */
1909     { "msr", 0, &monitor_get_msr, },
1910     { "xer", 0, &monitor_get_xer, },
1911     { "tbu", 0, &monitor_get_tbu, },
1912     { "tbl", 0, &monitor_get_tbl, },
1913 #if defined(TARGET_PPC64)
1914     /* Address space register */
1915     { "asr", offsetof(CPUState, asr) },
1916 #endif
1917     /* Segment registers */
1918     { "sdr1", offsetof(CPUState, sdr1) },
1919     { "sr0", offsetof(CPUState, sr[0]) },
1920     { "sr1", offsetof(CPUState, sr[1]) },
1921     { "sr2", offsetof(CPUState, sr[2]) },
1922     { "sr3", offsetof(CPUState, sr[3]) },
1923     { "sr4", offsetof(CPUState, sr[4]) },
1924     { "sr5", offsetof(CPUState, sr[5]) },
1925     { "sr6", offsetof(CPUState, sr[6]) },
1926     { "sr7", offsetof(CPUState, sr[7]) },
1927     { "sr8", offsetof(CPUState, sr[8]) },
1928     { "sr9", offsetof(CPUState, sr[9]) },
1929     { "sr10", offsetof(CPUState, sr[10]) },
1930     { "sr11", offsetof(CPUState, sr[11]) },
1931     { "sr12", offsetof(CPUState, sr[12]) },
1932     { "sr13", offsetof(CPUState, sr[13]) },
1933     { "sr14", offsetof(CPUState, sr[14]) },
1934     { "sr15", offsetof(CPUState, sr[15]) },
1935     /* Too lazy to put BATs and SPRs ... */
1936 #elif defined(TARGET_SPARC)
1937     { "g0", offsetof(CPUState, gregs[0]) },
1938     { "g1", offsetof(CPUState, gregs[1]) },
1939     { "g2", offsetof(CPUState, gregs[2]) },
1940     { "g3", offsetof(CPUState, gregs[3]) },
1941     { "g4", offsetof(CPUState, gregs[4]) },
1942     { "g5", offsetof(CPUState, gregs[5]) },
1943     { "g6", offsetof(CPUState, gregs[6]) },
1944     { "g7", offsetof(CPUState, gregs[7]) },
1945     { "o0", 0, monitor_get_reg },
1946     { "o1", 1, monitor_get_reg },
1947     { "o2", 2, monitor_get_reg },
1948     { "o3", 3, monitor_get_reg },
1949     { "o4", 4, monitor_get_reg },
1950     { "o5", 5, monitor_get_reg },
1951     { "o6", 6, monitor_get_reg },
1952     { "o7", 7, monitor_get_reg },
1953     { "l0", 8, monitor_get_reg },
1954     { "l1", 9, monitor_get_reg },
1955     { "l2", 10, monitor_get_reg },
1956     { "l3", 11, monitor_get_reg },
1957     { "l4", 12, monitor_get_reg },
1958     { "l5", 13, monitor_get_reg },
1959     { "l6", 14, monitor_get_reg },
1960     { "l7", 15, monitor_get_reg },
1961     { "i0", 16, monitor_get_reg },
1962     { "i1", 17, monitor_get_reg },
1963     { "i2", 18, monitor_get_reg },
1964     { "i3", 19, monitor_get_reg },
1965     { "i4", 20, monitor_get_reg },
1966     { "i5", 21, monitor_get_reg },
1967     { "i6", 22, monitor_get_reg },
1968     { "i7", 23, monitor_get_reg },
1969     { "pc", offsetof(CPUState, pc) },
1970     { "npc", offsetof(CPUState, npc) },
1971     { "y", offsetof(CPUState, y) },
1972 #ifndef TARGET_SPARC64
1973     { "psr", 0, &monitor_get_psr, },
1974     { "wim", offsetof(CPUState, wim) },
1975 #endif
1976     { "tbr", offsetof(CPUState, tbr) },
1977     { "fsr", offsetof(CPUState, fsr) },
1978     { "f0", offsetof(CPUState, fpr[0]) },
1979     { "f1", offsetof(CPUState, fpr[1]) },
1980     { "f2", offsetof(CPUState, fpr[2]) },
1981     { "f3", offsetof(CPUState, fpr[3]) },
1982     { "f4", offsetof(CPUState, fpr[4]) },
1983     { "f5", offsetof(CPUState, fpr[5]) },
1984     { "f6", offsetof(CPUState, fpr[6]) },
1985     { "f7", offsetof(CPUState, fpr[7]) },
1986     { "f8", offsetof(CPUState, fpr[8]) },
1987     { "f9", offsetof(CPUState, fpr[9]) },
1988     { "f10", offsetof(CPUState, fpr[10]) },
1989     { "f11", offsetof(CPUState, fpr[11]) },
1990     { "f12", offsetof(CPUState, fpr[12]) },
1991     { "f13", offsetof(CPUState, fpr[13]) },
1992     { "f14", offsetof(CPUState, fpr[14]) },
1993     { "f15", offsetof(CPUState, fpr[15]) },
1994     { "f16", offsetof(CPUState, fpr[16]) },
1995     { "f17", offsetof(CPUState, fpr[17]) },
1996     { "f18", offsetof(CPUState, fpr[18]) },
1997     { "f19", offsetof(CPUState, fpr[19]) },
1998     { "f20", offsetof(CPUState, fpr[20]) },
1999     { "f21", offsetof(CPUState, fpr[21]) },
2000     { "f22", offsetof(CPUState, fpr[22]) },
2001     { "f23", offsetof(CPUState, fpr[23]) },
2002     { "f24", offsetof(CPUState, fpr[24]) },
2003     { "f25", offsetof(CPUState, fpr[25]) },
2004     { "f26", offsetof(CPUState, fpr[26]) },
2005     { "f27", offsetof(CPUState, fpr[27]) },
2006     { "f28", offsetof(CPUState, fpr[28]) },
2007     { "f29", offsetof(CPUState, fpr[29]) },
2008     { "f30", offsetof(CPUState, fpr[30]) },
2009     { "f31", offsetof(CPUState, fpr[31]) },
2010 #ifdef TARGET_SPARC64
2011     { "f32", offsetof(CPUState, fpr[32]) },
2012     { "f34", offsetof(CPUState, fpr[34]) },
2013     { "f36", offsetof(CPUState, fpr[36]) },
2014     { "f38", offsetof(CPUState, fpr[38]) },
2015     { "f40", offsetof(CPUState, fpr[40]) },
2016     { "f42", offsetof(CPUState, fpr[42]) },
2017     { "f44", offsetof(CPUState, fpr[44]) },
2018     { "f46", offsetof(CPUState, fpr[46]) },
2019     { "f48", offsetof(CPUState, fpr[48]) },
2020     { "f50", offsetof(CPUState, fpr[50]) },
2021     { "f52", offsetof(CPUState, fpr[52]) },
2022     { "f54", offsetof(CPUState, fpr[54]) },
2023     { "f56", offsetof(CPUState, fpr[56]) },
2024     { "f58", offsetof(CPUState, fpr[58]) },
2025     { "f60", offsetof(CPUState, fpr[60]) },
2026     { "f62", offsetof(CPUState, fpr[62]) },
2027     { "asi", offsetof(CPUState, asi) },
2028     { "pstate", offsetof(CPUState, pstate) },
2029     { "cansave", offsetof(CPUState, cansave) },
2030     { "canrestore", offsetof(CPUState, canrestore) },
2031     { "otherwin", offsetof(CPUState, otherwin) },
2032     { "wstate", offsetof(CPUState, wstate) },
2033     { "cleanwin", offsetof(CPUState, cleanwin) },
2034     { "fprs", offsetof(CPUState, fprs) },
2035 #endif
2036 #endif
2037     { NULL },
2038 };
2039
2040 static void expr_error(Monitor *mon, const char *msg)
2041 {
2042     monitor_printf(mon, "%s\n", msg);
2043     longjmp(expr_env, 1);
2044 }
2045
2046 /* return 0 if OK, -1 if not found, -2 if no CPU defined */
2047 static int get_monitor_def(target_long *pval, const char *name)
2048 {
2049     const MonitorDef *md;
2050     void *ptr;
2051
2052     for(md = monitor_defs; md->name != NULL; md++) {
2053         if (compare_cmd(name, md->name)) {
2054             if (md->get_value) {
2055                 *pval = md->get_value(md, md->offset);
2056             } else {
2057                 CPUState *env = mon_get_cpu();
2058                 if (!env)
2059                     return -2;
2060                 ptr = (uint8_t *)env + md->offset;
2061                 switch(md->type) {
2062                 case MD_I32:
2063                     *pval = *(int32_t *)ptr;
2064                     break;
2065                 case MD_TLONG:
2066                     *pval = *(target_long *)ptr;
2067                     break;
2068                 default:
2069                     *pval = 0;
2070                     break;
2071                 }
2072             }
2073             return 0;
2074         }
2075     }
2076     return -1;
2077 }
2078
2079 static void next(void)
2080 {
2081     if (pch != '\0') {
2082         pch++;
2083         while (qemu_isspace(*pch))
2084             pch++;
2085     }
2086 }
2087
2088 static int64_t expr_sum(Monitor *mon);
2089
2090 static int64_t expr_unary(Monitor *mon)
2091 {
2092     int64_t n;
2093     char *p;
2094     int ret;
2095
2096     switch(*pch) {
2097     case '+':
2098         next();
2099         n = expr_unary(mon);
2100         break;
2101     case '-':
2102         next();
2103         n = -expr_unary(mon);
2104         break;
2105     case '~':
2106         next();
2107         n = ~expr_unary(mon);
2108         break;
2109     case '(':
2110         next();
2111         n = expr_sum(mon);
2112         if (*pch != ')') {
2113             expr_error(mon, "')' expected");
2114         }
2115         next();
2116         break;
2117     case '\'':
2118         pch++;
2119         if (*pch == '\0')
2120             expr_error(mon, "character constant expected");
2121         n = *pch;
2122         pch++;
2123         if (*pch != '\'')
2124             expr_error(mon, "missing terminating \' character");
2125         next();
2126         break;
2127     case '$':
2128         {
2129             char buf[128], *q;
2130             target_long reg=0;
2131
2132             pch++;
2133             q = buf;
2134             while ((*pch >= 'a' && *pch <= 'z') ||
2135                    (*pch >= 'A' && *pch <= 'Z') ||
2136                    (*pch >= '0' && *pch <= '9') ||
2137                    *pch == '_' || *pch == '.') {
2138                 if ((q - buf) < sizeof(buf) - 1)
2139                     *q++ = *pch;
2140                 pch++;
2141             }
2142             while (qemu_isspace(*pch))
2143                 pch++;
2144             *q = 0;
2145             ret = get_monitor_def(&reg, buf);
2146             if (ret == -1)
2147                 expr_error(mon, "unknown register");
2148             else if (ret == -2)
2149                 expr_error(mon, "no cpu defined");
2150             n = reg;
2151         }
2152         break;
2153     case '\0':
2154         expr_error(mon, "unexpected end of expression");
2155         n = 0;
2156         break;
2157     default:
2158 #if TARGET_PHYS_ADDR_BITS > 32
2159         n = strtoull(pch, &p, 0);
2160 #else
2161         n = strtoul(pch, &p, 0);
2162 #endif
2163         if (pch == p) {
2164             expr_error(mon, "invalid char in expression");
2165         }
2166         pch = p;
2167         while (qemu_isspace(*pch))
2168             pch++;
2169         break;
2170     }
2171     return n;
2172 }
2173
2174
2175 static int64_t expr_prod(Monitor *mon)
2176 {
2177     int64_t val, val2;
2178     int op;
2179
2180     val = expr_unary(mon);
2181     for(;;) {
2182         op = *pch;
2183         if (op != '*' && op != '/' && op != '%')
2184             break;
2185         next();
2186         val2 = expr_unary(mon);
2187         switch(op) {
2188         default:
2189         case '*':
2190             val *= val2;
2191             break;
2192         case '/':
2193         case '%':
2194             if (val2 == 0)
2195                 expr_error(mon, "division by zero");
2196             if (op == '/')
2197                 val /= val2;
2198             else
2199                 val %= val2;
2200             break;
2201         }
2202     }
2203     return val;
2204 }
2205
2206 static int64_t expr_logic(Monitor *mon)
2207 {
2208     int64_t val, val2;
2209     int op;
2210
2211     val = expr_prod(mon);
2212     for(;;) {
2213         op = *pch;
2214         if (op != '&' && op != '|' && op != '^')
2215             break;
2216         next();
2217         val2 = expr_prod(mon);
2218         switch(op) {
2219         default:
2220         case '&':
2221             val &= val2;
2222             break;
2223         case '|':
2224             val |= val2;
2225             break;
2226         case '^':
2227             val ^= val2;
2228             break;
2229         }
2230     }
2231     return val;
2232 }
2233
2234 static int64_t expr_sum(Monitor *mon)
2235 {
2236     int64_t val, val2;
2237     int op;
2238
2239     val = expr_logic(mon);
2240     for(;;) {
2241         op = *pch;
2242         if (op != '+' && op != '-')
2243             break;
2244         next();
2245         val2 = expr_logic(mon);
2246         if (op == '+')
2247             val += val2;
2248         else
2249             val -= val2;
2250     }
2251     return val;
2252 }
2253
2254 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2255 {
2256     pch = *pp;
2257     if (setjmp(expr_env)) {
2258         *pp = pch;
2259         return -1;
2260     }
2261     while (qemu_isspace(*pch))
2262         pch++;
2263     *pval = expr_sum(mon);
2264     *pp = pch;
2265     return 0;
2266 }
2267
2268 static int get_str(char *buf, int buf_size, const char **pp)
2269 {
2270     const char *p;
2271     char *q;
2272     int c;
2273
2274     q = buf;
2275     p = *pp;
2276     while (qemu_isspace(*p))
2277         p++;
2278     if (*p == '\0') {
2279     fail:
2280         *q = '\0';
2281         *pp = p;
2282         return -1;
2283     }
2284     if (*p == '\"') {
2285         p++;
2286         while (*p != '\0' && *p != '\"') {
2287             if (*p == '\\') {
2288                 p++;
2289                 c = *p++;
2290                 switch(c) {
2291                 case 'n':
2292                     c = '\n';
2293                     break;
2294                 case 'r':
2295                     c = '\r';
2296                     break;
2297                 case '\\':
2298                 case '\'':
2299                 case '\"':
2300                     break;
2301                 default:
2302                     qemu_printf("unsupported escape code: '\\%c'\n", c);
2303                     goto fail;
2304                 }
2305                 if ((q - buf) < buf_size - 1) {
2306                     *q++ = c;
2307                 }
2308             } else {
2309                 if ((q - buf) < buf_size - 1) {
2310                     *q++ = *p;
2311                 }
2312                 p++;
2313             }
2314         }
2315         if (*p != '\"') {
2316             qemu_printf("unterminated string\n");
2317             goto fail;
2318         }
2319         p++;
2320     } else {
2321         while (*p != '\0' && !qemu_isspace(*p)) {
2322             if ((q - buf) < buf_size - 1) {
2323                 *q++ = *p;
2324             }
2325             p++;
2326         }
2327     }
2328     *q = '\0';
2329     *pp = p;
2330     return 0;
2331 }
2332
2333 static int default_fmt_format = 'x';
2334 static int default_fmt_size = 4;
2335
2336 #define MAX_ARGS 16
2337
2338 static void monitor_handle_command(Monitor *mon, const char *cmdline)
2339 {
2340     const char *p, *pstart, *typestr;
2341     char *q;
2342     int c, nb_args, len, i, has_arg;
2343     const mon_cmd_t *cmd;
2344     char cmdname[256];
2345     char buf[1024];
2346     void *str_allocated[MAX_ARGS];
2347     void *args[MAX_ARGS];
2348     void (*handler_0)(Monitor *mon);
2349     void (*handler_1)(Monitor *mon, void *arg0);
2350     void (*handler_2)(Monitor *mon, void *arg0, void *arg1);
2351     void (*handler_3)(Monitor *mon, void *arg0, void *arg1, void *arg2);
2352     void (*handler_4)(Monitor *mon, void *arg0, void *arg1, void *arg2,
2353                       void *arg3);
2354     void (*handler_5)(Monitor *mon, void *arg0, void *arg1, void *arg2,
2355                       void *arg3, void *arg4);
2356     void (*handler_6)(Monitor *mon, void *arg0, void *arg1, void *arg2,
2357                       void *arg3, void *arg4, void *arg5);
2358     void (*handler_7)(Monitor *mon, void *arg0, void *arg1, void *arg2,
2359                       void *arg3, void *arg4, void *arg5, void *arg6);
2360
2361 #ifdef DEBUG
2362     monitor_printf(mon, "command='%s'\n", cmdline);
2363 #endif
2364
2365     /* extract the command name */
2366     p = cmdline;
2367     q = cmdname;
2368     while (qemu_isspace(*p))
2369         p++;
2370     if (*p == '\0')
2371         return;
2372     pstart = p;
2373     while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2374         p++;
2375     len = p - pstart;
2376     if (len > sizeof(cmdname) - 1)
2377         len = sizeof(cmdname) - 1;
2378     memcpy(cmdname, pstart, len);
2379     cmdname[len] = '\0';
2380
2381     /* find the command */
2382     for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
2383         if (compare_cmd(cmdname, cmd->name))
2384             goto found;
2385     }
2386     monitor_printf(mon, "unknown command: '%s'\n", cmdname);
2387     return;
2388  found:
2389
2390     for(i = 0; i < MAX_ARGS; i++)
2391         str_allocated[i] = NULL;
2392
2393     /* parse the parameters */
2394     typestr = cmd->args_type;
2395     nb_args = 0;
2396     for(;;) {
2397         c = *typestr;
2398         if (c == '\0')
2399             break;
2400         typestr++;
2401         switch(c) {
2402         case 'F':
2403         case 'B':
2404         case 's':
2405             {
2406                 int ret;
2407                 char *str;
2408
2409                 while (qemu_isspace(*p))
2410                     p++;
2411                 if (*typestr == '?') {
2412                     typestr++;
2413                     if (*p == '\0') {
2414                         /* no optional string: NULL argument */
2415                         str = NULL;
2416                         goto add_str;
2417                     }
2418                 }
2419                 ret = get_str(buf, sizeof(buf), &p);
2420                 if (ret < 0) {
2421                     switch(c) {
2422                     case 'F':
2423                         monitor_printf(mon, "%s: filename expected\n",
2424                                        cmdname);
2425                         break;
2426                     case 'B':
2427                         monitor_printf(mon, "%s: block device name expected\n",
2428                                        cmdname);
2429                         break;
2430                     default:
2431                         monitor_printf(mon, "%s: string expected\n", cmdname);
2432                         break;
2433                     }
2434                     goto fail;
2435                 }
2436                 str = qemu_malloc(strlen(buf) + 1);
2437                 pstrcpy(str, sizeof(buf), buf);
2438                 str_allocated[nb_args] = str;
2439             add_str:
2440                 if (nb_args >= MAX_ARGS) {
2441                 error_args:
2442                     monitor_printf(mon, "%s: too many arguments\n", cmdname);
2443                     goto fail;
2444                 }
2445                 args[nb_args++] = str;
2446             }
2447             break;
2448         case '/':
2449             {
2450                 int count, format, size;
2451
2452                 while (qemu_isspace(*p))
2453                     p++;
2454                 if (*p == '/') {
2455                     /* format found */
2456                     p++;
2457                     count = 1;
2458                     if (qemu_isdigit(*p)) {
2459                         count = 0;
2460                         while (qemu_isdigit(*p)) {
2461                             count = count * 10 + (*p - '0');
2462                             p++;
2463                         }
2464                     }
2465                     size = -1;
2466                     format = -1;
2467                     for(;;) {
2468                         switch(*p) {
2469                         case 'o':
2470                         case 'd':
2471                         case 'u':
2472                         case 'x':
2473                         case 'i':
2474                         case 'c':
2475                             format = *p++;
2476                             break;
2477                         case 'b':
2478                             size = 1;
2479                             p++;
2480                             break;
2481                         case 'h':
2482                             size = 2;
2483                             p++;
2484                             break;
2485                         case 'w':
2486                             size = 4;
2487                             p++;
2488                             break;
2489                         case 'g':
2490                         case 'L':
2491                             size = 8;
2492                             p++;
2493                             break;
2494                         default:
2495                             goto next;
2496                         }
2497                     }
2498                 next:
2499                     if (*p != '\0' && !qemu_isspace(*p)) {
2500                         monitor_printf(mon, "invalid char in format: '%c'\n",
2501                                        *p);
2502                         goto fail;
2503                     }
2504                     if (format < 0)
2505                         format = default_fmt_format;
2506                     if (format != 'i') {
2507                         /* for 'i', not specifying a size gives -1 as size */
2508                         if (size < 0)
2509                             size = default_fmt_size;
2510                         default_fmt_size = size;
2511                     }
2512                     default_fmt_format = format;
2513                 } else {
2514                     count = 1;
2515                     format = default_fmt_format;
2516                     if (format != 'i') {
2517                         size = default_fmt_size;
2518                     } else {
2519                         size = -1;
2520                     }
2521                 }
2522                 if (nb_args + 3 > MAX_ARGS)
2523                     goto error_args;
2524                 args[nb_args++] = (void*)(long)count;
2525                 args[nb_args++] = (void*)(long)format;
2526                 args[nb_args++] = (void*)(long)size;
2527             }
2528             break;
2529         case 'i':
2530         case 'l':
2531             {
2532                 int64_t val;
2533
2534                 while (qemu_isspace(*p))
2535                     p++;
2536                 if (*typestr == '?' || *typestr == '.') {
2537                     if (*typestr == '?') {
2538                         if (*p == '\0')
2539                             has_arg = 0;
2540                         else
2541                             has_arg = 1;
2542                     } else {
2543                         if (*p == '.') {
2544                             p++;
2545                             while (qemu_isspace(*p))
2546                                 p++;
2547                             has_arg = 1;
2548                         } else {
2549                             has_arg = 0;
2550                         }
2551                     }
2552                     typestr++;
2553                     if (nb_args >= MAX_ARGS)
2554                         goto error_args;
2555                     args[nb_args++] = (void *)(long)has_arg;
2556                     if (!has_arg) {
2557                         if (nb_args >= MAX_ARGS)
2558                             goto error_args;
2559                         val = -1;
2560                         goto add_num;
2561                     }
2562                 }
2563                 if (get_expr(mon, &val, &p))
2564                     goto fail;
2565             add_num:
2566                 if (c == 'i') {
2567                     if (nb_args >= MAX_ARGS)
2568                         goto error_args;
2569                     args[nb_args++] = (void *)(long)val;
2570                 } else {
2571                     if ((nb_args + 1) >= MAX_ARGS)
2572                         goto error_args;
2573 #if TARGET_PHYS_ADDR_BITS > 32
2574                     args[nb_args++] = (void *)(long)((val >> 32) & 0xffffffff);
2575 #else
2576                     args[nb_args++] = (void *)0;
2577 #endif
2578                     args[nb_args++] = (void *)(long)(val & 0xffffffff);
2579                 }
2580             }
2581             break;
2582         case '-':
2583             {
2584                 int has_option;
2585                 /* option */
2586
2587                 c = *typestr++;
2588                 if (c == '\0')
2589                     goto bad_type;
2590                 while (qemu_isspace(*p))
2591                     p++;
2592                 has_option = 0;
2593                 if (*p == '-') {
2594                     p++;
2595                     if (*p != c) {
2596                         monitor_printf(mon, "%s: unsupported option -%c\n",
2597                                        cmdname, *p);
2598                         goto fail;
2599                     }
2600                     p++;
2601                     has_option = 1;
2602                 }
2603                 if (nb_args >= MAX_ARGS)
2604                     goto error_args;
2605                 args[nb_args++] = (void *)(long)has_option;
2606             }
2607             break;
2608         default:
2609         bad_type:
2610             monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
2611             goto fail;
2612         }
2613     }
2614     /* check that all arguments were parsed */
2615     while (qemu_isspace(*p))
2616         p++;
2617     if (*p != '\0') {
2618         monitor_printf(mon, "%s: extraneous characters at the end of line\n",
2619                        cmdname);
2620         goto fail;
2621     }
2622
2623     switch(nb_args) {
2624     case 0:
2625         handler_0 = cmd->handler;
2626         handler_0(mon);
2627         break;
2628     case 1:
2629         handler_1 = cmd->handler;
2630         handler_1(mon, args[0]);
2631         break;
2632     case 2:
2633         handler_2 = cmd->handler;
2634         handler_2(mon, args[0], args[1]);
2635         break;
2636     case 3:
2637         handler_3 = cmd->handler;
2638         handler_3(mon, args[0], args[1], args[2]);
2639         break;
2640     case 4:
2641         handler_4 = cmd->handler;
2642         handler_4(mon, args[0], args[1], args[2], args[3]);
2643         break;
2644     case 5:
2645         handler_5 = cmd->handler;
2646         handler_5(mon, args[0], args[1], args[2], args[3], args[4]);
2647         break;
2648     case 6:
2649         handler_6 = cmd->handler;
2650         handler_6(mon, args[0], args[1], args[2], args[3], args[4], args[5]);
2651         break;
2652     case 7:
2653         handler_7 = cmd->handler;
2654         handler_7(mon, args[0], args[1], args[2], args[3], args[4], args[5],
2655                   args[6]);
2656         break;
2657     default:
2658         monitor_printf(mon, "unsupported number of arguments: %d\n", nb_args);
2659         goto fail;
2660     }
2661  fail:
2662     for(i = 0; i < MAX_ARGS; i++)
2663         qemu_free(str_allocated[i]);
2664     return;
2665 }
2666
2667 static void cmd_completion(const char *name, const char *list)
2668 {
2669     const char *p, *pstart;
2670     char cmd[128];
2671     int len;
2672
2673     p = list;
2674     for(;;) {
2675         pstart = p;
2676         p = strchr(p, '|');
2677         if (!p)
2678             p = pstart + strlen(pstart);
2679         len = p - pstart;
2680         if (len > sizeof(cmd) - 2)
2681             len = sizeof(cmd) - 2;
2682         memcpy(cmd, pstart, len);
2683         cmd[len] = '\0';
2684         if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
2685             readline_add_completion(cmd);
2686         }
2687         if (*p == '\0')
2688             break;
2689         p++;
2690     }
2691 }
2692
2693 static void file_completion(const char *input)
2694 {
2695     DIR *ffs;
2696     struct dirent *d;
2697     char path[1024];
2698     char file[1024], file_prefix[1024];
2699     int input_path_len;
2700     const char *p;
2701
2702     p = strrchr(input, '/');
2703     if (!p) {
2704         input_path_len = 0;
2705         pstrcpy(file_prefix, sizeof(file_prefix), input);
2706         pstrcpy(path, sizeof(path), ".");
2707     } else {
2708         input_path_len = p - input + 1;
2709         memcpy(path, input, input_path_len);
2710         if (input_path_len > sizeof(path) - 1)
2711             input_path_len = sizeof(path) - 1;
2712         path[input_path_len] = '\0';
2713         pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
2714     }
2715 #ifdef DEBUG_COMPLETION
2716     monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
2717                    input, path, file_prefix);
2718 #endif
2719     ffs = opendir(path);
2720     if (!ffs)
2721         return;
2722     for(;;) {
2723         struct stat sb;
2724         d = readdir(ffs);
2725         if (!d)
2726             break;
2727         if (strstart(d->d_name, file_prefix, NULL)) {
2728             memcpy(file, input, input_path_len);
2729             if (input_path_len < sizeof(file))
2730                 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
2731                         d->d_name);
2732             /* stat the file to find out if it's a directory.
2733              * In that case add a slash to speed up typing long paths
2734              */
2735             stat(file, &sb);
2736             if(S_ISDIR(sb.st_mode))
2737                 pstrcat(file, sizeof(file), "/");
2738             readline_add_completion(file);
2739         }
2740     }
2741     closedir(ffs);
2742 }
2743
2744 static void block_completion_it(void *opaque, BlockDriverState *bs)
2745 {
2746     const char *name = bdrv_get_device_name(bs);
2747     const char *input = opaque;
2748
2749     if (input[0] == '\0' ||
2750         !strncmp(name, (char *)input, strlen(input))) {
2751         readline_add_completion(name);
2752     }
2753 }
2754
2755 /* NOTE: this parser is an approximate form of the real command parser */
2756 static void parse_cmdline(const char *cmdline,
2757                          int *pnb_args, char **args)
2758 {
2759     const char *p;
2760     int nb_args, ret;
2761     char buf[1024];
2762
2763     p = cmdline;
2764     nb_args = 0;
2765     for(;;) {
2766         while (qemu_isspace(*p))
2767             p++;
2768         if (*p == '\0')
2769             break;
2770         if (nb_args >= MAX_ARGS)
2771             break;
2772         ret = get_str(buf, sizeof(buf), &p);
2773         args[nb_args] = qemu_strdup(buf);
2774         nb_args++;
2775         if (ret < 0)
2776             break;
2777     }
2778     *pnb_args = nb_args;
2779 }
2780
2781 void readline_find_completion(const char *cmdline)
2782 {
2783     const char *cmdname;
2784     char *args[MAX_ARGS];
2785     int nb_args, i, len;
2786     const char *ptype, *str;
2787     const mon_cmd_t *cmd;
2788     const KeyDef *key;
2789
2790     parse_cmdline(cmdline, &nb_args, args);
2791 #ifdef DEBUG_COMPLETION
2792     for(i = 0; i < nb_args; i++) {
2793         monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
2794     }
2795 #endif
2796
2797     /* if the line ends with a space, it means we want to complete the
2798        next arg */
2799     len = strlen(cmdline);
2800     if (len > 0 && qemu_isspace(cmdline[len - 1])) {
2801         if (nb_args >= MAX_ARGS)
2802             return;
2803         args[nb_args++] = qemu_strdup("");
2804     }
2805     if (nb_args <= 1) {
2806         /* command completion */
2807         if (nb_args == 0)
2808             cmdname = "";
2809         else
2810             cmdname = args[0];
2811         readline_set_completion_index(strlen(cmdname));
2812         for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
2813             cmd_completion(cmdname, cmd->name);
2814         }
2815     } else {
2816         /* find the command */
2817         for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
2818             if (compare_cmd(args[0], cmd->name))
2819                 goto found;
2820         }
2821         return;
2822     found:
2823         ptype = cmd->args_type;
2824         for(i = 0; i < nb_args - 2; i++) {
2825             if (*ptype != '\0') {
2826                 ptype++;
2827                 while (*ptype == '?')
2828                     ptype++;
2829             }
2830         }
2831         str = args[nb_args - 1];
2832         switch(*ptype) {
2833         case 'F':
2834             /* file completion */
2835             readline_set_completion_index(strlen(str));
2836             file_completion(str);
2837             break;
2838         case 'B':
2839             /* block device name completion */
2840             readline_set_completion_index(strlen(str));
2841             bdrv_iterate(block_completion_it, (void *)str);
2842             break;
2843         case 's':
2844             /* XXX: more generic ? */
2845             if (!strcmp(cmd->name, "info")) {
2846                 readline_set_completion_index(strlen(str));
2847                 for(cmd = info_cmds; cmd->name != NULL; cmd++) {
2848                     cmd_completion(str, cmd->name);
2849                 }
2850             } else if (!strcmp(cmd->name, "sendkey")) {
2851                 readline_set_completion_index(strlen(str));
2852                 for(key = key_defs; key->name != NULL; key++) {
2853                     cmd_completion(str, key->name);
2854                 }
2855             }
2856             break;
2857         default:
2858             break;
2859         }
2860     }
2861     for(i = 0; i < nb_args; i++)
2862         qemu_free(args[i]);
2863 }
2864
2865 static int term_can_read(void *opaque)
2866 {
2867     return 128;
2868 }
2869
2870 static void term_read(void *opaque, const uint8_t *buf, int size)
2871 {
2872     int i;
2873
2874     for (i = 0; i < size; i++)
2875         readline_handle_byte(buf[i]);
2876 }
2877
2878 static int monitor_suspended;
2879
2880 static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
2881 {
2882     monitor_handle_command(mon, cmdline);
2883     if (!monitor_suspended)
2884         readline_show_prompt();
2885     else
2886         monitor_suspended = 2;
2887 }
2888
2889 void monitor_suspend(Monitor *mon)
2890 {
2891     monitor_suspended = 1;
2892 }
2893
2894 void monitor_resume(Monitor *mon)
2895 {
2896     if (monitor_suspended == 2)
2897         monitor_start_input();
2898     monitor_suspended = 0;
2899 }
2900
2901 static void monitor_start_input(void)
2902 {
2903     readline_start("(qemu) ", 0, monitor_command_cb, NULL);
2904     readline_show_prompt();
2905 }
2906
2907 static void term_event(void *opaque, int event)
2908 {
2909     Monitor *mon = opaque;
2910
2911     if (event != CHR_EVENT_RESET)
2912         return;
2913
2914     if (!hide_banner)
2915         monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
2916                        "information\n", QEMU_VERSION);
2917     monitor_start_input();
2918 }
2919
2920 static int is_first_init = 1;
2921
2922 void monitor_init(CharDriverState *chr, int show_banner)
2923 {
2924     int i;
2925
2926     if (is_first_init) {
2927         key_timer = qemu_new_timer(vm_clock, release_keys, NULL);
2928         if (!key_timer)
2929             return;
2930         for (i = 0; i < MAX_MON; i++) {
2931             monitor_hd[i] = NULL;
2932         }
2933         is_first_init = 0;
2934     }
2935     for (i = 0; i < MAX_MON; i++) {
2936         if (monitor_hd[i] == NULL) {
2937             monitor_hd[i] = chr;
2938             break;
2939         }
2940     }
2941
2942     hide_banner = !show_banner;
2943
2944     qemu_chr_add_handlers(chr, term_can_read, term_read, term_event, cur_mon);
2945
2946     readline_start("", 0, monitor_command_cb, NULL);
2947 }
2948
2949 static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
2950 {
2951     BlockDriverState *bs = opaque;
2952     int ret = 0;
2953
2954     if (bdrv_set_key(bs, password) != 0) {
2955         monitor_printf(mon, "invalid password\n");
2956         ret = -EPERM;
2957     }
2958     if (password_completion_cb)
2959         password_completion_cb(password_opaque, ret);
2960
2961     monitor_start_input();
2962 }
2963
2964 void monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
2965                                  BlockDriverCompletionFunc *completion_cb,
2966                                  void *opaque)
2967 {
2968     if (!bdrv_key_required(bs)) {
2969         if (completion_cb)
2970             completion_cb(opaque, 0);
2971         return;
2972     }
2973
2974     monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
2975                    bdrv_get_encrypted_filename(bs));
2976
2977     password_completion_cb = completion_cb;
2978     password_opaque = opaque;
2979
2980     monitor_read_password(mon, bdrv_password_cb, bs);
2981 }