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