Statistics
| Branch: | Revision:

root / monitor.c @ bead3ce1

History | View | Annotate | Download (122.2 kB)

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

    
63
//#define DEBUG
64
//#define DEBUG_COMPLETION
65

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

    
98
typedef struct MonitorCompletionData MonitorCompletionData;
99
struct MonitorCompletionData {
100
    Monitor *mon;
101
    void (*user_print)(Monitor *mon, const QObject *data);
102
};
103

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

    
122
/* file descriptors passed via SCM_RIGHTS */
123
typedef struct mon_fd_t mon_fd_t;
124
struct mon_fd_t {
125
    char *name;
126
    int fd;
127
    QLIST_ENTRY(mon_fd_t) next;
128
};
129

    
130
typedef struct MonitorControl {
131
    QObject *id;
132
    JSONMessageParser parser;
133
    int command_mode;
134
} MonitorControl;
135

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

    
157
#ifdef CONFIG_DEBUG_MONITOR
158
#define MON_DEBUG(fmt, ...) do {    \
159
    fprintf(stderr, "Monitor: ");       \
160
    fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
161

    
162
static inline void mon_print_count_inc(Monitor *mon)
163
{
164
    mon->print_calls_nr++;
165
}
166

    
167
static inline void mon_print_count_init(Monitor *mon)
168
{
169
    mon->print_calls_nr = 0;
170
}
171

    
172
static inline int mon_print_count_get(const Monitor *mon)
173
{
174
    return mon->print_calls_nr;
175
}
176

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

    
184
/* QMP checker flags */
185
#define QMP_ACCEPT_UNKNOWNS 1
186

    
187
static QLIST_HEAD(mon_list, Monitor) mon_list;
188

    
189
static const mon_cmd_t mon_cmds[];
190
static const mon_cmd_t info_cmds[];
191

    
192
Monitor *cur_mon;
193
Monitor *default_mon;
194

    
195
static void monitor_command_cb(Monitor *mon, const char *cmdline,
196
                               void *opaque);
197

    
198
static inline int qmp_cmd_mode(const Monitor *mon)
199
{
200
    return (mon->mc ? mon->mc->command_mode : 0);
201
}
202

    
203
/* Return true if in control mode, false otherwise */
204
static inline int monitor_ctrl_mode(const Monitor *mon)
205
{
206
    return (mon->flags & MONITOR_USE_CONTROL);
207
}
208

    
209
/* Return non-zero iff we have a current monitor, and it is in QMP mode.  */
210
int monitor_cur_is_qmp(void)
211
{
212
    return cur_mon && monitor_ctrl_mode(cur_mon);
213
}
214

    
215
static void monitor_read_command(Monitor *mon, int show_prompt)
216
{
217
    if (!mon->rs)
218
        return;
219

    
220
    readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
221
    if (show_prompt)
222
        readline_show_prompt(mon->rs);
223
}
224

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

    
241
void monitor_flush(Monitor *mon)
242
{
243
    if (mon && mon->outbuf_index != 0 && !mon->mux_out) {
244
        qemu_chr_write(mon->chr, mon->outbuf, mon->outbuf_index);
245
        mon->outbuf_index = 0;
246
    }
247
}
248

    
249
/* flush at every end of line or if the buffer is full */
250
static void monitor_puts(Monitor *mon, const char *str)
251
{
252
    char c;
253

    
254
    for(;;) {
255
        c = *str++;
256
        if (c == '\0')
257
            break;
258
        if (c == '\n')
259
            mon->outbuf[mon->outbuf_index++] = '\r';
260
        mon->outbuf[mon->outbuf_index++] = c;
261
        if (mon->outbuf_index >= (sizeof(mon->outbuf) - 1)
262
            || c == '\n')
263
            monitor_flush(mon);
264
    }
265
}
266

    
267
void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
268
{
269
    char buf[4096];
270

    
271
    if (!mon)
272
        return;
273

    
274
    mon_print_count_inc(mon);
275

    
276
    if (monitor_ctrl_mode(mon)) {
277
        return;
278
    }
279

    
280
    vsnprintf(buf, sizeof(buf), fmt, ap);
281
    monitor_puts(mon, buf);
282
}
283

    
284
void monitor_printf(Monitor *mon, const char *fmt, ...)
285
{
286
    va_list ap;
287
    va_start(ap, fmt);
288
    monitor_vprintf(mon, fmt, ap);
289
    va_end(ap);
290
}
291

    
292
void monitor_print_filename(Monitor *mon, const char *filename)
293
{
294
    int i;
295

    
296
    for (i = 0; filename[i]; i++) {
297
        switch (filename[i]) {
298
        case ' ':
299
        case '"':
300
        case '\\':
301
            monitor_printf(mon, "\\%c", filename[i]);
302
            break;
303
        case '\t':
304
            monitor_printf(mon, "\\t");
305
            break;
306
        case '\r':
307
            monitor_printf(mon, "\\r");
308
            break;
309
        case '\n':
310
            monitor_printf(mon, "\\n");
311
            break;
312
        default:
313
            monitor_printf(mon, "%c", filename[i]);
314
            break;
315
        }
316
    }
317
}
318

    
319
static int monitor_fprintf(FILE *stream, const char *fmt, ...)
320
{
321
    va_list ap;
322
    va_start(ap, fmt);
323
    monitor_vprintf((Monitor *)stream, fmt, ap);
324
    va_end(ap);
325
    return 0;
326
}
327

    
328
static void monitor_user_noop(Monitor *mon, const QObject *data) { }
329

    
330
static inline int monitor_handler_ported(const mon_cmd_t *cmd)
331
{
332
    return cmd->user_print != NULL;
333
}
334

    
335
static inline bool monitor_handler_is_async(const mon_cmd_t *cmd)
336
{
337
    return cmd->flags & MONITOR_CMD_ASYNC;
338
}
339

    
340
static inline bool monitor_cmd_user_only(const mon_cmd_t *cmd)
341
{
342
    return (cmd->flags & MONITOR_CMD_USER_ONLY);
343
}
344

    
345
static inline int monitor_has_error(const Monitor *mon)
346
{
347
    return mon->error != NULL;
348
}
349

    
350
static void monitor_json_emitter(Monitor *mon, const QObject *data)
351
{
352
    QString *json;
353

    
354
    if (mon->flags & MONITOR_USE_PRETTY)
355
        json = qobject_to_json_pretty(data);
356
    else
357
        json = qobject_to_json(data);
358
    assert(json != NULL);
359

    
360
    qstring_append_chr(json, '\n');
361
    monitor_puts(mon, qstring_get_str(json));
362

    
363
    QDECREF(json);
364
}
365

    
366
static void monitor_protocol_emitter(Monitor *mon, QObject *data)
367
{
368
    QDict *qmp;
369

    
370
    qmp = qdict_new();
371

    
372
    if (!monitor_has_error(mon)) {
373
        /* success response */
374
        if (data) {
375
            qobject_incref(data);
376
            qdict_put_obj(qmp, "return", data);
377
        } else {
378
            /* return an empty QDict by default */
379
            qdict_put(qmp, "return", qdict_new());
380
        }
381
    } else {
382
        /* error response */
383
        qdict_put(mon->error->error, "desc", qerror_human(mon->error));
384
        qdict_put(qmp, "error", mon->error->error);
385
        QINCREF(mon->error->error);
386
        QDECREF(mon->error);
387
        mon->error = NULL;
388
    }
389

    
390
    if (mon->mc->id) {
391
        qdict_put_obj(qmp, "id", mon->mc->id);
392
        mon->mc->id = NULL;
393
    }
394

    
395
    monitor_json_emitter(mon, QOBJECT(qmp));
396
    QDECREF(qmp);
397
}
398

    
399
static void timestamp_put(QDict *qdict)
400
{
401
    int err;
402
    QObject *obj;
403
    qemu_timeval tv;
404

    
405
    err = qemu_gettimeofday(&tv);
406
    if (err < 0)
407
        return;
408

    
409
    obj = qobject_from_jsonf("{ 'seconds': %" PRId64 ", "
410
                                "'microseconds': %" PRId64 " }",
411
                                (int64_t) tv.tv_sec, (int64_t) tv.tv_usec);
412
    qdict_put_obj(qdict, "timestamp", obj);
413
}
414

    
415
/**
416
 * monitor_protocol_event(): Generate a Monitor event
417
 *
418
 * Event-specific data can be emitted through the (optional) 'data' parameter.
419
 */
420
void monitor_protocol_event(MonitorEvent event, QObject *data)
421
{
422
    QDict *qmp;
423
    const char *event_name;
424
    Monitor *mon;
425

    
426
    assert(event < QEVENT_MAX);
427

    
428
    switch (event) {
429
        case QEVENT_SHUTDOWN:
430
            event_name = "SHUTDOWN";
431
            break;
432
        case QEVENT_RESET:
433
            event_name = "RESET";
434
            break;
435
        case QEVENT_POWERDOWN:
436
            event_name = "POWERDOWN";
437
            break;
438
        case QEVENT_STOP:
439
            event_name = "STOP";
440
            break;
441
        case QEVENT_RESUME:
442
            event_name = "RESUME";
443
            break;
444
        case QEVENT_VNC_CONNECTED:
445
            event_name = "VNC_CONNECTED";
446
            break;
447
        case QEVENT_VNC_INITIALIZED:
448
            event_name = "VNC_INITIALIZED";
449
            break;
450
        case QEVENT_VNC_DISCONNECTED:
451
            event_name = "VNC_DISCONNECTED";
452
            break;
453
        case QEVENT_BLOCK_IO_ERROR:
454
            event_name = "BLOCK_IO_ERROR";
455
            break;
456
        case QEVENT_RTC_CHANGE:
457
            event_name = "RTC_CHANGE";
458
            break;
459
        case QEVENT_WATCHDOG:
460
            event_name = "WATCHDOG";
461
            break;
462
        default:
463
            abort();
464
            break;
465
    }
466

    
467
    qmp = qdict_new();
468
    timestamp_put(qmp);
469
    qdict_put(qmp, "event", qstring_from_str(event_name));
470
    if (data) {
471
        qobject_incref(data);
472
        qdict_put_obj(qmp, "data", data);
473
    }
474

    
475
    QLIST_FOREACH(mon, &mon_list, entry) {
476
        if (monitor_ctrl_mode(mon) && qmp_cmd_mode(mon)) {
477
            monitor_json_emitter(mon, QOBJECT(qmp));
478
        }
479
    }
480
    QDECREF(qmp);
481
}
482

    
483
static int do_qmp_capabilities(Monitor *mon, const QDict *params,
484
                               QObject **ret_data)
485
{
486
    /* Will setup QMP capabilities in the future */
487
    if (monitor_ctrl_mode(mon)) {
488
        mon->mc->command_mode = 1;
489
    }
490

    
491
    return 0;
492
}
493

    
494
static int compare_cmd(const char *name, const char *list)
495
{
496
    const char *p, *pstart;
497
    int len;
498
    len = strlen(name);
499
    p = list;
500
    for(;;) {
501
        pstart = p;
502
        p = strchr(p, '|');
503
        if (!p)
504
            p = pstart + strlen(pstart);
505
        if ((p - pstart) == len && !memcmp(pstart, name, len))
506
            return 1;
507
        if (*p == '\0')
508
            break;
509
        p++;
510
    }
511
    return 0;
512
}
513

    
514
static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
515
                          const char *prefix, const char *name)
516
{
517
    const mon_cmd_t *cmd;
518

    
519
    for(cmd = cmds; cmd->name != NULL; cmd++) {
520
        if (!name || !strcmp(name, cmd->name))
521
            monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
522
                           cmd->params, cmd->help);
523
    }
524
}
525

    
526
static void help_cmd(Monitor *mon, const char *name)
527
{
528
    if (name && !strcmp(name, "info")) {
529
        help_cmd_dump(mon, info_cmds, "info ", NULL);
530
    } else {
531
        help_cmd_dump(mon, mon_cmds, "", name);
532
        if (name && !strcmp(name, "log")) {
533
            const CPULogItem *item;
534
            monitor_printf(mon, "Log items (comma separated):\n");
535
            monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
536
            for(item = cpu_log_items; item->mask != 0; item++) {
537
                monitor_printf(mon, "%-10s %s\n", item->name, item->help);
538
            }
539
        }
540
    }
541
}
542

    
543
static void do_help_cmd(Monitor *mon, const QDict *qdict)
544
{
545
    help_cmd(mon, qdict_get_try_str(qdict, "name"));
546
}
547

    
548
#ifdef CONFIG_SIMPLE_TRACE
549
static void do_change_trace_event_state(Monitor *mon, const QDict *qdict)
550
{
551
    const char *tp_name = qdict_get_str(qdict, "name");
552
    bool new_state = qdict_get_bool(qdict, "option");
553
    st_change_trace_event_state(tp_name, new_state);
554
}
555

    
556
static void do_trace_file(Monitor *mon, const QDict *qdict)
557
{
558
    const char *op = qdict_get_try_str(qdict, "op");
559
    const char *arg = qdict_get_try_str(qdict, "arg");
560

    
561
    if (!op) {
562
        st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
563
    } else if (!strcmp(op, "on")) {
564
        st_set_trace_file_enabled(true);
565
    } else if (!strcmp(op, "off")) {
566
        st_set_trace_file_enabled(false);
567
    } else if (!strcmp(op, "flush")) {
568
        st_flush_trace_buffer();
569
    } else if (!strcmp(op, "set")) {
570
        if (arg) {
571
            st_set_trace_file(arg);
572
        }
573
    } else {
574
        monitor_printf(mon, "unexpected argument \"%s\"\n", op);
575
        help_cmd(mon, "trace-file");
576
    }
577
}
578
#endif
579

    
580
static void user_monitor_complete(void *opaque, QObject *ret_data)
581
{
582
    MonitorCompletionData *data = (MonitorCompletionData *)opaque; 
583

    
584
    if (ret_data) {
585
        data->user_print(data->mon, ret_data);
586
    }
587
    monitor_resume(data->mon);
588
    qemu_free(data);
589
}
590

    
591
static void qmp_monitor_complete(void *opaque, QObject *ret_data)
592
{
593
    monitor_protocol_emitter(opaque, ret_data);
594
}
595

    
596
static int qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
597
                                 const QDict *params)
598
{
599
    return cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);
600
}
601

    
602
static void qmp_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
603
{
604
    cmd->mhandler.info_async(mon, qmp_monitor_complete, mon);
605
}
606

    
607
static void user_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
608
                                   const QDict *params)
609
{
610
    int ret;
611

    
612
    MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
613
    cb_data->mon = mon;
614
    cb_data->user_print = cmd->user_print;
615
    monitor_suspend(mon);
616
    ret = cmd->mhandler.cmd_async(mon, params,
617
                                  user_monitor_complete, cb_data);
618
    if (ret < 0) {
619
        monitor_resume(mon);
620
        qemu_free(cb_data);
621
    }
622
}
623

    
624
static void user_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
625
{
626
    int ret;
627

    
628
    MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
629
    cb_data->mon = mon;
630
    cb_data->user_print = cmd->user_print;
631
    monitor_suspend(mon);
632
    ret = cmd->mhandler.info_async(mon, user_monitor_complete, cb_data);
633
    if (ret < 0) {
634
        monitor_resume(mon);
635
        qemu_free(cb_data);
636
    }
637
}
638

    
639
static void do_info(Monitor *mon, const QDict *qdict)
640
{
641
    const mon_cmd_t *cmd;
642
    const char *item = qdict_get_try_str(qdict, "item");
643

    
644
    if (!item) {
645
        goto help;
646
    }
647

    
648
    for (cmd = info_cmds; cmd->name != NULL; cmd++) {
649
        if (compare_cmd(item, cmd->name))
650
            break;
651
    }
652

    
653
    if (cmd->name == NULL) {
654
        goto help;
655
    }
656

    
657
    if (monitor_handler_is_async(cmd)) {
658
        user_async_info_handler(mon, cmd);
659
    } else if (monitor_handler_ported(cmd)) {
660
        QObject *info_data = NULL;
661

    
662
        cmd->mhandler.info_new(mon, &info_data);
663
        if (info_data) {
664
            cmd->user_print(mon, info_data);
665
            qobject_decref(info_data);
666
        }
667
    } else {
668
        cmd->mhandler.info(mon);
669
    }
670

    
671
    return;
672

    
673
help:
674
    help_cmd(mon, "info");
675
}
676

    
677
static void do_info_version_print(Monitor *mon, const QObject *data)
678
{
679
    QDict *qdict;
680
    QDict *qemu;
681

    
682
    qdict = qobject_to_qdict(data);
683
    qemu = qdict_get_qdict(qdict, "qemu");
684

    
685
    monitor_printf(mon, "%" PRId64 ".%" PRId64 ".%" PRId64 "%s\n",
686
                  qdict_get_int(qemu, "major"),
687
                  qdict_get_int(qemu, "minor"),
688
                  qdict_get_int(qemu, "micro"),
689
                  qdict_get_str(qdict, "package"));
690
}
691

    
692
static void do_info_version(Monitor *mon, QObject **ret_data)
693
{
694
    const char *version = QEMU_VERSION;
695
    int major = 0, minor = 0, micro = 0;
696
    char *tmp;
697

    
698
    major = strtol(version, &tmp, 10);
699
    tmp++;
700
    minor = strtol(tmp, &tmp, 10);
701
    tmp++;
702
    micro = strtol(tmp, &tmp, 10);
703

    
704
    *ret_data = qobject_from_jsonf("{ 'qemu': { 'major': %d, 'minor': %d, \
705
        'micro': %d }, 'package': %s }", major, minor, micro, QEMU_PKGVERSION);
