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