Statistics
| Branch: | Revision:

root / monitor.c @ d5a7b38f

History | View | Annotate | Download (122.2 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
 * 'i'          32 bit integer
71
 * 'l'          target long (32 or 64 bit)
72
 * 'M'          just like 'l', except in user mode the value is
73
 *              multiplied by 2^20 (think Mebibyte)
74
 * 'b'          double
75
 *              user mode accepts an optional G, g, M, m, K, k suffix,
76
 *              which multiplies the value by 2^30 for suffixes G and
77
 *              g, 2^20 for M and m, 2^10 for K and k
78
 * 'T'          double
79
 *              user mode accepts an optional ms, us, ns suffix,
80
 *              which divides the value by 1e3, 1e6, 1e9, respectively
81
 * '/'          optional gdb-like print format (like "/10x")
82
 *
83
 * '?'          optional type (for all types, except '/')
84
 * '.'          other form of optional type (for 'i' and 'l')
85
 * '-'          optional parameter (eg. '-f')
86
 *
87
 */
88

    
89
typedef struct MonitorCompletionData MonitorCompletionData;
90
struct MonitorCompletionData {
91
    Monitor *mon;
92
    void (*user_print)(Monitor *mon, const QObject *data);
93
};
94

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

    
114
/* file descriptors passed via SCM_RIGHTS */
115
typedef struct mon_fd_t mon_fd_t;
116
struct mon_fd_t {
117
    char *name;
118
    int fd;
119
    QLIST_ENTRY(mon_fd_t) next;
120
};
121

    
122
typedef struct MonitorControl {
123
    QObject *id;
124
    int print_enabled;
125
    JSONMessageParser parser;
126
    int command_mode;
127
} MonitorControl;
128

    
129
struct Monitor {
130
    CharDriverState *chr;
131
    int mux_out;
132
    int reset_seen;
133
    int flags;
134
    int suspend_cnt;
135
    uint8_t outbuf[1024];
136
    int outbuf_index;
137
    ReadLineState *rs;
138
    MonitorControl *mc;
139
    CPUState *mon_cpu;
140
    BlockDriverCompletionFunc *password_completion_cb;
141
    void *password_opaque;
142
    QError *error;
143
    QLIST_HEAD(,mon_fd_t) fds;
144
    QLIST_ENTRY(Monitor) entry;
145
};
146

    
147
static QLIST_HEAD(mon_list, Monitor) mon_list;
148

    
149
static const mon_cmd_t mon_cmds[];
150
static const mon_cmd_t info_cmds[];
151

    
152
Monitor *cur_mon = NULL;
153

    
154
static void monitor_command_cb(Monitor *mon, const char *cmdline,
155
                               void *opaque);
156

    
157
static inline int qmp_cmd_mode(const Monitor *mon)
158
{
159
    return (mon->mc ? mon->mc->command_mode : 0);
160
}
161

    
162
/* Return true if in control mode, false otherwise */
163
static inline int monitor_ctrl_mode(const Monitor *mon)
164
{
165
    return (mon->flags & MONITOR_USE_CONTROL);
166
}
167

    
168
static void monitor_read_command(Monitor *mon, int show_prompt)
169
{
170
    if (!mon->rs)
171
        return;
172

    
173
    readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
174
    if (show_prompt)
175
        readline_show_prompt(mon->rs);
176
}
177

    
178
static int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
179
                                 void *opaque)
180
{
181
    if (monitor_ctrl_mode(mon)) {
182
        qemu_error_new(QERR_MISSING_PARAMETER, "password");
183
        return -EINVAL;
184
    } else if (mon->rs) {
185
        readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
186
        /* prompt is printed on return from the command handler */
187
        return 0;
188
    } else {
189
        monitor_printf(mon, "terminal does not support password prompting\n");
190
        return -ENOTTY;
191
    }
192
}
193

    
194
void monitor_flush(Monitor *mon)
195
{
196
    if (mon && mon->outbuf_index != 0 && !mon->mux_out) {
197
        qemu_chr_write(mon->chr, mon->outbuf, mon->outbuf_index);
198
        mon->outbuf_index = 0;
199
    }
200
}
201

    
202
/* flush at every end of line or if the buffer is full */
203
static void monitor_puts(Monitor *mon, const char *str)
204
{
205
    char c;
206

    
207
    for(;;) {
208
        c = *str++;
209
        if (c == '\0')
210
            break;
211
        if (c == '\n')
212
            mon->outbuf[mon->outbuf_index++] = '\r';
213
        mon->outbuf[mon->outbuf_index++] = c;
214
        if (mon->outbuf_index >= (sizeof(mon->outbuf) - 1)
215
            || c == '\n')
216
            monitor_flush(mon);
217
    }
218
}
219

    
220
void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
221
{
222
    if (!mon)
223
        return;
224

    
225
    if (mon->mc && !mon->mc->print_enabled) {
226
        qemu_error_new(QERR_UNDEFINED_ERROR);
227
    } else {
228
        char buf[4096];
229
        vsnprintf(buf, sizeof(buf), fmt, ap);
230
        monitor_puts(mon, buf);
231
    }
232
}
233

    
234
void monitor_printf(Monitor *mon, const char *fmt, ...)
235
{
236
    va_list ap;
237
    va_start(ap, fmt);
238
    monitor_vprintf(mon, fmt, ap);
239
    va_end(ap);
240
}
241

    
242
void monitor_print_filename(Monitor *mon, const char *filename)
243
{
244
    int i;
245

    
246
    for (i = 0; filename[i]; i++) {
247
        switch (filename[i]) {
248
        case ' ':
249
        case '"':
250
        case '\\':
251
            monitor_printf(mon, "\\%c", filename[i]);
252
            break;
253
        case '\t':
254
            monitor_printf(mon, "\\t");
255
            break;
256
        case '\r':
257
            monitor_printf(mon, "\\r");
258
            break;
259
        case '\n':
260
            monitor_printf(mon, "\\n");
261
            break;
262
        default:
263
            monitor_printf(mon, "%c", filename[i]);
264
            break;
265
        }
266
    }
267
}
268

    
269
static int monitor_fprintf(FILE *stream, const char *fmt, ...)
270
{
271
    va_list ap;
272
    va_start(ap, fmt);
273
    monitor_vprintf((Monitor *)stream, fmt, ap);
274
    va_end(ap);
275
    return 0;
276
}
277

    
278
static void monitor_user_noop(Monitor *mon, const QObject *data) { }
279

    
280
static inline int monitor_handler_ported(const mon_cmd_t *cmd)
281
{
282
    return cmd->user_print != NULL;
283
}
284

    
285
static inline bool monitor_handler_is_async(const mon_cmd_t *cmd)
286
{
287
    return cmd->async != 0;
288
}
289

    
290
static inline int monitor_has_error(const Monitor *mon)
291
{
292
    return mon->error != NULL;
293
}
294

    
295
static void monitor_json_emitter(Monitor *mon, const QObject *data)
296
{
297
    QString *json;
298

    
299
    json = qobject_to_json(data);
300
    assert(json != NULL);
301

    
302
    mon->mc->print_enabled = 1;
303
    monitor_printf(mon, "%s\n", qstring_get_str(json));
304
    mon->mc->print_enabled = 0;
305

    
306
    QDECREF(json);
307
}
308

    
309
static void monitor_protocol_emitter(Monitor *mon, QObject *data)
310
{
311
    QDict *qmp;
312

    
313
    qmp = qdict_new();
314

    
315
    if (!monitor_has_error(mon)) {
316
        /* success response */
317
        if (data) {
318
            qobject_incref(data);
319
            qdict_put_obj(qmp, "return", data);
320
        } else {
321
            /* return an empty QDict by default */
322
            qdict_put(qmp, "return", qdict_new());
323
        }
324
    } else {
325
        /* error response */
326
        qdict_put(mon->error->error, "desc", qerror_human(mon->error));
327
        qdict_put(qmp, "error", mon->error->error);
328
        QINCREF(mon->error->error);
329
        QDECREF(mon->error);
330
        mon->error = NULL;
331
    }
332

    
333
    if (mon->mc->id) {
334
        qdict_put_obj(qmp, "id", mon->mc->id);
335
        mon->mc->id = NULL;
336
    }
337

    
338
    monitor_json_emitter(mon, QOBJECT(qmp));
339
    QDECREF(qmp);
340
}
341

    
342
static void timestamp_put(QDict *qdict)
343
{
344
    int err;
345
    QObject *obj;
346
    qemu_timeval tv;
347

    
348
    err = qemu_gettimeofday(&tv);
349
    if (err < 0)
350
        return;
351

    
352
    obj = qobject_from_jsonf("{ 'seconds': %" PRId64 ", "
353
                                "'microseconds': %" PRId64 " }",
354
                                (int64_t) tv.tv_sec, (int64_t) tv.tv_usec);
355
    qdict_put_obj(qdict, "timestamp", obj);
356
}
357

    
358
/**
359
 * monitor_protocol_event(): Generate a Monitor event
360
 *
361
 * Event-specific data can be emitted through the (optional) 'data' parameter.
362
 */
363
void monitor_protocol_event(MonitorEvent event, QObject *data)
364
{
365
    QDict *qmp;
366
    const char *event_name;
367
    Monitor *mon;
368

    
369
    assert(event < QEVENT_MAX);
370

    
371
    switch (event) {
372
        case QEVENT_DEBUG:
373
            event_name = "DEBUG";
374
            break;
375
        case QEVENT_SHUTDOWN:
376
            event_name = "SHUTDOWN";
377
            break;
378
        case QEVENT_RESET:
379
            event_name = "RESET";
380
            break;
381
        case QEVENT_POWERDOWN:
382
            event_name = "POWERDOWN";
383
            break;
384
        case QEVENT_STOP:
385
            event_name = "STOP";
386
            break;
387
        case QEVENT_VNC_CONNECTED:
388
            event_name = "VNC_CONNECTED";
389
            break;
390
        case QEVENT_VNC_INITIALIZED:
391
            event_name = "VNC_INITIALIZED";
392
            break;
393
        case QEVENT_VNC_DISCONNECTED:
394
            event_name = "VNC_DISCONNECTED";
395
            break;
396
        case QEVENT_BLOCK_IO_ERROR:
397
            event_name = "BLOCK_IO_ERROR";
398
            break;
399
        default:
400
            abort();
401
            break;
402
    }
403

    
404
    qmp = qdict_new();
405
    timestamp_put(qmp);
406
    qdict_put(qmp, "event", qstring_from_str(event_name));
407
    if (data) {
408
        qobject_incref(data);
409
        qdict_put_obj(qmp, "data", data);
410
    }
411

    
412
    QLIST_FOREACH(mon, &mon_list, entry) {
413
        if (monitor_ctrl_mode(mon) && qmp_cmd_mode(mon)) {
414
            monitor_json_emitter(mon, QOBJECT(qmp));
415
        }
416
    }
417
    QDECREF(qmp);
418
}
419

    
420
static int do_qmp_capabilities(Monitor *mon, const QDict *params,
421
                               QObject **ret_data)
422
{
423
    /* Will setup QMP capabilities in the future */
424
    if (monitor_ctrl_mode(mon)) {
425
        mon->mc->command_mode = 1;
426
    }
427

    
428
    return 0;
429
}
430

    
431
static int compare_cmd(const char *name, const char *list)
432
{
433
    const char *p, *pstart;
434
    int len;
435
    len = strlen(name);
436
    p = list;
437
    for(;;) {
438
        pstart = p;
439
        p = strchr(p, '|');
440
        if (!p)
441
            p = pstart + strlen(pstart);
442
        if ((p - pstart) == len && !memcmp(pstart, name, len))
443
            return 1;
444
        if (*p == '\0')
445
            break;
446
        p++;
447
    }
448
    return 0;
449
}
450

    
451
static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
452
                          const char *prefix, const char *name)
453
{
454
    const mon_cmd_t *cmd;
455

    
456
    for(cmd = cmds; cmd->name != NULL; cmd++) {
457
        if (!name || !strcmp(name, cmd->name))
458
            monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
459
                           cmd->params, cmd->help);
460
    }
461
}
462

    
463
static void help_cmd(Monitor *mon, const char *name)
464
{
465
    if (name && !strcmp(name, "info")) {
466
        help_cmd_dump(mon, info_cmds, "info ", NULL);
467
    } else {
468
        help_cmd_dump(mon, mon_cmds, "", name);
469
        if (name && !strcmp(name, "log")) {
470
            const CPULogItem *item;
471
            monitor_printf(mon, "Log items (comma separated):\n");
472
            monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
473
            for(item = cpu_log_items; item->mask != 0; item++) {
474
                monitor_printf(mon, "%-10s %s\n", item->name, item->help);
475
            }
476
        }
477
    }
478
}
479

    
480
static void do_help_cmd(Monitor *mon, const QDict *qdict)
481
{
482
    help_cmd(mon, qdict_get_try_str(qdict, "name"));
483
}
484

    
485
static void do_commit(Monitor *mon, const QDict *qdict)
486
{
487
    int all_devices;
488
    DriveInfo *dinfo;
489
    const char *device = qdict_get_str(qdict, "device");
490

    
491
    all_devices = !strcmp(device, "all");
492
    QTAILQ_FOREACH(dinfo, &drives, next) {
493
        if (!all_devices)
494
            if (strcmp(bdrv_get_device_name(dinfo->bdrv), device))
495
                continue;
496
        bdrv_commit(dinfo->bdrv);
497
    }
498
}
499

    
500
static void user_monitor_complete(void *opaque, QObject *ret_data)
501
{
502
    MonitorCompletionData *data = (MonitorCompletionData *)opaque; 
503

    
504
    if (ret_data) {
505
        data->user_print(data->mon, ret_data);
506
    }
507
    monitor_resume(data->mon);
508
    qemu_free(data);
509
}
510

    
511
static void qmp_monitor_complete(void *opaque, QObject *ret_data)
512
{
513
    monitor_protocol_emitter(opaque, ret_data);
514
}
515

    
516
static void qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
517
                                  const QDict *params)
518
{
519
    cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);
520
}
521

    
522
static void qmp_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
523
{
524
    cmd->mhandler.info_async(mon, qmp_monitor_complete, mon);
525
}
526

    
527
static void user_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
528
                                   const QDict *params)
529
{
530
    int ret;
531

    
532
    MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
533
    cb_data->mon = mon;
534
    cb_data->user_print = cmd->user_print;
535
    monitor_suspend(mon);
536
    ret = cmd->mhandler.cmd_async(mon, params,
537
                                  user_monitor_complete, cb_data);
538
    if (ret < 0) {
539
        monitor_resume(mon);
540
        qemu_free(cb_data);
541
    }
542
}
543

    
544
static void user_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
545
{
546
    int ret;
547

    
548
    MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
549
    cb_data->mon = mon;
550
    cb_data->user_print = cmd->user_print;
551
    monitor_suspend(mon);
552
    ret = cmd->mhandler.info_async(mon, user_monitor_complete, cb_data);
553
    if (ret < 0) {
554
        monitor_resume(mon);
555
        qemu_free(cb_data);
556
    }
557
}
558

    
559
static void do_info(Monitor *mon, const QDict *qdict, QObject **ret_data)
560
{
561
    const mon_cmd_t *cmd;
562
    const char *item = qdict_get_try_str(qdict, "item");
563

    
564
    if (!item) {
565
        assert(monitor_ctrl_mode(mon) == 0);
566
        goto help;
567
    }
568

    
569
    for (cmd = info_cmds; cmd->name != NULL; cmd++) {
570
        if (compare_cmd(item, cmd->name))
571
            break;
572
    }
573

    
574
    if (cmd->name == NULL) {
575
        if (monitor_ctrl_mode(mon)) {
576
            qemu_error_new(QERR_COMMAND_NOT_FOUND, item);
577
            return;
578
        }
579
        goto help;
580
    }
581

    
582
    if (monitor_handler_is_async(cmd)) {
583
        if (monitor_ctrl_mode(mon)) {
584
            qmp_async_info_handler(mon, cmd);
585
        } else {
586
            user_async_info_handler(mon, cmd);
587
        }
588
        /*
589
         * Indicate that this command is asynchronous and will not return any
590
         * data (not even empty).  Instead, the data will be returned via a
591
         * completion callback.
592
         */
593
        *ret_data = qobject_from_jsonf("{ '__mon_async': 'return' }");
594
    } else if (monitor_handler_ported(cmd)) {
595
        cmd->mhandler.info_new(mon, ret_data);
596

    
597
        if (!monitor_ctrl_mode(mon)) {
598
            /*
599
             * User Protocol function is called here, Monitor Protocol is
600
             * handled by monitor_call_handler()
601
             */
602
            if (*ret_data)
603
                cmd->user_print(mon, *ret_data);
604
        }
605
    } else {
606
        if (monitor_ctrl_mode(mon)) {
607
            /* handler not converted yet */
608
            qemu_error_new(QERR_COMMAND_NOT_FOUND, item);
609
        } else {
610
            cmd->mhandler.info(mon);
611
        }
612
    }
613

    
614
    return;
615

    
616
help:
617
    help_cmd(mon, "info");
618
}
619

    
620
static void do_info_version_print(Monitor *mon, const QObject *data)
621
{
622
    QDict *qdict;
623

    
624
    qdict = qobject_to_qdict(data);
625

    
626
    monitor_printf(mon, "%s%s\n", qdict_get_str(qdict, "qemu"),
627
                                  qdict_get_str(qdict, "package"));
628
}
629

    
630
/**
631
 * do_info_version(): Show QEMU version
632
 *
633
 * Return a QDict with the following information:
634
 *
635
 * - "qemu": QEMU's version
636
 * - "package": package's version
637
 *
638
 * Example:
639
 *
640
 * { "qemu": "0.11.50", "package": "" }
641
 */
642
static void do_info_version(Monitor *mon, QObject **ret_data)
643
{
644
    *ret_data = qobject_from_jsonf("{ 'qemu': %s, 'package': %s }",
645
                                   QEMU_VERSION, QEMU_PKGVERSION);
646
}
647

    
648
static void do_info_name_print(Monitor *mon, const QObject *data)
649
{
650
    QDict *qdict;
651

    
652
    qdict = qobject_to_qdict(data);
653
    if (qdict_size(qdict) == 0) {
654
        return;
655
    }
656

    
657
    monitor_printf(mon, "%s\n", qdict_get_str(qdict, "name"));
658
}
659

    
660
/**
661
 * do_info_name(): Show VM name
662
 *
663
 * Return a QDict with the following information:
664
 *
665
 * - "name": VM's name (optional)
666
 *
667
 * Example:
668
 *
669
 * { "name": "qemu-name" }
670
 */
671
static void do_info_name(Monitor *mon, QObject **ret_data)
672
{
673
    *ret_data = qemu_name ? qobject_from_jsonf("{'name': %s }", qemu_name) :
674
                            qobject_from_jsonf("{}");
675
}
676

    
677
static QObject *get_cmd_dict(const char *name)
678
{
679
    const char *p;
680

    
681
    /* Remove '|' from some commands */
682
    p = strchr(name, '|');
683
    if (p) {
684
        p++;
685
    } else {
686
        p = name;
687
    }
688

    
689
    return qobject_from_jsonf("{ 'name': %s }", p);
690
}
691

    
692
/**
693
 * do_info_commands(): List QMP available commands
694
 *
695
 * Each command is represented by a QDict, the returned QObject is a QList
696
 * of all commands.
697
 *
698
 * The QDict contains:
699
 *
700
 * - "name": command's name
701
 *
702
 * Example:
703
 *
704
 * { [ { "name": "query-balloon" }, { "name": "system_powerdown" } ] }
705
 */
