Statistics
| Branch: | Revision:

root / monitor.c @ 89bd820a

History | View | Annotate | Download (148.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 "ui/qemu-spice.h"
38
#include "sysemu.h"
39
#include "monitor.h"
40
#include "readline.h"
41
#include "console.h"
42
#include "blockdev.h"
43
#include "audio/audio.h"
44
#include "disas.h"
45
#include "balloon.h"
46
#include "qemu-timer.h"
47
#include "migration.h"
48
#include "kvm.h"
49
#include "acl.h"
50
#include "qint.h"
51
#include "qfloat.h"
52
#include "qlist.h"
53
#include "qbool.h"
54
#include "qstring.h"
55
#include "qjson.h"
56
#include "json-streamer.h"
57
#include "json-parser.h"
58
#include "osdep.h"
59
#include "cpu.h"
60
#include "trace.h"
61
#include "trace/control.h"
62
#ifdef CONFIG_TRACE_SIMPLE
63
#include "trace/simple.h"
64
#endif
65
#include "ui/qemu-spice.h"
66
#include "memory.h"
67

    
68
//#define DEBUG
69
//#define DEBUG_COMPLETION
70

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

    
104
typedef struct MonitorCompletionData MonitorCompletionData;
105
struct MonitorCompletionData {
106
    Monitor *mon;
107
    void (*user_print)(Monitor *mon, const QObject *data);
108
};
109

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

    
128
/* file descriptors passed via SCM_RIGHTS */
129
typedef struct mon_fd_t mon_fd_t;
130
struct mon_fd_t {
131
    char *name;
132
    int fd;
133
    QLIST_ENTRY(mon_fd_t) next;
134
};
135

    
136
typedef struct MonitorControl {
137
    QObject *id;
138
    JSONMessageParser parser;
139
    int command_mode;
140
} MonitorControl;
141

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

    
163
#ifdef CONFIG_DEBUG_MONITOR
164
#define MON_DEBUG(fmt, ...) do {    \
165
    fprintf(stderr, "Monitor: ");       \
166
    fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
167

    
168
static inline void mon_print_count_inc(Monitor *mon)
169
{
170
    mon->print_calls_nr++;
171
}
172

    
173
static inline void mon_print_count_init(Monitor *mon)
174
{
175
    mon->print_calls_nr = 0;
176
}
177

    
178
static inline int mon_print_count_get(const Monitor *mon)
179
{
180
    return mon->print_calls_nr;
181
}
182

    
183
#else /* !CONFIG_DEBUG_MONITOR */
184
#define MON_DEBUG(fmt, ...) do { } while (0)
185
static inline void mon_print_count_inc(Monitor *mon) { }
186
static inline void mon_print_count_init(Monitor *mon) { }
187
static inline int mon_print_count_get(const Monitor *mon) { return 0; }
188
#endif /* CONFIG_DEBUG_MONITOR */
189

    
190
/* QMP checker flags */
191
#define QMP_ACCEPT_UNKNOWNS 1
192

    
193
static QLIST_HEAD(mon_list, Monitor) mon_list;
194

    
195
static const mon_cmd_t mon_cmds[];
196
static const mon_cmd_t info_cmds[];
197

    
198
static const mon_cmd_t qmp_cmds[];
199
static const mon_cmd_t qmp_query_cmds[];
200

    
201
Monitor *cur_mon;
202
Monitor *default_mon;
203

    
204
static void monitor_command_cb(Monitor *mon, const char *cmdline,
205
                               void *opaque);
206

    
207
static inline int qmp_cmd_mode(const Monitor *mon)
208
{
209
    return (mon->mc ? mon->mc->command_mode : 0);
210
}
211

    
212
/* Return true if in control mode, false otherwise */
213
static inline int monitor_ctrl_mode(const Monitor *mon)
214
{
215
    return (mon->flags & MONITOR_USE_CONTROL);
216
}
217

    
218
/* Return non-zero iff we have a current monitor, and it is in QMP mode.  */
219
int monitor_cur_is_qmp(void)
220
{
221
    return cur_mon && monitor_ctrl_mode(cur_mon);
222
}
223

    
224
static void monitor_read_command(Monitor *mon, int show_prompt)
225
{
226
    if (!mon->rs)
227
        return;
228

    
229
    readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
230
    if (show_prompt)
231
        readline_show_prompt(mon->rs);
232
}
233

    
234
static int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
235
                                 void *opaque)
236
{
237
    if (monitor_ctrl_mode(mon)) {
238
        qerror_report(QERR_MISSING_PARAMETER, "password");
239
        return -EINVAL;
240
    } else if (mon->rs) {
241
        readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
242
        /* prompt is printed on return from the command handler */
243
        return 0;
244
    } else {
245
        monitor_printf(mon, "terminal does not support password prompting\n");
246
        return -ENOTTY;
247
    }
248
}
249

    
250
void monitor_flush(Monitor *mon)
251
{
252
    if (mon && mon->outbuf_index != 0 && !mon->mux_out) {
253
        qemu_chr_fe_write(mon->chr, mon->outbuf, mon->outbuf_index);
254
        mon->outbuf_index = 0;
255
    }
256
}
257

    
258
/* flush at every end of line or if the buffer is full */
259
static void monitor_puts(Monitor *mon, const char *str)
260
{
261
    char c;
262

    
263
    for(;;) {
264
        c = *str++;
265
        if (c == '\0')
266
            break;
267
        if (c == '\n')
268
            mon->outbuf[mon->outbuf_index++] = '\r';
269
        mon->outbuf[mon->outbuf_index++] = c;
270
        if (mon->outbuf_index >= (sizeof(mon->outbuf) - 1)
271
            || c == '\n')
272
            monitor_flush(mon);
273
    }
274
}
275

    
276
void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
277
{
278
    char buf[4096];
279

    
280
    if (!mon)
281
        return;
282

    
283
    mon_print_count_inc(mon);
284

    
285
    if (monitor_ctrl_mode(mon)) {
286
        return;
287
    }
288

    
289
    vsnprintf(buf, sizeof(buf), fmt, ap);
290
    monitor_puts(mon, buf);
291
}
292

    
293
void monitor_printf(Monitor *mon, const char *fmt, ...)
294
{
295
    va_list ap;
296
    va_start(ap, fmt);
297
    monitor_vprintf(mon, fmt, ap);
298
    va_end(ap);
299
}
300

    
301
void monitor_print_filename(Monitor *mon, const char *filename)
302
{
303
    int i;
304

    
305
    for (i = 0; filename[i]; i++) {
306
        switch (filename[i]) {
307
        case ' ':
308
        case '"':
309
        case '\\':
310
            monitor_printf(mon, "\\%c", filename[i]);
311
            break;
312
        case '\t':
313
            monitor_printf(mon, "\\t");
314
            break;
315
        case '\r':
316
            monitor_printf(mon, "\\r");
317
            break;
318
        case '\n':
319
            monitor_printf(mon, "\\n");
320
            break;
321
        default:
322
            monitor_printf(mon, "%c", filename[i]);
323
            break;
324
        }
325
    }
326
}
327

    
328
static int GCC_FMT_ATTR(2, 3) monitor_fprintf(FILE *stream,
329
                                              const char *fmt, ...)
330
{
331
    va_list ap;
332
    va_start(ap, fmt);
333
    monitor_vprintf((Monitor *)stream, fmt, ap);
334
    va_end(ap);
335
    return 0;
336
}
337

    
338
static void monitor_user_noop(Monitor *mon, const QObject *data) { }
339

    
340
static inline int handler_is_qobject(const mon_cmd_t *cmd)
341
{
342
    return cmd->user_print != NULL;
343
}
344

    
345
static inline bool handler_is_async(const mon_cmd_t *cmd)
346
{
347
    return cmd->flags & MONITOR_CMD_ASYNC;
348
}
349

    
350
static inline int monitor_has_error(const Monitor *mon)
351
{
352
    return mon->error != NULL;
353
}
354

    
355
static void monitor_json_emitter(Monitor *mon, const QObject *data)
356
{
357
    QString *json;
358

    
359
    json = mon->flags & MONITOR_USE_PRETTY ? qobject_to_json_pretty(data) :
360
                                             qobject_to_json(data);
361
    assert(json != NULL);
362

    
363
    qstring_append_chr(json, '\n');
364
    monitor_puts(mon, qstring_get_str(json));
365

    
366
    QDECREF(json);
367
}
368

    
369
static void monitor_protocol_emitter(Monitor *mon, QObject *data)
370
{
371
    QDict *qmp;
372

    
373
    trace_monitor_protocol_emitter(mon);
374

    
375
    qmp = qdict_new();
376

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

    
395
    if (mon->mc->id) {
396
        qdict_put_obj(qmp, "id", mon->mc->id);
397
        mon->mc->id = NULL;
398
    }
399

    
400
    monitor_json_emitter(mon, QOBJECT(qmp));
401
    QDECREF(qmp);
402
}
403

    
404
static void timestamp_put(QDict *qdict)
405
{
406
    int err;
407
    QObject *obj;
408
    qemu_timeval tv;
409

    
410
    err = qemu_gettimeofday(&tv);
411
    if (err < 0)
412
        return;
413

    
414
    obj = qobject_from_jsonf("{ 'seconds': %" PRId64 ", "
415
                                "'microseconds': %" PRId64 " }",
416
                                (int64_t) tv.tv_sec, (int64_t) tv.tv_usec);
417
    qdict_put_obj(qdict, "timestamp", obj);
418
}
419

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

    
431
    assert(event < QEVENT_MAX);
432

    
433
    switch (event) {
434
        case QEVENT_SHUTDOWN:
435
            event_name = "SHUTDOWN";
436
            break;
437
        case QEVENT_RESET:
438
            event_name = "RESET";
439
            break;
440
        case QEVENT_POWERDOWN:
441
            event_name = "POWERDOWN";
442
            break;
443
        case QEVENT_STOP:
444
            event_name = "STOP";
445
            break;
446
        case QEVENT_RESUME:
447
            event_name = "RESUME";
448
            break;
449
        case QEVENT_VNC_CONNECTED:
450
            event_name = "VNC_CONNECTED";
451
            break;
452
        case QEVENT_VNC_INITIALIZED:
453
            event_name = "VNC_INITIALIZED";
454
            break;
455
        case QEVENT_VNC_DISCONNECTED:
456
            event_name = "VNC_DISCONNECTED";
457
            break;
458
        case QEVENT_BLOCK_IO_ERROR:
459
            event_name = "BLOCK_IO_ERROR";
460
            break;
461
        case QEVENT_RTC_CHANGE:
462
            event_name = "RTC_CHANGE";
463
            break;
464
        case QEVENT_WATCHDOG:
465
            event_name = "WATCHDOG";
466
            break;
467
        case QEVENT_SPICE_CONNECTED:
468
            event_name = "SPICE_CONNECTED";
469
            break;
470
        case QEVENT_SPICE_INITIALIZED:
471
            event_name = "SPICE_INITIALIZED";
472
            break;
473
        case QEVENT_SPICE_DISCONNECTED:
474
            event_name = "SPICE_DISCONNECTED";
475
            break;
476
        default:
477
            abort();
478
            break;
479
    }
480

    
481
    qmp = qdict_new();
482
    timestamp_put(qmp);
483
    qdict_put(qmp, "event", qstring_from_str(event_name));
484
    if (data) {
485
        qobject_incref(data);
486
        qdict_put_obj(qmp, "data", data);
487
    }
488

    
489
    QLIST_FOREACH(mon, &mon_list, entry) {
490
        if (monitor_ctrl_mode(mon) && qmp_cmd_mode(mon)) {
491
            monitor_json_emitter(mon, QOBJECT(qmp));
492
        }
493
    }
494
    QDECREF(qmp);
495
}
496

    
497
static int do_qmp_capabilities(Monitor *mon, const QDict *params,
498
                               QObject **ret_data)
499
{
500
    /* Will setup QMP capabilities in the future */
501
    if (monitor_ctrl_mode(mon)) {
502
        mon->mc->command_mode = 1;
503
    }
504

    
505
    return 0;
506
}
507

    
508
static int mon_set_cpu(int cpu_index);
509
static void handle_user_command(Monitor *mon, const char *cmdline);
510

    
511
static int do_hmp_passthrough(Monitor *mon, const QDict *params,
512
                              QObject **ret_data)
513
{
514
    int ret = 0;
515
    Monitor *old_mon, hmp;
516
    CharDriverState mchar;
517

    
518
    memset(&hmp, 0, sizeof(hmp));
519
    qemu_chr_init_mem(&mchar);
520
    hmp.chr = &mchar;
521

    
522
    old_mon = cur_mon;
523
    cur_mon = &hmp;
524

    
525
    if (qdict_haskey(params, "cpu-index")) {
526
        ret = mon_set_cpu(qdict_get_int(params, "cpu-index"));
527
        if (ret < 0) {
528
            cur_mon = old_mon;
529
            qerror_report(QERR_INVALID_PARAMETER_VALUE, "cpu-index", "a CPU number");
530
            goto out;
531
        }
532
    }
533

    
534
    handle_user_command(&hmp, qdict_get_str(params, "command-line"));
535
    cur_mon = old_mon;
536

    
537
    if (qemu_chr_mem_osize(hmp.chr) > 0) {
538
        *ret_data = QOBJECT(qemu_chr_mem_to_qs(hmp.chr));
539
    }
540

    
541
out:
542
    qemu_chr_close_mem(hmp.chr);
543
    return ret;
544
}
545

    
546
static int compare_cmd(const char *name, const char *list)
547
{
548
    const char *p, *pstart;
549
    int len;
550
    len = strlen(name);
551
    p = list;
552
    for(;;) {
553
        pstart = p;
554
        p = strchr(p, '|');
555
        if (!p)
556
            p = pstart + strlen(pstart);
557
        if ((p - pstart) == len && !memcmp(pstart, name, len))
558
            return 1;
559
        if (*p == '\0')
560
            break;
561
        p++;
562
    }
563
    return 0;
564
}
565

    
566
static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
567
                          const char *prefix, const char *name)
568
{
569
    const mon_cmd_t *cmd;
570

    
571
    for(cmd = cmds; cmd->name != NULL; cmd++) {
572
        if (!name || !strcmp(name, cmd->name))
573
            monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
574
                           cmd->params, cmd->help);
575
    }
576
}
577

    
578
static void help_cmd(Monitor *mon, const char *name)
579
{
580
    if (name && !strcmp(name, "info")) {
581
        help_cmd_dump(mon, info_cmds, "info ", NULL);
582
    } else {
583
        help_cmd_dump(mon, mon_cmds, "", name);
584
        if (name && !strcmp(name, "log")) {
585
            const CPULogItem *item;
586
            monitor_printf(mon, "Log items (comma separated):\n");
587
            monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
588
            for(item = cpu_log_items; item->mask != 0; item++) {
589
                monitor_printf(mon, "%-10s %s\n", item->name, item->help);
590
            }
591
        }
592
    }
593
}
594

    
595
static void do_help_cmd(Monitor *mon, const QDict *qdict)
596
{
597
    help_cmd(mon, qdict_get_try_str(qdict, "name"));
598
}
599

    
600
static void do_trace_event_set_state(Monitor *mon, const QDict *qdict)
601
{
602
    const char *tp_name = qdict_get_str(qdict, "name");
603
    bool new_state = qdict_get_bool(qdict, "option");
604
    int ret = trace_event_set_state(tp_name, new_state);
605

    
606
    if (!ret) {
607
        monitor_printf(mon, "unknown event name \"%s\"\n", tp_name);
608
    }
609
}
610

    
611
#ifdef CONFIG_TRACE_SIMPLE
612
static void do_trace_file(Monitor *mon, const QDict *qdict)
613
{
614
    const char *op = qdict_get_try_str(qdict, "op");
615
    const char *arg = qdict_get_try_str(qdict, "arg");
616

    
617
    if (!op) {
618
        st_print_trace_file_status((FILE *)mon, &monitor_fprintf);
619
    } else if (!strcmp(op, "on")) {
620
        st_set_trace_file_enabled(true);
621
    } else if (!strcmp(op, "off")) {
622
        st_set_trace_file_enabled(false);
623
    } else if (!strcmp(op, "flush")) {
624
        st_flush_trace_buffer();
625
    } else if (!strcmp(op, "set")) {
626
        if (arg) {
627
            st_set_trace_file(arg);
628
        }
629
    } else {
630
        monitor_printf(mon, "unexpected argument \"%s\"\n", op);
631
        help_cmd(mon, "trace-file");
632
    }
633
}
634
#endif
635

    
636
static void user_monitor_complete(void *opaque, QObject *ret_data)
637
{
638
    MonitorCompletionData *data = (MonitorCompletionData *)opaque; 
639

    
640
    if (ret_data) {
641
        data->user_print(data->mon, ret_data);
642
    }
643
    monitor_resume(data->mon);
644
    g_free(data);
645
}
646

    
647
static void qmp_monitor_complete(void *opaque, QObject *ret_data)
648
{
649
    monitor_protocol_emitter(opaque, ret_data);
650
}
651

    
652
static int qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
653
                                 const QDict *params)
654
{
655
    return cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);
656
}
657

    
658
static void qmp_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
659
{
660
    cmd->mhandler.info_async(mon, qmp_monitor_complete, mon);
661
}
662

    
663
static void user_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
664
                                   const QDict *params)
665
{
666
    int ret;
667

    
668
    MonitorCompletionData *cb_data = g_malloc(sizeof(*cb_data));
669
    cb_data->mon = mon;
670
    cb_data->user_print = cmd->user_print;
671
    monitor_suspend(mon);
672
    ret = cmd->mhandler.cmd_async(mon, params,
673
                                  user_monitor_complete, cb_data);
674
    if (ret < 0) {
675
        monitor_resume(mon);
676
        g_free(cb_data);
677
    }
678
}
679

    
680
static void user_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
681
{
682
    int ret;
683

    
684
    MonitorCompletionData *cb_data = g_malloc(sizeof(*cb_data));
685
    cb_data->mon = mon;
686
    cb_data->user_print = cmd->user_print;
687
    monitor_suspend(mon);
688
    ret = cmd->mhandler.info_async(mon, user_monitor_complete, cb_data);
689
    if (ret < 0) {
690
        monitor_resume(mon);
691
        g_free(cb_data);
692
    }
693
}
694

    
695
static void do_info(Monitor *mon, const QDict *qdict)
696
{
697
    const mon_cmd_t *cmd;
698
    const char *item = qdict_get_try_str(qdict, "item");
699

    
700
    if (!item) {
701
        goto help;
702
    }
703

    
704
    for (cmd = info_cmds; cmd->name != NULL; cmd++) {
705
        if (compare_cmd(item, cmd->name))
706
            break;
707
    }
708

    
709
    if (cmd->name == NULL) {
710
        goto help;
711
    }
712

    
713
    if (handler_is_async(cmd)) {
714
        user_async_info_handler(mon, cmd);
715
    } else if (handler_is_qobject(cmd)) {
716
        QObject *info_data = NULL;
717

    
718
        cmd->mhandler.info_new(mon, &info_data);
719
        if (info_data) {
720
            cmd->user_print(mon, info_data);
721
            qobject_decref(info_data);
722
        }
723
    } else {
724
        cmd->mhandler.info(mon);
725
    }
726

    
727
    return;
728

    
729
help:
730
    help_cmd(mon, "info");
731
}
732

    
733
static void do_info_version_print(Monitor *mon, const QObject *data)
734
{
735
    QDict *qdict;
736
    QDict *qemu;
737

    
738
    qdict = qobject_to_qdict(data);
739
    qemu = qdict_get_qdict(qdict, "qemu");
740

    
741
    monitor_printf(mon, "%" PRId64 ".%" PRId64 ".%" PRId64 "%s\n",
742
                  qdict_get_int(qemu, "major"),
743
                  qdict_get_int(qemu, "minor"),
744
                  qdict_get_int(qemu, "micro"),
745
                  qdict_get_str(qdict, "package"));
746
}
747

    
748
static void do_info_version(Monitor *mon, QObject **ret_data)
749
{
750
    const char *version = QEMU_VERSION;
751
    int major = 0, minor = 0, micro = 0;
752
    char *tmp;
753

    
754
    major = strtol(version, &tmp, 10);
755
    tmp++;
756
    minor = strtol(tmp, &tmp, 10);
757
    tmp++;
758
    micro = strtol(tmp, &tmp, 10);
759

    
760
    *ret_data = qobject_from_jsonf("{ 'qemu': { 'major': %d, 'minor': %d, \
761
        'micro': %d }, 'package': %s }", major, minor, micro, QEMU_PKGVERSION);
762
}
763

    
764
static void do_info_name_print(Monitor *mon, const QObject *data)
765
{
766
    QDict *qdict;
767

    
768
    qdict = qobject_to_qdict(data);
769
    if (qdict_size(qdict) == 0) {
770
        return;
771
    }
772

    
773
    monitor_printf(mon, "%s\n", qdict_get_str(qdict, "name"));
774
}
775

    
776
static void do_info_name(Monitor *mon, QObject **ret_data)
777
{
778
    *ret_data = qemu_name ? qobject_from_jsonf("{'name': %s }", qemu_name) :
779
                            qobject_from_jsonf("{}");
780
}
781

    
782
static QObject *get_cmd_dict(const char *name)
783
{
784
    const char *p;
785

    
786
    /* Remove '|' from some commands */
787
    p = strchr(name, '|');
788
    if (p) {
789
        p++;
790
    } else {
791
        p = name;
792
    }
793

    
794
    return qobject_from_jsonf("{ 'name': %s }", p);
795
}
796

    
797
static void do_info_commands(Monitor *mon, QObject **ret_data)
798
{
799
    QList *cmd_list;
800
    const mon_cmd_t *cmd;
801

    
802
    cmd_list = qlist_new();
803

    
804
    for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {
805
        qlist_append_obj(cmd_list, get_cmd_dict(cmd->name));
806
    }
807

    
808
    for (cmd = qmp_query_cmds; cmd->name != NULL; cmd++) {
809
        char buf[128];
810
        snprintf(buf, sizeof(buf), "query-%s", cmd->name);
811
        qlist_append_obj(cmd_list, get_cmd_dict(buf));
812
    }
813

    
814
    *ret_data = QOBJECT(cmd_list);
815
}
816

    
817
static void do_info_uuid_print(Monitor *mon, const QObject *data)
818
{
819
    monitor_printf(mon, "%s\n", qdict_get_str(qobject_to_qdict(data), "UUID"));
820
}
821

    
822
static void do_info_uuid(Monitor *mon, QObject **ret_data)
823
{
824
    char uuid[64];
825

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

    
834
/* get the current CPU defined by the user */
835
static int mon_set_cpu(int cpu_index)
836
{
837
    CPUState *env;
838

    
839
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
840
        if (env->cpu_index == cpu_index) {
841
            cur_mon->mon_cpu = env;
842
            return 0;
843
        }
844
    }
845
    return -1;
846
}
847

    
848
static CPUState *mon_get_cpu(void)
849
{
850
    if (!cur_mon->mon_cpu) {
851
        mon_set_cpu(0);
852
    }
853
    cpu_synchronize_state(cur_mon->mon_cpu);
854
    return cur_mon->mon_cpu;
855
}
856

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

    
870
static void print_cpu_iter(QObject *obj, void *opaque)
871
{
872
    QDict *cpu;
873
    int active = ' ';
874
    Monitor *mon = opaque;
875

    
876
    assert(qobject_type(obj) == QTYPE_QDICT);
877
    cpu = qobject_to_qdict(obj);
878

    
879
    if (qdict_get_bool(cpu, "current")) {
880
        active = '*';
881
    }
882

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

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

    
901
    if (qdict_get_bool(cpu, "halted")) {
902
        monitor_printf(mon, " (halted)");
903
    }
904

    
905
    monitor_printf(mon, " thread_id=%" PRId64 " ",
906
                   qdict_get_int(cpu, "thread_id"));
907

    
908
    monitor_printf(mon, "\n");
909
}
910

    
911
static void monitor_print_cpus(Monitor *mon, const QObject *data)
912
{
913
    QList *cpu_list;
914

    
915
    assert(qobject_type(data) == QTYPE_QLIST);
916
    cpu_list = qobject_to_qlist(data);
917
    qlist_iter(cpu_list, print_cpu_iter, mon);
918
}
919

    
920
static void do_info_cpus(Monitor *mon, QObject **ret_data)
921
{
922
    CPUState *env;
923
    QList *cpu_list;
924

    
925
    cpu_list = qlist_new();
926

    
927
    /* just to set the default cpu if not already done */
928
    mon_get_cpu();
929

    
930
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
931
        QDict *cpu;
932
        QObject *obj;
933

    
934
        cpu_synchronize_state(env);
935

    
936
        obj = qobject_from_jsonf("{ 'CPU': %d, 'current': %i, 'halted': %i }",
937
                                 env->cpu_index, env == mon->mon_cpu,
938
                                 env->halted);
939

    
940
        cpu = qobject_to_qdict(obj);
941

    
942
#if defined(TARGET_I386)
943
        qdict_put(cpu, "pc", qint_from_int(env->eip + env->segs[R_CS].base));
944
#elif defined(TARGET_PPC)
945
        qdict_put(cpu, "nip", qint_from_int(env->nip));
946
#elif defined(TARGET_SPARC)
947
        qdict_put(cpu, "pc", qint_from_int(env->pc));
948
        qdict_put(cpu, "npc", qint_from_int(env->npc));
949
#elif defined(TARGET_MIPS)
950
        qdict_put(cpu, "PC", qint_from_int(env->active_tc.PC));
951
#endif
952
        qdict_put(cpu, "thread_id", qint_from_int(env->thread_id));
953

    
954
        qlist_append(cpu_list, cpu);
955
    }
