]> git.proxmox.com Git - qemu.git/blob - monitor.c
qapi: convert add_client
[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 #if TARGET_PHYS_ADDR_BITS > 32
3227 n = strtoull(pch, &p, 0);
3228 #else
3229 n = strtoul(pch, &p, 0);
3230 #endif
3231 if (errno == ERANGE) {
3232 expr_error(mon, "number too large");
3233 }
3234 if (pch == p) {
3235 expr_error(mon, "invalid char in expression");
3236 }
3237 pch = p;
3238 while (qemu_isspace(*pch))
3239 pch++;
3240 break;
3241 }
3242 return n;
3243 }
3244
3245
3246 static int64_t expr_prod(Monitor *mon)
3247 {
3248 int64_t val, val2;
3249 int op;
3250
3251 val = expr_unary(mon);
3252 for(;;) {
3253 op = *pch;
3254 if (op != '*' && op != '/' && op != '%')
3255 break;
3256 next();
3257 val2 = expr_unary(mon);
3258 switch(op) {
3259 default:
3260 case '*':
3261 val *= val2;
3262 break;
3263 case '/':
3264 case '%':
3265 if (val2 == 0)
3266 expr_error(mon, "division by zero");
3267 if (op == '/')
3268 val /= val2;
3269 else
3270 val %= val2;
3271 break;
3272 }
3273 }
3274 return val;
3275 }
3276
3277 static int64_t expr_logic(Monitor *mon)
3278 {
3279 int64_t val, val2;
3280 int op;
3281
3282 val = expr_prod(mon);
3283 for(;;) {
3284 op = *pch;
3285 if (op != '&' && op != '|' && op != '^')
3286 break;
3287 next();
3288 val2 = expr_prod(mon);
3289 switch(op) {
3290 default:
3291 case '&':
3292 val &= val2;
3293 break;
3294 case '|':
3295 val |= val2;
3296 break;
3297 case '^':
3298 val ^= val2;
3299 break;
3300 }
3301 }
3302 return val;
3303 }
3304
3305 static int64_t expr_sum(Monitor *mon)
3306 {
3307 int64_t val, val2;
3308 int op;
3309
3310 val = expr_logic(mon);
3311 for(;;) {
3312 op = *pch;
3313 if (op != '+' && op != '-')
3314 break;
3315 next();
3316 val2 = expr_logic(mon);
3317 if (op == '+')
3318 val += val2;
3319 else
3320 val -= val2;
3321 }
3322 return val;
3323 }
3324
3325 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3326 {
3327 pch = *pp;
3328 if (setjmp(expr_env)) {
3329 *pp = pch;
3330 return -1;
3331 }
3332 while (qemu_isspace(*pch))
3333 pch++;
3334 *pval = expr_sum(mon);
3335 *pp = pch;
3336 return 0;
3337 }
3338
3339 static int get_double(Monitor *mon, double *pval, const char **pp)
3340 {
3341 const char *p = *pp;
3342 char *tailp;
3343 double d;
3344
3345 d = strtod(p, &tailp);
3346 if (tailp == p) {
3347 monitor_printf(mon, "Number expected\n");
3348 return -1;
3349 }
3350 if (d != d || d - d != 0) {
3351 /* NaN or infinity */
3352 monitor_printf(mon, "Bad number\n");
3353 return -1;
3354 }
3355 *pval = d;
3356 *pp = tailp;
3357 return 0;
3358 }
3359
3360 static int get_str(char *buf, int buf_size, const char **pp)
3361 {
3362 const char *p;
3363 char *q;
3364 int c;
3365
3366 q = buf;
3367 p = *pp;
3368 while (qemu_isspace(*p))
3369 p++;
3370 if (*p == '\0') {
3371 fail:
3372 *q = '\0';
3373 *pp = p;
3374 return -1;
3375 }
3376 if (*p == '\"') {
3377 p++;
3378 while (*p != '\0' && *p != '\"') {
3379 if (*p == '\\') {
3380 p++;
3381 c = *p++;
3382 switch(c) {
3383 case 'n':
3384 c = '\n';
3385 break;
3386 case 'r':
3387 c = '\r';
3388 break;
3389 case '\\':
3390 case '\'':
3391 case '\"':
3392 break;
3393 default:
3394 qemu_printf("unsupported escape code: '\\%c'\n", c);
3395 goto fail;
3396 }
3397 if ((q - buf) < buf_size - 1) {
3398 *q++ = c;
3399 }
3400 } else {
3401 if ((q - buf) < buf_size - 1) {
3402 *q++ = *p;
3403 }
3404 p++;
3405 }
3406 }
3407 if (*p != '\"') {
3408 qemu_printf("unterminated string\n");
3409 goto fail;
3410 }
3411 p++;
3412 } else {
3413 while (*p != '\0' && !qemu_isspace(*p)) {
3414 if ((q - buf) < buf_size - 1) {
3415 *q++ = *p;
3416 }
3417 p++;
3418 }
3419 }
3420 *q = '\0';
3421 *pp = p;
3422 return 0;
3423 }
3424
3425 /*
3426 * Store the command-name in cmdname, and return a pointer to
3427 * the remaining of the command string.
3428 */
3429 static const char *get_command_name(const char *cmdline,
3430 char *cmdname, size_t nlen)
3431 {
3432 size_t len;
3433 const char *p, *pstart;
3434
3435 p = cmdline;
3436 while (qemu_isspace(*p))
3437 p++;
3438 if (*p == '\0')
3439 return NULL;
3440 pstart = p;
3441 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3442 p++;
3443 len = p - pstart;
3444 if (len > nlen - 1)
3445 len = nlen - 1;
3446 memcpy(cmdname, pstart, len);
3447 cmdname[len] = '\0';
3448 return p;
3449 }
3450
3451 /**
3452 * Read key of 'type' into 'key' and return the current
3453 * 'type' pointer.
3454 */
3455 static char *key_get_info(const char *type, char **key)
3456 {
3457 size_t len;
3458 char *p, *str;
3459
3460 if (*type == ',')
3461 type++;
3462
3463 p = strchr(type, ':');
3464 if (!p) {
3465 *key = NULL;
3466 return NULL;
3467 }
3468 len = p - type;
3469
3470 str = g_malloc(len + 1);
3471 memcpy(str, type, len);
3472 str[len] = '\0';
3473
3474 *key = str;
3475 return ++p;
3476 }
3477
3478 static int default_fmt_format = 'x';
3479 static int default_fmt_size = 4;
3480
3481 #define MAX_ARGS 16
3482
3483 static int is_valid_option(const char *c, const char *typestr)
3484 {
3485 char option[3];
3486
3487 option[0] = '-';
3488 option[1] = *c;
3489 option[2] = '\0';
3490
3491 typestr = strstr(typestr, option);
3492 return (typestr != NULL);
3493 }
3494
3495 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3496 const char *cmdname)
3497 {
3498 const mon_cmd_t *cmd;
3499
3500 for (cmd = disp_table; cmd->name != NULL; cmd++) {
3501 if (compare_cmd(cmdname, cmd->name)) {
3502 return cmd;
3503 }
3504 }
3505
3506 return NULL;
3507 }
3508
3509 static const mon_cmd_t *monitor_find_command(const char *cmdname)
3510 {
3511 return search_dispatch_table(mon_cmds, cmdname);
3512 }
3513
3514 static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
3515 {
3516 return search_dispatch_table(qmp_cmds, cmdname);
3517 }
3518
3519 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3520 const char *cmdline,
3521 QDict *qdict)
3522 {
3523 const char *p, *typestr;
3524 int c;
3525 const mon_cmd_t *cmd;
3526 char cmdname[256];
3527 char buf[1024];
3528 char *key;
3529
3530 #ifdef DEBUG
3531 monitor_printf(mon, "command='%s'\n", cmdline);
3532 #endif
3533
3534 /* extract the command name */
3535 p = get_command_name(cmdline, cmdname, sizeof(cmdname));
3536 if (!p)
3537 return NULL;
3538
3539 cmd = monitor_find_command(cmdname);
3540 if (!cmd) {
3541 monitor_printf(mon, "unknown command: '%s'\n", cmdname);
3542 return NULL;
3543 }
3544
3545 /* parse the parameters */
3546 typestr = cmd->args_type;
3547 for(;;) {
3548 typestr = key_get_info(typestr, &key);
3549 if (!typestr)
3550 break;
3551 c = *typestr;
3552 typestr++;
3553 switch(c) {
3554 case 'F':
3555 case 'B':
3556 case 's':
3557 {
3558 int ret;
3559
3560 while (qemu_isspace(*p))
3561 p++;
3562 if (*typestr == '?') {
3563 typestr++;
3564 if (*p == '\0') {
3565 /* no optional string: NULL argument */
3566 break;
3567 }
3568 }
3569 ret = get_str(buf, sizeof(buf), &p);
3570 if (ret < 0) {
3571 switch(c) {
3572 case 'F':
3573 monitor_printf(mon, "%s: filename expected\n",
3574 cmdname);
3575 break;
3576 case 'B':
3577 monitor_printf(mon, "%s: block device name expected\n",
3578 cmdname);
3579 break;
3580 default:
3581 monitor_printf(mon, "%s: string expected\n", cmdname);
3582 break;
3583 }
3584 goto fail;
3585 }
3586 qdict_put(qdict, key, qstring_from_str(buf));
3587 }
3588 break;
3589 case 'O':
3590 {
3591 QemuOptsList *opts_list;
3592 QemuOpts *opts;
3593
3594 opts_list = qemu_find_opts(key);
3595 if (!opts_list || opts_list->desc->name) {
3596 goto bad_type;
3597 }
3598 while (qemu_isspace(*p)) {
3599 p++;
3600 }
3601 if (!*p)
3602 break;
3603 if (get_str(buf, sizeof(buf), &p) < 0) {
3604 goto fail;
3605 }
3606 opts = qemu_opts_parse(opts_list, buf, 1);
3607 if (!opts) {
3608 goto fail;
3609 }
3610 qemu_opts_to_qdict(opts, qdict);
3611 qemu_opts_del(opts);
3612 }
3613 break;
3614 case '/':
3615 {
3616 int count, format, size;
3617
3618 while (qemu_isspace(*p))
3619 p++;
3620 if (*p == '/') {
3621 /* format found */
3622 p++;
3623 count = 1;
3624 if (qemu_isdigit(*p)) {
3625 count = 0;
3626 while (qemu_isdigit(*p)) {
3627 count = count * 10 + (*p - '0');
3628 p++;
3629 }
3630 }
3631 size = -1;
3632 format = -1;
3633 for(;;) {
3634 switch(*p) {
3635 case 'o':
3636 case 'd':
3637 case 'u':
3638 case 'x':
3639 case 'i':
3640 case 'c':
3641 format = *p++;
3642 break;
3643 case 'b':
3644 size = 1;
3645 p++;
3646 break;
3647 case 'h':
3648 size = 2;
3649 p++;
3650 break;
3651 case 'w':
3652 size = 4;
3653 p++;
3654 break;
3655 case 'g':
3656 case 'L':
3657 size = 8;
3658 p++;
3659 break;
3660 default:
3661 goto next;
3662 }
3663 }
3664 next:
3665 if (*p != '\0' && !qemu_isspace(*p)) {
3666 monitor_printf(mon, "invalid char in format: '%c'\n",
3667 *p);
3668 goto fail;
3669 }
3670 if (format < 0)
3671 format = default_fmt_format;
3672 if (format != 'i') {
3673 /* for 'i', not specifying a size gives -1 as size */
3674 if (size < 0)
3675 size = default_fmt_size;
3676 default_fmt_size = size;
3677 }
3678 default_fmt_format = format;
3679 } else {
3680 count = 1;
3681 format = default_fmt_format;
3682 if (format != 'i') {
3683 size = default_fmt_size;
3684 } else {
3685 size = -1;
3686 }
3687 }
3688 qdict_put(qdict, "count", qint_from_int(count));
3689 qdict_put(qdict, "format", qint_from_int(format));
3690 qdict_put(qdict, "size", qint_from_int(size));
3691 }
3692 break;
3693 case 'i':
3694 case 'l':
3695 case 'M':
3696 {
3697 int64_t val;
3698
3699 while (qemu_isspace(*p))
3700 p++;
3701 if (*typestr == '?' || *typestr == '.') {
3702 if (*typestr == '?') {
3703 if (*p == '\0') {
3704 typestr++;
3705 break;
3706 }
3707 } else {
3708 if (*p == '.') {
3709 p++;
3710 while (qemu_isspace(*p))
3711 p++;
3712 } else {
3713 typestr++;
3714 break;
3715 }
3716 }
3717 typestr++;
3718 }
3719 if (get_expr(mon, &val, &p))
3720 goto fail;
3721 /* Check if 'i' is greater than 32-bit */
3722 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3723 monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3724 monitor_printf(mon, "integer is for 32-bit values\n");
3725 goto fail;
3726 } else if (c == 'M') {
3727 if (val < 0) {
3728 monitor_printf(mon, "enter a positive value\n");
3729 goto fail;
3730 }
3731 val <<= 20;
3732 }
3733 qdict_put(qdict, key, qint_from_int(val));
3734 }
3735 break;
3736 case 'o':
3737 {
3738 int64_t val;
3739 char *end;
3740
3741 while (qemu_isspace(*p)) {
3742 p++;
3743 }
3744 if (*typestr == '?') {
3745 typestr++;
3746 if (*p == '\0') {
3747 break;
3748 }
3749 }
3750 val = strtosz(p, &end);
3751 if (val < 0) {
3752 monitor_printf(mon, "invalid size\n");
3753 goto fail;
3754 }
3755 qdict_put(qdict, key, qint_from_int(val));
3756 p = end;
3757 }
3758 break;
3759 case 'T':
3760 {
3761 double val;
3762
3763 while (qemu_isspace(*p))
3764 p++;
3765 if (*typestr == '?') {
3766 typestr++;
3767 if (*p == '\0') {
3768 break;
3769 }
3770 }
3771 if (get_double(mon, &val, &p) < 0) {
3772 goto fail;
3773 }
3774 if (p[0] && p[1] == 's') {
3775 switch (*p) {
3776 case 'm':
3777 val /= 1e3; p += 2; break;
3778 case 'u':
3779 val /= 1e6; p += 2; break;
3780 case 'n':
3781 val /= 1e9; p += 2; break;
3782 }
3783 }
3784 if (*p && !qemu_isspace(*p)) {
3785 monitor_printf(mon, "Unknown unit suffix\n");
3786 goto fail;
3787 }
3788 qdict_put(qdict, key, qfloat_from_double(val));
3789 }
3790 break;
3791 case 'b':
3792 {
3793 const char *beg;
3794 int val;
3795
3796 while (qemu_isspace(*p)) {
3797 p++;
3798 }
3799 beg = p;
3800 while (qemu_isgraph(*p)) {
3801 p++;
3802 }
3803 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3804 val = 1;
3805 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3806 val = 0;
3807 } else {
3808 monitor_printf(mon, "Expected 'on' or 'off'\n");
3809 goto fail;
3810 }
3811 qdict_put(qdict, key, qbool_from_int(val));
3812 }
3813 break;
3814 case '-':
3815 {
3816 const char *tmp = p;
3817 int skip_key = 0;
3818 /* option */
3819
3820 c = *typestr++;
3821 if (c == '\0')
3822 goto bad_type;
3823 while (qemu_isspace(*p))
3824 p++;
3825 if (*p == '-') {
3826 p++;
3827 if(c != *p) {
3828 if(!is_valid_option(p, typestr)) {
3829
3830 monitor_printf(mon, "%s: unsupported option -%c\n",
3831 cmdname, *p);
3832 goto fail;
3833 } else {
3834 skip_key = 1;
3835 }
3836 }
3837 if(skip_key) {
3838 p = tmp;
3839 } else {
3840 /* has option */
3841 p++;
3842 qdict_put(qdict, key, qbool_from_int(1));
3843 }
3844 }
3845 }
3846 break;
3847 default:
3848 bad_type:
3849 monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
3850 goto fail;
3851 }
3852 g_free(key);
3853 key = NULL;
3854 }
3855 /* check that all arguments were parsed */
3856 while (qemu_isspace(*p))
3857 p++;
3858 if (*p != '\0') {
3859 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3860 cmdname);
3861 goto fail;
3862 }
3863
3864 return cmd;
3865
3866 fail:
3867 g_free(key);
3868 return NULL;
3869 }
3870
3871 void monitor_set_error(Monitor *mon, QError *qerror)
3872 {
3873 /* report only the first error */
3874 if (!mon->error) {
3875 mon->error = qerror;
3876 } else {
3877 QDECREF(qerror);
3878 }
3879 }
3880
3881 static void handler_audit(Monitor *mon, const mon_cmd_t *cmd, int ret)
3882 {
3883 if (ret && !monitor_has_error(mon)) {
3884 /*
3885 * If it returns failure, it must have passed on error.
3886 *
3887 * Action: Report an internal error to the client if in QMP.
3888 */
3889 qerror_report(QERR_UNDEFINED_ERROR);
3890 }
3891 }
3892
3893 static void handle_user_command(Monitor *mon, const char *cmdline)
3894 {
3895 QDict *qdict;
3896 const mon_cmd_t *cmd;
3897
3898 qdict = qdict_new();
3899
3900 cmd = monitor_parse_command(mon, cmdline, qdict);
3901 if (!cmd)
3902 goto out;
3903
3904 if (handler_is_async(cmd)) {
3905 user_async_cmd_handler(mon, cmd, qdict);
3906 } else if (handler_is_qobject(cmd)) {
3907 QObject *data = NULL;
3908
3909 /* XXX: ignores the error code */
3910 cmd->mhandler.cmd_new(mon, qdict, &data);
3911 assert(!monitor_has_error(mon));
3912 if (data) {
3913 cmd->user_print(mon, data);
3914 qobject_decref(data);
3915 }
3916 } else {
3917 cmd->mhandler.cmd(mon, qdict);
3918 }
3919
3920 out:
3921 QDECREF(qdict);
3922 }
3923
3924 static void cmd_completion(const char *name, const char *list)
3925 {
3926 const char *p, *pstart;
3927 char cmd[128];
3928 int len;
3929
3930 p = list;
3931 for(;;) {
3932 pstart = p;
3933 p = strchr(p, '|');
3934 if (!p)
3935 p = pstart + strlen(pstart);
3936 len = p - pstart;
3937 if (len > sizeof(cmd) - 2)
3938 len = sizeof(cmd) - 2;
3939 memcpy(cmd, pstart, len);
3940 cmd[len] = '\0';
3941 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3942 readline_add_completion(cur_mon->rs, cmd);
3943 }
3944 if (*p == '\0')
3945 break;
3946 p++;
3947 }
3948 }
3949
3950 static void file_completion(const char *input)
3951 {
3952 DIR *ffs;
3953 struct dirent *d;
3954 char path[1024];
3955 char file[1024], file_prefix[1024];
3956 int input_path_len;
3957 const char *p;
3958
3959 p = strrchr(input, '/');
3960 if (!p) {
3961 input_path_len = 0;
3962 pstrcpy(file_prefix, sizeof(file_prefix), input);
3963 pstrcpy(path, sizeof(path), ".");
3964 } else {
3965 input_path_len = p - input + 1;
3966 memcpy(path, input, input_path_len);
3967 if (input_path_len > sizeof(path) - 1)
3968 input_path_len = sizeof(path) - 1;
3969 path[input_path_len] = '\0';
3970 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3971 }
3972 #ifdef DEBUG_COMPLETION
3973 monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
3974 input, path, file_prefix);
3975 #endif
3976 ffs = opendir(path);
3977 if (!ffs)
3978 return;
3979 for(;;) {
3980 struct stat sb;
3981 d = readdir(ffs);
3982 if (!d)
3983 break;
3984
3985 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3986 continue;
3987 }
3988
3989 if (strstart(d->d_name, file_prefix, NULL)) {
3990 memcpy(file, input, input_path_len);
3991 if (input_path_len < sizeof(file))
3992 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3993 d->d_name);
3994 /* stat the file to find out if it's a directory.
3995 * In that case add a slash to speed up typing long paths
3996 */
3997 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3998 pstrcat(file, sizeof(file), "/");
3999 }
4000 readline_add_completion(cur_mon->rs, file);
4001 }
4002 }
4003 closedir(ffs);
4004 }
4005
4006 static void block_completion_it(void *opaque, BlockDriverState *bs)
4007 {
4008 const char *name = bdrv_get_device_name(bs);
4009 const char *input = opaque;
4010
4011 if (input[0] == '\0' ||
4012 !strncmp(name, (char *)input, strlen(input))) {
4013 readline_add_completion(cur_mon->rs, name);
4014 }
4015 }
4016
4017 /* NOTE: this parser is an approximate form of the real command parser */
4018 static void parse_cmdline(const char *cmdline,
4019 int *pnb_args, char **args)
4020 {
4021 const char *p;
4022 int nb_args, ret;
4023 char buf[1024];
4024
4025 p = cmdline;
4026 nb_args = 0;
4027 for(;;) {
4028 while (qemu_isspace(*p))
4029 p++;
4030 if (*p == '\0')
4031 break;
4032 if (nb_args >= MAX_ARGS)
4033 break;
4034 ret = get_str(buf, sizeof(buf), &p);
4035 args[nb_args] = g_strdup(buf);
4036 nb_args++;
4037 if (ret < 0)
4038 break;
4039 }
4040 *pnb_args = nb_args;
4041 }
4042
4043 static const char *next_arg_type(const char *typestr)
4044 {
4045 const char *p = strchr(typestr, ':');
4046 return (p != NULL ? ++p : typestr);
4047 }
4048
4049 static void monitor_find_completion(const char *cmdline)
4050 {
4051 const char *cmdname;
4052 char *args[MAX_ARGS];
4053 int nb_args, i, len;
4054 const char *ptype, *str;
4055 const mon_cmd_t *cmd;
4056
4057 parse_cmdline(cmdline, &nb_args, args);
4058 #ifdef DEBUG_COMPLETION
4059 for(i = 0; i < nb_args; i++) {
4060 monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
4061 }
4062 #endif
4063
4064 /* if the line ends with a space, it means we want to complete the
4065 next arg */
4066 len = strlen(cmdline);
4067 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4068 if (nb_args >= MAX_ARGS) {
4069 goto cleanup;
4070 }
4071 args[nb_args++] = g_strdup("");
4072 }
4073 if (nb_args <= 1) {
4074 /* command completion */
4075 if (nb_args == 0)
4076 cmdname = "";
4077 else
4078 cmdname = args[0];
4079 readline_set_completion_index(cur_mon->rs, strlen(cmdname));
4080 for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
4081 cmd_completion(cmdname, cmd->name);
4082 }
4083 } else {
4084 /* find the command */
4085 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4086 if (compare_cmd(args[0], cmd->name)) {
4087 break;
4088 }
4089 }
4090 if (!cmd->name) {
4091 goto cleanup;
4092 }
4093
4094 ptype = next_arg_type(cmd->args_type);
4095 for(i = 0; i < nb_args - 2; i++) {
4096 if (*ptype != '\0') {
4097 ptype = next_arg_type(ptype);
4098 while (*ptype == '?')
4099 ptype = next_arg_type(ptype);
4100 }
4101 }
4102 str = args[nb_args - 1];
4103 if (*ptype == '-' && ptype[1] != '\0') {
4104 ptype = next_arg_type(ptype);
4105 }
4106 switch(*ptype) {
4107 case 'F':
4108 /* file completion */
4109 readline_set_completion_index(cur_mon->rs, strlen(str));
4110 file_completion(str);
4111 break;
4112 case 'B':
4113 /* block device name completion */
4114 readline_set_completion_index(cur_mon->rs, strlen(str));
4115 bdrv_iterate(block_completion_it, (void *)str);
4116 break;
4117 case 's':
4118 /* XXX: more generic ? */
4119 if (!strcmp(cmd->name, "info")) {
4120 readline_set_completion_index(cur_mon->rs, strlen(str));
4121 for(cmd = info_cmds; cmd->name != NULL; cmd++) {
4122 cmd_completion(str, cmd->name);
4123 }
4124 } else if (!strcmp(cmd->name, "sendkey")) {
4125 char *sep = strrchr(str, '-');
4126 if (sep)
4127 str = sep + 1;
4128 readline_set_completion_index(cur_mon->rs, strlen(str));
4129 for (i = 0; i < Q_KEY_CODE_MAX; i++) {
4130 cmd_completion(str, QKeyCode_lookup[i]);
4131 }
4132 } else if (!strcmp(cmd->name, "help|?")) {
4133 readline_set_completion_index(cur_mon->rs, strlen(str));
4134 for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4135 cmd_completion(str, cmd->name);
4136 }
4137 }
4138 break;
4139 default:
4140 break;
4141 }
4142 }
4143
4144 cleanup:
4145 for (i = 0; i < nb_args; i++) {
4146 g_free(args[i]);
4147 }
4148 }
4149
4150 static int monitor_can_read(void *opaque)
4151 {
4152 Monitor *mon = opaque;
4153
4154 return (mon->suspend_cnt == 0) ? 1 : 0;
4155 }
4156
4157 static int invalid_qmp_mode(const Monitor *mon, const char *cmd_name)
4158 {
4159 int is_cap = compare_cmd(cmd_name, "qmp_capabilities");
4160 return (qmp_cmd_mode(mon) ? is_cap : !is_cap);
4161 }
4162
4163 /*
4164 * Argument validation rules:
4165 *
4166 * 1. The argument must exist in cmd_args qdict
4167 * 2. The argument type must be the expected one
4168 *
4169 * Special case: If the argument doesn't exist in cmd_args and
4170 * the QMP_ACCEPT_UNKNOWNS flag is set, then the
4171 * checking is skipped for it.
4172 */
4173 static int check_client_args_type(const QDict *client_args,
4174 const QDict *cmd_args, int flags)
4175 {
4176 const QDictEntry *ent;
4177
4178 for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
4179 QObject *obj;
4180 QString *arg_type;
4181 const QObject *client_arg = qdict_entry_value(ent);
4182 const char *client_arg_name = qdict_entry_key(ent);
4183
4184 obj = qdict_get(cmd_args, client_arg_name);
4185 if (!obj) {
4186 if (flags & QMP_ACCEPT_UNKNOWNS) {
4187 /* handler accepts unknowns */
4188 continue;
4189 }
4190 /* client arg doesn't exist */
4191 qerror_report(QERR_INVALID_PARAMETER, client_arg_name);
4192 return -1;
4193 }
4194
4195 arg_type = qobject_to_qstring(obj);
4196 assert(arg_type != NULL);
4197
4198 /* check if argument's type is correct */
4199 switch (qstring_get_str(arg_type)[0]) {
4200 case 'F':
4201 case 'B':
4202 case 's':
4203 if (qobject_type(client_arg) != QTYPE_QSTRING) {
4204 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4205 "string");
4206 return -1;
4207 }
4208 break;
4209 case 'i':
4210 case 'l':
4211 case 'M':
4212 case 'o':
4213 if (qobject_type(client_arg) != QTYPE_QINT) {
4214 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4215 "int");
4216 return -1;
4217 }
4218 break;
4219 case 'T':
4220 if (qobject_type(client_arg) != QTYPE_QINT &&
4221 qobject_type(client_arg) != QTYPE_QFLOAT) {
4222 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4223 "number");
4224 return -1;
4225 }
4226 break;
4227 case 'b':
4228 case '-':
4229 if (qobject_type(client_arg) != QTYPE_QBOOL) {
4230 qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4231 "bool");
4232 return -1;
4233 }
4234 break;
4235 case 'O':
4236 assert(flags & QMP_ACCEPT_UNKNOWNS);
4237 break;
4238 case 'q':
4239 /* Any QObject can be passed. */
4240 break;
4241 case '/':
4242 case '.':
4243 /*
4244 * These types are not supported by QMP and thus are not
4245 * handled here. Fall through.
4246 */
4247 default:
4248 abort();
4249 }
4250 }
4251
4252 return 0;
4253 }
4254
4255 /*
4256 * - Check if the client has passed all mandatory args
4257 * - Set special flags for argument validation
4258 */
4259 static int check_mandatory_args(const QDict *cmd_args,
4260 const QDict *client_args, int *flags)
4261 {
4262 const QDictEntry *ent;
4263
4264 for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
4265 const char *cmd_arg_name = qdict_entry_key(ent);
4266 QString *type = qobject_to_qstring(qdict_entry_value(ent));
4267 assert(type != NULL);
4268
4269 if (qstring_get_str(type)[0] == 'O') {
4270 assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
4271 *flags |= QMP_ACCEPT_UNKNOWNS;
4272 } else if (qstring_get_str(type)[0] != '-' &&
4273 qstring_get_str(type)[1] != '?' &&
4274 !qdict_haskey(client_args, cmd_arg_name)) {
4275 qerror_report(QERR_MISSING_PARAMETER, cmd_arg_name);
4276 return -1;
4277 }
4278 }
4279
4280 return 0;
4281 }
4282
4283 static QDict *qdict_from_args_type(const char *args_type)
4284 {
4285 int i;
4286 QDict *qdict;
4287 QString *key, *type, *cur_qs;
4288
4289 assert(args_type != NULL);
4290
4291 qdict = qdict_new();
4292
4293 if (args_type == NULL || args_type[0] == '\0') {
4294 /* no args, empty qdict */
4295 goto out;
4296 }
4297
4298 key = qstring_new();
4299 type = qstring_new();
4300
4301 cur_qs = key;
4302
4303 for (i = 0;; i++) {
4304 switch (args_type[i]) {
4305 case ',':
4306 case '\0':
4307 qdict_put(qdict, qstring_get_str(key), type);
4308 QDECREF(key);
4309 if (args_type[i] == '\0') {
4310 goto out;
4311 }
4312 type = qstring_new(); /* qdict has ref */
4313 cur_qs = key = qstring_new();
4314 break;
4315 case ':':
4316 cur_qs = type;
4317 break;
4318 default:
4319 qstring_append_chr(cur_qs, args_type[i]);
4320 break;
4321 }
4322 }
4323
4324 out:
4325 return qdict;
4326 }
4327
4328 /*
4329 * Client argument checking rules:
4330 *
4331 * 1. Client must provide all mandatory arguments
4332 * 2. Each argument provided by the client must be expected
4333 * 3. Each argument provided by the client must have the type expected
4334 * by the command
4335 */
4336 static int qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args)
4337 {
4338 int flags, err;
4339 QDict *cmd_args;
4340
4341 cmd_args = qdict_from_args_type(cmd->args_type);
4342
4343 flags = 0;
4344 err = check_mandatory_args(cmd_args, client_args, &flags);
4345 if (err) {
4346 goto out;
4347 }
4348
4349 err = check_client_args_type(client_args, cmd_args, flags);
4350
4351 out:
4352 QDECREF(cmd_args);
4353 return err;
4354 }
4355
4356 /*
4357 * Input object checking rules
4358 *
4359 * 1. Input object must be a dict
4360 * 2. The "execute" key must exist
4361 * 3. The "execute" key must be a string
4362 * 4. If the "arguments" key exists, it must be a dict
4363 * 5. If the "id" key exists, it can be anything (ie. json-value)
4364 * 6. Any argument not listed above is considered invalid
4365 */
4366 static QDict *qmp_check_input_obj(QObject *input_obj)
4367 {
4368 const QDictEntry *ent;
4369 int has_exec_key = 0;
4370 QDict *input_dict;
4371
4372 if (qobject_type(input_obj) != QTYPE_QDICT) {
4373 qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "object");
4374 return NULL;
4375 }
4376
4377 input_dict = qobject_to_qdict(input_obj);
4378
4379 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
4380 const char *arg_name = qdict_entry_key(ent);
4381 const QObject *arg_obj = qdict_entry_value(ent);
4382
4383 if (!strcmp(arg_name, "execute")) {
4384 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
4385 qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "execute",
4386 "string");
4387 return NULL;
4388 }
4389 has_exec_key = 1;
4390 } else if (!strcmp(arg_name, "arguments")) {
4391 if (qobject_type(arg_obj) != QTYPE_QDICT) {
4392 qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "arguments",
4393 "object");
4394 return NULL;
4395 }
4396 } else if (!strcmp(arg_name, "id")) {
4397 /* FIXME: check duplicated IDs for async commands */
4398 } else {
4399 qerror_report(QERR_QMP_EXTRA_MEMBER, arg_name);
4400 return NULL;
4401 }
4402 }
4403
4404 if (!has_exec_key) {
4405 qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4406 return NULL;
4407 }
4408
4409 return input_dict;
4410 }
4411
4412 static void qmp_call_cmd(Monitor *mon, const mon_cmd_t *cmd,
4413 const QDict *params)
4414 {
4415 int ret;
4416 QObject *data = NULL;
4417
4418 ret = cmd->mhandler.cmd_new(mon, params, &data);
4419 handler_audit(mon, cmd, ret);
4420 monitor_protocol_emitter(mon, data);
4421 qobject_decref(data);
4422 }
4423
4424 static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
4425 {
4426 int err;
4427 QObject *obj;
4428 QDict *input, *args;
4429 const mon_cmd_t *cmd;
4430 const char *cmd_name;
4431 Monitor *mon = cur_mon;
4432
4433 args = input = NULL;
4434
4435 obj = json_parser_parse(tokens, NULL);
4436 if (!obj) {
4437 // FIXME: should be triggered in json_parser_parse()
4438 qerror_report(QERR_JSON_PARSING);
4439 goto err_out;
4440 }
4441
4442 input = qmp_check_input_obj(obj);
4443 if (!input) {
4444 qobject_decref(obj);
4445 goto err_out;
4446 }
4447
4448 mon->mc->id = qdict_get(input, "id");
4449 qobject_incref(mon->mc->id);
4450
4451 cmd_name = qdict_get_str(input, "execute");
4452 trace_handle_qmp_command(mon, cmd_name);
4453 if (invalid_qmp_mode(mon, cmd_name)) {
4454 qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
4455 goto err_out;
4456 }
4457
4458 cmd = qmp_find_cmd(cmd_name);
4459 if (!cmd) {
4460 qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
4461 goto err_out;
4462 }
4463
4464 obj = qdict_get(input, "arguments");
4465 if (!obj) {
4466 args = qdict_new();
4467 } else {
4468 args = qobject_to_qdict(obj);
4469 QINCREF(args);
4470 }
4471
4472 err = qmp_check_client_args(cmd, args);
4473 if (err < 0) {
4474 goto err_out;
4475 }
4476
4477 if (handler_is_async(cmd)) {
4478 err = qmp_async_cmd_handler(mon, cmd, args);
4479 if (err) {
4480 /* emit the error response */
4481 goto err_out;
4482 }
4483 } else {
4484 qmp_call_cmd(mon, cmd, args);
4485 }
4486
4487 goto out;
4488
4489 err_out:
4490 monitor_protocol_emitter(mon, NULL);
4491 out:
4492 QDECREF(input);
4493 QDECREF(args);
4494 }
4495
4496 /**
4497 * monitor_control_read(): Read and handle QMP input
4498 */
4499 static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
4500 {
4501 Monitor *old_mon = cur_mon;
4502
4503 cur_mon = opaque;
4504
4505 json_message_parser_feed(&cur_mon->mc->parser, (const char *) buf, size);
4506
4507 cur_mon = old_mon;
4508 }
4509
4510 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4511 {
4512 Monitor *old_mon = cur_mon;
4513 int i;
4514
4515 cur_mon = opaque;
4516
4517 if (cur_mon->rs) {
4518 for (i = 0; i < size; i++)
4519 readline_handle_byte(cur_mon->rs, buf[i]);
4520 } else {
4521 if (size == 0 || buf[size - 1] != 0)
4522 monitor_printf(cur_mon, "corrupted command\n");
4523 else
4524 handle_user_command(cur_mon, (char *)buf);
4525 }
4526
4527 cur_mon = old_mon;
4528 }
4529
4530 static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
4531 {
4532 monitor_suspend(mon);
4533 handle_user_command(mon, cmdline);
4534 monitor_resume(mon);
4535 }
4536
4537 int monitor_suspend(Monitor *mon)
4538 {
4539 if (!mon->rs)
4540 return -ENOTTY;
4541 mon->suspend_cnt++;
4542 return 0;
4543 }
4544
4545 void monitor_resume(Monitor *mon)
4546 {
4547 if (!mon->rs)
4548 return;
4549 if (--mon->suspend_cnt == 0)
4550 readline_show_prompt(mon->rs);
4551 }
4552
4553 static QObject *get_qmp_greeting(void)
4554 {
4555 QObject *ver = NULL;
4556
4557 qmp_marshal_input_query_version(NULL, NULL, &ver);
4558 return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
4559 }
4560
4561 /**
4562 * monitor_control_event(): Print QMP gretting
4563 */
4564 static void monitor_control_event(void *opaque, int event)
4565 {
4566 QObject *data;
4567 Monitor *mon = opaque;
4568
4569 switch (event) {
4570 case CHR_EVENT_OPENED:
4571 mon->mc->command_mode = 0;
4572 data = get_qmp_greeting();
4573 monitor_json_emitter(mon, data);
4574 qobject_decref(data);
4575 mon_refcount++;
4576 break;
4577 case CHR_EVENT_CLOSED:
4578 json_message_parser_destroy(&mon->mc->parser);
4579 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4580 mon_refcount--;
4581 monitor_fdsets_cleanup();
4582 break;
4583 }
4584 }
4585
4586 static void monitor_event(void *opaque, int event)
4587 {
4588 Monitor *mon = opaque;
4589
4590 switch (event) {
4591 case CHR_EVENT_MUX_IN:
4592 mon->mux_out = 0;
4593 if (mon->reset_seen) {
4594 readline_restart(mon->rs);
4595 monitor_resume(mon);
4596 monitor_flush(mon);
4597 } else {
4598 mon->suspend_cnt = 0;
4599 }
4600 break;
4601
4602 case CHR_EVENT_MUX_OUT:
4603 if (mon->reset_seen) {
4604 if (mon->suspend_cnt == 0) {
4605 monitor_printf(mon, "\n");
4606 }
4607 monitor_flush(mon);
4608 monitor_suspend(mon);
4609 } else {
4610 mon->suspend_cnt++;
4611 }
4612 mon->mux_out = 1;
4613 break;
4614
4615 case CHR_EVENT_OPENED:
4616 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4617 "information\n", QEMU_VERSION);
4618 if (!mon->mux_out) {
4619 readline_show_prompt(mon->rs);
4620 }
4621 mon->reset_seen = 1;
4622 mon_refcount++;
4623 break;
4624
4625 case CHR_EVENT_CLOSED:
4626 mon_refcount--;
4627 monitor_fdsets_cleanup();
4628 break;
4629 }
4630 }
4631
4632 static int
4633 compare_mon_cmd(const void *a, const void *b)
4634 {
4635 return strcmp(((const mon_cmd_t *)a)->name,
4636 ((const mon_cmd_t *)b)->name);
4637 }
4638
4639 static void sortcmdlist(void)
4640 {
4641 int array_num;
4642 int elem_size = sizeof(mon_cmd_t);
4643
4644 array_num = sizeof(mon_cmds)/elem_size-1;
4645 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4646
4647 array_num = sizeof(info_cmds)/elem_size-1;
4648 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4649 }
4650
4651
4652 /*
4653 * Local variables:
4654 * c-indent-level: 4
4655 * c-basic-offset: 4
4656 * tab-width: 8
4657 * End:
4658 */
4659
4660 void monitor_init(CharDriverState *chr, int flags)
4661 {
4662 static int is_first_init = 1;
4663 Monitor *mon;
4664
4665 if (is_first_init) {
4666 monitor_protocol_event_init();
4667 is_first_init = 0;
4668 }
4669
4670 mon = g_malloc0(sizeof(*mon));
4671
4672 mon->chr = chr;
4673 mon->flags = flags;
4674 if (flags & MONITOR_USE_READLINE) {
4675 mon->rs = readline_init(mon, monitor_find_completion);
4676 monitor_read_command(mon, 0);
4677 }
4678
4679 if (monitor_ctrl_mode(mon)) {
4680 mon->mc = g_malloc0(sizeof(MonitorControl));
4681 /* Control mode requires special handlers */
4682 qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
4683 monitor_control_event, mon);
4684 qemu_chr_fe_set_echo(chr, true);
4685
4686 json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4687 } else {
4688 qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4689 monitor_event, mon);
4690 }
4691
4692 QLIST_INSERT_HEAD(&mon_list, mon, entry);
4693 if (!default_mon || (flags & MONITOR_IS_DEFAULT))
4694 default_mon = mon;
4695
4696 sortcmdlist();
4697 }
4698
4699 static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
4700 {
4701 BlockDriverState *bs = opaque;
4702 int ret = 0;
4703
4704 if (bdrv_set_key(bs, password) != 0) {
4705 monitor_printf(mon, "invalid password\n");
4706 ret = -EPERM;
4707 }
4708 if (mon->password_completion_cb)
4709 mon->password_completion_cb(mon->password_opaque, ret);
4710
4711 monitor_read_command(mon, 1);
4712 }
4713
4714 ReadLineState *monitor_get_rs(Monitor *mon)
4715 {
4716 return mon->rs;
4717 }
4718
4719 int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4720 BlockDriverCompletionFunc *completion_cb,
4721 void *opaque)
4722 {
4723 int err;
4724
4725 if (!bdrv_key_required(bs)) {
4726 if (completion_cb)
4727 completion_cb(opaque, 0);
4728 return 0;
4729 }
4730
4731 if (monitor_ctrl_mode(mon)) {
4732 qerror_report(QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
4733 bdrv_get_encrypted_filename(bs));
4734 return -1;
4735 }
4736
4737 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4738 bdrv_get_encrypted_filename(bs));
4739
4740 mon->password_completion_cb = completion_cb;
4741 mon->password_opaque = opaque;
4742
4743 err = monitor_read_password(mon, bdrv_password_cb, bs);
4744
4745 if (err && completion_cb)
4746 completion_cb(opaque, err);
4747
4748 return err;
4749 }
4750
4751 int monitor_read_block_device_key(Monitor *mon, const char *device,
4752 BlockDriverCompletionFunc *completion_cb,
4753 void *opaque)
4754 {
4755 BlockDriverState *bs;
4756
4757 bs = bdrv_find(device);
4758 if (!bs) {
4759 monitor_printf(mon, "Device not found %s\n", device);
4760 return -1;
4761 }
4762
4763 return monitor_read_bdrv_key_start(mon, bs, completion_cb, opaque);
4764 }