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