monitor.c 154 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.
 */
24
#include <dirent.h>
pbrook's avatar
pbrook committed
25
#include "hw/hw.h"
26
#include "monitor/qdev.h"
pbrook's avatar
pbrook committed
27
#include "hw/usb.h"
Paolo Bonzini's avatar
Paolo Bonzini committed
28
#include "hw/i386/pc.h"
29
#include "hw/pci/pci.h"
Paolo Bonzini's avatar
Paolo Bonzini committed
30
#include "sysemu/watchdog.h"
31
#include "hw/loader.h"
32
#include "exec/gdbstub.h"
Paolo Bonzini's avatar
Paolo Bonzini committed
33
#include "net/net.h"
34
#include "net/slirp.h"
35
#include "sysemu/char.h"
36
#include "ui/qemu-spice.h"
37
#include "sysemu/sysemu.h"
38
#include "monitor/monitor.h"
39
#include "qemu/readline.h"
40
#include "ui/console.h"
41
#include "ui/input.h"
42
#include "sysemu/blockdev.h"
pbrook's avatar
pbrook committed
43
#include "audio/audio.h"
44
#include "disas/disas.h"
45
#include "sysemu/balloon.h"
46
#include "qemu/timer.h"
47
#include "migration/migration.h"
48
#include "sysemu/kvm.h"
49
#include "qemu/acl.h"
50
#include "sysemu/tpm.h"
51
52
53
54
55
56
57
58
#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"
59
#include <qom/object_interfaces.h>
60
#include "qemu/osdep.h"
61
#include "cpu.h"
62
#include "trace.h"
63
#include "trace/control.h"
64
#ifdef CONFIG_TRACE_SIMPLE
65
#include "trace/simple.h"
66
#endif
67
#include "exec/memory.h"
Paolo Bonzini's avatar
Paolo Bonzini committed
68
#include "exec/cpu_ldst.h"
Anthony Liguori's avatar
Anthony Liguori committed
69
70
#include "qmp-commands.h"
#include "hmp.h"
71
#include "qemu/thread.h"
72
#include "block/qapi.h"
73
74
#include "qapi/qmp-event.h"
#include "qapi-event.h"
ths's avatar
ths committed
75

76
77
/* for pic/irq_info */
#if defined(TARGET_SPARC)
Paolo Bonzini's avatar
Paolo Bonzini committed
78
#include "hw/sparc/sun4m.h"
79
#endif
Paolo Bonzini's avatar
Paolo Bonzini committed
80
#include "hw/lm32/lm32_pic.h"
81

bellard's avatar
bellard committed
82
//#define DEBUG
bellard's avatar
bellard committed
83
//#define DEBUG_COMPLETION
bellard's avatar
bellard committed
84

85
86
/*
 * Supported types:
87
 *
88
 * 'F'          filename
bellard's avatar
bellard committed
89
 * 'B'          block device name
90
 * 's'          string (accept optional quote)
91
 * 'S'          it just appends the rest of the string (accept optional quote)
92
93
94
95
96
 * '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
97
98
 * 'i'          32 bit integer
 * 'l'          target long (32 or 64 bit)
99
100
 * 'M'          Non-negative target long (32 or 64 bit), in user mode the
 *              value is multiplied by 2^20 (think Mebibyte)
101
 * 'o'          octets (aka bytes)
102
103
104
105
 *              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
106
107
108
 * 'T'          double
 *              user mode accepts an optional ms, us, ns suffix,
 *              which divides the value by 1e3, 1e6, 1e9, respectively
109
110
 * '/'          optional gdb-like print format (like "/10x")
 *
111
112
 * '?'          optional type (for all types, except '/')
 * '.'          other form of optional type (for 'i' and 'l')
113
114
 * 'b'          boolean
 *              user mode accepts "on" or "off"
115
 * '-'          optional parameter (eg. '-f')
116
117
118
 *
 */

119
120
121
122
123
124
typedef struct MonitorCompletionData MonitorCompletionData;
struct MonitorCompletionData {
    Monitor *mon;
    void (*user_print)(Monitor *mon, const QObject *data);
};

