Statistics
| Branch: | Revision:

root / monitor.c @ 361127df

History | View | Annotate | Download (124.6 kB)

1
/*
2
 * QEMU monitor
3
 *
4
 * Copyright (c) 2003-2004 Fabrice Bellard
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include <dirent.h>
25
#include "hw/hw.h"
26
#include "hw/qdev.h"
27
#include "hw/usb.h"
28
#include "hw/pcmcia.h"
29
#include "hw/pc.h"
30
#include "hw/pci.h"
31
#include "hw/watchdog.h"
32
#include "hw/loader.h"
33
#include "gdbstub.h"
34
#include "net.h"
35
#include "net/slirp.h"
36
#include "qemu-char.h"
37
#include "sysemu.h"
38
#include "monitor.h"
39
#include "readline.h"
40
#include "console.h"
41
#include "block.h"
42
#include "audio/audio.h"
43
#include "disas.h"
44
#include "balloon.h"
45
#include "qemu-timer.h"
46
#include "migration.h"
47
#include "kvm.h"
48
#include "acl.h"
49
#include "qint.h"
50
#include "qfloat.h"
51
#include "qlist.h"
52
#include "qdict.h"
53
#include "qbool.h"
54
#include "qstring.h"
55
#include "qerror.h"
56
#include "qjson.h"
57
#include "json-streamer.h"
58
#include "json-parser.h"
59
#include "osdep.h"
60

    
61
//#define DEBUG
62
//#define DEBUG_COMPLETION
63

    
64
/*
65
 * Supported types:
66
 *
67
 * 'F'          filename
68
 * 'B'          block device name
69
 * 's'          string (accept optional quote)
70
 * 'O'          option string of the form NAME=VALUE,...
71
 *              parsed according to QemuOptsList given by its name
72
 *              Example: 'device:O' uses qemu_device_opts.
73
 *              Restriction: only lists with empty desc are supported
74
 *              TODO lift the restriction
75
 * 'i'          32 bit integer
76
 * 'l'          target long (32 or 64 bit)
77
 * 'M'          just like 'l', except in user mode the value is
78
 *              multiplied by 2^20 (think Mebibyte)
79
 * 'b'          double
80
 *              user mode accepts an optional G, g, M, m, K, k suffix,
81
 *              which multiplies the value by 2^30 for suffixes G and
82
 *              g, 2^20 for M and m, 2^10 for K and k
83
 * 'T'          double
84
 *              user mode accepts an optional ms, us, ns suffix,
85
 *              which divides the value by 1e3, 1e6, 1e9, respectively
86
 * '/'          optional gdb-like print format (like "/10x")
87
 *
88
 * '?'          optional type (for all types, except '/')
89
 * '.'          other form of optional type (for 'i' and 'l')
90
 * '-'          optional parameter (eg. '-f')
91
 *
92
 */
93

    
94
typedef struct MonitorCompletionData MonitorCompletionData;
95
struct MonitorCompletionData {
96
    Monitor *mon;
97
    void (*user_print)(Monitor *mon, const QObject *data);
98
};
99

    
100
typedef struct mon_cmd_t {
101
    const char *name;
102
    const char *args_type;
103
    const char *params;
104
    const char *help;
105
    void (*user_print)(Monitor *mon, const QObject *data);
106
    union {
107
        void (*info)(Monitor *mon);
108
        void (*info_new)(Monitor *mon, QObject **ret_data);
109
        int  (*info_async)(Monitor *mon, MonitorCompletion *cb, void *opaque);
110
        void (*cmd)(Monitor *mon, const QDict *qdict);
111
        int  (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data);
112
        int  (*cmd_async)(Monitor *mon, const QDict *params,
113
                          MonitorCompletion *cb, void *opaque);
114
    } mhandler;
115
    int async;
116
} mon_cmd_t;
117

    
118
/* file descriptors passed via SCM_RIGHTS */
119
typedef struct mon_fd_t mon_fd_t;
120
struct mon_fd_t {
121
    char *name;
122
    int fd;
123
    QLIST_ENTRY(mon_fd_t) next;
124
};
125

    
126
typedef struct MonitorControl {
127
    QObject *id;
128
    JSONMessageParser parser;
129
    int command_mode;
130
} MonitorControl;
131

    
132
struct Monitor {
133
    CharDriverState *chr;
134
    int mux_out;
135
    int reset_seen;
136
    int flags;
137
    int suspend_cnt;
138
    uint8_t outbuf[1024];
139
    int outbuf_index;
140
    ReadLineState *rs;
141
    MonitorControl *mc;
142
    CPUState *mon_cpu;
143
    BlockDriverCompletionFunc *password_completion_cb;
144
    void *password_opaque;
145
#ifdef CONFIG_DEBUG_MONITOR
146
    int print_calls_nr;
147
#endif
148
    QError *error;
149
    QLIST_HEAD(,mon_fd_t) fds;
150
    QLIST_ENTRY(Monitor) entry;
151
};
152

    
153
#ifdef CONFIG_DEBUG_MONITOR
154
#define MON_DEBUG(fmt, ...) do {    \
155
    fprintf(stderr, "Monitor: ");       \
156
    fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
157

    
158
static inline void mon_print_count_inc(Monitor *mon)
159
{
160
    mon->print_calls_nr++;
161
}
162

    
163
static inline void mon_print_count_init(Monitor *mon)
164
{
165
    mon->print_calls_nr = 0;
166
}
167

    
168
static inline int mon_print_count_get(const Monitor *mon)
169
{
170
    return mon->print_calls_nr;
171
}
172

    
173
#else /* !CONFIG_DEBUG_MONITOR */
174
#define MON_DEBUG(fmt, ...) do { } while (0)
175
static inline void mon_print_count_inc(Monitor *mon) { }
176
static inline void mon_print_count_init(Monitor *mon) { }
177
static inline int mon_print_count_get(const Monitor *mon) { return 0; }
178
#endif /* CONFIG_DEBUG_MONITOR */
179

    
180
static QLIST_HEAD(mon_list, Monitor) mon_list;
181

    
182
static const mon_cmd_t mon_cmds[];
183
static const mon_cmd_t info_cmds[];
184

    
185
Monitor *cur_mon;
186
Monitor *default_mon;
187

    
188
static void monitor_command_cb(Monitor *mon, const char *cmdline,
189
                               void *opaque);
190

    
191
static inline int qmp_cmd_mode(const Monitor *mon)
192
{
193
    return (mon->mc ? mon->mc->command_mode : 0);
194
}
195

    
196
/* Return true if in control mode, false otherwise */
197
static inline int monitor_ctrl_mode(const Monitor *mon)
198
{
199
    return (mon->flags & MONITOR_USE_CONTROL);
200
}
201

    
202
/* Return non-zero iff we have a current monitor, and it is in QMP mode.  */
203
int monitor_cur_is_qmp(void)
204
{
205
    return cur_mon && monitor_ctrl_mode(cur_mon);
206
}
207

    
208
static void monitor_read_command(Monitor *mon, int show_prompt)
209
{
210
    if (!mon->rs)
211
        return;
212

    
213
    readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
214
    if (show_prompt)
215
        readline_show_prompt(mon->rs);
216
}
217

    
218
static int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
219
                                 void *opaque)
220
{
221
    if (monitor_ctrl_mode(mon)) {
222
        qerror_report(QERR_MISSING_PARAMETER, "password");
223
        return -EINVAL;
224
    } else if (mon->rs) {
225
        readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
226
        /* prompt is printed on return from the command handler */
227
        return 0;
228
    } else {
229
        monitor_printf(mon, "terminal does not support password prompting\n");
230
        return -ENOTTY;
231
    }
232
}
233

    
234
void monitor_flush(Monitor *mon)
235
{
236
    if (mon && mon->outbuf_index != 0 && !mon->mux_out) {
237
        qemu_chr_write(mon->chr, mon->outbuf, mon->outbuf_index);
238
        mon->outbuf_index = 0;
239
    }
240
}
241

    
242
/* flush at every end of line or if the buffer is full */
243
static void monitor_puts(Monitor *mon, const char *str)
244
{
245
    char c;
246

    
247
    for(;;) {
248
        c = *str++;
249
        if (c == '\0')
250
            break;
251
        if (c == '\n')
252
            mon->outbuf[mon->outbuf_index++] = '\r';
253
        mon->outbuf[mon->outbuf_index++] = c;
254
        if (mon->outbuf_index >= (sizeof(mon->outbuf) - 1)
255
            || c == '\n')
256
            monitor_flush(mon);
257
    }
258
}
259

    
260
void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
261
{
262
    char buf[4096];
263

    
264
    if (!mon)
265
        return;
266

    
267
    mon_print_count_inc(mon);
268

    
269
    if (monitor_ctrl_mode(mon)) {
270
        return;
271
    }
272

    
273
    vsnprintf(buf, sizeof(buf), fmt, ap);
274
    monitor_puts(mon, buf);
275
}
276

    
277
void monitor_printf(Monitor *mon, const char *fmt, ...)
278
{
279
    va_list ap;
280
    va_start(ap, fmt);
281
    monitor_vprintf(mon, fmt, ap);
282
    va_end(ap);
283
}
284

    
285
void monitor_print_filename(Monitor *mon, const char *filename)
286
{
287
    int i;
288

    
289
    for (i = 0; filename[i]; i++) {
290
        switch (filename[i]) {
291
        case ' ':
292
        case '"':
293
        case '\\':
294
            monitor_printf(mon, "\\%c", filename[i]);
295
            break;
296
        case '\t':
297
            monitor_printf(mon, "\\t");
298
            break;
299
        case '\r':
300
            monitor_printf(mon, "\\r");
301
            break;
302
        case '\n':
303
            monitor_printf(mon, "\\n");
304
            break;
305
        default:
306
            monitor_printf(mon, "%c", filename[i]);
307
            break;
308
        }
309
    }
310
}
311

    
312
static int monitor_fprintf(FILE *stream, const char *fmt, ...)
313
{
314
    va_list ap;
315
    va_start(ap, fmt);
316
    monitor_vprintf((Monitor *)stream, fmt, ap);
317
    va_end(ap);
318
    return 0;
319
}
320

    
321
static void monitor_user_noop(Monitor *mon, const QObject *data) { }
322

    
323
static inline int monitor_handler_ported(const mon_cmd_t *cmd)
324
{
325
    return cmd->user_print != NULL;
326
}
327

    
328
static inline bool monitor_handler_is_async(const mon_cmd_t *cmd)
329
{
330
    return cmd->async != 0;
331
}
332

    
333
static inline int monitor_has_error(const Monitor *mon)
334
{
335
    return mon->error != NULL;
336
}
337

    
338
static void monitor_json_emitter(Monitor *mon, const QObject *data)
339
{
340
    QString *json;
341

    
342
    json = qobject_to_json(data);
343
    assert(json != NULL);
344

    
345
    qstring_append_chr(json, '\n');
346
    monitor_puts(mon, qstring_get_str(json));
347

    
348
    QDECREF(json);
349
}
350

    
351
static void monitor_protocol_emitter(Monitor *mon, QObject *data)
352
{
353
    QDict *qmp;
354

    
355
    qmp = qdict_new();
356

    
357
    if (!monitor_has_error(mon)) {
358
        /* success response */
359
        if (data) {
360
            qobject_incref(data);
361
            qdict_put_obj(qmp, "return", data);
362
        } else {
363
            /* return an empty QDict by default */
364
            qdict_put(qmp, "return", qdict_new());
365
        }
366
    } else {
367
        /* error response */
368
        qdict_put(mon->error->error, "desc", qerror_human(mon->error));
369
        qdict_put(qmp, "error", mon->error->error);
370
        QINCREF(mon->error->error);
371
        QDECREF(mon->error);
372
        mon->error = NULL;
373
    }
374

    
375
    if (mon->mc->id) {
376
        qdict_put_obj(qmp, "id", mon->mc->id);
377
        mon->mc->id = NULL;
378
    }
379

    
380
    monitor_json_emitter(mon, QOBJECT(qmp));
381
    QDECREF(qmp);
382
}
383

    
384
static void timestamp_put(QDict *qdict)
385
{
386
    int err;
387
    QObject *obj;
388
    qemu_timeval tv;
389

    
390
    err = qemu_gettimeofday(&tv);
391
    if (err < 0)
392
        return;
393

    
394
    obj = qobject_from_jsonf("{ 'seconds': %" PRId64 ", "
395
                                "'microseconds': %" PRId64 " }",
396
                                (int64_t) tv.tv_sec, (int64_t) tv.tv_usec);
397
    qdict_put_obj(qdict, "timestamp", obj);
398
}
399

    
400
/**
401
 * monitor_protocol_event(): Generate a Monitor event
402
 *
403
 * Event-specific data can be emitted through the (optional) 'data' parameter.
404
 */
405
void monitor_protocol_event(MonitorEvent event, QObject *data)
406
{
407
    QDict *qmp;
408
    const char *event_name;
409
    Monitor *mon;
410

    
411
    assert(event < QEVENT_MAX);
412

    
413
    switch (event) {
414
        case QEVENT_SHUTDOWN:
415
            event_name = "SHUTDOWN";
416
            break;
417
        case QEVENT_RESET:
418
            event_name = "RESET";
419
            break;
420
        case QEVENT_POWERDOWN:
421
            event_name = "POWERDOWN";
422
            break;
423
        case QEVENT_STOP:
424
            event_name = "STOP";
425
            break;
426
        case QEVENT_VNC_CONNECTED:
427
            event_name = "VNC_CONNECTED";
428
            break;
429
        case QEVENT_VNC_INITIALIZED:
430
            event_name = "VNC_INITIALIZED";
431
            break;
432
        case QEVENT_VNC_DISCONNECTED:
433
            event_name = "VNC_DISCONNECTED";
434
            break;
435
        case QEVENT_BLOCK_IO_ERROR:
436
            event_name = "BLOCK_IO_ERROR";
437
            break;
438
        case QEVENT_RTC_CHANGE:
439
            event_name = "RTC_CHANGE";
440
            break;
441
        case QEVENT_WATCHDOG:
442
            event_name = "WATCHDOG";
443
            break;
444
        default:
445
            abort();
446
            break;
447
    }
448

    
449
    qmp = qdict_new();
450
    timestamp_put(qmp);
451
    qdict_put(qmp, "event", qstring_from_str(event_name));
452
    if (data) {
453
        qobject_incref(data);
454
        qdict_put_obj(qmp, "data", data);
455
    }
456

    
457
    QLIST_FOREACH(mon, &mon_list, entry) {
458
        if (monitor_ctrl_mode(mon) && qmp_cmd_mode(mon)) {
459
            monitor_json_emitter(mon, QOBJECT(qmp));
460
        }
461
    }
462
    QDECREF(qmp);
463
}
464

    
465
static int do_qmp_capabilities(Monitor *mon, const QDict *params,
466
                               QObject **ret_data)
467
{
468
    /* Will setup QMP capabilities in the future */
469
    if (monitor_ctrl_mode(mon)) {
470
        mon->mc->command_mode = 1;
471
    }
472

    
473
    return 0;
474
}
475

    
476
static int compare_cmd(const char *name, const char *list)
477
{
478
    const char *p, *pstart;
479
    int len;
480
    len = strlen(name);
481
    p = list;
482
    for(;;) {
483
        pstart = p;
484
        p = strchr(p, '|');
485
        if (!p)
486
            p = pstart + strlen(pstart);
487
        if ((p - pstart) == len && !memcmp(pstart, name, len))
488
            return 1;
489
        if (*p == '\0')
490
            break;
491
        p++;
492
    }
493
    return 0;
494
}
495

    
496
static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
497
                          const char *prefix, const char *name)
498
{
499
    const mon_cmd_t *cmd;
500

    
501
    for(cmd = cmds; cmd->name != NULL; cmd++) {
502
        if (!name || !strcmp(name, cmd->name))
503
            monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
504
                           cmd->params, cmd->help);
505
    }
506
}
507

    
508
static void help_cmd(Monitor *mon, const char *name)
509
{
510
    if (name && !strcmp(name, "info")) {
511
        help_cmd_dump(mon, info_cmds, "info ", NULL);
512
    } else {
513
        help_cmd_dump(mon, mon_cmds, "", name);
514
        if (name && !strcmp(name, "log")) {
515
            const CPULogItem *item;
516
            monitor_printf(mon, "Log items (comma separated):\n");
517
            monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
518
            for(item = cpu_log_items; item->mask != 0; item++) {
519
                monitor_printf(mon, "%-10s %s\n", item->name, item->help);
520
            }
521
        }
522
    }
523
}
524

    
525
static void do_help_cmd(Monitor *mon, const QDict *qdict)
526
{
527
    help_cmd(mon, qdict_get_try_str(qdict, "name"));
528
}
529

    
530
static void do_commit(Monitor *mon, const QDict *qdict)
531
{
532
    int all_devices;
533
    DriveInfo *dinfo;
534
    const char *device = qdict_get_str(qdict, "device");
535

    
536
    all_devices = !strcmp(device, "all");
537
    QTAILQ_FOREACH(dinfo, &drives, next) {
538
        if (!all_devices)
539
            if (strcmp(bdrv_get_device_name(dinfo->bdrv), device))
540
                continue;
541
        bdrv_commit(dinfo->bdrv);
542
    }
543
}
544

    
545
static void user_monitor_complete(void *opaque, QObject *ret_data)
546
{
547
    MonitorCompletionData *data = (MonitorCompletionData *)opaque; 
548

    
549
    if (ret_data) {
550
        data->user_print(data->mon, ret_data);
551
    }
552
    monitor_resume(data->mon);
553
    qemu_free(data);
554
}
555

    
556
static void qmp_monitor_complete(void *opaque, QObject *ret_data)
557
{
558
    monitor_protocol_emitter(opaque, ret_data);
559
}
560

    
561
static void qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
562
                                  const QDict *params)
563
{
564
    cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);
565
}
566

    
567
static void qmp_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
568
{
569
    cmd->mhandler.info_async(mon, qmp_monitor_complete, mon);
570
}
571

    
572
static void user_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
573
                                   const QDict *params)
574
{
575
    int ret;
576

    
577
    MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
578
    cb_data->mon = mon;
579
    cb_data->user_print = cmd->user_print;
580
    monitor_suspend(mon);
581
    ret = cmd->mhandler.cmd_async(mon, params,
582
                                  user_monitor_complete, cb_data);
583
    if (ret < 0) {
584
        monitor_resume(mon);
585
        qemu_free(cb_data);
586
    }
587
}
588

    
589
static void user_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
590
{
591
    int ret;
592

    
593
    MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
594
    cb_data->mon = mon;
595
    cb_data->user_print = cmd->user_print;
596
    monitor_suspend(mon);
597
    ret = cmd->mhandler.info_async(mon, user_monitor_complete, cb_data);
598
    if (ret < 0) {
599
        monitor_resume(mon);
600
        qemu_free(cb_data);
601
    }
602
}
603

    
604
static int do_info(Monitor *mon, const QDict *qdict, QObject **ret_data)
605
{
606
    const mon_cmd_t *cmd;
607
    const char *item = qdict_get_try_str(qdict, "item");
608

    
609
    if (!item) {
610
        assert(monitor_ctrl_mode(mon) == 0);
611
        goto help;
612
    }
613

    
614
    for (cmd = info_cmds; cmd->name != NULL; cmd++) {
615
        if (compare_cmd(item, cmd->name))
616
            break;
617
    }
618

    
619
    if (cmd->name == NULL) {
620
        if (monitor_ctrl_mode(mon)) {
621
            qerror_report(QERR_COMMAND_NOT_FOUND, item);
622
            return -1;
623
        }
624
        goto help;
625
    }
626

    
627
    if (monitor_handler_is_async(cmd)) {
628
        if (monitor_ctrl_mode(mon)) {
629
            qmp_async_info_handler(mon, cmd);
630
        } else {
631
            user_async_info_handler(mon, cmd);
632
        }
633
        /*
634
         * Indicate that this command is asynchronous and will not return any
635
         * data (not even empty).  Instead, the data will be returned via a
636
         * completion callback.
637
         */
638
        *ret_data = qobject_from_jsonf("{ '__mon_async': 'return' }");
639
    } else if (monitor_handler_ported(cmd)) {
640
        cmd->mhandler.info_new(mon, ret_data);
641

    
642
        if (!monitor_ctrl_mode(mon)) {
643
            /*
644
             * User Protocol function is called here, Monitor Protocol is
645
             * handled by monitor_call_handler()
646
             */
647
            if (*ret_data)
648
                cmd->user_print(mon, *ret_data);
649
        }
650
    } else {
651
        if (monitor_ctrl_mode(mon)) {
652
            /* handler not converted yet */
653
            qerror_report(QERR_COMMAND_NOT_FOUND, item);
654
            return -1;
655
        } else {
656
            cmd->mhandler.info(mon);
657
        }
658
    }
659

    
660
    return 0;
661

    
662
help:
663
    help_cmd(mon, "info");
664
    return 0;
665
}
666

    
667
static void do_info_version_print(Monitor *mon, const QObject *data)
668
{
669
    QDict *qdict;
670

    
671
    qdict = qobject_to_qdict(data);
672

    
673
    monitor_printf(mon, "%s%s\n", qdict_get_str(qdict, "qemu"),
674
                                  qdict_get_str(qdict, "package"));
675
}
676

    
677
/**
678
 * do_info_version(): Show QEMU version
679
 *
680
 * Return a QDict with the following information:
681
 *
682
 * - "qemu": QEMU's version
683
 * - "package": package's version
684
 *
685
 * Example:
686
 *
687
 * { "qemu": "0.11.50", "package": "" }
688
 */