706
}
707

    
708
static void do_info_name_print(Monitor *mon, const QObject *data)
709
{
710
    QDict *qdict;
711

    
712
    qdict = qobject_to_qdict(data);
713
    if (qdict_size(qdict) == 0) {
714
        return;
715
    }
716

    
717
    monitor_printf(mon, "%s\n", qdict_get_str(qdict, "name"));
718
}
719

    
720
static void do_info_name(Monitor *mon, QObject **ret_data)
721
{
722
    *ret_data = qemu_name ? qobject_from_jsonf("{'name': %s }", qemu_name) :
723
                            qobject_from_jsonf("{}");
724
}
725

    
726
static QObject *get_cmd_dict(const char *name)
727
{
728
    const char *p;
729

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

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

    
741
static void do_info_commands(Monitor *mon, QObject **ret_data)
742
{
743
    QList *cmd_list;
744
    const mon_cmd_t *cmd;
745

    
746
    cmd_list = qlist_new();
747

    
748
    for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
749
        if (monitor_handler_ported(cmd) && !monitor_cmd_user_only(cmd) &&
750
            !compare_cmd(cmd->name, "info")) {
751
            qlist_append_obj(cmd_list, get_cmd_dict(cmd->name));
752
        }
753
    }
754

    
755
    for (cmd = info_cmds; cmd->name != NULL; cmd++) {
756
        if (monitor_handler_ported(cmd) && !monitor_cmd_user_only(cmd)) {
757
            char buf[128];
758
            snprintf(buf, sizeof(buf), "query-%s", cmd->name);
759
            qlist_append_obj(cmd_list, get_cmd_dict(buf));
760
        }
761
    }
762

    
763
    *ret_data = QOBJECT(cmd_list);
764
}
765

    
766
static void do_info_uuid_print(Monitor *mon, const QObject *data)
767
{
768
    monitor_printf(mon, "%s\n", qdict_get_str(qobject_to_qdict(data), "UUID"));
769
}
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
static void do_info_cpus(Monitor *mon, QObject **ret_data)
867
{
868
    CPUState *env;
869
    QList *cpu_list;
870

    
871
    cpu_list = qlist_new();
872

    
873
    /* just to set the default cpu if not already done */
874
    mon_get_cpu();
875

    
876
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
877
        QDict *cpu;
878
        QObject *obj;
879

    
880
        cpu_synchronize_state(env);
881

    
882
        obj = qobject_from_jsonf("{ 'CPU': %d, 'current': %i, 'halted': %i }",
883
                                 env->cpu_index, env == mon->mon_cpu,
884
                                 env->halted);
885

    
886
        cpu = qobject_to_qdict(obj);
887

    
888
#if defined(TARGET_I386)
889
        qdict_put(cpu, "pc", qint_from_int(env->eip + env->segs[R_CS].base));
890
#elif defined(TARGET_PPC)
891
        qdict_put(cpu, "nip", qint_from_int(env->nip));
892
#elif defined(TARGET_SPARC)
893
        qdict_put(cpu, "pc", qint_from_int(env->pc));
894
        qdict_put(cpu, "npc", qint_from_int(env->npc));
895
#elif defined(TARGET_MIPS)
896
        qdict_put(cpu, "PC", qint_from_int(env->active_tc.PC));
897
#endif
898

    
899
        qlist_append(cpu_list, cpu);
900
    }
901

    
902
    *ret_data = QOBJECT(cpu_list);
903
}
904

    
905
static int do_cpu_set(Monitor *mon, const QDict *qdict, QObject **ret_data)
906
{
907
    int index = qdict_get_int(qdict, "index");
908
    if (mon_set_cpu(index) < 0) {
909
        qerror_report(QERR_INVALID_PARAMETER_VALUE, "index",
910
                      "a CPU number");
911
        return -1;
912
    }
913
    return 0;
914
}
915

    
916
static void do_info_jit(Monitor *mon)
917
{
918
    dump_exec_info((FILE *)mon, monitor_fprintf);
919
}
920

    
921
static void do_info_history(Monitor *mon)
922
{
923
    int i;
924
    const char *str;
925

    
926
    if (!mon->rs)
927
        return;
928
    i = 0;
929
    for(;;) {
930
        str = readline_get_history(mon->rs, i);
931
        if (!str)
932
            break;
933
        monitor_printf(mon, "%d: '%s'\n", i, str);
934
        i++;
935
    }
936
}
937

    
938
#if defined(TARGET_PPC)
939
/* XXX: not implemented in other targets */
940
static void do_info_cpu_stats(Monitor *mon)
941
{
942
    CPUState *env;
943

    
944
    env = mon_get_cpu();
945
    cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
946
}
947
#endif
948

    
949
#if defined(CONFIG_SIMPLE_TRACE)
950
static void do_info_trace(Monitor *mon)
951
{
952
    st_print_trace((FILE *)mon, &monitor_fprintf);
953
}
954

    
955
static void do_info_trace_events(Monitor *mon)
956
{
957
    st_print_trace_events((FILE *)mon, &monitor_fprintf);
958
}
959
#endif
960

    
961
/**
962
 * do_quit(): Quit QEMU execution
963
 */
964
static int do_quit(Monitor *mon, const QDict *qdict, QObject **ret_data)
965
{
966
    monitor_suspend(mon);
967
    no_shutdown = 0;
968
    qemu_system_shutdown_request();
969

    
970
    return 0;
971
}
972

    
973
static int change_vnc_password(const char *password)
974
{
975
    if (vnc_display_password(NULL, password) < 0) {
976
        qerror_report(QERR_SET_PASSWD_FAILED);
977
        return -1;
978
    }
979

    
980
    return 0;
981
}
982

    
983
static void change_vnc_password_cb(Monitor *mon, const char *password,
984
                                   void *opaque)
985
{
986
    change_vnc_password(password);
987
    monitor_read_command(mon, 1);
988
}
989

    
990
static int do_change_vnc(Monitor *mon, const char *target, const char *arg)
991
{
992
    if (strcmp(target, "passwd") == 0 ||
993
        strcmp(target, "password") == 0) {
994
        if (arg) {
995
            char password[9];
996
            strncpy(password, arg, sizeof(password));
997
            password[sizeof(password) - 1] = '\0';
998
            return change_vnc_password(password);
999
        } else {
1000
            return monitor_read_password(mon, change_vnc_password_cb, NULL);
1001
        }
1002
    } else {
1003
        if (vnc_display_open(NULL, target) < 0) {
1004
            qerror_report(QERR_VNC_SERVER_FAILED, target);
1005
            return -1;
1006
        }
1007
    }
1008

    
1009
    return 0;
1010
}
1011

    
1012
/**
1013
 * do_change(): Change a removable medium, or VNC configuration
1014
 */
1015
static int do_change(Monitor *mon, const QDict *qdict, QObject **ret_data)
1016
{
1017
    const char *device = qdict_get_str(qdict, "device");
1018
    const char *target = qdict_get_str(qdict, "target");
1019
    const char *arg = qdict_get_try_str(qdict, "arg");
1020
    int ret;
1021

    
1022
    if (strcmp(device, "vnc") == 0) {
1023
        ret = do_change_vnc(mon, target, arg);
1024
    } else {
1025
        ret = do_change_block(mon, device, target, arg);
1026
    }
1027

    
1028
    return ret;
1029
}
1030

    
1031
static int do_screen_dump(Monitor *mon, const QDict *qdict, QObject **ret_data)
1032
{
1033
    vga_hw_screen_dump(qdict_get_str(qdict, "filename"));
1034
    return 0;
1035
}
1036

    
1037
static void do_logfile(Monitor *mon, const QDict *qdict)
1038
{
1039
    cpu_set_log_filename(qdict_get_str(qdict, "filename"));
1040
}
1041

    
1042
static void do_log(Monitor *mon, const QDict *qdict)
1043
{
1044
    int mask;
1045
    const char *items = qdict_get_str(qdict, "items");
1046

    
1047
    if (!strcmp(items, "none")) {
1048
        mask = 0;
1049
    } else {
1050
        mask = cpu_str_to_log_mask(items);
1051
        if (!mask) {
1052
            help_cmd(mon, "log");
1053
            return;
1054
        }
1055
    }
1056
    cpu_set_log(mask);
1057
}
1058

    
1059
static void do_singlestep(Monitor *mon, const QDict *qdict)
1060
{
1061
    const char *option = qdict_get_try_str(qdict, "option");
1062
    if (!option || !strcmp(option, "on")) {
1063
        singlestep = 1;
1064
    } else if (!strcmp(option, "off")) {
1065
        singlestep = 0;
1066
    } else {
1067
        monitor_printf(mon, "unexpected option %s\n", option);
1068
    }
1069
}
1070

    
1071
/**
1072
 * do_stop(): Stop VM execution
1073
 */
1074
static int do_stop(Monitor *mon, const QDict *qdict, QObject **ret_data)
1075
{
1076
    vm_stop(EXCP_INTERRUPT);
1077
    return 0;
1078
}
1079

    
1080
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs);
1081

    
1082
struct bdrv_iterate_context {
1083
    Monitor *mon;
1084
    int err;
1085
};
1086

    
1087
/**
1088
 * do_cont(): Resume emulation.
1089
 */
1090
static int do_cont(Monitor *mon, const QDict *qdict, QObject **ret_data)
1091
{
1092
    struct bdrv_iterate_context context = { mon, 0 };
1093

    
1094
    if (incoming_expected) {
1095
        qerror_report(QERR_MIGRATION_EXPECTED);
1096
        return -1;
1097
    }
1098
    bdrv_iterate(encrypted_bdrv_it, &context);
1099
    /* only resume the vm if all keys are set and valid */
1100
    if (!context.err) {
1101
        vm_start();
1102
        return 0;
1103
    } else {
1104
        return -1;
1105
    }
1106
}
1107

    
1108
static void bdrv_key_cb(void *opaque, int err)
1109
{
1110
    Monitor *mon = opaque;
1111

    
1112
    /* another key was set successfully, retry to continue */
1113
    if (!err)
1114
        do_cont(mon, NULL, NULL);
1115
}
1116

    
1117
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs)
1118
{
1119
    struct bdrv_iterate_context *context = opaque;
1120

    
1121
    if (!context->err && bdrv_key_required(bs)) {
1122
        context->err = -EBUSY;
1123
        monitor_read_bdrv_key_start(context->mon, bs, bdrv_key_cb,
1124
                                    context->mon);
1125
    }
1126
}
1127

    
1128
static void do_gdbserver(Monitor *mon, const QDict *qdict)
1129
{
1130
    const char *device = qdict_get_try_str(qdict, "device");
1131
    if (!device)
1132
        device = "tcp::" DEFAULT_GDBSTUB_PORT;
1133
    if (gdbserver_start(device) < 0) {
1134
        monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1135
                       device);
1136
    } else if (strcmp(device, "none") == 0) {
1137
        monitor_printf(mon, "Disabled gdbserver\n");
1138
    } else {
1139
        monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1140
                       device);
1141
    }
1142
}
1143

    
1144
static void do_watchdog_action(Monitor *mon, const QDict *qdict)
1145
{
1146
    const char *action = qdict_get_str(qdict, "action");
1147
    if (select_watchdog_action(action) == -1) {
1148
        monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1149
    }
1150
}
1151

    
1152
static void monitor_printc(Monitor *mon, int c)
1153
{
1154
    monitor_printf(mon, "'");
1155
    switch(c) {
1156
    case '\'':
1157
        monitor_printf(mon, "\\'");
1158
        break;
1159
    case '\\':
1160
        monitor_printf(mon, "\\\\");
1161
        break;
1162
    case '\n':
1163
        monitor_printf(mon, "\\n");
1164
        break;
1165
    case '\r':
1166
        monitor_printf(mon, "\\r");
1167
        break;
1168
    default:
1169
        if (c >= 32 && c <= 126) {
1170
            monitor_printf(mon, "%c", c);
1171
        } else {
1172
            monitor_printf(mon, "\\x%02x", c);
1173
        }
1174
        break;
1175
    }
1176
    monitor_printf(mon, "'");
1177
}
1178

    
1179
static void memory_dump(Monitor *mon, int count, int format, int wsize,
1180
                        target_phys_addr_t addr, int is_physical)
1181
{
1182
    CPUState *env;
1183
    int l, line_size, i, max_digits, len;
1184
    uint8_t buf[16];
1185
    uint64_t v;
1186

    
1187
    if (format == 'i') {
1188
        int flags;
1189
        flags = 0;
1190
        env = mon_get_cpu();
1191
#ifdef TARGET_I386
1192
        if (wsize == 2) {
1193
            flags = 1;
1194
        } else if (wsize == 4) {
1195
            flags = 0;
1196
        } else {
1197
            /* as default we use the current CS size */
1198
            flags = 0;
1199
            if (env) {
1200
#ifdef TARGET_X86_64
1201
                if ((env->efer & MSR_EFER_LMA) &&
1202
                    (env->segs[R_CS].flags & DESC_L_MASK))
1203
                    flags = 2;
1204
                else
1205
#endif
1206
                if (!(env->segs[R_CS].flags & DESC_B_MASK))
1207
                    flags = 1;
1208
            }
1209
        }
1210
#endif
1211
        monitor_disas(mon, env, addr, count, is_physical, flags);
1212
        return;
1213
    }
1214

    
1215
    len = wsize * count;
1216
    if (wsize == 1)
1217
        line_size = 8;
1218
    else
1219
        line_size = 16;
1220
    max_digits = 0;
1221

    
1222
    switch(format) {
1223
    case 'o':
1224
        max_digits = (wsize * 8 + 2) / 3;
1225
        break;
1226
    default:
1227
    case 'x':
1228
        max_digits = (wsize * 8) / 4;
1229
        break;
1230
    case 'u':
1231
    case 'd':
1232
        max_digits = (wsize * 8 * 10 + 32) / 33;
1233
        break;
1234
    case 'c':
1235
        wsize = 1;
1236
        break;
1237
    }
1238

    
1239
    while (len > 0) {
1240
        if (is_physical)
1241
            monitor_printf(mon, TARGET_FMT_plx ":", addr);
1242
        else
1243
            monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1244
        l = len;
1245
        if (l > line_size)
1246
            l = line_size;
1247
        if (is_physical) {
1248
            cpu_physical_memory_rw(addr, buf, l, 0);
1249
        } else {
1250
            env = mon_get_cpu();
1251
            if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {
1252
                monitor_printf(mon, " Cannot access memory\n");
1253
                break;
1254
            }
1255
        }
1256
        i = 0;
1257
        while (i < l) {
1258
            switch(wsize) {
1259
            default:
1260
            case 1:
1261
                v = ldub_raw(buf + i);
1262
                break;
1263
            case 2:
1264
                v = lduw_raw(buf + i);
1265
                break;
1266
            case 4:
1267
                v = (uint32_t)ldl_raw(buf + i);
1268
                break;
1269
            case 8:
1270
                v = ldq_raw(buf + i);
1271
                break;
1272
            }
1273
            monitor_printf(mon, " ");
1274
            switch(format) {
1275
            case 'o':
1276
                monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1277
                break;
1278
            case 'x':
1279
                monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1280
                break;
1281
            case 'u':
1282
                monitor_printf(mon, "%*" PRIu64, max_digits, v);
1283
                break;
1284
            case 'd':
1285
                monitor_printf(mon, "%*" PRId64, max_digits, v);
1286
                break;
1287
            case 'c':
1288
                monitor_printc(mon, v);
1289
                break;
1290
            }
1291
            i += wsize;
1292
        }
1293
        monitor_printf(mon, "\n");
1294
        addr += l;
1295
        len -= l;
1296
    }
1297
}
1298

    
1299
static void do_memory_dump(Monitor *mon, const QDict *qdict)
1300
{
1301
    int count = qdict_get_int(qdict, "count");
1302
    int format = qdict_get_int(qdict, "format");
1303
    int size = qdict_get_int(qdict, "size");
1304
    target_long addr = qdict_get_int(qdict, "addr");
1305

    
1306
    memory_dump(mon, count, format, size, addr, 0);
1307
}
1308

    
1309
static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
1310
{
1311
    int count = qdict_get_int(qdict, "count");
1312
    int format = qdict_get_int(qdict, "format");
1313
    int size = qdict_get_int(qdict, "size");
1314
    target_phys_addr_t addr = qdict_get_int(qdict, "addr");
1315

    
1316
    memory_dump(mon, count, format, size, addr, 1);
1317
}
1318

    
1319
static void do_print(Monitor *mon, const QDict *qdict)
1320
{
1321
    int format = qdict_get_int(qdict, "format");
1322
    target_phys_addr_t val = qdict_get_int(qdict, "val");
1323

    
1324
#if TARGET_PHYS_ADDR_BITS == 32
1325
    switch(format) {
1326
    case 'o':
1327
        monitor_printf(mon, "%#o", val);
1328
        break;
1329
    case 'x':
1330
        monitor_printf(mon, "%#x", val);
1331
        break;
1332
    case 'u':
1333
        monitor_printf(mon, "%u", val);
1334
        break;
1335
    default:
1336
    case 'd':
1337
        monitor_printf(mon, "%d", val);
1338
        break;
1339
    case 'c':
1340
        monitor_printc(mon, val);
1341
        break;
1342
    }
1343
#else
1344
    switch(format) {
1345
    case 'o':
1346
        monitor_printf(mon, "%#" PRIo64, val);
1347
        break;
1348
    case 'x':
1349
        monitor_printf(mon, "%#" PRIx64, val);
1350
        break;
1351
    case 'u':
1352
        monitor_printf(mon, "%" PRIu64, val);
1353
        break;
1354
    default:
1355
    case 'd':
1356
        monitor_printf(mon, "%" PRId64, val);
1357
        break;
1358
    case 'c':
1359
        monitor_printc(mon, val);
1360
        break;
1361
    }
1362
#endif
1363
    monitor_printf(mon, "\n");
1364
}
1365

    
1366
static int do_memory_save(Monitor *mon, const QDict *qdict, QObject **ret_data)
1367
{
1368
    FILE *f;
1369
    uint32_t size = qdict_get_int(qdict, "size");
1370
    const char *filename = qdict_get_str(qdict, "filename");
1371
    target_long addr = qdict_get_int(qdict, "val");
1372
    uint32_t l;
1373
    CPUState *env;
1374
    uint8_t buf[1024];
1375
    int ret = -1;
1376

    
1377
    env = mon_get_cpu();
1378

    
1379
    f = fopen(filename, "wb");
1380
    if (!f) {
1381
        qerror_report(QERR_OPEN_FILE_FAILED, filename);
1382
        return -1;
1383
    }
1384
    while (size != 0) {
1385
        l = sizeof(buf);
1386
        if (l > size)
1387
            l = size;
1388
        cpu_memory_rw_debug(env, addr, buf, l, 0);
1389
        if (fwrite(buf, 1, l, f) != l) {
1390
            monitor_printf(mon, "fwrite() error in do_memory_save\n");
1391
            goto exit;
1392
        }
1393
        addr += l;
1394
        size -= l;
1395
    }
1396

    
1397
    ret = 0;
1398

    
1399
exit:
1400
    fclose(f);
1401
    return ret;
1402
}
1403

    
1404
static int do_physical_memory_save(Monitor *mon, const QDict *qdict,
1405
                                    QObject **ret_data)
