Statistics
| Branch: | Revision:

root / monitor.c @ 9869622e

History | View | Annotate | Download (122.4 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 int 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
        return -1;
930
    }
931
    return 0;
932
}
933

    
934
static void do_info_jit(Monitor *mon)
935
{
936
    dump_exec_info((FILE *)mon, monitor_fprintf);
937
}
938

    
939
static void do_info_history(Monitor *mon)
940
{
941
    int i;
942
    const char *str;
943

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

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

    
962
    env = mon_get_cpu();
963
    cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
964
}
965
#endif
966

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

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

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

    
1001
    bs = bdrv_find(filename);
1002
    if (!bs) {
1003
        qemu_error_new(QERR_DEVICE_NOT_FOUND, filename);
1004
        return -1;
1005
    }
1006
    return eject_device(mon, bs, force);
1007
}
1008

    
1009
static int do_block_set_passwd(Monitor *mon, const QDict *qdict,
1010
                                QObject **ret_data)
1011
{
1012
    BlockDriverState *bs;
1013

    
1014
    bs = bdrv_find(qdict_get_str(qdict, "device"));
1015
    if (!bs) {
1016
        qemu_error_new(QERR_DEVICE_NOT_FOUND, qdict_get_str(qdict, "device"));
1017
        return -1;
1018
    }
1019

    
1020
    if (bdrv_set_key(bs, qdict_get_str(qdict, "password")) < 0) {
1021
        qemu_error_new(QERR_INVALID_PASSWORD);
1022
        return -1;
1023
    }
1024

    
1025
    return 0;
1026
}
1027

    
1028
static void do_change_block(Monitor *mon, const char *device,
1029
                            const char *filename, const char *fmt)
1030
{
1031
    BlockDriverState *bs;
1032
    BlockDriver *drv = NULL;
1033

    
1034
    bs = bdrv_find(device);
1035
    if (!bs) {
1036
        qemu_error_new(QERR_DEVICE_NOT_FOUND, device);
1037
        return;
1038
    }
1039
    if (fmt) {
1040
        drv = bdrv_find_whitelisted_format(fmt);
1041
        if (!drv) {
1042
            qemu_error_new(QERR_INVALID_BLOCK_FORMAT, fmt);
1043
            return;
1044
        }
1045
    }
1046
    if (eject_device(mon, bs, 0) < 0)
1047
        return;
1048
    bdrv_open2(bs, filename, BDRV_O_RDWR, drv);
1049
    monitor_read_bdrv_key_start(mon, bs, NULL, NULL);
1050
}
1051

    
1052
static void change_vnc_password(const char *password)
1053
{
1054
    if (vnc_display_password(NULL, password) < 0)
1055
        qemu_error_new(QERR_SET_PASSWD_FAILED);
1056

    
1057
}
1058

    
1059
static void change_vnc_password_cb(Monitor *mon, const char *password,
1060
                                   void *opaque)
1061
{
1062
    change_vnc_password(password);
1063
    monitor_read_command(mon, 1);
1064
}
1065

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

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

    
1099
static void do_screen_dump(Monitor *mon, const QDict *qdict)
1100
{
1101
    vga_hw_screen_dump(qdict_get_str(qdict, "filename"));
1102
}
1103

    
1104
static void do_logfile(Monitor *mon, const QDict *qdict)
1105
{
1106
    cpu_set_log_filename(qdict_get_str(qdict, "filename"));
1107
}
1108

    
1109
static void do_log(Monitor *mon, const QDict *qdict)
1110
{
1111
    int mask;
1112
    const char *items = qdict_get_str(qdict, "items");
1113

    
1114
    if (!strcmp(items, "none")) {
1115
        mask = 0;
1116
    } else {
1117
        mask = cpu_str_to_log_mask(items);
1118
        if (!mask) {
1119
            help_cmd(mon, "log");
1120
            return;
1121
        }
1122
    }
1123
    cpu_set_log(mask);
1124
}
1125

    
1126
static void do_singlestep(Monitor *mon, const QDict *qdict)
1127
{
1128
    const char *option = qdict_get_try_str(qdict, "option");
1129
    if (!option || !strcmp(option, "on")) {
1130
        singlestep = 1;
1131
    } else if (!strcmp(option, "off")) {
1132
        singlestep = 0;
1133
    } else {
1134
        monitor_printf(mon, "unexpected option %s\n", option);
1135
    }
1136
}
1137

    
1138
/**
1139
 * do_stop(): Stop VM execution
1140
 */
1141
static int do_stop(Monitor *mon, const QDict *qdict, QObject **ret_data)
1142
{
1143
    vm_stop(EXCP_INTERRUPT);
1144
    return 0;
1145
}
1146

    
1147
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs);
1148

    
1149
struct bdrv_iterate_context {
1150
    Monitor *mon;
1151
    int err;
1152
};
1153

    
1154
/**
1155
 * do_cont(): Resume emulation.
1156
 */
1157
static int do_cont(Monitor *mon, const QDict *qdict, QObject **ret_data)
1158
{
1159
    struct bdrv_iterate_context context = { mon, 0 };
1160

    
1161
    bdrv_iterate(encrypted_bdrv_it, &context);
1162
    /* only resume the vm if all keys are set and valid */
1163
    if (!context.err) {
1164
        vm_start();
1165
        return 0;
1166
    } else {
1167
        return -1;
1168
    }
1169
}
1170

    
1171
static void bdrv_key_cb(void *opaque, int err)
1172
{
1173
    Monitor *mon = opaque;
1174

    
1175
    /* another key was set successfully, retry to continue */
1176
    if (!err)
1177
        do_cont(mon, NULL, NULL);
1178
}
1179

    
1180
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs)
1181
{
1182
    struct bdrv_iterate_context *context = opaque;
1183

    
1184
    if (!context->err && bdrv_key_required(bs)) {
1185
        context->err = -EBUSY;
1186
        monitor_read_bdrv_key_start(context->mon, bs, bdrv_key_cb,
1187
                                    context->mon);
1188
    }
1189
}
1190

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

    
1207
static void do_watchdog_action(Monitor *mon, const QDict *qdict)
1208
{
1209
    const char *action = qdict_get_str(qdict, "action");
1210
    if (select_watchdog_action(action) == -1) {
1211
        monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1212
    }
1213
}
1214

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

    
1242
static void memory_dump(Monitor *mon, int count, int format, int wsize,
1243
                        target_phys_addr_t addr, int is_physical)