689
static void do_info_version(Monitor *mon, QObject **ret_data)
690
{
691
    *ret_data = qobject_from_jsonf("{ 'qemu': %s, 'package': %s }",
692
                                   QEMU_VERSION, QEMU_PKGVERSION);
693
}
694

    
695
static void do_info_name_print(Monitor *mon, const QObject *data)
696
{
697
    QDict *qdict;
698

    
699
    qdict = qobject_to_qdict(data);
700
    if (qdict_size(qdict) == 0) {
701
        return;
702
    }
703

    
704
    monitor_printf(mon, "%s\n", qdict_get_str(qdict, "name"));
705
}
706

    
707
/**
708
 * do_info_name(): Show VM name
709
 *
710
 * Return a QDict with the following information:
711
 *
712
 * - "name": VM's name (optional)
713
 *
714
 * Example:
715
 *
716
 * { "name": "qemu-name" }
717
 */
718
static void do_info_name(Monitor *mon, QObject **ret_data)
719
{
720
    *ret_data = qemu_name ? qobject_from_jsonf("{'name': %s }", qemu_name) :
721
                            qobject_from_jsonf("{}");
722
}
723

    
724
static QObject *get_cmd_dict(const char *name)
725
{
726
    const char *p;
727

    
728
    /* Remove '|' from some commands */
729
    p = strchr(name, '|');
730
    if (p) {
731
        p++;
732
    } else {
733
        p = name;
734
    }
735

    
736
    return qobject_from_jsonf("{ 'name': %s }", p);
737
}
738

    
739
/**
740
 * do_info_commands(): List QMP available commands
741
 *
742
 * Each command is represented by a QDict, the returned QObject is a QList
743
 * of all commands.
744
 *
745
 * The QDict contains:
746
 *
747
 * - "name": command's name
748
 *
749
 * Example:
750
 *
751
 * { [ { "name": "query-balloon" }, { "name": "system_powerdown" } ] }
752
 */
753
static void do_info_commands(Monitor *mon, QObject **ret_data)
754
{
755
    QList *cmd_list;
756
    const mon_cmd_t *cmd;
757

    
758
    cmd_list = qlist_new();
759

    
760
    for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
761
        if (monitor_handler_ported(cmd) && !compare_cmd(cmd->name, "info")) {
762
            qlist_append_obj(cmd_list, get_cmd_dict(cmd->name));
763
        }
764
    }
765

    
766
    for (cmd = info_cmds; cmd->name != NULL; cmd++) {
767
        if (monitor_handler_ported(cmd)) {
768
            char buf[128];
769
            snprintf(buf, sizeof(buf), "query-%s", cmd->name);
770
            qlist_append_obj(cmd_list, get_cmd_dict(buf));
771
        }
772
    }
773

    
774
    *ret_data = QOBJECT(cmd_list);
775
}
776

    
777
#if defined(TARGET_I386)
778
static void do_info_hpet_print(Monitor *mon, const QObject *data)
779
{
780
    monitor_printf(mon, "HPET is %s by QEMU\n",
781
                   qdict_get_bool(qobject_to_qdict(data), "enabled") ?
782
                   "enabled" : "disabled");
783
}
784

    
785
/**
786
 * do_info_hpet(): Show HPET state
787
 *
788
 * Return a QDict with the following information:
789
 *
790
 * - "enabled": true if hpet if enabled, false otherwise
791
 *
792
 * Example:
793
 *
794
 * { "enabled": true }
795
 */
796
static void do_info_hpet(Monitor *mon, QObject **ret_data)
797
{
798
    *ret_data = qobject_from_jsonf("{ 'enabled': %i }", !no_hpet);
799
}
800
#endif
801

    
802
static void do_info_uuid_print(Monitor *mon, const QObject *data)
803
{
804
    monitor_printf(mon, "%s\n", qdict_get_str(qobject_to_qdict(data), "UUID"));
805
}
806

    
807
/**
808
 * do_info_uuid(): Show VM UUID
809
 *
810
 * Return a QDict with the following information:
811
 *
812
 * - "UUID": Universally Unique Identifier
813
 *
814
 * Example:
815
 *
816
 * { "UUID": "550e8400-e29b-41d4-a716-446655440000" }
817
 */
818
static void do_info_uuid(Monitor *mon, QObject **ret_data)
819
{
820
    char uuid[64];
821

    
822
    snprintf(uuid, sizeof(uuid), UUID_FMT, qemu_uuid[0], qemu_uuid[1],
823
                   qemu_uuid[2], qemu_uuid[3], qemu_uuid[4], qemu_uuid[5],
824
                   qemu_uuid[6], qemu_uuid[7], qemu_uuid[8], qemu_uuid[9],
825
                   qemu_uuid[10], qemu_uuid[11], qemu_uuid[12], qemu_uuid[13],
826
                   qemu_uuid[14], qemu_uuid[15]);
827
    *ret_data = qobject_from_jsonf("{ 'UUID': %s }", uuid);
828
}
829

    
830
/* get the current CPU defined by the user */
831
static int mon_set_cpu(int cpu_index)
832
{
833
    CPUState *env;
834

    
835
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
836
        if (env->cpu_index == cpu_index) {
837
            cur_mon->mon_cpu = env;
838
            return 0;
839
        }
840
    }
841
    return -1;
842
}
843

    
844
static CPUState *mon_get_cpu(void)
845
{
846
    if (!cur_mon->mon_cpu) {
847
        mon_set_cpu(0);
848
    }
849
    cpu_synchronize_state(cur_mon->mon_cpu);
850
    return cur_mon->mon_cpu;
851
}
852

    
853
static void do_info_registers(Monitor *mon)
854
{
855
    CPUState *env;
856
    env = mon_get_cpu();
857
#ifdef TARGET_I386
858
    cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
859
                   X86_DUMP_FPU);
860
#else
861
    cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
862
                   0);
863
#endif
864
}
865

    
866
static void print_cpu_iter(QObject *obj, void *opaque)
867
{
868
    QDict *cpu;
869
    int active = ' ';
870
    Monitor *mon = opaque;
871

    
872
    assert(qobject_type(obj) == QTYPE_QDICT);
873
    cpu = qobject_to_qdict(obj);
874

    
875
    if (qdict_get_bool(cpu, "current")) {
876
        active = '*';
877
    }
878

    
879
    monitor_printf(mon, "%c CPU #%d: ", active, (int)qdict_get_int(cpu, "CPU"));
880

    
881
#if defined(TARGET_I386)
882
    monitor_printf(mon, "pc=0x" TARGET_FMT_lx,
883
                   (target_ulong) qdict_get_int(cpu, "pc"));
884
#elif defined(TARGET_PPC)
885
    monitor_printf(mon, "nip=0x" TARGET_FMT_lx,
886
                   (target_long) qdict_get_int(cpu, "nip"));
887
#elif defined(TARGET_SPARC)
888
    monitor_printf(mon, "pc=0x " TARGET_FMT_lx,
889
                   (target_long) qdict_get_int(cpu, "pc"));
890
    monitor_printf(mon, "npc=0x" TARGET_FMT_lx,
891
                   (target_long) qdict_get_int(cpu, "npc"));
892
#elif defined(TARGET_MIPS)
893
    monitor_printf(mon, "PC=0x" TARGET_FMT_lx,
894
                   (target_long) qdict_get_int(cpu, "PC"));
895
#endif
896

    
897
    if (qdict_get_bool(cpu, "halted")) {
898
        monitor_printf(mon, " (halted)");
899
    }
900

    
901
    monitor_printf(mon, "\n");
902
}
903

    
904
static void monitor_print_cpus(Monitor *mon, const QObject *data)
905
{
906
    QList *cpu_list;
907

    
908
    assert(qobject_type(data) == QTYPE_QLIST);
909
    cpu_list = qobject_to_qlist(data);
910
    qlist_iter(cpu_list, print_cpu_iter, mon);
911
}
912

    
913
/**
914
 * do_info_cpus(): Show CPU information
915
 *
916
 * Return a QList. Each CPU is represented by a QDict, which contains:
917
 *
918
 * - "cpu": CPU index
919
 * - "current": true if this is the current CPU, false otherwise
920
 * - "halted": true if the cpu is halted, false otherwise
921
 * - Current program counter. The key's name depends on the architecture:
922
 *      "pc": i386/x86)64
923
 *      "nip": PPC
924
 *      "pc" and "npc": sparc
925
 *      "PC": mips
926
 *
927
 * Example:
928
 *
929
 * [ { "CPU": 0, "current": true, "halted": false, "pc": 3227107138 },
930
 *   { "CPU": 1, "current": false, "halted": true, "pc": 7108165 } ]
931
 */
932
static void do_info_cpus(Monitor *mon, QObject **ret_data)
933
{
934
    CPUState *env;
935
    QList *cpu_list;
936

    
937
    cpu_list = qlist_new();
938

    
939
    /* just to set the default cpu if not already done */
940
    mon_get_cpu();
941

    
942
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
943
        QDict *cpu;
944
        QObject *obj;
945

    
946
        cpu_synchronize_state(env);
947

    
948
        obj = qobject_from_jsonf("{ 'CPU': %d, 'current': %i, 'halted': %i }",
949
                                 env->cpu_index, env == mon->mon_cpu,
950
                                 env->halted);
951

    
952
        cpu = qobject_to_qdict(obj);
953

    
954
#if defined(TARGET_I386)
955
        qdict_put(cpu, "pc", qint_from_int(env->eip + env->segs[R_CS].base));
956
#elif defined(TARGET_PPC)
957
        qdict_put(cpu, "nip", qint_from_int(env->nip));
958
#elif defined(TARGET_SPARC)
959
        qdict_put(cpu, "pc", qint_from_int(env->pc));
960
        qdict_put(cpu, "npc", qint_from_int(env->npc));
961
#elif defined(TARGET_MIPS)
962
        qdict_put(cpu, "PC", qint_from_int(env->active_tc.PC));
963
#endif
964

    
965
        qlist_append(cpu_list, cpu);
966
    }
967

    
968
    *ret_data = QOBJECT(cpu_list);
969
}
970

    
971
static int do_cpu_set(Monitor *mon, const QDict *qdict, QObject **ret_data)
972
{
973
    int index = qdict_get_int(qdict, "index");
974
    if (mon_set_cpu(index) < 0) {
975
        qerror_report(QERR_INVALID_PARAMETER, "index");
976
        return -1;
977
    }
978
    return 0;
979
}
980

    
981
static void do_info_jit(Monitor *mon)
982
{
983
    dump_exec_info((FILE *)mon, monitor_fprintf);
984
}
985

    
986
static void do_info_history(Monitor *mon)
987
{
988
    int i;
989
    const char *str;
990

    
991
    if (!mon->rs)
992
        return;
993
    i = 0;
994
    for(;;) {
995
        str = readline_get_history(mon->rs, i);
996
        if (!str)
997
            break;
998
        monitor_printf(mon, "%d: '%s'\n", i, str);
999
        i++;
1000
    }
1001
}
1002

    
1003
#if defined(TARGET_PPC)
1004
/* XXX: not implemented in other targets */
1005
static void do_info_cpu_stats(Monitor *mon)
1006
{
1007
    CPUState *env;
1008

    
1009
    env = mon_get_cpu();
1010
    cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
1011
}
1012
#endif
1013

    
1014
/**
1015
 * do_quit(): Quit QEMU execution
1016
 */
1017
static int do_quit(Monitor *mon, const QDict *qdict, QObject **ret_data)
1018
{
1019
    exit(0);
1020
    return 0;
1021
}
1022

    
1023
static int eject_device(Monitor *mon, BlockDriverState *bs, int force)
1024
{
1025
    if (bdrv_is_inserted(bs)) {
1026
        if (!force) {
1027
            if (!bdrv_is_removable(bs)) {
1028
                qerror_report(QERR_DEVICE_NOT_REMOVABLE,
1029
                               bdrv_get_device_name(bs));
1030
                return -1;
1031
            }
1032
            if (bdrv_is_locked(bs)) {
1033
                qerror_report(QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));
1034
                return -1;
1035
            }
1036
        }
1037
        bdrv_close(bs);
1038
    }
1039
    return 0;
1040
}
1041

    
1042
static int do_eject(Monitor *mon, const QDict *qdict, QObject **ret_data)
1043
{
1044
    BlockDriverState *bs;
1045
    int force = qdict_get_int(qdict, "force");
1046
    const char *filename = qdict_get_str(qdict, "device");
1047

    
1048
    bs = bdrv_find(filename);
1049
    if (!bs) {
1050
        qerror_report(QERR_DEVICE_NOT_FOUND, filename);
1051
        return -1;
1052
    }
1053
    return eject_device(mon, bs, force);
1054
}
1055

    
1056
static int do_block_set_passwd(Monitor *mon, const QDict *qdict,
1057
                                QObject **ret_data)
1058
{
1059
    BlockDriverState *bs;
1060

    
1061
    bs = bdrv_find(qdict_get_str(qdict, "device"));
1062
    if (!bs) {
1063
        qerror_report(QERR_DEVICE_NOT_FOUND, qdict_get_str(qdict, "device"));
1064
        return -1;
1065
    }
1066

    
1067
    if (bdrv_set_key(bs, qdict_get_str(qdict, "password")) < 0) {
1068
        qerror_report(QERR_INVALID_PASSWORD);
1069
        return -1;
1070
    }
1071

    
1072
    return 0;
1073
}
1074

    
1075
static int do_change_block(Monitor *mon, const char *device,
1076
                           const char *filename, const char *fmt)
1077
{
1078
    BlockDriverState *bs;
1079
    BlockDriver *drv = NULL;
1080

    
1081
    bs = bdrv_find(device);
1082
    if (!bs) {
1083
        qerror_report(QERR_DEVICE_NOT_FOUND, device);
1084
        return -1;
1085
    }
1086
    if (fmt) {
1087
        drv = bdrv_find_whitelisted_format(fmt);
1088
        if (!drv) {
1089
            qerror_report(QERR_INVALID_BLOCK_FORMAT, fmt);
1090
            return -1;
1091
        }
1092
    }
1093
    if (eject_device(mon, bs, 0) < 0) {
1094
        return -1;
1095
    }
1096
    if (bdrv_open2(bs, filename, BDRV_O_RDWR, drv) < 0) {
1097
        return -1;
1098
    }
1099
    return monitor_read_bdrv_key_start(mon, bs, NULL, NULL);
1100
}
1101

    
1102
static int change_vnc_password(const char *password)
1103
{
1104
    if (vnc_display_password(NULL, password) < 0) {
1105
        qerror_report(QERR_SET_PASSWD_FAILED);
1106
        return -1;
1107
    }
1108

    
1109
    return 0;
1110
}
1111

    
1112
static void change_vnc_password_cb(Monitor *mon, const char *password,
1113
                                   void *opaque)
1114
{
1115
    change_vnc_password(password);
1116
    monitor_read_command(mon, 1);
1117
}
1118

    
1119
static int do_change_vnc(Monitor *mon, const char *target, const char *arg)
1120
{
1121
    if (strcmp(target, "passwd") == 0 ||
1122
        strcmp(target, "password") == 0) {
1123
        if (arg) {
1124
            char password[9];
1125
            strncpy(password, arg, sizeof(password));
1126
            password[sizeof(password) - 1] = '\0';
1127
            return change_vnc_password(password);
1128
        } else {
1129
            return monitor_read_password(mon, change_vnc_password_cb, NULL);
1130
        }
1131
    } else {
1132
        if (vnc_display_open(NULL, target) < 0) {
1133
            qerror_report(QERR_VNC_SERVER_FAILED, target);
1134
            return -1;
1135
        }
1136
    }
1137

    
1138
    return 0;
1139
}
1140

    
1141
/**
1142
 * do_change(): Change a removable medium, or VNC configuration
1143
 */
1144
static int do_change(Monitor *mon, const QDict *qdict, QObject **ret_data)
1145
{
1146
    const char *device = qdict_get_str(qdict, "device");
1147
    const char *target = qdict_get_str(qdict, "target");
1148
    const char *arg = qdict_get_try_str(qdict, "arg");
1149
    int ret;
1150

    
1151
    if (strcmp(device, "vnc") == 0) {
1152
        ret = do_change_vnc(mon, target, arg);
1153
    } else {
1154
        ret = do_change_block(mon, device, target, arg);
1155
    }
1156

    
1157
    return ret;
1158
}
1159

    
1160
static void do_screen_dump(Monitor *mon, const QDict *qdict)
1161
{
1162
    vga_hw_screen_dump(qdict_get_str(qdict, "filename"));
1163
}
1164

    
1165
static void do_logfile(Monitor *mon, const QDict *qdict)
1166
{
1167
    cpu_set_log_filename(qdict_get_str(qdict, "filename"));
1168
}
1169

    
1170
static void do_log(Monitor *mon, const QDict *qdict)
1171
{
1172
    int mask;
1173
    const char *items = qdict_get_str(qdict, "items");
1174

    
1175
    if (!strcmp(items, "none")) {
1176
        mask = 0;
1177
    } else {
1178
        mask = cpu_str_to_log_mask(items);
1179
        if (!mask) {
1180
            help_cmd(mon, "log");
1181
            return;
1182
        }
1183
    }
1184
    cpu_set_log(mask);
1185
}
1186

    
1187
static void do_singlestep(Monitor *mon, const QDict *qdict)
1188
{
1189
    const char *option = qdict_get_try_str(qdict, "option");
1190
    if (!option || !strcmp(option, "on")) {
1191
        singlestep = 1;
1192
    } else if (!strcmp(option, "off")) {
1193
        singlestep = 0;
1194
    } else {
1195
        monitor_printf(mon, "unexpected option %s\n", option);
1196
    }
1197
}
1198

    
1199
/**
1200
 * do_stop(): Stop VM execution
1201
 */
1202
static int do_stop(Monitor *mon, const QDict *qdict, QObject **ret_data)
1203
{
1204
    vm_stop(EXCP_INTERRUPT);
1205
    return 0;
1206
}
1207

    
1208
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs);
1209

    
1210
struct bdrv_iterate_context {
1211
    Monitor *mon;
1212
    int err;
1213
};
1214

    
1215
/**
1216
 * do_cont(): Resume emulation.
1217
 */