1406
{
1407
    FILE *f;
1408
    uint32_t l;
1409
    uint8_t buf[1024];
1410
    uint32_t size = qdict_get_int(qdict, "size");
1411
    const char *filename = qdict_get_str(qdict, "filename");
1412
    target_phys_addr_t addr = qdict_get_int(qdict, "val");
1413
    int ret = -1;
1414

    
1415
    f = fopen(filename, "wb");
1416
    if (!f) {
1417
        qerror_report(QERR_OPEN_FILE_FAILED, filename);
1418
        return -1;
1419
    }
1420
    while (size != 0) {
1421
        l = sizeof(buf);
1422
        if (l > size)
1423
            l = size;
1424
        cpu_physical_memory_rw(addr, buf, l, 0);
1425
        if (fwrite(buf, 1, l, f) != l) {
1426
            monitor_printf(mon, "fwrite() error in do_physical_memory_save\n");
1427
            goto exit;
1428
        }
1429
        fflush(f);
1430
        addr += l;
1431
        size -= l;
1432
    }
1433

    
1434
    ret = 0;
1435

    
1436
exit:
1437
    fclose(f);
1438
    return ret;
1439
}
1440

    
1441
static void do_sum(Monitor *mon, const QDict *qdict)
1442
{
1443
    uint32_t addr;
1444
    uint8_t buf[1];
1445
    uint16_t sum;
1446
    uint32_t start = qdict_get_int(qdict, "start");
1447
    uint32_t size = qdict_get_int(qdict, "size");
1448

    
1449
    sum = 0;
1450
    for(addr = start; addr < (start + size); addr++) {
1451
        cpu_physical_memory_rw(addr, buf, 1, 0);
1452
        /* BSD sum algorithm ('sum' Unix command) */
1453
        sum = (sum >> 1) | (sum << 15);
1454
        sum += buf[0];
1455
    }
1456
    monitor_printf(mon, "%05d\n", sum);
1457
}
1458

    
1459
typedef struct {
1460
    int keycode;
1461
    const char *name;
1462
} KeyDef;
1463

    
1464
static const KeyDef key_defs[] = {
1465
    { 0x2a, "shift" },
1466
    { 0x36, "shift_r" },
1467

    
1468
    { 0x38, "alt" },
1469
    { 0xb8, "alt_r" },
1470
    { 0x64, "altgr" },
1471
    { 0xe4, "altgr_r" },
1472
    { 0x1d, "ctrl" },
1473
    { 0x9d, "ctrl_r" },
1474

    
1475
    { 0xdd, "menu" },
1476

    
1477
    { 0x01, "esc" },
1478

    
1479
    { 0x02, "1" },
1480
    { 0x03, "2" },
1481
    { 0x04, "3" },
1482
    { 0x05, "4" },
1483
    { 0x06, "5" },
1484
    { 0x07, "6" },
1485
    { 0x08, "7" },
1486
    { 0x09, "8" },
1487
    { 0x0a, "9" },
1488
    { 0x0b, "0" },
1489
    { 0x0c, "minus" },
1490
    { 0x0d, "equal" },
1491
    { 0x0e, "backspace" },
1492

    
1493
    { 0x0f, "tab" },
1494
    { 0x10, "q" },
1495
    { 0x11, "w" },
1496
    { 0x12, "e" },
1497
    { 0x13, "r" },
1498
    { 0x14, "t" },
1499
    { 0x15, "y" },
1500
    { 0x16, "u" },
1501
    { 0x17, "i" },
1502
    { 0x18, "o" },
1503
    { 0x19, "p" },
1504
    { 0x1a, "bracket_left" },
1505
    { 0x1b, "bracket_right" },
1506
    { 0x1c, "ret" },
1507

    
1508
    { 0x1e, "a" },
1509
    { 0x1f, "s" },
1510
    { 0x20, "d" },
1511
    { 0x21, "f" },
1512
    { 0x22, "g" },
1513
    { 0x23, "h" },
1514
    { 0x24, "j" },
1515
    { 0x25, "k" },
1516
    { 0x26, "l" },
1517
    { 0x27, "semicolon" },
1518
    { 0x28, "apostrophe" },
1519
    { 0x29, "grave_accent" },
1520

    
1521
    { 0x2b, "backslash" },
1522
    { 0x2c, "z" },
1523
    { 0x2d, "x" },
1524
    { 0x2e, "c" },
1525
    { 0x2f, "v" },
1526
    { 0x30, "b" },
1527
    { 0x31, "n" },
1528
    { 0x32, "m" },
1529
    { 0x33, "comma" },
1530
    { 0x34, "dot" },
1531
    { 0x35, "slash" },
1532

    
1533
    { 0x37, "asterisk" },
1534

    
1535
    { 0x39, "spc" },
1536
    { 0x3a, "caps_lock" },
1537
    { 0x3b, "f1" },
1538
    { 0x3c, "f2" },
1539
    { 0x3d, "f3" },
1540
    { 0x3e, "f4" },
1541
    { 0x3f, "f5" },
1542
    { 0x40, "f6" },
1543
    { 0x41, "f7" },
1544
    { 0x42, "f8" },
1545
    { 0x43, "f9" },
1546
    { 0x44, "f10" },
1547
    { 0x45, "num_lock" },
1548
    { 0x46, "scroll_lock" },
1549

    
1550
    { 0xb5, "kp_divide" },
1551
    { 0x37, "kp_multiply" },
1552
    { 0x4a, "kp_subtract" },
1553
    { 0x4e, "kp_add" },
1554
    { 0x9c, "kp_enter" },
1555
    { 0x53, "kp_decimal" },
1556
    { 0x54, "sysrq" },
1557

    
1558
    { 0x52, "kp_0" },
1559
    { 0x4f, "kp_1" },
1560
    { 0x50, "kp_2" },
1561
    { 0x51, "kp_3" },
1562
    { 0x4b, "kp_4" },
1563
    { 0x4c, "kp_5" },
1564
    { 0x4d, "kp_6" },
1565
    { 0x47, "kp_7" },
1566
    { 0x48, "kp_8" },
1567
    { 0x49, "kp_9" },
1568

    
1569
    { 0x56, "<" },
1570

    
1571
    { 0x57, "f11" },
1572
    { 0x58, "f12" },
1573

    
1574
    { 0xb7, "print" },
1575

    
1576
    { 0xc7, "home" },
1577
    { 0xc9, "pgup" },
1578
    { 0xd1, "pgdn" },
1579
    { 0xcf, "end" },
1580

    
1581
    { 0xcb, "left" },
1582
    { 0xc8, "up" },
1583
    { 0xd0, "down" },
1584
    { 0xcd, "right" },
1585

    
1586
    { 0xd2, "insert" },
1587
    { 0xd3, "delete" },
1588
#if defined(TARGET_SPARC) && !defined(TARGET_SPARC64)
1589
    { 0xf0, "stop" },
1590
    { 0xf1, "again" },
1591
    { 0xf2, "props" },
1592
    { 0xf3, "undo" },
1593
    { 0xf4, "front" },
1594
    { 0xf5, "copy" },
1595
    { 0xf6, "open" },
1596
    { 0xf7, "paste" },
1597
    { 0xf8, "find" },
1598
    { 0xf9, "cut" },
1599
    { 0xfa, "lf" },
1600
    { 0xfb, "help" },
1601
    { 0xfc, "meta_l" },
1602
    { 0xfd, "meta_r" },
1603
    { 0xfe, "compose" },
1604
#endif
1605
    { 0, NULL },
1606
};
1607

    
1608
static int get_keycode(const char *key)
1609
{
1610
    const KeyDef *p;
1611
    char *endp;
1612
    int ret;
1613

    
1614
    for(p = key_defs; p->name != NULL; p++) {
1615
        if (!strcmp(key, p->name))
1616
            return p->keycode;
1617
    }
1618
    if (strstart(key, "0x", NULL)) {
1619
        ret = strtoul(key, &endp, 0);
1620
        if (*endp == '\0' && ret >= 0x01 && ret <= 0xff)
1621
            return ret;
1622
    }
1623
    return -1;
1624
}
1625

    
1626
#define MAX_KEYCODES 16
1627
static uint8_t keycodes[MAX_KEYCODES];
1628
static int nb_pending_keycodes;
1629
static QEMUTimer *key_timer;
1630

    
1631
static void release_keys(void *opaque)
1632
{
1633
    int keycode;
1634

    
1635
    while (nb_pending_keycodes > 0) {
1636
        nb_pending_keycodes--;
1637
        keycode = keycodes[nb_pending_keycodes];
1638
        if (keycode & 0x80)
1639
            kbd_put_keycode(0xe0);
1640
        kbd_put_keycode(keycode | 0x80);
1641
    }
1642
}
1643

    
1644
static void do_sendkey(Monitor *mon, const QDict *qdict)
1645
{
1646
    char keyname_buf[16];
1647
    char *separator;
1648
    int keyname_len, keycode, i;
1649
    const char *string = qdict_get_str(qdict, "string");
1650
    int has_hold_time = qdict_haskey(qdict, "hold_time");
1651
    int hold_time = qdict_get_try_int(qdict, "hold_time", -1);
1652

    
1653
    if (nb_pending_keycodes > 0) {
1654
        qemu_del_timer(key_timer);
1655
        release_keys(NULL);
1656
    }
1657
    if (!has_hold_time)
1658
        hold_time = 100;
1659
    i = 0;
1660
    while (1) {
1661
        separator = strchr(string, '-');
1662
        keyname_len = separator ? separator - string : strlen(string);
1663
        if (keyname_len > 0) {
1664
            pstrcpy(keyname_buf, sizeof(keyname_buf), string);
1665
            if (keyname_len > sizeof(keyname_buf) - 1) {
1666
                monitor_printf(mon, "invalid key: '%s...'\n", keyname_buf);
1667
                return;
1668
            }
1669
            if (i == MAX_KEYCODES) {
1670
                monitor_printf(mon, "too many keys\n");
1671
                return;
1672
            }
1673
            keyname_buf[keyname_len] = 0;
1674
            keycode = get_keycode(keyname_buf);
1675
            if (keycode < 0) {
1676
                monitor_printf(mon, "unknown key: '%s'\n", keyname_buf);
1677
                return;
1678
            }
1679
            keycodes[i++] = keycode;
1680
        }
1681
        if (!separator)
1682
            break;
1683
        string = separator + 1;
1684
    }
1685
    nb_pending_keycodes = i;
1686
    /* key down events */
1687
    for (i = 0; i < nb_pending_keycodes; i++) {
1688
        keycode = keycodes[i];
1689
        if (keycode & 0x80)
1690
            kbd_put_keycode(0xe0);
1691
        kbd_put_keycode(keycode & 0x7f);
1692
    }
1693
    /* delayed key up events */
1694
    qemu_mod_timer(key_timer, qemu_get_clock(vm_clock) +
1695
                   muldiv64(get_ticks_per_sec(), hold_time, 1000));
1696
}
1697

    
1698
static int mouse_button_state;
1699

    
1700
static void do_mouse_move(Monitor *mon, const QDict *qdict)
1701
{
1702
    int dx, dy, dz;
1703
    const char *dx_str = qdict_get_str(qdict, "dx_str");
1704
    const char *dy_str = qdict_get_str(qdict, "dy_str");
1705
    const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1706
    dx = strtol(dx_str, NULL, 0);
1707
    dy = strtol(dy_str, NULL, 0);
1708
    dz = 0;
1709
    if (dz_str)
1710
        dz = strtol(dz_str, NULL, 0);
1711
    kbd_mouse_event(dx, dy, dz, mouse_button_state);
1712
}
1713

    
1714
static void do_mouse_button(Monitor *mon, const QDict *qdict)
1715
{
1716
    int button_state = qdict_get_int(qdict, "button_state");
1717
    mouse_button_state = button_state;
1718
    kbd_mouse_event(0, 0, 0, mouse_button_state);
1719
}
1720

    
1721
static void do_ioport_read(Monitor *mon, const QDict *qdict)
1722
{
1723
    int size = qdict_get_int(qdict, "size");
1724
    int addr = qdict_get_int(qdict, "addr");
1725
    int has_index = qdict_haskey(qdict, "index");
1726
    uint32_t val;
1727
    int suffix;
1728

    
1729
    if (has_index) {
1730
        int index = qdict_get_int(qdict, "index");
1731
        cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1732
        addr++;
1733
    }
1734
    addr &= 0xffff;
1735

    
1736
    switch(size) {
1737
    default:
1738
    case 1:
1739
        val = cpu_inb(addr);
1740
        suffix = 'b';
1741
        break;
1742
    case 2:
1743
        val = cpu_inw(addr);
1744
        suffix = 'w';
1745
        break;
1746
    case 4:
1747
        val = cpu_inl(addr);
1748
        suffix = 'l';
1749
        break;
1750
    }
1751
    monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1752
                   suffix, addr, size * 2, val);
1753
}
1754

    
1755
static void do_ioport_write(Monitor *mon, const QDict *qdict)
1756
{
1757
    int size = qdict_get_int(qdict, "size");
1758
    int addr = qdict_get_int(qdict, "addr");
1759
    int val = qdict_get_int(qdict, "val");
1760

    
1761
    addr &= IOPORTS_MASK;
1762

    
1763
    switch (size) {
1764
    default:
1765
    case 1:
1766
        cpu_outb(addr, val);
1767
        break;
1768
    case 2:
1769
        cpu_outw(addr, val);
1770
        break;
1771
    case 4:
1772
        cpu_outl(addr, val);
1773
        break;
1774
    }
1775
}
1776

    
1777
static void do_boot_set(Monitor *mon, const QDict *qdict)
1778
{
1779
    int res;
1780
    const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1781

    
1782
    res = qemu_boot_set(bootdevice);
1783
    if (res == 0) {
1784
        monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1785
    } else if (res > 0) {
1786
        monitor_printf(mon, "setting boot device list failed\n");
1787
    } else {
1788
        monitor_printf(mon, "no function defined to set boot device list for "
1789
                       "this architecture\n");
1790
    }
1791
}
1792

    
1793
/**
1794
 * do_system_reset(): Issue a machine reset
1795
 */
1796
static int do_system_reset(Monitor *mon, const QDict *qdict,
1797
                           QObject **ret_data)
1798
{
1799
    qemu_system_reset_request();
1800
    return 0;
1801
}
1802

    
1803
/**
1804
 * do_system_powerdown(): Issue a machine powerdown
1805
 */
1806
static int do_system_powerdown(Monitor *mon, const QDict *qdict,
1807
                               QObject **ret_data)
1808
{
1809
    qemu_system_powerdown_request();
1810
    return 0;
1811
}
1812

    
1813
#if defined(TARGET_I386)
1814
static void print_pte(Monitor *mon, uint32_t addr, uint32_t pte, uint32_t mask)
1815
{
1816
    monitor_printf(mon, "%08x: %08x %c%c%c%c%c%c%c%c\n",
1817
                   addr,
1818
                   pte & mask,
1819
                   pte & PG_GLOBAL_MASK ? 'G' : '-',
1820
                   pte & PG_PSE_MASK ? 'P' : '-',
1821
                   pte & PG_DIRTY_MASK ? 'D' : '-',
1822
                   pte & PG_ACCESSED_MASK ? 'A' : '-',
1823
                   pte & PG_PCD_MASK ? 'C' : '-',
1824
                   pte & PG_PWT_MASK ? 'T' : '-',
1825
                   pte & PG_USER_MASK ? 'U' : '-',
1826
                   pte & PG_RW_MASK ? 'W' : '-');
1827
}
1828

    
1829
static void tlb_info(Monitor *mon)
1830
{
1831
    CPUState *env;
1832
    int l1, l2;
1833
    uint32_t pgd, pde, pte;
1834

    
1835
    env = mon_get_cpu();
1836

    
1837
    if (!(env->cr[0] & CR0_PG_MASK)) {
1838
        monitor_printf(mon, "PG disabled\n");
1839
        return;
1840
    }
1841
    pgd = env->cr[3] & ~0xfff;
1842
    for(l1 = 0; l1 < 1024; l1++) {
1843
        cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1844
        pde = le32_to_cpu(pde);
1845
        if (pde & PG_PRESENT_MASK) {
1846
            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1847
                print_pte(mon, (l1 << 22), pde, ~((1 << 20) - 1));
1848
            } else {
1849
                for(l2 = 0; l2 < 1024; l2++) {
1850
                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1851
                                             (uint8_t *)&pte, 4);
1852
                    pte = le32_to_cpu(pte);
1853
                    if (pte & PG_PRESENT_MASK) {
1854
                        print_pte(mon, (l1 << 22) + (l2 << 12),
1855
                                  pte & ~PG_PSE_MASK,
1856
                                  ~0xfff);
1857
                    }
1858
                }
1859
            }
1860
        }
1861
    }
1862
}
1863

    
1864
static void mem_print(Monitor *mon, uint32_t *pstart, int *plast_prot,
1865
                      uint32_t end, int prot)
1866
{
1867
    int prot1;
1868
    prot1 = *plast_prot;
1869
    if (prot != prot1) {
1870
        if (*pstart != -1) {
1871
            monitor_printf(mon, "%08x-%08x %08x %c%c%c\n",
1872
                           *pstart, end, end - *pstart,
1873
                           prot1 & PG_USER_MASK ? 'u' : '-',
1874
                           'r',
1875
                           prot1 & PG_RW_MASK ? 'w' : '-');
1876
        }
1877
        if (prot != 0)
1878
            *pstart = end;
1879
        else
1880
            *pstart = -1;
1881
        *plast_prot = prot;
1882
    }
1883
}
1884

    
1885
static void mem_info(Monitor *mon)
1886
{
1887
    CPUState *env;
1888
    int l1, l2, prot, last_prot;
1889
    uint32_t pgd, pde, pte, start, end;
1890

    
1891
    env = mon_get_cpu();
1892

    
1893
    if (!(env->cr[0] & CR0_PG_MASK)) {
1894
        monitor_printf(mon, "PG disabled\n");
1895
        return;
1896
    }
1897
    pgd = env->cr[3] & ~0xfff;
1898
    last_prot = 0;
1899
    start = -1;
1900
    for(l1 = 0; l1 < 1024; l1++) {
1901
        cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1902
        pde = le32_to_cpu(pde);
1903
        end = l1 << 22;
1904
        if (pde & PG_PRESENT_MASK) {
1905
            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1906
                prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1907
                mem_print(mon, &start, &last_prot, end, prot);
1908
            } else {
1909
                for(l2 = 0; l2 < 1024; l2++) {
1910
                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1911
                                             (uint8_t *)&pte, 4);
1912
                    pte = le32_to_cpu(pte);
1913
                    end = (l1 << 22) + (l2 << 12);
1914
                    if (pte & PG_PRESENT_MASK) {
1915
                        prot = pte & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1916
                    } else {
1917
                        prot = 0;
1918
                    }
1919
                    mem_print(mon, &start, &last_prot, end, prot);
1920
                }
1921
            }
1922
        } else {
1923
            prot = 0;
1924
            mem_print(mon, &start, &last_prot, end, prot);
1925
        }