956

    
957
    *ret_data = QOBJECT(cpu_list);
958
}
959

    
960
static int do_cpu_set(Monitor *mon, const QDict *qdict, QObject **ret_data)
961
{
962
    int index = qdict_get_int(qdict, "index");
963
    if (mon_set_cpu(index) < 0) {
964
        qerror_report(QERR_INVALID_PARAMETER_VALUE, "index",
965
                      "a CPU number");
966
        return -1;
967
    }
968
    return 0;
969
}
970

    
971
static void do_info_jit(Monitor *mon)
972
{
973
    dump_exec_info((FILE *)mon, monitor_fprintf);
974
}
975

    
976
static void do_info_history(Monitor *mon)
977
{
978
    int i;
979
    const char *str;
980

    
981
    if (!mon->rs)
982
        return;
983
    i = 0;
984
    for(;;) {
985
        str = readline_get_history(mon->rs, i);
986
        if (!str)
987
            break;
988
        monitor_printf(mon, "%d: '%s'\n", i, str);
989
        i++;
990
    }
991
}
992

    
993
#if defined(TARGET_PPC)
994
/* XXX: not implemented in other targets */
995
static void do_info_cpu_stats(Monitor *mon)
996
{
997
    CPUState *env;
998

    
999
    env = mon_get_cpu();
1000
    cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
1001
}
1002
#endif
1003

    
1004
#if defined(CONFIG_TRACE_SIMPLE)
1005
static void do_info_trace(Monitor *mon)
1006
{
1007
    st_print_trace((FILE *)mon, &monitor_fprintf);
1008
}
1009
#endif
1010

    
1011
static void do_trace_print_events(Monitor *mon)
1012
{
1013
    trace_print_events((FILE *)mon, &monitor_fprintf);
1014
}
1015

    
1016
/**
1017
 * do_quit(): Quit QEMU execution
1018
 */
1019
static int do_quit(Monitor *mon, const QDict *qdict, QObject **ret_data)
1020
{
1021
    monitor_suspend(mon);
1022
    no_shutdown = 0;
1023
    qemu_system_shutdown_request();
1024

    
1025
    return 0;
1026
}
1027

    
1028
#ifdef CONFIG_VNC
1029
static int change_vnc_password(const char *password)
1030
{
1031
    if (!password || !password[0]) {
1032
        if (vnc_display_disable_login(NULL)) {
1033
            qerror_report(QERR_SET_PASSWD_FAILED);
1034
            return -1;
1035
        }
1036
        return 0;
1037
    }
1038

    
1039
    if (vnc_display_password(NULL, password) < 0) {
1040
        qerror_report(QERR_SET_PASSWD_FAILED);
1041
        return -1;
1042
    }
1043

    
1044
    return 0;
1045
}
1046

    
1047
static void change_vnc_password_cb(Monitor *mon, const char *password,
1048
                                   void *opaque)
1049
{
1050
    change_vnc_password(password);
1051
    monitor_read_command(mon, 1);
1052
}
1053

    
1054
static int do_change_vnc(Monitor *mon, const char *target, const char *arg)
1055
{
1056
    if (strcmp(target, "passwd") == 0 ||
1057
        strcmp(target, "password") == 0) {
1058
        if (arg) {
1059
            char password[9];
1060
            strncpy(password, arg, sizeof(password));
1061
            password[sizeof(password) - 1] = '\0';
1062
            return change_vnc_password(password);
1063
        } else {
1064
            return monitor_read_password(mon, change_vnc_password_cb, NULL);
1065
        }
1066
    } else {
1067
        if (vnc_display_open(NULL, target) < 0) {
1068
            qerror_report(QERR_VNC_SERVER_FAILED, target);
1069
            return -1;
1070
        }
1071
    }
1072

    
1073
    return 0;
1074
}
1075
#else
1076
static int do_change_vnc(Monitor *mon, const char *target, const char *arg)
1077
{
1078
    qerror_report(QERR_FEATURE_DISABLED, "vnc");
1079
    return -ENODEV;
1080
}
1081
#endif
1082

    
1083
/**
1084
 * do_change(): Change a removable medium, or VNC configuration
1085
 */
1086
static int do_change(Monitor *mon, const QDict *qdict, QObject **ret_data)
1087
{
1088
    const char *device = qdict_get_str(qdict, "device");
1089
    const char *target = qdict_get_str(qdict, "target");
1090
    const char *arg = qdict_get_try_str(qdict, "arg");
1091
    int ret;
1092

    
1093
    if (strcmp(device, "vnc") == 0) {
1094
        ret = do_change_vnc(mon, target, arg);
1095
    } else {
1096
        ret = do_change_block(mon, device, target, arg);
1097
    }
1098

    
1099
    return ret;
1100
}
1101

    
1102
static int set_password(Monitor *mon, const QDict *qdict, QObject **ret_data)
1103
{
1104
    const char *protocol  = qdict_get_str(qdict, "protocol");
1105
    const char *password  = qdict_get_str(qdict, "password");
1106
    const char *connected = qdict_get_try_str(qdict, "connected");
1107
    int disconnect_if_connected = 0;
1108
    int fail_if_connected = 0;
1109
    int rc;
1110

    
1111
    if (connected) {
1112
        if (strcmp(connected, "fail") == 0) {
1113
            fail_if_connected = 1;
1114
        } else if (strcmp(connected, "disconnect") == 0) {
1115
            disconnect_if_connected = 1;
1116
        } else if (strcmp(connected, "keep") == 0) {
1117
            /* nothing */
1118
        } else {
1119
            qerror_report(QERR_INVALID_PARAMETER, "connected");
1120
            return -1;
1121
        }
1122
    }
1123

    
1124
    if (strcmp(protocol, "spice") == 0) {
1125
        if (!using_spice) {
1126
            /* correct one? spice isn't a device ,,, */
1127
            qerror_report(QERR_DEVICE_NOT_ACTIVE, "spice");
1128
            return -1;
1129
        }
1130
        rc = qemu_spice_set_passwd(password, fail_if_connected,
1131
                                   disconnect_if_connected);
1132
        if (rc != 0) {
1133
            qerror_report(QERR_SET_PASSWD_FAILED);
1134
            return -1;
1135
        }
1136
        return 0;
1137
    }
1138

    
1139
    if (strcmp(protocol, "vnc") == 0) {
1140
        if (fail_if_connected || disconnect_if_connected) {
1141
            /* vnc supports "connected=keep" only */
1142
            qerror_report(QERR_INVALID_PARAMETER, "connected");
1143
            return -1;
1144
        }
1145
        /* Note that setting an empty password will not disable login through
1146
         * this interface. */
1147
        return vnc_display_password(NULL, password);
1148
    }
1149

    
1150
    qerror_report(QERR_INVALID_PARAMETER, "protocol");
1151
    return -1;
1152
}
1153

    
1154
static int expire_password(Monitor *mon, const QDict *qdict, QObject **ret_data)
1155
{
1156
    const char *protocol  = qdict_get_str(qdict, "protocol");
1157
    const char *whenstr = qdict_get_str(qdict, "time");
1158
    time_t when;
1159
    int rc;
1160

    
1161
    if (strcmp(whenstr, "now") == 0) {
1162
        when = 0;
1163
    } else if (strcmp(whenstr, "never") == 0) {
1164
        when = TIME_MAX;
1165
    } else if (whenstr[0] == '+') {
1166
        when = time(NULL) + strtoull(whenstr+1, NULL, 10);
1167
    } else {
1168
        when = strtoull(whenstr, NULL, 10);
1169
    }
1170

    
1171
    if (strcmp(protocol, "spice") == 0) {
1172
        if (!using_spice) {
1173
            /* correct one? spice isn't a device ,,, */
1174
            qerror_report(QERR_DEVICE_NOT_ACTIVE, "spice");
1175
            return -1;
1176
        }
1177
        rc = qemu_spice_set_pw_expire(when);
1178
        if (rc != 0) {
1179
            qerror_report(QERR_SET_PASSWD_FAILED);
1180
            return -1;
1181
        }
1182
        return 0;
1183
    }
1184

    
1185
    if (strcmp(protocol, "vnc") == 0) {
1186
        return vnc_display_pw_expire(NULL, when);
1187
    }
1188

    
1189
    qerror_report(QERR_INVALID_PARAMETER, "protocol");
1190
    return -1;
1191
}
1192

    
1193
static int add_graphics_client(Monitor *mon, const QDict *qdict, QObject **ret_data)
1194
{
1195
    const char *protocol  = qdict_get_str(qdict, "protocol");
1196
    const char *fdname = qdict_get_str(qdict, "fdname");
1197
    CharDriverState *s;
1198

    
1199
    if (strcmp(protocol, "spice") == 0) {
1200
        if (!using_spice) {
1201
            /* correct one? spice isn't a device ,,, */
1202
            qerror_report(QERR_DEVICE_NOT_ACTIVE, "spice");
1203
            return -1;
1204
        }
1205
        qerror_report(QERR_ADD_CLIENT_FAILED);
1206
        return -1;
1207
#ifdef CONFIG_VNC
1208
    } else if (strcmp(protocol, "vnc") == 0) {
1209
        int fd = monitor_get_fd(mon, fdname);
1210
        int skipauth = qdict_get_try_bool(qdict, "skipauth", 0);
1211
        vnc_display_add_client(NULL, fd, skipauth);
1212
        return 0;
1213
#endif
1214
    } else if ((s = qemu_chr_find(protocol)) != NULL) {
1215
        int fd = monitor_get_fd(mon, fdname);
1216
        if (qemu_chr_add_client(s, fd) < 0) {
1217
            qerror_report(QERR_ADD_CLIENT_FAILED);
1218
            return -1;
1219
        }
1220
        return 0;
1221
    }
1222

    
1223
    qerror_report(QERR_INVALID_PARAMETER, "protocol");
1224
    return -1;
1225
}
1226

    
1227
static int client_migrate_info(Monitor *mon, const QDict *qdict, QObject **ret_data)
1228
{
1229
    const char *protocol = qdict_get_str(qdict, "protocol");
1230
    const char *hostname = qdict_get_str(qdict, "hostname");
1231
    const char *subject  = qdict_get_try_str(qdict, "cert-subject");
1232
    int port             = qdict_get_try_int(qdict, "port", -1);
1233
    int tls_port         = qdict_get_try_int(qdict, "tls-port", -1);
1234
    int ret;
1235

    
1236
    if (strcmp(protocol, "spice") == 0) {
1237
        if (!using_spice) {
1238
            qerror_report(QERR_DEVICE_NOT_ACTIVE, "spice");
1239
            return -1;
1240
        }
1241

    
1242
        ret = qemu_spice_migrate_info(hostname, port, tls_port, subject);
1243
        if (ret != 0) {
1244
            qerror_report(QERR_UNDEFINED_ERROR);
1245
            return -1;
1246
        }
1247
        return 0;
1248
    }
1249

    
1250
    qerror_report(QERR_INVALID_PARAMETER, "protocol");
1251
    return -1;
1252
}
1253

    
1254
static int do_screen_dump(Monitor *mon, const QDict *qdict, QObject **ret_data)
1255
{
1256
    vga_hw_screen_dump(qdict_get_str(qdict, "filename"));
1257
    return 0;
1258
}
1259

    
1260
static void do_logfile(Monitor *mon, const QDict *qdict)
1261
{
1262
    cpu_set_log_filename(qdict_get_str(qdict, "filename"));
1263
}
1264

    
1265
static void do_log(Monitor *mon, const QDict *qdict)
1266
{
1267
    int mask;
1268
    const char *items = qdict_get_str(qdict, "items");
1269

    
1270
    if (!strcmp(items, "none")) {
1271
        mask = 0;
1272
    } else {
1273
        mask = cpu_str_to_log_mask(items);
1274
        if (!mask) {
1275
            help_cmd(mon, "log");
1276
            return;
1277
        }
1278
    }
1279
    cpu_set_log(mask);
1280
}
1281

    
1282
static void do_singlestep(Monitor *mon, const QDict *qdict)
1283
{
1284
    const char *option = qdict_get_try_str(qdict, "option");
1285
    if (!option || !strcmp(option, "on")) {
1286
        singlestep = 1;
1287
    } else if (!strcmp(option, "off")) {
1288
        singlestep = 0;
1289
    } else {
1290
        monitor_printf(mon, "unexpected option %s\n", option);
1291
    }
1292
}
1293

    
1294
/**
1295
 * do_stop(): Stop VM execution
1296
 */
1297
static int do_stop(Monitor *mon, const QDict *qdict, QObject **ret_data)
1298
{
1299
    vm_stop(RSTATE_PAUSED);
1300
    return 0;
1301
}
1302

    
1303
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs);
1304

    
1305
struct bdrv_iterate_context {
1306
    Monitor *mon;
1307
    int err;
1308
};
1309

    
1310
/**
1311
 * do_cont(): Resume emulation.
1312
 */
1313
static int do_cont(Monitor *mon, const QDict *qdict, QObject **ret_data)
1314
{
1315
    struct bdrv_iterate_context context = { mon, 0 };
1316

    
1317
    if (runstate_check(RSTATE_IN_MIGRATE)) {
1318
        qerror_report(QERR_MIGRATION_EXPECTED);
1319
        return -1;
1320
    } else if (runstate_check(RSTATE_PANICKED) ||
1321
               runstate_check(RSTATE_SHUTDOWN)) {
1322
        qerror_report(QERR_RESET_REQUIRED);
1323
        return -1;
1324
    }
1325

    
1326
    bdrv_iterate(encrypted_bdrv_it, &context);
1327
    /* only resume the vm if all keys are set and valid */
1328
    if (!context.err) {
1329
        vm_start();
1330
        return 0;
1331
    } else {
1332
        return -1;
1333
    }
1334
}
1335

    
1336
static void bdrv_key_cb(void *opaque, int err)
1337
{
1338
    Monitor *mon = opaque;
1339

    
1340
    /* another key was set successfully, retry to continue */
1341
    if (!err)
1342
        do_cont(mon, NULL, NULL);
1343
}
1344

    
1345
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs)
1346
{
1347
    struct bdrv_iterate_context *context = opaque;
1348

    
1349
    if (!context->err && bdrv_key_required(bs)) {
1350
        context->err = -EBUSY;
1351
        monitor_read_bdrv_key_start(context->mon, bs, bdrv_key_cb,
1352
                                    context->mon);
1353
    }
1354
}
1355

    
1356
static void do_gdbserver(Monitor *mon, const QDict *qdict)
1357
{
1358
    const char *device = qdict_get_try_str(qdict, "device");
1359
    if (!device)
1360
        device = "tcp::" DEFAULT_GDBSTUB_PORT;
1361
    if (gdbserver_start(device) < 0) {
1362
        monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1363
                       device);
1364
    } else if (strcmp(device, "none") == 0) {
1365
        monitor_printf(mon, "Disabled gdbserver\n");
1366
    } else {
1367
        monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1368
                       device);
1369
    }
1370
}
1371

    
1372
static void do_watchdog_action(Monitor *mon, const QDict *qdict)
1373
{
1374
    const char *action = qdict_get_str(qdict, "action");
1375
    if (select_watchdog_action(action) == -1) {
1376
        monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1377
    }
1378
}
1379

    
1380
static void monitor_printc(Monitor *mon, int c)
1381
{
1382
    monitor_printf(mon, "'");
1383
    switch(c) {
1384
    case '\'':
1385
        monitor_printf(mon, "\\'");
1386
        break;
1387
    case '\\':
1388
        monitor_printf(mon, "\\\\");
1389
        break;
1390
    case '\n':
1391
        monitor_printf(mon, "\\n");
1392
        break;
1393
    case '\r':
1394
        monitor_printf(mon, "\\r");
1395
        break;
1396
    default:
1397
        if (c >= 32 && c <= 126) {
1398
            monitor_printf(mon, "%c", c);
1399
        } else {
1400
            monitor_printf(mon, "\\x%02x", c);
1401
        }
1402
        break;
1403
    }
1404
    monitor_printf(mon, "'");
1405
}
1406

    
1407
static void memory_dump(Monitor *mon, int count, int format, int wsize,
1408
                        target_phys_addr_t addr, int is_physical)
1409
{
1410
    CPUState *env;
1411
    int l, line_size, i, max_digits, len;
1412
    uint8_t buf[16];
1413
    uint64_t v;
1414

    
1415
    if (format == 'i') {
1416
        int flags;
1417
        flags = 0;
1418
        env = mon_get_cpu();
1419
#ifdef TARGET_I386
1420
        if (wsize == 2) {
1421
            flags = 1;
1422
        } else if (wsize == 4) {
1423
            flags = 0;
1424
        } else {
1425
            /* as default we use the current CS size */
1426
            flags = 0;
1427
            if (env) {
1428
#ifdef TARGET_X86_64
1429
                if ((env->efer & MSR_EFER_LMA) &&
1430
                    (env->segs[R_CS].flags & DESC_L_MASK))
1431
                    flags = 2;
1432
                else
1433
#endif
1434
                if (!(env->segs[R_CS].flags & DESC_B_MASK))
1435
                    flags = 1;
1436
            }
1437
        }
1438
#endif
1439
        monitor_disas(mon, env, addr, count, is_physical, flags);
1440
        return;
1441
    }
1442

    
1443
    len = wsize * count;
1444
    if (wsize == 1)
1445
        line_size = 8;
1446
    else
1447
        line_size = 16;
1448
    max_digits = 0;
1449

    
1450
    switch(format) {
1451
    case 'o':
1452
        max_digits = (wsize * 8 + 2) / 3;
1453
        break;
1454
    default:
1455
    case 'x':
1456
        max_digits = (wsize * 8) / 4;
1457
        break;
1458
    case 'u':
1459
    case 'd':
1460
        max_digits = (wsize * 8 * 10 + 32) / 33;
1461
        break;
1462
    case 'c':
1463
        wsize = 1;
1464
        break;
1465
    }
1466

    
1467
    while (len > 0) {
1468
        if (is_physical)
1469
            monitor_printf(mon, TARGET_FMT_plx ":", addr);
1470
        else
1471
            monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1472
        l = len;
1473
        if (l > line_size)
1474
            l = line_size;
1475
        if (is_physical) {
1476
            cpu_physical_memory_read(addr, buf, l);
1477
        } else {
1478
            env = mon_get_cpu();
1479
            if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {
1480
                monitor_printf(mon, " Cannot access memory\n");
1481
                break;
1482
            }
1483
        }
1484
        i = 0;
1485
        while (i < l) {
1486
            switch(wsize) {
1487
            default:
1488
            case 1:
1489
                v = ldub_raw(buf + i);
1490
                break;
1491
            case 2:
1492
                v = lduw_raw(buf + i);
1493
                break;
1494
            case 4:
1495
                v = (uint32_t)ldl_raw(buf + i);
1496
                break;
1497
            case 8:
1498
                v = ldq_raw(buf + i);
1499
                break;
1500
            }
1501
            monitor_printf(mon, " ");
1502
            switch(format) {
1503
            case 'o':
1504
                monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1505
                break;
1506
            case 'x':
1507
                monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1508
                break;
1509
            case 'u':
1510
                monitor_printf(mon, "%*" PRIu64, max_digits, v);
1511
                break;
1512
            case 'd':
1513
                monitor_printf(mon, "%*" PRId64, max_digits, v);
1514
                break;
1515
            case 'c':
1516
                monitor_printc(mon, v);
1517
                break;
1518
            }
1519
            i += wsize;
1520
        }
1521
        monitor_printf(mon, "\n");
1522
        addr += l;
1523
        len -= l;
1524
    }
1525
}
1526

    
1527
static void do_memory_dump(Monitor *mon, const QDict *qdict)
1528
{
1529
    int count = qdict_get_int(qdict, "count");
1530
    int format = qdict_get_int(qdict, "format");
1531
    int size = qdict_get_int(qdict, "size");
1532
    target_long addr = qdict_get_int(qdict, "addr");
1533

    
1534
    memory_dump(mon, count, format, size, addr, 0);
1535
}
1536

    
1537
static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
1538
{
1539
    int count = qdict_get_int(qdict, "count");
1540
    int format = qdict_get_int(qdict, "format");
1541
    int size = qdict_get_int(qdict, "size");
1542
    target_phys_addr_t addr = qdict_get_int(qdict, "addr");
1543

    
1544
    memory_dump(mon, count, format, size, addr, 1);
1545
}
1546

    
1547
static void do_print(Monitor *mon, const QDict *qdict)
1548
{
1549
    int format = qdict_get_int(qdict, "format");
1550
    target_phys_addr_t val = qdict_get_int(qdict, "val");
1551

    
1552
#if TARGET_PHYS_ADDR_BITS == 32
1553
    switch(format) {
1554
    case 'o':
1555
        monitor_printf(mon, "%#o", val);
1556
        break;
1557
    case 'x':
1558
        monitor_printf(mon, "%#x", val);
1559
        break;
1560
    case 'u':
1561
        monitor_printf(mon, "%u", val);
1562
        break;
1563
    default:
1564
    case 'd':
1565
        monitor_printf(mon, "%d", val);
1566
        break;
1567
    case 'c':
1568
        monitor_printc(mon, val);
1569
        break;
1570
    }
1571
#else
1572
    switch(format) {
1573
    case 'o':
1574
        monitor_printf(mon, "%#" PRIo64, val);
1575
        break;
1576
    case 'x':
1577
        monitor_printf(mon, "%#" PRIx64, val);
1578
        break;
1579
    case 'u':
1580
        monitor_printf(mon, "%" PRIu64, val);
1581
        break;
1582
    default:
1583
    case 'd':
1584
        monitor_printf(mon, "%" PRId64, val);
1585
        break;
1586
    case 'c':
1587
        monitor_printc(mon, val);
1588
        break;
1589
    }
1590
#endif
1591
    monitor_printf(mon, "\n");
1592
}
1593

    
1594
static int do_memory_save(Monitor *mon, const QDict *qdict, QObject **ret_data)
1595
{
1596
    FILE *f;
1597
    uint32_t size = qdict_get_int(qdict, "size");
1598
    const char *filename = qdict_get_str(qdict, "filename");
1599
    target_long addr = qdict_get_int(qdict, "val");
1600
    uint32_t l;
1601
    CPUState *env;
1602
    uint8_t buf[1024];
1603
    int ret = -1;
1604

    
1605
    env = mon_get_cpu();
1606

    
1607
    f = fopen(filename, "wb");
1608
    if (!f) {
1609
        qerror_report(QERR_OPEN_FILE_FAILED, filename);
1610
        return -1;
1611
    }
1612
    while (size != 0) {
1613
        l = sizeof(buf);
1614
        if (l > size)
1615
            l = size;
1616
        cpu_memory_rw_debug(env, addr, buf, l, 0);
1617
        if (fwrite(buf, 1, l, f) != l) {
1618
            monitor_printf(mon, "fwrite() error in do_memory_save\n");
1619
            goto exit;
1620
        }
1621
        addr += l;
1622
        size -= l;
1623
    }
1624

    
1625
    ret = 0;
1626

    
1627
exit:
1628
    fclose(f);
1629
    return ret;
1630
}
1631

    
1632
static int do_physical_memory_save(Monitor *mon, const QDict *qdict,
1633
                                    QObject **ret_data)