1218
static int do_cont(Monitor *mon, const QDict *qdict, QObject **ret_data)
1219
{
1220
    struct bdrv_iterate_context context = { mon, 0 };
1221

    
1222
    bdrv_iterate(encrypted_bdrv_it, &context);
1223
    /* only resume the vm if all keys are set and valid */
1224
    if (!context.err) {
1225
        vm_start();
1226
        return 0;
1227
    } else {
1228
        return -1;
1229
    }
1230
}
1231

    
1232
static void bdrv_key_cb(void *opaque, int err)
1233
{
1234
    Monitor *mon = opaque;
1235

    
1236
    /* another key was set successfully, retry to continue */
1237
    if (!err)
1238
        do_cont(mon, NULL, NULL);
1239
}
1240

    
1241
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs)
1242
{
1243
    struct bdrv_iterate_context *context = opaque;
1244

    
1245
    if (!context->err && bdrv_key_required(bs)) {
1246
        context->err = -EBUSY;
1247
        monitor_read_bdrv_key_start(context->mon, bs, bdrv_key_cb,
1248
                                    context->mon);
1249
    }
1250
}
1251

    
1252
static void do_gdbserver(Monitor *mon, const QDict *qdict)
1253
{
1254
    const char *device = qdict_get_try_str(qdict, "device");
1255
    if (!device)
1256
        device = "tcp::" DEFAULT_GDBSTUB_PORT;
1257
    if (gdbserver_start(device) < 0) {
1258
        monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1259
                       device);
1260
    } else if (strcmp(device, "none") == 0) {
1261
        monitor_printf(mon, "Disabled gdbserver\n");
1262
    } else {
1263
        monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1264
                       device);
1265
    }
1266
}
1267

    
1268
static void do_watchdog_action(Monitor *mon, const QDict *qdict)
1269
{
1270
    const char *action = qdict_get_str(qdict, "action");
1271
    if (select_watchdog_action(action) == -1) {
1272
        monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1273
    }
1274
}
1275

    
1276
static void monitor_printc(Monitor *mon, int c)
1277
{
1278
    monitor_printf(mon, "'");
1279
    switch(c) {
1280
    case '\'':
1281
        monitor_printf(mon, "\\'");
1282
        break;
1283
    case '\\':
1284
        monitor_printf(mon, "\\\\");
1285
        break;
1286
    case '\n':
1287
        monitor_printf(mon, "\\n");
1288
        break;
1289
    case '\r':
1290
        monitor_printf(mon, "\\r");
1291
        break;
1292
    default:
1293
        if (c >= 32 && c <= 126) {
1294
            monitor_printf(mon, "%c", c);
1295
        } else {
1296
            monitor_printf(mon, "\\x%02x", c);
1297
        }
1298
        break;
1299
    }
1300
    monitor_printf(mon, "'");
1301
}
1302

    
1303
static void memory_dump(Monitor *mon, int count, int format, int wsize,
1304
                        target_phys_addr_t addr, int is_physical)
1305
{
1306
    CPUState *env;
1307
    int l, line_size, i, max_digits, len;
1308
    uint8_t buf[16];
1309
    uint64_t v;
1310

    
1311
    if (format == 'i') {
1312
        int flags;
1313
        flags = 0;
1314
        env = mon_get_cpu();
1315
#ifdef TARGET_I386
1316
        if (wsize == 2) {
1317
            flags = 1;
1318
        } else if (wsize == 4) {
1319
            flags = 0;
1320
        } else {
1321
            /* as default we use the current CS size */
1322
            flags = 0;
1323
            if (env) {
1324
#ifdef TARGET_X86_64
1325
                if ((env->efer & MSR_EFER_LMA) &&
1326
                    (env->segs[R_CS].flags & DESC_L_MASK))
1327
                    flags = 2;
1328
                else
1329
#endif
1330
                if (!(env->segs[R_CS].flags & DESC_B_MASK))
1331
                    flags = 1;
1332
            }
1333
        }
1334
#endif
1335
        monitor_disas(mon, env, addr, count, is_physical, flags);
1336
        return;
1337
    }
1338

    
1339
    len = wsize * count;
1340
    if (wsize == 1)
1341
        line_size = 8;
1342
    else
1343
        line_size = 16;
1344
    max_digits = 0;
1345

    
1346
    switch(format) {
1347
    case 'o':
1348
        max_digits = (wsize * 8 + 2) / 3;
1349
        break;
1350
    default:
1351
    case 'x':
1352
        max_digits = (wsize * 8) / 4;
1353
        break;
1354
    case 'u':
1355
    case 'd':
1356
        max_digits = (wsize * 8 * 10 + 32) / 33;
1357
        break;
1358
    case 'c':
1359
        wsize = 1;
1360
        break;
1361
    }
1362

    
1363
    while (len > 0) {
1364
        if (is_physical)
1365
            monitor_printf(mon, TARGET_FMT_plx ":", addr);
1366
        else
1367
            monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1368
        l = len;
1369
        if (l > line_size)
1370
            l = line_size;
1371
        if (is_physical) {
1372
            cpu_physical_memory_rw(addr, buf, l, 0);
1373
        } else {
1374
            env = mon_get_cpu();
1375
            if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {
1376
                monitor_printf(mon, " Cannot access memory\n");
1377
                break;
1378
            }
1379
        }
1380
        i = 0;
1381
        while (i < l) {
1382
            switch(wsize) {
1383
            default:
1384
            case 1:
1385
                v = ldub_raw(buf + i);
1386
                break;
1387
            case 2:
1388
                v = lduw_raw(buf + i);
1389
                break;
1390
            case 4:
1391
                v = (uint32_t)ldl_raw(buf + i);
1392
                break;
1393
            case 8:
1394
                v = ldq_raw(buf + i);
1395
                break;
1396
            }
1397
            monitor_printf(mon, " ");
1398
            switch(format) {
1399
            case 'o':
1400
                monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1401
                break;
1402
            case 'x':
1403
                monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1404
                break;
1405
            case 'u':
1406
                monitor_printf(mon, "%*" PRIu64, max_digits, v);
1407
                break;
1408
            case 'd':
1409
                monitor_printf(mon, "%*" PRId64, max_digits, v);
1410
                break;
1411
            case 'c':
1412
                monitor_printc(mon, v);
1413
                break;
1414
            }
1415
            i += wsize;
1416
        }
1417
        monitor_printf(mon, "\n");
1418
        addr += l;
1419
        len -= l;
1420
    }
1421
}
1422

    
1423
static void do_memory_dump(Monitor *mon, const QDict *qdict)
1424
{
1425
    int count = qdict_get_int(qdict, "count");
1426
    int format = qdict_get_int(qdict, "format");
1427
    int size = qdict_get_int(qdict, "size");
1428
    target_long addr = qdict_get_int(qdict, "addr");
1429

    
1430
    memory_dump(mon, count, format, size, addr, 0);
1431
}
1432

    
1433
static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
1434
{
1435
    int count = qdict_get_int(qdict, "count");
1436
    int format = qdict_get_int(qdict, "format");
1437
    int size = qdict_get_int(qdict, "size");
1438
    target_phys_addr_t addr = qdict_get_int(qdict, "addr");
1439

    
1440
    memory_dump(mon, count, format, size, addr, 1);
1441
}
1442

    
1443
static void do_print(Monitor *mon, const QDict *qdict)
1444
{
1445
    int format = qdict_get_int(qdict, "format");
1446
    target_phys_addr_t val = qdict_get_int(qdict, "val");
1447

    
1448
#if TARGET_PHYS_ADDR_BITS == 32
1449
    switch(format) {
1450
    case 'o':
1451
        monitor_printf(mon, "%#o", val);
1452
        break;
1453
    case 'x':
1454
        monitor_printf(mon, "%#x", val);
1455
        break;
1456
    case 'u':
1457
        monitor_printf(mon, "%u", val);
1458
        break;
1459
    default:
1460
    case 'd':
1461
        monitor_printf(mon, "%d", val);
1462
        break;
1463
    case 'c':
1464
        monitor_printc(mon, val);
1465
        break;
1466
    }
1467
#else
1468
    switch(format) {
1469
    case 'o':
1470
        monitor_printf(mon, "%#" PRIo64, val);
1471
        break;
1472
    case 'x':
1473
        monitor_printf(mon, "%#" PRIx64, val);
1474
        break;
1475
    case 'u':
1476
        monitor_printf(mon, "%" PRIu64, val);
1477
        break;
1478
    default:
1479
    case 'd':
1480
        monitor_printf(mon, "%" PRId64, val);
1481
        break;
1482
    case 'c':
1483
        monitor_printc(mon, val);
1484
        break;
1485
    }
1486
#endif
1487
    monitor_printf(mon, "\n");
1488
}
1489

    
1490
static int do_memory_save(Monitor *mon, const QDict *qdict, QObject **ret_data)
1491
{
1492
    FILE *f;
1493
    uint32_t size = qdict_get_int(qdict, "size");
1494
    const char *filename = qdict_get_str(qdict, "filename");
1495
    target_long addr = qdict_get_int(qdict, "val");
1496
    uint32_t l;
1497
    CPUState *env;
1498
    uint8_t buf[1024];
1499
    int ret = -1;
1500

    
1501
    env = mon_get_cpu();
1502

    
1503
    f = fopen(filename, "wb");
1504
    if (!f) {
1505
        qerror_report(QERR_OPEN_FILE_FAILED, filename);
1506
        return -1;
1507
    }
1508
    while (size != 0) {
1509
        l = sizeof(buf);
1510
        if (l > size)
1511
            l = size;
1512
        cpu_memory_rw_debug(env, addr, buf, l, 0);
1513
        if (fwrite(buf, 1, l, f) != l) {
1514
            monitor_printf(mon, "fwrite() error in do_memory_save\n");
1515
            goto exit;
1516
        }
1517
        addr += l;
1518
        size -= l;
1519
    }
1520

    
1521
    ret = 0;
1522

    
1523
exit:
1524
    fclose(f);
1525
    return ret;
1526
}
1527

    
1528
static int do_physical_memory_save(Monitor *mon, const QDict *qdict,
1529
                                    QObject **ret_data)
1530
{
1531
    FILE *f;
1532
    uint32_t l;
1533
    uint8_t buf[1024];
1534
    uint32_t size = qdict_get_int(qdict, "size");
1535
    const char *filename = qdict_get_str(qdict, "filename");
1536
    target_phys_addr_t addr = qdict_get_int(qdict, "val");
1537
    int ret = -1;
1538

    
1539
    f = fopen(filename, "wb");
1540
    if (!f) {
1541
        qerror_report(QERR_OPEN_FILE_FAILED, filename);
1542
        return -1;
1543
    }
1544
    while (size != 0) {
1545
        l = sizeof(buf);
1546
        if (l > size)
1547
            l = size;
1548
        cpu_physical_memory_rw(addr, buf, l, 0);
1549
        if (fwrite(buf, 1, l, f) != l) {
1550
            monitor_printf(mon, "fwrite() error in do_physical_memory_save\n");
1551
            goto exit;
1552
        }
1553
        fflush(f);
1554
        addr += l;
1555
        size -= l;
1556
    }
1557

    
1558
    ret = 0;
1559

    
1560
exit:
1561
    fclose(f);
1562
    return ret;
1563
}
1564

    
1565
static void do_sum(Monitor *mon, const QDict *qdict)
1566
{
1567
    uint32_t addr;
1568
    uint8_t buf[1];
1569
    uint16_t sum;
1570
    uint32_t start = qdict_get_int(qdict, "start");
1571
    uint32_t size = qdict_get_int(qdict, "size");
1572

    
1573
    sum = 0;
1574
    for(addr = start; addr < (start + size); addr++) {
1575
        cpu_physical_memory_rw(addr, buf, 1, 0);
1576
        /* BSD sum algorithm ('sum' Unix command) */
1577
        sum = (sum >> 1) | (sum << 15);
1578
        sum += buf[0];
1579
    }
1580
    monitor_printf(mon, "%05d\n", sum);
1581
}
1582

    
1583
typedef struct {
1584
    int keycode;
1585
    const char *name;
1586
} KeyDef;
1587

    
1588
static const KeyDef key_defs[] = {
1589
    { 0x2a, "shift" },
1590
    { 0x36, "shift_r" },
1591

    
1592
    { 0x38, "alt" },
1593
    { 0xb8, "alt_r" },
1594
    { 0x64, "altgr" },
1595
    { 0xe4, "altgr_r" },
1596
    { 0x1d, "ctrl" },
1597
    { 0x9d, "ctrl_r" },
1598

    
1599
    { 0xdd, "menu" },
1600

    
1601
    { 0x01, "esc" },
1602

    
1603
    { 0x02, "1" },
1604
    { 0x03, "2" },
1605
    { 0x04, "3" },
1606
    { 0x05, "4" },
1607
    { 0x06, "5" },
1608
    { 0x07, "6" },
1609
    { 0x08, "7" },
1610
    { 0x09, "8" },
1611
    { 0x0a, "9" },
1612
    { 0x0b, "0" },
1613
    { 0x0c, "minus" },
1614
    { 0x0d, "equal" },
1615
    { 0x0e, "backspace" },
1616

    
1617
    { 0x0f, "tab" },
1618
    { 0x10, "q" },
1619
    { 0x11, "w" },
1620
    { 0x12, "e" },
1621
    { 0x13, "r" },
1622
    { 0x14, "t" },
1623
    { 0x15, "y" },
1624
    { 0x16, "u" },
1625
    { 0x17, "i" },
1626
    { 0x18, "o" },
1627
    { 0x19, "p" },
1628

    
1629
    { 0x1c, "ret" },
1630

    
1631
    { 0x1e, "a" },
1632
    { 0x1f, "s" },
1633
    { 0x20, "d" },
1634
    { 0x21, "f" },
1635
    { 0x22, "g" },
1636
    { 0x23, "h" },
1637
    { 0x24, "j" },
1638
    { 0x25, "k" },
1639
    { 0x26, "l" },
1640

    
1641
    { 0x2c, "z" },
1642
    { 0x2d, "x" },
1643
    { 0x2e, "c" },
1644
    { 0x2f, "v" },
1645
    { 0x30, "b" },
1646
    { 0x31, "n" },
1647
    { 0x32, "m" },
1648
    { 0x33, "comma" },
1649
    { 0x34, "dot" },
1650
    { 0x35, "slash" },
1651

    
1652
    { 0x37, "asterisk" },
1653

    
1654
    { 0x39, "spc" },
1655
    { 0x3a, "caps_lock" },
1656
    { 0x3b, "f1" },
1657
    { 0x3c, "f2" },
1658
    { 0x3d, "f3" },
1659
    { 0x3e, "f4" },
1660
    { 0x3f, "f5" },
1661
    { 0x40, "f6" },
1662
    { 0x41, "f7" },
1663
    { 0x42, "f8" },
1664
    { 0x43, "f9" },
1665
    { 0x44, "f10" },
1666
    { 0x45, "num_lock" },
1667
    { 0x46, "scroll_lock" },
1668

    
1669
    { 0xb5, "kp_divide" },
1670
    { 0x37, "kp_multiply" },
1671
    { 0x4a, "kp_subtract" },
1672
    { 0x4e, "kp_add" },
1673
    { 0x9c, "kp_enter" },
1674
    { 0x53, "kp_decimal" },
1675
    { 0x54, "sysrq" },
1676

    
1677
    { 0x52, "kp_0" },
1678
    { 0x4f, "kp_1" },
1679
    { 0x50, "kp_2" },
1680
    { 0x51, "kp_3" },
1681
    { 0x4b, "kp_4" },
1682
    { 0x4c, "kp_5" },
1683
    { 0x4d, "kp_6" },
1684
    { 0x47, "kp_7" },
1685
    { 0x48, "kp_8" },
1686
    { 0x49, "kp_9" },
1687

    
1688
    { 0x56, "<" },
1689

    
1690
    { 0x57, "f11" },
1691
    { 0x58, "f12" },
1692

    
1693
    { 0xb7, "print" },
1694

    
1695
    { 0xc7, "home" },
1696
    { 0xc9, "pgup" },
1697
    { 0xd1, "pgdn" },
1698
    { 0xcf, "end" },
1699

    
1700
    { 0xcb, "left" },
1701
    { 0xc8, "up" },
1702
    { 0xd0, "down" },
1703
    { 0xcd, "right" },
1704

    
1705
    { 0xd2, "insert" },
1706
    { 0xd3, "delete" },
1707
#if defined(TARGET_SPARC) && !defined(TARGET_SPARC64)
1708
    { 0xf0, "stop" },
1709
    { 0xf1, "again" },
1710
    { 0xf2, "props" },
1711
    { 0xf3, "undo" },
1712
    { 0xf4, "front" },
1713
    { 0xf5, "copy" },
1714
    { 0xf6, "open" },
1715
    { 0xf7, "paste" },
1716
    { 0xf8, "find" },
1717
    { 0xf9, "cut" },
1718
    { 0xfa, "lf" },
1719
    { 0xfb, "help" },
1720
    { 0xfc, "meta_l" },
1721
    { 0xfd, "meta_r" },
1722
    { 0xfe, "compose" },
1723
#endif
1724
    { 0, NULL },
1725
};
1726

    
1727
static int get_keycode(const char *key)
1728
{
1729
    const KeyDef *p;
1730
    char *endp;
1731
    int ret;
1732

    
1733
    for(p = key_defs; p->name != NULL; p++) {
1734
        if (!strcmp(key, p->name))
1735
            return p->keycode;
1736
    }
1737
    if (strstart(key, "0x", NULL)) {
1738
        ret = strtoul(key, &endp, 0);
1739
        if (*endp == '\0' && ret >= 0x01 && ret <= 0xff)
1740
            return ret;
1741
    }
1742
    return -1;
1743
}
1744

    
1745
#define MAX_KEYCODES 16
1746
static uint8_t keycodes[MAX_KEYCODES];
1747
static int nb_pending_keycodes;
1748
static QEMUTimer *key_timer;
1749

    
1750
static void release_keys(void *opaque)
1751
{
1752
    int keycode;
1753

    
1754
    while (nb_pending_keycodes > 0) {
1755
        nb_pending_keycodes--;
1756
        keycode = keycodes[nb_pending_keycodes];
1757
        if (keycode & 0x80)
1758
            kbd_put_keycode(0xe0);
1759
        kbd_put_keycode(keycode | 0x80);
1760
    }
1761
}
1762

    
1763
static void do_sendkey(Monitor *mon, const QDict *qdict)
1764
{
1765
    char keyname_buf[16];
1766
    char *separator;
1767
    int keyname_len, keycode, i;
1768
    const char *string = qdict_get_str(qdict, "string");
1769
    int has_hold_time = qdict_haskey(qdict, "hold_time");
1770
    int hold_time = qdict_get_try_int(qdict, "hold_time", -1);
1771

    
1772
    if (nb_pending_keycodes > 0) {
1773
        qemu_del_timer(key_timer);
1774
        release_keys(NULL);
1775
    }
1776
    if (!has_hold_time)
1777
        hold_time = 100;
1778
    i = 0;
1779
    while (1) {
1780
        separator = strchr(string, '-');
1781
        keyname_len = separator ? separator - string : strlen(string);
1782
        if (keyname_len > 0) {
1783
            pstrcpy(keyname_buf, sizeof(keyname_buf), string);
1784
            if (keyname_len > sizeof(keyname_buf) - 1) {
1785
                monitor_printf(mon, "invalid key: '%s...'\n", keyname_buf);
1786
                return;
1787
            }
1788
            if (i == MAX_KEYCODES) {
1789
                monitor_printf(mon, "too many keys\n");
1790
                return;
1791
            }
1792
            keyname_buf[keyname_len] = 0;
1793
            keycode = get_keycode(keyname_buf);
1794
            if (keycode < 0) {
1795
                monitor_printf(mon, "unknown key: '%s'\n", keyname_buf);
1796
                return;
1797
            }
1798
            keycodes[i++] = keycode;
1799
        }
1800
        if (!separator)
1801
            break;
1802
        string = separator + 1;
1803
    }
1804
    nb_pending_keycodes = i;
1805
    /* key down events */
1806
    for (i = 0; i < nb_pending_keycodes; i++) {
1807
        keycode = keycodes[i];
1808
        if (keycode & 0x80)
1809
            kbd_put_keycode(0xe0);
1810
        kbd_put_keycode(keycode & 0x7f);
1811
    }
1812
    /* delayed key up events */
1813
    qemu_mod_timer(key_timer, qemu_get_clock(vm_clock) +
1814
                   muldiv64(get_ticks_per_sec(), hold_time, 1000));
1815
}
1816

    
1817
static int mouse_button_state;
1818

    
1819
static void do_mouse_move(Monitor *mon, const QDict *qdict)
1820
{
1821
    int dx, dy, dz;
1822
    const char *dx_str = qdict_get_str(qdict, "dx_str");
1823
    const char *dy_str = qdict_get_str(qdict, "dy_str");
1824
    const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1825
    dx = strtol(dx_str, NULL, 0);
1826
    dy = strtol(dy_str, NULL, 0);
1827
    dz = 0;
1828
    if (dz_str)
1829
        dz = strtol(dz_str, NULL, 0);
1830
    kbd_mouse_event(dx, dy, dz, mouse_button_state);
1831
}
1832

    
1833
static void do_mouse_button(Monitor *mon, const QDict *qdict)
1834
{
1835
    int button_state = qdict_get_int(qdict, "button_state");
1836
    mouse_button_state = button_state;
1837
    kbd_mouse_event(0, 0, 0, mouse_button_state);
1838
}
1839

    
1840
static void do_ioport_read(Monitor *mon, const QDict *qdict)
1841
{
1842
    int size = qdict_get_int(qdict, "size");
1843
    int addr = qdict_get_int(qdict, "addr");
1844
    int has_index = qdict_haskey(qdict, "index");
1845
    uint32_t val;
1846
    int suffix;
1847

    
1848
    if (has_index) {
1849
        int index = qdict_get_int(qdict, "index");
1850
        cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1851
        addr++;
1852
    }
1853
    addr &= 0xffff;
1854

    
1855
    switch(size) {
1856
    default:
1857
    case 1:
1858
        val = cpu_inb(addr);
1859
        suffix = 'b';
1860
        break;
1861
    case 2:
1862
        val = cpu_inw(addr);
1863
        suffix = 'w';
1864
        break;
1865
    case 4:
1866
        val = cpu_inl(addr);
1867
        suffix = 'l';
1868
        break;
1869
    }
1870
    monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1871
                   suffix, addr, size * 2, val);