1926
    }
1927
}
1928
#endif
1929

    
1930
#if defined(TARGET_SH4)
1931

    
1932
static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1933
{
1934
    monitor_printf(mon, " tlb%i:\t"
1935
                   "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1936
                   "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1937
                   "dirty=%hhu writethrough=%hhu\n",
1938
                   idx,
1939
                   tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1940
                   tlb->v, tlb->sh, tlb->c, tlb->pr,
1941
                   tlb->d, tlb->wt);
1942
}
1943

    
1944
static void tlb_info(Monitor *mon)
1945
{
1946
    CPUState *env = mon_get_cpu();
1947
    int i;
1948

    
1949
    monitor_printf (mon, "ITLB:\n");
1950
    for (i = 0 ; i < ITLB_SIZE ; i++)
1951
        print_tlb (mon, i, &env->itlb[i]);
1952
    monitor_printf (mon, "UTLB:\n");
1953
    for (i = 0 ; i < UTLB_SIZE ; i++)
1954
        print_tlb (mon, i, &env->utlb[i]);
1955
}
1956

    
1957
#endif
1958

    
1959
static void do_info_kvm_print(Monitor *mon, const QObject *data)
1960
{
1961
    QDict *qdict;
1962

    
1963
    qdict = qobject_to_qdict(data);
1964

    
1965
    monitor_printf(mon, "kvm support: ");
1966
    if (qdict_get_bool(qdict, "present")) {
1967
        monitor_printf(mon, "%s\n", qdict_get_bool(qdict, "enabled") ?
1968
                                    "enabled" : "disabled");
1969
    } else {
1970
        monitor_printf(mon, "not compiled\n");
1971
    }
1972
}
1973

    
1974
static void do_info_kvm(Monitor *mon, QObject **ret_data)
1975
{
1976
#ifdef CONFIG_KVM
1977
    *ret_data = qobject_from_jsonf("{ 'enabled': %i, 'present': true }",
1978
                                   kvm_enabled());
1979
#else
1980
    *ret_data = qobject_from_jsonf("{ 'enabled': false, 'present': false }");
1981
#endif
1982
}
1983

    
1984
static void do_info_numa(Monitor *mon)
1985
{
1986
    int i;
1987
    CPUState *env;
1988

    
1989
    monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1990
    for (i = 0; i < nb_numa_nodes; i++) {
1991
        monitor_printf(mon, "node %d cpus:", i);
1992
        for (env = first_cpu; env != NULL; env = env->next_cpu) {
1993
            if (env->numa_node == i) {
1994
                monitor_printf(mon, " %d", env->cpu_index);
1995
            }
1996
        }
1997
        monitor_printf(mon, "\n");
1998
        monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1999
            node_mem[i] >> 20);
2000
    }
2001
}
2002

    
2003
#ifdef CONFIG_PROFILER
2004

    
2005
int64_t qemu_time;
2006
int64_t dev_time;
2007

    
2008
static void do_info_profile(Monitor *mon)
2009
{
2010
    int64_t total;
2011
    total = qemu_time;
2012
    if (total == 0)
2013
        total = 1;
2014
    monitor_printf(mon, "async time  %" PRId64 " (%0.3f)\n",
2015
                   dev_time, dev_time / (double)get_ticks_per_sec());
2016
    monitor_printf(mon, "qemu time   %" PRId64 " (%0.3f)\n",
2017
                   qemu_time, qemu_time / (double)get_ticks_per_sec());
2018
    qemu_time = 0;
2019
    dev_time = 0;
2020
}
2021
#else
2022
static void do_info_profile(Monitor *mon)
2023
{
2024
    monitor_printf(mon, "Internal profiler not compiled\n");
2025
}
2026
#endif
2027

    
2028
/* Capture support */
2029
static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2030

    
2031
static void do_info_capture(Monitor *mon)
2032
{
2033
    int i;
2034
    CaptureState *s;
2035

    
2036
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2037
        monitor_printf(mon, "[%d]: ", i);
2038
        s->ops.info (s->opaque);
2039
    }
2040
}
2041

    
2042
#ifdef HAS_AUDIO
2043
static void do_stop_capture(Monitor *mon, const QDict *qdict)
2044
{
2045
    int i;
2046
    int n = qdict_get_int(qdict, "n");
2047
    CaptureState *s;
2048

    
2049
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2050
        if (i == n) {
2051
            s->ops.destroy (s->opaque);
2052
            QLIST_REMOVE (s, entries);
2053
            qemu_free (s);
2054
            return;
2055
        }
2056
    }
2057
}
2058

    
2059
static void do_wav_capture(Monitor *mon, const QDict *qdict)
2060
{
2061
    const char *path = qdict_get_str(qdict, "path");
2062
    int has_freq = qdict_haskey(qdict, "freq");
2063
    int freq = qdict_get_try_int(qdict, "freq", -1);
2064
    int has_bits = qdict_haskey(qdict, "bits");
2065
    int bits = qdict_get_try_int(qdict, "bits", -1);
2066
    int has_channels = qdict_haskey(qdict, "nchannels");
2067
    int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2068
    CaptureState *s;
2069

    
2070
    s = qemu_mallocz (sizeof (*s));
2071

    
2072
    freq = has_freq ? freq : 44100;
2073
    bits = has_bits ? bits : 16;
2074
    nchannels = has_channels ? nchannels : 2;
2075

    
2076
    if (wav_start_capture (s, path, freq, bits, nchannels)) {
2077
        monitor_printf(mon, "Faied to add wave capture\n");
2078
        qemu_free (s);
2079
    }
2080
    QLIST_INSERT_HEAD (&capture_head, s, entries);
2081
}
2082
#endif
2083

    
2084
#if defined(TARGET_I386)
2085
static void do_inject_nmi(Monitor *mon, const QDict *qdict)
2086
{
2087
    CPUState *env;
2088
    int cpu_index = qdict_get_int(qdict, "cpu_index");
2089

    
2090
    for (env = first_cpu; env != NULL; env = env->next_cpu)
2091
        if (env->cpu_index == cpu_index) {
2092
            cpu_interrupt(env, CPU_INTERRUPT_NMI);
2093
            break;
2094
        }
2095
}
2096
#endif
2097

    
2098
static void do_info_status_print(Monitor *mon, const QObject *data)
2099
{
2100
    QDict *qdict;
2101

    
2102
    qdict = qobject_to_qdict(data);
2103

    
2104
    monitor_printf(mon, "VM status: ");
2105
    if (qdict_get_bool(qdict, "running")) {
2106
        monitor_printf(mon, "running");
2107
        if (qdict_get_bool(qdict, "singlestep")) {
2108
            monitor_printf(mon, " (single step mode)");
2109
        }
2110
    } else {
2111
        monitor_printf(mon, "paused");
2112
    }
2113

    
2114
    monitor_printf(mon, "\n");
2115
}
2116

    
2117
static void do_info_status(Monitor *mon, QObject **ret_data)
2118
{
2119
    *ret_data = qobject_from_jsonf("{ 'running': %i, 'singlestep': %i }",
2120
                                    vm_running, singlestep);
2121
}
2122

    
2123
static qemu_acl *find_acl(Monitor *mon, const char *name)
2124
{
2125
    qemu_acl *acl = qemu_acl_find(name);
2126

    
2127
    if (!acl) {
2128
        monitor_printf(mon, "acl: unknown list '%s'\n", name);
2129
    }
2130
    return acl;
2131
}
2132

    
2133
static void do_acl_show(Monitor *mon, const QDict *qdict)
2134
{
2135
    const char *aclname = qdict_get_str(qdict, "aclname");
2136
    qemu_acl *acl = find_acl(mon, aclname);
2137
    qemu_acl_entry *entry;
2138
    int i = 0;
2139

    
2140
    if (acl) {
2141
        monitor_printf(mon, "policy: %s\n",
2142
                       acl->defaultDeny ? "deny" : "allow");
2143
        QTAILQ_FOREACH(entry, &acl->entries, next) {
2144
            i++;
2145
            monitor_printf(mon, "%d: %s %s\n", i,
2146
                           entry->deny ? "deny" : "allow", entry->match);
2147
        }
2148
    }
2149
}
2150

    
2151
static void do_acl_reset(Monitor *mon, const QDict *qdict)
2152
{
2153
    const char *aclname = qdict_get_str(qdict, "aclname");
2154
    qemu_acl *acl = find_acl(mon, aclname);
2155

    
2156
    if (acl) {
2157
        qemu_acl_reset(acl);
2158
        monitor_printf(mon, "acl: removed all rules\n");
2159
    }
2160
}
2161

    
2162
static void do_acl_policy(Monitor *mon, const QDict *qdict)
2163
{
2164
    const char *aclname = qdict_get_str(qdict, "aclname");
2165
    const char *policy = qdict_get_str(qdict, "policy");
2166
    qemu_acl *acl = find_acl(mon, aclname);
2167

    
2168
    if (acl) {
2169
        if (strcmp(policy, "allow") == 0) {
2170
            acl->defaultDeny = 0;
2171
            monitor_printf(mon, "acl: policy set to 'allow'\n");
2172
        } else if (strcmp(policy, "deny") == 0) {
2173
            acl->defaultDeny = 1;
2174
            monitor_printf(mon, "acl: policy set to 'deny'\n");
2175
        } else {
2176
            monitor_printf(mon, "acl: unknown policy '%s', "
2177
                           "expected 'deny' or 'allow'\n", policy);
2178
        }
2179
    }
2180
}
2181

    
2182
static void do_acl_add(Monitor *mon, const QDict *qdict)
2183
{
2184
    const char *aclname = qdict_get_str(qdict, "aclname");
2185
    const char *match = qdict_get_str(qdict, "match");
2186
    const char *policy = qdict_get_str(qdict, "policy");
2187
    int has_index = qdict_haskey(qdict, "index");
2188
    int index = qdict_get_try_int(qdict, "index", -1);
2189
    qemu_acl *acl = find_acl(mon, aclname);
2190
    int deny, ret;
2191

    
2192
    if (acl) {
2193
        if (strcmp(policy, "allow") == 0) {
2194
            deny = 0;
2195
        } else if (strcmp(policy, "deny") == 0) {
2196
            deny = 1;
2197
        } else {
2198
            monitor_printf(mon, "acl: unknown policy '%s', "
2199
                           "expected 'deny' or 'allow'\n", policy);
2200
            return;
2201
        }
2202
        if (has_index)
2203
            ret = qemu_acl_insert(acl, deny, match, index);
2204
        else
2205
            ret = qemu_acl_append(acl, deny, match);
2206
        if (ret < 0)
2207
            monitor_printf(mon, "acl: unable to add acl entry\n");
2208
        else
2209
            monitor_printf(mon, "acl: added rule at position %d\n", ret);
2210
    }
2211
}
2212

    
2213
static void do_acl_remove(Monitor *mon, const QDict *qdict)
2214
{
2215
    const char *aclname = qdict_get_str(qdict, "aclname");
2216
    const char *match = qdict_get_str(qdict, "match");
2217
    qemu_acl *acl = find_acl(mon, aclname);
2218
    int ret;
2219

    
2220
    if (acl) {
2221
        ret = qemu_acl_remove(acl, match);
2222
        if (ret < 0)
2223
            monitor_printf(mon, "acl: no matching acl entry\n");
2224
        else
2225
            monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2226
    }
2227
}
2228

    
2229
#if defined(TARGET_I386)
2230
static void do_inject_mce(Monitor *mon, const QDict *qdict)
2231
{
2232
    CPUState *cenv;
2233
    int cpu_index = qdict_get_int(qdict, "cpu_index");
2234
    int bank = qdict_get_int(qdict, "bank");
2235
    uint64_t status = qdict_get_int(qdict, "status");
2236
    uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2237
    uint64_t addr = qdict_get_int(qdict, "addr");
2238
    uint64_t misc = qdict_get_int(qdict, "misc");
2239

    
2240
    for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu)
2241
        if (cenv->cpu_index == cpu_index && cenv->mcg_cap) {
2242
            cpu_inject_x86_mce(cenv, bank, status, mcg_status, addr, misc);
2243
            break;
2244
        }