1634
{
1635
    FILE *f;
1636
    uint32_t l;
1637
    uint8_t buf[1024];
1638
    uint32_t size = qdict_get_int(qdict, "size");
1639
    const char *filename = qdict_get_str(qdict, "filename");
1640
    target_phys_addr_t addr = qdict_get_int(qdict, "val");
1641
    int ret = -1;
1642

    
1643
    f = fopen(filename, "wb");
1644
    if (!f) {
1645
        qerror_report(QERR_OPEN_FILE_FAILED, filename);
1646
        return -1;
1647
    }
1648
    while (size != 0) {
1649
        l = sizeof(buf);
1650
        if (l > size)
1651
            l = size;
1652
        cpu_physical_memory_read(addr, buf, l);
1653
        if (fwrite(buf, 1, l, f) != l) {
1654
            monitor_printf(mon, "fwrite() error in do_physical_memory_save\n");
1655
            goto exit;
1656
        }
1657
        fflush(f);
1658
        addr += l;
1659
        size -= l;
1660
    }
1661

    
1662
    ret = 0;
1663

    
1664
exit:
1665
    fclose(f);
1666
    return ret;
1667
}
1668

    
1669
static void do_sum(Monitor *mon, const QDict *qdict)
1670
{
1671
    uint32_t addr;
1672
    uint16_t sum;
1673
    uint32_t start = qdict_get_int(qdict, "start");
1674
    uint32_t size = qdict_get_int(qdict, "size");
1675

    
1676
    sum = 0;
1677
    for(addr = start; addr < (start + size); addr++) {
1678
        uint8_t val = ldub_phys(addr);
1679
        /* BSD sum algorithm ('sum' Unix command) */
1680
        sum = (sum >> 1) | (sum << 15);
1681
        sum += val;
1682
    }
1683
    monitor_printf(mon, "%05d\n", sum);
1684
}
1685

    
1686
typedef struct {
1687
    int keycode;
1688
    const char *name;
1689
} KeyDef;
1690

    
1691
static const KeyDef key_defs[] = {
1692
    { 0x2a, "shift" },
1693
    { 0x36, "shift_r" },
1694

    
1695
    { 0x38, "alt" },
1696
    { 0xb8, "alt_r" },
1697
    { 0x64, "altgr" },
1698
    { 0xe4, "altgr_r" },
1699
    { 0x1d, "ctrl" },
1700
    { 0x9d, "ctrl_r" },
1701

    
1702
    { 0xdd, "menu" },
1703

    
1704
    { 0x01, "esc" },
1705

    
1706
    { 0x02, "1" },
1707
    { 0x03, "2" },
1708
    { 0x04, "3" },
1709
    { 0x05, "4" },
1710
    { 0x06, "5" },
1711
    { 0x07, "6" },
1712
    { 0x08, "7" },
1713
    { 0x09, "8" },
1714
    { 0x0a, "9" },
1715
    { 0x0b, "0" },
1716
    { 0x0c, "minus" },
1717
    { 0x0d, "equal" },
1718
    { 0x0e, "backspace" },
1719

    
1720
    { 0x0f, "tab" },
1721
    { 0x10, "q" },
1722
    { 0x11, "w" },
1723
    { 0x12, "e" },
1724
    { 0x13, "r" },
1725
    { 0x14, "t" },
1726
    { 0x15, "y" },
1727
    { 0x16, "u" },
1728
    { 0x17, "i" },
1729
    { 0x18, "o" },
1730
    { 0x19, "p" },
1731
    { 0x1a, "bracket_left" },
1732
    { 0x1b, "bracket_right" },
1733
    { 0x1c, "ret" },
1734

    
1735
    { 0x1e, "a" },
1736
    { 0x1f, "s" },
1737
    { 0x20, "d" },
1738
    { 0x21, "f" },
1739
    { 0x22, "g" },
1740
    { 0x23, "h" },
1741
    { 0x24, "j" },
1742
    { 0x25, "k" },
1743
    { 0x26, "l" },
1744
    { 0x27, "semicolon" },
1745
    { 0x28, "apostrophe" },
1746
    { 0x29, "grave_accent" },
1747

    
1748
    { 0x2b, "backslash" },
1749
    { 0x2c, "z" },
1750
    { 0x2d, "x" },
1751
    { 0x2e, "c" },
1752
    { 0x2f, "v" },
1753
    { 0x30, "b" },
1754
    { 0x31, "n" },
1755
    { 0x32, "m" },
1756
    { 0x33, "comma" },
1757
    { 0x34, "dot" },
1758
    { 0x35, "slash" },
1759

    
1760
    { 0x37, "asterisk" },
1761

    
1762
    { 0x39, "spc" },
1763
    { 0x3a, "caps_lock" },
1764
    { 0x3b, "f1" },
1765
    { 0x3c, "f2" },
1766
    { 0x3d, "f3" },
1767
    { 0x3e, "f4" },
1768
    { 0x3f, "f5" },
1769
    { 0x40, "f6" },
1770
    { 0x41, "f7" },
1771
    { 0x42, "f8" },
1772
    { 0x43, "f9" },
1773
    { 0x44, "f10" },
1774
    { 0x45, "num_lock" },
1775
    { 0x46, "scroll_lock" },
1776

    
1777
    { 0xb5, "kp_divide" },
1778
    { 0x37, "kp_multiply" },
1779
    { 0x4a, "kp_subtract" },
1780
    { 0x4e, "kp_add" },
1781
    { 0x9c, "kp_enter" },
1782
    { 0x53, "kp_decimal" },
1783
    { 0x54, "sysrq" },
1784

    
1785
    { 0x52, "kp_0" },
1786
    { 0x4f, "kp_1" },
1787
    { 0x50, "kp_2" },
1788
    { 0x51, "kp_3" },
1789
    { 0x4b, "kp_4" },
1790
    { 0x4c, "kp_5" },
1791
    { 0x4d, "kp_6" },
1792
    { 0x47, "kp_7" },
1793
    { 0x48, "kp_8" },
1794
    { 0x49, "kp_9" },
1795

    
1796
    { 0x56, "<" },
1797

    
1798
    { 0x57, "f11" },
1799
    { 0x58, "f12" },
1800

    
1801
    { 0xb7, "print" },
1802

    
1803
    { 0xc7, "home" },
1804
    { 0xc9, "pgup" },
1805
    { 0xd1, "pgdn" },
1806
    { 0xcf, "end" },
1807

    
1808
    { 0xcb, "left" },
1809
    { 0xc8, "up" },
1810
    { 0xd0, "down" },
1811
    { 0xcd, "right" },
1812

    
1813
    { 0xd2, "insert" },
1814
    { 0xd3, "delete" },
1815
#if defined(TARGET_SPARC) && !defined(TARGET_SPARC64)
1816
    { 0xf0, "stop" },
1817
    { 0xf1, "again" },
1818
    { 0xf2, "props" },
1819
    { 0xf3, "undo" },
1820
    { 0xf4, "front" },
1821
    { 0xf5, "copy" },
1822
    { 0xf6, "open" },
1823
    { 0xf7, "paste" },
1824
    { 0xf8, "find" },
1825
    { 0xf9, "cut" },
1826
    { 0xfa, "lf" },
1827
    { 0xfb, "help" },
1828
    { 0xfc, "meta_l" },
1829
    { 0xfd, "meta_r" },
1830
    { 0xfe, "compose" },
1831
#endif
1832
    { 0, NULL },
1833
};
1834

    
1835
static int get_keycode(const char *key)
1836
{
1837
    const KeyDef *p;
1838
    char *endp;
1839
    int ret;
1840

    
1841
    for(p = key_defs; p->name != NULL; p++) {
1842
        if (!strcmp(key, p->name))
1843
            return p->keycode;
1844
    }
1845
    if (strstart(key, "0x", NULL)) {
1846
        ret = strtoul(key, &endp, 0);
1847
        if (*endp == '\0' && ret >= 0x01 && ret <= 0xff)
1848
            return ret;
1849
    }
1850
    return -1;
1851
}
1852

    
1853
#define MAX_KEYCODES 16
1854
static uint8_t keycodes[MAX_KEYCODES];
1855
static int nb_pending_keycodes;
1856
static QEMUTimer *key_timer;
1857

    
1858
static void release_keys(void *opaque)
1859
{
1860
    int keycode;
1861

    
1862
    while (nb_pending_keycodes > 0) {
1863
        nb_pending_keycodes--;
1864
        keycode = keycodes[nb_pending_keycodes];
1865
        if (keycode & 0x80)
1866
            kbd_put_keycode(0xe0);
1867
        kbd_put_keycode(keycode | 0x80);
1868
    }
1869
}
1870

    
1871
static void do_sendkey(Monitor *mon, const QDict *qdict)
1872
{
1873
    char keyname_buf[16];
1874
    char *separator;
1875
    int keyname_len, keycode, i;
1876
    const char *string = qdict_get_str(qdict, "string");
1877
    int has_hold_time = qdict_haskey(qdict, "hold_time");
1878
    int hold_time = qdict_get_try_int(qdict, "hold_time", -1);
1879

    
1880
    if (nb_pending_keycodes > 0) {
1881
        qemu_del_timer(key_timer);
1882
        release_keys(NULL);
1883
    }
1884
    if (!has_hold_time)
1885
        hold_time = 100;
1886
    i = 0;
1887
    while (1) {
1888
        separator = strchr(string, '-');
1889
        keyname_len = separator ? separator - string : strlen(string);
1890
        if (keyname_len > 0) {
1891
            pstrcpy(keyname_buf, sizeof(keyname_buf), string);
1892
            if (keyname_len > sizeof(keyname_buf) - 1) {
1893
                monitor_printf(mon, "invalid key: '%s...'\n", keyname_buf);
1894
                return;
1895
            }
1896
            if (i == MAX_KEYCODES) {
1897
                monitor_printf(mon, "too many keys\n");
1898
                return;
1899
            }
1900
            keyname_buf[keyname_len] = 0;
1901
            keycode = get_keycode(keyname_buf);
1902
            if (keycode < 0) {
1903
                monitor_printf(mon, "unknown key: '%s'\n", keyname_buf);
1904
                return;
1905
            }
1906
            keycodes[i++] = keycode;
1907
        }
1908
        if (!separator)
1909
            break;
1910
        string = separator + 1;
1911
    }
1912
    nb_pending_keycodes = i;
1913
    /* key down events */
1914
    for (i = 0; i < nb_pending_keycodes; i++) {
1915
        keycode = keycodes[i];
1916
        if (keycode & 0x80)
1917
            kbd_put_keycode(0xe0);
1918
        kbd_put_keycode(keycode & 0x7f);
1919
    }
1920
    /* delayed key up events */
1921
    qemu_mod_timer(key_timer, qemu_get_clock_ns(vm_clock) +
1922
                   muldiv64(get_ticks_per_sec(), hold_time, 1000));
1923
}
1924

    
1925
static int mouse_button_state;
1926

    
1927
static void do_mouse_move(Monitor *mon, const QDict *qdict)
1928
{
1929
    int dx, dy, dz;
1930
    const char *dx_str = qdict_get_str(qdict, "dx_str");
1931
    const char *dy_str = qdict_get_str(qdict, "dy_str");
1932
    const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1933
    dx = strtol(dx_str, NULL, 0);
1934
    dy = strtol(dy_str, NULL, 0);
1935
    dz = 0;
1936
    if (dz_str)
1937
        dz = strtol(dz_str, NULL, 0);
1938
    kbd_mouse_event(dx, dy, dz, mouse_button_state);
1939
}
1940

    
1941
static void do_mouse_button(Monitor *mon, const QDict *qdict)
1942
{
1943
    int button_state = qdict_get_int(qdict, "button_state");
1944
    mouse_button_state = button_state;
1945
    kbd_mouse_event(0, 0, 0, mouse_button_state);
1946
}
1947

    
1948
static void do_ioport_read(Monitor *mon, const QDict *qdict)
1949
{
1950
    int size = qdict_get_int(qdict, "size");
1951
    int addr = qdict_get_int(qdict, "addr");
1952
    int has_index = qdict_haskey(qdict, "index");
1953
    uint32_t val;
1954
    int suffix;
1955

    
1956
    if (has_index) {
1957
        int index = qdict_get_int(qdict, "index");
1958
        cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1959
        addr++;
1960
    }
1961
    addr &= 0xffff;
1962

    
1963
    switch(size) {
1964
    default:
1965
    case 1:
1966
        val = cpu_inb(addr);
1967
        suffix = 'b';
1968
        break;
1969
    case 2:
1970
        val = cpu_inw(addr);
1971
        suffix = 'w';
1972
        break;
1973
    case 4:
1974
        val = cpu_inl(addr);
1975
        suffix = 'l';
1976
        break;
1977
    }
1978
    monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1979
                   suffix, addr, size * 2, val);
1980
}
1981

    
1982
static void do_ioport_write(Monitor *mon, const QDict *qdict)
1983
{
1984
    int size = qdict_get_int(qdict, "size");
1985
    int addr = qdict_get_int(qdict, "addr");
1986
    int val = qdict_get_int(qdict, "val");
1987

    
1988
    addr &= IOPORTS_MASK;
1989

    
1990
    switch (size) {
1991
    default:
1992
    case 1:
1993
        cpu_outb(addr, val);
1994
        break;
1995
    case 2:
1996
        cpu_outw(addr, val);
1997
        break;
1998
    case 4:
1999
        cpu_outl(addr, val);
2000
        break;
2001
    }
2002
}
2003

    
2004
static void do_boot_set(Monitor *mon, const QDict *qdict)
2005
{
2006
    int res;
2007
    const char *bootdevice = qdict_get_str(qdict, "bootdevice");
2008

    
2009
    res = qemu_boot_set(bootdevice);
2010
    if (res == 0) {
2011
        monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
2012
    } else if (res > 0) {
2013
        monitor_printf(mon, "setting boot device list failed\n");
2014
    } else {
2015
        monitor_printf(mon, "no function defined to set boot device list for "
2016
                       "this architecture\n");
2017
    }
2018
}
2019

    
2020
/**
2021
 * do_system_reset(): Issue a machine reset
2022
 */
2023
static int do_system_reset(Monitor *mon, const QDict *qdict,
2024
                           QObject **ret_data)
2025
{
2026
    qemu_system_reset_request();
2027
    return 0;
2028
}
2029

    
2030
/**
2031
 * do_system_powerdown(): Issue a machine powerdown
2032
 */
2033
static int do_system_powerdown(Monitor *mon, const QDict *qdict,
2034
                               QObject **ret_data)
2035
{
2036
    qemu_system_powerdown_request();
2037
    return 0;
2038
}
2039

    
2040
#if defined(TARGET_I386)
2041
static void print_pte(Monitor *mon, target_phys_addr_t addr,
2042
                      target_phys_addr_t pte,
2043
                      target_phys_addr_t mask)
2044
{
2045
#ifdef TARGET_X86_64
2046
    if (addr & (1ULL << 47)) {
2047
        addr |= -1LL << 48;
2048
    }
2049
#endif
2050
    monitor_printf(mon, TARGET_FMT_plx ": " TARGET_FMT_plx
2051
                   " %c%c%c%c%c%c%c%c%c\n",
2052
                   addr,
2053
                   pte & mask,
2054
                   pte & PG_NX_MASK ? 'X' : '-',
2055
                   pte & PG_GLOBAL_MASK ? 'G' : '-',
2056
                   pte & PG_PSE_MASK ? 'P' : '-',
2057
                   pte & PG_DIRTY_MASK ? 'D' : '-',
2058
                   pte & PG_ACCESSED_MASK ? 'A' : '-',
2059
                   pte & PG_PCD_MASK ? 'C' : '-',
2060
                   pte & PG_PWT_MASK ? 'T' : '-',
2061
                   pte & PG_USER_MASK ? 'U' : '-',
2062
                   pte & PG_RW_MASK ? 'W' : '-');
2063
}
2064

    
2065
static void tlb_info_32(Monitor *mon, CPUState *env)
2066
{
2067
    unsigned int l1, l2;
2068
    uint32_t pgd, pde, pte;
2069

    
2070
    pgd = env->cr[3] & ~0xfff;
2071
    for(l1 = 0; l1 < 1024; l1++) {
2072
        cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
2073
        pde = le32_to_cpu(pde);
2074
        if (pde & PG_PRESENT_MASK) {
2075
            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
2076
                /* 4M pages */
2077
                print_pte(mon, (l1 << 22), pde, ~((1 << 21) - 1));
2078
            } else {
2079
                for(l2 = 0; l2 < 1024; l2++) {
2080
                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
2081
                    pte = le32_to_cpu(pte);
2082
                    if (pte & PG_PRESENT_MASK) {
2083
                        print_pte(mon, (l1 << 22) + (l2 << 12),
2084
                                  pte & ~PG_PSE_MASK,
2085
                                  ~0xfff);
2086
                    }
2087
                }
2088
            }
2089
        }
2090
    }
2091
}
2092

    
2093
static void tlb_info_pae32(Monitor *mon, CPUState *env)
2094
{
2095
    unsigned int l1, l2, l3;
2096
    uint64_t pdpe, pde, pte;
2097
    uint64_t pdp_addr, pd_addr, pt_addr;
2098

    
2099
    pdp_addr = env->cr[3] & ~0x1f;
2100
    for (l1 = 0; l1 < 4; l1++) {
2101
        cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
2102
        pdpe = le64_to_cpu(pdpe);
2103
        if (pdpe & PG_PRESENT_MASK) {
2104
            pd_addr = pdpe & 0x3fffffffff000ULL;
2105
            for (l2 = 0; l2 < 512; l2++) {
2106
                cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
2107
                pde = le64_to_cpu(pde);
2108
                if (pde & PG_PRESENT_MASK) {
2109
                    if (pde & PG_PSE_MASK) {
2110
                        /* 2M pages with PAE, CR4.PSE is ignored */
2111
                        print_pte(mon, (l1 << 30 ) + (l2 << 21), pde,
2112
                                  ~((target_phys_addr_t)(1 << 20) - 1));
2113
                    } else {
2114
                        pt_addr = pde & 0x3fffffffff000ULL;
2115
                        for (l3 = 0; l3 < 512; l3++) {
2116
                            cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
2117
                            pte = le64_to_cpu(pte);
2118
                            if (pte & PG_PRESENT_MASK) {
2119
                                print_pte(mon, (l1 << 30 ) + (l2 << 21)
2120
                                          + (l3 << 12),
2121
                                          pte & ~PG_PSE_MASK,
2122
                                          ~(target_phys_addr_t)0xfff);
2123
                            }
2124
                        }
2125
                    }
2126
                }
2127
            }
2128
        }
2129
    }
2130
}
2131

    
2132
#ifdef TARGET_X86_64
2133
static void tlb_info_64(Monitor *mon, CPUState *env)
2134
{
2135
    uint64_t l1, l2, l3, l4;
2136
    uint64_t pml4e, pdpe, pde, pte;
2137
    uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr;
2138

    
2139
    pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
2140
    for (l1 = 0; l1 < 512; l1++) {
2141
        cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
2142
        pml4e = le64_to_cpu(pml4e);
2143
        if (pml4e & PG_PRESENT_MASK) {
2144
            pdp_addr = pml4e & 0x3fffffffff000ULL;
2145
            for (l2 = 0; l2 < 512; l2++) {
2146
                cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
2147
                pdpe = le64_to_cpu(pdpe);
2148
                if (pdpe & PG_PRESENT_MASK) {
2149
                    if (pdpe & PG_PSE_MASK) {
2150
                        /* 1G pages, CR4.PSE is ignored */
2151
                        print_pte(mon, (l1 << 39) + (l2 << 30), pdpe,
2152
                                  0x3ffffc0000000ULL);
2153
                    } else {
2154
                        pd_addr = pdpe & 0x3fffffffff000ULL;
2155
                        for (l3 = 0; l3 < 512; l3++) {
2156
                            cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
2157
                            pde = le64_to_cpu(pde);
2158
                            if (pde & PG_PRESENT_MASK) {
2159
                                if (pde & PG_PSE_MASK) {
2160
                                    /* 2M pages, CR4.PSE is ignored */
2161
                                    print_pte(mon, (l1 << 39) + (l2 << 30) +
2162
                                              (l3 << 21), pde,
2163
                                              0x3ffffffe00000ULL);
2164
                                } else {
2165
                                    pt_addr = pde & 0x3fffffffff000ULL;
2166
                                    for (l4 = 0; l4 < 512; l4++) {
2167
                                        cpu_physical_memory_read(pt_addr
2168
                                                                 + l4 * 8,
2169
                                                                 &pte, 8);
2170
                                        pte = le64_to_cpu(pte);
2171
                                        if (pte & PG_PRESENT_MASK) {
2172
                                            print_pte(mon, (l1 << 39) +
2173
                                                      (l2 << 30) +
2174
                                                      (l3 << 21) + (l4 << 12),
2175
                                                      pte & ~PG_PSE_MASK,
2176
                                                      0x3fffffffff000ULL);
2177
                                        }
2178
                                    }
2179
                                }
2180
                            }
2181
                        }
2182
                    }
2183
                }
2184
            }
2185
        }
2186
    }
2187
}
2188
#endif
2189

    
2190
static void tlb_info(Monitor *mon)
2191
{
2192
    CPUState *env;
2193

    
2194
    env = mon_get_cpu();
2195

    
2196
    if (!(env->cr[0] & CR0_PG_MASK)) {
2197
        monitor_printf(mon, "PG disabled\n");
2198
        return;
2199
    }
2200
    if (env->cr[4] & CR4_PAE_MASK) {
2201
#ifdef TARGET_X86_64
2202
        if (env->hflags & HF_LMA_MASK) {
2203
            tlb_info_64(mon, env);
2204
        } else
2205
#endif
2206
        {
2207
            tlb_info_pae32(mon, env);
2208
        }
2209
    } else {
2210
        tlb_info_32(mon, env);
2211
    }
2212
}
2213

    
2214
static void mem_print(Monitor *mon, target_phys_addr_t *pstart,
2215
                      int *plast_prot,
2216
                      target_phys_addr_t end, int prot)