706
static void do_info_commands(Monitor *mon, QObject **ret_data)
707
{
708
    QList *cmd_list;
709
    const mon_cmd_t *cmd;
710

    
711
    cmd_list = qlist_new();
712

    
713
    for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
714
        if (monitor_handler_ported(cmd) && !compare_cmd(cmd->name, "info")) {
715
            qlist_append_obj(cmd_list, get_cmd_dict(cmd->name));
716
        }
717
    }
718

    
719
    for (cmd = info_cmds; cmd->name != NULL; cmd++) {
720
        if (monitor_handler_ported(cmd)) {
721
            char buf[128];
722
            snprintf(buf, sizeof(buf), "query-%s", cmd->name);
723
            qlist_append_obj(cmd_list, get_cmd_dict(buf));
724
        }
725
    }
726

    
727
    *ret_data = QOBJECT(cmd_list);
728
}
729

    
730
#if defined(TARGET_I386)
731
static void do_info_hpet_print(Monitor *mon, const QObject *data)
732
{
733
    monitor_printf(mon, "HPET is %s by QEMU\n",
734
                   qdict_get_bool(qobject_to_qdict(data), "enabled") ?
735
                   "enabled" : "disabled");
736
}
737

    
738
/**
739
 * do_info_hpet(): Show HPET state
740
 *
741
 * Return a QDict with the following information:
742
 *
743
 * - "enabled": true if hpet if enabled, false otherwise
744
 *
745
 * Example:
746
 *
747
 * { "enabled": true }
748
 */
749
static void do_info_hpet(Monitor *mon, QObject **ret_data)
750
{
751
    *ret_data = qobject_from_jsonf("{ 'enabled': %i }", !no_hpet);
752
}
753
#endif
754

    
755
static void do_info_uuid_print(Monitor *mon, const QObject *data)
756
{
757
    monitor_printf(mon, "%s\n", qdict_get_str(qobject_to_qdict(data), "UUID"));
758
}
759

    
760
/**
761
 * do_info_uuid(): Show VM UUID
762
 *
763
 * Return a QDict with the following information:
764
 *
765
 * - "UUID": Universally Unique Identifier
766
 *
767
 * Example:
768
 *
769
 * { "UUID": "550e8400-e29b-41d4-a716-446655440000" }
770
 */
771
static void do_info_uuid(Monitor *mon, QObject **ret_data)
772
{
773
    char uuid[64];
774

    
775
    snprintf(uuid, sizeof(uuid), UUID_FMT, qemu_uuid[0], qemu_uuid[1],
776
                   qemu_uuid[2], qemu_uuid[3], qemu_uuid[4], qemu_uuid[5],
777
                   qemu_uuid[6], qemu_uuid[7], qemu_uuid[8], qemu_uuid[9],
778
                   qemu_uuid[10], qemu_uuid[11], qemu_uuid[12], qemu_uuid[13],
779
                   qemu_uuid[14], qemu_uuid[15]);
780
    *ret_data = qobject_from_jsonf("{ 'UUID': %s }", uuid);
781
}
782

    
783
/* get the current CPU defined by the user */
784
static int mon_set_cpu(int cpu_index)
785
{
786
    CPUState *env;
787

    
788
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
789
        if (env->cpu_index == cpu_index) {
790
            cur_mon->mon_cpu = env;
791
            return 0;
792
        }
793
    }
794
    return -1;
795
}
796

    
797
static CPUState *mon_get_cpu(void)
798
{
799
    if (!cur_mon->mon_cpu) {
800
        mon_set_cpu(0);
801
    }
802
    cpu_synchronize_state(cur_mon->mon_cpu);
803
    return cur_mon->mon_cpu;
804
}
805

    
806
static void do_info_registers(Monitor *mon)
807
{
808
    CPUState *env;
809
    env = mon_get_cpu();
810
#ifdef TARGET_I386
811
    cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
812
                   X86_DUMP_FPU);
813
#else
814
    cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
815
                   0);
816
#endif
817
}
818

    
819
static void print_cpu_iter(QObject *obj, void *opaque)
820
{
821
    QDict *cpu;
822
    int active = ' ';
823
    Monitor *mon = opaque;
824

    
825
    assert(qobject_type(obj) == QTYPE_QDICT);
826
    cpu = qobject_to_qdict(obj);
827

    
828
    if (qdict_get_bool(cpu, "current")) {
829
        active = '*';
830
    }
831

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

    
834
#if defined(TARGET_I386)
835
    monitor_printf(mon, "pc=0x" TARGET_FMT_lx,
836
                   (target_ulong) qdict_get_int(cpu, "pc"));
837
#elif defined(TARGET_PPC)
838
    monitor_printf(mon, "nip=0x" TARGET_FMT_lx,
839
                   (target_long) qdict_get_int(cpu, "nip"));
840
#elif defined(TARGET_SPARC)
841
    monitor_printf(mon, "pc=0x " TARGET_FMT_lx,
842
                   (target_long) qdict_get_int(cpu, "pc"));
843
    monitor_printf(mon, "npc=0x" TARGET_FMT_lx,
844
                   (target_long) qdict_get_int(cpu, "npc"));
845
#elif defined(TARGET_MIPS)
846
    monitor_printf(mon, "PC=0x" TARGET_FMT_lx,
847
                   (target_long) qdict_get_int(cpu, "PC"));
848
#endif
849

    
850
    if (qdict_get_bool(cpu, "halted")) {
851
        monitor_printf(mon, " (halted)");
852
    }
853

    
854
    monitor_printf(mon, "\n");
855
}
856

    
857
static void monitor_print_cpus(Monitor *mon, const QObject *data)
858
{
859
    QList *cpu_list;
860

    
861
    assert(qobject_type(data) == QTYPE_QLIST);
862
    cpu_list = qobject_to_qlist(data);
863
    qlist_iter(cpu_list, print_cpu_iter, mon);
864
}
865

    
866
/**
867
 * do_info_cpus(): Show CPU information
868
 *
869
 * Return a QList. Each CPU is represented by a QDict, which contains:
870
 *
871
 * - "cpu": CPU index
872
 * - "current": true if this is the current CPU, false otherwise
873
 * - "halted": true if the cpu is halted, false otherwise
874
 * - Current program counter. The key's name depends on the architecture:
875
 *      "pc": i386/x86)64
876
 *      "nip": PPC
877
 *      "pc" and "npc": sparc
878
 *      "PC": mips
879
 *
880
 * Example:
881
 *
882
 * [ { "CPU": 0, "current": true, "halted": false, "pc": 3227107138 },
883
 *   { "CPU": 1, "current": false, "halted": true, "pc": 7108165 } ]
884
 */
885
static void do_info_cpus(Monitor *mon, QObject **ret_data)
886
{
887
    CPUState *env;
888
    QList *cpu_list;
889

    
890
    cpu_list = qlist_new();
891

    
892
    /* just to set the default cpu if not already done */
893
    mon_get_cpu();
894

    
895
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
896
        QDict *cpu;
897
        QObject *obj;
898

    
899
        cpu_synchronize_state(env);
900

    
901
        obj = qobject_from_jsonf("{ 'CPU': %d, 'current': %i, 'halted': %i }",
902
                                 env->cpu_index, env == mon->mon_cpu,
903
                                 env->halted);
904

    
905
        cpu = qobject_to_qdict(obj);
906

    
907
#if defined(TARGET_I386)
908
        qdict_put(cpu, "pc", qint_from_int(env->eip + env->segs[R_CS].base));
909
#elif defined(TARGET_PPC)
910
        qdict_put(cpu, "nip", qint_from_int(env->nip));
911
#elif defined(TARGET_SPARC)
912
        qdict_put(cpu, "pc", qint_from_int(env->pc));
913
        qdict_put(cpu, "npc", qint_from_int(env->npc));
914
#elif defined(TARGET_MIPS)
915
        qdict_put(cpu, "PC", qint_from_int(env->active_tc.PC));
916
#endif
917

    
918
        qlist_append(cpu_list, cpu);
919
    }
920

    
921
    *ret_data = QOBJECT(cpu_list);
922
}
923

    
924
static void do_cpu_set(Monitor *mon, const QDict *qdict, QObject **ret_data)
925
{
926
    int index = qdict_get_int(qdict, "index");
927
    if (mon_set_cpu(index) < 0)
928
        qemu_error_new(QERR_INVALID_PARAMETER, "index");
929
}
930

    
931
static void do_info_jit(Monitor *mon)
932
{
933
    dump_exec_info((FILE *)mon, monitor_fprintf);
934
}
935

    
936
static void do_info_history(Monitor *mon)
937
{
938
    int i;
939
    const char *str;
940

    
941
    if (!mon->rs)
942
        return;
943
    i = 0;
944
    for(;;) {
945
        str = readline_get_history(mon->rs, i);
946
        if (!str)
947
            break;
948
        monitor_printf(mon, "%d: '%s'\n", i, str);
949
        i++;
950
    }
951
}
952

    
953
#if defined(TARGET_PPC)
954
/* XXX: not implemented in other targets */
955
static void do_info_cpu_stats(Monitor *mon)
956
{
957
    CPUState *env;
958

    
959
    env = mon_get_cpu();
960
    cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
961
}
962
#endif
963

    
964
/**
965
 * do_quit(): Quit QEMU execution
966
 */
967
static int do_quit(Monitor *mon, const QDict *qdict, QObject **ret_data)
968
{
969
    exit(0);
970
    return 0;
971
}
972

    
973
static int eject_device(Monitor *mon, BlockDriverState *bs, int force)
974
{
975
    if (bdrv_is_inserted(bs)) {
976
        if (!force) {
977
            if (!bdrv_is_removable(bs)) {
978
                qemu_error_new(QERR_DEVICE_NOT_REMOVABLE,
979
                               bdrv_get_device_name(bs));
980
                return -1;
981
            }
982
            if (bdrv_is_locked(bs)) {
983
                qemu_error_new(QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));
984
                return -1;
985
            }
986
        }
987
        bdrv_close(bs);
988
    }
989
    return 0;
990
}
991

    
992
static void do_eject(Monitor *mon, const QDict *qdict, QObject **ret_data)
993
{
994
    BlockDriverState *bs;
995
    int force = qdict_get_int(qdict, "force");
996
    const char *filename = qdict_get_str(qdict, "device");
997

    
998
    bs = bdrv_find(filename);
999
    if (!bs) {
1000
        qemu_error_new(QERR_DEVICE_NOT_FOUND, filename);
1001
        return;
1002
    }
1003
    eject_device(mon, bs, force);
1004
}
1005

    
1006
static void do_block_set_passwd(Monitor *mon, const QDict *qdict,
1007
                                QObject **ret_data)
1008
{
1009
    BlockDriverState *bs;
1010

    
1011
    bs = bdrv_find(qdict_get_str(qdict, "device"));
1012
    if (!bs) {
1013
        qemu_error_new(QERR_DEVICE_NOT_FOUND, qdict_get_str(qdict, "device"));
1014
        return;
1015
    }
1016

    
1017
    if (bdrv_set_key(bs, qdict_get_str(qdict, "password")) < 0) {
1018
        qemu_error_new(QERR_INVALID_PASSWORD);
1019
    }
1020
}
1021

    
1022
static void do_change_block(Monitor *mon, const char *device,
1023
                            const char *filename, const char *fmt)
1024
{
1025
    BlockDriverState *bs;
1026
    BlockDriver *drv = NULL;
1027

    
1028
    bs = bdrv_find(device);
1029
    if (!bs) {
1030
        qemu_error_new(QERR_DEVICE_NOT_FOUND, device);
1031
        return;
1032
    }
1033
    if (fmt) {
1034
        drv = bdrv_find_whitelisted_format(fmt);
1035
        if (!drv) {
1036
            qemu_error_new(QERR_INVALID_BLOCK_FORMAT, fmt);
1037
            return;
1038
        }
1039
    }
1040
    if (eject_device(mon, bs, 0) < 0)
1041
        return;
1042
    bdrv_open2(bs, filename, BDRV_O_RDWR, drv);
1043
    monitor_read_bdrv_key_start(mon, bs, NULL, NULL);
1044
}
1045

    
1046
static void change_vnc_password(const char *password)
1047
{
1048
    if (vnc_display_password(NULL, password) < 0)
1049
        qemu_error_new(QERR_SET_PASSWD_FAILED);
1050

    
1051
}
1052

    
1053
static void change_vnc_password_cb(Monitor *mon, const char *password,
1054
                                   void *opaque)
1055
{
1056
    change_vnc_password(password);
1057
    monitor_read_command(mon, 1);
1058
}
1059

    
1060
static void do_change_vnc(Monitor *mon, const char *target, const char *arg)
1061
{
1062
    if (strcmp(target, "passwd") == 0 ||
1063
        strcmp(target, "password") == 0) {
1064
        if (arg) {
1065
            char password[9];
1066
            strncpy(password, arg, sizeof(password));
1067
            password[sizeof(password) - 1] = '\0';
1068
            change_vnc_password(password);
1069
        } else {
1070
            monitor_read_password(mon, change_vnc_password_cb, NULL);
1071
        }
1072
    } else {
1073
        if (vnc_display_open(NULL, target) < 0)
1074
            qemu_error_new(QERR_VNC_SERVER_FAILED, target);
1075
    }
1076
}
1077

    
1078
/**
1079
 * do_change(): Change a removable medium, or VNC configuration
1080
 */
1081
static void do_change(Monitor *mon, const QDict *qdict, QObject **ret_data)
1082
{
1083
    const char *device = qdict_get_str(qdict, "device");
1084
    const char *target = qdict_get_str(qdict, "target");
1085
    const char *arg = qdict_get_try_str(qdict, "arg");
1086
    if (strcmp(device, "vnc") == 0) {
1087
        do_change_vnc(mon, target, arg);
1088
    } else {
1089
        do_change_block(mon, device, target, arg);
1090
    }
1091
}
1092

    
1093
static void do_screen_dump(Monitor *mon, const QDict *qdict)
1094
{
1095
    vga_hw_screen_dump(qdict_get_str(qdict, "filename"));
1096
}
1097

    
1098
static void do_logfile(Monitor *mon, const QDict *qdict)
1099
{
1100
    cpu_set_log_filename(qdict_get_str(qdict, "filename"));
1101
}
1102

    
1103
static void do_log(Monitor *mon, const QDict *qdict)
1104
{
1105
    int mask;
1106
    const char *items = qdict_get_str(qdict, "items");
1107

    
1108
    if (!strcmp(items, "none")) {
1109
        mask = 0;
1110
    } else {
1111
        mask = cpu_str_to_log_mask(items);
1112
        if (!mask) {
1113
            help_cmd(mon, "log");
1114
            return;
1115
        }
1116
    }
1117
    cpu_set_log(mask);
1118
}
1119

    
1120
static void do_singlestep(Monitor *mon, const QDict *qdict)
1121
{
1122
    const char *option = qdict_get_try_str(qdict, "option");
1123
    if (!option || !strcmp(option, "on")) {
1124
        singlestep = 1;
1125
    } else if (!strcmp(option, "off")) {
1126
        singlestep = 0;
1127
    } else {
1128
        monitor_printf(mon, "unexpected option %s\n", option);
1129
    }
1130
}
1131

    
1132
/**
1133
 * do_stop(): Stop VM execution
1134
 */
1135
static int do_stop(Monitor *mon, const QDict *qdict, QObject **ret_data)
1136
{
1137
    vm_stop(EXCP_INTERRUPT);
1138
    return 0;
1139
}
1140

    
1141
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs);
1142

    
1143
struct bdrv_iterate_context {
1144
    Monitor *mon;
1145
    int err;
1146
};
1147

    
1148
/**
1149
 * do_cont(): Resume emulation.
1150
 */
1151
static int do_cont(Monitor *mon, const QDict *qdict, QObject **ret_data)
1152
{
1153
    struct bdrv_iterate_context context = { mon, 0 };
1154

    
1155
    bdrv_iterate(encrypted_bdrv_it, &context);
1156
    /* only resume the vm if all keys are set and valid */
1157
    if (!context.err) {
1158
        vm_start();
1159
        return 0;
1160
    } else {
1161
        return -1;
1162
    }
1163
}
1164

    
1165
static void bdrv_key_cb(void *opaque, int err)
1166
{
1167
    Monitor *mon = opaque;
1168

    
1169
    /* another key was set successfully, retry to continue */
1170
    if (!err)
1171
        do_cont(mon, NULL, NULL);
1172
}
1173

    
1174
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs)
1175
{
1176
    struct bdrv_iterate_context *context = opaque;
1177

    
1178
    if (!context->err && bdrv_key_required(bs)) {
1179
        context->err = -EBUSY;
1180
        monitor_read_bdrv_key_start(context->mon, bs, bdrv_key_cb,
1181
                                    context->mon);
1182
    }
1183
}
1184

    
1185
static void do_gdbserver(Monitor *mon, const QDict *qdict)
1186
{
1187
    const char *device = qdict_get_try_str(qdict, "device");
1188
    if (!device)
1189
        device = "tcp::" DEFAULT_GDBSTUB_PORT;
1190
    if (gdbserver_start(device) < 0) {
1191
        monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1192
                       device);
1193
    } else if (strcmp(device, "none") == 0) {
1194
        monitor_printf(mon, "Disabled gdbserver\n");
1195
    } else {
1196
        monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1197
                       device);
1198
    }
1199
}
1200

    
1201
static void do_watchdog_action(Monitor *mon, const QDict *qdict)
1202
{
1203
    const char *action = qdict_get_str(qdict, "action");
1204
    if (select_watchdog_action(action) == -1) {
1205
        monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1206
    }
1207
}
1208

    
1209
static void monitor_printc(Monitor *mon, int c)
1210
{
1211
    monitor_printf(mon, "'");
1212
    switch(c) {
1213
    case '\'':
1214
        monitor_printf(mon, "\\'");
1215
        break;
1216
    case '\\':
1217
        monitor_printf(mon, "\\\\");
1218
        break;
1219
    case '\n':
1220
        monitor_printf(mon, "\\n");
1221
        break;
1222
    case '\r':
1223
        monitor_printf(mon, "\\r");
1224
        break;
1225
    default:
1226
        if (c >= 32 && c <= 126) {
1227
            monitor_printf(mon, "%c", c);
1228
        } else {
1229
            monitor_printf(mon, "\\x%02x", c);
1230
        }
1231
        break;
1232
    }
1233
    monitor_printf(mon, "'");
1234
}
1235

    
1236
static void memory_dump(Monitor *mon, int count, int format, int wsize,
1237
                        target_phys_addr_t addr, int is_physical)
