]> git.proxmox.com Git - mirror_qemu.git/blob - monitor.c
qapi: add conditions to SPICE type/commands/events on the schema
[mirror_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
25 #include "qemu/osdep.h"
26 #include "qemu/units.h"
27 #include <dirent.h>
28 #include "cpu.h"
29 #include "hw/hw.h"
30 #include "monitor/qdev.h"
31 #include "hw/usb.h"
32 #include "hw/pci/pci.h"
33 #include "sysemu/watchdog.h"
34 #include "hw/loader.h"
35 #include "exec/gdbstub.h"
36 #include "net/net.h"
37 #include "net/slirp.h"
38 #include "chardev/char-fe.h"
39 #include "chardev/char-io.h"
40 #include "chardev/char-mux.h"
41 #include "ui/qemu-spice.h"
42 #include "sysemu/numa.h"
43 #include "monitor/monitor.h"
44 #include "qemu/config-file.h"
45 #include "qemu/readline.h"
46 #include "ui/console.h"
47 #include "ui/input.h"
48 #include "sysemu/block-backend.h"
49 #include "audio/audio.h"
50 #include "disas/disas.h"
51 #include "sysemu/balloon.h"
52 #include "qemu/timer.h"
53 #include "sysemu/hw_accel.h"
54 #include "qemu/acl.h"
55 #include "sysemu/tpm.h"
56 #include "qapi/qmp/qdict.h"
57 #include "qapi/qmp/qerror.h"
58 #include "qapi/qmp/qnum.h"
59 #include "qapi/qmp/qstring.h"
60 #include "qapi/qmp/qjson.h"
61 #include "qapi/qmp/json-streamer.h"
62 #include "qapi/qmp/json-parser.h"
63 #include "qapi/qmp/qlist.h"
64 #include "qom/object_interfaces.h"
65 #include "trace-root.h"
66 #include "trace/control.h"
67 #include "monitor/hmp-target.h"
68 #ifdef CONFIG_TRACE_SIMPLE
69 #include "trace/simple.h"
70 #endif
71 #include "exec/memory.h"
72 #include "exec/exec-all.h"
73 #include "qemu/log.h"
74 #include "qemu/option.h"
75 #include "hmp.h"
76 #include "qemu/thread.h"
77 #include "block/qapi.h"
78 #include "qapi/qapi-commands.h"
79 #include "qapi/qapi-events.h"
80 #include "qapi/error.h"
81 #include "qapi/qmp-event.h"
82 #include "qapi/qapi-introspect.h"
83 #include "sysemu/qtest.h"
84 #include "sysemu/cpus.h"
85 #include "sysemu/iothread.h"
86 #include "qemu/cutils.h"
87
88 #if defined(TARGET_S390X)
89 #include "hw/s390x/storage-keys.h"
90 #include "hw/s390x/storage-attributes.h"
91 #endif
92
93 /*
94 * Supported types:
95 *
96 * 'F' filename
97 * 'B' block device name
98 * 's' string (accept optional quote)
99 * 'S' it just appends the rest of the string (accept optional quote)
100 * 'O' option string of the form NAME=VALUE,...
101 * parsed according to QemuOptsList given by its name
102 * Example: 'device:O' uses qemu_device_opts.
103 * Restriction: only lists with empty desc are supported
104 * TODO lift the restriction
105 * 'i' 32 bit integer
106 * 'l' target long (32 or 64 bit)
107 * 'M' Non-negative target long (32 or 64 bit), in user mode the
108 * value is multiplied by 2^20 (think Mebibyte)
109 * 'o' octets (aka bytes)
110 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
111 * K, k suffix, which multiplies the value by 2^60 for suffixes E
112 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
113 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
114 * 'T' double
115 * user mode accepts an optional ms, us, ns suffix,
116 * which divides the value by 1e3, 1e6, 1e9, respectively
117 * '/' optional gdb-like print format (like "/10x")
118 *
119 * '?' optional type (for all types, except '/')
120 * '.' other form of optional type (for 'i' and 'l')
121 * 'b' boolean
122 * user mode accepts "on" or "off"
123 * '-' optional parameter (eg. '-f')
124 *
125 */
126
127 typedef struct mon_cmd_t {
128 const char *name;
129 const char *args_type;
130 const char *params;
131 const char *help;
132 const char *flags; /* p=preconfig */
133 void (*cmd)(Monitor *mon, const QDict *qdict);
134 /* @sub_table is a list of 2nd level of commands. If it does not exist,
135 * cmd should be used. If it exists, sub_table[?].cmd should be
136 * used, and cmd of 1st level plays the role of help function.
137 */
138 struct mon_cmd_t *sub_table;
139 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
140 } mon_cmd_t;
141
142 /* file descriptors passed via SCM_RIGHTS */
143 typedef struct mon_fd_t mon_fd_t;
144 struct mon_fd_t {
145 char *name;
146 int fd;
147 QLIST_ENTRY(mon_fd_t) next;
148 };
149
150 /* file descriptor associated with a file descriptor set */
151 typedef struct MonFdsetFd MonFdsetFd;
152 struct MonFdsetFd {
153 int fd;
154 bool removed;
155 char *opaque;
156 QLIST_ENTRY(MonFdsetFd) next;
157 };
158
159 /* file descriptor set containing fds passed via SCM_RIGHTS */
160 typedef struct MonFdset MonFdset;
161 struct MonFdset {
162 int64_t id;
163 QLIST_HEAD(, MonFdsetFd) fds;
164 QLIST_HEAD(, MonFdsetFd) dup_fds;
165 QLIST_ENTRY(MonFdset) next;
166 };
167
168 typedef struct {
169 JSONMessageParser parser;
170 /*
171 * When a client connects, we're in capabilities negotiation mode.
172 * When command qmp_capabilities succeeds, we go into command
173 * mode.
174 */
175 QmpCommandList *commands;
176 bool qmp_caps[QMP_CAPABILITY__MAX];
177 /*
178 * Protects qmp request/response queue. Please take monitor_lock
179 * first when used together.
180 */
181 QemuMutex qmp_queue_lock;
182 /* Input queue that holds all the parsed QMP requests */
183 GQueue *qmp_requests;
184 /* Output queue contains all the QMP responses in order */
185 GQueue *qmp_responses;
186 } MonitorQMP;
187
188 /*
189 * To prevent flooding clients, events can be throttled. The
190 * throttling is calculated globally, rather than per-Monitor
191 * instance.
192 */
193 typedef struct MonitorQAPIEventState {
194 QAPIEvent event; /* Throttling state for this event type and... */
195 QDict *data; /* ... data, see qapi_event_throttle_equal() */
196 QEMUTimer *timer; /* Timer for handling delayed events */
197 QDict *qdict; /* Delayed event (if any) */
198 } MonitorQAPIEventState;
199
200 typedef struct {
201 int64_t rate; /* Minimum time (in ns) between two events */
202 } MonitorQAPIEventConf;
203
204 struct Monitor {
205 CharBackend chr;
206 int reset_seen;
207 int flags;
208 int suspend_cnt; /* Needs to be accessed atomically */
209 bool skip_flush;
210 bool use_io_thr;
211
212 /*
213 * State used only in the thread "owning" the monitor.
214 * If @use_io_thr, this is mon_global.mon_iothread.
215 * Else, it's the main thread.
216 * These members can be safely accessed without locks.
217 */
218 ReadLineState *rs;
219
220 MonitorQMP qmp;
221 gchar *mon_cpu_path;
222 BlockCompletionFunc *password_completion_cb;
223 void *password_opaque;
224 mon_cmd_t *cmd_table;
225 QTAILQ_ENTRY(Monitor) entry;
226
227 /*
228 * The per-monitor lock. We can't access guest memory when holding
229 * the lock.
230 */
231 QemuMutex mon_lock;
232
233 /*
234 * Fields that are protected by the per-monitor lock.
235 */
236 QLIST_HEAD(, mon_fd_t) fds;
237 QString *outbuf;
238 guint out_watch;
239 /* Read under either BQL or mon_lock, written with BQL+mon_lock. */
240 int mux_out;
241 };
242
243 /* Let's add monitor global variables to this struct. */
244 static struct {
245 IOThread *mon_iothread;
246 /* Bottom half to dispatch the requests received from IO thread */
247 QEMUBH *qmp_dispatcher_bh;
248 /* Bottom half to deliver the responses back to clients */
249 QEMUBH *qmp_respond_bh;
250 } mon_global;
251
252 struct QMPRequest {
253 /* Owner of the request */
254 Monitor *mon;
255 /* "id" field of the request */
256 QObject *id;
257 /* Request object to be handled */
258 QObject *req;
259 /*
260 * Whether we need to resume the monitor afterward. This flag is
261 * used to emulate the old QMP server behavior that the current
262 * command must be completed before execution of the next one.
263 */
264 bool need_resume;
265 };
266 typedef struct QMPRequest QMPRequest;
267
268 /* QMP checker flags */
269 #define QMP_ACCEPT_UNKNOWNS 1
270
271 /* Protects mon_list, monitor_qapi_event_state. */
272 static QemuMutex monitor_lock;
273 static GHashTable *monitor_qapi_event_state;
274 static QTAILQ_HEAD(mon_list, Monitor) mon_list;
275
276 /* Protects mon_fdsets */
277 static QemuMutex mon_fdsets_lock;
278 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
279
280 static int mon_refcount;
281
282 static mon_cmd_t mon_cmds[];
283 static mon_cmd_t info_cmds[];
284
285 QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
286
287 Monitor *cur_mon;
288
289 static void monitor_command_cb(void *opaque, const char *cmdline,
290 void *readline_opaque);
291
292 /**
293 * Is @mon a QMP monitor?
294 */
295 static inline bool monitor_is_qmp(const Monitor *mon)
296 {
297 return (mon->flags & MONITOR_USE_CONTROL);
298 }
299
300 /**
301 * Whether @mon is using readline? Note: not all HMP monitors use
302 * readline, e.g., gdbserver has a non-interactive HMP monitor, so
303 * readline is not used there.
304 */
305 static inline bool monitor_uses_readline(const Monitor *mon)
306 {
307 return mon->flags & MONITOR_USE_READLINE;
308 }
309
310 static inline bool monitor_is_hmp_non_interactive(const Monitor *mon)
311 {
312 return !monitor_is_qmp(mon) && !monitor_uses_readline(mon);
313 }
314
315 /*
316 * Return the clock to use for recording an event's time.
317 * Beware: result is invalid before configure_accelerator().
318 */
319 static inline QEMUClockType monitor_get_event_clock(void)
320 {
321 /*
322 * This allows us to perform tests on the monitor queues to verify
323 * that the rate limits are enforced.
324 */
325 return qtest_enabled() ? QEMU_CLOCK_VIRTUAL : QEMU_CLOCK_REALTIME;
326 }
327
328 /**
329 * Is the current monitor, if any, a QMP monitor?
330 */
331 bool monitor_cur_is_qmp(void)
332 {
333 return cur_mon && monitor_is_qmp(cur_mon);
334 }
335
336 void monitor_read_command(Monitor *mon, int show_prompt)
337 {
338 if (!mon->rs)
339 return;
340
341 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
342 if (show_prompt)
343 readline_show_prompt(mon->rs);
344 }
345
346 int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
347 void *opaque)
348 {
349 if (mon->rs) {
350 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
351 /* prompt is printed on return from the command handler */
352 return 0;
353 } else {
354 monitor_printf(mon, "terminal does not support password prompting\n");
355 return -ENOTTY;
356 }
357 }
358
359 static void qmp_request_free(QMPRequest *req)
360 {
361 qobject_unref(req->id);
362 qobject_unref(req->req);
363 g_free(req);
364 }
365
366 /* Must with the mon->qmp.qmp_queue_lock held */
367 static void monitor_qmp_cleanup_req_queue_locked(Monitor *mon)
368 {
369 while (!g_queue_is_empty(mon->qmp.qmp_requests)) {
370 qmp_request_free(g_queue_pop_head(mon->qmp.qmp_requests));
371 }
372 }
373
374 /* Must with the mon->qmp.qmp_queue_lock held */
375 static void monitor_qmp_cleanup_resp_queue_locked(Monitor *mon)
376 {
377 while (!g_queue_is_empty(mon->qmp.qmp_responses)) {
378 qobject_unref((QObject *)g_queue_pop_head(mon->qmp.qmp_responses));
379 }
380 }
381
382 static void monitor_qmp_cleanup_queues(Monitor *mon)
383 {
384 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
385 monitor_qmp_cleanup_req_queue_locked(mon);
386 monitor_qmp_cleanup_resp_queue_locked(mon);
387 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
388 }
389
390
391 static void monitor_flush_locked(Monitor *mon);
392
393 static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
394 void *opaque)
395 {
396 Monitor *mon = opaque;
397
398 qemu_mutex_lock(&mon->mon_lock);
399 mon->out_watch = 0;
400 monitor_flush_locked(mon);
401 qemu_mutex_unlock(&mon->mon_lock);
402 return FALSE;
403 }
404
405 /* Called with mon->mon_lock held. */
406 static void monitor_flush_locked(Monitor *mon)
407 {
408 int rc;
409 size_t len;
410 const char *buf;
411
412 if (mon->skip_flush) {
413 return;
414 }
415
416 buf = qstring_get_str(mon->outbuf);
417 len = qstring_get_length(mon->outbuf);
418
419 if (len && !mon->mux_out) {
420 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
421 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
422 /* all flushed or error */
423 qobject_unref(mon->outbuf);
424 mon->outbuf = qstring_new();
425 return;
426 }
427 if (rc > 0) {
428 /* partial write */
429 QString *tmp = qstring_from_str(buf + rc);
430 qobject_unref(mon->outbuf);
431 mon->outbuf = tmp;
432 }
433 if (mon->out_watch == 0) {
434 mon->out_watch =
435 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
436 monitor_unblocked, mon);
437 }
438 }
439 }
440
441 void monitor_flush(Monitor *mon)
442 {
443 qemu_mutex_lock(&mon->mon_lock);
444 monitor_flush_locked(mon);
445 qemu_mutex_unlock(&mon->mon_lock);
446 }
447
448 /* flush at every end of line */
449 static void monitor_puts(Monitor *mon, const char *str)
450 {
451 char c;
452
453 qemu_mutex_lock(&mon->mon_lock);
454 for(;;) {
455 c = *str++;
456 if (c == '\0')
457 break;
458 if (c == '\n') {
459 qstring_append_chr(mon->outbuf, '\r');
460 }
461 qstring_append_chr(mon->outbuf, c);
462 if (c == '\n') {
463 monitor_flush_locked(mon);
464 }
465 }
466 qemu_mutex_unlock(&mon->mon_lock);
467 }
468
469 void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
470 {
471 char *buf;
472
473 if (!mon)
474 return;
475
476 if (monitor_is_qmp(mon)) {
477 return;
478 }
479
480 buf = g_strdup_vprintf(fmt, ap);
481 monitor_puts(mon, buf);
482 g_free(buf);
483 }
484
485 void monitor_printf(Monitor *mon, const char *fmt, ...)
486 {
487 va_list ap;
488 va_start(ap, fmt);
489 monitor_vprintf(mon, fmt, ap);
490 va_end(ap);
491 }
492
493 int monitor_fprintf(FILE *stream, const char *fmt, ...)
494 {
495 va_list ap;
496 va_start(ap, fmt);
497 monitor_vprintf((Monitor *)stream, fmt, ap);
498 va_end(ap);
499 return 0;
500 }
501
502 static void monitor_json_emitter_raw(Monitor *mon,
503 QObject *data)
504 {
505 QString *json;
506
507 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
508 qobject_to_json(data);
509 assert(json != NULL);
510
511 qstring_append_chr(json, '\n');
512 monitor_puts(mon, qstring_get_str(json));
513
514 qobject_unref(json);
515 }
516
517 static void monitor_json_emitter(Monitor *mon, QObject *data)
518 {
519 if (mon->use_io_thr) {
520 /*
521 * If using IO thread, we need to queue the item so that IO
522 * thread will do the rest for us. Take refcount so that
523 * caller won't free the data (which will be finally freed in
524 * responder thread).
525 */
526 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
527 g_queue_push_tail(mon->qmp.qmp_responses, qobject_ref(data));
528 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
529 qemu_bh_schedule(mon_global.qmp_respond_bh);
530 } else {
531 /*
532 * If not using monitor IO thread, then we are in main thread.
533 * Do the emission right away.
534 */
535 monitor_json_emitter_raw(mon, data);
536 }
537 }
538
539 struct QMPResponse {
540 Monitor *mon;
541 QObject *data;
542 };
543 typedef struct QMPResponse QMPResponse;
544
545 static QObject *monitor_qmp_response_pop_one(Monitor *mon)
546 {
547 QObject *data;
548
549 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
550 data = g_queue_pop_head(mon->qmp.qmp_responses);
551 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
552
553 return data;
554 }
555
556 static void monitor_qmp_response_flush(Monitor *mon)
557 {
558 QObject *data;
559
560 while ((data = monitor_qmp_response_pop_one(mon))) {
561 monitor_json_emitter_raw(mon, data);
562 qobject_unref(data);
563 }
564 }
565
566 /*
567 * Pop a QMPResponse from any monitor's response queue into @response.
568 * Return false if all the queues are empty; else true.
569 */
570 static bool monitor_qmp_response_pop_any(QMPResponse *response)
571 {
572 Monitor *mon;
573 QObject *data = NULL;
574
575 qemu_mutex_lock(&monitor_lock);
576 QTAILQ_FOREACH(mon, &mon_list, entry) {
577 data = monitor_qmp_response_pop_one(mon);
578 if (data) {
579 response->mon = mon;
580 response->data = data;
581 break;
582 }
583 }
584 qemu_mutex_unlock(&monitor_lock);
585 return data != NULL;
586 }
587
588 static void monitor_qmp_bh_responder(void *opaque)
589 {
590 QMPResponse response;
591
592 while (monitor_qmp_response_pop_any(&response)) {
593 monitor_json_emitter_raw(response.mon, response.data);
594 qobject_unref(response.data);
595 }
596 }
597
598 static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
599 /* Limit guest-triggerable events to 1 per second */
600 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
601 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
602 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
603 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
604 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
605 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
606 };
607
608 /*
609 * Emits the event to every monitor instance, @event is only used for trace
610 * Called with monitor_lock held.
611 */
612 static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
613 {
614 Monitor *mon;
615
616 trace_monitor_protocol_event_emit(event, qdict);
617 QTAILQ_FOREACH(mon, &mon_list, entry) {
618 if (monitor_is_qmp(mon)
619 && mon->qmp.commands != &qmp_cap_negotiation_commands) {
620 monitor_json_emitter(mon, QOBJECT(qdict));
621 }
622 }
623 }
624
625 static void monitor_qapi_event_handler(void *opaque);
626
627 /*
628 * Queue a new event for emission to Monitor instances,
629 * applying any rate limiting if required.
630 */
631 static void
632 monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
633 {
634 MonitorQAPIEventConf *evconf;
635 MonitorQAPIEventState *evstate;
636
637 assert(event < QAPI_EVENT__MAX);
638 evconf = &monitor_qapi_event_conf[event];
639 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
640
641 qemu_mutex_lock(&monitor_lock);
642
643 if (!evconf->rate) {
644 /* Unthrottled event */
645 monitor_qapi_event_emit(event, qdict);
646 } else {
647 QDict *data = qobject_to(QDict, qdict_get(qdict, "data"));
648 MonitorQAPIEventState key = { .event = event, .data = data };
649
650 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
651 assert(!evstate || timer_pending(evstate->timer));
652
653 if (evstate) {
654 /*
655 * Timer is pending for (at least) evconf->rate ns after
656 * last send. Store event for sending when timer fires,
657 * replacing a prior stored event if any.
658 */
659 qobject_unref(evstate->qdict);
660 evstate->qdict = qobject_ref(qdict);
661 } else {
662 /*
663 * Last send was (at least) evconf->rate ns ago.
664 * Send immediately, and arm the timer to call
665 * monitor_qapi_event_handler() in evconf->rate ns. Any
666 * events arriving before then will be delayed until then.
667 */
668 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
669
670 monitor_qapi_event_emit(event, qdict);
671
672 evstate = g_new(MonitorQAPIEventState, 1);
673 evstate->event = event;
674 evstate->data = qobject_ref(data);
675 evstate->qdict = NULL;
676 evstate->timer = timer_new_ns(monitor_get_event_clock(),
677 monitor_qapi_event_handler,
678 evstate);
679 g_hash_table_add(monitor_qapi_event_state, evstate);
680 timer_mod_ns(evstate->timer, now + evconf->rate);
681 }
682 }
683
684 qemu_mutex_unlock(&monitor_lock);
685 }
686
687 /*
688 * This function runs evconf->rate ns after sending a throttled
689 * event.
690 * If another event has since been stored, send it.
691 */
692 static void monitor_qapi_event_handler(void *opaque)
693 {
694 MonitorQAPIEventState *evstate = opaque;
695 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
696
697 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
698 qemu_mutex_lock(&monitor_lock);
699
700 if (evstate->qdict) {
701 int64_t now = qemu_clock_get_ns(monitor_get_event_clock());
702
703 monitor_qapi_event_emit(evstate->event, evstate->qdict);
704 qobject_unref(evstate->qdict);
705 evstate->qdict = NULL;
706 timer_mod_ns(evstate->timer, now + evconf->rate);
707 } else {
708 g_hash_table_remove(monitor_qapi_event_state, evstate);
709 qobject_unref(evstate->data);
710 timer_free(evstate->timer);
711 g_free(evstate);
712 }
713
714 qemu_mutex_unlock(&monitor_lock);
715 }
716
717 static unsigned int qapi_event_throttle_hash(const void *key)
718 {
719 const MonitorQAPIEventState *evstate = key;
720 unsigned int hash = evstate->event * 255;
721
722 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
723 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
724 }
725
726 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
727 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
728 }
729
730 return hash;
731 }
732
733 static gboolean qapi_event_throttle_equal(const void *a, const void *b)
734 {
735 const MonitorQAPIEventState *eva = a;
736 const MonitorQAPIEventState *evb = b;
737
738 if (eva->event != evb->event) {
739 return FALSE;
740 }
741
742 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
743 return !strcmp(qdict_get_str(eva->data, "id"),
744 qdict_get_str(evb->data, "id"));
745 }
746
747 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
748 return !strcmp(qdict_get_str(eva->data, "node-name"),
749 qdict_get_str(evb->data, "node-name"));
750 }
751
752 return TRUE;
753 }
754
755 static void monitor_qapi_event_init(void)
756 {
757 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
758 qapi_event_throttle_equal);
759 qmp_event_set_func_emit(monitor_qapi_event_queue);
760 }
761
762 static void handle_hmp_command(Monitor *mon, const char *cmdline);
763
764 static void monitor_data_init(Monitor *mon, bool skip_flush,
765 bool use_io_thr)
766 {
767 memset(mon, 0, sizeof(Monitor));
768 qemu_mutex_init(&mon->mon_lock);
769 qemu_mutex_init(&mon->qmp.qmp_queue_lock);
770 mon->outbuf = qstring_new();
771 /* Use *mon_cmds by default. */
772 mon->cmd_table = mon_cmds;
773 mon->skip_flush = skip_flush;
774 mon->use_io_thr = use_io_thr;
775 mon->qmp.qmp_requests = g_queue_new();
776 mon->qmp.qmp_responses = g_queue_new();
777 }
778
779 static void monitor_data_destroy(Monitor *mon)
780 {
781 g_free(mon->mon_cpu_path);
782 qemu_chr_fe_deinit(&mon->chr, false);
783 if (monitor_is_qmp(mon)) {
784 json_message_parser_destroy(&mon->qmp.parser);
785 }
786 readline_free(mon->rs);
787 qobject_unref(mon->outbuf);
788 qemu_mutex_destroy(&mon->mon_lock);
789 qemu_mutex_destroy(&mon->qmp.qmp_queue_lock);
790 monitor_qmp_cleanup_req_queue_locked(mon);
791 monitor_qmp_cleanup_resp_queue_locked(mon);
792 g_queue_free(mon->qmp.qmp_requests);
793 g_queue_free(mon->qmp.qmp_responses);
794 }
795
796 char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
797 int64_t cpu_index, Error **errp)
798 {
799 char *output = NULL;
800 Monitor *old_mon, hmp;
801
802 monitor_data_init(&hmp, true, false);
803
804 old_mon = cur_mon;
805 cur_mon = &hmp;
806
807 if (has_cpu_index) {
808 int ret = monitor_set_cpu(cpu_index);
809 if (ret < 0) {
810 cur_mon = old_mon;
811 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
812 "a CPU number");
813 goto out;
814 }
815 }
816
817 handle_hmp_command(&hmp, command_line);
818 cur_mon = old_mon;
819
820 qemu_mutex_lock(&hmp.mon_lock);
821 if (qstring_get_length(hmp.outbuf) > 0) {
822 output = g_strdup(qstring_get_str(hmp.outbuf));
823 } else {
824 output = g_strdup("");
825 }
826 qemu_mutex_unlock(&hmp.mon_lock);
827
828 out:
829 monitor_data_destroy(&hmp);
830 return output;
831 }
832
833 static int compare_cmd(const char *name, const char *list)
834 {
835 const char *p, *pstart;
836 int len;
837 len = strlen(name);
838 p = list;
839 for(;;) {
840 pstart = p;
841 p = qemu_strchrnul(p, '|');
842 if ((p - pstart) == len && !memcmp(pstart, name, len))
843 return 1;
844 if (*p == '\0')
845 break;
846 p++;
847 }
848 return 0;
849 }
850
851 static int get_str(char *buf, int buf_size, const char **pp)
852 {
853 const char *p;
854 char *q;
855 int c;
856
857 q = buf;
858 p = *pp;
859 while (qemu_isspace(*p)) {
860 p++;
861 }
862 if (*p == '\0') {
863 fail:
864 *q = '\0';
865 *pp = p;
866 return -1;
867 }
868 if (*p == '\"') {
869 p++;
870 while (*p != '\0' && *p != '\"') {
871 if (*p == '\\') {
872 p++;
873 c = *p++;
874 switch (c) {
875 case 'n':
876 c = '\n';
877 break;
878 case 'r':
879 c = '\r';
880 break;
881 case '\\':
882 case '\'':
883 case '\"':
884 break;
885 default:
886 printf("unsupported escape code: '\\%c'\n", c);
887 goto fail;
888 }
889 if ((q - buf) < buf_size - 1) {
890 *q++ = c;
891 }
892 } else {
893 if ((q - buf) < buf_size - 1) {
894 *q++ = *p;
895 }
896 p++;
897 }
898 }
899 if (*p != '\"') {
900 printf("unterminated string\n");
901 goto fail;
902 }
903 p++;
904 } else {
905 while (*p != '\0' && !qemu_isspace(*p)) {
906 if ((q - buf) < buf_size - 1) {
907 *q++ = *p;
908 }
909 p++;
910 }
911 }
912 *q = '\0';
913 *pp = p;
914 return 0;
915 }
916
917 #define MAX_ARGS 16
918
919 static void free_cmdline_args(char **args, int nb_args)
920 {
921 int i;
922
923 assert(nb_args <= MAX_ARGS);
924
925 for (i = 0; i < nb_args; i++) {
926 g_free(args[i]);
927 }
928
929 }
930
931 /*
932 * Parse the command line to get valid args.
933 * @cmdline: command line to be parsed.
934 * @pnb_args: location to store the number of args, must NOT be NULL.
935 * @args: location to store the args, which should be freed by caller, must
936 * NOT be NULL.
937 *
938 * Returns 0 on success, negative on failure.
939 *
940 * NOTE: this parser is an approximate form of the real command parser. Number
941 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
942 * return with failure.
943 */
944 static int parse_cmdline(const char *cmdline,
945 int *pnb_args, char **args)
946 {
947 const char *p;
948 int nb_args, ret;
949 char buf[1024];
950
951 p = cmdline;
952 nb_args = 0;
953 for (;;) {
954 while (qemu_isspace(*p)) {
955 p++;
956 }
957 if (*p == '\0') {
958 break;
959 }
960 if (nb_args >= MAX_ARGS) {
961 goto fail;
962 }
963 ret = get_str(buf, sizeof(buf), &p);
964 if (ret < 0) {
965 goto fail;
966 }
967 args[nb_args] = g_strdup(buf);
968 nb_args++;
969 }
970 *pnb_args = nb_args;
971 return 0;
972
973 fail:
974 free_cmdline_args(args, nb_args);
975 return -1;
976 }
977
978 /*
979 * Returns true if the command can be executed in preconfig mode
980 * i.e. it has the 'p' flag.
981 */
982 static bool cmd_can_preconfig(const mon_cmd_t *cmd)
983 {
984 if (!cmd->flags) {
985 return false;
986 }
987
988 return strchr(cmd->flags, 'p');
989 }
990
991 static void help_cmd_dump_one(Monitor *mon,
992 const mon_cmd_t *cmd,
993 char **prefix_args,
994 int prefix_args_nb)
995 {
996 int i;
997
998 if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
999 return;
1000 }
1001
1002 for (i = 0; i < prefix_args_nb; i++) {
1003 monitor_printf(mon, "%s ", prefix_args[i]);
1004 }
1005 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
1006 }
1007
1008 /* @args[@arg_index] is the valid command need to find in @cmds */
1009 static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
1010 char **args, int nb_args, int arg_index)
1011 {
1012 const mon_cmd_t *cmd;
1013
1014 /* No valid arg need to compare with, dump all in *cmds */
1015 if (arg_index >= nb_args) {
1016 for (cmd = cmds; cmd->name != NULL; cmd++) {
1017 help_cmd_dump_one(mon, cmd, args, arg_index);
1018 }
1019 return;
1020 }
1021
1022 /* Find one entry to dump */
1023 for (cmd = cmds; cmd->name != NULL; cmd++) {
1024 if (compare_cmd(args[arg_index], cmd->name) &&
1025 ((!runstate_check(RUN_STATE_PRECONFIG) ||
1026 cmd_can_preconfig(cmd)))) {
1027 if (cmd->sub_table) {
1028 /* continue with next arg */
1029 help_cmd_dump(mon, cmd->sub_table,
1030 args, nb_args, arg_index + 1);
1031 } else {
1032 help_cmd_dump_one(mon, cmd, args, arg_index);
1033 }
1034 break;
1035 }
1036 }
1037 }
1038
1039 static void help_cmd(Monitor *mon, const char *name)
1040 {
1041 char *args[MAX_ARGS];
1042 int nb_args = 0;
1043
1044 /* 1. parse user input */
1045 if (name) {
1046 /* special case for log, directly dump and return */
1047 if (!strcmp(name, "log")) {
1048 const QEMULogItem *item;
1049 monitor_printf(mon, "Log items (comma separated):\n");
1050 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
1051 for (item = qemu_log_items; item->mask != 0; item++) {
1052 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
1053 }
1054 return;
1055 }
1056
1057 if (parse_cmdline(name, &nb_args, args) < 0) {
1058 return;
1059 }
1060 }
1061
1062 /* 2. dump the contents according to parsed args */
1063 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
1064
1065 free_cmdline_args(args, nb_args);
1066 }
1067
1068 static void do_help_cmd(Monitor *mon, const QDict *qdict)
1069 {
1070 help_cmd(mon, qdict_get_try_str(qdict, "name"));
1071 }
1072
1073 static void hmp_trace_event(Monitor *mon, const QDict *qdict)
1074 {
1075 const char *tp_name = qdict_get_str(qdict, "name");
1076 bool new_state = qdict_get_bool(qdict, "option");
1077 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1078 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1079 Error *local_err = NULL;
1080
1081 if (vcpu < 0) {
1082 monitor_printf(mon, "argument vcpu must be positive");
1083 return;
1084 }
1085
1086 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
1087 if (local_err) {
1088 error_report_err(local_err);
1089 }
1090 }
1091
1092 #ifdef CONFIG_TRACE_SIMPLE
1093 static void hmp_trace_file(Monitor *mon, const QDict *qdict)
1094 {
1095 const char *op = qdict_get_try_str(qdict, "op");
1096 const char *arg = qdict_get_try_str(qdict, "arg");
1097
1098 if (!op) {
1099 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
1100 } else if (!strcmp(op, "on")) {
1101 st_set_trace_file_enabled(true);
1102 } else if (!strcmp(op, "off")) {
1103 st_set_trace_file_enabled(false);
1104 } else if (!strcmp(op, "flush")) {
1105 st_flush_trace_buffer();
1106 } else if (!strcmp(op, "set")) {
1107 if (arg) {
1108 st_set_trace_file(arg);
1109 }
1110 } else {
1111 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
1112 help_cmd(mon, "trace-file");
1113 }
1114 }
1115 #endif
1116
1117 static void hmp_info_help(Monitor *mon, const QDict *qdict)
1118 {
1119 help_cmd(mon, "info");
1120 }
1121
1122 static void query_commands_cb(QmpCommand *cmd, void *opaque)
1123 {
1124 CommandInfoList *info, **list = opaque;
1125
1126 if (!cmd->enabled) {
1127 return;
1128 }
1129
1130 info = g_malloc0(sizeof(*info));
1131 info->value = g_malloc0(sizeof(*info->value));
1132 info->value->name = g_strdup(cmd->name);
1133 info->next = *list;
1134 *list = info;
1135 }
1136
1137 CommandInfoList *qmp_query_commands(Error **errp)
1138 {
1139 CommandInfoList *list = NULL;
1140
1141 qmp_for_each_command(cur_mon->qmp.commands, query_commands_cb, &list);
1142
1143 return list;
1144 }
1145
1146 EventInfoList *qmp_query_events(Error **errp)
1147 {
1148 EventInfoList *info, *ev_list = NULL;
1149 QAPIEvent e;
1150
1151 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
1152 const char *event_name = QAPIEvent_str(e);
1153 assert(event_name != NULL);
1154 info = g_malloc0(sizeof(*info));
1155 info->value = g_malloc0(sizeof(*info->value));
1156 info->value->name = g_strdup(event_name);
1157
1158 info->next = ev_list;
1159 ev_list = info;
1160 }
1161
1162 return ev_list;
1163 }
1164
1165 /*
1166 * Minor hack: generated marshalling suppressed for this command
1167 * ('gen': false in the schema) so we can parse the JSON string
1168 * directly into QObject instead of first parsing it with
1169 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
1170 * to QObject with generated output marshallers, every time. Instead,
1171 * we do it in test-qobject-input-visitor.c, just to make sure
1172 * qapi-gen.py's output actually conforms to the schema.
1173 */
1174 static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
1175 Error **errp)
1176 {
1177 *ret_data = qobject_from_qlit(&qmp_schema_qlit);
1178 }
1179
1180 /*
1181 * We used to define commands in qmp-commands.hx in addition to the
1182 * QAPI schema. This permitted defining some of them only in certain
1183 * configurations. query-commands has always reflected that (good,
1184 * because it lets QMP clients figure out what's actually available),
1185 * while query-qmp-schema never did (not so good). This function is a
1186 * hack to keep the configuration-specific commands defined exactly as
1187 * before, even though qmp-commands.hx is gone.
1188 *
1189 * FIXME Educate the QAPI schema on configuration-specific commands,
1190 * and drop this hack.
1191 */
1192 static void qmp_unregister_commands_hack(void)
1193 {
1194 #ifndef CONFIG_REPLICATION
1195 qmp_unregister_command(&qmp_commands, "xen-set-replication");
1196 qmp_unregister_command(&qmp_commands, "query-xen-replication-status");
1197 qmp_unregister_command(&qmp_commands, "xen-colo-do-checkpoint");
1198 #endif
1199 #ifndef TARGET_I386
1200 qmp_unregister_command(&qmp_commands, "rtc-reset-reinjection");
1201 qmp_unregister_command(&qmp_commands, "query-sev");
1202 qmp_unregister_command(&qmp_commands, "query-sev-launch-measure");
1203 qmp_unregister_command(&qmp_commands, "query-sev-capabilities");
1204 #endif
1205 #ifndef TARGET_S390X
1206 qmp_unregister_command(&qmp_commands, "dump-skeys");
1207 #endif
1208 #ifndef TARGET_ARM
1209 qmp_unregister_command(&qmp_commands, "query-gic-capabilities");
1210 #endif
1211 #if !defined(TARGET_S390X) && !defined(TARGET_I386)
1212 qmp_unregister_command(&qmp_commands, "query-cpu-model-expansion");
1213 #endif
1214 #if !defined(TARGET_S390X)
1215 qmp_unregister_command(&qmp_commands, "query-cpu-model-baseline");
1216 qmp_unregister_command(&qmp_commands, "query-cpu-model-comparison");
1217 #endif
1218 #if !defined(TARGET_PPC) && !defined(TARGET_ARM) && !defined(TARGET_I386) \
1219 && !defined(TARGET_S390X)
1220 qmp_unregister_command(&qmp_commands, "query-cpu-definitions");
1221 #endif
1222 }
1223
1224 static void monitor_init_qmp_commands(void)
1225 {
1226 /*
1227 * Two command lists:
1228 * - qmp_commands contains all QMP commands
1229 * - qmp_cap_negotiation_commands contains just
1230 * "qmp_capabilities", to enforce capability negotiation
1231 */
1232
1233 qmp_init_marshal(&qmp_commands);
1234
1235 qmp_register_command(&qmp_commands, "query-qmp-schema",
1236 qmp_query_qmp_schema, QCO_ALLOW_PRECONFIG);
1237 qmp_register_command(&qmp_commands, "device_add", qmp_device_add,
1238 QCO_NO_OPTIONS);
1239 qmp_register_command(&qmp_commands, "netdev_add", qmp_netdev_add,
1240 QCO_NO_OPTIONS);
1241
1242 qmp_unregister_commands_hack();
1243
1244 QTAILQ_INIT(&qmp_cap_negotiation_commands);
1245 qmp_register_command(&qmp_cap_negotiation_commands, "qmp_capabilities",
1246 qmp_marshal_qmp_capabilities, QCO_ALLOW_PRECONFIG);
1247 }
1248
1249 static bool qmp_cap_enabled(Monitor *mon, QMPCapability cap)
1250 {
1251 return mon->qmp.qmp_caps[cap];
1252 }
1253
1254 static bool qmp_oob_enabled(Monitor *mon)
1255 {
1256 return qmp_cap_enabled(mon, QMP_CAPABILITY_OOB);
1257 }
1258
1259 static void qmp_caps_check(Monitor *mon, QMPCapabilityList *list,
1260 Error **errp)
1261 {
1262 for (; list; list = list->next) {
1263 assert(list->value < QMP_CAPABILITY__MAX);
1264 switch (list->value) {
1265 case QMP_CAPABILITY_OOB:
1266 if (!mon->use_io_thr) {
1267 /*
1268 * Out-Of-Band only works with monitors that are
1269 * running on dedicated IOThread.
1270 */
1271 error_setg(errp, "This monitor does not support "
1272 "Out-Of-Band (OOB)");
1273 return;
1274 }
1275 break;
1276 default:
1277 break;
1278 }
1279 }
1280 }
1281
1282 /* This function should only be called after capabilities are checked. */
1283 static void qmp_caps_apply(Monitor *mon, QMPCapabilityList *list)
1284 {
1285 for (; list; list = list->next) {
1286 mon->qmp.qmp_caps[list->value] = true;
1287 }
1288 }
1289
1290 /*
1291 * Return true if check successful, or false otherwise. When false is
1292 * returned, detailed error will be in errp if provided.
1293 */
1294 static bool qmp_cmd_oob_check(Monitor *mon, QDict *req, Error **errp)
1295 {
1296 const char *command;
1297 QmpCommand *cmd;
1298
1299 command = qdict_get_try_str(req, "execute");
1300 if (!command) {
1301 error_setg(errp, "Command field 'execute' missing");
1302 return false;
1303 }
1304
1305 cmd = qmp_find_command(mon->qmp.commands, command);
1306 if (!cmd) {
1307 if (mon->qmp.commands == &qmp_cap_negotiation_commands) {
1308 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1309 "Expecting capabilities negotiation "
1310 "with 'qmp_capabilities'");
1311 } else {
1312 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1313 "The command %s has not been found", command);
1314 }
1315 return false;
1316 }
1317
1318 if (qmp_is_oob(req)) {
1319 if (!qmp_oob_enabled(mon)) {
1320 error_setg(errp, "Please enable Out-Of-Band first "
1321 "for the session during capabilities negotiation");
1322 return false;
1323 }
1324 if (!(cmd->options & QCO_ALLOW_OOB)) {
1325 error_setg(errp, "The command %s does not support OOB",
1326 command);
1327 return false;
1328 }
1329 }
1330
1331 return true;
1332 }
1333
1334 void qmp_qmp_capabilities(bool has_enable, QMPCapabilityList *enable,
1335 Error **errp)
1336 {
1337 Error *local_err = NULL;
1338
1339 if (cur_mon->qmp.commands == &qmp_commands) {
1340 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
1341 "Capabilities negotiation is already complete, command "
1342 "ignored");
1343 return;
1344 }
1345
1346 /* Enable QMP capabilities provided by the client if applicable. */
1347 if (has_enable) {
1348 qmp_caps_check(cur_mon, enable, &local_err);
1349 if (local_err) {
1350 /*
1351 * Failed check on any of the capabilities will fail the
1352 * entire command (and thus not apply any of the other
1353 * capabilities that were also requested).
1354 */
1355 error_propagate(errp, local_err);
1356 return;
1357 }
1358 qmp_caps_apply(cur_mon, enable);
1359 }
1360
1361 cur_mon->qmp.commands = &qmp_commands;
1362 }
1363
1364 /* Set the current CPU defined by the user. Callers must hold BQL. */
1365 int monitor_set_cpu(int cpu_index)
1366 {
1367 CPUState *cpu;
1368
1369 cpu = qemu_get_cpu(cpu_index);
1370 if (cpu == NULL) {
1371 return -1;
1372 }
1373 g_free(cur_mon->mon_cpu_path);
1374 cur_mon->mon_cpu_path = object_get_canonical_path(OBJECT(cpu));
1375 return 0;
1376 }
1377
1378 /* Callers must hold BQL. */
1379 static CPUState *mon_get_cpu_sync(bool synchronize)
1380 {
1381 CPUState *cpu;
1382
1383 if (cur_mon->mon_cpu_path) {
1384 cpu = (CPUState *) object_resolve_path_type(cur_mon->mon_cpu_path,
1385 TYPE_CPU, NULL);
1386 if (!cpu) {
1387 g_free(cur_mon->mon_cpu_path);
1388 cur_mon->mon_cpu_path = NULL;
1389 }
1390 }
1391 if (!cur_mon->mon_cpu_path) {
1392 if (!first_cpu) {
1393 return NULL;
1394 }
1395 monitor_set_cpu(first_cpu->cpu_index);
1396 cpu = first_cpu;
1397 }
1398 if (synchronize) {
1399 cpu_synchronize_state(cpu);
1400 }
1401 return cpu;
1402 }
1403
1404 CPUState *mon_get_cpu(void)
1405 {
1406 return mon_get_cpu_sync(true);
1407 }
1408
1409 CPUArchState *mon_get_cpu_env(void)
1410 {
1411 CPUState *cs = mon_get_cpu();
1412
1413 return cs ? cs->env_ptr : NULL;
1414 }
1415
1416 int monitor_get_cpu_index(void)
1417 {
1418 CPUState *cs = mon_get_cpu_sync(false);
1419
1420 return cs ? cs->cpu_index : UNASSIGNED_CPU_INDEX;
1421 }
1422
1423 static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1424 {
1425 bool all_cpus = qdict_get_try_bool(qdict, "cpustate_all", false);
1426 CPUState *cs;
1427
1428 if (all_cpus) {
1429 CPU_FOREACH(cs) {
1430 monitor_printf(mon, "\nCPU#%d\n", cs->cpu_index);
1431 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1432 }
1433 } else {
1434 cs = mon_get_cpu();
1435
1436 if (!cs) {
1437 monitor_printf(mon, "No CPU available\n");
1438 return;
1439 }
1440
1441 cpu_dump_state(cs, (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1442 }
1443 }
1444
1445 #ifdef CONFIG_TCG
1446 static void hmp_info_jit(Monitor *mon, const QDict *qdict)
1447 {
1448 if (!tcg_enabled()) {
1449 error_report("JIT information is only available with accel=tcg");
1450 return;
1451 }
1452
1453 dump_exec_info((FILE *)mon, monitor_fprintf);
1454 dump_drift_info((FILE *)mon, monitor_fprintf);
1455 }
1456
1457 static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1458 {
1459 dump_opcount_info((FILE *)mon, monitor_fprintf);
1460 }
1461 #endif
1462
1463 static void hmp_info_history(Monitor *mon, const QDict *qdict)
1464 {
1465 int i;
1466 const char *str;
1467
1468 if (!mon->rs)
1469 return;
1470 i = 0;
1471 for(;;) {
1472 str = readline_get_history(mon->rs, i);
1473 if (!str)
1474 break;
1475 monitor_printf(mon, "%d: '%s'\n", i, str);
1476 i++;
1477 }
1478 }
1479
1480 static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1481 {
1482 CPUState *cs = mon_get_cpu();
1483
1484 if (!cs) {
1485 monitor_printf(mon, "No CPU available\n");
1486 return;
1487 }
1488 cpu_dump_statistics(cs, (FILE *)mon, &monitor_fprintf, 0);
1489 }
1490
1491 static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1492 {
1493 const char *name = qdict_get_try_str(qdict, "name");
1494 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1495 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
1496 TraceEventInfoList *events;
1497 TraceEventInfoList *elem;
1498 Error *local_err = NULL;
1499
1500 if (name == NULL) {
1501 name = "*";
1502 }
1503 if (vcpu < 0) {
1504 monitor_printf(mon, "argument vcpu must be positive");
1505 return;
1506 }
1507
1508 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
1509 if (local_err) {
1510 error_report_err(local_err);
1511 return;
1512 }
1513
1514 for (elem = events; elem != NULL; elem = elem->next) {
1515 monitor_printf(mon, "%s : state %u\n",
1516 elem->value->name,
1517 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1518 }
1519 qapi_free_TraceEventInfoList(events);
1520 }
1521
1522 void qmp_client_migrate_info(const char *protocol, const char *hostname,
1523 bool has_port, int64_t port,
1524 bool has_tls_port, int64_t tls_port,
1525 bool has_cert_subject, const char *cert_subject,
1526 Error **errp)
1527 {
1528 if (strcmp(protocol, "spice") == 0) {
1529 if (!qemu_using_spice(errp)) {
1530 return;
1531 }
1532
1533 if (!has_port && !has_tls_port) {
1534 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1535 return;
1536 }
1537
1538 if (qemu_spice_migrate_info(hostname,
1539 has_port ? port : -1,
1540 has_tls_port ? tls_port : -1,
1541 cert_subject)) {
1542 error_setg(errp, QERR_UNDEFINED_ERROR);
1543 return;
1544 }
1545 return;
1546 }
1547
1548 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1549 }
1550
1551 static void hmp_logfile(Monitor *mon, const QDict *qdict)
1552 {
1553 Error *err = NULL;
1554
1555 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1556 if (err) {
1557 error_report_err(err);
1558 }
1559 }
1560
1561 static void hmp_log(Monitor *mon, const QDict *qdict)
1562 {
1563 int mask;
1564 const char *items = qdict_get_str(qdict, "items");
1565
1566 if (!strcmp(items, "none")) {
1567 mask = 0;
1568 } else {
1569 mask = qemu_str_to_log_mask(items);
1570 if (!mask) {
1571 help_cmd(mon, "log");
1572 return;
1573 }
1574 }
1575 qemu_set_log(mask);
1576 }
1577
1578 static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1579 {
1580 const char *option = qdict_get_try_str(qdict, "option");
1581 if (!option || !strcmp(option, "on")) {
1582 singlestep = 1;
1583 } else if (!strcmp(option, "off")) {
1584 singlestep = 0;
1585 } else {
1586 monitor_printf(mon, "unexpected option %s\n", option);
1587 }
1588 }
1589
1590 static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1591 {
1592 const char *device = qdict_get_try_str(qdict, "device");
1593 if (!device)
1594 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1595 if (gdbserver_start(device) < 0) {
1596 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1597 device);
1598 } else if (strcmp(device, "none") == 0) {
1599 monitor_printf(mon, "Disabled gdbserver\n");
1600 } else {
1601 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1602 device);
1603 }
1604 }
1605
1606 static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
1607 {
1608 const char *action = qdict_get_str(qdict, "action");
1609 if (select_watchdog_action(action) == -1) {
1610 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1611 }
1612 }
1613
1614 static void monitor_printc(Monitor *mon, int c)
1615 {
1616 monitor_printf(mon, "'");
1617 switch(c) {
1618 case '\'':
1619 monitor_printf(mon, "\\'");
1620 break;
1621 case '\\':
1622 monitor_printf(mon, "\\\\");
1623 break;
1624 case '\n':
1625 monitor_printf(mon, "\\n");
1626 break;
1627 case '\r':
1628 monitor_printf(mon, "\\r");
1629 break;
1630 default:
1631 if (c >= 32 && c <= 126) {
1632 monitor_printf(mon, "%c", c);
1633 } else {
1634 monitor_printf(mon, "\\x%02x", c);
1635 }
1636 break;
1637 }
1638 monitor_printf(mon, "'");
1639 }
1640
1641 static void memory_dump(Monitor *mon, int count, int format, int wsize,
1642 hwaddr addr, int is_physical)
1643 {
1644 int l, line_size, i, max_digits, len;
1645 uint8_t buf[16];
1646 uint64_t v;
1647 CPUState *cs = mon_get_cpu();
1648
1649 if (!cs && (format == 'i' || !is_physical)) {
1650 monitor_printf(mon, "Can not dump without CPU\n");
1651 return;
1652 }
1653
1654 if (format == 'i') {
1655 monitor_disas(mon, cs, addr, count, is_physical);
1656 return;
1657 }
1658
1659 len = wsize * count;
1660 if (wsize == 1)
1661 line_size = 8;
1662 else
1663 line_size = 16;
1664 max_digits = 0;
1665
1666 switch(format) {
1667 case 'o':
1668 max_digits = DIV_ROUND_UP(wsize * 8, 3);
1669 break;
1670 default:
1671 case 'x':
1672 max_digits = (wsize * 8) / 4;
1673 break;
1674 case 'u':
1675 case 'd':
1676 max_digits = DIV_ROUND_UP(wsize * 8 * 10, 33);
1677 break;
1678 case 'c':
1679 wsize = 1;
1680 break;
1681 }
1682
1683 while (len > 0) {
1684 if (is_physical)
1685 monitor_printf(mon, TARGET_FMT_plx ":", addr);
1686 else
1687 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1688 l = len;
1689 if (l > line_size)
1690 l = line_size;
1691 if (is_physical) {
1692 cpu_physical_memory_read(addr, buf, l);
1693 } else {
1694 if (cpu_memory_rw_debug(cs, addr, buf, l, 0) < 0) {
1695 monitor_printf(mon, " Cannot access memory\n");
1696 break;
1697 }
1698 }
1699 i = 0;
1700 while (i < l) {
1701 switch(wsize) {
1702 default:
1703 case 1:
1704 v = ldub_p(buf + i);
1705 break;
1706 case 2:
1707 v = lduw_p(buf + i);
1708 break;
1709 case 4:
1710 v = (uint32_t)ldl_p(buf + i);
1711 break;
1712 case 8:
1713 v = ldq_p(buf + i);
1714 break;
1715 }
1716 monitor_printf(mon, " ");
1717 switch(format) {
1718 case 'o':
1719 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1720 break;
1721 case 'x':
1722 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1723 break;
1724 case 'u':
1725 monitor_printf(mon, "%*" PRIu64, max_digits, v);
1726 break;
1727 case 'd':
1728 monitor_printf(mon, "%*" PRId64, max_digits, v);
1729 break;
1730 case 'c':
1731 monitor_printc(mon, v);
1732 break;
1733 }
1734 i += wsize;
1735 }
1736 monitor_printf(mon, "\n");
1737 addr += l;
1738 len -= l;
1739 }
1740 }
1741
1742 static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
1743 {
1744 int count = qdict_get_int(qdict, "count");
1745 int format = qdict_get_int(qdict, "format");
1746 int size = qdict_get_int(qdict, "size");
1747 target_long addr = qdict_get_int(qdict, "addr");
1748
1749 memory_dump(mon, count, format, size, addr, 0);
1750 }
1751
1752 static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
1753 {
1754 int count = qdict_get_int(qdict, "count");
1755 int format = qdict_get_int(qdict, "format");
1756 int size = qdict_get_int(qdict, "size");
1757 hwaddr addr = qdict_get_int(qdict, "addr");
1758
1759 memory_dump(mon, count, format, size, addr, 1);
1760 }
1761
1762 static void *gpa2hva(MemoryRegion **p_mr, hwaddr addr, Error **errp)
1763 {
1764 MemoryRegionSection mrs = memory_region_find(get_system_memory(),
1765 addr, 1);
1766
1767 if (!mrs.mr) {
1768 error_setg(errp, "No memory is mapped at address 0x%" HWADDR_PRIx, addr);
1769 return NULL;
1770 }
1771
1772 if (!memory_region_is_ram(mrs.mr) && !memory_region_is_romd(mrs.mr)) {
1773 error_setg(errp, "Memory at address 0x%" HWADDR_PRIx "is not RAM", addr);
1774 memory_region_unref(mrs.mr);
1775 return NULL;
1776 }
1777
1778 *p_mr = mrs.mr;
1779 return qemu_map_ram_ptr(mrs.mr->ram_block, mrs.offset_within_region);
1780 }
1781
1782 static void hmp_gpa2hva(Monitor *mon, const QDict *qdict)
1783 {
1784 hwaddr addr = qdict_get_int(qdict, "addr");
1785 Error *local_err = NULL;
1786 MemoryRegion *mr = NULL;
1787 void *ptr;
1788
1789 ptr = gpa2hva(&mr, addr, &local_err);
1790 if (local_err) {
1791 error_report_err(local_err);
1792 return;
1793 }
1794
1795 monitor_printf(mon, "Host virtual address for 0x%" HWADDR_PRIx
1796 " (%s) is %p\n",
1797 addr, mr->name, ptr);
1798
1799 memory_region_unref(mr);
1800 }
1801
1802 #ifdef CONFIG_LINUX
1803 static uint64_t vtop(void *ptr, Error **errp)
1804 {
1805 uint64_t pinfo;
1806 uint64_t ret = -1;
1807 uintptr_t addr = (uintptr_t) ptr;
1808 uintptr_t pagesize = getpagesize();
1809 off_t offset = addr / pagesize * sizeof(pinfo);
1810 int fd;
1811
1812 fd = open("/proc/self/pagemap", O_RDONLY);
1813 if (fd == -1) {
1814 error_setg_errno(errp, errno, "Cannot open /proc/self/pagemap");
1815 return -1;
1816 }
1817
1818 /* Force copy-on-write if necessary. */
1819 atomic_add((uint8_t *)ptr, 0);
1820
1821 if (pread(fd, &pinfo, sizeof(pinfo), offset) != sizeof(pinfo)) {
1822 error_setg_errno(errp, errno, "Cannot read pagemap");
1823 goto out;
1824 }
1825 if ((pinfo & (1ull << 63)) == 0) {
1826 error_setg(errp, "Page not present");
1827 goto out;
1828 }
1829 ret = ((pinfo & 0x007fffffffffffffull) * pagesize) | (addr & (pagesize - 1));
1830
1831 out:
1832 close(fd);
1833 return ret;
1834 }
1835
1836 static void hmp_gpa2hpa(Monitor *mon, const QDict *qdict)
1837 {
1838 hwaddr addr = qdict_get_int(qdict, "addr");
1839 Error *local_err = NULL;
1840 MemoryRegion *mr = NULL;
1841 void *ptr;
1842 uint64_t physaddr;
1843
1844 ptr = gpa2hva(&mr, addr, &local_err);
1845 if (local_err) {
1846 error_report_err(local_err);
1847 return;
1848 }
1849
1850 physaddr = vtop(ptr, &local_err);
1851 if (local_err) {
1852 error_report_err(local_err);
1853 } else {
1854 monitor_printf(mon, "Host physical address for 0x%" HWADDR_PRIx
1855 " (%s) is 0x%" PRIx64 "\n",
1856 addr, mr->name, (uint64_t) physaddr);
1857 }
1858
1859 memory_region_unref(mr);
1860 }
1861 #endif
1862
1863 static void do_print(Monitor *mon, const QDict *qdict)
1864 {
1865 int format = qdict_get_int(qdict, "format");
1866 hwaddr val = qdict_get_int(qdict, "val");
1867
1868 switch(format) {
1869 case 'o':
1870 monitor_printf(mon, "%#" HWADDR_PRIo, val);
1871 break;
1872 case 'x':
1873 monitor_printf(mon, "%#" HWADDR_PRIx, val);
1874 break;
1875 case 'u':
1876 monitor_printf(mon, "%" HWADDR_PRIu, val);
1877 break;
1878 default:
1879 case 'd':
1880 monitor_printf(mon, "%" HWADDR_PRId, val);
1881 break;
1882 case 'c':
1883 monitor_printc(mon, val);
1884 break;
1885 }
1886 monitor_printf(mon, "\n");
1887 }
1888
1889 static void hmp_sum(Monitor *mon, const QDict *qdict)
1890 {
1891 uint32_t addr;
1892 uint16_t sum;
1893 uint32_t start = qdict_get_int(qdict, "start");
1894 uint32_t size = qdict_get_int(qdict, "size");
1895
1896 sum = 0;
1897 for(addr = start; addr < (start + size); addr++) {
1898 uint8_t val = address_space_ldub(&address_space_memory, addr,
1899 MEMTXATTRS_UNSPECIFIED, NULL);
1900 /* BSD sum algorithm ('sum' Unix command) */
1901 sum = (sum >> 1) | (sum << 15);
1902 sum += val;
1903 }
1904 monitor_printf(mon, "%05d\n", sum);
1905 }
1906
1907 static int mouse_button_state;
1908
1909 static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
1910 {
1911 int dx, dy, dz, button;
1912 const char *dx_str = qdict_get_str(qdict, "dx_str");
1913 const char *dy_str = qdict_get_str(qdict, "dy_str");
1914 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1915
1916 dx = strtol(dx_str, NULL, 0);
1917 dy = strtol(dy_str, NULL, 0);
1918 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1919 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1920
1921 if (dz_str) {
1922 dz = strtol(dz_str, NULL, 0);
1923 if (dz != 0) {
1924 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1925 qemu_input_queue_btn(NULL, button, true);
1926 qemu_input_event_sync();
1927 qemu_input_queue_btn(NULL, button, false);
1928 }
1929 }
1930 qemu_input_event_sync();
1931 }
1932
1933 static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
1934 {
1935 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1936 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1937 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1938 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1939 };
1940 int button_state = qdict_get_int(qdict, "button_state");
1941
1942 if (mouse_button_state == button_state) {
1943 return;
1944 }
1945 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1946 qemu_input_event_sync();
1947 mouse_button_state = button_state;
1948 }
1949
1950 static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
1951 {
1952 int size = qdict_get_int(qdict, "size");
1953 int addr = qdict_get_int(qdict, "addr");
1954 int has_index = qdict_haskey(qdict, "index");
1955 uint32_t val;
1956 int suffix;
1957
1958 if (has_index) {
1959 int index = qdict_get_int(qdict, "index");
1960 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1961 addr++;
1962 }
1963 addr &= 0xffff;
1964
1965 switch(size) {
1966 default:
1967 case 1:
1968 val = cpu_inb(addr);
1969 suffix = 'b';
1970 break;
1971 case 2:
1972 val = cpu_inw(addr);
1973 suffix = 'w';
1974 break;
1975 case 4:
1976 val = cpu_inl(addr);
1977 suffix = 'l';
1978 break;
1979 }
1980 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1981 suffix, addr, size * 2, val);
1982 }
1983
1984 static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
1985 {
1986 int size = qdict_get_int(qdict, "size");
1987 int addr = qdict_get_int(qdict, "addr");
1988 int val = qdict_get_int(qdict, "val");
1989
1990 addr &= IOPORTS_MASK;
1991
1992 switch (size) {
1993 default:
1994 case 1:
1995 cpu_outb(addr, val);
1996 break;
1997 case 2:
1998 cpu_outw(addr, val);
1999 break;
2000 case 4:
2001 cpu_outl(addr, val);
2002 break;
2003 }
2004 }
2005
2006 static void hmp_boot_set(Monitor *mon, const QDict *qdict)
2007 {
2008 Error *local_err = NULL;
2009 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
2010
2011 qemu_boot_set(bootdevice, &local_err);
2012 if (local_err) {
2013 error_report_err(local_err);
2014 } else {
2015 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
2016 }
2017 }
2018
2019 static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
2020 {
2021 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
2022 bool dispatch_tree = qdict_get_try_bool(qdict, "dispatch_tree", false);
2023 bool owner = qdict_get_try_bool(qdict, "owner", false);
2024
2025 mtree_info((fprintf_function)monitor_printf, mon, flatview, dispatch_tree,
2026 owner);
2027 }
2028
2029 static void hmp_info_numa(Monitor *mon, const QDict *qdict)
2030 {
2031 int i;
2032 NumaNodeMem *node_mem;
2033 CpuInfoList *cpu_list, *cpu;
2034
2035 cpu_list = qmp_query_cpus(&error_abort);
2036 node_mem = g_new0(NumaNodeMem, nb_numa_nodes);
2037
2038 query_numa_node_mem(node_mem);
2039 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
2040 for (i = 0; i < nb_numa_nodes; i++) {
2041 monitor_printf(mon, "node %d cpus:", i);
2042 for (cpu = cpu_list; cpu; cpu = cpu->next) {
2043 if (cpu->value->has_props && cpu->value->props->has_node_id &&
2044 cpu->value->props->node_id == i) {
2045 monitor_printf(mon, " %" PRIi64, cpu->value->CPU);
2046 }
2047 }
2048 monitor_printf(mon, "\n");
2049 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
2050 node_mem[i].node_mem >> 20);
2051 monitor_printf(mon, "node %d plugged: %" PRId64 " MB\n", i,
2052 node_mem[i].node_plugged_mem >> 20);
2053 }
2054 qapi_free_CpuInfoList(cpu_list);
2055 g_free(node_mem);
2056 }
2057
2058 #ifdef CONFIG_PROFILER
2059
2060 int64_t tcg_time;
2061 int64_t dev_time;
2062
2063 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
2064 {
2065 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
2066 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
2067 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
2068 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
2069 tcg_time = 0;
2070 dev_time = 0;
2071 }
2072 #else
2073 static void hmp_info_profile(Monitor *mon, const QDict *qdict)
2074 {
2075 monitor_printf(mon, "Internal profiler not compiled\n");
2076 }
2077 #endif
2078
2079 /* Capture support */
2080 static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2081
2082 static void hmp_info_capture(Monitor *mon, const QDict *qdict)
2083 {
2084 int i;
2085 CaptureState *s;
2086
2087 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2088 monitor_printf(mon, "[%d]: ", i);
2089 s->ops.info (s->opaque);
2090 }
2091 }
2092
2093 static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
2094 {
2095 int i;
2096 int n = qdict_get_int(qdict, "n");
2097 CaptureState *s;
2098
2099 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2100 if (i == n) {
2101 s->ops.destroy (s->opaque);
2102 QLIST_REMOVE (s, entries);
2103 g_free (s);
2104 return;
2105 }
2106 }
2107 }
2108
2109 static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
2110 {
2111 const char *path = qdict_get_str(qdict, "path");
2112 int has_freq = qdict_haskey(qdict, "freq");
2113 int freq = qdict_get_try_int(qdict, "freq", -1);
2114 int has_bits = qdict_haskey(qdict, "bits");
2115 int bits = qdict_get_try_int(qdict, "bits", -1);
2116 int has_channels = qdict_haskey(qdict, "nchannels");
2117 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2118 CaptureState *s;
2119
2120 s = g_malloc0 (sizeof (*s));
2121
2122 freq = has_freq ? freq : 44100;
2123 bits = has_bits ? bits : 16;
2124 nchannels = has_channels ? nchannels : 2;
2125
2126 if (wav_start_capture (s, path, freq, bits, nchannels)) {
2127 monitor_printf(mon, "Failed to add wave capture\n");
2128 g_free (s);
2129 return;
2130 }
2131 QLIST_INSERT_HEAD (&capture_head, s, entries);
2132 }
2133
2134 static qemu_acl *find_acl(Monitor *mon, const char *name)
2135 {
2136 qemu_acl *acl = qemu_acl_find(name);
2137
2138 if (!acl) {
2139 monitor_printf(mon, "acl: unknown list '%s'\n", name);
2140 }
2141 return acl;
2142 }
2143
2144 static void hmp_acl_show(Monitor *mon, const QDict *qdict)
2145 {
2146 const char *aclname = qdict_get_str(qdict, "aclname");
2147 qemu_acl *acl = find_acl(mon, aclname);
2148 qemu_acl_entry *entry;
2149 int i = 0;
2150
2151 if (acl) {
2152 monitor_printf(mon, "policy: %s\n",
2153 acl->defaultDeny ? "deny" : "allow");
2154 QTAILQ_FOREACH(entry, &acl->entries, next) {
2155 i++;
2156 monitor_printf(mon, "%d: %s %s\n", i,
2157 entry->deny ? "deny" : "allow", entry->match);
2158 }
2159 }
2160 }
2161
2162 static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
2163 {
2164 const char *aclname = qdict_get_str(qdict, "aclname");
2165 qemu_acl *acl = find_acl(mon, aclname);
2166
2167 if (acl) {
2168 qemu_acl_reset(acl);
2169 monitor_printf(mon, "acl: removed all rules\n");
2170 }
2171 }
2172
2173 static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
2174 {
2175 const char *aclname = qdict_get_str(qdict, "aclname");
2176 const char *policy = qdict_get_str(qdict, "policy");
2177 qemu_acl *acl = find_acl(mon, aclname);
2178
2179 if (acl) {
2180 if (strcmp(policy, "allow") == 0) {
2181 acl->defaultDeny = 0;
2182 monitor_printf(mon, "acl: policy set to 'allow'\n");
2183 } else if (strcmp(policy, "deny") == 0) {
2184 acl->defaultDeny = 1;
2185 monitor_printf(mon, "acl: policy set to 'deny'\n");
2186 } else {
2187 monitor_printf(mon, "acl: unknown policy '%s', "
2188 "expected 'deny' or 'allow'\n", policy);
2189 }
2190 }
2191 }
2192
2193 static void hmp_acl_add(Monitor *mon, const QDict *qdict)
2194 {
2195 const char *aclname = qdict_get_str(qdict, "aclname");
2196 const char *match = qdict_get_str(qdict, "match");
2197 const char *policy = qdict_get_str(qdict, "policy");
2198 int has_index = qdict_haskey(qdict, "index");
2199 int index = qdict_get_try_int(qdict, "index", -1);
2200 qemu_acl *acl = find_acl(mon, aclname);
2201 int deny, ret;
2202
2203 if (acl) {
2204 if (strcmp(policy, "allow") == 0) {
2205 deny = 0;
2206 } else if (strcmp(policy, "deny") == 0) {
2207 deny = 1;
2208 } else {
2209 monitor_printf(mon, "acl: unknown policy '%s', "
2210 "expected 'deny' or 'allow'\n", policy);
2211 return;
2212 }
2213 if (has_index)
2214 ret = qemu_acl_insert(acl, deny, match, index);
2215 else
2216 ret = qemu_acl_append(acl, deny, match);
2217 if (ret < 0)
2218 monitor_printf(mon, "acl: unable to add acl entry\n");
2219 else
2220 monitor_printf(mon, "acl: added rule at position %d\n", ret);
2221 }
2222 }
2223
2224 static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
2225 {
2226 const char *aclname = qdict_get_str(qdict, "aclname");
2227 const char *match = qdict_get_str(qdict, "match");
2228 qemu_acl *acl = find_acl(mon, aclname);
2229 int ret;
2230
2231 if (acl) {
2232 ret = qemu_acl_remove(acl, match);
2233 if (ret < 0)
2234 monitor_printf(mon, "acl: no matching acl entry\n");
2235 else
2236 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2237 }
2238 }
2239
2240 void qmp_getfd(const char *fdname, Error **errp)
2241 {
2242 mon_fd_t *monfd;
2243 int fd, tmp_fd;
2244
2245 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
2246 if (fd == -1) {
2247 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2248 return;
2249 }
2250
2251 if (qemu_isdigit(fdname[0])) {
2252 close(fd);
2253 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
2254 "a name not starting with a digit");
2255 return;
2256 }
2257
2258 qemu_mutex_lock(&cur_mon->mon_lock);
2259 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2260 if (strcmp(monfd->name, fdname) != 0) {
2261 continue;
2262 }
2263
2264 tmp_fd = monfd->fd;
2265 monfd->fd = fd;
2266 qemu_mutex_unlock(&cur_mon->mon_lock);
2267 /* Make sure close() is out of critical section */
2268 close(tmp_fd);
2269 return;
2270 }
2271
2272 monfd = g_malloc0(sizeof(mon_fd_t));
2273 monfd->name = g_strdup(fdname);
2274 monfd->fd = fd;
2275
2276 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
2277 qemu_mutex_unlock(&cur_mon->mon_lock);
2278 }
2279
2280 void qmp_closefd(const char *fdname, Error **errp)
2281 {
2282 mon_fd_t *monfd;
2283 int tmp_fd;
2284
2285 qemu_mutex_lock(&cur_mon->mon_lock);
2286 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
2287 if (strcmp(monfd->name, fdname) != 0) {
2288 continue;
2289 }
2290
2291 QLIST_REMOVE(monfd, next);
2292 tmp_fd = monfd->fd;
2293 g_free(monfd->name);
2294 g_free(monfd);
2295 qemu_mutex_unlock(&cur_mon->mon_lock);
2296 /* Make sure close() is out of critical section */
2297 close(tmp_fd);
2298 return;
2299 }
2300
2301 qemu_mutex_unlock(&cur_mon->mon_lock);
2302 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
2303 }
2304
2305 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
2306 {
2307 mon_fd_t *monfd;
2308
2309 qemu_mutex_lock(&mon->mon_lock);
2310 QLIST_FOREACH(monfd, &mon->fds, next) {
2311 int fd;
2312
2313 if (strcmp(monfd->name, fdname) != 0) {
2314 continue;
2315 }
2316
2317 fd = monfd->fd;
2318
2319 /* caller takes ownership of fd */
2320 QLIST_REMOVE(monfd, next);
2321 g_free(monfd->name);
2322 g_free(monfd);
2323 qemu_mutex_unlock(&mon->mon_lock);
2324
2325 return fd;
2326 }
2327
2328 qemu_mutex_unlock(&mon->mon_lock);
2329 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
2330 return -1;
2331 }
2332
2333 static void monitor_fdset_cleanup(MonFdset *mon_fdset)
2334 {
2335 MonFdsetFd *mon_fdset_fd;
2336 MonFdsetFd *mon_fdset_fd_next;
2337
2338 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
2339 if ((mon_fdset_fd->removed ||
2340 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
2341 runstate_is_running()) {
2342 close(mon_fdset_fd->fd);
2343 g_free(mon_fdset_fd->opaque);
2344 QLIST_REMOVE(mon_fdset_fd, next);
2345 g_free(mon_fdset_fd);
2346 }
2347 }
2348
2349 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
2350 QLIST_REMOVE(mon_fdset, next);
2351 g_free(mon_fdset);
2352 }
2353 }
2354
2355 static void monitor_fdsets_cleanup(void)
2356 {
2357 MonFdset *mon_fdset;
2358 MonFdset *mon_fdset_next;
2359
2360 qemu_mutex_lock(&mon_fdsets_lock);
2361 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
2362 monitor_fdset_cleanup(mon_fdset);
2363 }
2364 qemu_mutex_unlock(&mon_fdsets_lock);
2365 }
2366
2367 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
2368 const char *opaque, Error **errp)
2369 {
2370 int fd;
2371 Monitor *mon = cur_mon;
2372 AddfdInfo *fdinfo;
2373
2374 fd = qemu_chr_fe_get_msgfd(&mon->chr);
2375 if (fd == -1) {
2376 error_setg(errp, QERR_FD_NOT_SUPPLIED);
2377 goto error;
2378 }
2379
2380 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
2381 has_opaque, opaque, errp);
2382 if (fdinfo) {
2383 return fdinfo;
2384 }
2385
2386 error:
2387 if (fd != -1) {
2388 close(fd);
2389 }
2390 return NULL;
2391 }
2392
2393 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
2394 {
2395 MonFdset *mon_fdset;
2396 MonFdsetFd *mon_fdset_fd;
2397 char fd_str[60];
2398
2399 qemu_mutex_lock(&mon_fdsets_lock);
2400 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2401 if (mon_fdset->id != fdset_id) {
2402 continue;
2403 }
2404 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2405 if (has_fd) {
2406 if (mon_fdset_fd->fd != fd) {
2407 continue;
2408 }
2409 mon_fdset_fd->removed = true;
2410 break;
2411 } else {
2412 mon_fdset_fd->removed = true;
2413 }
2414 }
2415 if (has_fd && !mon_fdset_fd) {
2416 goto error;
2417 }
2418 monitor_fdset_cleanup(mon_fdset);
2419 qemu_mutex_unlock(&mon_fdsets_lock);
2420 return;
2421 }
2422
2423 error:
2424 qemu_mutex_unlock(&mon_fdsets_lock);
2425 if (has_fd) {
2426 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
2427 fdset_id, fd);
2428 } else {
2429 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
2430 }
2431 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
2432 }
2433
2434 FdsetInfoList *qmp_query_fdsets(Error **errp)
2435 {
2436 MonFdset *mon_fdset;
2437 MonFdsetFd *mon_fdset_fd;
2438 FdsetInfoList *fdset_list = NULL;
2439
2440 qemu_mutex_lock(&mon_fdsets_lock);
2441 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2442 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
2443 FdsetFdInfoList *fdsetfd_list = NULL;
2444
2445 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
2446 fdset_info->value->fdset_id = mon_fdset->id;
2447
2448 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2449 FdsetFdInfoList *fdsetfd_info;
2450
2451 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
2452 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
2453 fdsetfd_info->value->fd = mon_fdset_fd->fd;
2454 if (mon_fdset_fd->opaque) {
2455 fdsetfd_info->value->has_opaque = true;
2456 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
2457 } else {
2458 fdsetfd_info->value->has_opaque = false;
2459 }
2460
2461 fdsetfd_info->next = fdsetfd_list;
2462 fdsetfd_list = fdsetfd_info;
2463 }
2464
2465 fdset_info->value->fds = fdsetfd_list;
2466
2467 fdset_info->next = fdset_list;
2468 fdset_list = fdset_info;
2469 }
2470 qemu_mutex_unlock(&mon_fdsets_lock);
2471
2472 return fdset_list;
2473 }
2474
2475 AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
2476 bool has_opaque, const char *opaque,
2477 Error **errp)
2478 {
2479 MonFdset *mon_fdset = NULL;
2480 MonFdsetFd *mon_fdset_fd;
2481 AddfdInfo *fdinfo;
2482
2483 qemu_mutex_lock(&mon_fdsets_lock);
2484 if (has_fdset_id) {
2485 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2486 /* Break if match found or match impossible due to ordering by ID */
2487 if (fdset_id <= mon_fdset->id) {
2488 if (fdset_id < mon_fdset->id) {
2489 mon_fdset = NULL;
2490 }
2491 break;
2492 }
2493 }
2494 }
2495
2496 if (mon_fdset == NULL) {
2497 int64_t fdset_id_prev = -1;
2498 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
2499
2500 if (has_fdset_id) {
2501 if (fdset_id < 0) {
2502 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
2503 "a non-negative value");
2504 qemu_mutex_unlock(&mon_fdsets_lock);
2505 return NULL;
2506 }
2507 /* Use specified fdset ID */
2508 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2509 mon_fdset_cur = mon_fdset;
2510 if (fdset_id < mon_fdset_cur->id) {
2511 break;
2512 }
2513 }
2514 } else {
2515 /* Use first available fdset ID */
2516 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2517 mon_fdset_cur = mon_fdset;
2518 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2519 fdset_id_prev = mon_fdset_cur->id;
2520 continue;
2521 }
2522 break;
2523 }
2524 }
2525
2526 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2527 if (has_fdset_id) {
2528 mon_fdset->id = fdset_id;
2529 } else {
2530 mon_fdset->id = fdset_id_prev + 1;
2531 }
2532
2533 /* The fdset list is ordered by fdset ID */
2534 if (!mon_fdset_cur) {
2535 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2536 } else if (mon_fdset->id < mon_fdset_cur->id) {
2537 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2538 } else {
2539 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2540 }
2541 }
2542
2543 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2544 mon_fdset_fd->fd = fd;
2545 mon_fdset_fd->removed = false;
2546 if (has_opaque) {
2547 mon_fdset_fd->opaque = g_strdup(opaque);
2548 }
2549 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2550
2551 fdinfo = g_malloc0(sizeof(*fdinfo));
2552 fdinfo->fdset_id = mon_fdset->id;
2553 fdinfo->fd = mon_fdset_fd->fd;
2554
2555 qemu_mutex_unlock(&mon_fdsets_lock);
2556 return fdinfo;
2557 }
2558
2559 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2560 {
2561 #ifdef _WIN32
2562 return -ENOENT;
2563 #else
2564 MonFdset *mon_fdset;
2565 MonFdsetFd *mon_fdset_fd;
2566 int mon_fd_flags;
2567 int ret;
2568
2569 qemu_mutex_lock(&mon_fdsets_lock);
2570 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2571 if (mon_fdset->id != fdset_id) {
2572 continue;
2573 }
2574 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2575 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2576 if (mon_fd_flags == -1) {
2577 ret = -errno;
2578 goto out;
2579 }
2580
2581 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2582 ret = mon_fdset_fd->fd;
2583 goto out;
2584 }
2585 }
2586 ret = -EACCES;
2587 goto out;
2588 }
2589 ret = -ENOENT;
2590
2591 out:
2592 qemu_mutex_unlock(&mon_fdsets_lock);
2593 return ret;
2594 #endif
2595 }
2596
2597 int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2598 {
2599 MonFdset *mon_fdset;
2600 MonFdsetFd *mon_fdset_fd_dup;
2601
2602 qemu_mutex_lock(&mon_fdsets_lock);
2603 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2604 if (mon_fdset->id != fdset_id) {
2605 continue;
2606 }
2607 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2608 if (mon_fdset_fd_dup->fd == dup_fd) {
2609 goto err;
2610 }
2611 }
2612 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2613 mon_fdset_fd_dup->fd = dup_fd;
2614 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2615 qemu_mutex_unlock(&mon_fdsets_lock);
2616 return 0;
2617 }
2618
2619 err:
2620 qemu_mutex_unlock(&mon_fdsets_lock);
2621 return -1;
2622 }
2623
2624 static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2625 {
2626 MonFdset *mon_fdset;
2627 MonFdsetFd *mon_fdset_fd_dup;
2628
2629 qemu_mutex_lock(&mon_fdsets_lock);
2630 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2631 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2632 if (mon_fdset_fd_dup->fd == dup_fd) {
2633 if (remove) {
2634 QLIST_REMOVE(mon_fdset_fd_dup, next);
2635 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2636 monitor_fdset_cleanup(mon_fdset);
2637 }
2638 goto err;
2639 } else {
2640 qemu_mutex_unlock(&mon_fdsets_lock);
2641 return mon_fdset->id;
2642 }
2643 }
2644 }
2645 }
2646
2647 err:
2648 qemu_mutex_unlock(&mon_fdsets_lock);
2649 return -1;
2650 }
2651
2652 int monitor_fdset_dup_fd_find(int dup_fd)
2653 {
2654 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2655 }
2656
2657 void monitor_fdset_dup_fd_remove(int dup_fd)
2658 {
2659 monitor_fdset_dup_fd_find_remove(dup_fd, true);
2660 }
2661
2662 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
2663 {
2664 int fd;
2665 Error *local_err = NULL;
2666
2667 if (!qemu_isdigit(fdname[0]) && mon) {
2668 fd = monitor_get_fd(mon, fdname, &local_err);
2669 } else {
2670 fd = qemu_parse_fd(fdname);
2671 if (fd == -1) {
2672 error_setg(&local_err, "Invalid file descriptor number '%s'",
2673 fdname);
2674 }
2675 }
2676 if (local_err) {
2677 error_propagate(errp, local_err);
2678 assert(fd == -1);
2679 } else {
2680 assert(fd != -1);
2681 }
2682
2683 return fd;
2684 }
2685
2686 /* Please update hmp-commands.hx when adding or changing commands */
2687 static mon_cmd_t info_cmds[] = {
2688 #include "hmp-commands-info.h"
2689 { NULL, NULL, },
2690 };
2691
2692 /* mon_cmds and info_cmds would be sorted at runtime */
2693 static mon_cmd_t mon_cmds[] = {
2694 #include "hmp-commands.h"
2695 { NULL, NULL, },
2696 };
2697
2698 /*******************************************************************/
2699
2700 static const char *pch;
2701 static sigjmp_buf expr_env;
2702
2703
2704 static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2705 expr_error(Monitor *mon, const char *fmt, ...)
2706 {
2707 va_list ap;
2708 va_start(ap, fmt);
2709 monitor_vprintf(mon, fmt, ap);
2710 monitor_printf(mon, "\n");
2711 va_end(ap);
2712 siglongjmp(expr_env, 1);
2713 }
2714
2715 /* return 0 if OK, -1 if not found */
2716 static int get_monitor_def(target_long *pval, const char *name)
2717 {
2718 const MonitorDef *md = target_monitor_defs();
2719 CPUState *cs = mon_get_cpu();
2720 void *ptr;
2721 uint64_t tmp = 0;
2722 int ret;
2723
2724 if (cs == NULL || md == NULL) {
2725 return -1;
2726 }
2727
2728 for(; md->name != NULL; md++) {
2729 if (compare_cmd(name, md->name)) {
2730 if (md->get_value) {
2731 *pval = md->get_value(md, md->offset);
2732 } else {
2733 CPUArchState *env = mon_get_cpu_env();
2734 ptr = (uint8_t *)env + md->offset;
2735 switch(md->type) {
2736 case MD_I32:
2737 *pval = *(int32_t *)ptr;
2738 break;
2739 case MD_TLONG:
2740 *pval = *(target_long *)ptr;
2741 break;
2742 default:
2743 *pval = 0;
2744 break;
2745 }
2746 }
2747 return 0;
2748 }
2749 }
2750
2751 ret = target_get_monitor_def(cs, name, &tmp);
2752 if (!ret) {
2753 *pval = (target_long) tmp;
2754 }
2755
2756 return ret;
2757 }
2758
2759 static void next(void)
2760 {
2761 if (*pch != '\0') {
2762 pch++;
2763 while (qemu_isspace(*pch))
2764 pch++;
2765 }
2766 }
2767
2768 static int64_t expr_sum(Monitor *mon);
2769
2770 static int64_t expr_unary(Monitor *mon)
2771 {
2772 int64_t n;
2773 char *p;
2774 int ret;
2775
2776 switch(*pch) {
2777 case '+':
2778 next();
2779 n = expr_unary(mon);
2780 break;
2781 case '-':
2782 next();
2783 n = -expr_unary(mon);
2784 break;
2785 case '~':
2786 next();
2787 n = ~expr_unary(mon);
2788 break;
2789 case '(':
2790 next();
2791 n = expr_sum(mon);
2792 if (*pch != ')') {
2793 expr_error(mon, "')' expected");
2794 }
2795 next();
2796 break;
2797 case '\'':
2798 pch++;
2799 if (*pch == '\0')
2800 expr_error(mon, "character constant expected");
2801 n = *pch;
2802 pch++;
2803 if (*pch != '\'')
2804 expr_error(mon, "missing terminating \' character");
2805 next();
2806 break;
2807 case '$':
2808 {
2809 char buf[128], *q;
2810 target_long reg=0;
2811
2812 pch++;
2813 q = buf;
2814 while ((*pch >= 'a' && *pch <= 'z') ||
2815 (*pch >= 'A' && *pch <= 'Z') ||
2816 (*pch >= '0' && *pch <= '9') ||
2817 *pch == '_' || *pch == '.') {
2818 if ((q - buf) < sizeof(buf) - 1)
2819 *q++ = *pch;
2820 pch++;
2821 }
2822 while (qemu_isspace(*pch))
2823 pch++;
2824 *q = 0;
2825 ret = get_monitor_def(&reg, buf);
2826 if (ret < 0)
2827 expr_error(mon, "unknown register");
2828 n = reg;
2829 }
2830 break;
2831 case '\0':
2832 expr_error(mon, "unexpected end of expression");
2833 n = 0;
2834 break;
2835 default:
2836 errno = 0;
2837 n = strtoull(pch, &p, 0);
2838 if (errno == ERANGE) {
2839 expr_error(mon, "number too large");
2840 }
2841 if (pch == p) {
2842 expr_error(mon, "invalid char '%c' in expression", *p);
2843 }
2844 pch = p;
2845 while (qemu_isspace(*pch))
2846 pch++;
2847 break;
2848 }
2849 return n;
2850 }
2851
2852
2853 static int64_t expr_prod(Monitor *mon)
2854 {
2855 int64_t val, val2;
2856 int op;
2857
2858 val = expr_unary(mon);
2859 for(;;) {
2860 op = *pch;
2861 if (op != '*' && op != '/' && op != '%')
2862 break;
2863 next();
2864 val2 = expr_unary(mon);
2865 switch(op) {
2866 default:
2867 case '*':
2868 val *= val2;
2869 break;
2870 case '/':
2871 case '%':
2872 if (val2 == 0)
2873 expr_error(mon, "division by zero");
2874 if (op == '/')
2875 val /= val2;
2876 else
2877 val %= val2;
2878 break;
2879 }
2880 }
2881 return val;
2882 }
2883
2884 static int64_t expr_logic(Monitor *mon)
2885 {
2886 int64_t val, val2;
2887 int op;
2888
2889 val = expr_prod(mon);
2890 for(;;) {
2891 op = *pch;
2892 if (op != '&' && op != '|' && op != '^')
2893 break;
2894 next();
2895 val2 = expr_prod(mon);
2896 switch(op) {
2897 default:
2898 case '&':
2899 val &= val2;
2900 break;
2901 case '|':
2902 val |= val2;
2903 break;
2904 case '^':
2905 val ^= val2;
2906 break;
2907 }
2908 }
2909 return val;
2910 }
2911
2912 static int64_t expr_sum(Monitor *mon)
2913 {
2914 int64_t val, val2;
2915 int op;
2916
2917 val = expr_logic(mon);
2918 for(;;) {
2919 op = *pch;
2920 if (op != '+' && op != '-')
2921 break;
2922 next();
2923 val2 = expr_logic(mon);
2924 if (op == '+')
2925 val += val2;
2926 else
2927 val -= val2;
2928 }
2929 return val;
2930 }
2931
2932 static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2933 {
2934 pch = *pp;
2935 if (sigsetjmp(expr_env, 0)) {
2936 *pp = pch;
2937 return -1;
2938 }
2939 while (qemu_isspace(*pch))
2940 pch++;
2941 *pval = expr_sum(mon);
2942 *pp = pch;
2943 return 0;
2944 }
2945
2946 static int get_double(Monitor *mon, double *pval, const char **pp)
2947 {
2948 const char *p = *pp;
2949 char *tailp;
2950 double d;
2951
2952 d = strtod(p, &tailp);
2953 if (tailp == p) {
2954 monitor_printf(mon, "Number expected\n");
2955 return -1;
2956 }
2957 if (d != d || d - d != 0) {
2958 /* NaN or infinity */
2959 monitor_printf(mon, "Bad number\n");
2960 return -1;
2961 }
2962 *pval = d;
2963 *pp = tailp;
2964 return 0;
2965 }
2966
2967 /*
2968 * Store the command-name in cmdname, and return a pointer to
2969 * the remaining of the command string.
2970 */
2971 static const char *get_command_name(const char *cmdline,
2972 char *cmdname, size_t nlen)
2973 {
2974 size_t len;
2975 const char *p, *pstart;
2976
2977 p = cmdline;
2978 while (qemu_isspace(*p))
2979 p++;
2980 if (*p == '\0')
2981 return NULL;
2982 pstart = p;
2983 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2984 p++;
2985 len = p - pstart;
2986 if (len > nlen - 1)
2987 len = nlen - 1;
2988 memcpy(cmdname, pstart, len);
2989 cmdname[len] = '\0';
2990 return p;
2991 }
2992
2993 /**
2994 * Read key of 'type' into 'key' and return the current
2995 * 'type' pointer.
2996 */
2997 static char *key_get_info(const char *type, char **key)
2998 {
2999 size_t len;
3000 char *p, *str;
3001
3002 if (*type == ',')
3003 type++;
3004
3005 p = strchr(type, ':');
3006 if (!p) {
3007 *key = NULL;
3008 return NULL;
3009 }
3010 len = p - type;
3011
3012 str = g_malloc(len + 1);
3013 memcpy(str, type, len);
3014 str[len] = '\0';
3015
3016 *key = str;
3017 return ++p;
3018 }
3019
3020 static int default_fmt_format = 'x';
3021 static int default_fmt_size = 4;
3022
3023 static int is_valid_option(const char *c, const char *typestr)
3024 {
3025 char option[3];
3026
3027 option[0] = '-';
3028 option[1] = *c;
3029 option[2] = '\0';
3030
3031 typestr = strstr(typestr, option);
3032 return (typestr != NULL);
3033 }
3034
3035 static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3036 const char *cmdname)
3037 {
3038 const mon_cmd_t *cmd;
3039
3040 for (cmd = disp_table; cmd->name != NULL; cmd++) {
3041 if (compare_cmd(cmdname, cmd->name)) {
3042 return cmd;
3043 }
3044 }
3045
3046 return NULL;
3047 }
3048
3049 /*
3050 * Parse command name from @cmdp according to command table @table.
3051 * If blank, return NULL.
3052 * Else, if no valid command can be found, report to @mon, and return
3053 * NULL.
3054 * Else, change @cmdp to point right behind the name, and return its
3055 * command table entry.
3056 * Do not assume the return value points into @table! It doesn't when
3057 * the command is found in a sub-command table.
3058 */
3059 static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3060 const char *cmdp_start,
3061 const char **cmdp,
3062 mon_cmd_t *table)
3063 {
3064 const char *p;
3065 const mon_cmd_t *cmd;
3066 char cmdname[256];
3067
3068 /* extract the command name */
3069 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
3070 if (!p)
3071 return NULL;
3072
3073 cmd = search_dispatch_table(table, cmdname);
3074 if (!cmd) {
3075 monitor_printf(mon, "unknown command: '%.*s'\n",
3076 (int)(p - cmdp_start), cmdp_start);
3077 return NULL;
3078 }
3079 if (runstate_check(RUN_STATE_PRECONFIG) && !cmd_can_preconfig(cmd)) {
3080 monitor_printf(mon, "Command '%.*s' not available with -preconfig "
3081 "until after exit_preconfig.\n",
3082 (int)(p - cmdp_start), cmdp_start);
3083 return NULL;
3084 }
3085
3086 /* filter out following useless space */
3087 while (qemu_isspace(*p)) {
3088 p++;
3089 }
3090
3091 *cmdp = p;
3092 /* search sub command */
3093 if (cmd->sub_table != NULL && *p != '\0') {
3094 return monitor_parse_command(mon, cmdp_start, cmdp, cmd->sub_table);
3095 }
3096
3097 return cmd;
3098 }
3099
3100 /*
3101 * Parse arguments for @cmd.
3102 * If it can't be parsed, report to @mon, and return NULL.
3103 * Else, insert command arguments into a QDict, and return it.
3104 * Note: On success, caller has to free the QDict structure.
3105 */
3106
3107 static QDict *monitor_parse_arguments(Monitor *mon,
3108 const char **endp,
3109 const mon_cmd_t *cmd)
3110 {
3111 const char *typestr;
3112 char *key;
3113 int c;
3114 const char *p = *endp;
3115 char buf[1024];
3116 QDict *qdict = qdict_new();
3117
3118 /* parse the parameters */
3119 typestr = cmd->args_type;
3120 for(;;) {
3121 typestr = key_get_info(typestr, &key);
3122 if (!typestr)
3123 break;
3124 c = *typestr;
3125 typestr++;
3126 switch(c) {
3127 case 'F':
3128 case 'B':
3129 case 's':
3130 {
3131 int ret;
3132
3133 while (qemu_isspace(*p))
3134 p++;
3135 if (*typestr == '?') {
3136 typestr++;
3137 if (*p == '\0') {
3138 /* no optional string: NULL argument */
3139 break;
3140 }
3141 }
3142 ret = get_str(buf, sizeof(buf), &p);
3143 if (ret < 0) {
3144 switch(c) {
3145 case 'F':
3146 monitor_printf(mon, "%s: filename expected\n",
3147 cmd->name);
3148 break;
3149 case 'B':
3150 monitor_printf(mon, "%s: block device name expected\n",
3151 cmd->name);
3152 break;
3153 default:
3154 monitor_printf(mon, "%s: string expected\n", cmd->name);
3155 break;
3156 }
3157 goto fail;
3158 }
3159 qdict_put_str(qdict, key, buf);
3160 }
3161 break;
3162 case 'O':
3163 {
3164 QemuOptsList *opts_list;
3165 QemuOpts *opts;
3166
3167 opts_list = qemu_find_opts(key);
3168 if (!opts_list || opts_list->desc->name) {
3169 goto bad_type;
3170 }
3171 while (qemu_isspace(*p)) {
3172 p++;
3173 }
3174 if (!*p)
3175 break;
3176 if (get_str(buf, sizeof(buf), &p) < 0) {
3177 goto fail;
3178 }
3179 opts = qemu_opts_parse_noisily(opts_list, buf, true);
3180 if (!opts) {
3181 goto fail;
3182 }
3183 qemu_opts_to_qdict(opts, qdict);
3184 qemu_opts_del(opts);
3185 }
3186 break;
3187 case '/':
3188 {
3189 int count, format, size;
3190
3191 while (qemu_isspace(*p))
3192 p++;
3193 if (*p == '/') {
3194 /* format found */
3195 p++;
3196 count = 1;
3197 if (qemu_isdigit(*p)) {
3198 count = 0;
3199 while (qemu_isdigit(*p)) {
3200 count = count * 10 + (*p - '0');
3201 p++;
3202 }
3203 }
3204 size = -1;
3205 format = -1;
3206 for(;;) {
3207 switch(*p) {
3208 case 'o':
3209 case 'd':
3210 case 'u':
3211 case 'x':
3212 case 'i':
3213 case 'c':
3214 format = *p++;
3215 break;
3216 case 'b':
3217 size = 1;
3218 p++;
3219 break;
3220 case 'h':
3221 size = 2;
3222 p++;
3223 break;
3224 case 'w':
3225 size = 4;
3226 p++;
3227 break;
3228 case 'g':
3229 case 'L':
3230 size = 8;
3231 p++;
3232 break;
3233 default:
3234 goto next;
3235 }
3236 }
3237 next:
3238 if (*p != '\0' && !qemu_isspace(*p)) {
3239 monitor_printf(mon, "invalid char in format: '%c'\n",
3240 *p);
3241 goto fail;
3242 }
3243 if (format < 0)
3244 format = default_fmt_format;
3245 if (format != 'i') {
3246 /* for 'i', not specifying a size gives -1 as size */
3247 if (size < 0)
3248 size = default_fmt_size;
3249 default_fmt_size = size;
3250 }
3251 default_fmt_format = format;
3252 } else {
3253 count = 1;
3254 format = default_fmt_format;
3255 if (format != 'i') {
3256 size = default_fmt_size;
3257 } else {
3258 size = -1;
3259 }
3260 }
3261 qdict_put_int(qdict, "count", count);
3262 qdict_put_int(qdict, "format", format);
3263 qdict_put_int(qdict, "size", size);
3264 }
3265 break;
3266 case 'i':
3267 case 'l':
3268 case 'M':
3269 {
3270 int64_t val;
3271
3272 while (qemu_isspace(*p))
3273 p++;
3274 if (*typestr == '?' || *typestr == '.') {
3275 if (*typestr == '?') {
3276 if (*p == '\0') {
3277 typestr++;
3278 break;
3279 }
3280 } else {
3281 if (*p == '.') {
3282 p++;
3283 while (qemu_isspace(*p))
3284 p++;
3285 } else {
3286 typestr++;
3287 break;
3288 }
3289 }
3290 typestr++;
3291 }
3292 if (get_expr(mon, &val, &p))
3293 goto fail;
3294 /* Check if 'i' is greater than 32-bit */
3295 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3296 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
3297 monitor_printf(mon, "integer is for 32-bit values\n");
3298 goto fail;
3299 } else if (c == 'M') {
3300 if (val < 0) {
3301 monitor_printf(mon, "enter a positive value\n");
3302 goto fail;
3303 }
3304 val *= MiB;
3305 }
3306 qdict_put_int(qdict, key, val);
3307 }
3308 break;
3309 case 'o':
3310 {
3311 int ret;
3312 uint64_t val;
3313 char *end;
3314
3315 while (qemu_isspace(*p)) {
3316 p++;
3317 }
3318 if (*typestr == '?') {
3319 typestr++;
3320 if (*p == '\0') {
3321 break;
3322 }
3323 }
3324 ret = qemu_strtosz_MiB(p, &end, &val);
3325 if (ret < 0 || val > INT64_MAX) {
3326 monitor_printf(mon, "invalid size\n");
3327 goto fail;
3328 }
3329 qdict_put_int(qdict, key, val);
3330 p = end;
3331 }
3332 break;
3333 case 'T':
3334 {
3335 double val;
3336
3337 while (qemu_isspace(*p))
3338 p++;
3339 if (*typestr == '?') {
3340 typestr++;
3341 if (*p == '\0') {
3342 break;
3343 }
3344 }
3345 if (get_double(mon, &val, &p) < 0) {
3346 goto fail;
3347 }
3348 if (p[0] && p[1] == 's') {
3349 switch (*p) {
3350 case 'm':
3351 val /= 1e3; p += 2; break;
3352 case 'u':
3353 val /= 1e6; p += 2; break;
3354 case 'n':
3355 val /= 1e9; p += 2; break;
3356 }
3357 }
3358 if (*p && !qemu_isspace(*p)) {
3359 monitor_printf(mon, "Unknown unit suffix\n");
3360 goto fail;
3361 }
3362 qdict_put(qdict, key, qnum_from_double(val));
3363 }
3364 break;
3365 case 'b':
3366 {
3367 const char *beg;
3368 bool val;
3369
3370 while (qemu_isspace(*p)) {
3371 p++;
3372 }
3373 beg = p;
3374 while (qemu_isgraph(*p)) {
3375 p++;
3376 }
3377 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3378 val = true;
3379 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3380 val = false;
3381 } else {
3382 monitor_printf(mon, "Expected 'on' or 'off'\n");
3383 goto fail;
3384 }
3385 qdict_put_bool(qdict, key, val);
3386 }
3387 break;
3388 case '-':
3389 {
3390 const char *tmp = p;
3391 int skip_key = 0;
3392 /* option */
3393
3394 c = *typestr++;
3395 if (c == '\0')
3396 goto bad_type;
3397 while (qemu_isspace(*p))
3398 p++;
3399 if (*p == '-') {
3400 p++;
3401 if(c != *p) {
3402 if(!is_valid_option(p, typestr)) {
3403
3404 monitor_printf(mon, "%s: unsupported option -%c\n",
3405 cmd->name, *p);
3406 goto fail;
3407 } else {
3408 skip_key = 1;
3409 }
3410 }
3411 if(skip_key) {
3412 p = tmp;
3413 } else {
3414 /* has option */
3415 p++;
3416 qdict_put_bool(qdict, key, true);
3417 }
3418 }
3419 }
3420 break;
3421 case 'S':
3422 {
3423 /* package all remaining string */
3424 int len;
3425
3426 while (qemu_isspace(*p)) {
3427 p++;
3428 }
3429 if (*typestr == '?') {
3430 typestr++;
3431 if (*p == '\0') {
3432 /* no remaining string: NULL argument */
3433 break;
3434 }
3435 }
3436 len = strlen(p);
3437 if (len <= 0) {
3438 monitor_printf(mon, "%s: string expected\n",
3439 cmd->name);
3440 goto fail;
3441 }
3442 qdict_put_str(qdict, key, p);
3443 p += len;
3444 }
3445 break;
3446 default:
3447 bad_type:
3448 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
3449 goto fail;
3450 }
3451 g_free(key);
3452 key = NULL;
3453 }
3454 /* check that all arguments were parsed */
3455 while (qemu_isspace(*p))
3456 p++;
3457 if (*p != '\0') {
3458 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3459 cmd->name);
3460 goto fail;
3461 }
3462
3463 return qdict;
3464
3465 fail:
3466 qobject_unref(qdict);
3467 g_free(key);
3468 return NULL;
3469 }
3470
3471 static void handle_hmp_command(Monitor *mon, const char *cmdline)
3472 {
3473 QDict *qdict;
3474 const mon_cmd_t *cmd;
3475 const char *cmd_start = cmdline;
3476
3477 trace_handle_hmp_command(mon, cmdline);
3478
3479 cmd = monitor_parse_command(mon, cmdline, &cmdline, mon->cmd_table);
3480 if (!cmd) {
3481 return;
3482 }
3483
3484 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
3485 if (!qdict) {
3486 while (cmdline > cmd_start && qemu_isspace(cmdline[-1])) {
3487 cmdline--;
3488 }
3489 monitor_printf(mon, "Try \"help %.*s\" for more information\n",
3490 (int)(cmdline - cmd_start), cmd_start);
3491 return;
3492 }
3493
3494 cmd->cmd(mon, qdict);
3495 qobject_unref(qdict);
3496 }
3497
3498 static void cmd_completion(Monitor *mon, const char *name, const char *list)
3499 {
3500 const char *p, *pstart;
3501 char cmd[128];
3502 int len;
3503
3504 p = list;
3505 for(;;) {
3506 pstart = p;
3507 p = qemu_strchrnul(p, '|');
3508 len = p - pstart;
3509 if (len > sizeof(cmd) - 2)
3510 len = sizeof(cmd) - 2;
3511 memcpy(cmd, pstart, len);
3512 cmd[len] = '\0';
3513 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3514 readline_add_completion(mon->rs, cmd);
3515 }
3516 if (*p == '\0')
3517 break;
3518 p++;
3519 }
3520 }
3521
3522 static void file_completion(Monitor *mon, const char *input)
3523 {
3524 DIR *ffs;
3525 struct dirent *d;
3526 char path[1024];
3527 char file[1024], file_prefix[1024];
3528 int input_path_len;
3529 const char *p;
3530
3531 p = strrchr(input, '/');
3532 if (!p) {
3533 input_path_len = 0;
3534 pstrcpy(file_prefix, sizeof(file_prefix), input);
3535 pstrcpy(path, sizeof(path), ".");
3536 } else {
3537 input_path_len = p - input + 1;
3538 memcpy(path, input, input_path_len);
3539 if (input_path_len > sizeof(path) - 1)
3540 input_path_len = sizeof(path) - 1;
3541 path[input_path_len] = '\0';
3542 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3543 }
3544
3545 ffs = opendir(path);
3546 if (!ffs)
3547 return;
3548 for(;;) {
3549 struct stat sb;
3550 d = readdir(ffs);
3551 if (!d)
3552 break;
3553
3554 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3555 continue;
3556 }
3557
3558 if (strstart(d->d_name, file_prefix, NULL)) {
3559 memcpy(file, input, input_path_len);
3560 if (input_path_len < sizeof(file))
3561 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3562 d->d_name);
3563 /* stat the file to find out if it's a directory.
3564 * In that case add a slash to speed up typing long paths
3565 */
3566 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
3567 pstrcat(file, sizeof(file), "/");
3568 }
3569 readline_add_completion(mon->rs, file);
3570 }
3571 }
3572 closedir(ffs);
3573 }
3574
3575 static const char *next_arg_type(const char *typestr)
3576 {
3577 const char *p = strchr(typestr, ':');
3578 return (p != NULL ? ++p : typestr);
3579 }
3580
3581 static void add_completion_option(ReadLineState *rs, const char *str,
3582 const char *option)
3583 {
3584 if (!str || !option) {
3585 return;
3586 }
3587 if (!strncmp(option, str, strlen(str))) {
3588 readline_add_completion(rs, option);
3589 }
3590 }
3591
3592 void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3593 {
3594 size_t len;
3595 ChardevBackendInfoList *list, *start;
3596
3597 if (nb_args != 2) {
3598 return;
3599 }
3600 len = strlen(str);
3601 readline_set_completion_index(rs, len);
3602
3603 start = list = qmp_query_chardev_backends(NULL);
3604 while (list) {
3605 const char *chr_name = list->value->name;
3606
3607 if (!strncmp(chr_name, str, len)) {
3608 readline_add_completion(rs, chr_name);
3609 }
3610 list = list->next;
3611 }
3612 qapi_free_ChardevBackendInfoList(start);
3613 }
3614
3615 void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3616 {
3617 size_t len;
3618 int i;
3619
3620 if (nb_args != 2) {
3621 return;
3622 }
3623 len = strlen(str);
3624 readline_set_completion_index(rs, len);
3625 for (i = 0; i < NET_CLIENT_DRIVER__MAX; i++) {
3626 add_completion_option(rs, str, NetClientDriver_str(i));
3627 }
3628 }
3629
3630 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
3631 {
3632 GSList *list, *elt;
3633 size_t len;
3634
3635 if (nb_args != 2) {
3636 return;
3637 }
3638
3639 len = strlen(str);
3640 readline_set_completion_index(rs, len);
3641 list = elt = object_class_get_list(TYPE_DEVICE, false);
3642 while (elt) {
3643 const char *name;
3644 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3645 TYPE_DEVICE);
3646 name = object_class_get_name(OBJECT_CLASS(dc));
3647
3648 if (dc->user_creatable
3649 && !strncmp(name, str, len)) {
3650 readline_add_completion(rs, name);
3651 }
3652 elt = elt->next;
3653 }
3654 g_slist_free(list);
3655 }
3656
3657 void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
3658 {
3659 GSList *list, *elt;
3660 size_t len;
3661
3662 if (nb_args != 2) {
3663 return;
3664 }
3665
3666 len = strlen(str);
3667 readline_set_completion_index(rs, len);
3668 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3669 while (elt) {
3670 const char *name;
3671
3672 name = object_class_get_name(OBJECT_CLASS(elt->data));
3673 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3674 readline_add_completion(rs, name);
3675 }
3676 elt = elt->next;
3677 }
3678 g_slist_free(list);
3679 }
3680
3681 static void peripheral_device_del_completion(ReadLineState *rs,
3682 const char *str, size_t len)
3683 {
3684 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3685 GSList *list, *item;
3686
3687 list = qdev_build_hotpluggable_device_list(peripheral);
3688 if (!list) {
3689 return;
3690 }
3691
3692 for (item = list; item; item = g_slist_next(item)) {
3693 DeviceState *dev = item->data;
3694
3695 if (dev->id && !strncmp(str, dev->id, len)) {
3696 readline_add_completion(rs, dev->id);
3697 }
3698 }
3699
3700 g_slist_free(list);
3701 }
3702
3703 void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3704 {
3705 size_t len;
3706 ChardevInfoList *list, *start;
3707
3708 if (nb_args != 2) {
3709 return;
3710 }
3711 len = strlen(str);
3712 readline_set_completion_index(rs, len);
3713
3714 start = list = qmp_query_chardev(NULL);
3715 while (list) {
3716 ChardevInfo *chr = list->value;
3717
3718 if (!strncmp(chr->label, str, len)) {
3719 readline_add_completion(rs, chr->label);
3720 }
3721 list = list->next;
3722 }
3723 qapi_free_ChardevInfoList(start);
3724 }
3725
3726 static void ringbuf_completion(ReadLineState *rs, const char *str)
3727 {
3728 size_t len;
3729 ChardevInfoList *list, *start;
3730
3731 len = strlen(str);
3732 readline_set_completion_index(rs, len);
3733
3734 start = list = qmp_query_chardev(NULL);
3735 while (list) {
3736 ChardevInfo *chr_info = list->value;
3737
3738 if (!strncmp(chr_info->label, str, len)) {
3739 Chardev *chr = qemu_chr_find(chr_info->label);
3740 if (chr && CHARDEV_IS_RINGBUF(chr)) {
3741 readline_add_completion(rs, chr_info->label);
3742 }
3743 }
3744 list = list->next;
3745 }
3746 qapi_free_ChardevInfoList(start);
3747 }
3748
3749 void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3750 {
3751 if (nb_args != 2) {
3752 return;
3753 }
3754 ringbuf_completion(rs, str);
3755 }
3756
3757 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3758 {
3759 size_t len;
3760
3761 if (nb_args != 2) {
3762 return;
3763 }
3764
3765 len = strlen(str);
3766 readline_set_completion_index(rs, len);
3767 peripheral_device_del_completion(rs, str, len);
3768 }
3769
3770 void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
3771 {
3772 ObjectPropertyInfoList *list, *start;
3773 size_t len;
3774
3775 if (nb_args != 2) {
3776 return;
3777 }
3778 len = strlen(str);
3779 readline_set_completion_index(rs, len);
3780
3781 start = list = qmp_qom_list("/objects", NULL);
3782 while (list) {
3783 ObjectPropertyInfo *info = list->value;
3784
3785 if (!strncmp(info->type, "child<", 5)
3786 && !strncmp(info->name, str, len)) {
3787 readline_add_completion(rs, info->name);
3788 }
3789 list = list->next;
3790 }
3791 qapi_free_ObjectPropertyInfoList(start);
3792 }
3793
3794 void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3795 {
3796 int i;
3797 char *sep;
3798 size_t len;
3799
3800 if (nb_args != 2) {
3801 return;
3802 }
3803 sep = strrchr(str, '-');
3804 if (sep) {
3805 str = sep + 1;
3806 }
3807 len = strlen(str);
3808 readline_set_completion_index(rs, len);
3809 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
3810 if (!strncmp(str, QKeyCode_str(i), len)) {
3811 readline_add_completion(rs, QKeyCode_str(i));
3812 }
3813 }
3814 }
3815
3816 void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3817 {
3818 size_t len;
3819
3820 len = strlen(str);
3821 readline_set_completion_index(rs, len);
3822 if (nb_args == 2) {
3823 NetClientState *ncs[MAX_QUEUE_NUM];
3824 int count, i;
3825 count = qemu_find_net_clients_except(NULL, ncs,
3826 NET_CLIENT_DRIVER_NONE,
3827 MAX_QUEUE_NUM);
3828 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3829 const char *name = ncs[i]->name;
3830 if (!strncmp(str, name, len)) {
3831 readline_add_completion(rs, name);
3832 }
3833 }
3834 } else if (nb_args == 3) {
3835 add_completion_option(rs, str, "on");
3836 add_completion_option(rs, str, "off");
3837 }
3838 }
3839
3840 void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3841 {
3842 int len, count, i;
3843 NetClientState *ncs[MAX_QUEUE_NUM];
3844
3845 if (nb_args != 2) {
3846 return;
3847 }
3848
3849 len = strlen(str);
3850 readline_set_completion_index(rs, len);
3851 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
3852 MAX_QUEUE_NUM);
3853 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
3854 QemuOpts *opts;
3855 const char *name = ncs[i]->name;
3856 if (strncmp(str, name, len)) {
3857 continue;
3858 }
3859 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3860 if (opts) {
3861 readline_add_completion(rs, name);
3862 }
3863 }
3864 }
3865
3866 void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3867 {
3868 size_t len;
3869
3870 len = strlen(str);
3871 readline_set_completion_index(rs, len);
3872 if (nb_args == 2) {
3873 TraceEventIter iter;
3874 TraceEvent *ev;
3875 char *pattern = g_strdup_printf("%s*", str);
3876 trace_event_iter_init(&iter, pattern);
3877 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3878 readline_add_completion(rs, trace_event_get_name(ev));
3879 }
3880 g_free(pattern);
3881 }
3882 }
3883
3884 void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3885 {
3886 size_t len;
3887
3888 len = strlen(str);
3889 readline_set_completion_index(rs, len);
3890 if (nb_args == 2) {
3891 TraceEventIter iter;
3892 TraceEvent *ev;
3893 char *pattern = g_strdup_printf("%s*", str);
3894 trace_event_iter_init(&iter, pattern);
3895 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3896 readline_add_completion(rs, trace_event_get_name(ev));
3897 }
3898 g_free(pattern);
3899 } else if (nb_args == 3) {
3900 add_completion_option(rs, str, "on");
3901 add_completion_option(rs, str, "off");
3902 }
3903 }
3904
3905 void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3906 {
3907 int i;
3908
3909 if (nb_args != 2) {
3910 return;
3911 }
3912 readline_set_completion_index(rs, strlen(str));
3913 for (i = 0; i < WATCHDOG_ACTION__MAX; i++) {
3914 add_completion_option(rs, str, WatchdogAction_str(i));
3915 }
3916 }
3917
3918 void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3919 const char *str)
3920 {
3921 size_t len;
3922
3923 len = strlen(str);
3924 readline_set_completion_index(rs, len);
3925 if (nb_args == 2) {
3926 int i;
3927 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3928 const char *name = MigrationCapability_str(i);
3929 if (!strncmp(str, name, len)) {
3930 readline_add_completion(rs, name);
3931 }
3932 }
3933 } else if (nb_args == 3) {
3934 add_completion_option(rs, str, "on");
3935 add_completion_option(rs, str, "off");
3936 }
3937 }
3938
3939 void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3940 const char *str)
3941 {
3942 size_t len;
3943
3944 len = strlen(str);
3945 readline_set_completion_index(rs, len);
3946 if (nb_args == 2) {
3947 int i;
3948 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
3949 const char *name = MigrationParameter_str(i);
3950 if (!strncmp(str, name, len)) {
3951 readline_add_completion(rs, name);
3952 }
3953 }
3954 }
3955 }
3956
3957 static void vm_completion(ReadLineState *rs, const char *str)
3958 {
3959 size_t len;
3960 BlockDriverState *bs;
3961 BdrvNextIterator it;
3962
3963 len = strlen(str);
3964 readline_set_completion_index(rs, len);
3965
3966 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3967 SnapshotInfoList *snapshots, *snapshot;
3968 AioContext *ctx = bdrv_get_aio_context(bs);
3969 bool ok = false;
3970
3971 aio_context_acquire(ctx);
3972 if (bdrv_can_snapshot(bs)) {
3973 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
3974 }
3975 aio_context_release(ctx);
3976 if (!ok) {
3977 continue;
3978 }
3979
3980 snapshot = snapshots;
3981 while (snapshot) {
3982 char *completion = snapshot->value->name;
3983 if (!strncmp(str, completion, len)) {
3984 readline_add_completion(rs, completion);
3985 }
3986 completion = snapshot->value->id;
3987 if (!strncmp(str, completion, len)) {
3988 readline_add_completion(rs, completion);
3989 }
3990 snapshot = snapshot->next;
3991 }
3992 qapi_free_SnapshotInfoList(snapshots);
3993 }
3994
3995 }
3996
3997 void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3998 {
3999 if (nb_args == 2) {
4000 vm_completion(rs, str);
4001 }
4002 }
4003
4004 void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
4005 {
4006 if (nb_args == 2) {
4007 vm_completion(rs, str);
4008 }
4009 }
4010
4011 static void monitor_find_completion_by_table(Monitor *mon,
4012 const mon_cmd_t *cmd_table,
4013 char **args,
4014 int nb_args)
4015 {
4016 const char *cmdname;
4017 int i;
4018 const char *ptype, *old_ptype, *str, *name;
4019 const mon_cmd_t *cmd;
4020 BlockBackend *blk = NULL;
4021
4022 if (nb_args <= 1) {
4023 /* command completion */
4024 if (nb_args == 0)
4025 cmdname = "";
4026 else
4027 cmdname = args[0];
4028 readline_set_completion_index(mon->rs, strlen(cmdname));
4029 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4030 if (!runstate_check(RUN_STATE_PRECONFIG) ||
4031 cmd_can_preconfig(cmd)) {
4032 cmd_completion(mon, cmdname, cmd->name);
4033 }
4034 }
4035 } else {
4036 /* find the command */
4037 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
4038 if (compare_cmd(args[0], cmd->name) &&
4039 (!runstate_check(RUN_STATE_PRECONFIG) ||
4040 cmd_can_preconfig(cmd))) {
4041 break;
4042 }
4043 }
4044 if (!cmd->name) {
4045 return;
4046 }
4047
4048 if (cmd->sub_table) {
4049 /* do the job again */
4050 monitor_find_completion_by_table(mon, cmd->sub_table,
4051 &args[1], nb_args - 1);
4052 return;
4053 }
4054 if (cmd->command_completion) {
4055 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
4056 return;
4057 }
4058
4059 ptype = next_arg_type(cmd->args_type);
4060 for(i = 0; i < nb_args - 2; i++) {
4061 if (*ptype != '\0') {
4062 ptype = next_arg_type(ptype);
4063 while (*ptype == '?')
4064 ptype = next_arg_type(ptype);
4065 }
4066 }
4067 str = args[nb_args - 1];
4068 old_ptype = NULL;
4069 while (*ptype == '-' && old_ptype != ptype) {
4070 old_ptype = ptype;
4071 ptype = next_arg_type(ptype);
4072 }
4073 switch(*ptype) {
4074 case 'F':
4075 /* file completion */
4076 readline_set_completion_index(mon->rs, strlen(str));
4077 file_completion(mon, str);
4078 break;
4079 case 'B':
4080 /* block device name completion */
4081 readline_set_completion_index(mon->rs, strlen(str));
4082 while ((blk = blk_next(blk)) != NULL) {
4083 name = blk_name(blk);
4084 if (str[0] == '\0' ||
4085 !strncmp(name, str, strlen(str))) {
4086 readline_add_completion(mon->rs, name);
4087 }
4088 }
4089 break;
4090 case 's':
4091 case 'S':
4092 if (!strcmp(cmd->name, "help|?")) {
4093 monitor_find_completion_by_table(mon, cmd_table,
4094 &args[1], nb_args - 1);
4095 }
4096 break;
4097 default:
4098 break;
4099 }
4100 }
4101 }
4102
4103 static void monitor_find_completion(void *opaque,
4104 const char *cmdline)
4105 {
4106 Monitor *mon = opaque;
4107 char *args[MAX_ARGS];
4108 int nb_args, len;
4109
4110 /* 1. parse the cmdline */
4111 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
4112 return;
4113 }
4114
4115 /* if the line ends with a space, it means we want to complete the
4116 next arg */
4117 len = strlen(cmdline);
4118 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4119 if (nb_args >= MAX_ARGS) {
4120 goto cleanup;
4121 }
4122 args[nb_args++] = g_strdup("");
4123 }
4124
4125 /* 2. auto complete according to args */
4126 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
4127
4128 cleanup:
4129 free_cmdline_args(args, nb_args);
4130 }
4131
4132 static int monitor_can_read(void *opaque)
4133 {
4134 Monitor *mon = opaque;
4135
4136 return !atomic_mb_read(&mon->suspend_cnt);
4137 }
4138
4139 /*
4140 * 1. This function takes ownership of rsp, err, and id.
4141 * 2. rsp, err, and id may be NULL.
4142 * 3. If err != NULL then rsp must be NULL.
4143 */
4144 static void monitor_qmp_respond(Monitor *mon, QObject *rsp,
4145 Error *err, QObject *id)
4146 {
4147 QDict *qdict = NULL;
4148
4149 if (err) {
4150 assert(!rsp);
4151 qdict = qdict_new();
4152 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
4153 error_free(err);
4154 rsp = QOBJECT(qdict);
4155 }
4156
4157 if (rsp) {
4158 if (id) {
4159 qdict_put_obj(qobject_to(QDict, rsp), "id", qobject_ref(id));
4160 }
4161
4162 monitor_json_emitter(mon, rsp);
4163 }
4164
4165 qobject_unref(id);
4166 qobject_unref(rsp);
4167 }
4168
4169 /*
4170 * Dispatch one single QMP request. The function will free the req_obj
4171 * and objects inside it before return.
4172 */
4173 static void monitor_qmp_dispatch_one(QMPRequest *req_obj)
4174 {
4175 Monitor *mon, *old_mon;
4176 QObject *req, *rsp = NULL, *id;
4177 bool need_resume;
4178
4179 req = req_obj->req;
4180 mon = req_obj->mon;
4181 id = req_obj->id;
4182 need_resume = req_obj->need_resume;
4183
4184 g_free(req_obj);
4185
4186 if (trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
4187 QString *req_json = qobject_to_json(req);
4188 trace_handle_qmp_command(mon, qstring_get_str(req_json));
4189 qobject_unref(req_json);
4190 }
4191
4192 old_mon = cur_mon;
4193 cur_mon = mon;
4194
4195 rsp = qmp_dispatch(mon->qmp.commands, req);
4196
4197 cur_mon = old_mon;
4198
4199 /* Respond if necessary */
4200 monitor_qmp_respond(mon, rsp, NULL, id);
4201
4202 /* This pairs with the monitor_suspend() in handle_qmp_command(). */
4203 if (need_resume) {
4204 monitor_resume(mon);
4205 }
4206
4207 qobject_unref(req);
4208 }
4209
4210 /*
4211 * Pop one QMP request from monitor queues, return NULL if not found.
4212 * We are using round-robin fashion to pop the request, to avoid
4213 * processing commands only on a very busy monitor. To achieve that,
4214 * when we process one request on a specific monitor, we put that
4215 * monitor to the end of mon_list queue.
4216 */
4217 static QMPRequest *monitor_qmp_requests_pop_any(void)
4218 {
4219 QMPRequest *req_obj = NULL;
4220 Monitor *mon;
4221
4222 qemu_mutex_lock(&monitor_lock);
4223
4224 QTAILQ_FOREACH(mon, &mon_list, entry) {
4225 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
4226 req_obj = g_queue_pop_head(mon->qmp.qmp_requests);
4227 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
4228 if (req_obj) {
4229 break;
4230 }
4231 }
4232
4233 if (req_obj) {
4234 /*
4235 * We found one request on the monitor. Degrade this monitor's
4236 * priority to lowest by re-inserting it to end of queue.
4237 */
4238 QTAILQ_REMOVE(&mon_list, mon, entry);
4239 QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
4240 }
4241
4242 qemu_mutex_unlock(&monitor_lock);
4243
4244 return req_obj;
4245 }
4246
4247 static void monitor_qmp_bh_dispatcher(void *data)
4248 {
4249 QMPRequest *req_obj = monitor_qmp_requests_pop_any();
4250
4251 if (req_obj) {
4252 trace_monitor_qmp_cmd_in_band(qobject_get_try_str(req_obj->id) ?: "");
4253 monitor_qmp_dispatch_one(req_obj);
4254 /* Reschedule instead of looping so the main loop stays responsive */
4255 qemu_bh_schedule(mon_global.qmp_dispatcher_bh);
4256 }
4257 }
4258
4259 #define QMP_REQ_QUEUE_LEN_MAX (8)
4260
4261 static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
4262 {
4263 QObject *req, *id = NULL;
4264 QDict *qdict = NULL;
4265 MonitorQMP *mon_qmp = container_of(parser, MonitorQMP, parser);
4266 Monitor *mon = container_of(mon_qmp, Monitor, qmp);
4267 Error *err = NULL;
4268 QMPRequest *req_obj;
4269
4270 req = json_parser_parse_err(tokens, NULL, &err);
4271 if (!req && !err) {
4272 /* json_parser_parse_err() sucks: can fail without setting @err */
4273 error_setg(&err, QERR_JSON_PARSING);
4274 }
4275 if (err) {
4276 goto err;
4277 }
4278
4279 /* Check against the request in general layout */
4280 qdict = qmp_dispatch_check_obj(req, &err);
4281 if (!qdict) {
4282 goto err;
4283 }
4284
4285 /* Check against OOB specific */
4286 if (!qmp_cmd_oob_check(mon, qdict, &err)) {
4287 goto err;
4288 }
4289
4290 id = qdict_get(qdict, "id");
4291
4292 /* When OOB is enabled, the "id" field is mandatory. */
4293 if (qmp_oob_enabled(mon) && !id) {
4294 error_setg(&err, "Out-Of-Band capability requires that "
4295 "every command contains an 'id' field");
4296 goto err;
4297 }
4298
4299 req_obj = g_new0(QMPRequest, 1);
4300 req_obj->mon = mon;
4301 req_obj->id = qobject_ref(id);
4302 req_obj->req = req;
4303 req_obj->need_resume = false;
4304
4305 qdict_del(qdict, "id");
4306
4307 if (qmp_is_oob(qdict)) {
4308 /* Out-Of-Band (OOB) requests are executed directly in parser. */
4309 trace_monitor_qmp_cmd_out_of_band(qobject_get_try_str(req_obj->id)
4310 ?: "");
4311 monitor_qmp_dispatch_one(req_obj);
4312 return;
4313 }
4314
4315 /* Protect qmp_requests and fetching its length. */
4316 qemu_mutex_lock(&mon->qmp.qmp_queue_lock);
4317
4318 /*
4319 * If OOB is not enabled on the current monitor, we'll emulate the
4320 * old behavior that we won't process the current monitor any more
4321 * until it has responded. This helps make sure that as long as
4322 * OOB is not enabled, the server will never drop any command.
4323 */
4324 if (!qmp_oob_enabled(mon)) {
4325 monitor_suspend(mon);
4326 req_obj->need_resume = true;
4327 } else {
4328 /* Drop the request if queue is full. */
4329 if (mon->qmp.qmp_requests->length >= QMP_REQ_QUEUE_LEN_MAX) {
4330 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
4331 qapi_event_send_command_dropped(id,
4332 COMMAND_DROP_REASON_QUEUE_FULL,
4333 &error_abort);
4334 qmp_request_free(req_obj);
4335 return;
4336 }
4337 }
4338
4339 /*
4340 * Put the request to the end of queue so that requests will be
4341 * handled in time order. Ownership for req_obj, req, id,
4342 * etc. will be delivered to the handler side.
4343 */
4344 g_queue_push_tail(mon->qmp.qmp_requests, req_obj);
4345 qemu_mutex_unlock(&mon->qmp.qmp_queue_lock);
4346
4347 /* Kick the dispatcher routine */
4348 qemu_bh_schedule(mon_global.qmp_dispatcher_bh);
4349 return;
4350
4351 err:
4352 monitor_qmp_respond(mon, NULL, err, NULL);
4353 qobject_unref(req);
4354 }
4355
4356 static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
4357 {
4358 Monitor *mon = opaque;
4359
4360 json_message_parser_feed(&mon->qmp.parser, (const char *) buf, size);
4361 }
4362
4363 static void monitor_read(void *opaque, const uint8_t *buf, int size)
4364 {
4365 Monitor *old_mon = cur_mon;
4366 int i;
4367
4368 cur_mon = opaque;
4369
4370 if (cur_mon->rs) {
4371 for (i = 0; i < size; i++)
4372 readline_handle_byte(cur_mon->rs, buf[i]);
4373 } else {
4374 if (size == 0 || buf[size - 1] != 0)
4375 monitor_printf(cur_mon, "corrupted command\n");
4376 else
4377 handle_hmp_command(cur_mon, (char *)buf);
4378 }
4379
4380 cur_mon = old_mon;
4381 }
4382
4383 static void monitor_command_cb(void *opaque, const char *cmdline,
4384 void *readline_opaque)
4385 {
4386 Monitor *mon = opaque;
4387
4388 monitor_suspend(mon);
4389 handle_hmp_command(mon, cmdline);
4390 monitor_resume(mon);
4391 }
4392
4393 int monitor_suspend(Monitor *mon)
4394 {
4395 if (monitor_is_hmp_non_interactive(mon)) {
4396 return -ENOTTY;
4397 }
4398
4399 atomic_inc(&mon->suspend_cnt);
4400
4401 if (monitor_is_qmp(mon)) {
4402 /*
4403 * Kick iothread to make sure this takes effect. It'll be
4404 * evaluated again in prepare() of the watch object.
4405 */
4406 aio_notify(iothread_get_aio_context(mon_global.mon_iothread));
4407 }
4408
4409 trace_monitor_suspend(mon, 1);
4410 return 0;
4411 }
4412
4413 void monitor_resume(Monitor *mon)
4414 {
4415 if (monitor_is_hmp_non_interactive(mon)) {
4416 return;
4417 }
4418
4419 if (atomic_dec_fetch(&mon->suspend_cnt) == 0) {
4420 if (monitor_is_qmp(mon)) {
4421 /*
4422 * For QMP monitors that are running in IOThread, let's
4423 * kick the thread in case it's sleeping.
4424 */
4425 if (mon->use_io_thr) {
4426 aio_notify(iothread_get_aio_context(mon_global.mon_iothread));
4427 }
4428 } else {
4429 assert(mon->rs);
4430 readline_show_prompt(mon->rs);
4431 }
4432 }
4433 trace_monitor_suspend(mon, -1);
4434 }
4435
4436 static QObject *get_qmp_greeting(Monitor *mon)
4437 {
4438 QList *cap_list = qlist_new();
4439 QObject *ver = NULL;
4440 QMPCapability cap;
4441
4442 qmp_marshal_query_version(NULL, &ver, NULL);
4443
4444 for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
4445 if (!mon->use_io_thr && cap == QMP_CAPABILITY_OOB) {
4446 /* Monitors that are not using IOThread won't support OOB */
4447 continue;
4448 }
4449 qlist_append_str(cap_list, QMPCapability_str(cap));
4450 }
4451
4452 return qobject_from_jsonf("{'QMP': {'version': %p, 'capabilities': %p}}",
4453 ver, cap_list);
4454 }
4455
4456 static void monitor_qmp_caps_reset(Monitor *mon)
4457 {
4458 memset(mon->qmp.qmp_caps, 0, sizeof(mon->qmp.qmp_caps));
4459 }
4460
4461 static void monitor_qmp_event(void *opaque, int event)
4462 {
4463 QObject *data;
4464 Monitor *mon = opaque;
4465
4466 switch (event) {
4467 case CHR_EVENT_OPENED:
4468 mon->qmp.commands = &qmp_cap_negotiation_commands;
4469 monitor_qmp_caps_reset(mon);
4470 data = get_qmp_greeting(mon);
4471 monitor_json_emitter(mon, data);
4472 qobject_unref(data);
4473 mon_refcount++;
4474 break;
4475 case CHR_EVENT_CLOSED:
4476 /*
4477 * Note: this is only useful when the output of the chardev
4478 * backend is still open. For example, when the backend is
4479 * stdio, it's possible that stdout is still open when stdin
4480 * is closed.
4481 */
4482 monitor_qmp_response_flush(mon);
4483 monitor_qmp_cleanup_queues(mon);
4484 json_message_parser_destroy(&mon->qmp.parser);
4485 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4486 mon_refcount--;
4487 monitor_fdsets_cleanup();
4488 break;
4489 }
4490 }
4491
4492 static void monitor_event(void *opaque, int event)
4493 {
4494 Monitor *mon = opaque;
4495
4496 switch (event) {
4497 case CHR_EVENT_MUX_IN:
4498 qemu_mutex_lock(&mon->mon_lock);
4499 mon->mux_out = 0;
4500 qemu_mutex_unlock(&mon->mon_lock);
4501 if (mon->reset_seen) {
4502 readline_restart(mon->rs);
4503 monitor_resume(mon);
4504 monitor_flush(mon);
4505 } else {
4506 atomic_mb_set(&mon->suspend_cnt, 0);
4507 }
4508 break;
4509
4510 case CHR_EVENT_MUX_OUT:
4511 if (mon->reset_seen) {
4512 if (atomic_mb_read(&mon->suspend_cnt) == 0) {
4513 monitor_printf(mon, "\n");
4514 }
4515 monitor_flush(mon);
4516 monitor_suspend(mon);
4517 } else {
4518 atomic_inc(&mon->suspend_cnt);
4519 }
4520 qemu_mutex_lock(&mon->mon_lock);
4521 mon->mux_out = 1;
4522 qemu_mutex_unlock(&mon->mon_lock);
4523 break;
4524
4525 case CHR_EVENT_OPENED:
4526 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4527 "information\n", QEMU_VERSION);
4528 if (!mon->mux_out) {
4529 readline_restart(mon->rs);
4530 readline_show_prompt(mon->rs);
4531 }
4532 mon->reset_seen = 1;
4533 mon_refcount++;
4534 break;
4535
4536 case CHR_EVENT_CLOSED:
4537 mon_refcount--;
4538 monitor_fdsets_cleanup();
4539 break;
4540 }
4541 }
4542
4543 static int
4544 compare_mon_cmd(const void *a, const void *b)
4545 {
4546 return strcmp(((const mon_cmd_t *)a)->name,
4547 ((const mon_cmd_t *)b)->name);
4548 }
4549
4550 static void sortcmdlist(void)
4551 {
4552 int array_num;
4553 int elem_size = sizeof(mon_cmd_t);
4554
4555 array_num = sizeof(mon_cmds)/elem_size-1;
4556 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
4557
4558 array_num = sizeof(info_cmds)/elem_size-1;
4559 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
4560 }
4561
4562 static GMainContext *monitor_get_io_context(void)
4563 {
4564 return iothread_get_g_main_context(mon_global.mon_iothread);
4565 }
4566
4567 static AioContext *monitor_get_aio_context(void)
4568 {
4569 return iothread_get_aio_context(mon_global.mon_iothread);
4570 }
4571
4572 static void monitor_iothread_init(void)
4573 {
4574 mon_global.mon_iothread = iothread_create("mon_iothread",
4575 &error_abort);
4576
4577 /*
4578 * This MUST be on main loop thread since we have commands that
4579 * have assumption to be run on main loop thread. It would be
4580 * nice that one day we can remove this assumption in the future.
4581 */
4582 mon_global.qmp_dispatcher_bh = aio_bh_new(iohandler_get_aio_context(),
4583 monitor_qmp_bh_dispatcher,
4584 NULL);
4585
4586 /*
4587 * Unlike the dispatcher BH, this must be run on the monitor IO
4588 * thread, so that monitors that are using IO thread will make
4589 * sure read/write operations are all done on the IO thread.
4590 */
4591 mon_global.qmp_respond_bh = aio_bh_new(monitor_get_aio_context(),
4592 monitor_qmp_bh_responder,
4593 NULL);
4594 }
4595
4596 void monitor_init_globals(void)
4597 {
4598 monitor_init_qmp_commands();
4599 monitor_qapi_event_init();
4600 sortcmdlist();
4601 qemu_mutex_init(&monitor_lock);
4602 qemu_mutex_init(&mon_fdsets_lock);
4603 monitor_iothread_init();
4604 }
4605
4606 /* These functions just adapt the readline interface in a typesafe way. We
4607 * could cast function pointers but that discards compiler checks.
4608 */
4609 static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
4610 const char *fmt, ...)
4611 {
4612 va_list ap;
4613 va_start(ap, fmt);
4614 monitor_vprintf(opaque, fmt, ap);
4615 va_end(ap);
4616 }
4617
4618 static void monitor_readline_flush(void *opaque)
4619 {
4620 monitor_flush(opaque);
4621 }
4622
4623 /*
4624 * Print to current monitor if we have one, else to stderr.
4625 * TODO should return int, so callers can calculate width, but that
4626 * requires surgery to monitor_vprintf(). Left for another day.
4627 */
4628 void error_vprintf(const char *fmt, va_list ap)
4629 {
4630 if (cur_mon && !monitor_cur_is_qmp()) {
4631 monitor_vprintf(cur_mon, fmt, ap);
4632 } else {
4633 vfprintf(stderr, fmt, ap);
4634 }
4635 }
4636
4637 void error_vprintf_unless_qmp(const char *fmt, va_list ap)
4638 {
4639 if (cur_mon && !monitor_cur_is_qmp()) {
4640 monitor_vprintf(cur_mon, fmt, ap);
4641 } else if (!cur_mon) {
4642 vfprintf(stderr, fmt, ap);
4643 }
4644 }
4645
4646 static void monitor_list_append(Monitor *mon)
4647 {
4648 qemu_mutex_lock(&monitor_lock);
4649 QTAILQ_INSERT_HEAD(&mon_list, mon, entry);
4650 qemu_mutex_unlock(&monitor_lock);
4651 }
4652
4653 static void monitor_qmp_setup_handlers_bh(void *opaque)
4654 {
4655 Monitor *mon = opaque;
4656 GMainContext *context;
4657
4658 if (mon->use_io_thr) {
4659 /*
4660 * When use_io_thr is set, we use the global shared dedicated
4661 * IO thread for this monitor to handle input/output.
4662 */
4663 context = monitor_get_io_context();
4664 /* We should have inited globals before reaching here. */
4665 assert(context);
4666 } else {
4667 /* The default main loop, which is the main thread */
4668 context = NULL;
4669 }
4670
4671 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
4672 monitor_qmp_event, NULL, mon, context, true);
4673 monitor_list_append(mon);
4674 }
4675
4676 void monitor_init(Chardev *chr, int flags)
4677 {
4678 Monitor *mon = g_malloc(sizeof(*mon));
4679 bool use_readline = flags & MONITOR_USE_READLINE;
4680 bool use_oob = flags & MONITOR_USE_OOB;
4681
4682 if (use_oob) {
4683 if (CHARDEV_IS_MUX(chr)) {
4684 error_report("Monitor Out-Of-Band is not supported with "
4685 "MUX typed chardev backend");
4686 exit(1);
4687 }
4688 if (use_readline) {
4689 error_report("Monitor Out-Of-band is only supported by QMP");
4690 exit(1);
4691 }
4692 }
4693
4694 monitor_data_init(mon, false, use_oob);
4695
4696 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
4697 mon->flags = flags;
4698 if (use_readline) {
4699 mon->rs = readline_init(monitor_readline_printf,
4700 monitor_readline_flush,
4701 mon,
4702 monitor_find_completion);
4703 monitor_read_command(mon, 0);
4704 }
4705
4706 if (monitor_is_qmp(mon)) {
4707 qemu_chr_fe_set_echo(&mon->chr, true);
4708 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
4709 if (mon->use_io_thr) {
4710 /*
4711 * Make sure the old iowatch is gone. It's possible when
4712 * e.g. the chardev is in client mode, with wait=on.
4713 */
4714 remove_fd_in_watch(chr);
4715 /*
4716 * We can't call qemu_chr_fe_set_handlers() directly here
4717 * since during the procedure the chardev will be active
4718 * and running in monitor iothread, while we'll still do
4719 * something before returning from it, which is a possible
4720 * race too. To avoid that, we just create a BH to setup
4721 * the handlers.
4722 */
4723 aio_bh_schedule_oneshot(monitor_get_aio_context(),
4724 monitor_qmp_setup_handlers_bh, mon);
4725 /* We'll add this to mon_list in the BH when setup done */
4726 return;
4727 } else {
4728 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read,
4729 monitor_qmp_read, monitor_qmp_event,
4730 NULL, mon, NULL, true);
4731 }
4732 } else {
4733 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
4734 monitor_event, NULL, mon, NULL, true);
4735 }
4736
4737 monitor_list_append(mon);
4738 }
4739
4740 void monitor_cleanup(void)
4741 {
4742 Monitor *mon, *next;
4743
4744 /*
4745 * We need to explicitly stop the iothread (but not destroy it),
4746 * cleanup the monitor resources, then destroy the iothread since
4747 * we need to unregister from chardev below in
4748 * monitor_data_destroy(), and chardev is not thread-safe yet
4749 */
4750 iothread_stop(mon_global.mon_iothread);
4751
4752 /*
4753 * After we have IOThread to send responses, it's possible that
4754 * when we stop the IOThread there are still replies queued in the
4755 * responder queue. Flush all of them. Note that even after this
4756 * flush it's still possible that out buffer is not flushed.
4757 * It'll be done in below monitor_flush() as the last resort.
4758 */
4759 monitor_qmp_bh_responder(NULL);
4760
4761 qemu_mutex_lock(&monitor_lock);
4762 QTAILQ_FOREACH_SAFE(mon, &mon_list, entry, next) {
4763 QTAILQ_REMOVE(&mon_list, mon, entry);
4764 monitor_flush(mon);
4765 monitor_data_destroy(mon);
4766 g_free(mon);
4767 }
4768 qemu_mutex_unlock(&monitor_lock);
4769
4770 /* QEMUBHs needs to be deleted before destroying the IOThread. */
4771 qemu_bh_delete(mon_global.qmp_dispatcher_bh);
4772 mon_global.qmp_dispatcher_bh = NULL;
4773 qemu_bh_delete(mon_global.qmp_respond_bh);
4774 mon_global.qmp_respond_bh = NULL;
4775
4776 iothread_destroy(mon_global.mon_iothread);
4777 mon_global.mon_iothread = NULL;
4778 }
4779
4780 QemuOptsList qemu_mon_opts = {
4781 .name = "mon",
4782 .implied_opt_name = "chardev",
4783 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4784 .desc = {
4785 {
4786 .name = "mode",
4787 .type = QEMU_OPT_STRING,
4788 },{
4789 .name = "chardev",
4790 .type = QEMU_OPT_STRING,
4791 },{
4792 .name = "pretty",
4793 .type = QEMU_OPT_BOOL,
4794 },{
4795 .name = "x-oob",
4796 .type = QEMU_OPT_BOOL,
4797 },
4798 { /* end of list */ }
4799 },
4800 };
4801
4802 #ifndef TARGET_I386
4803 void qmp_rtc_reset_reinjection(Error **errp)
4804 {
4805 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
4806 }
4807
4808 SevInfo *qmp_query_sev(Error **errp)
4809 {
4810 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev");
4811 return NULL;
4812 }
4813
4814 SevLaunchMeasureInfo *qmp_query_sev_launch_measure(Error **errp)
4815 {
4816 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev-launch-measure");
4817 return NULL;
4818 }
4819
4820 SevCapability *qmp_query_sev_capabilities(Error **errp)
4821 {
4822 error_setg(errp, QERR_FEATURE_DISABLED, "query-sev-capabilities");
4823 return NULL;
4824 }
4825 #endif
4826
4827 #ifndef TARGET_S390X
4828 void qmp_dump_skeys(const char *filename, Error **errp)
4829 {
4830 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4831 }
4832 #endif
4833
4834 #ifndef TARGET_ARM
4835 GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4836 {
4837 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4838 return NULL;
4839 }
4840 #endif
4841
4842 HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4843 {
4844 MachineState *ms = MACHINE(qdev_get_machine());
4845 MachineClass *mc = MACHINE_GET_CLASS(ms);
4846
4847 if (!mc->has_hotpluggable_cpus) {
4848 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4849 return NULL;
4850 }
4851
4852 return machine_query_hotpluggable_cpus(ms);
4853 }