125
typedef struct mon_cmd_t {
bellard's avatar
bellard committed
126
    const char *name;
127
    const char *args_type;
bellard's avatar
bellard committed
128
129
    const char *params;
    const char *help;
130
    void (*user_print)(Monitor *mon, const QObject *data);
131
    union {
132
        void (*cmd)(Monitor *mon, const QDict *qdict);
133
        int  (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data);
134
135
        int  (*cmd_async)(Monitor *mon, const QDict *params,
                          MonitorCompletion *cb, void *opaque);
136
    } mhandler;
137
    int flags;
138
139
140
141
142
    /* @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;
143
    void (*command_completion)(ReadLineState *rs, int nb_args, const char *str);
144
} mon_cmd_t;
bellard's avatar
bellard committed
145

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

154
155
156
157
158
159
160
161
162
163
164
165
166
167
/* 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;
168
    QLIST_HEAD(, MonFdsetFd) dup_fds;
169
170
171
    QLIST_ENTRY(MonFdset) next;
};

Luiz Capitulino's avatar
Luiz Capitulino committed
172
173
174
typedef struct MonitorControl {
    QObject *id;
    JSONMessageParser parser;
175
    int command_mode;
Luiz Capitulino's avatar
Luiz Capitulino committed
176
177
} MonitorControl;

178
179
180
181
182
/*
 * To prevent flooding clients, events can be throttled. The
 * throttling is calculated globally, rather than per-Monitor
 * instance.
 */
183
184
185
186
typedef struct MonitorQAPIEventState {
    QAPIEvent event;    /* Event being tracked */
    int64_t rate;       /* Minimum time (in ns) between two events */
    int64_t last;       /* QEMU_CLOCK_REALTIME value at last emission */
187
188
    QEMUTimer *timer;   /* Timer for handling delayed events */
    QObject *data;      /* Event pending delayed dispatch */
189
} MonitorQAPIEventState;
190

191
192
struct Monitor {
    CharDriverState *chr;
Gerd Hoffmann's avatar
Gerd Hoffmann committed
193
    int reset_seen;
194
195
    int flags;
    int suspend_cnt;
196
    bool skip_flush;
197
198

    QemuMutex out_lock;
199
    QString *outbuf;
200
201
202
203
204
    guint out_watch;

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

205
    ReadLineState *rs;
Luiz Capitulino's avatar
Luiz Capitulino committed
206
    MonitorControl *mc;
207
    CPUState *mon_cpu;
208
    BlockCompletionFunc *password_completion_cb;
209
    void *password_opaque;
210
    mon_cmd_t *cmd_table;
Luiz Capitulino's avatar
Luiz Capitulino committed
211
    QError *error;
212
    QLIST_HEAD(,mon_fd_t) fds;
Blue Swirl's avatar
Blue Swirl committed
213
    QLIST_ENTRY(Monitor) entry;
214
215
};

216
217
218
/* QMP checker flags */
#define QMP_ACCEPT_UNKNOWNS 1

219
220
221
/* Protects mon_list, monitor_event_state.  */
static QemuMutex monitor_lock;

Blue Swirl's avatar
Blue Swirl committed
222
static QLIST_HEAD(mon_list, Monitor) mon_list;
223
static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
224
static int mon_refcount;
225

226
227
static mon_cmd_t mon_cmds[];
static mon_cmd_t info_cmds[];
bellard's avatar
bellard committed
228

229
230
static const mon_cmd_t qmp_cmds[];

231
232
Monitor *cur_mon;
Monitor *default_mon;
aliguori's avatar
aliguori committed
233

234
235
static void monitor_command_cb(void *opaque, const char *cmdline,
                               void *readline_opaque);
236

237
238
239
240
241
static inline int qmp_cmd_mode(const Monitor *mon)
{
    return (mon->mc ? mon->mc->command_mode : 0);
}

242
243
244
245
246
247
/* Return true if in control mode, false otherwise */
static inline int monitor_ctrl_mode(const Monitor *mon)
{
    return (mon->flags & MONITOR_USE_CONTROL);
}

248
249
250
251
252
253
/* Return non-zero iff we have a current monitor, and it is in QMP mode.  */
int monitor_cur_is_qmp(void)
{
    return cur_mon && monitor_ctrl_mode(cur_mon);
}

254
void monitor_read_command(Monitor *mon, int show_prompt)
255
{
256
257
258
    if (!mon->rs)
        return;

259
260
261
262
    readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
    if (show_prompt)
        readline_show_prompt(mon->rs);
}
bellard's avatar
bellard committed
263

264
265
int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
                          void *opaque)