1238
{
1239
    CPUState *env;
1240
    int l, line_size, i, max_digits, len;
1241
    uint8_t buf[16];
1242
    uint64_t v;
1243

    
1244
    if (format == 'i') {
1245
        int flags;
1246
        flags = 0;
1247
        env = mon_get_cpu();
1248
        if (!is_physical)
1249
            return;
1250
#ifdef TARGET_I386
1251
        if (wsize == 2) {
1252
            flags = 1;
1253
        } else if (wsize == 4) {
1254
            flags = 0;
1255
        } else {
1256
            /* as default we use the current CS size */
1257
            flags = 0;
1258
            if (env) {
1259
#ifdef TARGET_X86_64
1260
                if ((env->efer & MSR_EFER_LMA) &&
1261
                    (env->segs[R_CS].flags & DESC_L_MASK))
1262
                    flags = 2;
1263
                else
1264
#endif
1265
                if (!(env->segs[R_CS].flags & DESC_B_MASK))
1266
                    flags = 1;
1267
            }
1268
        }
1269
#endif
1270
        monitor_disas(mon, env, addr, count, is_physical, flags);
1271
        return;
1272
    }
1273

    
1274
    len = wsize * count;
1275
    if (wsize == 1)
1276
        line_size = 8;
1277
    else
1278
        line_size = 16;
1279
    max_digits = 0;
1280

    
1281
    switch(format) {
1282
    case 'o':
1283
        max_digits = (wsize * 8 + 2) / 3;
1284
        break;
1285
    default:
1286
    case 'x':
1287
        max_digits = (wsize * 8) / 4;
1288
        break;
1289
    case 'u':
1290
    case 'd':
1291
        max_digits = (wsize * 8 * 10 + 32) / 33;
1292
        break;
1293
    case 'c':
1294
        wsize = 1;
1295
        break;
1296
    }
1297

    
1298
    while (len > 0) {
1299
        if (is_physical)
1300
            monitor_printf(mon, TARGET_FMT_plx ":", addr);
1301
        else
1302
            monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1303
        l = len;
1304
        if (l > line_size)
1305
            l = line_size;
1306
        if (is_physical) {
1307
            cpu_physical_memory_rw(addr, buf, l, 0);
1308
        } else {
1309
            env = mon_get_cpu();
1310
            if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {
1311
                monitor_printf(mon, " Cannot access memory\n");
1312
                break;
1313
            }
1314
        }
1315
        i = 0;
1316
        while (i < l) {
1317
            switch(wsize) {
1318
            default:
1319
            case 1:
1320
                v = ldub_raw(buf + i);
1321
                break;
1322
            case 2:
1323
                v = lduw_raw(buf + i);
1324
                break;
1325
            case 4:
1326
                v = (uint32_t)ldl_raw(buf + i);
1327
                break;
1328
            case 8:
1329
                v = ldq_raw(buf + i);
1330
                break;
1331
            }
1332
            monitor_printf(mon, " ");
1333
            switch(format) {
1334
            case 'o':
1335
                monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1336
                break;
1337
            case 'x':
1338
                monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1339
                break;
1340
            case 'u':
1341
                monitor_printf(mon, "%*" PRIu64, max_digits, v);
1342
                break;
1343
            case 'd':
1344
                monitor_printf(mon, "%*" PRId64, max_digits, v);
1345
                break;
1346
            case 'c':
1347
                monitor_printc(mon, v);
1348
                break;
1349
            }
1350
            i += wsize;
1351
        }
1352
        monitor_printf(mon, "\n");
1353
        addr += l;
1354
        len -= l;
1355
    }
1356
}
1357

    
1358
static void do_memory_dump(Monitor *mon, const QDict *qdict)
1359
{
1360
    int count = qdict_get_int(qdict, "count");
1361
    int format = qdict_get_int(qdict, "format");
1362
    int size = qdict_get_int(qdict, "size");
1363
    target_long addr = qdict_get_int(qdict, "addr");
1364

    
1365
    memory_dump(mon, count, format, size, addr, 0);
1366
}
1367

    
1368
static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
1369
{
1370
    int count = qdict_get_int(qdict, "count");
1371
    int format = qdict_get_int(qdict, "format");
1372
    int size = qdict_get_int(qdict, "size");
1373
    target_phys_addr_t addr = qdict_get_int(qdict, "addr");
1374

    
1375
    memory_dump(mon, count, format, size, addr, 1);
1376
}
1377

    
1378
static void do_print(Monitor *mon, const QDict *qdict)
1379
{
1380
    int format = qdict_get_int(qdict, "format");
1381
    target_phys_addr_t val = qdict_get_int(qdict, "val");
1382

    
1383
#if TARGET_PHYS_ADDR_BITS == 32
1384
    switch(format) {
1385
    case 'o':
1386
        monitor_printf(mon, "%#o", val);
1387
        break;
1388
    case 'x':
1389
        monitor_printf(mon, "%#x", val);
1390
        break;
1391
    case 'u':
1392
        monitor_printf(mon, "%u", val);
1393
        break;
1394
    default:
1395
    case 'd':
1396
        monitor_printf(mon, "%d", val);
1397
        break;
1398
    case 'c':
1399
        monitor_printc(mon, val);
1400
        break;
1401
    }
1402
#else
1403
    switch(format) {
1404
    case 'o':
1405
        monitor_printf(mon, "%#" PRIo64, val);
1406
        break;
1407
    case 'x':
1408
        monitor_printf(mon, "%#" PRIx64, val);
1409
        break;
1410
    case 'u':
1411
        monitor_printf(mon, "%" PRIu64, val);
1412
        break;
1413
    default:
1414
    case 'd':
1415
        monitor_printf(mon, "%" PRId64, val);
1416
        break;
1417
    case 'c':
1418
        monitor_printc(mon, val);
1419
        break;
1420
    }
1421
#endif
1422
    monitor_printf(mon, "\n");
1423
}
1424

    
1425
static void do_memory_save(Monitor *mon, const QDict *qdict, QObject **ret_data)
1426
{
1427
    FILE *f;
1428
    uint32_t size = qdict_get_int(qdict, "size");
1429
    const char *filename = qdict_get_str(qdict, "filename");
1430
    target_long addr = qdict_get_int(qdict, "val");
1431
    uint32_t l;
1432
    CPUState *env;
1433
    uint8_t buf[1024];
1434

    
1435
    env = mon_get_cpu();
1436

    
1437
    f = fopen(filename, "wb");
1438
    if (!f) {
1439
        qemu_error_new(QERR_OPEN_FILE_FAILED, filename);
1440
        return;
1441
    }
1442
    while (size != 0) {
1443
        l = sizeof(buf);
1444
        if (l > size)
1445
            l = size;
1446
        cpu_memory_rw_debug(env, addr, buf, l, 0);
1447
        if (fwrite(buf, 1, l, f) != l) {
1448
            monitor_printf(mon, "fwrite() error in do_memory_save\n");
1449
            goto exit;
1450
        }
1451
        addr += l;
1452
        size -= l;
1453
    }
1454
exit:
1455
    fclose(f);
1456
}
1457

    
1458
static void do_physical_memory_save(Monitor *mon, const QDict *qdict,
1459
                                    QObject **ret_data)
1460
{
1461
    FILE *f;
1462
    uint32_t l;
1463
    uint8_t buf[1024];
1464
    uint32_t size = qdict_get_int(qdict, "size");
1465
    const char *filename = qdict_get_str(qdict, "filename");
1466
    target_phys_addr_t addr = qdict_get_int(qdict, "val");
1467

    
1468
    f = fopen(filename, "wb");
1469
    if (!f) {
1470
        qemu_error_new(QERR_OPEN_FILE_FAILED, filename);
1471
        return;
1472
    }
1473
    while (size != 0) {
1474
        l = sizeof(buf);
1475
        if (l > size)
1476
            l = size;
1477
        cpu_physical_memory_rw(addr, buf, l, 0);
1478
        if (fwrite(buf, 1, l, f) != l) {
1479
            monitor_printf(mon, "fwrite() error in do_physical_memory_save\n");
1480
            goto exit;
1481
        }
1482
        fflush(f);
1483
        addr += l;
1484
        size -= l;
1485
    }
1486
exit:
1487
    fclose(f);
1488
}
1489

    
1490
static void do_sum(Monitor *mon, const QDict *qdict)
1491
{
1492
    uint32_t addr;
1493
    uint8_t buf[1];
1494
    uint16_t sum;
1495
    uint32_t start = qdict_get_int(qdict, "start");
1496
    uint32_t size = qdict_get_int(qdict, "size");
1497

    
1498
    sum = 0;
1499
    for(addr = start; addr < (start + size); addr++) {
1500
        cpu_physical_memory_rw(addr, buf, 1, 0);
1501
        /* BSD sum algorithm ('sum' Unix command) */
1502
        sum = (sum >> 1) | (sum << 15);
1503
        sum += buf[0];
1504
    }
1505
    monitor_printf(mon, "%05d\n", sum);
1506
}
1507

    
1508
typedef struct {
1509
    int keycode;
1510
    const char *name;
1511
} KeyDef;
1512

    
1513
static const KeyDef key_defs[] = {
1514
    { 0x2a, "shift" },
1515
    { 0x36, "shift_r" },
1516

    
1517
    { 0x38, "alt" },
1518
    { 0xb8, "alt_r" },
1519
    { 0x64, "altgr" },
1520
    { 0xe4, "altgr_r" },
1521
    { 0x1d, "ctrl" },
1522
    { 0x9d, "ctrl_r" },
1523

    
1524
    { 0xdd, "menu" },
1525

    
1526
    { 0x01, "esc" },
1527

    
1528
    { 0x02, "1" },
1529
    { 0x03, "2" },
1530
    { 0x04, "3" },
1531
    { 0x05, "4" },
1532
    { 0x06, "5" },
1533
    { 0x07, "6" },
1534
    { 0x08, "7" },
1535
    { 0x09, "8" },
1536
    { 0x0a, "9" },
1537
    { 0x0b, "0" },
1538
    { 0x0c, "minus" },
1539
    { 0x0d, "equal" },
1540
    { 0x0e, "backspace" },
1541

    
1542
    { 0x0f, "tab" },
1543
    { 0x10, "q" },
1544
    { 0x11, "w" },
1545
    { 0x12, "e" },
1546
    { 0x13, "r" },
1547
    { 0x14, "t" },
1548
    { 0x15, "y" },
1549
    { 0x16, "u" },
1550
    { 0x17, "i" },
1551
    { 0x18, "o" },
1552
    { 0x19, "p" },
1553

    
1554
    { 0x1c, "ret" },
1555

    
1556
    { 0x1e, "a" },
1557
    { 0x1f, "s" },
1558
    { 0x20, "d" },
1559
    { 0x21, "f" },
1560
    { 0x22, "g" },
1561
    { 0x23, "h" },
1562
    { 0x24, "j" },
1563
    { 0x25, "k" },
1564
    { 0x26, "l" },
1565

    
1566
    { 0x2c, "z" },
1567
    { 0x2d, "x" },
1568
    { 0x2e, "c" },
1569
    { 0x2f, "v" },
1570
    { 0x30, "b" },
1571
    { 0x31, "n" },
1572
    { 0x32, "m" },
1573
    { 0x33, "comma" },
1574
    { 0x34, "dot" },
1575
    { 0x35, "slash" },
1576

    
1577
    { 0x37, "asterisk" },
1578

    
1579
    { 0x39, "spc" },
1580
    { 0x3a, "caps_lock" },
1581
    { 0x3b, "f1" },
1582
    { 0x3c, "f2" },
1583
    { 0x3d, "f3" },
1584
    { 0x3e, "f4" },
1585
    { 0x3f, "f5" },
1586
    { 0x40, "f6" },
1587
    { 0x41, "f7" },
1588
    { 0x42, "f8" },
1589
    { 0x43, "f9" },
1590
    { 0x44, "f10" },
1591
    { 0x45, "num_lock" },
1592
    { 0x46, "scroll_lock" },
1593

    
1594
    { 0xb5, "kp_divide" },
1595
    { 0x37, "kp_multiply" },
1596
    { 0x4a, "kp_subtract" },
1597
    { 0x4e, "kp_add" },
1598
    { 0x9c, "kp_enter" },
1599
    { 0x53, "kp_decimal" },
1600
    { 0x54, "sysrq" },
1601

    
1602
    { 0x52, "kp_0" },
1603
    { 0x4f, "kp_1" },
1604
    { 0x50, "kp_2" },
1605
    { 0x51, "kp_3" },
1606
    { 0x4b, "kp_4" },
1607
    { 0x4c, "kp_5" },
1608
    { 0x4d, "kp_6" },
1609
    { 0x47, "kp_7" },
1610
    { 0x48, "kp_8" },
1611
    { 0x49, "kp_9" },
1612

    
1613
    { 0x56, "<" },
1614

    
1615
    { 0x57, "f11" },
1616
    { 0x58, "f12" },
1617

    
1618
    { 0xb7, "print" },
1619

    
1620
    { 0xc7, "home" },
1621
    { 0xc9, "pgup" },
1622
    { 0xd1, "pgdn" },
1623
    { 0xcf, "end" },
1624

    
1625
    { 0xcb, "left" },
1626
    { 0xc8, "up" },
1627
    { 0xd0, "down" },
1628
    { 0xcd, "right" },
1629

    
1630
    { 0xd2, "insert" },
1631
    { 0xd3, "delete" },
1632
#if defined(TARGET_SPARC) && !defined(TARGET_SPARC64)
1633
    { 0xf0, "stop" },
1634
    { 0xf1, "again" },
1635
    { 0xf2, "props" },
1636
    { 0xf3, "undo" },
1637
    { 0xf4, "front" },
1638
    { 0xf5, "copy" },
1639
    { 0xf6, "open" },
1640
    { 0xf7, "paste" },
1641
    { 0xf8, "find" },
1642
    { 0xf9, "cut" },
1643
    { 0xfa, "lf" },
1644
    { 0xfb, "help" },
1645
    { 0xfc, "meta_l" },
1646
    { 0xfd, "meta_r" },
1647
    { 0xfe, "compose" },
1648
#endif
1649
    { 0, NULL },
1650
};
1651

    
1652
static int get_keycode(const char *key)
1653
{
1654
    const KeyDef *p;
1655
    char *endp;
1656
    int ret;
1657

    
1658
    for(p = key_defs; p->name != NULL; p++) {
1659
        if (!strcmp(key, p->name))
1660
            return p->keycode;
1661
    }
1662
    if (strstart(key, "0x", NULL)) {
1663
        ret = strtoul(key, &endp, 0);
1664
        if (*endp == '\0' && ret >= 0x01 && ret <= 0xff)
1665
            return ret;
1666
    }
1667
    return -1;
1668
}
1669

    
1670
#define MAX_KEYCODES 16
1671
static uint8_t keycodes[MAX_KEYCODES];
1672
static int nb_pending_keycodes;
1673
static QEMUTimer *key_timer;
1674

    
1675
static void release_keys(void *opaque)
1676
{
1677
    int keycode;
1678

    
1679
    while (nb_pending_keycodes > 0) {
1680
        nb_pending_keycodes--;
1681
        keycode = keycodes[nb_pending_keycodes];
1682
        if (keycode & 0x80)
1683
            kbd_put_keycode(0xe0);
1684
        kbd_put_keycode(keycode | 0x80);
1685
    }
1686
}
1687

    
1688
static void do_sendkey(Monitor *mon, const QDict *qdict)
1689
{
1690
    char keyname_buf[16];
1691
    char *separator;
1692
    int keyname_len, keycode, i;
1693
    const char *string = qdict_get_str(qdict, "string");
1694
    int has_hold_time = qdict_haskey(qdict, "hold_time");
1695
    int hold_time = qdict_get_try_int(qdict, "hold_time", -1);
1696

    
1697
    if (nb_pending_keycodes > 0) {
1698
        qemu_del_timer(key_timer);
1699
        release_keys(NULL);
1700
    }
1701
    if (!has_hold_time)
1702
        hold_time = 100;
1703
    i = 0;
1704
    while (1) {
1705
        separator = strchr(string, '-');
1706
        keyname_len = separator ? separator - string : strlen(string);
1707
        if (keyname_len > 0) {
1708
            pstrcpy(keyname_buf, sizeof(keyname_buf), string);
1709
            if (keyname_len > sizeof(keyname_buf) - 1) {
1710
                monitor_printf(mon, "invalid key: '%s...'\n", keyname_buf);
1711
                return;
1712
            }
1713
            if (i == MAX_KEYCODES) {
1714
                monitor_printf(mon, "too many keys\n");
1715
                return;
1716
            }
1717
            keyname_buf[keyname_len] = 0;
1718
            keycode = get_keycode(keyname_buf);
1719
            if (keycode < 0) {
1720
                monitor_printf(mon, "unknown key: '%s'\n", keyname_buf);
1721
                return;
1722
            }
1723
            keycodes[i++] = keycode;
1724
        }
1725
        if (!separator)
1726
            break;
1727
        string = separator + 1;
1728
    }
1729
    nb_pending_keycodes = i;
1730
    /* key down events */
1731
    for (i = 0; i < nb_pending_keycodes; i++) {
1732
        keycode = keycodes[i];
1733
        if (keycode & 0x80)
1734
            kbd_put_keycode(0xe0);
1735
        kbd_put_keycode(keycode & 0x7f);
1736
    }
1737
    /* delayed key up events */
1738
    qemu_mod_timer(key_timer, qemu_get_clock(vm_clock) +
1739
                   muldiv64(get_ticks_per_sec(), hold_time, 1000));
1740
}
1741

    
1742
static int mouse_button_state;
1743

    
1744
static void do_mouse_move(Monitor *mon, const QDict *qdict)
1745
{
1746
    int dx, dy, dz;
1747
    const char *dx_str = qdict_get_str(qdict, "dx_str");
1748
    const char *dy_str = qdict_get_str(qdict, "dy_str");
1749
    const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1750
    dx = strtol(dx_str, NULL, 0);
1751
    dy = strtol(dy_str, NULL, 0);
1752
    dz = 0;
1753
    if (dz_str)
1754
        dz = strtol(dz_str, NULL, 0);
1755
    kbd_mouse_event(dx, dy, dz, mouse_button_state);
1756
}
1757

    
1758
static void do_mouse_button(Monitor *mon, const QDict *qdict)
1759
{
1760
    int button_state = qdict_get_int(qdict, "button_state");
1761
    mouse_button_state = button_state;
1762
    kbd_mouse_event(0, 0, 0, mouse_button_state);
1763
}
1764

    
1765
static void do_ioport_read(Monitor *mon, const QDict *qdict)
1766
{
1767
    int size = qdict_get_int(qdict, "size");
1768
    int addr = qdict_get_int(qdict, "addr");
1769
    int has_index = qdict_haskey(qdict, "index");
1770
    uint32_t val;
1771
    int suffix;
1772

    
1773
    if (has_index) {
1774
        int index = qdict_get_int(qdict, "index");
1775
        cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1776
        addr++;
1777
    }
1778
    addr &= 0xffff;
1779

    
1780
    switch(size) {
1781
    default:
1782
    case 1:
1783
        val = cpu_inb(addr);
1784
        suffix = 'b';
1785
        break;
1786
    case 2:
1787
        val = cpu_inw(addr);
1788
        suffix = 'w';
1789
        break;
1790
    case 4:
1791
        val = cpu_inl(addr);
1792
        suffix = 'l';
1793
        break;
1794
    }
1795
    monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1796
                   suffix, addr, size * 2, val);
1797
}
1798

    
1799
static void do_ioport_write(Monitor *mon, const QDict *qdict)
1800
{
1801
    int size = qdict_get_int(qdict, "size");
1802
    int addr = qdict_get_int(qdict, "addr");
1803
    int val = qdict_get_int(qdict, "val");
1804

    
1805
    addr &= IOPORTS_MASK;
1806

    
1807
    switch (size) {
1808
    default:
1809
    case 1:
1810
        cpu_outb(addr, val);
1811
        break;
1812
    case 2:
1813
        cpu_outw(addr, val);
1814
        break;
1815
    case 4:
1816
        cpu_outl(addr, val);
1817
        break;
1818
    }
1819
}
1820

    
1821
static void do_boot_set(Monitor *mon, const QDict *qdict)
1822
{
1823
    int res;
1824
    const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1825

    
1826
    res = qemu_boot_set(bootdevice);
1827
    if (res == 0) {
1828
        monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1829
    } else if (res > 0) {
1830
        monitor_printf(mon, "setting boot device list failed\n");
1831
    } else {
1832
        monitor_printf(mon, "no function defined to set boot device list for "
1833
                       "this architecture\n");
1834
    }
1835
}
1836

    
1837
/**
1838
 * do_system_reset(): Issue a machine reset
1839
 */
1840
static int do_system_reset(Monitor *mon, const QDict *qdict,
1841
                           QObject **ret_data)
