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