monitor fixes (Johannes Schindelin)
[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'          integer
42  * '/'          optional gdb-like print format (like "/10x")
43  *
44  * '?'          optional type (for 'F', 's' and 'i')
45  *
46  */
47
48 typedef struct term_cmd_t {
49     const char *name;
50     const char *args_type;
51     void (*handler)();
52     const char *params;
53     const char *help;
54 } term_cmd_t;
55
56 static CharDriverState *monitor_hd;
57
58 static term_cmd_t term_cmds[];
59 static term_cmd_t info_cmds[];
60
61 static char term_outbuf[1024];
62 static int term_outbuf_index;
63
64 static void monitor_start_input(void);
65
66 void term_flush(void)
67 {
68     if (term_outbuf_index > 0) {
69         qemu_chr_write(monitor_hd, term_outbuf, term_outbuf_index);
70         term_outbuf_index = 0;
71     }
72 }
73
74 /* flush at every end of line or if the buffer is full */
75 void term_puts(const char *str)
76 {
77     int c;
78     for(;;) {
79         c = *str++;
80         if (c == '\0')
81             break;
82         term_outbuf[term_outbuf_index++] = c;
83         if (term_outbuf_index >= sizeof(term_outbuf) ||
84             c == '\n')
85             term_flush();
86     }
87 }
88
89 void term_vprintf(const char *fmt, va_list ap)
90 {
91     char buf[4096];
92     vsnprintf(buf, sizeof(buf), fmt, ap);
93     term_puts(buf);
94 }
95
96 void term_printf(const char *fmt, ...)
97 {
98     va_list ap;
99     va_start(ap, fmt);
100     term_vprintf(fmt, ap);
101     va_end(ap);
102 }
103
104 static int compare_cmd(const char *name, const char *list)
105 {
106     const char *p, *pstart;
107     int len;
108     len = strlen(name);
109     p = list;
110     for(;;) {
111         pstart = p;
112         p = strchr(p, '|');
113         if (!p)
114             p = pstart + strlen(pstart);
115         if ((p - pstart) == len && !memcmp(pstart, name, len))
116             return 1;
117         if (*p == '\0')
118             break;
119         p++;
120     }
121     return 0;
122 }
123
124 static void help_cmd1(term_cmd_t *cmds, const char *prefix, const char *name)
125 {
126     term_cmd_t *cmd;
127
128     for(cmd = cmds; cmd->name != NULL; cmd++) {
129         if (!name || !strcmp(name, cmd->name))
130             term_printf("%s%s %s -- %s\n", prefix, cmd->name, cmd->params, cmd->help);
131     }
132 }
133
134 static void help_cmd(const char *name)
135 {
136     if (name && !strcmp(name, "info")) {
137         help_cmd1(info_cmds, "info ", NULL);
138     } else {
139         help_cmd1(term_cmds, "", name);
140         if (name && !strcmp(name, "log")) {
141             CPULogItem *item;
142             term_printf("Log items (comma separated):\n");
143             term_printf("%-10s %s\n", "none", "remove all logs");
144             for(item = cpu_log_items; item->mask != 0; item++) {
145                 term_printf("%-10s %s\n", item->name, item->help);
146             }
147         }
148     }
149 }
150
151 static void do_help(const char *name)
152 {
153     help_cmd(name);
154 }
155
156 static void do_commit(void)
157 {
158     int i;
159
160     for (i = 0; i < MAX_DISKS; i++) {
161         if (bs_table[i]) {
162             bdrv_commit(bs_table[i]);
163         }
164     }
165 }
166
167 static void do_info(const char *item)
168 {
169     term_cmd_t *cmd;
170
171     if (!item)
172         goto help;
173     for(cmd = info_cmds; cmd->name != NULL; cmd++) {
174         if (compare_cmd(item, cmd->name)) 
175             goto found;
176     }
177  help:
178     help_cmd("info");
179     return;
180  found:
181     cmd->handler();
182 }
183
184 static void do_info_network(void)
185 {
186     int i, j;
187     NetDriverState *nd;
188     
189     for(i = 0; i < nb_nics; i++) {
190         nd = &nd_table[i];
191         term_printf("%d: ifname=%s macaddr=", i, nd->ifname);
192         for(j = 0; j < 6; j++) {
193             if (j > 0)
194                 term_printf(":");
195             term_printf("%02x", nd->macaddr[j]);
196         }
197         term_printf("\n");
198     }
199 }
200  
201 static void do_info_block(void)
202 {
203     bdrv_info();
204 }
205
206 static void do_info_registers(void)
207 {
208 #ifdef TARGET_I386
209     cpu_dump_state(cpu_single_env, stdout, X86_DUMP_FPU | X86_DUMP_CCOP);
210 #else
211     cpu_dump_state(cpu_single_env, stdout, 0);
212 #endif
213 }
214
215 static void do_info_history (void)
216 {
217     int i;
218     const char *str;
219     
220     i = 0;
221     for(;;) {
222         str = readline_get_history(i);
223         if (!str)
224             break;
225         term_printf("%d: '%s'\n", i, str);
226         i++;
227     }
228 }
229
230 static void do_quit(void)
231 {
232     exit(0);
233 }
234
235 static int eject_device(BlockDriverState *bs, int force)
236 {
237     if (bdrv_is_inserted(bs)) {
238         if (!force) {
239             if (!bdrv_is_removable(bs)) {
240                 term_printf("device is not removable\n");
241                 return -1;
242             }
243             if (bdrv_is_locked(bs)) {
244                 term_printf("device is locked\n");
245                 return -1;
246             }
247         }
248         bdrv_close(bs);
249     }
250     return 0;
251 }
252
253 static void do_eject(int force, const char *filename)
254 {
255     BlockDriverState *bs;
256
257     bs = bdrv_find(filename);
258     if (!bs) {
259         term_printf("device not found\n");
260         return;
261     }
262     eject_device(bs, force);
263 }
264
265 static void do_change(const char *device, const char *filename)
266 {
267     BlockDriverState *bs;
268     int i;
269     char password[256];
270
271     bs = bdrv_find(device);
272     if (!bs) {
273         term_printf("device not found\n");
274         return;
275     }
276     if (eject_device(bs, 0) < 0)
277         return;
278     bdrv_open(bs, filename, 0);
279     if (bdrv_is_encrypted(bs)) {
280         term_printf("%s is encrypted.\n", device);
281         for(i = 0; i < 3; i++) {
282             monitor_readline("Password: ", 1, password, sizeof(password));
283             if (bdrv_set_key(bs, password) == 0)
284                 break;
285             term_printf("invalid password\n");
286         }
287     }
288 }
289
290 static void do_screen_dump(const char *filename)
291 {
292     vga_screen_dump(filename);
293 }
294
295 static void do_log(const char *items)
296 {
297     int mask;
298     
299     if (!strcmp(items, "none")) {
300         mask = 0;
301     } else {
302         mask = cpu_str_to_log_mask(items);
303         if (!mask) {
304             help_cmd("log");
305             return;
306         }
307     }
308     cpu_set_log(mask);
309 }
310
311 static void do_savevm(const char *filename)
312 {
313     if (qemu_savevm(filename) < 0)
314         term_printf("I/O error when saving VM to '%s'\n", filename);
315 }
316
317 static void do_loadvm(const char *filename)
318 {
319     if (qemu_loadvm(filename) < 0) 
320         term_printf("I/O error when loading VM from '%s'\n", filename);
321 }
322
323 static void do_stop(void)
324 {
325     vm_stop(EXCP_INTERRUPT);
326 }
327
328 static void do_cont(void)
329 {
330     vm_start();
331 }
332
333 #ifdef CONFIG_GDBSTUB
334 static void do_gdbserver(int has_port, int port)
335 {
336     if (!has_port)
337         port = DEFAULT_GDBSTUB_PORT;
338     if (gdbserver_start(port) < 0) {
339         qemu_printf("Could not open gdbserver socket on port %d\n", port);
340     } else {
341         qemu_printf("Waiting gdb connection on port %d\n", port);
342     }
343 }
344 #endif
345
346 static void term_printc(int c)
347 {
348     term_printf("'");
349     switch(c) {
350     case '\'':
351         term_printf("\\'");
352         break;
353     case '\\':
354         term_printf("\\\\");
355         break;
356     case '\n':
357         term_printf("\\n");
358         break;
359     case '\r':
360         term_printf("\\r");
361         break;
362     default:
363         if (c >= 32 && c <= 126) {
364             term_printf("%c", c);
365         } else {
366             term_printf("\\x%02x", c);
367         }
368         break;
369     }
370     term_printf("'");
371 }
372
373 static void memory_dump(int count, int format, int wsize, 
374                         target_ulong addr, int is_physical)
375 {
376     int nb_per_line, l, line_size, i, max_digits, len;
377     uint8_t buf[16];
378     uint64_t v;
379
380     if (format == 'i') {
381         int flags;
382         flags = 0;
383 #ifdef TARGET_I386
384         if (wsize == 2) {
385             flags = 1;
386         } else if (wsize == 4) {
387             flags = 0;
388         } else {
389             /* as default we use the current CS size */
390             flags = 0;
391             if (!(cpu_single_env->segs[R_CS].flags & DESC_B_MASK))
392                 flags = 1;
393         }
394 #endif
395         monitor_disas(addr, count, is_physical, flags);
396         return;
397     }
398
399     len = wsize * count;
400     if (wsize == 1)
401         line_size = 8;
402     else
403         line_size = 16;
404     nb_per_line = line_size / wsize;
405     max_digits = 0;
406
407     switch(format) {
408     case 'o':
409         max_digits = (wsize * 8 + 2) / 3;
410         break;
411     default:
412     case 'x':
413         max_digits = (wsize * 8) / 4;
414         break;
415     case 'u':
416     case 'd':
417         max_digits = (wsize * 8 * 10 + 32) / 33;
418         break;
419     case 'c':
420         wsize = 1;
421         break;
422     }
423
424     while (len > 0) {
425         term_printf("0x%08x:", addr);
426         l = len;
427         if (l > line_size)
428             l = line_size;
429         if (is_physical) {
430             cpu_physical_memory_rw(addr, buf, l, 0);
431         } else {
432             cpu_memory_rw_debug(cpu_single_env, addr, buf, l, 0);
433         }
434         i = 0; 
435         while (i < l) {
436             switch(wsize) {
437             default:
438             case 1:
439                 v = ldub_raw(buf + i);
440                 break;
441             case 2:
442                 v = lduw_raw(buf + i);
443                 break;
444             case 4:
445                 v = ldl_raw(buf + i);
446                 break;
447             case 8:
448                 v = ldq_raw(buf + i);
449                 break;
450             }
451             term_printf(" ");
452             switch(format) {
453             case 'o':
454                 term_printf("%#*llo", max_digits, v);
455                 break;
456             case 'x':
457                 term_printf("0x%0*llx", max_digits, v);
458                 break;
459             case 'u':
460                 term_printf("%*llu", max_digits, v);
461                 break;
462             case 'd':
463                 term_printf("%*lld", max_digits, v);
464                 break;
465             case 'c':
466                 term_printc(v);
467                 break;
468             }
469             i += wsize;
470         }
471         term_printf("\n");
472         addr += l;
473         len -= l;
474     }
475 }
476
477 static void do_memory_dump(int count, int format, int size, int addr)
478 {
479     memory_dump(count, format, size, addr, 0);
480 }
481
482 static void do_physical_memory_dump(int count, int format, int size, int addr)
483 {
484     memory_dump(count, format, size, addr, 1);
485 }
486
487 static void do_print(int count, int format, int size, int val)
488 {
489     switch(format) {
490     case 'o':
491         term_printf("%#o", val);
492         break;
493     case 'x':
494         term_printf("%#x", val);
495         break;
496     case 'u':
497         term_printf("%u", val);
498         break;
499     default:
500     case 'd':
501         term_printf("%d", val);
502         break;
503     case 'c':
504         term_printc(val);
505         break;
506     }
507     term_printf("\n");
508 }
509
510 typedef struct {
511     int keycode;
512     const char *name;
513 } KeyDef;
514
515 static const KeyDef key_defs[] = {
516     { 0x2a, "shift" },
517     { 0x36, "shift_r" },
518     
519     { 0x38, "alt" },
520     { 0xb8, "alt_r" },
521     { 0x1d, "ctrl" },
522     { 0x9d, "ctrl_r" },
523
524     { 0xdd, "menu" },
525
526     { 0x01, "esc" },
527
528     { 0x02, "1" },
529     { 0x03, "2" },
530     { 0x04, "3" },
531     { 0x05, "4" },
532     { 0x06, "5" },
533     { 0x07, "6" },
534     { 0x08, "7" },
535     { 0x09, "8" },
536     { 0x0a, "9" },
537     { 0x0b, "0" },
538     { 0x0e, "backspace" },
539
540     { 0x0f, "tab" },
541     { 0x10, "q" },
542     { 0x11, "w" },
543     { 0x12, "e" },
544     { 0x13, "r" },
545     { 0x14, "t" },
546     { 0x15, "y" },
547     { 0x16, "u" },
548     { 0x17, "i" },
549     { 0x18, "o" },
550     { 0x19, "p" },
551
552     { 0x1c, "ret" },
553
554     { 0x1e, "a" },
555     { 0x1f, "s" },
556     { 0x20, "d" },
557     { 0x21, "f" },
558     { 0x22, "g" },
559     { 0x23, "h" },
560     { 0x24, "j" },
561     { 0x25, "k" },
562     { 0x26, "l" },
563
564     { 0x2c, "z" },
565     { 0x2d, "x" },
566     { 0x2e, "c" },
567     { 0x2f, "v" },
568     { 0x30, "b" },
569     { 0x31, "n" },
570     { 0x32, "m" },
571     
572     { 0x39, "spc" },
573     { 0x3a, "caps_lock" },
574     { 0x3b, "f1" },
575     { 0x3c, "f2" },
576     { 0x3d, "f3" },
577     { 0x3e, "f4" },
578     { 0x3f, "f5" },
579     { 0x40, "f6" },
580     { 0x41, "f7" },
581     { 0x42, "f8" },
582     { 0x43, "f9" },
583     { 0x44, "f10" },
584     { 0x45, "num_lock" },
585     { 0x46, "scroll_lock" },
586
587     { 0x56, "<" },
588
589     { 0x57, "f11" },
590     { 0x58, "f12" },
591
592     { 0xb7, "print" },
593
594     { 0xc7, "home" },
595     { 0xc9, "pgup" },
596     { 0xd1, "pgdn" },
597     { 0xcf, "end" },
598
599     { 0xcb, "left" },
600     { 0xc8, "up" },
601     { 0xd0, "down" },
602     { 0xcd, "right" },
603
604     { 0xd2, "insert" },
605     { 0xd3, "delete" },
606     { 0, NULL },
607 };
608
609 static int get_keycode(const char *key)
610 {
611     const KeyDef *p;
612
613     for(p = key_defs; p->name != NULL; p++) {
614         if (!strcmp(key, p->name))
615             return p->keycode;
616     }
617     return -1;
618 }
619
620 static void do_send_key(const char *string)
621 {
622     char keybuf[16], *q;
623     uint8_t keycodes[16];
624     const char *p;
625     int nb_keycodes, keycode, i;
626     
627     nb_keycodes = 0;
628     p = string;
629     while (*p != '\0') {
630         q = keybuf;
631         while (*p != '\0' && *p != '-') {
632             if ((q - keybuf) < sizeof(keybuf) - 1) {
633                 *q++ = *p;
634             }
635             p++;
636         }
637         *q = '\0';
638         keycode = get_keycode(keybuf);
639         if (keycode < 0) {
640             term_printf("unknown key: '%s'\n", keybuf);
641             return;
642         }
643         keycodes[nb_keycodes++] = keycode;
644         if (*p == '\0')
645             break;
646         p++;
647     }
648     /* key down events */
649     for(i = 0; i < nb_keycodes; i++) {
650         keycode = keycodes[i];
651         if (keycode & 0x80)
652             kbd_put_keycode(0xe0);
653         kbd_put_keycode(keycode & 0x7f);
654     }
655     /* key up events */
656     for(i = nb_keycodes - 1; i >= 0; i--) {
657         keycode = keycodes[i];
658         if (keycode & 0x80)
659             kbd_put_keycode(0xe0);
660         kbd_put_keycode(keycode | 0x80);
661     }
662 }
663
664 static void do_ioport_read(int count, int format, int size, int addr, int has_index, int index)
665 {
666     uint32_t val;
667     int suffix;
668
669     if (has_index) {
670         cpu_outb(NULL, addr & 0xffff, index & 0xff);
671         addr++;
672     }
673     addr &= 0xffff;
674
675     switch(size) {
676     default:
677     case 1:
678         val = cpu_inb(NULL, addr);
679         suffix = 'b';
680         break;
681     case 2:
682         val = cpu_inw(NULL, addr);
683         suffix = 'w';
684         break;
685     case 4:
686         val = cpu_inl(NULL, addr);
687         suffix = 'l';
688         break;
689     }
690     term_printf("port%c[0x%04x] = %#0*x\n",
691                 suffix, addr, size * 2, val);
692 }
693
694 static void do_system_reset(void)
695 {
696     qemu_system_reset_request();
697 }
698
699 #if defined(TARGET_I386)
700 static void print_pte(uint32_t addr, uint32_t pte, uint32_t mask)
701 {
702     term_printf("%08x: %08x %c%c%c%c%c%c%c%c\n", 
703                 addr,
704                 pte & mask,
705                 pte & PG_GLOBAL_MASK ? 'G' : '-',
706                 pte & PG_PSE_MASK ? 'P' : '-',
707                 pte & PG_DIRTY_MASK ? 'D' : '-',
708                 pte & PG_ACCESSED_MASK ? 'A' : '-',
709                 pte & PG_PCD_MASK ? 'C' : '-',
710                 pte & PG_PWT_MASK ? 'T' : '-',
711                 pte & PG_USER_MASK ? 'U' : '-',
712                 pte & PG_RW_MASK ? 'W' : '-');
713 }
714
715 static void tlb_info(void)
716 {
717     CPUState *env = cpu_single_env;
718     int l1, l2;
719     uint32_t pgd, pde, pte;
720
721     if (!(env->cr[0] & CR0_PG_MASK)) {
722         term_printf("PG disabled\n");
723         return;
724     }
725     pgd = env->cr[3] & ~0xfff;
726     for(l1 = 0; l1 < 1024; l1++) {
727         cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
728         pde = le32_to_cpu(pde);
729         if (pde & PG_PRESENT_MASK) {
730             if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
731                 print_pte((l1 << 22), pde, ~((1 << 20) - 1));
732             } else {
733                 for(l2 = 0; l2 < 1024; l2++) {
734                     cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, 
735                                              (uint8_t *)&pte, 4);
736                     pte = le32_to_cpu(pte);
737                     if (pte & PG_PRESENT_MASK) {
738                         print_pte((l1 << 22) + (l2 << 12), 
739                                   pte & ~PG_PSE_MASK, 
740                                   ~0xfff);
741                     }
742                 }
743             }
744         }
745     }
746 }
747
748 static void mem_print(uint32_t *pstart, int *plast_prot, 
749                       uint32_t end, int prot)
750 {
751     if (prot != *plast_prot) {
752         if (*pstart != -1) {
753             term_printf("%08x-%08x %08x %c%c%c\n",
754                         *pstart, end, end - *pstart, 
755                         prot & PG_USER_MASK ? 'u' : '-',
756                         'r',
757                         prot & PG_RW_MASK ? 'w' : '-');
758         }
759         if (prot != 0)
760             *pstart = end;
761         else
762             *pstart = -1;
763         *plast_prot = prot;
764     }
765 }
766
767 static void mem_info(void)
768 {
769     CPUState *env = cpu_single_env;
770     int l1, l2, prot, last_prot;
771     uint32_t pgd, pde, pte, start, end;
772
773     if (!(env->cr[0] & CR0_PG_MASK)) {
774         term_printf("PG disabled\n");
775         return;
776     }
777     pgd = env->cr[3] & ~0xfff;
778     last_prot = 0;
779     start = -1;
780     for(l1 = 0; l1 < 1024; l1++) {
781         cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
782         pde = le32_to_cpu(pde);
783         end = l1 << 22;
784         if (pde & PG_PRESENT_MASK) {
785             if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
786                 prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
787                 mem_print(&start, &last_prot, end, prot);
788             } else {
789                 for(l2 = 0; l2 < 1024; l2++) {
790                     cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, 
791                                              (uint8_t *)&pte, 4);
792                     pte = le32_to_cpu(pte);
793                     end = (l1 << 22) + (l2 << 12);
794                     if (pte & PG_PRESENT_MASK) {
795                         prot = pte & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
796                     } else {
797                         prot = 0;
798                     }
799                     mem_print(&start, &last_prot, end, prot);
800                 }
801             }
802         } else {
803             prot = 0;
804             mem_print(&start, &last_prot, end, prot);
805         }
806     }
807 }
808 #endif
809
810 static term_cmd_t term_cmds[] = {
811     { "help|?", "s?", do_help, 
812       "[cmd]", "show the help" },
813     { "commit", "", do_commit, 
814       "", "commit changes to the disk images (if -snapshot is used)" },
815     { "info", "s?", do_info,
816       "subcommand", "show various information about the system state" },
817     { "q|quit", "", do_quit,
818       "", "quit the emulator" },
819     { "eject", "-fB", do_eject,
820       "[-f] device", "eject a removable media (use -f to force it)" },
821     { "change", "BF", do_change,
822       "device filename", "change a removable media" },
823     { "screendump", "F", do_screen_dump, 
824       "filename", "save screen into PPM image 'filename'" },
825     { "log", "s", do_log,
826       "item1[,...]", "activate logging of the specified items to '/tmp/qemu.log'" }, 
827     { "savevm", "F", do_savevm,
828       "filename", "save the whole virtual machine state to 'filename'" }, 
829     { "loadvm", "F", do_loadvm,
830       "filename", "restore the whole virtual machine state from 'filename'" }, 
831     { "stop", "", do_stop, 
832       "", "stop emulation", },
833     { "c|cont", "", do_cont, 
834       "", "resume emulation", },
835 #ifdef CONFIG_GDBSTUB
836     { "gdbserver", "i?", do_gdbserver, 
837       "[port]", "start gdbserver session (default port=1234)", },
838 #endif
839     { "x", "/i", do_memory_dump, 
840       "/fmt addr", "virtual memory dump starting at 'addr'", },
841     { "xp", "/i", do_physical_memory_dump, 
842       "/fmt addr", "physical memory dump starting at 'addr'", },
843     { "p|print", "/i", do_print, 
844       "/fmt expr", "print expression value (use $reg for CPU register access)", },
845     { "i", "/ii.", do_ioport_read, 
846       "/fmt addr", "I/O port read" },
847
848     { "sendkey", "s", do_send_key, 
849       "keys", "send keys to the VM (e.g. 'sendkey ctrl-alt-f1')" },
850     { "system_reset", "", do_system_reset, 
851       "", "reset the system" },
852     { NULL, NULL, }, 
853 };
854
855 static term_cmd_t info_cmds[] = {
856     { "network", "", do_info_network,
857       "", "show the network state" },
858     { "block", "", do_info_block,
859       "", "show the block devices" },
860     { "registers", "", do_info_registers,
861       "", "show the cpu registers" },
862     { "history", "", do_info_history,
863       "", "show the command line history", },
864     { "irq", "", irq_info,
865       "", "show the interrupts statistics (if available)", },
866     { "pic", "", pic_info,
867       "", "show i8259 (PIC) state", },
868     { "pci", "", pci_info,
869       "", "show PCI info", },
870 #if defined(TARGET_I386)
871     { "tlb", "", tlb_info,
872       "", "show virtual to physical memory mappings", },
873     { "mem", "", mem_info,
874       "", "show the active virtual memory mappings", },
875 #endif
876     { NULL, NULL, },
877 };
878
879 /*******************************************************************/
880
881 static const char *pch;
882 static jmp_buf expr_env;
883
884 typedef struct MonitorDef {
885     const char *name;
886     int offset;
887     int (*get_value)(struct MonitorDef *md, int val);
888 } MonitorDef;
889
890 #if defined(TARGET_I386)
891 static int monitor_get_pc (struct MonitorDef *md, int val)
892 {
893     return cpu_single_env->eip + (long)cpu_single_env->segs[R_CS].base;
894 }
895 #endif
896
897 #if defined(TARGET_PPC)
898 static int monitor_get_ccr (struct MonitorDef *md, int val)
899 {
900     unsigned int u;
901     int i;
902
903     u = 0;
904     for (i = 0; i < 8; i++)
905         u |= cpu_single_env->crf[i] << (32 - (4 * i));
906
907     return u;
908 }
909
910 static int monitor_get_msr (struct MonitorDef *md, int val)
911 {
912     return (cpu_single_env->msr[MSR_POW] << MSR_POW) |
913         (cpu_single_env->msr[MSR_ILE] << MSR_ILE) |
914         (cpu_single_env->msr[MSR_EE] << MSR_EE) |
915         (cpu_single_env->msr[MSR_PR] << MSR_PR) |
916         (cpu_single_env->msr[MSR_FP] << MSR_FP) |
917         (cpu_single_env->msr[MSR_ME] << MSR_ME) |
918         (cpu_single_env->msr[MSR_FE0] << MSR_FE0) |
919         (cpu_single_env->msr[MSR_SE] << MSR_SE) |
920         (cpu_single_env->msr[MSR_BE] << MSR_BE) |
921         (cpu_single_env->msr[MSR_FE1] << MSR_FE1) |
922         (cpu_single_env->msr[MSR_IP] << MSR_IP) |
923         (cpu_single_env->msr[MSR_IR] << MSR_IR) |
924         (cpu_single_env->msr[MSR_DR] << MSR_DR) |
925         (cpu_single_env->msr[MSR_RI] << MSR_RI) |
926         (cpu_single_env->msr[MSR_LE] << MSR_LE);
927 }
928
929 static int monitor_get_xer (struct MonitorDef *md, int val)
930 {
931     return (cpu_single_env->xer[XER_SO] << XER_SO) |
932         (cpu_single_env->xer[XER_OV] << XER_OV) |
933         (cpu_single_env->xer[XER_CA] << XER_CA) |
934         (cpu_single_env->xer[XER_BC] << XER_BC);
935 }
936
937 static int monitor_get_decr (struct MonitorDef *md, int val)
938 {
939     return cpu_ppc_load_decr(cpu_single_env);
940 }
941
942 static int monitor_get_tbu (struct MonitorDef *md, int val)
943 {
944     return cpu_ppc_load_tbu(cpu_single_env);
945 }
946
947 static int monitor_get_tbl (struct MonitorDef *md, int val)
948 {
949     return cpu_ppc_load_tbl(cpu_single_env);
950 }
951 #endif
952
953 #if defined(TARGET_SPARC)
954 static int monitor_get_psr (struct MonitorDef *md, int val)
955 {
956     return GET_PSR(cpu_single_env);
957 }
958
959 static int monitor_get_reg(struct MonitorDef *md, int val)
960 {
961     return cpu_single_env->regwptr[val];
962 }
963 #endif
964
965 static MonitorDef monitor_defs[] = {
966 #ifdef TARGET_I386
967
968 #define SEG(name, seg) \
969     { name, offsetof(CPUState, segs[seg].selector) },\
970     { name ".base", offsetof(CPUState, segs[seg].base) },\
971     { name ".limit", offsetof(CPUState, segs[seg].limit) },
972
973     { "eax", offsetof(CPUState, regs[0]) },
974     { "ecx", offsetof(CPUState, regs[1]) },
975     { "edx", offsetof(CPUState, regs[2]) },
976     { "ebx", offsetof(CPUState, regs[3]) },
977     { "esp|sp", offsetof(CPUState, regs[4]) },
978     { "ebp|fp", offsetof(CPUState, regs[5]) },
979     { "esi", offsetof(CPUState, regs[6]) },
980     { "edi", offsetof(CPUState, regs[7]) },
981     { "eflags", offsetof(CPUState, eflags) },
982     { "eip", offsetof(CPUState, eip) },
983     SEG("cs", R_CS)
984     SEG("ds", R_DS)
985     SEG("es", R_ES)
986     SEG("ss", R_SS)
987     SEG("fs", R_FS)
988     SEG("gs", R_GS)
989     { "pc", 0, monitor_get_pc, },
990 #elif defined(TARGET_PPC)
991     { "r0", offsetof(CPUState, gpr[0]) },
992     { "r1", offsetof(CPUState, gpr[1]) },
993     { "r2", offsetof(CPUState, gpr[2]) },
994     { "r3", offsetof(CPUState, gpr[3]) },
995     { "r4", offsetof(CPUState, gpr[4]) },
996     { "r5", offsetof(CPUState, gpr[5]) },
997     { "r6", offsetof(CPUState, gpr[6]) },
998     { "r7", offsetof(CPUState, gpr[7]) },
999     { "r8", offsetof(CPUState, gpr[8]) },
1000     { "r9", offsetof(CPUState, gpr[9]) },
1001     { "r10", offsetof(CPUState, gpr[10]) },
1002     { "r11", offsetof(CPUState, gpr[11]) },
1003     { "r12", offsetof(CPUState, gpr[12]) },
1004     { "r13", offsetof(CPUState, gpr[13]) },
1005     { "r14", offsetof(CPUState, gpr[14]) },
1006     { "r15", offsetof(CPUState, gpr[15]) },
1007     { "r16", offsetof(CPUState, gpr[16]) },
1008     { "r17", offsetof(CPUState, gpr[17]) },
1009     { "r18", offsetof(CPUState, gpr[18]) },
1010     { "r19", offsetof(CPUState, gpr[19]) },
1011     { "r20", offsetof(CPUState, gpr[20]) },
1012     { "r21", offsetof(CPUState, gpr[21]) },
1013     { "r22", offsetof(CPUState, gpr[22]) },
1014     { "r23", offsetof(CPUState, gpr[23]) },
1015     { "r24", offsetof(CPUState, gpr[24]) },
1016     { "r25", offsetof(CPUState, gpr[25]) },
1017     { "r26", offsetof(CPUState, gpr[26]) },
1018     { "r27", offsetof(CPUState, gpr[27]) },
1019     { "r28", offsetof(CPUState, gpr[28]) },
1020     { "r29", offsetof(CPUState, gpr[29]) },
1021     { "r30", offsetof(CPUState, gpr[30]) },
1022     { "r31", offsetof(CPUState, gpr[31]) },
1023     { "nip|pc", offsetof(CPUState, nip) },
1024     { "lr", offsetof(CPUState, lr) },
1025     { "ctr", offsetof(CPUState, ctr) },
1026     { "decr", 0, &monitor_get_decr, },
1027     { "ccr", 0, &monitor_get_ccr, },
1028     { "msr", 0, &monitor_get_msr, },
1029     { "xer", 0, &monitor_get_xer, },
1030     { "tbu", 0, &monitor_get_tbu, },
1031     { "tbl", 0, &monitor_get_tbl, },
1032     { "sdr1", offsetof(CPUState, sdr1) },
1033     { "sr0", offsetof(CPUState, sr[0]) },
1034     { "sr1", offsetof(CPUState, sr[1]) },
1035     { "sr2", offsetof(CPUState, sr[2]) },
1036     { "sr3", offsetof(CPUState, sr[3]) },
1037     { "sr4", offsetof(CPUState, sr[4]) },
1038     { "sr5", offsetof(CPUState, sr[5]) },
1039     { "sr6", offsetof(CPUState, sr[6]) },
1040     { "sr7", offsetof(CPUState, sr[7]) },
1041     { "sr8", offsetof(CPUState, sr[8]) },
1042     { "sr9", offsetof(CPUState, sr[9]) },
1043     { "sr10", offsetof(CPUState, sr[10]) },
1044     { "sr11", offsetof(CPUState, sr[11]) },
1045     { "sr12", offsetof(CPUState, sr[12]) },
1046     { "sr13", offsetof(CPUState, sr[13]) },
1047     { "sr14", offsetof(CPUState, sr[14]) },
1048     { "sr15", offsetof(CPUState, sr[15]) },
1049     /* Too lazy to put BATs and SPRs ... */
1050 #elif defined(TARGET_SPARC)
1051     { "g0", offsetof(CPUState, gregs[0]) },
1052     { "g1", offsetof(CPUState, gregs[1]) },
1053     { "g2", offsetof(CPUState, gregs[2]) },
1054     { "g3", offsetof(CPUState, gregs[3]) },
1055     { "g4", offsetof(CPUState, gregs[4]) },
1056     { "g5", offsetof(CPUState, gregs[5]) },
1057     { "g6", offsetof(CPUState, gregs[6]) },
1058     { "g7", offsetof(CPUState, gregs[7]) },
1059     { "o0", 0, monitor_get_reg },
1060     { "o1", 1, monitor_get_reg },
1061     { "o2", 2, monitor_get_reg },
1062     { "o3", 3, monitor_get_reg },
1063     { "o4", 4, monitor_get_reg },
1064     { "o5", 5, monitor_get_reg },
1065     { "o6", 6, monitor_get_reg },
1066     { "o7", 7, monitor_get_reg },
1067     { "l0", 8, monitor_get_reg },
1068     { "l1", 9, monitor_get_reg },
1069     { "l2", 10, monitor_get_reg },
1070     { "l3", 11, monitor_get_reg },
1071     { "l4", 12, monitor_get_reg },
1072     { "l5", 13, monitor_get_reg },
1073     { "l6", 14, monitor_get_reg },
1074     { "l7", 15, monitor_get_reg },
1075     { "i0", 16, monitor_get_reg },
1076     { "i1", 17, monitor_get_reg },
1077     { "i2", 18, monitor_get_reg },
1078     { "i3", 19, monitor_get_reg },
1079     { "i4", 20, monitor_get_reg },
1080     { "i5", 21, monitor_get_reg },
1081     { "i6", 22, monitor_get_reg },
1082     { "i7", 23, monitor_get_reg },
1083     { "pc", offsetof(CPUState, pc) },
1084     { "npc", offsetof(CPUState, npc) },
1085     { "y", offsetof(CPUState, y) },
1086     { "psr", 0, &monitor_get_psr, },
1087     { "wim", offsetof(CPUState, wim) },
1088     { "tbr", offsetof(CPUState, tbr) },
1089     { "fsr", offsetof(CPUState, fsr) },
1090     { "f0", offsetof(CPUState, fpr[0]) },
1091     { "f1", offsetof(CPUState, fpr[1]) },
1092     { "f2", offsetof(CPUState, fpr[2]) },
1093     { "f3", offsetof(CPUState, fpr[3]) },
1094     { "f4", offsetof(CPUState, fpr[4]) },
1095     { "f5", offsetof(CPUState, fpr[5]) },
1096     { "f6", offsetof(CPUState, fpr[6]) },
1097     { "f7", offsetof(CPUState, fpr[7]) },
1098     { "f8", offsetof(CPUState, fpr[8]) },
1099     { "f9", offsetof(CPUState, fpr[9]) },
1100     { "f10", offsetof(CPUState, fpr[10]) },
1101     { "f11", offsetof(CPUState, fpr[11]) },
1102     { "f12", offsetof(CPUState, fpr[12]) },
1103     { "f13", offsetof(CPUState, fpr[13]) },
1104     { "f14", offsetof(CPUState, fpr[14]) },
1105     { "f15", offsetof(CPUState, fpr[15]) },
1106     { "f16", offsetof(CPUState, fpr[16]) },
1107     { "f17", offsetof(CPUState, fpr[17]) },
1108     { "f18", offsetof(CPUState, fpr[18]) },
1109     { "f19", offsetof(CPUState, fpr[19]) },
1110     { "f20", offsetof(CPUState, fpr[20]) },
1111     { "f21", offsetof(CPUState, fpr[21]) },
1112     { "f22", offsetof(CPUState, fpr[22]) },
1113     { "f23", offsetof(CPUState, fpr[23]) },
1114     { "f24", offsetof(CPUState, fpr[24]) },
1115     { "f25", offsetof(CPUState, fpr[25]) },
1116     { "f26", offsetof(CPUState, fpr[26]) },
1117     { "f27", offsetof(CPUState, fpr[27]) },
1118     { "f28", offsetof(CPUState, fpr[28]) },
1119     { "f29", offsetof(CPUState, fpr[29]) },
1120     { "f30", offsetof(CPUState, fpr[30]) },
1121     { "f31", offsetof(CPUState, fpr[31]) },
1122 #endif
1123     { NULL },
1124 };
1125
1126 static void expr_error(const char *fmt) 
1127 {
1128     term_printf(fmt);
1129     term_printf("\n");
1130     longjmp(expr_env, 1);
1131 }
1132
1133 static int get_monitor_def(int *pval, const char *name)
1134 {
1135     MonitorDef *md;
1136     for(md = monitor_defs; md->name != NULL; md++) {
1137         if (compare_cmd(name, md->name)) {
1138             if (md->get_value) {
1139                 *pval = md->get_value(md, md->offset);
1140             } else {
1141                 *pval = *(uint32_t *)((uint8_t *)cpu_single_env + md->offset);
1142             }
1143             return 0;
1144         }
1145     }
1146     return -1;
1147 }
1148
1149 static void next(void)
1150 {
1151     if (pch != '\0') {
1152         pch++;
1153         while (isspace(*pch))
1154             pch++;
1155     }
1156 }
1157
1158 static int expr_sum(void);
1159
1160 static int expr_unary(void)
1161 {
1162     int n;
1163     char *p;
1164
1165     switch(*pch) {
1166     case '+':
1167         next();
1168         n = expr_unary();
1169         break;
1170     case '-':
1171         next();
1172         n = -expr_unary();
1173         break;
1174     case '~':
1175         next();
1176         n = ~expr_unary();
1177         break;
1178     case '(':
1179         next();
1180         n = expr_sum();
1181         if (*pch != ')') {
1182             expr_error("')' expected");
1183         }
1184         next();
1185         break;
1186     case '\'':
1187         pch++;
1188         if (*pch == '\0')
1189             expr_error("character constant expected");
1190         n = *pch;
1191         pch++;
1192         if (*pch != '\'')
1193             expr_error("missing terminating \' character");
1194         next();
1195         break;
1196     case '$':
1197         {
1198             char buf[128], *q;
1199             
1200             pch++;
1201             q = buf;
1202             while ((*pch >= 'a' && *pch <= 'z') ||
1203                    (*pch >= 'A' && *pch <= 'Z') ||
1204                    (*pch >= '0' && *pch <= '9') ||
1205                    *pch == '_' || *pch == '.') {
1206                 if ((q - buf) < sizeof(buf) - 1)
1207                     *q++ = *pch;
1208                 pch++;
1209             }
1210             while (isspace(*pch))
1211                 pch++;
1212             *q = 0;
1213             if (get_monitor_def(&n, buf))
1214                 expr_error("unknown register");
1215         }
1216         break;
1217     case '\0':
1218         expr_error("unexpected end of expression");
1219         n = 0;
1220         break;
1221     default:
1222         n = strtoul(pch, &p, 0);
1223         if (pch == p) {
1224             expr_error("invalid char in expression");
1225         }
1226         pch = p;
1227         while (isspace(*pch))
1228             pch++;
1229         break;
1230     }
1231     return n;
1232 }
1233
1234
1235 static int expr_prod(void)
1236 {
1237     int val, val2, op;
1238
1239     val = expr_unary();
1240     for(;;) {
1241         op = *pch;
1242         if (op != '*' && op != '/' && op != '%')
1243             break;
1244         next();
1245         val2 = expr_unary();
1246         switch(op) {
1247         default:
1248         case '*':
1249             val *= val2;
1250             break;
1251         case '/':
1252         case '%':
1253             if (val2 == 0) 
1254                 expr_error("division by zero");
1255             if (op == '/')
1256                 val /= val2;
1257             else
1258                 val %= val2;
1259             break;
1260         }
1261     }
1262     return val;
1263 }
1264
1265 static int expr_logic(void)
1266 {
1267     int val, val2, op;
1268
1269     val = expr_prod();
1270     for(;;) {
1271         op = *pch;
1272         if (op != '&' && op != '|' && op != '^')
1273             break;
1274         next();
1275         val2 = expr_prod();
1276         switch(op) {
1277         default:
1278         case '&':
1279             val &= val2;
1280             break;
1281         case '|':
1282             val |= val2;
1283             break;
1284         case '^':
1285             val ^= val2;
1286             break;
1287         }
1288     }
1289     return val;
1290 }
1291
1292 static int expr_sum(void)
1293 {
1294     int val, val2, op;
1295
1296     val = expr_logic();
1297     for(;;) {
1298         op = *pch;
1299         if (op != '+' && op != '-')
1300             break;
1301         next();
1302         val2 = expr_logic();
1303         if (op == '+')
1304             val += val2;
1305         else
1306             val -= val2;
1307     }
1308     return val;
1309 }
1310
1311 static int get_expr(int *pval, const char **pp)
1312 {
1313     pch = *pp;
1314     if (setjmp(expr_env)) {
1315         *pp = pch;
1316         return -1;
1317     }
1318     while (isspace(*pch))
1319         pch++;
1320     *pval = expr_sum();
1321     *pp = pch;
1322     return 0;
1323 }
1324
1325 static int get_str(char *buf, int buf_size, const char **pp)
1326 {
1327     const char *p;
1328     char *q;
1329     int c;
1330
1331     q = buf;
1332     p = *pp;
1333     while (isspace(*p))
1334         p++;
1335     if (*p == '\0') {
1336     fail:
1337         *q = '\0';
1338         *pp = p;
1339         return -1;
1340     }
1341     if (*p == '\"') {
1342         p++;
1343         while (*p != '\0' && *p != '\"') {
1344             if (*p == '\\') {
1345                 p++;
1346                 c = *p++;
1347                 switch(c) {
1348                 case 'n':
1349                     c = '\n';
1350                     break;
1351                 case 'r':
1352                     c = '\r';
1353                     break;
1354                 case '\\':
1355                 case '\'':
1356                 case '\"':
1357                     break;
1358                 default:
1359                     qemu_printf("unsupported escape code: '\\%c'\n", c);
1360                     goto fail;
1361                 }
1362                 if ((q - buf) < buf_size - 1) {
1363                     *q++ = c;
1364                 }
1365             } else {
1366                 if ((q - buf) < buf_size - 1) {
1367                     *q++ = *p;
1368                 }
1369                 p++;
1370             }
1371         }
1372         if (*p != '\"') {
1373             qemu_printf("unterminated string\n");
1374             goto fail;
1375         }
1376         p++;
1377     } else {
1378         while (*p != '\0' && !isspace(*p)) {
1379             if ((q - buf) < buf_size - 1) {
1380                 *q++ = *p;
1381             }
1382             p++;
1383         }
1384     }
1385     *q = '\0';
1386     *pp = p;
1387     return 0;
1388 }
1389
1390 static int default_fmt_format = 'x';
1391 static int default_fmt_size = 4;
1392
1393 #define MAX_ARGS 16
1394
1395 static void monitor_handle_command(const char *cmdline)
1396 {
1397     const char *p, *pstart, *typestr;
1398     char *q;
1399     int c, nb_args, len, i, has_arg;
1400     term_cmd_t *cmd;
1401     char cmdname[256];
1402     char buf[1024];
1403     void *str_allocated[MAX_ARGS];
1404     void *args[MAX_ARGS];
1405
1406 #ifdef DEBUG
1407     term_printf("command='%s'\n", cmdline);
1408 #endif
1409     
1410     /* extract the command name */
1411     p = cmdline;
1412     q = cmdname;
1413     while (isspace(*p))
1414         p++;
1415     if (*p == '\0')
1416         return;
1417     pstart = p;
1418     while (*p != '\0' && *p != '/' && !isspace(*p))
1419         p++;
1420     len = p - pstart;
1421     if (len > sizeof(cmdname) - 1)
1422         len = sizeof(cmdname) - 1;
1423     memcpy(cmdname, pstart, len);
1424     cmdname[len] = '\0';
1425     
1426     /* find the command */
1427     for(cmd = term_cmds; cmd->name != NULL; cmd++) {
1428         if (compare_cmd(cmdname, cmd->name)) 
1429             goto found;
1430     }
1431     term_printf("unknown command: '%s'\n", cmdname);
1432     return;
1433  found:
1434
1435     for(i = 0; i < MAX_ARGS; i++)
1436         str_allocated[i] = NULL;
1437     
1438     /* parse the parameters */
1439     typestr = cmd->args_type;
1440     nb_args = 0;
1441     for(;;) {
1442         c = *typestr;
1443         if (c == '\0')
1444             break;
1445         typestr++;
1446         switch(c) {
1447         case 'F':
1448         case 'B':
1449         case 's':
1450             {
1451                 int ret;
1452                 char *str;
1453                 
1454                 while (isspace(*p)) 
1455                     p++;
1456                 if (*typestr == '?') {
1457                     typestr++;
1458                     if (*p == '\0') {
1459                         /* no optional string: NULL argument */
1460                         str = NULL;
1461                         goto add_str;
1462                     }
1463                 }
1464                 ret = get_str(buf, sizeof(buf), &p);
1465                 if (ret < 0) {
1466                     switch(c) {
1467                     case 'F':
1468                         term_printf("%s: filename expected\n", cmdname);
1469                         break;
1470                     case 'B':
1471                         term_printf("%s: block device name expected\n", cmdname);
1472                         break;
1473                     default:
1474                         term_printf("%s: string expected\n", cmdname);
1475                         break;
1476                     }
1477                     goto fail;
1478                 }
1479                 str = qemu_malloc(strlen(buf) + 1);
1480                 strcpy(str, buf);
1481                 str_allocated[nb_args] = str;
1482             add_str:
1483                 if (nb_args >= MAX_ARGS) {
1484                 error_args:
1485                     term_printf("%s: too many arguments\n", cmdname);
1486                     goto fail;
1487                 }
1488                 args[nb_args++] = str;
1489             }
1490             break;
1491         case '/':
1492             {
1493                 int count, format, size;
1494                 
1495                 while (isspace(*p))
1496                     p++;
1497                 if (*p == '/') {
1498                     /* format found */
1499                     p++;
1500                     count = 1;
1501                     if (isdigit(*p)) {
1502                         count = 0;
1503                         while (isdigit(*p)) {
1504                             count = count * 10 + (*p - '0');
1505                             p++;
1506                         }
1507                     }
1508                     size = -1;
1509                     format = -1;
1510                     for(;;) {
1511                         switch(*p) {
1512                         case 'o':
1513                         case 'd':
1514                         case 'u':
1515                         case 'x':
1516                         case 'i':
1517                         case 'c':
1518                             format = *p++;
1519                             break;
1520                         case 'b':
1521                             size = 1;
1522                             p++;
1523                             break;
1524                         case 'h':
1525                             size = 2;
1526                             p++;
1527                             break;
1528                         case 'w':
1529                             size = 4;
1530                             p++;
1531                             break;
1532                         case 'g':
1533                         case 'L':
1534                             size = 8;
1535                             p++;
1536                             break;
1537                         default:
1538                             goto next;
1539                         }
1540                     }
1541                 next:
1542                     if (*p != '\0' && !isspace(*p)) {
1543                         term_printf("invalid char in format: '%c'\n", *p);
1544                         goto fail;
1545                     }
1546                     if (format < 0)
1547                         format = default_fmt_format;
1548                     if (format != 'i') {
1549                         /* for 'i', not specifying a size gives -1 as size */
1550                         if (size < 0)
1551                             size = default_fmt_size;
1552                     }
1553                     default_fmt_size = size;
1554                     default_fmt_format = format;
1555                 } else {
1556                     count = 1;
1557                     format = default_fmt_format;
1558                     if (format != 'i') {
1559                         size = default_fmt_size;
1560                     } else {
1561                         size = -1;
1562                     }
1563                 }
1564                 if (nb_args + 3 > MAX_ARGS)
1565                     goto error_args;
1566                 args[nb_args++] = (void*)count;
1567                 args[nb_args++] = (void*)format;
1568                 args[nb_args++] = (void*)size;
1569             }
1570             break;
1571         case 'i':
1572             {
1573                 int val;
1574                 while (isspace(*p)) 
1575                     p++;
1576                 if (*typestr == '?' || *typestr == '.') {
1577                     typestr++;
1578                     if (*typestr == '?') {
1579                         if (*p == '\0')
1580                             has_arg = 0;
1581                         else
1582                             has_arg = 1;
1583                     } else {
1584                         if (*p == '.') {
1585                             p++;
1586                             while (isspace(*p)) 
1587                                 p++;
1588                             has_arg = 1;
1589                         } else {
1590                             has_arg = 0;
1591                         }
1592                     }
1593                     if (nb_args >= MAX_ARGS)
1594                         goto error_args;
1595                     args[nb_args++] = (void *)has_arg;
1596                     if (!has_arg) {
1597                         if (nb_args >= MAX_ARGS)
1598                             goto error_args;
1599                         val = -1;
1600                         goto add_num;
1601                     }
1602                 }
1603                 if (get_expr(&val, &p))
1604                     goto fail;
1605             add_num:
1606                 if (nb_args >= MAX_ARGS)
1607                     goto error_args;
1608                 args[nb_args++] = (void *)val;
1609             }
1610             break;
1611         case '-':
1612             {
1613                 int has_option;
1614                 /* option */
1615                 
1616                 c = *typestr++;
1617                 if (c == '\0')
1618                     goto bad_type;
1619                 while (isspace(*p)) 
1620                     p++;
1621                 has_option = 0;
1622                 if (*p == '-') {
1623                     p++;
1624                     if (*p != c) {
1625                         term_printf("%s: unsupported option -%c\n", 
1626                                     cmdname, *p);
1627                         goto fail;
1628                     }
1629                     p++;
1630                     has_option = 1;
1631                 }
1632                 if (nb_args >= MAX_ARGS)
1633                     goto error_args;
1634                 args[nb_args++] = (void *)has_option;
1635             }
1636             break;
1637         default:
1638         bad_type:
1639             term_printf("%s: unknown type '%c'\n", cmdname, c);
1640             goto fail;
1641         }
1642     }
1643     /* check that all arguments were parsed */
1644     while (isspace(*p))
1645         p++;
1646     if (*p != '\0') {
1647         term_printf("%s: extraneous characters at the end of line\n", 
1648                     cmdname);
1649         goto fail;
1650     }
1651
1652     switch(nb_args) {
1653     case 0:
1654         cmd->handler();
1655         break;
1656     case 1:
1657         cmd->handler(args[0]);
1658         break;
1659     case 2:
1660         cmd->handler(args[0], args[1]);
1661         break;
1662     case 3:
1663         cmd->handler(args[0], args[1], args[2]);
1664         break;
1665     case 4:
1666         cmd->handler(args[0], args[1], args[2], args[3]);
1667         break;
1668     case 5:
1669         cmd->handler(args[0], args[1], args[2], args[3], args[4]);
1670         break;
1671     case 6:
1672         cmd->handler(args[0], args[1], args[2], args[3], args[4], args[5]);
1673         break;
1674     default:
1675         term_printf("unsupported number of arguments: %d\n", nb_args);
1676         goto fail;
1677     }
1678  fail:
1679     for(i = 0; i < MAX_ARGS; i++)
1680         qemu_free(str_allocated[i]);
1681     return;
1682 }
1683
1684 static void cmd_completion(const char *name, const char *list)
1685 {
1686     const char *p, *pstart;
1687     char cmd[128];
1688     int len;
1689
1690     p = list;
1691     for(;;) {
1692         pstart = p;
1693         p = strchr(p, '|');
1694         if (!p)
1695             p = pstart + strlen(pstart);
1696         len = p - pstart;
1697         if (len > sizeof(cmd) - 2)
1698             len = sizeof(cmd) - 2;
1699         memcpy(cmd, pstart, len);
1700         cmd[len] = '\0';
1701         if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
1702             add_completion(cmd);
1703         }
1704         if (*p == '\0')
1705             break;
1706         p++;
1707     }
1708 }
1709
1710 static void file_completion(const char *input)
1711 {
1712     DIR *ffs;
1713     struct dirent *d;
1714     char path[1024];
1715     char file[1024], file_prefix[1024];
1716     int input_path_len;
1717     const char *p;
1718
1719     p = strrchr(input, '/'); 
1720     if (!p) {
1721         input_path_len = 0;
1722         pstrcpy(file_prefix, sizeof(file_prefix), input);
1723         strcpy(path, ".");
1724     } else {
1725         input_path_len = p - input + 1;
1726         memcpy(path, input, input_path_len);
1727         if (input_path_len > sizeof(path) - 1)
1728             input_path_len = sizeof(path) - 1;
1729         path[input_path_len] = '\0';
1730         pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
1731     }
1732 #ifdef DEBUG_COMPLETION
1733     term_printf("input='%s' path='%s' prefix='%s'\n", input, path, file_prefix);
1734 #endif
1735     ffs = opendir(path);
1736     if (!ffs)
1737         return;
1738     for(;;) {
1739         struct stat sb;
1740         d = readdir(ffs);
1741         if (!d)
1742             break;
1743         if (strstart(d->d_name, file_prefix, NULL)) {
1744             memcpy(file, input, input_path_len);
1745             strcpy(file + input_path_len, d->d_name);
1746             /* stat the file to find out if it's a directory.
1747              * In that case add a slash to speed up typing long paths
1748              */
1749             stat(file, &sb);
1750             if(S_ISDIR(sb.st_mode))
1751                 strcat(file, "/");
1752             add_completion(file);
1753         }
1754     }
1755     closedir(ffs);
1756 }
1757
1758 static void block_completion_it(void *opaque, const char *name)
1759 {
1760     const char *input = opaque;
1761
1762     if (input[0] == '\0' ||
1763         !strncmp(name, (char *)input, strlen(input))) {
1764         add_completion(name);
1765     }
1766 }
1767
1768 /* NOTE: this parser is an approximate form of the real command parser */
1769 static void parse_cmdline(const char *cmdline,
1770                          int *pnb_args, char **args)
1771 {
1772     const char *p;
1773     int nb_args, ret;
1774     char buf[1024];
1775
1776     p = cmdline;
1777     nb_args = 0;
1778     for(;;) {
1779         while (isspace(*p))
1780             p++;
1781         if (*p == '\0')
1782             break;
1783         if (nb_args >= MAX_ARGS)
1784             break;
1785         ret = get_str(buf, sizeof(buf), &p);
1786         args[nb_args] = qemu_strdup(buf);
1787         nb_args++;
1788         if (ret < 0)
1789             break;
1790     }
1791     *pnb_args = nb_args;
1792 }
1793
1794 void readline_find_completion(const char *cmdline)
1795 {
1796     const char *cmdname;
1797     char *args[MAX_ARGS];
1798     int nb_args, i, len;
1799     const char *ptype, *str;
1800     term_cmd_t *cmd;
1801
1802     parse_cmdline(cmdline, &nb_args, args);
1803 #ifdef DEBUG_COMPLETION
1804     for(i = 0; i < nb_args; i++) {
1805         term_printf("arg%d = '%s'\n", i, (char *)args[i]);
1806     }
1807 #endif
1808
1809     /* if the line ends with a space, it means we want to complete the
1810        next arg */
1811     len = strlen(cmdline);
1812     if (len > 0 && isspace(cmdline[len - 1])) {
1813         if (nb_args >= MAX_ARGS)
1814             return;
1815         args[nb_args++] = qemu_strdup("");
1816     }
1817     if (nb_args <= 1) {
1818         /* command completion */
1819         if (nb_args == 0)
1820             cmdname = "";
1821         else
1822             cmdname = args[0];
1823         completion_index = strlen(cmdname);
1824         for(cmd = term_cmds; cmd->name != NULL; cmd++) {
1825             cmd_completion(cmdname, cmd->name);
1826         }
1827     } else {
1828         /* find the command */
1829         for(cmd = term_cmds; cmd->name != NULL; cmd++) {
1830             if (compare_cmd(args[0], cmd->name))
1831                 goto found;
1832         }
1833         return;
1834     found:
1835         ptype = cmd->args_type;
1836         for(i = 0; i < nb_args - 2; i++) {
1837             if (*ptype != '\0') {
1838                 ptype++;
1839                 while (*ptype == '?')
1840                     ptype++;
1841             }
1842         }
1843         str = args[nb_args - 1];
1844         switch(*ptype) {
1845         case 'F':
1846             /* file completion */
1847             completion_index = strlen(str);
1848             file_completion(str);
1849             break;
1850         case 'B':
1851             /* block device name completion */
1852             completion_index = strlen(str);
1853             bdrv_iterate(block_completion_it, (void *)str);
1854             break;
1855         default:
1856             break;
1857         }
1858     }
1859     for(i = 0; i < nb_args; i++)
1860         qemu_free(args[i]);
1861 }
1862
1863 static int term_can_read(void *opaque)
1864 {
1865     return 128;
1866 }
1867
1868 static void term_read(void *opaque, const uint8_t *buf, int size)
1869 {
1870     int i;
1871     for(i = 0; i < size; i++)
1872         readline_handle_byte(buf[i]);
1873 }
1874
1875 static void monitor_start_input(void);
1876
1877 static void monitor_handle_command1(void *opaque, const char *cmdline)
1878 {
1879     monitor_handle_command(cmdline);
1880     monitor_start_input();
1881 }
1882
1883 static void monitor_start_input(void)
1884 {
1885     readline_start("(qemu) ", 0, monitor_handle_command1, NULL);
1886 }
1887
1888 void monitor_init(CharDriverState *hd, int show_banner)
1889 {
1890     monitor_hd = hd;
1891     if (show_banner) {
1892         term_printf("QEMU %s monitor - type 'help' for more information\n",
1893                     QEMU_VERSION);
1894     }
1895     qemu_chr_add_read_handler(hd, term_can_read, term_read, NULL);
1896     monitor_start_input();
1897 }
1898
1899 /* XXX: use threads ? */
1900 /* modal monitor readline */
1901 static int monitor_readline_started;
1902 static char *monitor_readline_buf;
1903 static int monitor_readline_buf_size;
1904
1905 static void monitor_readline_cb(void *opaque, const char *input)
1906 {
1907     pstrcpy(monitor_readline_buf, monitor_readline_buf_size, input);
1908     monitor_readline_started = 0;
1909 }
1910
1911 void monitor_readline(const char *prompt, int is_password,
1912                       char *buf, int buf_size)
1913 {
1914     if (is_password) {
1915         qemu_chr_send_event(monitor_hd, CHR_EVENT_FOCUS);
1916     }
1917     readline_start(prompt, is_password, monitor_readline_cb, NULL);
1918     monitor_readline_buf = buf;
1919     monitor_readline_buf_size = buf_size;
1920     monitor_readline_started = 1;
1921     while (monitor_readline_started) {
1922         main_loop_wait(10);
1923     }
1924 }