1842
{
1843
    qemu_system_reset_request();
1844
    return 0;
1845
}
1846

    
1847
/**
1848
 * do_system_powerdown(): Issue a machine powerdown
1849
 */
1850
static int do_system_powerdown(Monitor *mon, const QDict *qdict,
1851
                               QObject **ret_data)
1852
{
1853
    qemu_system_powerdown_request();
1854
    return 0;
1855
}
1856

    
1857
#if defined(TARGET_I386)
1858
static void print_pte(Monitor *mon, uint32_t addr, uint32_t pte, uint32_t mask)
1859
{
1860
    monitor_printf(mon, "%08x: %08x %c%c%c%c%c%c%c%c\n",
1861
                   addr,
1862
                   pte & mask,
1863
                   pte & PG_GLOBAL_MASK ? 'G' : '-',
1864
                   pte & PG_PSE_MASK ? 'P' : '-',
1865
                   pte & PG_DIRTY_MASK ? 'D' : '-',
1866
                   pte & PG_ACCESSED_MASK ? 'A' : '-',
1867
                   pte & PG_PCD_MASK ? 'C' : '-',
1868
                   pte & PG_PWT_MASK ? 'T' : '-',
1869
                   pte & PG_USER_MASK ? 'U' : '-',
1870
                   pte & PG_RW_MASK ? 'W' : '-');
1871
}
1872

    
1873
static void tlb_info(Monitor *mon)
1874
{
1875
    CPUState *env;
1876
    int l1, l2;
1877
    uint32_t pgd, pde, pte;
1878

    
1879
    env = mon_get_cpu();
1880

    
1881
    if (!(env->cr[0] & CR0_PG_MASK)) {
1882
        monitor_printf(mon, "PG disabled\n");
1883
        return;
1884
    }
1885
    pgd = env->cr[3] & ~0xfff;
1886
    for(l1 = 0; l1 < 1024; l1++) {
1887
        cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1888
        pde = le32_to_cpu(pde);
1889
        if (pde & PG_PRESENT_MASK) {
1890
            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1891
                print_pte(mon, (l1 << 22), pde, ~((1 << 20) - 1));
1892
            } else {
1893
                for(l2 = 0; l2 < 1024; l2++) {
1894
                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1895
                                             (uint8_t *)&pte, 4);
1896
                    pte = le32_to_cpu(pte);
1897
                    if (pte & PG_PRESENT_MASK) {
1898
                        print_pte(mon, (l1 << 22) + (l2 << 12),
1899
                                  pte & ~PG_PSE_MASK,
1900
                                  ~0xfff);
1901
                    }
1902
                }
1903
            }
1904
        }
1905
    }
1906
}
1907

    
1908
static void mem_print(Monitor *mon, uint32_t *pstart, int *plast_prot,
1909
                      uint32_t end, int prot)
1910
{
1911
    int prot1;
1912
    prot1 = *plast_prot;
1913
    if (prot != prot1) {
1914
        if (*pstart != -1) {
1915
            monitor_printf(mon, "%08x-%08x %08x %c%c%c\n",
1916
                           *pstart, end, end - *pstart,
1917
                           prot1 & PG_USER_MASK ? 'u' : '-',
1918
                           'r',
1919
                           prot1 & PG_RW_MASK ? 'w' : '-');
1920
        }
1921
        if (prot != 0)
1922
            *pstart = end;
1923
        else
1924
            *pstart = -1;
1925
        *plast_prot = prot;
1926
    }
1927
}
1928

    
1929
static void mem_info(Monitor *mon)
1930
{
1931
    CPUState *env;
1932
    int l1, l2, prot, last_prot;
1933
    uint32_t pgd, pde, pte, start, end;
1934

    
1935
    env = mon_get_cpu();
1936

    
1937
    if (!(env->cr[0] & CR0_PG_MASK)) {
1938
        monitor_printf(mon, "PG disabled\n");
1939
        return;
1940
    }
1941
    pgd = env->cr[3] & ~0xfff;
1942
    last_prot = 0;
1943
    start = -1;
1944
    for(l1 = 0; l1 < 1024; l1++) {
1945
        cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1946
        pde = le32_to_cpu(pde);
1947
        end = l1 << 22;
1948
        if (pde & PG_PRESENT_MASK) {
1949
            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1950
                prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1951
                mem_print(mon, &start, &last_prot, end, prot);
1952
            } else {
1953
                for(l2 = 0; l2 < 1024; l2++) {
1954
                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1955
                                             (uint8_t *)&pte, 4);
1956
                    pte = le32_to_cpu(pte);
1957
                    end = (l1 << 22) + (l2 << 12);
1958
                    if (pte & PG_PRESENT_MASK) {
1959
                        prot = pte & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1960
                    } else {
1961
                        prot = 0;
1962
                    }
1963
                    mem_print(mon, &start, &last_prot, end, prot);
1964
                }
1965
            }
1966
        } else {
1967
            prot = 0;
1968
            mem_print(mon, &start, &last_prot, end, prot);
1969
        }
1970
    }
1971
}
1972
#endif
1973

    
1974
#if defined(TARGET_SH4)
1975

    
1976
static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1977
{
1978
    monitor_printf(mon, " tlb%i:\t"
1979
                   "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1980
                   "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1981
                   "dirty=%hhu writethrough=%hhu\n",
1982
                   idx,
1983
                   tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1984
                   tlb->v, tlb->sh, tlb->c, tlb->pr,
1985
                   tlb->d, tlb->wt);
1986
}
1987

    
1988
static void tlb_info(Monitor *mon)
1989
{
1990
    CPUState *env = mon_get_cpu();
1991
    int i;
1992

    
1993
    monitor_printf (mon, "ITLB:\n");
1994
    for (i = 0 ; i < ITLB_SIZE ; i++)
1995
        print_tlb (mon, i, &env->itlb[i]);
1996
    monitor_printf (mon, "UTLB:\n");
1997
    for (i = 0 ; i < UTLB_SIZE ; i++)
1998
        print_tlb (mon, i, &env->utlb[i]);
1999
}
2000

    
2001
#endif
2002

    
2003
static void do_info_kvm_print(Monitor *mon, const QObject *data)
2004
{
2005
    QDict *qdict;
2006

    
2007
    qdict = qobject_to_qdict(data);
2008

    
2009
    monitor_printf(mon, "kvm support: ");
2010
    if (qdict_get_bool(qdict, "present")) {
2011
        monitor_printf(mon, "%s\n", qdict_get_bool(qdict, "enabled") ?
2012
                                    "enabled" : "disabled");
2013
    } else {
2014
        monitor_printf(mon, "not compiled\n");
2015
    }
2016
}
2017

    
2018
/**
2019
 * do_info_kvm(): Show KVM information
2020
 *
2021
 * Return a QDict with the following information:
2022
 *
2023
 * - "enabled": true if KVM support is enabled, false otherwise
2024
 * - "present": true if QEMU has KVM support, false otherwise
2025
 *
2026
 * Example:
2027
 *
2028
 * { "enabled": true, "present": true }
2029
 */
2030
static void do_info_kvm(Monitor *mon, QObject **ret_data)
2031
{
2032
#ifdef CONFIG_KVM
2033
    *ret_data = qobject_from_jsonf("{ 'enabled': %i, 'present': true }",
2034
                                   kvm_enabled());
2035
#else
2036
    *ret_data = qobject_from_jsonf("{ 'enabled': false, 'present': false }");
2037
#endif
2038
}
2039

    
2040
static void do_info_numa(Monitor *mon)
2041
{
2042
    int i;
2043
    CPUState *env;
2044

    
2045
    monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
2046
    for (i = 0; i < nb_numa_nodes; i++) {
2047
        monitor_printf(mon, "node %d cpus:", i);
2048
        for (env = first_cpu; env != NULL; env = env->next_cpu) {
2049
            if (env->numa_node == i) {
2050
                monitor_printf(mon, " %d", env->cpu_index);
2051
            }
2052
        }
2053
        monitor_printf(mon, "\n");
2054
        monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
2055
            node_mem[i] >> 20);
2056
    }
2057
}
2058

    
2059
#ifdef CONFIG_PROFILER
2060

    
2061
int64_t qemu_time;
2062
int64_t dev_time;
2063

    
2064
static void do_info_profile(Monitor *mon)
2065
{
2066
    int64_t total;
2067
    total = qemu_time;
2068
    if (total == 0)
2069
        total = 1;
2070
    monitor_printf(mon, "async time  %" PRId64 " (%0.3f)\n",
2071
                   dev_time, dev_time / (double)get_ticks_per_sec());
2072
    monitor_printf(mon, "qemu time   %" PRId64 " (%0.3f)\n",
2073
                   qemu_time, qemu_time / (double)get_ticks_per_sec());
2074
    qemu_time = 0;
2075
    dev_time = 0;
2076
}
2077
#else
2078
static void do_info_profile(Monitor *mon)
2079
{
2080
    monitor_printf(mon, "Internal profiler not compiled\n");
2081
}
2082
#endif
2083

    
2084
/* Capture support */
2085
static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2086

    
2087
static void do_info_capture(Monitor *mon)
2088
{
2089
    int i;
2090
    CaptureState *s;
2091

    
2092
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2093
        monitor_printf(mon, "[%d]: ", i);
2094
        s->ops.info (s->opaque);
2095
    }
2096
}
2097

    
2098
#ifdef HAS_AUDIO
2099
static void do_stop_capture(Monitor *mon, const QDict *qdict)
2100
{
2101
    int i;
2102
    int n = qdict_get_int(qdict, "n");
2103
    CaptureState *s;
2104

    
2105
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2106
        if (i == n) {
2107
            s->ops.destroy (s->opaque);
2108
            QLIST_REMOVE (s, entries);
2109
            qemu_free (s);
2110
            return;
2111
        }
2112
    }
2113
}
2114

    
2115
static void do_wav_capture(Monitor *mon, const QDict *qdict)
2116
{
2117
    const char *path = qdict_get_str(qdict, "path");
2118
    int has_freq = qdict_haskey(qdict, "freq");
2119
    int freq = qdict_get_try_int(qdict, "freq", -1);
2120
    int has_bits = qdict_haskey(qdict, "bits");
2121
    int bits = qdict_get_try_int(qdict, "bits", -1);
2122
    int has_channels = qdict_haskey(qdict, "nchannels");
2123
    int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2124
    CaptureState *s;
2125

    
2126
    s = qemu_mallocz (sizeof (*s));
2127

    
2128
    freq = has_freq ? freq : 44100;
2129
    bits = has_bits ? bits : 16;
2130
    nchannels = has_channels ? nchannels : 2;
2131

    
2132
    if (wav_start_capture (s, path, freq, bits, nchannels)) {
2133
        monitor_printf(mon, "Faied to add wave capture\n");
2134
        qemu_free (s);
2135
    }
2136
    QLIST_INSERT_HEAD (&capture_head, s, entries);
2137
}
2138
#endif
2139

    
2140
#if defined(TARGET_I386)
2141
static void do_inject_nmi(Monitor *mon, const QDict *qdict)
2142
{
2143
    CPUState *env;
2144
    int cpu_index = qdict_get_int(qdict, "cpu_index");
2145

    
2146
    for (env = first_cpu; env != NULL; env = env->next_cpu)
2147
        if (env->cpu_index == cpu_index) {
2148
            cpu_interrupt(env, CPU_INTERRUPT_NMI);
2149
            break;
2150
        }
2151
}
2152
#endif
2153

    
2154
static void do_info_status_print(Monitor *mon, const QObject *data)
2155
{
2156
    QDict *qdict;
2157

    
2158
    qdict = qobject_to_qdict(data);
2159

    
2160
    monitor_printf(mon, "VM status: ");
2161
    if (qdict_get_bool(qdict, "running")) {
2162
        monitor_printf(mon, "running");
2163
        if (qdict_get_bool(qdict, "singlestep")) {
2164
            monitor_printf(mon, " (single step mode)");
2165
        }
2166
    } else {
2167
        monitor_printf(mon, "paused");
2168
    }
2169

    
2170
    monitor_printf(mon, "\n");
2171
}
2172

    
2173
/**
2174
 * do_info_status(): VM status
2175
 *
2176
 * Return a QDict with the following information:
2177
 *
2178
 * - "running": true if the VM is running, or false if it is paused
2179
 * - "singlestep": true if the VM is in single step mode, false otherwise
2180
 *
2181
 * Example:
2182
 *
2183
 * { "running": true, "singlestep": false }
2184
 */
2185
static void do_info_status(Monitor *mon, QObject **ret_data)
2186
{
2187
    *ret_data = qobject_from_jsonf("{ 'running': %i, 'singlestep': %i }",
2188
                                    vm_running, singlestep);
2189
}
2190

    
2191
static void print_balloon_stat(const char *key, QObject *obj, void *opaque)
2192
{
2193
    Monitor *mon = opaque;
2194

    
2195
    if (strcmp(key, "actual"))
2196
        monitor_printf(mon, ",%s=%" PRId64, key,
2197
                       qint_get_int(qobject_to_qint(obj)));
2198
}
2199

    
2200
static void monitor_print_balloon(Monitor *mon, const QObject *data)
2201
{
2202
    QDict *qdict;
2203

    
2204
    qdict = qobject_to_qdict(data);
2205
    if (!qdict_haskey(qdict, "actual"))
2206
        return;
2207

    
2208
    monitor_printf(mon, "balloon: actual=%" PRId64,
2209
                   qdict_get_int(qdict, "actual") >> 20);
2210
    qdict_iter(qdict, print_balloon_stat, mon);
2211
    monitor_printf(mon, "\n");
2212
}
2213

    
2214
/**
2215
 * do_info_balloon(): Balloon information
2216
 *
2217
 * Make an asynchronous request for balloon info.  When the request completes
2218
 * a QDict will be returned according to the following specification:
2219
 *
2220
 * - "actual": current balloon value in bytes
2221
 * The following fields may or may not be present:
2222
 * - "mem_swapped_in": Amount of memory swapped in (bytes)
2223
 * - "mem_swapped_out": Amount of memory swapped out (bytes)
2224
 * - "major_page_faults": Number of major faults
2225
 * - "minor_page_faults": Number of minor faults
2226
 * - "free_mem": Total amount of free and unused memory (bytes)
2227
 * - "total_mem": Total amount of available memory (bytes)
2228
 *
2229
 * Example:
2230
 *
2231
 * { "actual": 1073741824, "mem_swapped_in": 0, "mem_swapped_out": 0,
2232
 *   "major_page_faults": 142, "minor_page_faults": 239245,
2233
 *   "free_mem": 1014185984, "total_mem": 1044668416 }
2234
 */
