monitor.c 114 KB
Newer Older
bellard's avatar
bellard committed
1 2
/*
 * QEMU monitor
3
 *
bellard's avatar
bellard committed
4
 * Copyright (c) 2003-2004 Fabrice Bellard
5
 *
bellard's avatar
bellard committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
Peter Maydell's avatar
Peter Maydell committed
24
#include "qemu/osdep.h"
25
#include <dirent.h>
26 27
#include "qemu-common.h"
#include "cpu.h"
pbrook's avatar
pbrook committed
28
#include "hw/hw.h"
29
#include "monitor/qdev.h"
pbrook's avatar
pbrook committed
30
#include "hw/usb.h"
31
#include "hw/i386/pc.h"
32
#include "hw/pci/pci.h"
33
#include "sysemu/watchdog.h"
34
#include "hw/loader.h"
35
#include "exec/gdbstub.h"
Paolo Bonzini's avatar
Paolo Bonzini committed
36
#include "net/net.h"
37
#include "net/slirp.h"
38
#include "sysemu/char.h"
39
#include "ui/qemu-spice.h"
40
#include "sysemu/sysemu.h"
41
#include "sysemu/numa.h"
42
#include "monitor/monitor.h"
43
#include "qemu/readline.h"
44
#include "ui/console.h"
45
#include "ui/input.h"
46
#include "sysemu/blockdev.h"
47
#include "sysemu/block-backend.h"
pbrook's avatar
pbrook committed
48
#include "audio/audio.h"
49
#include "disas/disas.h"
50
#include "sysemu/balloon.h"
51
#include "qemu/timer.h"
52
#include "migration/migration.h"
53
#include "sysemu/kvm.h"
54
#include "qemu/acl.h"
55
#include "sysemu/tpm.h"
56
#include "qapi/qmp/qerror.h"
57 58 59 60 61 62 63 64
#include "qapi/qmp/qint.h"
#include "qapi/qmp/qfloat.h"
#include "qapi/qmp/qlist.h"
#include "qapi/qmp/qbool.h"
#include "qapi/qmp/qstring.h"
#include "qapi/qmp/qjson.h"
#include "qapi/qmp/json-streamer.h"
#include "qapi/qmp/json-parser.h"
65
#include <qom/object_interfaces.h>
66
#include "cpu.h"
67
#include "trace.h"
68
#include "trace/control.h"
69
#include "monitor/hmp-target.h"
70
#ifdef CONFIG_TRACE_SIMPLE
71
#include "trace/simple.h"
72
#endif
73
#include "exec/memory.h"
74
#include "exec/exec-all.h"
75
#include "qemu/log.h"
76 77
#include "qmp-commands.h"
#include "hmp.h"
78
#include "qemu/thread.h"
79
#include "block/qapi.h"
80 81
#include "qapi/qmp-event.h"
#include "qapi-event.h"
82
#include "qmp-introspect.h"
83
#include "sysemu/block-backend.h"
84
#include "sysemu/qtest.h"
85
#include "qemu/cutils.h"
ths's avatar
ths committed
86

87
/* for hmp_info_irq/pic */
88
#if defined(TARGET_SPARC)
89
#include "hw/sparc/sun4m.h"
90
#endif
91
#include "hw/lm32/lm32_pic.h"
92

93 94 95 96
#if defined(TARGET_S390X)
#include "hw/s390x/storage-keys.h"
#endif

97 98
/*
 * Supported types:
99
 *
100
 * 'F'          filename
bellard's avatar
bellard committed
101
 * 'B'          block device name
102
 * 's'          string (accept optional quote)
103
 * 'S'          it just appends the rest of the string (accept optional quote)
104 105 106 107 108
 * 'O'          option string of the form NAME=VALUE,...
 *              parsed according to QemuOptsList given by its name
 *              Example: 'device:O' uses qemu_device_opts.
 *              Restriction: only lists with empty desc are supported
 *              TODO lift the restriction
bellard's avatar
bellard committed
109 110
 * 'i'          32 bit integer
 * 'l'          target long (32 or 64 bit)
111 112
 * 'M'          Non-negative target long (32 or 64 bit), in user mode the
 *              value is multiplied by 2^20 (think Mebibyte)
113
 * 'o'          octets (aka bytes)
114 115 116 117
 *              user mode accepts an optional E, e, P, p, T, t, G, g, M, m,
 *              K, k suffix, which multiplies the value by 2^60 for suffixes E
 *              and e, 2^50 for suffixes P and p, 2^40 for suffixes T and t,
 *              2^30 for suffixes G and g, 2^20 for M and m, 2^10 for K and k
118 119 120
 * 'T'          double
 *              user mode accepts an optional ms, us, ns suffix,
 *              which divides the value by 1e3, 1e6, 1e9, respectively
121 122
 * '/'          optional gdb-like print format (like "/10x")
 *
123 124
 * '?'          optional type (for all types, except '/')
 * '.'          other form of optional type (for 'i' and 'l')
125 126
 * 'b'          boolean
 *              user mode accepts "on" or "off"
127
 * '-'          optional parameter (eg. '-f')
128 129 130
 *
 */