2217
{
2218
    int prot1;
2219
    prot1 = *plast_prot;
2220
    if (prot != prot1) {
2221
        if (*pstart != -1) {
2222
            monitor_printf(mon, TARGET_FMT_plx "-" TARGET_FMT_plx " "
2223
                           TARGET_FMT_plx " %c%c%c\n",
2224
                           *pstart, end, end - *pstart,
2225
                           prot1 & PG_USER_MASK ? 'u' : '-',
2226
                           'r',
2227
                           prot1 & PG_RW_MASK ? 'w' : '-');
2228
        }
2229
        if (prot != 0)
2230
            *pstart = end;
2231
        else
2232
            *pstart = -1;
2233
        *plast_prot = prot;
2234
    }
2235
}
2236

    
2237
static void mem_info_32(Monitor *mon, CPUState *env)
2238
{
2239
    unsigned int l1, l2;
2240
    int prot, last_prot;
2241
    uint32_t pgd, pde, pte;
2242
    target_phys_addr_t start, end;
2243

    
2244
    pgd = env->cr[3] & ~0xfff;
2245
    last_prot = 0;
2246
    start = -1;
2247
    for(l1 = 0; l1 < 1024; l1++) {
2248
        cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
2249
        pde = le32_to_cpu(pde);
2250
        end = l1 << 22;
2251
        if (pde & PG_PRESENT_MASK) {
2252
            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
2253
                prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
2254
                mem_print(mon, &start, &last_prot, end, prot);
2255
            } else {
2256
                for(l2 = 0; l2 < 1024; l2++) {
2257
                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
2258
                    pte = le32_to_cpu(pte);
2259
                    end = (l1 << 22) + (l2 << 12);
2260
                    if (pte & PG_PRESENT_MASK) {
2261
                        prot = pte & pde &
2262
                            (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
2263
                    } else {
2264
                        prot = 0;
2265
                    }
2266
                    mem_print(mon, &start, &last_prot, end, prot);
2267
                }
2268
            }
2269
        } else {
2270
            prot = 0;
2271
            mem_print(mon, &start, &last_prot, end, prot);
2272
        }
2273
    }
2274
    /* Flush last range */
2275
    mem_print(mon, &start, &last_prot, (target_phys_addr_t)1 << 32, 0);
2276
}
2277

    
2278
static void mem_info_pae32(Monitor *mon, CPUState *env)
2279
{
2280
    unsigned int l1, l2, l3;
2281
    int prot, last_prot;
2282
    uint64_t pdpe, pde, pte;
2283
    uint64_t pdp_addr, pd_addr, pt_addr;
2284
    target_phys_addr_t start, end;
2285

    
2286
    pdp_addr = env->cr[3] & ~0x1f;
2287
    last_prot = 0;
2288
    start = -1;
2289
    for (l1 = 0; l1 < 4; l1++) {
2290
        cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
2291
        pdpe = le64_to_cpu(pdpe);
2292
        end = l1 << 30;
2293
        if (pdpe & PG_PRESENT_MASK) {
2294
            pd_addr = pdpe & 0x3fffffffff000ULL;
2295
            for (l2 = 0; l2 < 512; l2++) {
2296
                cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
2297
                pde = le64_to_cpu(pde);
2298
                end = (l1 << 30) + (l2 << 21);
2299
                if (pde & PG_PRESENT_MASK) {
2300
                    if (pde & PG_PSE_MASK) {
2301
                        prot = pde & (PG_USER_MASK | PG_RW_MASK |
2302
                                      PG_PRESENT_MASK);
2303
                        mem_print(mon, &start, &last_prot, end, prot);
2304
                    } else {
2305
                        pt_addr = pde & 0x3fffffffff000ULL;
2306
                        for (l3 = 0; l3 < 512; l3++) {
2307
                            cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
2308
                            pte = le64_to_cpu(pte);
2309
                            end = (l1 << 30) + (l2 << 21) + (l3 << 12);
2310
                            if (pte & PG_PRESENT_MASK) {
2311
                                prot = pte & pde & (PG_USER_MASK | PG_RW_MASK |
2312
                                                    PG_PRESENT_MASK);
2313
                            } else {
2314
                                prot = 0;
2315
                            }
2316
                            mem_print(mon, &start, &last_prot, end, prot);
2317
                        }
2318
                    }
2319
                } else {
2320
                    prot = 0;
2321
                    mem_print(mon, &start, &last_prot, end, prot);
2322
                }
2323
            }
2324
        } else {
2325
            prot = 0;
2326
            mem_print(mon, &start, &last_prot, end, prot);
2327
        }
2328
    }
2329
    /* Flush last range */
2330
    mem_print(mon, &start, &last_prot, (target_phys_addr_t)1 << 32, 0);
2331
}
2332

    
2333

    
2334
#ifdef TARGET_X86_64
2335
static void mem_info_64(Monitor *mon, CPUState *env)
2336
{
2337
    int prot, last_prot;
2338
    uint64_t l1, l2, l3, l4;
2339
    uint64_t pml4e, pdpe, pde, pte;
2340
    uint64_t pml4_addr, pdp_addr, pd_addr, pt_addr, start, end;
2341

    
2342
    pml4_addr = env->cr[3] & 0x3fffffffff000ULL;
2343
    last_prot = 0;
2344
    start = -1;
2345
    for (l1 = 0; l1 < 512; l1++) {
2346
        cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
2347
        pml4e = le64_to_cpu(pml4e);
2348
        end = l1 << 39;
2349
        if (pml4e & PG_PRESENT_MASK) {
2350
            pdp_addr = pml4e & 0x3fffffffff000ULL;
2351
            for (l2 = 0; l2 < 512; l2++) {
2352
                cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
2353
                pdpe = le64_to_cpu(pdpe);
2354
                end = (l1 << 39) + (l2 << 30);
2355
                if (pdpe & PG_PRESENT_MASK) {
2356
                    if (pdpe & PG_PSE_MASK) {
2357
                        prot = pdpe & (PG_USER_MASK | PG_RW_MASK |
2358
                                       PG_PRESENT_MASK);
2359
                        prot &= pml4e;
2360
                        mem_print(mon, &start, &last_prot, end, prot);
2361
                    } else {
2362
                        pd_addr = pdpe & 0x3fffffffff000ULL;
2363
                        for (l3 = 0; l3 < 512; l3++) {
2364
                            cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
2365
                            pde = le64_to_cpu(pde);
2366
                            end = (l1 << 39) + (l2 << 30) + (l3 << 21);
2367
                            if (pde & PG_PRESENT_MASK) {
2368
                                if (pde & PG_PSE_MASK) {
2369
                                    prot = pde & (PG_USER_MASK | PG_RW_MASK |
2370
                                                  PG_PRESENT_MASK);
2371
                                    prot &= pml4e & pdpe;
2372
                                    mem_print(mon, &start, &last_prot, end, prot);
2373
                                } else {
2374
                                    pt_addr = pde & 0x3fffffffff000ULL;
2375
                                    for (l4 = 0; l4 < 512; l4++) {
2376
                                        cpu_physical_memory_read(pt_addr
2377
                                                                 + l4 * 8,
2378
                                                                 &pte, 8);
2379
                                        pte = le64_to_cpu(pte);
2380
                                        end = (l1 << 39) + (l2 << 30) +
2381
                                            (l3 << 21) + (l4 << 12);
2382
                                        if (pte & PG_PRESENT_MASK) {
2383
                                            prot = pte & (PG_USER_MASK | PG_RW_MASK |
2384
                                                          PG_PRESENT_MASK);
2385
                                            prot &= pml4e & pdpe & pde;
2386
                                        } else {
2387
                                            prot = 0;
2388
                                        }
2389
                                        mem_print(mon, &start, &last_prot, end, prot);
2390
                                    }
2391
                                }
2392
                            } else {
2393
                                prot = 0;
2394
                                mem_print(mon, &start, &last_prot, end, prot);
2395
                            }
2396
                        }
2397
                    }
2398
                } else {
2399
                    prot = 0;
2400
                    mem_print(mon, &start, &last_prot, end, prot);
2401
                }
2402
            }
2403
        } else {
2404
            prot = 0;
2405
            mem_print(mon, &start, &last_prot, end, prot);
2406
        }
2407
    }
2408
    /* Flush last range */
2409
    mem_print(mon, &start, &last_prot, (target_phys_addr_t)1 << 48, 0);
2410
}
2411
#endif
2412

    
2413
static void mem_info(Monitor *mon)
2414
{
2415
    CPUState *env;
2416

    
2417
    env = mon_get_cpu();
2418

    
2419
    if (!(env->cr[0] & CR0_PG_MASK)) {
2420
        monitor_printf(mon, "PG disabled\n");
2421
        return;
2422
    }
2423
    if (env->cr[4] & CR4_PAE_MASK) {
2424
#ifdef TARGET_X86_64
2425
        if (env->hflags & HF_LMA_MASK) {
2426
            mem_info_64(mon, env);
2427
        } else
2428
#endif
2429
        {
2430
            mem_info_pae32(mon, env);
2431
        }
2432
    } else {
2433
        mem_info_32(mon, env);
2434
    }
2435
}
2436
#endif
2437

    
2438
#if defined(TARGET_SH4)
2439

    
2440
static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
2441
{
2442
    monitor_printf(mon, " tlb%i:\t"
2443
                   "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
2444
                   "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
2445
                   "dirty=%hhu writethrough=%hhu\n",
2446
                   idx,
2447
                   tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
2448
                   tlb->v, tlb->sh, tlb->c, tlb->pr,
2449
                   tlb->d, tlb->wt);
2450
}
2451

    
2452
static void tlb_info(Monitor *mon)
2453
{
2454
    CPUState *env = mon_get_cpu();
2455
    int i;
2456

    
2457
    monitor_printf (mon, "ITLB:\n");
2458
    for (i = 0 ; i < ITLB_SIZE ; i++)
2459
        print_tlb (mon, i, &env->itlb[i]);
2460
    monitor_printf (mon, "UTLB:\n");
2461
    for (i = 0 ; i < UTLB_SIZE ; i++)
2462
        print_tlb (mon, i, &env->utlb[i]);
2463
}
2464

    
2465
#endif
2466

    
2467
#if defined(TARGET_SPARC)
2468
static void tlb_info(Monitor *mon)
2469
{
2470
    CPUState *env1 = mon_get_cpu();
2471

    
2472
    dump_mmu((FILE*)mon, (fprintf_function)monitor_printf, env1);
2473
}
2474
#endif
2475

    
2476
static void do_info_mtree(Monitor *mon)
2477
{
2478
    mtree_info((fprintf_function)monitor_printf, mon);
2479
}
2480

    
2481
static void do_info_kvm_print(Monitor *mon, const QObject *data)
2482
{
2483
    QDict *qdict;
2484

    
2485
    qdict = qobject_to_qdict(data);
2486

    
2487
    monitor_printf(mon, "kvm support: ");
2488
    if (qdict_get_bool(qdict, "present")) {
2489
        monitor_printf(mon, "%s\n", qdict_get_bool(qdict, "enabled") ?
2490
                                    "enabled" : "disabled");
2491
    } else {
2492
        monitor_printf(mon, "not compiled\n");
2493
    }
2494
}
2495

    
2496
static void do_info_kvm(Monitor *mon, QObject **ret_data)
2497
{
2498
#ifdef CONFIG_KVM
2499
    *ret_data = qobject_from_jsonf("{ 'enabled': %i, 'present': true }",
2500
                                   kvm_enabled());
2501
#else
2502
    *ret_data = qobject_from_jsonf("{ 'enabled': false, 'present': false }");
2503
#endif
2504
}
2505

    
2506
static void do_info_numa(Monitor *mon)
2507
{
2508
    int i;
2509
    CPUState *env;
2510

    
2511
    monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
2512
    for (i = 0; i < nb_numa_nodes; i++) {
2513
        monitor_printf(mon, "node %d cpus:", i);
2514
        for (env = first_cpu; env != NULL; env = env->next_cpu) {
2515
            if (env->numa_node == i) {
2516
                monitor_printf(mon, " %d", env->cpu_index);
2517
            }
2518
        }
2519
        monitor_printf(mon, "\n");
2520
        monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
2521
            node_mem[i] >> 20);
2522
    }
2523
}
2524

    
2525
#ifdef CONFIG_PROFILER
2526

    
2527
int64_t qemu_time;
2528
int64_t dev_time;
2529

    
2530
static void do_info_profile(Monitor *mon)
2531
{
2532
    int64_t total;
2533
    total = qemu_time;
2534
    if (total == 0)
2535
        total = 1;
2536
    monitor_printf(mon, "async time  %" PRId64 " (%0.3f)\n",
2537
                   dev_time, dev_time / (double)get_ticks_per_sec());
2538
    monitor_printf(mon, "qemu time   %" PRId64 " (%0.3f)\n",
2539
                   qemu_time, qemu_time / (double)get_ticks_per_sec());
2540
    qemu_time = 0;
2541
    dev_time = 0;
2542
}
2543
#else
2544
static void do_info_profile(Monitor *mon)
2545
{
2546
    monitor_printf(mon, "Internal profiler not compiled\n");
2547
}
2548
#endif
2549

    
2550
/* Capture support */
2551
static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2552

    
2553
static void do_info_capture(Monitor *mon)
2554
{
2555
    int i;
2556
    CaptureState *s;
2557

    
2558
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2559
        monitor_printf(mon, "[%d]: ", i);
2560
        s->ops.info (s->opaque);
2561
    }
2562
}
2563

    
2564
#ifdef HAS_AUDIO
2565
static void do_stop_capture(Monitor *mon, const QDict *qdict)
2566
{
2567
    int i;
2568
    int n = qdict_get_int(qdict, "n");
2569
    CaptureState *s;
2570

    
2571
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2572
        if (i == n) {
2573
            s->ops.destroy (s->opaque);
2574
            QLIST_REMOVE (s, entries);
2575
            g_free (s);
2576
            return;
2577
        }
2578
    }
2579
}
2580

    
2581
static void do_wav_capture(Monitor *mon, const QDict *qdict)
2582
{
2583
    const char *path = qdict_get_str(qdict, "path");
2584
    int has_freq = qdict_haskey(qdict, "freq");
2585
    int freq = qdict_get_try_int(qdict, "freq", -1);
2586
    int has_bits = qdict_haskey(qdict, "bits");
2587
    int bits = qdict_get_try_int(qdict, "bits", -1);
2588
    int has_channels = qdict_haskey(qdict, "nchannels");
2589
    int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2590
    CaptureState *s;
2591

    
2592
    s = g_malloc0 (sizeof (*s));
2593

    
2594
    freq = has_freq ? freq : 44100;
2595
    bits = has_bits ? bits : 16;
2596
    nchannels = has_channels ? nchannels : 2;
2597

    
2598
    if (wav_start_capture (s, path, freq, bits, nchannels)) {
2599
        monitor_printf(mon, "Failed to add wave capture\n");
2600
        g_free (s);
2601
        return;
2602
    }
2603
    QLIST_INSERT_HEAD (&capture_head, s, entries);
2604
}
2605
#endif
2606

    
2607
#if defined(TARGET_I386)
2608
static int do_inject_nmi(Monitor *mon, const QDict *qdict, QObject **ret_data)
2609
{
2610
    CPUState *env;
2611

    
2612
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
2613
        cpu_interrupt(env, CPU_INTERRUPT_NMI);
2614
    }
2615

    
2616
    return 0;
2617
}
2618
#else
2619
static int do_inject_nmi(Monitor *mon, const QDict *qdict, QObject **ret_data)
2620
{
2621
    qerror_report(QERR_UNSUPPORTED);
2622
    return -1;
2623
}
2624
#endif
2625

    
2626
static void do_info_status_print(Monitor *mon, const QObject *data)
2627
{
2628
    QDict *qdict;
2629
    const char *status;
2630

    
2631
    qdict = qobject_to_qdict(data);
2632

    
2633
    monitor_printf(mon, "VM status: ");
2634
    if (qdict_get_bool(qdict, "running")) {
2635
        monitor_printf(mon, "running");
2636
        if (qdict_get_bool(qdict, "singlestep")) {
2637
            monitor_printf(mon, " (single step mode)");
2638
        }
2639
    } else {
2640
        monitor_printf(mon, "paused");
2641
    }
2642

    
2643
    status = qdict_get_str(qdict, "status");
2644
    if (strcmp(status, "paused") && strcmp(status, "running")) {
2645
        monitor_printf(mon, " (%s)", status);
2646
    }
2647

    
2648
    monitor_printf(mon, "\n");
2649
}
2650

    
2651
static void do_info_status(Monitor *mon, QObject **ret_data)
2652
{
2653
    *ret_data = qobject_from_jsonf("{ 'running': %i, 'singlestep': %i, 'status': %s }", runstate_is_running(), singlestep, runstate_as_string());
2654
}
2655

    
2656
static qemu_acl *find_acl(Monitor *mon, const char *name)
2657
{
2658
    qemu_acl *acl = qemu_acl_find(name);
2659

    
2660
    if (!acl) {
2661
        monitor_printf(mon, "acl: unknown list '%s'\n", name);
2662
    }
2663
    return acl;
2664
}
2665

    
2666
static void do_acl_show(Monitor *mon, const QDict *qdict)
2667
{
2668
    const char *aclname = qdict_get_str(qdict, "aclname");
2669
    qemu_acl *acl = find_acl(mon, aclname);
2670
    qemu_acl_entry *entry;
2671
    int i = 0;
2672

    
2673
    if (acl) {
2674
        monitor_printf(mon, "policy: %s\n",
2675
                       acl->defaultDeny ? "deny" : "allow");
2676
        QTAILQ_FOREACH(entry, &acl->entries, next) {
2677
            i++;
2678
            monitor_printf(mon, "%d: %s %s\n", i,
2679
                           entry->deny ? "deny" : "allow", entry->match);
2680
        }
2681
    }
2682
}
2683

    
2684
static void do_acl_reset(Monitor *mon, const QDict *qdict)
2685
{
2686
    const char *aclname = qdict_get_str(qdict, "aclname");
2687
    qemu_acl *acl = find_acl(mon, aclname);
2688

    
2689
    if (acl) {
2690
        qemu_acl_reset(acl);
2691
        monitor_printf(mon, "acl: removed all rules\n");
2692
    }
2693
}
2694

    
2695
static void do_acl_policy(Monitor *mon, const QDict *qdict)
2696
{
2697
    const char *aclname = qdict_get_str(qdict, "aclname");
2698
    const char *policy = qdict_get_str(qdict, "policy");
2699
    qemu_acl *acl = find_acl(mon, aclname);
2700

    
2701
    if (acl) {
2702
        if (strcmp(policy, "allow") == 0) {
2703
            acl->defaultDeny = 0;
2704
            monitor_printf(mon, "acl: policy set to 'allow'\n");
2705
        } else if (strcmp(policy, "deny") == 0) {
2706
            acl->defaultDeny = 1;
2707
            monitor_printf(mon, "acl: policy set to 'deny'\n");
2708
        } else {
2709
            monitor_printf(mon, "acl: unknown policy '%s', "
2710
                           "expected 'deny' or 'allow'\n", policy);
2711
        }
2712
    }
2713
}
2714

    
2715
static void do_acl_add(Monitor *mon, const QDict *qdict)
2716
{
2717
    const char *aclname = qdict_get_str(qdict, "aclname");
2718
    const char *match = qdict_get_str(qdict, "match");
2719
    const char *policy = qdict_get_str(qdict, "policy");
2720
    int has_index = qdict_haskey(qdict, "index");
2721
    int index = qdict_get_try_int(qdict, "index", -1);
2722
    qemu_acl *acl = find_acl(mon, aclname);
2723
    int deny, ret;
2724

    
2725
    if (acl) {
2726
        if (strcmp(policy, "allow") == 0) {
2727
            deny = 0;
2728
        } else if (strcmp(policy, "deny") == 0) {
2729
            deny = 1;
2730
        } else {
2731
            monitor_printf(mon, "acl: unknown policy '%s', "
2732
                           "expected 'deny' or 'allow'\n", policy);
2733
            return;
2734
        }
2735
        if (has_index)
2736
            ret = qemu_acl_insert(acl, deny, match, index);
2737
        else
2738
            ret = qemu_acl_append(acl, deny, match);
2739
        if (ret < 0)
2740
            monitor_printf(mon, "acl: unable to add acl entry\n");
2741
        else
2742
            monitor_printf(mon, "acl: added rule at position %d\n", ret);
2743
    }
2744
}
2745

    
2746
static void do_acl_remove(Monitor *mon, const QDict *qdict)
2747
{
2748
    const char *aclname = qdict_get_str(qdict, "aclname");
2749
    const char *match = qdict_get_str(qdict, "match");
2750
    qemu_acl *acl = find_acl(mon, aclname);
2751
    int ret;
2752

    
2753
    if (acl) {
2754
        ret = qemu_acl_remove(acl, match);
2755
        if (ret < 0)
2756
            monitor_printf(mon, "acl: no matching acl entry\n");
2757
        else
2758
            monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2759
    }
2760
}
2761

    
2762
#if defined(TARGET_I386)
2763
static void do_inject_mce(Monitor *mon, const QDict *qdict)
2764
{
2765
    CPUState *cenv;
2766
    int cpu_index = qdict_get_int(qdict, "cpu_index");
2767
    int bank = qdict_get_int(qdict, "bank");
2768
    uint64_t status = qdict_get_int(qdict, "status");
2769
    uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2770
    uint64_t addr = qdict_get_int(qdict, "addr");
2771
    uint64_t misc = qdict_get_int(qdict, "misc");
2772
    int flags = MCE_INJECT_UNCOND_AO;
2773

    
2774
    if (qdict_get_try_bool(qdict, "broadcast", 0)) {
2775
        flags |= MCE_INJECT_BROADCAST;
2776
    }
2777
    for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu) {
2778
        if (cenv->cpu_index == cpu_index) {
2779
            cpu_x86_inject_mce(mon, cenv, bank, status, mcg_status, addr, misc,
2780
                               flags);
2781
            break;
2782
        }
2783
    }
