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