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