2245
}
2246
#endif
2247

    
2248
static int do_getfd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2249
{
2250
    const char *fdname = qdict_get_str(qdict, "fdname");
2251
    mon_fd_t *monfd;
2252
    int fd;
2253

    
2254
    fd = qemu_chr_get_msgfd(mon->chr);
2255
    if (fd == -1) {
2256
        qerror_report(QERR_FD_NOT_SUPPLIED);
2257
        return -1;
2258
    }
2259

    
2260
    if (qemu_isdigit(fdname[0])) {
2261
        qerror_report(QERR_INVALID_PARAMETER_VALUE, "fdname",
2262
                      "a name not starting with a digit");
2263
        return -1;
2264
    }
2265

    
2266
    QLIST_FOREACH(monfd, &mon->fds, next) {
2267
        if (strcmp(monfd->name, fdname) != 0) {
2268
            continue;
2269
        }
2270

    
2271
        close(monfd->fd);
2272
        monfd->fd = fd;
2273
        return 0;
2274
    }
2275

    
2276
    monfd = qemu_mallocz(sizeof(mon_fd_t));
2277
    monfd->name = qemu_strdup(fdname);
2278
    monfd->fd = fd;
2279

    
2280
    QLIST_INSERT_HEAD(&mon->fds, monfd, next);
2281
    return 0;
2282
}
2283

    
2284
static int do_closefd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2285
{
2286
    const char *fdname = qdict_get_str(qdict, "fdname");
2287
    mon_fd_t *monfd;
2288

    
2289
    QLIST_FOREACH(monfd, &mon->fds, next) {
2290
        if (strcmp(monfd->name, fdname) != 0) {
2291
            continue;
2292
        }
2293

    
2294
        QLIST_REMOVE(monfd, next);
2295
        close(monfd->fd);
2296
        qemu_free(monfd->name);
2297
        qemu_free(monfd);
2298
        return 0;
2299
    }
2300

    
2301
    qerror_report(QERR_FD_NOT_FOUND, fdname);
2302
    return -1;
2303
}
2304

    
2305
static void do_loadvm(Monitor *mon, const QDict *qdict)
2306
{
2307
    int saved_vm_running  = vm_running;
2308
    const char *name = qdict_get_str(qdict, "name");
2309

    
2310
    vm_stop(0);
2311

    
2312
    if (load_vmstate(name) == 0 && saved_vm_running) {
2313
        vm_start();
2314
    }
2315
}
2316

    
2317
int monitor_get_fd(Monitor *mon, const char *fdname)
2318
{
2319
    mon_fd_t *monfd;
2320

    
2321
    QLIST_FOREACH(monfd, &mon->fds, next) {
2322
        int fd;
2323

    
2324
        if (strcmp(monfd->name, fdname) != 0) {
2325
            continue;
2326
        }
2327

    
2328
        fd = monfd->fd;
2329

    
2330
        /* caller takes ownership of fd */
2331
        QLIST_REMOVE(monfd, next);
2332
        qemu_free(monfd->name);
2333
        qemu_free(monfd);
2334

    
2335
        return fd;
2336
    }
2337

    
2338
    return -1;
2339
}
2340

    
2341
static const mon_cmd_t mon_cmds[] = {
2342
#include "qemu-monitor.h"
2343
    { NULL, NULL, },
2344
};
2345

    
2346
/* Please update qemu-monitor.hx when adding or changing commands */
2347
static const mon_cmd_t info_cmds[] = {
2348
    {
2349
        .name       = "version",
2350
        .args_type  = "",
2351
        .params     = "",
2352
        .help       = "show the version of QEMU",
2353
        .user_print = do_info_version_print,
2354
        .mhandler.info_new = do_info_version,
2355
    },
2356
    {
2357
        .name       = "commands",
2358
        .args_type  = "",
2359
        .params     = "",
2360
        .help       = "list QMP available commands",
2361
        .user_print = monitor_user_noop,
2362
        .mhandler.info_new = do_info_commands,
2363
    },
2364
    {
2365
        .name       = "network",
2366
        .args_type  = "",
2367
        .params     = "",
2368
        .help       = "show the network state",
2369
        .mhandler.info = do_info_network,
2370
    },
2371
    {
2372
        .name       = "chardev",
2373
        .args_type  = "",
2374
        .params     = "",
2375
        .help       = "show the character devices",
2376
        .user_print = qemu_chr_info_print,
2377
        .mhandler.info_new = qemu_chr_info,
2378
    },
2379
    {
2380
        .name       = "block",
2381
        .args_type  = "",
2382
        .params     = "",
2383
        .help       = "show the block devices",
2384
        .user_print = bdrv_info_print,
2385
        .mhandler.info_new = bdrv_info,
2386
    },
2387
    {
2388
        .name       = "blockstats",
2389
        .args_type  = "",
2390
        .params     = "",
2391
        .help       = "show block device statistics",
2392
        .user_print = bdrv_stats_print,
2393
        .mhandler.info_new = bdrv_info_stats,
2394
    },
2395
    {
2396
        .name       = "registers",
2397
        .args_type  = "",
2398
        .params     = "",
2399
        .help       = "show the cpu registers",
2400
        .mhandler.info = do_info_registers,
2401
    },
2402
    {
2403
        .name       = "cpus",
2404
        .args_type  = "",
2405
        .params     = "",
2406
        .help       = "show infos for each CPU",
2407
        .user_print = monitor_print_cpus,
2408
        .mhandler.info_new = do_info_cpus,
2409
    },
2410
    {
2411
        .name       = "history",
2412
        .args_type  = "",
2413
        .params     = "",
2414
        .help       = "show the command line history",
2415
        .mhandler.info = do_info_history,
2416
    },
2417
    {
2418
        .name       = "irq",
2419
        .args_type  = "",
2420
        .params     = "",
2421
        .help       = "show the interrupts statistics (if available)",
2422
        .mhandler.info = irq_info,
2423
    },
2424
    {
2425
        .name       = "pic",
2426
        .args_type  = "",
2427
        .params     = "",
2428
        .help       = "show i8259 (PIC) state",
2429
        .mhandler.info = pic_info,
2430
    },
2431
    {
2432
        .name       = "pci",
2433
        .args_type  = "",
2434
        .params     = "",
2435
        .help       = "show PCI info",
2436
        .user_print = do_pci_info_print,
2437
        .mhandler.info_new = do_pci_info,
2438
    },
2439
#if defined(TARGET_I386) || defined(TARGET_SH4)
2440
    {
2441
        .name       = "tlb",
2442
        .args_type  = "",
2443
        .params     = "",
2444
        .help       = "show virtual to physical memory mappings",
2445
        .mhandler.info = tlb_info,
2446
    },
2447
#endif
2448
#if defined(TARGET_I386)
2449
    {
2450
        .name       = "mem",
2451
        .args_type  = "",
2452
        .params     = "",
2453
        .help       = "show the active virtual memory mappings",
2454
        .mhandler.info = mem_info,
2455
    },
2456
#endif
2457
    {
2458
        .name       = "jit",
2459
        .args_type  = "",
2460
        .params     = "",
2461
        .help       = "show dynamic compiler info",
2462
        .mhandler.info = do_info_jit,
2463
    },
2464
    {
2465
        .name       = "kvm",
2466
        .args_type  = "",
2467
        .params     = "",
2468
        .help       = "show KVM information",
2469
        .user_print = do_info_kvm_print,
2470
        .mhandler.info_new = do_info_kvm,
2471
    },
2472
    {
2473
        .name       = "numa",
2474
        .args_type  = "",
2475
        .params     = "",
2476
        .help       = "show NUMA information",
2477
        .mhandler.info = do_info_numa,
2478
    },
2479
    {
2480
        .name       = "usb",
2481
        .args_type  = "",
2482
        .params     = "",
2483
        .help       = "show guest USB devices",
2484
        .mhandler.info = usb_info,
2485
    },
2486
    {
2487
        .name       = "usbhost",
2488
        .args_type  = "",
2489
        .params     = "",
2490
        .help       = "show host USB devices",
2491
        .mhandler.info = usb_host_info,
2492
    },
2493
    {
2494
        .name       = "profile",
2495
        .args_type  = "",
2496
        .params     = "",
2497
        .help       = "show profiling information",
2498
        .mhandler.info = do_info_profile,
2499
    },
2500
    {
2501
        .name       = "capture",
2502
        .args_type  = "",
2503
        .params     = "",
2504
        .help       = "show capture information",
2505
        .mhandler.info = do_info_capture,
2506
    },
2507
    {
2508
        .name       = "snapshots",
2509
        .args_type  = "",
2510
        .params     = "",
2511
        .help       = "show the currently saved VM snapshots",
2512
        .mhandler.info = do_info_snapshots,
2513
    },
2514
    {
2515
        .name       = "status",
2516
        .args_type  = "",
2517
        .params     = "",
2518
        .help       = "show the current VM status (running|paused)",
2519
        .user_print = do_info_status_print,
2520
        .mhandler.info_new = do_info_status,
2521
    },
2522
    {
2523
        .name       = "pcmcia",
2524
        .args_type  = "",
2525
        .params     = "",
2526
        .help       = "show guest PCMCIA status",
2527
        .mhandler.info = pcmcia_info,
2528
    },
2529
    {
2530
        .name       = "mice",
2531
        .args_type  = "",
2532
        .params     = "",
2533
        .help       = "show which guest mouse is receiving events",
2534
        .user_print = do_info_mice_print,
2535
        .mhandler.info_new = do_info_mice,
2536
    },
2537
    {
2538
        .name       = "vnc",
2539
        .args_type  = "",
2540
        .params     = "",
2541
        .help       = "show the vnc server status",
2542
        .user_print = do_info_vnc_print,
2543
        .mhandler.info_new = do_info_vnc,
2544
    },
2545
    {
2546
        .name       = "name",
2547
        .args_type  = "",
2548
        .params     = "",
2549
        .help       = "show the current VM name",
2550
        .user_print = do_info_name_print,
2551
        .mhandler.info_new = do_info_name,
2552
    },
2553
    {
2554
        .name       = "uuid",
2555
        .args_type  = "",
2556
        .params     = "",
2557
        .help       = "show the current VM UUID",
2558
        .user_print = do_info_uuid_print,
2559
        .mhandler.info_new = do_info_uuid,
2560
    },
2561
#if defined(TARGET_PPC)
2562
    {
2563
        .name       = "cpustats",
2564
        .args_type  = "",
2565
        .params     = "",
2566
        .help       = "show CPU statistics",
2567
        .mhandler.info = do_info_cpu_stats,
2568
    },
2569
#endif
2570
#if defined(CONFIG_SLIRP)
2571
    {
2572
        .name       = "usernet",
2573
        .args_type  = "",
2574
        .params     = "",
2575
        .help       = "show user network stack connection states",
2576
        .mhandler.info = do_info_usernet,
2577
    },
2578
#endif
2579
    {
2580
        .name       = "migrate",
2581
        .args_type  = "",
2582
        .params     = "",
2583
        .help       = "show migration status",
2584
        .user_print = do_info_migrate_print,
2585
        .mhandler.info_new = do_info_migrate,
2586
    },
2587
    {
2588
        .name       = "balloon",
2589
        .args_type  = "",
2590
        .params     = "",
2591
        .help       = "show balloon information",
2592
        .user_print = monitor_print_balloon,
2593
        .mhandler.info_async = do_info_balloon,
2594
        .flags      = MONITOR_CMD_ASYNC,
2595
    },
2596
    {
2597
        .name       = "qtree",
2598
        .args_type  = "",
2599
        .params     = "",
2600
        .help       = "show device tree",
2601
        .mhandler.info = do_info_qtree,
2602
    },
2603
    {
2604
        .name       = "qdm",
2605
        .args_type  = "",
2606
        .params     = "",
2607
        .help       = "show qdev device model list",
2608
        .mhandler.info = do_info_qdm,
2609
    },
2610
    {
2611
        .name       = "roms",
2612
        .args_type  = "",
2613
        .params     = "",
2614
        .help       = "show roms",
2615
        .mhandler.info = do_info_roms,
2616
    },
2617
#if defined(CONFIG_SIMPLE_TRACE)
2618
    {
2619
        .name       = "trace",
2620
        .args_type  = "",
2621
        .params     = "",
2622
        .help       = "show current contents of trace buffer",
2623
        .mhandler.info = do_info_trace,
2624
    },
2625
    {
2626
        .name       = "trace-events",
2627
        .args_type  = "",
2628
        .params     = "",
2629
        .help       = "show available trace-events & their state",
2630
        .mhandler.info = do_info_trace_events,
2631
    },
2632
#endif
2633
    {
2634
        .name       = NULL,
2635
    },
2636
};
2637

    
2638
/*******************************************************************/
2639

    
2640
static const char *pch;
2641
static jmp_buf expr_env;
2642

    
2643
#define MD_TLONG 0
2644
#define MD_I32   1
2645

    
2646
typedef struct MonitorDef {
2647
    const char *name;
2648
    int offset;
2649
    target_long (*get_value)(const struct MonitorDef *md, int val);
2650
    int type;
2651
} MonitorDef;
2652

    
2653
#if defined(TARGET_I386)
2654
static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2655
{
2656
    CPUState *env = mon_get_cpu();
2657
    return env->eip + env->segs[R_CS].base;
2658
}
2659
#endif
2660

    
2661
#if defined(TARGET_PPC)
2662
static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2663
{
2664
    CPUState *env = mon_get_cpu();
2665
    unsigned int u;
2666
    int i;
2667

    
2668
    u = 0;
2669
    for (i = 0; i < 8; i++)
2670
        u |= env->crf[i] << (32 - (4 * i));
2671

    
2672
    return u;
2673
}
2674

    
2675
static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2676
{
2677
    CPUState *env = mon_get_cpu();
2678
    return env->msr;
2679
}
2680

    
2681
static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2682
{
2683
    CPUState *env = mon_get_cpu();
2684
    return env->xer;
2685
}
2686

    
2687
static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2688
{
2689
    CPUState *env = mon_get_cpu();
2690
    return cpu_ppc_load_decr(env);
2691
}
2692

    
2693
static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2694
{
2695
    CPUState *env = mon_get_cpu();
2696
    return cpu_ppc_load_tbu(env);
2697
}
2698

    
2699
static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2700
{
2701
    CPUState *env = mon_get_cpu();
2702
    return cpu_ppc_load_tbl(env);
2703
}
2704
#endif
2705

    
2706
#if defined(TARGET_SPARC)
2707
#ifndef TARGET_SPARC64
2708
static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2709
{
2710
    CPUState *env = mon_get_cpu();
2711

    
2712
    return cpu_get_psr(env);
2713
}
2714
#endif
2715

    
2716
static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2717
{
2718
    CPUState *env = mon_get_cpu();
2719
    return env->regwptr[val];
2720
}
2721
#endif
2722

    
2723
static const MonitorDef monitor_defs[] = {
2724
#ifdef TARGET_I386
2725

    
2726
#define SEG(name, seg) \
2727
    { name, offsetof(CPUState, segs[seg].selector), NULL, MD_I32 },\
2728
    { name ".base", offsetof(CPUState, segs[seg].base) },\
2729
    { name ".limit", offsetof(CPUState, segs[seg].limit), NULL, MD_I32 },
2730

    
2731
    { "eax", offsetof(CPUState, regs[0]) },
2732
    { "ecx", offsetof(CPUState, regs[1]) },
2733
    { "edx", offsetof(CPUState, regs[2]) },
2734
    { "ebx", offsetof(CPUState, regs[3]) },
2735
    { "esp|sp", offsetof(CPUState, regs[4]) },
2736
    { "ebp|fp", offsetof(CPUState, regs[5]) },
2737
    { "esi", offsetof(CPUState, regs[6]) },
2738
    { "edi", offsetof(CPUState, regs[7]) },
2739
#ifdef TARGET_X86_64
2740
    { "r8", offsetof(CPUState, regs[8]) },
2741
    { "r9", offsetof(CPUState, regs[9]) },
2742
    { "r10", offsetof(CPUState, regs[10]) },
2743
    { "r11", offsetof(CPUState, regs[11]) },
2744
    { "r12", offsetof(CPUState, regs[12]) },
2745
    { "r13", offsetof(CPUState, regs[13]) },
2746
    { "r14", offsetof(CPUState, regs[14]) },
2747
    { "r15", offsetof(CPUState, regs[15]) },
2748
#endif
2749
    { "eflags", offsetof(CPUState, eflags) },
2750
    { "eip", offsetof(CPUState, eip) },
2751
    SEG("cs", R_CS)
2752
    SEG("ds", R_DS)
2753
    SEG("es", R_ES)
2754
    SEG("ss", R_SS)
2755
    SEG("fs", R_FS)
2756
    SEG("gs", R_GS)
2757
    { "pc", 0, monitor_get_pc, },
2758
#elif defined(TARGET_PPC)
2759
    /* General purpose registers */
2760
    { "r0", offsetof(CPUState, gpr[0]) },
2761
    { "r1", offsetof(CPUState, gpr[1]) },
2762
    { "r2", offsetof(CPUState, gpr[2]) },
2763
    { "r3", offsetof(CPUState, gpr[3]) },
2764
    { "r4", offsetof(CPUState, gpr[4]) },
2765
    { "r5", offsetof(CPUState, gpr[5]) },
2766
    { "r6", offsetof(CPUState, gpr[6]) },
2767
    { "r7", offsetof(CPUState, gpr[7]) },
2768
    { "r8", offsetof(CPUState, gpr[8]) },
2769
    { "r9", offsetof(CPUState, gpr[9]) },
2770
    { "r10", offsetof(CPUState, gpr[10]) },
2771
    { "r11", offsetof(CPUState, gpr[11]) },
2772
    { "r12", offsetof(CPUState, gpr[12]) },
2773
    { "r13", offsetof(CPUState, gpr[13]) },
2774
    { "r14", offsetof(CPUState, gpr[14]) },
2775
    { "r15", offsetof(CPUState, gpr[15]) },
2776
    { "r16", offsetof(CPUState, gpr[16]) },
2777
    { "r17", offsetof(CPUState, gpr[17]) },
2778
    { "r18", offsetof(CPUState, gpr[18]) },
2779
    { "r19", offsetof(CPUState, gpr[19]) },
2780
    { "r20", offsetof(CPUState, gpr[20]) },
2781
    { "r21", offsetof(CPUState, gpr[21]) },
2782
    { "r22", offsetof(CPUState, gpr[22]) },
2783
    { "r23", offsetof(CPUState, gpr[23]) },
2784
    { "r24", offsetof(CPUState, gpr[24]) },
2785
    { "r25", offsetof(CPUState, gpr[25]) },
2786
    { "r26", offsetof(CPUState, gpr[26]) },
2787
    { "r27", offsetof(CPUState, gpr[27]) },
2788
    { "r28", offsetof(CPUState, gpr[28]) },
2789
    { "r29", offsetof(CPUState, gpr[29]) },
2790
    { "r30", offsetof(CPUState, gpr[30]) },
2791
    { "r31", offsetof(CPUState, gpr[31]) },
2792
    /* Floating point registers */
2793
    { "f0", offsetof(CPUState, fpr[0]) },
2794
    { "f1", offsetof(CPUState, fpr[1]) },
2795
    { "f2", offsetof(CPUState, fpr[2]) },
2796
    { "f3", offsetof(CPUState, fpr[3]) },
2797
    { "f4", offsetof(CPUState, fpr[4]) },
2798
    { "f5", offsetof(CPUState, fpr[5]) },
2799
    { "f6", offsetof(CPUState, fpr[6]) },
2800
    { "f7", offsetof(CPUState, fpr[7]) },
2801
    { "f8", offsetof(CPUState, fpr[8]) },
2802
    { "f9", offsetof(CPUState, fpr[9]) },
2803
    { "f10", offsetof(CPUState, fpr[10]) },
2804
    { "f11", offsetof(CPUState, fpr[11]) },
2805
    { "f12", offsetof(CPUState, fpr[12]) },
2806
    { "f13", offsetof(CPUState, fpr[13]) },
2807
    { "f14", offsetof(CPUState, fpr[14]) },
2808
    { "f15", offsetof(CPUState, fpr[15]) },
2809
    { "f16", offsetof(CPUState, fpr[16]) },
2810
    { "f17", offsetof(CPUState, fpr[17]) },
2811
    { "f18", offsetof(CPUState, fpr[18]) },
2812
    { "f19", offsetof(CPUState, fpr[19]) },
2813
    { "f20", offsetof(CPUState, fpr[20]) },
2814
    { "f21", offsetof(CPUState, fpr[21]) },
2815
    { "f22", offsetof(CPUState, fpr[22]) },
2816
    { "f23", offsetof(CPUState, fpr[23]) },
2817
    { "f24", offsetof(CPUState, fpr[24]) },
2818
    { "f25", offsetof(CPUState, fpr[25]) },
2819
    { "f26", offsetof(CPUState, fpr[26]) },
2820
    { "f27", offsetof(CPUState, fpr[27]) },
2821
    { "f28", offsetof(CPUState, fpr[28]) },
2822
    { "f29", offsetof(CPUState, fpr[29]) },
2823
    { "f30", offsetof(CPUState, fpr[30]) },
2824
    { "f31", offsetof(CPUState, fpr[31]) },
2825
    { "fpscr", offsetof(CPUState, fpscr) },
2826
    /* Next instruction pointer */
2827
    { "nip|pc", offsetof(CPUState, nip) },
2828
    { "lr", offsetof(CPUState, lr) },
2829
    { "ctr", offsetof(CPUState, ctr) },
2830
    { "decr", 0, &monitor_get_decr, },
2831
    { "ccr", 0, &monitor_get_ccr, },
2832
    /* Machine state register */
2833
    { "msr", 0, &monitor_get_msr, },
2834
    { "xer", 0, &monitor_get_xer, },
2835
    { "tbu", 0, &monitor_get_tbu, },
2836
    { "tbl", 0, &monitor_get_tbl, },
2837
#if defined(TARGET_PPC64)
2838
    /* Address space register */
2839
    { "asr", offsetof(CPUState, asr) },
2840
#endif
2841
    /* Segment registers */
2842
    { "sdr1", offsetof(CPUState, sdr1) },
2843
    { "sr0", offsetof(CPUState, sr[0]) },
2844
    { "sr1", offsetof(CPUState, sr[1]) },
2845
    { "sr2", offsetof(CPUState, sr[2]) },
2846
    { "sr3", offsetof(CPUState, sr[3]) },
2847
    { "sr4", offsetof(CPUState, sr[4]) },
2848
    { "sr5", offsetof(CPUState, sr[5]) },
2849
    { "sr6", offsetof(CPUState, sr[6]) },
2850
    { "sr7", offsetof(CPUState, sr[7]) },
2851
    { "sr8", offsetof(CPUState, sr[8]) },
2852
    { "sr9", offsetof(CPUState, sr[9]) },
2853
    { "sr10", offsetof(CPUState, sr[10]) },
2854
    { "sr11", offsetof(CPUState, sr[11]) },
2855
    { "sr12", offsetof(CPUState, sr[12]) },
2856
    { "sr13", offsetof(CPUState, sr[13]) },
2857
    { "sr14", offsetof(CPUState, sr[14]) },
2858
    { "sr15", offsetof(CPUState, sr[15]) },
2859
    /* Too lazy to put BATs and SPRs ... */
2860
#elif defined(TARGET_SPARC)
2861
    { "g0", offsetof(CPUState, gregs[0]) },
2862
    { "g1", offsetof(CPUState, gregs[1]) },
2863
    { "g2", offsetof(CPUState, gregs[2]) },
2864
    { "g3", offsetof(CPUState, gregs[3]) },
2865
    { "g4", offsetof(CPUState, gregs[4]) },
2866
    { "g5", offsetof(CPUState, gregs[5]) },
2867
    { "g6", offsetof(CPUState, gregs[6]) },
2868
    { "g7", offsetof(CPUState, gregs[7]) },
2869
    { "o0", 0, monitor_get_reg },
2870
    { "o1", 1, monitor_get_reg },
2871
    { "o2", 2, monitor_get_reg },
2872
    { "o3", 3, monitor_get_reg },
2873
    { "o4", 4, monitor_get_reg },
2874
    { "o5", 5, monitor_get_reg },
2875
    { "o6", 6, monitor_get_reg },
2876
    { "o7", 7, monitor_get_reg },
2877
    { "l0", 8, monitor_get_reg },
2878
    { "l1", 9, monitor_get_reg },
2879
    { "l2", 10, monitor_get_reg },
2880
    { "l3", 11, monitor_get_reg },
2881
    { "l4", 12, monitor_get_reg },
2882
    { "l5", 13, monitor_get_reg },
2883
    { "l6", 14, monitor_get_reg },
2884
    { "l7", 15, monitor_get_reg },
2885
    { "i0", 16, monitor_get_reg },
2886
    { "i1", 17, monitor_get_reg },
2887
    { "i2", 18, monitor_get_reg },
2888
    { "i3", 19, monitor_get_reg },
2889
    { "i4", 20, monitor_get_reg },
2890
    { "i5", 21, monitor_get_reg },
2891
    { "i6", 22, monitor_get_reg },
2892
    { "i7", 23, monitor_get_reg },
2893
    { "pc", offsetof(CPUState, pc) },
2894
    { "npc", offsetof(CPUState, npc) },
2895
    { "y", offsetof(CPUState, y) },
2896
#ifndef TARGET_SPARC64
2897
    { "psr", 0, &monitor_get_psr, },
2898
    { "wim", offsetof(CPUState, wim) },
2899
#endif
2900
    { "tbr", offsetof(CPUState, tbr) },
2901
    { "fsr", offsetof(CPUState, fsr) },
2902
    { "f0", offsetof(CPUState, fpr[0]) },
2903
    { "f1", offsetof(CPUState, fpr[1]) },
2904
    { "f2", offsetof(CPUState, fpr[2]) },
2905
    { "f3", offsetof(CPUState, fpr[3]) },
2906
    { "f4", offsetof(CPUState, fpr[4]) },
2907
    { "f5", offsetof(CPUState, fpr[5]) },
2908
    { "f6", offsetof(CPUState, fpr[6]) },
2909
    { "f7", offsetof(CPUState, fpr[7]) },
2910
    { "f8", offsetof(CPUState, fpr[8]) },
2911
    { "f9", offsetof(CPUState, fpr[9]) },
2912
    { "f10", offsetof(CPUState, fpr[10]) },
2913
    { "f11", offsetof(CPUState, fpr[11]) },
2914
    { "f12", offsetof(CPUState, fpr[12]) },
2915
    { "f13", offsetof(CPUState, fpr[13]) },
2916
    { "f14", offsetof(CPUState, fpr[14]) },
2917
    { "f15", offsetof(CPUState, fpr[15]) },
2918
    { "f16", offsetof(CPUState, fpr[16]) },
2919
    { "f17", offsetof(CPUState, fpr[17]) },
2920
    { "f18", offsetof(CPUState, fpr[18]) },
2921
    { "f19", offsetof(CPUState, fpr[19]) },
2922
    { "f20", offsetof(CPUState, fpr[20]) },
2923
    { "f21", offsetof(CPUState, fpr[21]) },
2924
    { "f22", offsetof(CPUState, fpr[22]) },
2925
    { "f23", offsetof(CPUState, fpr[23]) },
2926
    { "f24", offsetof(CPUState, fpr[24]) },
2927
    { "f25", offsetof(CPUState, fpr[25]) },
2928
    { "f26", offsetof(CPUState, fpr[26]) },
2929
    { "f27", offsetof(CPUState, fpr[27]) },
2930
    { "f28", offsetof(CPUState, fpr[28]) },
2931
    { "f29", offsetof(CPUState, fpr[29]) },
2932
    { "f30", offsetof(CPUState, fpr[30]) },
2933
    { "f31", offsetof(CPUState, fpr[31]) },
2934
#ifdef TARGET_SPARC64
2935
    { "f32", offsetof(CPUState, fpr[32]) },
2936
    { "f34", offsetof(CPUState, fpr[34]) },
2937
    { "f36", offsetof(CPUState, fpr[36]) },
2938
    { "f38", offsetof(CPUState, fpr[38]) },
2939
    { "f40", offsetof(CPUState, fpr[40]) },
2940
    { "f42", offsetof(CPUState, fpr[42]) },
2941
    { "f44", offsetof(CPUState, fpr[44]) },
2942
    { "f46", offsetof(CPUState, fpr[46]) },
2943
    { "f48", offsetof(CPUState, fpr[48]) },
2944
    { "f50", offsetof(CPUState, fpr[50]) },
2945
    { "f52", offsetof(CPUState, fpr[52]) },
2946
    { "f54", offsetof(CPUState, fpr[54]) },
2947
    { "f56", offsetof(CPUState, fpr[56]) },
2948
    { "f58", offsetof(CPUState, fpr[58]) },
2949
    { "f60", offsetof(CPUState, fpr[60]) },
2950
    { "f62", offsetof(CPUState, fpr[62]) },
2951
    { "asi", offsetof(CPUState, asi) },
2952
    { "pstate", offsetof(CPUState, pstate) },
2953
    { "cansave", offsetof(CPUState, cansave) },
2954
    { "canrestore", offsetof(CPUState, canrestore) },
2955
    { "otherwin", offsetof(CPUState, otherwin) },
2956
    { "wstate", offsetof(CPUState, wstate) },
2957
    { "cleanwin", offsetof(CPUState, cleanwin) },
2958
    { "fprs", offsetof(CPUState, fprs) },
2959
#endif
2960
#endif
2961
    { NULL },
2962
};
2963

    
2964
static void expr_error(Monitor *mon, const char *msg)
2965
{
2966
    monitor_printf(mon, "%s\n", msg);
2967
    longjmp(expr_env, 1);
2968
}
2969

    
2970
/* return 0 if OK, -1 if not found */
2971
static int get_monitor_def(target_long *pval, const char *name)
2972
{
2973
    const MonitorDef *md;
2974
    void *ptr;
2975

    
2976
    for(md = monitor_defs; md->name != NULL; md++) {
2977
        if (compare_cmd(name, md->name)) {
2978
            if (md->get_value) {
2979
                *pval = md->get_value(md, md->offset);
2980
            } else {
2981
                CPUState *env = mon_get_cpu();
2982
                ptr = (uint8_t *)env + md->offset;
2983
                switch(md->type) {
2984
                case MD_I32:
2985
                    *pval = *(int32_t *)ptr;
2986
                    break;
2987
                case MD_TLONG:
2988
                    *pval = *(target_long *)ptr;
2989
                    break;
2990
                default:
2991
                    *pval = 0;
2992
                    break;
2993
                }
2994
            }
2995
            return 0;
2996
        }
2997
    }
2998
    return -1;
2999
}
3000

    
3001
static void next(void)
3002
{
3003
    if (*pch != '\0') {
3004
        pch++;
3005
        while (qemu_isspace(*pch))
3006
            pch++;
3007
    }
3008
}
3009

    
3010
static int64_t expr_sum(Monitor *mon);
3011

    
3012
static int64_t expr_unary(Monitor *mon)
3013
{
3014
    int64_t n;
3015
    char *p;
3016
    int ret;
3017

    
3018
    switch(*pch) {
3019
    case '+':
3020
        next();
3021
        n = expr_unary(mon);
3022
        break;
3023
    case '-':
3024
        next();
3025
        n = -expr_unary(mon);
3026
        break;
3027
    case '~':
3028
        next();
3029
        n = ~expr_unary(mon);
3030
        break;
3031
    case '(':
3032
        next();
3033
        n = expr_sum(mon);
3034
        if (*pch != ')') {
3035
            expr_error(mon, "')' expected");
3036
        }
3037
        next();
3038
        break;
3039
    case '\'':
3040
        pch++;
3041
        if (*pch == '\0')
3042
            expr_error(mon, "character constant expected");
3043
        n = *pch;
3044
        pch++;
3045
        if (*pch != '\'')
3046
            expr_error(mon, "missing terminating \' character");
3047
        next();
3048
        break;
3049
    case '$':
3050
        {
3051
            char buf[128], *q;
3052
            target_long reg=0;
3053

    
3054
            pch++;
3055
            q = buf;
3056
            while ((*pch >= 'a' && *pch <= 'z') ||
3057
                   (*pch >= 'A' && *pch <= 'Z') ||
3058
                   (*pch >= '0' && *pch <= '9') ||
3059
                   *pch == '_' || *pch == '.') {
3060
                if ((q - buf) < sizeof(buf) - 1)
3061
                    *q++ = *pch;
3062
                pch++;
3063
            }
3064
            while (qemu_isspace(*pch))
3065
                pch++;
3066
            *q = 0;
3067
            ret = get_monitor_def(&reg, buf);
3068
            if (ret < 0)
3069
                expr_error(mon, "unknown register");
3070
            n = reg;
3071
        }
3072
        break;
3073
    case '\0':
3074
        expr_error(mon, "unexpected end of expression");
3075
        n = 0;
3076
        break;
3077
    default:
3078
#if TARGET_PHYS_ADDR_BITS > 32
3079
        n = strtoull(pch, &p, 0);
3080
#else
3081
        n = strtoul(pch, &p, 0);
3082
#endif
3083
        if (pch == p) {
3084
            expr_error(mon, "invalid char in expression");
3085
        }
3086
        pch = p;
3087
        while (qemu_isspace(*pch))
3088
            pch++;
3089
        break;
3090
    }
3091
    return n;
3092
}
3093

    
3094

    
3095
static int64_t expr_prod(Monitor *mon)
3096
{
3097
    int64_t val, val2;
3098
    int op;
3099

    
3100
    val = expr_unary(mon);
3101
    for(;;) {
3102
        op = *pch;
3103
        if (op != '*' && op != '/' && op != '%')
3104
            break;
3105
        next();
3106
        val2 = expr_unary(mon);
3107
        switch(op) {
3108
        default:
3109
        case '*':
3110
            val *= val2;
3111
            break;
3112
        case '/':
3113
        case '%':
3114
            if (val2 == 0)
3115
                expr_error(mon, "division by zero");
3116
            if (op == '/')
3117
                val /= val2;
3118
            else
3119
                val %= val2;
3120
            break;
3121
        }
3122
    }
3123
    return val;
3124
}
3125

    
3126
static int64_t expr_logic(Monitor *mon)
3127
{
3128
    int64_t val, val2;
3129
    int op;
3130

    
3131
    val = expr_prod(mon);
3132
    for(;;) {
3133
        op = *pch;
3134
        if (op != '&' && op != '|' && op != '^')
3135
            break;
3136
        next();
3137
        val2 = expr_prod(mon);
3138
        switch(op) {
3139
        default:
3140
        case '&':
3141
            val &= val2;
3142
            break;
3143
        case '|':
3144
            val |= val2;
3145
            break;
3146
        case '^':
3147
            val ^= val2;
3148
            break;
3149
        }
3150
    }
3151
    return val;
3152
}
3153

    
3154
static int64_t expr_sum(Monitor *mon)
3155
{
3156
    int64_t val, val2;
3157
    int op;
3158

    
3159
    val = expr_logic(mon);
3160
    for(;;) {
3161
        op = *pch;
3162
        if (op != '+' && op != '-')
3163
            break;
3164
        next();
3165
        val2 = expr_logic(mon);
3166
        if (op == '+')
3167
            val += val2;
3168
        else
3169
            val -= val2;
3170
    }
3171
    return val;
3172
}
3173

    
3174
static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3175
{
3176
    pch = *pp;
3177
    if (setjmp(expr_env)) {
3178
        *pp = pch;
3179
        return -1;
3180
    }
3181
    while (qemu_isspace(*pch))
3182
        pch++;
3183
    *pval = expr_sum(mon);
3184
    *pp = pch;
3185
    return 0;
3186
}
3187

    
3188
static int get_double(Monitor *mon, double *pval, const char **pp)
3189
{
3190
    const char *p = *pp;
3191
    char *tailp;
3192
    double d;
3193

    
3194
    d = strtod(p, &tailp);
3195
    if (tailp == p) {
3196
        monitor_printf(mon, "Number expected\n");
3197
        return -1;
3198
    }
3199
    if (d != d || d - d != 0) {
3200
        /* NaN or infinity */
3201
        monitor_printf(mon, "Bad number\n");
3202
        return -1;
3203
    }
3204
    *pval = d;
3205
    *pp = tailp;
3206
    return 0;
3207
}
3208

    
3209
static int get_str(char *buf, int buf_size, const char **pp)
3210
{
3211
    const char *p;
3212
    char *q;
3213
    int c;
3214

    
3215
    q = buf;
3216
    p = *pp;
3217
    while (qemu_isspace(*p))
3218
        p++;
3219
    if (*p == '\0') {
3220
    fail:
3221
        *q = '\0';
3222
        *pp = p;
3223
        return -1;
3224
    }
3225
    if (*p == '\"') {
3226
        p++;
3227
        while (*p != '\0' && *p != '\"') {
3228
            if (*p == '\\') {
3229
                p++;
3230
                c = *p++;
3231
                switch(c) {
3232
                case 'n':
3233
                    c = '\n';
3234
                    break;
3235
                case 'r':
3236
                    c = '\r';
3237
                    break;
3238
                case '\\':
3239
                case '\'':
3240
                case '\"':
3241
                    break;
3242
                default:
3243
                    qemu_printf("unsupported escape code: '\\%c'\n", c);
3244
                    goto fail;
3245
                }
3246
                if ((q - buf) < buf_size - 1) {
3247
                    *q++ = c;
3248
                }
3249
            } else {
3250
                if ((q - buf) < buf_size - 1) {
3251
                    *q++ = *p;
3252
                }
3253
                p++;
3254
            }
3255
        }
3256
        if (*p != '\"') {
3257
            qemu_printf("unterminated string\n");
3258
            goto fail;
3259
        }
3260
        p++;
3261
    } else {
3262
        while (*p != '\0' && !qemu_isspace(*p)) {
3263
            if ((q - buf) < buf_size - 1) {
3264
                *q++ = *p;
3265
            }
3266
            p++;
3267
        }
3268
    }
3269
    *q = '\0';
3270
    *pp = p;
3271
    return 0;
3272
}
3273

    
3274
/*
3275
 * Store the command-name in cmdname, and return a pointer to
3276
 * the remaining of the command string.
3277
 */