131
typedef struct mon_cmd_t {
bellard's avatar
bellard committed
132
    const char *name;
133
    const char *args_type;
bellard's avatar
bellard committed
134 135
    const char *params;
    const char *help;
136
    union {
137
        void (*cmd)(Monitor *mon, const QDict *qdict);
138
        void (*cmd_new)(QDict *params, QObject **ret_data, Error **errp);
139
    } mhandler;
140 141 142 143 144
    /* @sub_table is a list of 2nd level of commands. If it do not exist,
     * mhandler should be used. If it exist, sub_table[?].mhandler should be
     * used, and mhandler of 1st level plays the role of help function.
     */
    struct mon_cmd_t *sub_table;
145
    void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
146
} mon_cmd_t;
bellard's avatar
bellard committed
147

148
/* file descriptors passed via SCM_RIGHTS */
149 150
typedef struct mon_fd_t mon_fd_t;
struct mon_fd_t {
151 152
    char *name;
    int fd;
153
    QLIST_ENTRY(mon_fd_t) next;
154 155
};

156 157 158 159 160 161 162 163 164 165 166 167 168 169
/* file descriptor associated with a file descriptor set */
typedef struct MonFdsetFd MonFdsetFd;
struct MonFdsetFd {
    int fd;
    bool removed;
    char *opaque;
    QLIST_ENTRY(MonFdsetFd) next;
};

/* file descriptor set containing fds passed via SCM_RIGHTS */
typedef struct MonFdset MonFdset;
struct MonFdset {
    int64_t id;
    QLIST_HEAD(, MonFdsetFd) fds;
170
    QLIST_HEAD(, MonFdsetFd) dup_fds;
171 172 173
    QLIST_ENTRY(MonFdset) next;
};

174
typedef struct {
Luiz Capitulino's avatar
Luiz Capitulino committed
175 176
    QObject *id;
    JSONMessageParser parser;
177 178 179 180 181 182
    /*
     * When a client connects, we're in capabilities negotiation mode.
     * When command qmp_capabilities succeeds, we go into command
     * mode.
     */
    bool in_command_mode;       /* are we in command mode? */
183
} MonitorQMP;
Luiz Capitulino's avatar
Luiz Capitulino committed
184

185 186 187 188 189
/*
 * To prevent flooding clients, events can be throttled. The
 * throttling is calculated globally, rather than per-Monitor
 * instance.
 */
190
typedef struct MonitorQAPIEventState {
191 192
    QAPIEvent event;    /* Throttling state for this event type and... */
    QDict *data;        /* ... data, see qapi_event_throttle_equal() */
193
    QEMUTimer *timer;   /* Timer for handling delayed events */
194
    QDict *qdict;       /* Delayed event (if any) */
195
} MonitorQAPIEventState;
196

197 198 199 200
typedef struct {
    int64_t rate;       /* Minimum time (in ns) between two events */
} MonitorQAPIEventConf;

201 202
struct Monitor {
    CharDriverState *chr;
Gerd Hoffmann's avatar
Gerd Hoffmann committed
203
    int reset_seen;
204 205
    int flags;
    int suspend_cnt;
206
    bool skip_flush;
207 208

    QemuMutex out_lock;
209
    QString *outbuf;
210 211 212 213 214
    guint out_watch;

    /* Read under either BQL or out_lock, written with BQL+out_lock.  */
    int mux_out;

215
    ReadLineState *rs;
216
    MonitorQMP qmp;
217
    CPUState *mon_cpu;
218
    BlockCompletionFunc *password_completion_cb;
219
    void *password_opaque;
220
    mon_cmd_t *cmd_table;
221
    QLIST_HEAD(,mon_fd_t) fds;
222
    QLIST_ENTRY(Monitor) entry;
223 224
};

225 226 227
/* QMP checker flags */
#define QMP_ACCEPT_UNKNOWNS 1

228 229 230
/* Protects mon_list, monitor_event_state.  */
static QemuMutex monitor_lock;

231
static QLIST_HEAD(mon_list, Monitor) mon_list;
232
static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
233
static int mon_refcount;
234

235 236
static mon_cmd_t mon_cmds[];
static mon_cmd_t info_cmds[];
bellard's avatar
bellard committed
237

238 239
static const mon_cmd_t qmp_cmds[];

240
Monitor *cur_mon;
241

242 243
static QEMUClockType event_clock_type = QEMU_CLOCK_REALTIME;

244 245
static void monitor_command_cb(void *opaque, const char *cmdline,
                               void *readline_opaque);
246

247 248 249 250
/**
 * Is @mon a QMP monitor?
 */
static inline bool monitor_is_qmp(const Monitor *mon)
251 252 253 254
{
    return (mon->flags & MONITOR_USE_CONTROL);
}

255 256 257 258
/**
 * Is the current monitor, if any, a QMP monitor?
 */
bool monitor_cur_is_qmp(void)
259
{
260
    return cur_mon && monitor_is_qmp(cur_mon);
261 262
}

263
void monitor_read_command(Monitor *mon, int show_prompt)
264
{
265 266 267
    if (!mon->rs)
        return;

268 269 270 271
    readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
    if (show_prompt)
        readline_show_prompt(mon->rs);
}
bellard's avatar
bellard committed
272