1872
}
1873

    
1874
static void do_ioport_write(Monitor *mon, const QDict *qdict)
1875
{
1876
    int size = qdict_get_int(qdict, "size");
1877
    int addr = qdict_get_int(qdict, "addr");
1878
    int val = qdict_get_int(qdict, "val");
1879

    
1880
    addr &= IOPORTS_MASK;
1881

    
1882
    switch (size) {
1883
    default:
1884
    case 1:
1885
        cpu_outb(addr, val);
1886
        break;
1887
    case 2:
1888
        cpu_outw(addr, val);
1889
        break;
1890
    case 4:
1891
        cpu_outl(addr, val);
1892
        break;
1893
    }
1894
}
1895

    
1896
static void do_boot_set(Monitor *mon, const QDict *qdict)
1897
{
1898
    int res;
1899
    const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1900

    
1901
    res = qemu_boot_set(bootdevice);
1902
    if (res == 0) {
1903
        monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1904
    } else if (res > 0) {
1905
        monitor_printf(mon, "setting boot device list failed\n");
1906
    } else {
1907
        monitor_printf(mon, "no function defined to set boot device list for "
1908
                       "this architecture\n");
1909
    }
1910
}
1911

    
1912
/**
1913
 * do_system_reset(): Issue a machine reset
1914
 */
1915
static int do_system_reset(Monitor *mon, const QDict *qdict,
1916
                           QObject **ret_data)
1917
{
1918
    qemu_system_reset_request();
1919
    return 0;
1920
}
1921

    
1922
/**
1923
 * do_system_powerdown(): Issue a machine powerdown
1924
 */
1925
static int do_system_powerdown(Monitor *mon, const QDict *qdict,
1926
                               QObject **ret_data)
1927
{
1928
    qemu_system_powerdown_request();
1929
    return 0;
1930
}
1931

    
1932
#if defined(TARGET_I386)
1933
static void print_pte(Monitor *mon, uint32_t addr, uint32_t pte, uint32_t mask)
1934
{
1935
    monitor_printf(mon, "%08x: %08x %c%c%c%c%c%c%c%c\n",
1936
                   addr,
1937
                   pte & mask,
1938
                   pte & PG_GLOBAL_MASK ? 'G' : '-',
1939
                   pte & PG_PSE_MASK ? 'P' : '-',
1940
                   pte & PG_DIRTY_MASK ? 'D' : '-',
1941
                   pte & PG_ACCESSED_MASK ? 'A' : '-',
1942
                   pte & PG_PCD_MASK ? 'C' : '-',
1943
                   pte & PG_PWT_MASK ? 'T' : '-',
1944
                   pte & PG_USER_MASK ? 'U' : '-',
1945
                   pte & PG_RW_MASK ? 'W' : '-');
1946
}
1947

    
1948
static void tlb_info(Monitor *mon)
1949
{
1950
    CPUState *env;
1951
    int l1, l2;
1952
    uint32_t pgd, pde, pte;
1953

    
1954
    env = mon_get_cpu();
1955

    
1956
    if (!(env->cr[0] & CR0_PG_MASK)) {
1957
        monitor_printf(mon, "PG disabled\n");
1958
        return;
1959
    }
1960
    pgd = env->cr[3] & ~0xfff;
1961
    for(l1 = 0; l1 < 1024; l1++) {
1962
        cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1963
        pde = le32_to_cpu(pde);
1964
        if (pde & PG_PRESENT_MASK) {
1965
            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1966
                print_pte(mon, (l1 << 22), pde, ~((1 << 20) - 1));
1967
            } else {
1968
                for(l2 = 0; l2 < 1024; l2++) {
1969
                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1970
                                             (uint8_t *)&pte, 4);
1971
                    pte = le32_to_cpu(pte);
1972
                    if (pte & PG_PRESENT_MASK) {
1973
                        print_pte(mon, (l1 << 22) + (l2 << 12),
1974
                                  pte & ~PG_PSE_MASK,
1975
                                  ~0xfff);
1976
                    }
1977
                }
1978
            }
1979
        }
1980
    }
1981
}
1982

    
1983
static void mem_print(Monitor *mon, uint32_t *pstart, int *plast_prot,
1984
                      uint32_t end, int prot)
1985
{
1986
    int prot1;
1987
    prot1 = *plast_prot;
1988
    if (prot != prot1) {
1989
        if (*pstart != -1) {
1990
            monitor_printf(mon, "%08x-%08x %08x %c%c%c\n",
1991
                           *pstart, end, end - *pstart,
1992
                           prot1 & PG_USER_MASK ? 'u' : '-',
1993
                           'r',
1994
                           prot1 & PG_RW_MASK ? 'w' : '-');
1995
        }
1996
        if (prot != 0)
1997
            *pstart = end;
1998
        else
1999
            *pstart = -1;
2000
        *plast_prot = prot;
2001
    }
2002
}
2003

    
2004
static void mem_info(Monitor *mon)
2005
{
2006
    CPUState *env;
2007
    int l1, l2, prot, last_prot;
2008
    uint32_t pgd, pde, pte, start, end;
2009

    
2010
    env = mon_get_cpu();
2011

    
2012
    if (!(env->cr[0] & CR0_PG_MASK)) {
2013
        monitor_printf(mon, "PG disabled\n");
2014
        return;
2015
    }
2016
    pgd = env->cr[3] & ~0xfff;
2017
    last_prot = 0;
2018
    start = -1;
2019
    for(l1 = 0; l1 < 1024; l1++) {
2020
        cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
2021
        pde = le32_to_cpu(pde);
2022
        end = l1 << 22;
2023
        if (pde & PG_PRESENT_MASK) {
2024
            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
2025
                prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
2026
                mem_print(mon, &start, &last_prot, end, prot);
2027
            } else {
2028
                for(l2 = 0; l2 < 1024; l2++) {
2029
                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
2030
                                             (uint8_t *)&pte, 4);
2031
                    pte = le32_to_cpu(pte);
2032
                    end = (l1 << 22) + (l2 << 12);
2033
                    if (pte & PG_PRESENT_MASK) {
2034
                        prot = pte & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
2035
                    } else {
2036
                        prot = 0;
2037
                    }
2038
                    mem_print(mon, &start, &last_prot, end, prot);
2039
                }
2040
            }
2041
        } else {
2042
            prot = 0;
2043
            mem_print(mon, &start, &last_prot, end, prot);
2044
        }
2045
    }
2046
}
2047
#endif
2048

    
2049
#if defined(TARGET_SH4)
2050

    
2051
static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
2052
{
2053
    monitor_printf(mon, " tlb%i:\t"
2054
                   "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
2055
                   "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
2056
                   "dirty=%hhu writethrough=%hhu\n",
2057
                   idx,
2058
                   tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
2059
                   tlb->v, tlb->sh, tlb->c, tlb->pr,
2060
                   tlb->d, tlb->wt);
2061
}
2062

    
2063
static void tlb_info(Monitor *mon)
2064
{
2065
    CPUState *env = mon_get_cpu();
2066
    int i;
2067

    
2068
    monitor_printf (mon, "ITLB:\n");
2069
    for (i = 0 ; i < ITLB_SIZE ; i++)
2070
        print_tlb (mon, i, &env->itlb[i]);
2071
    monitor_printf (mon, "UTLB:\n");
2072
    for (i = 0 ; i < UTLB_SIZE ; i++)
2073
        print_tlb (mon, i, &env->utlb[i]);
2074
}
2075

    
2076
#endif
2077

    
2078
static void do_info_kvm_print(Monitor *mon, const QObject *data)
2079
{
2080
    QDict *qdict;
2081

    
2082
    qdict = qobject_to_qdict(data);
2083

    
2084
    monitor_printf(mon, "kvm support: ");
2085
    if (qdict_get_bool(qdict, "present")) {
2086
        monitor_printf(mon, "%s\n", qdict_get_bool(qdict, "enabled") ?
2087
                                    "enabled" : "disabled");
2088
    } else {
2089
        monitor_printf(mon, "not compiled\n");
2090
    }
2091
}
2092

    
2093
/**
2094
 * do_info_kvm(): Show KVM information
2095
 *
2096
 * Return a QDict with the following information:
2097
 *
2098
 * - "enabled": true if KVM support is enabled, false otherwise
2099
 * - "present": true if QEMU has KVM support, false otherwise
2100
 *
2101
 * Example:
2102
 *
2103
 * { "enabled": true, "present": true }
2104
 */
2105
static void do_info_kvm(Monitor *mon, QObject **ret_data)
2106
{
2107
#ifdef CONFIG_KVM
2108
    *ret_data = qobject_from_jsonf("{ 'enabled': %i, 'present': true }",
2109
                                   kvm_enabled());
2110
#else
2111
    *ret_data = qobject_from_jsonf("{ 'enabled': false, 'present': false }");
2112
#endif
2113
}
2114

    
2115
static void do_info_numa(Monitor *mon)
2116
{
2117
    int i;
2118
    CPUState *env;
2119

    
2120
    monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
2121
    for (i = 0; i < nb_numa_nodes; i++) {
2122
        monitor_printf(mon, "node %d cpus:", i);
2123
        for (env = first_cpu; env != NULL; env = env->next_cpu) {
2124
            if (env->numa_node == i) {
2125
                monitor_printf(mon, " %d", env->cpu_index);
2126
            }
2127
        }
2128
        monitor_printf(mon, "\n");
2129
        monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
2130
            node_mem[i] >> 20);
2131
    }
2132
}
2133

    
2134
#ifdef CONFIG_PROFILER
2135

    
2136
int64_t qemu_time;
2137
int64_t dev_time;
2138

    
2139
static void do_info_profile(Monitor *mon)
2140
{
2141
    int64_t total;
2142
    total = qemu_time;
2143
    if (total == 0)
2144
        total = 1;
2145
    monitor_printf(mon, "async time  %" PRId64 " (%0.3f)\n",
2146
                   dev_time, dev_time / (double)get_ticks_per_sec());
2147
    monitor_printf(mon, "qemu time   %" PRId64 " (%0.3f)\n",
2148
                   qemu_time, qemu_time / (double)get_ticks_per_sec());
2149
    qemu_time = 0;
2150
    dev_time = 0;
2151
}
2152
#else
2153
static void do_info_profile(Monitor *mon)
2154
{
2155
    monitor_printf(mon, "Internal profiler not compiled\n");
2156
}
2157
#endif
2158

    
2159
/* Capture support */
2160
static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2161

    
2162
static void do_info_capture(Monitor *mon)
2163
{
2164
    int i;
2165
    CaptureState *s;
2166

    
2167
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2168
        monitor_printf(mon, "[%d]: ", i);
2169
        s->ops.info (s->opaque);
2170
    }
2171
}
2172

    
2173
#ifdef HAS_AUDIO
2174
static void do_stop_capture(Monitor *mon, const QDict *qdict)
2175
{
2176
    int i;
2177
    int n = qdict_get_int(qdict, "n");
2178
    CaptureState *s;
2179

    
2180
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2181
        if (i == n) {
2182
            s->ops.destroy (s->opaque);
2183
            QLIST_REMOVE (s, entries);
2184
            qemu_free (s);
2185
            return;
2186
        }
2187
    }
2188
}
2189

    
2190
static void do_wav_capture(Monitor *mon, const QDict *qdict)
2191
{
2192
    const char *path = qdict_get_str(qdict, "path");
2193
    int has_freq = qdict_haskey(qdict, "freq");
2194
    int freq = qdict_get_try_int(qdict, "freq", -1);
2195
    int has_bits = qdict_haskey(qdict, "bits");
2196
    int bits = qdict_get_try_int(qdict, "bits", -1);
2197
    int has_channels = qdict_haskey(qdict, "nchannels");
2198
    int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2199
    CaptureState *s;
2200

    
2201
    s = qemu_mallocz (sizeof (*s));
2202

    
2203
    freq = has_freq ? freq : 44100;
2204
    bits = has_bits ? bits : 16;
2205
    nchannels = has_channels ? nchannels : 2;
2206

    
2207
    if (wav_start_capture (s, path, freq, bits, nchannels)) {
2208
        monitor_printf(mon, "Faied to add wave capture\n");
2209
        qemu_free (s);
2210
    }
2211
    QLIST_INSERT_HEAD (&capture_head, s, entries);
2212
}
2213
#endif
2214

    
2215
#if defined(TARGET_I386)
2216
static void do_inject_nmi(Monitor *mon, const QDict *qdict)
2217
{
2218
    CPUState *env;
2219
    int cpu_index = qdict_get_int(qdict, "cpu_index");
2220

    
2221
    for (env = first_cpu; env != NULL; env = env->next_cpu)
2222
        if (env->cpu_index == cpu_index) {
2223
            cpu_interrupt(env, CPU_INTERRUPT_NMI);
2224
            break;
2225
        }
2226
}
2227
#endif
2228

    
2229
static void do_info_status_print(Monitor *mon, const QObject *data)
2230
{
2231
    QDict *qdict;
2232

    
2233
    qdict = qobject_to_qdict(data);
2234

    
2235
    monitor_printf(mon, "VM status: ");
2236
    if (qdict_get_bool(qdict, "running")) {
2237
        monitor_printf(mon, "running");
2238
        if (qdict_get_bool(qdict, "singlestep")) {
2239
            monitor_printf(mon, " (single step mode)");
2240
        }
2241
    } else {
2242
        monitor_printf(mon, "paused");
2243
    }
2244

    
2245
    monitor_printf(mon, "\n");
2246
}
2247

    
2248
/**
2249
 * do_info_status(): VM status
2250
 *
2251
 * Return a QDict with the following information:
2252
 *
2253
 * - "running": true if the VM is running, or false if it is paused
2254
 * - "singlestep": true if the VM is in single step mode, false otherwise
2255
 *
2256
 * Example:
2257
 *
2258
 * { "running": true, "singlestep": false }
2259
 */
2260
static void do_info_status(Monitor *mon, QObject **ret_data)
2261
{
2262
    *ret_data = qobject_from_jsonf("{ 'running': %i, 'singlestep': %i }",
2263
                                    vm_running, singlestep);
2264
}
2265

    
2266
static void print_balloon_stat(const char *key, QObject *obj, void *opaque)
2267
{
2268
    Monitor *mon = opaque;
2269

    
2270
    if (strcmp(key, "actual"))
2271
        monitor_printf(mon, ",%s=%" PRId64, key,
2272
                       qint_get_int(qobject_to_qint(obj)));
2273
}
2274

    
2275
static void monitor_print_balloon(Monitor *mon, const QObject *data)
2276
{
2277
    QDict *qdict;
2278

    
2279
    qdict = qobject_to_qdict(data);
2280
    if (!qdict_haskey(qdict, "actual"))
2281
        return;
2282

    
2283
    monitor_printf(mon, "balloon: actual=%" PRId64,
2284
                   qdict_get_int(qdict, "actual") >> 20);
2285
    qdict_iter(qdict, print_balloon_stat, mon);
2286
    monitor_printf(mon, "\n");
2287
}
2288

    
2289
/**
2290
 * do_info_balloon(): Balloon information
2291
 *
2292
 * Make an asynchronous request for balloon info.  When the request completes
2293
 * a QDict will be returned according to the following specification:
2294
 *
2295
 * - "actual": current balloon value in bytes
2296
 * The following fields may or may not be present:
2297
 * - "mem_swapped_in": Amount of memory swapped in (bytes)
2298
 * - "mem_swapped_out": Amount of memory swapped out (bytes)
2299
 * - "major_page_faults": Number of major faults
2300
 * - "minor_page_faults": Number of minor faults
2301
 * - "free_mem": Total amount of free and unused memory (bytes)
2302
 * - "total_mem": Total amount of available memory (bytes)
2303
 *
2304
 * Example:
2305
 *
2306
 * { "actual": 1073741824, "mem_swapped_in": 0, "mem_swapped_out": 0,
2307
 *   "major_page_faults": 142, "minor_page_faults": 239245,
2308
 *   "free_mem": 1014185984, "total_mem": 1044668416 }
2309
 */
