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