2784
}
2785
#endif
2786

    
2787
static int do_getfd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2788
{
2789
    const char *fdname = qdict_get_str(qdict, "fdname");
2790
    mon_fd_t *monfd;
2791
    int fd;
2792

    
2793
    fd = qemu_chr_fe_get_msgfd(mon->chr);
2794
    if (fd == -1) {
2795
        qerror_report(QERR_FD_NOT_SUPPLIED);
2796
        return -1;
2797
    }
2798

    
2799
    if (qemu_isdigit(fdname[0])) {
2800
        qerror_report(QERR_INVALID_PARAMETER_VALUE, "fdname",
2801
                      "a name not starting with a digit");
2802
        return -1;
2803
    }
2804

    
2805
    QLIST_FOREACH(monfd, &mon->fds, next) {
2806
        if (strcmp(monfd->name, fdname) != 0) {
2807
            continue;
2808
        }
2809

    
2810
        close(monfd->fd);
2811
        monfd->fd = fd;
2812
        return 0;
2813
    }
2814

    
2815
    monfd = g_malloc0(sizeof(mon_fd_t));
2816
    monfd->name = g_strdup(fdname);
2817
    monfd->fd = fd;
2818

    
2819
    QLIST_INSERT_HEAD(&mon->fds, monfd, next);
2820
    return 0;
2821
}
2822

    
2823
static int do_closefd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2824
{
2825
    const char *fdname = qdict_get_str(qdict, "fdname");
2826
    mon_fd_t *monfd;
2827

    
2828
    QLIST_FOREACH(monfd, &mon->fds, next) {
2829
        if (strcmp(monfd->name, fdname) != 0) {
2830
            continue;
2831
        }
2832

    
2833
        QLIST_REMOVE(monfd, next);
2834
        close(monfd->fd);
2835
        g_free(monfd->name);
2836
        g_free(monfd);
2837
        return 0;
2838
    }
2839

    
2840
    qerror_report(QERR_FD_NOT_FOUND, fdname);
2841
    return -1;
2842
}
2843

    
2844
static void do_loadvm(Monitor *mon, const QDict *qdict)
2845
{
2846
    int saved_vm_running  = runstate_is_running();
2847
    const char *name = qdict_get_str(qdict, "name");
2848

    
2849
    vm_stop(RSTATE_RESTORE);
2850

    
2851
    if (load_vmstate(name) == 0 && saved_vm_running) {
2852
        vm_start();
2853
    }
2854
}
2855

    
2856
int monitor_get_fd(Monitor *mon, const char *fdname)
2857
{
2858
    mon_fd_t *monfd;
2859

    
2860
    QLIST_FOREACH(monfd, &mon->fds, next) {
2861
        int fd;
2862

    
2863
        if (strcmp(monfd->name, fdname) != 0) {
2864
            continue;
2865
        }
2866

    
2867
        fd = monfd->fd;
2868

    
2869
        /* caller takes ownership of fd */
2870
        QLIST_REMOVE(monfd, next);
2871
        g_free(monfd->name);
2872
        g_free(monfd);
2873

    
2874
        return fd;
2875
    }
2876

    
2877
    return -1;
2878
}
2879

    
2880
static const mon_cmd_t mon_cmds[] = {
2881
#include "hmp-commands.h"
2882
    { NULL, NULL, },
2883
};
2884

    
2885
/* Please update hmp-commands.hx when adding or changing commands */
2886
static const mon_cmd_t info_cmds[] = {
2887
    {
2888
        .name       = "version",
2889
        .args_type  = "",
2890
        .params     = "",
2891
        .help       = "show the version of QEMU",
2892
        .user_print = do_info_version_print,
2893
        .mhandler.info_new = do_info_version,
2894
    },
2895
    {
2896
        .name       = "network",
2897
        .args_type  = "",
2898
        .params     = "",
2899
        .help       = "show the network state",
2900
        .mhandler.info = do_info_network,
2901
    },
2902
    {
2903
        .name       = "chardev",
2904
        .args_type  = "",
2905
        .params     = "",
2906
        .help       = "show the character devices",
2907
        .user_print = qemu_chr_info_print,
2908
        .mhandler.info_new = qemu_chr_info,
2909
    },
2910
    {
2911
        .name       = "block",
2912
        .args_type  = "",
2913
        .params     = "",
2914
        .help       = "show the block devices",
2915
        .user_print = bdrv_info_print,
2916
        .mhandler.info_new = bdrv_info,
2917
    },
2918
    {
2919
        .name       = "blockstats",
2920
        .args_type  = "",
2921
        .params     = "",
2922
        .help       = "show block device statistics",
2923
        .user_print = bdrv_stats_print,
2924
        .mhandler.info_new = bdrv_info_stats,
2925
    },
2926
    {
2927
        .name       = "registers",
2928
        .args_type  = "",
2929
        .params     = "",
2930
        .help       = "show the cpu registers",
2931
        .mhandler.info = do_info_registers,
2932
    },
2933
    {
2934
        .name       = "cpus",
2935
        .args_type  = "",
2936
        .params     = "",
2937
        .help       = "show infos for each CPU",
2938
        .user_print = monitor_print_cpus,
2939
        .mhandler.info_new = do_info_cpus,
2940
    },
2941
    {
2942
        .name       = "history",
2943
        .args_type  = "",
2944
        .params     = "",
2945
        .help       = "show the command line history",
2946
        .mhandler.info = do_info_history,
2947
    },
2948
    {
2949
        .name       = "irq",
2950
        .args_type  = "",
2951
        .params     = "",
2952
        .help       = "show the interrupts statistics (if available)",
2953
        .mhandler.info = irq_info,
2954
    },
2955
    {
2956
        .name       = "pic",
2957
        .args_type  = "",
2958
        .params     = "",
2959
        .help       = "show i8259 (PIC) state",
2960
        .mhandler.info = pic_info,
2961
    },
2962
    {
2963
        .name       = "pci",
2964
        .args_type  = "",
2965
        .params     = "",
2966
        .help       = "show PCI info",
2967
        .user_print = do_pci_info_print,
2968
        .mhandler.info_new = do_pci_info,
2969
    },
2970
#if defined(TARGET_I386) || defined(TARGET_SH4) || defined(TARGET_SPARC)
2971
    {
2972
        .name       = "tlb",
2973
        .args_type  = "",
2974
        .params     = "",
2975
        .help       = "show virtual to physical memory mappings",
2976
        .mhandler.info = tlb_info,
2977
    },
2978
#endif
2979
#if defined(TARGET_I386)
2980
    {
2981
        .name       = "mem",
2982
        .args_type  = "",
2983
        .params     = "",
2984
        .help       = "show the active virtual memory mappings",
2985
        .mhandler.info = mem_info,
2986
    },
2987
#endif
2988
    {
2989
        .name       = "mtree",
2990
        .args_type  = "",
2991
        .params     = "",
2992
        .help       = "show memory tree",
2993
        .mhandler.info = do_info_mtree,
2994
    },
2995
    {
2996
        .name       = "jit",
2997
        .args_type  = "",
2998
        .params     = "",
2999
        .help       = "show dynamic compiler info",
3000
        .mhandler.info = do_info_jit,
3001
    },
3002
    {
3003
        .name       = "kvm",
3004
        .args_type  = "",
3005
        .params     = "",
3006
        .help       = "show KVM information",
3007
        .user_print = do_info_kvm_print,
3008
        .mhandler.info_new = do_info_kvm,
3009
    },
3010
    {
3011
        .name       = "numa",
3012
        .args_type  = "",
3013
        .params     = "",
3014
        .help       = "show NUMA information",
3015
        .mhandler.info = do_info_numa,
3016
    },
3017
    {
3018
        .name       = "usb",
3019
        .args_type  = "",
3020
        .params     = "",
3021
        .help       = "show guest USB devices",
3022
        .mhandler.info = usb_info,
3023
    },
3024
    {
3025
        .name       = "usbhost",
3026
        .args_type  = "",
3027
        .params     = "",
3028
        .help       = "show host USB devices",
3029
        .mhandler.info = usb_host_info,
3030
    },
3031
    {
3032
        .name       = "profile",
3033
        .args_type  = "",
3034
        .params     = "",
3035
        .help       = "show profiling information",
3036
        .mhandler.info = do_info_profile,
3037
    },
3038
    {
3039
        .name       = "capture",
3040
        .args_type  = "",
3041
        .params     = "",
3042
        .help       = "show capture information",
3043
        .mhandler.info = do_info_capture,
3044
    },
3045
    {
3046
        .name       = "snapshots",
3047
        .args_type  = "",
3048
        .params     = "",
3049
        .help       = "show the currently saved VM snapshots",
3050
        .mhandler.info = do_info_snapshots,
3051
    },
3052
    {
3053
        .name       = "status",
3054
        .args_type  = "",
3055
        .params     = "",
3056
        .help       = "show the current VM status (running|paused)",
3057
        .user_print = do_info_status_print,
3058
        .mhandler.info_new = do_info_status,
3059
    },
3060
    {
3061
        .name       = "pcmcia",
3062
        .args_type  = "",
3063
        .params     = "",
3064
        .help       = "show guest PCMCIA status",
3065
        .mhandler.info = pcmcia_info,
3066
    },
3067
    {
3068
        .name       = "mice",
3069
        .args_type  = "",
3070
        .params     = "",
3071
        .help       = "show which guest mouse is receiving events",
3072
        .user_print = do_info_mice_print,
3073
        .mhandler.info_new = do_info_mice,
3074
    },
3075
    {
3076
        .name       = "vnc",
3077
        .args_type  = "",
3078
        .params     = "",
3079
        .help       = "show the vnc server status",
3080
        .user_print = do_info_vnc_print,
3081
        .mhandler.info_new = do_info_vnc,
3082
    },
3083
#if defined(CONFIG_SPICE)
3084
    {
3085
        .name       = "spice",
3086
        .args_type  = "",
3087
        .params     = "",
3088
        .help       = "show the spice server status",
3089
        .user_print = do_info_spice_print,
3090
        .mhandler.info_new = do_info_spice,
3091
    },
3092
#endif
3093
    {
3094
        .name       = "name",
3095
        .args_type  = "",
3096
        .params     = "",
3097
        .help       = "show the current VM name",
3098
        .user_print = do_info_name_print,
3099
        .mhandler.info_new = do_info_name,
3100
    },
3101
    {
3102
        .name       = "uuid",
3103
        .args_type  = "",
3104
        .params     = "",
3105
        .help       = "show the current VM UUID",
3106
        .user_print = do_info_uuid_print,
3107
        .mhandler.info_new = do_info_uuid,
3108
    },
3109
#if defined(TARGET_PPC)
3110
    {
3111
        .name       = "cpustats",
3112
        .args_type  = "",
3113
        .params     = "",
3114
        .help       = "show CPU statistics",
3115
        .mhandler.info = do_info_cpu_stats,
3116
    },
3117
#endif
3118
#if defined(CONFIG_SLIRP)
3119
    {
3120
        .name       = "usernet",
3121
        .args_type  = "",
3122
        .params     = "",
3123
        .help       = "show user network stack connection states",
3124
        .mhandler.info = do_info_usernet,
3125
    },
3126
#endif
3127
    {
3128
        .name       = "migrate",
3129
        .args_type  = "",
3130
        .params     = "",
3131
        .help       = "show migration status",
3132
        .user_print = do_info_migrate_print,
3133
        .mhandler.info_new = do_info_migrate,
3134
    },
3135
    {
3136
        .name       = "balloon",
3137
        .args_type  = "",
3138
        .params     = "",
3139
        .help       = "show balloon information",
3140
        .user_print = monitor_print_balloon,
3141
        .mhandler.info_async = do_info_balloon,
3142
        .flags      = MONITOR_CMD_ASYNC,
3143
    },
3144
    {
3145
        .name       = "qtree",
3146
        .args_type  = "",
3147
        .params     = "",
3148
        .help       = "show device tree",
3149
        .mhandler.info = do_info_qtree,
3150
    },
3151
    {
3152
        .name       = "qdm",
3153
        .args_type  = "",
3154
        .params     = "",
3155
        .help       = "show qdev device model list",
3156
        .mhandler.info = do_info_qdm,
3157
    },
3158
    {
3159
        .name       = "roms",
3160
        .args_type  = "",
3161
        .params     = "",
3162
        .help       = "show roms",
3163
        .mhandler.info = do_info_roms,
3164
    },
3165
#if defined(CONFIG_TRACE_SIMPLE)
3166
    {
3167
        .name       = "trace",
3168
        .args_type  = "",
3169
        .params     = "",
3170
        .help       = "show current contents of trace buffer",
3171
        .mhandler.info = do_info_trace,
3172
    },
3173
#endif
3174
    {
3175
        .name       = "trace-events",
3176
        .args_type  = "",
3177
        .params     = "",
3178
        .help       = "show available trace-events & their state",
3179
        .mhandler.info = do_trace_print_events,
3180
    },
3181
    {
3182
        .name       = NULL,
3183
    },
3184
};
3185

    
3186
static const mon_cmd_t qmp_cmds[] = {
3187
#include "qmp-commands.h"
3188
    { /* NULL */ },
3189
};
3190

    
3191
static const mon_cmd_t qmp_query_cmds[] = {
3192
    {
3193
        .name       = "version",
3194
        .args_type  = "",
3195
        .params     = "",
3196
        .help       = "show the version of QEMU",
3197
        .user_print = do_info_version_print,
3198
        .mhandler.info_new = do_info_version,
3199
    },
3200
    {
3201
        .name       = "commands",
3202
        .args_type  = "",
3203
        .params     = "",
3204
        .help       = "list QMP available commands",
3205
        .user_print = monitor_user_noop,
3206
        .mhandler.info_new = do_info_commands,
3207
    },
3208
    {
3209
        .name       = "chardev",
3210
        .args_type  = "",
3211
        .params     = "",
3212
        .help       = "show the character devices",
3213
        .user_print = qemu_chr_info_print,
3214
        .mhandler.info_new = qemu_chr_info,
3215
    },
3216
    {
3217
        .name       = "block",
3218
        .args_type  = "",
3219
        .params     = "",
3220
        .help       = "show the block devices",
3221
        .user_print = bdrv_info_print,
3222
        .mhandler.info_new = bdrv_info,
3223
    },
3224
    {
3225
        .name       = "blockstats",
3226
        .args_type  = "",
3227
        .params     = "",
3228
        .help       = "show block device statistics",
3229
        .user_print = bdrv_stats_print,
3230
        .mhandler.info_new = bdrv_info_stats,
3231
    },
3232
    {
3233
        .name       = "cpus",
3234
        .args_type  = "",
3235
        .params     = "",
3236
        .help       = "show infos for each CPU",
3237
        .user_print = monitor_print_cpus,
3238
        .mhandler.info_new = do_info_cpus,
3239
    },
3240
    {
3241
        .name       = "pci",
3242
        .args_type  = "",
3243
        .params     = "",
3244
        .help       = "show PCI info",
3245
        .user_print = do_pci_info_print,
3246
        .mhandler.info_new = do_pci_info,
3247
    },
3248
    {
3249
        .name       = "kvm",
3250
        .args_type  = "",
3251
        .params     = "",
3252
        .help       = "show KVM information",
3253
        .user_print = do_info_kvm_print,
3254
        .mhandler.info_new = do_info_kvm,
3255
    },
3256
    {
3257
        .name       = "status",
3258
        .args_type  = "",
3259
        .params     = "",
3260
        .help       = "show the current VM status (running|paused)",
3261
        .user_print = do_info_status_print,
3262
        .mhandler.info_new = do_info_status,
3263
    },
3264
    {
3265
        .name       = "mice",
3266
        .args_type  = "",
3267
        .params     = "",
3268
        .help       = "show which guest mouse is receiving events",
3269
        .user_print = do_info_mice_print,
3270
        .mhandler.info_new = do_info_mice,
3271
    },
3272
    {
3273
        .name       = "vnc",
3274
        .args_type  = "",
3275
        .params     = "",
3276
        .help       = "show the vnc server status",
3277
        .user_print = do_info_vnc_print,
3278
        .mhandler.info_new = do_info_vnc,
3279
    },
3280
#if defined(CONFIG_SPICE)
3281
    {
3282
        .name       = "spice",
3283
        .args_type  = "",
3284
        .params     = "",
3285
        .help       = "show the spice server status",
3286
        .user_print = do_info_spice_print,
3287
        .mhandler.info_new = do_info_spice,
3288
    },
3289
#endif
3290
    {
3291
        .name       = "name",
3292
        .args_type  = "",
3293
        .params     = "",
3294
        .help       = "show the current VM name",
3295
        .user_print = do_info_name_print,
3296
        .mhandler.info_new = do_info_name,
3297
    },
3298
    {
3299
        .name       = "uuid",
3300
        .args_type  = "",
3301
        .params     = "",
3302
        .help       = "show the current VM UUID",
3303
        .user_print = do_info_uuid_print,
3304
        .mhandler.info_new = do_info_uuid,
3305
    },
3306
    {
3307
        .name       = "migrate",
3308
        .args_type  = "",
3309
        .params     = "",
3310
        .help       = "show migration status",
3311
        .user_print = do_info_migrate_print,
3312
        .mhandler.info_new = do_info_migrate,
3313
    },
3314
    {
3315
        .name       = "balloon",
3316
        .args_type  = "",
3317
        .params     = "",
3318
        .help       = "show balloon information",
3319
        .user_print = monitor_print_balloon,
3320
        .mhandler.info_async = do_info_balloon,
3321
        .flags      = MONITOR_CMD_ASYNC,
3322
    },
3323
    { /* NULL */ },
3324
};
3325

    
3326
/*******************************************************************/
3327

    
3328
static const char *pch;
3329
static jmp_buf expr_env;
3330

    
3331
#define MD_TLONG 0
3332
#define MD_I32   1
3333

    
3334
typedef struct MonitorDef {
3335
    const char *name;
3336
    int offset;
3337
    target_long (*get_value)(const struct MonitorDef *md, int val);
3338
    int type;
3339
} MonitorDef;
3340

    
3341
#if defined(TARGET_I386)
3342
static target_long monitor_get_pc (const struct MonitorDef *md, int val)
3343
{
3344
    CPUState *env = mon_get_cpu();
3345
    return env->eip + env->segs[R_CS].base;
3346
}
3347
#endif
3348

    
3349
#if defined(TARGET_PPC)
3350
static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
3351
{
3352
    CPUState *env = mon_get_cpu();
3353
    unsigned int u;
3354
    int i;
3355

    
3356
    u = 0;
3357
    for (i = 0; i < 8; i++)
3358
        u |= env->crf[i] << (32 - (4 * i));
3359

    
3360
    return u;
3361
}
3362

    
3363
static target_long monitor_get_msr (const struct MonitorDef *md, int val)
3364
{
3365
    CPUState *env = mon_get_cpu();
3366
    return env->msr;
3367
}
3368

    
3369
static target_long monitor_get_xer (const struct MonitorDef *md, int val)
3370
{
3371
    CPUState *env = mon_get_cpu();
3372
    return env->xer;
3373
}
3374

    
3375
static target_long monitor_get_decr (const struct MonitorDef *md, int val)
3376
{
3377
    CPUState *env = mon_get_cpu();
3378
    return cpu_ppc_load_decr(env);
3379
}
3380

    
3381
static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
3382
{
3383
    CPUState *env = mon_get_cpu();
3384
    return cpu_ppc_load_tbu(env);
3385
}
3386

    
3387
static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
3388
{
3389
    CPUState *env = mon_get_cpu();
3390
    return cpu_ppc_load_tbl(env);
3391
}
3392
#endif
3393

    
3394
#if defined(TARGET_SPARC)
3395
#ifndef TARGET_SPARC64
3396
static target_long monitor_get_psr (const struct MonitorDef *md, int val)
3397
{
3398
    CPUState *env = mon_get_cpu();
3399

    
3400
    return cpu_get_psr(env);
3401
}
3402
#endif
3403

    
3404
static target_long monitor_get_reg(const struct MonitorDef *md, int val)
3405
{
3406
    CPUState *env = mon_get_cpu();
3407
    return env->regwptr[val];
3408
}
3409
#endif
3410

    
3411
static const MonitorDef monitor_defs[] = {
3412
#ifdef TARGET_I386
3413

    
3414
#define SEG(name, seg) \
3415
    { name, offsetof(CPUState, segs[seg].selector), NULL, MD_I32 },\
3416
    { name ".base", offsetof(CPUState, segs[seg].base) },\
3417
    { name ".limit", offsetof(CPUState, segs[seg].limit), NULL, MD_I32 },
3418

    
3419
    { "eax", offsetof(CPUState, regs[0]) },
3420
    { "ecx", offsetof(CPUState, regs[1]) },
3421
    { "edx", offsetof(CPUState, regs[2]) },
3422
    { "ebx", offsetof(CPUState, regs[3]) },
3423
    { "esp|sp", offsetof(CPUState, regs[4]) },
3424
    { "ebp|fp", offsetof(CPUState, regs[5]) },
3425
    { "esi", offsetof(CPUState, regs[6]) },
3426
    { "edi", offsetof(CPUState, regs[7]) },
3427
#ifdef TARGET_X86_64
3428
    { "r8", offsetof(CPUState, regs[8]) },
3429
    { "r9", offsetof(CPUState, regs[9]) },
3430
    { "r10", offsetof(CPUState, regs[10]) },
3431
    { "r11", offsetof(CPUState, regs[11]) },
3432
    { "r12", offsetof(CPUState, regs[12]) },
3433
    { "r13", offsetof(CPUState, regs[13]) },
3434
    { "r14", offsetof(CPUState, regs[14]) },
3435
    { "r15", offsetof(CPUState, regs[15]) },
3436
#endif
3437
    { "eflags", offsetof(CPUState, eflags) },
3438
    { "eip", offsetof(CPUState, eip) },
3439
    SEG("cs", R_CS)
3440
    SEG("ds", R_DS)
3441
    SEG("es", R_ES)
3442
    SEG("ss", R_SS)
3443
    SEG("fs", R_FS)
3444
    SEG("gs", R_GS)
3445
    { "pc", 0, monitor_get_pc, },
3446
#elif defined(TARGET_PPC)
3447
    /* General purpose registers */
3448
    { "r0", offsetof(CPUState, gpr[0]) },
3449
    { "r1", offsetof(CPUState, gpr[1]) },
3450
    { "r2", offsetof(CPUState, gpr[2]) },
3451
    { "r3", offsetof(CPUState, gpr[3]) },
3452
    { "r4", offsetof(CPUState, gpr[4]) },
3453
    { "r5", offsetof(CPUState, gpr[5]) },
3454
    { "r6", offsetof(CPUState, gpr[6]) },
3455
    { "r7", offsetof(CPUState, gpr[7]) },
3456
    { "r8", offsetof(CPUState, gpr[8]) },
3457
    { "r9", offsetof(CPUState, gpr[9]) },
3458
    { "r10", offsetof(CPUState, gpr[10]) },
3459
    { "r11", offsetof(CPUState, gpr[11]) },
3460
    { "r12", offsetof(CPUState, gpr[12]) },
3461
    { "r13", offsetof(CPUState, gpr[13]) },
3462
    { "r14", offsetof(CPUState, gpr[14]) },
3463
    { "r15", offsetof(CPUState, gpr[15]) },
3464
    { "r16", offsetof(CPUState, gpr[16]) },
3465
    { "r17", offsetof(CPUState, gpr[17]) },
3466
    { "r18", offsetof(CPUState, gpr[18]) },
3467
    { "r19", offsetof(CPUState, gpr[19]) },
3468
    { "r20", offsetof(CPUState, gpr[20]) },
3469
    { "r21", offsetof(CPUState, gpr[21]) },
3470
    { "r22", offsetof(CPUState, gpr[22]) },
3471
    { "r23", offsetof(CPUState, gpr[23]) },
3472
    { "r24", offsetof(CPUState, gpr[24]) },
3473
    { "r25", offsetof(CPUState, gpr[25]) },
3474
    { "r26", offsetof(CPUState, gpr[26]) },
3475
    { "r27", offsetof(CPUState, gpr[27]) },
3476
    { "r28", offsetof(CPUState, gpr[28]) },
3477
    { "r29", offsetof(CPUState, gpr[29]) },
3478
    { "r30", offsetof(CPUState, gpr[30]) },
3479
    { "r31", offsetof(CPUState, gpr[31]) },
3480
    /* Floating point registers */
3481
    { "f0", offsetof(CPUState, fpr[0]) },
3482
    { "f1", offsetof(CPUState, fpr[1]) },
3483
    { "f2", offsetof(CPUState, fpr[2]) },
3484
    { "f3", offsetof(CPUState, fpr[3]) },
3485
    { "f4", offsetof(CPUState, fpr[4]) },
3486
    { "f5", offsetof(CPUState, fpr[5]) },
3487
    { "f6", offsetof(CPUState, fpr[6]) },
3488
    { "f7", offsetof(CPUState, fpr[7]) },
3489
    { "f8", offsetof(CPUState, fpr[8]) },
3490
    { "f9", offsetof(CPUState, fpr[9]) },
3491
    { "f10", offsetof(CPUState, fpr[10]) },
3492
    { "f11", offsetof(CPUState, fpr[11]) },
3493
    { "f12", offsetof(CPUState, fpr[12]) },
3494
    { "f13", offsetof(CPUState, fpr[13]) },
3495
    { "f14", offsetof(CPUState, fpr[14]) },
3496
    { "f15", offsetof(CPUState, fpr[15]) },
3497
    { "f16", offsetof(CPUState, fpr[16]) },
3498
    { "f17", offsetof(CPUState, fpr[17]) },
3499
    { "f18", offsetof(CPUState, fpr[18]) },
3500
    { "f19", offsetof(CPUState, fpr[19]) },
3501
    { "f20", offsetof(CPUState, fpr[20]) },
3502
    { "f21", offsetof(CPUState, fpr[21]) },
3503
    { "f22", offsetof(CPUState, fpr[22]) },
3504
    { "f23", offsetof(CPUState, fpr[23]) },
3505
    { "f24", offsetof(CPUState, fpr[24]) },
3506
    { "f25", offsetof(CPUState, fpr[25]) },
3507
    { "f26", offsetof(CPUState, fpr[26]) },
3508
    { "f27", offsetof(CPUState, fpr[27]) },
3509
    { "f28", offsetof(CPUState, fpr[28]) },
3510
    { "f29", offsetof(CPUState, fpr[29]) },
3511
    { "f30", offsetof(CPUState, fpr[30]) },
3512
    { "f31", offsetof(CPUState, fpr[31]) },
3513
    { "fpscr", offsetof(CPUState, fpscr) },
3514
    /* Next instruction pointer */
3515
    { "nip|pc", offsetof(CPUState, nip) },
3516
    { "lr", offsetof(CPUState, lr) },
3517
    { "ctr", offsetof(CPUState, ctr) },
3518
    { "decr", 0, &monitor_get_decr, },
3519
    { "ccr", 0, &monitor_get_ccr, },
3520
    /* Machine state register */
3521
    { "msr", 0, &monitor_get_msr, },
3522
    { "xer", 0, &monitor_get_xer, },
3523
    { "tbu", 0, &monitor_get_tbu, },
3524
    { "tbl", 0, &monitor_get_tbl, },
3525
#if defined(TARGET_PPC64)
3526
    /* Address space register */
3527
    { "asr", offsetof(CPUState, asr) },
3528
#endif
3529
    /* Segment registers */
3530
    { "sdr1", offsetof(CPUState, spr[SPR_SDR1]) },
3531
    { "sr0", offsetof(CPUState, sr[0]) },
3532
    { "sr1", offsetof(CPUState, sr[1]) },
3533
    { "sr2", offsetof(CPUState, sr[2]) },
3534
    { "sr3", offsetof(CPUState, sr[3]) },
3535
    { "sr4", offsetof(CPUState, sr[4]) },
3536
    { "sr5", offsetof(CPUState, sr[5]) },
3537
    { "sr6", offsetof(CPUState, sr[6]) },
3538
    { "sr7", offsetof(CPUState, sr[7]) },
3539
    { "sr8", offsetof(CPUState, sr[8]) },
3540
    { "sr9", offsetof(CPUState, sr[9]) },
3541
    { "sr10", offsetof(CPUState, sr[10]) },
3542
    { "sr11", offsetof(CPUState, sr[11]) },
3543
    { "sr12", offsetof(CPUState, sr[12]) },
3544
    { "sr13", offsetof(CPUState, sr[13]) },
3545
    { "sr14", offsetof(CPUState, sr[14]) },
3546
    { "sr15", offsetof(CPUState, sr[15]) },
3547
    /* Too lazy to put BATs... */
3548
    { "pvr", offsetof(CPUState, spr[SPR_PVR]) },
3549

    
3550
    { "srr0", offsetof(CPUState, spr[SPR_SRR0]) },
3551
    { "srr1", offsetof(CPUState, spr[SPR_SRR1]) },
3552
    { "sprg0", offsetof(CPUState, spr[SPR_SPRG0]) },
3553
    { "sprg1", offsetof(CPUState, spr[SPR_SPRG1]) },
3554
    { "sprg2", offsetof(CPUState, spr[SPR_SPRG2]) },
3555
    { "sprg3", offsetof(CPUState, spr[SPR_SPRG3]) },
3556
    { "sprg4", offsetof(CPUState, spr[SPR_SPRG4]) },
3557
    { "sprg5", offsetof(CPUState, spr[SPR_SPRG5]) },
3558
    { "sprg6", offsetof(CPUState, spr[SPR_SPRG6]) },
3559
    { "sprg7", offsetof(CPUState, spr[SPR_SPRG7]) },
3560
    { "pid", offsetof(CPUState, spr[SPR_BOOKE_PID]) },
3561
    { "csrr0", offsetof(CPUState, spr[SPR_BOOKE_CSRR0]) },
3562
    { "csrr1", offsetof(CPUState, spr[SPR_BOOKE_CSRR1]) },
3563
    { "esr", offsetof(CPUState, spr[SPR_BOOKE_ESR]) },
3564
    { "dear", offsetof(CPUState, spr[SPR_BOOKE_DEAR]) },
3565
    { "mcsr", offsetof(CPUState, spr[SPR_BOOKE_MCSR]) },
3566
    { "tsr", offsetof(CPUState, spr[SPR_BOOKE_TSR]) },
3567
    { "tcr", offsetof(CPUState, spr[SPR_BOOKE_TCR]) },
3568
    { "vrsave", offsetof(CPUState, spr[SPR_VRSAVE]) },
3569
    { "pir", offsetof(CPUState, spr[SPR_BOOKE_PIR]) },
3570
    { "mcsrr0", offsetof(CPUState, spr[SPR_BOOKE_MCSRR0]) },
3571
    { "mcsrr1", offsetof(CPUState, spr[SPR_BOOKE_MCSRR1]) },
3572
    { "decar", offsetof(CPUState, spr[SPR_BOOKE_DECAR]) },
3573
    { "ivpr", offsetof(CPUState, spr[SPR_BOOKE_IVPR]) },
3574
    { "epcr", offsetof(CPUState, spr[SPR_BOOKE_EPCR]) },
3575
    { "sprg8", offsetof(CPUState, spr[SPR_BOOKE_SPRG8]) },
3576
    { "ivor0", offsetof(CPUState, spr[SPR_BOOKE_IVOR0]) },
3577
    { "ivor1", offsetof(CPUState, spr[SPR_BOOKE_IVOR1]) },
3578
    { "ivor2", offsetof(CPUState, spr[SPR_BOOKE_IVOR2]) },
3579
    { "ivor3", offsetof(CPUState, spr[SPR_BOOKE_IVOR3]) },
3580
    { "ivor4", offsetof(CPUState, spr[SPR_BOOKE_IVOR4]) },
3581
    { "ivor5", offsetof(CPUState, spr[SPR_BOOKE_IVOR5]) },
3582
    { "ivor6", offsetof(CPUState, spr[SPR_BOOKE_IVOR6]) },
3583
    { "ivor7", offsetof(CPUState, spr[SPR_BOOKE_IVOR7]) },
3584
    { "ivor8", offsetof(CPUState, spr[SPR_BOOKE_IVOR8]) },
3585
    { "ivor9", offsetof(CPUState, spr[SPR_BOOKE_IVOR9]) },
3586
    { "ivor10", offsetof(CPUState, spr[SPR_BOOKE_IVOR10]) },
3587
    { "ivor11", offsetof(CPUState, spr[SPR_BOOKE_IVOR11]) },
3588
    { "ivor12", offsetof(CPUState, spr[SPR_BOOKE_IVOR12]) },
3589
    { "ivor13", offsetof(CPUState, spr[SPR_BOOKE_IVOR13]) },
3590
    { "ivor14", offsetof(CPUState, spr[SPR_BOOKE_IVOR14]) },
3591
    { "ivor15", offsetof(CPUState, spr[SPR_BOOKE_IVOR15]) },
3592
    { "ivor32", offsetof(CPUState, spr[SPR_BOOKE_IVOR32]) },
3593
    { "ivor33", offsetof(CPUState, spr[SPR_BOOKE_IVOR33]) },
3594
    { "ivor34", offsetof(CPUState, spr[SPR_BOOKE_IVOR34]) },
3595
    { "ivor35", offsetof(CPUState, spr[SPR_BOOKE_IVOR35]) },
3596
    { "ivor36", offsetof(CPUState, spr[SPR_BOOKE_IVOR36]) },
3597
    { "ivor37", offsetof(CPUState, spr[SPR_BOOKE_IVOR37]) },
3598
    { "mas0", offsetof(CPUState, spr[SPR_BOOKE_MAS0]) },
3599
    { "mas1", offsetof(CPUState, spr[SPR_BOOKE_MAS1]) },
3600
    { "mas2", offsetof(CPUState, spr[SPR_BOOKE_MAS2]) },
3601
    { "mas3", offsetof(CPUState, spr[SPR_BOOKE_MAS3]) },
3602
    { "mas4", offsetof(CPUState, spr[SPR_BOOKE_MAS4]) },
3603
    { "mas6", offsetof(CPUState, spr[SPR_BOOKE_MAS6]) },
3604
    { "mas7", offsetof(CPUState, spr[SPR_BOOKE_MAS7]) },
3605
    { "mmucfg", offsetof(CPUState, spr[SPR_MMUCFG]) },
3606
    { "tlb0cfg", offsetof(CPUState, spr[SPR_BOOKE_TLB0CFG]) },
3607
    { "tlb1cfg", offsetof(CPUState, spr[SPR_BOOKE_TLB1CFG]) },
3608
    { "epr", offsetof(CPUState, spr[SPR_BOOKE_EPR]) },
3609
    { "eplc", offsetof(CPUState, spr[SPR_BOOKE_EPLC]) },
3610
    { "epsc", offsetof(CPUState, spr[SPR_BOOKE_EPSC]) },
3611
    { "svr", offsetof(CPUState, spr[SPR_E500_SVR]) },
3612
    { "mcar", offsetof(CPUState, spr[SPR_Exxx_MCAR]) },
3613
    { "pid1", offsetof(CPUState, spr[SPR_BOOKE_PID1]) },
3614
    { "pid2", offsetof(CPUState, spr[SPR_BOOKE_PID2]) },
3615
    { "hid0", offsetof(CPUState, spr[SPR_HID0]) },
3616

    
3617
#elif defined(TARGET_SPARC)
3618
    { "g0", offsetof(CPUState, gregs[0]) },
3619
    { "g1", offsetof(CPUState, gregs[1]) },
3620
    { "g2", offsetof(CPUState, gregs[2]) },
3621
    { "g3", offsetof(CPUState, gregs[3]) },
3622
    { "g4", offsetof(CPUState, gregs[4]) },
3623
    { "g5", offsetof(CPUState, gregs[5]) },
3624
    { "g6", offsetof(CPUState, gregs[6]) },
3625
    { "g7", offsetof(CPUState, gregs[7]) },
3626
    { "o0", 0, monitor_get_reg },
3627
    { "o1", 1, monitor_get_reg },
3628
    { "o2", 2, monitor_get_reg },
3629
    { "o3", 3, monitor_get_reg },
3630
    { "o4", 4, monitor_get_reg },
3631
    { "o5", 5, monitor_get_reg },
3632
    { "o6", 6, monitor_get_reg },
3633
    { "o7", 7, monitor_get_reg },
3634
    { "l0", 8, monitor_get_reg },
3635
    { "l1", 9, monitor_get_reg },
3636
    { "l2", 10, monitor_get_reg },
3637
    { "l3", 11, monitor_get_reg },
3638
    { "l4", 12, monitor_get_reg },
3639
    { "l5", 13, monitor_get_reg },
3640
    { "l6", 14, monitor_get_reg },
3641
    { "l7", 15, monitor_get_reg },
3642
    { "i0", 16, monitor_get_reg },
3643
    { "i1", 17, monitor_get_reg },
3644
    { "i2", 18, monitor_get_reg },
3645
    { "i3", 19, monitor_get_reg },
3646
    { "i4", 20, monitor_get_reg },
3647
    { "i5", 21, monitor_get_reg },
3648
    { "i6", 22, monitor_get_reg },
3649
    { "i7", 23, monitor_get_reg },
3650
    { "pc", offsetof(CPUState, pc) },
3651
    { "npc", offsetof(CPUState, npc) },
3652
    { "y", offsetof(CPUState, y) },
3653
#ifndef TARGET_SPARC64
3654
    { "psr", 0, &monitor_get_psr, },
3655
    { "wim", offsetof(CPUState, wim) },
3656
#endif
3657
    { "tbr", offsetof(CPUState, tbr) },
3658
    { "fsr", offsetof(CPUState, fsr) },
3659
    { "f0", offsetof(CPUState, fpr[0]) },
3660
    { "f1", offsetof(CPUState, fpr[1]) },
3661
    { "f2", offsetof(CPUState, fpr[2]) },
3662
    { "f3", offsetof(CPUState, fpr[3]) },
3663
    { "f4", offsetof(CPUState, fpr[4]) },
3664
    { "f5", offsetof(CPUState, fpr[5]) },
3665
    { "f6", offsetof(CPUState, fpr[6]) },
3666
    { "f7", offsetof(CPUState, fpr[7]) },
3667
    { "f8", offsetof(CPUState, fpr[8]) },
3668
    { "f9", offsetof(CPUState, fpr[9]) },
3669
    { "f10", offsetof(CPUState, fpr[10]) },
3670
    { "f11", offsetof(CPUState, fpr[11]) },
3671
    { "f12", offsetof(CPUState, fpr[12]) },
3672
    { "f13", offsetof(CPUState, fpr[13]) },
3673
    { "f14", offsetof(CPUState, fpr[14]) },
3674
    { "f15", offsetof(CPUState, fpr[15]) },
3675
    { "f16", offsetof(CPUState, fpr[16]) },
3676
    { "f17", offsetof(CPUState, fpr[17]) },
3677
    { "f18", offsetof(CPUState, fpr[18]) },
3678
    { "f19", offsetof(CPUState, fpr[19]) },
3679
    { "f20", offsetof(CPUState, fpr[20]) },
3680
    { "f21", offsetof(CPUState, fpr[21]) },
3681
    { "f22", offsetof(CPUState, fpr[22]) },
3682
    { "f23", offsetof(CPUState, fpr[23]) },
3683
    { "f24", offsetof(CPUState, fpr[24]) },
3684
    { "f25", offsetof(CPUState, fpr[25]) },
3685
    { "f26", offsetof(CPUState, fpr[26]) },
3686
    { "f27", offsetof(CPUState, fpr[27]) },
3687
    { "f28", offsetof(CPUState, fpr[28]) },
3688
    { "f29", offsetof(CPUState, fpr[29]) },
3689
    { "f30", offsetof(CPUState, fpr[30]) },
3690
    { "f31", offsetof(CPUState, fpr[31]) },
3691
#ifdef TARGET_SPARC64
3692
    { "f32", offsetof(CPUState, fpr[32]) },
3693
    { "f34", offsetof(CPUState, fpr[34]) },
3694
    { "f36", offsetof(CPUState, fpr[36]) },
3695
    { "f38", offsetof(CPUState, fpr[38]) },
3696
    { "f40", offsetof(CPUState, fpr[40]) },
3697
    { "f42", offsetof(CPUState, fpr[42]) },
3698
    { "f44", offsetof(CPUState, fpr[44]) },
3699
    { "f46", offsetof(CPUState, fpr[46]) },
3700
    { "f48", offsetof(CPUState, fpr[48]) },
3701
    { "f50", offsetof(CPUState, fpr[50]) },
3702
    { "f52", offsetof(CPUState, fpr[52]) },
3703
    { "f54", offsetof(CPUState, fpr[54]) },
3704
    { "f56", offsetof(CPUState, fpr[56]) },
3705
    { "f58", offsetof(CPUState, fpr[58]) },
3706
    { "f60", offsetof(CPUState, fpr[60]) },
3707
    { "f62", offsetof(CPUState, fpr[62]) },
3708
    { "asi", offsetof(CPUState, asi) },
3709
    { "pstate", offsetof(CPUState, pstate) },
3710
    { "cansave", offsetof(CPUState, cansave) },
3711
    { "canrestore", offsetof(CPUState, canrestore) },
3712
    { "otherwin", offsetof(CPUState, otherwin) },
3713
    { "wstate", offsetof(CPUState, wstate) },
3714
    { "cleanwin", offsetof(CPUState, cleanwin) },
3715
    { "fprs", offsetof(CPUState, fprs) },
3716
#endif
3717
#endif
3718
    { NULL },
3719
};
3720

    
3721
static void expr_error(Monitor *mon, const char *msg)
3722
{
3723
    monitor_printf(mon, "%s\n", msg);
3724
    longjmp(expr_env, 1);
3725
}
3726

    
3727
/* return 0 if OK, -1 if not found */
3728
static int get_monitor_def(target_long *pval, const char *name)
3729
{
3730
    const MonitorDef *md;
3731
    void *ptr;
3732

    
3733
    for(md = monitor_defs; md->name != NULL; md++) {
3734
        if (compare_cmd(name, md->name)) {
3735
            if (md->get_value) {
3736
                *pval = md->get_value(md, md->offset);
3737
            } else {
3738
                CPUState *env = mon_get_cpu();
3739
                ptr = (uint8_t *)env + md->offset;
3740
                switch(md->type) {
3741
                case MD_I32:
3742
                    *pval = *(int32_t *)ptr;
3743
                    break;
3744
                case MD_TLONG:
3745
                    *pval = *(target_long *)ptr;
3746
                    break;
3747
                default:
3748
                    *pval = 0;
3749
                    break;
3750
                }
3751
            }
3752
            return 0;
3753
        }
3754
    }
3755
    return -1;
3756
}
3757

    
3758
static void next(void)
3759
{
3760
    if (*pch != '\0') {
3761
        pch++;
3762
        while (qemu_isspace(*pch))
3763
            pch++;
3764
    }
3765
}
3766

    
3767
static int64_t expr_sum(Monitor *mon);
3768

    
3769
static int64_t expr_unary(Monitor *mon)
3770
{
3771
    int64_t n;
3772
    char *p;
3773
    int ret;
3774

    
3775
    switch(*pch) {
3776
    case '+':
3777
        next();
3778
        n = expr_unary(mon);
3779
        break;
3780
    case '-':
3781
        next();
3782
        n = -expr_unary(mon);
3783
        break;
3784
    case '~':
3785
        next();
3786
        n = ~expr_unary(mon);
3787
        break;
3788
    case '(':
3789
        next();
3790
        n = expr_sum(mon);
3791
        if (*pch != ')') {
3792
            expr_error(mon, "')' expected");
3793
        }
3794
        next();
3795
        break;
3796
    case '\'':
3797
        pch++;
3798
        if (*pch == '\0')
3799
            expr_error(mon, "character constant expected");
3800
        n = *pch;
3801
        pch++;
3802
        if (*pch != '\'')
3803
            expr_error(mon, "missing terminating \' character");
3804
        next();
3805
        break;
3806
    case '$':
3807
        {
3808
            char buf[128], *q;
3809
            target_long reg=0;
3810

    
3811
            pch++;
3812
            q = buf;
3813
            while ((*pch >= 'a' && *pch <= 'z') ||
3814
                   (*pch >= 'A' && *pch <= 'Z') ||
3815
                   (*pch >= '0' && *pch <= '9') ||
3816
                   *pch == '_' || *pch == '.') {
3817
                if ((q - buf) < sizeof(buf) - 1)
3818
                    *q++ = *pch;
3819
                pch++;
3820
            }
3821
            while (qemu_isspace(*pch))
3822
                pch++;
3823
            *q = 0;
3824
            ret = get_monitor_def(&reg, buf);
3825
            if (ret < 0)
3826
                expr_error(mon, "unknown register");
3827
            n = reg;
3828
        }
3829
        break;
3830
    case '\0':
3831
        expr_error(mon, "unexpected end of expression");
3832
        n = 0;
3833
        break;
3834
    default:
3835
#if TARGET_PHYS_ADDR_BITS > 32
3836
        n = strtoull(pch, &p, 0);
3837
#else
3838
        n = strtoul(pch, &p, 0);
3839
#endif
3840
        if (pch == p) {
3841
            expr_error(mon, "invalid char in expression");
3842
        }
3843
        pch = p;
3844
        while (qemu_isspace(*pch))
3845
            pch++;
3846
        break;
3847
    }
3848
    return n;
3849
}
3850

    
3851

    
3852
static int64_t expr_prod(Monitor *mon)
3853
{
3854
    int64_t val, val2;
3855
    int op;
3856

    
3857
    val = expr_unary(mon);
3858
    for(;;) {
3859
        op = *pch;
3860
        if (op != '*' && op != '/' && op != '%')
3861
            break;
3862
        next();
3863
        val2 = expr_unary(mon);
3864
        switch(op) {
3865
        default:
3866
        case '*':
3867
            val *= val2;
3868
            break;
3869
        case '/':
3870
        case '%':
3871
            if (val2 == 0)
3872
                expr_error(mon, "division by zero");
3873
            if (op == '/')
3874
                val /= val2;
3875
            else
3876
                val %= val2;
3877
            break;
3878
        }
3879
    }
3880
    return val;
3881
}
3882

    
3883
static int64_t expr_logic(Monitor *mon)
3884
{
3885
    int64_t val, val2;
3886
    int op;
3887

    
3888
    val = expr_prod(mon);
3889
    for(;;) {
3890
        op = *pch;
3891
        if (op != '&' && op != '|' && op != '^')
3892
            break;
3893
        next();
3894
        val2 = expr_prod(mon);
3895
        switch(op) {
3896
        default:
3897
        case '&':
3898
            val &= val2;
3899
            break;
3900
        case '|':
3901
            val |= val2;
3902
            break;
3903
        case '^':
3904
            val ^= val2;
3905
            break;
3906
        }
3907
    }
3908
    return val;
3909
}
3910

    
3911
static int64_t expr_sum(Monitor *mon)
3912
{
3913
    int64_t val, val2;
3914
    int op;
3915

    
3916
    val = expr_logic(mon);
3917
    for(;;) {
3918
        op = *pch;
3919
        if (op != '+' && op != '-')
3920
            break;
3921
        next();
3922
        val2 = expr_logic(mon);
3923
        if (op == '+')
3924
            val += val2;
3925
        else
3926
            val -= val2;
3927
    }
3928
    return val;
3929
}
3930

    
3931
static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3932
{
3933
    pch = *pp;
3934
    if (setjmp(expr_env)) {
3935
        *pp = pch;
3936
        return -1;
3937
    }
3938
    while (qemu_isspace(*pch))
3939
        pch++;
3940
    *pval = expr_sum(mon);
3941
    *pp = pch;
3942
    return 0;
3943
}
3944

    
3945
static int get_double(Monitor *mon, double *pval, const char **pp)
3946
{
3947
    const char *p = *pp;
3948
    char *tailp;
3949
    double d;
3950

    
3951
    d = strtod(p, &tailp);
3952
    if (tailp == p) {
3953
        monitor_printf(mon, "Number expected\n");
3954
        return -1;
3955
    }
3956
    if (d != d || d - d != 0) {
3957
        /* NaN or infinity */
3958
        monitor_printf(mon, "Bad number\n");
3959
        return -1;
3960
    }
3961
    *pval = d;
3962
    *pp = tailp;
3963
    return 0;
3964
}
3965

    
3966
static int get_str(char *buf, int buf_size, const char **pp)
3967
{
3968
    const char *p;
3969
    char *q;
3970
    int c;
3971

    
3972
    q = buf;
3973
    p = *pp;
3974
    while (qemu_isspace(*p))
3975
        p++;
3976
    if (*p == '\0') {
3977
    fail:
3978
        *q = '\0';
3979
        *pp = p;
3980
        return -1;
3981
    }
3982
    if (*p == '\"') {
3983
        p++;
3984
        while (*p != '\0' && *p != '\"') {
3985
            if (*p == '\\') {
3986
                p++;
3987
                c = *p++;
3988
                switch(c) {
3989
                case 'n':
3990
                    c = '\n';
3991
                    break;
3992
                case 'r':
3993
                    c = '\r';
3994
                    break;
3995
                case '\\':
3996
                case '\'':
3997
                case '\"':
3998
                    break;
3999
                default:
4000
                    qemu_printf("unsupported escape code: '\\%c'\n", c);
4001
                    goto fail;
4002
                }
4003
                if ((q - buf) < buf_size - 1) {
4004
                    *q++ = c;
4005
                }
4006
            } else {
4007
                if ((q - buf) < buf_size - 1) {
4008
                    *q++ = *p;
4009
                }
4010
                p++;
4011
            }
4012
        }
4013
        if (*p != '\"') {
4014
            qemu_printf("unterminated string\n");
4015
            goto fail;
4016
        }
4017
        p++;
4018
    } else {
4019
        while (*p != '\0' && !qemu_isspace(*p)) {
4020
            if ((q - buf) < buf_size - 1) {
4021
                *q++ = *p;
4022
            }
4023
            p++;
4024
        }
4025
    }
4026
    *q = '\0';
4027
    *pp = p;
4028
    return 0;
4029
}
4030

    
4031
/*
4032
 * Store the command-name in cmdname, and return a pointer to
4033
 * the remaining of the command string.
4034
 */
