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