266
{
267
    if (monitor_ctrl_mode(mon)) {
268
        qerror_report(QERR_MISSING_PARAMETER, "password");
269
270
        return -EINVAL;
    } else if (mon->rs) {
271
272
273
274
275
276
277
        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;
    }
278
279
}

280
281
static void monitor_flush_locked(Monitor *mon);

Gerd Hoffmann's avatar
Gerd Hoffmann committed
282
283
284
static gboolean monitor_unblocked(GIOChannel *chan, GIOCondition cond,
                                  void *opaque)
{
285
286
    Monitor *mon = opaque;

287
288
289
290
    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
291
292
293
    return FALSE;
}

294
295
/* Called with mon->out_lock held.  */
static void monitor_flush_locked(Monitor *mon)
296
{
Gerd Hoffmann's avatar
Gerd Hoffmann committed
297
    int rc;
298
299
300
    size_t len;
    const char *buf;

301
302
303
304
    if (mon->skip_flush) {
        return;
    }

305
306
    buf = qstring_get_str(mon->outbuf);
    len = qstring_get_length(mon->outbuf);
Gerd Hoffmann's avatar
Gerd Hoffmann committed
307

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

329
330
331
332
333
334
335
void monitor_flush(Monitor *mon)
{
    qemu_mutex_lock(&mon->out_lock);
    monitor_flush_locked(mon);
    qemu_mutex_unlock(&mon->out_lock);
}

336
/* flush at every end of line */
aliguori's avatar
aliguori committed
337
static void monitor_puts(Monitor *mon, const char *str)
338
{
ths's avatar
ths committed
339
    char c;
340

341
    qemu_mutex_lock(&mon->out_lock);
342
343
344
345
    for(;;) {
        c = *str++;
        if (c == '\0')
            break;
346
347
348
349
350
        if (c == '\n') {
            qstring_append_chr(mon->outbuf, '\r');
        }
        qstring_append_chr(mon->outbuf, c);
        if (c == '\n') {
351
            monitor_flush_locked(mon);
352
        }
353
    }
354
    qemu_mutex_unlock(&mon->out_lock);
355
356
}

aliguori's avatar
aliguori committed
357
void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
bellard's avatar
bellard committed
358
{
359
    char *buf;
360

361
362
363
    if (!mon)
        return;

364
365
    if (monitor_ctrl_mode(mon)) {
        return;
366
    }
367

368
    buf = g_strdup_vprintf(fmt, ap);
369
    monitor_puts(mon, buf);
370
    g_free(buf);
bellard's avatar
bellard committed
371
372
}

aliguori's avatar
aliguori committed
373
void monitor_printf(Monitor *mon, const char *fmt, ...)
bellard's avatar
bellard committed
374
{
375
376
    va_list ap;
    va_start(ap, fmt);
aliguori's avatar
aliguori committed
377
    monitor_vprintf(mon, fmt, ap);
378
    va_end(ap);
bellard's avatar
bellard committed
379
380
}

381
382
static int GCC_FMT_ATTR(2, 3) monitor_fprintf(FILE *stream,
                                              const char *fmt, ...)
bellard's avatar
bellard committed
383
384
385
{
    va_list ap;
    va_start(ap, fmt);
aliguori's avatar
aliguori committed
386
    monitor_vprintf((Monitor *)stream, fmt, ap);
bellard's avatar
bellard committed
387
388
389
390
    va_end(ap);
    return 0;
}

391
392
static void monitor_user_noop(Monitor *mon, const QObject *data) { }

393
static inline int handler_is_qobject(const mon_cmd_t *cmd)
394
395
396
397
{
    return cmd->user_print != NULL;
}

398
static inline bool handler_is_async(const mon_cmd_t *cmd)
399
{
400
    return cmd->flags & MONITOR_CMD_ASYNC;
401
402
}

Luiz Capitulino's avatar
Luiz Capitulino committed
403
404
405
406
407
static inline int monitor_has_error(const Monitor *mon)
{
    return mon->error != NULL;
}

Luiz Capitulino's avatar
Luiz Capitulino committed
408
409
410
411
static void monitor_json_emitter(Monitor *mon, const QObject *data)
{
    QString *json;

412
413
    json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
                                             qobject_to_json(data);
Luiz Capitulino's avatar
Luiz Capitulino committed
414
415
    assert(json != NULL);

416
417
    qstring_append_chr(json, '\n');
    monitor_puts(mon, qstring_get_str(json));
418

Luiz Capitulino's avatar
Luiz Capitulino committed
419
420
421
    QDECREF(json);
}

422
423
424
425
426
427
428
429
430
431
432
static QDict *build_qmp_error_dict(const QError *err)
{
    QObject *obj;

    obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %p } }",
                             ErrorClass_lookup[err->err_class],
                             qerror_human(err));

    return qobject_to_qdict(obj);
}