4035
static const char *get_command_name(const char *cmdline,
4036
                                    char *cmdname, size_t nlen)
4037
{
4038
    size_t len;
4039
    const char *p, *pstart;
4040

    
4041
    p = cmdline;
4042
    while (qemu_isspace(*p))
4043
        p++;
4044
    if (*p == '\0')
4045
        return NULL;
4046
    pstart = p;
4047
    while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
4048
        p++;
4049
    len = p - pstart;
4050
    if (len > nlen - 1)
4051
        len = nlen - 1;
4052
    memcpy(cmdname, pstart, len);
4053
    cmdname[len] = '\0';
4054
    return p;
4055
}
4056

    
4057
/**
4058
 * Read key of 'type' into 'key' and return the current
4059
 * 'type' pointer.
4060
 */
4061
static char *key_get_info(const char *type, char **key)
4062
{
4063
    size_t len;
4064
    char *p, *str;
4065

    
4066
    if (*type == ',')
4067
        type++;
4068

    
4069
    p = strchr(type, ':');
4070
    if (!p) {
4071
        *key = NULL;
4072
        return NULL;
4073
    }
4074
    len = p - type;
4075

    
4076
    str = g_malloc(len + 1);
4077
    memcpy(str, type, len);
4078
    str[len] = '\0';
4079

    
4080
    *key = str;
4081
    return ++p;
4082
}
4083

    
4084
static int default_fmt_format = 'x';
4085
static int default_fmt_size = 4;
4086

    
4087
#define MAX_ARGS 16
4088

    
4089
static int is_valid_option(const char *c, const char *typestr)
4090
{
4091
    char option[3];
4092
  
4093
    option[0] = '-';
4094
    option[1] = *c;
4095
    option[2] = '\0';
4096
  
4097
    typestr = strstr(typestr, option);
4098
    return (typestr != NULL);
4099
}
4100

    
4101
static const mon_cmd_t *search_dispatch_table(const mon_cmd_t *disp_table,
4102
                                              const char *cmdname)
