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