2310
static int do_info_balloon(Monitor *mon, MonitorCompletion cb, void *opaque)
2311
{
2312
    int ret;
2313

    
2314
    if (kvm_enabled() && !kvm_has_sync_mmu()) {
2315
        qerror_report(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
2316
        return -1;
2317
    }
2318

    
2319
    ret = qemu_balloon_status(cb, opaque);
2320
    if (!ret) {
2321
        qerror_report(QERR_DEVICE_NOT_ACTIVE, "balloon");
2322
        return -1;
2323
    }
2324

    
2325
    return 0;
2326
}
2327

    
2328
/**
2329
 * do_balloon(): Request VM to change its memory allocation
2330
 */
2331
static int do_balloon(Monitor *mon, const QDict *params,
2332
                       MonitorCompletion cb, void *opaque)
2333
{
2334
    int ret;
2335

    
2336
    if (kvm_enabled() && !kvm_has_sync_mmu()) {
2337
        qerror_report(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
2338
        return -1;
2339
    }
2340

    
2341
    ret = qemu_balloon(qdict_get_int(params, "value"), cb, opaque);
2342
    if (ret == 0) {
2343
        qerror_report(QERR_DEVICE_NOT_ACTIVE, "balloon");
2344
        return -1;
2345
    }
2346

    
2347
    cb(opaque, NULL);
2348
    return 0;
2349
}
2350

    
2351
static qemu_acl *find_acl(Monitor *mon, const char *name)
2352
{
2353
    qemu_acl *acl = qemu_acl_find(name);
2354

    
2355
    if (!acl) {
2356
        monitor_printf(mon, "acl: unknown list '%s'\n", name);
2357
    }
2358
    return acl;
2359
}
2360

    
2361
static void do_acl_show(Monitor *mon, const QDict *qdict)
2362
{
2363
    const char *aclname = qdict_get_str(qdict, "aclname");
2364
    qemu_acl *acl = find_acl(mon, aclname);
2365
    qemu_acl_entry *entry;
2366
    int i = 0;
2367

    
2368
    if (acl) {
2369
        monitor_printf(mon, "policy: %s\n",
2370
                       acl->defaultDeny ? "deny" : "allow");
2371
        QTAILQ_FOREACH(entry, &acl->entries, next) {
2372
            i++;
2373
            monitor_printf(mon, "%d: %s %s\n", i,
2374
                           entry->deny ? "deny" : "allow", entry->match);
2375
        }
2376
    }
2377
}
2378

    
2379
static void do_acl_reset(Monitor *mon, const QDict *qdict)
2380
{
2381
    const char *aclname = qdict_get_str(qdict, "aclname");
2382
    qemu_acl *acl = find_acl(mon, aclname);
2383

    
2384
    if (acl) {
2385
        qemu_acl_reset(acl);
2386
        monitor_printf(mon, "acl: removed all rules\n");
2387
    }
2388
}
2389

    
2390
static void do_acl_policy(Monitor *mon, const QDict *qdict)
2391
{
2392
    const char *aclname = qdict_get_str(qdict, "aclname");
2393
    const char *policy = qdict_get_str(qdict, "policy");
2394
    qemu_acl *acl = find_acl(mon, aclname);
2395

    
2396
    if (acl) {
2397
        if (strcmp(policy, "allow") == 0) {
2398
            acl->defaultDeny = 0;
2399
            monitor_printf(mon, "acl: policy set to 'allow'\n");
2400
        } else if (strcmp(policy, "deny") == 0) {
2401
            acl->defaultDeny = 1;
2402
            monitor_printf(mon, "acl: policy set to 'deny'\n");
2403
        } else {
2404
            monitor_printf(mon, "acl: unknown policy '%s', "
2405
                           "expected 'deny' or 'allow'\n", policy);
2406
        }
2407
    }
2408
}
2409

    
2410
static void do_acl_add(Monitor *mon, const QDict *qdict)
2411
{
2412
    const char *aclname = qdict_get_str(qdict, "aclname");
2413
    const char *match = qdict_get_str(qdict, "match");
2414
    const char *policy = qdict_get_str(qdict, "policy");
2415
    int has_index = qdict_haskey(qdict, "index");
2416
    int index = qdict_get_try_int(qdict, "index", -1);
2417
    qemu_acl *acl = find_acl(mon, aclname);
2418
    int deny, ret;
2419

    
2420
    if (acl) {
2421
        if (strcmp(policy, "allow") == 0) {
2422
            deny = 0;
2423
        } else if (strcmp(policy, "deny") == 0) {
2424
            deny = 1;
2425
        } else {
2426
            monitor_printf(mon, "acl: unknown policy '%s', "
2427
                           "expected 'deny' or 'allow'\n", policy);
2428
            return;
2429
        }
2430
        if (has_index)
2431
            ret = qemu_acl_insert(acl, deny, match, index);
2432
        else
2433
            ret = qemu_acl_append(acl, deny, match);
2434
        if (ret < 0)
2435
            monitor_printf(mon, "acl: unable to add acl entry\n");
2436
        else
2437
            monitor_printf(mon, "acl: added rule at position %d\n", ret);
2438
    }
2439
}
2440

    
2441
static void do_acl_remove(Monitor *mon, const QDict *qdict)
2442
{
2443
    const char *aclname = qdict_get_str(qdict, "aclname");
2444
    const char *match = qdict_get_str(qdict, "match");
2445
    qemu_acl *acl = find_acl(mon, aclname);
2446
    int ret;
2447

    
2448
    if (acl) {
2449
        ret = qemu_acl_remove(acl, match);
2450
        if (ret < 0)
2451
            monitor_printf(mon, "acl: no matching acl entry\n");
2452
        else
2453
            monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2454
    }
2455
}
2456

    
2457
#if defined(TARGET_I386)
2458
static void do_inject_mce(Monitor *mon, const QDict *qdict)
2459
{
2460
    CPUState *cenv;
2461
    int cpu_index = qdict_get_int(qdict, "cpu_index");
2462
    int bank = qdict_get_int(qdict, "bank");
2463
    uint64_t status = qdict_get_int(qdict, "status");
2464
    uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2465
    uint64_t addr = qdict_get_int(qdict, "addr");
2466
    uint64_t misc = qdict_get_int(qdict, "misc");
2467

    
2468
    for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu)
2469
        if (cenv->cpu_index == cpu_index && cenv->mcg_cap) {
2470
            cpu_inject_x86_mce(cenv, bank, status, mcg_status, addr, misc);
2471
            break;
2472
        }
2473
}
2474
#endif
2475

    
2476
static int do_getfd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2477
{
2478
    const char *fdname = qdict_get_str(qdict, "fdname");
2479
    mon_fd_t *monfd;
2480
    int fd;
2481

    
2482
    fd = qemu_chr_get_msgfd(mon->chr);
2483
    if (fd == -1) {
2484
        qerror_report(QERR_FD_NOT_SUPPLIED);
2485
        return -1;
2486
    }
2487

    
2488
    if (qemu_isdigit(fdname[0])) {
2489
        qerror_report(QERR_INVALID_PARAMETER, "fdname");
2490
        return -1;
2491
    }
2492

    
2493
    fd = dup(fd);
2494
    if (fd == -1) {
2495
        if (errno == EMFILE)
2496
            qerror_report(QERR_TOO_MANY_FILES);
2497
        else
2498
            qerror_report(QERR_UNDEFINED_ERROR);
2499
        return -1;
2500
    }
2501

    
2502
    QLIST_FOREACH(monfd, &mon->fds, next) {
2503
        if (strcmp(monfd->name, fdname) != 0) {
2504
            continue;
2505
        }
2506

    
2507
        close(monfd->fd);
2508
        monfd->fd = fd;
2509
        return 0;
2510
    }
2511

    
2512
    monfd = qemu_mallocz(sizeof(mon_fd_t));
2513
    monfd->name = qemu_strdup(fdname);
2514
    monfd->fd = fd;
2515

    
2516
    QLIST_INSERT_HEAD(&mon->fds, monfd, next);
2517
    return 0;
2518
}
2519

    
2520
static int do_closefd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2521
{
2522
    const char *fdname = qdict_get_str(qdict, "fdname");
2523
    mon_fd_t *monfd;
2524

    
2525
    QLIST_FOREACH(monfd, &mon->fds, next) {
2526
        if (strcmp(monfd->name, fdname) != 0) {
2527
            continue;
2528
        }
2529

    
2530
        QLIST_REMOVE(monfd, next);
2531
        close(monfd->fd);
2532
        qemu_free(monfd->name);
2533
        qemu_free(monfd);
2534
        return 0;
2535
    }
2536

    
2537
    qerror_report(QERR_FD_NOT_FOUND, fdname);
2538
    return -1;
2539
}
2540

    
2541
static void do_loadvm(Monitor *mon, const QDict *qdict)
2542
{
2543
    int saved_vm_running  = vm_running;
2544
    const char *name = qdict_get_str(qdict, "name");
2545

    
2546
    vm_stop(0);
2547

    
2548
    if (load_vmstate(name) >= 0 && saved_vm_running)
2549
        vm_start();
2550
}
2551

    
2552
int monitor_get_fd(Monitor *mon, const char *fdname)
2553
{
2554
    mon_fd_t *monfd;
2555

    
2556
    QLIST_FOREACH(monfd, &mon->fds, next) {
2557
        int fd;
2558

    
2559
        if (strcmp(monfd->name, fdname) != 0) {
2560
            continue;
2561
        }
2562

    
2563
        fd = monfd->fd;
2564

    
2565
        /* caller takes ownership of fd */
2566
        QLIST_REMOVE(monfd, next);
2567
        qemu_free(monfd->name);
2568
        qemu_free(monfd);
2569

    
2570
        return fd;
2571
    }
2572

    
2573
    return -1;
2574
}
2575

    
2576
static const mon_cmd_t mon_cmds[] = {
2577
#include "qemu-monitor.h"
2578
    { NULL, NULL, },
2579
};
2580

    
2581
/* Please update qemu-monitor.hx when adding or changing commands */
2582
static const mon_cmd_t info_cmds[] = {
2583
    {
2584
        .name       = "version",
2585
        .args_type  = "",
2586
        .params     = "",
2587
        .help       = "show the version of QEMU",
2588
        .user_print = do_info_version_print,
2589
        .mhandler.info_new = do_info_version,
2590
    },
2591
    {
2592
        .name       = "commands",
2593
        .args_type  = "",
2594
        .params     = "",
2595
        .help       = "list QMP available commands",
2596
        .user_print = monitor_user_noop,
2597
        .mhandler.info_new = do_info_commands,
2598
    },
2599
    {
2600
        .name       = "network",
2601
        .args_type  = "",
2602
        .params     = "",
2603
        .help       = "show the network state",
2604
        .mhandler.info = do_info_network,
2605
    },
2606
    {
2607
        .name       = "chardev",
2608
        .args_type  = "",
2609
        .params     = "",
2610
        .help       = "show the character devices",
2611
        .user_print = qemu_chr_info_print,
2612
        .mhandler.info_new = qemu_chr_info,
2613
    },
2614
    {
2615
        .name       = "block",
2616
        .args_type  = "",
2617
        .params     = "",
2618
        .help       = "show the block devices",
2619
        .user_print = bdrv_info_print,
2620
        .mhandler.info_new = bdrv_info,
2621
    },
2622
    {
2623
        .name       = "blockstats",
2624
        .args_type  = "",
2625
        .params     = "",
2626
        .help       = "show block device statistics",
2627
        .user_print = bdrv_stats_print,
2628
        .mhandler.info_new = bdrv_info_stats,
2629
    },
2630
    {
2631
        .name       = "registers",
2632
        .args_type  = "",
2633
        .params     = "",
2634
        .help       = "show the cpu registers",
2635
        .mhandler.info = do_info_registers,
2636
    },
2637
    {
2638
        .name       = "cpus",
2639
        .args_type  = "",
2640
        .params     = "",
2641
        .help       = "show infos for each CPU",
2642
        .user_print = monitor_print_cpus,
2643
        .mhandler.info_new = do_info_cpus,
2644
    },
2645
    {
2646
        .name       = "history",
2647
        .args_type  = "",
2648
        .params     = "",
2649
        .help       = "show the command line history",
2650
        .mhandler.info = do_info_history,
2651
    },
2652
    {
2653
        .name       = "irq",
2654
        .args_type  = "",
2655
        .params     = "",
2656
        .help       = "show the interrupts statistics (if available)",
2657
        .mhandler.info = irq_info,
2658
    },
2659
    {
2660
        .name       = "pic",
2661
        .args_type  = "",
2662
        .params     = "",
2663
        .help       = "show i8259 (PIC) state",
2664
        .mhandler.info = pic_info,
2665
    },
2666
    {
2667
        .name       = "pci",
2668
        .args_type  = "",
2669
        .params     = "",
2670
        .help       = "show PCI info",
2671
        .user_print = do_pci_info_print,
2672
        .mhandler.info_new = do_pci_info,
2673
    },
2674
#if defined(TARGET_I386) || defined(TARGET_SH4)
2675
    {
2676
        .name       = "tlb",
2677
        .args_type  = "",
2678
        .params     = "",
2679
        .help       = "show virtual to physical memory mappings",
2680
        .mhandler.info = tlb_info,
2681
    },
2682
#endif
2683
#if defined(TARGET_I386)
2684
    {
2685
        .name       = "mem",
2686
        .args_type  = "",
2687
        .params     = "",
2688
        .help       = "show the active virtual memory mappings",
2689
        .mhandler.info = mem_info,
2690
    },
2691
    {
2692
        .name       = "hpet",
2693
        .args_type  = "",
2694
        .params     = "",
2695
        .help       = "show state of HPET",
2696
        .user_print = do_info_hpet_print,
2697
        .mhandler.info_new = do_info_hpet,
2698
    },
2699
#endif
2700
    {
2701
        .name       = "jit",
2702
        .args_type  = "",
2703
        .params     = "",
2704
        .help       = "show dynamic compiler info",
2705
        .mhandler.info = do_info_jit,
2706
    },
2707
    {
2708
        .name       = "kvm",
2709
        .args_type  = "",
2710
        .params     = "",
2711
        .help       = "show KVM information",
2712
        .user_print = do_info_kvm_print,
2713
        .mhandler.info_new = do_info_kvm,
2714
    },
2715
    {
2716
        .name       = "numa",
2717
        .args_type  = "",
2718
        .params     = "",
2719
        .help       = "show NUMA information",
2720
        .mhandler.info = do_info_numa,
2721
    },
2722
    {
2723
        .name       = "usb",
2724
        .args_type  = "",
2725
        .params     = "",
2726
        .help       = "show guest USB devices",
2727
        .mhandler.info = usb_info,
2728
    },
2729
    {
2730
        .name       = "usbhost",
2731
        .args_type  = "",
2732
        .params     = "",
2733
        .help       = "show host USB devices",
2734
        .mhandler.info = usb_host_info,
2735
    },
2736
    {
2737
        .name       = "profile",
2738
        .args_type  = "",
2739
        .params     = "",
2740
        .help       = "show profiling information",
2741
        .mhandler.info = do_info_profile,
2742
    },
2743
    {
2744
        .name       = "capture",
2745
        .args_type  = "",
2746
        .params     = "",
2747
        .help       = "show capture information",
2748
        .mhandler.info = do_info_capture,
2749
    },
2750
    {
2751
        .name       = "snapshots",
2752
        .args_type  = "",
2753
        .params     = "",
2754
        .help       = "show the currently saved VM snapshots",
2755
        .mhandler.info = do_info_snapshots,
2756
    },
2757
    {
2758
        .name       = "status",
2759
        .args_type  = "",
2760
        .params     = "",
2761
        .help       = "show the current VM status (running|paused)",
2762
        .user_print = do_info_status_print,
2763
        .mhandler.info_new = do_info_status,
2764
    },
2765
    {
2766
        .name       = "pcmcia",
2767
        .args_type  = "",
2768
        .params     = "",
2769
        .help       = "show guest PCMCIA status",
2770
        .mhandler.info = pcmcia_info,
2771
    },
2772
    {
2773
        .name       = "mice",
2774
        .args_type  = "",
2775
        .params     = "",
2776
        .help       = "show which guest mouse is receiving events",
2777
        .user_print = do_info_mice_print,
2778
        .mhandler.info_new = do_info_mice,
2779
    },
2780
    {
2781
        .name       = "vnc",
2782
        .args_type  = "",
2783
        .params     = "",
2784
        .help       = "show the vnc server status",
2785
        .user_print = do_info_vnc_print,
2786
        .mhandler.info_new = do_info_vnc,
2787
    },
2788
    {
2789
        .name       = "name",
2790
        .args_type  = "",
2791
        .params     = "",
2792
        .help       = "show the current VM name",
2793
        .user_print = do_info_name_print,
2794
        .mhandler.info_new = do_info_name,
2795
    },
2796
    {
2797
        .name       = "uuid",
2798
        .args_type  = "",
2799
        .params     = "",
2800
        .help       = "show the current VM UUID",
2801
        .user_print = do_info_uuid_print,
2802
        .mhandler.info_new = do_info_uuid,
2803
    },
2804
#if defined(TARGET_PPC)
2805
    {
2806
        .name       = "cpustats",
2807
        .args_type  = "",
2808
        .params     = "",
2809
        .help       = "show CPU statistics",
2810
        .mhandler.info = do_info_cpu_stats,
2811
    },
2812
#endif
2813
#if defined(CONFIG_SLIRP)
2814
    {
2815
        .name       = "usernet",
2816
        .args_type  = "",
2817
        .params     = "",
2818
        .help       = "show user network stack connection states",
2819
        .mhandler.info = do_info_usernet,
2820
    },
2821
#endif
2822
    {
2823
        .name       = "migrate",
2824
        .args_type  = "",
2825
        .params     = "",
2826
        .help       = "show migration status",
2827
        .user_print = do_info_migrate_print,
2828
        .mhandler.info_new = do_info_migrate,
2829
    },
2830
    {
2831
        .name       = "balloon",
2832
        .args_type  = "",
2833
        .params     = "",
2834
        .help       = "show balloon information",
2835
        .user_print = monitor_print_balloon,
2836
        .mhandler.info_async = do_info_balloon,
2837
        .async      = 1,
2838
    },
2839
    {
2840
        .name       = "qtree",
2841
        .args_type  = "",
2842
        .params     = "",
2843
        .help       = "show device tree",
2844
        .mhandler.info = do_info_qtree,
2845
    },
2846
    {
2847
        .name       = "qdm",
2848
        .args_type  = "",
2849
        .params     = "",
2850
        .help       = "show qdev device model list",
2851
        .mhandler.info = do_info_qdm,
2852
    },
2853
    {
2854
        .name       = "roms",
2855
        .args_type  = "",
2856
        .params     = "",
2857
        .help       = "show roms",
2858
        .mhandler.info = do_info_roms,
2859
    },
2860
    {
2861
        .name       = NULL,
2862
    },
2863
};
2864

    
2865
/*******************************************************************/
2866

    
2867
static const char *pch;
2868
static jmp_buf expr_env;
2869

    
2870
#define MD_TLONG 0
2871
#define MD_I32   1
2872

    
2873
typedef struct MonitorDef {
2874
    const char *name;
2875
    int offset;
2876
    target_long (*get_value)(const struct MonitorDef *md, int val);
2877
    int type;
2878
} MonitorDef;
2879

    
2880
#if defined(TARGET_I386)
2881
static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2882
{
2883
    CPUState *env = mon_get_cpu();
2884
    return env->eip + env->segs[R_CS].base;
2885
}
2886
#endif
2887

    
2888
#if defined(TARGET_PPC)
2889
static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2890
{
2891
    CPUState *env = mon_get_cpu();
2892
    unsigned int u;
2893
    int i;
2894

    
2895
    u = 0;
2896
    for (i = 0; i < 8; i++)
2897
        u |= env->crf[i] << (32 - (4 * i));
2898

    
2899
    return u;
2900
}
2901

    
2902
static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2903
{
2904
    CPUState *env = mon_get_cpu();
2905
    return env->msr;
2906
}
2907

    
2908
static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2909
{
2910
    CPUState *env = mon_get_cpu();
2911
    return env->xer;
2912
}
2913

    
2914
static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2915
{
2916
    CPUState *env = mon_get_cpu();
2917
    return cpu_ppc_load_decr(env);
2918
}
2919

    
2920
static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2921
{
2922
    CPUState *env = mon_get_cpu();
2923
    return cpu_ppc_load_tbu(env);
2924
}
2925

    
2926
static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2927
{
2928
    CPUState *env = mon_get_cpu();
2929
    return cpu_ppc_load_tbl(env);
2930
}
2931
#endif
2932

    
2933
#if defined(TARGET_SPARC)
2934
#ifndef TARGET_SPARC64
2935
static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2936
{
2937
    CPUState *env = mon_get_cpu();
2938
    return GET_PSR(env);
2939
}
2940
#endif
2941

    
2942
static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2943
{
2944
    CPUState *env = mon_get_cpu();
2945
    return env->regwptr[val];
2946
}
2947
#endif
2948

    
2949
static const MonitorDef monitor_defs[] = {
2950
#ifdef TARGET_I386
2951

    
2952
#define SEG(name, seg) \
2953
    { name, offsetof(CPUState, segs[seg].selector), NULL, MD_I32 },\
2954
    { name ".base", offsetof(CPUState, segs[seg].base) },\
2955
    { name ".limit", offsetof(CPUState, segs[seg].limit), NULL, MD_I32 },
2956

    
2957
    { "eax", offsetof(CPUState, regs[0]) },
2958
    { "ecx", offsetof(CPUState, regs[1]) },
2959
    { "edx", offsetof(CPUState, regs[2]) },
2960
    { "ebx", offsetof(CPUState, regs[3]) },
2961
    { "esp|sp", offsetof(CPUState, regs[4]) },
2962
    { "ebp|fp", offsetof(CPUState, regs[5]) },
2963
    { "esi", offsetof(CPUState, regs[6]) },
2964
    { "edi", offsetof(CPUState, regs[7]) },
2965
#ifdef TARGET_X86_64
2966
    { "r8", offsetof(CPUState, regs[8]) },
2967
    { "r9", offsetof(CPUState, regs[9]) },
2968
    { "r10", offsetof(CPUState, regs[10]) },
2969
    { "r11", offsetof(CPUState, regs[11]) },
2970
    { "r12", offsetof(CPUState, regs[12]) },
2971
    { "r13", offsetof(CPUState, regs[13]) },
2972
    { "r14", offsetof(CPUState, regs[14]) },
2973
    { "r15", offsetof(CPUState, regs[15]) },
2974
#endif
2975
    { "eflags", offsetof(CPUState, eflags) },
2976
    { "eip", offsetof(CPUState, eip) },
2977
    SEG("cs", R_CS)
2978
    SEG("ds", R_DS)
2979
    SEG("es", R_ES)
2980
    SEG("ss", R_SS)
2981
    SEG("fs", R_FS)
2982
    SEG("gs", R_GS)
2983
    { "pc", 0, monitor_get_pc, },
2984
#elif defined(TARGET_PPC)
2985
    /* General purpose registers */
2986
    { "r0", offsetof(CPUState, gpr[0]) },
2987
    { "r1", offsetof(CPUState, gpr[1]) },
2988
    { "r2", offsetof(CPUState, gpr[2]) },
2989
    { "r3", offsetof(CPUState, gpr[3]) },
2990
    { "r4", offsetof(CPUState, gpr[4]) },
2991
    { "r5", offsetof(CPUState, gpr[5]) },
2992
    { "r6", offsetof(CPUState, gpr[6]) },
2993
    { "r7", offsetof(CPUState, gpr[7]) },
2994
    { "r8", offsetof(CPUState, gpr[8]) },
2995
    { "r9", offsetof(CPUState, gpr[9]) },
2996
    { "r10", offsetof(CPUState, gpr[10]) },
2997
    { "r11", offsetof(CPUState, gpr[11]) },
2998
    { "r12", offsetof(CPUState, gpr[12]) },
2999
    { "r13", offsetof(CPUState, gpr[13]) },
3000
    { "r14", offsetof(CPUState, gpr[14]) },
3001
    { "r15", offsetof(CPUState, gpr[15]) },
3002
    { "r16", offsetof(CPUState, gpr[16]) },
3003
    { "r17", offsetof(CPUState, gpr[17]) },
3004
    { "r18", offsetof(CPUState, gpr[18]) },
3005
    { "r19", offsetof(CPUState, gpr[19]) },
3006
    { "r20", offsetof(CPUState, gpr[20]) },
3007
    { "r21", offsetof(CPUState, gpr[21]) },
3008
    { "r22", offsetof(CPUState, gpr[22]) },
3009
    { "r23", offsetof(CPUState, gpr[23]) },
3010
    { "r24", offsetof(CPUState, gpr[24]) },
3011
    { "r25", offsetof(CPUState, gpr[25]) },
3012
    { "r26", offsetof(CPUState, gpr[26]) },
3013
    { "r27", offsetof(CPUState, gpr[27]) },
3014
    { "r28", offsetof(CPUState, gpr[28]) },
3015
    { "r29", offsetof(CPUState, gpr[29]) },
3016
    { "r30", offsetof(CPUState, gpr[30]) },
3017
    { "r31", offsetof(CPUState, gpr[31]) },
3018
    /* Floating point registers */
3019
    { "f0", offsetof(CPUState, fpr[0]) },
3020
    { "f1", offsetof(CPUState, fpr[1]) },
3021
    { "f2", offsetof(CPUState, fpr[2]) },
3022
    { "f3", offsetof(CPUState, fpr[3]) },
3023
    { "f4", offsetof(CPUState, fpr[4]) },
3024
    { "f5", offsetof(CPUState, fpr[5]) },
3025
    { "f6", offsetof(CPUState, fpr[6]) },
3026
    { "f7", offsetof(CPUState, fpr[7]) },
3027
    { "f8", offsetof(CPUState, fpr[8]) },
3028
    { "f9", offsetof(CPUState, fpr[9]) },
3029
    { "f10", offsetof(CPUState, fpr[10]) },
3030
    { "f11", offsetof(CPUState, fpr[11]) },
3031
    { "f12", offsetof(CPUState, fpr[12]) },
3032
    { "f13", offsetof(CPUState, fpr[13]) },
3033
    { "f14", offsetof(CPUState, fpr[14]) },
3034
    { "f15", offsetof(CPUState, fpr[15]) },
3035
    { "f16", offsetof(CPUState, fpr[16]) },
3036
    { "f17", offsetof(CPUState, fpr[17]) },
3037
    { "f18", offsetof(CPUState, fpr[18]) },
3038
    { "f19", offsetof(CPUState, fpr[19]) },
3039
    { "f20", offsetof(CPUState, fpr[20]) },
3040
    { "f21", offsetof(CPUState, fpr[21]) },
3041
    { "f22", offsetof(CPUState, fpr[22]) },
3042
    { "f23", offsetof(CPUState, fpr[23]) },
3043
    { "f24", offsetof(CPUState, fpr[24]) },
3044
    { "f25", offsetof(CPUState, fpr[25]) },
3045
    { "f26", offsetof(CPUState, fpr[26]) },
3046
    { "f27", offsetof(CPUState, fpr[27]) },
3047
    { "f28", offsetof(CPUState, fpr[28]) },
3048
    { "f29", offsetof(CPUState, fpr[29]) },
3049
    { "f30", offsetof(CPUState, fpr[30]) },
3050
    { "f31", offsetof(CPUState, fpr[31]) },
3051
    { "fpscr", offsetof(CPUState, fpscr) },
3052
    /* Next instruction pointer */
3053
    { "nip|pc", offsetof(CPUState, nip) },
3054
    { "lr", offsetof(CPUState, lr) },
3055
    { "ctr", offsetof(CPUState, ctr) },
3056
    { "decr", 0, &monitor_get_decr, },
3057
    { "ccr", 0, &monitor_get_ccr, },
3058
    /* Machine state register */
3059
    { "msr", 0, &monitor_get_msr, },
3060
    { "xer", 0, &monitor_get_xer, },
3061
    { "tbu", 0, &monitor_get_tbu, },
3062
    { "tbl", 0, &monitor_get_tbl, },
3063
#if defined(TARGET_PPC64)
3064
    /* Address space register */
3065
    { "asr", offsetof(CPUState, asr) },
3066
#endif
3067
    /* Segment registers */
3068
    { "sdr1", offsetof(CPUState, sdr1) },
3069
    { "sr0", offsetof(CPUState, sr[0]) },
3070
    { "sr1", offsetof(CPUState, sr[1]) },
3071
    { "sr2", offsetof(CPUState, sr[2]) },
3072
    { "sr3", offsetof(CPUState, sr[3]) },
3073
    { "sr4", offsetof(CPUState, sr[4]) },
3074
    { "sr5", offsetof(CPUState, sr[5]) },
3075
    { "sr6", offsetof(CPUState, sr[6]) },
3076
    { "sr7", offsetof(CPUState, sr[7]) },
3077
    { "sr8", offsetof(CPUState, sr[8]) },
3078
    { "sr9", offsetof(CPUState, sr[9]) },
3079
    { "sr10", offsetof(CPUState, sr[10]) },
3080
    { "sr11", offsetof(CPUState, sr[11]) },
3081
    { "sr12", offsetof(CPUState, sr[12]) },
3082
    { "sr13", offsetof(CPUState, sr[13]) },
3083
    { "sr14", offsetof(CPUState, sr[14]) },
3084
    { "sr15", offsetof(CPUState, sr[15]) },
3085
    /* Too lazy to put BATs and SPRs ... */
3086
#elif defined(TARGET_SPARC)
3087
    { "g0", offsetof(CPUState, gregs[0]) },
3088
    { "g1", offsetof(CPUState, gregs[1]) },
3089
    { "g2", offsetof(CPUState, gregs[2]) },
3090
    { "g3", offsetof(CPUState, gregs[3]) },
3091
    { "g4", offsetof(CPUState, gregs[4]) },
3092
    { "g5", offsetof(CPUState, gregs[5]) },
3093
    { "g6", offsetof(CPUState, gregs[6]) },
3094
    { "g7", offsetof(CPUState, gregs[7]) },
3095
    { "o0", 0, monitor_get_reg },
3096
    { "o1", 1, monitor_get_reg },
3097
    { "o2", 2, monitor_get_reg },
3098
    { "o3", 3, monitor_get_reg },
3099
    { "o4", 4, monitor_get_reg },
3100
    { "o5", 5, monitor_get_reg },
3101
    { "o6", 6, monitor_get_reg },
3102
    { "o7", 7, monitor_get_reg },
3103
    { "l0", 8, monitor_get_reg },
3104
    { "l1", 9, monitor_get_reg },
3105
    { "l2", 10, monitor_get_reg },
3106
    { "l3", 11, monitor_get_reg },
3107
    { "l4", 12, monitor_get_reg },
3108
    { "l5", 13, monitor_get_reg },
3109
    { "l6", 14, monitor_get_reg },
3110
    { "l7", 15, monitor_get_reg },
3111
    { "i0", 16, monitor_get_reg },
3112
    { "i1", 17, monitor_get_reg },
3113
    { "i2", 18, monitor_get_reg },
3114
    { "i3", 19, monitor_get_reg },
3115
    { "i4", 20, monitor_get_reg },
3116
    { "i5", 21, monitor_get_reg },
3117
    { "i6", 22, monitor_get_reg },
3118
    { "i7", 23, monitor_get_reg },
3119
    { "pc", offsetof(CPUState, pc) },
3120
    { "npc", offsetof(CPUState, npc) },
3121
    { "y", offsetof(CPUState, y) },
3122
#ifndef TARGET_SPARC64
3123
    { "psr", 0, &monitor_get_psr, },
3124
    { "wim", offsetof(CPUState, wim) },
3125
#endif
3126
    { "tbr", offsetof(CPUState, tbr) },
3127
    { "fsr", offsetof(CPUState, fsr) },
3128
    { "f0", offsetof(CPUState, fpr[0]) },
3129
    { "f1", offsetof(CPUState, fpr[1]) },
3130
    { "f2", offsetof(CPUState, fpr[2]) },
3131
    { "f3", offsetof(CPUState, fpr[3]) },
3132
    { "f4", offsetof(CPUState, fpr[4]) },
3133
    { "f5", offsetof(CPUState, fpr[5]) },
3134
    { "f6", offsetof(CPUState, fpr[6]) },
3135
    { "f7", offsetof(CPUState, fpr[7]) },
3136
    { "f8", offsetof(CPUState, fpr[8]) },
3137
    { "f9", offsetof(CPUState, fpr[9]) },
3138
    { "f10", offsetof(CPUState, fpr[10]) },
3139
    { "f11", offsetof(CPUState, fpr[11]) },
3140
    { "f12", offsetof(CPUState, fpr[12]) },
3141
    { "f13", offsetof(CPUState, fpr[13]) },
3142
    { "f14", offsetof(CPUState, fpr[14]) },
3143
    { "f15", offsetof(CPUState, fpr[15]) },
3144
    { "f16", offsetof(CPUState, fpr[16]) },
3145
    { "f17", offsetof(CPUState, fpr[17]) },
3146
    { "f18", offsetof(CPUState, fpr[18]) },
3147
    { "f19", offsetof(CPUState, fpr[19]) },
3148
    { "f20", offsetof(CPUState, fpr[20]) },
3149
    { "f21", offsetof(CPUState, fpr[21]) },
3150
    { "f22", offsetof(CPUState, fpr[22]) },
3151
    { "f23", offsetof(CPUState, fpr[23]) },
3152
    { "f24", offsetof(CPUState, fpr[24]) },
3153
    { "f25", offsetof(CPUState, fpr[25]) },
3154
    { "f26", offsetof(CPUState, fpr[26]) },
3155
    { "f27", offsetof(CPUState, fpr[27]) },
3156
    { "f28", offsetof(CPUState, fpr[28]) },
3157
    { "f29", offsetof(CPUState, fpr[29]) },
3158
    { "f30", offsetof(CPUState, fpr[30]) },
3159
    { "f31", offsetof(CPUState, fpr[31]) },
3160
#ifdef TARGET_SPARC64
3161
    { "f32", offsetof(CPUState, fpr[32]) },
3162
    { "f34", offsetof(CPUState, fpr[34]) },
3163
    { "f36", offsetof(CPUState, fpr[36]) },
3164
    { "f38", offsetof(CPUState, fpr[38]) },
3165
    { "f40", offsetof(CPUState, fpr[40]) },
3166
    { "f42", offsetof(CPUState, fpr[42]) },
3167
    { "f44", offsetof(CPUState, fpr[44]) },
3168
    { "f46", offsetof(CPUState, fpr[46]) },
3169
    { "f48", offsetof(CPUState, fpr[48]) },
3170
    { "f50", offsetof(CPUState, fpr[50]) },
3171
    { "f52", offsetof(CPUState, fpr[52]) },
3172
    { "f54", offsetof(CPUState, fpr[54]) },
3173
    { "f56", offsetof(CPUState, fpr[56]) },
3174
    { "f58", offsetof(CPUState, fpr[58]) },
3175
    { "f60", offsetof(CPUState, fpr[60]) },
3176
    { "f62", offsetof(CPUState, fpr[62]) },
3177
    { "asi", offsetof(CPUState, asi) },
3178
    { "pstate", offsetof(CPUState, pstate) },
3179
    { "cansave", offsetof(CPUState, cansave) },
3180
    { "canrestore", offsetof(CPUState, canrestore) },
3181
    { "otherwin", offsetof(CPUState, otherwin) },
3182
    { "wstate", offsetof(CPUState, wstate) },
3183
    { "cleanwin", offsetof(CPUState, cleanwin) },
3184
    { "fprs", offsetof(CPUState, fprs) },
3185
#endif
3186
#endif
3187
    { NULL },
3188
};
3189

    
3190
static void expr_error(Monitor *mon, const char *msg)
3191
{
3192
    monitor_printf(mon, "%s\n", msg);
3193
    longjmp(expr_env, 1);
3194
}
3195

    
3196
/* return 0 if OK, -1 if not found */
3197
static int get_monitor_def(target_long *pval, const char *name)
3198
{
3199
    const MonitorDef *md;
3200
    void *ptr;
3201

    
3202
    for(md = monitor_defs; md->name != NULL; md++) {
3203
        if (compare_cmd(name, md->name)) {
3204
            if (md->get_value) {
3205
                *pval = md->get_value(md, md->offset);
3206
            } else {
3207
                CPUState *env = mon_get_cpu();
3208
                ptr = (uint8_t *)env + md->offset;
3209
                switch(md->type) {
3210
                case MD_I32:
3211
                    *pval = *(int32_t *)ptr;
3212
                    break;
3213
                case MD_TLONG:
3214
                    *pval = *(target_long *)ptr;
3215
                    break;
3216
                default:
3217
                    *pval = 0;
3218
                    break;
3219
                }
3220
            }
3221
            return 0;
3222
        }
3223
    }
3224
    return -1;
3225
}
3226

    
3227
static void next(void)
3228
{
3229
    if (*pch != '\0') {
3230
        pch++;
3231
        while (qemu_isspace(*pch))
3232
            pch++;
3233
    }
3234
}
3235

    
3236
static int64_t expr_sum(Monitor *mon);
3237

    
3238
static int64_t expr_unary(Monitor *mon)
3239
{
3240
    int64_t n;
3241
    char *p;
3242
    int ret;
3243

    
3244
    switch(*pch) {
3245
    case '+':
3246
        next();
3247
        n = expr_unary(mon);
3248
        break;
3249
    case '-':
3250
        next();
3251
        n = -expr_unary(mon);
3252
        break;
3253
    case '~':
3254
        next();
3255
        n = ~expr_unary(mon);
3256
        break;
3257
    case '(':
3258
        next();
3259
        n = expr_sum(mon);
3260
        if (*pch != ')') {
3261
            expr_error(mon, "')' expected");
3262
        }
3263
        next();
3264
        break;
3265
    case '\'':
3266
        pch++;
3267
        if (*pch == '\0')
3268
            expr_error(mon, "character constant expected");
3269
        n = *pch;
3270
        pch++;
3271
        if (*pch != '\'')
3272
            expr_error(mon, "missing terminating \' character");
3273
        next();
3274
        break;
3275
    case '$':
3276
        {
3277
            char buf[128], *q;
3278
            target_long reg=0;
3279

    
3280
            pch++;
3281
            q = buf;
3282
            while ((*pch >= 'a' && *pch <= 'z') ||
3283
                   (*pch >= 'A' && *pch <= 'Z') ||
3284
                   (*pch >= '0' && *pch <= '9') ||
3285
                   *pch == '_' || *pch == '.') {
3286
                if ((q - buf) < sizeof(buf) - 1)
3287
                    *q++ = *pch;
3288
                pch++;
3289
            }
3290
            while (qemu_isspace(*pch))
3291
                pch++;
3292
            *q = 0;
3293
            ret = get_monitor_def(&reg, buf);
3294
            if (ret < 0)
3295
                expr_error(mon, "unknown register");
3296
            n = reg;
3297
        }
3298
        break;
3299
    case '\0':
3300
        expr_error(mon, "unexpected end of expression");
3301
        n = 0;
3302
        break;
3303
    default:
3304
#if TARGET_PHYS_ADDR_BITS > 32
3305
        n = strtoull(pch, &p, 0);
3306
#else
3307
        n = strtoul(pch, &p, 0);
3308
#endif
3309
        if (pch == p) {
3310
            expr_error(mon, "invalid char in expression");
3311
        }
3312
        pch = p;
3313
        while (qemu_isspace(*pch))
3314
            pch++;
3315
        break;
3316
    }
3317
    return n;
3318
}
3319

    
3320

    
3321
static int64_t expr_prod(Monitor *mon)
3322
{
3323
    int64_t val, val2;
3324
    int op;
3325

    
3326
    val = expr_unary(mon);
3327
    for(;;) {
3328
        op = *pch;
3329
        if (op != '*' && op != '/' && op != '%')
3330
            break;
3331
        next();
3332
        val2 = expr_unary(mon);
3333
        switch(op) {
3334
        default:
3335
        case '*':
3336
            val *= val2;
3337
            break;
3338
        case '/':
3339
        case '%':
3340
            if (val2 == 0)
3341
                expr_error(mon, "division by zero");
3342
            if (op == '/')
3343
                val /= val2;
3344
            else
3345
                val %= val2;
3346
            break;
3347
        }
3348
    }
3349
    return val;
3350
}
3351

    
3352
static int64_t expr_logic(Monitor *mon)
3353
{
3354
    int64_t val, val2;
3355
    int op;
3356

    
3357
    val = expr_prod(mon);
3358
    for(;;) {
3359
        op = *pch;
3360
        if (op != '&' && op != '|' && op != '^')
3361
            break;
3362
        next();
3363
        val2 = expr_prod(mon);
3364
        switch(op) {
3365
        default:
3366
        case '&':
3367
            val &= val2;
3368
            break;
3369
        case '|':
3370
            val |= val2;
3371
            break;
3372
        case '^':
3373
            val ^= val2;
3374
            break;
3375
        }
3376
    }
3377
    return val;
3378
}
3379

    
3380
static int64_t expr_sum(Monitor *mon)
3381
{
3382
    int64_t val, val2;
3383
    int op;
3384

    
3385
    val = expr_logic(mon);
3386
    for(;;) {
3387
        op = *pch;
3388
        if (op != '+' && op != '-')
3389
            break;
3390
        next();
3391
        val2 = expr_logic(mon);
3392
        if (op == '+')
3393
            val += val2;
3394
        else
3395
            val -= val2;
3396
    }
3397
    return val;
3398
}
3399

    
3400
static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3401
{
3402
    pch = *pp;
3403
    if (setjmp(expr_env)) {
3404
        *pp = pch;
3405
        return -1;
3406
    }
3407
    while (qemu_isspace(*pch))
3408
        pch++;
3409
    *pval = expr_sum(mon);
3410
    *pp = pch;
3411
    return 0;
3412
}
3413

    
3414
static int get_double(Monitor *mon, double *pval, const char **pp)
3415
{
3416
    const char *p = *pp;
3417
    char *tailp;
3418
    double d;
3419

    
3420
    d = strtod(p, &tailp);
3421
    if (tailp == p) {
3422
        monitor_printf(mon, "Number expected\n");
3423
        return -1;
3424
    }
3425
    if (d != d || d - d != 0) {
3426
        /* NaN or infinity */
3427
        monitor_printf(mon, "Bad number\n");
3428
        return -1;
3429
    }
3430
    *pval = d;
3431
    *pp = tailp;
3432
    return 0;
3433
}
3434

    
3435
static int get_str(char *buf, int buf_size, const char **pp)
3436
{
3437
    const char *p;
3438
    char *q;
3439
    int c;
3440

    
3441
    q = buf;
3442
    p = *pp;
3443
    while (qemu_isspace(*p))
3444
        p++;
3445
    if (*p == '\0') {
3446
    fail:
3447
        *q = '\0';
3448
        *pp = p;
3449
        return -1;
3450
    }
3451
    if (*p == '\"') {
3452
        p++;
3453
        while (*p != '\0' && *p != '\"') {
3454
            if (*p == '\\') {
3455
                p++;
3456
                c = *p++;
3457
                switch(c) {
3458
                case 'n':
3459
                    c = '\n';
3460
                    break;
3461
                case 'r':
3462
                    c = '\r';
3463
                    break;
3464
                case '\\':
3465
                case '\'':
3466
                case '\"':
3467
                    break;
3468
                default:
3469
                    qemu_printf("unsupported escape code: '\\%c'\n", c);
3470
                    goto fail;
3471
                }
3472
                if ((q - buf) < buf_size - 1) {
3473
                    *q++ = c;
3474
                }
3475
            } else {
3476
                if ((q - buf) < buf_size - 1) {
3477
                    *q++ = *p;
3478
                }
3479
                p++;
3480
            }
3481
        }
3482
        if (*p != '\"') {
3483
            qemu_printf("unterminated string\n");
3484
            goto fail;
3485
        }
3486
        p++;
3487
    } else {
3488
        while (*p != '\0' && !qemu_isspace(*p)) {
3489
            if ((q - buf) < buf_size - 1) {
3490
                *q++ = *p;
3491
            }
3492
            p++;
3493
        }
3494
    }
3495
    *q = '\0';
3496
    *pp = p;
3497
    return 0;
3498
}
3499

    
3500
/*
3501
 * Store the command-name in cmdname, and return a pointer to
3502
 * the remaining of the command string.
3503
 */
3504
static const char *get_command_name(const char *cmdline,
3505
                                    char *cmdname, size_t nlen)
3506
{
3507
    size_t len;
3508
    const char *p, *pstart;
3509

    
3510
    p = cmdline;
3511
    while (qemu_isspace(*p))
3512
        p++;
3513
    if (*p == '\0')
3514
        return NULL;
3515
    pstart = p;
3516
    while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3517
        p++;
3518
    len = p - pstart;
3519
    if (len > nlen - 1)
3520
        len = nlen - 1;
3521
    memcpy(cmdname, pstart, len);
3522
    cmdname[len] = '\0';
3523
    return p;
3524
}
3525

    
3526
/**
3527
 * Read key of 'type' into 'key' and return the current
3528
 * 'type' pointer.
3529
 */
3530
static char *key_get_info(const char *type, char **key)
3531
{
3532
    size_t len;
3533
    char *p, *str;
3534

    
3535
    if (*type == ',')
3536
        type++;
3537

    
3538
    p = strchr(type, ':');
3539
    if (!p) {
3540
        *key = NULL;
3541
        return NULL;
3542
    }
3543
    len = p - type;
3544

    
3545
    str = qemu_malloc(len + 1);
3546
    memcpy(str, type, len);
3547
    str[len] = '\0';
3548

    
3549
    *key = str;
3550
    return ++p;
3551
}
3552

    
3553
static int default_fmt_format = 'x';
3554
static int default_fmt_size = 4;
3555

    
3556
#define MAX_ARGS 16
3557

    
3558
static int is_valid_option(const char *c, const char *typestr)
3559
{
3560
    char option[3];
3561
  
3562
    option[0] = '-';
3563
    option[1] = *c;
3564
    option[2] = '\0';
3565
  
3566
    typestr = strstr(typestr, option);
3567
    return (typestr != NULL);
3568
}
3569

    
3570
static const mon_cmd_t *monitor_find_command(const char *cmdname)
3571
{
3572
    const mon_cmd_t *cmd;
3573

    
3574
    for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
3575
        if (compare_cmd(cmdname, cmd->name)) {
3576
            return cmd;
3577
        }
3578
    }
3579

    
3580
    return NULL;
3581
}
3582

    
3583
static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3584
                                              const char *cmdline,
