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