3278
static const char *get_command_name(const char *cmdline,
3279
                                    char *cmdname, size_t nlen)
3280
{
3281
    size_t len;
3282
    const char *p, *pstart;
3283

    
3284
    p = cmdline;
3285
    while (qemu_isspace(*p))
3286
        p++;
3287
    if (*p == '\0')
3288
        return NULL;
3289
    pstart = p;
3290
    while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3291
        p++;
3292
    len = p - pstart;
3293
    if (len > nlen - 1)
3294
        len = nlen - 1;
3295
    memcpy(cmdname, pstart, len);
3296
    cmdname[len] = '\0';
3297
    return p;
3298
}
3299

    
3300
/**
3301
 * Read key of 'type' into 'key' and return the current
3302
 * 'type' pointer.
3303
 */
3304
static char *key_get_info(const char *type, char **key)
3305
{
3306
    size_t len;
3307
    char *p, *str;
3308

    
3309
    if (*type == ',')
3310
        type++;
3311

    
3312
    p = strchr(type, ':');
3313
    if (!p) {
3314
        *key = NULL;
3315
        return NULL;
3316
    }
3317
    len = p - type;
3318

    
3319
    str = qemu_malloc(len + 1);
3320
    memcpy(str, type, len);
3321
    str[len] = '\0';
3322

    
3323
    *key = str;
3324
    return ++p;
3325
}
3326

    
3327
static int default_fmt_format = 'x';
3328
static int default_fmt_size = 4;
3329

    
3330
#define MAX_ARGS 16
3331

    
3332
static int is_valid_option(const char *c, const char *typestr)
3333
{
3334
    char option[3];
3335
  
3336
    option[0] = '-';
3337
    option[1] = *c;
3338
    option[2] = '\0';
3339
  
3340
    typestr = strstr(typestr, option);
3341
    return (typestr != NULL);
3342
}
3343

    
3344
static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
3345
                                              const char *cmdname)
3346
{
3347
    const mon_cmd_t *cmd;
3348

    
3349
    for (cmd = disp_table; cmd->name != NULL; cmd++) {
3350
        if (compare_cmd(cmdname, cmd->name)) {
3351
            return cmd;
3352
        }
3353
    }
3354

    
3355
    return NULL;
3356
}
3357

    
3358
static const mon_cmd_t *monitor_find_command(const char *cmdname)
3359
{
3360
    return search_dispatch_table(mon_cmds, cmdname);
3361
}
3362

    
3363
static const mon_cmd_t *qmp_find_query_cmd(const char *info_item)
3364
{
3365
    return search_dispatch_table(info_cmds, info_item);
3366
}
3367

    
3368
static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
3369
{
3370
    return search_dispatch_table(mon_cmds, cmdname);
3371
}
3372

    
3373
static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3374
                                              const char *cmdline,
3375
                                              QDict *qdict)