1244
{
1245
    CPUState *env;
1246
    int l, line_size, i, max_digits, len;
1247
    uint8_t buf[16];
1248
    uint64_t v;
1249

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

    
1280
    len = wsize * count;
1281
    if (wsize == 1)
1282
        line_size = 8;
1283
    else
1284
        line_size = 16;
1285
    max_digits = 0;
1286

    
1287
    switch(format) {
1288
    case 'o':
1289
        max_digits = (wsize * 8 + 2) / 3;
1290
        break;
1291
    default:
1292
    case 'x':
1293
        max_digits = (wsize * 8) / 4;
1294
        break;
1295
    case 'u':
1296
    case 'd':
1297
        max_digits = (wsize * 8 * 10 + 32) / 33;
1298
        break;
1299
    case 'c':
1300
        wsize = 1;
1301
        break;
1302
    }
1303

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

    
1364
static void do_memory_dump(Monitor *mon, const QDict *qdict)
1365
{
1366
    int count = qdict_get_int(qdict, "count");
1367
    int format = qdict_get_int(qdict, "format");
1368
    int size = qdict_get_int(qdict, "size");
1369
    target_long addr = qdict_get_int(qdict, "addr");
1370

    
1371
    memory_dump(mon, count, format, size, addr, 0);
1372
}
1373

    
1374
static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
1375
{
1376
    int count = qdict_get_int(qdict, "count");
1377
    int format = qdict_get_int(qdict, "format");
1378
    int size = qdict_get_int(qdict, "size");
1379
    target_phys_addr_t addr = qdict_get_int(qdict, "addr");
1380

    
1381
    memory_dump(mon, count, format, size, addr, 1);
1382
}
1383

    
1384
static void do_print(Monitor *mon, const QDict *qdict)
1385
{
1386
    int format = qdict_get_int(qdict, "format");
1387
    target_phys_addr_t val = qdict_get_int(qdict, "val");
1388

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

    
1431
static int do_memory_save(Monitor *mon, const QDict *qdict, QObject **ret_data)
1432
{
1433
    FILE *f;
1434
    uint32_t size = qdict_get_int(qdict, "size");
1435
    const char *filename = qdict_get_str(qdict, "filename");
1436
    target_long addr = qdict_get_int(qdict, "val");
1437
    uint32_t l;
1438
    CPUState *env;
1439
    uint8_t buf[1024];
1440
    int ret = -1;
1441

    
1442
    env = mon_get_cpu();
1443

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

    
1462
    ret = 0;
1463

    
1464
exit:
1465
    fclose(f);
1466
    return ret;
1467
}
1468

    
1469
static void do_physical_memory_save(Monitor *mon, const QDict *qdict,
1470
                                    QObject **ret_data)
1471
{
1472
    FILE *f;
1473
    uint32_t l;
1474
    uint8_t buf[1024];
1475
    uint32_t size = qdict_get_int(qdict, "size");
1476
    const char *filename = qdict_get_str(qdict, "filename");
1477
    target_phys_addr_t addr = qdict_get_int(qdict, "val");
1478

    
1479
    f = fopen(filename, "wb");
1480
    if (!f) {
1481
        qemu_error_new(QERR_OPEN_FILE_FAILED, filename);
1482
        return;
1483
    }
1484
    while (size != 0) {
1485
        l = sizeof(buf);
1486
        if (l > size)
1487
            l = size;
1488
        cpu_physical_memory_rw(addr, buf, l, 0);
1489
        if (fwrite(buf, 1, l, f) != l) {
1490
            monitor_printf(mon, "fwrite() error in do_physical_memory_save\n");
1491
            goto exit;
1492
        }
1493
        fflush(f);
1494
        addr += l;
1495
        size -= l;
1496
    }
1497
exit:
1498
    fclose(f);
1499
}
1500

    
1501
static void do_sum(Monitor *mon, const QDict *qdict)
1502
{
1503
    uint32_t addr;
1504
    uint8_t buf[1];
1505
    uint16_t sum;
1506
    uint32_t start = qdict_get_int(qdict, "start");
1507
    uint32_t size = qdict_get_int(qdict, "size");
1508

    
1509
    sum = 0;
1510
    for(addr = start; addr < (start + size); addr++) {
1511
        cpu_physical_memory_rw(addr, buf, 1, 0);
1512
        /* BSD sum algorithm ('sum' Unix command) */
1513
        sum = (sum >> 1) | (sum << 15);
1514
        sum += buf[0];
1515
    }
1516
    monitor_printf(mon, "%05d\n", sum);
1517
}
1518

    
1519
typedef struct {
1520
    int keycode;
1521
    const char *name;
1522
} KeyDef;
1523

    
1524
static const KeyDef key_defs[] = {
1525
    { 0x2a, "shift" },
1526
    { 0x36, "shift_r" },
1527

    
1528
    { 0x38, "alt" },
1529
    { 0xb8, "alt_r" },
1530
    { 0x64, "altgr" },
1531
    { 0xe4, "altgr_r" },
1532
    { 0x1d, "ctrl" },
1533
    { 0x9d, "ctrl_r" },
1534

    
1535
    { 0xdd, "menu" },
1536

    
1537
    { 0x01, "esc" },
1538

    
1539
    { 0x02, "1" },
1540
    { 0x03, "2" },
1541
    { 0x04, "3" },
1542
    { 0x05, "4" },
1543
    { 0x06, "5" },
1544
    { 0x07, "6" },
1545
    { 0x08, "7" },
1546
    { 0x09, "8" },
1547
    { 0x0a, "9" },
1548
    { 0x0b, "0" },
1549
    { 0x0c, "minus" },
1550
    { 0x0d, "equal" },
1551
    { 0x0e, "backspace" },
1552

    
1553
    { 0x0f, "tab" },
1554
    { 0x10, "q" },
1555
    { 0x11, "w" },
1556
    { 0x12, "e" },
1557
    { 0x13, "r" },
1558
    { 0x14, "t" },
1559
    { 0x15, "y" },
1560
    { 0x16, "u" },
1561
    { 0x17, "i" },
1562
    { 0x18, "o" },
1563
    { 0x19, "p" },
1564

    
1565
    { 0x1c, "ret" },
1566

    
1567
    { 0x1e, "a" },
1568
    { 0x1f, "s" },
1569
    { 0x20, "d" },
1570
    { 0x21, "f" },
1571
    { 0x22, "g" },
1572
    { 0x23, "h" },
1573
    { 0x24, "j" },
1574
    { 0x25, "k" },
1575
    { 0x26, "l" },
1576

    
1577
    { 0x2c, "z" },
1578
    { 0x2d, "x" },
1579
    { 0x2e, "c" },
1580
    { 0x2f, "v" },
1581
    { 0x30, "b" },
1582
    { 0x31, "n" },
1583
    { 0x32, "m" },
1584
    { 0x33, "comma" },
1585
    { 0x34, "dot" },
1586
    { 0x35, "slash" },
1587

    
1588
    { 0x37, "asterisk" },
1589

    
1590
    { 0x39, "spc" },
1591
    { 0x3a, "caps_lock" },
1592
    { 0x3b, "f1" },
1593
    { 0x3c, "f2" },
1594
    { 0x3d, "f3" },
1595
    { 0x3e, "f4" },
1596
    { 0x3f, "f5" },
1597
    { 0x40, "f6" },
1598
    { 0x41, "f7" },
1599
    { 0x42, "f8" },
1600
    { 0x43, "f9" },
1601
    { 0x44, "f10" },
1602
    { 0x45, "num_lock" },
1603
    { 0x46, "scroll_lock" },
1604

    
1605
    { 0xb5, "kp_divide" },
1606
    { 0x37, "kp_multiply" },
1607
    { 0x4a, "kp_subtract" },
1608
    { 0x4e, "kp_add" },
1609
    { 0x9c, "kp_enter" },
1610
    { 0x53, "kp_decimal" },
1611
    { 0x54, "sysrq" },
1612

    
1613
    { 0x52, "kp_0" },
1614
    { 0x4f, "kp_1" },
1615
    { 0x50, "kp_2" },
1616
    { 0x51, "kp_3" },
1617
    { 0x4b, "kp_4" },
1618
    { 0x4c, "kp_5" },
1619
    { 0x4d, "kp_6" },
1620
    { 0x47, "kp_7" },
1621
    { 0x48, "kp_8" },
1622
    { 0x49, "kp_9" },
1623

    
1624
    { 0x56, "<" },
1625

    
1626
    { 0x57, "f11" },
1627
    { 0x58, "f12" },
1628

    
1629
    { 0xb7, "print" },
1630

    
1631
    { 0xc7, "home" },
1632
    { 0xc9, "pgup" },
1633
    { 0xd1, "pgdn" },
1634
    { 0xcf, "end" },
1635

    
1636
    { 0xcb, "left" },
1637
    { 0xc8, "up" },
1638
    { 0xd0, "down" },
1639
    { 0xcd, "right" },
1640

    
1641
    { 0xd2, "insert" },
1642
    { 0xd3, "delete" },
1643
#if defined(TARGET_SPARC) && !defined(TARGET_SPARC64)
1644
    { 0xf0, "stop" },
1645
    { 0xf1, "again" },
1646
    { 0xf2, "props" },
1647
    { 0xf3, "undo" },
1648
    { 0xf4, "front" },
1649
    { 0xf5, "copy" },
1650
    { 0xf6, "open" },
1651
    { 0xf7, "paste" },
1652
    { 0xf8, "find" },
1653
    { 0xf9, "cut" },
1654
    { 0xfa, "lf" },
1655
    { 0xfb, "help" },
1656
    { 0xfc, "meta_l" },
1657
    { 0xfd, "meta_r" },
1658
    { 0xfe, "compose" },
1659
#endif
1660
    { 0, NULL },
1661
};
1662

    
1663
static int get_keycode(const char *key)
1664
{
1665
    const KeyDef *p;
1666
    char *endp;
1667
    int ret;
1668

    
1669
    for(p = key_defs; p->name != NULL; p++) {
1670
        if (!strcmp(key, p->name))
1671
            return p->keycode;
1672
    }
1673
    if (strstart(key, "0x", NULL)) {
1674
        ret = strtoul(key, &endp, 0);
1675
        if (*endp == '\0' && ret >= 0x01 && ret <= 0xff)
1676
            return ret;
1677
    }
1678
    return -1;
1679
}
1680

    
1681
#define MAX_KEYCODES 16
1682
static uint8_t keycodes[MAX_KEYCODES];
1683
static int nb_pending_keycodes;
1684
static QEMUTimer *key_timer;
1685

    
1686
static void release_keys(void *opaque)
1687
{
1688
    int keycode;
1689

    
1690
    while (nb_pending_keycodes > 0) {
1691
        nb_pending_keycodes--;
1692
        keycode = keycodes[nb_pending_keycodes];
1693
        if (keycode & 0x80)
1694
            kbd_put_keycode(0xe0);
1695
        kbd_put_keycode(keycode | 0x80);
1696
    }
1697
}
1698

    
1699
static void do_sendkey(Monitor *mon, const QDict *qdict)
1700
{
1701
    char keyname_buf[16];
1702
    char *separator;
1703
    int keyname_len, keycode, i;
1704
    const char *string = qdict_get_str(qdict, "string");
1705
    int has_hold_time = qdict_haskey(qdict, "hold_time");
1706
    int hold_time = qdict_get_try_int(qdict, "hold_time", -1);
1707

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

    
1753
static int mouse_button_state;
1754

    
1755
static void do_mouse_move(Monitor *mon, const QDict *qdict)
1756
{
1757
    int dx, dy, dz;
1758
    const char *dx_str = qdict_get_str(qdict, "dx_str");
1759
    const char *dy_str = qdict_get_str(qdict, "dy_str");
1760
    const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1761
    dx = strtol(dx_str, NULL, 0);
1762
    dy = strtol(dy_str, NULL, 0);
1763
    dz = 0;
1764
    if (dz_str)
1765
        dz = strtol(dz_str, NULL, 0);
1766
    kbd_mouse_event(dx, dy, dz, mouse_button_state);
1767
}
1768

    
1769
static void do_mouse_button(Monitor *mon, const QDict *qdict)
1770
{
1771
    int button_state = qdict_get_int(qdict, "button_state");
1772
    mouse_button_state = button_state;
1773
    kbd_mouse_event(0, 0, 0, mouse_button_state);
1774
}
1775

    
1776
static void do_ioport_read(Monitor *mon, const QDict *qdict)
1777
{
1778
    int size = qdict_get_int(qdict, "size");
1779
    int addr = qdict_get_int(qdict, "addr");
1780
    int has_index = qdict_haskey(qdict, "index");
1781
    uint32_t val;
1782
    int suffix;
1783

    
1784
    if (has_index) {
1785
        int index = qdict_get_int(qdict, "index");
1786
        cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1787
        addr++;
1788
    }
1789
    addr &= 0xffff;
1790

    
1791
    switch(size) {
1792
    default:
1793
    case 1:
1794
        val = cpu_inb(addr);
1795
        suffix = 'b';
1796
        break;
1797
    case 2:
1798
        val = cpu_inw(addr);
1799
        suffix = 'w';
1800
        break;
1801
    case 4:
1802
        val = cpu_inl(addr);
1803
        suffix = 'l';
1804
        break;
1805
    }
1806
    monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1807
                   suffix, addr, size * 2, val);
1808
}
1809

    
1810
static void do_ioport_write(Monitor *mon, const QDict *qdict)
1811
{
1812
    int size = qdict_get_int(qdict, "size");
1813
    int addr = qdict_get_int(qdict, "addr");
1814
    int val = qdict_get_int(qdict, "val");
1815

    
1816
    addr &= IOPORTS_MASK;
1817

    
1818
    switch (size) {
1819
    default:
1820
    case 1:
1821
        cpu_outb(addr, val);
1822
        break;
1823
    case 2:
1824
        cpu_outw(addr, val);
1825
        break;
1826
    case 4:
1827
        cpu_outl(addr, val);
1828
        break;
1829
    }
1830
}
1831

    
1832
static void do_boot_set(Monitor *mon, const QDict *qdict)
1833
{
1834
    int res;
1835
    const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1836

    
1837
    res = qemu_boot_set(bootdevice);
1838
    if (res == 0) {
1839
        monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1840
    } else if (res > 0) {
1841
        monitor_printf(mon, "setting boot device list failed\n");
1842
    } else {
1843
        monitor_printf(mon, "no function defined to set boot device list for "
1844
                       "this architecture\n");
1845
    }
1846
}
1847

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

    
1858
/**
1859
 * do_system_powerdown(): Issue a machine powerdown
1860
 */
1861
static int do_system_powerdown(Monitor *mon, const QDict *qdict,
1862
                               QObject **ret_data)
1863
{
1864
    qemu_system_powerdown_request();
1865
    return 0;
1866
}
1867

    
1868
#if defined(TARGET_I386)
1869
static void print_pte(Monitor *mon, uint32_t addr, uint32_t pte, uint32_t mask)
1870
{
1871
    monitor_printf(mon, "%08x: %08x %c%c%c%c%c%c%c%c\n",
1872
                   addr,
1873
                   pte & mask,
1874
                   pte & PG_GLOBAL_MASK ? 'G' : '-',
1875
                   pte & PG_PSE_MASK ? 'P' : '-',
1876
                   pte & PG_DIRTY_MASK ? 'D' : '-',
1877
                   pte & PG_ACCESSED_MASK ? 'A' : '-',
1878
                   pte & PG_PCD_MASK ? 'C' : '-',
1879
                   pte & PG_PWT_MASK ? 'T' : '-',
1880
                   pte & PG_USER_MASK ? 'U' : '-',
1881
                   pte & PG_RW_MASK ? 'W' : '-');
1882
}
1883

    
1884
static void tlb_info(Monitor *mon)
1885
{
1886
    CPUState *env;
1887
    int l1, l2;
1888
    uint32_t pgd, pde, pte;
1889

    
1890
    env = mon_get_cpu();
1891

    
1892
    if (!(env->cr[0] & CR0_PG_MASK)) {
1893
        monitor_printf(mon, "PG disabled\n");
1894
        return;
1895
    }
1896
    pgd = env->cr[3] & ~0xfff;
1897
    for(l1 = 0; l1 < 1024; l1++) {
1898
        cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1899
        pde = le32_to_cpu(pde);
1900
        if (pde & PG_PRESENT_MASK) {
1901
            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1902
                print_pte(mon, (l1 << 22), pde, ~((1 << 20) - 1));
1903
            } else {
1904
                for(l2 = 0; l2 < 1024; l2++) {
1905
                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1906
                                             (uint8_t *)&pte, 4);
1907
                    pte = le32_to_cpu(pte);
1908
                    if (pte & PG_PRESENT_MASK) {
1909
                        print_pte(mon, (l1 << 22) + (l2 << 12),
1910
                                  pte & ~PG_PSE_MASK,
1911
                                  ~0xfff);
1912
                    }
1913
                }
1914
            }
1915
        }
1916
    }
1917
}
1918

    
1919
static void mem_print(Monitor *mon, uint32_t *pstart, int *plast_prot,
1920
                      uint32_t end, int prot)
