2dc94b44a7086e2e0bcb261ea711531fa5f605a2
[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
27 //#define DEBUG
28
29 #ifndef offsetof
30 #define offsetof(type, field) ((size_t) &((type *)0)->field)
31 #endif
32
33 #define TERM_CMD_BUF_SIZE 4095
34 #define TERM_MAX_CMDS 64
35
36 #define IS_NORM 0
37 #define IS_ESC  1
38 #define IS_CSI  2
39
40 #define printf do_not_use_printf
41
42 static char term_cmd_buf[TERM_CMD_BUF_SIZE + 1];
43 static int term_cmd_buf_index;
44 static int term_cmd_buf_size;
45 static int term_esc_state;
46 static int term_esc_param;
47
48 static char *term_history[TERM_MAX_CMDS];
49 static int term_hist_entry;
50
51 /*
52  * Supported types:
53  * 
54  * 'F'          filename
55  * 's'          string (accept optional quote)
56  * 'i'          integer
57  * '/'          optional gdb-like print format (like "/10x")
58  *
59  * '?'          optional type (for 'F', 's' and 'i')
60  *
61  */
62
63 typedef struct term_cmd_t {
64     const char *name;
65     const char *args_type;
66     void (*handler)();
67     const char *params;
68     const char *help;
69 } term_cmd_t;
70
71 static term_cmd_t term_cmds[];
72 static term_cmd_t info_cmds[];
73
74 void term_printf(const char *fmt, ...)
75 {
76     va_list ap;
77     va_start(ap, fmt);
78     vprintf(fmt, ap);
79     va_end(ap);
80 }
81
82 void term_flush(void)
83 {
84     fflush(stdout);
85 }
86
87 static int compare_cmd(const char *name, const char *list)
88 {
89     const char *p, *pstart;
90     int len;
91     len = strlen(name);
92     p = list;
93     for(;;) {
94         pstart = p;
95         p = strchr(p, '|');
96         if (!p)
97             p = pstart + strlen(pstart);
98         if ((p - pstart) == len && !memcmp(pstart, name, len))
99             return 1;
100         if (*p == '\0')
101             break;
102         p++;
103     }
104     return 0;
105 }
106
107 static void help_cmd1(term_cmd_t *cmds, const char *prefix, const char *name)
108 {
109     term_cmd_t *cmd;
110
111     for(cmd = cmds; cmd->name != NULL; cmd++) {
112         if (!name || !strcmp(name, cmd->name))
113             term_printf("%s%s %s -- %s\n", prefix, cmd->name, cmd->params, cmd->help);
114     }
115 }
116
117 static void help_cmd(const char *name)
118 {
119     if (name && !strcmp(name, "info")) {
120         help_cmd1(info_cmds, "info ", NULL);
121     } else {
122         help_cmd1(term_cmds, "", name);
123         if (name && !strcmp(name, "log")) {
124             CPULogItem *item;
125             term_printf("Log items (comma separated):\n");
126             term_printf("%-10s %s\n", "none", "remove all logs");
127             for(item = cpu_log_items; item->mask != 0; item++) {
128                 term_printf("%-10s %s\n", item->name, item->help);
129             }
130         }
131     }
132 }
133
134 static void do_help(const char *name)
135 {
136     help_cmd(name);
137 }
138
139 static void do_commit(void)
140 {
141     int i;
142
143     for (i = 0; i < MAX_DISKS; i++) {
144         if (bs_table[i])
145             bdrv_commit(bs_table[i]);
146     }
147 }
148
149 static void do_info(const char *item)
150 {
151     term_cmd_t *cmd;
152
153     if (!item)
154         goto help;
155     for(cmd = info_cmds; cmd->name != NULL; cmd++) {
156         if (compare_cmd(item, cmd->name)) 
157             goto found;
158     }
159  help:
160     help_cmd("info");
161     return;
162  found:
163     cmd->handler();
164 }
165
166 static void do_info_network(void)
167 {
168     int i, j;
169     NetDriverState *nd;
170     
171     for(i = 0; i < nb_nics; i++) {
172         nd = &nd_table[i];
173         term_printf("%d: ifname=%s macaddr=", i, nd->ifname);
174         for(j = 0; j < 6; j++) {
175             if (j > 0)
176                 term_printf(":");
177             term_printf("%02x", nd->macaddr[j]);
178         }
179         term_printf("\n");
180     }
181 }
182  
183 static void do_info_block(void)
184 {
185     bdrv_info();
186 }
187
188 static void do_info_registers(void)
189 {
190 #ifdef TARGET_I386
191     cpu_dump_state(cpu_single_env, stdout, X86_DUMP_FPU | X86_DUMP_CCOP);
192 #else
193     cpu_dump_state(cpu_single_env, stdout, 0);
194 #endif
195 }
196
197 static void do_info_history (void)
198 {
199     int i;
200
201     for (i = 0; i < TERM_MAX_CMDS; i++) {
202         if (term_history[i] == NULL)
203             break;
204         term_printf("%d: '%s'\n", i, term_history[i]);
205     }
206 }
207
208 static void do_quit(void)
209 {
210     exit(0);
211 }
212
213 static int eject_device(BlockDriverState *bs, int force)
214 {
215     if (bdrv_is_inserted(bs)) {
216         if (!force) {
217             if (!bdrv_is_removable(bs)) {
218                 term_printf("device is not removable\n");
219                 return -1;
220             }
221             if (bdrv_is_locked(bs)) {
222                 term_printf("device is locked\n");
223                 return -1;
224             }
225         }
226         bdrv_close(bs);
227     }
228     return 0;
229 }
230
231 static void do_eject(int force, const char *filename)
232 {
233     BlockDriverState *bs;
234
235     term_printf("%d %s\n", force, filename);
236
237     bs = bdrv_find(filename);
238     if (!bs) {
239         term_printf("device not found\n");
240         return;
241     }
242     eject_device(bs, force);
243 }
244
245 static void do_change(const char *device, const char *filename)
246 {
247     BlockDriverState *bs;
248
249     bs = bdrv_find(device);
250     if (!bs) {
251         term_printf("device not found\n");
252         return;
253     }
254     if (eject_device(bs, 0) < 0)
255         return;
256     bdrv_open(bs, filename, 0);
257 }
258
259 static void do_screen_dump(const char *filename)
260 {
261     vga_screen_dump(filename);
262 }
263
264 static void do_log(const char *items)
265 {
266     int mask;
267     
268     if (!strcmp(items, "none")) {
269         mask = 0;
270     } else {
271         mask = cpu_str_to_log_mask(items);
272         if (!mask) {
273             help_cmd("log");
274             return;
275         }
276     }
277     cpu_set_log(mask);
278 }
279
280 static void do_savevm(const char *filename)
281 {
282     if (qemu_savevm(filename) < 0)
283         term_printf("I/O error when saving VM to '%s'\n", filename);
284 }
285
286 static void do_loadvm(const char *filename)
287 {
288     if (qemu_loadvm(filename) < 0) 
289         term_printf("I/O error when loading VM from '%s'\n", filename);
290 }
291
292 static void do_stop(void)
293 {
294     vm_stop(EXCP_INTERRUPT);
295 }
296
297 static void do_cont(void)
298 {
299     vm_start();
300 }
301
302 #ifdef CONFIG_GDBSTUB
303 static void do_gdbserver(int has_port, int port)
304 {
305     if (!has_port)
306         port = DEFAULT_GDBSTUB_PORT;
307     if (gdbserver_start(port) < 0) {
308         qemu_printf("Could not open gdbserver socket on port %d\n", port);
309     } else {
310         qemu_printf("Waiting gdb connection on port %d\n", port);
311     }
312 }
313 #endif
314
315 static void term_printc(int c)
316 {
317     term_printf("'");
318     switch(c) {
319     case '\'':
320         term_printf("\\'");
321         break;
322     case '\\':
323         term_printf("\\\\");
324         break;
325     case '\n':
326         term_printf("\\n");
327         break;
328     case '\r':
329         term_printf("\\r");
330         break;
331     default:
332         if (c >= 32 && c <= 126) {
333             term_printf("%c", c);
334         } else {
335             term_printf("\\x%02x", c);
336         }
337         break;
338     }
339     term_printf("'");
340 }
341
342 static void memory_dump(int count, int format, int wsize, 
343                         target_ulong addr, int is_physical)
344 {
345     int nb_per_line, l, line_size, i, max_digits, len;
346     uint8_t buf[16];
347     uint64_t v;
348
349     if (format == 'i') {
350         int flags;
351         flags = 0;
352 #ifdef TARGET_I386
353         if (wsize == 2) {
354             flags = 1;
355         } else if (wsize == 4) {
356             flags = 0;
357         } else {
358             /* as default we use the current CS size */
359             flags = 0;
360             if (!(cpu_single_env->segs[R_CS].flags & DESC_B_MASK))
361                 flags = 1;
362         }
363 #endif
364         monitor_disas(addr, count, is_physical, flags);
365         return;
366     }
367
368     len = wsize * count;
369     if (wsize == 1)
370         line_size = 8;
371     else
372         line_size = 16;
373     nb_per_line = line_size / wsize;
374     max_digits = 0;
375
376     switch(format) {
377     case 'o':
378         max_digits = (wsize * 8 + 2) / 3;
379         break;
380     default:
381     case 'x':
382         max_digits = (wsize * 8) / 4;
383         break;
384     case 'u':
385     case 'd':
386         max_digits = (wsize * 8 * 10 + 32) / 33;
387         break;
388     case 'c':
389         wsize = 1;
390         break;
391     }
392
393     while (len > 0) {
394         term_printf("0x%08x:", addr);
395         l = len;
396         if (l > line_size)
397             l = line_size;
398         if (is_physical) {
399             cpu_physical_memory_rw(addr, buf, l, 0);
400         } else {
401             cpu_memory_rw_debug(cpu_single_env, addr, buf, l, 0);
402         }
403         i = 0; 
404         while (i < l) {
405             switch(wsize) {
406             default:
407             case 1:
408                 v = ldub_raw(buf + i);
409                 break;
410             case 2:
411                 v = lduw_raw(buf + i);
412                 break;
413             case 4:
414                 v = ldl_raw(buf + i);
415                 break;
416             case 8:
417                 v = ldq_raw(buf + i);
418                 break;
419             }
420             term_printf(" ");
421             switch(format) {
422             case 'o':
423                 term_printf("%#*llo", max_digits, v);
424                 break;
425             case 'x':
426                 term_printf("0x%0*llx", max_digits, v);
427                 break;
428             case 'u':
429                 term_printf("%*llu", max_digits, v);
430                 break;
431             case 'd':
432                 term_printf("%*lld", max_digits, v);
433                 break;
434             case 'c':
435                 term_printc(v);
436                 break;
437             }
438             i += wsize;
439         }
440         term_printf("\n");
441         addr += l;
442         len -= l;
443     }
444 }
445
446 static void do_memory_dump(int count, int format, int size, int addr)
447 {
448     memory_dump(count, format, size, addr, 0);
449 }
450
451 static void do_physical_memory_dump(int count, int format, int size, int addr)
452 {
453     memory_dump(count, format, size, addr, 1);
454 }
455
456 static void do_print(int count, int format, int size, int val)
457 {
458     switch(format) {
459     case 'o':
460         term_printf("%#o", val);
461         break;
462     case 'x':
463         term_printf("%#x", val);
464         break;
465     case 'u':
466         term_printf("%u", val);
467         break;
468     default:
469     case 'd':
470         term_printf("%d", val);
471         break;
472     case 'c':
473         term_printc(val);
474         break;
475     }
476     term_printf("\n");
477 }
478
479 static term_cmd_t term_cmds[] = {
480     { "help|?", "s?", do_help, 
481       "[cmd]", "show the help" },
482     { "commit", "", do_commit, 
483       "", "commit changes to the disk images (if -snapshot is used)" },
484     { "info", "s?", do_info,
485       "subcommand", "show various information about the system state" },
486     { "q|quit", "", do_quit,
487       "", "quit the emulator" },
488     { "eject", "-fs", do_eject,
489       "[-f] device", "eject a removable media (use -f to force it)" },
490     { "change", "sF", do_change,
491       "device filename", "change a removable media" },
492     { "screendump", "F", do_screen_dump, 
493       "filename", "save screen into PPM image 'filename'" },
494     { "log", "s", do_log,
495       "item1[,...]", "activate logging of the specified items to '/tmp/qemu.log'" }, 
496     { "savevm", "F", do_savevm,
497       "filename", "save the whole virtual machine state to 'filename'" }, 
498     { "loadvm", "F", do_loadvm,
499       "filename", "restore the whole virtual machine state from 'filename'" }, 
500     { "stop", "", do_stop, 
501       "", "stop emulation", },
502     { "c|cont", "", do_cont, 
503       "", "resume emulation", },
504 #ifdef CONFIG_GDBSTUB
505     { "gdbserver", "i?", do_gdbserver, 
506       "[port]", "start gdbserver session (default port=1234)", },
507 #endif
508     { "x", "/i", do_memory_dump, 
509       "/fmt addr", "virtual memory dump starting at 'addr'", },
510     { "xp", "/i", do_physical_memory_dump, 
511       "/fmt addr", "physical memory dump starting at 'addr'", },
512     { "p|print", "/i", do_print, 
513       "/fmt expr", "print expression value (use $reg for CPU register access)", },
514     { NULL, NULL, }, 
515 };
516
517 static term_cmd_t info_cmds[] = {
518     { "network", "", do_info_network,
519       "", "show the network state" },
520     { "block", "", do_info_block,
521       "", "show the block devices" },
522     { "registers", "", do_info_registers,
523       "", "show the cpu registers" },
524     { "history", "", do_info_history,
525       "", "show the command line history", },
526     { "pic", "", pic_info,
527       "", "show i8259 (PIC) state", },
528     { "pci", "", pci_info,
529       "", "show PCI info", },
530     { NULL, NULL, },
531 };
532
533 /*******************************************************************/
534
535 static const char *pch;
536 static jmp_buf expr_env;
537
538 typedef struct MonitorDef {
539     const char *name;
540     int offset;
541     int (*get_value)(struct MonitorDef *md);
542 } MonitorDef;
543
544 #if defined(TARGET_I386)
545 static int monitor_get_pc (struct MonitorDef *md)
546 {
547     return cpu_single_env->eip + (long)cpu_single_env->segs[R_CS].base;
548 }
549 #endif
550
551 #if defined(TARGET_PPC)
552 static int monitor_get_ccr (struct MonitorDef *md)
553 {
554     unsigned int u;
555     int i;
556
557     u = 0;
558     for (i = 0; i < 8; i++)
559         u |= cpu_single_env->crf[i] << (32 - (4 * i));
560
561     return u;
562 }
563
564 static int monitor_get_msr (struct MonitorDef *md)
565 {
566     return (cpu_single_env->msr[MSR_POW] << MSR_POW) |
567         (cpu_single_env->msr[MSR_ILE] << MSR_ILE) |
568         (cpu_single_env->msr[MSR_EE] << MSR_EE) |
569         (cpu_single_env->msr[MSR_PR] << MSR_PR) |
570         (cpu_single_env->msr[MSR_FP] << MSR_FP) |
571         (cpu_single_env->msr[MSR_ME] << MSR_ME) |
572         (cpu_single_env->msr[MSR_FE0] << MSR_FE0) |
573         (cpu_single_env->msr[MSR_SE] << MSR_SE) |
574         (cpu_single_env->msr[MSR_BE] << MSR_BE) |
575         (cpu_single_env->msr[MSR_FE1] << MSR_FE1) |
576         (cpu_single_env->msr[MSR_IP] << MSR_IP) |
577         (cpu_single_env->msr[MSR_IR] << MSR_IR) |
578         (cpu_single_env->msr[MSR_DR] << MSR_DR) |
579         (cpu_single_env->msr[MSR_RI] << MSR_RI) |
580         (cpu_single_env->msr[MSR_LE] << MSR_LE);
581 }
582
583 static int monitor_get_xer (struct MonitorDef *md)
584 {
585     return (cpu_single_env->xer[XER_SO] << XER_SO) |
586         (cpu_single_env->xer[XER_OV] << XER_OV) |
587         (cpu_single_env->xer[XER_CA] << XER_CA) |
588         (cpu_single_env->xer[XER_BC] << XER_BC);
589 }
590 #endif
591
592 static MonitorDef monitor_defs[] = {
593 #ifdef TARGET_I386
594
595 #define SEG(name, seg) \
596     { name, offsetof(CPUState, segs[seg].selector) },\
597     { name ".base", offsetof(CPUState, segs[seg].base) },\
598     { name ".limit", offsetof(CPUState, segs[seg].limit) },
599
600     { "eax", offsetof(CPUState, regs[0]) },
601     { "ecx", offsetof(CPUState, regs[1]) },
602     { "edx", offsetof(CPUState, regs[2]) },
603     { "ebx", offsetof(CPUState, regs[3]) },
604     { "esp|sp", offsetof(CPUState, regs[4]) },
605     { "ebp|fp", offsetof(CPUState, regs[5]) },
606     { "esi", offsetof(CPUState, regs[6]) },
607     { "esi", offsetof(CPUState, regs[7]) },
608     { "eflags", offsetof(CPUState, eflags) },
609     { "eip", offsetof(CPUState, eip) },
610     SEG("cs", R_CS)
611     SEG("ds", R_DS)
612     SEG("es", R_ES)
613     SEG("fs", R_FS)
614     SEG("gs", R_GS)
615     { "pc", 0, monitor_get_pc, },
616 #elif defined(TARGET_PPC)
617     { "r0", offsetof(CPUState, gpr[0]) },
618     { "r1", offsetof(CPUState, gpr[1]) },
619     { "r2", offsetof(CPUState, gpr[2]) },
620     { "r3", offsetof(CPUState, gpr[3]) },
621     { "r4", offsetof(CPUState, gpr[4]) },
622     { "r5", offsetof(CPUState, gpr[5]) },
623     { "r6", offsetof(CPUState, gpr[6]) },
624     { "r7", offsetof(CPUState, gpr[7]) },
625     { "r8", offsetof(CPUState, gpr[8]) },
626     { "r9", offsetof(CPUState, gpr[9]) },
627     { "r10", offsetof(CPUState, gpr[10]) },
628     { "r11", offsetof(CPUState, gpr[11]) },
629     { "r12", offsetof(CPUState, gpr[12]) },
630     { "r13", offsetof(CPUState, gpr[13]) },
631     { "r14", offsetof(CPUState, gpr[14]) },
632     { "r15", offsetof(CPUState, gpr[15]) },
633     { "r16", offsetof(CPUState, gpr[16]) },
634     { "r17", offsetof(CPUState, gpr[17]) },
635     { "r18", offsetof(CPUState, gpr[18]) },
636     { "r19", offsetof(CPUState, gpr[19]) },
637     { "r20", offsetof(CPUState, gpr[20]) },
638     { "r21", offsetof(CPUState, gpr[21]) },
639     { "r22", offsetof(CPUState, gpr[22]) },
640     { "r23", offsetof(CPUState, gpr[23]) },
641     { "r24", offsetof(CPUState, gpr[24]) },
642     { "r25", offsetof(CPUState, gpr[25]) },
643     { "r26", offsetof(CPUState, gpr[26]) },
644     { "r27", offsetof(CPUState, gpr[27]) },
645     { "r28", offsetof(CPUState, gpr[28]) },
646     { "r29", offsetof(CPUState, gpr[29]) },
647     { "r30", offsetof(CPUState, gpr[30]) },
648     { "r31", offsetof(CPUState, gpr[31]) },
649     { "nip|pc", offsetof(CPUState, nip) },
650     { "lr", offsetof(CPUState, lr) },
651     { "ctr", offsetof(CPUState, ctr) },
652     { "decr", offsetof(CPUState, decr) },
653     { "ccr", 0, &monitor_get_ccr, },
654     { "msr", 0, &monitor_get_msr, },
655     { "xer", 0, &monitor_get_xer, },
656     { "tbu", offsetof(CPUState, tb[0]) },
657     { "tbl", offsetof(CPUState, tb[1]) },
658     { "sdr1", offsetof(CPUState, sdr1) },
659     { "sr0", offsetof(CPUState, sr[0]) },
660     { "sr1", offsetof(CPUState, sr[1]) },
661     { "sr2", offsetof(CPUState, sr[2]) },
662     { "sr3", offsetof(CPUState, sr[3]) },
663     { "sr4", offsetof(CPUState, sr[4]) },
664     { "sr5", offsetof(CPUState, sr[5]) },
665     { "sr6", offsetof(CPUState, sr[6]) },
666     { "sr7", offsetof(CPUState, sr[7]) },
667     { "sr8", offsetof(CPUState, sr[8]) },
668     { "sr9", offsetof(CPUState, sr[9]) },
669     { "sr10", offsetof(CPUState, sr[10]) },
670     { "sr11", offsetof(CPUState, sr[11]) },
671     { "sr12", offsetof(CPUState, sr[12]) },
672     { "sr13", offsetof(CPUState, sr[13]) },
673     { "sr14", offsetof(CPUState, sr[14]) },
674     { "sr15", offsetof(CPUState, sr[15]) },
675     /* Too lazy to put BATs and SPRs ... */
676 #endif
677     { NULL },
678 };
679
680 static void expr_error(const char *fmt) 
681 {
682     term_printf(fmt);
683     term_printf("\n");
684     longjmp(expr_env, 1);
685 }
686
687 static int get_monitor_def(int *pval, const char *name)
688 {
689     MonitorDef *md;
690     for(md = monitor_defs; md->name != NULL; md++) {
691         if (compare_cmd(name, md->name)) {
692             if (md->get_value) {
693                 *pval = md->get_value(md);
694             } else {
695                 *pval = *(uint32_t *)((uint8_t *)cpu_single_env + md->offset);
696             }
697             return 0;
698         }
699     }
700     return -1;
701 }
702
703 static void next(void)
704 {
705     if (pch != '\0') {
706         pch++;
707         while (isspace(*pch))
708             pch++;
709     }
710 }
711
712 static int expr_sum(void);
713
714 static int expr_unary(void)
715 {
716     int n;
717     char *p;
718
719     switch(*pch) {
720     case '+':
721         next();
722         n = expr_unary();
723         break;
724     case '-':
725         next();
726         n = -expr_unary();
727         break;
728     case '~':
729         next();
730         n = ~expr_unary();
731         break;
732     case '(':
733         next();
734         n = expr_sum();
735         if (*pch != ')') {
736             expr_error("')' expected");
737         }
738         next();
739         break;
740     case '$':
741         {
742             char buf[128], *q;
743             
744             pch++;
745             q = buf;
746             while ((*pch >= 'a' && *pch <= 'z') ||
747                    (*pch >= 'A' && *pch <= 'Z') ||
748                    (*pch >= '0' && *pch <= '9') ||
749                    *pch == '_' || *pch == '.') {
750                 if ((q - buf) < sizeof(buf) - 1)
751                     *q++ = *pch;
752                 pch++;
753             }
754             while (isspace(*pch))
755                 pch++;
756             *q = 0;
757             if (get_monitor_def(&n, buf))
758                 expr_error("unknown register");
759         }
760         break;
761     case '\0':
762         expr_error("unexpected end of expression");
763         n = 0;
764         break;
765     default:
766         n = strtoul(pch, &p, 0);
767         if (pch == p) {
768             expr_error("invalid char in expression");
769         }
770         pch = p;
771         while (isspace(*pch))
772             pch++;
773         break;
774     }
775     return n;
776 }
777
778
779 static int expr_prod(void)
780 {
781     int val, val2, op;
782
783     val = expr_unary();
784     for(;;) {
785         op = *pch;
786         if (op != '*' && op != '/' && op != '%')
787             break;
788         next();
789         val2 = expr_unary();
790         switch(op) {
791         default:
792         case '*':
793             val *= val2;
794             break;
795         case '/':
796         case '%':
797             if (val2 == 0) 
798                 expr_error("divison by zero");
799             if (op == '/')
800                 val /= val2;
801             else
802                 val %= val2;
803             break;
804         }
805     }
806     return val;
807 }
808
809 static int expr_logic(void)
810 {
811     int val, val2, op;
812
813     val = expr_prod();
814     for(;;) {
815         op = *pch;
816         if (op != '&' && op != '|' && op != '^')
817             break;
818         next();
819         val2 = expr_prod();
820         switch(op) {
821         default:
822         case '&':
823             val &= val2;
824             break;
825         case '|':
826             val |= val2;
827             break;
828         case '^':
829             val ^= val2;
830             break;
831         }
832     }
833     return val;
834 }
835
836 static int expr_sum(void)
837 {
838     int val, val2, op;
839
840     val = expr_logic();
841     for(;;) {
842         op = *pch;
843         if (op != '+' && op != '-')
844             break;
845         next();
846         val2 = expr_logic();
847         if (op == '+')
848             val += val2;
849         else
850             val -= val2;
851     }
852     return val;
853 }
854
855 static int get_expr(int *pval, const char **pp)
856 {
857     pch = *pp;
858     if (setjmp(expr_env)) {
859         *pp = pch;
860         return -1;
861     }
862     while (isspace(*pch))
863         pch++;
864     *pval = expr_sum();
865     *pp = pch;
866     return 0;
867 }
868
869 static int get_str(char *buf, int buf_size, const char **pp)
870 {
871     const char *p;
872     char *q;
873     int c;
874
875     p = *pp;
876     while (isspace(*p))
877         p++;
878     if (*p == '\0') {
879     fail:
880         *pp = p;
881         return -1;
882     }
883     q = buf;
884     if (*p == '\"') {
885         p++;
886         while (*p != '\0' && *p != '\"') {
887             if (*p == '\\') {
888                 p++;
889                 c = *p++;
890                 switch(c) {
891                 case 'n':
892                     c = '\n';
893                     break;
894                 case 'r':
895                     c = '\r';
896                     break;
897                 case '\\':
898                 case '\'':
899                 case '\"':
900                     break;
901                 default:
902                     qemu_printf("unsupported escape code: '\\%c'\n", c);
903                     goto fail;
904                 }
905                 if ((q - buf) < buf_size - 1) {
906                     *q++ = c;
907                 }
908             } else {
909                 if ((q - buf) < buf_size - 1) {
910                     *q++ = *p;
911                 }
912                 p++;
913             }
914         }
915         if (*p != '\"') {
916             qemu_printf("untermintated string\n");
917             goto fail;
918         }
919         p++;
920     } else {
921         while (*p != '\0' && !isspace(*p)) {
922             if ((q - buf) < buf_size - 1) {
923                 *q++ = *p;
924             }
925             p++;
926         }
927         *q = '\0';
928     }
929     *pp = p;
930     return 0;
931 }
932
933 static int default_fmt_format = 'x';
934 static int default_fmt_size = 4;
935
936 #define MAX_ARGS 16
937
938 static void term_handle_command(const char *cmdline)
939 {
940     const char *p, *pstart, *typestr;
941     char *q;
942     int c, nb_args, len, i, has_arg;
943     term_cmd_t *cmd;
944     char cmdname[256];
945     char buf[1024];
946     void *str_allocated[MAX_ARGS];
947     void *args[MAX_ARGS];
948
949 #ifdef DEBUG
950     term_printf("command='%s'\n", cmdline);
951 #endif
952     
953     /* extract the command name */
954     p = cmdline;
955     q = cmdname;
956     while (isspace(*p))
957         p++;
958     if (*p == '\0')
959         return;
960     pstart = p;
961     while (*p != '\0' && *p != '/' && !isspace(*p))
962         p++;
963     len = p - pstart;
964     if (len > sizeof(cmdname) - 1)
965         len = sizeof(cmdname) - 1;
966     memcpy(cmdname, pstart, len);
967     cmdname[len] = '\0';
968     
969     /* find the command */
970     for(cmd = term_cmds; cmd->name != NULL; cmd++) {
971         if (compare_cmd(cmdname, cmd->name)) 
972             goto found;
973     }
974     term_printf("unknown command: '%s'\n", cmdname);
975     return;
976  found:
977
978     for(i = 0; i < MAX_ARGS; i++)
979         str_allocated[i] = NULL;
980     
981     /* parse the parameters */
982     typestr = cmd->args_type;
983     nb_args = 0;
984     for(;;) {
985         c = *typestr;
986         if (c == '\0')
987             break;
988         typestr++;
989         switch(c) {
990         case 'F':
991         case 's':
992             {
993                 int ret;
994                 char *str;
995                 
996                 while (isspace(*p)) 
997                     p++;
998                 if (*typestr == '?') {
999                     typestr++;
1000                     if (*p == '\0') {
1001                         /* no optional string: NULL argument */
1002                         str = NULL;
1003                         goto add_str;
1004                     }
1005                 }
1006                 ret = get_str(buf, sizeof(buf), &p);
1007                 if (ret < 0) {
1008                     if (c == 'F')
1009                         term_printf("%s: filename expected\n", cmdname);
1010                     else
1011                         term_printf("%s: string expected\n", cmdname);
1012                     goto fail;
1013                 }
1014                 str = qemu_malloc(strlen(buf) + 1);
1015                 strcpy(str, buf);
1016                 str_allocated[nb_args] = str;
1017             add_str:
1018                 if (nb_args >= MAX_ARGS) {
1019                 error_args:
1020                     term_printf("%s: too many arguments\n", cmdname);
1021                     goto fail;
1022                 }
1023                 args[nb_args++] = str;
1024             }
1025             break;
1026         case '/':
1027             {
1028                 int count, format, size;
1029                 
1030                 while (isspace(*p))
1031                     p++;
1032                 if (*p == '/') {
1033                     /* format found */
1034                     p++;
1035                     count = 1;
1036                     if (isdigit(*p)) {
1037                         count = 0;
1038                         while (isdigit(*p)) {
1039                             count = count * 10 + (*p - '0');
1040                             p++;
1041                         }
1042                     }
1043                     size = -1;
1044                     format = -1;
1045                     for(;;) {
1046                         switch(*p) {
1047                         case 'o':
1048                         case 'd':
1049                         case 'u':
1050                         case 'x':
1051                         case 'i':
1052                         case 'c':
1053                             format = *p++;
1054                             break;
1055                         case 'b':
1056                             size = 1;
1057                             p++;
1058                             break;
1059                         case 'h':
1060                             size = 2;
1061                             p++;
1062                             break;
1063                         case 'w':
1064                             size = 4;
1065                             p++;
1066                             break;
1067                         case 'g':
1068                         case 'L':
1069                             size = 8;
1070                             p++;
1071                             break;
1072                         default:
1073                             goto next;
1074                         }
1075                     }
1076                 next:
1077                     if (*p != '\0' && !isspace(*p)) {
1078                         term_printf("invalid char in format: '%c'\n", *p);
1079                         goto fail;
1080                     }
1081                     if (format < 0)
1082                         format = default_fmt_format;
1083                     if (format != 'i') {
1084                         /* for 'i', not specifying a size gives -1 as size */
1085                         if (size < 0)
1086                             size = default_fmt_size;
1087                     }
1088                     default_fmt_size = size;
1089                     default_fmt_format = format;
1090                 } else {
1091                     count = 1;
1092                     format = default_fmt_format;
1093                     if (format != 'i') {
1094                         size = default_fmt_size;
1095                     } else {
1096                         size = -1;
1097                     }
1098                 }
1099                 if (nb_args + 3 > MAX_ARGS)
1100                     goto error_args;
1101                 args[nb_args++] = (void*)count;
1102                 args[nb_args++] = (void*)format;
1103                 args[nb_args++] = (void*)size;
1104             }
1105             break;
1106         case 'i':
1107             {
1108                 int val;
1109                 while (isspace(*p)) 
1110                     p++;
1111                 if (*typestr == '?') {
1112                     typestr++;
1113                     if (*p == '\0')
1114                         has_arg = 0;
1115                     else
1116                         has_arg = 1;
1117                     if (nb_args >= MAX_ARGS)
1118                         goto error_args;
1119                     args[nb_args++] = (void *)has_arg;
1120                     if (!has_arg) {
1121                         if (nb_args >= MAX_ARGS)
1122                             goto error_args;
1123                         val = -1;
1124                         goto add_num;
1125                     }
1126                 }
1127                 if (get_expr(&val, &p))
1128                     goto fail;
1129             add_num:
1130                 if (nb_args >= MAX_ARGS)
1131                     goto error_args;
1132                 args[nb_args++] = (void *)val;
1133             }
1134             break;
1135         case '-':
1136             {
1137                 int has_option;
1138                 /* option */
1139                 
1140                 c = *typestr++;
1141                 if (c == '\0')
1142                     goto bad_type;
1143                 while (isspace(*p)) 
1144                     p++;
1145                 has_option = 0;
1146                 if (*p == '-') {
1147                     p++;
1148                     if (*p != c) {
1149                         term_printf("%s: unsupported option -%c\n", 
1150                                     cmdname, *p);
1151                         goto fail;
1152                     }
1153                     p++;
1154                     has_option = 1;
1155                 }
1156                 if (nb_args >= MAX_ARGS)
1157                     goto error_args;
1158                 args[nb_args++] = (void *)has_option;
1159             }
1160             break;
1161         default:
1162         bad_type:
1163             term_printf("%s: unknown type '%c'\n", cmdname, c);
1164             goto fail;
1165         }
1166     }
1167     /* check that all arguments were parsed */
1168     while (isspace(*p))
1169         p++;
1170     if (*p != '\0') {
1171         term_printf("%s: extraneous characters at the end of line\n", 
1172                     cmdname);
1173         goto fail;
1174     }
1175
1176     switch(nb_args) {
1177     case 0:
1178         cmd->handler();
1179         break;
1180     case 1:
1181         cmd->handler(args[0]);
1182         break;
1183     case 2:
1184         cmd->handler(args[0], args[1]);
1185         break;
1186     case 3:
1187         cmd->handler(args[0], args[1], args[2]);
1188         break;
1189     case 4:
1190         cmd->handler(args[0], args[1], args[2], args[3]);
1191         break;
1192     case 5:
1193         cmd->handler(args[0], args[1], args[2], args[3], args[4]);
1194         break;
1195     default:
1196         term_printf("unsupported number of arguments: %d\n", nb_args);
1197         goto fail;
1198     }
1199  fail:
1200     for(i = 0; i < MAX_ARGS; i++)
1201         qemu_free(str_allocated[i]);
1202     return;
1203 }
1204
1205 static void term_show_prompt(void)
1206 {
1207     term_printf("(qemu) ");
1208     fflush(stdout);
1209     term_cmd_buf_index = 0;
1210     term_cmd_buf_size = 0;
1211     term_esc_state = IS_NORM;
1212 }
1213
1214 static void term_print_cmdline (const char *cmdline)
1215 {
1216     term_show_prompt();
1217     term_printf(cmdline);
1218     term_flush();
1219 }
1220
1221 static void term_insert_char(int ch)
1222 {
1223     if (term_cmd_buf_index < TERM_CMD_BUF_SIZE) {
1224         memmove(term_cmd_buf + term_cmd_buf_index + 1,
1225                 term_cmd_buf + term_cmd_buf_index,
1226                 term_cmd_buf_size - term_cmd_buf_index);
1227         term_cmd_buf[term_cmd_buf_index] = ch;
1228         term_cmd_buf_size++;
1229         term_printf("\033[@%c", ch);
1230         term_cmd_buf_index++;
1231         term_flush();
1232     }
1233 }
1234
1235 static void term_backward_char(void)
1236 {
1237     if (term_cmd_buf_index > 0) {
1238         term_cmd_buf_index--;
1239         term_printf("\033[D");
1240         term_flush();
1241     }
1242 }
1243
1244 static void term_forward_char(void)
1245 {
1246     if (term_cmd_buf_index < term_cmd_buf_size) {
1247         term_cmd_buf_index++;
1248         term_printf("\033[C");
1249         term_flush();
1250     }
1251 }
1252
1253 static void term_delete_char(void)
1254 {
1255     if (term_cmd_buf_index < term_cmd_buf_size) {
1256         memmove(term_cmd_buf + term_cmd_buf_index,
1257                 term_cmd_buf + term_cmd_buf_index + 1,
1258                 term_cmd_buf_size - term_cmd_buf_index - 1);
1259         term_printf("\033[P");
1260         term_cmd_buf_size--;
1261         term_flush();
1262     }
1263 }
1264
1265 static void term_backspace(void)
1266 {
1267     if (term_cmd_buf_index > 0) {
1268         term_backward_char();
1269         term_delete_char();
1270     }
1271 }
1272
1273 static void term_bol(void)
1274 {
1275     while (term_cmd_buf_index > 0)
1276         term_backward_char();
1277 }
1278
1279 static void term_eol(void)
1280 {
1281     while (term_cmd_buf_index < term_cmd_buf_size)
1282         term_forward_char();
1283 }
1284
1285 static void term_up_char(void)
1286 {
1287     int idx;
1288
1289     if (term_hist_entry == 0)
1290         return;
1291     if (term_hist_entry == -1) {
1292         /* Find latest entry */
1293         for (idx = 0; idx < TERM_MAX_CMDS; idx++) {
1294             if (term_history[idx] == NULL)
1295                 break;
1296         }
1297         term_hist_entry = idx;
1298     }
1299     term_hist_entry--;
1300     if (term_hist_entry >= 0) {
1301         strcpy(term_cmd_buf, term_history[term_hist_entry]);
1302         term_printf("\n");
1303         term_print_cmdline(term_cmd_buf);
1304         term_cmd_buf_index = term_cmd_buf_size = strlen(term_cmd_buf);
1305     }
1306 }
1307
1308 static void term_down_char(void)
1309 {
1310     if (term_hist_entry == TERM_MAX_CMDS - 1 || term_hist_entry == -1)
1311         return;
1312     if (term_history[++term_hist_entry] != NULL) {
1313         strcpy(term_cmd_buf, term_history[term_hist_entry]);
1314     } else {
1315         term_hist_entry = -1;
1316     }
1317     term_printf("\n");
1318     term_print_cmdline(term_cmd_buf);
1319     term_cmd_buf_index = term_cmd_buf_size = strlen(term_cmd_buf);
1320 }
1321
1322 static void term_hist_add(const char *cmdline)
1323 {
1324     char *hist_entry, *new_entry;
1325     int idx;
1326
1327     if (cmdline[0] == '\0')
1328         return;
1329     new_entry = NULL;
1330     if (term_hist_entry != -1) {
1331         /* We were editing an existing history entry: replace it */
1332         hist_entry = term_history[term_hist_entry];
1333         idx = term_hist_entry;
1334         if (strcmp(hist_entry, cmdline) == 0) {
1335             goto same_entry;
1336         }
1337     }
1338     /* Search cmdline in history buffers */
1339     for (idx = 0; idx < TERM_MAX_CMDS; idx++) {
1340         hist_entry = term_history[idx];
1341         if (hist_entry == NULL)
1342             break;
1343         if (strcmp(hist_entry, cmdline) == 0) {
1344         same_entry:
1345             new_entry = hist_entry;
1346             /* Put this entry at the end of history */
1347             memmove(&term_history[idx], &term_history[idx + 1],
1348                     &term_history[TERM_MAX_CMDS] - &term_history[idx + 1]);
1349             term_history[TERM_MAX_CMDS - 1] = NULL;
1350             for (; idx < TERM_MAX_CMDS; idx++) {
1351                 if (term_history[idx] == NULL)
1352                     break;
1353             }
1354             break;
1355         }
1356     }
1357     if (idx == TERM_MAX_CMDS) {
1358         /* Need to get one free slot */
1359         free(term_history[0]);
1360         memcpy(term_history, &term_history[1],
1361                &term_history[TERM_MAX_CMDS] - &term_history[1]);
1362         term_history[TERM_MAX_CMDS - 1] = NULL;
1363         idx = TERM_MAX_CMDS - 1;
1364     }
1365     if (new_entry == NULL)
1366         new_entry = strdup(cmdline);
1367     term_history[idx] = new_entry;
1368     term_hist_entry = -1;
1369 }
1370
1371 /* return true if command handled */
1372 static void term_handle_byte(int ch)
1373 {
1374     switch(term_esc_state) {
1375     case IS_NORM:
1376         switch(ch) {
1377         case 1:
1378             term_bol();
1379             break;
1380         case 5:
1381             term_eol();
1382             break;
1383         case 10:
1384         case 13:
1385             term_cmd_buf[term_cmd_buf_size] = '\0';
1386             term_hist_add(term_cmd_buf);
1387             term_printf("\n");
1388             term_handle_command(term_cmd_buf);
1389             term_show_prompt();
1390             break;
1391         case 27:
1392             term_esc_state = IS_ESC;
1393             break;
1394         case 127:
1395         case 8:
1396             term_backspace();
1397             break;
1398         case 155:
1399             term_esc_state = IS_CSI;
1400             break;
1401         default:
1402             if (ch >= 32) {
1403                 term_insert_char(ch);
1404             }
1405             break;
1406         }
1407         break;
1408     case IS_ESC:
1409         if (ch == '[') {
1410             term_esc_state = IS_CSI;
1411             term_esc_param = 0;
1412         } else {
1413             term_esc_state = IS_NORM;
1414         }
1415         break;
1416     case IS_CSI:
1417         switch(ch) {
1418         case 'A':
1419         case 'F':
1420             term_up_char();
1421             break;
1422         case 'B':
1423         case 'E':
1424             term_down_char();
1425             break;
1426         case 'D':
1427             term_backward_char();
1428             break;
1429         case 'C':
1430             term_forward_char();
1431             break;
1432         case '0' ... '9':
1433             term_esc_param = term_esc_param * 10 + (ch - '0');
1434             goto the_end;
1435         case '~':
1436             switch(term_esc_param) {
1437             case 1:
1438                 term_bol();
1439                 break;
1440             case 3:
1441                 term_delete_char();
1442                 break;
1443             case 4:
1444                 term_eol();
1445                 break;
1446             }
1447             break;
1448         default:
1449             break;
1450         }
1451         term_esc_state = IS_NORM;
1452     the_end:
1453         break;
1454     }
1455 }
1456
1457 /*************************************************************/
1458 /* serial console support */
1459
1460 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1461
1462 static int term_got_escape, term_command;
1463
1464 void term_print_help(void)
1465 {
1466     term_printf("\n"
1467                 "C-a h    print this help\n"
1468                 "C-a x    exit emulatior\n"
1469                 "C-a s    save disk data back to file (if -snapshot)\n"
1470                 "C-a b    send break (magic sysrq)\n"
1471                 "C-a c    switch between console and monitor\n"
1472                 "C-a C-a  send C-a\n"
1473                 );
1474 }
1475
1476 /* called when a char is received */
1477 static void term_received_byte(int ch)
1478 {
1479     if (!serial_console) {
1480         /* if no serial console, handle every command */
1481         term_handle_byte(ch);
1482     } else {
1483         if (term_got_escape) {
1484             term_got_escape = 0;
1485             switch(ch) {
1486             case 'h':
1487                 term_print_help();
1488                 break;
1489             case 'x':
1490                 exit(0);
1491                 break;
1492             case 's': 
1493                 {
1494                     int i;
1495                     for (i = 0; i < MAX_DISKS; i++) {
1496                         if (bs_table[i])
1497                             bdrv_commit(bs_table[i]);
1498                     }
1499                 }
1500                 break;
1501             case 'b':
1502                 if (serial_console)
1503                     serial_receive_break(serial_console);
1504                 break;
1505             case 'c':
1506                 if (!term_command) {
1507                     term_show_prompt();
1508                     term_command = 1;
1509                 } else {
1510                     term_command = 0;
1511                 }
1512                 break;
1513             case TERM_ESCAPE:
1514                 goto send_char;
1515             }
1516         } else if (ch == TERM_ESCAPE) {
1517             term_got_escape = 1;
1518         } else {
1519         send_char:
1520             if (term_command) {
1521                 term_handle_byte(ch);
1522             } else {
1523                 if (serial_console)
1524                     serial_receive_byte(serial_console, ch);
1525             }
1526         }
1527     }
1528 }
1529
1530 static int term_can_read(void *opaque)
1531 {
1532     if (serial_console) {
1533         return serial_can_receive(serial_console);
1534     } else {
1535         return 128;
1536     }
1537 }
1538
1539 static void term_read(void *opaque, const uint8_t *buf, int size)
1540 {
1541     int i;
1542     for(i = 0; i < size; i++)
1543         term_received_byte(buf[i]);
1544 }
1545
1546 void monitor_init(void)
1547 {
1548     if (!serial_console) {
1549         term_printf("QEMU %s monitor - type 'help' for more information\n",
1550                     QEMU_VERSION);
1551         term_show_prompt();
1552     }
1553     term_hist_entry = -1;
1554     qemu_add_fd_read_handler(0, term_can_read, term_read, NULL);
1555 }