273 274
int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
                          void *opaque)
275
{
276
    if (mon->rs) {
277 278 279 280 281 282 283
        readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
        /* prompt is printed on return from the command handler */
        return 0;
    } else {
        monitor_printf(mon, "terminal does not support password prompting\n");
        return -ENOTTY;
    }
284 285
}

286 287
static void monitor_flush_locked(Monitor *mon);

Gerd Hoffmann's avatar
Gerd Hoffmann committed
288 289 290
static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
                                  void *opaque)
{
291 292
    Monitor *mon = opaque;

293 294 295 296
    qemu_mutex_lock(&mon->out_lock);
    mon->out_watch = 0;
    monitor_flush_locked(mon);
    qemu_mutex_unlock(&mon->out_lock);
Gerd Hoffmann's avatar
Gerd Hoffmann committed
297 298 299
    return FALSE;
}

300 301
/* Called with mon->out_lock held.  */
static void monitor_flush_locked(Monitor *mon)
302
{
Gerd Hoffmann's avatar
Gerd Hoffmann committed
303
    int rc;
304 305 306
    size_t len;
    const char *buf;

307 308 309 310
    if (mon->skip_flush) {
        return;
    }

311 312
    buf = qstring_get_str(mon->outbuf);
    len = qstring_get_length(mon->outbuf);
Gerd Hoffmann's avatar
Gerd Hoffmann committed
313

314
    if (len && !mon->mux_out) {
315
        rc = qemu_chr_fe_write(mon->chr, (const uint8_t *) buf, len);
316 317
        if ((rc < 0 && errno != EAGAIN) || (rc == len)) {
            /* all flushed or error */
318 319
            QDECREF(mon->outbuf);
            mon->outbuf = qstring_new();
Gerd Hoffmann's avatar
Gerd Hoffmann committed
320 321 322
            return;
        }
        if (rc > 0) {
Eric Blake's avatar
Eric Blake committed
323
            /* partial write */
324 325 326
            QString *tmp = qstring_from_str(buf + rc);
            QDECREF(mon->outbuf);
            mon->outbuf = tmp;
Gerd Hoffmann's avatar
Gerd Hoffmann committed
327
        }
328
        if (mon->out_watch == 0) {
329
            mon->out_watch = qemu_chr_fe_add_watch(mon->chr, G_IO_OUT|G_IO_HUP,
330
                                                   monitor_unblocked, mon);
331
        }
332 333 334
    }
}

335 336 337 338 339 340 341
void monitor_flush(Monitor *mon)
{
    qemu_mutex_lock(&mon->out_lock);
    monitor_flush_locked(mon);
    qemu_mutex_unlock(&mon->out_lock);
}

342
/* flush at every end of line */
343
static void monitor_puts(Monitor *mon, const char *str)
344
{
345
    char c;
346

347
    qemu_mutex_lock(&mon->out_lock);
348 349 350 351
    for(;;) {
        c = *str++;
        if (c == '\0')
            break;
352 353 354 355 356
        if (c == '\n') {
            qstring_append_chr(mon->outbuf, '\r');
        }
        qstring_append_chr(mon->outbuf, c);
        if (c == '\n') {
357
            monitor_flush_locked(mon);
358
        }
359
    }
360
    qemu_mutex_unlock(&mon->out_lock);
361 362
}

363
void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
bellard's avatar
bellard committed
364
{
365
    char *buf;
366

367 368 369
    if (!mon)
        return;

370
    if (monitor_is_qmp(mon)) {
371
        return;
372
    }
373

374
    buf = g_strdup_vprintf(fmt, ap);
375
    monitor_puts(mon, buf);
376
    g_free(buf);
bellard's avatar
bellard committed
377 378
}

379
void monitor_printf(Monitor *mon, const char *fmt, ...)
bellard's avatar
bellard committed
380
{
381 382
    va_list ap;
    va_start(ap, fmt);
383
    monitor_vprintf(mon, fmt, ap);
384
    va_end(ap);
bellard's avatar
bellard committed
385 386
}

387
int monitor_fprintf(FILE *stream, const char *fmt, ...)
bellard's avatar
bellard committed
388 389 390
{
    va_list ap;
    va_start(ap, fmt);
391
    monitor_vprintf((Monitor *)stream, fmt, ap);
bellard's avatar
bellard committed
392 393 394 395
    va_end(ap);
    return 0;
}

Luiz Capitulino's avatar
Luiz Capitulino committed
396 397 398 399
static void monitor_json_emitter(Monitor *mon, const QObject *data)
{
    QString *json;

400 401
    json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
                                             qobject_to_json(data);
Luiz Capitulino's avatar
Luiz Capitulino committed
402 403
    assert(json != NULL);

404 405
    qstring_append_chr(json, '\n');
    monitor_puts(mon, qstring_get_str(json));
406

Luiz Capitulino's avatar
Luiz Capitulino committed
407 408 409
    QDECREF(json);
}

410
static QDict *build_qmp_error_dict(Error *err)
411 412 413
{
    QObject *obj;

414
    obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %s } }",
415
                             QapiErrorClass_lookup[error_get_class(err)],