2235
static int do_info_balloon(Monitor *mon, MonitorCompletion cb, void *opaque)
2236
{
2237
    int ret;
2238

    
2239
    if (kvm_enabled() && !kvm_has_sync_mmu()) {
2240
        qemu_error_new(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
2241
        return -1;
2242
    }
2243

    
2244
    ret = qemu_balloon_status(cb, opaque);
2245
    if (!ret) {
2246
        qemu_error_new(QERR_DEVICE_NOT_ACTIVE, "balloon");
2247
        return -1;
2248
    }
2249

    
2250
    return 0;
2251
}
2252

    
2253
/**
2254
 * do_balloon(): Request VM to change its memory allocation
2255
 */
2256
static int do_balloon(Monitor *mon, const QDict *params,
2257
                       MonitorCompletion cb, void *opaque)
2258
{
2259
    int ret;
2260

    
2261
    if (kvm_enabled() && !kvm_has_sync_mmu()) {
2262
        qemu_error_new(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
2263
        return -1;
2264
    }
2265

    
2266
    ret = qemu_balloon(qdict_get_int(params, "value"), cb, opaque);
2267
    if (ret == 0) {
2268
        qemu_error_new(QERR_DEVICE_NOT_ACTIVE, "balloon");
2269
        return -1;
2270
    }
2271

    
2272
    return 0;
2273
}
2274

    
2275
static qemu_acl *find_acl(Monitor *mon, const char *name)
2276
{
2277
    qemu_acl *acl = qemu_acl_find(name);
2278

    
2279
    if (!acl) {
2280
        monitor_printf(mon, "acl: unknown list '%s'\n", name);
2281
    }
2282
    return acl;
2283
}
2284

    
2285
static void do_acl_show(Monitor *mon, const QDict *qdict)
2286
{
2287
    const char *aclname = qdict_get_str(qdict, "aclname");
2288
    qemu_acl *acl = find_acl(mon, aclname);
2289
    qemu_acl_entry *entry;
2290
    int i = 0;
2291

    
2292
    if (acl) {
2293
        monitor_printf(mon, "policy: %s\n",
2294
                       acl->defaultDeny ? "deny" : "allow");
2295
        QTAILQ_FOREACH(entry, &acl->entries, next) {
2296
            i++;
2297
            monitor_printf(mon, "%d: %s %s\n", i,
2298
                           entry->deny ? "deny" : "allow", entry->match);
2299
        }
2300
    }
2301
}
2302

    
2303
static void do_acl_reset(Monitor *mon, const QDict *qdict)
2304
{
2305
    const char *aclname = qdict_get_str(qdict, "aclname");
2306
    qemu_acl *acl = find_acl(mon, aclname);
2307

    
2308
    if (acl) {
2309
        qemu_acl_reset(acl);
2310
        monitor_printf(mon, "acl: removed all rules\n");
2311
    }
2312
}
2313

    
2314
static void do_acl_policy(Monitor *mon, const QDict *qdict)
2315
{
2316
    const char *aclname = qdict_get_str(qdict, "aclname");
2317
    const char *policy = qdict_get_str(qdict, "policy");
2318
    qemu_acl *acl = find_acl(mon, aclname);
2319

    
2320
    if (acl) {
2321
        if (strcmp(policy, "allow") == 0) {
2322
            acl->defaultDeny = 0;
2323
            monitor_printf(mon, "acl: policy set to 'allow'\n");
2324
        } else if (strcmp(policy, "deny") == 0) {
2325
            acl->defaultDeny = 1;
2326
            monitor_printf(mon, "acl: policy set to 'deny'\n");
2327
        } else {
2328
            monitor_printf(mon, "acl: unknown policy '%s', "
2329
                           "expected 'deny' or 'allow'\n", policy);
2330
        }
2331
    }
2332
}
2333

    
2334
static void do_acl_add(Monitor *mon, const QDict *qdict)
2335
{
2336
    const char *aclname = qdict_get_str(qdict, "aclname");
2337
    const char *match = qdict_get_str(qdict, "match");
2338
    const char *policy = qdict_get_str(qdict, "policy");
2339
    int has_index = qdict_haskey(qdict, "index");
2340
    int index = qdict_get_try_int(qdict, "index", -1);
2341
    qemu_acl *acl = find_acl(mon, aclname);
2342
    int deny, ret;
2343

    
2344
    if (acl) {
2345
        if (strcmp(policy, "allow") == 0) {
2346
            deny = 0;
2347
        } else if (strcmp(policy, "deny") == 0) {
2348
            deny = 1;
2349
        } else {
2350
            monitor_printf(mon, "acl: unknown policy '%s', "
2351
                           "expected 'deny' or 'allow'\n", policy);
2352
            return;
2353
        }
2354
        if (has_index)
2355
            ret = qemu_acl_insert(acl, deny, match, index);
2356
        else
2357
            ret = qemu_acl_append(acl, deny, match);
2358
        if (ret < 0)
2359
            monitor_printf(mon, "acl: unable to add acl entry\n");
2360
        else
2361
            monitor_printf(mon, "acl: added rule at position %d\n", ret);
2362
    }
2363
}
2364

    
2365
static void do_acl_remove(Monitor *mon, const QDict *qdict)
2366
{
2367
    const char *aclname = qdict_get_str(qdict, "aclname");
2368
    const char *match = qdict_get_str(qdict, "match");
2369
    qemu_acl *acl = find_acl(mon, aclname);
2370
    int ret;
2371

    
2372
    if (acl) {
2373
        ret = qemu_acl_remove(acl, match);
2374
        if (ret < 0)
2375
            monitor_printf(mon, "acl: no matching acl entry\n");
2376
        else
2377
            monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2378
    }
2379
}
2380

    
2381
#if defined(TARGET_I386)
2382
static void do_inject_mce(Monitor *mon, const QDict *qdict)
2383
{
2384
    CPUState *cenv;
2385
    int cpu_index = qdict_get_int(qdict, "cpu_index");
2386
    int bank = qdict_get_int(qdict, "bank");
2387
    uint64_t status = qdict_get_int(qdict, "status");
2388
    uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2389
    uint64_t addr = qdict_get_int(qdict, "addr");
2390
    uint64_t misc = qdict_get_int(qdict, "misc");
2391

    
2392
    for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu)
2393
        if (cenv->cpu_index == cpu_index && cenv->mcg_cap) {
2394
            cpu_inject_x86_mce(cenv, bank, status, mcg_status, addr, misc);
2395
            break;
2396
        }
2397
}
2398
#endif
2399

    
2400
static void do_getfd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2401
{
2402
    const char *fdname = qdict_get_str(qdict, "fdname");
2403
    mon_fd_t *monfd;
2404
    int fd;
2405

    
2406
    fd = qemu_chr_get_msgfd(mon->chr);
2407
    if (fd == -1) {
2408
        qemu_error_new(QERR_FD_NOT_SUPPLIED);
2409
        return;
2410
    }
2411

    
2412
    if (qemu_isdigit(fdname[0])) {
2413
        qemu_error_new(QERR_INVALID_PARAMETER, "fdname");
2414
        return;
2415
    }
2416

    
2417
    fd = dup(fd);
2418
    if (fd == -1) {
2419
        if (errno == EMFILE)
2420
            qemu_error_new(QERR_TOO_MANY_FILES);
2421
        else
2422
            qemu_error_new(QERR_UNDEFINED_ERROR);
2423
        return;
2424
    }
2425

    
2426
    QLIST_FOREACH(monfd, &mon->fds, next) {
2427
        if (strcmp(monfd->name, fdname) != 0) {
2428
            continue;
2429
        }
2430

    
2431
        close(monfd->fd);
2432
        monfd->fd = fd;
2433
        return;
2434
    }
2435

    
2436
    monfd = qemu_mallocz(sizeof(mon_fd_t));
2437
    monfd->name = qemu_strdup(fdname);
2438
    monfd->fd = fd;
2439

    
2440
    QLIST_INSERT_HEAD(&mon->fds, monfd, next);
2441
}
2442

    
2443
static void do_closefd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2444
{
2445
    const char *fdname = qdict_get_str(qdict, "fdname");
2446
    mon_fd_t *monfd;
2447

    
2448
    QLIST_FOREACH(monfd, &mon->fds, next) {
2449
        if (strcmp(monfd->name, fdname) != 0) {
2450
            continue;
2451
        }
2452

    
2453
        QLIST_REMOVE(monfd, next);
2454
        close(monfd->fd);
2455
        qemu_free(monfd->name);
2456
        qemu_free(monfd);
2457
        return;
2458
    }
2459

    
2460
    qemu_error_new(QERR_FD_NOT_FOUND, fdname);
2461
}
2462

    
2463
static void do_loadvm(Monitor *mon, const QDict *qdict)
2464
{
2465
    int saved_vm_running  = vm_running;
2466
    const char *name = qdict_get_str(qdict, "name");
2467

    
2468
    vm_stop(0);
2469

    
2470
    if (load_vmstate(mon, name) >= 0 && saved_vm_running)
2471
        vm_start();
2472
}
2473

    
2474
int monitor_get_fd(Monitor *mon, const char *fdname)
2475
{
2476
    mon_fd_t *monfd;
2477

    
2478
    QLIST_FOREACH(monfd, &mon->fds, next) {
2479
        int fd;
2480

    
2481
        if (strcmp(monfd->name, fdname) != 0) {
2482
            continue;
2483
        }
2484

    
2485
        fd = monfd->fd;
2486

    
2487
        /* caller takes ownership of fd */
2488
        QLIST_REMOVE(monfd, next);
2489
        qemu_free(monfd->name);
2490
        qemu_free(monfd);
2491

    
2492
        return fd;
2493
    }
2494

    
2495
    return -1;
2496
}
2497

    
2498
static const mon_cmd_t mon_cmds[] = {
2499
#include "qemu-monitor.h"
2500
    { NULL, NULL, },
2501
};
2502

    
2503
/* Please update qemu-monitor.hx when adding or changing commands */
2504
static const mon_cmd_t info_cmds[] = {
2505
    {
2506
        .name       = "version",
2507
        .args_type  = "",
2508
        .params     = "",
2509
        .help       = "show the version of QEMU",
2510
        .user_print = do_info_version_print,
2511
        .mhandler.info_new = do_info_version,
2512
    },
2513
    {
2514
        .name       = "commands",
2515
        .args_type  = "",
2516
        .params     = "",
2517
        .help       = "list QMP available commands",
2518
        .user_print = monitor_user_noop,
2519
        .mhandler.info_new = do_info_commands,
2520
    },
2521
    {
2522
        .name       = "network",
2523
        .args_type  = "",
2524
        .params     = "",
2525
        .help       = "show the network state",
2526
        .mhandler.info = do_info_network,
2527
    },
2528
    {
2529
        .name       = "chardev",
2530
        .args_type  = "",
2531
        .params     = "",
2532
        .help       = "show the character devices",
2533
        .user_print = qemu_chr_info_print,
2534
        .mhandler.info_new = qemu_chr_info,
2535
    },
2536
    {
2537
        .name       = "block",
2538
        .args_type  = "",
2539
        .params     = "",
2540
        .help       = "show the block devices",
2541
        .user_print = bdrv_info_print,
2542
        .mhandler.info_new = bdrv_info,
2543
    },
2544
    {
2545
        .name       = "blockstats",
2546
        .args_type  = "",
2547
        .params     = "",
2548
        .help       = "show block device statistics",
2549
        .user_print = bdrv_stats_print,
2550
        .mhandler.info_new = bdrv_info_stats,
2551
    },
2552
    {
2553
        .name       = "registers",
2554
        .args_type  = "",
2555
        .params     = "",
2556
        .help       = "show the cpu registers",
2557
        .mhandler.info = do_info_registers,
2558
    },
2559
    {
2560
        .name       = "cpus",
2561
        .args_type  = "",
2562
        .params     = "",
2563
        .help       = "show infos for each CPU",
2564
        .user_print = monitor_print_cpus,
2565
        .mhandler.info_new = do_info_cpus,
2566
    },
2567
    {
2568
        .name       = "history",
2569
        .args_type  = "",
2570
        .params     = "",
2571
        .help       = "show the command line history",
2572
        .mhandler.info = do_info_history,
2573
    },
2574
    {
2575
        .name       = "irq",
2576
        .args_type  = "",
2577
        .params     = "",
2578
        .help       = "show the interrupts statistics (if available)",
2579
        .mhandler.info = irq_info,
2580
    },
2581
    {
2582
        .name       = "pic",
2583
        .args_type  = "",
2584
        .params     = "",
2585
        .help       = "show i8259 (PIC) state",
2586
        .mhandler.info = pic_info,
2587
    },
2588
    {
2589
        .name       = "pci",
2590
        .args_type  = "",
2591
        .params     = "",
2592
        .help       = "show PCI info",
2593
        .user_print = do_pci_info_print,
2594
        .mhandler.info_new = do_pci_info,
2595
    },
2596
#if defined(TARGET_I386) || defined(TARGET_SH4)
2597
    {
2598
        .name       = "tlb",
2599
        .args_type  = "",
2600
        .params     = "",
2601
        .help       = "show virtual to physical memory mappings",
2602
        .mhandler.info = tlb_info,
2603
    },
2604
#endif
2605
#if defined(TARGET_I386)
2606
    {
2607
        .name       = "mem",
2608
        .args_type  = "",
2609
        .params     = "",
2610
        .help       = "show the active virtual memory mappings",
2611
        .mhandler.info = mem_info,
2612
    },
2613
    {
2614
        .name       = "hpet",
2615
        .args_type  = "",
2616
        .params     = "",
2617
        .help       = "show state of HPET",
2618
        .user_print = do_info_hpet_print,
2619
        .mhandler.info_new = do_info_hpet,
2620
    },
2621
#endif
2622
    {
2623
        .name       = "jit",
2624
        .args_type  = "",
2625
        .params     = "",
2626
        .help       = "show dynamic compiler info",
2627
        .mhandler.info = do_info_jit,
2628
    },
2629
    {
2630
        .name       = "kvm",
2631
        .args_type  = "",
2632
        .params     = "",
2633
        .help       = "show KVM information",
2634
        .user_print = do_info_kvm_print,
2635
        .mhandler.info_new = do_info_kvm,
2636
    },
2637
    {
2638
        .name       = "numa",
2639
        .args_type  = "",
2640
        .params     = "",
2641
        .help       = "show NUMA information",
2642
        .mhandler.info = do_info_numa,
2643
    },
2644
    {
2645
        .name       = "usb",
2646
        .args_type  = "",
2647
        .params     = "",
2648
        .help       = "show guest USB devices",
2649
        .mhandler.info = usb_info,
2650
    },
2651
    {
2652
        .name       = "usbhost",
2653
        .args_type  = "",
2654
        .params     = "",
2655
        .help       = "show host USB devices",
2656
        .mhandler.info = usb_host_info,
2657
    },
2658
    {
2659
        .name       = "profile",
2660
        .args_type  = "",
2661
        .params     = "",
2662
        .help       = "show profiling information",
2663
        .mhandler.info = do_info_profile,
2664
    },
2665
    {
2666
        .name       = "capture",
2667
        .args_type  = "",
2668
        .params     = "",
2669
        .help       = "show capture information",
2670
        .mhandler.info = do_info_capture,
2671
    },
2672
    {
2673
        .name       = "snapshots",
2674
        .args_type  = "",
2675
        .params     = "",
2676
        .help       = "show the currently saved VM snapshots",
2677
        .mhandler.info = do_info_snapshots,
2678
    },
2679
    {
2680
        .name       = "status",
2681
        .args_type  = "",
2682
        .params     = "",
2683
        .help       = "show the current VM status (running|paused)",
2684
        .user_print = do_info_status_print,
2685
        .mhandler.info_new = do_info_status,
2686
    },
2687
    {
2688
        .name       = "pcmcia",
2689
        .args_type  = "",
2690
        .params     = "",
2691
        .help       = "show guest PCMCIA status",
2692
        .mhandler.info = pcmcia_info,
2693
    },
2694
    {
2695
        .name       = "mice",
2696
        .args_type  = "",
2697
        .params     = "",
2698
        .help       = "show which guest mouse is receiving events",
2699
        .user_print = do_info_mice_print,
2700
        .mhandler.info_new = do_info_mice,
2701
    },
2702
    {
2703
        .name       = "vnc",
2704
        .args_type  = "",
2705
        .params     = "",
2706
        .help       = "show the vnc server status",
2707
        .user_print = do_info_vnc_print,
2708
        .mhandler.info_new = do_info_vnc,
2709
    },
2710
    {
2711
        .name       = "name",
2712
        .args_type  = "",
2713
        .params     = "",
2714
        .help       = "show the current VM name",
2715
        .user_print = do_info_name_print,
2716
        .mhandler.info_new = do_info_name,
2717
    },
2718
    {
2719
        .name       = "uuid",
2720
        .args_type  = "",
2721
        .params     = "",
2722
        .help       = "show the current VM UUID",
2723
        .user_print = do_info_uuid_print,
2724
        .mhandler.info_new = do_info_uuid,
2725
    },
2726
#if defined(TARGET_PPC)
2727
    {
2728
        .name       = "cpustats",
2729
        .args_type  = "",
2730
        .params     = "",
2731
        .help       = "show CPU statistics",
2732
        .mhandler.info = do_info_cpu_stats,
2733
    },
2734
#endif
2735
#if defined(CONFIG_SLIRP)
2736
    {
2737
        .name       = "usernet",
2738
        .args_type  = "",
2739
        .params     = "",
2740
        .help       = "show user network stack connection states",
2741
        .mhandler.info = do_info_usernet,
2742
    },
2743
#endif
2744
    {
2745
        .name       = "migrate",
2746
        .args_type  = "",
2747
        .params     = "",
2748
        .help       = "show migration status",
2749
        .user_print = do_info_migrate_print,
2750
        .mhandler.info_new = do_info_migrate,
2751
    },
2752
    {
2753
        .name       = "balloon",
2754
        .args_type  = "",
2755
        .params     = "",
2756
        .help       = "show balloon information",
2757
        .user_print = monitor_print_balloon,
2758
        .mhandler.info_async = do_info_balloon,
2759
        .async      = 1,
2760
    },
2761
    {
2762
        .name       = "qtree",
2763
        .args_type  = "",
2764
        .params     = "",
2765
        .help       = "show device tree",
2766
        .mhandler.info = do_info_qtree,
2767
    },
2768
    {
2769
        .name       = "qdm",
2770
        .args_type  = "",
2771
        .params     = "",
2772
        .help       = "show qdev device model list",
2773
        .mhandler.info = do_info_qdm,
2774
    },
2775
    {
2776
        .name       = "roms",
2777
        .args_type  = "",
2778
        .params     = "",
2779
        .help       = "show roms",
2780
        .mhandler.info = do_info_roms,
2781
    },
2782
    {
2783
        .name       = NULL,
2784
    },
2785
};
2786

    
2787
/*******************************************************************/
2788

    
2789
static const char *pch;
2790
static jmp_buf expr_env;
2791

    
2792
#define MD_TLONG 0
2793
#define MD_I32   1
2794

    
2795
typedef struct MonitorDef {
2796
    const char *name;
2797
    int offset;
2798
    target_long (*get_value)(const struct MonitorDef *md, int val);
2799
    int type;
2800
} MonitorDef;
2801

    
2802
#if defined(TARGET_I386)
2803
static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2804
{
2805
    CPUState *env = mon_get_cpu();
2806
    return env->eip + env->segs[R_CS].base;
2807
}
2808
#endif
2809

    
2810
#if defined(TARGET_PPC)
2811
static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2812
{
2813
    CPUState *env = mon_get_cpu();
2814
    unsigned int u;
2815
    int i;
2816

    
2817
    u = 0;
2818
    for (i = 0; i < 8; i++)
2819
        u |= env->crf[i] << (32 - (4 * i));
2820

    
2821
    return u;
2822
}
2823

    
2824
static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2825
{
2826
    CPUState *env = mon_get_cpu();
2827
    return env->msr;
2828
}
2829

    
2830
static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2831
{
2832
    CPUState *env = mon_get_cpu();
2833
    return env->xer;
2834
}
2835

    
2836
static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2837
{
2838
    CPUState *env = mon_get_cpu();
2839
    return cpu_ppc_load_decr(env);
2840
}
2841

    
2842
static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2843
{
2844
    CPUState *env = mon_get_cpu();
2845
    return cpu_ppc_load_tbu(env);
2846
}
2847

    
2848
static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2849
{
2850
    CPUState *env = mon_get_cpu();
2851
    return cpu_ppc_load_tbl(env);
2852
}
2853
#endif
2854

    
2855
#if defined(TARGET_SPARC)
2856
#ifndef TARGET_SPARC64
2857
static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2858
{
2859
    CPUState *env = mon_get_cpu();
2860
    return GET_PSR(env);
2861
}
2862
#endif
2863

    
2864
static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2865
{
2866
    CPUState *env = mon_get_cpu();
2867
    return env->regwptr[val];
2868
}
2869
#endif
2870

    
2871
static const MonitorDef monitor_defs[] = {
2872
#ifdef TARGET_I386
2873

    
2874
#define SEG(name, seg) \
2875
    { name, offsetof(CPUState, segs[seg].selector), NULL, MD_I32 },\
2876
    { name ".base", offsetof(CPUState, segs[seg].base) },\
2877
    { name ".limit", offsetof(CPUState, segs[seg].limit), NULL, MD_I32 },
2878

    
2879
    { "eax", offsetof(CPUState, regs[0]) },
2880
    { "ecx", offsetof(CPUState, regs[1]) },
2881
    { "edx", offsetof(CPUState, regs[2]) },
2882
    { "ebx", offsetof(CPUState, regs[3]) },
2883
    { "esp|sp", offsetof(CPUState, regs[4]) },
2884
    { "ebp|fp", offsetof(CPUState, regs[5]) },
2885
    { "esi", offsetof(CPUState, regs[6]) },
2886
    { "edi", offsetof(CPUState, regs[7]) },
2887
#ifdef TARGET_X86_64
2888
    { "r8", offsetof(CPUState, regs[8]) },
2889
    { "r9", offsetof(CPUState, regs[9]) },
2890
    { "r10", offsetof(CPUState, regs[10]) },
2891
    { "r11", offsetof(CPUState, regs[11]) },
2892
    { "r12", offsetof(CPUState, regs[12]) },
2893
    { "r13", offsetof(CPUState, regs[13]) },
2894
    { "r14", offsetof(CPUState, regs[14]) },
2895
    { "r15", offsetof(CPUState, regs[15]) },
2896
#endif
2897
    { "eflags", offsetof(CPUState, eflags) },
2898
    { "eip", offsetof(CPUState, eip) },
2899
    SEG("cs", R_CS)
2900
    SEG("ds", R_DS)
2901
    SEG("es", R_ES)
2902
    SEG("ss", R_SS)
2903
    SEG("fs", R_FS)
2904
    SEG("gs", R_GS)
2905
    { "pc", 0, monitor_get_pc, },
2906
#elif defined(TARGET_PPC)
2907
    /* General purpose registers */
2908
    { "r0", offsetof(CPUState, gpr[0]) },
2909
    { "r1", offsetof(CPUState, gpr[1]) },
2910
    { "r2", offsetof(CPUState, gpr[2]) },
2911
    { "r3", offsetof(CPUState, gpr[3]) },
2912
    { "r4", offsetof(CPUState, gpr[4]) },
2913
    { "r5", offsetof(CPUState, gpr[5]) },
2914
    { "r6", offsetof(CPUState, gpr[6]) },
2915
    { "r7", offsetof(CPUState, gpr[7]) },
2916
    { "r8", offsetof(CPUState, gpr[8]) },
2917
    { "r9", offsetof(CPUState, gpr[9]) },
2918
    { "r10", offsetof(CPUState, gpr[10]) },
2919
    { "r11", offsetof(CPUState, gpr[11]) },
2920
    { "r12", offsetof(CPUState, gpr[12]) },
2921
    { "r13", offsetof(CPUState, gpr[13]) },
2922
    { "r14", offsetof(CPUState, gpr[14]) },
2923
    { "r15", offsetof(CPUState, gpr[15]) },
2924
    { "r16", offsetof(CPUState, gpr[16]) },
2925
    { "r17", offsetof(CPUState, gpr[17]) },
2926
    { "r18", offsetof(CPUState, gpr[18]) },
2927
    { "r19", offsetof(CPUState, gpr[19]) },
2928
    { "r20", offsetof(CPUState, gpr[20]) },
2929
    { "r21", offsetof(CPUState, gpr[21]) },
2930
    { "r22", offsetof(CPUState, gpr[22]) },
2931
    { "r23", offsetof(CPUState, gpr[23]) },
2932
    { "r24", offsetof(CPUState, gpr[24]) },
2933
    { "r25", offsetof(CPUState, gpr[25]) },
2934
    { "r26", offsetof(CPUState, gpr[26]) },
2935
    { "r27", offsetof(CPUState, gpr[27]) },
2936
    { "r28", offsetof(CPUState, gpr[28]) },
2937
    { "r29", offsetof(CPUState, gpr[29]) },
2938
    { "r30", offsetof(CPUState, gpr[30]) },
2939
    { "r31", offsetof(CPUState, gpr[31]) },
2940
    /* Floating point registers */
2941
    { "f0", offsetof(CPUState, fpr[0]) },
2942
    { "f1", offsetof(CPUState, fpr[1]) },
2943
    { "f2", offsetof(CPUState, fpr[2]) },
2944
    { "f3", offsetof(CPUState, fpr[3]) },
2945
    { "f4", offsetof(CPUState, fpr[4]) },
2946
    { "f5", offsetof(CPUState, fpr[5]) },
2947
    { "f6", offsetof(CPUState, fpr[6]) },
2948
    { "f7", offsetof(CPUState, fpr[7]) },
2949
    { "f8", offsetof(CPUState, fpr[8]) },
2950
    { "f9", offsetof(CPUState, fpr[9]) },
2951
    { "f10", offsetof(CPUState, fpr[10]) },
2952
    { "f11", offsetof(CPUState, fpr[11]) },
2953
    { "f12", offsetof(CPUState, fpr[12]) },
2954
    { "f13", offsetof(CPUState, fpr[13]) },
2955
    { "f14", offsetof(CPUState, fpr[14]) },
2956
    { "f15", offsetof(CPUState, fpr[15]) },
2957
    { "f16", offsetof(CPUState, fpr[16]) },
2958
    { "f17", offsetof(CPUState, fpr[17]) },
2959
    { "f18", offsetof(CPUState, fpr[18]) },
2960
    { "f19", offsetof(CPUState, fpr[19]) },
2961
    { "f20", offsetof(CPUState, fpr[20]) },
2962
    { "f21", offsetof(CPUState, fpr[21]) },
2963
    { "f22", offsetof(CPUState, fpr[22]) },
2964
    { "f23", offsetof(CPUState, fpr[23]) },
2965
    { "f24", offsetof(CPUState, fpr[24]) },
2966
    { "f25", offsetof(CPUState, fpr[25]) },
2967
    { "f26", offsetof(CPUState, fpr[26]) },
2968
    { "f27", offsetof(CPUState, fpr[27]) },
2969
    { "f28", offsetof(CPUState, fpr[28]) },
2970
    { "f29", offsetof(CPUState, fpr[29]) },
2971
    { "f30", offsetof(CPUState, fpr[30]) },
2972
    { "f31", offsetof(CPUState, fpr[31]) },
2973
    { "fpscr", offsetof(CPUState, fpscr) },
2974
    /* Next instruction pointer */
2975
    { "nip|pc", offsetof(CPUState, nip) },
2976
    { "lr", offsetof(CPUState, lr) },
2977
    { "ctr", offsetof(CPUState, ctr) },
2978
    { "decr", 0, &monitor_get_decr, },
2979
    { "ccr", 0, &monitor_get_ccr, },
2980
    /* Machine state register */
2981
    { "msr", 0, &monitor_get_msr, },
2982
    { "xer", 0, &monitor_get_xer, },
2983
    { "tbu", 0, &monitor_get_tbu, },
2984
    { "tbl", 0, &monitor_get_tbl, },
2985
#if defined(TARGET_PPC64)
2986
    /* Address space register */
2987
    { "asr", offsetof(CPUState, asr) },
2988
#endif
2989
    /* Segment registers */
2990
    { "sdr1", offsetof(CPUState, sdr1) },
2991
    { "sr0", offsetof(CPUState, sr[0]) },
2992
    { "sr1", offsetof(CPUState, sr[1]) },
2993
    { "sr2", offsetof(CPUState, sr[2]) },
2994
    { "sr3", offsetof(CPUState, sr[3]) },
2995
    { "sr4", offsetof(CPUState, sr[4]) },
2996
    { "sr5", offsetof(CPUState, sr[5]) },
2997
    { "sr6", offsetof(CPUState, sr[6]) },
2998
    { "sr7", offsetof(CPUState, sr[7]) },
2999
    { "sr8", offsetof(CPUState, sr[8]) },
3000
    { "sr9", offsetof(CPUState, sr[9]) },
3001
    { "sr10", offsetof(CPUState, sr[10]) },
3002
    { "sr11", offsetof(CPUState, sr[11]) },
3003
    { "sr12", offsetof(CPUState, sr[12]) },
3004
    { "sr13", offsetof(CPUState, sr[13]) },
3005
    { "sr14", offsetof(CPUState, sr[14]) },
3006
    { "sr15", offsetof(CPUState, sr[15]) },
3007
    /* Too lazy to put BATs and SPRs ... */
3008
#elif defined(TARGET_SPARC)
3009
    { "g0", offsetof(CPUState, gregs[0]) },
3010
    { "g1", offsetof(CPUState, gregs[1]) },
3011
    { "g2", offsetof(CPUState, gregs[2]) },
3012
    { "g3", offsetof(CPUState, gregs[3]) },
3013
    { "g4", offsetof(CPUState, gregs[4]) },
3014
    { "g5", offsetof(CPUState, gregs[5]) },
3015
    { "g6", offsetof(CPUState, gregs[6]) },
3016
    { "g7", offsetof(CPUState, gregs[7]) },
3017
    { "o0", 0, monitor_get_reg },
3018
    { "o1", 1, monitor_get_reg },
3019
    { "o2", 2, monitor_get_reg },
3020
    { "o3", 3, monitor_get_reg },
3021
    { "o4", 4, monitor_get_reg },
3022
    { "o5", 5, monitor_get_reg },
3023
    { "o6", 6, monitor_get_reg },
3024
    { "o7", 7, monitor_get_reg },
3025
    { "l0", 8, monitor_get_reg },
3026
    { "l1", 9, monitor_get_reg },
3027
    { "l2", 10, monitor_get_reg },
3028
    { "l3", 11, monitor_get_reg },
3029
    { "l4", 12, monitor_get_reg },
3030
    { "l5", 13, monitor_get_reg },
3031
    { "l6", 14, monitor_get_reg },
3032
    { "l7", 15, monitor_get_reg },
3033
    { "i0", 16, monitor_get_reg },
3034
    { "i1", 17, monitor_get_reg },
3035
    { "i2", 18, monitor_get_reg },
3036
    { "i3", 19, monitor_get_reg },
3037
    { "i4", 20, monitor_get_reg },
3038
    { "i5", 21, monitor_get_reg },
3039
    { "i6", 22, monitor_get_reg },
3040
    { "i7", 23, monitor_get_reg },
3041
    { "pc", offsetof(CPUState, pc) },
3042
    { "npc", offsetof(CPUState, npc) },
3043
    { "y", offsetof(CPUState, y) },
3044
#ifndef TARGET_SPARC64
3045
    { "psr", 0, &monitor_get_psr, },
3046
    { "wim", offsetof(CPUState, wim) },
3047
#endif
3048
    { "tbr", offsetof(CPUState, tbr) },
3049
    { "fsr", offsetof(CPUState, fsr) },
3050
    { "f0", offsetof(CPUState, fpr[0]) },
3051
    { "f1", offsetof(CPUState, fpr[1]) },
3052
    { "f2", offsetof(CPUState, fpr[2]) },
3053
    { "f3", offsetof(CPUState, fpr[3]) },
3054
    { "f4", offsetof(CPUState, fpr[4]) },
3055
    { "f5", offsetof(CPUState, fpr[5]) },
3056
    { "f6", offsetof(CPUState, fpr[6]) },
3057
    { "f7", offsetof(CPUState, fpr[7]) },
3058
    { "f8", offsetof(CPUState, fpr[8]) },
3059
    { "f9", offsetof(CPUState, fpr[9]) },
3060
    { "f10", offsetof(CPUState, fpr[10]) },
3061
    { "f11", offsetof(CPUState, fpr[11]) },
3062
    { "f12", offsetof(CPUState, fpr[12]) },
3063
    { "f13", offsetof(CPUState, fpr[13]) },
3064
    { "f14", offsetof(CPUState, fpr[14]) },
3065
    { "f15", offsetof(CPUState, fpr[15]) },
3066
    { "f16", offsetof(CPUState, fpr[16]) },
3067
    { "f17", offsetof(CPUState, fpr[17]) },
3068
    { "f18", offsetof(CPUState, fpr[18]) },
3069
    { "f19", offsetof(CPUState, fpr[19]) },
3070
    { "f20", offsetof(CPUState, fpr[20]) },
3071
    { "f21", offsetof(CPUState, fpr[21]) },
3072
    { "f22", offsetof(CPUState, fpr[22]) },
3073
    { "f23", offsetof(CPUState, fpr[23]) },
3074
    { "f24", offsetof(CPUState, fpr[24]) },
3075
    { "f25", offsetof(CPUState, fpr[25]) },
3076
    { "f26", offsetof(CPUState, fpr[26]) },
3077
    { "f27", offsetof(CPUState, fpr[27]) },
3078
    { "f28", offsetof(CPUState, fpr[28]) },
3079
    { "f29", offsetof(CPUState, fpr[29]) },
3080
    { "f30", offsetof(CPUState, fpr[30]) },
3081
    { "f31", offsetof(CPUState, fpr[31]) },
3082
#ifdef TARGET_SPARC64
3083
    { "f32", offsetof(CPUState, fpr[32]) },
3084
    { "f34", offsetof(CPUState, fpr[34]) },
3085
    { "f36", offsetof(CPUState, fpr[36]) },
3086
    { "f38", offsetof(CPUState, fpr[38]) },
3087
    { "f40", offsetof(CPUState, fpr[40]) },
3088
    { "f42", offsetof(CPUState, fpr[42]) },
3089
    { "f44", offsetof(CPUState, fpr[44]) },
3090
    { "f46", offsetof(CPUState, fpr[46]) },
3091
    { "f48", offsetof(CPUState, fpr[48]) },
3092
    { "f50", offsetof(CPUState, fpr[50]) },
3093
    { "f52", offsetof(CPUState, fpr[52]) },
3094
    { "f54", offsetof(CPUState, fpr[54]) },
3095
    { "f56", offsetof(CPUState, fpr[56]) },
3096
    { "f58", offsetof(CPUState, fpr[58]) },
3097
    { "f60", offsetof(CPUState, fpr[60]) },
3098
    { "f62", offsetof(CPUState, fpr[62]) },
3099
    { "asi", offsetof(CPUState, asi) },
3100
    { "pstate", offsetof(CPUState, pstate) },
3101
    { "cansave", offsetof(CPUState, cansave) },
3102
    { "canrestore", offsetof(CPUState, canrestore) },
3103
    { "otherwin", offsetof(CPUState, otherwin) },
3104
    { "wstate", offsetof(CPUState, wstate) },
3105
    { "cleanwin", offsetof(CPUState, cleanwin) },
3106
    { "fprs", offsetof(CPUState, fprs) },
3107
#endif
3108
#endif
3109
    { NULL },
3110
};
3111

    
3112
static void expr_error(Monitor *mon, const char *msg)
3113
{
3114
    monitor_printf(mon, "%s\n", msg);
3115
    longjmp(expr_env, 1);
3116
}
3117

    
3118
/* return 0 if OK, -1 if not found */
3119
static int get_monitor_def(target_long *pval, const char *name)
3120
{
3121
    const MonitorDef *md;
3122
    void *ptr;
3123

    
3124
    for(md = monitor_defs; md->name != NULL; md++) {
3125
        if (compare_cmd(name, md->name)) {
3126
            if (md->get_value) {
3127
                *pval = md->get_value(md, md->offset);
3128
            } else {
3129
                CPUState *env = mon_get_cpu();
3130
                ptr = (uint8_t *)env + md->offset;
3131
                switch(md->type) {
3132
                case MD_I32:
3133
                    *pval = *(int32_t *)ptr;
3134
                    break;
3135
                case MD_TLONG:
3136
                    *pval = *(target_long *)ptr;
3137
                    break;
3138
                default:
3139
                    *pval = 0;
3140
                    break;
3141
                }
3142
            }
3143
            return 0;
3144
        }
3145
    }
3146
    return -1;
3147
}
3148

    
3149
static void next(void)
3150
{
3151
    if (*pch != '\0') {
3152
        pch++;
3153
        while (qemu_isspace(*pch))
3154
            pch++;
3155
    }
3156
}
3157

    
3158
static int64_t expr_sum(Monitor *mon);
3159

    
3160
static int64_t expr_unary(Monitor *mon)
3161
{
3162
    int64_t n;
3163
    char *p;
3164
    int ret;
3165

    
3166
    switch(*pch) {
3167
    case '+':
3168
        next();
3169
        n = expr_unary(mon);
3170
        break;
3171
    case '-':
3172
        next();
3173
        n = -expr_unary(mon);
3174
        break;
3175
    case '~':
3176
        next();
3177
        n = ~expr_unary(mon);
3178
        break;
3179
    case '(':
3180
        next();
3181
        n = expr_sum(mon);
3182
        if (*pch != ')') {
3183
            expr_error(mon, "')' expected");
3184
        }
3185
        next();
3186
        break;
3187
    case '\'':
3188
        pch++;
3189
        if (*pch == '\0')
3190
            expr_error(mon, "character constant expected");
3191
        n = *pch;
3192
        pch++;
3193
        if (*pch != '\'')
3194
            expr_error(mon, "missing terminating \' character");
3195
        next();
3196
        break;
3197
    case '$':
3198
        {
3199
            char buf[128], *q;
3200
            target_long reg=0;
3201

    
3202
            pch++;
3203
            q = buf;
3204
            while ((*pch >= 'a' && *pch <= 'z') ||
3205
                   (*pch >= 'A' && *pch <= 'Z') ||
3206
                   (*pch >= '0' && *pch <= '9') ||
3207
                   *pch == '_' || *pch == '.') {
3208
                if ((q - buf) < sizeof(buf) - 1)
3209
                    *q++ = *pch;
3210
                pch++;
3211
            }
3212
            while (qemu_isspace(*pch))
3213
                pch++;
3214
            *q = 0;
3215
            ret = get_monitor_def(&reg, buf);
3216
            if (ret < 0)
3217
                expr_error(mon, "unknown register");
3218
            n = reg;
3219
        }
3220
        break;
3221
    case '\0':
3222
        expr_error(mon, "unexpected end of expression");
3223
        n = 0;
3224
        break;
3225
    default:
3226
#if TARGET_PHYS_ADDR_BITS > 32
3227
        n = strtoull(pch, &p, 0);
3228
#else
3229
        n = strtoul(pch, &p, 0);
3230
#endif
3231
        if (pch == p) {
3232
            expr_error(mon, "invalid char in expression");
3233
        }
3234
        pch = p;
3235
        while (qemu_isspace(*pch))
3236
            pch++;
3237
        break;
3238
    }
3239
    return n;
3240
}
3241

    
3242

    
3243
static int64_t expr_prod(Monitor *mon)
3244
{
3245
    int64_t val, val2;
3246
    int op;
3247

    
3248
    val = expr_unary(mon);
3249
    for(;;) {
3250
        op = *pch;
3251
        if (op != '*' && op != '/' && op != '%')
3252
            break;
3253
        next();
3254
        val2 = expr_unary(mon);
3255
        switch(op) {
3256
        default:
3257
        case '*':
3258
            val *= val2;
3259
            break;
3260
        case '/':
3261
        case '%':
3262
            if (val2 == 0)
3263
                expr_error(mon, "division by zero");
3264
            if (op == '/')
3265
                val /= val2;
3266
            else
3267
                val %= val2;
3268
            break;
3269
        }
3270
    }
3271
    return val;
3272
}
3273

    
3274
static int64_t expr_logic(Monitor *mon)
3275
{
3276
    int64_t val, val2;
3277
    int op;
3278

    
3279
    val = expr_prod(mon);
3280
    for(;;) {
3281
        op = *pch;
3282
        if (op != '&' && op != '|' && op != '^')
3283
            break;
3284
        next();
3285
        val2 = expr_prod(mon);
3286
        switch(op) {
3287
        default:
3288
        case '&':
3289
            val &= val2;
3290
            break;
3291
        case '|':
3292
            val |= val2;
3293
            break;
3294
        case '^':
3295
            val ^= val2;
3296
            break;
3297
        }
3298
    }
3299
    return val;
3300
}
3301

    
3302
static int64_t expr_sum(Monitor *mon)
3303
{
3304
    int64_t val, val2;
3305
    int op;
3306

    
3307
    val = expr_logic(mon);
3308
    for(;;) {
3309
        op = *pch;
3310
        if (op != '+' && op != '-')
3311
            break;
3312
        next();
3313
        val2 = expr_logic(mon);
3314
        if (op == '+')
3315
            val += val2;
3316
        else
3317
            val -= val2;
3318
    }
3319
    return val;
3320
}
3321

    
3322
static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3323
{
3324
    pch = *pp;
3325
    if (setjmp(expr_env)) {
3326
        *pp = pch;
3327
        return -1;
3328
    }
3329
    while (qemu_isspace(*pch))
3330
        pch++;
3331
    *pval = expr_sum(mon);
3332
    *pp = pch;
3333
    return 0;
3334
}
3335

    
3336
static int get_double(Monitor *mon, double *pval, const char **pp)
3337
{
3338
    const char *p = *pp;
3339
    char *tailp;
3340
    double d;
3341

    
3342
    d = strtod(p, &tailp);
3343
    if (tailp == p) {
3344
        monitor_printf(mon, "Number expected\n");
3345
        return -1;
3346
    }
3347
    if (d != d || d - d != 0) {
3348
        /* NaN or infinity */
3349
        monitor_printf(mon, "Bad number\n");
3350
        return -1;
3351
    }
3352
    *pval = d;
3353
    *pp = tailp;
3354
    return 0;
3355
}
3356

    
3357
static int get_str(char *buf, int buf_size, const char **pp)
3358
{
3359
    const char *p;
3360
    char *q;
3361
    int c;
3362

    
3363
    q = buf;
3364
    p = *pp;
3365
    while (qemu_isspace(*p))
3366
        p++;
3367
    if (*p == '\0') {
3368
    fail:
3369
        *q = '\0';
3370
        *pp = p;
3371
        return -1;
3372
    }
3373
    if (*p == '\"') {
3374
        p++;
3375
        while (*p != '\0' && *p != '\"') {
3376
            if (*p == '\\') {
3377
                p++;
3378
                c = *p++;
3379
                switch(c) {
3380
                case 'n':
3381
                    c = '\n';
3382
                    break;
3383
                case 'r':
3384
                    c = '\r';
3385
                    break;
3386
                case '\\':
3387
                case '\'':
3388
                case '\"':
3389
                    break;
3390
                default:
3391
                    qemu_printf("unsupported escape code: '\\%c'\n", c);
3392
                    goto fail;
3393
                }
3394
                if ((q - buf) < buf_size - 1) {
3395
                    *q++ = c;
3396
                }
3397
            } else {
3398
                if ((q - buf) < buf_size - 1) {
3399
                    *q++ = *p;
3400
                }
3401
                p++;
3402
            }
3403
        }
3404
        if (*p != '\"') {
3405
            qemu_printf("unterminated string\n");
3406
            goto fail;
3407
        }
3408
        p++;
3409
    } else {
3410
        while (*p != '\0' && !qemu_isspace(*p)) {
3411
            if ((q - buf) < buf_size - 1) {
3412
                *q++ = *p;
3413
            }
3414
            p++;
3415
        }
3416
    }
3417
    *q = '\0';
3418
    *pp = p;
3419
    return 0;
3420
}
3421

    
3422
/*
3423
 * Store the command-name in cmdname, and return a pointer to
3424
 * the remaining of the command string.
3425
 */
3426
static const char *get_command_name(const char *cmdline,
3427
                                    char *cmdname, size_t nlen)
3428
{
3429
    size_t len;
3430
    const char *p, *pstart;
3431

    
3432
    p = cmdline;
3433
    while (qemu_isspace(*p))
3434
        p++;
3435
    if (*p == '\0')
3436
        return NULL;
3437
    pstart = p;
3438
    while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3439
        p++;
3440
    len = p - pstart;
3441
    if (len > nlen - 1)
3442
        len = nlen - 1;
3443
    memcpy(cmdname, pstart, len);
3444
    cmdname[len] = '\0';
3445
    return p;
3446
}
3447

    
3448
/**
3449
 * Read key of 'type' into 'key' and return the current
3450
 * 'type' pointer.
3451
 */
3452
static char *key_get_info(const char *type, char **key)
3453
{
3454
    size_t len;
3455
    char *p, *str;
3456

    
3457
    if (*type == ',')
3458
        type++;
3459

    
3460
    p = strchr(type, ':');
3461
    if (!p) {
3462
        *key = NULL;
3463
        return NULL;
3464
    }
3465
    len = p - type;
3466

    
3467
    str = qemu_malloc(len + 1);
3468
    memcpy(str, type, len);
3469
    str[len] = '\0';
3470

    
3471
    *key = str;
3472
    return ++p;
3473
}
3474

    
3475
static int default_fmt_format = 'x';
3476
static int default_fmt_size = 4;
3477

    
3478
#define MAX_ARGS 16
3479

    
3480
static int is_valid_option(const char *c, const char *typestr)
3481
{
3482
    char option[3];
3483
  
3484
    option[0] = '-';
3485
    option[1] = *c;
3486
    option[2] = '\0';
3487
  
3488
    typestr = strstr(typestr, option);
3489
    return (typestr != NULL);
3490
}
3491

    
3492
static const mon_cmd_t *monitor_find_command(const char *cmdname)
3493
{
3494
    const mon_cmd_t *cmd;
3495

    
3496
    for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
3497
        if (compare_cmd(cmdname, cmd->name)) {
3498
            return cmd;
3499
        }
3500
    }
3501

    
3502
    return NULL;
3503
}
3504

    
3505
static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3506
                                              const char *cmdline,