1921
{
1922
    int prot1;
1923
    prot1 = *plast_prot;
1924
    if (prot != prot1) {
1925
        if (*pstart != -1) {
1926
            monitor_printf(mon, "%08x-%08x %08x %c%c%c\n",
1927
                           *pstart, end, end - *pstart,
1928
                           prot1 & PG_USER_MASK ? 'u' : '-',
1929
                           'r',
1930
                           prot1 & PG_RW_MASK ? 'w' : '-');
1931
        }
1932
        if (prot != 0)
1933
            *pstart = end;
1934
        else
1935
            *pstart = -1;
1936
        *plast_prot = prot;
1937
    }
1938
}
1939

    
1940
static void mem_info(Monitor *mon)
1941
{
1942
    CPUState *env;
1943
    int l1, l2, prot, last_prot;
1944
    uint32_t pgd, pde, pte, start, end;
1945

    
1946
    env = mon_get_cpu();
1947

    
1948
    if (!(env->cr[0] & CR0_PG_MASK)) {
1949
        monitor_printf(mon, "PG disabled\n");
1950
        return;
1951
    }
1952
    pgd = env->cr[3] & ~0xfff;
1953
    last_prot = 0;
1954
    start = -1;
1955
    for(l1 = 0; l1 < 1024; l1++) {
1956
        cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1957
        pde = le32_to_cpu(pde);
1958
        end = l1 << 22;
1959
        if (pde & PG_PRESENT_MASK) {
1960
            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1961
                prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1962
                mem_print(mon, &start, &last_prot, end, prot);
1963
            } else {
1964
                for(l2 = 0; l2 < 1024; l2++) {
1965
                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1966
                                             (uint8_t *)&pte, 4);
1967
                    pte = le32_to_cpu(pte);
1968
                    end = (l1 << 22) + (l2 << 12);
1969
                    if (pte & PG_PRESENT_MASK) {
1970
                        prot = pte & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1971
                    } else {
1972
                        prot = 0;
1973
                    }
1974
                    mem_print(mon, &start, &last_prot, end, prot);
1975
                }
1976
            }
1977
        } else {
1978
            prot = 0;
1979
            mem_print(mon, &start, &last_prot, end, prot);
1980
        }
1981
    }
1982
}
1983
#endif
1984

    
1985
#if defined(TARGET_SH4)
1986

    
1987
static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1988
{
1989
    monitor_printf(mon, " tlb%i:\t"
1990
                   "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1991
                   "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1992
                   "dirty=%hhu writethrough=%hhu\n",
1993
                   idx,
1994
                   tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1995
                   tlb->v, tlb->sh, tlb->c, tlb->pr,
1996
                   tlb->d, tlb->wt);
1997
}
1998

    
1999
static void tlb_info(Monitor *mon)
2000
{
2001
    CPUState *env = mon_get_cpu();
2002
    int i;
2003

    
2004
    monitor_printf (mon, "ITLB:\n");
2005
    for (i = 0 ; i < ITLB_SIZE ; i++)
2006
        print_tlb (mon, i, &env->itlb[i]);
2007
    monitor_printf (mon, "UTLB:\n");
2008
    for (i = 0 ; i < UTLB_SIZE ; i++)
2009
        print_tlb (mon, i, &env->utlb[i]);
2010
}
2011

    
2012
#endif
2013

    
2014
static void do_info_kvm_print(Monitor *mon, const QObject *data)
2015
{
2016
    QDict *qdict;
2017

    
2018
    qdict = qobject_to_qdict(data);
2019

    
2020
    monitor_printf(mon, "kvm support: ");
2021
    if (qdict_get_bool(qdict, "present")) {
2022
        monitor_printf(mon, "%s\n", qdict_get_bool(qdict, "enabled") ?
2023
                                    "enabled" : "disabled");
2024
    } else {
2025
        monitor_printf(mon, "not compiled\n");
2026
    }
2027
}
2028

    
2029
/**
2030
 * do_info_kvm(): Show KVM information
2031
 *
2032
 * Return a QDict with the following information:
2033
 *
2034
 * - "enabled": true if KVM support is enabled, false otherwise
2035
 * - "present": true if QEMU has KVM support, false otherwise
2036
 *
2037
 * Example:
2038
 *
2039
 * { "enabled": true, "present": true }
2040
 */
2041
static void do_info_kvm(Monitor *mon, QObject **ret_data)
2042
{
2043
#ifdef CONFIG_KVM
2044
    *ret_data = qobject_from_jsonf("{ 'enabled': %i, 'present': true }",
2045
                                   kvm_enabled());
2046
#else
2047
    *ret_data = qobject_from_jsonf("{ 'enabled': false, 'present': false }");
2048
#endif
2049
}
2050

    
2051
static void do_info_numa(Monitor *mon)
2052
{
2053
    int i;
2054
    CPUState *env;
2055

    
2056
    monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
2057
    for (i = 0; i < nb_numa_nodes; i++) {
2058
        monitor_printf(mon, "node %d cpus:", i);
2059
        for (env = first_cpu; env != NULL; env = env->next_cpu) {
2060
            if (env->numa_node == i) {
2061
                monitor_printf(mon, " %d", env->cpu_index);
2062
            }
2063
        }
2064
        monitor_printf(mon, "\n");
2065
        monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
2066
            node_mem[i] >> 20);
2067
    }
2068
}
2069

    
2070
#ifdef CONFIG_PROFILER
2071

    
2072
int64_t qemu_time;
2073
int64_t dev_time;
2074

    
2075
static void do_info_profile(Monitor *mon)
2076
{
2077
    int64_t total;
2078
    total = qemu_time;
2079
    if (total == 0)
2080
        total = 1;
2081
    monitor_printf(mon, "async time  %" PRId64 " (%0.3f)\n",
2082
                   dev_time, dev_time / (double)get_ticks_per_sec());
2083
    monitor_printf(mon, "qemu time   %" PRId64 " (%0.3f)\n",
2084
                   qemu_time, qemu_time / (double)get_ticks_per_sec());
2085
    qemu_time = 0;
2086
    dev_time = 0;
2087
}
2088
#else
2089
static void do_info_profile(Monitor *mon)
2090
{
2091
    monitor_printf(mon, "Internal profiler not compiled\n");
2092
}
2093
#endif
2094

    
2095
/* Capture support */
2096
static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2097

    
2098
static void do_info_capture(Monitor *mon)
2099
{
2100
    int i;
2101
    CaptureState *s;
2102

    
2103
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2104
        monitor_printf(mon, "[%d]: ", i);
2105
        s->ops.info (s->opaque);
2106
    }
2107
}
2108

    
2109
#ifdef HAS_AUDIO
2110
static void do_stop_capture(Monitor *mon, const QDict *qdict)
2111
{
2112
    int i;
2113
    int n = qdict_get_int(qdict, "n");
2114
    CaptureState *s;
2115

    
2116
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2117
        if (i == n) {
2118
            s->ops.destroy (s->opaque);
2119
            QLIST_REMOVE (s, entries);
2120
            qemu_free (s);
2121
            return;
2122
        }
2123
    }
2124
}
2125

    
2126
static void do_wav_capture(Monitor *mon, const QDict *qdict)
2127
{
2128
    const char *path = qdict_get_str(qdict, "path");
2129
    int has_freq = qdict_haskey(qdict, "freq");
2130
    int freq = qdict_get_try_int(qdict, "freq", -1);
2131
    int has_bits = qdict_haskey(qdict, "bits");
2132
    int bits = qdict_get_try_int(qdict, "bits", -1);
2133
    int has_channels = qdict_haskey(qdict, "nchannels");
2134
    int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2135
    CaptureState *s;
2136

    
2137
    s = qemu_mallocz (sizeof (*s));
2138

    
2139
    freq = has_freq ? freq : 44100;
2140
    bits = has_bits ? bits : 16;
2141
    nchannels = has_channels ? nchannels : 2;
2142

    
2143
    if (wav_start_capture (s, path, freq, bits, nchannels)) {
2144
        monitor_printf(mon, "Faied to add wave capture\n");
2145
        qemu_free (s);
2146
    }
2147
    QLIST_INSERT_HEAD (&capture_head, s, entries);
2148
}
2149
#endif
2150

    
2151
#if defined(TARGET_I386)
2152
static void do_inject_nmi(Monitor *mon, const QDict *qdict)
2153
{
2154
    CPUState *env;
2155
    int cpu_index = qdict_get_int(qdict, "cpu_index");
2156

    
2157
    for (env = first_cpu; env != NULL; env = env->next_cpu)
2158
        if (env->cpu_index == cpu_index) {
2159
            cpu_interrupt(env, CPU_INTERRUPT_NMI);
2160
            break;
2161
        }
2162
}
2163
#endif
2164

    
2165
static void do_info_status_print(Monitor *mon, const QObject *data)
2166
{
2167
    QDict *qdict;
2168

    
2169
    qdict = qobject_to_qdict(data);
2170

    
2171
    monitor_printf(mon, "VM status: ");
2172
    if (qdict_get_bool(qdict, "running")) {
2173
        monitor_printf(mon, "running");
2174
        if (qdict_get_bool(qdict, "singlestep")) {
2175
            monitor_printf(mon, " (single step mode)");
2176
        }
2177
    } else {
2178
        monitor_printf(mon, "paused");
2179
    }
2180

    
2181
    monitor_printf(mon, "\n");
2182
}
2183

    
2184
/**
2185
 * do_info_status(): VM status
2186
 *
2187
 * Return a QDict with the following information:
2188
 *
2189
 * - "running": true if the VM is running, or false if it is paused
2190
 * - "singlestep": true if the VM is in single step mode, false otherwise
2191
 *
2192
 * Example:
2193
 *
2194
 * { "running": true, "singlestep": false }
2195
 */