3585
                                              QDict *qdict)
3586
{
3587
    const char *p, *typestr;
3588
    int c;
3589
    const mon_cmd_t *cmd;
3590
    char cmdname[256];
3591
    char buf[1024];
3592
    char *key;
3593

    
3594
#ifdef DEBUG
3595
    monitor_printf(mon, "command='%s'\n", cmdline);
3596
#endif
3597

    
3598
    /* extract the command name */
3599
    p = get_command_name(cmdline, cmdname, sizeof(cmdname));
3600
    if (!p)
3601
        return NULL;
3602

    
3603
    cmd = monitor_find_command(cmdname);
3604
    if (!cmd) {
3605
        monitor_printf(mon, "unknown command: '%s'\n", cmdname);
3606
        return NULL;
3607
    }
3608

    
3609
    /* parse the parameters */
3610
    typestr = cmd->args_type;
3611
    for(;;) {
3612
        typestr = key_get_info(typestr, &key);
3613
        if (!typestr)
3614
            break;
3615
        c = *typestr;
3616
        typestr++;
3617
        switch(c) {
3618
        case 'F':
3619
        case 'B':
3620
        case 's':
3621
            {
3622
                int ret;
3623

    
3624
                while (qemu_isspace(*p))
3625
                    p++;
3626
                if (*typestr == '?') {
3627
                    typestr++;
3628
                    if (*p == '\0') {
3629
                        /* no optional string: NULL argument */
3630
                        break;
3631
                    }
3632
                }
3633
                ret = get_str(buf, sizeof(buf), &p);
3634
                if (ret < 0) {
3635
                    switch(c) {
3636
                    case 'F':
3637
                        monitor_printf(mon, "%s: filename expected\n",
3638
                                       cmdname);
3639
                        break;
3640
                    case 'B':
3641
                        monitor_printf(mon, "%s: block device name expected\n",
3642
                                       cmdname);
3643
                        break;
3644
                    default:
3645
                        monitor_printf(mon, "%s: string expected\n", cmdname);
3646
                        break;
3647
                    }
3648
                    goto fail;
3649
                }
3650
                qdict_put(qdict, key, qstring_from_str(buf));
3651
            }
3652
            break;
3653
        case 'O':
3654
            {
3655
                QemuOptsList *opts_list;
3656
                QemuOpts *opts;
3657

    
3658
                opts_list = qemu_find_opts(key);
3659
                if (!opts_list || opts_list->desc->name) {
3660
                    goto bad_type;
3661
                }
3662
                while (qemu_isspace(*p)) {
3663
                    p++;
3664
                }
3665
                if (!*p)
3666
                    break;
3667
                if (get_str(buf, sizeof(buf), &p) < 0) {
3668
                    goto fail;
3669
                }
3670
                opts = qemu_opts_parse(opts_list, buf, 1);
3671
                if (!opts) {
3672
                    goto fail;
3673
                }
3674
                qemu_opts_to_qdict(opts, qdict);
3675
                qemu_opts_del(opts);
3676
            }
3677
            break;
3678
        case '/':
3679
            {
3680
                int count, format, size;
3681

    
3682
                while (qemu_isspace(*p))
3683
                    p++;
3684
                if (*p == '/') {
3685
                    /* format found */
3686
                    p++;
3687
                    count = 1;
3688
                    if (qemu_isdigit(*p)) {
3689
                        count = 0;
3690
                        while (qemu_isdigit(*p)) {
3691
                            count = count * 10 + (*p - '0');
3692
                            p++;
3693
                        }
3694
                    }
3695
                    size = -1;
3696
                    format = -1;
3697
                    for(;;) {
3698
                        switch(*p) {
3699
                        case 'o':
3700
                        case 'd':
3701
                        case 'u':
3702
                        case 'x':
3703
                        case 'i':
3704
                        case 'c':
3705
                            format = *p++;
3706
                            break;
3707
                        case 'b':
3708
                            size = 1;
3709
                            p++;
3710
                            break;
3711
                        case 'h':
3712
                            size = 2;
3713
                            p++;
3714
                            break;
3715
                        case 'w':
3716
                            size = 4;
3717
                            p++;
3718
                            break;
3719
                        case 'g':
3720
                        case 'L':
3721
                            size = 8;
3722
                            p++;
3723
                            break;
3724
                        default:
3725
                            goto next;
3726
                        }
3727
                    }
3728
                next:
3729
                    if (*p != '\0' && !qemu_isspace(*p)) {
3730
                        monitor_printf(mon, "invalid char in format: '%c'\n",
3731
                                       *p);
3732
                        goto fail;
3733
                    }
3734
                    if (format < 0)
3735
                        format = default_fmt_format;
3736
                    if (format != 'i') {
3737
                        /* for 'i', not specifying a size gives -1 as size */
3738
                        if (size < 0)
3739
                            size = default_fmt_size;
3740
                        default_fmt_size = size;
3741
                    }
3742
                    default_fmt_format = format;
3743
                } else {
3744
                    count = 1;
3745
                    format = default_fmt_format;
3746
                    if (format != 'i') {
3747
                        size = default_fmt_size;
3748
                    } else {
3749
                        size = -1;
3750
                    }
3751
                }
3752
                qdict_put(qdict, "count", qint_from_int(count));
3753
                qdict_put(qdict, "format", qint_from_int(format));
3754
                qdict_put(qdict, "size", qint_from_int(size));
3755
            }
3756
            break;
3757
        case 'i':
3758
        case 'l':
3759
        case 'M':
3760
            {
3761
                int64_t val;
3762

    
3763
                while (qemu_isspace(*p))
3764
                    p++;
3765
                if (*typestr == '?' || *typestr == '.') {
3766
                    if (*typestr == '?') {
3767
                        if (*p == '\0') {
3768
                            typestr++;
3769
                            break;
3770
                        }
3771
                    } else {
3772
                        if (*p == '.') {
3773
                            p++;
3774
                            while (qemu_isspace(*p))
3775
                                p++;
3776
                        } else {
3777
                            typestr++;
3778
                            break;
3779
                        }
3780
                    }
3781
                    typestr++;
3782
                }
3783
                if (get_expr(mon, &val, &p))
3784
                    goto fail;
3785
                /* Check if 'i' is greater than 32-bit */
3786
                if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3787
                    monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3788
                    monitor_printf(mon, "integer is for 32-bit values\n");
3789
                    goto fail;
3790
                } else if (c == 'M') {
3791
                    val <<= 20;
3792
                }
3793
                qdict_put(qdict, key, qint_from_int(val));
3794
            }
3795
            break;
3796
        case 'b':
3797
        case 'T':
3798
            {
3799
                double val;
3800

    
3801
                while (qemu_isspace(*p))
3802
                    p++;
3803
                if (*typestr == '?') {
3804
                    typestr++;
3805
                    if (*p == '\0') {
3806
                        break;
3807
                    }
3808
                }
3809
                if (get_double(mon, &val, &p) < 0) {
3810
                    goto fail;
3811
                }
3812
                if (c == 'b' && *p) {
3813
                    switch (*p) {
3814
                    case 'K': case 'k':
3815
                        val *= 1 << 10; p++; break;
3816
                    case 'M': case 'm':
3817
                        val *= 1 << 20; p++; break;
3818
                    case 'G': case 'g':
3819
                        val *= 1 << 30; p++; break;
3820
                    }
3821
                }
3822
                if (c == 'T' && p[0] && p[1] == 's') {
3823
                    switch (*p) {
3824
                    case 'm':
3825
                        val /= 1e3; p += 2; break;
3826
                    case 'u':
3827
                        val /= 1e6; p += 2; break;
3828
                    case 'n':
3829
                        val /= 1e9; p += 2; break;
3830
                    }
3831
                }
3832
                if (*p && !qemu_isspace(*p)) {
3833
                    monitor_printf(mon, "Unknown unit suffix\n");
3834
                    goto fail;
3835
                }
3836
                qdict_put(qdict, key, qfloat_from_double(val));
3837
            }
3838
            break;
3839
        case '-':
3840
            {
3841
                const char *tmp = p;
3842
                int has_option, skip_key = 0;
3843
                /* option */
3844

    
3845
                c = *typestr++;
3846
                if (c == '\0')
3847
                    goto bad_type;
3848
                while (qemu_isspace(*p))
3849
                    p++;
3850
                has_option = 0;
3851
                if (*p == '-') {
3852
                    p++;
3853
                    if(c != *p) {
3854
                        if(!is_valid_option(p, typestr)) {
3855
                  
3856
                            monitor_printf(mon, "%s: unsupported option -%c\n",
3857
                                           cmdname, *p);
3858
                            goto fail;
3859
                        } else {
3860
                            skip_key = 1;
3861
                        }
3862
                    }
3863
                    if(skip_key) {
3864
                        p = tmp;
3865
                    } else {
3866
                        p++;
3867
                        has_option = 1;
3868
                    }
3869
                }
3870
                qdict_put(qdict, key, qint_from_int(has_option));
3871
            }
3872
            break;
3873
        default:
3874
        bad_type:
3875
            monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
3876
            goto fail;
3877
        }
3878
        qemu_free(key);
3879
        key = NULL;
3880
    }