Luiz Capitulino's avatar
Luiz Capitulino committed
433
434
435
436
static void monitor_protocol_emitter(Monitor *mon, QObject *data)
{
    QDict *qmp;

437
438
    trace_monitor_protocol_emitter(mon);

Luiz Capitulino's avatar
Luiz Capitulino committed
439
440
    if (!monitor_has_error(mon)) {
        /* success response */
441
        qmp = qdict_new();
Luiz Capitulino's avatar
Luiz Capitulino committed
442
443
444
445
        if (data) {
            qobject_incref(data);
            qdict_put_obj(qmp, "return", data);
        } else {
446
447
            /* return an empty QDict by default */
            qdict_put(qmp, "return", qdict_new());
Luiz Capitulino's avatar
Luiz Capitulino committed
448
449
450
        }
    } else {
        /* error response */
451
        qmp = build_qmp_error_dict(mon->error);
Luiz Capitulino's avatar
Luiz Capitulino committed
452
453
454
455
        QDECREF(mon->error);
        mon->error = NULL;
    }

Luiz Capitulino's avatar
Luiz Capitulino committed
456
457
458
459
460
    if (mon->mc->id) {
        qdict_put_obj(qmp, "id", mon->mc->id);
        mon->mc->id = NULL;
    }

Luiz Capitulino's avatar
Luiz Capitulino committed
461
462
463
464
    monitor_json_emitter(mon, QOBJECT(qmp));
    QDECREF(qmp);
}

465

466
static MonitorQAPIEventState monitor_qapi_event_state[QAPI_EVENT_MAX];
467
468

/*
469
 * Emits the event to every monitor instance, @event is only used for trace
470
 * Called with monitor_lock held.
471
 */
472
static void monitor_qapi_event_emit(QAPIEvent event, QObject *data)
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
{
    Monitor *mon;

    trace_monitor_protocol_event_emit(event, data);
    QLIST_FOREACH(mon, &mon_list, entry) {
        if (monitor_ctrl_mode(mon) && qmp_cmd_mode(mon)) {
            monitor_json_emitter(mon, data);
        }
    }
}

/*
 * Queue a new event for emission to Monitor instances,
 * applying any rate limiting if required.
 */