2196
static void do_info_status(Monitor *mon, QObject **ret_data)
2197
{
2198
    *ret_data = qobject_from_jsonf("{ 'running': %i, 'singlestep': %i }",
2199
                                    vm_running, singlestep);
2200
}
2201

    
2202
static void print_balloon_stat(const char *key, QObject *obj, void *opaque)
2203
{
2204
    Monitor *mon = opaque;
2205

    
2206
    if (strcmp(key, "actual"))
2207
        monitor_printf(mon, ",%s=%" PRId64, key,
2208
                       qint_get_int(qobject_to_qint(obj)));
2209
}
2210

    
2211
static void monitor_print_balloon(Monitor *mon, const QObject *data)
2212
{
2213
    QDict *qdict;
2214

    
2215
    qdict = qobject_to_qdict(data);
2216
    if (!qdict_haskey(qdict, "actual"))
2217
        return;
2218

    
2219
    monitor_printf(mon, "balloon: actual=%" PRId64,
2220
                   qdict_get_int(qdict, "actual") >> 20);
2221
    qdict_iter(qdict, print_balloon_stat, mon);
2222
    monitor_printf(mon, "\n");
2223
}
2224

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

    
2250
    if (kvm_enabled() && !kvm_has_sync_mmu()) {
2251
        qemu_error_new(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
2252
        return -1;
2253
    }
2254

    
2255
    ret = qemu_balloon_status(cb, opaque);
2256
    if (!ret) {
2257
        qemu_error_new(QERR_DEVICE_NOT_ACTIVE, "balloon");
2258
        return -1;
2259
    }
2260

    
2261
    return 0;
2262
}
2263

    
2264
/**
2265
 * do_balloon(): Request VM to change its memory allocation
2266
 */
2267
static int do_balloon(Monitor *mon, const QDict *params,
2268
                       MonitorCompletion cb, void *opaque)
2269
{
2270
    int ret;
2271

    
2272
    if (kvm_enabled() && !kvm_has_sync_mmu()) {
2273
        qemu_error_new(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
2274
        return -1;
2275
    }
2276

    
2277
    ret = qemu_balloon(qdict_get_int(params, "value"), cb, opaque);
2278
    if (ret == 0) {
2279
        qemu_error_new(QERR_DEVICE_NOT_ACTIVE, "balloon");
2280
        return -1;
2281
    }
2282

    
2283
    return 0;
2284
}
2285

    
2286
static qemu_acl *find_acl(Monitor *mon, const char *name)
2287
{
2288
    qemu_acl *acl = qemu_acl_find(name);
2289

    
2290
    if (!acl) {
2291
        monitor_printf(mon, "acl: unknown list '%s'\n", name);
2292
    }
2293
    return acl;
2294
}
2295

    
2296
static void do_acl_show(Monitor *mon, const QDict *qdict)
2297
{
2298
    const char *aclname = qdict_get_str(qdict, "aclname");
2299
    qemu_acl *acl = find_acl(mon, aclname);
2300
    qemu_acl_entry *entry;
2301
    int i = 0;
2302

    
2303
    if (acl) {
2304
        monitor_printf(mon, "policy: %s\n",
2305
                       acl->defaultDeny ? "deny" : "allow");
2306
        QTAILQ_FOREACH(entry, &acl->entries, next) {
2307
            i++;
2308
            monitor_printf(mon, "%d: %s %s\n", i,
2309
                           entry->deny ? "deny" : "allow", entry->match);
2310
        }
2311
    }
2312
}
2313

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

    
2319
    if (acl) {
2320
        qemu_acl_reset(acl);
2321
        monitor_printf(mon, "acl: removed all rules\n");
2322
    }
2323
}
2324

    
2325
static void do_acl_policy(Monitor *mon, const QDict *qdict)
2326
{
2327
    const char *aclname = qdict_get_str(qdict, "aclname");
2328
    const char *policy = qdict_get_str(qdict, "policy");
2329
    qemu_acl *acl = find_acl(mon, aclname);
2330

    
2331
    if (acl) {
2332
        if (strcmp(policy, "allow") == 0) {
2333
            acl->defaultDeny = 0;
2334
            monitor_printf(mon, "acl: policy set to 'allow'\n");
2335
        } else if (strcmp(policy, "deny") == 0) {
2336
            acl->defaultDeny = 1;
2337
            monitor_printf(mon, "acl: policy set to 'deny'\n");
2338
        } else {
2339
            monitor_printf(mon, "acl: unknown policy '%s', "
2340
                           "expected 'deny' or 'allow'\n", policy);
2341
        }
2342
    }
2343
}
2344

    
2345
static void do_acl_add(Monitor *mon, const QDict *qdict)
2346
{
2347
    const char *aclname = qdict_get_str(qdict, "aclname");
2348
    const char *match = qdict_get_str(qdict, "match");
2349
    const char *policy = qdict_get_str(qdict, "policy");
2350
    int has_index = qdict_haskey(qdict, "index");
2351
    int index = qdict_get_try_int(qdict, "index", -1);
2352
    qemu_acl *acl = find_acl(mon, aclname);
2353
    int deny, ret;
2354

    
2355
    if (acl) {
2356
        if (strcmp(policy, "allow") == 0) {
2357
            deny = 0;
2358
        } else if (strcmp(policy, "deny") == 0) {
2359
            deny = 1;
2360
        } else {
2361
            monitor_printf(mon, "acl: unknown policy '%s', "
2362
                           "expected 'deny' or 'allow'\n", policy);
2363
            return;
2364
        }
2365
        if (has_index)
2366
            ret = qemu_acl_insert(acl, deny, match, index);
2367
        else
2368
            ret = qemu_acl_append(acl, deny, match);
2369
        if (ret < 0)
2370
            monitor_printf(mon, "acl: unable to add acl entry\n");
2371
        else
2372
            monitor_printf(mon, "acl: added rule at position %d\n", ret);
2373
    }
2374
}
2375

    
2376
static void do_acl_remove(Monitor *mon, const QDict *qdict)
2377
{
2378
    const char *aclname = qdict_get_str(qdict, "aclname");
2379
    const char *match = qdict_get_str(qdict, "match");
2380
    qemu_acl *acl = find_acl(mon, aclname);
2381
    int ret;
2382

    
2383
    if (acl) {
2384
        ret = qemu_acl_remove(acl, match);
2385
        if (ret < 0)
2386
            monitor_printf(mon, "acl: no matching acl entry\n");
2387
        else
2388
            monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2389
    }
2390
}
2391

    
2392
#if defined(TARGET_I386)
2393
static void do_inject_mce(Monitor *mon, const QDict *qdict)
2394
{
2395
    CPUState *cenv;
2396
    int cpu_index = qdict_get_int(qdict, "cpu_index");
2397
    int bank = qdict_get_int(qdict, "bank");
2398
    uint64_t status = qdict_get_int(qdict, "status");
2399
    uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2400
    uint64_t addr = qdict_get_int(qdict, "addr");
2401
    uint64_t misc = qdict_get_int(qdict, "misc");
2402

    
2403
    for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu)
2404
        if (cenv->cpu_index == cpu_index && cenv->mcg_cap) {
2405
            cpu_inject_x86_mce(cenv, bank, status, mcg_status, addr, misc);
2406
            break;
2407
        }