3881
    /* check that all arguments were parsed */
3882
    while (qemu_isspace(*p))
3883
        p++;
3884
    if (*p != '\0') {
3885
        monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3886
                       cmdname);
3887
        goto fail;
3888
    }
3889

    
3890
    return cmd;
3891

    
3892
fail:
3893
    qemu_free(key);
3894
    return NULL;
3895
}
3896

    
3897
void monitor_set_error(Monitor *mon, QError *qerror)
3898
{
3899
    /* report only the first error */
3900
    if (!mon->error) {
3901
        mon->error = qerror;
3902
    } else {
3903
        MON_DEBUG("Additional error report at %s:%d\n",
3904
                  qerror->file, qerror->linenr);
3905
        QDECREF(qerror);
3906
    }
3907
}
3908

    
3909
static int is_async_return(const QObject *data)
3910
{
3911
    if (data && qobject_type(data) == QTYPE_QDICT) {
3912
        return qdict_haskey(qobject_to_qdict(data), "__mon_async");
3913
    }
3914

    
3915
    return 0;
3916
}
3917

    
3918
static void handler_audit(Monitor *mon, const mon_cmd_t *cmd, int ret)
3919
{
3920
    if (monitor_ctrl_mode(mon)) {
3921
        if (ret && !monitor_has_error(mon)) {
3922
            /*
3923
             * If it returns failure, it must have passed on error.
3924
             *
3925
             * Action: Report an internal error to the client if in QMP.
3926
             */
3927
            qerror_report(QERR_UNDEFINED_ERROR);
3928
            MON_DEBUG("command '%s' returned failure but did not pass an error\n",
3929
                      cmd->name);
3930
        }
3931

    
3932
#ifdef CONFIG_DEBUG_MONITOR
3933
        if (!ret && monitor_has_error(mon)) {
3934
            /*
3935
             * If it returns success, it must not have passed an error.
3936
             *
3937
             * Action: Report the passed error to the client.
3938
             */
3939
            MON_DEBUG("command '%s' returned success but passed an error\n",
3940
                      cmd->name);
3941
        }
3942

    
3943
        if (mon_print_count_get(mon) > 0 && strcmp(cmd->name, "info") != 0) {
3944
            /*
3945
             * Handlers should not call Monitor print functions.
3946
             *
3947
             * Action: Ignore them in QMP.
3948
             *
3949
             * (XXX: we don't check any 'info' or 'query' command here
3950
             * because the user print function _is_ called by do_info(), hence
3951
             * we will trigger this check. This problem will go away when we
3952
             * make 'query' commands real and kill do_info())
3953
             */
3954
            MON_DEBUG("command '%s' called print functions %d time(s)\n",
3955
                      cmd->name, mon_print_count_get(mon));
3956
        }
3957
#endif
3958
    } else {
3959
        assert(!monitor_has_error(mon));
3960
        QDECREF(mon->error);
3961
        mon->error = NULL;
3962
    }
3963
}
3964

    
3965
static void monitor_call_handler(Monitor *mon, const mon_cmd_t *cmd,
3966
                                 const QDict *params)
3967
{
3968
    int ret;
3969
    QObject *data = NULL;
3970

    
3971
    mon_print_count_init(mon);
3972

    
3973
    ret = cmd->mhandler.cmd_new(mon, params, &data);
3974
    handler_audit(mon, cmd, ret);
3975

    
3976
    if (is_async_return(data)) {
3977
        /*
3978
         * Asynchronous commands have no initial return data but they can
3979
         * generate errors.  Data is returned via the async completion handler.
3980
         */
3981
        if (monitor_ctrl_mode(mon) && monitor_has_error(mon)) {
3982
            monitor_protocol_emitter(mon, NULL);
3983
        }
3984
    } else if (monitor_ctrl_mode(mon)) {
3985
        /* Monitor Protocol */
3986
        monitor_protocol_emitter(mon, data);
3987
    } else {
3988
        /* User Protocol */
3989
         if (data)
3990
            cmd->user_print(mon, data);
3991
    }
3992

    
3993
    qobject_decref(data);
3994
}
3995

    
3996
static void handle_user_command(Monitor *mon, const char *cmdline)
3997
{
3998
    QDict *qdict;
3999
    const mon_cmd_t *cmd;
4000

    
4001
    qdict = qdict_new();
4002

    
4003
    cmd = monitor_parse_command(mon, cmdline, qdict);
4004
    if (!cmd)
4005
        goto out;
4006

    
4007
    if (monitor_handler_is_async(cmd)) {
4008
        user_async_cmd_handler(mon, cmd, qdict);
4009
    } else if (monitor_handler_ported(cmd)) {
4010
        monitor_call_handler(mon, cmd, qdict);
4011
    } else {
4012
        cmd->mhandler.cmd(mon, qdict);
4013
    }
4014

    
4015
out:
4016
    QDECREF(qdict);
4017
}
4018

    
4019
static void cmd_completion(const char *name, const char *list)
4020
{
4021
    const char *p, *pstart;
4022
    char cmd[128];
4023
    int len;
4024

    
4025
    p = list;
4026
    for(;;) {
4027
        pstart = p;
4028
        p = strchr(p, '|');
4029
        if (!p)
4030
            p = pstart + strlen(pstart);
4031
        len = p - pstart;
4032
        if (len > sizeof(cmd) - 2)
4033
            len = sizeof(cmd) - 2;
4034
        memcpy(cmd, pstart, len);
4035
        cmd[len] = '\0';
4036
        if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
4037
            readline_add_completion(cur_mon->rs, cmd);
4038
        }
4039
        if (*p == '\0')
4040
            break;
4041
        p++;
4042
    }
