]> git.proxmox.com Git - qemu.git/blob - monitor.c
Merge remote-tracking branch 'qmp/queue/qmp' into staging
[qemu.git] / monitor.c
1 /*
2 * QEMU monitor
3 *
4 * Copyright (c) 2003-2004 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 #include <dirent.h>
25 #include "hw/hw.h"
26 #include "hw/qdev.h"
27 #include "hw/usb.h"
28 #include "hw/pcmcia.h"
29 #include "hw/pc.h"
30 #include "hw/pci.h"
31 #include "hw/watchdog.h"
32 #include "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 "cpu.h"
60 #include "trace.h"
61 #include "trace/control.h"
62 #ifdef CONFIG_TRACE_SIMPLE
63 #include "trace/simple.h"
64 #endif
65 #include "ui/qemu-spice.h"
66 #include "memory.h"
67 #include "qmp-commands.h"
68 #include "hmp.h"
69 #include "qemu-thread.h"
70
71 /* for pic/irq_info */
72 #if defined(TARGET_SPARC)
73 #include "hw/sun4m.h"
74 #endif
75 #include "hw/lm32_pic.h"
76
77 //#define DEBUG
78 //#define DEBUG_COMPLETION
79
80 /*
81 * Supported types:
82 *
83 * 'F' filename
84 * 'B' block device name
85 * 's' string (accept optional quote)
86 * 'O' option string of the form NAME=VALUE,...
87 * parsed according to QemuOptsList given by its name
88 * Example: 'device:O' uses qemu_device_opts.
89 * Restriction: only lists with empty desc are supported
90 * TODO lift the restriction
91 * 'i' 32 bit integer
92 * 'l' target long (32 or 64 bit)
93 * 'M' Non-negative target long (32 or 64 bit), in user mode the
94 * value is multiplied by 2^20 (think Mebibyte)
95 * 'o' octets (aka bytes)
96 * user mode accepts an optional T, t, G, g, M, m, K, k
97 * suffix, which multiplies the value by 2^40 for
98 * suffixes T and t, 2^30 for suffixes G and g, 2^20 for
99 * M and m, 2^10 for K and k
100 * 'T' double
101 * user mode accepts an optional ms, us, ns suffix,
102 * which divides the value by 1e3, 1e6, 1e9, respectively
103 * '/' optional gdb-like print format (like "/10x")
104 *
105 * '?' optional type (for all types, except '/')
106 * '.' other form of optional type (for 'i' and 'l')
107 * 'b' boolean
108 * user mode accepts "on" or "off"
109 * '-' optional parameter (eg. '-f')
110 *
111 */
112
113 typedef struct MonitorCompletionData MonitorCompletionData;
114 struct MonitorCompletionData {
115 Monitor *mon;
116 void (*user_print)(Monitor *mon, const QObject *data);
117 };
118
119 typedef struct mon_cmd_t {
120 const char *name;
121 const char *args_type;
122 const char *params;
123 const char *help;
124 void (*user_print)(Monitor *mon, const QObject *data);
125 union {
126 void (*info)(Monitor *mon);
127 void (*cmd)(Monitor *mon, const QDict *qdict);
128 int (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data);
129 int (*cmd_async)(Monitor *mon, const QDict *params,
130 MonitorCompletion *cb, void *opaque);
131 } mhandler;
132 int flags;
133 } mon_cmd_t;
134
135 /* file descriptors passed via SCM_RIGHTS */
136 typedef struct mon_fd_t mon_fd_t;
137 struct mon_fd_t {
138 char *name;
139 int fd;
140 QLIST_ENTRY(mon_fd_t) next;
141 };
142
143 /* file descriptor associated with a file descriptor set */
144 typedef struct MonFdsetFd MonFdsetFd;
145 struct MonFdsetFd {
146 int fd;
147 bool removed;
148 char *opaque;
149 QLIST_ENTRY(MonFdsetFd) next;
150 };
151
152 /* file descriptor set containing fds passed via SCM_RIGHTS */
153 typedef struct MonFdset MonFdset;
154 struct MonFdset {
155 int64_t id;
156 QLIST_HEAD(, MonFdsetFd) fds;
157 QLIST_HEAD(, MonFdsetFd) dup_fds;
158 QLIST_ENTRY(MonFdset) next;
159 };
160
161 typedef struct MonitorControl {
162 QObject *id;
163 JSONMessageParser parser;
164 int command_mode;
165 } MonitorControl;
166
167 /*
168 * To prevent flooding clients, events can be throttled. The
169 * throttling is calculated globally, rather than per-Monitor
170 * instance.
171 */
172 typedef struct MonitorEventState {
173 MonitorEvent event; /* Event being tracked */
174 int64_t rate; /* Period over which to throttle. 0 to disable */
175 int64_t last; /* Time at which event was last emitted */
176 QEMUTimer *timer; /* Timer for handling delayed events */
177 QObject *data; /* Event pending delayed dispatch */
178 } MonitorEventState;
179
180 struct Monitor {
181 CharDriverState *chr;
182 int mux_out;
183 int reset_seen;
184 int flags;
185 int suspend_cnt;
186 uint8_t outbuf[1024];
187 int outbuf_index;
188 ReadLineState *rs;
189 MonitorControl *mc;
190 CPUArchState *mon_cpu;
191 BlockDriverCompletionFunc *password_completion_cb;
192 void *password_opaque;
193 QError *error;
194 QLIST_HEAD(,mon_fd_t) fds;
195 QLIST_ENTRY(Monitor) entry;
196 };
197
198 /* QMP checker flags */
199 #define QMP_ACCEPT_UNKNOWNS 1
200
201 static QLIST_HEAD(mon_list, Monitor) mon_list;
202 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
203 static int mon_refcount;
204
205 static mon_cmd_t mon_cmds[];
206 static mon_cmd_t info_cmds[];
207
208 static const mon_cmd_t qmp_cmds[];
209
210 Monitor *cur_mon;
211 Monitor *default_mon;
212
213 static void monitor_command_cb(Monitor *mon, const char *cmdline,
214 void *opaque);
215
216 static inline int qmp_cmd_mode(const Monitor *mon)
217 {
218 return (mon->mc ? mon->mc->command_mode : 0);
219 }
220
221 /* Return true if in control mode, false otherwise */
222 static inline int monitor_ctrl_mode(const Monitor *mon)
223 {
224 return (mon->flags & MONITOR_USE_CONTROL);
225 }
226
227 /* Return non-zero iff we have a current monitor, and it is in QMP mode. */
228 int monitor_cur_is_qmp(void)
229 {
230 return cur_mon && monitor_ctrl_mode(cur_mon);
231 }
232
233 void monitor_read_command(Monitor *mon, int show_prompt)
234 {
235 if (!mon->rs)
236 return;
237
238 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
239 if (show_prompt)
240 readline_show_prompt(mon->rs);
241 }
242
243 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
244 void *opaque)
245 {
246 if (monitor_ctrl_mode(mon)) {
247 qerror_report(QERR_MISSING_PARAMETER, "password");
248 return -EINVAL;
249 } else if (mon->rs) {
250 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
251 /* prompt is printed on return from the command handler */
252 return 0;
253 } else {
254 monitor_printf(mon, "terminal does not support password prompting\n");
255 return -ENOTTY;
256 }
257 }
258
259 void monitor_flush(Monitor *mon)
260 {
261 if (mon && mon->outbuf_index != 0 && !mon->mux_out) {
262 qemu_chr_fe_write(mon->chr, mon->outbuf, mon->outbuf_index);
263 mon->outbuf_index = 0;
264 }
265 }
266
267 /* flush at every end of line or if the buffer is full */
268 static void monitor_puts(Monitor *mon, const char *str)
269 {
270 char c;
271
272 for(;;) {
273 c = *str++;
274 if (c == '\0')
275 break;
276 if (c == '\n')
277 mon->outbuf[mon->outbuf_index++] = '\r';
278 mon->outbuf[mon->outbuf_index++] = c;
279 if (mon->outbuf_index >= (sizeof(mon->outbuf) - 1)
280 || c == '\n')
281 monitor_flush(mon);
282 }
283 }
284
285 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
286 {
287 char buf[4096];
288
289 if (!mon)
290 return;
291
292 if (monitor_ctrl_mode(mon)) {
293 return;
294 }
295
296 vsnprintf(buf, sizeof(buf), fmt, ap);
297 monitor_puts(mon, buf);
298 }
299
300 void monitor_printf(Monitor *mon, const char *fmt, ...)
301 {
302 va_list ap;
303 va_start(ap, fmt);
304 monitor_vprintf(mon, fmt, ap);
305 va_end(ap);
306 }
307
308 void monitor_print_filename(Monitor *mon, const char *filename)
309 {
310 int i;
311
312 for (i = 0; filename[i]; i++) {
313 switch (filename[i]) {
314 case ' ':
315 case '"':
316 case '\\':
317 monitor_printf(mon, "\\%c", filename[i]);
318 break;
319 case '\t':
320 monitor_printf(mon, "\\t");
321 break;
322 case '\r':
323 monitor_printf(mon, "\\r");
324 break;
325 case '\n':
326 monitor_printf(mon, "\\n");
327 break;
328 default:
329 monitor_printf(mon, "%c", filename[i]);
330 break;
331 }
332 }
333 }
334
335 static int GCC_FMT_ATTR(2, 3) monitor_fprintf(FILE *stream,
336 const char *fmt, ...)
337 {
338 va_list ap;
339 va_start(ap, fmt);
340 monitor_vprintf((Monitor *)stream, fmt, ap);
341 va_end(ap);
342 return 0;
343 }
344
345 static void monitor_user_noop(Monitor *mon, const QObject *data) { }
346
347 static inline int handler_is_qobject(const mon_cmd_t *cmd)
348 {
349 return cmd->user_print != NULL;
350 }
351
352 static inline bool handler_is_async(const mon_cmd_t *cmd)
353 {
354 return cmd->flags & MONITOR_CMD_ASYNC;
355 }
356
357 static inline int monitor_has_error(const Monitor *mon)
358 {
359 return mon->error != NULL;
360 }
361
362 static void monitor_json_emitter(Monitor *mon, const QObject *data)
363 {
364 QString *json;
365
366 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
367 qobject_to_json(data);
368 assert(json != NULL);
369
370 qstring_append_chr(json, '\n');
371 monitor_puts(mon, qstring_get_str(json));
372
373 QDECREF(json);
374 }
375
376 static QDict *build_qmp_error_dict(const QError *err)
377 {
378 QObject *obj;
379
380 obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %p } }",
381 ErrorClass_lookup[err->err_class],
382 qerror_human(err));
383
384 return qobject_to_qdict(obj);
385 }
386
387 static void monitor_protocol_emitter(Monitor *mon, QObject *data)
388 {
389 QDict *qmp;
390
391 trace_monitor_protocol_emitter(mon);
392
393 if (!monitor_has_error(mon)) {
394 /* success response */
395 qmp = qdict_new();
396 if (data) {
397 qobject_incref(data);
398 qdict_put_obj(qmp, "return", data);
399 } else {
400 /* return an empty QDict by default */
401 qdict_put(qmp, "return", qdict_new());
402 }
403 } else {
404 /* error response */
405 qmp = build_qmp_error_dict(mon->error);
406 QDECREF(mon->error);
407 mon->error = NULL;
408 }
409
410 if (mon->mc->id) {
411 qdict_put_obj(qmp, "id", mon->mc->id);
412 mon->mc->id = NULL;
413 }
414
415 monitor_json_emitter(mon, QOBJECT(qmp));
416 QDECREF(qmp);
417 }
418
419 static void timestamp_put(QDict *qdict)
420 {
421 int err;
422 QObject *obj;
423 qemu_timeval tv;
424
425 err = qemu_gettimeofday(&tv);
426 if (err < 0)
427 return;
428
429 obj = qobject_from_jsonf("{ 'seconds': %" PRId64 ", "
430 "'microseconds': %" PRId64 " }",
431 (int64_t) tv.tv_sec, (int64_t) tv.tv_usec);
432 qdict_put_obj(qdict, "timestamp", obj);
433 }
434
435
436 static const char *monitor_event_names[] = {
437 [QEVENT_SHUTDOWN] = "SHUTDOWN",
438 [QEVENT_RESET] = "RESET",
439 [QEVENT_POWERDOWN] = "POWERDOWN",
440 [QEVENT_STOP] = "STOP",
441 [QEVENT_RESUME] = "RESUME",
442 [QEVENT_VNC_CONNECTED] = "VNC_CONNECTED",
443 [QEVENT_VNC_INITIALIZED] = "VNC_INITIALIZED",
444 [QEVENT_VNC_DISCONNECTED] = "VNC_DISCONNECTED",
445 [QEVENT_BLOCK_IO_ERROR] = "BLOCK_IO_ERROR",
446 [QEVENT_RTC_CHANGE] = "RTC_CHANGE",
447 [QEVENT_WATCHDOG] = "WATCHDOG",
448 [QEVENT_SPICE_CONNECTED] = "SPICE_CONNECTED",
449 [QEVENT_SPICE_INITIALIZED] = "SPICE_INITIALIZED",
450 [QEVENT_SPICE_DISCONNECTED] = "SPICE_DISCONNECTED",
451 [QEVENT_BLOCK_JOB_COMPLETED] = "BLOCK_JOB_COMPLETED",
452 [QEVENT_BLOCK_JOB_CANCELLED] = "BLOCK_JOB_CANCELLED",
453 [QEVENT_DEVICE_TRAY_MOVED] = "DEVICE_TRAY_MOVED",
454 [QEVENT_SUSPEND] = "SUSPEND",
455 [QEVENT_SUSPEND_DISK] = "SUSPEND_DISK",
456 [QEVENT_WAKEUP] = "WAKEUP",
457 [QEVENT_BALLOON_CHANGE] = "BALLOON_CHANGE",
458 [QEVENT_SPICE_MIGRATE_COMPLETED] = "SPICE_MIGRATE_COMPLETED",
459 };
460 QEMU_BUILD_BUG_ON(ARRAY_SIZE(monitor_event_names) != QEVENT_MAX)
461
462 MonitorEventState monitor_event_state[QEVENT_MAX];
463 QemuMutex monitor_event_state_lock;
464
465 /*
466 * Emits the event to every monitor instance
467 */
468 static void
469 monitor_protocol_event_emit(MonitorEvent event,
470 QObject *data)
471 {
472 Monitor *mon;
473
474 trace_monitor_protocol_event_emit(event, data);
475 QLIST_FOREACH(mon, &mon_list, entry) {
476 if (monitor_ctrl_mode(mon) && qmp_cmd_mode(mon)) {
477 monitor_json_emitter(mon, data);
478 }
479 }
480 }
481
482
483 /*
484 * Queue a new event for emission to Monitor instances,
485 * applying any rate limiting if required.
486 */
487 static void
488 monitor_protocol_event_queue(MonitorEvent event,
489 QObject *data)
490 {
491 MonitorEventState *evstate;
492 int64_t now = qemu_get_clock_ns(rt_clock);
493 assert(event < QEVENT_MAX);
494
495 qemu_mutex_lock(&monitor_event_state_lock);
496 evstate = &(monitor_event_state[event]);
497 trace_monitor_protocol_event_queue(event,
498 data,
499 evstate->rate,
500 evstate->last,
501 now);
502
503 /* Rate limit of 0 indicates no throttling */
504 if (!evstate->rate) {
505 monitor_protocol_event_emit(event, data);
506 evstate->last = now;
507 } else {
508 int64_t delta = now - evstate->last;
509 if (evstate->data ||
510 delta < evstate->rate) {
511 /* If there's an existing event pending, replace
512 * it with the new event, otherwise schedule a
513 * timer for delayed emission
514 */
515 if (evstate->data) {
516 qobject_decref(evstate->data);
517 } else {
518 int64_t then = evstate->last + evstate->rate;
519 qemu_mod_timer_ns(evstate->timer, then);
520 }
521 evstate->data = data;
522 qobject_incref(evstate->data);
523 } else {
524 monitor_protocol_event_emit(event, data);
525 evstate->last = now;
526 }
527 }
528 qemu_mutex_unlock(&monitor_event_state_lock);
529 }
530
531
532 /*
533 * The callback invoked by QemuTimer when a delayed
534 * event is ready to be emitted
535 */
536 static void monitor_protocol_event_handler(void *opaque)
537 {
538 MonitorEventState *evstate = opaque;
539 int64_t now = qemu_get_clock_ns(rt_clock);
540
541 qemu_mutex_lock(&monitor_event_state_lock);
542
543 trace_monitor_protocol_event_handler(evstate->event,
544 evstate->data,
545 evstate->last,
546 now);
547 if (evstate->data) {
548 monitor_protocol_event_emit(evstate->event, evstate->data);
549 qobject_decref(evstate->data);
550 evstate->data = NULL;
551 }
552 evstate->last = now;
553 qemu_mutex_unlock(&monitor_event_state_lock);
554 }
555
556
557 /*
558 * @event: the event ID to be limited
559 * @rate: the rate limit in milliseconds
560 *
561 * Sets a rate limit on a particular event, so no
562 * more than 1 event will be emitted within @rate
563 * milliseconds
564 */
565 static void
566 monitor_protocol_event_throttle(MonitorEvent event,
567 int64_t rate)
568 {
569 MonitorEventState *evstate;
570 assert(event < QEVENT_MAX);
571
572 evstate = &(monitor_event_state[event]);
573
574 trace_monitor_protocol_event_throttle(event, rate);
575 evstate->event = event;
576 evstate->rate = rate * SCALE_MS;
577 evstate->timer = qemu_new_timer(rt_clock,
578 SCALE_MS,
579 monitor_protocol_event_handler,
580 evstate);
581 evstate->last = 0;
582 evstate->data = NULL;
583 }
584
585
586 /* Global, one-time initializer to configure the rate limiting
587 * and initialize state */
588 static void monitor_protocol_event_init(void)
589 {
590 qemu_mutex_init(&monitor_event_state_lock);
591 /* Limit RTC & BALLOON events to 1 per second */
592 monitor_protocol_event_throttle(QEVENT_RTC_CHANGE, 1000);
593 monitor_protocol_event_throttle(QEVENT_BALLOON_CHANGE, 1000);
594 monitor_protocol_event_throttle(QEVENT_WATCHDOG, 1000);
595 }
596
597 /**
598 * monitor_protocol_event(): Generate a Monitor event
599 *
600 * Event-specific data can be emitted through the (optional) 'data' parameter.
601 */
602 void monitor_protocol_event(MonitorEvent event, QObject *data)
603 {
604 QDict *qmp;
605 const char *event_name;
606
607 assert(event < QEVENT_MAX);
608
609 event_name = monitor_event_names[event];
610 assert(event_name != NULL);
611
612 qmp = qdict_new();
613 timestamp_put(qmp);
614 qdict_put(qmp, "event", qstring_from_str(event_name));
615 if (data) {
616 qobject_incref(data);
617 qdict_put_obj(qmp, "data", data);
618 }
619
620 trace_monitor_protocol_event(event, event_name, qmp);
621 monitor_protocol_event_queue(event, QOBJECT(qmp));
622 QDECREF(qmp);
623 }
624
625 static int do_qmp_capabilities(Monitor *mon, const QDict *params,
626 QObject **ret_data)
627 {
628 /* Will setup QMP capabilities in the future */
629 if (monitor_ctrl_mode(mon)) {
630 mon->mc->command_mode = 1;
631 }
632
633 return 0;
634 }
635
636 static void handle_user_command(Monitor *mon, const char *cmdline);
637
638 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
639 int64_t cpu_index, Error **errp)
640 {
641 char *output = NULL;
642 Monitor *old_mon, hmp;
643 CharDriverState mchar;
644
645 memset(&hmp, 0, sizeof(hmp));
646 qemu_chr_init_mem(&mchar);
647 hmp.chr = &mchar;
648
649 old_mon = cur_mon;
650 cur_mon = &hmp;
651
652 if (has_cpu_index) {
653 int ret = monitor_set_cpu(cpu_index);
654 if (ret < 0) {
655 cur_mon = old_mon;
656 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
657 "a CPU number");
658 goto out;
659 }
660 }
661
662 handle_user_command(&hmp, command_line);
663 cur_mon = old_mon;
664
665 if (qemu_chr_mem_osize(hmp.chr) > 0) {
666 QString *str = qemu_chr_mem_to_qs(hmp.chr);
667 output = g_strdup(qstring_get_str(str));
668 QDECREF(str);
669 } else {
670 output = g_strdup("");
671 }
672
673 out:
674 qemu_chr_close_mem(hmp.chr);
675 return output;
676 }
677
678 static int compare_cmd(const char *name, const char *list)
679 {
680 const char *p, *pstart;
681 int len;
682 len = strlen(name);
683 p = list;
684 for(;;) {
685 pstart = p;
686 p = strchr(p, '|');
687 if (!p)
688 p = pstart + strlen(pstart);
689 if ((p - pstart) == len && !memcmp(pstart, name, len))
690 return 1;
691 if (*p == '\0')
692 break;
693 p++;
694 }
695 return 0;
696 }
697
698 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
699 const char *prefix, const char *name)
700 {
701 const mon_cmd_t *cmd;
702
703 for(cmd = cmds; cmd->name != NULL; cmd++) {
704 if (!name || !strcmp(name, cmd->name))
705 monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
706 cmd->params, cmd->help);
707 }
708 }
709
710 static void help_cmd(Monitor *mon, const char *name)
711 {
712 if (name && !strcmp(name, "info")) {
713 help_cmd_dump(mon, info_cmds, "info ", NULL);
714 } else {
715 help_cmd_dump(mon, mon_cmds, "", name);
716 if (name && !strcmp(name, "log")) {
717 const CPULogItem *item;
718 monitor_printf(mon, "Log items (comma separated):\n");
719 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
720 for(item = cpu_log_items; item->mask != 0; item++) {
721 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
722 }
723 }
724 }
725 }
726
727 static void do_help_cmd(Monitor *mon, const QDict *qdict)
728 {
729 help_cmd(mon, qdict_get_try_str(qdict, "name"));
730 }
731
732 static void do_trace_event_set_state(Monitor *mon, const QDict *qdict)
733 {
734 const char *tp_name = qdict_get_str(qdict, "name");
735 bool new_state = qdict_get_bool(qdict, "option");
736 int ret = trace_event_set_state(tp_name, new_state);
737
738 if (!ret) {
739 monitor_printf(mon, "unknown event name \"%s\"\n", tp_name);
740 }
741 }
742
743 #ifdef CONFIG_TRACE_SIMPLE
744 static void do_trace_file(Monitor *mon, const QDict *qdict)
745 {
746 const char *op = qdict_get_try_str(qdict, "op");
747 const char *arg = qdict_get_try_str(qdict, "arg");
748
749 if (!op) {
750 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
751 } else if (!strcmp(op, "on")) {
752 st_set_trace_file_enabled(true);
753 } else if (!strcmp(op, "off")) {
754 st_set_trace_file_enabled(false);
755 } else if (!strcmp(op, "flush")) {
756 st_flush_trace_buffer();
757 } else if (!strcmp(op, "set")) {
758 if (arg) {
759 st_set_trace_file(arg);
760 }
761 } else {
762 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
763 help_cmd(mon, "trace-file");
764 }
765 }
766 #endif
767
768 static void user_monitor_complete(void *opaque, QObject *ret_data)
769 {
770 MonitorCompletionData *data = (MonitorCompletionData *)opaque;
771
772 if (ret_data) {
773 data->user_print(data->mon, ret_data);
774 }
775 monitor_resume(data->mon);
776 g_free(data);
777 }
778
779 static void qmp_monitor_complete(void *opaque, QObject *ret_data)
780 {
781 monitor_protocol_emitter(opaque, ret_data);
782 }
783
784 static int qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
785 const QDict *params)
786 {
787 return cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);
788 }
789
790 static void user_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
791 const QDict *params)
792 {
793 int ret;
794
795 MonitorCompletionData *cb_data = g_malloc(sizeof(*cb_data));
796 cb_data->mon = mon;
797 cb_data->user_print = cmd->user_print;
798 monitor_suspend(mon);
799 ret = cmd->mhandler.cmd_async(mon, params,
800 user_monitor_complete, cb_data);
801 if (ret < 0) {
802 monitor_resume(mon);
803 g_free(cb_data);
804 }
805 }
806
807 static void do_info(Monitor *mon, const QDict *qdict)
808 {
809 const mon_cmd_t *cmd;
810 const char *item = qdict_get_try_str(qdict, "item");
811
812 if (!item) {
813 goto help;
814 }
815
816 for (cmd = info_cmds; cmd->name != NULL; cmd++) {
817 if (compare_cmd(item, cmd->name))
818 break;
819 }
820
821 if (cmd->name == NULL) {
822 goto help;
823 }
824
825 cmd->mhandler.info(mon);
826 return;
827
828 help:
829 help_cmd(mon, "info");
830 }
831
832 CommandInfoList *qmp_query_commands(Error **errp)
833 {
834 CommandInfoList *info, *cmd_list = NULL;
835 const mon_cmd_t *cmd;
836
837 for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
838 info = g_malloc0(sizeof(*info));
839 info->value = g_malloc0(sizeof(*info->value));
840 info->value->name = g_strdup(cmd->name);
841
842 info->next = cmd_list;
843 cmd_list = info;
844 }
845
846 return cmd_list;
847 }
848
849 EventInfoList *qmp_query_events(Error **errp)
850 {
851 EventInfoList *info, *ev_list = NULL;
852 MonitorEvent e;
853
854 for (e = 0 ; e < QEVENT_MAX ; e++) {
855 const char *event_name = monitor_event_names[e];
856 assert(event_name != NULL);
857 info = g_malloc0(sizeof(*info));
858 info->value = g_malloc0(sizeof(*info->value));
859 info->value->name = g_strdup(event_name);
860
861 info->next = ev_list;
862 ev_list = info;
863 }
864
865 return ev_list;
866 }
867
868 /* set the current CPU defined by the user */
869 int monitor_set_cpu(int cpu_index)
870 {
871 CPUArchState *env;
872
873 for(env = first_cpu; env != NULL; env = env->next_cpu) {
874 if (env->cpu_index == cpu_index) {
875 cur_mon->mon_cpu = env;
876 return 0;
877 }
878 }
879 return -1;
880 }
881
882 static CPUArchState *mon_get_cpu(void)
883 {
884 if (!cur_mon->mon_cpu) {
885 monitor_set_cpu(0);
886 }
887 cpu_synchronize_state(cur_mon->mon_cpu);
888 return cur_mon->mon_cpu;
889 }
890
891 int monitor_get_cpu_index(void)
892 {
893 return mon_get_cpu()->cpu_index;
894 }
895
896 static void do_info_registers(Monitor *mon)
897 {
898 CPUArchState *env;
899 env = mon_get_cpu();
900 #ifdef TARGET_I386
901 cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
902 X86_DUMP_FPU);
903 #else
904 cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
905 0);
906 #endif
907 }
908
909 static void do_info_jit(Monitor *mon)
910 {
911 dump_exec_info((FILE *)mon, monitor_fprintf);
912 }
913
914 static void do_info_history(Monitor *mon)
915 {
916 int i;
917 const char *str;
918
919 if (!mon->rs)
920 return;
921 i = 0;
922 for(;;) {
923 str = readline_get_history(mon->rs, i);
924 if (!str)
925 break;
926 monitor_printf(mon, "%d: '%s'\n", i, str);
927 i++;
928 }
929 }
930
931 #if defined(TARGET_PPC)
932 /* XXX: not implemented in other targets */
933 static void do_info_cpu_stats(Monitor *mon)
934 {
935 CPUArchState *env;
936
937 env = mon_get_cpu();
938 cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
939 }
940 #endif
941
942 static void do_trace_print_events(Monitor *mon)
943 {
944 trace_print_events((FILE *)mon, &monitor_fprintf);
945 }
946
947 static int client_migrate_info(Monitor *mon, const QDict *qdict,
948 MonitorCompletion cb, void *opaque)
949 {
950 const char *protocol = qdict_get_str(qdict, "protocol");
951 const char *hostname = qdict_get_str(qdict, "hostname");
952 const char *subject = qdict_get_try_str(qdict, "cert-subject");
953 int port = qdict_get_try_int(qdict, "port", -1);
954 int tls_port = qdict_get_try_int(qdict, "tls-port", -1);
955 int ret;
956
957 if (strcmp(protocol, "spice") == 0) {
958 if (!using_spice) {
959 qerror_report(QERR_DEVICE_NOT_ACTIVE, "spice");
960 return -1;
961 }
962
963 if (port == -1 && tls_port == -1) {
964 qerror_report(QERR_MISSING_PARAMETER, "port/tls-port");
965 return -1;
966 }
967
968 ret = qemu_spice_migrate_info(hostname, port, tls_port, subject,
969 cb, opaque);
970 if (ret != 0) {
971 qerror_report(QERR_UNDEFINED_ERROR);
972 return -1;
973 }
974 return 0;
975 }
976
977 qerror_report(QERR_INVALID_PARAMETER, "protocol");
978 return -1;
979 }
980
981 static void do_logfile(Monitor *mon, const QDict *qdict)
982 {
983 cpu_set_log_filename(qdict_get_str(qdict, "filename"));
984 }
985
986 static void do_log(Monitor *mon, const QDict *qdict)
987 {
988 int mask;
989 const char *items = qdict_get_str(qdict, "items");
990
991 if (!strcmp(items, "none")) {
992 mask = 0;
993 } else {
994 mask = cpu_str_to_log_mask(items);
995 if (!mask) {
996 help_cmd(mon, "log");
997 return;
998 }
999 }
1000 cpu_set_log(mask);
1001 }
1002
1003 static void do_singlestep(Monitor *mon, const QDict *qdict)
1004 {
1005 const char *option = qdict_get_try_str(qdict, "option");
1006 if (!option || !strcmp(option, "on")) {
1007 singlestep = 1;
1008 } else if (!strcmp(option, "off")) {
1009 singlestep = 0;
1010 } else {
1011 monitor_printf(mon, "unexpected option %s\n", option);
1012 }
1013 }
1014
1015 static void do_gdbserver(Monitor *mon, const QDict *qdict)
1016 {
1017 const char *device = qdict_get_try_str(qdict, "device");
1018 if (!device)
1019 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1020 if (gdbserver_start(device) < 0) {
1021 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1022 device);
1023 } else if (strcmp(device, "none") == 0) {
1024 monitor_printf(mon, "Disabled gdbserver\n");
1025 } else {
1026 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1027 device);
1028 }
1029 }
1030
1031 static void do_watchdog_action(Monitor *mon, const QDict *qdict)
1032 {
1033 const char *action = qdict_get_str(qdict, "action");
1034 if (select_watchdog_action(action) == -1) {
1035 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1036 }
1037 }
1038
1039 static void monitor_printc(Monitor *mon, int c)
1040 {
1041 monitor_printf(mon, "'");
1042 switch(c) {
1043 case '\'':
1044 monitor_printf(mon, "\\'");
1045 break;
1046 case '\\':
1047 monitor_printf(mon, "\\\\");
1048 break;
1049 case '\n':
1050 monitor_printf(mon, "\\n");
1051 break;
1052 case '\r':
1053 monitor_printf(mon, "\\r");
1054 break;
1055 default:
1056 if (c >= 32 && c <= 126) {
1057 monitor_printf(mon, "%c", c);
1058 } else {
1059 monitor_printf(mon, "\\x%02x", c);
1060 }
1061 break;
1062 }
1063 monitor_printf(mon, "'");
1064 }
1065
1066 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1067 target_phys_addr_t addr, int is_physical)
1068 {
1069 CPUArchState *env;
1070 int l, line_size, i, max_digits, len;
1071 uint8_t buf[16];
1072 uint64_t v;
1073
1074 if (format == 'i') {
1075 int flags;
1076 flags = 0;
1077 env = mon_get_cpu();
1078 #ifdef TARGET_I386
1079 if (wsize == 2) {
1080 flags = 1;
1081 } else if (wsize == 4) {
1082 flags = 0;
1083 } else {
1084 /* as default we use the current CS size */
1085 flags = 0;
1086 if (env) {
1087 #ifdef TARGET_X86_64
1088 if ((env->efer & MSR_EFER_LMA) &&
1089 (env->segs[R_CS].flags & DESC_L_MASK))
1090 flags = 2;
1091 else
1092 #endif
1093 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1094 flags = 1;
1095 }
1096 }
1097 #endif
1098 monitor_disas(mon, env, addr, count, is_physical, flags);
1099 return;
1100 }
1101
1102 len = wsize * count;
1103 if (wsize == 1)
1104 line_size = 8;
1105 else
1106 line_size = 16;
1107 max_digits = 0;
1108
1109 switch(format) {
1110 case 'o':
1111 max_digits = (wsize * 8 + 2) / 3;
1112 break;
1113 default:
1114 case 'x':
1115 max_digits = (wsize * 8) / 4;
1116 break;
1117 case 'u':
1118 case 'd':
1119 max_digits = (wsize * 8 * 10 + 32) / 33;
1120 break;
1121 case 'c':
1122 wsize = 1;
1123 break;
1124 }
1125
1126 while (len > 0) {
1127 if (is_physical)
1128 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1129 else
1130 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1131 l = len;
1132 if (l > line_size)
1133 l = line_size;
1134 if (is_physical) {
1135 cpu_physical_memory_read(addr, buf, l);
1136 } else {
1137 env = mon_get_cpu();
1138 if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {
1139 monitor_printf(mon, " Cannot access memory\n");
1140 break;
1141 }
1142 }
1143 i = 0;
1144 while (i < l) {
1145 switch(wsize) {
1146 default:
1147 case 1:
1148 v = ldub_raw(buf + i);
1149 break;
1150 case 2:
1151 v = lduw_raw(buf + i);
1152 break;
1153 case 4:
1154 v = (uint32_t)ldl_raw(buf + i);
1155 break;
1156 case 8:
1157 v = ldq_raw(buf + i);
1158 break;
1159 }
1160 monitor_printf(mon, " ");
1161 switch(format) {
1162 case 'o':
1163 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1164 break;
1165 case 'x':
1166 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1167 break;
1168 case 'u':
1169 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1170 break;
1171 case 'd':
1172 monitor_printf(mon, "%*" PRId64, max_digits, v);
1173 break;
1174 case 'c':
1175 monitor_printc(mon, v);
1176 break;
1177 }
1178 i += wsize;
1179 }
1180 monitor_printf(mon, "\n");
1181 addr += l;
1182 len -= l;
1183 }
1184 }
1185
1186 static void do_memory_dump(Monitor *mon, const QDict *qdict)
1187 {
1188 int count = qdict_get_int(qdict, "count");
1189 int format = qdict_get_int(qdict, "format");
1190 int size = qdict_get_int(qdict, "size");
1191 target_long addr = qdict_get_int(qdict, "addr");
1192
1193 memory_dump(mon, count, format, size, addr, 0);
1194 }
1195
1196 static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
1197 {
1198 int count = qdict_get_int(qdict, "count");
1199 int format = qdict_get_int(qdict, "format");
1200 int size = qdict_get_int(qdict, "size");
1201 target_phys_addr_t addr = qdict_get_int(qdict, "addr");
1202
1203 memory_dump(mon, count, format, size, addr, 1);
1204 }
1205
1206 static void do_print(Monitor *mon, const QDict *qdict)
1207 {
1208 int format = qdict_get_int(qdict, "format");
1209 target_phys_addr_t val = qdict_get_int(qdict, "val");
1210
1211 switch(format) {
1212 case 'o':
1213 monitor_printf(mon, "%#" TARGET_PRIoPHYS, val);
1214 break;
1215 case 'x':
1216 monitor_printf(mon, "%#" TARGET_PRIxPHYS, val);
1217 break;
1218 case 'u':
1219 monitor_printf(mon, "%" TARGET_PRIuPHYS, val);
1220 break;
1221 default:
1222 case 'd':
1223 monitor_printf(mon, "%" TARGET_PRIdPHYS, val);
1224 break;
1225 case 'c':
1226 monitor_printc(mon, val);
1227 break;
1228 }
1229 monitor_printf(mon, "\n");
1230 }
1231
1232 static void do_sum(Monitor *mon, const QDict *qdict)
1233 {
1234 uint32_t addr;
1235 uint16_t sum;
1236 uint32_t start = qdict_get_int(qdict, "start");
1237 uint32_t size = qdict_get_int(qdict, "size");
1238
1239 sum = 0;
1240 for(addr = start; addr < (start + size); addr++) {
1241 uint8_t val = ldub_phys(addr);
1242 /* BSD sum algorithm ('sum' Unix command) */
1243 sum = (sum >> 1) | (sum << 15);
1244 sum += val;
1245 }
1246 monitor_printf(mon, "%05d\n", sum);
1247 }
1248
1249 static int mouse_button_state;
1250
1251 static void do_mouse_move(Monitor *mon, const QDict *qdict)
1252 {
1253 int dx, dy, dz;
1254 const char *dx_str = qdict_get_str(qdict, "dx_str");
1255 const char *dy_str = qdict_get_str(qdict, "dy_str");
1256 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1257 dx = strtol(dx_str, NULL, 0);
1258 dy = strtol(dy_str, NULL, 0);
1259 dz = 0;
1260 if (dz_str)
1261 dz = strtol(dz_str, NULL, 0);
1262 kbd_mouse_event(dx, dy, dz, mouse_button_state);
1263 }
1264
1265 static void do_mouse_button(Monitor *mon, const QDict *qdict)
1266 {
1267 int button_state = qdict_get_int(qdict, "button_state");
1268 mouse_button_state = button_state;
1269 kbd_mouse_event(0, 0, 0, mouse_button_state);
1270 }
1271
1272 static void do_ioport_read(Monitor *mon, const QDict *qdict)
1273 {
1274 int size = qdict_get_int(qdict, "size");
1275 int addr = qdict_get_int(qdict, "addr");
1276 int has_index = qdict_haskey(qdict, "index");
1277 uint32_t val;
1278 int suffix;
1279
1280 if (has_index) {
1281 int index = qdict_get_int(qdict, "index");
1282 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1283 addr++;
1284 }
1285 addr &= 0xffff;
1286
1287 switch(size) {
1288 default:
1289 case 1:
1290 val = cpu_inb(addr);
1291 suffix = 'b';
1292 break;
1293 case 2:
1294 val = cpu_inw(addr);
1295 suffix = 'w';
1296 break;
1297 case 4:
1298 val = cpu_inl(addr);
1299 suffix = 'l';
1300 break;
1301 }
1302 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1303 suffix, addr, size * 2, val);
1304 }
1305
1306 static void do_ioport_write(Monitor *mon, const QDict *qdict)
1307 {
1308 int size = qdict_get_int(qdict, "size");
1309 int addr = qdict_get_int(qdict, "addr");
1310 int val = qdict_get_int(qdict, "val");
1311
1312 addr &= IOPORTS_MASK;
1313
1314 switch (size) {
1315 default:
1316 case 1:
1317 cpu_outb(addr, val);
1318 break;
1319 case 2:
1320 cpu_outw(addr, val);
1321 break;
1322 case 4:
1323 cpu_outl(addr, val);
1324 break;
1325 }
1326 }
1327
1328 static void do_boot_set(Monitor *mon, const QDict *qdict)
1329 {
1330 int res;
1331 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1332
1333 res = qemu_boot_set(bootdevice);
1334 if (res == 0) {
1335 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1336 } else if (res > 0) {
1337 monitor_printf(mon, "setting boot device list failed\n");
1338 } else {
1339 monitor_printf(mon, "no function defined to set boot device list for "
1340 "this architecture\n");
1341 }
1342 }
1343
1344 #if defined(TARGET_I386)
1345 static void print_pte(Monitor *mon, target_phys_addr_t addr,
1346 target_phys_addr_t pte,
1347 target_phys_addr_t mask)
1348 {
1349 #ifdef TARGET_X86_64
1350 if (addr & (1ULL << 47)) {
1351 addr |= -1LL << 48;
1352 }
1353 #endif
1354 monitor_printf(mon, TARGET_FMT_plx ": " TARGET_FMT_plx
1355 " %c%c%c%c%c%c%c%c%c\n",
1356 addr,
1357 pte & mask,
1358 pte & PG_NX_MASK ? 'X' : '-',
1359 pte & PG_GLOBAL_MASK ? 'G' : '-',
1360 pte & PG_PSE_MASK ? 'P' : '-',
1361 pte & PG_DIRTY_MASK ? 'D' : '-',
1362 pte & PG_ACCESSED_MASK ? 'A' : '-',
1363 pte & PG_PCD_MASK ? 'C' : '-',
1364 pte & PG_PWT_MASK ? 'T' : '-',
1365 pte & PG_USER_MASK ? 'U' : '-',
1366 pte & PG_RW_MASK ? 'W' : '-');
1367 }
1368
1369 static void tlb_info_32(Monitor *mon, CPUArchState *env)
1370 {
1371 unsigned int l1, l2;
1372 uint32_t pgd, pde, pte;
1373
1374 pgd = env->cr[3] & ~0xfff;
1375 for(l1 = 0; l1 < 1024; l1++) {
1376 cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
1377 pde = le32_to_cpu(pde);
1378 if (pde & PG_PRESENT_MASK) {
1379 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1380 /* 4M pages */
1381 print_pte(mon, (l1 << 22), pde, ~((1 << 21) - 1));
1382 } else {
1383 for(l2 = 0; l2 < 1024; l2++) {
1384 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
1385 pte = le32_to_cpu(pte);
1386 if (pte & PG_PRESENT_MASK) {
1387 print_pte(mon, (l1 << 22) + (l2 << 12),
1388 pte & ~PG_PSE_MASK,
1389 ~0xfff);
1390 }
1391 }
1392 }
1393 }
1394 }
1395 }
1396
1397 static void tlb_info_pae32(Monitor *mon, CPUArchState *env)
1398 {
1399 unsigned int l1, l2, l3;
1400 uint64_t pdpe, pde, pte;
1401 uint64_t pdp_addr, pd_addr, pt_addr;
1402
1403 pdp_addr = env->cr[3] & ~0x1f;
1404 for (l1 = 0; l1 < 4; l1++) {
1405 cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
1406 pdpe = le64_to_cpu(pdpe);
1407 if (pdpe & PG_PRESENT_MASK) {
1408 pd_addr = pdpe & 0x3fffffffff000ULL;
1409 for (l2 = 0; l2 < 512; l2++) {
1410 cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
1411 pde = le64_to_cpu(pde);
1412 if (pde & PG_PRESENT_MASK) {
1413 if (pde & PG_PSE_MASK) {
1414 /* 2M pages with PAE, CR4.PSE is ignored */
1415 print_pte(mon, (l1 << 30 ) + (l2 << 21), pde,
1416 ~((target_phys_addr_t)(1 << 20) - 1));
1417 } else {
1418 pt_addr = pde & 0x3fffffffff000ULL;
1419 for (l3 = 0; l3 < 512; l3++) {
1420 cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
1421 pte = le64_to_cpu(pte);
1422 if (pte & PG_PRESENT_MASK) {
1423 print_pte(mon, (l1 << 30 ) + (l2 << 21)
1424 + (l3 << 12),
1425 pte & ~PG_PSE_MASK,
1426 ~(target_phys_addr_t)0xfff);
1427 }
1428 }
1429 }
1430 }
1431 }
1432 }
1433 }
1434 }
1435
1436 #ifdef TARGET_X86_64
1437 static void tlb_info_64(Monitor *mon, CPUArchState *env)
1438 {
1439 uint64_t l1, l2, l3, l4;
1440 uint64_t pml4e, pdpe, pde, pte;
1441 uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr;
1442
1443 pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
1444 for (l1 = 0; l1 < 512; l1++) {
1445 cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
1446 pml4e = le64_to_cpu(pml4e);
1447 if (pml4e & PG_PRESENT_MASK) {
1448 pdp_addr = pml4e & 0x3fffffffff000ULL;
1449 for (l2 = 0; l2 < 512; l2++) {
1450 cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
1451 pdpe = le64_to_cpu(pdpe);
1452 if (pdpe & PG_PRESENT_MASK) {
1453 if (pdpe & PG_PSE_MASK) {
1454 /* 1G pages, CR4.PSE is ignored */
1455 print_pte(mon, (l1 << 39) + (l2 << 30), pdpe,
1456 0x3ffffc0000000ULL);
1457 } else {
1458 pd_addr = pdpe & 0x3fffffffff000ULL;
1459 for (l3 = 0; l3 < 512; l3++) {
1460 cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
1461 pde = le64_to_cpu(pde);
1462 if (pde & PG_PRESENT_MASK) {
1463 if (pde & PG_PSE_MASK) {
1464 /* 2M pages, CR4.PSE is ignored */
1465 print_pte(mon, (l1 << 39) + (l2 << 30) +
1466 (l3 << 21), pde,
1467 0x3ffffffe00000ULL);
1468 } else {
1469 pt_addr = pde & 0x3fffffffff000ULL;
1470 for (l4 = 0; l4 < 512; l4++) {
1471 cpu_physical_memory_read(pt_addr
1472 + l4 * 8,
1473 &pte, 8);
1474 pte = le64_to_cpu(pte);
1475 if (pte & PG_PRESENT_MASK) {
1476 print_pte(mon, (l1 << 39) +
1477 (l2 << 30) +
1478 (l3 << 21) + (l4 << 12),
1479 pte & ~PG_PSE_MASK,
1480 0x3fffffffff000ULL);
1481 }
1482 }
1483 }
1484 }
1485 }
1486 }
1487 }
1488 }
1489 }
1490 }
1491 }
1492 #endif
1493
1494 static void tlb_info(Monitor *mon)
1495 {
1496 CPUArchState *env;
1497
1498 env = mon_get_cpu();
1499
1500 if (!(env->cr[0] & CR0_PG_MASK)) {
1501 monitor_printf(mon, "PG disabled\n");
1502 return;
1503 }
1504 if (env->cr[4] & CR4_PAE_MASK) {
1505 #ifdef TARGET_X86_64
1506 if (env->hflags & HF_LMA_MASK) {
1507 tlb_info_64(mon, env);
1508 } else
1509 #endif
1510 {
1511 tlb_info_pae32(mon, env);
1512 }
1513 } else {
1514 tlb_info_32(mon, env);
1515 }
1516 }
1517
1518 static void mem_print(Monitor *mon, target_phys_addr_t *pstart,
1519 int *plast_prot,
1520 target_phys_addr_t end, int prot)
1521 {
1522 int prot1;
1523 prot1 = *plast_prot;
1524 if (prot != prot1) {
1525 if (*pstart != -1) {
1526 monitor_printf(mon, TARGET_FMT_plx "-" TARGET_FMT_plx " "
1527 TARGET_FMT_plx " %c%c%c\n",
1528 *pstart, end, end - *pstart,
1529 prot1 & PG_USER_MASK ? 'u' : '-',
1530 'r',
1531 prot1 & PG_RW_MASK ? 'w' : '-');
1532 }
1533 if (prot != 0)
1534 *pstart = end;
1535 else
1536 *pstart = -1;
1537 *plast_prot = prot;
1538 }
1539 }
1540
1541 static void mem_info_32(Monitor *mon, CPUArchState *env)
1542 {
1543 unsigned int l1, l2;
1544 int prot, last_prot;
1545 uint32_t pgd, pde, pte;
1546 target_phys_addr_t start, end;
1547
1548 pgd = env->cr[3] & ~0xfff;
1549 last_prot = 0;
1550 start = -1;
1551 for(l1 = 0; l1 < 1024; l1++) {
1552 cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
1553 pde = le32_to_cpu(pde);
1554 end = l1 << 22;
1555 if (pde & PG_PRESENT_MASK) {
1556 if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1557 prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1558 mem_print(mon, &start, &last_prot, end, prot);
1559 } else {
1560 for(l2 = 0; l2 < 1024; l2++) {
1561 cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
1562 pte = le32_to_cpu(pte);
1563 end = (l1 << 22) + (l2 << 12);
1564 if (pte & PG_PRESENT_MASK) {
1565 prot = pte & pde &
1566 (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1567 } else {
1568 prot = 0;
1569 }
1570 mem_print(mon, &start, &last_prot, end, prot);
1571 }
1572 }
1573 } else {
1574 prot = 0;
1575 mem_print(mon, &start, &last_prot, end, prot);
1576 }
1577 }
1578 /* Flush last range */
1579 mem_print(mon, &start, &last_prot, (target_phys_addr_t)1 << 32, 0);
1580 }
1581
1582 static void mem_info_pae32(Monitor *mon, CPUArchState *env)
1583 {
1584 unsigned int l1, l2, l3;
1585 int prot, last_prot;
1586 uint64_t pdpe, pde, pte;
1587 uint64_t pdp_addr, pd_addr, pt_addr;
1588 target_phys_addr_t start, end;
1589
1590 pdp_addr = env->cr[3] & ~0x1f;
1591 last_prot = 0;
1592 start = -1;
1593 for (l1 = 0; l1 < 4; l1++) {
1594 cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
1595 pdpe = le64_to_cpu(pdpe);
1596 end = l1 << 30;
1597 if (pdpe & PG_PRESENT_MASK) {
1598 pd_addr = pdpe & 0x3fffffffff000ULL;
1599 for (l2 = 0; l2 < 512; l2++) {
1600 cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
1601 pde = le64_to_cpu(pde);
1602 end = (l1 << 30) + (l2 << 21);
1603 if (pde & PG_PRESENT_MASK) {
1604 if (pde & PG_PSE_MASK) {
1605 prot = pde & (PG_USER_MASK | PG_RW_MASK |
1606 PG_PRESENT_MASK);
1607 mem_print(mon, &start, &last_prot, end, prot);
1608 } else {
1609 pt_addr = pde & 0x3fffffffff000ULL;
1610 for (l3 = 0; l3 < 512; l3++) {
1611 cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
1612 pte = le64_to_cpu(pte);
1613 end = (l1 << 30) + (l2 << 21) + (l3 << 12);
1614 if (pte & PG_PRESENT_MASK) {
1615 prot = pte & pde & (PG_USER_MASK | PG_RW_MASK |
1616 PG_PRESENT_MASK);
1617 } else {
1618 prot = 0;
1619 }
1620 mem_print(mon, &start, &last_prot, end, prot);
1621 }
1622 }
1623 } else {
1624 prot = 0;
1625 mem_print(mon, &start, &last_prot, end, prot);
1626 }
1627 }
1628 } else {
1629 prot = 0;
1630 mem_print(mon, &start, &last_prot, end, prot);
1631 }
1632 }
1633 /* Flush last range */
1634 mem_print(mon, &start, &last_prot, (target_phys_addr_t)1 << 32, 0);
1635 }
1636
1637
1638 #ifdef TARGET_X86_64
1639 static void mem_info_64(Monitor *mon, CPUArchState *env)
1640 {
1641 int prot, last_prot;
1642 uint64_t l1, l2, l3, l4;
1643 uint64_t pml4e, pdpe, pde, pte;
1644 uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr, start, end;
1645
1646 pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
1647 last_prot = 0;
1648 start = -1;
1649 for (l1 = 0; l1 < 512; l1++) {
1650 cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
1651 pml4e = le64_to_cpu(pml4e);
1652 end = l1 << 39;
1653 if (pml4e & PG_PRESENT_MASK) {
1654 pdp_addr = pml4e & 0x3fffffffff000ULL;
1655 for (l2 = 0; l2 < 512; l2++) {
1656 cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
1657 pdpe = le64_to_cpu(pdpe);
1658 end = (l1 << 39) + (l2 << 30);
1659 if (pdpe & PG_PRESENT_MASK) {
1660 if (pdpe & PG_PSE_MASK) {
1661 prot = pdpe & (PG_USER_MASK | PG_RW_MASK |
1662 PG_PRESENT_MASK);
1663 prot &= pml4e;
1664 mem_print(mon, &start, &last_prot, end, prot);
1665 } else {
1666 pd_addr = pdpe & 0x3fffffffff000ULL;
1667 for (l3 = 0; l3 < 512; l3++) {
1668 cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
1669 pde = le64_to_cpu(pde);
1670 end = (l1 << 39) + (l2 << 30) + (l3 << 21);
1671 if (pde & PG_PRESENT_MASK) {
1672 if (pde & PG_PSE_MASK) {
1673 prot = pde & (PG_USER_MASK | PG_RW_MASK |
1674 PG_PRESENT_MASK);
1675 prot &= pml4e & pdpe;
1676 mem_print(mon, &start, &last_prot, end, prot);
1677 } else {
1678 pt_addr = pde & 0x3fffffffff000ULL;
1679 for (l4 = 0; l4 < 512; l4++) {
1680 cpu_physical_memory_read(pt_addr
1681 + l4 * 8,
1682 &pte, 8);
1683 pte = le64_to_cpu(pte);
1684 end = (l1 << 39) + (l2 << 30) +
1685 (l3 << 21) + (l4 << 12);
1686 if (pte & PG_PRESENT_MASK) {
1687 prot = pte & (PG_USER_MASK | PG_RW_MASK |
1688 PG_PRESENT_MASK);
1689 prot &= pml4e & pdpe & pde;
1690 } else {
1691 prot = 0;
1692 }
1693 mem_print(mon, &start, &last_prot, end, prot);
1694 }
1695 }
1696 } else {
1697 prot = 0;
1698 mem_print(mon, &start, &last_prot, end, prot);
1699 }
1700 }
1701 }
1702 } else {
1703 prot = 0;
1704 mem_print(mon, &start, &last_prot, end, prot);
1705 }
1706 }
1707 } else {
1708 prot = 0;
1709 mem_print(mon, &start, &last_prot, end, prot);
1710 }
1711 }
1712 /* Flush last range */
1713 mem_print(mon, &start, &last_prot, (target_phys_addr_t)1 << 48, 0);
1714 }
1715 #endif
1716
1717 static void mem_info(Monitor *mon)
1718 {
1719 CPUArchState *env;
1720
1721 env = mon_get_cpu();
1722
1723 if (!(env->cr[0] & CR0_PG_MASK)) {
1724 monitor_printf(mon, "PG disabled\n");
1725 return;
1726 }
1727 if (env->cr[4] & CR4_PAE_MASK) {
1728 #ifdef TARGET_X86_64
1729 if (env->hflags & HF_LMA_MASK) {
1730 mem_info_64(mon, env);
1731 } else
1732 #endif
1733 {
1734 mem_info_pae32(mon, env);
1735 }
1736 } else {
1737 mem_info_32(mon, env);
1738 }
1739 }
1740 #endif
1741
1742 #if defined(TARGET_SH4)
1743
1744 static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1745 {
1746 monitor_printf(mon, " tlb%i:\t"
1747 "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1748 "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1749 "dirty=%hhu writethrough=%hhu\n",
1750 idx,
1751 tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1752 tlb->v, tlb->sh, tlb->c, tlb->pr,
1753 tlb->d, tlb->wt);
1754 }
1755
1756 static void tlb_info(Monitor *mon)
1757 {
1758 CPUArchState *env = mon_get_cpu();
1759 int i;
1760
1761 monitor_printf (mon, "ITLB:\n");
1762 for (i = 0 ; i < ITLB_SIZE ; i++)
1763 print_tlb (mon, i, &env->itlb[i]);
1764 monitor_printf (mon, "UTLB:\n");
1765 for (i = 0 ; i < UTLB_SIZE ; i++)
1766 print_tlb (mon, i, &env->utlb[i]);
1767 }
1768
1769 #endif
1770
1771 #if defined(TARGET_SPARC) || defined(TARGET_PPC) || defined(TARGET_XTENSA)
1772 static void tlb_info(Monitor *mon)
1773 {
1774 CPUArchState *env1 = mon_get_cpu();
1775
1776 dump_mmu((FILE*)mon, (fprintf_function)monitor_printf, env1);
1777 }
1778 #endif
1779
1780 static void do_info_mtree(Monitor *mon)
1781 {
1782 mtree_info((fprintf_function)monitor_printf, mon);
1783 }
1784
1785 static void do_info_numa(Monitor *mon)
1786 {
1787 int i;
1788 CPUArchState *env;
1789
1790 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1791 for (i = 0; i < nb_numa_nodes; i++) {
1792 monitor_printf(mon, "node %d cpus:", i);
1793 for (env = first_cpu; env != NULL; env = env->next_cpu) {
1794 if (env->numa_node == i) {
1795 monitor_printf(mon, " %d", env->cpu_index);
1796 }
1797 }
1798 monitor_printf(mon, "\n");
1799 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1800 node_mem[i] >> 20);
1801 }
1802 }
1803
1804 #ifdef CONFIG_PROFILER
1805
1806 int64_t qemu_time;
1807 int64_t dev_time;
1808
1809 static void do_info_profile(Monitor *mon)
1810 {
1811 int64_t total;
1812 total = qemu_time;
1813 if (total == 0)
1814 total = 1;
1815 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
1816 dev_time, dev_time / (double)get_ticks_per_sec());
1817 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
1818 qemu_time, qemu_time / (double)get_ticks_per_sec());
1819 qemu_time = 0;
1820 dev_time = 0;
1821 }
1822 #else
1823 static void do_info_profile(Monitor *mon)
1824 {
1825 monitor_printf(mon, "Internal profiler not compiled\n");
1826 }
1827 #endif
1828
1829 /* Capture support */
1830 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1831
1832 static void do_info_capture(Monitor *mon)
1833 {
1834 int i;
1835 CaptureState *s;
1836
1837 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1838 monitor_printf(mon, "[%d]: ", i);
1839 s->ops.info (s->opaque);
1840 }
1841 }
1842
1843 #ifdef HAS_AUDIO
1844 static void do_stop_capture(Monitor *mon, const QDict *qdict)
1845 {
1846 int i;
1847 int n = qdict_get_int(qdict, "n");
1848 CaptureState *s;
1849
1850 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1851 if (i == n) {
1852 s->ops.destroy (s->opaque);
1853 QLIST_REMOVE (s, entries);
1854 g_free (s);
1855 return;
1856 }
1857 }
1858 }
1859
1860 static void do_wav_capture(Monitor *mon, const QDict *qdict)
1861 {
1862 const char *path = qdict_get_str(qdict, "path");
1863 int has_freq = qdict_haskey(qdict, "freq");
1864 int freq = qdict_get_try_int(qdict, "freq", -1);
1865 int has_bits = qdict_haskey(qdict, "bits");
1866 int bits = qdict_get_try_int(qdict, "bits", -1);
1867 int has_channels = qdict_haskey(qdict, "nchannels");
1868 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1869 CaptureState *s;
1870
1871 s = g_malloc0 (sizeof (*s));
1872
1873 freq = has_freq ? freq : 44100;
1874 bits = has_bits ? bits : 16;
1875 nchannels = has_channels ? nchannels : 2;
1876
1877 if (wav_start_capture (s, path, freq, bits, nchannels)) {
1878 monitor_printf(mon, "Failed to add wave capture\n");
1879 g_free (s);
1880 return;
1881 }
1882 QLIST_INSERT_HEAD (&capture_head, s, entries);
1883 }
1884 #endif
1885
1886 static qemu_acl *find_acl(Monitor *mon, const char *name)
1887 {
1888 qemu_acl *acl = qemu_acl_find(name);
1889
1890 if (!acl) {
1891 monitor_printf(mon, "acl: unknown list '%s'\n", name);
1892 }
1893 return acl;
1894 }
1895
1896 static void do_acl_show(Monitor *mon, const QDict *qdict)
1897 {
1898 const char *aclname = qdict_get_str(qdict, "aclname");
1899 qemu_acl *acl = find_acl(mon, aclname);
1900 qemu_acl_entry *entry;
1901 int i = 0;
1902
1903 if (acl) {
1904 monitor_printf(mon, "policy: %s\n",
1905 acl->defaultDeny ? "deny" : "allow");
1906 QTAILQ_FOREACH(entry, &acl->entries, next) {
1907 i++;
1908 monitor_printf(mon, "%d: %s %s\n", i,
1909 entry->deny ? "deny" : "allow", entry->match);
1910 }
1911 }
1912 }
1913
1914 static void do_acl_reset(Monitor *mon, const QDict *qdict)
1915 {
1916 const char *aclname = qdict_get_str(qdict, "aclname");
1917 qemu_acl *acl = find_acl(mon, aclname);
1918
1919 if (acl) {
1920 qemu_acl_reset(acl);
1921 monitor_printf(mon, "acl: removed all rules\n");
1922 }
1923 }
1924
1925 static void do_acl_policy(Monitor *mon, const QDict *qdict)
1926 {
1927 const char *aclname = qdict_get_str(qdict, "aclname");
1928 const char *policy = qdict_get_str(qdict, "policy");
1929 qemu_acl *acl = find_acl(mon, aclname);
1930
1931 if (acl) {
1932 if (strcmp(policy, "allow") == 0) {
1933 acl->defaultDeny = 0;
1934 monitor_printf(mon, "acl: policy set to 'allow'\n");
1935 } else if (strcmp(policy, "deny") == 0) {
1936 acl->defaultDeny = 1;
1937 monitor_printf(mon, "acl: policy set to 'deny'\n");
1938 } else {
1939 monitor_printf(mon, "acl: unknown policy '%s', "
1940 "expected 'deny' or 'allow'\n", policy);
1941 }
1942 }
1943 }
1944
1945 static void do_acl_add(Monitor *mon, const QDict *qdict)
1946 {
1947 const char *aclname = qdict_get_str(qdict, "aclname");
1948 const char *match = qdict_get_str(qdict, "match");
1949 const char *policy = qdict_get_str(qdict, "policy");
1950 int has_index = qdict_haskey(qdict, "index");
1951 int index = qdict_get_try_int(qdict, "index", -1);
1952 qemu_acl *acl = find_acl(mon, aclname);
1953 int deny, ret;
1954
1955 if (acl) {
1956 if (strcmp(policy, "allow") == 0) {
1957 deny = 0;
1958 } else if (strcmp(policy, "deny") == 0) {
1959 deny = 1;
1960 } else {
1961 monitor_printf(mon, "acl: unknown policy '%s', "
1962 "expected 'deny' or 'allow'\n", policy);
1963 return;
1964 }
1965 if (has_index)
1966 ret = qemu_acl_insert(acl, deny, match, index);
1967 else
1968 ret = qemu_acl_append(acl, deny, match);
1969 if (ret < 0)
1970 monitor_printf(mon, "acl: unable to add acl entry\n");
1971 else
1972 monitor_printf(mon, "acl: added rule at position %d\n", ret);
1973 }
1974 }
1975
1976 static void do_acl_remove(Monitor *mon, const QDict *qdict)
1977 {
1978 const char *aclname = qdict_get_str(qdict, "aclname");
1979 const char *match = qdict_get_str(qdict, "match");
1980 qemu_acl *acl = find_acl(mon, aclname);
1981 int ret;
1982
1983 if (acl) {
1984 ret = qemu_acl_remove(acl, match);
1985 if (ret < 0)
1986 monitor_printf(mon, "acl: no matching acl entry\n");
1987 else
1988 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1989 }
1990 }
1991
1992 #if defined(TARGET_I386)
1993 static void do_inject_mce(Monitor *mon, const QDict *qdict)
1994 {
1995 CPUArchState *cenv;
1996 int cpu_index = qdict_get_int(qdict, "cpu_index");
1997 int bank = qdict_get_int(qdict, "bank");
1998 uint64_t status = qdict_get_int(qdict, "status");
1999 uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2000 uint64_t addr = qdict_get_int(qdict, "addr");
2001 uint64_t misc = qdict_get_int(qdict, "misc");
2002 int flags = MCE_INJECT_UNCOND_AO;
2003
2004 if (qdict_get_try_bool(qdict, "broadcast", 0)) {
2005 flags |= MCE_INJECT_BROADCAST;
2006 }
2007 for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu) {
2008 if (cenv->cpu_index == cpu_index) {
2009 cpu_x86_inject_mce(mon, cenv, bank, status, mcg_status, addr, misc,
2010 flags);
2011 break;
2012 }
2013 }
2014 }
2015 #endif
2016
2017 void qmp_getfd(const char *fdname, Error **errp)
2018 {
2019 mon_fd_t *monfd;
2020 int fd;
2021
2022 fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
2023 if (fd == -1) {
2024 error_set(errp, QERR_FD_NOT_SUPPLIED);
2025 return;
2026 }
2027
2028 if (qemu_isdigit(fdname[0])) {
2029 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2030 "a name not starting with a digit");
2031 return;
2032 }
2033
2034 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2035 if (strcmp(monfd->name, fdname) != 0) {
2036 continue;
2037 }
2038
2039 close(monfd->fd);
2040 monfd->fd = fd;
2041 return;
2042 }
2043
2044 monfd = g_malloc0(sizeof(mon_fd_t));
2045 monfd->name = g_strdup(fdname);
2046 monfd->fd = fd;
2047
2048 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2049 }
2050
2051 void qmp_closefd(const char *fdname, Error **errp)
2052 {
2053 mon_fd_t *monfd;
2054
2055 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2056 if (strcmp(monfd->name, fdname) != 0) {
2057 continue;
2058 }
2059
2060 QLIST_REMOVE(monfd, next);
2061 close(monfd->fd);
2062 g_free(monfd->name);
2063 g_free(monfd);
2064 return;
2065 }
2066
2067 error_set(errp, QERR_FD_NOT_FOUND, fdname);
2068 }
2069
2070 static void do_loadvm(Monitor *mon, const QDict *qdict)
2071 {
2072 int saved_vm_running = runstate_is_running();
2073 const char *name = qdict_get_str(qdict, "name");
2074
2075 vm_stop(RUN_STATE_RESTORE_VM);
2076
2077 if (load_vmstate(name) == 0 && saved_vm_running) {
2078 vm_start();
2079 }
2080 }
2081
2082 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2083 {
2084 mon_fd_t *monfd;
2085
2086 QLIST_FOREACH(monfd, &mon->fds, next) {
2087 int fd;
2088
2089 if (strcmp(monfd->name, fdname) != 0) {
2090 continue;
2091 }
2092
2093 fd = monfd->fd;
2094
2095 /* caller takes ownership of fd */
2096 QLIST_REMOVE(monfd, next);
2097 g_free(monfd->name);
2098 g_free(monfd);
2099
2100 return fd;
2101 }
2102
2103 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2104 return -1;
2105 }
2106
2107 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2108 {
2109 MonFdsetFd *mon_fdset_fd;
2110 MonFdsetFd *mon_fdset_fd_next;
2111
2112 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2113 if (mon_fdset_fd->removed ||
2114 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) {
2115 close(mon_fdset_fd->fd);
2116 g_free(mon_fdset_fd->opaque);
2117 QLIST_REMOVE(mon_fdset_fd, next);
2118 g_free(mon_fdset_fd);
2119 }
2120 }
2121
2122 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2123 QLIST_REMOVE(mon_fdset, next);
2124 g_free(mon_fdset);
2125 }
2126 }
2127
2128 static void monitor_fdsets_cleanup(void)
2129 {
2130 MonFdset *mon_fdset;
2131 MonFdset *mon_fdset_next;
2132
2133 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2134 monitor_fdset_cleanup(mon_fdset);
2135 }
2136 }
2137
2138 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2139 const char *opaque, Error **errp)
2140 {
2141 int fd;
2142 Monitor *mon = cur_mon;
2143 MonFdset *mon_fdset;
2144 MonFdsetFd *mon_fdset_fd;
2145 AddfdInfo *fdinfo;
2146
2147 fd = qemu_chr_fe_get_msgfd(mon->chr);
2148 if (fd == -1) {
2149 error_set(errp, QERR_FD_NOT_SUPPLIED);
2150 goto error;
2151 }
2152
2153 if (has_fdset_id) {
2154 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2155 if (mon_fdset->id == fdset_id) {
2156 break;
2157 }
2158 }
2159 if (mon_fdset == NULL) {
2160 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2161 "an existing fdset-id");
2162 goto error;
2163 }
2164 } else {
2165 int64_t fdset_id_prev = -1;
2166 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2167
2168 /* Use first available fdset ID */
2169 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2170 mon_fdset_cur = mon_fdset;
2171 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2172 fdset_id_prev = mon_fdset_cur->id;
2173 continue;
2174 }
2175 break;
2176 }
2177
2178 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2179 mon_fdset->id = fdset_id_prev + 1;
2180
2181 /* The fdset list is ordered by fdset ID */
2182 if (mon_fdset->id == 0) {
2183 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2184 } else if (mon_fdset->id < mon_fdset_cur->id) {
2185 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2186 } else {
2187 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2188 }
2189 }
2190
2191 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2192 mon_fdset_fd->fd = fd;
2193 mon_fdset_fd->removed = false;
2194 if (has_opaque) {
2195 mon_fdset_fd->opaque = g_strdup(opaque);
2196 }
2197 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2198
2199 fdinfo = g_malloc0(sizeof(*fdinfo));
2200 fdinfo->fdset_id = mon_fdset->id;
2201 fdinfo->fd = mon_fdset_fd->fd;
2202
2203 return fdinfo;
2204
2205 error:
2206 if (fd != -1) {
2207 close(fd);
2208 }
2209 return NULL;
2210 }
2211
2212 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2213 {
2214 MonFdset *mon_fdset;
2215 MonFdsetFd *mon_fdset_fd;
2216 char fd_str[60];
2217
2218 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2219 if (mon_fdset->id != fdset_id) {
2220 continue;
2221 }
2222 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2223 if (has_fd) {
2224 if (mon_fdset_fd->fd != fd) {
2225 continue;
2226 }
2227 mon_fdset_fd->removed = true;
2228 break;
2229 } else {
2230 mon_fdset_fd->removed = true;
2231 }
2232 }
2233 if (has_fd && !mon_fdset_fd) {
2234 goto error;
2235 }
2236 monitor_fdset_cleanup(mon_fdset);
2237 return;
2238 }
2239
2240 error:
2241 if (has_fd) {
2242 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2243 fdset_id, fd);
2244 } else {
2245 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2246 }
2247 error_set(errp, QERR_FD_NOT_FOUND, fd_str);
2248 }
2249
2250 FdsetInfoList *qmp_query_fdsets(Error **errp)
2251 {
2252 MonFdset *mon_fdset;
2253 MonFdsetFd *mon_fdset_fd;
2254 FdsetInfoList *fdset_list = NULL;
2255
2256 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2257 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2258 FdsetFdInfoList *fdsetfd_list = NULL;
2259
2260 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2261 fdset_info->value->fdset_id = mon_fdset->id;
2262
2263 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2264 FdsetFdInfoList *fdsetfd_info;
2265
2266 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2267 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2268 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2269 if (mon_fdset_fd->opaque) {
2270 fdsetfd_info->value->has_opaque = true;
2271 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2272 } else {
2273 fdsetfd_info->value->has_opaque = false;
2274 }
2275
2276 fdsetfd_info->next = fdsetfd_list;
2277 fdsetfd_list = fdsetfd_info;
2278 }
2279
2280 fdset_info->value->fds = fdsetfd_list;
2281
2282 fdset_info->next = fdset_list;
2283 fdset_list = fdset_info;
2284 }
2285
2286 return fdset_list;
2287 }
2288
2289 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2290 {
2291 #ifndef _WIN32
2292 MonFdset *mon_fdset;
2293 MonFdsetFd *mon_fdset_fd;
2294 int mon_fd_flags;
2295
2296 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2297 if (mon_fdset->id != fdset_id) {
2298 continue;
2299 }
2300 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2301 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2302 if (mon_fd_flags == -1) {
2303 return -1;
2304 }
2305
2306 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2307 return mon_fdset_fd->fd;
2308 }
2309 }
2310 errno = EACCES;
2311 return -1;
2312 }
2313 #endif
2314
2315 errno = ENOENT;
2316 return -1;
2317 }
2318
2319 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2320 {
2321 MonFdset *mon_fdset;
2322 MonFdsetFd *mon_fdset_fd_dup;
2323
2324 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2325 if (mon_fdset->id != fdset_id) {
2326 continue;
2327 }
2328 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2329 if (mon_fdset_fd_dup->fd == dup_fd) {
2330 return -1;
2331 }
2332 }
2333 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2334 mon_fdset_fd_dup->fd = dup_fd;
2335 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2336 return 0;
2337 }
2338 return -1;
2339 }
2340
2341 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2342 {
2343 MonFdset *mon_fdset;
2344 MonFdsetFd *mon_fdset_fd_dup;
2345
2346 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2347 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2348 if (mon_fdset_fd_dup->fd == dup_fd) {
2349 if (remove) {
2350 QLIST_REMOVE(mon_fdset_fd_dup, next);
2351 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2352 monitor_fdset_cleanup(mon_fdset);
2353 }
2354 }
2355 return mon_fdset->id;
2356 }
2357 }
2358 }
2359 return -1;
2360 }
2361
2362 int monitor_fdset_dup_fd_find(int dup_fd)
2363 {
2364 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2365 }
2366
2367 int monitor_fdset_dup_fd_remove(int dup_fd)
2368 {
2369 return monitor_fdset_dup_fd_find_remove(dup_fd, true);
2370 }
2371
2372 int monitor_handle_fd_param(Monitor *mon, const char *fdname)
2373 {
2374 int fd;
2375 Error *local_err = NULL;
2376
2377 if (!qemu_isdigit(fdname[0]) && mon) {
2378
2379 fd = monitor_get_fd(mon, fdname, &local_err);
2380 if (fd == -1) {
2381 qerror_report_err(local_err);
2382 error_free(local_err);
2383 return -1;
2384 }
2385 } else {
2386 fd = qemu_parse_fd(fdname);
2387 }
2388
2389 return fd;
2390 }
2391
2392 /* mon_cmds and info_cmds would be sorted at runtime */
2393 static mon_cmd_t mon_cmds[] = {
2394 #include "hmp-commands.h"
2395 { NULL, NULL, },
2396 };
2397
2398 /* Please update hmp-commands.hx when adding or changing commands */
2399 static mon_cmd_t info_cmds[] = {
2400 {
2401 .name = "version",
2402 .args_type = "",
2403 .params = "",
2404 .help = "show the version of QEMU",
2405 .mhandler.info = hmp_info_version,
2406 },
2407 {
2408 .name = "network",
2409 .args_type = "",
2410 .params = "",
2411 .help = "show the network state",
2412 .mhandler.info = do_info_network,
2413 },
2414 {
2415 .name = "chardev",
2416 .args_type = "",
2417 .params = "",
2418 .help = "show the character devices",
2419 .mhandler.info = hmp_info_chardev,
2420 },
2421 {
2422 .name = "block",
2423 .args_type = "",
2424 .params = "",
2425 .help = "show the block devices",
2426 .mhandler.info = hmp_info_block,
2427 },
2428 {
2429 .name = "blockstats",
2430 .args_type = "",
2431 .params = "",
2432 .help = "show block device statistics",
2433 .mhandler.info = hmp_info_blockstats,
2434 },
2435 {
2436 .name = "block-jobs",
2437 .args_type = "",
2438 .params = "",
2439 .help = "show progress of ongoing block device operations",
2440 .mhandler.info = hmp_info_block_jobs,
2441 },
2442 {
2443 .name = "registers",
2444 .args_type = "",
2445 .params = "",
2446 .help = "show the cpu registers",
2447 .mhandler.info = do_info_registers,
2448 },
2449 {
2450 .name = "cpus",
2451 .args_type = "",
2452 .params = "",
2453 .help = "show infos for each CPU",
2454 .mhandler.info = hmp_info_cpus,
2455 },
2456 {
2457 .name = "history",
2458 .args_type = "",
2459 .params = "",
2460 .help = "show the command line history",
2461 .mhandler.info = do_info_history,
2462 },
2463 #if defined(TARGET_I386) || defined(TARGET_PPC) || defined(TARGET_MIPS) || \
2464 defined(TARGET_LM32) || (defined(TARGET_SPARC) && !defined(TARGET_SPARC64))
2465 {
2466 .name = "irq",
2467 .args_type = "",
2468 .params = "",
2469 .help = "show the interrupts statistics (if available)",
2470 #ifdef TARGET_SPARC
2471 .mhandler.info = sun4m_irq_info,
2472 #elif defined(TARGET_LM32)
2473 .mhandler.info = lm32_irq_info,
2474 #else
2475 .mhandler.info = irq_info,
2476 #endif
2477 },
2478 {
2479 .name = "pic",
2480 .args_type = "",
2481 .params = "",
2482 .help = "show i8259 (PIC) state",
2483 #ifdef TARGET_SPARC
2484 .mhandler.info = sun4m_pic_info,
2485 #elif defined(TARGET_LM32)
2486 .mhandler.info = lm32_do_pic_info,
2487 #else
2488 .mhandler.info = pic_info,
2489 #endif
2490 },
2491 #endif
2492 {
2493 .name = "pci",
2494 .args_type = "",
2495 .params = "",
2496 .help = "show PCI info",
2497 .mhandler.info = hmp_info_pci,
2498 },
2499 #if defined(TARGET_I386) || defined(TARGET_SH4) || defined(TARGET_SPARC) || \
2500 defined(TARGET_PPC) || defined(TARGET_XTENSA)
2501 {
2502 .name = "tlb",
2503 .args_type = "",
2504 .params = "",
2505 .help = "show virtual to physical memory mappings",
2506 .mhandler.info = tlb_info,
2507 },
2508 #endif
2509 #if defined(TARGET_I386)
2510 {
2511 .name = "mem",
2512 .args_type = "",
2513 .params = "",
2514 .help = "show the active virtual memory mappings",
2515 .mhandler.info = mem_info,
2516 },
2517 #endif
2518 {
2519 .name = "mtree",
2520 .args_type = "",
2521 .params = "",
2522 .help = "show memory tree",
2523 .mhandler.info = do_info_mtree,
2524 },
2525 {
2526 .name = "jit",
2527 .args_type = "",
2528 .params = "",
2529 .help = "show dynamic compiler info",
2530 .mhandler.info = do_info_jit,
2531 },
2532 {
2533 .name = "kvm",
2534 .args_type = "",
2535 .params = "",
2536 .help = "show KVM information",
2537 .mhandler.info = hmp_info_kvm,
2538 },
2539 {
2540 .name = "numa",
2541 .args_type = "",
2542 .params = "",
2543 .help = "show NUMA information",
2544 .mhandler.info = do_info_numa,
2545 },
2546 {
2547 .name = "usb",
2548 .args_type = "",
2549 .params = "",
2550 .help = "show guest USB devices",
2551 .mhandler.info = usb_info,
2552 },
2553 {
2554 .name = "usbhost",
2555 .args_type = "",
2556 .params = "",
2557 .help = "show host USB devices",
2558 .mhandler.info = usb_host_info,
2559 },
2560 {
2561 .name = "profile",
2562 .args_type = "",
2563 .params = "",
2564 .help = "show profiling information",
2565 .mhandler.info = do_info_profile,
2566 },
2567 {
2568 .name = "capture",
2569 .args_type = "",
2570 .params = "",
2571 .help = "show capture information",
2572 .mhandler.info = do_info_capture,
2573 },
2574 {
2575 .name = "snapshots",
2576 .args_type = "",
2577 .params = "",
2578 .help = "show the currently saved VM snapshots",
2579 .mhandler.info = do_info_snapshots,
2580 },
2581 {
2582 .name = "status",
2583 .args_type = "",
2584 .params = "",
2585 .help = "show the current VM status (running|paused)",
2586 .mhandler.info = hmp_info_status,
2587 },
2588 {
2589 .name = "pcmcia",
2590 .args_type = "",
2591 .params = "",
2592 .help = "show guest PCMCIA status",
2593 .mhandler.info = pcmcia_info,
2594 },
2595 {
2596 .name = "mice",
2597 .args_type = "",
2598 .params = "",
2599 .help = "show which guest mouse is receiving events",
2600 .mhandler.info = hmp_info_mice,
2601 },
2602 {
2603 .name = "vnc",
2604 .args_type = "",
2605 .params = "",
2606 .help = "show the vnc server status",
2607 .mhandler.info = hmp_info_vnc,
2608 },
2609 #if defined(CONFIG_SPICE)
2610 {
2611 .name = "spice",
2612 .args_type = "",
2613 .params = "",
2614 .help = "show the spice server status",
2615 .mhandler.info = hmp_info_spice,
2616 },
2617 #endif
2618 {
2619 .name = "name",
2620 .args_type = "",
2621 .params = "",
2622 .help = "show the current VM name",
2623 .mhandler.info = hmp_info_name,
2624 },
2625 {
2626 .name = "uuid",
2627 .args_type = "",
2628 .params = "",
2629 .help = "show the current VM UUID",
2630 .mhandler.info = hmp_info_uuid,
2631 },
2632 #if defined(TARGET_PPC)
2633 {
2634 .name = "cpustats",
2635 .args_type = "",
2636 .params = "",
2637 .help = "show CPU statistics",
2638 .mhandler.info = do_info_cpu_stats,
2639 },
2640 #endif
2641 #if defined(CONFIG_SLIRP)
2642 {
2643 .name = "usernet",
2644 .args_type = "",
2645 .params = "",
2646 .help = "show user network stack connection states",
2647 .mhandler.info = do_info_usernet,
2648 },
2649 #endif
2650 {
2651 .name = "migrate",
2652 .args_type = "",
2653 .params = "",
2654 .help = "show migration status",
2655 .mhandler.info = hmp_info_migrate,
2656 },
2657 {
2658 .name = "migrate_capabilities",
2659 .args_type = "",
2660 .params = "",
2661 .help = "show current migration capabilities",
2662 .mhandler.info = hmp_info_migrate_capabilities,
2663 },
2664 {
2665 .name = "migrate_cache_size",
2666 .args_type = "",
2667 .params = "",
2668 .help = "show current migration xbzrle cache size",
2669 .mhandler.info = hmp_info_migrate_cache_size,
2670 },
2671 {
2672 .name = "balloon",
2673 .args_type = "",
2674 .params = "",
2675 .help = "show balloon information",
2676 .mhandler.info = hmp_info_balloon,
2677 },
2678 {
2679 .name = "qtree",
2680 .args_type = "",
2681 .params = "",
2682 .help = "show device tree",
2683 .mhandler.info = do_info_qtree,
2684 },
2685 {
2686 .name = "qdm",
2687 .args_type = "",
2688 .params = "",
2689 .help = "show qdev device model list",
2690 .mhandler.info = do_info_qdm,
2691 },
2692 {
2693 .name = "roms",
2694 .args_type = "",
2695 .params = "",
2696 .help = "show roms",
2697 .mhandler.info = do_info_roms,
2698 },
2699 {
2700 .name = "trace-events",
2701 .args_type = "",
2702 .params = "",
2703 .help = "show available trace-events & their state",
2704 .mhandler.info = do_trace_print_events,
2705 },
2706 {
2707 .name = NULL,
2708 },
2709 };
2710
2711 static const mon_cmd_t qmp_cmds[] = {
2712 #include "qmp-commands-old.h"
2713 { /* NULL */ },
2714 };
2715
2716 /*******************************************************************/
2717
2718 static const char *pch;
2719 static jmp_buf expr_env;
2720
2721 #define MD_TLONG 0
2722 #define MD_I32 1
2723
2724 typedef struct MonitorDef {
2725 const char *name;
2726 int offset;
2727 target_long (*get_value)(const struct MonitorDef *md, int val);
2728 int type;
2729 } MonitorDef;
2730
2731 #if defined(TARGET_I386)
2732 static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2733 {
2734 CPUArchState *env = mon_get_cpu();
2735 return env->eip + env->segs[R_CS].base;
2736 }
2737 #endif
2738
2739 #if defined(TARGET_PPC)
2740 static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2741 {
2742 CPUArchState *env = mon_get_cpu();
2743 unsigned int u;
2744 int i;
2745
2746 u = 0;
2747 for (i = 0; i < 8; i++)
2748 u |= env->crf[i] << (32 - (4 * i));
2749
2750 return u;
2751 }
2752
2753 static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2754 {
2755 CPUArchState *env = mon_get_cpu();
2756 return env->msr;
2757 }
2758
2759 static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2760 {
2761 CPUArchState *env = mon_get_cpu();
2762 return env->xer;
2763 }
2764
2765 static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2766 {
2767 CPUArchState *env = mon_get_cpu();
2768 return cpu_ppc_load_decr(env);
2769 }
2770
2771 static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2772 {
2773 CPUArchState *env = mon_get_cpu();
2774 return cpu_ppc_load_tbu(env);
2775 }
2776
2777 static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2778 {
2779 CPUArchState *env = mon_get_cpu();
2780 return cpu_ppc_load_tbl(env);
2781 }
2782 #endif
2783
2784 #if defined(TARGET_SPARC)
2785 #ifndef TARGET_SPARC64
2786 static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2787 {
2788 CPUArchState *env = mon_get_cpu();
2789
2790 return cpu_get_psr(env);
2791 }
2792 #endif
2793
2794 static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2795 {
2796 CPUArchState *env = mon_get_cpu();
2797 return env->regwptr[val];
2798 }
2799 #endif
2800
2801 static const MonitorDef monitor_defs[] = {
2802 #ifdef TARGET_I386
2803
2804 #define SEG(name, seg) \
2805 { name, offsetof(CPUX86State, segs[seg].selector), NULL, MD_I32 },\
2806 { name ".base", offsetof(CPUX86State, segs[seg].base) },\
2807 { name ".limit", offsetof(CPUX86State, segs[seg].limit), NULL, MD_I32 },
2808
2809 { "eax", offsetof(CPUX86State, regs[0]) },
2810 { "ecx", offsetof(CPUX86State, regs[1]) },
2811 { "edx", offsetof(CPUX86State, regs[2]) },
2812 { "ebx", offsetof(CPUX86State, regs[3]) },
2813 { "esp|sp", offsetof(CPUX86State, regs[4]) },
2814 { "ebp|fp", offsetof(CPUX86State, regs[5]) },
2815 { "esi", offsetof(CPUX86State, regs[6]) },
2816 { "edi", offsetof(CPUX86State, regs[7]) },
2817 #ifdef TARGET_X86_64
2818 { "r8", offsetof(CPUX86State, regs[8]) },
2819 { "r9", offsetof(CPUX86State, regs[9]) },
2820 { "r10", offsetof(CPUX86State, regs[10]) },
2821 { "r11", offsetof(CPUX86State, regs[11]) },
2822 { "r12", offsetof(CPUX86State, regs[12]) },
2823 { "r13", offsetof(CPUX86State, regs[13]) },
2824 { "r14", offsetof(CPUX86State, regs[14]) },
2825 { "r15", offsetof(CPUX86State, regs[15]) },
2826 #endif
2827 { "eflags", offsetof(CPUX86State, eflags) },
2828 { "eip", offsetof(CPUX86State, eip) },
2829 SEG("cs", R_CS)
2830 SEG("ds", R_DS)
2831 SEG("es", R_ES)
2832 SEG("ss", R_SS)
2833 SEG("fs", R_FS)
2834 SEG("gs", R_GS)
2835 { "pc", 0, monitor_get_pc, },
2836 #elif defined(TARGET_PPC)
2837 /* General purpose registers */
2838 { "r0", offsetof(CPUPPCState, gpr[0]) },
2839 { "r1", offsetof(CPUPPCState, gpr[1]) },
2840 { "r2", offsetof(CPUPPCState, gpr[2]) },
2841 { "r3", offsetof(CPUPPCState, gpr[3]) },
2842 { "r4", offsetof(CPUPPCState, gpr[4]) },
2843 { "r5", offsetof(CPUPPCState, gpr[5]) },
2844 { "r6", offsetof(CPUPPCState, gpr[6]) },
2845 { "r7", offsetof(CPUPPCState, gpr[7]) },
2846 { "r8", offsetof(CPUPPCState, gpr[8]) },
2847 { "r9", offsetof(CPUPPCState, gpr[9]) },
2848 { "r10", offsetof(CPUPPCState, gpr[10]) },
2849 { "r11", offsetof(CPUPPCState, gpr[11]) },
2850 { "r12", offsetof(CPUPPCState, gpr[12]) },
2851 { "r13", offsetof(CPUPPCState, gpr[13]) },
2852 { "r14", offsetof(CPUPPCState, gpr[14]) },
2853 { "r15", offsetof(CPUPPCState, gpr[15]) },
2854 { "r16", offsetof(CPUPPCState, gpr[16]) },
2855 { "r17", offsetof(CPUPPCState, gpr[17]) },
2856 { "r18", offsetof(CPUPPCState, gpr[18]) },
2857 { "r19", offsetof(CPUPPCState, gpr[19]) },
2858 { "r20", offsetof(CPUPPCState, gpr[20]) },
2859 { "r21", offsetof(CPUPPCState, gpr[21]) },
2860 { "r22", offsetof(CPUPPCState, gpr[22]) },
2861 { "r23", offsetof(CPUPPCState, gpr[23]) },
2862 { "r24", offsetof(CPUPPCState, gpr[24]) },
2863 { "r25", offsetof(CPUPPCState, gpr[25]) },
2864 { "r26", offsetof(CPUPPCState, gpr[26]) },
2865 { "r27", offsetof(CPUPPCState, gpr[27]) },
2866 { "r28", offsetof(CPUPPCState, gpr[28]) },
2867 { "r29", offsetof(CPUPPCState, gpr[29]) },
2868 { "r30", offsetof(CPUPPCState, gpr[30]) },
2869 { "r31", offsetof(CPUPPCState, gpr[31]) },
2870 /* Floating point registers */
2871 { "f0", offsetof(CPUPPCState, fpr[0]) },
2872 { "f1", offsetof(CPUPPCState, fpr[1]) },
2873 { "f2", offsetof(CPUPPCState, fpr[2]) },
2874 { "f3", offsetof(CPUPPCState, fpr[3]) },
2875 { "f4", offsetof(CPUPPCState, fpr[4]) },
2876 { "f5", offsetof(CPUPPCState, fpr[5]) },
2877 { "f6", offsetof(CPUPPCState, fpr[6]) },
2878 { "f7", offsetof(CPUPPCState, fpr[7]) },
2879 { "f8", offsetof(CPUPPCState, fpr[8]) },
2880 { "f9", offsetof(CPUPPCState, fpr[9]) },
2881 { "f10", offsetof(CPUPPCState, fpr[10]) },
2882 { "f11", offsetof(CPUPPCState, fpr[11]) },
2883 { "f12", offsetof(CPUPPCState, fpr[12]) },
2884 { "f13", offsetof(CPUPPCState, fpr[13]) },
2885 { "f14", offsetof(CPUPPCState, fpr[14]) },
2886 { "f15", offsetof(CPUPPCState, fpr[15]) },
2887 { "f16", offsetof(CPUPPCState, fpr[16]) },
2888 { "f17", offsetof(CPUPPCState, fpr[17]) },
2889 { "f18", offsetof(CPUPPCState, fpr[18]) },
2890 { "f19", offsetof(CPUPPCState, fpr[19]) },
2891 { "f20", offsetof(CPUPPCState, fpr[20]) },
2892 { "f21", offsetof(CPUPPCState, fpr[21]) },
2893 { "f22", offsetof(CPUPPCState, fpr[22]) },
2894 { "f23", offsetof(CPUPPCState, fpr[23]) },
2895 { "f24", offsetof(CPUPPCState, fpr[24]) },
2896 { "f25", offsetof(CPUPPCState, fpr[25]) },
2897 { "f26", offsetof(CPUPPCState, fpr[26]) },
2898 { "f27", offsetof(CPUPPCState, fpr[27]) },
2899 { "f28", offsetof(CPUPPCState, fpr[28]) },
2900 { "f29", offsetof(CPUPPCState, fpr[29]) },
2901 { "f30", offsetof(CPUPPCState, fpr[30]) },
2902 { "f31", offsetof(CPUPPCState, fpr[31]) },
2903 { "fpscr", offsetof(CPUPPCState, fpscr) },
2904 /* Next instruction pointer */
2905 { "nip|pc", offsetof(CPUPPCState, nip) },
2906 { "lr", offsetof(CPUPPCState, lr) },
2907 { "ctr", offsetof(CPUPPCState, ctr) },
2908 { "decr", 0, &monitor_get_decr, },
2909 { "ccr", 0, &monitor_get_ccr, },
2910 /* Machine state register */
2911 { "msr", 0, &monitor_get_msr, },
2912 { "xer", 0, &monitor_get_xer, },
2913 { "tbu", 0, &monitor_get_tbu, },
2914 { "tbl", 0, &monitor_get_tbl, },
2915 #if defined(TARGET_PPC64)
2916 /* Address space register */
2917 { "asr", offsetof(CPUPPCState, asr) },
2918 #endif
2919 /* Segment registers */
2920 { "sdr1", offsetof(CPUPPCState, spr[SPR_SDR1]) },
2921 { "sr0", offsetof(CPUPPCState, sr[0]) },
2922 { "sr1", offsetof(CPUPPCState, sr[1]) },
2923 { "sr2", offsetof(CPUPPCState, sr[2]) },
2924 { "sr3", offsetof(CPUPPCState, sr[3]) },
2925 { "sr4", offsetof(CPUPPCState, sr[4]) },
2926 { "sr5", offsetof(CPUPPCState, sr[5]) },
2927 { "sr6", offsetof(CPUPPCState, sr[6]) },
2928 { "sr7", offsetof(CPUPPCState, sr[7]) },
2929 { "sr8", offsetof(CPUPPCState, sr[8]) },
2930 { "sr9", offsetof(CPUPPCState, sr[9]) },
2931 { "sr10", offsetof(CPUPPCState, sr[10]) },
2932 { "sr11", offsetof(CPUPPCState, sr[11]) },
2933 { "sr12", offsetof(CPUPPCState, sr[12]) },
2934 { "sr13", offsetof(CPUPPCState, sr[13]) },
2935 { "sr14", offsetof(CPUPPCState, sr[14]) },
2936 { "sr15", offsetof(CPUPPCState, sr[15]) },
2937 /* Too lazy to put BATs... */
2938 { "pvr", offsetof(CPUPPCState, spr[SPR_PVR]) },
2939
2940 { "srr0", offsetof(CPUPPCState, spr[SPR_SRR0]) },
2941 { "srr1", offsetof(CPUPPCState, spr[SPR_SRR1]) },
2942 { "sprg0", offsetof(CPUPPCState, spr[SPR_SPRG0]) },
2943 { "sprg1", offsetof(CPUPPCState, spr[SPR_SPRG1]) },
2944 { "sprg2", offsetof(CPUPPCState, spr[SPR_SPRG2]) },
2945 { "sprg3", offsetof(CPUPPCState, spr[SPR_SPRG3]) },
2946 { "sprg4", offsetof(CPUPPCState, spr[SPR_SPRG4]) },
2947 { "sprg5", offsetof(CPUPPCState, spr[SPR_SPRG5]) },
2948 { "sprg6", offsetof(CPUPPCState, spr[SPR_SPRG6]) },
2949 { "sprg7", offsetof(CPUPPCState, spr[SPR_SPRG7]) },
2950 { "pid", offsetof(CPUPPCState, spr[SPR_BOOKE_PID]) },
2951 { "csrr0", offsetof(CPUPPCState, spr[SPR_BOOKE_CSRR0]) },
2952 { "csrr1", offsetof(CPUPPCState, spr[SPR_BOOKE_CSRR1]) },
2953 { "esr", offsetof(CPUPPCState, spr[SPR_BOOKE_ESR]) },
2954 { "dear", offsetof(CPUPPCState, spr[SPR_BOOKE_DEAR]) },
2955 { "mcsr", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSR]) },
2956 { "tsr", offsetof(CPUPPCState, spr[SPR_BOOKE_TSR]) },
2957 { "tcr", offsetof(CPUPPCState, spr[SPR_BOOKE_TCR]) },
2958 { "vrsave", offsetof(CPUPPCState, spr[SPR_VRSAVE]) },
2959 { "pir", offsetof(CPUPPCState, spr[SPR_BOOKE_PIR]) },
2960 { "mcsrr0", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSRR0]) },
2961 { "mcsrr1", offsetof(CPUPPCState, spr[SPR_BOOKE_MCSRR1]) },
2962 { "decar", offsetof(CPUPPCState, spr[SPR_BOOKE_DECAR]) },
2963 { "ivpr", offsetof(CPUPPCState, spr[SPR_BOOKE_IVPR]) },
2964 { "epcr", offsetof(CPUPPCState, spr[SPR_BOOKE_EPCR]) },
2965 { "sprg8", offsetof(CPUPPCState, spr[SPR_BOOKE_SPRG8]) },
2966 { "ivor0", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR0]) },
2967 { "ivor1", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR1]) },
2968 { "ivor2", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR2]) },
2969 { "ivor3", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR3]) },
2970 { "ivor4", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR4]) },
2971 { "ivor5", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR5]) },
2972 { "ivor6", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR6]) },
2973 { "ivor7", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR7]) },
2974 { "ivor8", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR8]) },
2975 { "ivor9", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR9]) },
2976 { "ivor10", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR10]) },
2977 { "ivor11", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR11]) },
2978 { "ivor12", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR12]) },
2979 { "ivor13", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR13]) },
2980 { "ivor14", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR14]) },
2981 { "ivor15", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR15]) },
2982 { "ivor32", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR32]) },
2983 { "ivor33", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR33]) },
2984 { "ivor34", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR34]) },
2985 { "ivor35", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR35]) },
2986 { "ivor36", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR36]) },
2987 { "ivor37", offsetof(CPUPPCState, spr[SPR_BOOKE_IVOR37]) },
2988 { "mas0", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS0]) },
2989 { "mas1", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS1]) },
2990 { "mas2", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS2]) },
2991 { "mas3", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS3]) },
2992 { "mas4", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS4]) },
2993 { "mas6", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS6]) },
2994 { "mas7", offsetof(CPUPPCState, spr[SPR_BOOKE_MAS7]) },
2995 { "mmucfg", offsetof(CPUPPCState, spr[SPR_MMUCFG]) },
2996 { "tlb0cfg", offsetof(CPUPPCState, spr[SPR_BOOKE_TLB0CFG]) },
2997 { "tlb1cfg", offsetof(CPUPPCState, spr[SPR_BOOKE_TLB1CFG]) },
2998 { "epr", offsetof(CPUPPCState, spr[SPR_BOOKE_EPR]) },
2999 { "eplc", offsetof(CPUPPCState, spr[SPR_BOOKE_EPLC]) },
3000 { "epsc", offsetof(CPUPPCState, spr[SPR_BOOKE_EPSC]) },
3001 { "svr", offsetof(CPUPPCState, spr[SPR_E500_SVR]) },
3002 { "mcar", offsetof(CPUPPCState, spr[SPR_Exxx_MCAR]) },
3003 { "pid1", offsetof(CPUPPCState, spr[SPR_BOOKE_PID1]) },
3004 { "pid2", offsetof(CPUPPCState, spr[SPR_BOOKE_PID2]) },
3005 { "hid0", offsetof(CPUPPCState, spr[SPR_HID0]) },
3006
3007 #elif defined(TARGET_SPARC)
3008 { "g0", offsetof(CPUSPARCState, gregs[0]) },
3009 { "g1", offsetof(CPUSPARCState, gregs[1]) },
3010 { "g2", offsetof(CPUSPARCState, gregs[2]) },
3011 { "g3", offsetof(CPUSPARCState, gregs[3]) },
3012 { "g4", offsetof(CPUSPARCState, gregs[4]) },
3013 { "g5", offsetof(CPUSPARCState, gregs[5]) },
3014 { "g6", offsetof(CPUSPARCState, gregs[6]) },
3015 { "g7", offsetof(CPUSPARCState, gregs[7]) },
3016 { "o0", 0, monitor_get_reg },
3017 { "o1", 1, monitor_get_reg },
3018 { "o2", 2, monitor_get_reg },
3019 { "o3", 3, monitor_get_reg },
3020 { "o4", 4, monitor_get_reg },
3021 { "o5", 5, monitor_get_reg },
3022 { "o6", 6, monitor_get_reg },
3023 { "o7", 7, monitor_get_reg },
3024 { "l0", 8, monitor_get_reg },
3025 { "l1", 9, monitor_get_reg },
3026 { "l2", 10, monitor_get_reg },
3027 { "l3", 11, monitor_get_reg },
3028 { "l4", 12, monitor_get_reg },
3029 { "l5", 13, monitor_get_reg },
3030 { "l6", 14, monitor_get_reg },
3031 { "l7", 15, monitor_get_reg },
3032 { "i0", 16, monitor_get_reg },
3033 { "i1", 17, monitor_get_reg },
3034 { "i2", 18, monitor_get_reg },
3035 { "i3", 19, monitor_get_reg },
3036 { "i4", 20, monitor_get_reg },
3037 { "i5", 21, monitor_get_reg },
3038 { "i6", 22, monitor_get_reg },
3039 { "i7", 23, monitor_get_reg },
3040 { "pc", offsetof(CPUSPARCState, pc) },
3041 { "npc", offsetof(CPUSPARCState, npc) },
3042 { "y", offsetof(CPUSPARCState, y) },
3043 #ifndef TARGET_SPARC64
3044 { "psr", 0, &monitor_get_psr, },
3045 { "wim", offsetof(CPUSPARCState, wim) },
3046 #endif
3047 { "tbr", offsetof(CPUSPARCState, tbr) },
3048 { "fsr", offsetof(CPUSPARCState, fsr) },
3049 { "f0", offsetof(CPUSPARCState, fpr[0].l.upper) },
3050 { "f1", offsetof(CPUSPARCState, fpr[0].l.lower) },
3051 { "f2", offsetof(CPUSPARCState, fpr[1].l.upper) },
3052 { "f3", offsetof(CPUSPARCState, fpr[1].l.lower) },
3053 { "f4", offsetof(CPUSPARCState, fpr[2].l.upper) },
3054 { "f5", offsetof(CPUSPARCState, fpr[2].l.lower) },
3055 { "f6", offsetof(CPUSPARCState, fpr[3].l.upper) },
3056 { "f7", offsetof(CPUSPARCState, fpr[3].l.lower) },
3057 { "f8", offsetof(CPUSPARCState, fpr[4].l.upper) },
3058 { "f9", offsetof(CPUSPARCState, fpr[4].l.lower) },
3059 { "f10", offsetof(CPUSPARCState, fpr[5].l.upper) },
3060 { "f11", offsetof(CPUSPARCState, fpr[5].l.lower) },
3061 { "f12", offsetof(CPUSPARCState, fpr[6].l.upper) },
3062 { "f13", offsetof(CPUSPARCState, fpr[6].l.lower) },
3063 { "f14", offsetof(CPUSPARCState, fpr[7].l.upper) },
3064 { "f15", offsetof(CPUSPARCState, fpr[7].l.lower) },
3065 { "f16", offsetof(CPUSPARCState, fpr[8].l.upper) },
3066 { "f17", offsetof(CPUSPARCState, fpr[8].l.lower) },
3067 { "f18", offsetof(CPUSPARCState, fpr[9].l.upper) },
3068 { "f19", offsetof(CPUSPARCState, fpr[9].l.lower) },
3069 { "f20", offsetof(CPUSPARCState, fpr[10].l.upper) },
3070 { "f21", offsetof(CPUSPARCState, fpr[10].l.lower) },
3071 { "f22", offsetof(CPUSPARCState, fpr[11].l.upper) },
3072 { "f23", offsetof(CPUSPARCState, fpr[11].l.lower) },
3073 { "f24", offsetof(CPUSPARCState, fpr[12].l.upper) },
3074 { "f25", offsetof(CPUSPARCState, fpr[12].l.lower) },
3075 { "f26", offsetof(CPUSPARCState, fpr[13].l.upper) },
3076 { "f27", offsetof(CPUSPARCState, fpr[13].l.lower) },
3077 { "f28", offsetof(CPUSPARCState, fpr[14].l.upper) },
3078 { "f29", offsetof(CPUSPARCState, fpr[14].l.lower) },
3079 { "f30", offsetof(CPUSPARCState, fpr[15].l.upper) },
3080 { "f31", offsetof(CPUSPARCState, fpr[15].l.lower) },
3081 #ifdef TARGET_SPARC64
3082 { "f32", offsetof(CPUSPARCState, fpr[16]) },
3083 { "f34", offsetof(CPUSPARCState, fpr[17]) },
3084 { "f36", offsetof(CPUSPARCState, fpr[18]) },
3085 { "f38", offsetof(CPUSPARCState, fpr[19]) },
3086 { "f40", offsetof(CPUSPARCState, fpr[20]) },
3087 { "f42", offsetof(CPUSPARCState, fpr[21]) },
3088 { "f44", offsetof(CPUSPARCState, fpr[22]) },
3089 { "f46", offsetof(CPUSPARCState, fpr[23]) },
3090 { "f48", offsetof(CPUSPARCState, fpr[24]) },
3091 { "f50", offsetof(CPUSPARCState, fpr[25]) },
3092 { "f52", offsetof(CPUSPARCState, fpr[26]) },
3093 { "f54", offsetof(CPUSPARCState, fpr[27]) },
3094 { "f56", offsetof(CPUSPARCState, fpr[28]) },
3095 { "f58", offsetof(CPUSPARCState, fpr[29]) },
3096 { "f60", offsetof(CPUSPARCState, fpr[30]) },
3097 { "f62", offsetof(CPUSPARCState, fpr[31]) },
3098 { "asi", offsetof(CPUSPARCState, asi) },
3099 { "pstate", offsetof(CPUSPARCState, pstate) },
3100 { "cansave", offsetof(CPUSPARCState, cansave) },
3101 { "canrestore", offsetof(CPUSPARCState, canrestore) },
3102 { "otherwin", offsetof(CPUSPARCState, otherwin) },
3103 { "wstate", offsetof(CPUSPARCState, wstate) },
3104 { "cleanwin", offsetof(CPUSPARCState, cleanwin) },
3105 { "fprs", offsetof(CPUSPARCState, fprs) },
3106 #endif
3107 #endif
3108 { NULL },
3109 };
3110
3111 static void expr_error(Monitor *mon, const char *msg)
3112 {
3113 monitor_printf(mon, "%s\n", msg);
3114 longjmp(expr_env, 1);
3115 }
3116
3117 /* return 0 if OK, -1 if not found */
3118 static int get_monitor_def(target_long *pval, const char *name)
3119 {
3120 const MonitorDef *md;
3121 void *ptr;
3122
3123 for(md = monitor_defs; md->name != NULL; md++) {
3124 if (compare_cmd(name, md->name)) {
3125 if (md->get_value) {
3126 *pval = md->get_value(md, md->offset);
3127 } else {
3128 CPUArchState *env = mon_get_cpu();
3129 ptr = (uint8_t *)env + md->offset;
3130 switch(md->type) {
3131 case MD_I32:
3132 *pval = *(int32_t *)ptr;
3133 break;
3134 case MD_TLONG:
3135 *pval = *(target_long *)ptr;
3136 break;
3137 default:
3138 *pval = 0;
3139 break;
3140 }
3141 }
3142 return 0;
3143 }
3144 }
3145 return -1;
3146 }
3147
3148 static void next(void)
3149 {
3150 if (*pch != '\0') {
3151 pch++;
3152 while (qemu_isspace(*pch))
3153 pch++;
3154 }
3155 }
3156
3157 static int64_t expr_sum(Monitor *mon);
3158
3159 static int64_t expr_unary(Monitor *mon)
3160 {
3161 int64_t n;
3162 char *p;
3163 int ret;
3164
3165 switch(*pch) {
3166 case '+':
3167 next();
3168 n = expr_unary(mon);
3169 break;
3170 case '-':
3171 next();
3172 n = -expr_unary(mon);
3173 break;
3174 case '~':
3175 next();
3176 n = ~expr_unary(mon);
3177 break;
3178 case '(':
3179 next();
3180 n = expr_sum(mon);
3181 if (*pch != ')') {
3182 expr_error(mon, "')' expected");
3183 }
3184 next();
3185 break;
3186 case '\'':
3187 pch++;
3188 if (*pch == '\0')
3189 expr_error(mon, "character constant expected");
3190 n = *pch;
3191 pch++;
3192 if (*pch != '\'')
3193 expr_error(mon, "missing terminating \' character");
3194 next();
3195 break;
3196 case '$':
3197 {
3198 char buf[128], *q;
3199 target_long reg=0;
3200
3201 pch++;
3202 q = buf;
3203 while ((*pch >= 'a' && *pch <= 'z') ||
3204 (*pch >= 'A' && *pch <= 'Z') ||
3205 (*pch >= '0' && *pch <= '9') ||
3206 *pch == '_' || *pch == '.') {
3207 if ((q - buf) < sizeof(buf) - 1)
3208 *q++ = *pch;
3209 pch++;
3210 }
3211 while (qemu_isspace(*pch))
3212 pch++;
3213 *q = 0;
3214 ret = get_monitor_def(&reg, buf);
3215 if (ret < 0)
3216 expr_error(mon, "unknown register");
3217 n = reg;
3218 }
3219 break;
3220 case '\0':
3221 expr_error(mon, "unexpected end of expression");
3222 n = 0;
3223 break;
3224 default:
3225 errno = 0;
3226 n = strtoull(pch, &p, 0);
3227 if (errno == ERANGE) {
3228 expr_error(mon, "number too large");
3229 }
3230 if (pch == p) {
3231 expr_error(mon, "invalid char in expression");
3232 }
3233 pch = p;
3234 while (qemu_isspace(*pch))
3235 pch++;
3236 break;
3237 }
3238 return n;
3239 }
3240
3241
3242 static int64_t expr_prod(Monitor *mon)
3243 {
3244 int64_t val, val2;
3245 int op;
3246
3247 val = expr_unary(mon);
3248 for(;;) {
3249 op = *pch;
3250 if (op != '*' && op != '/' && op != '%')
3251 break;
3252 next();
3253 val2 = expr_unary(mon);
3254 switch(op) {
3255 default:
3256 case '*':
3257 val *= val2;
3258 break;
3259 case '/':
3260 case '%':
3261 if (val2 == 0)
3262 expr_error(mon, "division by zero");
3263 if (op == '/')
3264 val /= val2;
3265 else
3266 val %= val2;
3267 break;
3268 }
3269 }
3270 return val;
3271 }
3272
3273 static int64_t expr_logic(Monitor *mon)
3274 {
3275 int64_t val, val2;
3276 int op;
3277
3278 val = expr_prod(mon);
3279 for(;;) {
3280 op = *pch;
3281 if (op != '&' && op != '|' && op != '^')
3282 break;
3283 next();
3284 val2 = expr_prod(mon);
3285 switch(op) {
3286 default:
3287 case '&':
3288 val &= val2;
3289 break;
3290 case '|':
3291 val |= val2;
3292 break;
3293 case '^':
3294 val ^= val2;
3295 break;
3296 }
3297 }
3298 return val;
3299 }
3300
3301 static int64_t expr_sum(Monitor *mon)
3302 {
3303 int64_t val, val2;
3304 int op;
3305
3306 val = expr_logic(mon);
3307 for(;;) {
3308 op = *pch;
3309 if (op != '+' && op != '-')
3310 break;
3311 next();
3312 val2 = expr_logic(mon);
3313 if (op == '+')
3314 val += val2;
3315 else
3316 val -= val2;
3317 }
3318 return val;
3319 }
3320
3321 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3322 {
3323 pch = *pp;
3324 if (setjmp(expr_env)) {
3325 *pp = pch;
3326 return -1;
3327 }
3328 while (qemu_isspace(*pch))
3329 pch++;
3330 *pval = expr_sum(mon);
3331 *pp = pch;
3332 return 0;
3333 }
3334
3335 static int get_double(Monitor *mon, double *pval, const char **pp)
3336 {
3337 const char *p = *pp;
3338 char *tailp;
3339 double d;
3340
3341 d = strtod(p, &tailp);
3342 if (tailp == p) {
3343 monitor_printf(mon, "Number expected\n");
3344 return -1;
3345 }
3346 if (d != d || d - d != 0) {
3347 /* NaN or infinity */
3348 monitor_printf(mon, "Bad number\n");
3349 return -1;
3350 }
3351 *pval = d;
3352 *pp = tailp;
3353 return 0;
3354 }
3355
3356 static int get_str(char *buf, int buf_size, const char **pp)
3357 {
3358 const char *p;
3359 char *q;
3360 int c;
3361
3362 q = buf;
3363 p = *pp;
3364 while (qemu_isspace(*p))
3365 p++;
3366 if (*p == '\0') {
3367 fail:
3368 *q = '\0';
3369 *pp = p;
3370 return -1;
3371 }
3372 if (*p == '\"') {
3373 p++;
3374 while (*p != '\0' && *p != '\"') {
3375 if (*p == '\\') {
3376 p++;
3377 c = *p++;
3378 switch(c) {
3379 case 'n':
3380 c = '\n';
3381 break;
3382 case 'r':
3383 c = '\r';
3384 break;
3385 case '\\':
3386 case '\'':
3387 case '\"':
3388 break;
3389 default:
3390 qemu_printf("unsupported escape code: '\\%c'\n", c);
3391 goto fail;
3392 }
3393 if ((q - buf) < buf_size - 1) {
3394 *q++ = c;
3395 }
3396 } else {
3397 if ((q - buf) < buf_size - 1) {
3398 *q++ = *p;
3399 }
3400 p++;
3401 }
3402 }
3403 if (*p != '\"') {
3404 qemu_printf("unterminated string\n");
3405 goto fail;
3406 }
3407 p++;
3408 } else {
3409 while (*p != '\0' && !qemu_isspace(*p)) {
3410 if ((q - buf) < buf_size - 1) {
3411 *q++ = *p;
3412 }
3413 p++;
3414 }
3415 }
3416 *q = '\0';
3417 *pp = p;
3418 return 0;
3419 }
3420
3421 /*
3422 * Store the command-name in cmdname, and return a pointer to
3423 * the remaining of the command string.
3424 */
3425 static const char *get_command_name(const char *cmdline,
3426 char *cmdname, size_t nlen)
3427 {
3428 size_t len;
3429 const char *p, *pstart;
3430
3431 p = cmdline;
3432 while (qemu_isspace(*p))
3433 p++;
3434 if (*p == '\0')
3435 return NULL;
3436 pstart = p;
3437 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3438 p++;
3439 len = p - pstart;
3440 if (len > nlen - 1)
3441 len = nlen - 1;
3442 memcpy(cmdname, pstart, len);
3443 cmdname[len] = '\0';
3444 return p;
3445 }
3446
3447 /**
3448 * Read key of 'type' into 'key' and return the current
3449 * 'type' pointer.
3450 */
3451 static char *key_get_info(const char *type, char **key)
3452 {
3453 size_t len;
3454 char *p, *str;
3455
3456 if (*type == ',')
3457 type++;
3458
3459 p = strchr(type, ':');
3460 if (!p) {
3461 *key = NULL;
3462 return NULL;
3463 }
3464 len = p - type;
3465
3466 str = g_malloc(len + 1);
3467 memcpy(str, type, len);
3468 str[len] = '\0';
3469
3470 *key = str;
3471 return ++p;
3472 }
3473
3474 static int default_fmt_format = 'x';
3475 static int default_fmt_size = 4;
3476
3477 #define MAX_ARGS 16
3478
3479 static int is_valid_option(const char *c, const char *typestr)
3480 {
3481 char option[3];
3482
3483 option[0] = '-';
3484 option[1] = *c;
3485 option[2] = '\0';
3486
3487 typestr = strstr(typestr, option);
3488 return (typestr != NULL);
3489 }
3490
3491 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3492 const char *cmdname)
3493 {
3494 const mon_cmd_t *cmd;
3495
3496 for (cmd = disp_table; cmd->name != NULL; cmd++) {
3497 if (compare_cmd(cmdname, cmd->name)) {
3498 return cmd;
3499 }
3500 }
3501
3502 return NULL;
3503 }
3504
3505 static const mon_cmd_t *monitor_find_command(const char *cmdname)
3506 {
3507 return search_dispatch_table(mon_cmds, cmdname);
3508 }
3509
3510 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
3511 {
3512 return search_dispatch_table(qmp_cmds, cmdname);
3513 }
3514
3515 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3516 const char *cmdline,
3517 QDict *qdict)
3518 {
3519 const char *p, *typestr;
3520 int c;
3521 const mon_cmd_t *cmd;
3522 char cmdname[256];
3523 char buf[1024];
3524 char *key;
3525
3526 #ifdef DEBUG
3527 monitor_printf(mon, "command='%s'\n", cmdline);
3528 #endif
3529
3530 /* extract the command name */
3531 p = get_command_name(cmdline, cmdname, sizeof(cmdname));
3532 if (!p)
3533 return NULL;
3534
3535 cmd = monitor_find_command(cmdname);
3536 if (!cmd) {
3537 monitor_printf(mon, "unknown command: '%s'\n", cmdname);
3538 return NULL;
3539 }
3540
3541 /* parse the parameters */
3542 typestr = cmd->args_type;
3543 for(;;) {
3544 typestr = key_get_info(typestr, &key);
3545 if (!typestr)
3546 break;
3547 c = *typestr;
3548 typestr++;
3549 switch(c) {
3550 case 'F':
3551 case 'B':
3552 case 's':
3553 {
3554 int ret;
3555
3556 while (qemu_isspace(*p))
3557 p++;
3558 if (*typestr == '?') {
3559 typestr++;
3560 if (*p == '\0') {
3561 /* no optional string: NULL argument */
3562 break;
3563 }
3564 }
3565 ret = get_str(buf, sizeof(buf), &p);
3566 if (ret < 0) {
3567 switch(c) {
3568 case 'F':
3569 monitor_printf(mon, "%s: filename expected\n",
3570 cmdname);
3571 break;
3572 case 'B':
3573 monitor_printf(mon, "%s: block device name expected\n",
3574 cmdname);
3575 break;
3576 default:
3577 monitor_printf(mon, "%s: string expected\n", cmdname);
3578 break;
3579 }
3580 goto fail;
3581 }
3582 qdict_put(qdict, key, qstring_from_str(buf));
3583 }
3584 break;
3585 case 'O':
3586 {
3587 QemuOptsList *opts_list;
3588 QemuOpts *opts;
3589
3590 opts_list = qemu_find_opts(key);
3591 if (!opts_list || opts_list->desc->name) {
3592 goto bad_type;
3593 }
3594 while (qemu_isspace(*p)) {
3595 p++;
3596 }
3597 if (!*p)
3598 break;
3599 if (get_str(buf, sizeof(buf), &p) < 0) {
3600 goto fail;
3601 }
3602 opts = qemu_opts_parse(opts_list, buf, 1);
3603 if (!opts) {
3604 goto fail;
3605 }
3606 qemu_opts_to_qdict(opts, qdict);
3607 qemu_opts_del(opts);
3608 }
3609 break;
3610 case '/':
3611 {
3612 int count, format, size;
3613
3614 while (qemu_isspace(*p))
3615 p++;
3616 if (*p == '/') {
3617 /* format found */
3618 p++;
3619 count = 1;
3620 if (qemu_isdigit(*p)) {
3621 count = 0;
3622 while (qemu_isdigit(*p)) {
3623 count = count * 10 + (*p - '0');
3624 p++;
3625 }
3626 }
3627 size = -1;
3628 format = -1;
3629 for(;;) {
3630 switch(*p) {
3631 case 'o':
3632 case 'd':
3633 case 'u':
3634 case 'x':
3635 case 'i':
3636 case 'c':
3637 format = *p++;
3638 break;
3639 case 'b':
3640 size = 1;
3641 p++;
3642 break;
3643 case 'h':
3644 size = 2;
3645 p++;
3646 break;
3647 case 'w':
3648 size = 4;
3649 p++;
3650 break;
3651 case 'g':
3652 case 'L':
3653 size = 8;
3654 p++;
3655 break;
3656 default:
3657 goto next;
3658 }
3659 }
3660 next:
3661 if (*p != '\0' && !qemu_isspace(*p)) {
3662 monitor_printf(mon, "invalid char in format: '%c'\n",
3663 *p);
3664 goto fail;
3665 }
3666 if (format < 0)
3667 format = default_fmt_format;
3668 if (format != 'i') {
3669 /* for 'i', not specifying a size gives -1 as size */
3670 if (size < 0)
3671 size = default_fmt_size;
3672 default_fmt_size = size;
3673 }
3674 default_fmt_format = format;
3675 } else {
3676 count = 1;
3677 format = default_fmt_format;
3678 if (format != 'i') {
3679 size = default_fmt_size;
3680 } else {
3681 size = -1;
3682 }
3683 }
3684 qdict_put(qdict, "count", qint_from_int(count));
3685 qdict_put(qdict, "format", qint_from_int(format));
3686 qdict_put(qdict, "size", qint_from_int(size));
3687 }
3688 break;
3689 case 'i':
3690 case 'l':
3691 case 'M':
3692 {
3693 int64_t val;
3694
3695 while (qemu_isspace(*p))
3696 p++;
3697 if (*typestr == '?' || *typestr == '.') {
3698 if (*typestr == '?') {
3699 if (*p == '\0') {
3700 typestr++;
3701 break;
3702 }
3703 } else {
3704 if (*p == '.') {
3705 p++;
3706 while (qemu_isspace(*p))
3707 p++;
3708 } else {
3709 typestr++;
3710 break;
3711 }
3712 }
3713 typestr++;
3714 }
3715 if (get_expr(mon, &val, &p))
3716 goto fail;
3717 /* Check if 'i' is greater than 32-bit */
3718 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3719 monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3720 monitor_printf(mon, "integer is for 32-bit values\n");
3721 goto fail;
3722 } else if (c == 'M') {
3723 if (val < 0) {
3724 monitor_printf(mon, "enter a positive value\n");
3725 goto fail;
3726 }
3727 val <<= 20;
3728 }
3729 qdict_put(qdict, key, qint_from_int(val));
3730 }
3731 break;
3732 case 'o':
3733 {
3734 int64_t val;
3735 char *end;
3736
3737 while (qemu_isspace(*p)) {
3738 p++;
3739 }
3740 if (*typestr == '?') {
3741 typestr++;
3742 if (*p == '\0') {
3743 break;
3744 }
3745 }
3746 val = strtosz(p, &end);
3747 if (val < 0) {
3748 monitor_printf(mon, "invalid size\n");
3749 goto fail;
3750 }
3751 qdict_put(qdict, key, qint_from_int(val));
3752 p = end;
3753 }
3754 break;
3755 case 'T':
3756 {
3757 double val;
3758
3759 while (qemu_isspace(*p))
3760 p++;
3761 if (*typestr == '?') {
3762 typestr++;
3763 if (*p == '\0') {
3764 break;
3765 }
3766 }
3767 if (get_double(mon, &val, &p) < 0) {
3768 goto fail;
3769 }
3770 if (p[0] && p[1] == 's') {
3771 switch (*p) {
3772 case 'm':
3773 val /= 1e3; p += 2; break;
3774 case 'u':
3775 val /= 1e6; p += 2; break;
3776 case 'n':
3777 val /= 1e9; p += 2; break;
3778 }
3779 }
3780 if (*p && !qemu_isspace(*p)) {
3781 monitor_printf(mon, "Unknown unit suffix\n");
3782 goto fail;
3783 }
3784 qdict_put(qdict, key, qfloat_from_double(val));
3785 }
3786 break;
3787 case 'b':
3788 {
3789 const char *beg;
3790 int val;
3791
3792 while (qemu_isspace(*p)) {
3793 p++;
3794 }
3795 beg = p;
3796 while (qemu_isgraph(*p)) {
3797 p++;
3798 }
3799 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3800 val = 1;
3801 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3802 val = 0;
3803 } else {
3804 monitor_printf(mon, "Expected 'on' or 'off'\n");
3805 goto fail;
3806 }
3807 qdict_put(qdict, key, qbool_from_int(val));
3808 }
3809 break;
3810 case '-':
3811 {
3812 const char *tmp = p;
3813 int skip_key = 0;
3814 /* option */
3815
3816 c = *typestr++;
3817 if (c == '\0')
3818 goto bad_type;
3819 while (qemu_isspace(*p))
3820 p++;
3821 if (*p == '-') {
3822 p++;
3823 if(c != *p) {
3824 if(!is_valid_option(p, typestr)) {
3825
3826 monitor_printf(mon, "%s: unsupported option -%c\n",
3827 cmdname, *p);
3828 goto fail;
3829 } else {
3830 skip_key = 1;
3831 }
3832 }
3833 if(skip_key) {
3834 p = tmp;
3835 } else {
3836 /* has option */
3837 p++;
3838 qdict_put(qdict, key, qbool_from_int(1));
3839 }
3840 }
3841 }
3842 break;
3843 default:
3844 bad_type:
3845 monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
3846 goto fail;
3847 }
3848 g_free(key);
3849 key = NULL;
3850 }
3851 /* check that all arguments were parsed */
3852 while (qemu_isspace(*p))
3853 p++;
3854 if (*p != '\0') {
3855 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3856 cmdname);
3857 goto fail;
3858 }
3859
3860 return cmd;
3861
3862 fail:
3863 g_free(key);
3864 return NULL;
3865 }
3866
3867 void monitor_set_error(Monitor *mon, QError *qerror)
3868 {
3869 /* report only the first error */
3870 if (!mon->error) {
3871 mon->error = qerror;
3872 } else {
3873 QDECREF(qerror);
3874 }
3875 }
3876
3877 static void handler_audit(Monitor *mon, const mon_cmd_t *cmd, int ret)
3878 {
3879 if (ret && !monitor_has_error(mon)) {
3880 /*
3881 * If it returns failure, it must have passed on error.
3882 *
3883 * Action: Report an internal error to the client if in QMP.
3884 */
3885 qerror_report(QERR_UNDEFINED_ERROR);
3886 }
3887 }
3888
3889 static void handle_user_command(Monitor *mon, const char *cmdline)
3890 {
3891 QDict *qdict;
3892 const mon_cmd_t *cmd;
3893
3894 qdict = qdict_new();
3895
3896 cmd = monitor_parse_command(mon, cmdline, qdict);
3897 if (!cmd)
3898 goto out;
3899
3900 if (handler_is_async(cmd)) {
3901 user_async_cmd_handler(mon, cmd, qdict);
3902 } else if (handler_is_qobject(cmd)) {
3903 QObject *data = NULL;
3904
3905 /* XXX: ignores the error code */
3906 cmd->mhandler.cmd_new(mon, qdict, &data);
3907 assert(!monitor_has_error(mon));
3908 if (data) {
3909 cmd->user_print(mon, data);
3910 qobject_decref(data);
3911 }
3912 } else {
3913 cmd->mhandler.cmd(mon, qdict);
3914 }
3915
3916 out:
3917 QDECREF(qdict);
3918 }
3919
3920 static void cmd_completion(const char *name, const char *list)
3921 {
3922 const char *p, *pstart;
3923 char cmd[128];
3924 int len;
3925
3926 p = list;
3927 for(;;) {
3928 pstart = p;
3929 p = strchr(p, '|');
3930 if (!p)
3931 p = pstart + strlen(pstart);
3932 len = p - pstart;
3933 if (len > sizeof(cmd) - 2)
3934 len = sizeof(cmd) - 2;
3935 memcpy(cmd, pstart, len);
3936 cmd[len] = '\0';
3937 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3938 readline_add_completion(cur_mon->rs, cmd);
3939 }
3940 if (*p == '\0')
3941 break;
3942 p++;
3943 }
3944 }
3945
3946 static void file_completion(const char *input)
3947 {
3948 DIR *ffs;
3949 struct dirent *d;
3950 char path[1024];
3951 char file[1024], file_prefix[1024];
3952 int input_path_len;
3953 const char *p;
3954
3955 p = strrchr(input, '/');
3956 if (!p) {
3957 input_path_len = 0;
3958 pstrcpy(file_prefix, sizeof(file_prefix), input);
3959 pstrcpy(path, sizeof(path), ".");
3960 } else {
3961 input_path_len = p - input + 1;
3962 memcpy(path, input, input_path_len);
3963 if (input_path_len > sizeof(path) - 1)
3964 input_path_len = sizeof(path) - 1;
3965 path[input_path_len] = '\0';
3966 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3967 }
3968 #ifdef DEBUG_COMPLETION
3969 monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
3970 input, path, file_prefix);
3971 #endif
3972 ffs = opendir(path);
3973 if (!ffs)
3974 return;
3975 for(;;) {
3976 struct stat sb;
3977 d = readdir(ffs);
3978 if (!d)
3979 break;
3980
3981 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3982 continue;
3983 }
3984
3985 if (strstart(d->d_name, file_prefix, NULL)) {
3986 memcpy(file, input, input_path_len);
3987 if (input_path_len < sizeof(file))
3988 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3989 d->d_name);
3990 /* stat the file to find out if it's a directory.
3991 * In that case add a slash to speed up typing long paths
3992 */
3993 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3994 pstrcat(file, sizeof(file), "/");
3995 }
3996 readline_add_completion(cur_mon->rs, file);
3997 }
3998 }
3999 closedir(ffs);
4000 }
4001
4002 static void block_completion_it(void *opaque, BlockDriverState *bs)
4003 {
4004 const char *name = bdrv_get_device_name(bs);
4005 const char *input = opaque;
4006
4007 if (input[0] == '\0' ||
4008 !strncmp(name, (char *)input, strlen(input))) {
4009 readline_add_completion(cur_mon->rs, name);
4010 }
4011 }
4012
4013 /* NOTE: this parser is an approximate form of the real command parser */
4014 static void parse_cmdline(const char *cmdline,
4015 int *pnb_args, char **args)
4016 {
4017 const char *p;
4018 int nb_args, ret;
4019 char buf[1024];
4020
4021 p = cmdline;
4022 nb_args = 0;
4023 for(;;) {
4024 while (qemu_isspace(*p))
4025 p++;
4026 if (*p == '\0')
4027 break;
4028 if (nb_args >= MAX_ARGS)
4029 break;
4030 ret = get_str(buf, sizeof(buf), &p);
4031 args[nb_args] = g_strdup(buf);
4032 nb_args++;
4033 if (ret < 0)
4034 break;
4035 }
4036 *pnb_args = nb_args;
4037 }
4038
4039 static const char *next_arg_type(const char *typestr)
4040 {
4041 const char *p = strchr(typestr, ':');
4042 return (p != NULL ? ++p : typestr);
4043 }
4044
4045 static void monitor_find_completion(const char *cmdline)
4046 {
4047 const char *cmdname;
4048 char *args[MAX_ARGS];
4049 int nb_args, i, len;
4050 const char *ptype, *str;
4051 const mon_cmd_t *cmd;
4052
4053 parse_cmdline(cmdline, &nb_args, args);
4054 #ifdef DEBUG_COMPLETION
4055 for(i = 0; i < nb_args; i++) {
4056 monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
4057 }
4058 #endif
4059
4060 /* if the line ends with a space, it means we want to complete the
4061 next arg */
4062 len = strlen(cmdline);
4063 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4064 if (nb_args >= MAX_ARGS) {
4065 goto cleanup;
4066 }
4067 args[nb_args++] = g_strdup("");
4068 }
4069 if (nb_args <= 1) {
4070 /* command completion */
4071 if (nb_args == 0)
4072 cmdname = "";
4073 else
4074 cmdname = args[0];
4075 readline_set_completion_index(cur_mon->rs, strlen(cmdname));
4076 for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
4077 cmd_completion(cmdname, cmd->name);
4078 }
4079 } else {
4080 /* find the command */
4081 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4082 if (compare_cmd(args[0], cmd->name)) {
4083 break;
4084 }
4085 }
4086 if (!cmd->name) {
4087 goto cleanup;
4088 }
4089
4090 ptype = next_arg_type(cmd->args_type);
4091 for(i = 0; i < nb_args - 2; i++) {
4092 if (*ptype != '\0') {
4093 ptype = next_arg_type(ptype);
4094 while (*ptype == '?')
4095 ptype = next_arg_type(ptype);
4096 }
4097 }
4098 str = args[nb_args - 1];
4099 if (*ptype == '-' && ptype[1] != '\0') {
4100 ptype = next_arg_type(ptype);
4101 }
4102 switch(*ptype) {
4103 case 'F':
4104 /* file completion */
4105 readline_set_completion_index(cur_mon->rs, strlen(str));
4106 file_completion(str);
4107 break;
4108 case 'B':
4109 /* block device name completion */
4110 readline_set_completion_index(cur_mon->rs, strlen(str));
4111 bdrv_iterate(block_completion_it, (void *)str);
4112 break;
4113 case 's':
4114 /* XXX: more generic ? */
4115 if (!strcmp(cmd->name, "info")) {
4116 readline_set_completion_index(cur_mon->rs, strlen(str));
4117 for(cmd = info_cmds; cmd->name != NULL; cmd++) {
4118 cmd_completion(str, cmd->name);
4119 }
4120 } else if (!strcmp(cmd->name, "sendkey")) {
4121 char *sep = strrchr(str, '-');
4122 if (sep)
4123 str = sep + 1;
4124 readline_set_completion_index(cur_mon->rs, strlen(str));
4125 for (i = 0; i < Q_KEY_CODE_MAX; i++) {
4126 cmd_completion(str, QKeyCode_lookup[i]);
4127 }
4128 } else if (!strcmp(cmd->name, "help|?")) {
4129 readline_set_completion_index(cur_mon->rs, strlen(str));
4130 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4131 cmd_completion(str, cmd->name);
4132 }
4133 }
4134 break;
4135 default:
4136 break;
4137 }
4138 }
4139
4140 cleanup:
4141 for (i = 0; i < nb_args; i++) {
4142 g_free(args[i]);
4143 }
4144 }
4145
4146 static int monitor_can_read(void *opaque)
4147 {
4148 Monitor *mon = opaque;
4149
4150 return (mon->suspend_cnt == 0) ? 1 : 0;
4151 }
4152
4153 static int invalid_qmp_mode(const Monitor *mon, const char *cmd_name)
4154 {
4155 int is_cap = compare_cmd(cmd_name, "qmp_capabilities");
4156 return (qmp_cmd_mode(mon) ? is_cap : !is_cap);
4157 }
4158
4159 /*
4160 * Argument validation rules:
4161 *
4162 * 1. The argument must exist in cmd_args qdict
4163 * 2. The argument type must be the expected one
4164 *
4165 * Special case: If the argument doesn't exist in cmd_args and
4166 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
4167 * checking is skipped for it.
4168 */
4169 static int check_client_args_type(const QDict *client_args,
4170 const QDict *cmd_args, int flags)
4171 {
4172 const QDictEntry *ent;
4173
4174 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
4175 QObject *obj;
4176 QString *arg_type;
4177 const QObject *client_arg = qdict_entry_value(ent);
4178 const char *client_arg_name = qdict_entry_key(ent);
4179
4180 obj = qdict_get(cmd_args, client_arg_name);
4181 if (!obj) {
4182 if (flags & QMP_ACCEPT_UNKNOWNS) {
4183 /* handler accepts unknowns */
4184 continue;
4185 }
4186 /* client arg doesn't exist */
4187 qerror_report(QERR_INVALID_PARAMETER, client_arg_name);
4188 return -1;
4189 }
4190
4191 arg_type = qobject_to_qstring(obj);
4192 assert(arg_type != NULL);
4193
4194 /* check if argument's type is correct */
4195 switch (qstring_get_str(arg_type)[0]) {
4196 case 'F':
4197 case 'B':
4198 case 's':
4199 if (qobject_type(client_arg) != QTYPE_QSTRING) {
4200 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4201 "string");
4202 return -1;
4203 }
4204 break;
4205 case 'i':
4206 case 'l':
4207 case 'M':
4208 case 'o':
4209 if (qobject_type(client_arg) != QTYPE_QINT) {
4210 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4211 "int");
4212 return -1;
4213 }
4214 break;
4215 case 'T':
4216 if (qobject_type(client_arg) != QTYPE_QINT &&
4217 qobject_type(client_arg) != QTYPE_QFLOAT) {
4218 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4219 "number");
4220 return -1;
4221 }
4222 break;
4223 case 'b':
4224 case '-':
4225 if (qobject_type(client_arg) != QTYPE_QBOOL) {
4226 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4227 "bool");
4228 return -1;
4229 }
4230 break;
4231 case 'O':
4232 assert(flags & QMP_ACCEPT_UNKNOWNS);
4233 break;
4234 case 'q':
4235 /* Any QObject can be passed. */
4236 break;
4237 case '/':
4238 case '.':
4239 /*
4240 * These types are not supported by QMP and thus are not
4241 * handled here. Fall through.
4242 */
4243 default:
4244 abort();
4245 }
4246 }
4247
4248 return 0;
4249 }
4250
4251 /*
4252 * - Check if the client has passed all mandatory args
4253 * - Set special flags for argument validation
4254 */
4255 static int check_mandatory_args(const QDict *cmd_args,
4256 const QDict *client_args, int *flags)
4257 {
4258 const QDictEntry *ent;
4259
4260 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
4261 const char *cmd_arg_name = qdict_entry_key(ent);
4262 QString *type = qobject_to_qstring(qdict_entry_value(ent));
4263 assert(type != NULL);
4264
4265 if (qstring_get_str(type)[0] == 'O') {
4266 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
4267 *flags |= QMP_ACCEPT_UNKNOWNS;
4268 } else if (qstring_get_str(type)[0] != '-' &&
4269 qstring_get_str(type)[1] != '?' &&
4270 !qdict_haskey(client_args, cmd_arg_name)) {
4271 qerror_report(QERR_MISSING_PARAMETER, cmd_arg_name);
4272 return -1;
4273 }
4274 }
4275
4276 return 0;
4277 }
4278
4279 static QDict *qdict_from_args_type(const char *args_type)
4280 {
4281 int i;
4282 QDict *qdict;
4283 QString *key, *type, *cur_qs;
4284
4285 assert(args_type != NULL);
4286
4287 qdict = qdict_new();
4288
4289 if (args_type == NULL || args_type[0] == '\0') {
4290 /* no args, empty qdict */
4291 goto out;
4292 }
4293
4294 key = qstring_new();
4295 type = qstring_new();
4296
4297 cur_qs = key;
4298
4299 for (i = 0;; i++) {
4300 switch (args_type[i]) {
4301 case ',':
4302 case '\0':
4303 qdict_put(qdict, qstring_get_str(key), type);
4304 QDECREF(key);
4305 if (args_type[i] == '\0') {
4306 goto out;
4307 }
4308 type = qstring_new(); /* qdict has ref */
4309 cur_qs = key = qstring_new();
4310 break;
4311 case ':':
4312 cur_qs = type;
4313 break;
4314 default:
4315 qstring_append_chr(cur_qs, args_type[i]);
4316 break;
4317 }
4318 }
4319
4320 out:
4321 return qdict;
4322 }
4323
4324 /*
4325 * Client argument checking rules:
4326 *
4327 * 1. Client must provide all mandatory arguments
4328 * 2. Each argument provided by the client must be expected
4329 * 3. Each argument provided by the client must have the type expected
4330 * by the command
4331 */
4332 static int qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args)
4333 {
4334 int flags, err;
4335 QDict *cmd_args;
4336
4337 cmd_args = qdict_from_args_type(cmd->args_type);
4338
4339 flags = 0;
4340 err = check_mandatory_args(cmd_args, client_args, &flags);
4341 if (err) {
4342 goto out;
4343 }
4344
4345 err = check_client_args_type(client_args, cmd_args, flags);
4346
4347 out:
4348 QDECREF(cmd_args);
4349 return err;
4350 }
4351
4352 /*
4353 * Input object checking rules
4354 *
4355 * 1. Input object must be a dict
4356 * 2. The "execute" key must exist
4357 * 3. The "execute" key must be a string
4358 * 4. If the "arguments" key exists, it must be a dict
4359 * 5. If the "id" key exists, it can be anything (ie. json-value)
4360 * 6. Any argument not listed above is considered invalid
4361 */
4362 static QDict *qmp_check_input_obj(QObject *input_obj)
4363 {
4364 const QDictEntry *ent;
4365 int has_exec_key = 0;
4366 QDict *input_dict;
4367
4368 if (qobject_type(input_obj) != QTYPE_QDICT) {
4369 qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "object");
4370 return NULL;
4371 }
4372
4373 input_dict = qobject_to_qdict(input_obj);
4374
4375 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
4376 const char *arg_name = qdict_entry_key(ent);
4377 const QObject *arg_obj = qdict_entry_value(ent);
4378
4379 if (!strcmp(arg_name, "execute")) {
4380 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
4381 qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "execute",
4382 "string");
4383 return NULL;
4384 }
4385 has_exec_key = 1;
4386 } else if (!strcmp(arg_name, "arguments")) {
4387 if (qobject_type(arg_obj) != QTYPE_QDICT) {
4388 qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "arguments",
4389 "object");
4390 return NULL;
4391 }
4392 } else if (!strcmp(arg_name, "id")) {
4393 /* FIXME: check duplicated IDs for async commands */
4394 } else {
4395 qerror_report(QERR_QMP_EXTRA_MEMBER, arg_name);
4396 return NULL;
4397 }
4398 }
4399
4400 if (!has_exec_key) {
4401 qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4402 return NULL;
4403 }
4404
4405 return input_dict;
4406 }
4407
4408 static void qmp_call_cmd(Monitor *mon, const mon_cmd_t *cmd,
4409 const QDict *params)
4410 {
4411 int ret;
4412 QObject *data = NULL;
4413
4414 ret = cmd->mhandler.cmd_new(mon, params, &data);
4415 handler_audit(mon, cmd, ret);
4416 monitor_protocol_emitter(mon, data);
4417 qobject_decref(data);
4418 }
4419
4420 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
4421 {
4422 int err;
4423 QObject *obj;
4424 QDict *input, *args;
4425 const mon_cmd_t *cmd;
4426 const char *cmd_name;
4427 Monitor *mon = cur_mon;
4428
4429 args = input = NULL;
4430
4431 obj = json_parser_parse(tokens, NULL);
4432 if (!obj) {
4433 // FIXME: should be triggered in json_parser_parse()
4434 qerror_report(QERR_JSON_PARSING);
4435 goto err_out;
4436 }
4437
4438 input = qmp_check_input_obj(obj);
4439 if (!input) {
4440 qobject_decref(obj);
4441 goto err_out;
4442 }
4443
4444 mon->mc->id = qdict_get(input, "id");
4445 qobject_incref(mon->mc->id);
4446
4447 cmd_name = qdict_get_str(input, "execute");
4448 trace_handle_qmp_command(mon, cmd_name);
4449 if (invalid_qmp_mode(mon, cmd_name)) {
4450 qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
4451 goto err_out;
4452 }
4453
4454 cmd = qmp_find_cmd(cmd_name);
4455 if (!cmd) {
4456 qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
4457 goto err_out;
4458 }
4459
4460 obj = qdict_get(input, "arguments");
4461 if (!obj) {
4462 args = qdict_new();
4463 } else {
4464 args = qobject_to_qdict(obj);
4465 QINCREF(args);
4466 }
4467
4468 err = qmp_check_client_args(cmd, args);
4469 if (err < 0) {
4470 goto err_out;
4471 }
4472
4473 if (handler_is_async(cmd)) {
4474 err = qmp_async_cmd_handler(mon, cmd, args);
4475 if (err) {
4476 /* emit the error response */
4477 goto err_out;
4478 }
4479 } else {
4480 qmp_call_cmd(mon, cmd, args);
4481 }
4482
4483 goto out;
4484
4485 err_out:
4486 monitor_protocol_emitter(mon, NULL);
4487 out:
4488 QDECREF(input);
4489 QDECREF(args);
4490 }
4491
4492 /**
4493 * monitor_control_read(): Read and handle QMP input
4494 */
4495 static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
4496 {
4497 Monitor *old_mon = cur_mon;
4498
4499 cur_mon = opaque;
4500
4501 json_message_parser_feed(&cur_mon->mc->parser, (const char *) buf, size);
4502
4503 cur_mon = old_mon;
4504 }
4505
4506 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4507 {
4508 Monitor *old_mon = cur_mon;
4509 int i;
4510
4511 cur_mon = opaque;
4512
4513 if (cur_mon->rs) {
4514 for (i = 0; i < size; i++)
4515 readline_handle_byte(cur_mon->rs, buf[i]);
4516 } else {
4517 if (size == 0 || buf[size - 1] != 0)
4518 monitor_printf(cur_mon, "corrupted command\n");
4519 else
4520 handle_user_command(cur_mon, (char *)buf);
4521 }
4522
4523 cur_mon = old_mon;
4524 }
4525
4526 static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
4527 {
4528 monitor_suspend(mon);
4529 handle_user_command(mon, cmdline);
4530 monitor_resume(mon);
4531 }
4532
4533 int monitor_suspend(Monitor *mon)
4534 {
4535 if (!mon->rs)
4536 return -ENOTTY;
4537 mon->suspend_cnt++;
4538 return 0;
4539 }
4540
4541 void monitor_resume(Monitor *mon)
4542 {
4543 if (!mon->rs)
4544 return;
4545 if (--mon->suspend_cnt == 0)
4546 readline_show_prompt(mon->rs);
4547 }
4548
4549 static QObject *get_qmp_greeting(void)
4550 {
4551 QObject *ver = NULL;
4552
4553 qmp_marshal_input_query_version(NULL, NULL, &ver);
4554 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
4555 }
4556
4557 /**
4558 * monitor_control_event(): Print QMP gretting
4559 */
4560 static void monitor_control_event(void *opaque, int event)
4561 {
4562 QObject *data;
4563 Monitor *mon = opaque;
4564
4565 switch (event) {
4566 case CHR_EVENT_OPENED:
4567 mon->mc->command_mode = 0;
4568 data = get_qmp_greeting();
4569 monitor_json_emitter(mon, data);
4570 qobject_decref(data);
4571 mon_refcount++;
4572 break;
4573 case CHR_EVENT_CLOSED:
4574 json_message_parser_destroy(&mon->mc->parser);
4575 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4576 mon_refcount--;
4577 monitor_fdsets_cleanup();
4578 break;
4579 }
4580 }
4581
4582 static void monitor_event(void *opaque, int event)
4583 {
4584 Monitor *mon = opaque;
4585
4586 switch (event) {
4587 case CHR_EVENT_MUX_IN:
4588 mon->mux_out = 0;
4589 if (mon->reset_seen) {
4590 readline_restart(mon->rs);
4591 monitor_resume(mon);
4592 monitor_flush(mon);
4593 } else {
4594 mon->suspend_cnt = 0;
4595 }
4596 break;
4597
4598 case CHR_EVENT_MUX_OUT:
4599 if (mon->reset_seen) {
4600 if (mon->suspend_cnt == 0) {
4601 monitor_printf(mon, "\n");
4602 }
4603 monitor_flush(mon);
4604 monitor_suspend(mon);
4605 } else {
4606 mon->suspend_cnt++;
4607 }
4608 mon->mux_out = 1;
4609 break;
4610
4611 case CHR_EVENT_OPENED:
4612 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4613 "information\n", QEMU_VERSION);
4614 if (!mon->mux_out) {
4615 readline_show_prompt(mon->rs);
4616 }
4617 mon->reset_seen = 1;
4618 mon_refcount++;
4619 break;
4620
4621 case CHR_EVENT_CLOSED:
4622 mon_refcount--;
4623 monitor_fdsets_cleanup();
4624 break;
4625 }
4626 }
4627
4628 static int
4629 compare_mon_cmd(const void *a, const void *b)
4630 {
4631 return strcmp(((const mon_cmd_t *)a)->name,
4632 ((const mon_cmd_t *)b)->name);
4633 }
4634
4635 static void sortcmdlist(void)
4636 {
4637 int array_num;
4638 int elem_size = sizeof(mon_cmd_t);
4639
4640 array_num = sizeof(mon_cmds)/elem_size-1;
4641 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4642
4643 array_num = sizeof(info_cmds)/elem_size-1;
4644 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4645 }
4646
4647
4648 /*
4649 * Local variables:
4650 * c-indent-level: 4
4651 * c-basic-offset: 4
4652 * tab-width: 8
4653 * End:
4654 */
4655
4656 void monitor_init(CharDriverState *chr, int flags)
4657 {
4658 static int is_first_init = 1;
4659 Monitor *mon;
4660
4661 if (is_first_init) {
4662 monitor_protocol_event_init();
4663 is_first_init = 0;
4664 }
4665
4666 mon = g_malloc0(sizeof(*mon));
4667
4668 mon->chr = chr;
4669 mon->flags = flags;
4670 if (flags & MONITOR_USE_READLINE) {
4671 mon->rs = readline_init(mon, monitor_find_completion);
4672 monitor_read_command(mon, 0);
4673 }
4674
4675 if (monitor_ctrl_mode(mon)) {
4676 mon->mc = g_malloc0(sizeof(MonitorControl));
4677 /* Control mode requires special handlers */
4678 qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
4679 monitor_control_event, mon);
4680 qemu_chr_fe_set_echo(chr, true);
4681
4682 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4683 } else {
4684 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4685 monitor_event, mon);
4686 }
4687
4688 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4689 if (!default_mon || (flags & MONITOR_IS_DEFAULT))
4690 default_mon = mon;
4691
4692 sortcmdlist();
4693 }
4694
4695 static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
4696 {
4697 BlockDriverState *bs = opaque;
4698 int ret = 0;
4699
4700 if (bdrv_set_key(bs, password) != 0) {
4701 monitor_printf(mon, "invalid password\n");
4702 ret = -EPERM;
4703 }
4704 if (mon->password_completion_cb)
4705 mon->password_completion_cb(mon->password_opaque, ret);
4706
4707 monitor_read_command(mon, 1);
4708 }
4709
4710 ReadLineState *monitor_get_rs(Monitor *mon)
4711 {
4712 return mon->rs;
4713 }
4714
4715 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4716 BlockDriverCompletionFunc *completion_cb,
4717 void *opaque)
4718 {
4719 int err;
4720
4721 if (!bdrv_key_required(bs)) {
4722 if (completion_cb)
4723 completion_cb(opaque, 0);
4724 return 0;
4725 }
4726
4727 if (monitor_ctrl_mode(mon)) {
4728 qerror_report(QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
4729 bdrv_get_encrypted_filename(bs));
4730 return -1;
4731 }
4732
4733 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4734 bdrv_get_encrypted_filename(bs));
4735
4736 mon->password_completion_cb = completion_cb;
4737 mon->password_opaque = opaque;
4738
4739 err = monitor_read_password(mon, bdrv_password_cb, bs);
4740
4741 if (err && completion_cb)
4742 completion_cb(opaque, err);
4743
4744 return err;
4745 }
4746
4747 int monitor_read_block_device_key(Monitor *mon, const char *device,
4748 BlockDriverCompletionFunc *completion_cb,
4749 void *opaque)
4750 {
4751 BlockDriverState *bs;
4752
4753 bs = bdrv_find(device);
4754 if (!bs) {
4755 monitor_printf(mon, "Device not found %s\n", device);
4756 return -1;
4757 }
4758
4759 return monitor_read_bdrv_key_start(mon, bs, completion_cb, opaque);
4760 }