2408
}
2409
#endif
2410

    
2411
static int do_getfd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2412
{
2413
    const char *fdname = qdict_get_str(qdict, "fdname");
2414
    mon_fd_t *monfd;
2415
    int fd;
2416

    
2417
    fd = qemu_chr_get_msgfd(mon->chr);
2418
    if (fd == -1) {
2419
        qemu_error_new(QERR_FD_NOT_SUPPLIED);
2420
        return -1;
2421
    }
2422

    
2423
    if (qemu_isdigit(fdname[0])) {
2424
        qemu_error_new(QERR_INVALID_PARAMETER, "fdname");
2425
        return -1;
2426
    }
2427

    
2428
    fd = dup(fd);
2429
    if (fd == -1) {
2430
        if (errno == EMFILE)
2431
            qemu_error_new(QERR_TOO_MANY_FILES);
2432
        else
2433
            qemu_error_new(QERR_UNDEFINED_ERROR);
2434
        return -1;
2435
    }
2436

    
2437
    QLIST_FOREACH(monfd, &mon->fds, next) {
2438
        if (strcmp(monfd->name, fdname) != 0) {
2439
            continue;
2440
        }
2441

    
2442
        close(monfd->fd);
2443
        monfd->fd = fd;
2444
        return 0;
2445
    }
2446

    
2447
    monfd = qemu_mallocz(sizeof(mon_fd_t));
2448
    monfd->name = qemu_strdup(fdname);
2449
    monfd->fd = fd;
2450

    
2451
    QLIST_INSERT_HEAD(&mon->fds, monfd, next);
2452
    return 0;
2453
}
2454

    
2455
static int do_closefd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2456
{
2457
    const char *fdname = qdict_get_str(qdict, "fdname");
2458
    mon_fd_t *monfd;
2459

    
2460
    QLIST_FOREACH(monfd, &mon->fds, next) {
2461
        if (strcmp(monfd->name, fdname) != 0) {
2462
            continue;
2463
        }
2464

    
2465
        QLIST_REMOVE(monfd, next);
2466
        close(monfd->fd);
2467
        qemu_free(monfd->name);
2468
        qemu_free(monfd);
2469
        return 0;
2470
    }
2471

    
2472
    qemu_error_new(QERR_FD_NOT_FOUND, fdname);
2473
    return -1;
2474
}
2475

    
2476
static void do_loadvm(Monitor *mon, const QDict *qdict)
2477
{
2478
    int saved_vm_running  = vm_running;
2479
    const char *name = qdict_get_str(qdict, "name");
2480

    
2481
    vm_stop(0);
2482

    
2483
    if (load_vmstate(mon, name) >= 0 && saved_vm_running)
2484
        vm_start();
2485
}
2486

    
2487
int monitor_get_fd(Monitor *mon, const char *fdname)
2488
{
2489
    mon_fd_t *monfd;
2490

    
2491
    QLIST_FOREACH(monfd, &mon->fds, next) {
2492
        int fd;
2493

    
2494
        if (strcmp(monfd->name, fdname) != 0) {
2495
            continue;
2496
        }
2497

    
2498
        fd = monfd->fd;
2499

    
2500
        /* caller takes ownership of fd */
2501
        QLIST_REMOVE(monfd, next);
2502
        qemu_free(monfd->name);
2503
        qemu_free(monfd);
2504

    
2505
        return fd;
2506
    }
2507

    
2508
    return -1;
2509
}
2510

    
2511
static const mon_cmd_t mon_cmds[] = {
2512
#include "qemu-monitor.h"
2513
    { NULL, NULL, },
2514
};
2515

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

    
2800
/*******************************************************************/
2801

    
2802
static const char *pch;
2803
static jmp_buf expr_env;
2804

    
2805
#define MD_TLONG 0
2806
#define MD_I32   1
2807

    
2808
typedef struct MonitorDef {
2809
    const char *name;
2810
    int offset;
2811
    target_long (*get_value)(const struct MonitorDef *md, int val);
2812
    int type;
2813
} MonitorDef;
2814

    
2815
#if defined(TARGET_I386)
2816
static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2817
{
2818
    CPUState *env = mon_get_cpu();
2819
    return env->eip + env->segs[R_CS].base;
2820
}
2821
#endif
2822

    
2823
#if defined(TARGET_PPC)
2824
static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2825
{
2826
    CPUState *env = mon_get_cpu();
2827
    unsigned int u;
2828
    int i;
2829

    
2830
    u = 0;
2831
    for (i = 0; i < 8; i++)
2832
        u |= env->crf[i] << (32 - (4 * i));
2833

    
2834
    return u;
2835
}
2836

    
2837
static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2838
{
2839
    CPUState *env = mon_get_cpu();
2840
    return env->msr;
2841
}
2842

    
2843
static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2844
{
2845
    CPUState *env = mon_get_cpu();
2846
    return env->xer;
2847
}
2848

    
2849
static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2850
{
2851
    CPUState *env = mon_get_cpu();
2852
    return cpu_ppc_load_decr(env);
2853
}
2854

    
2855
static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2856
{
2857
    CPUState *env = mon_get_cpu();
2858
    return cpu_ppc_load_tbu(env);
2859
}
2860

    
2861
static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2862
{
2863
    CPUState *env = mon_get_cpu();
2864
    return cpu_ppc_load_tbl(env);
2865
}
2866
#endif
2867

    
2868
#if defined(TARGET_SPARC)
2869
#ifndef TARGET_SPARC64
2870
static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2871
{
2872
    CPUState *env = mon_get_cpu();
2873
    return GET_PSR(env);
2874
}
2875
#endif
2876

    
2877
static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2878
{
2879
    CPUState *env = mon_get_cpu();
2880
    return env->regwptr[val];
2881
}
2882
#endif
2883

    
2884
static const MonitorDef monitor_defs[] = {
2885
#ifdef TARGET_I386
2886

    
2887
#define SEG(name, seg) \
2888
    { name, offsetof(CPUState, segs[seg].selector), NULL, MD_I32 },\
2889
    { name ".base", offsetof(CPUState, segs[seg].base) },\
2890
    { name ".limit", offsetof(CPUState, segs[seg].limit), NULL, MD_I32 },
2891

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

    
3125
static void expr_error(Monitor *mon, const char *msg)
3126
{
3127
    monitor_printf(mon, "%s\n", msg);
3128
    longjmp(expr_env, 1);
3129
}
3130

    
3131
/* return 0 if OK, -1 if not found */
3132
static int get_monitor_def(target_long *pval, const char *name)
3133
{
3134
    const MonitorDef *md;
3135
    void *ptr;
3136

    
3137
    for(md = monitor_defs; md->name != NULL; md++) {
3138
        if (compare_cmd(name, md->name)) {
3139
            if (md->get_value) {
3140
                *pval = md->get_value(md, md->offset);
3141
            } else {
3142
                CPUState *env = mon_get_cpu();
3143
                ptr = (uint8_t *)env + md->offset;
3144
                switch(md->type) {
3145
                case MD_I32:
3146
                    *pval = *(int32_t *)ptr;
3147
                    break;
3148
                case MD_TLONG:
3149
                    *pval = *(target_long *)ptr;
3150
                    break;
3151
                default:
3152
                    *pval = 0;
3153
                    break;
3154
                }
3155
            }
3156
            return 0;
3157
        }
3158
    }
3159
    return -1;
3160
}
3161

    
3162
static void next(void)
3163
{
3164
    if (*pch != '\0') {
3165
        pch++;
3166
        while (qemu_isspace(*pch))
3167
            pch++;
3168
    }
3169
}
3170

    
3171
static int64_t expr_sum(Monitor *mon);
3172

    
3173
static int64_t expr_unary(Monitor *mon)
3174
{
3175
    int64_t n;
3176
    char *p;
3177
    int ret;
3178

    
3179
    switch(*pch) {
3180
    case '+':
3181
        next();
3182
        n = expr_unary(mon);
3183
        break;
3184
    case '-':
3185
        next();
3186
        n = -expr_unary(mon);
3187
        break;
3188
    case '~':
3189
        next();
3190
        n = ~expr_unary(mon);
3191
        break;
3192
    case '(':
3193
        next();
3194
        n = expr_sum(mon);
3195
        if (*pch != ')') {
3196
            expr_error(mon, "')' expected");
3197
        }
3198
        next();
3199
        break;
3200
    case '\'':
3201
        pch++;
3202
        if (*pch == '\0')
3203
            expr_error(mon, "character constant expected");
3204
        n = *pch;
3205
        pch++;
3206
        if (*pch != '\'')
3207
            expr_error(mon, "missing terminating \' character");
3208
        next();
3209
        break;
3210
    case '$':
3211
        {
3212
            char buf[128], *q;
3213
            target_long reg=0;
3214

    
3215
            pch++;
3216
            q = buf;
3217
            while ((*pch >= 'a' && *pch <= 'z') ||
3218
                   (*pch >= 'A' && *pch <= 'Z') ||
3219
                   (*pch >= '0' && *pch <= '9') ||
3220
                   *pch == '_' || *pch == '.') {
3221
                if ((q - buf) < sizeof(buf) - 1)
3222
                    *q++ = *pch;
3223
                pch++;
3224
            }
3225
            while (qemu_isspace(*pch))
3226
                pch++;
3227
            *q = 0;
3228
            ret = get_monitor_def(&reg, buf);
3229
            if (ret < 0)
3230
                expr_error(mon, "unknown register");
3231
            n = reg;
3232
        }
3233
        break;
3234
    case '\0':
3235
        expr_error(mon, "unexpected end of expression");
3236
        n = 0;
3237
        break;
3238
    default:
3239
#if TARGET_PHYS_ADDR_BITS > 32
3240
        n = strtoull(pch, &p, 0);
3241
#else
3242
        n = strtoul(pch, &p, 0);
3243
#endif
3244
        if (pch == p) {
3245
            expr_error(mon, "invalid char in expression");
3246
        }
3247
        pch = p;
3248
        while (qemu_isspace(*pch))
3249
            pch++;
3250
        break;
3251
    }
3252
    return n;
3253
}
3254

    
3255

    
3256
static int64_t expr_prod(Monitor *mon)
3257
{
3258
    int64_t val, val2;
3259
    int op;
3260

    
3261
    val = expr_unary(mon);
3262
    for(;;) {
3263
        op = *pch;
3264
        if (op != '*' && op != '/' && op != '%')
3265
            break;
3266
        next();
3267
        val2 = expr_unary(mon);
3268
        switch(op) {
3269
        default:
3270
        case '*':
3271
            val *= val2;
3272
            break;
3273
        case '/':
3274
        case '%':
3275
            if (val2 == 0)
3276
                expr_error(mon, "division by zero");
3277
            if (op == '/')
3278
                val /= val2;
3279
            else
3280
                val %= val2;
3281
            break;
3282
        }
3283
    }
3284
    return val;
3285
}
3286

    
3287
static int64_t expr_logic(Monitor *mon)
3288
{
3289
    int64_t val, val2;
3290
    int op;
3291

    
3292
    val = expr_prod(mon);
3293
    for(;;) {
3294
        op = *pch;
3295
        if (op != '&' && op != '|' && op != '^')
3296
            break;
3297
        next();
3298
        val2 = expr_prod(mon);
3299
        switch(op) {
3300
        default:
3301
        case '&':
3302
            val &= val2;
3303
            break;
3304
        case '|':
3305
            val |= val2;
3306
            break;
3307
        case '^':
3308
            val ^= val2;
3309
            break;
3310
        }
3311
    }
3312
    return val;
3313
}
3314

    
3315
static int64_t expr_sum(Monitor *mon)
3316
{
3317
    int64_t val, val2;
3318
    int op;
3319

    
3320
    val = expr_logic(mon);
3321
    for(;;) {
3322
        op = *pch;
3323
        if (op != '+' && op != '-')
3324
            break;
3325
        next();
3326
        val2 = expr_logic(mon);
3327
        if (op == '+')
3328
            val += val2;
3329
        else
3330
            val -= val2;
3331
    }
3332
    return val;
3333
}
3334

    
3335
static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3336
{
3337
    pch = *pp;
3338
    if (setjmp(expr_env)) {
3339
        *pp = pch;
3340
        return -1;
3341
    }
3342
    while (qemu_isspace(*pch))
3343
        pch++;
3344
    *pval = expr_sum(mon);
3345
    *pp = pch;
3346
    return 0;
3347
}
3348

    
3349
static int get_double(Monitor *mon, double *pval, const char **pp)
3350
{
3351
    const char *p = *pp;
3352
    char *tailp;
3353
    double d;
3354

    
3355
    d = strtod(p, &tailp);
3356
    if (tailp == p) {
3357
        monitor_printf(mon, "Number expected\n");
3358
        return -1;
3359
    }
3360
    if (d != d || d - d != 0) {
3361
        /* NaN or infinity */
3362
        monitor_printf(mon, "Bad number\n");
3363
        return -1;
3364
    }
3365
    *pval = d;
3366
    *pp = tailp;
3367
    return 0;
3368
}
3369

    
3370
static int get_str(char *buf, int buf_size, const char **pp)
3371
{
3372
    const char *p;
3373
    char *q;
3374
    int c;
3375

    
3376
    q = buf;
3377
    p = *pp;
3378
    while (qemu_isspace(*p))
3379
        p++;
3380
    if (*p == '\0') {
3381
    fail:
3382
        *q = '\0';
3383
        *pp = p;
3384
        return -1;
3385
    }
3386
    if (*p == '\"') {
3387
        p++;
3388
        while (*p != '\0' && *p != '\"') {
3389
            if (*p == '\\') {
3390
                p++;
3391
                c = *p++;
3392
                switch(c) {
3393
                case 'n':
3394
                    c = '\n';
3395
                    break;
3396
                case 'r':
3397
                    c = '\r';
3398
                    break;
3399
                case '\\':
3400
                case '\'':
3401
                case '\"':
3402
                    break;
3403
                default:
3404
                    qemu_printf("unsupported escape code: '\\%c'\n", c);
3405
                    goto fail;
3406
                }
3407
                if ((q - buf) < buf_size - 1) {
3408
                    *q++ = c;
3409
                }
3410
            } else {
3411
                if ((q - buf) < buf_size - 1) {
3412
                    *q++ = *p;
3413
                }
3414
                p++;
3415
            }
3416
        }
3417
        if (*p != '\"') {
3418
            qemu_printf("unterminated string\n");
3419
            goto fail;
3420
        }
3421
        p++;
3422
    } else {
3423
        while (*p != '\0' && !qemu_isspace(*p)) {
3424
            if ((q - buf) < buf_size - 1) {
3425
                *q++ = *p;
3426
            }
3427
            p++;
3428
        }
3429
    }
3430
    *q = '\0';
3431
    *pp = p;
3432
    return 0;
3433
}
3434

    
3435
/*
3436
 * Store the command-name in cmdname, and return a pointer to
3437
 * the remaining of the command string.
3438
 */
3439
static const char *get_command_name(const char *cmdline,
3440
                                    char *cmdname, size_t nlen)
3441
{
3442
    size_t len;
3443
    const char *p, *pstart;
3444

    
3445
    p = cmdline;
3446
    while (qemu_isspace(*p))
3447
        p++;
3448
    if (*p == '\0')
3449
        return NULL;
3450
    pstart = p;
3451
    while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3452
        p++;
3453
    len = p - pstart;
3454
    if (len > nlen - 1)
3455
        len = nlen - 1;
3456
    memcpy(cmdname, pstart, len);
3457
    cmdname[len] = '\0';
3458
    return p;
3459
}
3460

    
3461
/**
3462
 * Read key of 'type' into 'key' and return the current
3463
 * 'type' pointer.
3464
 */
3465
static char *key_get_info(const char *type, char **key)
3466
{
3467
    size_t len;
3468
    char *p, *str;
3469

    
3470
    if (*type == ',')
3471
        type++;
3472

    
3473
    p = strchr(type, ':');
3474
    if (!p) {
3475
        *key = NULL;
3476
        return NULL;
3477
    }
3478
    len = p - type;
3479

    
3480
    str = qemu_malloc(len + 1);
3481
    memcpy(str, type, len);
3482
    str[len] = '\0';
3483

    
3484
    *key = str;
3485
    return ++p;
3486
}
3487

    
3488
static int default_fmt_format = 'x';
3489
static int default_fmt_size = 4;
3490

    
3491
#define MAX_ARGS 16
3492

    
3493
static int is_valid_option(const char *c, const char *typestr)
3494
{
3495
    char option[3];
3496
  
3497
    option[0] = '-';
3498
    option[1] = *c;
3499
    option[2] = '\0';
3500
  
3501
    typestr = strstr(typestr, option);
3502
    return (typestr != NULL);
3503
}
3504

    
3505
static const mon_cmd_t *monitor_find_command(const char *cmdname)
3506
{
3507
    const mon_cmd_t *cmd;
3508

    
3509
    for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
3510
        if (compare_cmd(cmdname, cmd->name)) {
3511
            return cmd;
3512
        }
3513
    }
3514

    
3515
    return NULL;
3516
}
3517

    
3518
static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3519
                                              const char *cmdline,