static void
489
monitor_qapi_event_queue(QAPIEvent event, QDict *data, Error **errp)
490
{
491
492
    MonitorQAPIEventState *evstate;
    assert(event < QAPI_EVENT_MAX);
493
    int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
494

495
    evstate = &(monitor_qapi_event_state[event]);
496
497
498
499
500
501
502
    trace_monitor_protocol_event_queue(event,
                                       data,
                                       evstate->rate,
                                       evstate->last,
                                       now);

    /* Rate limit of 0 indicates no throttling */
503
    qemu_mutex_lock(&monitor_lock);
504
    if (!evstate->rate) {
505
        monitor_qapi_event_emit(event, QOBJECT(data));
506
507
508
509
510
511
512
513
514
515
516
517
518
        evstate->last = now;
    } else {
        int64_t delta = now - evstate->last;
        if (evstate->data ||
            delta < evstate->rate) {
            /* If there's an existing event pending, replace
             * it with the new event, otherwise schedule a
             * timer for delayed emission
             */
            if (evstate->data) {
                qobject_decref(evstate->data);
            } else {
                int64_t then = evstate->last + evstate->rate;
519
                timer_mod_ns(evstate->timer, then);
520
            }
521
            evstate->data = QOBJECT(data);
522
523
            qobject_incref(evstate->data);
        } else {
524
            monitor_qapi_event_emit(event, QOBJECT(data));
525
526
527
            evstate->last = now;
        }
    }
528
    qemu_mutex_unlock(&monitor_lock);
529
530
531
532
533
534
}

/*
 * The callback invoked by QemuTimer when a delayed
 * event is ready to be emitted
 */
535
static void monitor_qapi_event_handler(void *opaque)
536
{
537
    MonitorQAPIEventState *evstate = opaque;
538
    int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
539
540
541
542
543

    trace_monitor_protocol_event_handler(evstate->event,
                                         evstate->data,
                                         evstate->last,
                                         now);
544
    qemu_mutex_lock(&monitor_lock);
545
    if (evstate->data) {
546
        monitor_qapi_event_emit(evstate->event, evstate->data);
547
548
549
550
        qobject_decref(evstate->data);
        evstate->data = NULL;
    }
    evstate->last = now;
551
    qemu_mutex_unlock(&monitor_lock);
552
553
554
555
556
557
558
559
560
561
562
}

/*
 * @event: the event ID to be limited
 * @rate: the rate limit in milliseconds
 *
 * Sets a rate limit on a particular event, so no
 * more than 1 event will be emitted within @rate
 * milliseconds
 */
static void
563
monitor_qapi_event_throttle(QAPIEvent event, int64_t rate)
564
{
565
566
    MonitorQAPIEventState *evstate;
    assert(event < QAPI_EVENT_MAX);
567

568
    evstate = &(monitor_qapi_event_state[event]);
569
570
571

    trace_monitor_protocol_event_throttle(event, rate);
    evstate->event = event;
Wenchao Xia's avatar
Wenchao Xia committed
572
    assert(rate * SCALE_MS <= INT64_MAX);
573
574
575
    evstate->rate = rate * SCALE_MS;
    evstate->last = 0;
    evstate->data = NULL;
576
577
578
579
    evstate->timer = timer_new(QEMU_CLOCK_REALTIME,
                               SCALE_MS,
                               monitor_qapi_event_handler,
                               evstate);
580
581
}

582
static void monitor_qapi_event_init(void)
583
{
Wenchao Xia's avatar
Wenchao Xia committed
584
585
    /* Limit guest-triggerable events to 1 per second */
    monitor_qapi_event_throttle(QAPI_EVENT_RTC_CHANGE, 1000);
Wenchao Xia's avatar
Wenchao Xia committed
586
    monitor_qapi_event_throttle(QAPI_EVENT_WATCHDOG, 1000);
587
    monitor_qapi_event_throttle(QAPI_EVENT_BALLOON_CHANGE, 1000);
588
589
    monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_REPORT_BAD, 1000);
    monitor_qapi_event_throttle(QAPI_EVENT_QUORUM_FAILURE, 1000);
590
    monitor_qapi_event_throttle(QAPI_EVENT_VSERPORT_CHANGE, 1000);
591

592
    qmp_event_set_func_emit(monitor_qapi_event_queue);
