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