3507
                                              QDict *qdict)
3508
{
3509
    const char *p, *typestr;
3510
    int c;
3511
    const mon_cmd_t *cmd;
3512
    char cmdname[256];
3513
    char buf[1024];
3514
    char *key;
3515

    
3516
#ifdef DEBUG
3517
    monitor_printf(mon, "command='%s'\n", cmdline);
3518
#endif
3519

    
3520
    /* extract the command name */
3521
    p = get_command_name(cmdline, cmdname, sizeof(cmdname));
3522
    if (!p)
3523
        return NULL;
3524

    
3525
    cmd = monitor_find_command(cmdname);
3526
    if (!cmd) {
3527
        monitor_printf(mon, "unknown command: '%s'\n", cmdname);
3528
        return NULL;
3529
    }
3530

    
3531
    /* parse the parameters */
3532
    typestr = cmd->args_type;
3533
    for(;;) {
3534
        typestr = key_get_info(typestr, &key);
3535
        if (!typestr)
3536
            break;
3537
        c = *typestr;
3538
        typestr++;
3539
        switch(c) {
3540
        case 'F':
3541
        case 'B':
3542
        case 's':
3543
            {
3544
                int ret;
3545

    
3546
                while (qemu_isspace(*p))
3547
                    p++;
3548
                if (*typestr == '?') {
3549
                    typestr++;
3550
                    if (*p == '\0') {
3551
                        /* no optional string: NULL argument */
3552
                        break;
3553
                    }
3554
                }
3555
                ret = get_str(buf, sizeof(buf), &p);
3556
                if (ret < 0) {
3557
                    switch(c) {
3558
                    case 'F':
3559
                        monitor_printf(mon, "%s: filename expected\n",
3560
                                       cmdname);
3561
                        break;
3562
                    case 'B':
3563
                        monitor_printf(mon, "%s: block device name expected\n",
3564
                                       cmdname);
3565
                        break;
3566
                    default:
3567
                        monitor_printf(mon, "%s: string expected\n", cmdname);
3568
                        break;
3569
                    }
3570
                    goto fail;
3571
                }
3572
                qdict_put(qdict, key, qstring_from_str(buf));
3573
            }
3574
            break;
3575
        case '/':
3576
            {
3577
                int count, format, size;
3578

    
3579
                while (qemu_isspace(*p))
3580
                    p++;
3581
                if (*p == '/') {
3582
                    /* format found */
3583
                    p++;
3584
                    count = 1;
3585
                    if (qemu_isdigit(*p)) {
3586
                        count = 0;
3587
                        while (qemu_isdigit(*p)) {
3588
                            count = count * 10 + (*p - '0');
3589
                            p++;
3590
                        }
3591
                    }
3592
                    size = -1;
3593
                    format = -1;
3594
                    for(;;) {
3595
                        switch(*p) {
3596
                        case 'o':
3597
                        case 'd':
3598
                        case 'u':
3599
                        case 'x':
3600
                        case 'i':
3601
                        case 'c':
3602
                            format = *p++;
3603
                            break;
3604
                        case 'b':
3605
                            size = 1;
3606
                            p++;
3607
                            break;
3608
                        case 'h':
3609
                            size = 2;
3610
                            p++;
3611
                            break;
3612
                        case 'w':
3613
                            size = 4;
3614
                            p++;
3615
                            break;
3616
                        case 'g':
3617
                        case 'L':
3618
                            size = 8;
3619
                            p++;
3620
                            break;
3621
                        default:
3622
                            goto next;
3623
                        }
3624
                    }
3625
                next:
3626
                    if (*p != '\0' && !qemu_isspace(*p)) {
3627
                        monitor_printf(mon, "invalid char in format: '%c'\n",
3628
                                       *p);
3629
                        goto fail;
3630
                    }
3631
                    if (format < 0)
3632
                        format = default_fmt_format;
3633
                    if (format != 'i') {
3634
                        /* for 'i', not specifying a size gives -1 as size */
3635
                        if (size < 0)
3636
                            size = default_fmt_size;
3637
                        default_fmt_size = size;
3638
                    }
3639
                    default_fmt_format = format;
3640
                } else {
3641
                    count = 1;
3642
                    format = default_fmt_format;
3643
                    if (format != 'i') {
3644
                        size = default_fmt_size;
3645
                    } else {
3646
                        size = -1;
3647
                    }
3648
                }
3649
                qdict_put(qdict, "count", qint_from_int(count));
3650
                qdict_put(qdict, "format", qint_from_int(format));
3651
                qdict_put(qdict, "size", qint_from_int(size));
3652
            }
3653
            break;
3654
        case 'i':
3655
        case 'l':
3656
        case 'M':
3657
            {
3658
                int64_t val;
3659

    
3660
                while (qemu_isspace(*p))
3661
                    p++;
3662
                if (*typestr == '?' || *typestr == '.') {
3663
                    if (*typestr == '?') {
3664
                        if (*p == '\0') {
3665
                            typestr++;
3666
                            break;
3667
                        }
3668
                    } else {
3669
                        if (*p == '.') {
3670
                            p++;
3671
                            while (qemu_isspace(*p))
3672
                                p++;
3673
                        } else {
3674
                            typestr++;
3675
                            break;
3676
                        }
3677
                    }
3678
                    typestr++;
3679
                }
3680
                if (get_expr(mon, &val, &p))
3681
                    goto fail;
3682
                /* Check if 'i' is greater than 32-bit */
3683
                if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3684
                    monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3685
                    monitor_printf(mon, "integer is for 32-bit values\n");
3686
                    goto fail;
3687
                } else if (c == 'M') {
3688
                    val <<= 20;
3689
                }
3690
                qdict_put(qdict, key, qint_from_int(val));
3691
            }
3692
            break;
3693
        case 'b':
3694
        case 'T':
3695
            {
3696
                double val;
3697

    
3698
                while (qemu_isspace(*p))
3699
                    p++;
3700
                if (*typestr == '?') {
3701
                    typestr++;
3702
                    if (*p == '\0') {
3703
                        break;
3704
                    }
3705
                }
3706
                if (get_double(mon, &val, &p) < 0) {
3707
                    goto fail;
3708
                }
3709
                if (c == 'b' && *p) {
3710
                    switch (*p) {
3711
                    case 'K': case 'k':
3712
                        val *= 1 << 10; p++; break;
3713
                    case 'M': case 'm':
3714
                        val *= 1 << 20; p++; break;
3715
                    case 'G': case 'g':
3716
                        val *= 1 << 30; p++; break;
3717
                    }
3718
                }
3719
                if (c == 'T' && p[0] && p[1] == 's') {
3720
                    switch (*p) {
3721
                    case 'm':
3722
                        val /= 1e3; p += 2; break;
3723
                    case 'u':
3724
                        val /= 1e6; p += 2; break;
3725
                    case 'n':
3726
                        val /= 1e9; p += 2; break;
3727
                    }
3728
                }
3729
                if (*p && !qemu_isspace(*p)) {
3730
                    monitor_printf(mon, "Unknown unit suffix\n");
3731
                    goto fail;
3732
                }
3733
                qdict_put(qdict, key, qfloat_from_double(val));
3734
            }
3735
            break;
3736
        case '-':
3737
            {
3738
                const char *tmp = p;
3739
                int has_option, skip_key = 0;
3740
                /* option */
3741

    
3742
                c = *typestr++;
3743
                if (c == '\0')
3744
                    goto bad_type;
3745
                while (qemu_isspace(*p))
3746
                    p++;
3747
                has_option = 0;
3748
                if (*p == '-') {
3749
                    p++;
3750
                    if(c != *p) {
3751
                        if(!is_valid_option(p, typestr)) {
3752
                  
3753
                            monitor_printf(mon, "%s: unsupported option -%c\n",
3754
                                           cmdname, *p);
3755
                            goto fail;
3756
                        } else {
3757
                            skip_key = 1;
3758
                        }
3759
                    }
3760
                    if(skip_key) {
3761
                        p = tmp;
3762
                    } else {
3763
                        p++;
3764
                        has_option = 1;
3765
                    }
3766
                }
3767
                qdict_put(qdict, key, qint_from_int(has_option));
3768
            }
3769
            break;
3770
        default:
3771
        bad_type:
3772
            monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
3773
            goto fail;
3774
        }
3775
        qemu_free(key);
3776
        key = NULL;
3777
    }