3520
                                              QDict *qdict)
3521
{
3522
    const char *p, *typestr;
3523
    int c;
3524
    const mon_cmd_t *cmd;
3525
    char cmdname[256];
3526
    char buf[1024];
3527
    char *key;
3528

    
3529
#ifdef DEBUG
3530
    monitor_printf(mon, "command='%s'\n", cmdline);
3531
#endif
3532

    
3533
    /* extract the command name */
3534
    p = get_command_name(cmdline, cmdname, sizeof(cmdname));
3535
    if (!p)
3536
        return NULL;
3537

    
3538
    cmd = monitor_find_command(cmdname);
3539
    if (!cmd) {
3540
        monitor_printf(mon, "unknown command: '%s'\n", cmdname);
3541
        return NULL;
3542
    }
3543

    
3544
    /* parse the parameters */
3545
    typestr = cmd->args_type;
3546
    for(;;) {
3547
        typestr = key_get_info(typestr, &key);
3548
        if (!typestr)
3549
            break;
3550
        c = *typestr;
3551
        typestr++;
3552
        switch(c) {
3553
        case 'F':
3554
        case 'B':
3555
        case 's':
3556
            {
3557
                int ret;
3558

    
3559
                while (qemu_isspace(*p))
3560
                    p++;
3561
                if (*typestr == '?') {
3562
                    typestr++;
3563
                    if (*p == '\0') {
3564
                        /* no optional string: NULL argument */
3565
                        break;
3566
                    }
3567
                }
3568
                ret = get_str(buf, sizeof(buf), &p);
3569
                if (ret < 0) {
3570
                    switch(c) {
3571
                    case 'F':
3572
                        monitor_printf(mon, "%s: filename expected\n",
3573
                                       cmdname);
3574
                        break;
3575
                    case 'B':
3576
                        monitor_printf(mon, "%s: block device name expected\n",
3577
                                       cmdname);
3578
                        break;
3579
                    default:
3580
                        monitor_printf(mon, "%s: string expected\n", cmdname);
3581
                        break;
3582
                    }
3583
                    goto fail;
3584
                }
3585
                qdict_put(qdict, key, qstring_from_str(buf));
3586
            }
3587
            break;
3588
        case '/':
3589
            {
3590
                int count, format, size;
3591

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

    
3673
                while (qemu_isspace(*p))
3674
                    p++;
3675
                if (*typestr == '?' || *typestr == '.') {
3676
                    if (*typestr == '?') {
3677
                        if (*p == '\0') {
3678
                            typestr++;
3679
                            break;
3680
                        }
3681
                    } else {
3682
                        if (*p == '.') {
3683
                            p++;
3684
                            while (qemu_isspace(*p))
3685
                                p++;
3686
                        } else {
3687
                            typestr++;
3688
                            break;
3689
                        }
3690
                    }
3691
                    typestr++;
3692
                }
3693
                if (get_expr(mon, &val, &p))
3694
                    goto fail;
3695
                /* Check if 'i' is greater than 32-bit */
3696
                if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3697
                    monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3698
                    monitor_printf(mon, "integer is for 32-bit values\n");
3699
                    goto fail;
3700
                } else if (c == 'M') {
3701
                    val <<= 20;
3702
                }
3703
                qdict_put(qdict, key, qint_from_int(val));
3704
            }
3705
            break;
3706
        case 'b':
3707
        case 'T':
3708
            {
3709
                double val;
3710

    
3711
                while (qemu_isspace(*p))
3712
                    p++;
3713
                if (*typestr == '?') {
3714
                    typestr++;
3715
                    if (*p == '\0') {
3716
                        break;
3717
                    }
3718
                }
3719
                if (get_double(mon, &val, &p) < 0) {
3720
                    goto fail;
3721
                }
3722
                if (c == 'b' && *p) {
3723
                    switch (*p) {
3724
                    case 'K': case 'k':
3725
                        val *= 1 << 10; p++; break;
3726
                    case 'M': case 'm':
3727
                        val *= 1 << 20; p++; break;
3728
                    case 'G': case 'g':
3729
                        val *= 1 << 30; p++; break;
3730
                    }
3731
                }
3732
                if (c == 'T' && p[0] && p[1] == 's') {
3733
                    switch (*p) {
3734
                    case 'm':
3735
                        val /= 1e3; p += 2; break;
3736
                    case 'u':
3737
                        val /= 1e6; p += 2; break;
3738
                    case 'n':
3739
                        val /= 1e9; p += 2; break;
3740
                    }
3741
                }
3742
                if (*p && !qemu_isspace(*p)) {
3743
                    monitor_printf(mon, "Unknown unit suffix\n");
3744
                    goto fail;
3745
                }
3746
                qdict_put(qdict, key, qfloat_from_double(val));
3747
            }
3748
            break;
3749
        case '-':
3750
            {
3751
                const char *tmp = p;
3752
                int has_option, skip_key = 0;
3753
                /* option */
3754

    
3755
                c = *typestr++;
3756
                if (c == '\0')
3757
                    goto bad_type;
3758
                while (qemu_isspace(*p))
3759
                    p++;
3760
                has_option = 0;
3761
                if (*p == '-') {
3762
                    p++;
3763
                    if(c != *p) {
3764
                        if(!is_valid_option(p, typestr)) {
3765
                  
3766
                            monitor_printf(mon, "%s: unsupported option -%c\n",
3767
                                           cmdname, *p);
3768
                            goto fail;
3769
                        } else {
3770
                            skip_key = 1;
3771
                        }
3772
                    }
3773
                    if(skip_key) {
3774
                        p = tmp;
3775
                    } else {
3776
                        p++;
3777
                        has_option = 1;
3778
                    }
3779
                }
3780
                qdict_put(qdict, key, qint_from_int(has_option));
3781
            }
3782
            break;
3783
        default:
3784
        bad_type:
3785
            monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
3786
            goto fail;
3787
        }
3788
        qemu_free(key);
3789
        key = NULL;
3790
    }
3791
    /* check that all arguments were parsed */
3792
    while (qemu_isspace(*p))
3793
        p++;
3794
    if (*p != '\0') {
3795
        monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3796
                       cmdname);
3797
        goto fail;
3798
    }
3799

    
3800
    return cmd;
3801

    
3802
fail:
3803
    qemu_free(key);
3804
    return NULL;
3805
}
3806

    
3807
static void monitor_print_error(Monitor *mon)
3808
{
3809
    qerror_print(mon->error);
3810
    QDECREF(mon->error);
3811
    mon->error = NULL;
3812
}
3813

    
3814
static int is_async_return(const QObject *data)
3815
{
3816
    if (data && qobject_type(data) == QTYPE_QDICT) {
3817
        return qdict_haskey(qobject_to_qdict(data), "__mon_async");
3818
    }
3819

    
3820
    return 0;
3821
}
3822

    
3823
static void monitor_call_handler(Monitor *mon, const mon_cmd_t *cmd,
3824
                                 const QDict *params)
3825
{
3826
    QObject *data = NULL;
3827

    
3828
    if (cmd->cmd_new_ret) {
3829
        cmd->cmd_new_ret(mon, params, &data);
3830
    } else {
3831
        cmd->mhandler.cmd_new(mon, params, &data);
3832
    }
3833

    
3834
    if (is_async_return(data)) {
3835
        /*
3836
         * Asynchronous commands have no initial return data but they can
3837
         * generate errors.  Data is returned via the async completion handler.
3838
         */
3839
        if (monitor_ctrl_mode(mon) && monitor_has_error(mon)) {
3840
            monitor_protocol_emitter(mon, NULL);
3841
        }
3842
    } else if (monitor_ctrl_mode(mon)) {
3843
        /* Monitor Protocol */
3844
        monitor_protocol_emitter(mon, data);
3845
    } else {
3846
        /* User Protocol */
3847
         if (data)
3848
            cmd->user_print(mon, data);
3849
    }
3850

    
3851
    qobject_decref(data);
3852
}
3853

    
3854
static void handle_user_command(Monitor *mon, const char *cmdline)
3855
{
3856
    QDict *qdict;
3857
    const mon_cmd_t *cmd;
3858

    
3859
    qdict = qdict_new();
3860

    
3861
    cmd = monitor_parse_command(mon, cmdline, qdict);
3862
    if (!cmd)
3863
        goto out;
3864

    
3865
    qemu_errors_to_mon(mon);
3866

    
3867
    if (monitor_handler_is_async(cmd)) {
3868
        user_async_cmd_handler(mon, cmd, qdict);
3869
    } else if (monitor_handler_ported(cmd)) {
3870
        monitor_call_handler(mon, cmd, qdict);
3871
    } else {
3872
        cmd->mhandler.cmd(mon, qdict);
3873
    }
3874

    
3875
    if (monitor_has_error(mon))
3876
        monitor_print_error(mon);
3877

    
3878
    qemu_errors_to_previous();
3879

    
3880
out:
3881
    QDECREF(qdict);
3882
}
3883

    
3884
static void cmd_completion(const char *name, const char *list)
3885
{
3886
    const char *p, *pstart;
3887
    char cmd[128];
3888
    int len;
3889

    
3890
    p = list;
3891
    for(;;) {
3892
        pstart = p;
3893
        p = strchr(p, '|');
3894
        if (!p)
3895
            p = pstart + strlen(pstart);
3896
        len = p - pstart;
3897
        if (len > sizeof(cmd) - 2)
3898
            len = sizeof(cmd) - 2;
3899
        memcpy(cmd, pstart, len);
3900
        cmd[len] = '\0';
3901
        if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3902
            readline_add_completion(cur_mon->rs, cmd);
3903
        }
3904
        if (*p == '\0')
3905
            break;
3906
        p++;
3907
    }
