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