3376
{
3377
    const char *p, *typestr;
3378
    int c;
3379
    const mon_cmd_t *cmd;
3380
    char cmdname[256];
3381
    char buf[1024];
3382
    char *key;
3383

    
3384
#ifdef DEBUG
3385
    monitor_printf(mon, "command='%s'\n", cmdline);
3386
#endif
3387

    
3388
    /* extract the command name */
3389
    p = get_command_name(cmdline, cmdname, sizeof(cmdname));
3390
    if (!p)
3391
        return NULL;
3392

    
3393
    cmd = monitor_find_command(cmdname);
3394
    if (!cmd) {
3395
        monitor_printf(mon, "unknown command: '%s'\n", cmdname);
3396
        return NULL;
3397
    }
3398

    
3399
    /* parse the parameters */
3400
    typestr = cmd->args_type;
3401
    for(;;) {
3402
        typestr = key_get_info(typestr, &key);
3403
        if (!typestr)
3404
            break;
3405
        c = *typestr;
3406
        typestr++;
3407
        switch(c) {
3408
        case 'F':
3409
        case 'B':
3410
        case 's':
3411
            {
3412
                int ret;
3413

    
3414
                while (qemu_isspace(*p))
3415
                    p++;
3416
                if (*typestr == '?') {
3417
                    typestr++;
3418
                    if (*p == '\0') {
3419
                        /* no optional string: NULL argument */
3420
                        break;
3421
                    }
3422
                }
3423
                ret = get_str(buf, sizeof(buf), &p);
3424
                if (ret < 0) {
3425
                    switch(c) {
3426
                    case 'F':
3427
                        monitor_printf(mon, "%s: filename expected\n",
3428
                                       cmdname);
3429
                        break;
3430
                    case 'B':
3431
                        monitor_printf(mon, "%s: block device name expected\n",
3432
                                       cmdname);
3433
                        break;
3434
                    default:
3435
                        monitor_printf(mon, "%s: string expected\n", cmdname);
3436
                        break;
3437
                    }
3438
                    goto fail;
3439
                }
3440
                qdict_put(qdict, key, qstring_from_str(buf));
3441
            }
3442
            break;
3443
        case 'O':
3444
            {
3445
                QemuOptsList *opts_list;
3446
                QemuOpts *opts;
3447

    
3448
                opts_list = qemu_find_opts(key);
3449
                if (!opts_list || opts_list->desc->name) {
3450
                    goto bad_type;
3451
                }
3452
                while (qemu_isspace(*p)) {
3453
                    p++;
3454
                }
3455
                if (!*p)
3456
                    break;
3457
                if (get_str(buf, sizeof(buf), &p) < 0) {
3458
                    goto fail;
3459
                }
3460
                opts = qemu_opts_parse(opts_list, buf, 1);
3461
                if (!opts) {
3462
                    goto fail;
3463
                }
3464
                qemu_opts_to_qdict(opts, qdict);
3465
                qemu_opts_del(opts);
3466
            }
3467
            break;
3468
        case '/':
3469
            {
3470
                int count, format, size;
3471

    
3472
                while (qemu_isspace(*p))
3473
                    p++;
3474
                if (*p == '/') {
3475
                    /* format found */
3476
                    p++;
3477
                    count = 1;
3478
                    if (qemu_isdigit(*p)) {
3479
                        count = 0;
3480
                        while (qemu_isdigit(*p)) {
3481
                            count = count * 10 + (*p - '0');
3482
                            p++;
3483
                        }
3484
                    }
3485
                    size = -1;
3486
                    format = -1;
3487
                    for(;;) {
3488
                        switch(*p) {
3489
                        case 'o':
3490
                        case 'd':
3491
                        case 'u':
3492
                        case 'x':
3493
                        case 'i':
3494
                        case 'c':
3495
                            format = *p++;
3496
                            break;
3497
                        case 'b':
3498
                            size = 1;
3499
                            p++;
3500
                            break;
3501
                        case 'h':
3502
                            size = 2;
3503
                            p++;
3504
                            break;
3505
                        case 'w':
3506
                            size = 4;
3507
                            p++;
3508
                            break;
3509
                        case 'g':
3510
                        case 'L':
3511
                            size = 8;
3512
                            p++;
3513
                            break;
3514
                        default:
3515
                            goto next;
3516
                        }
3517
                    }
3518
                next:
3519
                    if (*p != '\0' && !qemu_isspace(*p)) {
3520
                        monitor_printf(mon, "invalid char in format: '%c'\n",
3521
                                       *p);
3522
                        goto fail;
3523
                    }
3524
                    if (format < 0)
3525
                        format = default_fmt_format;
3526
                    if (format != 'i') {
3527
                        /* for 'i', not specifying a size gives -1 as size */
3528
                        if (size < 0)
3529
                            size = default_fmt_size;
3530
                        default_fmt_size = size;
3531
                    }
3532
                    default_fmt_format = format;
3533
                } else {
3534
                    count = 1;
3535
                    format = default_fmt_format;
3536
                    if (format != 'i') {
3537
                        size = default_fmt_size;
3538
                    } else {
3539
                        size = -1;
3540
                    }
3541
                }
3542
                qdict_put(qdict, "count", qint_from_int(count));
3543
                qdict_put(qdict, "format", qint_from_int(format));
3544
                qdict_put(qdict, "size", qint_from_int(size));
3545
            }
3546
            break;
3547
        case 'i':
3548
        case 'l':
3549
        case 'M':
3550
            {
3551
                int64_t val;
3552

    
3553
                while (qemu_isspace(*p))
3554
                    p++;
3555
                if (*typestr == '?' || *typestr == '.') {
3556
                    if (*typestr == '?') {
3557
                        if (*p == '\0') {
3558
                            typestr++;
3559
                            break;
3560
                        }
3561
                    } else {
3562
                        if (*p == '.') {
3563
                            p++;
3564
                            while (qemu_isspace(*p))
3565
                                p++;
3566
                        } else {
3567
                            typestr++;
3568
                            break;
3569
                        }
3570
                    }
3571
                    typestr++;
3572
                }
3573
                if (get_expr(mon, &val, &p))
3574
                    goto fail;
3575
                /* Check if 'i' is greater than 32-bit */
3576
                if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3577
                    monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3578
                    monitor_printf(mon, "integer is for 32-bit values\n");
3579
                    goto fail;
3580
                } else if (c == 'M') {
3581
                    val <<= 20;
3582
                }
3583
                qdict_put(qdict, key, qint_from_int(val));
3584
            }
3585
            break;
3586
        case 'f':
3587
        case 'T':
3588
            {
3589
                double val;
3590

    
3591
                while (qemu_isspace(*p))
3592
                    p++;
3593
                if (*typestr == '?') {
3594
                    typestr++;
3595
                    if (*p == '\0') {
3596
                        break;
3597
                    }
3598
                }
3599
                if (get_double(mon, &val, &p) < 0) {
3600
                    goto fail;
3601
                }
3602
                if (c == 'f' && *p) {
3603
                    switch (*p) {
3604
                    case 'K': case 'k':
3605
                        val *= 1 << 10; p++; break;
3606
                    case 'M': case 'm':
3607
                        val *= 1 << 20; p++; break;
3608
                    case 'G': case 'g':
3609
                        val *= 1 << 30; p++; break;
3610
                    }
3611
                }
3612
                if (c == 'T' && p[0] && p[1] == 's') {
3613
                    switch (*p) {
3614
                    case 'm':
3615
                        val /= 1e3; p += 2; break;
3616
                    case 'u':
3617
                        val /= 1e6; p += 2; break;
3618
                    case 'n':
3619
                        val /= 1e9; p += 2; break;
3620
                    }
3621
                }
3622
                if (*p && !qemu_isspace(*p)) {
3623
                    monitor_printf(mon, "Unknown unit suffix\n");
3624
                    goto fail;
3625
                }
3626
                qdict_put(qdict, key, qfloat_from_double(val));
3627
            }
3628
            break;
3629
        case 'b':
3630
            {
3631
                const char *beg;
3632
                int val;
3633

    
3634
                while (qemu_isspace(*p)) {
3635
                    p++;
3636
                }
3637
                beg = p;
3638
                while (qemu_isgraph(*p)) {
3639
                    p++;
3640
                }
3641
                if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
3642
                    val = 1;
3643
                } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
3644
                    val = 0;
3645
                } else {
3646
                    monitor_printf(mon, "Expected 'on' or 'off'\n");
3647
                    goto fail;
3648
                }
3649
                qdict_put(qdict, key, qbool_from_int(val));
3650
            }
3651
            break;
3652
        case '-':
3653
            {
3654
                const char *tmp = p;
3655
                int skip_key = 0;
3656
                /* option */
3657

    
3658
                c = *typestr++;
3659
                if (c == '\0')
3660
                    goto bad_type;
3661
                while (qemu_isspace(*p))
3662
                    p++;
3663
                if (*p == '-') {
3664
                    p++;
3665
                    if(c != *p) {
3666
                        if(!is_valid_option(p, typestr)) {
3667
                  
3668
                            monitor_printf(mon, "%s: unsupported option -%c\n",
3669
                                           cmdname, *p);
3670
                            goto fail;
3671
                        } else {
3672
                            skip_key = 1;
3673
                        }
3674
                    }
3675
                    if(skip_key) {
3676
                        p = tmp;
3677
                    } else {
3678
                        /* has option */
3679
                        p++;
3680
                        qdict_put(qdict, key, qbool_from_int(1));
3681
                    }
3682
                }
3683
            }
3684
            break;
3685
        default:
3686
        bad_type:
3687
            monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
3688
            goto fail;
3689
        }
3690
        qemu_free(key);
3691
        key = NULL;
3692
    }
3693
    /* check that all arguments were parsed */
3694
    while (qemu_isspace(*p))
3695
        p++;
3696
    if (*p != '\0') {
3697
        monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3698
                       cmdname);
3699
        goto fail;
3700
    }
3701

    
3702
    return cmd;
3703

    
3704
fail:
3705
    qemu_free(key);
3706
    return NULL;
3707
}
3708

    
3709
void monitor_set_error(Monitor *mon, QError *qerror)
3710
{
3711
    /* report only the first error */
3712
    if (!mon->error) {
3713
        mon->error = qerror;
3714
    } else {
3715
        MON_DEBUG("Additional error report at %s:%d\n",
3716
                  qerror->file, qerror->linenr);
3717
        QDECREF(qerror);
3718
    }
3719
}
3720

    
3721
static void handler_audit(Monitor *mon, const mon_cmd_t *cmd, int ret)
3722
{
3723
    if (monitor_ctrl_mode(mon)) {
3724
        if (ret && !monitor_has_error(mon)) {
3725
            /*
3726
             * If it returns failure, it must have passed on error.
3727
             *
3728
             * Action: Report an internal error to the client if in QMP.
3729
             */
3730
            qerror_report(QERR_UNDEFINED_ERROR);
3731
            MON_DEBUG("command '%s' returned failure but did not pass an error\n",
3732
                      cmd->name);
3733
        }
3734

    
3735
#ifdef CONFIG_DEBUG_MONITOR
3736
        if (!ret && monitor_has_error(mon)) {
3737
            /*
3738
             * If it returns success, it must not have passed an error.
3739
             *
3740
             * Action: Report the passed error to the client.
3741
             */
3742
            MON_DEBUG("command '%s' returned success but passed an error\n",
3743
                      cmd->name);
3744
        }
3745

    
3746
        if (mon_print_count_get(mon) > 0 && strcmp(cmd->name, "info") != 0) {
3747
            /*
3748
             * Handlers should not call Monitor print functions.
3749
             *
3750
             * Action: Ignore them in QMP.
3751
             *
3752
             * (XXX: we don't check any 'info' or 'query' command here
3753
             * because the user print function _is_ called by do_info(), hence
3754
             * we will trigger this check. This problem will go away when we
3755
             * make 'query' commands real and kill do_info())
3756
             */
3757
            MON_DEBUG("command '%s' called print functions %d time(s)\n",
3758
                      cmd->name, mon_print_count_get(mon));
3759
        }
3760
#endif
3761
    } else {
3762
        assert(!monitor_has_error(mon));
3763
        QDECREF(mon->error);
3764
        mon->error = NULL;
3765
    }
3766
}
3767

    
3768
static void monitor_call_handler(Monitor *mon, const mon_cmd_t *cmd,
3769
                                 const QDict *params)
3770
{
3771
    int ret;
3772
    QObject *data = NULL;
3773

    
3774
    mon_print_count_init(mon);
3775

    
3776
    ret = cmd->mhandler.cmd_new(mon, params, &data);
3777
    handler_audit(mon, cmd, ret);
3778

    
3779
    if (monitor_ctrl_mode(mon)) {
3780
        /* Monitor Protocol */
3781
        monitor_protocol_emitter(mon, data);
3782
    } else {
3783
        /* User Protocol */
3784
         if (data)
3785
            cmd->user_print(mon, data);
3786
    }
3787

    
3788
    qobject_decref(data);
3789
}
3790

    
3791
static void handle_user_command(Monitor *mon, const char *cmdline)
3792
{
3793
    QDict *qdict;
3794
    const mon_cmd_t *cmd;
3795

    
3796
    qdict = qdict_new();
3797

    
3798
    cmd = monitor_parse_command(mon, cmdline, qdict);
3799
    if (!cmd)
3800
        goto out;
3801

    
3802
    if (monitor_handler_is_async(cmd)) {
3803
        user_async_cmd_handler(mon, cmd, qdict);
3804
    } else if (monitor_handler_ported(cmd)) {
3805
        monitor_call_handler(mon, cmd, qdict);
3806
    } else {
3807
        cmd->mhandler.cmd(mon, qdict);
3808
    }
3809

    
3810
out:
3811
    QDECREF(qdict);
3812
}
3813

    
3814
static void cmd_completion(const char *name, const char *list)
3815
{
3816
    const char *p, *pstart;
3817
    char cmd[128];
3818
    int len;
3819

    
3820
    p = list;
3821
    for(;;) {
3822
        pstart = p;
3823
        p = strchr(p, '|');
3824
        if (!p)
3825
            p = pstart + strlen(pstart);
3826
        len = p - pstart;
3827
        if (len > sizeof(cmd) - 2)
3828
            len = sizeof(cmd) - 2;
3829
        memcpy(cmd, pstart, len);
3830
        cmd[len] = '\0';
3831
        if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3832
            readline_add_completion(cur_mon->rs, cmd);
3833
        }
3834
        if (*p == '\0')
3835
            break;
3836
        p++;
3837
    }
3838
}
3839

    
3840
static void file_completion(const char *input)
3841
{
3842
    DIR *ffs;
3843
    struct dirent *d;
3844
    char path[1024];
3845
    char file[1024], file_prefix[1024];
3846
    int input_path_len;
3847
    const char *p;
3848

    
3849
    p = strrchr(input, '/');
3850
    if (!p) {
3851
        input_path_len = 0;
3852
        pstrcpy(file_prefix, sizeof(file_prefix), input);
3853
        pstrcpy(path, sizeof(path), ".");
3854
    } else {
3855
        input_path_len = p - input + 1;
3856
        memcpy(path, input, input_path_len);
3857
        if (input_path_len > sizeof(path) - 1)
3858
            input_path_len = sizeof(path) - 1;
3859
        path[input_path_len] = '\0';
3860
        pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3861
    }
3862
#ifdef DEBUG_COMPLETION
3863
    monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
3864
                   input, path, file_prefix);
3865
#endif
3866
    ffs = opendir(path);
3867
    if (!ffs)
3868
        return;
3869
    for(;;) {
3870
        struct stat sb;
3871
        d = readdir(ffs);
3872
        if (!d)
3873
            break;
3874
        if (strstart(d->d_name, file_prefix, NULL)) {
3875
            memcpy(file, input, input_path_len);
3876
            if (input_path_len < sizeof(file))
3877
                pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3878
                        d->d_name);
3879
            /* stat the file to find out if it's a directory.
3880
             * In that case add a slash to speed up typing long paths
3881
             */
3882
            stat(file, &sb);
3883
            if(S_ISDIR(sb.st_mode))
3884
                pstrcat(file, sizeof(file), "/");
3885
            readline_add_completion(cur_mon->rs, file);
3886
        }
3887
    }
3888
    closedir(ffs);
3889
}
3890

    
3891
static void block_completion_it(void *opaque, BlockDriverState *bs)
3892
{
3893
    const char *name = bdrv_get_device_name(bs);
3894
    const char *input = opaque;
3895

    
3896
    if (input[0] == '\0' ||
3897
        !strncmp(name, (char *)input, strlen(input))) {
3898
        readline_add_completion(cur_mon->rs, name);
3899
    }
3900
}
3901

    
3902
/* NOTE: this parser is an approximate form of the real command parser */
3903
static void parse_cmdline(const char *cmdline,
3904
                         int *pnb_args, char **args)
3905
{
3906
    const char *p;
3907
    int nb_args, ret;
3908
    char buf[1024];
3909

    
3910
    p = cmdline;
3911
    nb_args = 0;
3912
    for(;;) {
3913
        while (qemu_isspace(*p))
3914
            p++;
3915
        if (*p == '\0')
3916
            break;
3917
        if (nb_args >= MAX_ARGS)
3918
            break;
3919
        ret = get_str(buf, sizeof(buf), &p);
3920
        args[nb_args] = qemu_strdup(buf);
3921
        nb_args++;
3922
        if (ret < 0)
3923
            break;
3924
    }
3925
    *pnb_args = nb_args;
3926
}
3927

    
3928
static const char *next_arg_type(const char *typestr)
3929
{
3930
    const char *p = strchr(typestr, ':');
3931
    return (p != NULL ? ++p : typestr);
3932
}
3933

    
3934
static void monitor_find_completion(const char *cmdline)
3935
{
3936
    const char *cmdname;
3937
    char *args[MAX_ARGS];
3938
    int nb_args, i, len;
3939
    const char *ptype, *str;
3940
    const mon_cmd_t *cmd;
3941
    const KeyDef *key;
3942

    
3943
    parse_cmdline(cmdline, &nb_args, args);
3944
#ifdef DEBUG_COMPLETION
3945
    for(i = 0; i < nb_args; i++) {
3946
        monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
3947
    }
3948
#endif
3949

    
3950
    /* if the line ends with a space, it means we want to complete the
3951
       next arg */
3952
    len = strlen(cmdline);
3953
    if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3954
        if (nb_args >= MAX_ARGS) {
3955
            goto cleanup;
3956
        }
3957
        args[nb_args++] = qemu_strdup("");
3958
    }
3959
    if (nb_args <= 1) {
3960
        /* command completion */
3961
        if (nb_args == 0)
3962
            cmdname = "";
3963
        else
3964
            cmdname = args[0];
3965
        readline_set_completion_index(cur_mon->rs, strlen(cmdname));
3966
        for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
3967
            cmd_completion(cmdname, cmd->name);
3968
        }
3969
    } else {
3970
        /* find the command */
3971
        for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
3972
            if (compare_cmd(args[0], cmd->name)) {
3973
                break;
3974
            }
3975
        }
3976
        if (!cmd->name) {
3977
            goto cleanup;
3978
        }
3979

    
3980
        ptype = next_arg_type(cmd->args_type);
3981
        for(i = 0; i < nb_args - 2; i++) {
3982
            if (*ptype != '\0') {
3983
                ptype = next_arg_type(ptype);
3984
                while (*ptype == '?')
3985
                    ptype = next_arg_type(ptype);
3986
            }
3987
        }
3988
        str = args[nb_args - 1];
3989
        if (*ptype == '-' && ptype[1] != '\0') {
3990
            ptype = next_arg_type(ptype);
3991
        }
3992
        switch(*ptype) {
3993
        case 'F':
3994
            /* file completion */
3995
            readline_set_completion_index(cur_mon->rs, strlen(str));
3996
            file_completion(str);
3997
            break;
3998
        case 'B':
3999
            /* block device name completion */
4000
            readline_set_completion_index(cur_mon->rs, strlen(str));
4001
            bdrv_iterate(block_completion_it, (void *)str);
4002
            break;
4003
        case 's':
4004
            /* XXX: more generic ? */
4005
            if (!strcmp(cmd->name, "info")) {
4006
                readline_set_completion_index(cur_mon->rs, strlen(str));
4007
                for(cmd = info_cmds; cmd->name != NULL; cmd++) {
4008
                    cmd_completion(str, cmd->name);
4009
                }
4010
            } else if (!strcmp(cmd->name, "sendkey")) {
4011
                char *sep = strrchr(str, '-');
4012
                if (sep)
4013
                    str = sep + 1;
4014
                readline_set_completion_index(cur_mon->rs, strlen(str));
4015
                for(key = key_defs; key->name != NULL; key++) {
4016
                    cmd_completion(str, key->name);
4017
                }
4018
            } else if (!strcmp(cmd->name, "help|?")) {
4019
                readline_set_completion_index(cur_mon->rs, strlen(str));
4020
                for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4021
                    cmd_completion(str, cmd->name);
4022
                }
4023
            }
4024
            break;
4025
        default:
4026
            break;