3908
}
3909

    
3910
static void file_completion(const char *input)
3911
{
3912
    DIR *ffs;
3913
    struct dirent *d;
3914
    char path[1024];
3915
    char file[1024], file_prefix[1024];
3916
    int input_path_len;
3917
    const char *p;
3918

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

    
3961
static void block_completion_it(void *opaque, BlockDriverState *bs)
3962
{
3963
    const char *name = bdrv_get_device_name(bs);
3964
    const char *input = opaque;
3965

    
3966
    if (input[0] == '\0' ||
3967
        !strncmp(name, (char *)input, strlen(input))) {
3968
        readline_add_completion(cur_mon->rs, name);
3969
    }
3970
}
3971

    
3972
/* NOTE: this parser is an approximate form of the real command parser */
3973
static void parse_cmdline(const char *cmdline,
3974
                         int *pnb_args, char **args)
3975
{
3976
    const char *p;
3977
    int nb_args, ret;
3978
    char buf[1024];
3979

    
3980
    p = cmdline;
3981
    nb_args = 0;
3982
    for(;;) {
3983
        while (qemu_isspace(*p))
3984
            p++;
3985
        if (*p == '\0')
3986
            break;
3987
        if (nb_args >= MAX_ARGS)
3988
            break;
3989
        ret = get_str(buf, sizeof(buf), &p);
3990
        args[nb_args] = qemu_strdup(buf);
3991
        nb_args++;
3992
        if (ret < 0)
3993
            break;
3994
    }
3995
    *pnb_args = nb_args;
3996
}
3997

    
3998
static const char *next_arg_type(const char *typestr)
3999
{
4000
    const char *p = strchr(typestr, ':');
4001
    return (p != NULL ? ++p : typestr);
4002
}
4003

    
4004
static void monitor_find_completion(const char *cmdline)
4005
{
4006
    const char *cmdname;
4007
    char *args[MAX_ARGS];
4008
    int nb_args, i, len;
4009
    const char *ptype, *str;
4010
    const mon_cmd_t *cmd;
4011
    const KeyDef *key;
4012

    
4013
    parse_cmdline(cmdline, &nb_args, args);
4014
#ifdef DEBUG_COMPLETION
4015
    for(i = 0; i < nb_args; i++) {
4016
        monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
4017
    }
4018
#endif
4019

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

    
4099
static int monitor_can_read(void *opaque)
4100
{
4101
    Monitor *mon = opaque;
4102

    
4103
    return (mon->suspend_cnt == 0) ? 1 : 0;
4104
}
4105

    
4106
typedef struct CmdArgs {
4107
    QString *name;
4108
    int type;
4109
    int flag;
4110
    int optional;
4111
} CmdArgs;
4112

    
4113
static int check_opt(const CmdArgs *cmd_args, const char *name, QDict *args)
4114
{
4115
    if (!cmd_args->optional) {
4116
        qemu_error_new(QERR_MISSING_PARAMETER, name);
4117
        return -1;
4118
    }
4119

    
4120
    if (cmd_args->type == '-') {
4121
        /* handlers expect a value, they need to be changed */
4122
        qdict_put(args, name, qint_from_int(0));
4123
    }
4124

    
4125
    return 0;
4126
}
4127

    
4128
static int check_arg(const CmdArgs *cmd_args, QDict *args)
4129
{
4130
    QObject *value;
4131
    const char *name;
4132

    
4133
    name = qstring_get_str(cmd_args->name);
4134

    
4135
    if (!args) {
4136
        return check_opt(cmd_args, name, args);
4137
    }
4138

    
4139
    value = qdict_get(args, name);
4140
    if (!value) {
4141
        return check_opt(cmd_args, name, args);
4142
    }
4143

    
4144
    switch (cmd_args->type) {
4145
        case 'F':
4146
        case 'B':
4147
        case 's':
4148
            if (qobject_type(value) != QTYPE_QSTRING) {
4149
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "string");
4150
                return -1;
4151
            }
4152
            break;
4153
        case '/': {
4154
            int i;
4155
            const char *keys[] = { "count", "format", "size", NULL };
4156

    
4157
            for (i = 0; keys[i]; i++) {
4158
                QObject *obj = qdict_get(args, keys[i]);
4159
                if (!obj) {
4160
                    qemu_error_new(QERR_MISSING_PARAMETER, name);
4161
                    return -1;
4162
                }
4163
                if (qobject_type(obj) != QTYPE_QINT) {
4164
                    qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "int");
4165
                    return -1;
4166
                }
4167
            }
4168
            break;
4169
        }
4170
        case 'i':
4171
        case 'l':
4172
        case 'M':
4173
            if (qobject_type(value) != QTYPE_QINT) {
4174
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "int");
4175
                return -1;
4176
            }
4177
            break;
4178
        case 'b':
4179
        case 'T':
4180
            if (qobject_type(value) != QTYPE_QINT && qobject_type(value) != QTYPE_QFLOAT) {
4181
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "number");
4182
                return -1;
4183
            }
4184
            break;
4185
        case '-':
4186
            if (qobject_type(value) != QTYPE_QINT &&
4187
                qobject_type(value) != QTYPE_QBOOL) {
4188
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "bool");
4189
                return -1;
4190
            }
4191
            if (qobject_type(value) == QTYPE_QBOOL) {
4192
                /* handlers expect a QInt, they need to be changed */
4193
                qdict_put(args, name,
4194
                         qint_from_int(qbool_get_int(qobject_to_qbool(value))));
4195
            }
4196
            break;
4197
        default:
4198
            /* impossible */
4199
            abort();
4200
    }
4201

    
4202
    return 0;
4203
}
4204

    
4205
static void cmd_args_init(CmdArgs *cmd_args)
4206
{
4207
    cmd_args->name = qstring_new();
4208
    cmd_args->type = cmd_args->flag = cmd_args->optional = 0;
4209
}
4210

    
4211
/*
4212
 * This is not trivial, we have to parse Monitor command's argument
4213
 * type syntax to be able to check the arguments provided by clients.
4214
 *
4215
 * In the near future we will be using an array for that and will be
4216
 * able to drop all this parsing...
4217
 */
4218
static int monitor_check_qmp_args(const mon_cmd_t *cmd, QDict *args)
4219
{
4220
    int err;
4221
    const char *p;
4222
    CmdArgs cmd_args;
4223

    
4224
    if (cmd->args_type == NULL) {
4225
        return (qdict_size(args) == 0 ? 0 : -1);
4226
    }
4227

    
4228
    err = 0;
4229
    cmd_args_init(&cmd_args);
4230

    
4231
    for (p = cmd->args_type;; p++) {
4232
        if (*p == ':') {
4233
            cmd_args.type = *++p;
4234
            p++;
4235
            if (cmd_args.type == '-') {
4236
                cmd_args.flag = *p++;
4237
                cmd_args.optional = 1;
4238
            } else if (*p == '?') {
4239
                cmd_args.optional = 1;
4240
                p++;
4241
            }
4242

    
4243
            assert(*p == ',' || *p == '\0');
4244
            err = check_arg(&cmd_args, args);
4245

    
4246
            QDECREF(cmd_args.name);
4247
            cmd_args_init(&cmd_args);
4248

    
4249
            if (err < 0) {
4250
                break;
4251
            }
4252
        } else {
4253
            qstring_append_chr(cmd_args.name, *p);
4254
        }
4255

    
4256
        if (*p == '\0') {
4257
            break;
4258
        }
4259
    }
4260

    
4261
    QDECREF(cmd_args.name);
4262
    return err;
4263
}
4264

    
4265
static int invalid_qmp_mode(const Monitor *mon, const char *cmd_name)
4266
{
4267
    int is_cap = compare_cmd(cmd_name, "qmp_capabilities");
4268
    return (qmp_cmd_mode(mon) ? is_cap : !is_cap);
4269
}
4270

    
4271
static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
4272
{
4273
    int err;
4274
    QObject *obj;
4275
    QDict *input, *args;
4276
    const mon_cmd_t *cmd;
4277
    Monitor *mon = cur_mon;
4278
    const char *cmd_name, *info_item;
4279

    
4280
    args = NULL;
4281
    qemu_errors_to_mon(mon);
4282

    
4283
    obj = json_parser_parse(tokens, NULL);
4284
    if (!obj) {
4285
        // FIXME: should be triggered in json_parser_parse()
4286
        qemu_error_new(QERR_JSON_PARSING);
4287
        goto err_out;
4288
    } else if (qobject_type(obj) != QTYPE_QDICT) {
4289
        qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "object");
4290
        qobject_decref(obj);
4291
        goto err_out;
4292
    }
4293

    
4294
    input = qobject_to_qdict(obj);
4295

    
4296
    mon->mc->id = qdict_get(input, "id");
4297
    qobject_incref(mon->mc->id);
4298

    
4299
    obj = qdict_get(input, "execute");
4300
    if (!obj) {
4301
        qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4302
        goto err_input;
4303
    } else if (qobject_type(obj) != QTYPE_QSTRING) {
4304
        qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "string");
4305
        goto err_input;
4306
    }
4307

    
4308
    cmd_name = qstring_get_str(qobject_to_qstring(obj));
4309

    
4310
    if (invalid_qmp_mode(mon, cmd_name)) {
4311
        qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4312
        goto err_input;
4313
    }
4314

    
4315
    /*
4316
     * XXX: We need this special case until we get info handlers
4317
     * converted into 'query-' commands
4318
     */
4319
    if (compare_cmd(cmd_name, "info")) {
4320
        qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4321
        goto err_input;
4322
    } else if (strstart(cmd_name, "query-", &info_item)) {
4323
        cmd = monitor_find_command("info");
4324
        qdict_put_obj(input, "arguments",
4325
                      qobject_from_jsonf("{ 'item': %s }", info_item));
4326
    } else {
4327
        cmd = monitor_find_command(cmd_name);
4328
        if (!cmd || !monitor_handler_ported(cmd)) {
4329
            qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4330
            goto err_input;
4331
        }
4332
    }