416
                             error_get_pretty(err));
417 418 419 420

    return qobject_to_qdict(obj);
}

421
static void monitor_protocol_emitter(Monitor *mon, QObject *data,
422
                                     Error *err)
Luiz Capitulino's avatar
Luiz Capitulino committed
423 424 425
{
    QDict *qmp;

426 427
    trace_monitor_protocol_emitter(mon);

428
    if (!err) {
Luiz Capitulino's avatar
Luiz Capitulino committed
429
        /* success response */
430
        qmp = qdict_new();
Luiz Capitulino's avatar
Luiz Capitulino committed
431 432 433 434
        if (data) {
            qobject_incref(data);
            qdict_put_obj(qmp, "return", data);
        } else {
435 436
            /* return an empty QDict by default */
            qdict_put(qmp, "return", qdict_new());
Luiz Capitulino's avatar
Luiz Capitulino committed
437 438 439
        }
    } else {
        /* error response */
440
        qmp = build_qmp_error_dict(err);
Luiz Capitulino's avatar
Luiz Capitulino committed
441 442
    }

443 444 445
    if (mon->qmp.id) {
        qdict_put_obj(qmp, "id", mon->qmp.id);
        mon->qmp.id = NULL;
Luiz Capitulino's avatar
Luiz Capitulino committed
446 447
    }

Luiz Capitulino's avatar
Luiz Capitulino committed
448 449 450 451
    monitor_json_emitter(mon, QOBJECT(qmp));
    QDECREF(qmp);
}

452

453
static MonitorQAPIEventConf monitor_qapi_event_conf[QAPI_EVENT__MAX] = {
454 455 456 457 458 459 460 461 462
    /* Limit guest-triggerable events to 1 per second */
    [QAPI_EVENT_RTC_CHANGE]        = { 1000 * SCALE_MS },
    [QAPI_EVENT_WATCHDOG]          = { 1000 * SCALE_MS },
    [QAPI_EVENT_BALLOON_CHANGE]    = { 1000 * SCALE_MS },
    [QAPI_EVENT_QUORUM_REPORT_BAD] = { 1000 * SCALE_MS },
    [QAPI_EVENT_QUORUM_FAILURE]    = { 1000 * SCALE_MS },
    [QAPI_EVENT_VSERPORT_CHANGE]   = { 1000 * SCALE_MS },
};

463
GHashTable *monitor_qapi_event_state;
464 465

/*
466
 * Emits the event to every monitor instance, @event is only used for trace
467
 * Called with monitor_lock held.
468
 */
469
static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
470 471 472
{
    Monitor *mon;

473
    trace_monitor_protocol_event_emit(event, qdict);
474
    QLIST_FOREACH(mon, &mon_list, entry) {
475
        if (monitor_is_qmp(mon) && mon->qmp.in_command_mode) {
476
            monitor_json_emitter(mon, QOBJECT(qdict));
477 478 479 480
        }
    }
}

481 482
static void monitor_qapi_event_handler(void *opaque);

483 484 485 486 487
/*
 * Queue a new event for emission to Monitor instances,
 * applying any rate limiting if required.
 */
static void
488
monitor_qapi_event_queue(QAPIEvent event, QDict *qdict, Error **errp)
489
{
490
    MonitorQAPIEventConf *evconf;
491
    MonitorQAPIEventState *evstate;
492

493
    assert(event < QAPI_EVENT__MAX);
494 495
    evconf = &monitor_qapi_event_conf[event];
    trace_monitor_protocol_event_queue(event, qdict, evconf->rate);
496

497
    qemu_mutex_lock(&monitor_lock);
498

499
    if (!evconf->rate) {
500
        /* Unthrottled event */
501
        monitor_qapi_event_emit(event, qdict);
502
    } else {
503 504
        QDict *data = qobject_to_qdict(qdict_get(qdict, "data"));
        MonitorQAPIEventState key = { .event = event, .data = data };
505 506 507 508 509

        evstate = g_hash_table_lookup(monitor_qapi_event_state, &key);
        assert(!evstate || timer_pending(evstate->timer));

        if (evstate) {
510
            /*
511
             * Timer is pending for (at least) evconf->rate ns after
512 513
             * last send.  Store event for sending when timer fires,
             * replacing a prior stored event if any.
514
             */
515
            QDECREF(evstate->qdict);
516 517
            evstate->qdict = qdict;
            QINCREF(evstate->qdict);
518
        } else {
519
            /*
520
             * Last send was (at least) evconf->rate ns ago.
521
             * Send immediately, and arm the timer to call
522
             * monitor_qapi_event_handler() in evconf->rate ns.  Any
523 524
             * events arriving before then will be delayed until then.
             */
525
            int64_t now = qemu_clock_get_ns(event_clock_type);
526

527
            monitor_qapi_event_emit(event, qdict);
528 529 530

            evstate = g_new(MonitorQAPIEventState, 1);
            evstate->event = event;
531 532
            evstate->data = data;
            QINCREF(evstate->data);
533
            evstate->qdict = NULL;
534
            evstate->timer = timer_new_ns(event_clock_type,
535 536 537
                                          monitor_qapi_event_handler,
                                          evstate);
            g_hash_table_add(monitor_qapi_event_state, evstate);
538
            timer_mod_ns(evstate->timer, now + evconf->rate);
539 540
        }
    }
541

542
    qemu_mutex_unlock(&monitor_lock);
543 544 545
}