4103
{
4104
    const mon_cmd_t *cmd;
4105

    
4106
    for (cmd = disp_table; cmd->name != NULL; cmd++) {
4107
        if (compare_cmd(cmdname, cmd->name)) {
4108
            return cmd;
4109
        }
4110
    }
4111

    
4112
    return NULL;
4113
}
4114

    
4115
static const mon_cmd_t *monitor_find_command(const char *cmdname)
4116
{
4117
    return search_dispatch_table(mon_cmds, cmdname);
4118
}
4119

    
4120
static const mon_cmd_t *qmp_find_query_cmd(const char *info_item)
4121
{
4122
    return search_dispatch_table(qmp_query_cmds, info_item);
4123
}
4124

    
4125
static const mon_cmd_t *qmp_find_cmd(const char *cmdname)
4126
{
4127
    return search_dispatch_table(qmp_cmds, cmdname);
4128
}
4129

    
4130
static const mon_cmd_t *monitor_parse_command(Monitor *mon,
4131
                                              const char *cmdline,
4132
                                              QDict *qdict)
4133
{
4134
    const char *p, *typestr;
4135
    int c;
4136
    const mon_cmd_t *cmd;
4137
    char cmdname[256];
4138
    char buf[1024];
4139
    char *key;
4140

    
4141
#ifdef DEBUG
4142
    monitor_printf(mon, "command='%s'\n", cmdline);
4143
#endif
4144

    
4145
    /* extract the command name */
4146
    p = get_command_name(cmdline, cmdname, sizeof(cmdname));
4147
    if (!p)
4148
        return NULL;
4149

    
4150
    cmd = monitor_find_command(cmdname);
4151
    if (!cmd) {
4152
        monitor_printf(mon, "unknown command: '%s'\n", cmdname);
4153
        return NULL;
4154
    }
4155

    
4156
    /* parse the parameters */
4157
    typestr = cmd->args_type;
4158
    for(;;) {
4159
        typestr = key_get_info(typestr, &key);
4160
        if (!typestr)
4161
            break;
4162
        c = *typestr;
4163
        typestr++;
4164
        switch(c) {
4165
        case 'F':
4166
        case 'B':
4167
        case 's':
4168
            {
4169
                int ret;
4170

    
4171
                while (qemu_isspace(*p))
4172
                    p++;
4173
                if (*typestr == '?') {
4174
                    typestr++;
4175
                    if (*p == '\0') {
4176
                        /* no optional string: NULL argument */
4177
                        break;
4178
                    }
4179
                }
4180
                ret = get_str(buf, sizeof(buf), &p);
4181
                if (ret < 0) {
4182
                    switch(c) {
4183
                    case 'F':
4184
                        monitor_printf(mon, "%s: filename expected\n",
4185
                                       cmdname);
4186
                        break;
4187
                    case 'B':
4188
                        monitor_printf(mon, "%s: block device name expected\n",
4189
                                       cmdname);
4190
                        break;
4191
                    default:
4192
                        monitor_printf(mon, "%s: string expected\n", cmdname);
4193
                        break;
4194
                    }
4195
                    goto fail;
4196
                }
4197
                qdict_put(qdict, key, qstring_from_str(buf));
4198
            }
4199
            break;
4200
        case 'O':
4201
            {
4202
                QemuOptsList *opts_list;
4203
                QemuOpts *opts;
4204

    
4205
                opts_list = qemu_find_opts(key);
4206
                if (!opts_list || opts_list->desc->name) {
4207
                    goto bad_type;
4208
                }
4209
                while (qemu_isspace(*p)) {
4210
                    p++;
4211
                }
4212
                if (!*p)
4213
                    break;
4214
                if (get_str(buf, sizeof(buf), &p) < 0) {
4215
                    goto fail;
4216
                }
4217
                opts = qemu_opts_parse(opts_list, buf, 1);
4218
                if (!opts) {
4219
                    goto fail;
4220
                }
4221
                qemu_opts_to_qdict(opts, qdict);
4222
                qemu_opts_del(opts);
4223
            }
4224
            break;
4225
        case '/':
4226
            {
4227
                int count, format, size;
4228

    
4229
                while (qemu_isspace(*p))
4230
                    p++;
4231
                if (*p == '/') {
4232
                    /* format found */
4233
                    p++;
4234
                    count = 1;
4235
                    if (qemu_isdigit(*p)) {
4236
                        count = 0;
4237
                        while (qemu_isdigit(*p)) {
4238
                            count = count * 10 + (*p - '0');
4239
                            p++;
4240
                        }
4241
                    }
4242
                    size = -1;
4243
                    format = -1;
4244
                    for(;;) {
4245
                        switch(*p) {
4246
                        case 'o':
4247
                        case 'd':
4248
                        case 'u':
4249
                        case 'x':
4250
                        case 'i':
4251
                        case 'c':
4252
                            format = *p++;
4253
                            break;
4254
                        case 'b':
4255
                            size = 1;
4256
                            p++;
4257
                            break;
4258
                        case 'h':
4259
                            size = 2;
4260
                            p++;
4261
                            break;
4262
                        case 'w':
4263
                            size = 4;
4264
                            p++;
4265
                            break;
4266
                        case 'g':
4267
                        case 'L':
4268
                            size = 8;
4269
                            p++;
4270
                            break;
4271
                        default:
4272
                            goto next;
4273
                        }
4274
                    }
4275
                next:
4276
                    if (*p != '\0' && !qemu_isspace(*p)) {
4277
                        monitor_printf(mon, "invalid char in format: '%c'\n",
4278
                                       *p);
4279
                        goto fail;
4280
                    }
4281
                    if (format < 0)
4282
                        format = default_fmt_format;
4283
                    if (format != 'i') {
4284
                        /* for 'i', not specifying a size gives -1 as size */
4285
                        if (size < 0)
4286
                            size = default_fmt_size;
4287
                        default_fmt_size = size;
4288
                    }
4289
                    default_fmt_format = format;
4290
                } else {
4291
                    count = 1;
4292
                    format = default_fmt_format;
4293
                    if (format != 'i') {
4294
                        size = default_fmt_size;
4295
                    } else {
4296
                        size = -1;
4297
                    }
4298
                }
4299
                qdict_put(qdict, "count", qint_from_int(count));
4300
                qdict_put(qdict, "format", qint_from_int(format));
4301
                qdict_put(qdict, "size", qint_from_int(size));
4302
            }
4303
            break;
4304
        case 'i':
4305
        case 'l':
4306
        case 'M':
4307
            {
4308
                int64_t val;
4309

    
4310
                while (qemu_isspace(*p))
4311
                    p++;
4312
                if (*typestr == '?' || *typestr == '.') {
4313
                    if (*typestr == '?') {
4314
                        if (*p == '\0') {
4315
                            typestr++;
4316
                            break;
4317
                        }
4318
                    } else {
4319
                        if (*p == '.') {
4320
                            p++;
4321
                            while (qemu_isspace(*p))
4322
                                p++;
4323
                        } else {
4324
                            typestr++;
4325
                            break;
4326
                        }
4327
                    }
4328
                    typestr++;
4329
                }
4330
                if (get_expr(mon, &val, &p))
4331
                    goto fail;
4332
                /* Check if 'i' is greater than 32-bit */
4333
                if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
4334
                    monitor_printf(mon, "\'%s\' has failed: ", cmdname);
4335
                    monitor_printf(mon, "integer is for 32-bit values\n");
4336
                    goto fail;
4337
                } else if (c == 'M') {
4338
                    val <<= 20;
4339
                }
4340
                qdict_put(qdict, key, qint_from_int(val));
4341
            }
4342
            break;
4343
        case 'o':
4344
            {
4345
                int64_t val;
4346
                char *end;
4347

    
4348
                while (qemu_isspace(*p)) {
4349
                    p++;
4350
                }
4351
                if (*typestr == '?') {
4352
                    typestr++;
4353
                    if (*p == '\0') {
4354
                        break;
4355
                    }
4356
                }
4357
                val = strtosz(p, &end);
4358
                if (val < 0) {
4359
                    monitor_printf(mon, "invalid size\n");
4360
                    goto fail;
4361
                }
4362
                qdict_put(qdict, key, qint_from_int(val));
4363
                p = end;
4364
            }
4365
            break;
4366
        case 'T':
4367
            {
4368
                double val;
4369

    
4370
                while (qemu_isspace(*p))
4371
                    p++;
4372
                if (*typestr == '?') {
4373
                    typestr++;
4374
                    if (*p == '\0') {
4375
                        break;
4376
                    }
4377
                }
4378
                if (get_double(mon, &val, &p) < 0) {
4379
                    goto fail;
4380
                }
4381
                if (p[0] && p[1] == 's') {
4382
                    switch (*p) {
4383
                    case 'm':
4384
                        val /= 1e3; p += 2; break;
4385
                    case 'u':
4386
                        val /= 1e6; p += 2; break;
4387
                    case 'n':
4388
                        val /= 1e9; p += 2; break;
4389
                    }
4390
                }
4391
                if (*p && !qemu_isspace(*p)) {
4392
                    monitor_printf(mon, "Unknown unit suffix\n");
4393
                    goto fail;
4394
                }
4395
                qdict_put(qdict, key, qfloat_from_double(val));
4396
            }
4397
            break;
4398
        case 'b':
4399
            {
4400
                const char *beg;
4401
                int val;
4402

    
4403
                while (qemu_isspace(*p)) {
4404
                    p++;
4405
                }
4406
                beg = p;
4407
                while (qemu_isgraph(*p)) {
4408
                    p++;
4409
                }
4410
                if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {
4411
                    val = 1;
4412
                } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {
4413
                    val = 0;
4414
                } else {
4415
                    monitor_printf(mon, "Expected 'on' or 'off'\n");
4416
                    goto fail;
4417
                }
4418
                qdict_put(qdict, key, qbool_from_int(val));
4419
            }
4420
            break;
4421
        case '-':
4422
            {
4423
                const char *tmp = p;
4424
                int skip_key = 0;
4425
                /* option */
4426

    
4427
                c = *typestr++;
4428
                if (c == '\0')
4429
                    goto bad_type;
4430
                while (qemu_isspace(*p))
4431
                    p++;
4432
                if (*p == '-') {
4433
                    p++;
4434
                    if(c != *p) {
4435
                        if(!is_valid_option(p, typestr)) {
4436
                  
4437
                            monitor_printf(mon, "%s: unsupported option -%c\n",
4438
                                           cmdname, *p);
4439
                            goto fail;
4440
                        } else {
4441
                            skip_key = 1;
4442
                        }
4443
                    }
4444
                    if(skip_key) {
4445
                        p = tmp;
4446
                    } else {
4447
                        /* has option */
4448
                        p++;
4449
                        qdict_put(qdict, key, qbool_from_int(1));
4450
                    }
4451
                }
4452
            }
4453
            break;
4454
        default:
4455
        bad_type:
4456
            monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
4457
            goto fail;
4458
        }
4459
        g_free(key);
4460
        key = NULL;
4461
    }
4462
    /* check that all arguments were parsed */
4463
    while (qemu_isspace(*p))
4464
        p++;
4465
    if (*p != '\0') {
4466
        monitor_printf(mon, "%s: extraneous characters at the end of line\n",
4467
                       cmdname);
4468
        goto fail;
4469
    }
4470

    
4471
    return cmd;
4472

    
4473
fail:
4474
    g_free(key);
4475
    return NULL;
4476
}
4477

    
4478
void monitor_set_error(Monitor *mon, QError *qerror)
4479
{
4480
    /* report only the first error */
4481
    if (!mon->error) {
4482
        mon->error = qerror;
4483
    } else {
4484
        MON_DEBUG("Additional error report at %s:%d\n",
4485
                  qerror->file, qerror->linenr);
4486
        QDECREF(qerror);
4487
    }
4488
}
4489

    
4490
static void handler_audit(Monitor *mon, const mon_cmd_t *cmd, int ret)
4491
{
4492
    if (ret && !monitor_has_error(mon)) {
4493
        /*
4494
         * If it returns failure, it must have passed on error.
4495
         *
4496
         * Action: Report an internal error to the client if in QMP.
4497
         */
4498
        qerror_report(QERR_UNDEFINED_ERROR);
4499
        MON_DEBUG("command '%s' returned failure but did not pass an error\n",
4500
                  cmd->name);
4501
    }
4502

    
4503
#ifdef CONFIG_DEBUG_MONITOR
4504
    if (!ret && monitor_has_error(mon)) {
4505
        /*
4506
         * If it returns success, it must not have passed an error.
4507
         *
4508
         * Action: Report the passed error to the client.
4509
         */
4510
        MON_DEBUG("command '%s' returned success but passed an error\n",
4511
                  cmd->name);
4512
    }
4513

    
4514
    if (mon_print_count_get(mon) > 0 && strcmp(cmd->name, "info") != 0) {
4515
        /*
4516
         * Handlers should not call Monitor print functions.
4517
         *
4518
         * Action: Ignore them in QMP.
4519
         *
4520
         * (XXX: we don't check any 'info' or 'query' command here
4521
         * because the user print function _is_ called by do_info(), hence
4522
         * we will trigger this check. This problem will go away when we
4523
         * make 'query' commands real and kill do_info())
4524
         */
4525
        MON_DEBUG("command '%s' called print functions %d time(s)\n",
4526
                  cmd->name, mon_print_count_get(mon));
4527
    }
4528
#endif
4529
}
4530

    
4531
static void handle_user_command(Monitor *mon, const char *cmdline)
4532
{
4533
    QDict *qdict;
4534
    const mon_cmd_t *cmd;
4535

    
4536
    qdict = qdict_new();
4537

    
4538
    cmd = monitor_parse_command(mon, cmdline, qdict);
4539
    if (!cmd)
4540
        goto out;
4541

    
4542
    if (handler_is_async(cmd)) {
4543
        user_async_cmd_handler(mon, cmd, qdict);
4544
    } else if (handler_is_qobject(cmd)) {
4545
        QObject *data = NULL;
4546

    
4547
        /* XXX: ignores the error code */
4548
        cmd->mhandler.cmd_new(mon, qdict, &data);
4549
        assert(!monitor_has_error(mon));
4550
        if (data) {
4551
            cmd->user_print(mon, data);
4552
            qobject_decref(data);
4553
        }
4554
    } else {
4555
        cmd->mhandler.cmd(mon, qdict);
4556
    }
4557

    
4558
out:
4559
    QDECREF(qdict);
4560
}
4561

    
4562
static void cmd_completion(const char *name, const char *list)
4563
{
4564
    const char *p, *pstart;
4565
    char cmd[128];
4566
    int len;
4567

    
4568
    p = list;
4569
    for(;;) {
4570
        pstart = p;
4571
        p = strchr(p, '|');
4572
        if (!p)
4573
            p = pstart + strlen(pstart);
4574
        len = p - pstart;
4575
        if (len > sizeof(cmd) - 2)
4576
            len = sizeof(cmd) - 2;
4577
        memcpy(cmd, pstart, len);
4578
        cmd[len] = '\0';
4579
        if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
4580
            readline_add_completion(cur_mon->rs, cmd);
4581
        }
4582
        if (*p == '\0')
4583
            break;
4584
        p++;
4585
    }
4586
}
4587

    
4588
static void file_completion(const char *input)
4589
{
4590
    DIR *ffs;
4591
    struct dirent *d;
4592
    char path[1024];
4593
    char file[1024], file_prefix[1024];
4594
    int input_path_len;
4595
    const char *p;
4596

    
4597
    p = strrchr(input, '/');
4598
    if (!p) {
4599
        input_path_len = 0;
4600
        pstrcpy(file_prefix, sizeof(file_prefix), input);
4601
        pstrcpy(path, sizeof(path), ".");
4602
    } else {
4603
        input_path_len = p - input + 1;
4604
        memcpy(path, input, input_path_len);
4605
        if (input_path_len > sizeof(path) - 1)
4606
            input_path_len = sizeof(path) - 1;
4607
        path[input_path_len] = '\0';
4608
        pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
4609
    }
4610
#ifdef DEBUG_COMPLETION
4611
    monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
4612
                   input, path, file_prefix);
4613
#endif
4614
    ffs = opendir(path);
4615
    if (!ffs)
4616
        return;
4617
    for(;;) {
4618
        struct stat sb;
4619
        d = readdir(ffs);
4620
        if (!d)
4621
            break;
4622

    
4623
        if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
4624
            continue;
4625
        }
4626

    
4627
        if (strstart(d->d_name, file_prefix, NULL)) {
4628
            memcpy(file, input, input_path_len);
4629
            if (input_path_len < sizeof(file))
4630
                pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
4631
                        d->d_name);
4632
            /* stat the file to find out if it's a directory.
4633
             * In that case add a slash to speed up typing long paths
4634
             */
4635
            stat(file, &sb);
4636
            if(S_ISDIR(sb.st_mode))
4637
                pstrcat(file, sizeof(file), "/");
4638
            readline_add_completion(cur_mon->rs, file);
4639
        }
4640
    }
4641
    closedir(ffs);
4642
}
4643

    
4644
static void block_completion_it(void *opaque, BlockDriverState *bs)
4645
{
4646
    const char *name = bdrv_get_device_name(bs);
4647
    const char *input = opaque;
4648

    
4649
    if (input[0] == '\0' ||
4650
        !strncmp(name, (char *)input, strlen(input))) {
4651
        readline_add_completion(cur_mon->rs, name);
4652
    }
4653
}
4654

    
4655
/* NOTE: this parser is an approximate form of the real command parser */
4656
static void parse_cmdline(const char *cmdline,
4657
                         int *pnb_args, char **args)