4333

    
4334
    obj = qdict_get(input, "arguments");
4335
    if (!obj) {
4336
        args = qdict_new();
4337
    } else {
4338
        args = qobject_to_qdict(obj);
4339
        QINCREF(args);
4340
    }
4341

    
4342
    QDECREF(input);
4343

    
4344
    err = monitor_check_qmp_args(cmd, args);
4345
    if (err < 0) {
4346
        goto err_out;
4347
    }
4348

    
4349
    if (monitor_handler_is_async(cmd)) {
4350
        qmp_async_cmd_handler(mon, cmd, args);
4351
    } else {
4352
        monitor_call_handler(mon, cmd, args);
4353
    }
4354
    goto out;
4355

    
4356
err_input:
4357
    QDECREF(input);
4358
err_out:
4359
    monitor_protocol_emitter(mon, NULL);
4360
out:
4361
    QDECREF(args);
4362
    qemu_errors_to_previous();
4363
}
4364

    
4365
/**
4366
 * monitor_control_read(): Read and handle QMP input
4367
 */
4368
static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
4369
{
4370
    Monitor *old_mon = cur_mon;
4371

    
4372
    cur_mon = opaque;
4373

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

    
4376
    cur_mon = old_mon;
4377
}
4378

    
4379
static void monitor_read(void *opaque, const uint8_t *buf, int size)
4380
{
4381
    Monitor *old_mon = cur_mon;
4382
    int i;
4383

    
4384
    cur_mon = opaque;
4385

    
4386
    if (cur_mon->rs) {
4387
        for (i = 0; i < size; i++)
4388
            readline_handle_byte(cur_mon->rs, buf[i]);
4389
    } else {
4390
        if (size == 0 || buf[size - 1] != 0)
4391
            monitor_printf(cur_mon, "corrupted command\n");
4392
        else
4393
            handle_user_command(cur_mon, (char *)buf);
4394
    }
4395

    
4396
    cur_mon = old_mon;
4397
}
4398

    
4399
static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
4400
{
4401
    monitor_suspend(mon);
4402
    handle_user_command(mon, cmdline);
4403
    monitor_resume(mon);
4404
}
4405

    
4406
int monitor_suspend(Monitor *mon)
4407
{
4408
    if (!mon->rs)
4409
        return -ENOTTY;
4410
    mon->suspend_cnt++;
4411
    return 0;
4412
}
4413

    
4414
void monitor_resume(Monitor *mon)
4415
{
4416
    if (!mon->rs)
4417
        return;
4418
    if (--mon->suspend_cnt == 0)
4419
        readline_show_prompt(mon->rs);
4420
}
4421

    
4422
static QObject *get_qmp_greeting(void)
4423
{
4424
    QObject *ver;
4425

    
4426
    do_info_version(NULL, &ver);
4427
    return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
4428
}
4429

    
4430
/**
4431
 * monitor_control_event(): Print QMP gretting
4432
 */
4433
static void monitor_control_event(void *opaque, int event)
4434
{
4435
    QObject *data;
4436
    Monitor *mon = opaque;
4437

    
4438
    switch (event) {
4439
    case CHR_EVENT_OPENED:
4440
        mon->mc->command_mode = 0;
4441
        json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4442
        data = get_qmp_greeting();
4443
        monitor_json_emitter(mon, data);
4444
        qobject_decref(data);
4445
        break;
4446
    case CHR_EVENT_CLOSED:
4447
        json_message_parser_destroy(&mon->mc->parser);
4448
        break;
4449
    }
4450
}
4451

    
4452
static void monitor_event(void *opaque, int event)
4453
{
4454
    Monitor *mon = opaque;
4455

    
4456
    switch (event) {
4457
    case CHR_EVENT_MUX_IN:
4458
        mon->mux_out = 0;
4459
        if (mon->reset_seen) {
4460
            readline_restart(mon->rs);
4461
            monitor_resume(mon);
4462
            monitor_flush(mon);
4463
        } else {
4464
            mon->suspend_cnt = 0;
4465
        }
4466
        break;
4467

    
4468
    case CHR_EVENT_MUX_OUT:
4469
        if (mon->reset_seen) {
4470
            if (mon->suspend_cnt == 0) {
4471
                monitor_printf(mon, "\n");
4472
            }
4473
            monitor_flush(mon);
4474
            monitor_suspend(mon);
4475
        } else {
4476
            mon->suspend_cnt++;
4477
        }
4478
        mon->mux_out = 1;
4479
        break;
4480

    
4481
    case CHR_EVENT_OPENED:
4482
        monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4483
                       "information\n", QEMU_VERSION);
4484
        if (!mon->mux_out) {
4485
            readline_show_prompt(mon->rs);
4486
        }
4487
        mon->reset_seen = 1;
4488
        break;
4489
    }
4490
}
4491

    
4492

    
4493
/*
4494
 * Local variables:
4495
 *  c-indent-level: 4
4496
 *  c-basic-offset: 4
4497
 *  tab-width: 8
4498
 * End:
4499
 */
4500

    
4501
void monitor_init(CharDriverState *chr, int flags)
4502
{
4503
    static int is_first_init = 1;
4504
    Monitor *mon;
4505

    
4506
    if (is_first_init) {
4507
        key_timer = qemu_new_timer(vm_clock, release_keys, NULL);
4508
        is_first_init = 0;
4509
    }
4510

    
4511
    mon = qemu_mallocz(sizeof(*mon));
4512

    
4513
    mon->chr = chr;
4514
    mon->flags = flags;
4515
    if (flags & MONITOR_USE_READLINE) {
4516
        mon->rs = readline_init(mon, monitor_find_completion);
4517
        monitor_read_command(mon, 0);
4518
    }
4519

    
4520
    if (monitor_ctrl_mode(mon)) {
4521
        mon->mc = qemu_mallocz(sizeof(MonitorControl));
4522
        /* Control mode requires special handlers */
4523
        qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
4524
                              monitor_control_event, mon);
4525
    } else {
4526
        qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4527
                              monitor_event, mon);
4528
    }
4529

    
4530
    QLIST_INSERT_HEAD(&mon_list, mon, entry);
4531
    if (!cur_mon || (flags & MONITOR_IS_DEFAULT))
4532
        cur_mon = mon;
4533
}
4534

    
4535
static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
4536
{
4537
    BlockDriverState *bs = opaque;
4538
    int ret = 0;
4539

    
4540
    if (bdrv_set_key(bs, password) != 0) {
4541
        monitor_printf(mon, "invalid password\n");
4542
        ret = -EPERM;
4543
    }
4544
    if (mon->password_completion_cb)
4545
        mon->password_completion_cb(mon->password_opaque, ret);
4546

    
4547
    monitor_read_command(mon, 1);
4548
}
4549

    
4550
void monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4551
                                 BlockDriverCompletionFunc *completion_cb,
4552
                                 void *opaque)
4553
{
4554
    int err;
4555

    
4556
    if (!bdrv_key_required(bs)) {
4557
        if (completion_cb)
4558
            completion_cb(opaque, 0);
4559
        return;
4560
    }
4561

    
4562
    if (monitor_ctrl_mode(mon)) {
4563
        qemu_error_new(QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs));
4564
        return;
4565
    }
4566

    
4567
    monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4568
                   bdrv_get_encrypted_filename(bs));
4569

    
4570
    mon->password_completion_cb = completion_cb;
4571
    mon->password_opaque = opaque;
4572

    
4573
    err = monitor_read_password(mon, bdrv_password_cb, bs);
4574

    
4575
    if (err && completion_cb)
4576
        completion_cb(opaque, err);
4577
}
4578

    
4579
typedef struct QemuErrorSink QemuErrorSink;
4580
struct QemuErrorSink {
4581
    enum {
4582
        ERR_SINK_FILE,
4583
        ERR_SINK_MONITOR,
4584
    } dest;
4585
    union {
4586
        FILE    *fp;
4587
        Monitor *mon;
4588
    };
4589
    QemuErrorSink *previous;
4590
};
4591

    
4592
static QemuErrorSink *qemu_error_sink;
4593

    
4594
void qemu_errors_to_file(FILE *fp)
4595
{
4596
    QemuErrorSink *sink;
4597

    
4598
    sink = qemu_mallocz(sizeof(*sink));
4599
    sink->dest = ERR_SINK_FILE;
4600
    sink->fp = fp;
4601
    sink->previous = qemu_error_sink;
4602
    qemu_error_sink = sink;
4603
}
4604

    
4605
void qemu_errors_to_mon(Monitor *mon)
4606
{
4607
    QemuErrorSink *sink;
4608

    
4609
    sink = qemu_mallocz(sizeof(*sink));
4610
    sink->dest = ERR_SINK_MONITOR;
4611
    sink->mon = mon;
4612
    sink->previous = qemu_error_sink;
4613
    qemu_error_sink = sink;
4614
}
4615

    
4616
void qemu_errors_to_previous(void)
4617
{
4618
    QemuErrorSink *sink;
4619

    
4620
    assert(qemu_error_sink != NULL);
4621
    sink = qemu_error_sink;
4622
    qemu_error_sink = sink->previous;
4623
    qemu_free(sink);
4624
}
4625

    
4626
void qemu_error(const char *fmt, ...)
4627
{
4628
    va_list args;
4629

    
4630
    assert(qemu_error_sink != NULL);
4631
    switch (qemu_error_sink->dest) {
4632
    case ERR_SINK_FILE:
4633
        va_start(args, fmt);
4634
        vfprintf(qemu_error_sink->fp, fmt, args);
4635
        va_end(args);
4636
        break;
4637
    case ERR_SINK_MONITOR:
4638
        va_start(args, fmt);
4639
        monitor_vprintf(qemu_error_sink->mon, fmt, args);
4640
        va_end(args);
4641
        break;
4642
    }
4643
}
4644

    
4645
void qemu_error_internal(const char *file, int linenr, const char *func,
4646
                         const char *fmt, ...)
4647
{
4648
    va_list va;
4649
    QError *qerror;
4650

    
4651
    assert(qemu_error_sink != NULL);
4652

    
4653
    va_start(va, fmt);
4654
    qerror = qerror_from_info(file, linenr, func, fmt, &va);
4655
    va_end(va);
4656

    
4657
    switch (qemu_error_sink->dest) {
4658
    case ERR_SINK_FILE:
4659
        qerror_print(qerror);
4660
        QDECREF(qerror);
4661
        break;
4662
    case ERR_SINK_MONITOR:
4663
        /* report only the first error */
4664
        if (!qemu_error_sink->mon->error) {
4665
            qemu_error_sink->mon->error = qerror;
4666
        } else {
4667
            /* XXX: warn the programmer */
4668
            QDECREF(qerror);
4669
        }
4670
        break;
4671
    }
4672
}