593
594
}

595
596
static int do_qmp_capabilities(Monitor *mon, const QDict *params,
                               QObject **ret_data)
597
598
599
600
601
{
    /* Will setup QMP capabilities in the future */
    if (monitor_ctrl_mode(mon)) {
        mon->mc->command_mode = 1;
    }
602
603

    return 0;
604
605
}

606
607
static void handle_user_command(Monitor *mon, const char *cmdline);

608
609
610
static void monitor_data_init(Monitor *mon)
{
    memset(mon, 0, sizeof(Monitor));
611
    qemu_mutex_init(&mon->out_lock);
612
    mon->outbuf = qstring_new();
613
614
    /* Use *mon_cmds by default. */
    mon->cmd_table = mon_cmds;
615
616
617
618
619
}

static void monitor_data_destroy(Monitor *mon)
{
    QDECREF(mon->outbuf);
620
    qemu_mutex_destroy(&mon->out_lock);
621
622
}

623
624
char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,
                                int64_t cpu_index, Error **errp)
625
{
626
    char *output = NULL;
627
628
    Monitor *old_mon, hmp;

629
    monitor_data_init(&hmp);
630
    hmp.skip_flush = true;
631
632
633
634

    old_mon = cur_mon;
    cur_mon = &hmp;

635
636
    if (has_cpu_index) {
        int ret = monitor_set_cpu(cpu_index);
637
638
        if (ret < 0) {
            cur_mon = old_mon;
639
640
            error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
                      "a CPU number");
641
642
643
644
            goto out;
        }
    }

645
    handle_user_command(&hmp, command_line);
646
647
    cur_mon = old_mon;

648
    qemu_mutex_lock(&hmp.out_lock);
649
650
    if (qstring_get_length(hmp.outbuf) > 0) {
        output = g_strdup(qstring_get_str(hmp.outbuf));
651
652
    } else {
        output = g_strdup("");
653
    }
654
    qemu_mutex_unlock(&hmp.out_lock);
655
656

out:
657
    monitor_data_destroy(&hmp);
658
    return output;
659
660
}

bellard's avatar
bellard committed
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
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;
}

681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
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
739
740
741
742
743
744
745
746
747
748
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:
                    qemu_printf("unsupported escape code: '\\%c'\n", c);
                    goto fail;
                }
                if ((q - buf) < buf_size - 1) {
                    *q++ = c;
                }
            } else {
                if ((q - buf) < buf_size - 1) {
                    *q++ = *p;
                }
                p++;
            }
        }
        if (*p != '\"') {
            qemu_printf("unterminated string\n");
            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

Wenchao Xia's avatar
Wenchao Xia committed
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
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)
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
{
    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) {
Wenchao Xia's avatar
Wenchao Xia committed
791
            goto fail;
792
793
794
        }
        ret = get_str(buf, sizeof(buf), &p);
        if (ret < 0) {
Wenchao Xia's avatar
Wenchao Xia committed
795
            goto fail;
796
        }
Wenchao Xia's avatar
Wenchao Xia committed
797
798
        args[nb_args] = g_strdup(buf);
        nb_args++;
799
800
    }
    *pnb_args = nb_args;
Wenchao Xia's avatar
Wenchao Xia committed
801
802
803
804
805
    return 0;

 fail:
    free_cmdline_args(args, nb_args);
    return -1;
806
807
}

808
809
810
811
812
813
814
815
816
817
818
819
820
821
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 */
822
static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
823
                          char **args, int nb_args, int arg_index)