/*
546
 * This function runs evconf->rate ns after sending a throttled
547 548
 * event.
 * If another event has since been stored, send it.
549
 */
550
static void monitor_qapi_event_handler(void *opaque)
551
{
552
    MonitorQAPIEventState *evstate = opaque;
553
    MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];
554

555
    trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);
556
    qemu_mutex_lock(&monitor_lock);
557

558
    if (evstate->qdict) {
559
        int64_t now = qemu_clock_get_ns(event_clock_type);
560

561 562 563
        monitor_qapi_event_emit(evstate->event, evstate->qdict);
        QDECREF(evstate->qdict);
        evstate->qdict = NULL;
564
        timer_mod_ns(evstate->timer, now + evconf->rate);
565 566
    } else {
        g_hash_table_remove(monitor_qapi_event_state, evstate);
567
        QDECREF(evstate->data);
568 569
        timer_free(evstate->timer);
        g_free(evstate);
570
    }
571

572
    qemu_mutex_unlock(&monitor_lock);
573 574
}

575
static unsigned int qapi_event_throttle_hash(const void *key)
576
{
577
    const MonitorQAPIEventState *evstate = key;
578
    unsigned int hash = evstate->event * 255;
579

580 581 582 583
    if (evstate->event == QAPI_EVENT_VSERPORT_CHANGE) {
        hash += g_str_hash(qdict_get_str(evstate->data, "id"));
    }

584 585 586 587
    if (evstate->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
        hash += g_str_hash(qdict_get_str(evstate->data, "node-name"));
    }

588
    return hash;
589
}
590

591 592 593 594 595
static gboolean qapi_event_throttle_equal(const void *a, const void *b)
{
    const MonitorQAPIEventState *eva = a;
    const MonitorQAPIEventState *evb = b;

596 597 598 599 600 601 602 603 604
    if (eva->event != evb->event) {
        return FALSE;
    }

    if (eva->event == QAPI_EVENT_VSERPORT_CHANGE) {
        return !strcmp(qdict_get_str(eva->data, "id"),
                       qdict_get_str(evb->data, "id"));
    }

605 606 607 608 609
    if (eva->event == QAPI_EVENT_QUORUM_REPORT_BAD) {
        return !strcmp(qdict_get_str(eva->data, "node-name"),
                       qdict_get_str(evb->data, "node-name"));
    }

610
    return TRUE;
611 612 613 614
}

static void monitor_qapi_event_init(void)
{
615 616 617 618
    if (qtest_enabled()) {
        event_clock_type = QEMU_CLOCK_VIRTUAL;
    }

619 620
    monitor_qapi_event_state = g_hash_table_new(qapi_event_throttle_hash,
                                                qapi_event_throttle_equal);
621
    qmp_event_set_func_emit(monitor_qapi_event_queue);
622 623
}

624
static void qmp_capabilities(QDict *params, QObject **ret_data, Error **errp)
625
{
626
    cur_mon->qmp.in_command_mode = true;
627 628
}

629
static void handle_hmp_command(Monitor *mon, const char *cmdline);
630

631 632 633
static void monitor_data_init(Monitor *mon)
{
    memset(mon, 0, sizeof(Monitor));
634
    qemu_mutex_init(&mon->out_lock);
635
    mon->outbuf = qstring_new();
636 637
    /* Use *mon_cmds by default. */
    mon->cmd_table = mon_cmds;
638 639 640 641 642
}

static void monitor_data_destroy(Monitor *mon)
{
    QDECREF(mon->outbuf);
643
    qemu_mutex_destroy(&mon->out_lock);
644 645
}

646 647
char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
                                int64_t cpu_index, Error **errp)
648
{
649
    char *output = NULL;
650 651
    Monitor *old_mon, hmp;

652
    monitor_data_init(&hmp);
653
    hmp.skip_flush = true;
654 655 656 657

    old_mon = cur_mon;
    cur_mon = &hmp;

658 659
    if (has_cpu_index) {
        int ret = monitor_set_cpu(cpu_index);
660 661
        if (ret < 0) {
            cur_mon = old_mon;
662 663
            error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
                       "a CPU number");
664 665 666 667
            goto out;
        }
    }

668
    handle_hmp_command(&hmp, command_line);
669 670
    cur_mon = old_mon;

671
    qemu_mutex_lock(&hmp.out_lock);
672 673
    if (qstring_get_length(hmp.outbuf) > 0) {
        output = g_strdup(qstring_get_str(hmp.outbuf));
674 675
    } else {
        output = g_strdup("");
676
    }
677
    qemu_mutex_unlock(&hmp.out_lock);
678 679

out:
680
    monitor_data_destroy(&hmp);
681
    return output;
682 683
}

