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