bellard's avatar
bellard committed
824
{
825
    const mon_cmd_t *cmd;
bellard's avatar
bellard committed
826

827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
    /* 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
847
848
849
    }
}

aliguori's avatar
aliguori committed
850
static void help_cmd(Monitor *mon, const char *name)
bellard's avatar
bellard committed
851
{
852
853
854
855
856
857
858
    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")) {
859
            const QEMULogItem *item;
aliguori's avatar
aliguori committed
860
861
            monitor_printf(mon, "Log items (comma separated):\n");
            monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
862
            for (item = qemu_log_items; item->mask != 0; item++) {
aliguori's avatar
aliguori committed
863
                monitor_printf(mon, "%-10s %s\n", item->name, item->help);
864
            }
865
866
867
868
869
            return;
        }

        if (parse_cmdline(name, &nb_args, args) < 0) {
            return;
870
        }
bellard's avatar
bellard committed
871
    }
872
873
874
875
876

    /* 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
877
878
}

879
static void do_help_cmd(Monitor *mon, const QDict *qdict)
880
{
881
    help_cmd(mon, qdict_get_try_str(qdict, "name"));
882
883
}

884
static void do_trace_event_set_state(Monitor *mon, const QDict *qdict)
885
886
887
{
    const char *tp_name = qdict_get_str(qdict, "name");
    bool new_state = qdict_get_bool(qdict, "option");
888
    Error *local_err = NULL;
889

890
891
892
893
    qmp_trace_event_set_state(tp_name, new_state, true, true, &local_err);
    if (local_err) {
        qerror_report_err(local_err);
        error_free(local_err);
894
    }
895
}
896

897
#ifdef CONFIG_TRACE_SIMPLE
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
static void do_trace_file(Monitor *mon, const QDict *qdict)
{
    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");
    }
}
920
921
#endif

922
923
924
925
926
927
928
929
static void user_monitor_complete(void *opaque, QObject *ret_data)
{
    MonitorCompletionData *data = (MonitorCompletionData *)opaque; 

    if (ret_data) {
        data->user_print(data->mon, ret_data);
    }
    monitor_resume(data->mon);
930
    g_free(data);
931
932
933
934
935
936
937
}

static void qmp_monitor_complete(void *opaque, QObject *ret_data)
{
    monitor_protocol_emitter(opaque, ret_data);
}

938
939
static int qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
                                 const QDict *params)
940
{
941
    return cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);
942
943
944
945
946
947
948
}

static void user_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
                                   const QDict *params)
{
    int ret;

949
    MonitorCompletionData *cb_data = g_malloc(sizeof(*cb_data));
950
951
952
953
954
955
956
    cb_data->mon = mon;
    cb_data->user_print = cmd->user_print;
    monitor_suspend(mon);
    ret = cmd->mhandler.cmd_async(mon, params,
                                  user_monitor_complete, cb_data);
    if (ret < 0) {
        monitor_resume(mon);
957
        g_free(cb_data);
958
959
960
    }
}

961
static void do_info_help(Monitor *mon, const QDict *qdict)
bellard's avatar
bellard committed
962
{
963
    help_cmd(mon, "info");
bellard's avatar
bellard committed
964
965
}

Luiz Capitulino's avatar
Luiz Capitulino committed
966
CommandInfoList *qmp_query_commands(Error **errp)
967
{
Luiz Capitulino's avatar
Luiz Capitulino committed
968
    CommandInfoList *info, *cmd_list = NULL;
969
970
    const mon_cmd_t *cmd;

971
    for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
972
973
974
        info = g_malloc0(sizeof(*info));
        info->value = g_malloc0(sizeof(*info->value));
        info->value->name = g_strdup(cmd->name);
975

Luiz Capitulino's avatar
Luiz Capitulino committed
976
977
        info->next = cmd_list;
        cmd_list = info;
978
979
    }

Luiz Capitulino's avatar
Luiz Capitulino committed
980
    return cmd_list;
981
982
}

983
984
985
EventInfoList *qmp_query_events(Error **errp)
{
    EventInfoList *info, *ev_list = NULL;
Wenchao Xia's avatar
Wenchao Xia committed
986
    QAPIEvent e;
987

Wenchao Xia's avatar
Wenchao Xia committed
988
989
    for (e = 0 ; e < QAPI_EVENT_MAX ; e++) {
        const char *event_name = QAPIEvent_lookup[e];
990
991
992
993
994
995
996
997
998
999
1000
        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;
}
For faster browsing, not all history is shown. View entire blame