4043
}
4044

    
4045
static void file_completion(const char *input)
4046
{
4047
    DIR *ffs;
4048
    struct dirent *d;
4049
    char path[1024];
4050
    char file[1024], file_prefix[1024];
4051
    int input_path_len;
4052
    const char *p;
4053

    
4054
    p = strrchr(input, '/');
4055
    if (!p) {
4056
        input_path_len = 0;
4057
        pstrcpy(file_prefix, sizeof(file_prefix), input);
4058
        pstrcpy(path, sizeof(path), ".");
4059
    } else {
4060
        input_path_len = p - input + 1;
4061
        memcpy(path, input, input_path_len);
4062
        if (input_path_len > sizeof(path) - 1)
4063
            input_path_len = sizeof(path) - 1;
4064
        path[input_path_len] = '\0';
4065
        pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
4066
    }
4067
#ifdef DEBUG_COMPLETION
4068
    monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
4069
                   input, path, file_prefix);
4070
#endif
4071
    ffs = opendir(path);
4072
    if (!ffs)
4073
        return;
4074
    for(;;) {
4075
        struct stat sb;
4076
        d = readdir(ffs);
4077
        if (!d)
4078
            break;
4079
        if (strstart(d->d_name, file_prefix, NULL)) {
4080
            memcpy(file, input, input_path_len);
4081
            if (input_path_len < sizeof(file))
4082
                pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
4083
                        d->d_name);
4084
            /* stat the file to find out if it's a directory.
4085
             * In that case add a slash to speed up typing long paths
4086
             */
4087
            stat(file, &sb);
4088
            if(S_ISDIR(sb.st_mode))
4089
                pstrcat(file, sizeof(file), "/");
4090
            readline_add_completion(cur_mon->rs, file);
4091
        }
4092
    }
4093
    closedir(ffs);
4094
}
4095

    
4096
static void block_completion_it(void *opaque, BlockDriverState *bs)
4097
{
4098
    const char *name = bdrv_get_device_name(bs);
4099
    const char *input = opaque;
4100

    
4101
    if (input[0] == '\0' ||
4102
        !strncmp(name, (char *)input, strlen(input))) {
4103
        readline_add_completion(cur_mon->rs, name);
4104
    }
4105
}
4106

    
4107
/* NOTE: this parser is an approximate form of the real command parser */
4108
static void parse_cmdline(const char *cmdline,
4109
                         int *pnb_args, char **args)
4110
{
4111
    const char *p;
4112
    int nb_args, ret;
4113
    char buf[1024];
4114

    
4115
    p = cmdline;
4116
    nb_args = 0;
4117
    for(;;) {
4118
        while (qemu_isspace(*p))
4119
            p++;
4120
        if (*p == '\0')
4121
            break;
4122
        if (nb_args >= MAX_ARGS)
4123
            break;
4124
        ret = get_str(buf, sizeof(buf), &p);
4125
        args[nb_args] = qemu_strdup(buf);
4126
        nb_args++;
4127
        if (ret < 0)
4128
            break;
4129
    }
4130
    *pnb_args = nb_args;
4131
}
4132

    
4133
static const char *next_arg_type(const char *typestr)
4134
{
4135
    const char *p = strchr(typestr, ':');
4136
    return (p != NULL ? ++p : typestr);
4137
}
4138

    
4139
static void monitor_find_completion(const char *cmdline)
4140
{
4141
    const char *cmdname;
4142
    char *args[MAX_ARGS];
4143
    int nb_args, i, len;
4144
    const char *ptype, *str;
4145
    const mon_cmd_t *cmd;
4146
    const KeyDef *key;
4147

    
4148
    parse_cmdline(cmdline, &nb_args, args);
4149
#ifdef DEBUG_COMPLETION
4150
    for(i = 0; i < nb_args; i++) {
4151
        monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
4152
    }
4153
#endif
4154

    
4155
    /* if the line ends with a space, it means we want to complete the
4156
       next arg */
4157
    len = strlen(cmdline);
4158
    if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4159
        if (nb_args >= MAX_ARGS)
4160
            return;
4161
        args[nb_args++] = qemu_strdup("");
4162
    }
4163
    if (nb_args <= 1) {
4164
        /* command completion */
4165
        if (nb_args == 0)
4166
            cmdname = "";
4167
        else
4168
            cmdname = args[0];
4169
        readline_set_completion_index(cur_mon->rs, strlen(cmdname));
4170
        for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
4171
            cmd_completion(cmdname, cmd->name);
4172
        }
4173
    } else {
4174
        /* find the command */
4175
        for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
4176
            if (compare_cmd(args[0], cmd->name))
4177
                goto found;
4178
        }
4179
        return;
4180
    found:
4181
        ptype = next_arg_type(cmd->args_type);
4182
        for(i = 0; i < nb_args - 2; i++) {
4183
            if (*ptype != '\0') {
4184
                ptype = next_arg_type(ptype);
4185
                while (*ptype == '?')
4186
                    ptype = next_arg_type(ptype);
4187
            }
4188
        }
4189
        str = args[nb_args - 1];
4190
        if (*ptype == '-' && ptype[1] != '\0') {
4191
            ptype += 2;
4192
        }
4193
        switch(*ptype) {
4194
        case 'F':
4195
            /* file completion */
4196
            readline_set_completion_index(cur_mon->rs, strlen(str));
4197
            file_completion(str);
4198
            break;
4199
        case 'B':
4200
            /* block device name completion */
4201
            readline_set_completion_index(cur_mon->rs, strlen(str));
4202
            bdrv_iterate(block_completion_it, (void *)str);
4203
            break;
4204
        case 's':
4205
            /* XXX: more generic ? */
4206
            if (!strcmp(cmd->name, "info")) {
4207
                readline_set_completion_index(cur_mon->rs, strlen(str));
4208
                for(cmd = info_cmds; cmd->name != NULL; cmd++) {
4209
                    cmd_completion(str, cmd->name);
4210
                }
4211
            } else if (!strcmp(cmd->name, "sendkey")) {
4212
                char *sep = strrchr(str, '-');
4213
                if (sep)
4214
                    str = sep + 1;
4215
                readline_set_completion_index(cur_mon->rs, strlen(str));
4216
                for(key = key_defs; key->name != NULL; key++) {
4217
                    cmd_completion(str, key->name);
4218
                }
4219
            } else if (!strcmp(cmd->name, "help|?")) {
4220
                readline_set_completion_index(cur_mon->rs, strlen(str));
4221
                for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4222
                    cmd_completion(str, cmd->name);
4223
                }
4224
            }
4225
            break;
4226
        default:
4227
            break;
4228
        }
4229
    }
4230
    for(i = 0; i < nb_args; i++)
4231
        qemu_free(args[i]);
4232
}
4233

    
4234
static int monitor_can_read(void *opaque)
4235
{
4236
    Monitor *mon = opaque;
4237

    
4238
    return (mon->suspend_cnt == 0) ? 1 : 0;
4239
}
4240

    
4241
typedef struct CmdArgs {
4242
    QString *name;
4243
    int type;
4244
    int flag;
4245
    int optional;
4246
} CmdArgs;
4247

    
4248
static int check_opt(const CmdArgs *cmd_args, const char *name, QDict *args)
4249
{
4250
    if (!cmd_args->optional) {
4251
        qerror_report(QERR_MISSING_PARAMETER, name);
4252
        return -1;
4253
    }
4254

    
4255
    if (cmd_args->type == '-') {
4256
        /* handlers expect a value, they need to be changed */
4257
        qdict_put(args, name, qint_from_int(0));
4258
    }
4259

    
4260
    return 0;
4261
}
4262

    
4263
static int check_arg(const CmdArgs *cmd_args, QDict *args)
4264
{
4265
    QObject *value;
4266
    const char *name;
4267

    
4268
    name = qstring_get_str(cmd_args->name);
4269

    
4270
    if (!args) {
4271
        return check_opt(cmd_args, name, args);
4272
    }
4273

    
4274
    value = qdict_get(args, name);
4275
    if (!value) {
4276
        return check_opt(cmd_args, name, args);
4277
    }
4278

    
4279
    switch (cmd_args->type) {
4280
        case 'F':
4281
        case 'B':
4282
        case 's':
4283
            if (qobject_type(value) != QTYPE_QSTRING) {
4284
                qerror_report(QERR_INVALID_PARAMETER_TYPE, name, "string");
4285
                return -1;
4286
            }
4287
            break;
4288
        case '/': {
4289
            int i;
4290
            const char *keys[] = { "count", "format", "size", NULL };
4291

    
4292
            for (i = 0; keys[i]; i++) {
4293
                QObject *obj = qdict_get(args, keys[i]);
4294
                if (!obj) {
4295
                    qerror_report(QERR_MISSING_PARAMETER, name);
4296
                    return -1;
4297
                }
4298
                if (qobject_type(obj) != QTYPE_QINT) {
4299
                    qerror_report(QERR_INVALID_PARAMETER_TYPE, name, "int");
4300
                    return -1;
4301
                }
4302
            }
4303
            break;
4304
        }
4305
        case 'i':
4306
        case 'l':
4307
        case 'M':
4308
            if (qobject_type(value) != QTYPE_QINT) {
4309
                qerror_report(QERR_INVALID_PARAMETER_TYPE, name, "int");
4310
                return -1;
4311
            }
4312
            break;
4313
        case 'b':
4314
        case 'T':
4315
            if (qobject_type(value) != QTYPE_QINT && qobject_type(value) != QTYPE_QFLOAT) {
4316
                qerror_report(QERR_INVALID_PARAMETER_TYPE, name, "number");
4317
                return -1;
4318
            }
4319
            break;
4320
        case '-':
4321
            if (qobject_type(value) != QTYPE_QINT &&
4322
                qobject_type(value) != QTYPE_QBOOL) {
4323
                qerror_report(QERR_INVALID_PARAMETER_TYPE, name, "bool");
4324
                return -1;
4325
            }
4326
            if (qobject_type(value) == QTYPE_QBOOL) {
4327
                /* handlers expect a QInt, they need to be changed */
4328
                qdict_put(args, name,
4329
                         qint_from_int(qbool_get_int(qobject_to_qbool(value))));
4330
            }
4331
            break;
4332
        case 'O':
4333
        default:
4334
            /* impossible */
4335
            abort();
4336
    }
4337

    
4338
    return 0;
4339
}
4340

    
4341
static void cmd_args_init(CmdArgs *cmd_args)
4342
{
4343
    cmd_args->name = qstring_new();
4344
    cmd_args->type = cmd_args->flag = cmd_args->optional = 0;
4345
}
4346

    
4347
static int check_opts(QemuOptsList *opts_list, QDict *args)
4348
{
4349
    assert(!opts_list->desc->name);
4350
    return 0;
4351
}
4352

    
4353
/*
4354
 * This is not trivial, we have to parse Monitor command's argument
4355
 * type syntax to be able to check the arguments provided by clients.
4356
 *
4357
 * In the near future we will be using an array for that and will be
4358
 * able to drop all this parsing...
4359
 */
4360
static int monitor_check_qmp_args(const mon_cmd_t *cmd, QDict *args)
4361
{
4362
    int err;
4363
    const char *p;
4364
    CmdArgs cmd_args;
4365
    QemuOptsList *opts_list;
4366

    
4367
    if (cmd->args_type == NULL) {
4368
        return (qdict_size(args) == 0 ? 0 : -1);
4369
    }
4370

    
4371
    err = 0;
4372
    cmd_args_init(&cmd_args);
4373
    opts_list = NULL;
4374

    
4375
    for (p = cmd->args_type;; p++) {
4376
        if (*p == ':') {
4377
            cmd_args.type = *++p;
4378
            p++;
4379
            if (cmd_args.type == '-') {
4380
                cmd_args.flag = *p++;
4381
                cmd_args.optional = 1;
4382
            } else if (cmd_args.type == 'O') {
4383
                opts_list = qemu_find_opts(qstring_get_str(cmd_args.name));
4384
                assert(opts_list);
4385
            } else if (*p == '?') {
4386
                cmd_args.optional = 1;
4387
                p++;
4388
            }
4389

    
4390
            assert(*p == ',' || *p == '\0');
4391
            if (opts_list) {
4392
                err = check_opts(opts_list, args);
4393
                opts_list = NULL;
4394
            } else {
4395
                err = check_arg(&cmd_args, args);
4396
                QDECREF(cmd_args.name);
4397
                cmd_args_init(&cmd_args);
4398
            }
4399

    
4400
            if (err < 0) {
4401
                break;
4402
            }
4403
        } else {
4404
            qstring_append_chr(cmd_args.name, *p);
4405
        }
4406

    
4407
        if (*p == '\0') {
4408
            break;
4409
        }
4410
    }
4411

    
4412
    QDECREF(cmd_args.name);
4413
    return err;
4414
}
4415

    
4416
static int invalid_qmp_mode(const Monitor *mon, const char *cmd_name)
4417
{
4418
    int is_cap = compare_cmd(cmd_name, "qmp_capabilities");
4419
    return (qmp_cmd_mode(mon) ? is_cap : !is_cap);
4420
}
4421

    
4422
static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
4423
{
4424
    int err;
4425
    QObject *obj;
4426
    QDict *input, *args;
4427
    const mon_cmd_t *cmd;
4428
    Monitor *mon = cur_mon;
4429
    const char *cmd_name, *info_item;
4430

    
4431
    args = NULL;
4432

    
4433
    obj = json_parser_parse(tokens, NULL);
4434
    if (!obj) {
4435
        // FIXME: should be triggered in json_parser_parse()
4436
        qerror_report(QERR_JSON_PARSING);
4437
        goto err_out;
4438
    } else if (qobject_type(obj) != QTYPE_QDICT) {
4439
        qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "object");
4440
        qobject_decref(obj);
4441
        goto err_out;
4442
    }
4443

    
4444
    input = qobject_to_qdict(obj);
4445

    
4446
    mon->mc->id = qdict_get(input, "id");
4447
    qobject_incref(mon->mc->id);
4448

    
4449
    obj = qdict_get(input, "execute");
4450
    if (!obj) {
4451
        qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4452
        goto err_input;
4453
    } else if (qobject_type(obj) != QTYPE_QSTRING) {
4454
        qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "string");
4455
        goto err_input;
4456
    }
4457

    
4458
    cmd_name = qstring_get_str(qobject_to_qstring(obj));
4459

    
4460
    if (invalid_qmp_mode(mon, cmd_name)) {
4461
        qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
4462
        goto err_input;
4463
    }
4464

    
4465
    /*
4466
     * XXX: We need this special case until we get info handlers
4467
     * converted into 'query-' commands
4468
     */
4469
    if (compare_cmd(cmd_name, "info")) {
4470
        qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
4471
        goto err_input;
4472
    } else if (strstart(cmd_name, "query-", &info_item)) {
4473
        cmd = monitor_find_command("info");
4474
        qdict_put_obj(input, "arguments",
4475
                      qobject_from_jsonf("{ 'item': %s }", info_item));
4476
    } else {
4477
        cmd = monitor_find_command(cmd_name);
4478
        if (!cmd || !monitor_handler_ported(cmd)) {
4479
            qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
4480
            goto err_input;
4481
        }
4482
    }
4483

    
4484
    obj = qdict_get(input, "arguments");
4485
    if (!obj) {
4486
        args = qdict_new();
4487
    } else {
4488
        args = qobject_to_qdict(obj);
4489
        QINCREF(args);
4490
    }
4491

    
4492
    QDECREF(input);
4493

    
4494
    err = monitor_check_qmp_args(cmd, args);
4495
    if (err < 0) {
4496
        goto err_out;
4497
    }
4498

    
4499
    if (monitor_handler_is_async(cmd)) {
4500
        qmp_async_cmd_handler(mon, cmd, args);
4501
    } else {
4502
        monitor_call_handler(mon, cmd, args);
4503
    }
4504
    goto out;
4505

    
4506
err_input:
4507
    QDECREF(input);
4508
err_out:
4509
    monitor_protocol_emitter(mon, NULL);
4510
out:
4511
    QDECREF(args);
4512
}
4513

    
4514
/**
4515
 * monitor_control_read(): Read and handle QMP input
4516
 */
4517
static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
4518
{
4519
    Monitor *old_mon = cur_mon;
4520

    
4521
    cur_mon = opaque;
4522

    
4523
    json_message_parser_feed(&cur_mon->mc->parser, (const char *) buf, size);
4524

    
4525
    cur_mon = old_mon;
4526
}
4527

    
4528
static void monitor_read(void *opaque, const uint8_t *buf, int size)
4529
{
4530
    Monitor *old_mon = cur_mon;
4531
    int i;
4532

    
4533
    cur_mon = opaque;
4534

    
4535
    if (cur_mon->rs) {
4536
        for (i = 0; i < size; i++)
4537
            readline_handle_byte(cur_mon->rs, buf[i]);
4538
    } else {
4539
        if (size == 0 || buf[size - 1] != 0)
4540
            monitor_printf(cur_mon, "corrupted command\n");
4541
        else
4542
            handle_user_command(cur_mon, (char *)buf);
4543
    }
4544

    
4545
    cur_mon = old_mon;
4546
}
4547

    
4548
static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
4549
{
4550
    monitor_suspend(mon);
4551
    handle_user_command(mon, cmdline);
4552
    monitor_resume(mon);
4553
}
4554

    
4555
int monitor_suspend(Monitor *mon)
4556
{
4557
    if (!mon->rs)
4558
        return -ENOTTY;
4559
    mon->suspend_cnt++;
4560
    return 0;
4561
}
4562

    
4563
void monitor_resume(Monitor *mon)
4564
{
4565
    if (!mon->rs)
4566
        return;
4567
    if (--mon->suspend_cnt == 0)
4568
        readline_show_prompt(mon->rs);
4569
}
4570

    
4571
static QObject *get_qmp_greeting(void)
4572
{
4573
    QObject *ver;
4574

    
4575
    do_info_version(NULL, &ver);
4576
    return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
4577
}
4578

    
4579
/**
4580
 * monitor_control_event(): Print QMP gretting
4581
 */
4582
static void monitor_control_event(void *opaque, int event)
4583
{
4584
    QObject *data;
4585
    Monitor *mon = opaque;
4586

    
4587
    switch (event) {
4588
    case CHR_EVENT_OPENED:
4589
        mon->mc->command_mode = 0;
4590
        json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4591
        data = get_qmp_greeting();
4592
        monitor_json_emitter(mon, data);
4593
        qobject_decref(data);
4594
        break;
4595
    case CHR_EVENT_CLOSED:
4596
        json_message_parser_destroy(&mon->mc->parser);
4597
        break;
4598
    }
4599
}
4600

    
4601
static void monitor_event(void *opaque, int event)
4602
{
4603
    Monitor *mon = opaque;
4604

    
4605
    switch (event) {
4606
    case CHR_EVENT_MUX_IN:
4607
        mon->mux_out = 0;
4608
        if (mon->reset_seen) {
4609
            readline_restart(mon->rs);
4610
            monitor_resume(mon);
4611
            monitor_flush(mon);
4612
        } else {
4613
            mon->suspend_cnt = 0;
4614
        }
4615
        break;
4616

    
4617
    case CHR_EVENT_MUX_OUT:
4618
        if (mon->reset_seen) {
4619
            if (mon->suspend_cnt == 0) {
4620
                monitor_printf(mon, "\n");
4621
            }
4622
            monitor_flush(mon);
4623
            monitor_suspend(mon);
4624
        } else {