4658
{
4659
    const char *p;
4660
    int nb_args, ret;
4661
    char buf[1024];
4662

    
4663
    p = cmdline;
4664
    nb_args = 0;
4665
    for(;;) {
4666
        while (qemu_isspace(*p))
4667
            p++;
4668
        if (*p == '\0')
4669
            break;
4670
        if (nb_args >= MAX_ARGS)
4671
            break;
4672
        ret = get_str(buf, sizeof(buf), &p);
4673
        args[nb_args] = g_strdup(buf);
4674
        nb_args++;
4675
        if (ret < 0)
4676
            break;
4677
    }
4678
    *pnb_args = nb_args;
4679
}
4680

    
4681
static const char *next_arg_type(const char *typestr)
4682
{
4683
    const char *p = strchr(typestr, ':');
4684
    return (p != NULL ? ++p : typestr);
4685
}
4686

    
4687
static void monitor_find_completion(const char *cmdline)
4688
{
4689
    const char *cmdname;
4690
    char *args[MAX_ARGS];
4691
    int nb_args, i, len;
4692
    const char *ptype, *str;
4693
    const mon_cmd_t *cmd;
4694
    const KeyDef *key;
4695

    
4696
    parse_cmdline(cmdline, &nb_args, args);
4697
#ifdef DEBUG_COMPLETION
4698
    for(i = 0; i < nb_args; i++) {
4699
        monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
4700
    }
4701
#endif
4702

    
4703
    /* if the line ends with a space, it means we want to complete the
4704
       next arg */
4705
    len = strlen(cmdline);
4706
    if (len > 0 && qemu_isspace(cmdline[len - 1])) {
4707
        if (nb_args >= MAX_ARGS) {
4708
            goto cleanup;
4709
        }
4710
        args[nb_args++] = g_strdup("");
4711
    }
4712
    if (nb_args <= 1) {
4713
        /* command completion */
4714
        if (nb_args == 0)
4715
            cmdname = "";
4716
        else
4717
            cmdname = args[0];
4718
        readline_set_completion_index(cur_mon->rs, strlen(cmdname));
4719
        for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
4720
            cmd_completion(cmdname, cmd->name);
4721
        }
4722
    } else {
4723
        /* find the command */
4724
        for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4725
            if (compare_cmd(args[0], cmd->name)) {
4726
                break;
4727
            }
4728
        }
4729
        if (!cmd->name) {
4730
            goto cleanup;
4731
        }
4732

    
4733
        ptype = next_arg_type(cmd->args_type);
4734
        for(i = 0; i < nb_args - 2; i++) {
4735
            if (*ptype != '\0') {
4736
                ptype = next_arg_type(ptype);
4737
                while (*ptype == '?')
4738
                    ptype = next_arg_type(ptype);
4739
            }
4740
        }
4741
        str = args[nb_args - 1];
4742
        if (*ptype == '-' && ptype[1] != '\0') {
4743
            ptype = next_arg_type(ptype);
4744
        }
4745
        switch(*ptype) {
4746
        case 'F':
4747
            /* file completion */
4748
            readline_set_completion_index(cur_mon->rs, strlen(str));
4749
            file_completion(str);
4750
            break;
4751
        case 'B':
4752
            /* block device name completion */
4753
            readline_set_completion_index(cur_mon->rs, strlen(str));
4754
            bdrv_iterate(block_completion_it, (void *)str);
4755
            break;
4756
        case 's':
4757
            /* XXX: more generic ? */
4758
            if (!strcmp(cmd->name, "info")) {
4759
                readline_set_completion_index(cur_mon->rs, strlen(str));
4760
                for(cmd = info_cmds; cmd->name != NULL; cmd++) {
4761
                    cmd_completion(str, cmd->name);
4762
                }
4763
            } else if (!strcmp(cmd->name, "sendkey")) {
4764
                char *sep = strrchr(str, '-');
4765
                if (sep)
4766
                    str = sep + 1;
4767
                readline_set_completion_index(cur_mon->rs, strlen(str));
4768
                for(key = key_defs; key->name != NULL; key++) {
4769
                    cmd_completion(str, key->name);
4770
                }
4771
            } else if (!strcmp(cmd->name, "help|?")) {
4772
                readline_set_completion_index(cur_mon->rs, strlen(str));
4773
                for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4774
                    cmd_completion(str, cmd->name);
4775
                }
4776
            }
4777
            break;
4778
        default:
4779
            break;
4780
        }
4781
    }
4782

    
4783
cleanup:
4784
    for (i = 0; i < nb_args; i++) {
4785
        g_free(args[i]);
4786
    }
4787
}
4788

    
4789
static int monitor_can_read(void *opaque)
4790
{
4791
    Monitor *mon = opaque;
4792

    
4793
    return (mon->suspend_cnt == 0) ? 1 : 0;
4794
}
4795

    
4796
static int invalid_qmp_mode(const Monitor *mon, const char *cmd_name)
4797
{
4798
    int is_cap = compare_cmd(cmd_name, "qmp_capabilities");
4799
    return (qmp_cmd_mode(mon) ? is_cap : !is_cap);
4800
}
4801

    
4802
/*
4803
 * Argument validation rules:
4804
 *
4805
 * 1. The argument must exist in cmd_args qdict
4806
 * 2. The argument type must be the expected one
4807
 *
4808
 * Special case: If the argument doesn't exist in cmd_args and
4809
 *               the QMP_ACCEPT_UNKNOWNS flag is set, then the
4810
 *               checking is skipped for it.
4811
 */
4812
static int check_client_args_type(const QDict *client_args,
4813
                                  const QDict *cmd_args, int flags)
4814
{
4815
    const QDictEntry *ent;
4816

    
4817
    for (ent = qdict_first(client_args); ent;ent = qdict_next(client_args,ent)){
4818
        QObject *obj;
4819
        QString *arg_type;
4820
        const QObject *client_arg = qdict_entry_value(ent);
4821
        const char *client_arg_name = qdict_entry_key(ent);
4822

    
4823
        obj = qdict_get(cmd_args, client_arg_name);
4824
        if (!obj) {
4825
            if (flags & QMP_ACCEPT_UNKNOWNS) {
4826
                /* handler accepts unknowns */
4827
                continue;
4828
            }
4829
            /* client arg doesn't exist */
4830
            qerror_report(QERR_INVALID_PARAMETER, client_arg_name);
4831
            return -1;
4832
        }
4833

    
4834
        arg_type = qobject_to_qstring(obj);
4835
        assert(arg_type != NULL);
4836

    
4837
        /* check if argument's type is correct */
4838
        switch (qstring_get_str(arg_type)[0]) {
4839
        case 'F':
4840
        case 'B':
4841
        case 's':
4842
            if (qobject_type(client_arg) != QTYPE_QSTRING) {
4843
                qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4844
                              "string");
4845
                return -1;
4846
            }
4847
        break;
4848
        case 'i':
4849
        case 'l':
4850
        case 'M':
4851
        case 'o':
4852
            if (qobject_type(client_arg) != QTYPE_QINT) {
4853
                qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4854
                              "int");
4855
                return -1; 
4856
            }
4857
            break;
4858
        case 'T':
4859
            if (qobject_type(client_arg) != QTYPE_QINT &&
4860
                qobject_type(client_arg) != QTYPE_QFLOAT) {
4861
                qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4862
                              "number");
4863
               return -1; 
4864
            }
4865
            break;
4866
        case 'b':
4867
        case '-':
4868
            if (qobject_type(client_arg) != QTYPE_QBOOL) {
4869
                qerror_report(QERR_INVALID_PARAMETER_TYPE, client_arg_name,
4870
                              "bool");
4871
               return -1; 
4872
            }
4873
            break;
4874
        case 'O':
4875
            assert(flags & QMP_ACCEPT_UNKNOWNS);
4876
            break;
4877
        case '/':
4878
        case '.':
4879
            /*
4880
             * These types are not supported by QMP and thus are not
4881
             * handled here. Fall through.
4882
             */
4883
        default:
4884
            abort();
4885
        }
4886
    }
4887

    
4888
    return 0;
4889
}
4890

    
4891
/*
4892
 * - Check if the client has passed all mandatory args
4893
 * - Set special flags for argument validation
4894
 */
4895
static int check_mandatory_args(const QDict *cmd_args,
4896
                                const QDict *client_args, int *flags)
4897
{
4898
    const QDictEntry *ent;
4899

    
4900
    for (ent = qdict_first(cmd_args); ent; ent = qdict_next(cmd_args, ent)) {
4901
        const char *cmd_arg_name = qdict_entry_key(ent);
4902
        QString *type = qobject_to_qstring(qdict_entry_value(ent));
4903
        assert(type != NULL);
4904

    
4905
        if (qstring_get_str(type)[0] == 'O') {
4906
            assert((*flags & QMP_ACCEPT_UNKNOWNS) == 0);
4907
            *flags |= QMP_ACCEPT_UNKNOWNS;
4908
        } else if (qstring_get_str(type)[0] != '-' &&
4909
                   qstring_get_str(type)[1] != '?' &&
4910
                   !qdict_haskey(client_args, cmd_arg_name)) {
4911
            qerror_report(QERR_MISSING_PARAMETER, cmd_arg_name);
4912
            return -1;
4913
        }
4914
    }
4915

    
4916
    return 0;
4917
}
4918

    
4919
static QDict *qdict_from_args_type(const char *args_type)
4920
{
4921
    int i;
4922
    QDict *qdict;
4923
    QString *key, *type, *cur_qs;
4924

    
4925
    assert(args_type != NULL);
4926

    
4927
    qdict = qdict_new();
4928

    
4929
    if (args_type == NULL || args_type[0] == '\0') {
4930
        /* no args, empty qdict */
4931
        goto out;
4932
    }
4933

    
4934
    key = qstring_new();
4935
    type = qstring_new();
4936

    
4937
    cur_qs = key;
4938

    
4939
    for (i = 0;; i++) {
4940
        switch (args_type[i]) {
4941
            case ',':
4942
            case '\0':
4943
                qdict_put(qdict, qstring_get_str(key), type);
4944
                QDECREF(key);
4945
                if (args_type[i] == '\0') {
4946
                    goto out;
4947
                }
4948
                type = qstring_new(); /* qdict has ref */
4949
                cur_qs = key = qstring_new();
4950
                break;
4951
            case ':':
4952
                cur_qs = type;
4953
                break;
4954
            default:
4955
                qstring_append_chr(cur_qs, args_type[i]);
4956
                break;
4957
        }
4958
    }
4959

    
4960
out:
4961
    return qdict;
4962
}
4963

    
4964
/*
4965
 * Client argument checking rules:
4966
 *
4967
 * 1. Client must provide all mandatory arguments
4968
 * 2. Each argument provided by the client must be expected
4969
 * 3. Each argument provided by the client must have the type expected
4970
 *    by the command
4971
 */
4972
static int qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args)
4973
{
4974
    int flags, err;
4975
    QDict *cmd_args;
4976

    
4977
    cmd_args = qdict_from_args_type(cmd->args_type);
4978

    
4979
    flags = 0;
4980
    err = check_mandatory_args(cmd_args, client_args, &flags);
4981
    if (err) {
4982
        goto out;
4983
    }
4984

    
4985
    err = check_client_args_type(client_args, cmd_args, flags);
4986

    
4987
out:
4988
    QDECREF(cmd_args);
4989
    return err;
4990
}
4991

    
4992
/*
4993
 * Input object checking rules
4994
 *
4995
 * 1. Input object must be a dict
4996
 * 2. The "execute" key must exist
4997
 * 3. The "execute" key must be a string
4998
 * 4. If the "arguments" key exists, it must be a dict
4999
 * 5. If the "id" key exists, it can be anything (ie. json-value)
5000
 * 6. Any argument not listed above is considered invalid
5001
 */
5002
static QDict *qmp_check_input_obj(QObject *input_obj)
5003
{
5004
    const QDictEntry *ent;
5005
    int has_exec_key = 0;
5006
    QDict *input_dict;
5007

    
5008
    if (qobject_type(input_obj) != QTYPE_QDICT) {
5009
        qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "object");
5010
        return NULL;
5011
    }
5012

    
5013
    input_dict = qobject_to_qdict(input_obj);
5014

    
5015
    for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){
5016
        const char *arg_name = qdict_entry_key(ent);
5017
        const QObject *arg_obj = qdict_entry_value(ent);
5018

    
5019
        if (!strcmp(arg_name, "execute")) {
5020
            if (qobject_type(arg_obj) != QTYPE_QSTRING) {
5021
                qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "execute",
5022
                              "string");
5023
                return NULL;
5024
            }
5025
            has_exec_key = 1;
5026
        } else if (!strcmp(arg_name, "arguments")) {
5027
            if (qobject_type(arg_obj) != QTYPE_QDICT) {
5028
                qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "arguments",
5029
                              "object");
5030
                return NULL;
5031
            }
5032
        } else if (!strcmp(arg_name, "id")) {
5033
            /* FIXME: check duplicated IDs for async commands */
5034
        } else {
5035
            qerror_report(QERR_QMP_EXTRA_MEMBER, arg_name);
5036
            return NULL;
5037
        }
5038
    }
5039

    
5040
    if (!has_exec_key) {
5041
        qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "execute");
5042
        return NULL;
5043
    }
5044

    
5045
    return input_dict;
5046
}
5047

    
5048
static void qmp_call_query_cmd(Monitor *mon, const mon_cmd_t *cmd)
5049
{
5050
    QObject *ret_data = NULL;
5051

    
5052
    if (handler_is_async(cmd)) {
5053
        qmp_async_info_handler(mon, cmd);
5054
        if (monitor_has_error(mon)) {
5055
            monitor_protocol_emitter(mon, NULL);
5056
        }
5057
    } else {
5058
        cmd->mhandler.info_new(mon, &ret_data);
5059
        monitor_protocol_emitter(mon, ret_data);
5060
        qobject_decref(ret_data);
5061
    }
5062
}
5063

    
5064
static void qmp_call_cmd(Monitor *mon, const mon_cmd_t *cmd,
5065
                         const QDict *params)
5066
{
5067
    int ret;
5068
    QObject *data = NULL;
5069

    
5070
    mon_print_count_init(mon);
5071

    
5072
    ret = cmd->mhandler.cmd_new(mon, params, &data);
5073
    handler_audit(mon, cmd, ret);
5074
    monitor_protocol_emitter(mon, data);
5075
    qobject_decref(data);
5076
}
5077

    
5078
static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
5079
{
5080
    int err;
5081
    QObject *obj;
5082
    QDict *input, *args;
5083
    const mon_cmd_t *cmd;
5084
    Monitor *mon = cur_mon;
5085
    const char *cmd_name, *query_cmd;
5086

    
5087
    query_cmd = NULL;
5088
    args = input = NULL;
5089

    
5090
    obj = json_parser_parse(tokens, NULL);
5091
    if (!obj) {
5092
        // FIXME: should be triggered in json_parser_parse()
5093
        qerror_report(QERR_JSON_PARSING);
5094
        goto err_out;
5095
    }
5096

    
5097
    input = qmp_check_input_obj(obj);
5098
    if (!input) {
5099
        qobject_decref(obj);
5100
        goto err_out;
5101
    }
5102

    
5103
    mon->mc->id = qdict_get(input, "id");
5104
    qobject_incref(mon->mc->id);
5105

    
5106
    cmd_name = qdict_get_str(input, "execute");
5107
    trace_handle_qmp_command(mon, cmd_name);
5108
    if (invalid_qmp_mode(mon, cmd_name)) {
5109
        qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
5110
        goto err_out;
5111
    }
5112

    
5113
    if (strstart(cmd_name, "query-", &query_cmd)) {
5114
        cmd = qmp_find_query_cmd(query_cmd);
5115
    } else {
5116
        cmd = qmp_find_cmd(cmd_name);
5117
    }
5118

    
5119
    if (!cmd) {
5120
        qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);
5121
        goto err_out;
5122
    }
5123

    
5124
    obj = qdict_get(input, "arguments");
5125
    if (!obj) {
5126
        args = qdict_new();
5127
    } else {
5128
        args = qobject_to_qdict(obj);
5129
        QINCREF(args);
5130
    }
5131

    
5132
    err = qmp_check_client_args(cmd, args);
5133
    if (err < 0) {
5134
        goto err_out;
5135
    }
5136

    
5137
    if (query_cmd) {
5138
        qmp_call_query_cmd(mon, cmd);
5139
    } else if (handler_is_async(cmd)) {
5140
        err = qmp_async_cmd_handler(mon, cmd, args);
5141
        if (err) {
5142
            /* emit the error response */
5143
            goto err_out;
5144
        }
5145
    } else {
5146
        qmp_call_cmd(mon, cmd, args);
5147
    }
5148

    
5149
    goto out;
5150

    
5151
err_out:
5152
    monitor_protocol_emitter(mon, NULL);
5153
out:
5154
    QDECREF(input);
5155
    QDECREF(args);
5156
}
5157

    
5158
/**
5159
 * monitor_control_read(): Read and handle QMP input
5160
 */
5161
static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
5162
{
5163
    Monitor *old_mon = cur_mon;
5164

    
5165
    cur_mon = opaque;
5166

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

    
5169
    cur_mon = old_mon;
5170
}
5171

    
5172
static void monitor_read(void *opaque, const uint8_t *buf, int size)
5173
{
5174
    Monitor *old_mon = cur_mon;
5175
    int i;
5176

    
5177
    cur_mon = opaque;
5178

    
5179
    if (cur_mon->rs) {
5180
        for (i = 0; i < size; i++)
5181
            readline_handle_byte(cur_mon->rs, buf[i]);
5182
    } else {
5183
        if (size == 0 || buf[size - 1] != 0)
5184
            monitor_printf(cur_mon, "corrupted command\n");
5185
        else
5186
            handle_user_command(cur_mon, (char *)buf);
5187
    }
5188

    
5189
    cur_mon = old_mon;
5190
}
5191

    
5192
static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
5193
{
5194
    monitor_suspend(mon);
5195
    handle_user_command(mon, cmdline);
5196
    monitor_resume(mon);
5197
}
5198

    
5199
int monitor_suspend(Monitor *mon)
5200
{
5201
    if (!mon->rs)
5202
        return -ENOTTY;
5203
    mon->suspend_cnt++;
5204
    return 0;
5205
}
5206

    
5207
void monitor_resume(Monitor *mon)
5208
{
5209
    if (!mon->rs)
5210
        return;
5211
    if (--mon->suspend_cnt == 0)
5212
        readline_show_prompt(mon->rs);
5213
}
5214

    
5215
static QObject *get_qmp_greeting(void)
5216
{
5217
    QObject *ver;
5218

    
5219
    do_info_version(NULL, &ver);
5220
    return qobject_from_jsonf("{'QMP':{'version': %p,'capabilities': []}}",ver);
5221
}
5222

    
5223
/**
5224
 * monitor_control_event(): Print QMP gretting
5225
 */
5226
static void monitor_control_event(void *opaque, int event)
5227
{
5228
    QObject *data;
5229
    Monitor *mon = opaque;
5230

    
5231
    switch (event) {
5232
    case CHR_EVENT_OPENED:
5233
        mon->mc->command_mode = 0;
5234
        json_message_parser_init(&mon->mc->parser, handle_qmp_command);
5235
        data = get_qmp_greeting();
5236
        monitor_json_emitter(mon, data);
5237
        qobject_decref(data);
5238
        break;
5239
    case CHR_EVENT_CLOSED:
5240
        json_message_parser_destroy(&mon->mc->parser);
5241
        break;
5242
    }
5243
}
5244

    
5245
static void monitor_event(void *opaque, int event)
5246
{
5247
    Monitor *mon = opaque;
5248

    
5249
    switch (event) {
5250
    case CHR_EVENT_MUX_IN:
5251
        mon->mux_out = 0;
5252
        if (mon->reset_seen) {
5253
            readline_restart(mon->rs);
5254
            monitor_resume(mon);
5255
            monitor_flush(mon);
5256
        } else {
5257
            mon->suspend_cnt = 0;
5258
        }
5259
        break;
5260

    
5261
    case CHR_EVENT_MUX_OUT:
5262
        if (mon->reset_seen) {
5263
            if (mon->suspend_cnt == 0) {
5264
                monitor_printf(mon, "\n");
5265
            }
5266
            monitor_flush(mon);
5267
            monitor_suspend(mon);
5268
        } else {
5269
            mon->suspend_cnt++;
5270
        }
5271
        mon->mux_out = 1;
5272
        break;
5273

    
5274
    case CHR_EVENT_OPENED:
5275
        monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
5276
                       "information\n", QEMU_VERSION);
5277
        if (!mon->mux_out) {
5278
            readline_show_prompt(mon->rs);
5279
        }
5280
        mon->reset_seen = 1;
5281
        break;
5282
    }
5283
}
5284

    
5285

    
5286
/*
5287
 * Local variables:
5288
 *  c-indent-level: 4
5289
 *  c-basic-offset: 4
5290
 *  tab-width: 8
5291
 * End:
5292
 */
5293

    
5294
void monitor_init(CharDriverState *chr, int flags)
5295
{
5296
    static int is_first_init = 1;
5297
    Monitor *mon;
5298

    
5299
    if (is_first_init) {
5300
        key_timer = qemu_new_timer_ns(vm_clock, release_keys, NULL);
5301
        is_first_init = 0;
5302
    }
5303

    
5304
    mon = g_malloc0(sizeof(*mon));
5305

    
5306
    mon->chr = chr;
5307
    mon->flags = flags;
5308
    if (flags & MONITOR_USE_READLINE) {
5309
        mon->rs = readline_init(mon, monitor_find_completion);
5310
        monitor_read_command(mon, 0);
5311
    }
5312

    
5313
    if (monitor_ctrl_mode(mon)) {
5314
        mon->mc = g_malloc0(sizeof(MonitorControl));
5315
        /* Control mode requires special handlers */
5316
        qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
5317
                              monitor_control_event, mon);
5318
        qemu_chr_fe_set_echo(chr, true);
5319
    } else {
5320
        qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
5321
                              monitor_event, mon);
5322
    }
5323

    
5324
    QLIST_INSERT_HEAD(&mon_list, mon, entry);
5325
    if (!default_mon || (flags & MONITOR_IS_DEFAULT))
5326
        default_mon = mon;
5327
}
5328

    
5329
static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
5330
{
5331
    BlockDriverState *bs = opaque;
5332
    int ret = 0;
5333

    
5334
    if (bdrv_set_key(bs, password) != 0) {
5335
        monitor_printf(mon, "invalid password\n");
5336
        ret = -EPERM;
5337
    }
5338
    if (mon->password_completion_cb)
5339
        mon->password_completion_cb(mon->password_opaque, ret);
5340

    
5341
    monitor_read_command(mon, 1);
5342
}
5343

    
5344
int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
5345
                                BlockDriverCompletionFunc *completion_cb,
5346
                                void *opaque)
5347
{
5348
    int err;
5349

    
5350
    if (!bdrv_key_required(bs)) {
5351
        if (completion_cb)
5352
            completion_cb(opaque, 0);
5353
        return 0;
5354
    }
5355

    
5356
    if (monitor_ctrl_mode(mon)) {
5357
        qerror_report(QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs));
5358
        return -1;
5359
    }
5360

    
5361
    monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
5362
                   bdrv_get_encrypted_filename(bs));
5363

    
5364
    mon->password_completion_cb = completion_cb;
5365
    mon->password_opaque = opaque;
5366

    
5367
    err = monitor_read_password(mon, bdrv_password_cb, bs);
5368

    
5369
    if (err && completion_cb)
5370
        completion_cb(opaque, err);
5371

    
5372
    return err;
5373
}