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