bellard's avatar
bellard committed
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
static int compare_cmd(const char *name, const char *list)
{
    const char *p, *pstart;
    int len;
    len = strlen(name);
    p = list;
    for(;;) {
        pstart = p;
        p = strchr(p, '|');
        if (!p)
            p = pstart + strlen(pstart);
        if ((p - pstart) == len && !memcmp(pstart, name, len))
            return 1;
        if (*p == '\0')
            break;
        p++;
    }
    return 0;
}

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
static int get_str(char *buf, int buf_size, const char **pp)
{
    const char *p;
    char *q;
    int c;

    q = buf;
    p = *pp;
    while (qemu_isspace(*p)) {
        p++;
    }
    if (*p == '\0') {
    fail:
        *q = '\0';
        *pp = p;
        return -1;
    }
    if (*p == '\"') {
        p++;
        while (*p != '\0' && *p != '\"') {
            if (*p == '\\') {
                p++;
                c = *p++;
                switch (c) {
                case 'n':
                    c = '\n';
                    break;
                case 'r':
                    c = '\r';
                    break;
                case '\\':
                case '\'':
                case '\"':
                    break;
                default:
739
                    printf("unsupported escape code: '\\%c'\n", c);
740 741 742 743 744 745 746 747 748 749 750 751 752
                    goto fail;
                }
                if ((q - buf) < buf_size - 1) {
                    *q++ = c;
                }
            } else {
                if ((q - buf) < buf_size - 1) {
                    *q++ = *p;
                }
                p++;
            }
        }
        if (*p != '\"') {
753
            printf("unterminated string\n");
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
            goto fail;
        }
        p++;
    } else {
        while (*p != '\0' && !qemu_isspace(*p)) {
            if ((q - buf) < buf_size - 1) {
                *q++ = *p;
            }
            p++;
        }
    }
    *q = '\0';
    *pp = p;
    return 0;
}

#define MAX_ARGS 16

772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
static void free_cmdline_args(char **args, int nb_args)
{
    int i;

    assert(nb_args <= MAX_ARGS);

    for (i = 0; i < nb_args; i++) {
        g_free(args[i]);
    }

}

/*
 * Parse the command line to get valid args.
 * @cmdline: command line to be parsed.
 * @pnb_args: location to store the number of args, must NOT be NULL.
 * @args: location to store the args, which should be freed by caller, must
 *        NOT be NULL.
 *
 * Returns 0 on success, negative on failure.
 *
 * NOTE: this parser is an approximate form of the real command parser. Number
 *       of args have a limit of MAX_ARGS. If cmdline contains more, it will
 *       return with failure.
 */
static int parse_cmdline(const char *cmdline,
                         int *pnb_args, char **args)
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
{
    const char *p;
    int nb_args, ret;
    char buf[1024];

    p = cmdline;
    nb_args = 0;
    for (;;) {
        while (qemu_isspace(*p)) {
            p++;
        }
        if (*p == '\0') {
            break;
        }
        if (nb_args >= MAX_ARGS) {
814
            goto fail;
815 816 817
        }
        ret = get_str(buf, sizeof(buf), &p);
        if (ret < 0) {
818
            goto fail;
819
        }
820 821
        args[nb_args] = g_strdup(buf);
        nb_args++;
822 823
    }
    *pnb_args = nb_args;
824 825 826 827 828
    return 0;

 fail:
    free_cmdline_args(args, nb_args);
    return -1;
829 830
}

831 832 833 834 835 836 837 838 839 840 841 842 843 844
static void help_cmd_dump_one(Monitor *mon,
                              const mon_cmd_t *cmd,
                              char **prefix_args,
                              int prefix_args_nb)
{
    int i;

    for (i = 0; i < prefix_args_nb; i++) {
        monitor_printf(mon, "%s ", prefix_args[i]);
    }
    monitor_printf(mon, "%s %s -- %s\n", cmd->name, cmd->params, cmd->help);
}

/* @args[@arg_index] is the valid command need to find in @cmds */
845
static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
846
                          char **args, int nb_args, int arg_index)
bellard's avatar
bellard committed
847
{
848
    const mon_cmd_t *cmd;
bellard's avatar
bellard committed
849

850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
    /* No valid arg need to compare with, dump all in *cmds */
    if (arg_index >= nb_args) {
        for (cmd = cmds; cmd->name != NULL; cmd++) {
            help_cmd_dump_one(mon, cmd, args, arg_index);
        }
        return;
    }

    /* Find one entry to dump */
    for (cmd = cmds; cmd->name != NULL; cmd++) {
        if (compare_cmd(args[arg_index], cmd->name)) {
            if (cmd->sub_table) {
                /* continue with next arg */
                help_cmd_dump(mon, cmd->sub_table,
                              args, nb_args, arg_index + 1);
            } else {
                help_cmd_dump_one(mon, cmd, args, arg_index);
            }
            break;
        }
bellard's avatar
bellard committed
870 871 872
    }
}

