]> git.proxmox.com Git - mirror_qemu.git/blame - monitor.c
ppc: implement xsrqpxp instruction
[mirror_qemu.git] / monitor.c
CommitLineData
9dc39cba
FB
1/*
2 * QEMU monitor
5fafdf24 3 *
9dc39cba 4 * Copyright (c) 2003-2004 Fabrice Bellard
5fafdf24 5 *
9dc39cba
FB
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 */
d38ea87a 24#include "qemu/osdep.h"
511d2b14 25#include <dirent.h>
33c11879
PB
26#include "qemu-common.h"
27#include "cpu.h"
87ecb68b 28#include "hw/hw.h"
b4a42f81 29#include "monitor/qdev.h"
87ecb68b 30#include "hw/usb.h"
0d09e41a 31#include "hw/i386/pc.h"
a2cb15b0 32#include "hw/pci/pci.h"
0d09e41a 33#include "sysemu/watchdog.h"
45a50b16 34#include "hw/loader.h"
022c62cb 35#include "exec/gdbstub.h"
1422e32d 36#include "net/net.h"
68ac40d2 37#include "net/slirp.h"
dccfcd0e 38#include "sysemu/char.h"
7572150c 39#include "ui/qemu-spice.h"
9c17d615 40#include "sysemu/sysemu.h"
e35704ba 41#include "sysemu/numa.h"
83c9089e 42#include "monitor/monitor.h"
213dcb06 43#include "qemu/config-file.h"
0150cd81 44#include "qemu/readline.h"
28ecbaee 45#include "ui/console.h"
c751a74a 46#include "ui/input.h"
9c17d615 47#include "sysemu/blockdev.h"
da27a00e 48#include "sysemu/block-backend.h"
87ecb68b 49#include "audio/audio.h"
76cad711 50#include "disas/disas.h"
9c17d615 51#include "sysemu/balloon.h"
1de7afc9 52#include "qemu/timer.h"
caf71f86 53#include "migration/migration.h"
b3946626 54#include "sysemu/hw_accel.h"
1de7afc9 55#include "qemu/acl.h"
bdee56f5 56#include "sysemu/tpm.h"
cc7a8ea7 57#include "qapi/qmp/qerror.h"
c7eb39cb 58#include "qapi/qmp/types.h"
7b1b5d19
PB
59#include "qapi/qmp/qjson.h"
60#include "qapi/qmp/json-streamer.h"
61#include "qapi/qmp/json-parser.h"
a9c94277 62#include "qom/object_interfaces.h"
0ab8ed18 63#include "trace-root.h"
31965ae2 64#include "trace/control.h"
bf957284 65#include "monitor/hmp-target.h"
6d8a764e 66#ifdef CONFIG_TRACE_SIMPLE
31965ae2 67#include "trace/simple.h"
22890ab5 68#endif
022c62cb 69#include "exec/memory.h"
63c91552 70#include "exec/exec-all.h"
03dd024f 71#include "qemu/log.h"
48a32bed
AL
72#include "qmp-commands.h"
73#include "hmp.h"
1de7afc9 74#include "qemu/thread.h"
b21631f3 75#include "block/qapi.h"
43a14cfc
WX
76#include "qapi/qmp-event.h"
77#include "qapi-event.h"
39a18158 78#include "qmp-introspect.h"
dc599978 79#include "sysemu/qtest.h"
f348b6d1 80#include "qemu/cutils.h"
edcfaefe 81#include "qapi/qmp/dispatch.h"
6a5bd307 82
a4538a5c
JH
83#if defined(TARGET_S390X)
84#include "hw/s390x/storage-keys.h"
85#endif
86
9307c4c1
FB
87/*
88 * Supported types:
5fafdf24 89 *
9307c4c1 90 * 'F' filename
81d0912d 91 * 'B' block device name
9307c4c1 92 * 's' string (accept optional quote)
129be006 93 * 'S' it just appends the rest of the string (accept optional quote)
361127df
MA
94 * 'O' option string of the form NAME=VALUE,...
95 * parsed according to QemuOptsList given by its name
96 * Example: 'device:O' uses qemu_device_opts.
97 * Restriction: only lists with empty desc are supported
98 * TODO lift the restriction
92a31b1f
FB
99 * 'i' 32 bit integer
100 * 'l' target long (32 or 64 bit)
91162849
LC
101 * 'M' Non-negative target long (32 or 64 bit), in user mode the
102 * value is multiplied by 2^20 (think Mebibyte)
dbc0c67f 103 * 'o' octets (aka bytes)
5e00984a
KW
104 * user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
105 * K, k suffix, which multiplies the value by 2^60 for suffixes E
106 * and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
107 * 2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
fccfb11e
MA
108 * 'T' double
109 * user mode accepts an optional ms, us, ns suffix,
110 * which divides the value by 1e3, 1e6, 1e9, respectively
9307c4c1
FB
111 * '/' optional gdb-like print format (like "/10x")
112 *
fb46660e
LC
113 * '?' optional type (for all types, except '/')
114 * '.' other form of optional type (for 'i' and 'l')
942cd1f2
MA
115 * 'b' boolean
116 * user mode accepts "on" or "off"
fb46660e 117 * '-' optional parameter (eg. '-f')
9307c4c1
FB
118 *
119 */
120
c227f099 121typedef struct mon_cmd_t {
9dc39cba 122 const char *name;
9307c4c1 123 const char *args_type;
9dc39cba
FB
124 const char *params;
125 const char *help;
2b9e3576
MAL
126 void (*cmd)(Monitor *mon, const QDict *qdict);
127 /* @sub_table is a list of 2nd level of commands. If it does not exist,
128 * cmd should be used. If it exists, sub_table[?].cmd should be
129 * used, and cmd of 1st level plays the role of help function.
5f3d335f
WX
130 */
131 struct mon_cmd_t *sub_table;
bfa40f77 132 void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
c227f099 133} mon_cmd_t;
9dc39cba 134
f07918fd 135/* file descriptors passed via SCM_RIGHTS */
c227f099
AL
136typedef struct mon_fd_t mon_fd_t;
137struct mon_fd_t {
f07918fd
MM
138 char *name;
139 int fd;
c227f099 140 QLIST_ENTRY(mon_fd_t) next;
f07918fd
MM
141};
142
ba1c048a
CB
143/* file descriptor associated with a file descriptor set */
144typedef struct MonFdsetFd MonFdsetFd;
145struct MonFdsetFd {
146 int fd;
147 bool removed;
148 char *opaque;
149 QLIST_ENTRY(MonFdsetFd) next;
150};
151
152/* file descriptor set containing fds passed via SCM_RIGHTS */
153typedef struct MonFdset MonFdset;
154struct MonFdset {
155 int64_t id;
156 QLIST_HEAD(, MonFdsetFd) fds;
adb696f3 157 QLIST_HEAD(, MonFdsetFd) dup_fds;
ba1c048a
CB
158 QLIST_ENTRY(MonFdset) next;
159};
160
74358f2a 161typedef struct {
5fa737a4 162 JSONMessageParser parser;
f994b258
MA
163 /*
164 * When a client connects, we're in capabilities negotiation mode.
165 * When command qmp_capabilities succeeds, we go into command
166 * mode.
167 */
168 bool in_command_mode; /* are we in command mode? */
74358f2a 169} MonitorQMP;
5fa737a4 170
afeecec2
DB
171/*
172 * To prevent flooding clients, events can be throttled. The
173 * throttling is calculated globally, rather than per-Monitor
174 * instance.
175 */
43a14cfc 176typedef struct MonitorQAPIEventState {
7de0be65
MA
177 QAPIEvent event; /* Throttling state for this event type and... */
178 QDict *data; /* ... data, see qapi_event_throttle_equal() */
afeecec2 179 QEMUTimer *timer; /* Timer for handling delayed events */
688b4b7d 180 QDict *qdict; /* Delayed event (if any) */
43a14cfc 181} MonitorQAPIEventState;
afeecec2 182
b9b03ab0
MA
183typedef struct {
184 int64_t rate; /* Minimum time (in ns) between two events */
185} MonitorQAPIEventConf;
186
87127161 187struct Monitor {
32a6ebec 188 CharBackend chr;
a7aec5da 189 int reset_seen;
731b0364
AL
190 int flags;
191 int suspend_cnt;
48c043d0 192 bool skip_flush;
6cff3e85
PB
193
194 QemuMutex out_lock;
e1f2641b 195 QString *outbuf;
6cff3e85
PB
196 guint out_watch;
197
198 /* Read under either BQL or out_lock, written with BQL+out_lock. */
199 int mux_out;
200
731b0364 201 ReadLineState *rs;
74358f2a 202 MonitorQMP qmp;
cb446eca 203 CPUState *mon_cpu;
097310b5 204 BlockCompletionFunc *password_completion_cb;
731b0364 205 void *password_opaque;
7717239d 206 mon_cmd_t *cmd_table;
c227f099 207 QLIST_HEAD(,mon_fd_t) fds;
72cf2d4f 208 QLIST_ENTRY(Monitor) entry;
87127161
AL
209};
210
2dbc8db0
LC
211/* QMP checker flags */
212#define QMP_ACCEPT_UNKNOWNS 1
213
d622cb58
PB
214/* Protects mon_list, monitor_event_state. */
215static QemuMutex monitor_lock;
216
72cf2d4f 217static QLIST_HEAD(mon_list, Monitor) mon_list;
ba1c048a 218static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
efb87c16 219static int mon_refcount;
7e2515e8 220
816f8925
WX
221static mon_cmd_t mon_cmds[];
222static mon_cmd_t info_cmds[];
9dc39cba 223
8631b608 224Monitor *cur_mon;
376253ec 225
dc599978
AG
226static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;
227
c60bf339
SH
228static void monitor_command_cb(void *opaque, const char *cmdline,
229 void *readline_opaque);
83ab7950 230
9f3982f2
MA
231/**
232 * Is @mon a QMP monitor?
233 */
234static inline bool monitor_is_qmp(const Monitor *mon)
418173c7
LC
235{
236 return (mon->flags & MONITOR_USE_CONTROL);
237}
238
489653b5
MA
239/**
240 * Is the current monitor, if any, a QMP monitor?
241 */
242bool monitor_cur_is_qmp(void)
6620d3ce 243{
9f3982f2 244 return cur_mon && monitor_is_qmp(cur_mon);
6620d3ce
MA
245}
246
7060b478 247void monitor_read_command(Monitor *mon, int show_prompt)
731b0364 248{
183e6e52
LC
249 if (!mon->rs)
250 return;
251
731b0364
AL
252 readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
253 if (show_prompt)
254 readline_show_prompt(mon->rs);
255}
6a00d601 256
7060b478
AL
257int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
258 void *opaque)
bb5fc20f 259{
bcf5d19c 260 if (mon->rs) {
cde76ee1
AL
261 readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
262 /* prompt is printed on return from the command handler */
263 return 0;
264 } else {
265 monitor_printf(mon, "terminal does not support password prompting\n");
266 return -ENOTTY;
267 }
bb5fc20f
AL
268}
269
6cff3e85
PB
270static void monitor_flush_locked(Monitor *mon);
271
f628926b
GH
272static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
273 void *opaque)
274{
293d2a00
LE
275 Monitor *mon = opaque;
276
6cff3e85
PB
277 qemu_mutex_lock(&mon->out_lock);
278 mon->out_watch = 0;
279 monitor_flush_locked(mon);
280 qemu_mutex_unlock(&mon->out_lock);
f628926b
GH
281 return FALSE;
282}
283
6cff3e85
PB
284/* Called with mon->out_lock held. */
285static void monitor_flush_locked(Monitor *mon)
7e2515e8 286{
f628926b 287 int rc;
e1f2641b
LC
288 size_t len;
289 const char *buf;
290
48c043d0
LC
291 if (mon->skip_flush) {
292 return;
293 }
294
e1f2641b
LC
295 buf = qstring_get_str(mon->outbuf);
296 len = qstring_get_length(mon->outbuf);
f628926b 297
a4cc73d6 298 if (len && !mon->mux_out) {
5345fdb4 299 rc = qemu_chr_fe_write(&mon->chr, (const uint8_t *) buf, len);
056f49ff
SP
300 if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
301 /* all flushed or error */
e1f2641b
LC
302 QDECREF(mon->outbuf);
303 mon->outbuf = qstring_new();
f628926b
GH
304 return;
305 }
306 if (rc > 0) {
3b7c78c8 307 /* partial write */
e1f2641b
LC
308 QString *tmp = qstring_from_str(buf + rc);
309 QDECREF(mon->outbuf);
310 mon->outbuf = tmp;
f628926b 311 }
6cff3e85 312 if (mon->out_watch == 0) {
32a6ebec 313 mon->out_watch =
5345fdb4 314 qemu_chr_fe_add_watch(&mon->chr, G_IO_OUT | G_IO_HUP,
32a6ebec 315 monitor_unblocked, mon);
293d2a00 316 }
7e2515e8
FB
317 }
318}
319
6cff3e85
PB
320void monitor_flush(Monitor *mon)
321{
322 qemu_mutex_lock(&mon->out_lock);
323 monitor_flush_locked(mon);
324 qemu_mutex_unlock(&mon->out_lock);
325}
326
e1f2641b 327/* flush at every end of line */
376253ec 328static void monitor_puts(Monitor *mon, const char *str)
7e2515e8 329{
60fe76f3 330 char c;
731b0364 331
6cff3e85 332 qemu_mutex_lock(&mon->out_lock);
7e2515e8
FB
333 for(;;) {
334 c = *str++;
335 if (c == '\0')
336 break;
e1f2641b
LC
337 if (c == '\n') {
338 qstring_append_chr(mon->outbuf, '\r');
339 }
340 qstring_append_chr(mon->outbuf, c);
341 if (c == '\n') {
6cff3e85 342 monitor_flush_locked(mon);
e1f2641b 343 }
7e2515e8 344 }
6cff3e85 345 qemu_mutex_unlock(&mon->out_lock);
7e2515e8
FB
346}
347
376253ec 348void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
9dc39cba 349{
e1f2641b 350 char *buf;
b8b08266 351
2daa1191
LC
352 if (!mon)
353 return;
354
9f3982f2 355 if (monitor_is_qmp(mon)) {
b8b08266 356 return;
4a29a85d 357 }
b8b08266 358
e1f2641b 359 buf = g_strdup_vprintf(fmt, ap);
b8b08266 360 monitor_puts(mon, buf);
e1f2641b 361 g_free(buf);
9dc39cba
FB
362}
363
376253ec 364void monitor_printf(Monitor *mon, const char *fmt, ...)
9dc39cba 365{
7e2515e8
FB
366 va_list ap;
367 va_start(ap, fmt);
376253ec 368 monitor_vprintf(mon, fmt, ap);
7e2515e8 369 va_end(ap);
9dc39cba
FB
370}
371
caf15319 372int monitor_fprintf(FILE *stream, const char *fmt, ...)
7fe48483
FB
373{
374 va_list ap;
375 va_start(ap, fmt);
376253ec 376 monitor_vprintf((Monitor *)stream, fmt, ap);
7fe48483
FB
377 va_end(ap);
378 return 0;
379}
380
9b57c02e
LC
381static void monitor_json_emitter(Monitor *mon, const QObject *data)
382{
383 QString *json;
384
83a27d4d
LC
385 json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
386 qobject_to_json(data);
9b57c02e
LC
387 assert(json != NULL);
388
b8b08266
LC
389 qstring_append_chr(json, '\n');
390 monitor_puts(mon, qstring_get_str(json));
4a29a85d 391
9b57c02e
LC
392 QDECREF(json);
393}
394
7fb1cf16 395static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
b9b03ab0
MA
396 /* Limit guest-triggerable events to 1 per second */
397 [QAPI_EVENT_RTC_CHANGE] = { 1000 * SCALE_MS },
398 [QAPI_EVENT_WATCHDOG] = { 1000 * SCALE_MS },
399 [QAPI_EVENT_BALLOON_CHANGE] = { 1000 * SCALE_MS },
400 [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
401 [QAPI_EVENT_QUORUM_FAILURE] = { 1000 * SCALE_MS },
402 [QAPI_EVENT_VSERPORT_CHANGE] = { 1000 * SCALE_MS },
403};
404
a24712af 405GHashTable *monitor_qapi_event_state;
afeecec2
DB
406
407/*
43a14cfc 408 * Emits the event to every monitor instance, @event is only used for trace
d622cb58 409 * Called with monitor_lock held.
afeecec2 410 */
688b4b7d 411static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
afeecec2
DB
412{
413 Monitor *mon;
414
688b4b7d 415 trace_monitor_protocol_event_emit(event, qdict);
afeecec2 416 QLIST_FOREACH(mon, &mon_list, entry) {
9f3982f2 417 if (monitor_is_qmp(mon) && mon->qmp.in_command_mode) {
688b4b7d 418 monitor_json_emitter(mon, QOBJECT(qdict));
afeecec2
DB
419 }
420 }
421}
422
a24712af
MA
423static void monitor_qapi_event_handler(void *opaque);
424
afeecec2
DB
425/*
426 * Queue a new event for emission to Monitor instances,
427 * applying any rate limiting if required.
428 */
429static void
688b4b7d 430monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
afeecec2 431{
b9b03ab0 432 MonitorQAPIEventConf *evconf;
43a14cfc 433 MonitorQAPIEventState *evstate;
afeecec2 434
7fb1cf16 435 assert(event < QAPI_EVENT__MAX);
b9b03ab0 436 evconf = &monitor_qapi_event_conf[event];
b9b03ab0 437 trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
afeecec2 438
d622cb58 439 qemu_mutex_lock(&monitor_lock);
93f8f982 440
b9b03ab0 441 if (!evconf->rate) {
93f8f982 442 /* Unthrottled event */
688b4b7d 443 monitor_qapi_event_emit(event, qdict);
afeecec2 444 } else {
7de0be65
MA
445 QDict *data = qobject_to_qdict(qdict_get(qdict, "data"));
446 MonitorQAPIEventState key = { .event = event, .data = data };
a24712af
MA
447
448 evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
449 assert(!evstate || timer_pending(evstate->timer));
450
451 if (evstate) {
93f8f982 452 /*
b9b03ab0 453 * Timer is pending for (at least) evconf->rate ns after
93f8f982
MA
454 * last send. Store event for sending when timer fires,
455 * replacing a prior stored event if any.
afeecec2 456 */
93f8f982 457 QDECREF(evstate->qdict);
688b4b7d
MA
458 evstate->qdict = qdict;
459 QINCREF(evstate->qdict);
afeecec2 460 } else {
93f8f982 461 /*
b9b03ab0 462 * Last send was (at least) evconf->rate ns ago.
93f8f982 463 * Send immediately, and arm the timer to call
b9b03ab0 464 * monitor_qapi_event_handler() in evconf->rate ns. Any
93f8f982
MA
465 * events arriving before then will be delayed until then.
466 */
dc599978 467 int64_t now = qemu_clock_get_ns(event_clock_type);
93f8f982 468
688b4b7d 469 monitor_qapi_event_emit(event, qdict);
a24712af
MA
470
471 evstate = g_new(MonitorQAPIEventState, 1);
472 evstate->event = event;
7de0be65
MA
473 evstate->data = data;
474 QINCREF(evstate->data);
a24712af 475 evstate->qdict = NULL;
dc599978 476 evstate->timer = timer_new_ns(event_clock_type,
a24712af
MA
477 monitor_qapi_event_handler,
478 evstate);
479 g_hash_table_add(monitor_qapi_event_state, evstate);
b9b03ab0 480 timer_mod_ns(evstate->timer, now + evconf->rate);
afeecec2
DB
481 }
482 }
93f8f982 483
d622cb58 484 qemu_mutex_unlock(&monitor_lock);
afeecec2
DB
485}
486
afeecec2 487/*
b9b03ab0 488 * This function runs evconf->rate ns after sending a throttled
93f8f982
MA
489 * event.
490 * If another event has since been stored, send it.
afeecec2 491 */
43a14cfc 492static void monitor_qapi_event_handler(void *opaque)
afeecec2 493{
43a14cfc 494 MonitorQAPIEventState *evstate = opaque;
b9b03ab0 495 MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
afeecec2 496
93f8f982 497 trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
d622cb58 498 qemu_mutex_lock(&monitor_lock);
93f8f982 499
688b4b7d 500 if (evstate->qdict) {
dc599978 501 int64_t now = qemu_clock_get_ns(event_clock_type);
93f8f982 502
688b4b7d
MA
503 monitor_qapi_event_emit(evstate->event, evstate->qdict);
504 QDECREF(evstate->qdict);
505 evstate->qdict = NULL;
b9b03ab0 506 timer_mod_ns(evstate->timer, now + evconf->rate);
a24712af
MA
507 } else {
508 g_hash_table_remove(monitor_qapi_event_state, evstate);
7de0be65 509 QDECREF(evstate->data);
a24712af
MA
510 timer_free(evstate->timer);
511 g_free(evstate);
afeecec2 512 }
93f8f982 513
d622cb58 514 qemu_mutex_unlock(&monitor_lock);
afeecec2
DB
515}
516
a24712af 517static unsigned int qapi_event_throttle_hash(const void *key)
afeecec2 518{
a24712af 519 const MonitorQAPIEventState *evstate = key;
7de0be65 520 unsigned int hash = evstate->event * 255;
afeecec2 521
7de0be65
MA
522 if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
523 hash += g_str_hash(qdict_get_str(evstate->data, "id"));
524 }
525
6d425eb9
AG
526 if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
527 hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
528 }
529
7de0be65 530 return hash;
a24712af 531}
0d1ea871 532
a24712af
MA
533static gboolean qapi_event_throttle_equal(const void *a, const void *b)
534{
535 const MonitorQAPIEventState *eva = a;
536 const MonitorQAPIEventState *evb = b;
537
7de0be65
MA
538 if (eva->event != evb->event) {
539 return FALSE;
540 }
541
542 if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
543 return !strcmp(qdict_get_str(eva->data, "id"),
544 qdict_get_str(evb->data, "id"));
545 }
546
6d425eb9
AG
547 if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
548 return !strcmp(qdict_get_str(eva->data, "node-name"),
549 qdict_get_str(evb->data, "node-name"));
550 }
551
7de0be65 552 return TRUE;
a24712af
MA
553}
554
555static void monitor_qapi_event_init(void)
556{
dc599978
AG
557 if (qtest_enabled()) {
558 event_clock_type = QEMU_CLOCK_VIRTUAL;
559 }
560
a24712af
MA
561 monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
562 qapi_event_throttle_equal);
43a14cfc 563 qmp_event_set_func_emit(monitor_qapi_event_queue);
0d1ea871
LC
564}
565
119ebac1 566void qmp_qmp_capabilities(Error **errp)
4a7e1190 567{
485febc6 568 cur_mon->qmp.in_command_mode = true;
4a7e1190
LC
569}
570
7ef6cf63 571static void handle_hmp_command(Monitor *mon, const char *cmdline);
0268d97c 572
b01fe89e
WX
573static void monitor_data_init(Monitor *mon)
574{
575 memset(mon, 0, sizeof(Monitor));
6cff3e85 576 qemu_mutex_init(&mon->out_lock);
b01fe89e 577 mon->outbuf = qstring_new();
7717239d
WX
578 /* Use *mon_cmds by default. */
579 mon->cmd_table = mon_cmds;
b01fe89e
WX
580}
581
582static void monitor_data_destroy(Monitor *mon)
583{
c39860e6 584 qemu_chr_fe_deinit(&mon->chr);
2ef45716
MAL
585 if (monitor_is_qmp(mon)) {
586 json_message_parser_destroy(&mon->qmp.parser);
587 }
588 g_free(mon->rs);
b01fe89e 589 QDECREF(mon->outbuf);
6cff3e85 590 qemu_mutex_destroy(&mon->out_lock);
b01fe89e
WX
591}
592
d51a67b4
LC
593char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
594 int64_t cpu_index, Error **errp)
0268d97c 595{
d51a67b4 596 char *output = NULL;
0268d97c 597 Monitor *old_mon, hmp;
0268d97c 598
b01fe89e 599 monitor_data_init(&hmp);
48c043d0 600 hmp.skip_flush = true;
0268d97c
LC
601
602 old_mon = cur_mon;
603 cur_mon = &hmp;
604
d51a67b4
LC
605 if (has_cpu_index) {
606 int ret = monitor_set_cpu(cpu_index);
0268d97c
LC
607 if (ret < 0) {
608 cur_mon = old_mon;
c6bd8c70
MA
609 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
610 "a CPU number");
0268d97c
LC
611 goto out;
612 }
613 }
614
7ef6cf63 615 handle_hmp_command(&hmp, command_line);
0268d97c
LC
616 cur_mon = old_mon;
617
6cff3e85 618 qemu_mutex_lock(&hmp.out_lock);
48c043d0
LC
619 if (qstring_get_length(hmp.outbuf) > 0) {
620 output = g_strdup(qstring_get_str(hmp.outbuf));
d51a67b4
LC
621 } else {
622 output = g_strdup("");
0268d97c 623 }
6cff3e85 624 qemu_mutex_unlock(&hmp.out_lock);
0268d97c
LC
625
626out:
b01fe89e 627 monitor_data_destroy(&hmp);
d51a67b4 628 return output;
0268d97c
LC
629}
630
9dc39cba
FB
631static int compare_cmd(const char *name, const char *list)
632{
633 const char *p, *pstart;
634 int len;
635 len = strlen(name);
636 p = list;
637 for(;;) {
638 pstart = p;
639 p = strchr(p, '|');
640 if (!p)
641 p = pstart + strlen(pstart);
642 if ((p - pstart) == len && !memcmp(pstart, name, len))
643 return 1;
644 if (*p == '\0')
645 break;
646 p++;
647 }
648 return 0;
649}
650
f5438c05
WX
651static int get_str(char *buf, int buf_size, const char **pp)
652{
653 const char *p;
654 char *q;
655 int c;
656
657 q = buf;
658 p = *pp;
659 while (qemu_isspace(*p)) {
660 p++;
661 }
662 if (*p == '\0') {
663 fail:
664 *q = '\0';
665 *pp = p;
666 return -1;
667 }
668 if (*p == '\"') {
669 p++;
670 while (*p != '\0' && *p != '\"') {
671 if (*p == '\\') {
672 p++;
673 c = *p++;
674 switch (c) {
675 case 'n':
676 c = '\n';
677 break;
678 case 'r':
679 c = '\r';
680 break;
681 case '\\':
682 case '\'':
683 case '\"':
684 break;
685 default:
71baf787 686 printf("unsupported escape code: '\\%c'\n", c);
f5438c05
WX
687 goto fail;
688 }
689 if ((q - buf) < buf_size - 1) {
690 *q++ = c;
691 }
692 } else {
693 if ((q - buf) < buf_size - 1) {
694 *q++ = *p;
695 }
696 p++;
697 }
698 }
699 if (*p != '\"') {
71baf787 700 printf("unterminated string\n");
f5438c05
WX
701 goto fail;
702 }
703 p++;
704 } else {
705 while (*p != '\0' && !qemu_isspace(*p)) {
706 if ((q - buf) < buf_size - 1) {
707 *q++ = *p;
708 }
709 p++;
710 }
711 }
712 *q = '\0';
713 *pp = p;
714 return 0;
715}
716
717#define MAX_ARGS 16
718
dcc70cdf
WX
719static void free_cmdline_args(char **args, int nb_args)
720{
721 int i;
722
723 assert(nb_args <= MAX_ARGS);
724
725 for (i = 0; i < nb_args; i++) {
726 g_free(args[i]);
727 }
728
729}
730
731/*
732 * Parse the command line to get valid args.
733 * @cmdline: command line to be parsed.
734 * @pnb_args: location to store the number of args, must NOT be NULL.
735 * @args: location to store the args, which should be freed by caller, must
736 * NOT be NULL.
737 *
738 * Returns 0 on success, negative on failure.
739 *
740 * NOTE: this parser is an approximate form of the real command parser. Number
741 * of args have a limit of MAX_ARGS. If cmdline contains more, it will
742 * return with failure.
743 */
744static int parse_cmdline(const char *cmdline,
745 int *pnb_args, char **args)
f5438c05
WX
746{
747 const char *p;
748 int nb_args, ret;
749 char buf[1024];
750
751 p = cmdline;
752 nb_args = 0;
753 for (;;) {
754 while (qemu_isspace(*p)) {
755 p++;
756 }
757 if (*p == '\0') {
758 break;
759 }
760 if (nb_args >= MAX_ARGS) {
dcc70cdf 761 goto fail;
f5438c05
WX
762 }
763 ret = get_str(buf, sizeof(buf), &p);
f5438c05 764 if (ret < 0) {
dcc70cdf 765 goto fail;
f5438c05 766 }
dcc70cdf
WX
767 args[nb_args] = g_strdup(buf);
768 nb_args++;
f5438c05
WX
769 }
770 *pnb_args = nb_args;
dcc70cdf
WX
771 return 0;
772
773 fail:
774 free_cmdline_args(args, nb_args);
775 return -1;
f5438c05
WX
776}
777
66855495
WX
778static void help_cmd_dump_one(Monitor *mon,
779 const mon_cmd_t *cmd,
780 char **prefix_args,
781 int prefix_args_nb)
782{
783 int i;
784
785 for (i = 0; i < prefix_args_nb; i++) {
786 monitor_printf(mon, "%s ", prefix_args[i]);
787 }
788 monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
789}
790
791/* @args[@arg_index] is the valid command need to find in @cmds */
c227f099 792static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
66855495 793 char **args, int nb_args, int arg_index)
9dc39cba 794{
c227f099 795 const mon_cmd_t *cmd;
9dc39cba 796
66855495
WX
797 /* No valid arg need to compare with, dump all in *cmds */
798 if (arg_index >= nb_args) {
799 for (cmd = cmds; cmd->name != NULL; cmd++) {
800 help_cmd_dump_one(mon, cmd, args, arg_index);
801 }
802 return;
803 }
804
805 /* Find one entry to dump */
806 for (cmd = cmds; cmd->name != NULL; cmd++) {
807 if (compare_cmd(args[arg_index], cmd->name)) {
808 if (cmd->sub_table) {
809 /* continue with next arg */
810 help_cmd_dump(mon, cmd->sub_table,
811 args, nb_args, arg_index + 1);
812 } else {
813 help_cmd_dump_one(mon, cmd, args, arg_index);
814 }
815 break;
816 }
9dc39cba
FB
817 }
818}
819
376253ec 820static void help_cmd(Monitor *mon, const char *name)
9dc39cba 821{
66855495
WX
822 char *args[MAX_ARGS];
823 int nb_args = 0;
824
825 /* 1. parse user input */
826 if (name) {
827 /* special case for log, directly dump and return */
828 if (!strcmp(name, "log")) {
38dad9e5 829 const QEMULogItem *item;
376253ec
AL
830 monitor_printf(mon, "Log items (comma separated):\n");
831 monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
38dad9e5 832 for (item = qemu_log_items; item->mask != 0; item++) {
376253ec 833 monitor_printf(mon, "%-10s %s\n", item->name, item->help);
f193c797 834 }
66855495
WX
835 return;
836 }
837
838 if (parse_cmdline(name, &nb_args, args) < 0) {
839 return;
f193c797 840 }
9dc39cba 841 }
66855495
WX
842
843 /* 2. dump the contents according to parsed args */
844 help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);
845
846 free_cmdline_args(args, nb_args);
9dc39cba
FB
847}
848
d54908a5 849static void do_help_cmd(Monitor *mon, const QDict *qdict)
38183186 850{
d54908a5 851 help_cmd(mon, qdict_get_try_str(qdict, "name"));
38183186
LC
852}
853
3e5a50d6 854static void hmp_trace_event(Monitor *mon, const QDict *qdict)
22890ab5
PS
855{
856 const char *tp_name = qdict_get_str(qdict, "name");
857 bool new_state = qdict_get_bool(qdict, "option");
77e2b172
LV
858 bool has_vcpu = qdict_haskey(qdict, "vcpu");
859 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
14101d02 860 Error *local_err = NULL;
f871d689 861
77e2b172
LV
862 if (vcpu < 0) {
863 monitor_printf(mon, "argument vcpu must be positive");
864 return;
865 }
866
867 qmp_trace_event_set_state(tp_name, new_state, true, true, has_vcpu, vcpu, &local_err);
14101d02 868 if (local_err) {
091e38b7 869 error_report_err(local_err);
f871d689 870 }
22890ab5 871}
c5ceb523 872
c45a8168 873#ifdef CONFIG_TRACE_SIMPLE
3e5a50d6 874static void hmp_trace_file(Monitor *mon, const QDict *qdict)
c5ceb523
SH
875{
876 const char *op = qdict_get_try_str(qdict, "op");
877 const char *arg = qdict_get_try_str(qdict, "arg");
878
879 if (!op) {
880 st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
881 } else if (!strcmp(op, "on")) {
882 st_set_trace_file_enabled(true);
883 } else if (!strcmp(op, "off")) {
884 st_set_trace_file_enabled(false);
885 } else if (!strcmp(op, "flush")) {
886 st_flush_trace_buffer();
887 } else if (!strcmp(op, "set")) {
888 if (arg) {
889 st_set_trace_file(arg);
890 }
891 } else {
892 monitor_printf(mon, "unexpected argument \"%s\"\n", op);
893 help_cmd(mon, "trace-file");
894 }
895}
22890ab5
PS
896#endif
897
3e5a50d6 898static void hmp_info_help(Monitor *mon, const QDict *qdict)
9dc39cba 899{
13c7425e 900 help_cmd(mon, "info");
9dc39cba
FB
901}
902
9e812b6a 903static void query_commands_cb(QmpCommand *cmd, void *opaque)
e3bba9d0 904{
9e812b6a 905 CommandInfoList *info, **list = opaque;
e3bba9d0 906
9e812b6a
MAL
907 if (!cmd->enabled) {
908 return;
e3bba9d0
LC
909 }
910
9e812b6a
MAL
911 info = g_malloc0(sizeof(*info));
912 info->value = g_malloc0(sizeof(*info->value));
913 info->value->name = g_strdup(cmd->name);
914 info->next = *list;
915 *list = info;
916}
917
918CommandInfoList *qmp_query_commands(Error **errp)
919{
920 CommandInfoList *list = NULL;
921
922 qmp_for_each_command(query_commands_cb, &list);
923
924 return list;
a36e69dd
TS
925}
926
4860853d
DB
927EventInfoList *qmp_query_events(Error **errp)
928{
929 EventInfoList *info, *ev_list = NULL;
75175173 930 QAPIEvent e;
4860853d 931
7fb1cf16 932 for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
75175173 933 const char *event_name = QAPIEvent_lookup[e];
4860853d
DB
934 assert(event_name != NULL);
935 info = g_malloc0(sizeof(*info));
936 info->value = g_malloc0(sizeof(*info->value));
937 info->value->name = g_strdup(event_name);
938
939 info->next = ev_list;
940 ev_list = info;
941 }
942
943 return ev_list;
944}
945
39a18158
MA
946/*
947 * Minor hack: generated marshalling suppressed for this command
948 * ('gen': false in the schema) so we can parse the JSON string
949 * directly into QObject instead of first parsing it with
950 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
951 * to QObject with generated output marshallers, every time. Instead,
b3db211f 952 * we do it in test-qobject-input-visitor.c, just to make sure
39a18158
MA
953 * qapi-introspect.py's output actually conforms to the schema.
954 */
955static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
956 Error **errp)
957{
958 *ret_data = qobject_from_json(qmp_schema_json);
959}
960
5032a16d 961/*
5032a16d
MAL
962 * We used to define commands in qmp-commands.hx in addition to the
963 * QAPI schema. This permitted defining some of them only in certain
964 * configurations. query-commands has always reflected that (good,
965 * because it lets QMP clients figure out what's actually available),
966 * while query-qmp-schema never did (not so good). This function is a
967 * hack to keep the configuration-specific commands defined exactly as
968 * before, even though qmp-commands.hx is gone.
969 *
970 * FIXME Educate the QAPI schema on configuration-specific commands,
971 * and drop this hack.
972 */
973static void qmp_unregister_commands_hack(void)
974{
975#ifndef CONFIG_SPICE
976 qmp_unregister_command("query-spice");
977#endif
978#ifndef TARGET_I386
979 qmp_unregister_command("rtc-reset-reinjection");
980#endif
981#ifndef TARGET_S390X
982 qmp_unregister_command("dump-skeys");
983#endif
984#ifndef TARGET_ARM
985 qmp_unregister_command("query-gic-capabilities");
986#endif
728b1429
EH
987#if !defined(TARGET_S390X)
988 qmp_unregister_command("query-cpu-model-expansion");
989 qmp_unregister_command("query-cpu-model-baseline");
990 qmp_unregister_command("query-cpu-model-comparison");
991#endif
992#if !defined(TARGET_PPC) && !defined(TARGET_ARM) && !defined(TARGET_I386) \
993 && !defined(TARGET_S390X)
994 qmp_unregister_command("query-cpu-definitions");
995#endif
5032a16d
MAL
996}
997
edcfaefe
MAL
998static void qmp_init_marshal(void)
999{
1000 qmp_register_command("query-qmp-schema", qmp_query_qmp_schema,
1001 QCO_NO_OPTIONS);
1002 qmp_register_command("device_add", qmp_device_add,
1003 QCO_NO_OPTIONS);
1004 qmp_register_command("netdev_add", qmp_netdev_add,
1005 QCO_NO_OPTIONS);
5032a16d
MAL
1006
1007 /* call it after the rest of qapi_init() */
1008 register_module_init(qmp_unregister_commands_hack, MODULE_INIT_QAPI);
edcfaefe
MAL
1009}
1010
1011qapi_init(qmp_init_marshal);
1012
b025c8b4
LC
1013/* set the current CPU defined by the user */
1014int monitor_set_cpu(int cpu_index)
6a00d601 1015{
55e5c285 1016 CPUState *cpu;
6a00d601 1017
1c8bb3cc
AF
1018 cpu = qemu_get_cpu(cpu_index);
1019 if (cpu == NULL) {
1020 return -1;
6a00d601 1021 }
cb446eca 1022 cur_mon->mon_cpu = cpu;
1c8bb3cc 1023 return 0;
6a00d601
FB
1024}
1025
caf15319 1026CPUState *mon_get_cpu(void)
6a00d601 1027{
731b0364 1028 if (!cur_mon->mon_cpu) {
27a83f8e 1029 monitor_set_cpu(first_cpu->cpu_index);
6a00d601 1030 }
4c0960c0 1031 cpu_synchronize_state(cur_mon->mon_cpu);
5bcda5f7
PC
1032 return cur_mon->mon_cpu;
1033}
1034
bf957284 1035CPUArchState *mon_get_cpu_env(void)
5bcda5f7
PC
1036{
1037 return mon_get_cpu()->env_ptr;
6a00d601
FB
1038}
1039
99b7796f
LC
1040int monitor_get_cpu_index(void)
1041{
5bcda5f7 1042 return mon_get_cpu()->cpu_index;
99b7796f
LC
1043}
1044
1ce6be24 1045static void hmp_info_registers(Monitor *mon, const QDict *qdict)
9307c4c1 1046{
5bcda5f7 1047 cpu_dump_state(mon_get_cpu(), (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
9307c4c1
FB
1048}
1049
1ce6be24 1050static void hmp_info_jit(Monitor *mon, const QDict *qdict)
e3db7226 1051{
376253ec 1052 dump_exec_info((FILE *)mon, monitor_fprintf);
27498bef 1053 dump_drift_info((FILE *)mon, monitor_fprintf);
e3db7226
FB
1054}
1055
1ce6be24 1056static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
246ae24d
MF
1057{
1058 dump_opcount_info((FILE *)mon, monitor_fprintf);
1059}
1060
1ce6be24 1061static void hmp_info_history(Monitor *mon, const QDict *qdict)
aa455485
FB
1062{
1063 int i;
7e2515e8 1064 const char *str;
3b46e624 1065
cde76ee1
AL
1066 if (!mon->rs)
1067 return;
7e2515e8
FB
1068 i = 0;
1069 for(;;) {
731b0364 1070 str = readline_get_history(mon->rs, i);
7e2515e8
FB
1071 if (!str)
1072 break;
376253ec 1073 monitor_printf(mon, "%d: '%s'\n", i, str);
8e3a9fd2 1074 i++;
aa455485
FB
1075 }
1076}
1077
1ce6be24 1078static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
76a66253 1079{
5bcda5f7 1080 cpu_dump_statistics(mon_get_cpu(), (FILE *)mon, &monitor_fprintf, 0);
76a66253 1081}
76a66253 1082
1ce6be24 1083static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
22890ab5 1084{
bd71211d 1085 const char *name = qdict_get_try_str(qdict, "name");
77e2b172
LV
1086 bool has_vcpu = qdict_haskey(qdict, "vcpu");
1087 int vcpu = qdict_get_try_int(qdict, "vcpu", 0);
bd71211d 1088 TraceEventInfoList *events;
14101d02 1089 TraceEventInfoList *elem;
bd71211d
LV
1090 Error *local_err = NULL;
1091
1092 if (name == NULL) {
1093 name = "*";
1094 }
77e2b172
LV
1095 if (vcpu < 0) {
1096 monitor_printf(mon, "argument vcpu must be positive");
1097 return;
1098 }
bd71211d 1099
77e2b172 1100 events = qmp_trace_event_get_state(name, has_vcpu, vcpu, &local_err);
bd71211d
LV
1101 if (local_err) {
1102 error_report_err(local_err);
1103 return;
1104 }
14101d02
LV
1105
1106 for (elem = events; elem != NULL; elem = elem->next) {
1107 monitor_printf(mon, "%s : state %u\n",
1108 elem->value->name,
1109 elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
1110 }
1111 qapi_free_TraceEventInfoList(events);
22890ab5 1112}
22890ab5 1113
b8a185bc
MA
1114void qmp_client_migrate_info(const char *protocol, const char *hostname,
1115 bool has_port, int64_t port,
1116 bool has_tls_port, int64_t tls_port,
1117 bool has_cert_subject, const char *cert_subject,
1118 Error **errp)
e866e239 1119{
e866e239 1120 if (strcmp(protocol, "spice") == 0) {
b8a185bc
MA
1121 if (!qemu_using_spice(errp)) {
1122 return;
e866e239
GH
1123 }
1124
b8a185bc 1125 if (!has_port && !has_tls_port) {
c6bd8c70 1126 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
b8a185bc 1127 return;
6ec5dae5
YH
1128 }
1129
b8a185bc
MA
1130 if (qemu_spice_migrate_info(hostname,
1131 has_port ? port : -1,
1132 has_tls_port ? tls_port : -1,
1133 cert_subject)) {
c6bd8c70 1134 error_setg(errp, QERR_UNDEFINED_ERROR);
b8a185bc 1135 return;
e866e239 1136 }
b8a185bc 1137 return;
e866e239
GH
1138 }
1139
c6bd8c70 1140 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
e866e239
GH
1141}
1142
3e5a50d6 1143static void hmp_logfile(Monitor *mon, const QDict *qdict)
e735b91c 1144{
daa76aa4
MA
1145 Error *err = NULL;
1146
1147 qemu_set_log_filename(qdict_get_str(qdict, "filename"), &err);
1148 if (err) {
1149 error_report_err(err);
1150 }
e735b91c
PB
1151}
1152
3e5a50d6 1153static void hmp_log(Monitor *mon, const QDict *qdict)
f193c797
FB
1154{
1155 int mask;
d54908a5 1156 const char *items = qdict_get_str(qdict, "items");
3b46e624 1157
9307c4c1 1158 if (!strcmp(items, "none")) {
f193c797
FB
1159 mask = 0;
1160 } else {
4fde1eba 1161 mask = qemu_str_to_log_mask(items);
f193c797 1162 if (!mask) {
376253ec 1163 help_cmd(mon, "log");
f193c797
FB
1164 return;
1165 }
1166 }
24537a01 1167 qemu_set_log(mask);
f193c797
FB
1168}
1169
3e5a50d6 1170static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1b530a6d 1171{
d54908a5 1172 const char *option = qdict_get_try_str(qdict, "option");
1b530a6d
AJ
1173 if (!option || !strcmp(option, "on")) {
1174 singlestep = 1;
1175 } else if (!strcmp(option, "off")) {
1176 singlestep = 0;
1177 } else {
1178 monitor_printf(mon, "unexpected option %s\n", option);
1179 }
1180}
1181
3e5a50d6 1182static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
59030a8c 1183{
d54908a5 1184 const char *device = qdict_get_try_str(qdict, "device");
59030a8c
AL
1185 if (!device)
1186 device = "tcp::" DEFAULT_GDBSTUB_PORT;
1187 if (gdbserver_start(device) < 0) {
1188 monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1189 device);
1190 } else if (strcmp(device, "none") == 0) {
36556b20 1191 monitor_printf(mon, "Disabled gdbserver\n");
8a7ddc38 1192 } else {
59030a8c
AL
1193 monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1194 device);
8a7ddc38
FB
1195 }
1196}
1197
3e5a50d6 1198static void hmp_watchdog_action(Monitor *mon, const QDict *qdict)
9dd986cc 1199{
d54908a5 1200 const char *action = qdict_get_str(qdict, "action");
9dd986cc
RJ
1201 if (select_watchdog_action(action) == -1) {
1202 monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1203 }
1204}
1205
376253ec 1206static void monitor_printc(Monitor *mon, int c)
9307c4c1 1207{
376253ec 1208 monitor_printf(mon, "'");
9307c4c1
FB
1209 switch(c) {
1210 case '\'':
376253ec 1211 monitor_printf(mon, "\\'");
9307c4c1
FB
1212 break;
1213 case '\\':
376253ec 1214 monitor_printf(mon, "\\\\");
9307c4c1
FB
1215 break;
1216 case '\n':
376253ec 1217 monitor_printf(mon, "\\n");
9307c4c1
FB
1218 break;
1219 case '\r':
376253ec 1220 monitor_printf(mon, "\\r");
9307c4c1
FB
1221 break;
1222 default:
1223 if (c >= 32 && c <= 126) {
376253ec 1224 monitor_printf(mon, "%c", c);
9307c4c1 1225 } else {
376253ec 1226 monitor_printf(mon, "\\x%02x", c);
9307c4c1
FB
1227 }
1228 break;
1229 }
376253ec 1230 monitor_printf(mon, "'");
9307c4c1
FB
1231}
1232
376253ec 1233static void memory_dump(Monitor *mon, int count, int format, int wsize,
a8170e5e 1234 hwaddr addr, int is_physical)
9307c4c1 1235{
23842aab 1236 int l, line_size, i, max_digits, len;
9307c4c1
FB
1237 uint8_t buf[16];
1238 uint64_t v;
1239
1240 if (format == 'i') {
5bcda5f7 1241 int flags = 0;
9307c4c1 1242#ifdef TARGET_I386
5bcda5f7 1243 CPUArchState *env = mon_get_cpu_env();
4c27ba27 1244 if (wsize == 2) {
9307c4c1 1245 flags = 1;
4c27ba27
FB
1246 } else if (wsize == 4) {
1247 flags = 0;
1248 } else {
6a15fd12 1249 /* as default we use the current CS size */
4c27ba27 1250 flags = 0;
6a15fd12
FB
1251 if (env) {
1252#ifdef TARGET_X86_64
5fafdf24 1253 if ((env->efer & MSR_EFER_LMA) &&
6a15fd12
FB
1254 (env->segs[R_CS].flags & DESC_L_MASK))
1255 flags = 2;
1256 else
1257#endif
1258 if (!(env->segs[R_CS].flags & DESC_B_MASK))
1259 flags = 1;
1260 }
4c27ba27 1261 }
1c38f843
TM
1262#endif
1263#ifdef TARGET_PPC
5bcda5f7 1264 CPUArchState *env = mon_get_cpu_env();
1c38f843
TM
1265 flags = msr_le << 16;
1266 flags |= env->bfd_mach;
4c27ba27 1267#endif
d49190c4 1268 monitor_disas(mon, mon_get_cpu(), addr, count, is_physical, flags);
9307c4c1
FB
1269 return;
1270 }
1271
1272 len = wsize * count;
1273 if (wsize == 1)
1274 line_size = 8;
1275 else
1276 line_size = 16;
9307c4c1
FB
1277 max_digits = 0;
1278
1279 switch(format) {
1280 case 'o':
1281 max_digits = (wsize * 8 + 2) / 3;
1282 break;
1283 default:
1284 case 'x':
1285 max_digits = (wsize * 8) / 4;
1286 break;
1287 case 'u':
1288 case 'd':
1289 max_digits = (wsize * 8 * 10 + 32) / 33;
1290 break;
1291 case 'c':
1292 wsize = 1;
1293 break;
1294 }
1295
1296 while (len > 0) {
7743e588 1297 if (is_physical)
376253ec 1298 monitor_printf(mon, TARGET_FMT_plx ":", addr);
7743e588 1299 else
376253ec 1300 monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
9307c4c1
FB
1301 l = len;
1302 if (l > line_size)
1303 l = line_size;
1304 if (is_physical) {
54f7b4a3 1305 cpu_physical_memory_read(addr, buf, l);
9307c4c1 1306 } else {
5bcda5f7 1307 if (cpu_memory_rw_debug(mon_get_cpu(), addr, buf, l, 0) < 0) {
376253ec 1308 monitor_printf(mon, " Cannot access memory\n");
c8f79b67
AL
1309 break;
1310 }
9307c4c1 1311 }
5fafdf24 1312 i = 0;
9307c4c1
FB
1313 while (i < l) {
1314 switch(wsize) {
1315 default:
1316 case 1:
24e60305 1317 v = ldub_p(buf + i);
9307c4c1
FB
1318 break;
1319 case 2:
24e60305 1320 v = lduw_p(buf + i);
9307c4c1
FB
1321 break;
1322 case 4:
24e60305 1323 v = (uint32_t)ldl_p(buf + i);
9307c4c1
FB
1324 break;
1325 case 8:
24e60305 1326 v = ldq_p(buf + i);
9307c4c1
FB
1327 break;
1328 }
376253ec 1329 monitor_printf(mon, " ");
9307c4c1
FB
1330 switch(format) {
1331 case 'o':
376253ec 1332 monitor_printf(mon, "%#*" PRIo64, max_digits, v);
9307c4c1
FB
1333 break;
1334 case 'x':
376253ec 1335 monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
9307c4c1
FB
1336 break;
1337 case 'u':
376253ec 1338 monitor_printf(mon, "%*" PRIu64, max_digits, v);
9307c4c1
FB
1339 break;
1340 case 'd':
376253ec 1341 monitor_printf(mon, "%*" PRId64, max_digits, v);
9307c4c1
FB
1342 break;
1343 case 'c':
376253ec 1344 monitor_printc(mon, v);
9307c4c1
FB
1345 break;
1346 }
1347 i += wsize;
1348 }
376253ec 1349 monitor_printf(mon, "\n");
9307c4c1
FB
1350 addr += l;
1351 len -= l;
1352 }
1353}
1354
3e5a50d6 1355static void hmp_memory_dump(Monitor *mon, const QDict *qdict)
9307c4c1 1356{
1bd1442e
LC
1357 int count = qdict_get_int(qdict, "count");
1358 int format = qdict_get_int(qdict, "format");
1359 int size = qdict_get_int(qdict, "size");
1360 target_long addr = qdict_get_int(qdict, "addr");
1361
376253ec 1362 memory_dump(mon, count, format, size, addr, 0);
9307c4c1
FB
1363}
1364
3e5a50d6 1365static void hmp_physical_memory_dump(Monitor *mon, const QDict *qdict)
9307c4c1 1366{
1bd1442e
LC
1367 int count = qdict_get_int(qdict, "count");
1368 int format = qdict_get_int(qdict, "format");
1369 int size = qdict_get_int(qdict, "size");
a8170e5e 1370 hwaddr addr = qdict_get_int(qdict, "addr");
1bd1442e 1371
376253ec 1372 memory_dump(mon, count, format, size, addr, 1);
9307c4c1
FB
1373}
1374
1bd1442e 1375static void do_print(Monitor *mon, const QDict *qdict)
9307c4c1 1376{
1bd1442e 1377 int format = qdict_get_int(qdict, "format");
a8170e5e 1378 hwaddr val = qdict_get_int(qdict, "val");
1bd1442e 1379
9307c4c1
FB
1380 switch(format) {
1381 case 'o':
a8170e5e 1382 monitor_printf(mon, "%#" HWADDR_PRIo, val);
9307c4c1
FB
1383 break;
1384 case 'x':
a8170e5e 1385 monitor_printf(mon, "%#" HWADDR_PRIx, val);
9307c4c1
FB
1386 break;
1387 case 'u':
a8170e5e 1388 monitor_printf(mon, "%" HWADDR_PRIu, val);
9307c4c1
FB
1389 break;
1390 default:
1391 case 'd':
a8170e5e 1392 monitor_printf(mon, "%" HWADDR_PRId, val);
9307c4c1
FB
1393 break;
1394 case 'c':
376253ec 1395 monitor_printc(mon, val);
9307c4c1
FB
1396 break;
1397 }
376253ec 1398 monitor_printf(mon, "\n");
9307c4c1
FB
1399}
1400
3e5a50d6 1401static void hmp_sum(Monitor *mon, const QDict *qdict)
e4cf1adc
FB
1402{
1403 uint32_t addr;
e4cf1adc 1404 uint16_t sum;
f18c16de
LC
1405 uint32_t start = qdict_get_int(qdict, "start");
1406 uint32_t size = qdict_get_int(qdict, "size");
e4cf1adc
FB
1407
1408 sum = 0;
1409 for(addr = start; addr < (start + size); addr++) {
42874d3a
PM
1410 uint8_t val = address_space_ldub(&address_space_memory, addr,
1411 MEMTXATTRS_UNSPECIFIED, NULL);
e4cf1adc
FB
1412 /* BSD sum algorithm ('sum' Unix command) */
1413 sum = (sum >> 1) | (sum << 15);
54f7b4a3 1414 sum += val;
e4cf1adc 1415 }
376253ec 1416 monitor_printf(mon, "%05d\n", sum);
e4cf1adc
FB
1417}
1418
13224a87
FB
1419static int mouse_button_state;
1420
3e5a50d6 1421static void hmp_mouse_move(Monitor *mon, const QDict *qdict)
13224a87 1422{
c751a74a 1423 int dx, dy, dz, button;
1d4daa91
LC
1424 const char *dx_str = qdict_get_str(qdict, "dx_str");
1425 const char *dy_str = qdict_get_str(qdict, "dy_str");
1426 const char *dz_str = qdict_get_try_str(qdict, "dz_str");
c751a74a 1427
13224a87
FB
1428 dx = strtol(dx_str, NULL, 0);
1429 dy = strtol(dy_str, NULL, 0);
c751a74a
GH
1430 qemu_input_queue_rel(NULL, INPUT_AXIS_X, dx);
1431 qemu_input_queue_rel(NULL, INPUT_AXIS_Y, dy);
1432
1433 if (dz_str) {
13224a87 1434 dz = strtol(dz_str, NULL, 0);
c751a74a 1435 if (dz != 0) {
f22d0af0 1436 button = (dz > 0) ? INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
c751a74a
GH
1437 qemu_input_queue_btn(NULL, button, true);
1438 qemu_input_event_sync();
1439 qemu_input_queue_btn(NULL, button, false);
1440 }
1441 }
1442 qemu_input_event_sync();
13224a87
FB
1443}
1444
3e5a50d6 1445static void hmp_mouse_button(Monitor *mon, const QDict *qdict)
13224a87 1446{
7fb1cf16 1447 static uint32_t bmap[INPUT_BUTTON__MAX] = {
c751a74a
GH
1448 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1449 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1450 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
1451 };
d54908a5 1452 int button_state = qdict_get_int(qdict, "button_state");
c751a74a
GH
1453
1454 if (mouse_button_state == button_state) {
1455 return;
1456 }
1457 qemu_input_update_buttons(NULL, bmap, mouse_button_state, button_state);
1458 qemu_input_event_sync();
13224a87 1459 mouse_button_state = button_state;
13224a87
FB
1460}
1461
3e5a50d6 1462static void hmp_ioport_read(Monitor *mon, const QDict *qdict)
3440557b 1463{
aa93e39c
LC
1464 int size = qdict_get_int(qdict, "size");
1465 int addr = qdict_get_int(qdict, "addr");
1466 int has_index = qdict_haskey(qdict, "index");
3440557b
FB
1467 uint32_t val;
1468 int suffix;
1469
1470 if (has_index) {
aa93e39c 1471 int index = qdict_get_int(qdict, "index");
afcea8cb 1472 cpu_outb(addr & IOPORTS_MASK, index & 0xff);
3440557b
FB
1473 addr++;
1474 }
1475 addr &= 0xffff;
1476
1477 switch(size) {
1478 default:
1479 case 1:
afcea8cb 1480 val = cpu_inb(addr);
3440557b
FB
1481 suffix = 'b';
1482 break;
1483 case 2:
afcea8cb 1484 val = cpu_inw(addr);
3440557b
FB
1485 suffix = 'w';
1486 break;
1487 case 4:
afcea8cb 1488 val = cpu_inl(addr);
3440557b
FB
1489 suffix = 'l';
1490 break;
1491 }
376253ec
AL
1492 monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1493 suffix, addr, size * 2, val);
3440557b 1494}
a3a91a35 1495
3e5a50d6 1496static void hmp_ioport_write(Monitor *mon, const QDict *qdict)
f114784f 1497{
1bd1442e
LC
1498 int size = qdict_get_int(qdict, "size");
1499 int addr = qdict_get_int(qdict, "addr");
1500 int val = qdict_get_int(qdict, "val");
1501
f114784f
JK
1502 addr &= IOPORTS_MASK;
1503
1504 switch (size) {
1505 default:
1506 case 1:
afcea8cb 1507 cpu_outb(addr, val);
f114784f
JK
1508 break;
1509 case 2:
afcea8cb 1510 cpu_outw(addr, val);
f114784f
JK
1511 break;
1512 case 4:
afcea8cb 1513 cpu_outl(addr, val);
f114784f
JK
1514 break;
1515 }
1516}
1517
3e5a50d6 1518static void hmp_boot_set(Monitor *mon, const QDict *qdict)
0ecdffbb 1519{
f1839938 1520 Error *local_err = NULL;
d54908a5 1521 const char *bootdevice = qdict_get_str(qdict, "bootdevice");
0ecdffbb 1522
f1839938
GA
1523 qemu_boot_set(bootdevice, &local_err);
1524 if (local_err) {
193227f9 1525 error_report_err(local_err);
0ecdffbb 1526 } else {
f1839938 1527 monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
0ecdffbb
AJ
1528 }
1529}
1530
1ce6be24 1531static void hmp_info_mtree(Monitor *mon, const QDict *qdict)
314e2987 1532{
57bb40c9
PX
1533 bool flatview = qdict_get_try_bool(qdict, "flatview", false);
1534
1535 mtree_info((fprintf_function)monitor_printf, mon, flatview);
314e2987
BS
1536}
1537
1ce6be24 1538static void hmp_info_numa(Monitor *mon, const QDict *qdict)
030ea37b 1539{
b28b6230 1540 int i;
1b1ed8dc 1541 CPUState *cpu;
5b009e40 1542 uint64_t *node_mem;
030ea37b 1543
5b009e40
HZ
1544 node_mem = g_new0(uint64_t, nb_numa_nodes);
1545 query_numa_node_mem(node_mem);
030ea37b
AL
1546 monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1547 for (i = 0; i < nb_numa_nodes; i++) {
1548 monitor_printf(mon, "node %d cpus:", i);
bdc44640 1549 CPU_FOREACH(cpu) {
1b1ed8dc 1550 if (cpu->numa_node == i) {
55e5c285 1551 monitor_printf(mon, " %d", cpu->cpu_index);
030ea37b
AL
1552 }
1553 }
1554 monitor_printf(mon, "\n");
1555 monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
5b009e40 1556 node_mem[i] >> 20);
030ea37b 1557 }
5b009e40 1558 g_free(node_mem);
030ea37b
AL
1559}
1560
5f1ce948
FB
1561#ifdef CONFIG_PROFILER
1562
89d5cbdd 1563int64_t tcg_time;
e9a6625e
AJ
1564int64_t dev_time;
1565
1ce6be24 1566static void hmp_info_profile(Monitor *mon, const QDict *qdict)
5f1ce948 1567{
376253ec 1568 monitor_printf(mon, "async time %" PRId64 " (%0.3f)\n",
73bcb24d 1569 dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
376253ec 1570 monitor_printf(mon, "qemu time %" PRId64 " (%0.3f)\n",
73bcb24d 1571 tcg_time, tcg_time / (double)NANOSECONDS_PER_SECOND);
89d5cbdd 1572 tcg_time = 0;
5f1ce948 1573 dev_time = 0;
5f1ce948
FB
1574}
1575#else
1ce6be24 1576static void hmp_info_profile(Monitor *mon, const QDict *qdict)
5f1ce948 1577{
376253ec 1578 monitor_printf(mon, "Internal profiler not compiled\n");
5f1ce948
FB
1579}
1580#endif
1581
ec36b695 1582/* Capture support */
72cf2d4f 1583static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
ec36b695 1584
1ce6be24 1585static void hmp_info_capture(Monitor *mon, const QDict *qdict)
ec36b695
FB
1586{
1587 int i;
1588 CaptureState *s;
1589
1590 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
376253ec 1591 monitor_printf(mon, "[%d]: ", i);
ec36b695
FB
1592 s->ops.info (s->opaque);
1593 }
1594}
1595
3e5a50d6 1596static void hmp_stopcapture(Monitor *mon, const QDict *qdict)
ec36b695
FB
1597{
1598 int i;
d54908a5 1599 int n = qdict_get_int(qdict, "n");
ec36b695
FB
1600 CaptureState *s;
1601
1602 for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1603 if (i == n) {
1604 s->ops.destroy (s->opaque);
72cf2d4f 1605 QLIST_REMOVE (s, entries);
7267c094 1606 g_free (s);
ec36b695
FB
1607 return;
1608 }
1609 }
1610}
1611
3e5a50d6 1612static void hmp_wavcapture(Monitor *mon, const QDict *qdict)
c1925484
LC
1613{
1614 const char *path = qdict_get_str(qdict, "path");
1615 int has_freq = qdict_haskey(qdict, "freq");
1616 int freq = qdict_get_try_int(qdict, "freq", -1);
1617 int has_bits = qdict_haskey(qdict, "bits");
1618 int bits = qdict_get_try_int(qdict, "bits", -1);
1619 int has_channels = qdict_haskey(qdict, "nchannels");
1620 int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
ec36b695
FB
1621 CaptureState *s;
1622
7267c094 1623 s = g_malloc0 (sizeof (*s));
ec36b695
FB
1624
1625 freq = has_freq ? freq : 44100;
1626 bits = has_bits ? bits : 16;
1627 nchannels = has_channels ? nchannels : 2;
1628
1629 if (wav_start_capture (s, path, freq, bits, nchannels)) {
d00b2618 1630 monitor_printf(mon, "Failed to add wave capture\n");
7267c094 1631 g_free (s);
d00b2618 1632 return;
ec36b695 1633 }
72cf2d4f 1634 QLIST_INSERT_HEAD (&capture_head, s, entries);
ec36b695 1635}
ec36b695 1636
15dfcd45 1637static qemu_acl *find_acl(Monitor *mon, const char *name)
76655d6d 1638{
15dfcd45 1639 qemu_acl *acl = qemu_acl_find(name);
76655d6d 1640
76655d6d 1641 if (!acl) {
15dfcd45 1642 monitor_printf(mon, "acl: unknown list '%s'\n", name);
76655d6d 1643 }
15dfcd45
JK
1644 return acl;
1645}
1646
3e5a50d6 1647static void hmp_acl_show(Monitor *mon, const QDict *qdict)
15dfcd45 1648{
d54908a5 1649 const char *aclname = qdict_get_str(qdict, "aclname");
15dfcd45
JK
1650 qemu_acl *acl = find_acl(mon, aclname);
1651 qemu_acl_entry *entry;
1652 int i = 0;
76655d6d 1653
15dfcd45 1654 if (acl) {
28a76be8 1655 monitor_printf(mon, "policy: %s\n",
76655d6d 1656 acl->defaultDeny ? "deny" : "allow");
72cf2d4f 1657 QTAILQ_FOREACH(entry, &acl->entries, next) {
28a76be8
AL
1658 i++;
1659 monitor_printf(mon, "%d: %s %s\n", i,
15dfcd45 1660 entry->deny ? "deny" : "allow", entry->match);
28a76be8 1661 }
15dfcd45
JK
1662 }
1663}
1664
3e5a50d6 1665static void hmp_acl_reset(Monitor *mon, const QDict *qdict)
15dfcd45 1666{
d54908a5 1667 const char *aclname = qdict_get_str(qdict, "aclname");
15dfcd45
JK
1668 qemu_acl *acl = find_acl(mon, aclname);
1669
1670 if (acl) {
28a76be8
AL
1671 qemu_acl_reset(acl);
1672 monitor_printf(mon, "acl: removed all rules\n");
15dfcd45
JK
1673 }
1674}
1675
3e5a50d6 1676static void hmp_acl_policy(Monitor *mon, const QDict *qdict)
15dfcd45 1677{
f18c16de
LC
1678 const char *aclname = qdict_get_str(qdict, "aclname");
1679 const char *policy = qdict_get_str(qdict, "policy");
15dfcd45 1680 qemu_acl *acl = find_acl(mon, aclname);
28a76be8 1681
15dfcd45
JK
1682 if (acl) {
1683 if (strcmp(policy, "allow") == 0) {
28a76be8
AL
1684 acl->defaultDeny = 0;
1685 monitor_printf(mon, "acl: policy set to 'allow'\n");
15dfcd45 1686 } else if (strcmp(policy, "deny") == 0) {
28a76be8
AL
1687 acl->defaultDeny = 1;
1688 monitor_printf(mon, "acl: policy set to 'deny'\n");
1689 } else {
15dfcd45
JK
1690 monitor_printf(mon, "acl: unknown policy '%s', "
1691 "expected 'deny' or 'allow'\n", policy);
28a76be8 1692 }
15dfcd45
JK
1693 }
1694}
28a76be8 1695
3e5a50d6 1696static void hmp_acl_add(Monitor *mon, const QDict *qdict)
15dfcd45 1697{
1bd1442e
LC
1698 const char *aclname = qdict_get_str(qdict, "aclname");
1699 const char *match = qdict_get_str(qdict, "match");
1700 const char *policy = qdict_get_str(qdict, "policy");
1701 int has_index = qdict_haskey(qdict, "index");
1702 int index = qdict_get_try_int(qdict, "index", -1);
15dfcd45
JK
1703 qemu_acl *acl = find_acl(mon, aclname);
1704 int deny, ret;
1705
1706 if (acl) {
1707 if (strcmp(policy, "allow") == 0) {
1708 deny = 0;
1709 } else if (strcmp(policy, "deny") == 0) {
1710 deny = 1;
1711 } else {
1712 monitor_printf(mon, "acl: unknown policy '%s', "
1713 "expected 'deny' or 'allow'\n", policy);
28a76be8
AL
1714 return;
1715 }
28a76be8
AL
1716 if (has_index)
1717 ret = qemu_acl_insert(acl, deny, match, index);
1718 else
1719 ret = qemu_acl_append(acl, deny, match);
1720 if (ret < 0)
1721 monitor_printf(mon, "acl: unable to add acl entry\n");
1722 else
1723 monitor_printf(mon, "acl: added rule at position %d\n", ret);
15dfcd45
JK
1724 }
1725}
28a76be8 1726
3e5a50d6 1727static void hmp_acl_remove(Monitor *mon, const QDict *qdict)
15dfcd45 1728{
f18c16de
LC
1729 const char *aclname = qdict_get_str(qdict, "aclname");
1730 const char *match = qdict_get_str(qdict, "match");
15dfcd45
JK
1731 qemu_acl *acl = find_acl(mon, aclname);
1732 int ret;
28a76be8 1733
15dfcd45 1734 if (acl) {
28a76be8
AL
1735 ret = qemu_acl_remove(acl, match);
1736 if (ret < 0)
1737 monitor_printf(mon, "acl: no matching acl entry\n");
1738 else
1739 monitor_printf(mon, "acl: removed rule at position %d\n", ret);
76655d6d
AL
1740 }
1741}
1742
208c9d1b 1743void qmp_getfd(const char *fdname, Error **errp)
f07918fd 1744{
c227f099 1745 mon_fd_t *monfd;
f07918fd
MM
1746 int fd;
1747
5345fdb4 1748 fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
f07918fd 1749 if (fd == -1) {
c6bd8c70 1750 error_setg(errp, QERR_FD_NOT_SUPPLIED);
208c9d1b 1751 return;
f07918fd
MM
1752 }
1753
1754 if (qemu_isdigit(fdname[0])) {
0b9f0e2f 1755 close(fd);
c6bd8c70
MA
1756 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
1757 "a name not starting with a digit");
208c9d1b 1758 return;
f07918fd
MM
1759 }
1760
208c9d1b 1761 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
f07918fd
MM
1762 if (strcmp(monfd->name, fdname) != 0) {
1763 continue;
1764 }
1765
1766 close(monfd->fd);
1767 monfd->fd = fd;
208c9d1b 1768 return;
f07918fd
MM
1769 }
1770
7267c094
AL
1771 monfd = g_malloc0(sizeof(mon_fd_t));
1772 monfd->name = g_strdup(fdname);
f07918fd
MM
1773 monfd->fd = fd;
1774
208c9d1b 1775 QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
f07918fd
MM
1776}
1777
208c9d1b 1778void qmp_closefd(const char *fdname, Error **errp)
f07918fd 1779{
c227f099 1780 mon_fd_t *monfd;
f07918fd 1781
208c9d1b 1782 QLIST_FOREACH(monfd, &cur_mon->fds, next) {
f07918fd
MM
1783 if (strcmp(monfd->name, fdname) != 0) {
1784 continue;
1785 }
1786
72cf2d4f 1787 QLIST_REMOVE(monfd, next);
f07918fd 1788 close(monfd->fd);
7267c094
AL
1789 g_free(monfd->name);
1790 g_free(monfd);
208c9d1b 1791 return;
f07918fd
MM
1792 }
1793
c6bd8c70 1794 error_setg(errp, QERR_FD_NOT_FOUND, fdname);
f07918fd
MM
1795}
1796
3e5a50d6 1797static void hmp_loadvm(Monitor *mon, const QDict *qdict)
c8d41b2c 1798{
1354869c 1799 int saved_vm_running = runstate_is_running();
d54908a5 1800 const char *name = qdict_get_str(qdict, "name");
c8d41b2c 1801
0461d5a6 1802 vm_stop(RUN_STATE_RESTORE_VM);
c8d41b2c 1803
f0aa7a8b 1804 if (load_vmstate(name) == 0 && saved_vm_running) {
c8d41b2c 1805 vm_start();
f0aa7a8b 1806 }
c8d41b2c
JQ
1807}
1808
a9940fc4 1809int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp)
7768e04c 1810{
c227f099 1811 mon_fd_t *monfd;
7768e04c 1812
72cf2d4f 1813 QLIST_FOREACH(monfd, &mon->fds, next) {
7768e04c
MM
1814 int fd;
1815
1816 if (strcmp(monfd->name, fdname) != 0) {
1817 continue;
1818 }
1819
1820 fd = monfd->fd;
1821
1822 /* caller takes ownership of fd */
72cf2d4f 1823 QLIST_REMOVE(monfd, next);
7267c094
AL
1824 g_free(monfd->name);
1825 g_free(monfd);
7768e04c
MM
1826
1827 return fd;
1828 }
1829
a9940fc4 1830 error_setg(errp, "File descriptor named '%s' has not been found", fdname);
7768e04c
MM
1831 return -1;
1832}
1833
ba1c048a
CB
1834static void monitor_fdset_cleanup(MonFdset *mon_fdset)
1835{
1836 MonFdsetFd *mon_fdset_fd;
1837 MonFdsetFd *mon_fdset_fd_next;
1838
1839 QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
ebe52b59
CB
1840 if ((mon_fdset_fd->removed ||
1841 (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) &&
1842 runstate_is_running()) {
ba1c048a
CB
1843 close(mon_fdset_fd->fd);
1844 g_free(mon_fdset_fd->opaque);
1845 QLIST_REMOVE(mon_fdset_fd, next);
1846 g_free(mon_fdset_fd);
1847 }
1848 }
1849
adb696f3 1850 if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
ba1c048a
CB
1851 QLIST_REMOVE(mon_fdset, next);
1852 g_free(mon_fdset);
1853 }
1854}
1855
efb87c16
CB
1856static void monitor_fdsets_cleanup(void)
1857{
1858 MonFdset *mon_fdset;
1859 MonFdset *mon_fdset_next;
1860
1861 QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
1862 monitor_fdset_cleanup(mon_fdset);
1863 }
1864}
1865
ba1c048a
CB
1866AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
1867 const char *opaque, Error **errp)
1868{
1869 int fd;
1870 Monitor *mon = cur_mon;
ba1c048a
CB
1871 AddfdInfo *fdinfo;
1872
5345fdb4 1873 fd = qemu_chr_fe_get_msgfd(&mon->chr);
ba1c048a 1874 if (fd == -1) {
c6bd8c70 1875 error_setg(errp, QERR_FD_NOT_SUPPLIED);
ba1c048a
CB
1876 goto error;
1877 }
1878
e446f70d
CB
1879 fdinfo = monitor_fdset_add_fd(fd, has_fdset_id, fdset_id,
1880 has_opaque, opaque, errp);
1881 if (fdinfo) {
1882 return fdinfo;
ba1c048a 1883 }
ba1c048a
CB
1884
1885error:
1886 if (fd != -1) {
1887 close(fd);
1888 }
1889 return NULL;
1890}
1891
1892void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
1893{
1894 MonFdset *mon_fdset;
1895 MonFdsetFd *mon_fdset_fd;
1896 char fd_str[60];
1897
1898 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1899 if (mon_fdset->id != fdset_id) {
1900 continue;
1901 }
1902 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1903 if (has_fd) {
1904 if (mon_fdset_fd->fd != fd) {
1905 continue;
1906 }
1907 mon_fdset_fd->removed = true;
1908 break;
1909 } else {
1910 mon_fdset_fd->removed = true;
1911 }
1912 }
1913 if (has_fd && !mon_fdset_fd) {
1914 goto error;
1915 }
1916 monitor_fdset_cleanup(mon_fdset);
1917 return;
1918 }
1919
1920error:
1921 if (has_fd) {
1922 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
1923 fdset_id, fd);
1924 } else {
1925 snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
1926 }
c6bd8c70 1927 error_setg(errp, QERR_FD_NOT_FOUND, fd_str);
ba1c048a
CB
1928}
1929
1930FdsetInfoList *qmp_query_fdsets(Error **errp)
1931{
1932 MonFdset *mon_fdset;
1933 MonFdsetFd *mon_fdset_fd;
1934 FdsetInfoList *fdset_list = NULL;
1935
1936 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1937 FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
1938 FdsetFdInfoList *fdsetfd_list = NULL;
1939
1940 fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
1941 fdset_info->value->fdset_id = mon_fdset->id;
1942
1943 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
1944 FdsetFdInfoList *fdsetfd_info;
1945
1946 fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
1947 fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
1948 fdsetfd_info->value->fd = mon_fdset_fd->fd;
1949 if (mon_fdset_fd->opaque) {
1950 fdsetfd_info->value->has_opaque = true;
1951 fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
1952 } else {
1953 fdsetfd_info->value->has_opaque = false;
1954 }
1955
1956 fdsetfd_info->next = fdsetfd_list;
1957 fdsetfd_list = fdsetfd_info;
1958 }
1959
1960 fdset_info->value->fds = fdsetfd_list;
1961
1962 fdset_info->next = fdset_list;
1963 fdset_list = fdset_info;
1964 }
1965
1966 return fdset_list;
1967}
1968
e446f70d
CB
1969AddfdInfo *monitor_fdset_add_fd(int fd, bool has_fdset_id, int64_t fdset_id,
1970 bool has_opaque, const char *opaque,
1971 Error **errp)
1972{
1973 MonFdset *mon_fdset = NULL;
1974 MonFdsetFd *mon_fdset_fd;
1975 AddfdInfo *fdinfo;
1976
1977 if (has_fdset_id) {
1978 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
1979 /* Break if match found or match impossible due to ordering by ID */
1980 if (fdset_id <= mon_fdset->id) {
1981 if (fdset_id < mon_fdset->id) {
1982 mon_fdset = NULL;
1983 }
1984 break;
1985 }
1986 }
1987 }
1988
1989 if (mon_fdset == NULL) {
1990 int64_t fdset_id_prev = -1;
1991 MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
1992
1993 if (has_fdset_id) {
1994 if (fdset_id < 0) {
c6bd8c70
MA
1995 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
1996 "a non-negative value");
e446f70d
CB
1997 return NULL;
1998 }
1999 /* Use specified fdset ID */
2000 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2001 mon_fdset_cur = mon_fdset;
2002 if (fdset_id < mon_fdset_cur->id) {
2003 break;
2004 }
2005 }
2006 } else {
2007 /* Use first available fdset ID */
2008 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2009 mon_fdset_cur = mon_fdset;
2010 if (fdset_id_prev == mon_fdset_cur->id - 1) {
2011 fdset_id_prev = mon_fdset_cur->id;
2012 continue;
2013 }
2014 break;
2015 }
2016 }
2017
2018 mon_fdset = g_malloc0(sizeof(*mon_fdset));
2019 if (has_fdset_id) {
2020 mon_fdset->id = fdset_id;
2021 } else {
2022 mon_fdset->id = fdset_id_prev + 1;
2023 }
2024
2025 /* The fdset list is ordered by fdset ID */
2026 if (!mon_fdset_cur) {
2027 QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
2028 } else if (mon_fdset->id < mon_fdset_cur->id) {
2029 QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
2030 } else {
2031 QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
2032 }
2033 }
2034
2035 mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
2036 mon_fdset_fd->fd = fd;
2037 mon_fdset_fd->removed = false;
2038 if (has_opaque) {
2039 mon_fdset_fd->opaque = g_strdup(opaque);
2040 }
2041 QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
2042
2043 fdinfo = g_malloc0(sizeof(*fdinfo));
2044 fdinfo->fdset_id = mon_fdset->id;
2045 fdinfo->fd = mon_fdset_fd->fd;
2046
2047 return fdinfo;
2048}
2049
adb696f3
CB
2050int monitor_fdset_get_fd(int64_t fdset_id, int flags)
2051{
b2dc64c3 2052#ifndef _WIN32
adb696f3
CB
2053 MonFdset *mon_fdset;
2054 MonFdsetFd *mon_fdset_fd;
2055 int mon_fd_flags;
2056
adb696f3
CB
2057 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2058 if (mon_fdset->id != fdset_id) {
2059 continue;
2060 }
2061 QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
2062 mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
2063 if (mon_fd_flags == -1) {
2064 return -1;
2065 }
2066
2067 if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
2068 return mon_fdset_fd->fd;
2069 }
2070 }
2071 errno = EACCES;
2072 return -1;
2073 }
2074#endif
2075
2076 errno = ENOENT;
2077 return -1;
2078}
2079
2080int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
2081{
2082 MonFdset *mon_fdset;
2083 MonFdsetFd *mon_fdset_fd_dup;
2084
2085 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2086 if (mon_fdset->id != fdset_id) {
2087 continue;
2088 }
2089 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2090 if (mon_fdset_fd_dup->fd == dup_fd) {
2091 return -1;
2092 }
2093 }
2094 mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
2095 mon_fdset_fd_dup->fd = dup_fd;
2096 QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
2097 return 0;
2098 }
2099 return -1;
2100}
2101
2102static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
2103{
2104 MonFdset *mon_fdset;
2105 MonFdsetFd *mon_fdset_fd_dup;
2106
2107 QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
2108 QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
2109 if (mon_fdset_fd_dup->fd == dup_fd) {
2110 if (remove) {
2111 QLIST_REMOVE(mon_fdset_fd_dup, next);
2112 if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
2113 monitor_fdset_cleanup(mon_fdset);
2114 }
b3dd1b8c
MT
2115 return -1;
2116 } else {
2117 return mon_fdset->id;
adb696f3 2118 }
adb696f3
CB
2119 }
2120 }
2121 }
2122 return -1;
2123}
2124
2125int monitor_fdset_dup_fd_find(int dup_fd)
2126{
2127 return monitor_fdset_dup_fd_find_remove(dup_fd, false);
2128}
2129
b3dd1b8c 2130void monitor_fdset_dup_fd_remove(int dup_fd)
adb696f3 2131{
b3dd1b8c 2132 monitor_fdset_dup_fd_find_remove(dup_fd, true);
adb696f3
CB
2133}
2134
1677f4c6 2135int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp)
5906366e
LE
2136{
2137 int fd;
2138 Error *local_err = NULL;
a96ed02f 2139
5906366e 2140 if (!qemu_isdigit(fdname[0]) && mon) {
a9940fc4 2141 fd = monitor_get_fd(mon, fdname, &local_err);
5906366e
LE
2142 } else {
2143 fd = qemu_parse_fd(fdname);
a96ed02f 2144 if (fd == -1) {
5906366e
LE
2145 error_setg(&local_err, "Invalid file descriptor number '%s'",
2146 fdname);
a96ed02f 2147 }
5906366e
LE
2148 }
2149 if (local_err) {
2150 error_propagate(errp, local_err);
2151 assert(fd == -1);
a96ed02f 2152 } else {
5906366e 2153 assert(fd != -1);
a96ed02f
NB
2154 }
2155
2156 return fd;
2157}
2158
acd0a093 2159/* Please update hmp-commands.hx when adding or changing commands */
816f8925 2160static mon_cmd_t info_cmds[] = {
da76ee76
PB
2161#include "hmp-commands-info.h"
2162 { NULL, NULL, },
9dc39cba
FB
2163};
2164
a13ced59
WX
2165/* mon_cmds and info_cmds would be sorted at runtime */
2166static mon_cmd_t mon_cmds[] = {
2167#include "hmp-commands.h"
2168 { NULL, NULL, },
2169};
2170
9307c4c1
FB
2171/*******************************************************************/
2172
2173static const char *pch;
6ab7e546 2174static sigjmp_buf expr_env;
9307c4c1 2175
9307c4c1 2176
9c3175cc
SW
2177static void GCC_FMT_ATTR(2, 3) QEMU_NORETURN
2178expr_error(Monitor *mon, const char *fmt, ...)
9dc39cba 2179{
277acfe8
FZ
2180 va_list ap;
2181 va_start(ap, fmt);
2182 monitor_vprintf(mon, fmt, ap);
2183 monitor_printf(mon, "\n");
2184 va_end(ap);
6ab7e546 2185 siglongjmp(expr_env, 1);
9307c4c1
FB
2186}
2187
09b9418c 2188/* return 0 if OK, -1 if not found */
92a31b1f 2189static int get_monitor_def(target_long *pval, const char *name)
9307c4c1 2190{
bf957284 2191 const MonitorDef *md = target_monitor_defs();
92a31b1f 2192 void *ptr;
0a9516c2
AK
2193 uint64_t tmp = 0;
2194 int ret;
92a31b1f 2195
bf957284
PB
2196 if (md == NULL) {
2197 return -1;
2198 }
2199
2200 for(; md->name != NULL; md++) {
9307c4c1
FB
2201 if (compare_cmd(name, md->name)) {
2202 if (md->get_value) {
e95c8d51 2203 *pval = md->get_value(md, md->offset);
9307c4c1 2204 } else {
5bcda5f7 2205 CPUArchState *env = mon_get_cpu_env();
6a00d601 2206 ptr = (uint8_t *)env + md->offset;
92a31b1f
FB
2207 switch(md->type) {
2208 case MD_I32:
2209 *pval = *(int32_t *)ptr;
2210 break;
2211 case MD_TLONG:
2212 *pval = *(target_long *)ptr;
2213 break;
2214 default:
2215 *pval = 0;
2216 break;
2217 }
9307c4c1
FB
2218 }
2219 return 0;
2220 }
2221 }
0a9516c2
AK
2222
2223 ret = target_get_monitor_def(mon_get_cpu(), name, &tmp);
2224 if (!ret) {
2225 *pval = (target_long) tmp;
2226 }
2227
2228 return ret;
9307c4c1
FB
2229}
2230
2231static void next(void)
2232{
660f11be 2233 if (*pch != '\0') {
9307c4c1 2234 pch++;
cd390083 2235 while (qemu_isspace(*pch))
9307c4c1
FB
2236 pch++;
2237 }
2238}
2239
376253ec 2240static int64_t expr_sum(Monitor *mon);
9307c4c1 2241
376253ec 2242static int64_t expr_unary(Monitor *mon)
9307c4c1 2243{
c2efc95d 2244 int64_t n;
9307c4c1 2245 char *p;
6a00d601 2246 int ret;
9307c4c1
FB
2247
2248 switch(*pch) {
2249 case '+':
2250 next();
376253ec 2251 n = expr_unary(mon);
9307c4c1
FB
2252 break;
2253 case '-':
2254 next();
376253ec 2255 n = -expr_unary(mon);
9307c4c1
FB
2256 break;
2257 case '~':
2258 next();
376253ec 2259 n = ~expr_unary(mon);
9307c4c1
FB
2260 break;
2261 case '(':
2262 next();
376253ec 2263 n = expr_sum(mon);
9307c4c1 2264 if (*pch != ')') {
376253ec 2265 expr_error(mon, "')' expected");
9307c4c1
FB
2266 }
2267 next();
2268 break;
81d0912d
FB
2269 case '\'':
2270 pch++;
2271 if (*pch == '\0')
376253ec 2272 expr_error(mon, "character constant expected");
81d0912d
FB
2273 n = *pch;
2274 pch++;
2275 if (*pch != '\'')
376253ec 2276 expr_error(mon, "missing terminating \' character");
81d0912d
FB
2277 next();
2278 break;
9307c4c1
FB
2279 case '$':
2280 {
2281 char buf[128], *q;
69b34976 2282 target_long reg=0;
3b46e624 2283
9307c4c1
FB
2284 pch++;
2285 q = buf;
2286 while ((*pch >= 'a' && *pch <= 'z') ||
2287 (*pch >= 'A' && *pch <= 'Z') ||
2288 (*pch >= '0' && *pch <= '9') ||
57206fd4 2289 *pch == '_' || *pch == '.') {
9307c4c1
FB
2290 if ((q - buf) < sizeof(buf) - 1)
2291 *q++ = *pch;
2292 pch++;
2293 }
cd390083 2294 while (qemu_isspace(*pch))
9307c4c1
FB
2295 pch++;
2296 *q = 0;
7743e588 2297 ret = get_monitor_def(&reg, buf);
09b9418c 2298 if (ret < 0)
376253ec 2299 expr_error(mon, "unknown register");
7743e588 2300 n = reg;
9307c4c1
FB
2301 }
2302 break;
2303 case '\0':
376253ec 2304 expr_error(mon, "unexpected end of expression");
9307c4c1
FB
2305 n = 0;
2306 break;
2307 default:
6b0e33be 2308 errno = 0;
4f4fbf77 2309 n = strtoull(pch, &p, 0);
6b0e33be
LC
2310 if (errno == ERANGE) {
2311 expr_error(mon, "number too large");
2312 }
9307c4c1 2313 if (pch == p) {
277acfe8 2314 expr_error(mon, "invalid char '%c' in expression", *p);
9307c4c1
FB
2315 }
2316 pch = p;
cd390083 2317 while (qemu_isspace(*pch))
9307c4c1
FB
2318 pch++;
2319 break;
2320 }
2321 return n;
2322}
2323
2324
376253ec 2325static int64_t expr_prod(Monitor *mon)
9307c4c1 2326{
c2efc95d 2327 int64_t val, val2;
92a31b1f 2328 int op;
3b46e624 2329
376253ec 2330 val = expr_unary(mon);
9307c4c1
FB
2331 for(;;) {
2332 op = *pch;
2333 if (op != '*' && op != '/' && op != '%')
2334 break;
2335 next();
376253ec 2336 val2 = expr_unary(mon);
9307c4c1
FB
2337 switch(op) {
2338 default:
2339 case '*':
2340 val *= val2;
2341 break;
2342 case '/':
2343 case '%':
5fafdf24 2344 if (val2 == 0)
376253ec 2345 expr_error(mon, "division by zero");
9307c4c1
FB
2346 if (op == '/')
2347 val /= val2;
2348 else
2349 val %= val2;
2350 break;
2351 }
2352 }
2353 return val;
2354}
2355
376253ec 2356static int64_t expr_logic(Monitor *mon)
9307c4c1 2357{
c2efc95d 2358 int64_t val, val2;
92a31b1f 2359 int op;
9307c4c1 2360
376253ec 2361 val = expr_prod(mon);
9307c4c1
FB
2362 for(;;) {
2363 op = *pch;
2364 if (op != '&' && op != '|' && op != '^')
2365 break;
2366 next();
376253ec 2367 val2 = expr_prod(mon);
9307c4c1
FB
2368 switch(op) {
2369 default:
2370 case '&':
2371 val &= val2;
2372 break;
2373 case '|':
2374 val |= val2;
2375 break;
2376 case '^':
2377 val ^= val2;
2378 break;
2379 }
2380 }
2381 return val;
2382}
2383
376253ec 2384static int64_t expr_sum(Monitor *mon)
9307c4c1 2385{
c2efc95d 2386 int64_t val, val2;
92a31b1f 2387 int op;
9307c4c1 2388
376253ec 2389 val = expr_logic(mon);
9307c4c1
FB
2390 for(;;) {
2391 op = *pch;
2392 if (op != '+' && op != '-')
2393 break;
2394 next();
376253ec 2395 val2 = expr_logic(mon);
9307c4c1
FB
2396 if (op == '+')
2397 val += val2;
2398 else
2399 val -= val2;
2400 }
2401 return val;
2402}
2403
376253ec 2404static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
9307c4c1
FB
2405{
2406 pch = *pp;
6ab7e546 2407 if (sigsetjmp(expr_env, 0)) {
9307c4c1
FB
2408 *pp = pch;
2409 return -1;
2410 }
cd390083 2411 while (qemu_isspace(*pch))
9307c4c1 2412 pch++;
376253ec 2413 *pval = expr_sum(mon);
9307c4c1
FB
2414 *pp = pch;
2415 return 0;
2416}
2417
3350a4dd
MA
2418static int get_double(Monitor *mon, double *pval, const char **pp)
2419{
2420 const char *p = *pp;
2421 char *tailp;
2422 double d;
2423
2424 d = strtod(p, &tailp);
2425 if (tailp == p) {
2426 monitor_printf(mon, "Number expected\n");
2427 return -1;
2428 }
2429 if (d != d || d - d != 0) {
2430 /* NaN or infinity */
2431 monitor_printf(mon, "Bad number\n");
2432 return -1;
2433 }
2434 *pval = d;
2435 *pp = tailp;
2436 return 0;
2437}
2438
4590fd80
LC
2439/*
2440 * Store the command-name in cmdname, and return a pointer to
2441 * the remaining of the command string.
2442 */
2443static const char *get_command_name(const char *cmdline,
2444 char *cmdname, size_t nlen)
2445{
2446 size_t len;
2447 const char *p, *pstart;
2448
2449 p = cmdline;
2450 while (qemu_isspace(*p))
2451 p++;
2452 if (*p == '\0')
2453 return NULL;
2454 pstart = p;
2455 while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2456 p++;
2457 len = p - pstart;
2458 if (len > nlen - 1)
2459 len = nlen - 1;
2460 memcpy(cmdname, pstart, len);
2461 cmdname[len] = '\0';
2462 return p;
2463}
2464
4d76d2ba
LC
2465/**
2466 * Read key of 'type' into 'key' and return the current
2467 * 'type' pointer.
2468 */
2469static char *key_get_info(const char *type, char **key)
2470{
2471 size_t len;
2472 char *p, *str;
2473
2474 if (*type == ',')
2475 type++;
2476
2477 p = strchr(type, ':');
2478 if (!p) {
2479 *key = NULL;
2480 return NULL;
2481 }
2482 len = p - type;
2483
7267c094 2484 str = g_malloc(len + 1);
4d76d2ba
LC
2485 memcpy(str, type, len);
2486 str[len] = '\0';
2487
2488 *key = str;
2489 return ++p;
2490}
2491
9307c4c1
FB
2492static int default_fmt_format = 'x';
2493static int default_fmt_size = 4;
2494
fbc3d96c
LS
2495static int is_valid_option(const char *c, const char *typestr)
2496{
2497 char option[3];
2498
2499 option[0] = '-';
2500 option[1] = *c;
2501 option[2] = '\0';
2502
2503 typestr = strstr(typestr, option);
2504 return (typestr != NULL);
2505}
2506
945c5ac8
LC
2507static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
2508 const char *cmdname)
7fd669a1
LC
2509{
2510 const mon_cmd_t *cmd;
2511
945c5ac8 2512 for (cmd = disp_table; cmd->name != NULL; cmd++) {
7fd669a1
LC
2513 if (compare_cmd(cmdname, cmd->name)) {
2514 return cmd;
2515 }
2516 }
2517
2518 return NULL;
2519}
2520
5f3d335f 2521/*
ae50212f
BD
2522 * Parse command name from @cmdp according to command table @table.
2523 * If blank, return NULL.
2524 * Else, if no valid command can be found, report to @mon, and return
2525 * NULL.
2526 * Else, change @cmdp to point right behind the name, and return its
2527 * command table entry.
2528 * Do not assume the return value points into @table! It doesn't when
2529 * the command is found in a sub-command table.
5f3d335f 2530 */
c227f099 2531static const mon_cmd_t *monitor_parse_command(Monitor *mon,
ae50212f
BD
2532 const char **cmdp,
2533 mon_cmd_t *table)
9307c4c1 2534{
ae50212f 2535 const char *p;
c227f099 2536 const mon_cmd_t *cmd;
9307c4c1 2537 char cmdname[256];
9dc39cba 2538
9307c4c1 2539 /* extract the command name */
ae50212f 2540 p = get_command_name(*cmdp, cmdname, sizeof(cmdname));
4590fd80 2541 if (!p)
55f81d96 2542 return NULL;
3b46e624 2543
5f3d335f 2544 cmd = search_dispatch_table(table, cmdname);
7fd669a1 2545 if (!cmd) {
5f3d335f 2546 monitor_printf(mon, "unknown command: '%.*s'\n",
ae50212f 2547 (int)(p - *cmdp), *cmdp);
55f81d96 2548 return NULL;
9307c4c1 2549 }
9307c4c1 2550
5f3d335f
WX
2551 /* filter out following useless space */
2552 while (qemu_isspace(*p)) {
2553 p++;
2554 }
ae50212f
BD
2555
2556 *cmdp = p;
5f3d335f 2557 /* search sub command */
ae50212f
BD
2558 if (cmd->sub_table != NULL && *p != '\0') {
2559 return monitor_parse_command(mon, cmdp, cmd->sub_table);
5f3d335f
WX
2560 }
2561
ae50212f
BD
2562 return cmd;
2563}
2564
2565/*
2566 * Parse arguments for @cmd.
2567 * If it can't be parsed, report to @mon, and return NULL.
2568 * Else, insert command arguments into a QDict, and return it.
2569 * Note: On success, caller has to free the QDict structure.
2570 */
2571
2572static QDict *monitor_parse_arguments(Monitor *mon,
2573 const char **endp,
2574 const mon_cmd_t *cmd)
2575{
2576 const char *typestr;
2577 char *key;
2578 int c;
2579 const char *p = *endp;
2580 char buf[1024];
2581 QDict *qdict = qdict_new();
2582
9307c4c1
FB
2583 /* parse the parameters */
2584 typestr = cmd->args_type;
9dc39cba 2585 for(;;) {
4d76d2ba
LC
2586 typestr = key_get_info(typestr, &key);
2587 if (!typestr)
9dc39cba 2588 break;
4d76d2ba 2589 c = *typestr;
9307c4c1
FB
2590 typestr++;
2591 switch(c) {
2592 case 'F':
81d0912d 2593 case 'B':
9307c4c1
FB
2594 case 's':
2595 {
2596 int ret;
3b46e624 2597
cd390083 2598 while (qemu_isspace(*p))
9307c4c1
FB
2599 p++;
2600 if (*typestr == '?') {
2601 typestr++;
2602 if (*p == '\0') {
2603 /* no optional string: NULL argument */
53773581 2604 break;
9307c4c1
FB
2605 }
2606 }
2607 ret = get_str(buf, sizeof(buf), &p);
2608 if (ret < 0) {
81d0912d
FB
2609 switch(c) {
2610 case 'F':
376253ec 2611 monitor_printf(mon, "%s: filename expected\n",
ae50212f 2612 cmd->name);
81d0912d
FB
2613 break;
2614 case 'B':
376253ec 2615 monitor_printf(mon, "%s: block device name expected\n",
ae50212f 2616 cmd->name);
81d0912d
FB
2617 break;
2618 default:
ae50212f 2619 monitor_printf(mon, "%s: string expected\n", cmd->name);
81d0912d
FB
2620 break;
2621 }
9307c4c1
FB
2622 goto fail;
2623 }
53773581 2624 qdict_put(qdict, key, qstring_from_str(buf));
9307c4c1 2625 }
9dc39cba 2626 break;
361127df
MA
2627 case 'O':
2628 {
2629 QemuOptsList *opts_list;
2630 QemuOpts *opts;
2631
2632 opts_list = qemu_find_opts(key);
2633 if (!opts_list || opts_list->desc->name) {
2634 goto bad_type;
2635 }
2636 while (qemu_isspace(*p)) {
2637 p++;
2638 }
2639 if (!*p)
2640 break;
2641 if (get_str(buf, sizeof(buf), &p) < 0) {
2642 goto fail;
2643 }
70b94331 2644 opts = qemu_opts_parse_noisily(opts_list, buf, true);
361127df
MA
2645 if (!opts) {
2646 goto fail;
2647 }
2648 qemu_opts_to_qdict(opts, qdict);
2649 qemu_opts_del(opts);
2650 }
2651 break;
9307c4c1
FB
2652 case '/':
2653 {
2654 int count, format, size;
3b46e624 2655
cd390083 2656 while (qemu_isspace(*p))
9307c4c1
FB
2657 p++;
2658 if (*p == '/') {
2659 /* format found */
2660 p++;
2661 count = 1;
cd390083 2662 if (qemu_isdigit(*p)) {
9307c4c1 2663 count = 0;
cd390083 2664 while (qemu_isdigit(*p)) {
9307c4c1
FB
2665 count = count * 10 + (*p - '0');
2666 p++;
2667 }
2668 }
2669 size = -1;
2670 format = -1;
2671 for(;;) {
2672 switch(*p) {
2673 case 'o':
2674 case 'd':
2675 case 'u':
2676 case 'x':
2677 case 'i':
2678 case 'c':
2679 format = *p++;
2680 break;
2681 case 'b':
2682 size = 1;
2683 p++;
2684 break;
2685 case 'h':
2686 size = 2;
2687 p++;
2688 break;
2689 case 'w':
2690 size = 4;
2691 p++;
2692 break;
2693 case 'g':
2694 case 'L':
2695 size = 8;
2696 p++;
2697 break;
2698 default:
2699 goto next;
2700 }
2701 }
2702 next:
cd390083 2703 if (*p != '\0' && !qemu_isspace(*p)) {
376253ec
AL
2704 monitor_printf(mon, "invalid char in format: '%c'\n",
2705 *p);
9307c4c1
FB
2706 goto fail;
2707 }
9307c4c1
FB
2708 if (format < 0)
2709 format = default_fmt_format;
4c27ba27
FB
2710 if (format != 'i') {
2711 /* for 'i', not specifying a size gives -1 as size */
2712 if (size < 0)
2713 size = default_fmt_size;
e90f009b 2714 default_fmt_size = size;
4c27ba27 2715 }
9307c4c1
FB
2716 default_fmt_format = format;
2717 } else {
2718 count = 1;
2719 format = default_fmt_format;
4c27ba27
FB
2720 if (format != 'i') {
2721 size = default_fmt_size;
2722 } else {
2723 size = -1;
2724 }
9307c4c1 2725 }
f7188bbe
LC
2726 qdict_put(qdict, "count", qint_from_int(count));
2727 qdict_put(qdict, "format", qint_from_int(format));
2728 qdict_put(qdict, "size", qint_from_int(size));
9307c4c1 2729 }
9dc39cba 2730 break;
9307c4c1 2731 case 'i':
92a31b1f 2732 case 'l':
b6e098d7 2733 case 'M':
9307c4c1 2734 {
c2efc95d 2735 int64_t val;
7743e588 2736
cd390083 2737 while (qemu_isspace(*p))
9307c4c1 2738 p++;
3440557b 2739 if (*typestr == '?' || *typestr == '.') {
3440557b 2740 if (*typestr == '?') {
53773581
LC
2741 if (*p == '\0') {
2742 typestr++;
2743 break;
2744 }
3440557b
FB
2745 } else {
2746 if (*p == '.') {
2747 p++;
cd390083 2748 while (qemu_isspace(*p))
3440557b 2749 p++;
3440557b 2750 } else {
53773581
LC
2751 typestr++;
2752 break;
3440557b
FB
2753 }
2754 }
13224a87 2755 typestr++;
9307c4c1 2756 }
376253ec 2757 if (get_expr(mon, &val, &p))
9307c4c1 2758 goto fail;
675ebef9
LC
2759 /* Check if 'i' is greater than 32-bit */
2760 if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
ae50212f 2761 monitor_printf(mon, "\'%s\' has failed: ", cmd->name);
675ebef9
LC
2762 monitor_printf(mon, "integer is for 32-bit values\n");
2763 goto fail;
b6e098d7 2764 } else if (c == 'M') {
91162849
LC
2765 if (val < 0) {
2766 monitor_printf(mon, "enter a positive value\n");
2767 goto fail;
2768 }
b6e098d7 2769 val <<= 20;
675ebef9 2770 }
53773581 2771 qdict_put(qdict, key, qint_from_int(val));
9307c4c1
FB
2772 }
2773 break;
dbc0c67f
JS
2774 case 'o':
2775 {
70b4f4bb 2776 int64_t val;
dbc0c67f
JS
2777 char *end;
2778
2779 while (qemu_isspace(*p)) {
2780 p++;
2781 }
2782 if (*typestr == '?') {
2783 typestr++;
2784 if (*p == '\0') {
2785 break;
2786 }
2787 }
4677bb40 2788 val = qemu_strtosz(p, &end);
dbc0c67f
JS
2789 if (val < 0) {
2790 monitor_printf(mon, "invalid size\n");
2791 goto fail;
2792 }
2793 qdict_put(qdict, key, qint_from_int(val));
2794 p = end;
2795 }
2796 break;
fccfb11e 2797 case 'T':
3350a4dd
MA
2798 {
2799 double val;
2800
2801 while (qemu_isspace(*p))
2802 p++;
2803 if (*typestr == '?') {
2804 typestr++;
2805 if (*p == '\0') {
2806 break;
2807 }
2808 }
2809 if (get_double(mon, &val, &p) < 0) {
2810 goto fail;
2811 }
07de3e60 2812 if (p[0] && p[1] == 's') {
fccfb11e
MA
2813 switch (*p) {
2814 case 'm':
2815 val /= 1e3; p += 2; break;
2816 case 'u':
2817 val /= 1e6; p += 2; break;
2818 case 'n':
2819 val /= 1e9; p += 2; break;
2820 }
2821 }
3350a4dd
MA
2822 if (*p && !qemu_isspace(*p)) {
2823 monitor_printf(mon, "Unknown unit suffix\n");
2824 goto fail;
2825 }
2826 qdict_put(qdict, key, qfloat_from_double(val));
2827 }
2828 break;
942cd1f2
MA
2829 case 'b':
2830 {
2831 const char *beg;
fc48ffc3 2832 bool val;
942cd1f2
MA
2833
2834 while (qemu_isspace(*p)) {
2835 p++;
2836 }
2837 beg = p;
2838 while (qemu_isgraph(*p)) {
2839 p++;
2840 }
2841 if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
fc48ffc3 2842 val = true;
942cd1f2 2843 } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
fc48ffc3 2844 val = false;
942cd1f2
MA
2845 } else {
2846 monitor_printf(mon, "Expected 'on' or 'off'\n");
2847 goto fail;
2848 }
fc48ffc3 2849 qdict_put(qdict, key, qbool_from_bool(val));
942cd1f2
MA
2850 }
2851 break;
9307c4c1
FB
2852 case '-':
2853 {
fbc3d96c 2854 const char *tmp = p;
eb159d13 2855 int skip_key = 0;
9307c4c1 2856 /* option */
3b46e624 2857
9307c4c1
FB
2858 c = *typestr++;
2859 if (c == '\0')
2860 goto bad_type;
cd390083 2861 while (qemu_isspace(*p))
9307c4c1 2862 p++;
9307c4c1
FB
2863 if (*p == '-') {
2864 p++;
fbc3d96c
LS
2865 if(c != *p) {
2866 if(!is_valid_option(p, typestr)) {
2867
2868 monitor_printf(mon, "%s: unsupported option -%c\n",
ae50212f 2869 cmd->name, *p);
fbc3d96c
LS
2870 goto fail;
2871 } else {
2872 skip_key = 1;
2873 }
2874 }
2875 if(skip_key) {
2876 p = tmp;
2877 } else {
eb159d13 2878 /* has option */
fbc3d96c 2879 p++;
fc48ffc3 2880 qdict_put(qdict, key, qbool_from_bool(true));
9307c4c1 2881 }
9307c4c1 2882 }
9307c4c1
FB
2883 }
2884 break;
129be006
WX
2885 case 'S':
2886 {
2887 /* package all remaining string */
2888 int len;
2889
2890 while (qemu_isspace(*p)) {
2891 p++;
2892 }
2893 if (*typestr == '?') {
2894 typestr++;
2895 if (*p == '\0') {
2896 /* no remaining string: NULL argument */
2897 break;
2898 }
2899 }
2900 len = strlen(p);
2901 if (len <= 0) {
2902 monitor_printf(mon, "%s: string expected\n",
ae50212f 2903 cmd->name);
e549d2aa 2904 goto fail;
129be006
WX
2905 }
2906 qdict_put(qdict, key, qstring_from_str(p));
2907 p += len;
2908 }
2909 break;
9307c4c1
FB
2910 default:
2911 bad_type:
ae50212f 2912 monitor_printf(mon, "%s: unknown type '%c'\n", cmd->name, c);
9307c4c1
FB
2913 goto fail;
2914 }
7267c094 2915 g_free(key);
4d76d2ba 2916 key = NULL;
9dc39cba 2917 }
9307c4c1 2918 /* check that all arguments were parsed */
cd390083 2919 while (qemu_isspace(*p))
9307c4c1
FB
2920 p++;
2921 if (*p != '\0') {
376253ec 2922 monitor_printf(mon, "%s: extraneous characters at the end of line\n",
ae50212f 2923 cmd->name);
9307c4c1 2924 goto fail;
9dc39cba 2925 }
9307c4c1 2926
ae50212f 2927 return qdict;
ac7531ec 2928
55f81d96 2929fail:
ae50212f 2930 QDECREF(qdict);
7267c094 2931 g_free(key);
55f81d96
LC
2932 return NULL;
2933}
2934
7ef6cf63 2935static void handle_hmp_command(Monitor *mon, const char *cmdline)
55f81d96 2936{
55f81d96 2937 QDict *qdict;
c227f099 2938 const mon_cmd_t *cmd;
55f81d96 2939
ae50212f
BD
2940 cmd = monitor_parse_command(mon, &cmdline, mon->cmd_table);
2941 if (!cmd) {
2942 return;
2943 }
55f81d96 2944
ae50212f
BD
2945 qdict = monitor_parse_arguments(mon, &cmdline, cmd);
2946 if (!qdict) {
dd41eea7
BD
2947 monitor_printf(mon, "Try \"help %s\" for more information\n",
2948 cmd->name);
ae50212f 2949 return;
55f81d96
LC
2950 }
2951
2b9e3576 2952 cmd->cmd(mon, qdict);
f7188bbe 2953 QDECREF(qdict);
9dc39cba
FB
2954}
2955
cd5c6bba 2956static void cmd_completion(Monitor *mon, const char *name, const char *list)
81d0912d
FB
2957{
2958 const char *p, *pstart;
2959 char cmd[128];
2960 int len;
2961
2962 p = list;
2963 for(;;) {
2964 pstart = p;
2965 p = strchr(p, '|');
2966 if (!p)
2967 p = pstart + strlen(pstart);
2968 len = p - pstart;
2969 if (len > sizeof(cmd) - 2)
2970 len = sizeof(cmd) - 2;
2971 memcpy(cmd, pstart, len);
2972 cmd[len] = '\0';
2973 if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
cd5c6bba 2974 readline_add_completion(mon->rs, cmd);
81d0912d
FB
2975 }
2976 if (*p == '\0')
2977 break;
2978 p++;
2979 }
2980}
2981
cb8f68b1 2982static void file_completion(Monitor *mon, const char *input)
81d0912d
FB
2983{
2984 DIR *ffs;
2985 struct dirent *d;
2986 char path[1024];
2987 char file[1024], file_prefix[1024];
2988 int input_path_len;
2989 const char *p;
2990
5fafdf24 2991 p = strrchr(input, '/');
81d0912d
FB
2992 if (!p) {
2993 input_path_len = 0;
2994 pstrcpy(file_prefix, sizeof(file_prefix), input);
363a37d5 2995 pstrcpy(path, sizeof(path), ".");
81d0912d
FB
2996 } else {
2997 input_path_len = p - input + 1;
2998 memcpy(path, input, input_path_len);
2999 if (input_path_len > sizeof(path) - 1)
3000 input_path_len = sizeof(path) - 1;
3001 path[input_path_len] = '\0';
3002 pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3003 }
19f2db5c 3004
81d0912d
FB
3005 ffs = opendir(path);
3006 if (!ffs)
3007 return;
3008 for(;;) {
3009 struct stat sb;
3010 d = readdir(ffs);
3011 if (!d)
3012 break;
46c7fc18
KK
3013
3014 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
3015 continue;
3016 }
3017
81d0912d
FB
3018 if (strstart(d->d_name, file_prefix, NULL)) {
3019 memcpy(file, input, input_path_len);
363a37d5
BS
3020 if (input_path_len < sizeof(file))
3021 pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3022 d->d_name);
81d0912d
FB
3023 /* stat the file to find out if it's a directory.
3024 * In that case add a slash to speed up typing long paths
3025 */
c951d9a6 3026 if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
363a37d5 3027 pstrcat(file, sizeof(file), "/");
c951d9a6 3028 }
cb8f68b1 3029 readline_add_completion(mon->rs, file);
81d0912d
FB
3030 }
3031 }
3032 closedir(ffs);
3033}
3034
4d76d2ba
LC
3035static const char *next_arg_type(const char *typestr)
3036{
3037 const char *p = strchr(typestr, ':');
3038 return (p != NULL ? ++p : typestr);
3039}
3040
40d19394
HB
3041static void add_completion_option(ReadLineState *rs, const char *str,
3042 const char *option)
3043{
3044 if (!str || !option) {
3045 return;
3046 }
3047 if (!strncmp(option, str, strlen(str))) {
3048 readline_add_completion(rs, option);
3049 }
3050}
3051
13e315da
HB
3052void chardev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3053{
3054 size_t len;
3055 ChardevBackendInfoList *list, *start;
3056
3057 if (nb_args != 2) {
3058 return;
3059 }
3060 len = strlen(str);
3061 readline_set_completion_index(rs, len);
3062
3063 start = list = qmp_query_chardev_backends(NULL);
3064 while (list) {
3065 const char *chr_name = list->value->name;
3066
3067 if (!strncmp(chr_name, str, len)) {
3068 readline_add_completion(rs, chr_name);
3069 }
3070 list = list->next;
3071 }
3072 qapi_free_ChardevBackendInfoList(start);
3073}
3074
b162b49a
HB
3075void netdev_add_completion(ReadLineState *rs, int nb_args, const char *str)
3076{
3077 size_t len;
3078 int i;
3079
3080 if (nb_args != 2) {
3081 return;
3082 }
3083 len = strlen(str);
3084 readline_set_completion_index(rs, len);
f394b2e2
EB
3085 for (i = 0; NetClientDriver_lookup[i]; i++) {
3086 add_completion_option(rs, str, NetClientDriver_lookup[i]);
b162b49a
HB
3087 }
3088}
3089
2da1b3ab 3090void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
992d3e64
HB
3091{
3092 GSList *list, *elt;
3093 size_t len;
3094
2da1b3ab
HB
3095 if (nb_args != 2) {
3096 return;
3097 }
3098
992d3e64
HB
3099 len = strlen(str);
3100 readline_set_completion_index(rs, len);
3101 list = elt = object_class_get_list(TYPE_DEVICE, false);
3102 while (elt) {
3103 const char *name;
3104 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
3105 TYPE_DEVICE);
3106 name = object_class_get_name(OBJECT_CLASS(dc));
2da1b3ab
HB
3107
3108 if (!dc->cannot_instantiate_with_device_add_yet
3109 && !strncmp(name, str, len)) {
992d3e64
HB
3110 readline_add_completion(rs, name);
3111 }
3112 elt = elt->next;
3113 }
3114 g_slist_free(list);
3115}
3116
bfa40f77 3117void object_add_completion(ReadLineState *rs, int nb_args, const char *str)
1094fd3a
HB
3118{
3119 GSList *list, *elt;
3120 size_t len;
3121
bfa40f77
HB
3122 if (nb_args != 2) {
3123 return;
3124 }
3125
1094fd3a
HB
3126 len = strlen(str);
3127 readline_set_completion_index(rs, len);
3128 list = elt = object_class_get_list(TYPE_USER_CREATABLE, false);
3129 while (elt) {
3130 const char *name;
3131
3132 name = object_class_get_name(OBJECT_CLASS(elt->data));
3133 if (!strncmp(name, str, len) && strcmp(name, TYPE_USER_CREATABLE)) {
3134 readline_add_completion(rs, name);
3135 }
3136 elt = elt->next;
3137 }
3138 g_slist_free(list);
3139}
3140
6a1fa9f5
ZG
3141static void peripheral_device_del_completion(ReadLineState *rs,
3142 const char *str, size_t len)
3143{
4cae4d5a
MA
3144 Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
3145 GSList *list, *item;
6a1fa9f5 3146
4cae4d5a
MA
3147 list = qdev_build_hotpluggable_device_list(peripheral);
3148 if (!list) {
6a1fa9f5
ZG
3149 return;
3150 }
3151
6a1fa9f5
ZG
3152 for (item = list; item; item = g_slist_next(item)) {
3153 DeviceState *dev = item->data;
3154
3155 if (dev->id && !strncmp(str, dev->id, len)) {
3156 readline_add_completion(rs, dev->id);
3157 }
3158 }
3159
3160 g_slist_free(list);
3161}
3162
6297d9a2
HB
3163void chardev_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3164{
3165 size_t len;
3166 ChardevInfoList *list, *start;
3167
3168 if (nb_args != 2) {
3169 return;
3170 }
3171 len = strlen(str);
3172 readline_set_completion_index(rs, len);
3173
3174 start = list = qmp_query_chardev(NULL);
3175 while (list) {
3176 ChardevInfo *chr = list->value;
3177
3178 if (!strncmp(chr->label, str, len)) {
3179 readline_add_completion(rs, chr->label);
3180 }
3181 list = list->next;
3182 }
3183 qapi_free_ChardevInfoList(start);
3184}
3185
8e597779
HB
3186static void ringbuf_completion(ReadLineState *rs, const char *str)
3187{
3188 size_t len;
3189 ChardevInfoList *list, *start;
3190
3191 len = strlen(str);
3192 readline_set_completion_index(rs, len);
3193
3194 start = list = qmp_query_chardev(NULL);
3195 while (list) {
3196 ChardevInfo *chr_info = list->value;
3197
3198 if (!strncmp(chr_info->label, str, len)) {
0ec7b3e7 3199 Chardev *chr = qemu_chr_find(chr_info->label);
777357d7 3200 if (chr && CHARDEV_IS_RINGBUF(chr)) {
8e597779
HB
3201 readline_add_completion(rs, chr_info->label);
3202 }
3203 }
3204 list = list->next;
3205 }
3206 qapi_free_ChardevInfoList(start);
3207}
3208
8e597779
HB
3209void ringbuf_write_completion(ReadLineState *rs, int nb_args, const char *str)
3210{
3211 if (nb_args != 2) {
3212 return;
3213 }
3214 ringbuf_completion(rs, str);
3215}
3216
2da1b3ab
HB
3217void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
3218{
3219 size_t len;
3220
3221 if (nb_args != 2) {
3222 return;
3223 }
3224
3225 len = strlen(str);
3226 readline_set_completion_index(rs, len);
6a1fa9f5 3227 peripheral_device_del_completion(rs, str, len);
2da1b3ab
HB
3228}
3229
bfa40f77 3230void object_del_completion(ReadLineState *rs, int nb_args, const char *str)
b48fa074
HB
3231{
3232 ObjectPropertyInfoList *list, *start;
3233 size_t len;
3234
bfa40f77
HB
3235 if (nb_args != 2) {
3236 return;
3237 }
b48fa074
HB
3238 len = strlen(str);
3239 readline_set_completion_index(rs, len);
3240
3241 start = list = qmp_qom_list("/objects", NULL);
3242 while (list) {
3243 ObjectPropertyInfo *info = list->value;
3244
3245 if (!strncmp(info->type, "child<", 5)
3246 && !strncmp(info->name, str, len)) {
3247 readline_add_completion(rs, info->name);
3248 }
3249 list = list->next;
3250 }
3251 qapi_free_ObjectPropertyInfoList(start);
3252}
3253
29136cd8
HB
3254void sendkey_completion(ReadLineState *rs, int nb_args, const char *str)
3255{
3256 int i;
3257 char *sep;
3258 size_t len;
3259
3260 if (nb_args != 2) {
3261 return;
3262 }
3263 sep = strrchr(str, '-');
3264 if (sep) {
3265 str = sep + 1;
3266 }
3267 len = strlen(str);
3268 readline_set_completion_index(rs, len);
7fb1cf16 3269 for (i = 0; i < Q_KEY_CODE__MAX; i++) {
29136cd8
HB
3270 if (!strncmp(str, QKeyCode_lookup[i], len)) {
3271 readline_add_completion(rs, QKeyCode_lookup[i]);
3272 }
3273 }
3274}
3275
40d19394
HB
3276void set_link_completion(ReadLineState *rs, int nb_args, const char *str)
3277{
3278 size_t len;
3279
3280 len = strlen(str);
3281 readline_set_completion_index(rs, len);
3282 if (nb_args == 2) {
eaed483c 3283 NetClientState *ncs[MAX_QUEUE_NUM];
40d19394
HB
3284 int count, i;
3285 count = qemu_find_net_clients_except(NULL, ncs,
f394b2e2 3286 NET_CLIENT_DRIVER_NONE,
eaed483c 3287 MAX_QUEUE_NUM);
bcfa4d60 3288 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
40d19394
HB
3289 const char *name = ncs[i]->name;
3290 if (!strncmp(str, name, len)) {
3291 readline_add_completion(rs, name);
3292 }
3293 }
3294 } else if (nb_args == 3) {
3295 add_completion_option(rs, str, "on");
3296 add_completion_option(rs, str, "off");
3297 }
3298}
3299
11b389f2
HB
3300void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
3301{
3302 int len, count, i;
eaed483c 3303 NetClientState *ncs[MAX_QUEUE_NUM];
11b389f2
HB
3304
3305 if (nb_args != 2) {
3306 return;
3307 }
3308
3309 len = strlen(str);
3310 readline_set_completion_index(rs, len);
f394b2e2 3311 count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_DRIVER_NIC,
eaed483c 3312 MAX_QUEUE_NUM);
bcfa4d60 3313 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
11b389f2
HB
3314 QemuOpts *opts;
3315 const char *name = ncs[i]->name;
3316 if (strncmp(str, name, len)) {
3317 continue;
3318 }
3319 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);
3320 if (opts) {
3321 readline_add_completion(rs, name);
3322 }
3323 }
3324}
3325
bd71211d
LV
3326void info_trace_events_completion(ReadLineState *rs, int nb_args, const char *str)
3327{
3328 size_t len;
3329
3330 len = strlen(str);
3331 readline_set_completion_index(rs, len);
3332 if (nb_args == 2) {
0d4e995c
DB
3333 TraceEventIter iter;
3334 TraceEvent *ev;
3335 char *pattern = g_strdup_printf("%s*", str);
3336 trace_event_iter_init(&iter, pattern);
3337 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3338 readline_add_completion(rs, trace_event_get_name(ev));
bd71211d 3339 }
0d4e995c 3340 g_free(pattern);
bd71211d
LV
3341 }
3342}
3343
987bd270
DDAG
3344void trace_event_completion(ReadLineState *rs, int nb_args, const char *str)
3345{
3346 size_t len;
3347
3348 len = strlen(str);
3349 readline_set_completion_index(rs, len);
3350 if (nb_args == 2) {
0d4e995c
DB
3351 TraceEventIter iter;
3352 TraceEvent *ev;
3353 char *pattern = g_strdup_printf("%s*", str);
3354 trace_event_iter_init(&iter, pattern);
3355 while ((ev = trace_event_iter_next(&iter)) != NULL) {
3356 readline_add_completion(rs, trace_event_get_name(ev));
3357 }
3358 g_free(pattern);
987bd270
DDAG
3359 } else if (nb_args == 3) {
3360 add_completion_option(rs, str, "on");
3361 add_completion_option(rs, str, "off");
3362 }
3363}
3364
d0ece345
HB
3365void watchdog_action_completion(ReadLineState *rs, int nb_args, const char *str)
3366{
4bb08af3
HB
3367 int i;
3368
d0ece345
HB
3369 if (nb_args != 2) {
3370 return;
3371 }
3372 readline_set_completion_index(rs, strlen(str));
4bb08af3
HB
3373 for (i = 0; WatchdogExpirationAction_lookup[i]; i++) {
3374 add_completion_option(rs, str, WatchdogExpirationAction_lookup[i]);
3375 }
d0ece345
HB
3376}
3377
c68a0409
HB
3378void migrate_set_capability_completion(ReadLineState *rs, int nb_args,
3379 const char *str)
3380{
3381 size_t len;
3382
3383 len = strlen(str);
3384 readline_set_completion_index(rs, len);
3385 if (nb_args == 2) {
3386 int i;
7fb1cf16 3387 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
c68a0409
HB
3388 const char *name = MigrationCapability_lookup[i];
3389 if (!strncmp(str, name, len)) {
3390 readline_add_completion(rs, name);
3391 }
3392 }
3393 } else if (nb_args == 3) {
3394 add_completion_option(rs, str, "on");
3395 add_completion_option(rs, str, "off");
3396 }
3397}
3398
50e9a629
LL
3399void migrate_set_parameter_completion(ReadLineState *rs, int nb_args,
3400 const char *str)
3401{
3402 size_t len;
3403
3404 len = strlen(str);
3405 readline_set_completion_index(rs, len);
3406 if (nb_args == 2) {
3407 int i;
7fb1cf16 3408 for (i = 0; i < MIGRATION_PARAMETER__MAX; i++) {
50e9a629
LL
3409 const char *name = MigrationParameter_lookup[i];
3410 if (!strncmp(str, name, len)) {
3411 readline_add_completion(rs, name);
3412 }
3413 }
3414 }
3415}
3416
e3bb532c
HB
3417void host_net_add_completion(ReadLineState *rs, int nb_args, const char *str)
3418{
3419 int i;
3420 size_t len;
3421 if (nb_args != 2) {
3422 return;
3423 }
3424 len = strlen(str);
3425 readline_set_completion_index(rs, len);
3426 for (i = 0; host_net_devices[i]; i++) {
3427 if (!strncmp(host_net_devices[i], str, len)) {
3428 readline_add_completion(rs, host_net_devices[i]);
3429 }
3430 }
3431}
3432
ddd6b45c
HB
3433void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)
3434{
eaed483c 3435 NetClientState *ncs[MAX_QUEUE_NUM];
ddd6b45c
HB
3436 int count, i, len;
3437
3438 len = strlen(str);
3439 readline_set_completion_index(rs, len);
3440 if (nb_args == 2) {
3441 count = qemu_find_net_clients_except(NULL, ncs,
f394b2e2 3442 NET_CLIENT_DRIVER_NONE,
eaed483c 3443 MAX_QUEUE_NUM);
bcfa4d60 3444 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
ddd6b45c
HB
3445 int id;
3446 char name[16];
3447
3448 if (net_hub_id_for_client(ncs[i], &id)) {
3449 continue;
3450 }
3451 snprintf(name, sizeof(name), "%d", id);
3452 if (!strncmp(str, name, len)) {
3453 readline_add_completion(rs, name);
3454 }
3455 }
3456 return;
3457 } else if (nb_args == 3) {
3458 count = qemu_find_net_clients_except(NULL, ncs,
f394b2e2 3459 NET_CLIENT_DRIVER_NIC,
eaed483c 3460 MAX_QUEUE_NUM);
bcfa4d60 3461 for (i = 0; i < MIN(count, MAX_QUEUE_NUM); i++) {
2c4681f5 3462 int id;
ddd6b45c
HB
3463 const char *name;
3464
f394b2e2 3465 if (ncs[i]->info->type == NET_CLIENT_DRIVER_HUBPORT ||
2c4681f5
JW
3466 net_hub_id_for_client(ncs[i], &id)) {
3467 continue;
3468 }
ddd6b45c
HB
3469 name = ncs[i]->name;
3470 if (!strncmp(str, name, len)) {
3471 readline_add_completion(rs, name);
3472 }
3473 }
3474 return;
3475 }
3476}
3477
b21631f3
HB
3478static void vm_completion(ReadLineState *rs, const char *str)
3479{
3480 size_t len;
7c8eece4 3481 BlockDriverState *bs;
88be7b4b 3482 BdrvNextIterator it;
b21631f3
HB
3483
3484 len = strlen(str);
3485 readline_set_completion_index(rs, len);
7c8eece4 3486
88be7b4b 3487 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
b21631f3 3488 SnapshotInfoList *snapshots, *snapshot;
6bf1faa8
DL
3489 AioContext *ctx = bdrv_get_aio_context(bs);
3490 bool ok = false;
b21631f3 3491
6bf1faa8
DL
3492 aio_context_acquire(ctx);
3493 if (bdrv_can_snapshot(bs)) {
3494 ok = bdrv_query_snapshot_info_list(bs, &snapshots, NULL) == 0;
b21631f3 3495 }
6bf1faa8
DL
3496 aio_context_release(ctx);
3497 if (!ok) {
b21631f3
HB
3498 continue;
3499 }
6bf1faa8 3500
b21631f3
HB
3501 snapshot = snapshots;
3502 while (snapshot) {
3503 char *completion = snapshot->value->name;
3504 if (!strncmp(str, completion, len)) {
3505 readline_add_completion(rs, completion);
3506 }
3507 completion = snapshot->value->id;
3508 if (!strncmp(str, completion, len)) {
3509 readline_add_completion(rs, completion);
3510 }
3511 snapshot = snapshot->next;
3512 }
3513 qapi_free_SnapshotInfoList(snapshots);
3514 }
3515
3516}
3517
3518void delvm_completion(ReadLineState *rs, int nb_args, const char *str)
3519{
3520 if (nb_args == 2) {
3521 vm_completion(rs, str);
3522 }
3523}
3524
3525void loadvm_completion(ReadLineState *rs, int nb_args, const char *str)
3526{
3527 if (nb_args == 2) {
3528 vm_completion(rs, str);
3529 }
3530}
3531
c35b6400
WX
3532static void monitor_find_completion_by_table(Monitor *mon,
3533 const mon_cmd_t *cmd_table,
3534 char **args,
3535 int nb_args)
81d0912d
FB
3536{
3537 const char *cmdname;
c35b6400 3538 int i;
fea68bb6 3539 const char *ptype, *str, *name;
c227f099 3540 const mon_cmd_t *cmd;
da27a00e 3541 BlockBackend *blk = NULL;
81d0912d 3542
81d0912d
FB
3543 if (nb_args <= 1) {
3544 /* command completion */
3545 if (nb_args == 0)
3546 cmdname = "";
3547 else
3548 cmdname = args[0];
d2674b2c 3549 readline_set_completion_index(mon->rs, strlen(cmdname));
c35b6400 3550 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
cd5c6bba 3551 cmd_completion(mon, cmdname, cmd->name);
81d0912d
FB
3552 }
3553 } else {
3554 /* find the command */
c35b6400 3555 for (cmd = cmd_table; cmd->name != NULL; cmd++) {
03a63484
JK
3556 if (compare_cmd(args[0], cmd->name)) {
3557 break;
3558 }
81d0912d 3559 }
03a63484 3560 if (!cmd->name) {
c35b6400 3561 return;
03a63484
JK
3562 }
3563
d903a779
WX
3564 if (cmd->sub_table) {
3565 /* do the job again */
e7ae771f
SW
3566 monitor_find_completion_by_table(mon, cmd->sub_table,
3567 &args[1], nb_args - 1);
3568 return;
d903a779 3569 }
bfa40f77 3570 if (cmd->command_completion) {
e7ae771f
SW
3571 cmd->command_completion(mon->rs, nb_args, args[nb_args - 1]);
3572 return;
bfa40f77 3573 }
d903a779 3574
4d76d2ba 3575 ptype = next_arg_type(cmd->args_type);
81d0912d
FB
3576 for(i = 0; i < nb_args - 2; i++) {
3577 if (*ptype != '\0') {
4d76d2ba 3578 ptype = next_arg_type(ptype);
81d0912d 3579 while (*ptype == '?')
4d76d2ba 3580 ptype = next_arg_type(ptype);
81d0912d
FB
3581 }
3582 }
3583 str = args[nb_args - 1];
48fe86f6 3584 while (*ptype == '-' && ptype[1] != '\0') {
3b6dbf27 3585 ptype = next_arg_type(ptype);
2a1704a7 3586 }
81d0912d
FB
3587 switch(*ptype) {
3588 case 'F':
3589 /* file completion */
d2674b2c 3590 readline_set_completion_index(mon->rs, strlen(str));
cb8f68b1 3591 file_completion(mon, str);
81d0912d
FB
3592 break;
3593 case 'B':
3594 /* block device name completion */
599a926a 3595 readline_set_completion_index(mon->rs, strlen(str));
da27a00e
HR
3596 while ((blk = blk_next(blk)) != NULL) {
3597 name = blk_name(blk);
fea68bb6
MA
3598 if (str[0] == '\0' ||
3599 !strncmp(name, str, strlen(str))) {
3600 readline_add_completion(mon->rs, name);
3601 }
3602 }
81d0912d 3603 break;
7fe48483 3604 case 's':
129be006 3605 case 'S':
29136cd8 3606 if (!strcmp(cmd->name, "help|?")) {
7ca0e061
WX
3607 monitor_find_completion_by_table(mon, cmd_table,
3608 &args[1], nb_args - 1);
7fe48483
FB
3609 }
3610 break;
81d0912d
FB
3611 default:
3612 break;
3613 }
3614 }
c35b6400
WX
3615}
3616
c60bf339 3617static void monitor_find_completion(void *opaque,
c35b6400
WX
3618 const char *cmdline)
3619{
c60bf339 3620 Monitor *mon = opaque;
c35b6400
WX
3621 char *args[MAX_ARGS];
3622 int nb_args, len;
3623
3624 /* 1. parse the cmdline */
3625 if (parse_cmdline(cmdline, &nb_args, args) < 0) {
3626 return;
3627 }
c35b6400
WX
3628
3629 /* if the line ends with a space, it means we want to complete the
3630 next arg */
3631 len = strlen(cmdline);
3632 if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3633 if (nb_args >= MAX_ARGS) {
3634 goto cleanup;
3635 }
3636 args[nb_args++] = g_strdup("");
3637 }
3638
3639 /* 2. auto complete according to args */
3640 monitor_find_completion_by_table(mon, mon->cmd_table, args, nb_args);
03a63484
JK
3641
3642cleanup:
dcc70cdf 3643 free_cmdline_args(args, nb_args);
81d0912d
FB
3644}
3645
731b0364 3646static int monitor_can_read(void *opaque)
9dc39cba 3647{
731b0364
AL
3648 Monitor *mon = opaque;
3649
c62313bb 3650 return (mon->suspend_cnt == 0) ? 1 : 0;
9dc39cba
FB
3651}
3652
d79bedfa 3653static bool invalid_qmp_mode(const Monitor *mon, const char *cmd,
4086182f 3654 Error **errp)
5fa737a4 3655{
d79bedfa 3656 bool is_cap = g_str_equal(cmd, "qmp_capabilities");
f994b258
MA
3657
3658 if (is_cap && mon->qmp.in_command_mode) {
4086182f
MA
3659 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3660 "Capabilities negotiation is already complete, command "
d79bedfa 3661 "'%s' ignored", cmd);
2d5a8346
EB
3662 return true;
3663 }
f994b258 3664 if (!is_cap && !mon->qmp.in_command_mode) {
4086182f
MA
3665 error_set(errp, ERROR_CLASS_COMMAND_NOT_FOUND,
3666 "Expecting capabilities negotiation with "
d79bedfa 3667 "'qmp_capabilities' before command '%s'", cmd);
2d5a8346
EB
3668 return true;
3669 }
3670 return false;
5fa737a4
LC
3671}
3672
5fa737a4 3673/*
c917c8f3 3674 * Input object checking rules
5fa737a4 3675 *
c917c8f3
LC
3676 * 1. Input object must be a dict
3677 * 2. The "execute" key must exist
3678 * 3. The "execute" key must be a string
3679 * 4. If the "arguments" key exists, it must be a dict
3680 * 5. If the "id" key exists, it can be anything (ie. json-value)
3681 * 6. Any argument not listed above is considered invalid
5fa737a4 3682 */
ba0510aa 3683static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)
5fa737a4 3684{
c917c8f3
LC
3685 const QDictEntry *ent;
3686 int has_exec_key = 0;
3687 QDict *input_dict;
5fa737a4 3688
c917c8f3 3689 if (qobject_type(input_obj) != QTYPE_QDICT) {
c6bd8c70 3690 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");
c917c8f3 3691 return NULL;
5fa737a4
LC
3692 }
3693
c917c8f3 3694 input_dict = qobject_to_qdict(input_obj);
5fa737a4 3695
c917c8f3
LC
3696 for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
3697 const char *arg_name = qdict_entry_key(ent);
3698 const QObject *arg_obj = qdict_entry_value(ent);
5fa737a4 3699
c917c8f3
LC
3700 if (!strcmp(arg_name, "execute")) {
3701 if (qobject_type(arg_obj) != QTYPE_QSTRING) {
c6bd8c70
MA
3702 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3703 "execute", "string");
c917c8f3 3704 return NULL;
361127df 3705 }
c917c8f3
LC
3706 has_exec_key = 1;
3707 } else if (!strcmp(arg_name, "arguments")) {
3708 if (qobject_type(arg_obj) != QTYPE_QDICT) {
c6bd8c70
MA
3709 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
3710 "arguments", "object");
c917c8f3 3711 return NULL;
5fa737a4 3712 }
779cec4d
MA
3713 } else if (!strcmp(arg_name, "id")) {
3714 /* Any string is acceptable as "id", so nothing to check */
5fa737a4 3715 } else {
c6bd8c70 3716 error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);
c917c8f3 3717 return NULL;
5fa737a4
LC
3718 }
3719 }
3720
c917c8f3 3721 if (!has_exec_key) {
c6bd8c70 3722 error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");
c917c8f3
LC
3723 return NULL;
3724 }
5fa737a4 3725
c917c8f3 3726 return input_dict;
09069b19
LC
3727}
3728
95385fe9 3729static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)
5fa737a4 3730{
5c678ee8
MAL
3731 QObject *req, *rsp = NULL, *id = NULL;
3732 QDict *qdict = NULL;
40e5a01d 3733 const char *cmd_name;
5fa737a4 3734 Monitor *mon = cur_mon;
5c678ee8 3735 Error *err = NULL;
5fa737a4 3736
5c678ee8
MAL
3737 req = json_parser_parse_err(tokens, NULL, &err);
3738 if (err || !req || qobject_type(req) != QTYPE_QDICT) {
3739 if (!err) {
3740 error_setg(&err, QERR_JSON_PARSING);
3741 }
5fa737a4 3742 goto err_out;
5fa737a4
LC
3743 }
3744
5c678ee8
MAL
3745 qdict = qmp_check_input_obj(req, &err);
3746 if (!qdict) {
5fa737a4
LC
3747 goto err_out;
3748 }
3749
5c678ee8
MAL
3750 id = qdict_get(qdict, "id");
3751 qobject_incref(id);
3752 qdict_del(qdict, "id");
5fa737a4 3753
5c678ee8 3754 cmd_name = qdict_get_str(qdict, "execute");
89bd820a 3755 trace_handle_qmp_command(mon, cmd_name);
5c678ee8
MAL
3756
3757 if (invalid_qmp_mode(mon, cmd_name, &err)) {
2d5a8346
EB
3758 goto err_out;
3759 }
5fa737a4 3760
5c678ee8 3761 rsp = qmp_dispatch(req);
5fa737a4 3762
5c678ee8
MAL
3763err_out:
3764 if (err) {
3765 qdict = qdict_new();
3766 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
3767 error_free(err);
3768 rsp = QOBJECT(qdict);
5fa737a4
LC
3769 }
3770
5c678ee8
MAL
3771 if (rsp) {
3772 if (id) {
3773 qdict_put_obj(qobject_to_qdict(rsp), "id", id);
3774 id = NULL;
3775 }
5fa737a4 3776
5c678ee8
MAL
3777 monitor_json_emitter(mon, rsp);
3778 }
3779
3780 qobject_decref(id);
3781 qobject_decref(rsp);
3782 qobject_decref(req);
5fa737a4
LC
3783}
3784
c83fe23b 3785static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
9b57c02e
LC
3786{
3787 Monitor *old_mon = cur_mon;
3788
3789 cur_mon = opaque;
3790
74358f2a 3791 json_message_parser_feed(&cur_mon->qmp.parser, (const char *) buf, size);
9b57c02e
LC
3792
3793 cur_mon = old_mon;
3794}
3795
731b0364 3796static void monitor_read(void *opaque, const uint8_t *buf, int size)
9dc39cba 3797{
731b0364 3798 Monitor *old_mon = cur_mon;
7e2515e8 3799 int i;
376253ec 3800
731b0364
AL
3801 cur_mon = opaque;
3802
cde76ee1
AL
3803 if (cur_mon->rs) {
3804 for (i = 0; i < size; i++)
3805 readline_handle_byte(cur_mon->rs, buf[i]);
3806 } else {
3807 if (size == 0 || buf[size - 1] != 0)
3808 monitor_printf(cur_mon, "corrupted command\n");
3809 else
7ef6cf63 3810 handle_hmp_command(cur_mon, (char *)buf);
cde76ee1 3811 }
9dc39cba 3812
731b0364
AL
3813 cur_mon = old_mon;
3814}
d8f44609 3815
c60bf339
SH
3816static void monitor_command_cb(void *opaque, const char *cmdline,
3817 void *readline_opaque)
aa455485 3818{
c60bf339
SH
3819 Monitor *mon = opaque;
3820
731b0364 3821 monitor_suspend(mon);
7ef6cf63 3822 handle_hmp_command(mon, cmdline);
731b0364 3823 monitor_resume(mon);
d8f44609
AL
3824}
3825
cde76ee1 3826int monitor_suspend(Monitor *mon)
d8f44609 3827{
cde76ee1
AL
3828 if (!mon->rs)
3829 return -ENOTTY;
731b0364 3830 mon->suspend_cnt++;
cde76ee1 3831 return 0;
d8f44609
AL
3832}
3833
376253ec 3834void monitor_resume(Monitor *mon)
d8f44609 3835{
cde76ee1
AL
3836 if (!mon->rs)
3837 return;
731b0364
AL
3838 if (--mon->suspend_cnt == 0)
3839 readline_show_prompt(mon->rs);
aa455485
FB
3840}
3841
ca9567e2
LC
3842static QObject *get_qmp_greeting(void)
3843{
b9c15f16 3844 QObject *ver = NULL;
ca9567e2 3845
7fad30f0 3846 qmp_marshal_query_version(NULL, &ver, NULL);
c823501e
MAL
3847
3848 return qobject_from_jsonf("{'QMP': {'version': %p, 'capabilities': []}}",
3849 ver);
ca9567e2
LC
3850}
3851
c83fe23b 3852static void monitor_qmp_event(void *opaque, int event)
9b57c02e 3853{
47116d1c
LC
3854 QObject *data;
3855 Monitor *mon = opaque;
9b57c02e 3856
47116d1c
LC
3857 switch (event) {
3858 case CHR_EVENT_OPENED:
f994b258 3859 mon->qmp.in_command_mode = false;
ca9567e2 3860 data = get_qmp_greeting();
9b57c02e
LC
3861 monitor_json_emitter(mon, data);
3862 qobject_decref(data);
efb87c16 3863 mon_refcount++;
47116d1c
LC
3864 break;
3865 case CHR_EVENT_CLOSED:
74358f2a
MA
3866 json_message_parser_destroy(&mon->qmp.parser);
3867 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
efb87c16
CB
3868 mon_refcount--;
3869 monitor_fdsets_cleanup();
47116d1c 3870 break;
9b57c02e
LC
3871 }
3872}
3873
731b0364 3874static void monitor_event(void *opaque, int event)
86e94dea 3875{
376253ec
AL
3876 Monitor *mon = opaque;
3877
2724b180
AL
3878 switch (event) {
3879 case CHR_EVENT_MUX_IN:
6cff3e85 3880 qemu_mutex_lock(&mon->out_lock);
a7aec5da 3881 mon->mux_out = 0;
6cff3e85 3882 qemu_mutex_unlock(&mon->out_lock);
a7aec5da
GH
3883 if (mon->reset_seen) {
3884 readline_restart(mon->rs);
3885 monitor_resume(mon);
3886 monitor_flush(mon);
3887 } else {
3888 mon->suspend_cnt = 0;
3889 }
2724b180
AL
3890 break;
3891
3892 case CHR_EVENT_MUX_OUT:
a7aec5da
GH
3893 if (mon->reset_seen) {
3894 if (mon->suspend_cnt == 0) {
3895 monitor_printf(mon, "\n");
3896 }
3897 monitor_flush(mon);
3898 monitor_suspend(mon);
3899 } else {
3900 mon->suspend_cnt++;
3901 }
6cff3e85 3902 qemu_mutex_lock(&mon->out_lock);
a7aec5da 3903 mon->mux_out = 1;
6cff3e85 3904 qemu_mutex_unlock(&mon->out_lock);
2724b180 3905 break;
86e94dea 3906
b6b8df56 3907 case CHR_EVENT_OPENED:
2724b180
AL
3908 monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
3909 "information\n", QEMU_VERSION);
a7aec5da 3910 if (!mon->mux_out) {
e5554e20 3911 readline_restart(mon->rs);
2724b180 3912 readline_show_prompt(mon->rs);
a7aec5da
GH
3913 }
3914 mon->reset_seen = 1;
efb87c16
CB
3915 mon_refcount++;
3916 break;
3917
3918 case CHR_EVENT_CLOSED:
3919 mon_refcount--;
3920 monitor_fdsets_cleanup();
2724b180
AL
3921 break;
3922 }
86e94dea
TS
3923}
3924
816f8925
WX
3925static int
3926compare_mon_cmd(const void *a, const void *b)
3927{
3928 return strcmp(((const mon_cmd_t *)a)->name,
3929 ((const mon_cmd_t *)b)->name);
3930}
3931
3932static void sortcmdlist(void)
3933{
3934 int array_num;
3935 int elem_size = sizeof(mon_cmd_t);
3936
3937 array_num = sizeof(mon_cmds)/elem_size-1;
3938 qsort((void *)mon_cmds, array_num, elem_size, compare_mon_cmd);
3939
3940 array_num = sizeof(info_cmds)/elem_size-1;
3941 qsort((void *)info_cmds, array_num, elem_size, compare_mon_cmd);
3942}
3943
c60bf339
SH
3944/* These functions just adapt the readline interface in a typesafe way. We
3945 * could cast function pointers but that discards compiler checks.
3946 */
d5d1507b
SW
3947static void GCC_FMT_ATTR(2, 3) monitor_readline_printf(void *opaque,
3948 const char *fmt, ...)
c60bf339
SH
3949{
3950 va_list ap;
3951 va_start(ap, fmt);
3952 monitor_vprintf(opaque, fmt, ap);
3953 va_end(ap);
3954}
3955
3956static void monitor_readline_flush(void *opaque)
3957{
3958 monitor_flush(opaque);
3959}
3960
397d30e9
PB
3961/*
3962 * Print to current monitor if we have one, else to stderr.
3963 * TODO should return int, so callers can calculate width, but that
3964 * requires surgery to monitor_vprintf(). Left for another day.
3965 */
3966void error_vprintf(const char *fmt, va_list ap)
3967{
3968 if (cur_mon && !monitor_cur_is_qmp()) {
3969 monitor_vprintf(cur_mon, fmt, ap);
3970 } else {
3971 vfprintf(stderr, fmt, ap);
3972 }
3973}
3974
3975void error_vprintf_unless_qmp(const char *fmt, va_list ap)
3976{
3977 if (cur_mon && !monitor_cur_is_qmp()) {
3978 monitor_vprintf(cur_mon, fmt, ap);
0d6b50d4
MAL
3979 } else if (!cur_mon) {
3980 vfprintf(stderr, fmt, ap);
397d30e9
PB
3981 }
3982}
3983
d622cb58
PB
3984static void __attribute__((constructor)) monitor_lock_init(void)
3985{
3986 qemu_mutex_init(&monitor_lock);
3987}
3988
0ec7b3e7 3989void monitor_init(Chardev *chr, int flags)
aa455485 3990{
731b0364 3991 static int is_first_init = 1;
87127161 3992 Monitor *mon;
20d8a3ed
TS
3993
3994 if (is_first_init) {
43a14cfc 3995 monitor_qapi_event_init();
d038317c 3996 sortcmdlist();
20d8a3ed
TS
3997 is_first_init = 0;
3998 }
87127161 3999
b01fe89e
WX
4000 mon = g_malloc(sizeof(*mon));
4001 monitor_data_init(mon);
20d8a3ed 4002
32a6ebec 4003 qemu_chr_fe_init(&mon->chr, chr, &error_abort);
731b0364 4004 mon->flags = flags;
cde76ee1 4005 if (flags & MONITOR_USE_READLINE) {
c60bf339
SH
4006 mon->rs = readline_init(monitor_readline_printf,
4007 monitor_readline_flush,
4008 mon,
4009 monitor_find_completion);
cde76ee1
AL
4010 monitor_read_command(mon, 0);
4011 }
87127161 4012
9f3982f2 4013 if (monitor_is_qmp(mon)) {
5345fdb4 4014 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_qmp_read,
39ab61c6 4015 monitor_qmp_event, mon, NULL, true);
5345fdb4 4016 qemu_chr_fe_set_echo(&mon->chr, true);
74358f2a 4017 json_message_parser_init(&mon->qmp.parser, handle_qmp_command);
9b57c02e 4018 } else {
5345fdb4 4019 qemu_chr_fe_set_handlers(&mon->chr, monitor_can_read, monitor_read,
39ab61c6 4020 monitor_event, mon, NULL, true);
9b57c02e 4021 }
87127161 4022
d622cb58 4023 qemu_mutex_lock(&monitor_lock);
72cf2d4f 4024 QLIST_INSERT_HEAD(&mon_list, mon, entry);
d622cb58 4025 qemu_mutex_unlock(&monitor_lock);
aa455485
FB
4026}
4027
2ef45716
MAL
4028void monitor_cleanup(void)
4029{
4030 Monitor *mon, *next;
4031
4032 qemu_mutex_lock(&monitor_lock);
4033 QLIST_FOREACH_SAFE(mon, &mon_list, entry, next) {
4034 QLIST_REMOVE(mon, entry);
4035 monitor_data_destroy(mon);
4036 g_free(mon);
4037 }
4038 qemu_mutex_unlock(&monitor_lock);
4039}
4040
c60bf339
SH
4041static void bdrv_password_cb(void *opaque, const char *password,
4042 void *readline_opaque)
81d0912d 4043{
c60bf339
SH
4044 Monitor *mon = opaque;
4045 BlockDriverState *bs = readline_opaque;
bb5fc20f 4046 int ret = 0;
4d2855a3 4047 Error *local_err = NULL;
81d0912d 4048
4d2855a3
MA
4049 bdrv_add_key(bs, password, &local_err);
4050 if (local_err) {
193227f9 4051 error_report_err(local_err);
bb5fc20f 4052 ret = -EPERM;
9dc39cba 4053 }
731b0364
AL
4054 if (mon->password_completion_cb)
4055 mon->password_completion_cb(mon->password_opaque, ret);
bb5fc20f 4056
731b0364 4057 monitor_read_command(mon, 1);
9dc39cba 4058}
c0f4ce77 4059
0bbc47bb 4060int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
097310b5 4061 BlockCompletionFunc *completion_cb,
0bbc47bb 4062 void *opaque)
c0f4ce77 4063{
cde76ee1
AL
4064 int err;
4065
376253ec
AL
4066 monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4067 bdrv_get_encrypted_filename(bs));
bb5fc20f 4068
731b0364
AL
4069 mon->password_completion_cb = completion_cb;
4070 mon->password_opaque = opaque;
bb5fc20f 4071
cde76ee1
AL
4072 err = monitor_read_password(mon, bdrv_password_cb, bs);
4073
4074 if (err && completion_cb)
4075 completion_cb(opaque, err);
0bbc47bb
LC
4076
4077 return err;
c0f4ce77 4078}
e42e818b
LC
4079
4080int monitor_read_block_device_key(Monitor *mon, const char *device,
097310b5 4081 BlockCompletionFunc *completion_cb,
e42e818b
LC
4082 void *opaque)
4083{
9b14e0ef 4084 Error *err = NULL;
5560625b 4085 BlockBackend *blk;
e42e818b 4086
5560625b
FZ
4087 blk = blk_by_name(device);
4088 if (!blk) {
e42e818b
LC
4089 monitor_printf(mon, "Device not found %s\n", device);
4090 return -1;
4091 }
5433c24f
HR
4092 if (!blk_bs(blk)) {
4093 monitor_printf(mon, "Device '%s' has no medium\n", device);
4094 return -1;
4095 }
e42e818b 4096
9b14e0ef
MA
4097 bdrv_add_key(blk_bs(blk), NULL, &err);
4098 if (err) {
4099 error_free(err);
4100 return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);
4101 }
4102
4103 if (completion_cb) {
4104 completion_cb(opaque, 0);
4105 }
4106 return 0;
e42e818b 4107}
4d454574
PB
4108
4109QemuOptsList qemu_mon_opts = {
4110 .name = "mon",
4111 .implied_opt_name = "chardev",
4112 .head = QTAILQ_HEAD_INITIALIZER(qemu_mon_opts.head),
4113 .desc = {
4114 {
4115 .name = "mode",
4116 .type = QEMU_OPT_STRING,
4117 },{
4118 .name = "chardev",
4119 .type = QEMU_OPT_STRING,
4120 },{
bdbcb547 4121 .name = "default", /* deprecated */
4d454574
PB
4122 .type = QEMU_OPT_BOOL,
4123 },{
4124 .name = "pretty",
4125 .type = QEMU_OPT_BOOL,
4126 },
4127 { /* end of list */ }
4128 },
4129};
f2ae8abf
MT
4130
4131#ifndef TARGET_I386
4132void qmp_rtc_reset_reinjection(Error **errp)
4133{
c6bd8c70 4134 error_setg(errp, QERR_FEATURE_DISABLED, "rtc-reset-reinjection");
f2ae8abf
MT
4135}
4136#endif
7ee0c3e3
JH
4137
4138#ifndef TARGET_S390X
4139void qmp_dump_skeys(const char *filename, Error **errp)
4140{
4141 error_setg(errp, QERR_FEATURE_DISABLED, "dump-skeys");
4142}
4143#endif
ae50a770
PX
4144
4145#ifndef TARGET_ARM
4146GICCapabilityList *qmp_query_gic_capabilities(Error **errp)
4147{
4148 error_setg(errp, QERR_FEATURE_DISABLED, "query-gic-capabilities");
4149 return NULL;
4150}
4151#endif
d4633541
IM
4152
4153HotpluggableCPUList *qmp_query_hotpluggable_cpus(Error **errp)
4154{
4155 MachineState *ms = MACHINE(qdev_get_machine());
4156 MachineClass *mc = MACHINE_GET_CLASS(ms);
4157
4158 if (!mc->query_hotpluggable_cpus) {
4159 error_setg(errp, QERR_FEATURE_DISABLED, "query-hotpluggable-cpus");
4160 return NULL;
4161 }
4162
4163 return mc->query_hotpluggable_cpus(ms);
4164}