4027
        }
4028
    }
4029

    
4030
cleanup:
4031
    for (i = 0; i < nb_args; i++) {
4032
        qemu_free(args[i]);
4033
    }
4034
}
4035

    
4036
static int monitor_can_read(void *opaque)
4037
{
4038
    Monitor *mon = opaque;
4039

    
4040
    return (mon->suspend_cnt == 0) ? 1 : 0;
4041
}
4042

    
4043
static int invalid_qmp_mode(const Monitor *mon, const char *cmd_name)
4044
{
4045
    int is_cap = compare_cmd(cmd_name, "qmp_capabilities");
4046
    return (qmp_cmd_mode(mon) ? is_cap : !is_cap);
4047
}
4048

    
4049
/*
4050
 * Argument validation rules:
4051
 *
4052
 * 1. The argument must exist in cmd_args qdict
4053
 * 2. The argument type must be the expected one
4054
 *
4055
 * Special case: If the argument doesn't exist in cmd_args and
4056
 *               the QMP_ACCEPT_UNKNOWNS flag is set, then the
4057
 *               checking is skipped for it.
4058
 */
4059
static int check_client_args_type(const QDict *client_args,
4060
                                  const QDict *cmd_args, int flags)
4061
{
4062
    const QDictEntry *ent;
4063

    
4064
    for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
4065
        QObject *obj;
4066
        QString *arg_type;
4067
        const QObject *client_arg = qdict_entry_value(ent);
4068
        const char *client_arg_name = qdict_entry_key(ent);
4069

    
4070
        obj = qdict_get(cmd_args, client_arg_name);
4071
        if (!obj) {
4072
            if (flags & QMP_ACCEPT_UNKNOWNS) {
4073
                /* handler accepts unknowns */
4074
                continue;
4075
            }
4076
            /* client arg doesn't exist */
4077
            qerror_report(QERR_INVALID_PARAMETER, client_arg_name);
4078
            return -1;
4079
        }
4080

    
4081
        arg_type = qobject_to_qstring(obj);
4082
        assert(arg_type != NULL);
4083

    
4084
        /* check if argument's type is correct */
4085
        switch (qstring_get_str(arg_type)[0]) {
4086
        case 'F':
4087
        case 'B':
4088
        case 's':
4089
            if (qobject_type(client_arg) != QTYPE_QSTRING) {
4090
                qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4091
                              "string");
4092
                return -1;
4093
            }
4094
        break;
4095
        case 'i':
4096
        case 'l':
4097
        case 'M':
4098
            if (qobject_type(client_arg) != QTYPE_QINT) {
4099
                qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4100
                              "int");
4101
                return -1; 
4102
            }
4103
            break;
4104
        case 'f':
4105
        case 'T':
4106
            if (qobject_type(client_arg) != QTYPE_QINT &&
4107
                qobject_type(client_arg) != QTYPE_QFLOAT) {
4108
                qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4109
                              "number");
4110
               return -1; 
4111
            }
4112
            break;
4113
        case 'b':
4114
        case '-':
4115
            if (qobject_type(client_arg) != QTYPE_QBOOL) {
4116
                qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4117
                              "bool");
4118
               return -1; 
4119
            }
4120
            break;
4121
        case 'O':
4122
            assert(flags & QMP_ACCEPT_UNKNOWNS);
4123
            break;
4124
        case '/':
4125
        case '.':
4126
            /*
4127
             * These types are not supported by QMP and thus are not
4128
             * handled here. Fall through.
4129
             */
4130
        default:
4131
            abort();
4132
        }
4133
    }
4134

    
4135
    return 0;
4136
}
4137

    
4138
/*
4139
 * - Check if the client has passed all mandatory args
4140
 * - Set special flags for argument validation
4141
 */
4142
static int check_mandatory_args(const QDict *cmd_args,
4143
                                const QDict *client_args, int *flags)
4144
{
4145
    const QDictEntry *ent;
4146

    
4147
    for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
4148
        const char *cmd_arg_name = qdict_entry_key(ent);
4149
        QString *type = qobject_to_qstring(qdict_entry_value(ent));
4150
        assert(type != NULL);
4151

    
4152
        if (qstring_get_str(type)[0] == 'O') {
4153
            assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
4154
            *flags |= QMP_ACCEPT_UNKNOWNS;
4155
        } else if (qstring_get_str(type)[0] != '-' &&
4156
                   qstring_get_str(type)[1] != '?' &&
4157
                   !qdict_haskey(client_args, cmd_arg_name)) {
4158
            qerror_report(QERR_MISSING_PARAMETER, cmd_arg_name);
4159
            return -1;
4160
        }
4161
    }
4162

    
4163
    return 0;
4164
}
4165

    
4166
static QDict *qdict_from_args_type(const char *args_type)
4167
{
4168
    int i;
4169
    QDict *qdict;
4170
    QString *key, *type, *cur_qs;
4171

    
4172
    assert(args_type != NULL);
4173

    
4174
    qdict = qdict_new();
4175

    
4176
    if (args_type == NULL || args_type[0] == '\0') {
4177
        /* no args, empty qdict */
4178
        goto out;
4179
    }
4180

    
4181
    key = qstring_new();
4182
    type = qstring_new();
4183

    
4184
    cur_qs = key;
4185

    
4186
    for (i = 0;; i++) {
4187
        switch (args_type[i]) {
4188
            case ',':
4189
            case '\0':
4190
                qdict_put(qdict, qstring_get_str(key), type);
4191
                QDECREF(key);
4192
                if (args_type[i] == '\0') {
4193
                    goto out;
4194
                }
4195
                type = qstring_new(); /* qdict has ref */
4196
                cur_qs = key = qstring_new();
4197
                break;
4198
            case ':':
4199
                cur_qs = type;
4200
                break;
4201
            default:
4202
                qstring_append_chr(cur_qs, args_type[i]);
4203
                break;
4204
        }
4205
    }
4206

    
4207
out:
4208
    return qdict;
4209
}
4210

    
4211
/*
4212
 * Client argument checking rules:
4213
 *
4214
 * 1. Client must provide all mandatory arguments
4215
 * 2. Each argument provided by the client must be expected
4216
 * 3. Each argument provided by the client must have the type expected
4217
 *    by the command
4218
 */
4219
static int qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args)
4220
{
4221
    int flags, err;
4222
    QDict *cmd_args;
4223

    
4224
    cmd_args = qdict_from_args_type(cmd->args_type);
4225

    
4226
    flags = 0;
4227
    err = check_mandatory_args(cmd_args, client_args, &flags);
4228
    if (err) {
4229
        goto out;
4230
    }
4231

    
4232
    err = check_client_args_type(client_args, cmd_args, flags);
4233

    
4234
out:
4235
    QDECREF(cmd_args);
4236
    return err;
4237
}
4238

    
4239
/*
4240
 * Input object checking rules
4241
 *
4242
 * 1. Input object must be a dict
4243
 * 2. The "execute" key must exist
4244
 * 3. The "execute" key must be a string
4245
 * 4. If the "arguments" key exists, it must be a dict
4246
 * 5. If the "id" key exists, it can be anything (ie. json-value)
4247
 * 6. Any argument not listed above is considered invalid
4248
 */
4249
static QDict *qmp_check_input_obj(QObject *input_obj)
4250
{
4251
    const QDictEntry *ent;
4252
    int has_exec_key = 0;
4253
    QDict *input_dict;
4254

    
4255
    if (qobject_type(input_obj) != QTYPE_QDICT) {
4256
        qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "object");
4257
        return NULL;
4258
    }
4259

    
4260
    input_dict = qobject_to_qdict(input_obj);
4261

    
4262
    for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
4263
        const char *arg_name = qdict_entry_key(ent);
4264
        const QObject *arg_obj = qdict_entry_value(ent);
4265

    
4266
        if (!strcmp(arg_name, "execute")) {
4267
            if (qobject_type(arg_obj) != QTYPE_QSTRING) {
4268
                qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "execute",
4269
                              "string");
4270
                return NULL;
4271
            }
4272
            has_exec_key = 1;
4273
        } else if (!strcmp(arg_name, "arguments")) {
4274
            if (qobject_type(arg_obj) != QTYPE_QDICT) {
4275
                qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "arguments",
4276
                              "object");
4277
                return NULL;
4278
            }
4279
        } else if (!strcmp(arg_name, "id")) {
4280
            /* FIXME: check duplicated IDs for async commands */
4281
        } else {
4282
            qerror_report(QERR_QMP_EXTRA_MEMBER, arg_name);
4283
            return NULL;
4284
        }
4285
    }
4286

    
4287
    if (!has_exec_key) {
4288
        qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4289
        return NULL;
4290
    }
4291

    
4292
    return input_dict;
4293
}
4294

    
4295
static void qmp_call_query_cmd(Monitor *mon, const mon_cmd_t *cmd)
4296
{
4297
    QObject *ret_data = NULL;
4298

    
4299
    if (monitor_handler_is_async(cmd)) {
4300
        qmp_async_info_handler(mon, cmd);
4301
        if (monitor_has_error(mon)) {
4302
            monitor_protocol_emitter(mon, NULL);
4303
        }
4304
    } else {
4305
        cmd->mhandler.info_new(mon, &ret_data);
4306
        if (ret_data) {
4307
            monitor_protocol_emitter(mon, ret_data);
4308
            qobject_decref(ret_data);
4309
        }
4310
    }
4311
}
4312

    
4313
static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
4314
{
4315
    int err;
4316
    QObject *obj;
4317
    QDict *input, *args;
4318
    const mon_cmd_t *cmd;
4319
    Monitor *mon = cur_mon;
4320
    const char *cmd_name, *query_cmd;
4321

    
4322
    query_cmd = NULL;
4323
    args = input = NULL;
4324

    
4325
    obj = json_parser_parse(tokens, NULL);
4326
    if (!obj) {
4327
        // FIXME: should be triggered in json_parser_parse()
4328
        qerror_report(QERR_JSON_PARSING);
4329
        goto err_out;
4330
    }
4331

    
4332
    input = qmp_check_input_obj(obj);
4333
    if (!input) {
4334
        qobject_decref(obj);
4335
        goto err_out;
4336
    }
4337

    
4338
    mon->mc->id = qdict_get(input, "id");
4339
    qobject_incref(mon->mc->id);
4340

    
4341
    cmd_name = qdict_get_str(input, "execute");
4342
    if (invalid_qmp_mode(mon, cmd_name)) {
4343
        qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
4344
        goto err_out;
4345
    }
4346

    
4347
    /*
4348
     * XXX: We need this special case until QMP has its own dispatch table
4349
     */
4350
    if (compare_cmd(cmd_name, "info")) {
4351
        qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
4352
        goto err_out;
4353
    } else if (strstart(cmd_name, "query-", &query_cmd)) {
4354
        cmd = qmp_find_query_cmd(query_cmd);
4355
    } else {
4356
        cmd = qmp_find_cmd(cmd_name);
4357
    }
4358

    
4359
    if (!cmd || !monitor_handler_ported(cmd) || monitor_cmd_user_only(cmd)) {
4360
        qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
4361
        goto err_out;
4362
    }
4363

    
4364
    obj = qdict_get(input, "arguments");
4365
    if (!obj) {
4366
        args = qdict_new();
4367
    } else {
4368
        args = qobject_to_qdict(obj);
4369
        QINCREF(args);
4370
    }
4371

    
4372
    err = qmp_check_client_args(cmd, args);
4373
    if (err < 0) {
4374
        goto err_out;
4375
    }
4376

    
4377
    if (query_cmd) {
4378
        qmp_call_query_cmd(mon, cmd);
4379
    } else if (monitor_handler_is_async(cmd)) {
4380
        err = qmp_async_cmd_handler(mon, cmd, args);
4381
        if (err) {
4382
            /* emit the error response */
4383
            goto err_out;
4384
        }
4385
    } else {
4386
        monitor_call_handler(mon, cmd, args);
4387
    }
4388

    
4389
    goto out;
4390

    
4391
err_out:
4392
    monitor_protocol_emitter(mon, NULL);
4393
out:
4394
    QDECREF(input);
4395
    QDECREF(args);
4396
}
4397

    
4398
/**
4399
 * monitor_control_read(): Read and handle QMP input
4400
 */
4401
static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
4402
{
4403
    Monitor *old_mon = cur_mon;
4404

    
4405
    cur_mon = opaque;
4406

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

    
4409
    cur_mon = old_mon;
4410
}
4411

    
4412
static void monitor_read(void *opaque, const uint8_t *buf, int size)
4413
{
4414
    Monitor *old_mon = cur_mon;
4415
    int i;
4416

    
4417
    cur_mon = opaque;
4418

    
4419
    if (cur_mon->rs) {
4420
        for (i = 0; i < size; i++)
4421
            readline_handle_byte(cur_mon->rs, buf[i]);
4422
    } else {
4423
        if (size == 0 || buf[size - 1] != 0)
4424
            monitor_printf(cur_mon, "corrupted command\n");
4425
        else
4426
            handle_user_command(cur_mon, (char *)buf);
4427
    }
4428

    
4429
    cur_mon = old_mon;
4430
}
4431

    
4432
static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
4433
{
4434
    monitor_suspend(mon);
4435
    handle_user_command(mon, cmdline);
4436
    monitor_resume(mon);
4437
}
4438

    
4439
int monitor_suspend(Monitor *mon)
4440
{
4441
    if (!mon->rs)
4442
        return -ENOTTY;
4443
    mon->suspend_cnt++;
4444
    return 0;
4445
}
4446

    
4447
void monitor_resume(Monitor *mon)
4448
{
4449
    if (!mon->rs)
4450
        return;
4451
    if (--mon->suspend_cnt == 0)
4452
        readline_show_prompt(mon->rs);
4453
}
4454

    
4455
static QObject *get_qmp_greeting(void)
4456
{
4457
    QObject *ver;
4458

    
4459
    do_info_version(NULL, &ver);
4460
    return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
4461
}
4462

    
4463
/**
4464
 * monitor_control_event(): Print QMP gretting
4465
 */
4466
static void monitor_control_event(void *opaque, int event)
4467
{
4468
    QObject *data;
4469
    Monitor *mon = opaque;
4470

    
4471
    switch (event) {
4472
    case CHR_EVENT_OPENED:
4473
        mon->mc->command_mode = 0;
4474
        json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4475
        data = get_qmp_greeting();
4476
        monitor_json_emitter(mon, data);
4477
        qobject_decref(data);
4478
        break;
4479
    case CHR_EVENT_CLOSED:
4480
        json_message_parser_destroy(&mon->mc->parser);
4481
        break;
4482
    }
4483
}
4484

    
4485
static void monitor_event(void *opaque, int event)
4486
{
4487
    Monitor *mon = opaque;
4488

    
4489
    switch (event) {
4490
    case CHR_EVENT_MUX_IN:
4491
        mon->mux_out = 0;
4492
        if (mon->reset_seen) {
4493
            readline_restart(mon->rs);
4494
            monitor_resume(mon);
4495
            monitor_flush(mon);
4496
        } else {
4497
            mon->suspend_cnt = 0;
4498
        }
4499
        break;
4500

    
4501
    case CHR_EVENT_MUX_OUT:
4502
        if (mon->reset_seen) {
4503
            if (mon->suspend_cnt == 0) {
4504
                monitor_printf(mon, "\n");
4505
            }
4506
            monitor_flush(mon);
4507
            monitor_suspend(mon);
4508
        } else {
4509
            mon->suspend_cnt++;
4510
        }
4511
        mon->mux_out = 1;
4512
        break;
4513

    
4514
    case CHR_EVENT_OPENED:
4515
        monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4516
                       "information\n", QEMU_VERSION);
4517
        if (!mon->mux_out) {
4518
            readline_show_prompt(mon->rs);
4519
        }
4520
        mon->reset_seen = 1;
4521
        break;
4522
    }
4523
}
4524

    
4525

    
4526
/*
4527
 * Local variables:
4528
 *  c-indent-level: 4
4529
 *  c-basic-offset: 4
4530
 *  tab-width: 8
4531
 * End:
4532
 */
4533

    
4534
void monitor_init(CharDriverState *chr, int flags)
4535
{
4536
    static int is_first_init = 1;
4537
    Monitor *mon;
4538

    
4539
    if (is_first_init) {
4540
        key_timer = qemu_new_timer(vm_clock, release_keys, NULL);
4541
        is_first_init = 0;
4542
    }
4543

    
4544
    mon = qemu_mallocz(sizeof(*mon));
4545

    
4546
    mon->chr = chr;
4547
    mon->flags = flags;
4548
    if (flags & MONITOR_USE_READLINE) {
4549
        mon->rs = readline_init(mon, monitor_find_completion);
4550
        monitor_read_command(mon, 0);
4551
    }
4552

    
4553
    if (monitor_ctrl_mode(mon)) {
4554
        mon->mc = qemu_mallocz(sizeof(MonitorControl));
4555
        /* Control mode requires special handlers */
4556
        qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
4557
                              monitor_control_event, mon);
4558
    } else {
4559
        qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4560
                              monitor_event, mon);
4561
    }
4562

    
4563
    QLIST_INSERT_HEAD(&mon_list, mon, entry);
4564
    if (!default_mon || (flags & MONITOR_IS_DEFAULT))
4565
        default_mon = mon;
4566
}
4567

    
4568
static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
4569
{
4570
    BlockDriverState *bs = opaque;
4571
    int ret = 0;
4572

    
4573
    if (bdrv_set_key(bs, password) != 0) {
4574
        monitor_printf(mon, "invalid password\n");
4575
        ret = -EPERM;
4576
    }
4577
    if (mon->password_completion_cb)
4578
        mon->password_completion_cb(mon->password_opaque, ret);
4579

    
4580
    monitor_read_command(mon, 1);
4581
}
4582

    
4583
int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4584
                                BlockDriverCompletionFunc *completion_cb,
4585
                                void *opaque)
4586
{
4587
    int err;
4588

    
4589
    if (!bdrv_key_required(bs)) {
4590
        if (completion_cb)
4591
            completion_cb(opaque, 0);
4592
        return 0;
4593
    }
4594

    
4595
    if (monitor_ctrl_mode(mon)) {
4596
        qerror_report(QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs));
4597
        return -1;
4598
    }
4599

    
4600
    monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4601
                   bdrv_get_encrypted_filename(bs));
4602

    
4603
    mon->password_completion_cb = completion_cb;
4604
    mon->password_opaque = opaque;
4605

    
4606
    err = monitor_read_password(mon, bdrv_password_cb, bs);
4607

    
4608
    if (err && completion_cb)
4609
        completion_cb(opaque, err);
4610

    
4611
    return err;
4612
}