873
static void help_cmd(Monitor *mon, const char *name)
bellard's avatar
bellard committed
874
{
875 876 877 878 879 880 881
    char *args[MAX_ARGS];
    int nb_args = 0;

    /* 1. parse user input */
    if (name) {
        /* special case for log, directly dump and return */
        if (!strcmp(name, "log")) {
882
            const QEMULogItem *item;
883 884
            monitor_printf(mon, "Log items (comma separated):\n");
            monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
885
            for (item = qemu_log_items; item->mask != 0; item++) {
886
                monitor_printf(mon, "%-10s %s\n", item->name, item->help);
887
            }
888 889 890 891 892
            return;
        }

        if (parse_cmdline(name, &nb_args, args) < 0) {
            return;
893
        }
bellard's avatar
bellard committed
894
    }
895 896 897 898 899

    /* 2. dump the contents according to parsed args */
    help_cmd_dump(mon, mon->cmd_table, args, nb_args, 0);

    free_cmdline_args(args, nb_args);
bellard's avatar
bellard committed
900 901
}

902
static void do_help_cmd(Monitor *mon, const QDict *qdict)
903
{
904
    help_cmd(mon, qdict_get_try_str(qdict, "name"));
905 906
}

907
static void hmp_trace_event(Monitor *mon, const QDict *qdict)
908 909 910
{
    const char *tp_name = qdict_get_str(qdict, "name");
    bool new_state = qdict_get_bool(qdict, "option");
911
    Error *local_err = NULL;
912

913 914
    qmp_trace_event_set_state(tp_name, new_state, true, true, &local_err);
    if (local_err) {
915
        error_report_err(local_err);
916
    }
917
}
918

919
#ifdef CONFIG_TRACE_SIMPLE
920
static void hmp_trace_file(Monitor *mon, const QDict *qdict)
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
{
    const char *op = qdict_get_try_str(qdict, "op");
    const char *arg = qdict_get_try_str(qdict, "arg");

    if (!op) {
        st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
    } else if (!strcmp(op, "on")) {
        st_set_trace_file_enabled(true);
    } else if (!strcmp(op, "off")) {
        st_set_trace_file_enabled(false);
    } else if (!strcmp(op, "flush")) {
        st_flush_trace_buffer();
    } else if (!strcmp(op, "set")) {
        if (arg) {
            st_set_trace_file(arg);
        }
    } else {
        monitor_printf(mon, "unexpected argument \"%s\"\n", op);
        help_cmd(mon, "trace-file");
    }
}
942 943
#endif

944
static void hmp_info_help(Monitor *mon, const QDict *qdict)
bellard's avatar
bellard committed
945
{
946
    help_cmd(mon, "info");
bellard's avatar
bellard committed
947 948
}

949
CommandInfoList *qmp_query_commands(Error **errp)
950
{
951
    CommandInfoList *info, *cmd_list = NULL;
952 953
    const mon_cmd_t *cmd;

954
    for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
955 956 957
        info = g_malloc0(sizeof(*info));
        info->value = g_malloc0(sizeof(*info->value));
        info->value->name = g_strdup(cmd->name);
958

959 960
        info->next = cmd_list;
        cmd_list = info;
961 962
    }

963
    return cmd_list;
964 965
}

966 967 968
EventInfoList *qmp_query_events(Error **errp)
{
    EventInfoList *info, *ev_list = NULL;
Wenchao Xia's avatar
Wenchao Xia committed
969
    QAPIEvent e;
970

971
    for (e = 0 ; e < QAPI_EVENT__MAX ; e++) {
Wenchao Xia's avatar
Wenchao Xia committed
972
        const char *event_name = QAPIEvent_lookup[e];
973 974 975 976 977 978 979 980 981 982 983 984
        assert(event_name != NULL);
        info = g_malloc0(sizeof(*info));
        info->value = g_malloc0(sizeof(*info->value));
        info->value->name = g_strdup(event_name);

        info->next = ev_list;
        ev_list = info;
    }

    return ev_list;
}

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
/*
 * Minor hack: generated marshalling suppressed for this command
 * ('gen': false in the schema) so we can parse the JSON string
 * directly into QObject instead of first parsing it with
 * visit_type_SchemaInfoList() into a SchemaInfoList, then marshal it
 * to QObject with generated output marshallers, every time.  Instead,
 * we do it in test-qmp-input-visitor.c, just to make sure
 * qapi-introspect.py's output actually conforms to the schema.
 */
static void qmp_query_qmp_schema(QDict *qdict, QObject **ret_data,
                                 Error **errp)
{
    *ret_data = qobject_from_json(qmp_schema_json);
}

1000 1001
/* set the current CPU defined by the user */
int monitor_set_cpu(int cpu_index)
bellard's avatar
bellard committed
1002
{
1003
    CPUState *cpu;
bellard's avatar
bellard committed
1004

1005 1006 1007
    cpu = qemu_get_cpu(cpu_index);
    if (cpu == NULL) {
        return -1;
bellard's avatar
bellard committed
1008
    }
1009
    cur_mon->mon_cpu = cpu;
1010
    return 0;
bellard's avatar
bellard committed
1011 1012
}

1013
CPUState *mon_get_cpu(void)
bellard's avatar
bellard committed
1014
{
1015
    if (!cur_mon->mon_cpu) {
1016
        monitor_set_cpu(0);
bellard's avatar
bellard committed
1017
    }
1018
    cpu_synchronize_state(cur_mon->mon_cpu);
1019 1020 1021
    return cur_mon->mon_cpu;
}