3778
    /* check that all arguments were parsed */
3779
    while (qemu_isspace(*p))
3780
        p++;
3781
    if (*p != '\0') {
3782
        monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3783
                       cmdname);
3784
        goto fail;
3785
    }
3786

    
3787
    return cmd;
3788

    
3789
fail:
3790
    qemu_free(key);
3791
    return NULL;
3792
}
3793

    
3794
static void monitor_print_error(Monitor *mon)
3795
{
3796
    qerror_print(mon->error);
3797
    QDECREF(mon->error);
3798
    mon->error = NULL;
3799
}
3800

    
3801
static int is_async_return(const QObject *data)
3802
{
3803
    if (data && qobject_type(data) == QTYPE_QDICT) {
3804
        return qdict_haskey(qobject_to_qdict(data), "__mon_async");
3805
    }
3806

    
3807
    return 0;
3808
}
3809

    
3810
static void monitor_call_handler(Monitor *mon, const mon_cmd_t *cmd,
3811
                                 const QDict *params)
3812
{
3813
    QObject *data = NULL;
3814

    
3815
    if (cmd->cmd_new_ret) {
3816
        cmd->cmd_new_ret(mon, params, &data);
3817
    } else {
3818
        cmd->mhandler.cmd_new(mon, params, &data);
3819
    }
3820

    
3821
    if (is_async_return(data)) {
3822
        /*
3823
         * Asynchronous commands have no initial return data but they can
3824
         * generate errors.  Data is returned via the async completion handler.
3825
         */
3826
        if (monitor_ctrl_mode(mon) && monitor_has_error(mon)) {
3827
            monitor_protocol_emitter(mon, NULL);
3828
        }
3829
    } else if (monitor_ctrl_mode(mon)) {
3830
        /* Monitor Protocol */
3831
        monitor_protocol_emitter(mon, data);
3832
    } else {
3833
        /* User Protocol */
3834
         if (data)
3835
            cmd->user_print(mon, data);
3836
    }
3837

    
3838
    qobject_decref(data);
3839
}
3840

    
3841
static void handle_user_command(Monitor *mon, const char *cmdline)
3842
{
3843
    QDict *qdict;
3844
    const mon_cmd_t *cmd;
3845

    
3846
    qdict = qdict_new();
3847

    
3848
    cmd = monitor_parse_command(mon, cmdline, qdict);
3849
    if (!cmd)
3850
        goto out;
3851

    
3852
    qemu_errors_to_mon(mon);
3853

    
3854
    if (monitor_handler_is_async(cmd)) {
3855
        user_async_cmd_handler(mon, cmd, qdict);
3856
    } else if (monitor_handler_ported(cmd)) {
3857
        monitor_call_handler(mon, cmd, qdict);
3858
    } else {
3859
        cmd->mhandler.cmd(mon, qdict);
3860
    }
3861

    
3862
    if (monitor_has_error(mon))
3863
        monitor_print_error(mon);
3864

    
3865
    qemu_errors_to_previous();
3866

    
3867
out:
3868
    QDECREF(qdict);
3869
}
3870

    
3871
static void cmd_completion(const char *name, const char *list)
3872
{
3873
    const char *p, *pstart;
3874
    char cmd[128];
3875
    int len;
3876

    
3877
    p = list;
3878
    for(;;) {
3879
        pstart = p;
3880
        p = strchr(p, '|');
3881
        if (!p)
3882
            p = pstart + strlen(pstart);
3883
        len = p - pstart;
3884
        if (len > sizeof(cmd) - 2)
3885
            len = sizeof(cmd) - 2;
3886
        memcpy(cmd, pstart, len);
3887
        cmd[len] = '\0';
3888
        if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3889
            readline_add_completion(cur_mon->rs, cmd);
3890
        }
3891
        if (*p == '\0')
3892
            break;
3893
        p++;
3894
    }
3895
}
3896

    
3897
static void file_completion(const char *input)
3898
{
3899
    DIR *ffs;
3900
    struct dirent *d;
3901
    char path[1024];
3902
    char file[1024], file_prefix[1024];
3903
    int input_path_len;
3904
    const char *p;
3905

    
3906
    p = strrchr(input, '/');
3907
    if (!p) {
3908
        input_path_len = 0;
3909
        pstrcpy(file_prefix, sizeof(file_prefix), input);
3910
        pstrcpy(path, sizeof(path), ".");
3911
    } else {
3912
        input_path_len = p - input + 1;
3913
        memcpy(path, input, input_path_len);
3914
        if (input_path_len > sizeof(path) - 1)
3915
            input_path_len = sizeof(path) - 1;
3916
        path[input_path_len] = '\0';
3917
        pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3918
    }
3919
#ifdef DEBUG_COMPLETION
3920
    monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
3921
                   input, path, file_prefix);
3922
#endif
3923
    ffs = opendir(path);
3924
    if (!ffs)
3925
        return;
3926
    for(;;) {
3927
        struct stat sb;
3928
        d = readdir(ffs);
3929
        if (!d)
3930
            break;
3931
        if (strstart(d->d_name, file_prefix, NULL)) {
3932
            memcpy(file, input, input_path_len);
3933
            if (input_path_len < sizeof(file))
3934
                pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3935
                        d->d_name);
3936
            /* stat the file to find out if it's a directory.
3937
             * In that case add a slash to speed up typing long paths
3938
             */
3939
            stat(file, &sb);
3940
            if(S_ISDIR(sb.st_mode))
3941
                pstrcat(file, sizeof(file), "/");
3942
            readline_add_completion(cur_mon->rs, file);
3943
        }
3944
    }
3945
    closedir(ffs);
3946
}
3947

    
3948
static void block_completion_it(void *opaque, BlockDriverState *bs)
3949
{
3950
    const char *name = bdrv_get_device_name(bs);
3951
    const char *input = opaque;
3952

    
3953
    if (input[0] == '\0' ||
3954
        !strncmp(name, (char *)input, strlen(input))) {
3955
        readline_add_completion(cur_mon->rs, name);
3956
    }
3957
}
3958

    
3959
/* NOTE: this parser is an approximate form of the real command parser */
3960
static void parse_cmdline(const char *cmdline,
3961
                         int *pnb_args, char **args)
3962
{
3963
    const char *p;
3964
    int nb_args, ret;
3965
    char buf[1024];
3966

    
3967
    p = cmdline;
3968
    nb_args = 0;
3969
    for(;;) {
3970
        while (qemu_isspace(*p))
3971
            p++;
3972
        if (*p == '\0')
3973
            break;
3974
        if (nb_args >= MAX_ARGS)
3975
            break;
3976
        ret = get_str(buf, sizeof(buf), &p);
3977
        args[nb_args] = qemu_strdup(buf);
3978
        nb_args++;
3979
        if (ret < 0)
3980
            break;
3981
    }
3982
    *pnb_args = nb_args;
3983
}
3984

    
3985
static const char *next_arg_type(const char *typestr)
3986
{
3987
    const char *p = strchr(typestr, ':');
3988
    return (p != NULL ? ++p : typestr);
3989
}
3990

    
3991
static void monitor_find_completion(const char *cmdline)
3992
{
3993
    const char *cmdname;
3994
    char *args[MAX_ARGS];
3995
    int nb_args, i, len;
3996
    const char *ptype, *str;
3997
    const mon_cmd_t *cmd;
3998
    const KeyDef *key;
3999

    
4000
    parse_cmdline(cmdline, &nb_args, args);
4001
#ifdef DEBUG_COMPLETION
4002
    for(i = 0; i < nb_args; i++) {
4003
        monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
4004
    }
4005
#endif
4006

    
4007
    /* if the line ends with a space, it means we want to complete the
4008
       next arg */
4009
    len = strlen(cmdline);
4010
    if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4011
        if (nb_args >= MAX_ARGS)
4012
            return;
4013
        args[nb_args++] = qemu_strdup("");
4014
    }
4015
    if (nb_args <= 1) {
4016
        /* command completion */
4017
        if (nb_args == 0)
4018
            cmdname = "";
4019
        else
4020
            cmdname = args[0];
4021
        readline_set_completion_index(cur_mon->rs, strlen(cmdname));
4022
        for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
4023
            cmd_completion(cmdname, cmd->name);
4024
        }
4025
    } else {
4026
        /* find the command */
4027
        for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
4028
            if (compare_cmd(args[0], cmd->name))
4029
                goto found;
4030
        }
4031
        return;
4032
    found:
4033
        ptype = next_arg_type(cmd->args_type);
4034
        for(i = 0; i < nb_args - 2; i++) {
4035
            if (*ptype != '\0') {
4036
                ptype = next_arg_type(ptype);
4037
                while (*ptype == '?')
4038
                    ptype = next_arg_type(ptype);
4039
            }
4040
        }
4041
        str = args[nb_args - 1];
4042
        if (*ptype == '-' && ptype[1] != '\0') {
4043
            ptype += 2;
4044
        }
