convert braille chardev to QemuOpts.
[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 <dirent.h>
25 #include "hw/hw.h"
26 #include "hw/qdev.h"
27 #include "hw/usb.h"
28 #include "hw/pcmcia.h"
29 #include "hw/pc.h"
30 #include "hw/pci.h"
31 #include "hw/watchdog.h"
32 #include "gdbstub.h"
33 #include "net.h"
34 #include "qemu-char.h"
35 #include "sysemu.h"
36 #include "monitor.h"
37 #include "readline.h"
38 #include "console.h"
39 #include "block.h"
40 #include "audio/audio.h"
41 #include "disas.h"
42 #include "balloon.h"
43 #include "qemu-timer.h"
44 #include "migration.h"
45 #include "kvm.h"
46 #include "acl.h"
47 #include "qint.h"
48 #include "qdict.h"
49 #include "qstring.h"
50
51 //#define DEBUG
52 //#define DEBUG_COMPLETION
53
54 /*
55  * Supported types:
56  *
57  * 'F'          filename
58  * 'B'          block device name
59  * 's'          string (accept optional quote)
60  * 'i'          32 bit integer
61  * 'l'          target long (32 or 64 bit)
62  * '/'          optional gdb-like print format (like "/10x")
63  *
64  * '?'          optional type (for all types, except '/')
65  * '.'          other form of optional type (for 'i' and 'l')
66  * '-'          optional parameter (eg. '-f')
67  *
68  */
69
70 typedef struct mon_cmd_t {
71     const char *name;
72     const char *args_type;
73     void *handler;
74     const char *params;
75     const char *help;
76 } mon_cmd_t;
77
78 /* file descriptors passed via SCM_RIGHTS */
79 typedef struct mon_fd_t mon_fd_t;
80 struct mon_fd_t {
81     char *name;
82     int fd;
83     LIST_ENTRY(mon_fd_t) next;
84 };
85
86 struct Monitor {
87     CharDriverState *chr;
88     int flags;
89     int suspend_cnt;
90     uint8_t outbuf[1024];
91     int outbuf_index;
92     ReadLineState *rs;
93     CPUState *mon_cpu;
94     BlockDriverCompletionFunc *password_completion_cb;
95     void *password_opaque;
96     LIST_HEAD(,mon_fd_t) fds;
97     LIST_ENTRY(Monitor) entry;
98 };
99
100 static LIST_HEAD(mon_list, Monitor) mon_list;
101
102 static const mon_cmd_t mon_cmds[];
103 static const mon_cmd_t info_cmds[];
104
105 Monitor *cur_mon = NULL;
106
107 static void monitor_command_cb(Monitor *mon, const char *cmdline,
108                                void *opaque);
109
110 static void monitor_read_command(Monitor *mon, int show_prompt)
111 {
112     readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
113     if (show_prompt)
114         readline_show_prompt(mon->rs);
115 }
116
117 static int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
118                                  void *opaque)
119 {
120     if (mon->rs) {
121         readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
122         /* prompt is printed on return from the command handler */
123         return 0;
124     } else {
125         monitor_printf(mon, "terminal does not support password prompting\n");
126         return -ENOTTY;
127     }
128 }
129
130 void monitor_flush(Monitor *mon)
131 {
132     if (mon && mon->outbuf_index != 0 && mon->chr->focus == 0) {
133         qemu_chr_write(mon->chr, mon->outbuf, mon->outbuf_index);
134         mon->outbuf_index = 0;
135     }
136 }
137
138 /* flush at every end of line or if the buffer is full */
139 static void monitor_puts(Monitor *mon, const char *str)
140 {
141     char c;
142
143     if (!mon)
144         return;
145
146     for(;;) {
147         c = *str++;
148         if (c == '\0')
149             break;
150         if (c == '\n')
151             mon->outbuf[mon->outbuf_index++] = '\r';
152         mon->outbuf[mon->outbuf_index++] = c;
153         if (mon->outbuf_index >= (sizeof(mon->outbuf) - 1)
154             || c == '\n')
155             monitor_flush(mon);
156     }
157 }
158
159 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
160 {
161     char buf[4096];
162     vsnprintf(buf, sizeof(buf), fmt, ap);
163     monitor_puts(mon, buf);
164 }
165
166 void monitor_printf(Monitor *mon, const char *fmt, ...)
167 {
168     va_list ap;
169     va_start(ap, fmt);
170     monitor_vprintf(mon, fmt, ap);
171     va_end(ap);
172 }
173
174 void monitor_print_filename(Monitor *mon, const char *filename)
175 {
176     int i;
177
178     for (i = 0; filename[i]; i++) {
179         switch (filename[i]) {
180         case ' ':
181         case '"':
182         case '\\':
183             monitor_printf(mon, "\\%c", filename[i]);
184             break;
185         case '\t':
186             monitor_printf(mon, "\\t");
187             break;
188         case '\r':
189             monitor_printf(mon, "\\r");
190             break;
191         case '\n':
192             monitor_printf(mon, "\\n");
193             break;
194         default:
195             monitor_printf(mon, "%c", filename[i]);
196             break;
197         }
198     }
199 }
200
201 static int monitor_fprintf(FILE *stream, const char *fmt, ...)
202 {
203     va_list ap;
204     va_start(ap, fmt);
205     monitor_vprintf((Monitor *)stream, fmt, ap);
206     va_end(ap);
207     return 0;
208 }
209
210 static int compare_cmd(const char *name, const char *list)
211 {
212     const char *p, *pstart;
213     int len;
214     len = strlen(name);
215     p = list;
216     for(;;) {
217         pstart = p;
218         p = strchr(p, '|');
219         if (!p)
220             p = pstart + strlen(pstart);
221         if ((p - pstart) == len && !memcmp(pstart, name, len))
222             return 1;
223         if (*p == '\0')
224             break;
225         p++;
226     }
227     return 0;
228 }
229
230 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
231                           const char *prefix, const char *name)
232 {
233     const mon_cmd_t *cmd;
234
235     for(cmd = cmds; cmd->name != NULL; cmd++) {
236         if (!name || !strcmp(name, cmd->name))
237             monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
238                            cmd->params, cmd->help);
239     }
240 }
241
242 static void help_cmd(Monitor *mon, const char *name)
243 {
244     if (name && !strcmp(name, "info")) {
245         help_cmd_dump(mon, info_cmds, "info ", NULL);
246     } else {
247         help_cmd_dump(mon, mon_cmds, "", name);
248         if (name && !strcmp(name, "log")) {
249             const CPULogItem *item;
250             monitor_printf(mon, "Log items (comma separated):\n");
251             monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
252             for(item = cpu_log_items; item->mask != 0; item++) {
253                 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
254             }
255         }
256     }
257 }
258
259 static void do_help_cmd(Monitor *mon, const QDict *qdict)
260 {
261     help_cmd(mon, qdict_get_try_str(qdict, "name"));
262 }
263
264 static void do_commit(Monitor *mon, const QDict *qdict)
265 {
266     int all_devices;
267     DriveInfo *dinfo;
268     const char *device = qdict_get_str(qdict, "device");
269
270     all_devices = !strcmp(device, "all");
271     TAILQ_FOREACH(dinfo, &drives, next) {
272         if (!all_devices)
273             if (strcmp(bdrv_get_device_name(dinfo->bdrv), device))
274                 continue;
275         bdrv_commit(dinfo->bdrv);
276     }
277 }
278
279 static void do_info(Monitor *mon, const QDict *qdict)
280 {
281     const mon_cmd_t *cmd;
282     const char *item = qdict_get_try_str(qdict, "item");
283     void (*handler)(Monitor *);
284
285     if (!item)
286         goto help;
287     for(cmd = info_cmds; cmd->name != NULL; cmd++) {
288         if (compare_cmd(item, cmd->name))
289             goto found;
290     }
291  help:
292     help_cmd(mon, "info");
293     return;
294  found:
295     handler = cmd->handler;
296     handler(mon);
297 }
298
299 static void do_info_version(Monitor *mon)
300 {
301     monitor_printf(mon, "%s\n", QEMU_VERSION QEMU_PKGVERSION);
302 }
303
304 static void do_info_name(Monitor *mon)
305 {
306     if (qemu_name)
307         monitor_printf(mon, "%s\n", qemu_name);
308 }
309
310 #if defined(TARGET_I386)
311 static void do_info_hpet(Monitor *mon)
312 {
313     monitor_printf(mon, "HPET is %s by QEMU\n",
314                    (no_hpet) ? "disabled" : "enabled");
315 }
316 #endif
317
318 static void do_info_uuid(Monitor *mon)
319 {
320     monitor_printf(mon, UUID_FMT "\n", qemu_uuid[0], qemu_uuid[1],
321                    qemu_uuid[2], qemu_uuid[3], qemu_uuid[4], qemu_uuid[5],
322                    qemu_uuid[6], qemu_uuid[7], qemu_uuid[8], qemu_uuid[9],
323                    qemu_uuid[10], qemu_uuid[11], qemu_uuid[12], qemu_uuid[13],
324                    qemu_uuid[14], qemu_uuid[15]);
325 }
326
327 /* get the current CPU defined by the user */
328 static int mon_set_cpu(int cpu_index)
329 {
330     CPUState *env;
331
332     for(env = first_cpu; env != NULL; env = env->next_cpu) {
333         if (env->cpu_index == cpu_index) {
334             cur_mon->mon_cpu = env;
335             return 0;
336         }
337     }
338     return -1;
339 }
340
341 static CPUState *mon_get_cpu(void)
342 {
343     if (!cur_mon->mon_cpu) {
344         mon_set_cpu(0);
345     }
346     cpu_synchronize_state(cur_mon->mon_cpu);
347     return cur_mon->mon_cpu;
348 }
349
350 static void do_info_registers(Monitor *mon)
351 {
352     CPUState *env;
353     env = mon_get_cpu();
354     if (!env)
355         return;
356 #ifdef TARGET_I386
357     cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
358                    X86_DUMP_FPU);
359 #else
360     cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
361                    0);
362 #endif
363 }
364
365 static void do_info_cpus(Monitor *mon)
366 {
367     CPUState *env;
368
369     /* just to set the default cpu if not already done */
370     mon_get_cpu();
371
372     for(env = first_cpu; env != NULL; env = env->next_cpu) {
373         cpu_synchronize_state(env);
374         monitor_printf(mon, "%c CPU #%d:",
375                        (env == mon->mon_cpu) ? '*' : ' ',
376                        env->cpu_index);
377 #if defined(TARGET_I386)
378         monitor_printf(mon, " pc=0x" TARGET_FMT_lx,
379                        env->eip + env->segs[R_CS].base);
380 #elif defined(TARGET_PPC)
381         monitor_printf(mon, " nip=0x" TARGET_FMT_lx, env->nip);
382 #elif defined(TARGET_SPARC)
383         monitor_printf(mon, " pc=0x" TARGET_FMT_lx " npc=0x" TARGET_FMT_lx,
384                        env->pc, env->npc);
385 #elif defined(TARGET_MIPS)
386         monitor_printf(mon, " PC=0x" TARGET_FMT_lx, env->active_tc.PC);
387 #endif
388         if (env->halted)
389             monitor_printf(mon, " (halted)");
390         monitor_printf(mon, "\n");
391     }
392 }
393
394 static void do_cpu_set(Monitor *mon, const QDict *qdict)
395 {
396     int index = qdict_get_int(qdict, "index");
397     if (mon_set_cpu(index) < 0)
398         monitor_printf(mon, "Invalid CPU index\n");
399 }
400
401 static void do_info_jit(Monitor *mon)
402 {
403     dump_exec_info((FILE *)mon, monitor_fprintf);
404 }
405
406 static void do_info_history(Monitor *mon)
407 {
408     int i;
409     const char *str;
410
411     if (!mon->rs)
412         return;
413     i = 0;
414     for(;;) {
415         str = readline_get_history(mon->rs, i);
416         if (!str)
417             break;
418         monitor_printf(mon, "%d: '%s'\n", i, str);
419         i++;
420     }
421 }
422
423 #if defined(TARGET_PPC)
424 /* XXX: not implemented in other targets */
425 static void do_info_cpu_stats(Monitor *mon)
426 {
427     CPUState *env;
428
429     env = mon_get_cpu();
430     cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
431 }
432 #endif
433
434 static void do_quit(Monitor *mon, const QDict *qdict)
435 {
436     exit(0);
437 }
438
439 static int eject_device(Monitor *mon, BlockDriverState *bs, int force)
440 {
441     if (bdrv_is_inserted(bs)) {
442         if (!force) {
443             if (!bdrv_is_removable(bs)) {
444                 monitor_printf(mon, "device is not removable\n");
445                 return -1;
446             }
447             if (bdrv_is_locked(bs)) {
448                 monitor_printf(mon, "device is locked\n");
449                 return -1;
450             }
451         }
452         bdrv_close(bs);
453     }
454     return 0;
455 }
456
457 static void do_eject(Monitor *mon, const QDict *qdict)
458 {
459     BlockDriverState *bs;
460     int force = qdict_get_int(qdict, "force");
461     const char *filename = qdict_get_str(qdict, "filename");
462
463     bs = bdrv_find(filename);
464     if (!bs) {
465         monitor_printf(mon, "device not found\n");
466         return;
467     }
468     eject_device(mon, bs, force);
469 }
470
471 static void do_change_block(Monitor *mon, const char *device,
472                             const char *filename, const char *fmt)
473 {
474     BlockDriverState *bs;
475     BlockDriver *drv = NULL;
476
477     bs = bdrv_find(device);
478     if (!bs) {
479         monitor_printf(mon, "device not found\n");
480         return;
481     }
482     if (fmt) {
483         drv = bdrv_find_format(fmt);
484         if (!drv) {
485             monitor_printf(mon, "invalid format %s\n", fmt);
486             return;
487         }
488     }
489     if (eject_device(mon, bs, 0) < 0)
490         return;
491     bdrv_open2(bs, filename, 0, drv);
492     monitor_read_bdrv_key_start(mon, bs, NULL, NULL);
493 }
494
495 static void change_vnc_password_cb(Monitor *mon, const char *password,
496                                    void *opaque)
497 {
498     if (vnc_display_password(NULL, password) < 0)
499         monitor_printf(mon, "could not set VNC server password\n");
500
501     monitor_read_command(mon, 1);
502 }
503
504 static void do_change_vnc(Monitor *mon, const char *target, const char *arg)
505 {
506     if (strcmp(target, "passwd") == 0 ||
507         strcmp(target, "password") == 0) {
508         if (arg) {
509             char password[9];
510             strncpy(password, arg, sizeof(password));
511             password[sizeof(password) - 1] = '\0';
512             change_vnc_password_cb(mon, password, NULL);
513         } else {
514             monitor_read_password(mon, change_vnc_password_cb, NULL);
515         }
516     } else {
517         if (vnc_display_open(NULL, target) < 0)
518             monitor_printf(mon, "could not start VNC server on %s\n", target);
519     }
520 }
521
522 static void do_change(Monitor *mon, const QDict *qdict)
523 {
524     const char *device = qdict_get_str(qdict, "device");
525     const char *target = qdict_get_str(qdict, "target");
526     const char *arg = qdict_get_try_str(qdict, "arg");
527     if (strcmp(device, "vnc") == 0) {
528         do_change_vnc(mon, target, arg);
529     } else {
530         do_change_block(mon, device, target, arg);
531     }
532 }
533
534 static void do_screen_dump(Monitor *mon, const QDict *qdict)
535 {
536     vga_hw_screen_dump(qdict_get_str(qdict, "filename"));
537 }
538
539 static void do_logfile(Monitor *mon, const QDict *qdict)
540 {
541     cpu_set_log_filename(qdict_get_str(qdict, "filename"));
542 }
543
544 static void do_log(Monitor *mon, const QDict *qdict)
545 {
546     int mask;
547     const char *items = qdict_get_str(qdict, "items");
548
549     if (!strcmp(items, "none")) {
550         mask = 0;
551     } else {
552         mask = cpu_str_to_log_mask(items);
553         if (!mask) {
554             help_cmd(mon, "log");
555             return;
556         }
557     }
558     cpu_set_log(mask);
559 }
560
561 static void do_singlestep(Monitor *mon, const QDict *qdict)
562 {
563     const char *option = qdict_get_try_str(qdict, "option");
564     if (!option || !strcmp(option, "on")) {
565         singlestep = 1;
566     } else if (!strcmp(option, "off")) {
567         singlestep = 0;
568     } else {
569         monitor_printf(mon, "unexpected option %s\n", option);
570     }
571 }
572
573 static void do_stop(Monitor *mon, const QDict *qdict)
574 {
575     vm_stop(EXCP_INTERRUPT);
576 }
577
578 static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs);
579
580 struct bdrv_iterate_context {
581     Monitor *mon;
582     int err;
583 };
584
585 static void do_cont(Monitor *mon, const QDict *qdict)
586 {
587     struct bdrv_iterate_context context = { mon, 0 };
588
589     bdrv_iterate(encrypted_bdrv_it, &context);
590     /* only resume the vm if all keys are set and valid */
591     if (!context.err)
592         vm_start();
593 }
594
595 static void bdrv_key_cb(void *opaque, int err)
596 {
597     Monitor *mon = opaque;
598
599     /* another key was set successfully, retry to continue */
600     if (!err)
601         do_cont(mon, NULL);
602 }
603
604 static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs)
605 {
606     struct bdrv_iterate_context *context = opaque;
607
608     if (!context->err && bdrv_key_required(bs)) {
609         context->err = -EBUSY;
610         monitor_read_bdrv_key_start(context->mon, bs, bdrv_key_cb,
611                                     context->mon);
612     }
613 }
614
615 static void do_gdbserver(Monitor *mon, const QDict *qdict)
616 {
617     const char *device = qdict_get_try_str(qdict, "device");
618     if (!device)
619         device = "tcp::" DEFAULT_GDBSTUB_PORT;
620     if (gdbserver_start(device) < 0) {
621         monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
622                        device);
623     } else if (strcmp(device, "none") == 0) {
624         monitor_printf(mon, "Disabled gdbserver\n");
625     } else {
626         monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
627                        device);
628     }
629 }
630
631 static void do_watchdog_action(Monitor *mon, const QDict *qdict)
632 {
633     const char *action = qdict_get_str(qdict, "action");
634     if (select_watchdog_action(action) == -1) {
635         monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
636     }
637 }
638
639 static void monitor_printc(Monitor *mon, int c)
640 {
641     monitor_printf(mon, "'");
642     switch(c) {
643     case '\'':
644         monitor_printf(mon, "\\'");
645         break;
646     case '\\':
647         monitor_printf(mon, "\\\\");
648         break;
649     case '\n':
650         monitor_printf(mon, "\\n");
651         break;
652     case '\r':
653         monitor_printf(mon, "\\r");
654         break;
655     default:
656         if (c >= 32 && c <= 126) {
657             monitor_printf(mon, "%c", c);
658         } else {
659             monitor_printf(mon, "\\x%02x", c);
660         }
661         break;
662     }
663     monitor_printf(mon, "'");
664 }
665
666 static void memory_dump(Monitor *mon, int count, int format, int wsize,
667                         target_phys_addr_t addr, int is_physical)
668 {
669     CPUState *env;
670     int nb_per_line, l, line_size, i, max_digits, len;
671     uint8_t buf[16];
672     uint64_t v;
673
674     if (format == 'i') {
675         int flags;
676         flags = 0;
677         env = mon_get_cpu();
678         if (!env && !is_physical)
679             return;
680 #ifdef TARGET_I386
681         if (wsize == 2) {
682             flags = 1;
683         } else if (wsize == 4) {
684             flags = 0;
685         } else {
686             /* as default we use the current CS size */
687             flags = 0;
688             if (env) {
689 #ifdef TARGET_X86_64
690                 if ((env->efer & MSR_EFER_LMA) &&
691                     (env->segs[R_CS].flags & DESC_L_MASK))
692                     flags = 2;
693                 else
694 #endif
695                 if (!(env->segs[R_CS].flags & DESC_B_MASK))
696                     flags = 1;
697             }
698         }
699 #endif
700         monitor_disas(mon, env, addr, count, is_physical, flags);
701         return;
702     }
703
704     len = wsize * count;
705     if (wsize == 1)
706         line_size = 8;
707     else
708         line_size = 16;
709     nb_per_line = line_size / wsize;
710     max_digits = 0;
711
712     switch(format) {
713     case 'o':
714         max_digits = (wsize * 8 + 2) / 3;
715         break;
716     default:
717     case 'x':
718         max_digits = (wsize * 8) / 4;
719         break;
720     case 'u':
721     case 'd':
722         max_digits = (wsize * 8 * 10 + 32) / 33;
723         break;
724     case 'c':
725         wsize = 1;
726         break;
727     }
728
729     while (len > 0) {
730         if (is_physical)
731             monitor_printf(mon, TARGET_FMT_plx ":", addr);
732         else
733             monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
734         l = len;
735         if (l > line_size)
736             l = line_size;
737         if (is_physical) {
738             cpu_physical_memory_rw(addr, buf, l, 0);
739         } else {
740             env = mon_get_cpu();
741             if (!env)
742                 break;
743             if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {
744                 monitor_printf(mon, " Cannot access memory\n");
745                 break;
746             }
747         }
748         i = 0;
749         while (i < l) {
750             switch(wsize) {
751             default:
752             case 1:
753                 v = ldub_raw(buf + i);
754                 break;
755             case 2:
756                 v = lduw_raw(buf + i);
757                 break;
758             case 4:
759                 v = (uint32_t)ldl_raw(buf + i);
760                 break;
761             case 8:
762                 v = ldq_raw(buf + i);
763                 break;
764             }
765             monitor_printf(mon, " ");
766             switch(format) {
767             case 'o':
768                 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
769                 break;
770             case 'x':
771                 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
772                 break;
773             case 'u':
774                 monitor_printf(mon, "%*" PRIu64, max_digits, v);
775                 break;
776             case 'd':
777                 monitor_printf(mon, "%*" PRId64, max_digits, v);
778                 break;
779             case 'c':
780                 monitor_printc(mon, v);
781                 break;
782             }
783             i += wsize;
784         }
785         monitor_printf(mon, "\n");
786         addr += l;
787         len -= l;
788     }
789 }
790
791 static void do_memory_dump(Monitor *mon, const QDict *qdict)
792 {
793     int count = qdict_get_int(qdict, "count");
794     int format = qdict_get_int(qdict, "format");
795     int size = qdict_get_int(qdict, "size");
796     target_long addr = qdict_get_int(qdict, "addr");
797
798     memory_dump(mon, count, format, size, addr, 0);
799 }
800
801 static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
802 {
803     int count = qdict_get_int(qdict, "count");
804     int format = qdict_get_int(qdict, "format");
805     int size = qdict_get_int(qdict, "size");
806     target_phys_addr_t addr = qdict_get_int(qdict, "addr");
807
808     memory_dump(mon, count, format, size, addr, 1);
809 }
810
811 static void do_print(Monitor *mon, const QDict *qdict)
812 {
813     int format = qdict_get_int(qdict, "format");
814     target_phys_addr_t val = qdict_get_int(qdict, "val");
815
816 #if TARGET_PHYS_ADDR_BITS == 32
817     switch(format) {
818     case 'o':
819         monitor_printf(mon, "%#o", val);
820         break;
821     case 'x':
822         monitor_printf(mon, "%#x", val);
823         break;
824     case 'u':
825         monitor_printf(mon, "%u", val);
826         break;
827     default:
828     case 'd':
829         monitor_printf(mon, "%d", val);
830         break;
831     case 'c':
832         monitor_printc(mon, val);
833         break;
834     }
835 #else
836     switch(format) {
837     case 'o':
838         monitor_printf(mon, "%#" PRIo64, val);
839         break;
840     case 'x':
841         monitor_printf(mon, "%#" PRIx64, val);
842         break;
843     case 'u':
844         monitor_printf(mon, "%" PRIu64, val);
845         break;
846     default:
847     case 'd':
848         monitor_printf(mon, "%" PRId64, val);
849         break;
850     case 'c':
851         monitor_printc(mon, val);
852         break;
853     }
854 #endif
855     monitor_printf(mon, "\n");
856 }
857
858 static void do_memory_save(Monitor *mon, const QDict *qdict)
859 {
860     FILE *f;
861     uint32_t size = qdict_get_int(qdict, "size");
862     const char *filename = qdict_get_str(qdict, "filename");
863     target_long addr = qdict_get_int(qdict, "val");
864     uint32_t l;
865     CPUState *env;
866     uint8_t buf[1024];
867
868     env = mon_get_cpu();
869     if (!env)
870         return;
871
872     f = fopen(filename, "wb");
873     if (!f) {
874         monitor_printf(mon, "could not open '%s'\n", filename);
875         return;
876     }
877     while (size != 0) {
878         l = sizeof(buf);
879         if (l > size)
880             l = size;
881         cpu_memory_rw_debug(env, addr, buf, l, 0);
882         fwrite(buf, 1, l, f);
883         addr += l;
884         size -= l;
885     }
886     fclose(f);
887 }
888
889 static void do_physical_memory_save(Monitor *mon, const QDict *qdict)
890 {
891     FILE *f;
892     uint32_t l;
893     uint8_t buf[1024];
894     uint32_t size = qdict_get_int(qdict, "size");
895     const char *filename = qdict_get_str(qdict, "filename");
896     target_phys_addr_t addr = qdict_get_int(qdict, "val");
897
898     f = fopen(filename, "wb");
899     if (!f) {
900         monitor_printf(mon, "could not open '%s'\n", filename);
901         return;
902     }
903     while (size != 0) {
904         l = sizeof(buf);
905         if (l > size)
906             l = size;
907         cpu_physical_memory_rw(addr, buf, l, 0);
908         fwrite(buf, 1, l, f);
909         fflush(f);
910         addr += l;
911         size -= l;
912     }
913     fclose(f);
914 }
915
916 static void do_sum(Monitor *mon, const QDict *qdict)
917 {
918     uint32_t addr;
919     uint8_t buf[1];
920     uint16_t sum;
921     uint32_t start = qdict_get_int(qdict, "start");
922     uint32_t size = qdict_get_int(qdict, "size");
923
924     sum = 0;
925     for(addr = start; addr < (start + size); addr++) {
926         cpu_physical_memory_rw(addr, buf, 1, 0);
927         /* BSD sum algorithm ('sum' Unix command) */
928         sum = (sum >> 1) | (sum << 15);
929         sum += buf[0];
930     }
931     monitor_printf(mon, "%05d\n", sum);
932 }
933
934 typedef struct {
935     int keycode;
936     const char *name;
937 } KeyDef;
938
939 static const KeyDef key_defs[] = {
940     { 0x2a, "shift" },
941     { 0x36, "shift_r" },
942
943     { 0x38, "alt" },
944     { 0xb8, "alt_r" },
945     { 0x64, "altgr" },
946     { 0xe4, "altgr_r" },
947     { 0x1d, "ctrl" },
948     { 0x9d, "ctrl_r" },
949
950     { 0xdd, "menu" },
951
952     { 0x01, "esc" },
953
954     { 0x02, "1" },
955     { 0x03, "2" },
956     { 0x04, "3" },
957     { 0x05, "4" },
958     { 0x06, "5" },
959     { 0x07, "6" },
960     { 0x08, "7" },
961     { 0x09, "8" },
962     { 0x0a, "9" },
963     { 0x0b, "0" },
964     { 0x0c, "minus" },
965     { 0x0d, "equal" },
966     { 0x0e, "backspace" },
967
968     { 0x0f, "tab" },
969     { 0x10, "q" },
970     { 0x11, "w" },
971     { 0x12, "e" },
972     { 0x13, "r" },
973     { 0x14, "t" },
974     { 0x15, "y" },
975     { 0x16, "u" },
976     { 0x17, "i" },
977     { 0x18, "o" },
978     { 0x19, "p" },
979
980     { 0x1c, "ret" },
981
982     { 0x1e, "a" },
983     { 0x1f, "s" },
984     { 0x20, "d" },
985     { 0x21, "f" },
986     { 0x22, "g" },
987     { 0x23, "h" },
988     { 0x24, "j" },
989     { 0x25, "k" },
990     { 0x26, "l" },
991
992     { 0x2c, "z" },
993     { 0x2d, "x" },
994     { 0x2e, "c" },
995     { 0x2f, "v" },
996     { 0x30, "b" },
997     { 0x31, "n" },
998     { 0x32, "m" },
999     { 0x33, "comma" },
1000     { 0x34, "dot" },
1001     { 0x35, "slash" },
1002
1003     { 0x37, "asterisk" },
1004
1005     { 0x39, "spc" },
1006     { 0x3a, "caps_lock" },
1007     { 0x3b, "f1" },
1008     { 0x3c, "f2" },
1009     { 0x3d, "f3" },
1010     { 0x3e, "f4" },
1011     { 0x3f, "f5" },
1012     { 0x40, "f6" },
1013     { 0x41, "f7" },
1014     { 0x42, "f8" },
1015     { 0x43, "f9" },
1016     { 0x44, "f10" },
1017     { 0x45, "num_lock" },
1018     { 0x46, "scroll_lock" },
1019
1020     { 0xb5, "kp_divide" },
1021     { 0x37, "kp_multiply" },
1022     { 0x4a, "kp_subtract" },
1023     { 0x4e, "kp_add" },
1024     { 0x9c, "kp_enter" },
1025     { 0x53, "kp_decimal" },
1026     { 0x54, "sysrq" },
1027
1028     { 0x52, "kp_0" },
1029     { 0x4f, "kp_1" },
1030     { 0x50, "kp_2" },
1031     { 0x51, "kp_3" },
1032     { 0x4b, "kp_4" },
1033     { 0x4c, "kp_5" },
1034     { 0x4d, "kp_6" },
1035     { 0x47, "kp_7" },
1036     { 0x48, "kp_8" },
1037     { 0x49, "kp_9" },
1038
1039     { 0x56, "<" },
1040
1041     { 0x57, "f11" },
1042     { 0x58, "f12" },
1043
1044     { 0xb7, "print" },
1045
1046     { 0xc7, "home" },
1047     { 0xc9, "pgup" },
1048     { 0xd1, "pgdn" },
1049     { 0xcf, "end" },
1050
1051     { 0xcb, "left" },
1052     { 0xc8, "up" },
1053     { 0xd0, "down" },
1054     { 0xcd, "right" },
1055
1056     { 0xd2, "insert" },
1057     { 0xd3, "delete" },
1058 #if defined(TARGET_SPARC) && !defined(TARGET_SPARC64)
1059     { 0xf0, "stop" },
1060     { 0xf1, "again" },
1061     { 0xf2, "props" },
1062     { 0xf3, "undo" },
1063     { 0xf4, "front" },
1064     { 0xf5, "copy" },
1065     { 0xf6, "open" },
1066     { 0xf7, "paste" },
1067     { 0xf8, "find" },
1068     { 0xf9, "cut" },
1069     { 0xfa, "lf" },
1070     { 0xfb, "help" },
1071     { 0xfc, "meta_l" },
1072     { 0xfd, "meta_r" },
1073     { 0xfe, "compose" },
1074 #endif
1075     { 0, NULL },
1076 };
1077
1078 static int get_keycode(const char *key)
1079 {
1080     const KeyDef *p;
1081     char *endp;
1082     int ret;
1083
1084     for(p = key_defs; p->name != NULL; p++) {
1085         if (!strcmp(key, p->name))
1086             return p->keycode;
1087     }
1088     if (strstart(key, "0x", NULL)) {
1089         ret = strtoul(key, &endp, 0);
1090         if (*endp == '\0' && ret >= 0x01 && ret <= 0xff)
1091             return ret;
1092     }
1093     return -1;
1094 }
1095
1096 #define MAX_KEYCODES 16
1097 static uint8_t keycodes[MAX_KEYCODES];
1098 static int nb_pending_keycodes;
1099 static QEMUTimer *key_timer;
1100
1101 static void release_keys(void *opaque)
1102 {
1103     int keycode;
1104
1105     while (nb_pending_keycodes > 0) {
1106         nb_pending_keycodes--;
1107         keycode = keycodes[nb_pending_keycodes];
1108         if (keycode & 0x80)
1109             kbd_put_keycode(0xe0);
1110         kbd_put_keycode(keycode | 0x80);
1111     }
1112 }
1113
1114 static void do_sendkey(Monitor *mon, const QDict *qdict)
1115 {
1116     char keyname_buf[16];
1117     char *separator;
1118     int keyname_len, keycode, i;
1119     const char *string = qdict_get_str(qdict, "string");
1120     int has_hold_time = qdict_haskey(qdict, "hold_time");
1121     int hold_time = qdict_get_try_int(qdict, "hold_time", -1);
1122
1123     if (nb_pending_keycodes > 0) {
1124         qemu_del_timer(key_timer);
1125         release_keys(NULL);
1126     }
1127     if (!has_hold_time)
1128         hold_time = 100;
1129     i = 0;
1130     while (1) {
1131         separator = strchr(string, '-');
1132         keyname_len = separator ? separator - string : strlen(string);
1133         if (keyname_len > 0) {
1134             pstrcpy(keyname_buf, sizeof(keyname_buf), string);
1135             if (keyname_len > sizeof(keyname_buf) - 1) {
1136                 monitor_printf(mon, "invalid key: '%s...'\n", keyname_buf);
1137                 return;
1138             }
1139             if (i == MAX_KEYCODES) {
1140                 monitor_printf(mon, "too many keys\n");
1141                 return;
1142             }
1143             keyname_buf[keyname_len] = 0;
1144             keycode = get_keycode(keyname_buf);
1145             if (keycode < 0) {
1146                 monitor_printf(mon, "unknown key: '%s'\n", keyname_buf);
1147                 return;
1148             }
1149             keycodes[i++] = keycode;
1150         }
1151         if (!separator)
1152             break;
1153         string = separator + 1;
1154     }
1155     nb_pending_keycodes = i;
1156     /* key down events */
1157     for (i = 0; i < nb_pending_keycodes; i++) {
1158         keycode = keycodes[i];
1159         if (keycode & 0x80)
1160             kbd_put_keycode(0xe0);
1161         kbd_put_keycode(keycode & 0x7f);
1162     }
1163     /* delayed key up events */
1164     qemu_mod_timer(key_timer, qemu_get_clock(vm_clock) +
1165                     muldiv64(ticks_per_sec, hold_time, 1000));
1166 }
1167
1168 static int mouse_button_state;
1169
1170 static void do_mouse_move(Monitor *mon, const QDict *qdict)
1171 {
1172     int dx, dy, dz;
1173     const char *dx_str = qdict_get_str(qdict, "dx_str");
1174     const char *dy_str = qdict_get_str(qdict, "dy_str");
1175     const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1176     dx = strtol(dx_str, NULL, 0);
1177     dy = strtol(dy_str, NULL, 0);
1178     dz = 0;
1179     if (dz_str)
1180         dz = strtol(dz_str, NULL, 0);
1181     kbd_mouse_event(dx, dy, dz, mouse_button_state);
1182 }
1183
1184 static void do_mouse_button(Monitor *mon, const QDict *qdict)
1185 {
1186     int button_state = qdict_get_int(qdict, "button_state");
1187     mouse_button_state = button_state;
1188     kbd_mouse_event(0, 0, 0, mouse_button_state);
1189 }
1190
1191 static void do_ioport_read(Monitor *mon, const QDict *qdict)
1192 {
1193     int size = qdict_get_int(qdict, "size");
1194     int addr = qdict_get_int(qdict, "addr");
1195     int has_index = qdict_haskey(qdict, "index");
1196     uint32_t val;
1197     int suffix;
1198
1199     if (has_index) {
1200         int index = qdict_get_int(qdict, "index");
1201         cpu_outb(NULL, addr & IOPORTS_MASK, index & 0xff);
1202         addr++;
1203     }
1204     addr &= 0xffff;
1205
1206     switch(size) {
1207     default:
1208     case 1:
1209         val = cpu_inb(NULL, addr);
1210         suffix = 'b';
1211         break;
1212     case 2:
1213         val = cpu_inw(NULL, addr);
1214         suffix = 'w';
1215         break;
1216     case 4:
1217         val = cpu_inl(NULL, addr);
1218         suffix = 'l';
1219         break;
1220     }
1221     monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1222                    suffix, addr, size * 2, val);
1223 }
1224
1225 static void do_ioport_write(Monitor *mon, const QDict *qdict)
1226 {
1227     int size = qdict_get_int(qdict, "size");
1228     int addr = qdict_get_int(qdict, "addr");
1229     int val = qdict_get_int(qdict, "val");
1230
1231     addr &= IOPORTS_MASK;
1232
1233     switch (size) {
1234     default:
1235     case 1:
1236         cpu_outb(NULL, addr, val);
1237         break;
1238     case 2:
1239         cpu_outw(NULL, addr, val);
1240         break;
1241     case 4:
1242         cpu_outl(NULL, addr, val);
1243         break;
1244     }
1245 }
1246
1247 static void do_boot_set(Monitor *mon, const QDict *qdict)
1248 {
1249     int res;
1250     const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1251
1252     res = qemu_boot_set(bootdevice);
1253     if (res == 0) {
1254         monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1255     } else if (res > 0) {
1256         monitor_printf(mon, "setting boot device list failed\n");
1257     } else {
1258         monitor_printf(mon, "no function defined to set boot device list for "
1259                        "this architecture\n");
1260     }
1261 }
1262
1263 static void do_system_reset(Monitor *mon, const QDict *qdict)
1264 {
1265     qemu_system_reset_request();
1266 }
1267
1268 static void do_system_powerdown(Monitor *mon, const QDict *qdict)
1269 {
1270     qemu_system_powerdown_request();
1271 }
1272
1273 #if defined(TARGET_I386)
1274 static void print_pte(Monitor *mon, uint32_t addr, uint32_t pte, uint32_t mask)
1275 {
1276     monitor_printf(mon, "%08x: %08x %c%c%c%c%c%c%c%c\n",
1277                    addr,
1278                    pte & mask,
1279                    pte & PG_GLOBAL_MASK ? 'G' : '-',
1280                    pte & PG_PSE_MASK ? 'P' : '-',
1281                    pte & PG_DIRTY_MASK ? 'D' : '-',
1282                    pte & PG_ACCESSED_MASK ? 'A' : '-',
1283                    pte & PG_PCD_MASK ? 'C' : '-',
1284                    pte & PG_PWT_MASK ? 'T' : '-',
1285                    pte & PG_USER_MASK ? 'U' : '-',
1286                    pte & PG_RW_MASK ? 'W' : '-');
1287 }
1288
1289 static void tlb_info(Monitor *mon)
1290 {
1291     CPUState *env;
1292     int l1, l2;
1293     uint32_t pgd, pde, pte;
1294
1295     env = mon_get_cpu();
1296     if (!env)
1297         return;
1298
1299     if (!(env->cr[0] & CR0_PG_MASK)) {
1300         monitor_printf(mon, "PG disabled\n");
1301         return;
1302     }
1303     pgd = env->cr[3] & ~0xfff;
1304     for(l1 = 0; l1 < 1024; l1++) {
1305         cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1306         pde = le32_to_cpu(pde);
1307         if (pde & PG_PRESENT_MASK) {
1308             if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1309                 print_pte(mon, (l1 << 22), pde, ~((1 << 20) - 1));
1310             } else {
1311                 for(l2 = 0; l2 < 1024; l2++) {
1312                     cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1313                                              (uint8_t *)&pte, 4);
1314                     pte = le32_to_cpu(pte);
1315                     if (pte & PG_PRESENT_MASK) {
1316                         print_pte(mon, (l1 << 22) + (l2 << 12),
1317                                   pte & ~PG_PSE_MASK,
1318                                   ~0xfff);
1319                     }
1320                 }
1321             }
1322         }
1323     }
1324 }
1325
1326 static void mem_print(Monitor *mon, uint32_t *pstart, int *plast_prot,
1327                       uint32_t end, int prot)
1328 {
1329     int prot1;
1330     prot1 = *plast_prot;
1331     if (prot != prot1) {
1332         if (*pstart != -1) {
1333             monitor_printf(mon, "%08x-%08x %08x %c%c%c\n",
1334                            *pstart, end, end - *pstart,
1335                            prot1 & PG_USER_MASK ? 'u' : '-',
1336                            'r',
1337                            prot1 & PG_RW_MASK ? 'w' : '-');
1338         }
1339         if (prot != 0)
1340             *pstart = end;
1341         else
1342             *pstart = -1;
1343         *plast_prot = prot;
1344     }
1345 }
1346
1347 static void mem_info(Monitor *mon)
1348 {
1349     CPUState *env;
1350     int l1, l2, prot, last_prot;
1351     uint32_t pgd, pde, pte, start, end;
1352
1353     env = mon_get_cpu();
1354     if (!env)
1355         return;
1356
1357     if (!(env->cr[0] & CR0_PG_MASK)) {
1358         monitor_printf(mon, "PG disabled\n");
1359         return;
1360     }
1361     pgd = env->cr[3] & ~0xfff;
1362     last_prot = 0;
1363     start = -1;
1364     for(l1 = 0; l1 < 1024; l1++) {
1365         cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1366         pde = le32_to_cpu(pde);
1367         end = l1 << 22;
1368         if (pde & PG_PRESENT_MASK) {
1369             if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1370                 prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1371                 mem_print(mon, &start, &last_prot, end, prot);
1372             } else {
1373                 for(l2 = 0; l2 < 1024; l2++) {
1374                     cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1375                                              (uint8_t *)&pte, 4);
1376                     pte = le32_to_cpu(pte);
1377                     end = (l1 << 22) + (l2 << 12);
1378                     if (pte & PG_PRESENT_MASK) {
1379                         prot = pte & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1380                     } else {
1381                         prot = 0;
1382                     }
1383                     mem_print(mon, &start, &last_prot, end, prot);
1384                 }
1385             }
1386         } else {
1387             prot = 0;
1388             mem_print(mon, &start, &last_prot, end, prot);
1389         }
1390     }
1391 }
1392 #endif
1393
1394 #if defined(TARGET_SH4)
1395
1396 static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1397 {
1398     monitor_printf(mon, " tlb%i:\t"
1399                    "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1400                    "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1401                    "dirty=%hhu writethrough=%hhu\n",
1402                    idx,
1403                    tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1404                    tlb->v, tlb->sh, tlb->c, tlb->pr,
1405                    tlb->d, tlb->wt);
1406 }
1407
1408 static void tlb_info(Monitor *mon)
1409 {
1410     CPUState *env = mon_get_cpu();
1411     int i;
1412
1413     monitor_printf (mon, "ITLB:\n");
1414     for (i = 0 ; i < ITLB_SIZE ; i++)
1415         print_tlb (mon, i, &env->itlb[i]);
1416     monitor_printf (mon, "UTLB:\n");
1417     for (i = 0 ; i < UTLB_SIZE ; i++)
1418         print_tlb (mon, i, &env->utlb[i]);
1419 }
1420
1421 #endif
1422
1423 static void do_info_kvm(Monitor *mon)
1424 {
1425 #ifdef CONFIG_KVM
1426     monitor_printf(mon, "kvm support: ");
1427     if (kvm_enabled())
1428         monitor_printf(mon, "enabled\n");
1429     else
1430         monitor_printf(mon, "disabled\n");
1431 #else
1432     monitor_printf(mon, "kvm support: not compiled\n");
1433 #endif
1434 }
1435
1436 static void do_info_numa(Monitor *mon)
1437 {
1438     int i;
1439     CPUState *env;
1440
1441     monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1442     for (i = 0; i < nb_numa_nodes; i++) {
1443         monitor_printf(mon, "node %d cpus:", i);
1444         for (env = first_cpu; env != NULL; env = env->next_cpu) {
1445             if (env->numa_node == i) {
1446                 monitor_printf(mon, " %d", env->cpu_index);
1447             }
1448         }
1449         monitor_printf(mon, "\n");
1450         monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1451             node_mem[i] >> 20);
1452     }
1453 }
1454
1455 #ifdef CONFIG_PROFILER
1456
1457 static void do_info_profile(Monitor *mon)
1458 {
1459     int64_t total;
1460     total = qemu_time;
1461     if (total == 0)
1462         total = 1;
1463     monitor_printf(mon, "async time  %" PRId64 " (%0.3f)\n",
1464                    dev_time, dev_time / (double)ticks_per_sec);
1465     monitor_printf(mon, "qemu time   %" PRId64 " (%0.3f)\n",
1466                    qemu_time, qemu_time / (double)ticks_per_sec);
1467     qemu_time = 0;
1468     dev_time = 0;
1469 }
1470 #else
1471 static void do_info_profile(Monitor *mon)
1472 {
1473     monitor_printf(mon, "Internal profiler not compiled\n");
1474 }
1475 #endif
1476
1477 /* Capture support */
1478 static LIST_HEAD (capture_list_head, CaptureState) capture_head;
1479
1480 static void do_info_capture(Monitor *mon)
1481 {
1482     int i;
1483     CaptureState *s;
1484
1485     for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1486         monitor_printf(mon, "[%d]: ", i);
1487         s->ops.info (s->opaque);
1488     }
1489 }
1490
1491 #ifdef HAS_AUDIO
1492 static void do_stop_capture(Monitor *mon, const QDict *qdict)
1493 {
1494     int i;
1495     int n = qdict_get_int(qdict, "n");
1496     CaptureState *s;
1497
1498     for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1499         if (i == n) {
1500             s->ops.destroy (s->opaque);
1501             LIST_REMOVE (s, entries);
1502             qemu_free (s);
1503             return;
1504         }
1505     }
1506 }
1507
1508 static void do_wav_capture(Monitor *mon, const QDict *qdict)
1509 {
1510     const char *path = qdict_get_str(qdict, "path");
1511     int has_freq = qdict_haskey(qdict, "freq");
1512     int freq = qdict_get_try_int(qdict, "freq", -1);
1513     int has_bits = qdict_haskey(qdict, "bits");
1514     int bits = qdict_get_try_int(qdict, "bits", -1);
1515     int has_channels = qdict_haskey(qdict, "nchannels");
1516     int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1517     CaptureState *s;
1518
1519     s = qemu_mallocz (sizeof (*s));
1520
1521     freq = has_freq ? freq : 44100;
1522     bits = has_bits ? bits : 16;
1523     nchannels = has_channels ? nchannels : 2;
1524
1525     if (wav_start_capture (s, path, freq, bits, nchannels)) {
1526         monitor_printf(mon, "Faied to add wave capture\n");
1527         qemu_free (s);
1528     }
1529     LIST_INSERT_HEAD (&capture_head, s, entries);
1530 }
1531 #endif
1532
1533 #if defined(TARGET_I386)
1534 static void do_inject_nmi(Monitor *mon, const QDict *qdict)
1535 {
1536     CPUState *env;
1537     int cpu_index = qdict_get_int(qdict, "cpu_index");
1538
1539     for (env = first_cpu; env != NULL; env = env->next_cpu)
1540         if (env->cpu_index == cpu_index) {
1541             cpu_interrupt(env, CPU_INTERRUPT_NMI);
1542             break;
1543         }
1544 }
1545 #endif
1546
1547 static void do_info_status(Monitor *mon)
1548 {
1549     if (vm_running) {
1550         if (singlestep) {
1551             monitor_printf(mon, "VM status: running (single step mode)\n");
1552         } else {
1553             monitor_printf(mon, "VM status: running\n");
1554         }
1555     } else
1556        monitor_printf(mon, "VM status: paused\n");
1557 }
1558
1559
1560 static void do_balloon(Monitor *mon, const QDict *qdict)
1561 {
1562     int value = qdict_get_int(qdict, "value");
1563     ram_addr_t target = value;
1564     qemu_balloon(target << 20);
1565 }
1566
1567 static void do_info_balloon(Monitor *mon)
1568 {
1569     ram_addr_t actual;
1570
1571     actual = qemu_balloon_status();
1572     if (kvm_enabled() && !kvm_has_sync_mmu())
1573         monitor_printf(mon, "Using KVM without synchronous MMU, "
1574                        "ballooning disabled\n");
1575     else if (actual == 0)
1576         monitor_printf(mon, "Ballooning not activated in VM\n");
1577     else
1578         monitor_printf(mon, "balloon: actual=%d\n", (int)(actual >> 20));
1579 }
1580
1581 static qemu_acl *find_acl(Monitor *mon, const char *name)
1582 {
1583     qemu_acl *acl = qemu_acl_find(name);
1584
1585     if (!acl) {
1586         monitor_printf(mon, "acl: unknown list '%s'\n", name);
1587     }
1588     return acl;
1589 }
1590
1591 static void do_acl_show(Monitor *mon, const QDict *qdict)
1592 {
1593     const char *aclname = qdict_get_str(qdict, "aclname");
1594     qemu_acl *acl = find_acl(mon, aclname);
1595     qemu_acl_entry *entry;
1596     int i = 0;
1597
1598     if (acl) {
1599         monitor_printf(mon, "policy: %s\n",
1600                        acl->defaultDeny ? "deny" : "allow");
1601         TAILQ_FOREACH(entry, &acl->entries, next) {
1602             i++;
1603             monitor_printf(mon, "%d: %s %s\n", i,
1604                            entry->deny ? "deny" : "allow", entry->match);
1605         }
1606     }
1607 }
1608
1609 static void do_acl_reset(Monitor *mon, const QDict *qdict)
1610 {
1611     const char *aclname = qdict_get_str(qdict, "aclname");
1612     qemu_acl *acl = find_acl(mon, aclname);
1613
1614     if (acl) {
1615         qemu_acl_reset(acl);
1616         monitor_printf(mon, "acl: removed all rules\n");
1617     }
1618 }
1619
1620 static void do_acl_policy(Monitor *mon, const QDict *qdict)
1621 {
1622     const char *aclname = qdict_get_str(qdict, "aclname");
1623     const char *policy = qdict_get_str(qdict, "policy");
1624     qemu_acl *acl = find_acl(mon, aclname);
1625
1626     if (acl) {
1627         if (strcmp(policy, "allow") == 0) {
1628             acl->defaultDeny = 0;
1629             monitor_printf(mon, "acl: policy set to 'allow'\n");
1630         } else if (strcmp(policy, "deny") == 0) {
1631             acl->defaultDeny = 1;
1632             monitor_printf(mon, "acl: policy set to 'deny'\n");
1633         } else {
1634             monitor_printf(mon, "acl: unknown policy '%s', "
1635                            "expected 'deny' or 'allow'\n", policy);
1636         }
1637     }
1638 }
1639
1640 static void do_acl_add(Monitor *mon, const QDict *qdict)
1641 {
1642     const char *aclname = qdict_get_str(qdict, "aclname");
1643     const char *match = qdict_get_str(qdict, "match");
1644     const char *policy = qdict_get_str(qdict, "policy");
1645     int has_index = qdict_haskey(qdict, "index");
1646     int index = qdict_get_try_int(qdict, "index", -1);
1647     qemu_acl *acl = find_acl(mon, aclname);
1648     int deny, ret;
1649
1650     if (acl) {
1651         if (strcmp(policy, "allow") == 0) {
1652             deny = 0;
1653         } else if (strcmp(policy, "deny") == 0) {
1654             deny = 1;
1655         } else {
1656             monitor_printf(mon, "acl: unknown policy '%s', "
1657                            "expected 'deny' or 'allow'\n", policy);
1658             return;
1659         }
1660         if (has_index)
1661             ret = qemu_acl_insert(acl, deny, match, index);
1662         else
1663             ret = qemu_acl_append(acl, deny, match);
1664         if (ret < 0)
1665             monitor_printf(mon, "acl: unable to add acl entry\n");
1666         else
1667             monitor_printf(mon, "acl: added rule at position %d\n", ret);
1668     }
1669 }
1670
1671 static void do_acl_remove(Monitor *mon, const QDict *qdict)
1672 {
1673     const char *aclname = qdict_get_str(qdict, "aclname");
1674     const char *match = qdict_get_str(qdict, "match");
1675     qemu_acl *acl = find_acl(mon, aclname);
1676     int ret;
1677
1678     if (acl) {
1679         ret = qemu_acl_remove(acl, match);
1680         if (ret < 0)
1681             monitor_printf(mon, "acl: no matching acl entry\n");
1682         else
1683             monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1684     }
1685 }
1686
1687 #if defined(TARGET_I386)
1688 static void do_inject_mce(Monitor *mon, const QDict *qdict)
1689 {
1690     CPUState *cenv;
1691     int cpu_index = qdict_get_int(qdict, "cpu_index");
1692     int bank = qdict_get_int(qdict, "bank");
1693     uint64_t status = qdict_get_int(qdict, "status");
1694     uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
1695     uint64_t addr = qdict_get_int(qdict, "addr");
1696     uint64_t misc = qdict_get_int(qdict, "misc");
1697
1698     for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu)
1699         if (cenv->cpu_index == cpu_index && cenv->mcg_cap) {
1700             cpu_inject_x86_mce(cenv, bank, status, mcg_status, addr, misc);
1701             break;
1702         }
1703 }
1704 #endif
1705
1706 static void do_getfd(Monitor *mon, const QDict *qdict)
1707 {
1708     const char *fdname = qdict_get_str(qdict, "fdname");
1709     mon_fd_t *monfd;
1710     int fd;
1711
1712     fd = qemu_chr_get_msgfd(mon->chr);
1713     if (fd == -1) {
1714         monitor_printf(mon, "getfd: no file descriptor supplied via SCM_RIGHTS\n");
1715         return;
1716     }
1717
1718     if (qemu_isdigit(fdname[0])) {
1719         monitor_printf(mon, "getfd: monitor names may not begin with a number\n");
1720         return;
1721     }
1722
1723     fd = dup(fd);
1724     if (fd == -1) {
1725         monitor_printf(mon, "Failed to dup() file descriptor: %s\n",
1726                        strerror(errno));
1727         return;
1728     }
1729
1730     LIST_FOREACH(monfd, &mon->fds, next) {
1731         if (strcmp(monfd->name, fdname) != 0) {
1732             continue;
1733         }
1734
1735         close(monfd->fd);
1736         monfd->fd = fd;
1737         return;
1738     }
1739
1740     monfd = qemu_mallocz(sizeof(mon_fd_t));
1741     monfd->name = qemu_strdup(fdname);
1742     monfd->fd = fd;
1743
1744     LIST_INSERT_HEAD(&mon->fds, monfd, next);
1745 }
1746
1747 static void do_closefd(Monitor *mon, const QDict *qdict)
1748 {
1749     const char *fdname = qdict_get_str(qdict, "fdname");
1750     mon_fd_t *monfd;
1751
1752     LIST_FOREACH(monfd, &mon->fds, next) {
1753         if (strcmp(monfd->name, fdname) != 0) {
1754             continue;
1755         }
1756
1757         LIST_REMOVE(monfd, next);
1758         close(monfd->fd);
1759         qemu_free(monfd->name);
1760         qemu_free(monfd);
1761         return;
1762     }
1763
1764     monitor_printf(mon, "Failed to find file descriptor named %s\n",
1765                    fdname);
1766 }
1767
1768 static void do_loadvm(Monitor *mon, const QDict *qdict)
1769 {
1770     int saved_vm_running  = vm_running;
1771     const char *name = qdict_get_str(qdict, "name");
1772
1773     vm_stop(0);
1774
1775     if (load_vmstate(mon, name) >= 0 && saved_vm_running)
1776         vm_start();
1777 }
1778
1779 int monitor_get_fd(Monitor *mon, const char *fdname)
1780 {
1781     mon_fd_t *monfd;
1782
1783     LIST_FOREACH(monfd, &mon->fds, next) {
1784         int fd;
1785
1786         if (strcmp(monfd->name, fdname) != 0) {
1787             continue;
1788         }
1789
1790         fd = monfd->fd;
1791
1792         /* caller takes ownership of fd */
1793         LIST_REMOVE(monfd, next);
1794         qemu_free(monfd->name);
1795         qemu_free(monfd);
1796
1797         return fd;
1798     }
1799
1800     return -1;
1801 }
1802
1803 static const mon_cmd_t mon_cmds[] = {
1804 #include "qemu-monitor.h"
1805     { NULL, NULL, },
1806 };
1807
1808 /* Please update qemu-monitor.hx when adding or changing commands */
1809 static const mon_cmd_t info_cmds[] = {
1810     { "version", "", do_info_version,
1811       "", "show the version of QEMU" },
1812     { "network", "", do_info_network,
1813       "", "show the network state" },
1814     { "chardev", "", qemu_chr_info,
1815       "", "show the character devices" },
1816     { "block", "", bdrv_info,
1817       "", "show the block devices" },
1818     { "blockstats", "", bdrv_info_stats,
1819       "", "show block device statistics" },
1820     { "registers", "", do_info_registers,
1821       "", "show the cpu registers" },
1822     { "cpus", "", do_info_cpus,
1823       "", "show infos for each CPU" },
1824     { "history", "", do_info_history,
1825       "", "show the command line history", },
1826     { "irq", "", irq_info,
1827       "", "show the interrupts statistics (if available)", },
1828     { "pic", "", pic_info,
1829       "", "show i8259 (PIC) state", },
1830     { "pci", "", pci_info,
1831       "", "show PCI info", },
1832 #if defined(TARGET_I386) || defined(TARGET_SH4)
1833     { "tlb", "", tlb_info,
1834       "", "show virtual to physical memory mappings", },
1835 #endif
1836 #if defined(TARGET_I386)
1837     { "mem", "", mem_info,
1838       "", "show the active virtual memory mappings", },
1839     { "hpet", "", do_info_hpet,
1840       "", "show state of HPET", },
1841 #endif
1842     { "jit", "", do_info_jit,
1843       "", "show dynamic compiler info", },
1844     { "kvm", "", do_info_kvm,
1845       "", "show KVM information", },
1846     { "numa", "", do_info_numa,
1847       "", "show NUMA information", },
1848     { "usb", "", usb_info,
1849       "", "show guest USB devices", },
1850     { "usbhost", "", usb_host_info,
1851       "", "show host USB devices", },
1852     { "profile", "", do_info_profile,
1853       "", "show profiling information", },
1854     { "capture", "", do_info_capture,
1855       "", "show capture information" },
1856     { "snapshots", "", do_info_snapshots,
1857       "", "show the currently saved VM snapshots" },
1858     { "status", "", do_info_status,
1859       "", "show the current VM status (running|paused)" },
1860     { "pcmcia", "", pcmcia_info,
1861       "", "show guest PCMCIA status" },
1862     { "mice", "", do_info_mice,
1863       "", "show which guest mouse is receiving events" },
1864     { "vnc", "", do_info_vnc,
1865       "", "show the vnc server status"},
1866     { "name", "", do_info_name,
1867       "", "show the current VM name" },
1868     { "uuid", "", do_info_uuid,
1869       "", "show the current VM UUID" },
1870 #if defined(TARGET_PPC)
1871     { "cpustats", "", do_info_cpu_stats,
1872       "", "show CPU statistics", },
1873 #endif
1874 #if defined(CONFIG_SLIRP)
1875     { "usernet", "", do_info_usernet,
1876       "", "show user network stack connection states", },
1877 #endif
1878     { "migrate", "", do_info_migrate, "", "show migration status" },
1879     { "balloon", "", do_info_balloon,
1880       "", "show balloon information" },
1881     { "qtree", "", do_info_qtree,
1882       "", "show device tree" },
1883     { "qdm", "", do_info_qdm,
1884       "", "show qdev device model list" },
1885     { NULL, NULL, },
1886 };
1887
1888 /*******************************************************************/
1889
1890 static const char *pch;
1891 static jmp_buf expr_env;
1892
1893 #define MD_TLONG 0
1894 #define MD_I32   1
1895
1896 typedef struct MonitorDef {
1897     const char *name;
1898     int offset;
1899     target_long (*get_value)(const struct MonitorDef *md, int val);
1900     int type;
1901 } MonitorDef;
1902
1903 #if defined(TARGET_I386)
1904 static target_long monitor_get_pc (const struct MonitorDef *md, int val)
1905 {
1906     CPUState *env = mon_get_cpu();
1907     if (!env)
1908         return 0;
1909     return env->eip + env->segs[R_CS].base;
1910 }
1911 #endif
1912
1913 #if defined(TARGET_PPC)
1914 static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
1915 {
1916     CPUState *env = mon_get_cpu();
1917     unsigned int u;
1918     int i;
1919
1920     if (!env)
1921         return 0;
1922
1923     u = 0;
1924     for (i = 0; i < 8; i++)
1925         u |= env->crf[i] << (32 - (4 * i));
1926
1927     return u;
1928 }
1929
1930 static target_long monitor_get_msr (const struct MonitorDef *md, int val)
1931 {
1932     CPUState *env = mon_get_cpu();
1933     if (!env)
1934         return 0;
1935     return env->msr;
1936 }
1937
1938 static target_long monitor_get_xer (const struct MonitorDef *md, int val)
1939 {
1940     CPUState *env = mon_get_cpu();
1941     if (!env)
1942         return 0;
1943     return env->xer;
1944 }
1945
1946 static target_long monitor_get_decr (const struct MonitorDef *md, int val)
1947 {
1948     CPUState *env = mon_get_cpu();
1949     if (!env)
1950         return 0;
1951     return cpu_ppc_load_decr(env);
1952 }
1953
1954 static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
1955 {
1956     CPUState *env = mon_get_cpu();
1957     if (!env)
1958         return 0;
1959     return cpu_ppc_load_tbu(env);
1960 }
1961
1962 static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
1963 {
1964     CPUState *env = mon_get_cpu();
1965     if (!env)
1966         return 0;
1967     return cpu_ppc_load_tbl(env);
1968 }
1969 #endif
1970
1971 #if defined(TARGET_SPARC)
1972 #ifndef TARGET_SPARC64
1973 static target_long monitor_get_psr (const struct MonitorDef *md, int val)
1974 {
1975     CPUState *env = mon_get_cpu();
1976     if (!env)
1977         return 0;
1978     return GET_PSR(env);
1979 }
1980 #endif
1981
1982 static target_long monitor_get_reg(const struct MonitorDef *md, int val)
1983 {
1984     CPUState *env = mon_get_cpu();
1985     if (!env)
1986         return 0;
1987     return env->regwptr[val];
1988 }
1989 #endif
1990
1991 static const MonitorDef monitor_defs[] = {
1992 #ifdef TARGET_I386
1993
1994 #define SEG(name, seg) \
1995     { name, offsetof(CPUState, segs[seg].selector), NULL, MD_I32 },\
1996     { name ".base", offsetof(CPUState, segs[seg].base) },\
1997     { name ".limit", offsetof(CPUState, segs[seg].limit), NULL, MD_I32 },
1998
1999     { "eax", offsetof(CPUState, regs[0]) },
2000     { "ecx", offsetof(CPUState, regs[1]) },
2001     { "edx", offsetof(CPUState, regs[2]) },
2002     { "ebx", offsetof(CPUState, regs[3]) },
2003     { "esp|sp", offsetof(CPUState, regs[4]) },
2004     { "ebp|fp", offsetof(CPUState, regs[5]) },
2005     { "esi", offsetof(CPUState, regs[6]) },
2006     { "edi", offsetof(CPUState, regs[7]) },
2007 #ifdef TARGET_X86_64
2008     { "r8", offsetof(CPUState, regs[8]) },
2009     { "r9", offsetof(CPUState, regs[9]) },
2010     { "r10", offsetof(CPUState, regs[10]) },
2011     { "r11", offsetof(CPUState, regs[11]) },
2012     { "r12", offsetof(CPUState, regs[12]) },
2013     { "r13", offsetof(CPUState, regs[13]) },
2014     { "r14", offsetof(CPUState, regs[14]) },
2015     { "r15", offsetof(CPUState, regs[15]) },
2016 #endif
2017     { "eflags", offsetof(CPUState, eflags) },
2018     { "eip", offsetof(CPUState, eip) },
2019     SEG("cs", R_CS)
2020     SEG("ds", R_DS)
2021     SEG("es", R_ES)
2022     SEG("ss", R_SS)
2023     SEG("fs", R_FS)
2024     SEG("gs", R_GS)
2025     { "pc", 0, monitor_get_pc, },
2026 #elif defined(TARGET_PPC)
2027     /* General purpose registers */
2028     { "r0", offsetof(CPUState, gpr[0]) },
2029     { "r1", offsetof(CPUState, gpr[1]) },
2030     { "r2", offsetof(CPUState, gpr[2]) },
2031     { "r3", offsetof(CPUState, gpr[3]) },
2032     { "r4", offsetof(CPUState, gpr[4]) },
2033     { "r5", offsetof(CPUState, gpr[5]) },
2034     { "r6", offsetof(CPUState, gpr[6]) },
2035     { "r7", offsetof(CPUState, gpr[7]) },
2036     { "r8", offsetof(CPUState, gpr[8]) },
2037     { "r9", offsetof(CPUState, gpr[9]) },
2038     { "r10", offsetof(CPUState, gpr[10]) },
2039     { "r11", offsetof(CPUState, gpr[11]) },
2040     { "r12", offsetof(CPUState, gpr[12]) },
2041     { "r13", offsetof(CPUState, gpr[13]) },
2042     { "r14", offsetof(CPUState, gpr[14]) },
2043     { "r15", offsetof(CPUState, gpr[15]) },
2044     { "r16", offsetof(CPUState, gpr[16]) },
2045     { "r17", offsetof(CPUState, gpr[17]) },
2046     { "r18", offsetof(CPUState, gpr[18]) },
2047     { "r19", offsetof(CPUState, gpr[19]) },
2048     { "r20", offsetof(CPUState, gpr[20]) },
2049     { "r21", offsetof(CPUState, gpr[21]) },
2050     { "r22", offsetof(CPUState, gpr[22]) },
2051     { "r23", offsetof(CPUState, gpr[23]) },
2052     { "r24", offsetof(CPUState, gpr[24]) },
2053     { "r25", offsetof(CPUState, gpr[25]) },
2054     { "r26", offsetof(CPUState, gpr[26]) },
2055     { "r27", offsetof(CPUState, gpr[27]) },
2056     { "r28", offsetof(CPUState, gpr[28]) },
2057     { "r29", offsetof(CPUState, gpr[29]) },
2058     { "r30", offsetof(CPUState, gpr[30]) },
2059     { "r31", offsetof(CPUState, gpr[31]) },
2060     /* Floating point registers */
2061     { "f0", offsetof(CPUState, fpr[0]) },
2062     { "f1", offsetof(CPUState, fpr[1]) },
2063     { "f2", offsetof(CPUState, fpr[2]) },
2064     { "f3", offsetof(CPUState, fpr[3]) },
2065     { "f4", offsetof(CPUState, fpr[4]) },
2066     { "f5", offsetof(CPUState, fpr[5]) },
2067     { "f6", offsetof(CPUState, fpr[6]) },
2068     { "f7", offsetof(CPUState, fpr[7]) },
2069     { "f8", offsetof(CPUState, fpr[8]) },
2070     { "f9", offsetof(CPUState, fpr[9]) },
2071     { "f10", offsetof(CPUState, fpr[10]) },
2072     { "f11", offsetof(CPUState, fpr[11]) },
2073     { "f12", offsetof(CPUState, fpr[12]) },
2074     { "f13", offsetof(CPUState, fpr[13]) },
2075     { "f14", offsetof(CPUState, fpr[14]) },
2076     { "f15", offsetof(CPUState, fpr[15]) },
2077     { "f16", offsetof(CPUState, fpr[16]) },
2078     { "f17", offsetof(CPUState, fpr[17]) },
2079     { "f18", offsetof(CPUState, fpr[18]) },
2080     { "f19", offsetof(CPUState, fpr[19]) },
2081     { "f20", offsetof(CPUState, fpr[20]) },
2082     { "f21", offsetof(CPUState, fpr[21]) },
2083     { "f22", offsetof(CPUState, fpr[22]) },
2084     { "f23", offsetof(CPUState, fpr[23]) },
2085     { "f24", offsetof(CPUState, fpr[24]) },
2086     { "f25", offsetof(CPUState, fpr[25]) },
2087     { "f26", offsetof(CPUState, fpr[26]) },
2088     { "f27", offsetof(CPUState, fpr[27]) },
2089     { "f28", offsetof(CPUState, fpr[28]) },
2090     { "f29", offsetof(CPUState, fpr[29]) },
2091     { "f30", offsetof(CPUState, fpr[30]) },
2092     { "f31", offsetof(CPUState, fpr[31]) },
2093     { "fpscr", offsetof(CPUState, fpscr) },
2094     /* Next instruction pointer */
2095     { "nip|pc", offsetof(CPUState, nip) },
2096     { "lr", offsetof(CPUState, lr) },
2097     { "ctr", offsetof(CPUState, ctr) },
2098     { "decr", 0, &monitor_get_decr, },
2099     { "ccr", 0, &monitor_get_ccr, },
2100     /* Machine state register */
2101     { "msr", 0, &monitor_get_msr, },
2102     { "xer", 0, &monitor_get_xer, },
2103     { "tbu", 0, &monitor_get_tbu, },
2104     { "tbl", 0, &monitor_get_tbl, },
2105 #if defined(TARGET_PPC64)
2106     /* Address space register */
2107     { "asr", offsetof(CPUState, asr) },
2108 #endif
2109     /* Segment registers */
2110     { "sdr1", offsetof(CPUState, sdr1) },
2111     { "sr0", offsetof(CPUState, sr[0]) },
2112     { "sr1", offsetof(CPUState, sr[1]) },
2113     { "sr2", offsetof(CPUState, sr[2]) },
2114     { "sr3", offsetof(CPUState, sr[3]) },
2115     { "sr4", offsetof(CPUState, sr[4]) },
2116     { "sr5", offsetof(CPUState, sr[5]) },
2117     { "sr6", offsetof(CPUState, sr[6]) },
2118     { "sr7", offsetof(CPUState, sr[7]) },
2119     { "sr8", offsetof(CPUState, sr[8]) },
2120     { "sr9", offsetof(CPUState, sr[9]) },
2121     { "sr10", offsetof(CPUState, sr[10]) },
2122     { "sr11", offsetof(CPUState, sr[11]) },
2123     { "sr12", offsetof(CPUState, sr[12]) },
2124     { "sr13", offsetof(CPUState, sr[13]) },
2125     { "sr14", offsetof(CPUState, sr[14]) },
2126     { "sr15", offsetof(CPUState, sr[15]) },
2127     /* Too lazy to put BATs and SPRs ... */
2128 #elif defined(TARGET_SPARC)
2129     { "g0", offsetof(CPUState, gregs[0]) },
2130     { "g1", offsetof(CPUState, gregs[1]) },
2131     { "g2", offsetof(CPUState, gregs[2]) },
2132     { "g3", offsetof(CPUState, gregs[3]) },
2133     { "g4", offsetof(CPUState, gregs[4]) },
2134     { "g5", offsetof(CPUState, gregs[5]) },
2135     { "g6", offsetof(CPUState, gregs[6]) },
2136     { "g7", offsetof(CPUState, gregs[7]) },
2137     { "o0", 0, monitor_get_reg },
2138     { "o1", 1, monitor_get_reg },
2139     { "o2", 2, monitor_get_reg },
2140     { "o3", 3, monitor_get_reg },
2141     { "o4", 4, monitor_get_reg },
2142     { "o5", 5, monitor_get_reg },
2143     { "o6", 6, monitor_get_reg },
2144     { "o7", 7, monitor_get_reg },
2145     { "l0", 8, monitor_get_reg },
2146     { "l1", 9, monitor_get_reg },
2147     { "l2", 10, monitor_get_reg },
2148     { "l3", 11, monitor_get_reg },
2149     { "l4", 12, monitor_get_reg },
2150     { "l5", 13, monitor_get_reg },
2151     { "l6", 14, monitor_get_reg },
2152     { "l7", 15, monitor_get_reg },
2153     { "i0", 16, monitor_get_reg },
2154     { "i1", 17, monitor_get_reg },
2155     { "i2", 18, monitor_get_reg },
2156     { "i3", 19, monitor_get_reg },
2157     { "i4", 20, monitor_get_reg },
2158     { "i5", 21, monitor_get_reg },
2159     { "i6", 22, monitor_get_reg },
2160     { "i7", 23, monitor_get_reg },
2161     { "pc", offsetof(CPUState, pc) },
2162     { "npc", offsetof(CPUState, npc) },
2163     { "y", offsetof(CPUState, y) },
2164 #ifndef TARGET_SPARC64
2165     { "psr", 0, &monitor_get_psr, },
2166     { "wim", offsetof(CPUState, wim) },
2167 #endif
2168     { "tbr", offsetof(CPUState, tbr) },
2169     { "fsr", offsetof(CPUState, fsr) },
2170     { "f0", offsetof(CPUState, fpr[0]) },
2171     { "f1", offsetof(CPUState, fpr[1]) },
2172     { "f2", offsetof(CPUState, fpr[2]) },
2173     { "f3", offsetof(CPUState, fpr[3]) },
2174     { "f4", offsetof(CPUState, fpr[4]) },
2175     { "f5", offsetof(CPUState, fpr[5]) },
2176     { "f6", offsetof(CPUState, fpr[6]) },
2177     { "f7", offsetof(CPUState, fpr[7]) },
2178     { "f8", offsetof(CPUState, fpr[8]) },
2179     { "f9", offsetof(CPUState, fpr[9]) },
2180     { "f10", offsetof(CPUState, fpr[10]) },
2181     { "f11", offsetof(CPUState, fpr[11]) },
2182     { "f12", offsetof(CPUState, fpr[12]) },
2183     { "f13", offsetof(CPUState, fpr[13]) },
2184     { "f14", offsetof(CPUState, fpr[14]) },
2185     { "f15", offsetof(CPUState, fpr[15]) },
2186     { "f16", offsetof(CPUState, fpr[16]) },
2187     { "f17", offsetof(CPUState, fpr[17]) },
2188     { "f18", offsetof(CPUState, fpr[18]) },
2189     { "f19", offsetof(CPUState, fpr[19]) },
2190     { "f20", offsetof(CPUState, fpr[20]) },
2191     { "f21", offsetof(CPUState, fpr[21]) },
2192     { "f22", offsetof(CPUState, fpr[22]) },
2193     { "f23", offsetof(CPUState, fpr[23]) },
2194     { "f24", offsetof(CPUState, fpr[24]) },
2195     { "f25", offsetof(CPUState, fpr[25]) },
2196     { "f26", offsetof(CPUState, fpr[26]) },
2197     { "f27", offsetof(CPUState, fpr[27]) },
2198     { "f28", offsetof(CPUState, fpr[28]) },
2199     { "f29", offsetof(CPUState, fpr[29]) },
2200     { "f30", offsetof(CPUState, fpr[30]) },
2201     { "f31", offsetof(CPUState, fpr[31]) },
2202 #ifdef TARGET_SPARC64
2203     { "f32", offsetof(CPUState, fpr[32]) },
2204     { "f34", offsetof(CPUState, fpr[34]) },
2205     { "f36", offsetof(CPUState, fpr[36]) },
2206     { "f38", offsetof(CPUState, fpr[38]) },
2207     { "f40", offsetof(CPUState, fpr[40]) },
2208     { "f42", offsetof(CPUState, fpr[42]) },
2209     { "f44", offsetof(CPUState, fpr[44]) },
2210     { "f46", offsetof(CPUState, fpr[46]) },
2211     { "f48", offsetof(CPUState, fpr[48]) },
2212     { "f50", offsetof(CPUState, fpr[50]) },
2213     { "f52", offsetof(CPUState, fpr[52]) },
2214     { "f54", offsetof(CPUState, fpr[54]) },
2215     { "f56", offsetof(CPUState, fpr[56]) },
2216     { "f58", offsetof(CPUState, fpr[58]) },
2217     { "f60", offsetof(CPUState, fpr[60]) },
2218     { "f62", offsetof(CPUState, fpr[62]) },
2219     { "asi", offsetof(CPUState, asi) },
2220     { "pstate", offsetof(CPUState, pstate) },
2221     { "cansave", offsetof(CPUState, cansave) },
2222     { "canrestore", offsetof(CPUState, canrestore) },
2223     { "otherwin", offsetof(CPUState, otherwin) },
2224     { "wstate", offsetof(CPUState, wstate) },
2225     { "cleanwin", offsetof(CPUState, cleanwin) },
2226     { "fprs", offsetof(CPUState, fprs) },
2227 #endif
2228 #endif
2229     { NULL },
2230 };
2231
2232 static void expr_error(Monitor *mon, const char *msg)
2233 {
2234     monitor_printf(mon, "%s\n", msg);
2235     longjmp(expr_env, 1);
2236 }
2237
2238 /* return 0 if OK, -1 if not found, -2 if no CPU defined */
2239 static int get_monitor_def(target_long *pval, const char *name)
2240 {
2241     const MonitorDef *md;
2242     void *ptr;
2243
2244     for(md = monitor_defs; md->name != NULL; md++) {
2245         if (compare_cmd(name, md->name)) {
2246             if (md->get_value) {
2247                 *pval = md->get_value(md, md->offset);
2248             } else {
2249                 CPUState *env = mon_get_cpu();
2250                 if (!env)
2251                     return -2;
2252                 ptr = (uint8_t *)env + md->offset;
2253                 switch(md->type) {
2254                 case MD_I32:
2255                     *pval = *(int32_t *)ptr;
2256                     break;
2257                 case MD_TLONG:
2258                     *pval = *(target_long *)ptr;
2259                     break;
2260                 default:
2261                     *pval = 0;
2262                     break;
2263                 }
2264             }
2265             return 0;
2266         }
2267     }
2268     return -1;
2269 }
2270
2271 static void next(void)
2272 {
2273     if (*pch != '\0') {
2274         pch++;
2275         while (qemu_isspace(*pch))
2276             pch++;
2277     }
2278 }
2279
2280 static int64_t expr_sum(Monitor *mon);
2281
2282 static int64_t expr_unary(Monitor *mon)
2283 {
2284     int64_t n;
2285     char *p;
2286     int ret;
2287
2288     switch(*pch) {
2289     case '+':
2290         next();
2291         n = expr_unary(mon);
2292         break;
2293     case '-':
2294         next();
2295         n = -expr_unary(mon);
2296         break;
2297     case '~':
2298         next();
2299         n = ~expr_unary(mon);
2300         break;
2301     case '(':
2302         next();
2303         n = expr_sum(mon);
2304         if (*pch != ')') {
2305             expr_error(mon, "')' expected");
2306         }
2307         next();
2308         break;
2309     case '\'':
2310         pch++;
2311         if (*pch == '\0')
2312             expr_error(mon, "character constant expected");
2313         n = *pch;
2314         pch++;
2315         if (*pch != '\'')
2316             expr_error(mon, "missing terminating \' character");
2317         next();
2318         break;
2319     case '$':
2320         {
2321             char buf[128], *q;
2322             target_long reg=0;
2323
2324             pch++;
2325             q = buf;
2326             while ((*pch >= 'a' && *pch <= 'z') ||
2327                    (*pch >= 'A' && *pch <= 'Z') ||
2328                    (*pch >= '0' && *pch <= '9') ||
2329                    *pch == '_' || *pch == '.') {
2330                 if ((q - buf) < sizeof(buf) - 1)
2331                     *q++ = *pch;
2332                 pch++;
2333             }
2334             while (qemu_isspace(*pch))
2335                 pch++;
2336             *q = 0;
2337             ret = get_monitor_def(&reg, buf);
2338             if (ret == -1)
2339                 expr_error(mon, "unknown register");
2340             else if (ret == -2)
2341                 expr_error(mon, "no cpu defined");
2342             n = reg;
2343         }
2344         break;
2345     case '\0':
2346         expr_error(mon, "unexpected end of expression");
2347         n = 0;
2348         break;
2349     default:
2350 #if TARGET_PHYS_ADDR_BITS > 32
2351         n = strtoull(pch, &p, 0);
2352 #else
2353         n = strtoul(pch, &p, 0);
2354 #endif
2355         if (pch == p) {
2356             expr_error(mon, "invalid char in expression");
2357         }
2358         pch = p;
2359         while (qemu_isspace(*pch))
2360             pch++;
2361         break;
2362     }
2363     return n;
2364 }
2365
2366
2367 static int64_t expr_prod(Monitor *mon)
2368 {
2369     int64_t val, val2;
2370     int op;
2371
2372     val = expr_unary(mon);
2373     for(;;) {
2374         op = *pch;
2375         if (op != '*' && op != '/' && op != '%')
2376             break;
2377         next();
2378         val2 = expr_unary(mon);
2379         switch(op) {
2380         default:
2381         case '*':
2382             val *= val2;
2383             break;
2384         case '/':
2385         case '%':
2386             if (val2 == 0)
2387                 expr_error(mon, "division by zero");
2388             if (op == '/')
2389                 val /= val2;
2390             else
2391                 val %= val2;
2392             break;
2393         }
2394     }
2395     return val;
2396 }
2397
2398 static int64_t expr_logic(Monitor *mon)
2399 {
2400     int64_t val, val2;
2401     int op;
2402
2403     val = expr_prod(mon);
2404     for(;;) {
2405         op = *pch;
2406         if (op != '&' && op != '|' && op != '^')
2407             break;
2408         next();
2409         val2 = expr_prod(mon);
2410         switch(op) {
2411         default:
2412         case '&':
2413             val &= val2;
2414             break;
2415         case '|':
2416             val |= val2;
2417             break;
2418         case '^':
2419             val ^= val2;
2420             break;
2421         }
2422     }
2423     return val;
2424 }
2425
2426 static int64_t expr_sum(Monitor *mon)
2427 {
2428     int64_t val, val2;
2429     int op;
2430
2431     val = expr_logic(mon);
2432     for(;;) {
2433         op = *pch;
2434         if (op != '+' && op != '-')
2435             break;
2436         next();
2437         val2 = expr_logic(mon);
2438         if (op == '+')
2439             val += val2;
2440         else
2441             val -= val2;
2442     }
2443     return val;
2444 }
2445
2446 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2447 {
2448     pch = *pp;
2449     if (setjmp(expr_env)) {
2450         *pp = pch;
2451         return -1;
2452     }
2453     while (qemu_isspace(*pch))
2454         pch++;
2455     *pval = expr_sum(mon);
2456     *pp = pch;
2457     return 0;
2458 }
2459
2460 static int get_str(char *buf, int buf_size, const char **pp)
2461 {
2462     const char *p;
2463     char *q;
2464     int c;
2465
2466     q = buf;
2467     p = *pp;
2468     while (qemu_isspace(*p))
2469         p++;
2470     if (*p == '\0') {
2471     fail:
2472         *q = '\0';
2473         *pp = p;
2474         return -1;
2475     }
2476     if (*p == '\"') {
2477         p++;
2478         while (*p != '\0' && *p != '\"') {
2479             if (*p == '\\') {
2480                 p++;
2481                 c = *p++;
2482                 switch(c) {
2483                 case 'n':
2484                     c = '\n';
2485                     break;
2486                 case 'r':
2487                     c = '\r';
2488                     break;
2489                 case '\\':
2490                 case '\'':
2491                 case '\"':
2492                     break;
2493                 default:
2494                     qemu_printf("unsupported escape code: '\\%c'\n", c);
2495                     goto fail;
2496                 }
2497                 if ((q - buf) < buf_size - 1) {
2498                     *q++ = c;
2499                 }
2500             } else {
2501                 if ((q - buf) < buf_size - 1) {
2502                     *q++ = *p;
2503                 }
2504                 p++;
2505             }
2506         }
2507         if (*p != '\"') {
2508             qemu_printf("unterminated string\n");
2509             goto fail;
2510         }
2511         p++;
2512     } else {
2513         while (*p != '\0' && !qemu_isspace(*p)) {
2514             if ((q - buf) < buf_size - 1) {
2515                 *q++ = *p;
2516             }
2517             p++;
2518         }
2519     }
2520     *q = '\0';
2521     *pp = p;
2522     return 0;
2523 }
2524
2525 /*
2526  * Store the command-name in cmdname, and return a pointer to
2527  * the remaining of the command string.
2528  */
2529 static const char *get_command_name(const char *cmdline,
2530                                     char *cmdname, size_t nlen)
2531 {
2532     size_t len;
2533     const char *p, *pstart;
2534
2535     p = cmdline;
2536     while (qemu_isspace(*p))
2537         p++;
2538     if (*p == '\0')
2539         return NULL;
2540     pstart = p;
2541     while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2542         p++;
2543     len = p - pstart;
2544     if (len > nlen - 1)
2545         len = nlen - 1;
2546     memcpy(cmdname, pstart, len);
2547     cmdname[len] = '\0';
2548     return p;
2549 }
2550
2551 /**
2552  * Read key of 'type' into 'key' and return the current
2553  * 'type' pointer.
2554  */
2555 static char *key_get_info(const char *type, char **key)
2556 {
2557     size_t len;
2558     char *p, *str;
2559
2560     if (*type == ',')
2561         type++;
2562
2563     p = strchr(type, ':');
2564     if (!p) {
2565         *key = NULL;
2566         return NULL;
2567     }
2568     len = p - type;
2569
2570     str = qemu_malloc(len + 1);
2571     memcpy(str, type, len);
2572     str[len] = '\0';
2573
2574     *key = str;
2575     return ++p;
2576 }
2577
2578 static int default_fmt_format = 'x';
2579 static int default_fmt_size = 4;
2580
2581 #define MAX_ARGS 16
2582
2583 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2584                                               const char *cmdline,
2585                                               QDict *qdict)
2586 {
2587     const char *p, *typestr;
2588     int c;
2589     const mon_cmd_t *cmd;
2590     char cmdname[256];
2591     char buf[1024];
2592     char *key;
2593
2594 #ifdef DEBUG
2595     monitor_printf(mon, "command='%s'\n", cmdline);
2596 #endif
2597
2598     /* extract the command name */
2599     p = get_command_name(cmdline, cmdname, sizeof(cmdname));
2600     if (!p)
2601         return NULL;
2602
2603     /* find the command */
2604     for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
2605         if (compare_cmd(cmdname, cmd->name))
2606             break;
2607     }
2608
2609     if (cmd->name == NULL) {
2610         monitor_printf(mon, "unknown command: '%s'\n", cmdname);
2611         return NULL;
2612     }
2613
2614     /* parse the parameters */
2615     typestr = cmd->args_type;
2616     for(;;) {
2617         typestr = key_get_info(typestr, &key);
2618         if (!typestr)
2619             break;
2620         c = *typestr;
2621         typestr++;
2622         switch(c) {
2623         case 'F':
2624         case 'B':
2625         case 's':
2626             {
2627                 int ret;
2628
2629                 while (qemu_isspace(*p))
2630                     p++;
2631                 if (*typestr == '?') {
2632                     typestr++;
2633                     if (*p == '\0') {
2634                         /* no optional string: NULL argument */
2635                         break;
2636                     }
2637                 }
2638                 ret = get_str(buf, sizeof(buf), &p);
2639                 if (ret < 0) {
2640                     switch(c) {
2641                     case 'F':
2642                         monitor_printf(mon, "%s: filename expected\n",
2643                                        cmdname);
2644                         break;
2645                     case 'B':
2646                         monitor_printf(mon, "%s: block device name expected\n",
2647                                        cmdname);
2648                         break;
2649                     default:
2650                         monitor_printf(mon, "%s: string expected\n", cmdname);
2651                         break;
2652                     }
2653                     goto fail;
2654                 }
2655                 qdict_put(qdict, key, qstring_from_str(buf));
2656             }
2657             break;
2658         case '/':
2659             {
2660                 int count, format, size;
2661
2662                 while (qemu_isspace(*p))
2663                     p++;
2664                 if (*p == '/') {
2665                     /* format found */
2666                     p++;
2667                     count = 1;
2668                     if (qemu_isdigit(*p)) {
2669                         count = 0;
2670                         while (qemu_isdigit(*p)) {
2671                             count = count * 10 + (*p - '0');
2672                             p++;
2673                         }
2674                     }
2675                     size = -1;
2676                     format = -1;
2677                     for(;;) {
2678                         switch(*p) {
2679                         case 'o':
2680                         case 'd':
2681                         case 'u':
2682                         case 'x':
2683                         case 'i':
2684                         case 'c':
2685                             format = *p++;
2686                             break;
2687                         case 'b':
2688                             size = 1;
2689                             p++;
2690                             break;
2691                         case 'h':
2692                             size = 2;
2693                             p++;
2694                             break;
2695                         case 'w':
2696                             size = 4;
2697                             p++;
2698                             break;
2699                         case 'g':
2700                         case 'L':
2701                             size = 8;
2702                             p++;
2703                             break;
2704                         default:
2705                             goto next;
2706                         }
2707                     }
2708                 next:
2709                     if (*p != '\0' && !qemu_isspace(*p)) {
2710                         monitor_printf(mon, "invalid char in format: '%c'\n",
2711                                        *p);
2712                         goto fail;
2713                     }
2714                     if (format < 0)
2715                         format = default_fmt_format;
2716                     if (format != 'i') {
2717                         /* for 'i', not specifying a size gives -1 as size */
2718                         if (size < 0)
2719                             size = default_fmt_size;
2720                         default_fmt_size = size;
2721                     }
2722                     default_fmt_format = format;
2723                 } else {
2724                     count = 1;
2725                     format = default_fmt_format;
2726                     if (format != 'i') {
2727                         size = default_fmt_size;
2728                     } else {
2729                         size = -1;
2730                     }
2731                 }
2732                 qdict_put(qdict, "count", qint_from_int(count));
2733                 qdict_put(qdict, "format", qint_from_int(format));
2734                 qdict_put(qdict, "size", qint_from_int(size));
2735             }
2736             break;
2737         case 'i':
2738         case 'l':
2739             {
2740                 int64_t val;
2741
2742                 while (qemu_isspace(*p))
2743                     p++;
2744                 if (*typestr == '?' || *typestr == '.') {
2745                     if (*typestr == '?') {
2746                         if (*p == '\0') {
2747                             typestr++;
2748                             break;
2749                         }
2750                     } else {
2751                         if (*p == '.') {
2752                             p++;
2753                             while (qemu_isspace(*p))
2754                                 p++;
2755                         } else {
2756                             typestr++;
2757                             break;
2758                         }
2759                     }
2760                     typestr++;
2761                 }
2762                 if (get_expr(mon, &val, &p))
2763                     goto fail;
2764                 /* Check if 'i' is greater than 32-bit */
2765                 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2766                     monitor_printf(mon, "\'%s\' has failed: ", cmdname);
2767                     monitor_printf(mon, "integer is for 32-bit values\n");
2768                     goto fail;
2769                 }
2770                 qdict_put(qdict, key, qint_from_int(val));
2771             }
2772             break;
2773         case '-':
2774             {
2775                 int has_option;
2776                 /* option */
2777
2778                 c = *typestr++;
2779                 if (c == '\0')
2780                     goto bad_type;
2781                 while (qemu_isspace(*p))
2782                     p++;
2783                 has_option = 0;
2784                 if (*p == '-') {
2785                     p++;
2786                     if (*p != c) {
2787                         monitor_printf(mon, "%s: unsupported option -%c\n",
2788                                        cmdname, *p);
2789                         goto fail;
2790                     }
2791                     p++;
2792                     has_option = 1;
2793                 }
2794                 qdict_put(qdict, key, qint_from_int(has_option));
2795             }
2796             break;
2797         default:
2798         bad_type:
2799             monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
2800             goto fail;
2801         }
2802         qemu_free(key);
2803         key = NULL;
2804     }
2805     /* check that all arguments were parsed */
2806     while (qemu_isspace(*p))
2807         p++;
2808     if (*p != '\0') {
2809         monitor_printf(mon, "%s: extraneous characters at the end of line\n",
2810                        cmdname);
2811         goto fail;
2812     }
2813
2814     return cmd;
2815
2816 fail:
2817     qemu_free(key);
2818     return NULL;
2819 }
2820
2821 static void monitor_handle_command(Monitor *mon, const char *cmdline)
2822 {
2823     QDict *qdict;
2824     const mon_cmd_t *cmd;
2825
2826     qdict = qdict_new();
2827
2828     cmd = monitor_parse_command(mon, cmdline, qdict);
2829     if (cmd) {
2830         void (*handler)(Monitor *mon, const QDict *qdict);
2831
2832         qemu_errors_to_mon(mon);
2833
2834         handler = cmd->handler;
2835         handler(mon, qdict);
2836
2837         qemu_errors_to_previous();
2838     }
2839
2840     QDECREF(qdict);
2841 }
2842
2843 static void cmd_completion(const char *name, const char *list)
2844 {
2845     const char *p, *pstart;
2846     char cmd[128];
2847     int len;
2848
2849     p = list;
2850     for(;;) {
2851         pstart = p;
2852         p = strchr(p, '|');
2853         if (!p)
2854             p = pstart + strlen(pstart);
2855         len = p - pstart;
2856         if (len > sizeof(cmd) - 2)
2857             len = sizeof(cmd) - 2;
2858         memcpy(cmd, pstart, len);
2859         cmd[len] = '\0';
2860         if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
2861             readline_add_completion(cur_mon->rs, cmd);
2862         }
2863         if (*p == '\0')
2864             break;
2865         p++;
2866     }
2867 }
2868
2869 static void file_completion(const char *input)
2870 {
2871     DIR *ffs;
2872     struct dirent *d;
2873     char path[1024];
2874     char file[1024], file_prefix[1024];
2875     int input_path_len;
2876     const char *p;
2877
2878     p = strrchr(input, '/');
2879     if (!p) {
2880         input_path_len = 0;
2881         pstrcpy(file_prefix, sizeof(file_prefix), input);
2882         pstrcpy(path, sizeof(path), ".");
2883     } else {
2884         input_path_len = p - input + 1;
2885         memcpy(path, input, input_path_len);
2886         if (input_path_len > sizeof(path) - 1)
2887             input_path_len = sizeof(path) - 1;
2888         path[input_path_len] = '\0';
2889         pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
2890     }
2891 #ifdef DEBUG_COMPLETION
2892     monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
2893                    input, path, file_prefix);
2894 #endif
2895     ffs = opendir(path);
2896     if (!ffs)
2897         return;
2898     for(;;) {
2899         struct stat sb;
2900         d = readdir(ffs);
2901         if (!d)
2902             break;
2903         if (strstart(d->d_name, file_prefix, NULL)) {
2904             memcpy(file, input, input_path_len);
2905             if (input_path_len < sizeof(file))
2906                 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
2907                         d->d_name);
2908             /* stat the file to find out if it's a directory.
2909              * In that case add a slash to speed up typing long paths
2910              */
2911             stat(file, &sb);
2912             if(S_ISDIR(sb.st_mode))
2913                 pstrcat(file, sizeof(file), "/");
2914             readline_add_completion(cur_mon->rs, file);
2915         }
2916     }
2917     closedir(ffs);
2918 }
2919
2920 static void block_completion_it(void *opaque, BlockDriverState *bs)
2921 {
2922     const char *name = bdrv_get_device_name(bs);
2923     const char *input = opaque;
2924
2925     if (input[0] == '\0' ||
2926         !strncmp(name, (char *)input, strlen(input))) {
2927         readline_add_completion(cur_mon->rs, name);
2928     }
2929 }
2930
2931 /* NOTE: this parser is an approximate form of the real command parser */
2932 static void parse_cmdline(const char *cmdline,
2933                          int *pnb_args, char **args)
2934 {
2935     const char *p;
2936     int nb_args, ret;
2937     char buf[1024];
2938
2939     p = cmdline;
2940     nb_args = 0;
2941     for(;;) {
2942         while (qemu_isspace(*p))
2943             p++;
2944         if (*p == '\0')
2945             break;
2946         if (nb_args >= MAX_ARGS)
2947             break;
2948         ret = get_str(buf, sizeof(buf), &p);
2949         args[nb_args] = qemu_strdup(buf);
2950         nb_args++;
2951         if (ret < 0)
2952             break;
2953     }
2954     *pnb_args = nb_args;
2955 }
2956
2957 static const char *next_arg_type(const char *typestr)
2958 {
2959     const char *p = strchr(typestr, ':');
2960     return (p != NULL ? ++p : typestr);
2961 }
2962
2963 static void monitor_find_completion(const char *cmdline)
2964 {
2965     const char *cmdname;
2966     char *args[MAX_ARGS];
2967     int nb_args, i, len;
2968     const char *ptype, *str;
2969     const mon_cmd_t *cmd;
2970     const KeyDef *key;
2971
2972     parse_cmdline(cmdline, &nb_args, args);
2973 #ifdef DEBUG_COMPLETION
2974     for(i = 0; i < nb_args; i++) {
2975         monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
2976     }
2977 #endif
2978
2979     /* if the line ends with a space, it means we want to complete the
2980        next arg */
2981     len = strlen(cmdline);
2982     if (len > 0 && qemu_isspace(cmdline[len - 1])) {
2983         if (nb_args >= MAX_ARGS)
2984             return;
2985         args[nb_args++] = qemu_strdup("");
2986     }
2987     if (nb_args <= 1) {
2988         /* command completion */
2989         if (nb_args == 0)
2990             cmdname = "";
2991         else
2992             cmdname = args[0];
2993         readline_set_completion_index(cur_mon->rs, strlen(cmdname));
2994         for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
2995             cmd_completion(cmdname, cmd->name);
2996         }
2997     } else {
2998         /* find the command */
2999         for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
3000             if (compare_cmd(args[0], cmd->name))
3001                 goto found;
3002         }
3003         return;
3004     found:
3005         ptype = next_arg_type(cmd->args_type);
3006         for(i = 0; i < nb_args - 2; i++) {
3007             if (*ptype != '\0') {
3008                 ptype = next_arg_type(ptype);
3009                 while (*ptype == '?')
3010                     ptype = next_arg_type(ptype);
3011             }
3012         }
3013         str = args[nb_args - 1];
3014         if (*ptype == '-' && ptype[1] != '\0') {
3015             ptype += 2;
3016         }
3017         switch(*ptype) {
3018         case 'F':
3019             /* file completion */
3020             readline_set_completion_index(cur_mon->rs, strlen(str));
3021             file_completion(str);
3022             break;
3023         case 'B':
3024             /* block device name completion */
3025             readline_set_completion_index(cur_mon->rs, strlen(str));
3026             bdrv_iterate(block_completion_it, (void *)str);
3027             break;
3028         case 's':
3029             /* XXX: more generic ? */
3030             if (!strcmp(cmd->name, "info")) {
3031                 readline_set_completion_index(cur_mon->rs, strlen(str));
3032                 for(cmd = info_cmds; cmd->name != NULL; cmd++) {
3033                     cmd_completion(str, cmd->name);
3034                 }
3035             } else if (!strcmp(cmd->name, "sendkey")) {
3036                 char *sep = strrchr(str, '-');
3037                 if (sep)
3038                     str = sep + 1;
3039                 readline_set_completion_index(cur_mon->rs, strlen(str));
3040                 for(key = key_defs; key->name != NULL; key++) {
3041                     cmd_completion(str, key->name);
3042                 }
3043             } else if (!strcmp(cmd->name, "help|?")) {
3044                 readline_set_completion_index(cur_mon->rs, strlen(str));
3045                 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
3046                     cmd_completion(str, cmd->name);
3047                 }
3048             }
3049             break;
3050         default:
3051             break;
3052         }
3053     }
3054     for(i = 0; i < nb_args; i++)
3055         qemu_free(args[i]);
3056 }
3057
3058 static int monitor_can_read(void *opaque)
3059 {
3060     Monitor *mon = opaque;
3061
3062     return (mon->suspend_cnt == 0) ? 128 : 0;
3063 }
3064
3065 static void monitor_read(void *opaque, const uint8_t *buf, int size)
3066 {
3067     Monitor *old_mon = cur_mon;
3068     int i;
3069
3070     cur_mon = opaque;
3071
3072     if (cur_mon->rs) {
3073         for (i = 0; i < size; i++)
3074             readline_handle_byte(cur_mon->rs, buf[i]);
3075     } else {
3076         if (size == 0 || buf[size - 1] != 0)
3077             monitor_printf(cur_mon, "corrupted command\n");
3078         else
3079             monitor_handle_command(cur_mon, (char *)buf);
3080     }
3081
3082     cur_mon = old_mon;
3083 }
3084
3085 static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
3086 {
3087     monitor_suspend(mon);
3088     monitor_handle_command(mon, cmdline);
3089     monitor_resume(mon);
3090 }
3091
3092 int monitor_suspend(Monitor *mon)
3093 {
3094     if (!mon->rs)
3095         return -ENOTTY;
3096     mon->suspend_cnt++;
3097     return 0;
3098 }
3099
3100 void monitor_resume(Monitor *mon)
3101 {
3102     if (!mon->rs)
3103         return;
3104     if (--mon->suspend_cnt == 0)
3105         readline_show_prompt(mon->rs);
3106 }
3107
3108 static void monitor_event(void *opaque, int event)
3109 {
3110     Monitor *mon = opaque;
3111
3112     switch (event) {
3113     case CHR_EVENT_MUX_IN:
3114         readline_restart(mon->rs);
3115         monitor_resume(mon);
3116         monitor_flush(mon);
3117         break;
3118
3119     case CHR_EVENT_MUX_OUT:
3120         if (mon->suspend_cnt == 0)
3121             monitor_printf(mon, "\n");
3122         monitor_flush(mon);
3123         monitor_suspend(mon);
3124         break;
3125
3126     case CHR_EVENT_RESET:
3127         monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
3128                        "information\n", QEMU_VERSION);
3129         if (mon->chr->focus == 0)
3130             readline_show_prompt(mon->rs);
3131         break;
3132     }
3133 }
3134
3135
3136 /*
3137  * Local variables:
3138  *  c-indent-level: 4
3139  *  c-basic-offset: 4
3140  *  tab-width: 8
3141  * End:
3142  */
3143
3144 void monitor_init(CharDriverState *chr, int flags)
3145 {
3146     static int is_first_init = 1;
3147     Monitor *mon;
3148
3149     if (is_first_init) {
3150         key_timer = qemu_new_timer(vm_clock, release_keys, NULL);
3151         is_first_init = 0;
3152     }
3153
3154     mon = qemu_mallocz(sizeof(*mon));
3155
3156     mon->chr = chr;
3157     mon->flags = flags;
3158     if (mon->chr->focus != 0)
3159         mon->suspend_cnt = 1; /* mux'ed monitors start suspended */
3160     if (flags & MONITOR_USE_READLINE) {
3161         mon->rs = readline_init(mon, monitor_find_completion);
3162         monitor_read_command(mon, 0);
3163     }
3164
3165     qemu_chr_add_handlers(chr, monitor_can_read, monitor_read, monitor_event,
3166                           mon);
3167
3168     LIST_INSERT_HEAD(&mon_list, mon, entry);
3169     if (!cur_mon || (flags & MONITOR_IS_DEFAULT))
3170         cur_mon = mon;
3171 }
3172
3173 static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
3174 {
3175     BlockDriverState *bs = opaque;
3176     int ret = 0;
3177
3178     if (bdrv_set_key(bs, password) != 0) {
3179         monitor_printf(mon, "invalid password\n");
3180         ret = -EPERM;
3181     }
3182     if (mon->password_completion_cb)
3183         mon->password_completion_cb(mon->password_opaque, ret);
3184
3185     monitor_read_command(mon, 1);
3186 }
3187
3188 void monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
3189                                  BlockDriverCompletionFunc *completion_cb,
3190                                  void *opaque)
3191 {
3192     int err;
3193
3194     if (!bdrv_key_required(bs)) {
3195         if (completion_cb)
3196             completion_cb(opaque, 0);
3197         return;
3198     }
3199
3200     monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
3201                    bdrv_get_encrypted_filename(bs));
3202
3203     mon->password_completion_cb = completion_cb;
3204     mon->password_opaque = opaque;
3205
3206     err = monitor_read_password(mon, bdrv_password_cb, bs);
3207
3208     if (err && completion_cb)
3209         completion_cb(opaque, err);
3210 }
3211
3212 typedef struct QemuErrorSink QemuErrorSink;
3213 struct QemuErrorSink {
3214     enum {
3215         ERR_SINK_FILE,
3216         ERR_SINK_MONITOR,
3217     } dest;
3218     union {
3219         FILE    *fp;
3220         Monitor *mon;
3221     };
3222     QemuErrorSink *previous;
3223 };
3224
3225 static QemuErrorSink *qemu_error_sink;
3226
3227 void qemu_errors_to_file(FILE *fp)
3228 {
3229     QemuErrorSink *sink;
3230
3231     sink = qemu_mallocz(sizeof(*sink));
3232     sink->dest = ERR_SINK_FILE;
3233     sink->fp = fp;
3234     sink->previous = qemu_error_sink;
3235     qemu_error_sink = sink;
3236 }
3237
3238 void qemu_errors_to_mon(Monitor *mon)
3239 {
3240     QemuErrorSink *sink;
3241
3242     sink = qemu_mallocz(sizeof(*sink));
3243     sink->dest = ERR_SINK_MONITOR;
3244     sink->mon = mon;
3245     sink->previous = qemu_error_sink;
3246     qemu_error_sink = sink;
3247 }
3248
3249 void qemu_errors_to_previous(void)
3250 {
3251     QemuErrorSink *sink;
3252
3253     assert(qemu_error_sink != NULL);
3254     sink = qemu_error_sink;
3255     qemu_error_sink = sink->previous;
3256     qemu_free(sink);
3257 }
3258
3259 void qemu_error(const char *fmt, ...)
3260 {
3261     va_list args;
3262
3263     assert(qemu_error_sink != NULL);
3264     switch (qemu_error_sink->dest) {
3265     case ERR_SINK_FILE:
3266         va_start(args, fmt);
3267         vfprintf(qemu_error_sink->fp, fmt, args);
3268         va_end(args);
3269         break;
3270     case ERR_SINK_MONITOR:
3271         va_start(args, fmt);
3272         monitor_vprintf(qemu_error_sink->mon, fmt, args);
3273         va_end(args);
3274         break;
3275     }
3276 }