1022
CPUArchState *mon_get_cpu_env(void)
1023 1024
{
    return mon_get_cpu()->env_ptr;
bellard's avatar
bellard committed
1025 1026
}

1027 1028
int monitor_get_cpu_index(void)
{
1029
    return mon_get_cpu()->cpu_index;
1030 1031
}

1032
static void hmp_info_registers(Monitor *mon, const QDict *qdict)
1033
{
1034
    cpu_dump_state(mon_get_cpu(), (FILE *)mon, monitor_fprintf, CPU_DUMP_FPU);
1035 1036
}

1037
static void hmp_info_jit(Monitor *mon, const QDict *qdict)
bellard's avatar
bellard committed
1038
{
1039
    dump_exec_info((FILE *)mon, monitor_fprintf);
1040
    dump_drift_info((FILE *)mon, monitor_fprintf);
bellard's avatar
bellard committed
1041 1042
}

1043
static void hmp_info_opcount(Monitor *mon, const QDict *qdict)
1044 1045 1046 1047
{
    dump_opcount_info((FILE *)mon, monitor_fprintf);
}

1048
static void hmp_info_history(Monitor *mon, const QDict *qdict)
1049 1050
{
    int i;
1051
    const char *str;
1052

1053 1054
    if (!mon->rs)
        return;
1055 1056
    i = 0;
    for(;;) {
1057
        str = readline_get_history(mon->rs, i);
1058 1059
        if (!str)
            break;
1060
        monitor_printf(mon, "%d: '%s'\n", i, str);
1061
        i++;
1062 1063 1064
    }
}

1065
static void hmp_info_cpustats(Monitor *mon, const QDict *qdict)
1066
{
1067
    cpu_dump_statistics(mon_get_cpu(), (FILE *)mon, &monitor_fprintf, 0);
1068 1069
}

1070
static void hmp_info_trace_events(Monitor *mon, const QDict *qdict)
1071
{
1072 1073 1074 1075 1076 1077 1078 1079 1080
    TraceEventInfoList *events = qmp_trace_event_get_state("*", NULL);
    TraceEventInfoList *elem;

    for (elem = events; elem != NULL; elem = elem->next) {
        monitor_printf(mon, "%s : state %u\n",
                       elem->value->name,
                       elem->value->state == TRACE_EVENT_STATE_ENABLED ? 1 : 0);
    }
    qapi_free_TraceEventInfoList(events);
1081 1082
}

1083 1084 1085 1086 1087
void qmp_client_migrate_info(const char *protocol, const char *hostname,
                             bool has_port, int64_t port,
                             bool has_tls_port, int64_t tls_port,
                             bool has_cert_subject, const char *cert_subject,
                             Error **errp)
1088 1089
{
    if (strcmp(protocol, "spice") == 0) {
1090 1091
        if (!qemu_using_spice(errp)) {
            return;
1092 1093
        }

1094
        if (!has_port && !has_tls_port) {
1095
            error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1096
            return;
1097 1098
        }

1099 1100 1101 1102
        if (qemu_spice_migrate_info(hostname,
                                    has_port ? port : -1,
                                    has_tls_port ? tls_port : -1,
                                    cert_subject)) {
1103
            error_setg(errp, QERR_UNDEFINED_ERROR);
1104
            return;
1105
        }
1106
        return;
1107 1108
    }

1109
    error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "spice");
1110 1111
}

1112
static void hmp_logfile(Monitor *mon, const QDict *qdict)
pbrook's avatar
pbrook committed
1113
{
1114
    qemu_set_log_filename(qdict_get_str(qdict, "filename"));
pbrook's avatar
pbrook committed
1115 1116
}

1117
static void hmp_log(Monitor *mon, const QDict *qdict)
1118 1119
{
    int mask;
1120
    const char *items = qdict_get_str(qdict, "items");
1121

1122
    if (!strcmp(items, "none")) {
1123 1124
        mask = 0;
    } else {
1125
        mask = qemu_str_to_log_mask(items);
1126
        if (!mask) {
1127
            help_cmd(mon, "log");
1128 1129 1130
            return;
        }
    }
1131
    qemu_set_log(mask);
1132 1133
}

1134
static void hmp_singlestep(Monitor *mon, const QDict *qdict)
1135
{
1136
    const char *option = qdict_get_try_str(qdict, "option");
1137 1138 1139 1140 1141 1142 1143 1144 1145
    if (!option || !strcmp(option, "on")) {
        singlestep = 1;
    } else if (!strcmp(option, "off")) {
        singlestep = 0;
    } else {
        monitor_printf(mon, "unexpected option %s\n", option);
    }
}

1146
static void hmp_gdbserver(Monitor *mon, const QDict *qdict)
1147
{
1148
    const char *device = qdict_get_try_str(qdict, "device");
1149 1150 1151 1152 1153 1154
    if (!device)
        device = "tcp::" DEFAULT_GDBSTUB_PORT;
    if (gdbserver_start(device) < 0) {
        monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
                       device);
    } else if (strcmp(device, "none") == 0) {
1155
        monitor_printf(mon, "Disabled gdbserver\n");
1156
    } else {
1157 1158
        monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
                       device);
1159 1160 1161
    }
}

1162