4045
        switch(*ptype) {
4046
        case 'F':
4047
            /* file completion */
4048
            readline_set_completion_index(cur_mon->rs, strlen(str));
4049
            file_completion(str);
4050
            break;
4051
        case 'B':
4052
            /* block device name completion */
4053
            readline_set_completion_index(cur_mon->rs, strlen(str));
4054
            bdrv_iterate(block_completion_it, (void *)str);
4055
            break;
4056
        case 's':
4057
            /* XXX: more generic ? */
4058
            if (!strcmp(cmd->name, "info")) {
4059
                readline_set_completion_index(cur_mon->rs, strlen(str));
4060
                for(cmd = info_cmds; cmd->name != NULL; cmd++) {
4061
                    cmd_completion(str, cmd->name);
4062
                }
4063
            } else if (!strcmp(cmd->name, "sendkey")) {
4064
                char *sep = strrchr(str, '-');
4065
                if (sep)
4066
                    str = sep + 1;
4067
                readline_set_completion_index(cur_mon->rs, strlen(str));
4068
                for(key = key_defs; key->name != NULL; key++) {
4069
                    cmd_completion(str, key->name);
4070
                }
4071
            } else if (!strcmp(cmd->name, "help|?")) {
4072
                readline_set_completion_index(cur_mon->rs, strlen(str));
4073
                for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4074
                    cmd_completion(str, cmd->name);
4075
                }
4076
            }
4077
            break;
4078
        default:
4079
            break;
4080
        }
4081
    }
4082
    for(i = 0; i < nb_args; i++)
4083
        qemu_free(args[i]);
4084
}
4085

    
4086
static int monitor_can_read(void *opaque)
4087
{
4088
    Monitor *mon = opaque;
4089

    
4090
    return (mon->suspend_cnt == 0) ? 1 : 0;
4091
}
4092

    
4093
typedef struct CmdArgs {
4094
    QString *name;
4095
    int type;
4096
    int flag;
4097
    int optional;
4098
} CmdArgs;
4099

    
4100
static int check_opt(const CmdArgs *cmd_args, const char *name, QDict *args)
4101
{
4102
    if (!cmd_args->optional) {
4103
        qemu_error_new(QERR_MISSING_PARAMETER, name);
4104
        return -1;
4105
    }
4106

    
4107
    if (cmd_args->type == '-') {
4108
        /* handlers expect a value, they need to be changed */
4109
        qdict_put(args, name, qint_from_int(0));
4110
    }
4111

    
4112
    return 0;
4113
}
4114

    
4115
static int check_arg(const CmdArgs *cmd_args, QDict *args)
4116
{
4117
    QObject *value;
4118
    const char *name;
4119

    
4120
    name = qstring_get_str(cmd_args->name);
4121

    
4122
    if (!args) {
4123
        return check_opt(cmd_args, name, args);
4124
    }
4125

    
4126
    value = qdict_get(args, name);
4127
    if (!value) {
4128
        return check_opt(cmd_args, name, args);
4129
    }
4130

    
4131
    switch (cmd_args->type) {
4132
        case 'F':
4133
        case 'B':
4134
        case 's':
4135
            if (qobject_type(value) != QTYPE_QSTRING) {
4136
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "string");
4137
                return -1;
4138
            }
4139
            break;
4140
        case '/': {
4141
            int i;
4142
            const char *keys[] = { "count", "format", "size", NULL };
4143

    
4144
            for (i = 0; keys[i]; i++) {
4145
                QObject *obj = qdict_get(args, keys[i]);
4146
                if (!obj) {
4147
                    qemu_error_new(QERR_MISSING_PARAMETER, name);
4148
                    return -1;
4149
                }
4150
                if (qobject_type(obj) != QTYPE_QINT) {
4151
                    qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "int");
4152
                    return -1;
4153
                }
4154
            }
4155
            break;
4156
        }
4157
        case 'i':
4158
        case 'l':
4159
        case 'M':
4160
            if (qobject_type(value) != QTYPE_QINT) {
4161
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "int");
4162
                return -1;
4163
            }
4164
            break;
4165
        case 'b':
4166
        case 'T':
4167
            if (qobject_type(value) != QTYPE_QINT && qobject_type(value) != QTYPE_QFLOAT) {
4168
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "number");
4169
                return -1;
4170
            }
4171
            break;
4172
        case '-':
4173
            if (qobject_type(value) != QTYPE_QINT &&
4174
                qobject_type(value) != QTYPE_QBOOL) {
4175
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "bool");
4176
                return -1;
4177
            }
4178
            if (qobject_type(value) == QTYPE_QBOOL) {
4179
                /* handlers expect a QInt, they need to be changed */
4180
                qdict_put(args, name,
4181
                         qint_from_int(qbool_get_int(qobject_to_qbool(value))));
4182
            }
4183
            break;
4184
        default:
4185
            /* impossible */
4186
            abort();
4187
    }
4188

    
4189
    return 0;
4190
}
4191

    
4192
static void cmd_args_init(CmdArgs *cmd_args)
4193
{
4194
    cmd_args->name = qstring_new();
4195
    cmd_args->type = cmd_args->flag = cmd_args->optional = 0;
4196
}
4197

    
4198
/*
4199
 * This is not trivial, we have to parse Monitor command's argument
4200
 * type syntax to be able to check the arguments provided by clients.
4201
 *
4202
 * In the near future we will be using an array for that and will be
4203
 * able to drop all this parsing...
4204
 */
4205
static int monitor_check_qmp_args(const mon_cmd_t *cmd, QDict *args)
4206
{
4207
    int err;
4208
    const char *p;
4209
    CmdArgs cmd_args;
4210

    
4211
    if (cmd->args_type == NULL) {
4212
        return (qdict_size(args) == 0 ? 0 : -1);
4213
    }
4214

    
4215
    err = 0;
4216
    cmd_args_init(&cmd_args);
4217

    
4218
    for (p = cmd->args_type;; p++) {
4219
        if (*p == ':') {
4220
            cmd_args.type = *++p;
4221
            p++;
4222
            if (cmd_args.type == '-') {
4223
                cmd_args.flag = *p++;
4224
                cmd_args.optional = 1;
4225
            } else if (*p == '?') {
4226
                cmd_args.optional = 1;
4227
                p++;
4228
            }
4229

    
4230
            assert(*p == ',' || *p == '\0');
4231
            err = check_arg(&cmd_args, args);
4232

    
4233
            QDECREF(cmd_args.name);
4234
            cmd_args_init(&cmd_args);
4235

    
4236
            if (err < 0) {
4237
                break;
4238
            }
4239
        } else {
4240
            qstring_append_chr(cmd_args.name, *p);
4241
        }
4242

    
4243
        if (*p == '\0') {
4244
            break;
4245
        }
4246
    }
4247

    
4248
    QDECREF(cmd_args.name);
4249
    return err;
4250
}
4251

    
4252
static int invalid_qmp_mode(const Monitor *mon, const char *cmd_name)
4253
{
4254
    int is_cap = compare_cmd(cmd_name, "qmp_capabilities");
4255
    return (qmp_cmd_mode(mon) ? is_cap : !is_cap);
4256
}
4257

    
4258
static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
4259
{
4260
    int err;
4261
    QObject *obj;
4262
    QDict *input, *args;
4263
    const mon_cmd_t *cmd;
4264
    Monitor *mon = cur_mon;
4265
    const char *cmd_name, *info_item;
4266

    
4267
    args = NULL;
4268
    qemu_errors_to_mon(mon);
4269

    
4270
    obj = json_parser_parse(tokens, NULL);
4271
    if (!obj) {
4272
        // FIXME: should be triggered in json_parser_parse()
4273
        qemu_error_new(QERR_JSON_PARSING);
4274
        goto err_out;
4275
    } else if (qobject_type(obj) != QTYPE_QDICT) {
4276
        qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "object");
4277
        qobject_decref(obj);
4278
        goto err_out;
4279
    }
4280

    
4281
    input = qobject_to_qdict(obj);
4282

    
4283
    mon->mc->id = qdict_get(input, "id");
4284
    qobject_incref(mon->mc->id);
4285

    
4286
    obj = qdict_get(input, "execute");
4287
    if (!obj) {
4288
        qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4289
        goto err_input;
4290
    } else if (qobject_type(obj) != QTYPE_QSTRING) {
4291
        qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "string");
4292
        goto err_input;
4293
    }
4294

    
4295
    cmd_name = qstring_get_str(qobject_to_qstring(obj));
4296

    
4297
    if (invalid_qmp_mode(mon, cmd_name)) {
4298
        qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4299
        goto err_input;
4300
    }
4301

    
4302
    /*
4303
     * XXX: We need this special case until we get info handlers
4304
     * converted into 'query-' commands
4305
     */
4306
    if (compare_cmd(cmd_name, "info")) {
4307
        qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4308
        goto err_input;
4309
    } else if (strstart(cmd_name, "query-", &info_item)) {
4310
        cmd = monitor_find_command("info");
4311
        qdict_put_obj(input, "arguments",
4312
                      qobject_from_jsonf("{ 'item': %s }", info_item));
4313
    } else {
4314
        cmd = monitor_find_command(cmd_name);
4315
        if (!cmd || !monitor_handler_ported(cmd)) {
4316
            qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4317
            goto err_input;
4318
        }
4319
    }
4320

    
4321
    obj = qdict_get(input, "arguments");
4322
    if (!obj) {
4323
        args = qdict_new();
4324
    } else {
4325
        args = qobject_to_qdict(obj);
4326
        QINCREF(args);
4327
    }
4328

    
4329
    QDECREF(input);
4330

    
4331
    err = monitor_check_qmp_args(cmd, args);
4332
    if (err < 0) {
4333
        goto err_out;
4334
    }
4335

    
4336
    if (monitor_handler_is_async(cmd)) {
4337
        qmp_async_cmd_handler(mon, cmd, args);
4338
    } else {
4339
        monitor_call_handler(mon, cmd, args);
4340
    }
4341
    goto out;
4342

    
4343
err_input:
4344
    QDECREF(input);
4345
err_out:
4346
    monitor_protocol_emitter(mon, NULL);
4347
out:
4348
    QDECREF(args);
4349
    qemu_errors_to_previous();
4350
}
4351

    
4352
/**
4353
 * monitor_control_read(): Read and handle QMP input
4354
 */
4355
static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
4356
{
4357
    Monitor *old_mon = cur_mon;
4358

    
4359
    cur_mon = opaque;
4360

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

    
4363
    cur_mon = old_mon;
4364
}
4365

    
4366
static void monitor_read(void *opaque, const uint8_t *buf, int size)
4367
{
4368
    Monitor *old_mon = cur_mon;
4369
    int i;
4370

    
4371
    cur_mon = opaque;
4372

    
4373
    if (cur_mon->rs) {
4374
        for (i = 0; i < size; i++)
4375
            readline_handle_byte(cur_mon->rs, buf[i]);
4376
    } else {
4377
        if (size == 0 || buf[size - 1] != 0)
4378
            monitor_printf(cur_mon, "corrupted command\n");
4379
        else
4380
            handle_user_command(cur_mon, (char *)buf);
4381
    }
4382

    
4383
    cur_mon = old_mon;
4384
}
4385

    
4386
static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
4387
{
4388
    monitor_suspend(mon);
4389
    handle_user_command(mon, cmdline);
4390
    monitor_resume(mon);
4391
}
4392

    
4393
int monitor_suspend(Monitor *mon)
4394
{
4395
    if (!mon->rs)
4396
        return -ENOTTY;
4397
    mon->suspend_cnt++;
4398
    return 0;
4399
}
4400

    
4401
void monitor_resume(Monitor *mon)
4402
{
4403
    if (!mon->rs)
4404
        return;
4405
    if (--mon->suspend_cnt == 0)
4406
        readline_show_prompt(mon->rs);
4407
}
4408

    
4409
static QObject *get_qmp_greeting(void)
4410
{
4411
    QObject *ver;
4412

    
4413
    do_info_version(NULL, &ver);
4414
    return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
4415
}
4416

    
4417
/**
4418
 * monitor_control_event(): Print QMP gretting
4419
 */
4420
static void monitor_control_event(void *opaque, int event)
4421
{
4422
    QObject *data;
4423
    Monitor *mon = opaque;
4424

    
4425
    switch (event) {
4426
    case CHR_EVENT_OPENED:
4427
        mon->mc->command_mode = 0;
4428
        json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4429
        data = get_qmp_greeting();
4430
        monitor_json_emitter(mon, data);
4431
        qobject_decref(data);
4432
        break;
4433
    case CHR_EVENT_CLOSED:
4434
        json_message_parser_destroy(&mon->mc->parser);
4435
        break;
4436
    }
4437
}
4438

    
4439
static void monitor_event(void *opaque, int event)
4440
{
4441
    Monitor *mon = opaque;
4442

    
4443
    switch (event) {
4444
    case CHR_EVENT_MUX_IN:
4445
        mon->mux_out = 0;
4446
        if (mon->reset_seen) {
4447
            readline_restart(mon->rs);
4448
            monitor_resume(mon);
4449
            monitor_flush(mon);
4450
        } else {
4451
            mon->suspend_cnt = 0;
4452
        }
4453
        break;
4454

    
4455
    case CHR_EVENT_MUX_OUT:
4456
        if (mon->reset_seen) {
4457
            if (mon->suspend_cnt == 0) {
4458
                monitor_printf(mon, "\n");
4459
            }
4460
            monitor_flush(mon);
4461
            monitor_suspend(mon);
4462
        } else {
4463
            mon->suspend_cnt++;
4464
        }
4465
        mon->mux_out = 1;
4466
        break;
4467

    
4468
    case CHR_EVENT_OPENED:
4469
        monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4470
                       "information\n", QEMU_VERSION);
4471
        if (!mon->mux_out) {
4472
            readline_show_prompt(mon->rs);
4473
        }
4474
        mon->reset_seen = 1;
4475
        break;
4476
    }
4477
}
4478

    
4479

    
4480
/*
4481
 * Local variables:
4482
 *  c-indent-level: 4
4483
 *  c-basic-offset: 4
4484
 *  tab-width: 8
4485
 * End:
4486
 */
4487

    
4488
void monitor_init(CharDriverState *chr, int flags)
4489
{
4490
    static int is_first_init = 1;
4491
    Monitor *mon;
4492

    
4493
    if (is_first_init) {
4494
        key_timer = qemu_new_timer(vm_clock, release_keys, NULL);
4495
        is_first_init = 0;
4496
    }
4497

    
4498
    mon = qemu_mallocz(sizeof(*mon));
4499

    
4500
    mon->chr = chr;
4501
    mon->flags = flags;
4502
    if (flags & MONITOR_USE_READLINE) {
4503
        mon->rs = readline_init(mon, monitor_find_completion);
4504
        monitor_read_command(mon, 0);
4505
    }
4506

    
4507
    if (monitor_ctrl_mode(mon)) {
4508
        mon->mc = qemu_mallocz(sizeof(MonitorControl));
4509
        /* Control mode requires special handlers */
4510
        qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
4511
                              monitor_control_event, mon);
4512
    } else {
4513
        qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4514
                              monitor_event, mon);
4515
    }
4516

    
4517
    QLIST_INSERT_HEAD(&mon_list, mon, entry);
4518
    if (!cur_mon || (flags & MONITOR_IS_DEFAULT))
4519
        cur_mon = mon;
4520
}
4521

    
4522
static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
4523
{
4524
    BlockDriverState *bs = opaque;
4525
    int ret = 0;
4526

    
4527
    if (bdrv_set_key(bs, password) != 0) {
4528
        monitor_printf(mon, "invalid password\n");
4529
        ret = -EPERM;
4530
    }
4531
    if (mon->password_completion_cb)
4532
        mon->password_completion_cb(mon->password_opaque, ret);
4533

    
4534
    monitor_read_command(mon, 1);
4535
}
4536

    
4537
void monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4538
                                 BlockDriverCompletionFunc *completion_cb,
4539
                                 void *opaque)
4540
{
4541
    int err;
4542

    
4543
    if (!bdrv_key_required(bs)) {
4544
        if (completion_cb)
4545
            completion_cb(opaque, 0);
4546
        return;
4547
    }
4548

    
4549
    if (monitor_ctrl_mode(mon)) {
4550
        qemu_error_new(QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs));
4551
        return;
4552
    }
4553

    
4554
    monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4555
                   bdrv_get_encrypted_filename(bs));
4556

    
4557
    mon->password_completion_cb = completion_cb;
4558
    mon->password_opaque = opaque;
4559

    
4560
    err = monitor_read_password(mon, bdrv_password_cb, bs);
4561

    
4562
    if (err && completion_cb)
4563
        completion_cb(opaque, err);
4564
}
4565

    
4566
typedef struct QemuErrorSink QemuErrorSink;
4567
struct QemuErrorSink {
4568
    enum {
4569
        ERR_SINK_FILE,
4570
        ERR_SINK_MONITOR,
4571
    } dest;
4572
    union {
4573
        FILE    *fp;
4574
        Monitor *mon;
4575
    };
4576
    QemuErrorSink *previous;
4577
};
4578

    
4579
static QemuErrorSink *qemu_error_sink;
4580

    
4581
void qemu_errors_to_file(FILE *fp)
4582
{
4583
    QemuErrorSink *sink;
4584

    
4585
    sink = qemu_mallocz(sizeof(*sink));
4586
    sink->dest = ERR_SINK_FILE;
4587
    sink->fp = fp;
4588
    sink->previous = qemu_error_sink;
4589
    qemu_error_sink = sink;
4590
}
4591

    
4592
void qemu_errors_to_mon(Monitor *mon)
4593
{
4594
    QemuErrorSink *sink;
4595

    
4596
    sink = qemu_mallocz(sizeof(*sink));
4597
    sink->dest = ERR_SINK_MONITOR;
4598
    sink->mon = mon;
4599
    sink->previous = qemu_error_sink;
4600
    qemu_error_sink = sink;
4601
}
4602

    
4603
void qemu_errors_to_previous(void)
4604
{
4605
    QemuErrorSink *sink;
4606

    
4607
    assert(qemu_error_sink != NULL);
4608
    sink = qemu_error_sink;
4609
    qemu_error_sink = sink->previous;
4610
    qemu_free(sink);
4611
}
4612

    
4613
void qemu_error(const char *fmt, ...)
4614
{
4615
    va_list args;
4616

    
4617
    assert(qemu_error_sink != NULL);
4618
    switch (qemu_error_sink->dest) {
4619
    case ERR_SINK_FILE:
4620
        va_start(args, fmt);
4621
        vfprintf(qemu_error_sink->fp, fmt, args);
4622
        va_end(args);
4623
        break;
4624
    case ERR_SINK_MONITOR:
4625
        va_start(args, fmt);
4626
        monitor_vprintf(qemu_error_sink->mon, fmt, args);
4627
        va_end(args);
4628
        break;
4629
    }
4630
}
4631

    
4632
void qemu_error_internal(const char *file, int linenr, const char *func,
4633
                         const char *fmt, ...)
4634
{
4635
    va_list va;
4636
    QError *qerror;
4637

    
4638
    assert(qemu_error_sink != NULL);
4639

    
4640
    va_start(va, fmt);
4641
    qerror = qerror_from_info(file, linenr, func, fmt, &va);
4642
    va_end(va);
4643

    
4644
    switch (qemu_error_sink->dest) {
4645
    case ERR_SINK_FILE:
4646
        qerror_print(qerror);
4647
        QDECREF(qerror);
4648
        break;
4649
    case ERR_SINK_MONITOR:
4650
        /* report only the first error */
4651
        if (!qemu_error_sink->mon->error) {
4652
            qemu_error_sink->mon->error = qerror;
4653
        } else {
4654
            /* XXX: warn the programmer */
4655
            QDECREF(qerror);
4656
        }
4657
        break;
4658
    }
4659
}