Statistics
| Branch: | Revision:

root / monitor.c @ 9fec543f

History | View | Annotate | Download (118.3 kB)

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

    
60
//#define DEBUG
61
//#define DEBUG_COMPLETION
62

    
63
/*
64
 * Supported types:
65
 *
66
 * 'F'          filename
67
 * 'B'          block device name
68
 * 's'          string (accept optional quote)
69
 * 'i'          32 bit integer
70
 * 'l'          target long (32 or 64 bit)
71
 * 'M'          just like 'l', except in user mode the value is
72
 *              multiplied by 2^20 (think Mebibyte)
73
 * '/'          optional gdb-like print format (like "/10x")
74
 *
75
 * '?'          optional type (for all types, except '/')
76
 * '.'          other form of optional type (for 'i' and 'l')
77
 * '-'          optional parameter (eg. '-f')
78
 *
79
 */
80

    
81
typedef struct MonitorCompletionData MonitorCompletionData;
82
struct MonitorCompletionData {
83
    Monitor *mon;
84
    void (*user_print)(Monitor *mon, const QObject *data);
85
};
86

    
87
typedef struct mon_cmd_t {
88
    const char *name;
89
    const char *args_type;
90
    const char *params;
91
    const char *help;
92
    void (*user_print)(Monitor *mon, const QObject *data);
93
    union {
94
        void (*info)(Monitor *mon);
95
        void (*info_new)(Monitor *mon, QObject **ret_data);
96
        int  (*info_async)(Monitor *mon, MonitorCompletion *cb, void *opaque);
97
        void (*cmd)(Monitor *mon, const QDict *qdict);
98
        void (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data);
99
        int  (*cmd_async)(Monitor *mon, const QDict *params,
100
                          MonitorCompletion *cb, void *opaque);
101
    } mhandler;
102
    int async;
103
} mon_cmd_t;
104

    
105
/* file descriptors passed via SCM_RIGHTS */
106
typedef struct mon_fd_t mon_fd_t;
107
struct mon_fd_t {
108
    char *name;
109
    int fd;
110
    QLIST_ENTRY(mon_fd_t) next;
111
};
112

    
113
typedef struct MonitorControl {
114
    QObject *id;
115
    int print_enabled;
116
    JSONMessageParser parser;
117
} MonitorControl;
118

    
119
struct Monitor {
120
    CharDriverState *chr;
121
    int mux_out;
122
    int reset_seen;
123
    int flags;
124
    int suspend_cnt;
125
    uint8_t outbuf[1024];
126
    int outbuf_index;
127
    ReadLineState *rs;
128
    MonitorControl *mc;
129
    CPUState *mon_cpu;
130
    BlockDriverCompletionFunc *password_completion_cb;
131
    void *password_opaque;
132
    QError *error;
133
    QLIST_HEAD(,mon_fd_t) fds;
134
    QLIST_ENTRY(Monitor) entry;
135
};
136

    
137
static QLIST_HEAD(mon_list, Monitor) mon_list;
138

    
139
static const mon_cmd_t mon_cmds[];
140
static const mon_cmd_t info_cmds[];
141

    
142
Monitor *cur_mon = NULL;
143

    
144
static void monitor_command_cb(Monitor *mon, const char *cmdline,
145
                               void *opaque);
146

    
147
/* Return true if in control mode, false otherwise */
148
static inline int monitor_ctrl_mode(const Monitor *mon)
149
{
150
    return (mon->flags & MONITOR_USE_CONTROL);
151
}
152

    
153
static void monitor_read_command(Monitor *mon, int show_prompt)
154
{
155
    if (!mon->rs)
156
        return;
157

    
158
    readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
159
    if (show_prompt)
160
        readline_show_prompt(mon->rs);
161
}
162

    
163
static int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
164
                                 void *opaque)
165
{
166
    if (monitor_ctrl_mode(mon)) {
167
        qemu_error_new(QERR_MISSING_PARAMETER, "password");
168
        return -EINVAL;
169
    } else if (mon->rs) {
170
        readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
171
        /* prompt is printed on return from the command handler */
172
        return 0;
173
    } else {
174
        monitor_printf(mon, "terminal does not support password prompting\n");
175
        return -ENOTTY;
176
    }
177
}
178

    
179
void monitor_flush(Monitor *mon)
180
{
181
    if (mon && mon->outbuf_index != 0 && !mon->mux_out) {
182
        qemu_chr_write(mon->chr, mon->outbuf, mon->outbuf_index);
183
        mon->outbuf_index = 0;
184
    }
185
}
186

    
187
/* flush at every end of line or if the buffer is full */
188
static void monitor_puts(Monitor *mon, const char *str)
189
{
190
    char c;
191

    
192
    for(;;) {
193
        c = *str++;
194
        if (c == '\0')
195
            break;
196
        if (c == '\n')
197
            mon->outbuf[mon->outbuf_index++] = '\r';
198
        mon->outbuf[mon->outbuf_index++] = c;
199
        if (mon->outbuf_index >= (sizeof(mon->outbuf) - 1)
200
            || c == '\n')
201
            monitor_flush(mon);
202
    }
203
}
204

    
205
void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
206
{
207
    if (!mon)
208
        return;
209

    
210
    if (mon->mc && !mon->mc->print_enabled) {
211
        qemu_error_new(QERR_UNDEFINED_ERROR);
212
    } else {
213
        char buf[4096];
214
        vsnprintf(buf, sizeof(buf), fmt, ap);
215
        monitor_puts(mon, buf);
216
    }
217
}
218

    
219
void monitor_printf(Monitor *mon, const char *fmt, ...)
220
{
221
    va_list ap;
222
    va_start(ap, fmt);
223
    monitor_vprintf(mon, fmt, ap);
224
    va_end(ap);
225
}
226

    
227
void monitor_print_filename(Monitor *mon, const char *filename)
228
{
229
    int i;
230

    
231
    for (i = 0; filename[i]; i++) {
232
        switch (filename[i]) {
233
        case ' ':
234
        case '"':
235
        case '\\':
236
            monitor_printf(mon, "\\%c", filename[i]);
237
            break;
238
        case '\t':
239
            monitor_printf(mon, "\\t");
240
            break;
241
        case '\r':
242
            monitor_printf(mon, "\\r");
243
            break;
244
        case '\n':
245
            monitor_printf(mon, "\\n");
246
            break;
247
        default:
248
            monitor_printf(mon, "%c", filename[i]);
249
            break;
250
        }
251
    }
252
}
253

    
254
static int monitor_fprintf(FILE *stream, const char *fmt, ...)
255
{
256
    va_list ap;
257
    va_start(ap, fmt);
258
    monitor_vprintf((Monitor *)stream, fmt, ap);
259
    va_end(ap);
260
    return 0;
261
}
262

    
263
static void monitor_user_noop(Monitor *mon, const QObject *data) { }
264

    
265
static inline int monitor_handler_ported(const mon_cmd_t *cmd)
266
{
267
    return cmd->user_print != NULL;
268
}
269

    
270
static inline bool monitor_handler_is_async(const mon_cmd_t *cmd)
271
{
272
    return cmd->async != 0;
273
}
274

    
275
static inline int monitor_has_error(const Monitor *mon)
276
{
277
    return mon->error != NULL;
278
}
279

    
280
static void monitor_json_emitter(Monitor *mon, const QObject *data)
281
{
282
    QString *json;
283

    
284
    json = qobject_to_json(data);
285
    assert(json != NULL);
286

    
287
    mon->mc->print_enabled = 1;
288
    monitor_printf(mon, "%s\n", qstring_get_str(json));
289
    mon->mc->print_enabled = 0;
290

    
291
    QDECREF(json);
292
}
293

    
294
static void monitor_protocol_emitter(Monitor *mon, QObject *data)
295
{
296
    QDict *qmp;
297

    
298
    qmp = qdict_new();
299

    
300
    if (!monitor_has_error(mon)) {
301
        /* success response */
302
        if (data) {
303
            qobject_incref(data);
304
            qdict_put_obj(qmp, "return", data);
305
        } else {
306
            /* return an empty QDict by default */
307
            qdict_put(qmp, "return", qdict_new());
308
        }
309
    } else {
310
        /* error response */
311
        qdict_put(mon->error->error, "desc", qerror_human(mon->error));
312
        qdict_put(qmp, "error", mon->error->error);
313
        QINCREF(mon->error->error);
314
        QDECREF(mon->error);
315
        mon->error = NULL;
316
    }
317

    
318
    if (mon->mc->id) {
319
        qdict_put_obj(qmp, "id", mon->mc->id);
320
        mon->mc->id = NULL;
321
    }
322

    
323
    monitor_json_emitter(mon, QOBJECT(qmp));
324
    QDECREF(qmp);
325
}
326

    
327
static void timestamp_put(QDict *qdict)
328
{
329
    int err;
330
    QObject *obj;
331
    qemu_timeval tv;
332

    
333
    err = qemu_gettimeofday(&tv);
334
    if (err < 0)
335
        return;
336

    
337
    obj = qobject_from_jsonf("{ 'seconds': %" PRId64 ", "
338
                                "'microseconds': %" PRId64 " }",
339
                                (int64_t) tv.tv_sec, (int64_t) tv.tv_usec);
340
    assert(obj != NULL);
341

    
342
    qdict_put_obj(qdict, "timestamp", obj);
343
}
344

    
345
/**
346
 * monitor_protocol_event(): Generate a Monitor event
347
 *
348
 * Event-specific data can be emitted through the (optional) 'data' parameter.
349
 */
350
void monitor_protocol_event(MonitorEvent event, QObject *data)
351
{
352
    QDict *qmp;
353
    const char *event_name;
354
    Monitor *mon;
355

    
356
    assert(event < QEVENT_MAX);
357

    
358
    switch (event) {
359
        case QEVENT_DEBUG:
360
            event_name = "DEBUG";
361
            break;
362
        case QEVENT_SHUTDOWN:
363
            event_name = "SHUTDOWN";
364
            break;
365
        case QEVENT_RESET:
366
            event_name = "RESET";
367
            break;
368
        case QEVENT_POWERDOWN:
369
            event_name = "POWERDOWN";
370
            break;
371
        case QEVENT_STOP:
372
            event_name = "STOP";
373
            break;
374
        case QEVENT_VNC_CONNECTED:
375
            event_name = "VNC_CONNECTED";
376
            break;
377
        case QEVENT_VNC_INITIALIZED:
378
            event_name = "VNC_INITIALIZED";
379
            break;
380
        case QEVENT_VNC_DISCONNECTED:
381
            event_name = "VNC_DISCONNECTED";
382
            break;
383
        default:
384
            abort();
385
            break;
386
    }
387

    
388
    qmp = qdict_new();
389
    timestamp_put(qmp);
390
    qdict_put(qmp, "event", qstring_from_str(event_name));
391
    if (data) {
392
        qobject_incref(data);
393
        qdict_put_obj(qmp, "data", data);
394
    }
395

    
396
    QLIST_FOREACH(mon, &mon_list, entry) {
397
        if (monitor_ctrl_mode(mon)) {
398
            monitor_json_emitter(mon, QOBJECT(qmp));
399
        }
400
    }
401
    QDECREF(qmp);
402
}
403

    
404
static int compare_cmd(const char *name, const char *list)
405
{
406
    const char *p, *pstart;
407
    int len;
408
    len = strlen(name);
409
    p = list;
410
    for(;;) {
411
        pstart = p;
412
        p = strchr(p, '|');
413
        if (!p)
414
            p = pstart + strlen(pstart);
415
        if ((p - pstart) == len && !memcmp(pstart, name, len))
416
            return 1;
417
        if (*p == '\0')
418
            break;
419
        p++;
420
    }
421
    return 0;
422
}
423

    
424
static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
425
                          const char *prefix, const char *name)
426
{
427
    const mon_cmd_t *cmd;
428

    
429
    for(cmd = cmds; cmd->name != NULL; cmd++) {
430
        if (!name || !strcmp(name, cmd->name))
431
            monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
432
                           cmd->params, cmd->help);
433
    }
434
}
435

    
436
static void help_cmd(Monitor *mon, const char *name)
437
{
438
    if (name && !strcmp(name, "info")) {
439
        help_cmd_dump(mon, info_cmds, "info ", NULL);
440
    } else {
441
        help_cmd_dump(mon, mon_cmds, "", name);
442
        if (name && !strcmp(name, "log")) {
443
            const CPULogItem *item;
444
            monitor_printf(mon, "Log items (comma separated):\n");
445
            monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
446
            for(item = cpu_log_items; item->mask != 0; item++) {
447
                monitor_printf(mon, "%-10s %s\n", item->name, item->help);
448
            }
449
        }
450
    }
451
}
452

    
453
static void do_help_cmd(Monitor *mon, const QDict *qdict)
454
{
455
    help_cmd(mon, qdict_get_try_str(qdict, "name"));
456
}
457

    
458
static void do_commit(Monitor *mon, const QDict *qdict)
459
{
460
    int all_devices;
461
    DriveInfo *dinfo;
462
    const char *device = qdict_get_str(qdict, "device");
463

    
464
    all_devices = !strcmp(device, "all");
465
    QTAILQ_FOREACH(dinfo, &drives, next) {
466
        if (!all_devices)
467
            if (strcmp(bdrv_get_device_name(dinfo->bdrv), device))
468
                continue;
469
        bdrv_commit(dinfo->bdrv);
470
    }
471
}
472

    
473
static void user_monitor_complete(void *opaque, QObject *ret_data)
474
{
475
    MonitorCompletionData *data = (MonitorCompletionData *)opaque; 
476

    
477
    if (ret_data) {
478
        data->user_print(data->mon, ret_data);
479
    }
480
    monitor_resume(data->mon);
481
    qemu_free(data);
482
}
483

    
484
static void qmp_monitor_complete(void *opaque, QObject *ret_data)
485
{
486
    monitor_protocol_emitter(opaque, ret_data);
487
}
488

    
489
static void qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
490
                                  const QDict *params)
491
{
492
    cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);
493
}
494

    
495
static void qmp_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
496
{
497
    cmd->mhandler.info_async(mon, qmp_monitor_complete, mon);
498
}
499

    
500
static void user_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
501
                                   const QDict *params)
502
{
503
    int ret;
504

    
505
    MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
506
    cb_data->mon = mon;
507
    cb_data->user_print = cmd->user_print;
508
    monitor_suspend(mon);
509
    ret = cmd->mhandler.cmd_async(mon, params,
510
                                  user_monitor_complete, cb_data);
511
    if (ret < 0) {
512
        monitor_resume(mon);
513
        qemu_free(cb_data);
514
    }
515
}
516

    
517
static void user_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
518
{
519
    int ret;
520

    
521
    MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
522
    cb_data->mon = mon;
523
    cb_data->user_print = cmd->user_print;
524
    monitor_suspend(mon);
525
    ret = cmd->mhandler.info_async(mon, user_monitor_complete, cb_data);
526
    if (ret < 0) {
527
        monitor_resume(mon);
528
        qemu_free(cb_data);
529
    }
530
}
531

    
532
static void do_info(Monitor *mon, const QDict *qdict, QObject **ret_data)
533
{
534
    const mon_cmd_t *cmd;
535
    const char *item = qdict_get_try_str(qdict, "item");
536

    
537
    if (!item) {
538
        assert(monitor_ctrl_mode(mon) == 0);
539
        goto help;
540
    }
541

    
542
    for (cmd = info_cmds; cmd->name != NULL; cmd++) {
543
        if (compare_cmd(item, cmd->name))
544
            break;
545
    }
546

    
547
    if (cmd->name == NULL) {
548
        if (monitor_ctrl_mode(mon)) {
549
            qemu_error_new(QERR_COMMAND_NOT_FOUND, item);
550
            return;
551
        }
552
        goto help;
553
    }
554

    
555
    if (monitor_handler_is_async(cmd)) {
556
        if (monitor_ctrl_mode(mon)) {
557
            qmp_async_info_handler(mon, cmd);
558
        } else {
559
            user_async_info_handler(mon, cmd);
560
        }
561
        /*
562
         * Indicate that this command is asynchronous and will not return any
563
         * data (not even empty).  Instead, the data will be returned via a
564
         * completion callback.
565
         */
566
        *ret_data = qobject_from_jsonf("{ '__mon_async': 'return' }");
567
    } else if (monitor_handler_ported(cmd)) {
568
        cmd->mhandler.info_new(mon, ret_data);
569

    
570
        if (!monitor_ctrl_mode(mon)) {
571
            /*
572
             * User Protocol function is called here, Monitor Protocol is
573
             * handled by monitor_call_handler()
574
             */
575
            if (*ret_data)
576
                cmd->user_print(mon, *ret_data);
577
        }
578
    } else {
579
        if (monitor_ctrl_mode(mon)) {
580
            /* handler not converted yet */
581
            qemu_error_new(QERR_COMMAND_NOT_FOUND, item);
582
        } else {
583
            cmd->mhandler.info(mon);
584
        }
585
    }
586

    
587
    return;
588

    
589
help:
590
    help_cmd(mon, "info");
591
}
592

    
593
static void do_info_version_print(Monitor *mon, const QObject *data)
594
{
595
    QDict *qdict;
596

    
597
    qdict = qobject_to_qdict(data);
598

    
599
    monitor_printf(mon, "%s%s\n", qdict_get_str(qdict, "qemu"),
600
                                  qdict_get_str(qdict, "package"));
601
}
602

    
603
/**
604
 * do_info_version(): Show QEMU version
605
 *
606
 * Return a QDict with the following information:
607
 *
608
 * - "qemu": QEMU's version
609
 * - "package": package's version
610
 *
611
 * Example:
612
 *
613
 * { "qemu": "0.11.50", "package": "" }
614
 */
615
static void do_info_version(Monitor *mon, QObject **ret_data)
616
{
617
    *ret_data = qobject_from_jsonf("{ 'qemu': %s, 'package': %s }",
618
                                   QEMU_VERSION, QEMU_PKGVERSION);
619
}
620

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

    
625
    qdict = qobject_to_qdict(data);
626
    if (qdict_size(qdict) == 0) {
627
        return;
628
    }
629

    
630
    monitor_printf(mon, "%s\n", qdict_get_str(qdict, "name"));
631
}
632

    
633
/**
634
 * do_info_name(): Show VM name
635
 *
636
 * Return a QDict with the following information:
637
 *
638
 * - "name": VM's name (optional)
639
 *
640
 * Example:
641
 *
642
 * { "name": "qemu-name" }
643
 */
644
static void do_info_name(Monitor *mon, QObject **ret_data)
645
{
646
    *ret_data = qemu_name ? qobject_from_jsonf("{'name': %s }", qemu_name) :
647
                            qobject_from_jsonf("{}");
648
}
649

    
650
static QObject *get_cmd_dict(const char *name)
651
{
652
    const char *p;
653

    
654
    /* Remove '|' from some commands */
655
    p = strchr(name, '|');
656
    if (p) {
657
        p++;
658
    } else {
659
        p = name;
660
    }
661

    
662
    return qobject_from_jsonf("{ 'name': %s }", p);
663
}
664

    
665
/**
666
 * do_info_commands(): List QMP available commands
667
 *
668
 * Each command is represented by a QDict, the returned QObject is a QList
669
 * of all commands.
670
 *
671
 * The QDict contains:
672
 *
673
 * - "name": command's name
674
 *
675
 * Example:
676
 *
677
 * { [ { "name": "query-balloon" }, { "name": "system_powerdown" } ] }
678
 */
679
static void do_info_commands(Monitor *mon, QObject **ret_data)
680
{
681
    QList *cmd_list;
682
    const mon_cmd_t *cmd;
683

    
684
    cmd_list = qlist_new();
685

    
686
    for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
687
        if (monitor_handler_ported(cmd) && !compare_cmd(cmd->name, "info")) {
688
            qlist_append_obj(cmd_list, get_cmd_dict(cmd->name));
689
        }
690
    }
691

    
692
    for (cmd = info_cmds; cmd->name != NULL; cmd++) {
693
        if (monitor_handler_ported(cmd)) {
694
            char buf[128];
695
            snprintf(buf, sizeof(buf), "query-%s", cmd->name);
696
            qlist_append_obj(cmd_list, get_cmd_dict(buf));
697
        }
698
    }
699

    
700
    *ret_data = QOBJECT(cmd_list);
701
}
702

    
703
#if defined(TARGET_I386)
704
static void do_info_hpet_print(Monitor *mon, const QObject *data)
705
{
706
    monitor_printf(mon, "HPET is %s by QEMU\n",
707
                   qdict_get_bool(qobject_to_qdict(data), "enabled") ?
708
                   "enabled" : "disabled");
709
}
710

    
711
/**
712
 * do_info_hpet(): Show HPET state
713
 *
714
 * Return a QDict with the following information:
715
 *
716
 * - "enabled": true if hpet if enabled, false otherwise
717
 *
718
 * Example:
719
 *
720
 * { "enabled": true }
721
 */
722
static void do_info_hpet(Monitor *mon, QObject **ret_data)
723
{
724
    *ret_data = qobject_from_jsonf("{ 'enabled': %i }", !no_hpet);
725
}
726
#endif
727

    
728
static void do_info_uuid_print(Monitor *mon, const QObject *data)
729
{
730
    monitor_printf(mon, "%s\n", qdict_get_str(qobject_to_qdict(data), "UUID"));
731
}
732

    
733
/**
734
 * do_info_uuid(): Show VM UUID
735
 *
736
 * Return a QDict with the following information:
737
 *
738
 * - "UUID": Universally Unique Identifier
739
 *
740
 * Example:
741
 *
742
 * { "UUID": "550e8400-e29b-41d4-a716-446655440000" }
743
 */
744
static void do_info_uuid(Monitor *mon, QObject **ret_data)
745
{
746
    char uuid[64];
747

    
748
    snprintf(uuid, sizeof(uuid), UUID_FMT, qemu_uuid[0], qemu_uuid[1],
749
                   qemu_uuid[2], qemu_uuid[3], qemu_uuid[4], qemu_uuid[5],
750
                   qemu_uuid[6], qemu_uuid[7], qemu_uuid[8], qemu_uuid[9],
751
                   qemu_uuid[10], qemu_uuid[11], qemu_uuid[12], qemu_uuid[13],
752
                   qemu_uuid[14], qemu_uuid[15]);
753
    *ret_data = qobject_from_jsonf("{ 'UUID': %s }", uuid);
754
}
755

    
756
/* get the current CPU defined by the user */
757
static int mon_set_cpu(int cpu_index)
758
{
759
    CPUState *env;
760

    
761
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
762
        if (env->cpu_index == cpu_index) {
763
            cur_mon->mon_cpu = env;
764
            return 0;
765
        }
766
    }
767
    return -1;
768
}
769

    
770
static CPUState *mon_get_cpu(void)
771
{
772
    if (!cur_mon->mon_cpu) {
773
        mon_set_cpu(0);
774
    }
775
    cpu_synchronize_state(cur_mon->mon_cpu);
776
    return cur_mon->mon_cpu;
777
}
778

    
779
static void do_info_registers(Monitor *mon)
780
{
781
    CPUState *env;
782
    env = mon_get_cpu();
783
#ifdef TARGET_I386
784
    cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
785
                   X86_DUMP_FPU);
786
#else
787
    cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
788
                   0);
789
#endif
790
}
791

    
792
static void print_cpu_iter(QObject *obj, void *opaque)
793
{
794
    QDict *cpu;
795
    int active = ' ';
796
    Monitor *mon = opaque;
797

    
798
    assert(qobject_type(obj) == QTYPE_QDICT);
799
    cpu = qobject_to_qdict(obj);
800

    
801
    if (qdict_get_bool(cpu, "current")) {
802
        active = '*';
803
    }
804

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

    
807
#if defined(TARGET_I386)
808
    monitor_printf(mon, "pc=0x" TARGET_FMT_lx,
809
                   (target_ulong) qdict_get_int(cpu, "pc"));
810
#elif defined(TARGET_PPC)
811
    monitor_printf(mon, "nip=0x" TARGET_FMT_lx,
812
                   (target_long) qdict_get_int(cpu, "nip"));
813
#elif defined(TARGET_SPARC)
814
    monitor_printf(mon, "pc=0x " TARGET_FMT_lx,
815
                   (target_long) qdict_get_int(cpu, "pc"));
816
    monitor_printf(mon, "npc=0x" TARGET_FMT_lx,
817
                   (target_long) qdict_get_int(cpu, "npc"));
818
#elif defined(TARGET_MIPS)
819
    monitor_printf(mon, "PC=0x" TARGET_FMT_lx,
820
                   (target_long) qdict_get_int(cpu, "PC"));
821
#endif
822

    
823
    if (qdict_get_bool(cpu, "halted")) {
824
        monitor_printf(mon, " (halted)");
825
    }
826

    
827
    monitor_printf(mon, "\n");
828
}
829

    
830
static void monitor_print_cpus(Monitor *mon, const QObject *data)
831
{
832
    QList *cpu_list;
833

    
834
    assert(qobject_type(data) == QTYPE_QLIST);
835
    cpu_list = qobject_to_qlist(data);
836
    qlist_iter(cpu_list, print_cpu_iter, mon);
837
}
838

    
839
/**
840
 * do_info_cpus(): Show CPU information
841
 *
842
 * Return a QList. Each CPU is represented by a QDict, which contains:
843
 *
844
 * - "cpu": CPU index
845
 * - "current": true if this is the current CPU, false otherwise
846
 * - "halted": true if the cpu is halted, false otherwise
847
 * - Current program counter. The key's name depends on the architecture:
848
 *      "pc": i386/x86)64
849
 *      "nip": PPC
850
 *      "pc" and "npc": sparc
851
 *      "PC": mips
852
 *
853
 * Example:
854
 *
855
 * [ { "CPU": 0, "current": true, "halted": false, "pc": 3227107138 },
856
 *   { "CPU": 1, "current": false, "halted": true, "pc": 7108165 } ]
857
 */
858
static void do_info_cpus(Monitor *mon, QObject **ret_data)
859
{
860
    CPUState *env;
861
    QList *cpu_list;
862

    
863
    cpu_list = qlist_new();
864

    
865
    /* just to set the default cpu if not already done */
866
    mon_get_cpu();
867

    
868
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
869
        QDict *cpu;
870
        QObject *obj;
871

    
872
        cpu_synchronize_state(env);
873

    
874
        obj = qobject_from_jsonf("{ 'CPU': %d, 'current': %i, 'halted': %i }",
875
                                 env->cpu_index, env == mon->mon_cpu,
876
                                 env->halted);
877
        assert(obj != NULL);
878

    
879
        cpu = qobject_to_qdict(obj);
880

    
881
#if defined(TARGET_I386)
882
        qdict_put(cpu, "pc", qint_from_int(env->eip + env->segs[R_CS].base));
883
#elif defined(TARGET_PPC)
884
        qdict_put(cpu, "nip", qint_from_int(env->nip));
885
#elif defined(TARGET_SPARC)
886
        qdict_put(cpu, "pc", qint_from_int(env->pc));
887
        qdict_put(cpu, "npc", qint_from_int(env->npc));
888
#elif defined(TARGET_MIPS)
889
        qdict_put(cpu, "PC", qint_from_int(env->active_tc.PC));
890
#endif
891

    
892
        qlist_append(cpu_list, cpu);
893
    }
894

    
895
    *ret_data = QOBJECT(cpu_list);
896
}
897

    
898
static void do_cpu_set(Monitor *mon, const QDict *qdict, QObject **ret_data)
899
{
900
    int index = qdict_get_int(qdict, "index");
901
    if (mon_set_cpu(index) < 0)
902
        qemu_error_new(QERR_INVALID_CPU_INDEX);
903
}
904

    
905
static void do_info_jit(Monitor *mon)
906
{
907
    dump_exec_info((FILE *)mon, monitor_fprintf);
908
}
909

    
910
static void do_info_history(Monitor *mon)
911
{
912
    int i;
913
    const char *str;
914

    
915
    if (!mon->rs)
916
        return;
917
    i = 0;
918
    for(;;) {
919
        str = readline_get_history(mon->rs, i);
920
        if (!str)
921
            break;
922
        monitor_printf(mon, "%d: '%s'\n", i, str);
923
        i++;
924
    }
925
}
926

    
927
#if defined(TARGET_PPC)
928
/* XXX: not implemented in other targets */
929
static void do_info_cpu_stats(Monitor *mon)
930
{
931
    CPUState *env;
932

    
933
    env = mon_get_cpu();
934
    cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
935
}
936
#endif
937

    
938
/**
939
 * do_quit(): Quit QEMU execution
940
 */
941
static void do_quit(Monitor *mon, const QDict *qdict, QObject **ret_data)
942
{
943
    exit(0);
944
}
945

    
946
static int eject_device(Monitor *mon, BlockDriverState *bs, int force)
947
{
948
    if (bdrv_is_inserted(bs)) {
949
        if (!force) {
950
            if (!bdrv_is_removable(bs)) {
951
                qemu_error_new(QERR_DEVICE_NOT_REMOVABLE,
952
                               bdrv_get_device_name(bs));
953
                return -1;
954
            }
955
            if (bdrv_is_locked(bs)) {
956
                qemu_error_new(QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));
957
                return -1;
958
            }
959
        }
960
        bdrv_close(bs);
961
    }
962
    return 0;
963
}
964

    
965
static void do_eject(Monitor *mon, const QDict *qdict, QObject **ret_data)
966
{
967
    BlockDriverState *bs;
968
    int force = qdict_get_int(qdict, "force");
969
    const char *filename = qdict_get_str(qdict, "device");
970

    
971
    bs = bdrv_find(filename);
972
    if (!bs) {
973
        qemu_error_new(QERR_DEVICE_NOT_FOUND, filename);
974
        return;
975
    }
976
    eject_device(mon, bs, force);
977
}
978

    
979
static void do_block_set_passwd(Monitor *mon, const QDict *qdict,
980
                                QObject **ret_data)
981
{
982
    BlockDriverState *bs;
983

    
984
    bs = bdrv_find(qdict_get_str(qdict, "device"));
985
    if (!bs) {
986
        qemu_error_new(QERR_DEVICE_NOT_FOUND, qdict_get_str(qdict, "device"));
987
        return;
988
    }
989

    
990
    if (bdrv_set_key(bs, qdict_get_str(qdict, "password")) < 0) {
991
        qemu_error_new(QERR_INVALID_PASSWORD);
992
    }
993
}
994

    
995
static void do_change_block(Monitor *mon, const char *device,
996
                            const char *filename, const char *fmt)
997
{
998
    BlockDriverState *bs;
999
    BlockDriver *drv = NULL;
1000

    
1001
    bs = bdrv_find(device);
1002
    if (!bs) {
1003
        qemu_error_new(QERR_DEVICE_NOT_FOUND, device);
1004
        return;
1005
    }
1006
    if (fmt) {
1007
        drv = bdrv_find_whitelisted_format(fmt);
1008
        if (!drv) {
1009
            qemu_error_new(QERR_INVALID_BLOCK_FORMAT, fmt);
1010
            return;
1011
        }
1012
    }
1013
    if (eject_device(mon, bs, 0) < 0)
1014
        return;
1015
    bdrv_open2(bs, filename, BDRV_O_RDWR, drv);
1016
    monitor_read_bdrv_key_start(mon, bs, NULL, NULL);
1017
}
1018

    
1019
static void change_vnc_password(const char *password)
1020
{
1021
    if (vnc_display_password(NULL, password) < 0)
1022
        qemu_error_new(QERR_SET_PASSWD_FAILED);
1023

    
1024
}
1025

    
1026
static void change_vnc_password_cb(Monitor *mon, const char *password,
1027
                                   void *opaque)
1028
{
1029
    change_vnc_password(password);
1030
    monitor_read_command(mon, 1);
1031
}
1032

    
1033
static void do_change_vnc(Monitor *mon, const char *target, const char *arg)
1034
{
1035
    if (strcmp(target, "passwd") == 0 ||
1036
        strcmp(target, "password") == 0) {
1037
        if (arg) {
1038
            char password[9];
1039
            strncpy(password, arg, sizeof(password));
1040
            password[sizeof(password) - 1] = '\0';
1041
            change_vnc_password(password);
1042
        } else {
1043
            monitor_read_password(mon, change_vnc_password_cb, NULL);
1044
        }
1045
    } else {
1046
        if (vnc_display_open(NULL, target) < 0)
1047
            qemu_error_new(QERR_VNC_SERVER_FAILED, target);
1048
    }
1049
}
1050

    
1051
/**
1052
 * do_change(): Change a removable medium, or VNC configuration
1053
 */
1054
static void do_change(Monitor *mon, const QDict *qdict, QObject **ret_data)
1055
{
1056
    const char *device = qdict_get_str(qdict, "device");
1057
    const char *target = qdict_get_str(qdict, "target");
1058
    const char *arg = qdict_get_try_str(qdict, "arg");
1059
    if (strcmp(device, "vnc") == 0) {
1060
        do_change_vnc(mon, target, arg);
1061
    } else {
1062
        do_change_block(mon, device, target, arg);
1063
    }
1064
}
1065

    
1066
static void do_screen_dump(Monitor *mon, const QDict *qdict)
1067
{
1068
    vga_hw_screen_dump(qdict_get_str(qdict, "filename"));
1069
}
1070

    
1071
static void do_logfile(Monitor *mon, const QDict *qdict)
1072
{
1073
    cpu_set_log_filename(qdict_get_str(qdict, "filename"));
1074
}
1075

    
1076
static void do_log(Monitor *mon, const QDict *qdict)
1077
{
1078
    int mask;
1079
    const char *items = qdict_get_str(qdict, "items");
1080

    
1081
    if (!strcmp(items, "none")) {
1082
        mask = 0;
1083
    } else {
1084
        mask = cpu_str_to_log_mask(items);
1085
        if (!mask) {
1086
            help_cmd(mon, "log");
1087
            return;
1088
        }
1089
    }
1090
    cpu_set_log(mask);
1091
}
1092

    
1093
static void do_singlestep(Monitor *mon, const QDict *qdict)
1094
{
1095
    const char *option = qdict_get_try_str(qdict, "option");
1096
    if (!option || !strcmp(option, "on")) {
1097
        singlestep = 1;
1098
    } else if (!strcmp(option, "off")) {
1099
        singlestep = 0;
1100
    } else {
1101
        monitor_printf(mon, "unexpected option %s\n", option);
1102
    }
1103
}
1104

    
1105
/**
1106
 * do_stop(): Stop VM execution
1107
 */
1108
static void do_stop(Monitor *mon, const QDict *qdict, QObject **ret_data)
1109
{
1110
    vm_stop(EXCP_INTERRUPT);
1111
}
1112

    
1113
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs);
1114

    
1115
struct bdrv_iterate_context {
1116
    Monitor *mon;
1117
    int err;
1118
};
1119

    
1120
/**
1121
 * do_cont(): Resume emulation.
1122
 */
1123
static void do_cont(Monitor *mon, const QDict *qdict, QObject **ret_data)
1124
{
1125
    struct bdrv_iterate_context context = { mon, 0 };
1126

    
1127
    bdrv_iterate(encrypted_bdrv_it, &context);
1128
    /* only resume the vm if all keys are set and valid */
1129
    if (!context.err)
1130
        vm_start();
1131
}
1132

    
1133
static void bdrv_key_cb(void *opaque, int err)
1134
{
1135
    Monitor *mon = opaque;
1136

    
1137
    /* another key was set successfully, retry to continue */
1138
    if (!err)
1139
        do_cont(mon, NULL, NULL);
1140
}
1141

    
1142
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs)
1143
{
1144
    struct bdrv_iterate_context *context = opaque;
1145

    
1146
    if (!context->err && bdrv_key_required(bs)) {
1147
        context->err = -EBUSY;
1148
        monitor_read_bdrv_key_start(context->mon, bs, bdrv_key_cb,
1149
                                    context->mon);
1150
    }
1151
}
1152

    
1153
static void do_gdbserver(Monitor *mon, const QDict *qdict)
1154
{
1155
    const char *device = qdict_get_try_str(qdict, "device");
1156
    if (!device)
1157
        device = "tcp::" DEFAULT_GDBSTUB_PORT;
1158
    if (gdbserver_start(device) < 0) {
1159
        monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1160
                       device);
1161
    } else if (strcmp(device, "none") == 0) {
1162
        monitor_printf(mon, "Disabled gdbserver\n");
1163
    } else {
1164
        monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1165
                       device);
1166
    }
1167
}
1168

    
1169
static void do_watchdog_action(Monitor *mon, const QDict *qdict)
1170
{
1171
    const char *action = qdict_get_str(qdict, "action");
1172
    if (select_watchdog_action(action) == -1) {
1173
        monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1174
    }
1175
}
1176

    
1177
static void monitor_printc(Monitor *mon, int c)
1178
{
1179
    monitor_printf(mon, "'");
1180
    switch(c) {
1181
    case '\'':
1182
        monitor_printf(mon, "\\'");
1183
        break;
1184
    case '\\':
1185
        monitor_printf(mon, "\\\\");
1186
        break;
1187
    case '\n':
1188
        monitor_printf(mon, "\\n");
1189
        break;
1190
    case '\r':
1191
        monitor_printf(mon, "\\r");
1192
        break;
1193
    default:
1194
        if (c >= 32 && c <= 126) {
1195
            monitor_printf(mon, "%c", c);
1196
        } else {
1197
            monitor_printf(mon, "\\x%02x", c);
1198
        }
1199
        break;
1200
    }
1201
    monitor_printf(mon, "'");
1202
}
1203

    
1204
static void memory_dump(Monitor *mon, int count, int format, int wsize,
1205
                        target_phys_addr_t addr, int is_physical)
1206
{
1207
    CPUState *env;
1208
    int l, line_size, i, max_digits, len;
1209
    uint8_t buf[16];
1210
    uint64_t v;
1211

    
1212
    if (format == 'i') {
1213
        int flags;
1214
        flags = 0;
1215
        env = mon_get_cpu();
1216
        if (!is_physical)
1217
            return;
1218
#ifdef TARGET_I386
1219
        if (wsize == 2) {
1220
            flags = 1;
1221
        } else if (wsize == 4) {
1222
            flags = 0;
1223
        } else {
1224
            /* as default we use the current CS size */
1225
            flags = 0;
1226
            if (env) {
1227
#ifdef TARGET_X86_64
1228
                if ((env->efer & MSR_EFER_LMA) &&
1229
                    (env->segs[R_CS].flags & DESC_L_MASK))
1230
                    flags = 2;
1231
                else
1232
#endif
1233
                if (!(env->segs[R_CS].flags & DESC_B_MASK))
1234
                    flags = 1;
1235
            }
1236
        }
1237
#endif
1238
        monitor_disas(mon, env, addr, count, is_physical, flags);
1239
        return;
1240
    }
1241

    
1242
    len = wsize * count;
1243
    if (wsize == 1)
1244
        line_size = 8;
1245
    else
1246
        line_size = 16;
1247
    max_digits = 0;
1248

    
1249
    switch(format) {
1250
    case 'o':
1251
        max_digits = (wsize * 8 + 2) / 3;
1252
        break;
1253
    default:
1254
    case 'x':
1255
        max_digits = (wsize * 8) / 4;
1256
        break;
1257
    case 'u':
1258
    case 'd':
1259
        max_digits = (wsize * 8 * 10 + 32) / 33;
1260
        break;
1261
    case 'c':
1262
        wsize = 1;
1263
        break;
1264
    }
1265

    
1266
    while (len > 0) {
1267
        if (is_physical)
1268
            monitor_printf(mon, TARGET_FMT_plx ":", addr);
1269
        else
1270
            monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
1271
        l = len;
1272
        if (l > line_size)
1273
            l = line_size;
1274
        if (is_physical) {
1275
            cpu_physical_memory_rw(addr, buf, l, 0);
1276
        } else {
1277
            env = mon_get_cpu();
1278
            if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {
1279
                monitor_printf(mon, " Cannot access memory\n");
1280
                break;
1281
            }
1282
        }
1283
        i = 0;
1284
        while (i < l) {
1285
            switch(wsize) {
1286
            default:
1287
            case 1:
1288
                v = ldub_raw(buf + i);
1289
                break;
1290
            case 2:
1291
                v = lduw_raw(buf + i);
1292
                break;
1293
            case 4:
1294
                v = (uint32_t)ldl_raw(buf + i);
1295
                break;
1296
            case 8:
1297
                v = ldq_raw(buf + i);
1298
                break;
1299
            }
1300
            monitor_printf(mon, " ");
1301
            switch(format) {
1302
            case 'o':
1303
                monitor_printf(mon, "%#*" PRIo64, max_digits, v);
1304
                break;
1305
            case 'x':
1306
                monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
1307
                break;
1308
            case 'u':
1309
                monitor_printf(mon, "%*" PRIu64, max_digits, v);
1310
                break;
1311
            case 'd':
1312
                monitor_printf(mon, "%*" PRId64, max_digits, v);
1313
                break;
1314
            case 'c':
1315
                monitor_printc(mon, v);
1316
                break;
1317
            }
1318
            i += wsize;
1319
        }
1320
        monitor_printf(mon, "\n");
1321
        addr += l;
1322
        len -= l;
1323
    }
1324
}
1325

    
1326
static void do_memory_dump(Monitor *mon, const QDict *qdict)
1327
{
1328
    int count = qdict_get_int(qdict, "count");
1329
    int format = qdict_get_int(qdict, "format");
1330
    int size = qdict_get_int(qdict, "size");
1331
    target_long addr = qdict_get_int(qdict, "addr");
1332

    
1333
    memory_dump(mon, count, format, size, addr, 0);
1334
}
1335

    
1336
static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
1337
{
1338
    int count = qdict_get_int(qdict, "count");
1339
    int format = qdict_get_int(qdict, "format");
1340
    int size = qdict_get_int(qdict, "size");
1341
    target_phys_addr_t addr = qdict_get_int(qdict, "addr");
1342

    
1343
    memory_dump(mon, count, format, size, addr, 1);
1344
}
1345

    
1346
static void do_print(Monitor *mon, const QDict *qdict)
1347
{
1348
    int format = qdict_get_int(qdict, "format");
1349
    target_phys_addr_t val = qdict_get_int(qdict, "val");
1350

    
1351
#if TARGET_PHYS_ADDR_BITS == 32
1352
    switch(format) {
1353
    case 'o':
1354
        monitor_printf(mon, "%#o", val);
1355
        break;
1356
    case 'x':
1357
        monitor_printf(mon, "%#x", val);
1358
        break;
1359
    case 'u':
1360
        monitor_printf(mon, "%u", val);
1361
        break;
1362
    default:
1363
    case 'd':
1364
        monitor_printf(mon, "%d", val);
1365
        break;
1366
    case 'c':
1367
        monitor_printc(mon, val);
1368
        break;
1369
    }
1370
#else
1371
    switch(format) {
1372
    case 'o':
1373
        monitor_printf(mon, "%#" PRIo64, val);
1374
        break;
1375
    case 'x':
1376
        monitor_printf(mon, "%#" PRIx64, val);
1377
        break;
1378
    case 'u':
1379
        monitor_printf(mon, "%" PRIu64, val);
1380
        break;
1381
    default:
1382
    case 'd':
1383
        monitor_printf(mon, "%" PRId64, val);
1384
        break;
1385
    case 'c':
1386
        monitor_printc(mon, val);
1387
        break;
1388
    }
1389
#endif
1390
    monitor_printf(mon, "\n");
1391
}
1392

    
1393
static void do_memory_save(Monitor *mon, const QDict *qdict, QObject **ret_data)
1394
{
1395
    FILE *f;
1396
    uint32_t size = qdict_get_int(qdict, "size");
1397
    const char *filename = qdict_get_str(qdict, "filename");
1398
    target_long addr = qdict_get_int(qdict, "val");
1399
    uint32_t l;
1400
    CPUState *env;
1401
    uint8_t buf[1024];
1402

    
1403
    env = mon_get_cpu();
1404

    
1405
    f = fopen(filename, "wb");
1406
    if (!f) {
1407
        qemu_error_new(QERR_OPEN_FILE_FAILED, filename);
1408
        return;
1409
    }
1410
    while (size != 0) {
1411
        l = sizeof(buf);
1412
        if (l > size)
1413
            l = size;
1414
        cpu_memory_rw_debug(env, addr, buf, l, 0);
1415
        if (fwrite(buf, 1, l, f) != l) {
1416
            monitor_printf(mon, "fwrite() error in do_memory_save\n");
1417
            goto exit;
1418
        }
1419
        addr += l;
1420
        size -= l;
1421
    }
1422
exit:
1423
    fclose(f);
1424
}
1425

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

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

    
1458
static void do_sum(Monitor *mon, const QDict *qdict)
1459
{
1460
    uint32_t addr;
1461
    uint8_t buf[1];
1462
    uint16_t sum;
1463
    uint32_t start = qdict_get_int(qdict, "start");
1464
    uint32_t size = qdict_get_int(qdict, "size");
1465

    
1466
    sum = 0;
1467
    for(addr = start; addr < (start + size); addr++) {
1468
        cpu_physical_memory_rw(addr, buf, 1, 0);
1469
        /* BSD sum algorithm ('sum' Unix command) */
1470
        sum = (sum >> 1) | (sum << 15);
1471
        sum += buf[0];
1472
    }
1473
    monitor_printf(mon, "%05d\n", sum);
1474
}
1475

    
1476
typedef struct {
1477
    int keycode;
1478
    const char *name;
1479
} KeyDef;
1480

    
1481
static const KeyDef key_defs[] = {
1482
    { 0x2a, "shift" },
1483
    { 0x36, "shift_r" },
1484

    
1485
    { 0x38, "alt" },
1486
    { 0xb8, "alt_r" },
1487
    { 0x64, "altgr" },
1488
    { 0xe4, "altgr_r" },
1489
    { 0x1d, "ctrl" },
1490
    { 0x9d, "ctrl_r" },
1491

    
1492
    { 0xdd, "menu" },
1493

    
1494
    { 0x01, "esc" },
1495

    
1496
    { 0x02, "1" },
1497
    { 0x03, "2" },
1498
    { 0x04, "3" },
1499
    { 0x05, "4" },
1500
    { 0x06, "5" },
1501
    { 0x07, "6" },
1502
    { 0x08, "7" },
1503
    { 0x09, "8" },
1504
    { 0x0a, "9" },
1505
    { 0x0b, "0" },
1506
    { 0x0c, "minus" },
1507
    { 0x0d, "equal" },
1508
    { 0x0e, "backspace" },
1509

    
1510
    { 0x0f, "tab" },
1511
    { 0x10, "q" },
1512
    { 0x11, "w" },
1513
    { 0x12, "e" },
1514
    { 0x13, "r" },
1515
    { 0x14, "t" },
1516
    { 0x15, "y" },
1517
    { 0x16, "u" },
1518
    { 0x17, "i" },
1519
    { 0x18, "o" },
1520
    { 0x19, "p" },
1521

    
1522
    { 0x1c, "ret" },
1523

    
1524
    { 0x1e, "a" },
1525
    { 0x1f, "s" },
1526
    { 0x20, "d" },
1527
    { 0x21, "f" },
1528
    { 0x22, "g" },
1529
    { 0x23, "h" },
1530
    { 0x24, "j" },
1531
    { 0x25, "k" },
1532
    { 0x26, "l" },
1533

    
1534
    { 0x2c, "z" },
1535
    { 0x2d, "x" },
1536
    { 0x2e, "c" },
1537
    { 0x2f, "v" },
1538
    { 0x30, "b" },
1539
    { 0x31, "n" },
1540
    { 0x32, "m" },
1541
    { 0x33, "comma" },
1542
    { 0x34, "dot" },
1543
    { 0x35, "slash" },
1544

    
1545
    { 0x37, "asterisk" },
1546

    
1547
    { 0x39, "spc" },
1548
    { 0x3a, "caps_lock" },
1549
    { 0x3b, "f1" },
1550
    { 0x3c, "f2" },
1551
    { 0x3d, "f3" },
1552
    { 0x3e, "f4" },
1553
    { 0x3f, "f5" },
1554
    { 0x40, "f6" },
1555
    { 0x41, "f7" },
1556
    { 0x42, "f8" },
1557
    { 0x43, "f9" },
1558
    { 0x44, "f10" },
1559
    { 0x45, "num_lock" },
1560
    { 0x46, "scroll_lock" },
1561

    
1562
    { 0xb5, "kp_divide" },
1563
    { 0x37, "kp_multiply" },
1564
    { 0x4a, "kp_subtract" },
1565
    { 0x4e, "kp_add" },
1566
    { 0x9c, "kp_enter" },
1567
    { 0x53, "kp_decimal" },
1568
    { 0x54, "sysrq" },
1569

    
1570
    { 0x52, "kp_0" },
1571
    { 0x4f, "kp_1" },
1572
    { 0x50, "kp_2" },
1573
    { 0x51, "kp_3" },
1574
    { 0x4b, "kp_4" },
1575
    { 0x4c, "kp_5" },
1576
    { 0x4d, "kp_6" },
1577
    { 0x47, "kp_7" },
1578
    { 0x48, "kp_8" },
1579
    { 0x49, "kp_9" },
1580

    
1581
    { 0x56, "<" },
1582

    
1583
    { 0x57, "f11" },
1584
    { 0x58, "f12" },
1585

    
1586
    { 0xb7, "print" },
1587

    
1588
    { 0xc7, "home" },
1589
    { 0xc9, "pgup" },
1590
    { 0xd1, "pgdn" },
1591
    { 0xcf, "end" },
1592

    
1593
    { 0xcb, "left" },
1594
    { 0xc8, "up" },
1595
    { 0xd0, "down" },
1596
    { 0xcd, "right" },
1597

    
1598
    { 0xd2, "insert" },
1599
    { 0xd3, "delete" },
1600
#if defined(TARGET_SPARC) && !defined(TARGET_SPARC64)
1601
    { 0xf0, "stop" },
1602
    { 0xf1, "again" },
1603
    { 0xf2, "props" },
1604
    { 0xf3, "undo" },
1605
    { 0xf4, "front" },
1606
    { 0xf5, "copy" },
1607
    { 0xf6, "open" },
1608
    { 0xf7, "paste" },
1609
    { 0xf8, "find" },
1610
    { 0xf9, "cut" },
1611
    { 0xfa, "lf" },
1612
    { 0xfb, "help" },
1613
    { 0xfc, "meta_l" },
1614
    { 0xfd, "meta_r" },
1615
    { 0xfe, "compose" },
1616
#endif
1617
    { 0, NULL },
1618
};
1619

    
1620
static int get_keycode(const char *key)
1621
{
1622
    const KeyDef *p;
1623
    char *endp;
1624
    int ret;
1625

    
1626
    for(p = key_defs; p->name != NULL; p++) {
1627
        if (!strcmp(key, p->name))
1628
            return p->keycode;
1629
    }
1630
    if (strstart(key, "0x", NULL)) {
1631
        ret = strtoul(key, &endp, 0);
1632
        if (*endp == '\0' && ret >= 0x01 && ret <= 0xff)
1633
            return ret;
1634
    }
1635
    return -1;
1636
}
1637

    
1638
#define MAX_KEYCODES 16
1639
static uint8_t keycodes[MAX_KEYCODES];
1640
static int nb_pending_keycodes;
1641
static QEMUTimer *key_timer;
1642

    
1643
static void release_keys(void *opaque)
1644
{
1645
    int keycode;
1646

    
1647
    while (nb_pending_keycodes > 0) {
1648
        nb_pending_keycodes--;
1649
        keycode = keycodes[nb_pending_keycodes];
1650
        if (keycode & 0x80)
1651
            kbd_put_keycode(0xe0);
1652
        kbd_put_keycode(keycode | 0x80);
1653
    }
1654
}
1655

    
1656
static void do_sendkey(Monitor *mon, const QDict *qdict)
1657
{
1658
    char keyname_buf[16];
1659
    char *separator;
1660
    int keyname_len, keycode, i;
1661
    const char *string = qdict_get_str(qdict, "string");
1662
    int has_hold_time = qdict_haskey(qdict, "hold_time");
1663
    int hold_time = qdict_get_try_int(qdict, "hold_time", -1);
1664

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

    
1710
static int mouse_button_state;
1711

    
1712
static void do_mouse_move(Monitor *mon, const QDict *qdict)
1713
{
1714
    int dx, dy, dz;
1715
    const char *dx_str = qdict_get_str(qdict, "dx_str");
1716
    const char *dy_str = qdict_get_str(qdict, "dy_str");
1717
    const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1718
    dx = strtol(dx_str, NULL, 0);
1719
    dy = strtol(dy_str, NULL, 0);
1720
    dz = 0;
1721
    if (dz_str)
1722
        dz = strtol(dz_str, NULL, 0);
1723
    kbd_mouse_event(dx, dy, dz, mouse_button_state);
1724
}
1725

    
1726
static void do_mouse_button(Monitor *mon, const QDict *qdict)
1727
{
1728
    int button_state = qdict_get_int(qdict, "button_state");
1729
    mouse_button_state = button_state;
1730
    kbd_mouse_event(0, 0, 0, mouse_button_state);
1731
}
1732

    
1733
static void do_ioport_read(Monitor *mon, const QDict *qdict)
1734
{
1735
    int size = qdict_get_int(qdict, "size");
1736
    int addr = qdict_get_int(qdict, "addr");
1737
    int has_index = qdict_haskey(qdict, "index");
1738
    uint32_t val;
1739
    int suffix;
1740

    
1741
    if (has_index) {
1742
        int index = qdict_get_int(qdict, "index");
1743
        cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1744
        addr++;
1745
    }
1746
    addr &= 0xffff;
1747

    
1748
    switch(size) {
1749
    default:
1750
    case 1:
1751
        val = cpu_inb(addr);
1752
        suffix = 'b';
1753
        break;
1754
    case 2:
1755
        val = cpu_inw(addr);
1756
        suffix = 'w';
1757
        break;
1758
    case 4:
1759
        val = cpu_inl(addr);
1760
        suffix = 'l';
1761
        break;
1762
    }
1763
    monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1764
                   suffix, addr, size * 2, val);
1765
}
1766

    
1767
static void do_ioport_write(Monitor *mon, const QDict *qdict)
1768
{
1769
    int size = qdict_get_int(qdict, "size");
1770
    int addr = qdict_get_int(qdict, "addr");
1771
    int val = qdict_get_int(qdict, "val");
1772

    
1773
    addr &= IOPORTS_MASK;
1774

    
1775
    switch (size) {
1776
    default:
1777
    case 1:
1778
        cpu_outb(addr, val);
1779
        break;
1780
    case 2:
1781
        cpu_outw(addr, val);
1782
        break;
1783
    case 4:
1784
        cpu_outl(addr, val);
1785
        break;
1786
    }
1787
}
1788

    
1789
static void do_boot_set(Monitor *mon, const QDict *qdict)
1790
{
1791
    int res;
1792
    const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1793

    
1794
    res = qemu_boot_set(bootdevice);
1795
    if (res == 0) {
1796
        monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1797
    } else if (res > 0) {
1798
        monitor_printf(mon, "setting boot device list failed\n");
1799
    } else {
1800
        monitor_printf(mon, "no function defined to set boot device list for "
1801
                       "this architecture\n");
1802
    }
1803
}
1804

    
1805
/**
1806
 * do_system_reset(): Issue a machine reset
1807
 */
1808
static void do_system_reset(Monitor *mon, const QDict *qdict,
1809
                            QObject **ret_data)
1810
{
1811
    qemu_system_reset_request();
1812
}
1813

    
1814
/**
1815
 * do_system_powerdown(): Issue a machine powerdown
1816
 */
1817
static void do_system_powerdown(Monitor *mon, const QDict *qdict,
1818
                                QObject **ret_data)
1819
{
1820
    qemu_system_powerdown_request();
1821
}
1822

    
1823
#if defined(TARGET_I386)
1824
static void print_pte(Monitor *mon, uint32_t addr, uint32_t pte, uint32_t mask)
1825
{
1826
    monitor_printf(mon, "%08x: %08x %c%c%c%c%c%c%c%c\n",
1827
                   addr,
1828
                   pte & mask,
1829
                   pte & PG_GLOBAL_MASK ? 'G' : '-',
1830
                   pte & PG_PSE_MASK ? 'P' : '-',
1831
                   pte & PG_DIRTY_MASK ? 'D' : '-',
1832
                   pte & PG_ACCESSED_MASK ? 'A' : '-',
1833
                   pte & PG_PCD_MASK ? 'C' : '-',
1834
                   pte & PG_PWT_MASK ? 'T' : '-',
1835
                   pte & PG_USER_MASK ? 'U' : '-',
1836
                   pte & PG_RW_MASK ? 'W' : '-');
1837
}
1838

    
1839
static void tlb_info(Monitor *mon)
1840
{
1841
    CPUState *env;
1842
    int l1, l2;
1843
    uint32_t pgd, pde, pte;
1844

    
1845
    env = mon_get_cpu();
1846

    
1847
    if (!(env->cr[0] & CR0_PG_MASK)) {
1848
        monitor_printf(mon, "PG disabled\n");
1849
        return;
1850
    }
1851
    pgd = env->cr[3] & ~0xfff;
1852
    for(l1 = 0; l1 < 1024; l1++) {
1853
        cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1854
        pde = le32_to_cpu(pde);
1855
        if (pde & PG_PRESENT_MASK) {
1856
            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1857
                print_pte(mon, (l1 << 22), pde, ~((1 << 20) - 1));
1858
            } else {
1859
                for(l2 = 0; l2 < 1024; l2++) {
1860
                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1861
                                             (uint8_t *)&pte, 4);
1862
                    pte = le32_to_cpu(pte);
1863
                    if (pte & PG_PRESENT_MASK) {
1864
                        print_pte(mon, (l1 << 22) + (l2 << 12),
1865
                                  pte & ~PG_PSE_MASK,
1866
                                  ~0xfff);
1867
                    }
1868
                }
1869
            }
1870
        }
1871
    }
1872
}
1873

    
1874
static void mem_print(Monitor *mon, uint32_t *pstart, int *plast_prot,
1875
                      uint32_t end, int prot)
1876
{
1877
    int prot1;
1878
    prot1 = *plast_prot;
1879
    if (prot != prot1) {
1880
        if (*pstart != -1) {
1881
            monitor_printf(mon, "%08x-%08x %08x %c%c%c\n",
1882
                           *pstart, end, end - *pstart,
1883
                           prot1 & PG_USER_MASK ? 'u' : '-',
1884
                           'r',
1885
                           prot1 & PG_RW_MASK ? 'w' : '-');
1886
        }
1887
        if (prot != 0)
1888
            *pstart = end;
1889
        else
1890
            *pstart = -1;
1891
        *plast_prot = prot;
1892
    }
1893
}
1894

    
1895
static void mem_info(Monitor *mon)
1896
{
1897
    CPUState *env;
1898
    int l1, l2, prot, last_prot;
1899
    uint32_t pgd, pde, pte, start, end;
1900

    
1901
    env = mon_get_cpu();
1902

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

    
1940
#if defined(TARGET_SH4)
1941

    
1942
static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1943
{
1944
    monitor_printf(mon, " tlb%i:\t"
1945
                   "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1946
                   "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1947
                   "dirty=%hhu writethrough=%hhu\n",
1948
                   idx,
1949
                   tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1950
                   tlb->v, tlb->sh, tlb->c, tlb->pr,
1951
                   tlb->d, tlb->wt);
1952
}
1953

    
1954
static void tlb_info(Monitor *mon)
1955
{
1956
    CPUState *env = mon_get_cpu();
1957
    int i;
1958

    
1959
    monitor_printf (mon, "ITLB:\n");
1960
    for (i = 0 ; i < ITLB_SIZE ; i++)
1961
        print_tlb (mon, i, &env->itlb[i]);
1962
    monitor_printf (mon, "UTLB:\n");
1963
    for (i = 0 ; i < UTLB_SIZE ; i++)
1964
        print_tlb (mon, i, &env->utlb[i]);
1965
}
1966

    
1967
#endif
1968

    
1969
static void do_info_kvm_print(Monitor *mon, const QObject *data)
1970
{
1971
    QDict *qdict;
1972

    
1973
    qdict = qobject_to_qdict(data);
1974

    
1975
    monitor_printf(mon, "kvm support: ");
1976
    if (qdict_get_bool(qdict, "present")) {
1977
        monitor_printf(mon, "%s\n", qdict_get_bool(qdict, "enabled") ?
1978
                                    "enabled" : "disabled");
1979
    } else {
1980
        monitor_printf(mon, "not compiled\n");
1981
    }
1982
}
1983

    
1984
/**
1985
 * do_info_kvm(): Show KVM information
1986
 *
1987
 * Return a QDict with the following information:
1988
 *
1989
 * - "enabled": true if KVM support is enabled, false otherwise
1990
 * - "present": true if QEMU has KVM support, false otherwise
1991
 *
1992
 * Example:
1993
 *
1994
 * { "enabled": true, "present": true }
1995
 */
1996
static void do_info_kvm(Monitor *mon, QObject **ret_data)
1997
{
1998
#ifdef CONFIG_KVM
1999
    *ret_data = qobject_from_jsonf("{ 'enabled': %i, 'present': true }",
2000
                                   kvm_enabled());
2001
#else
2002
    *ret_data = qobject_from_jsonf("{ 'enabled': false, 'present': false }");
2003
#endif
2004
}
2005

    
2006
static void do_info_numa(Monitor *mon)
2007
{
2008
    int i;
2009
    CPUState *env;
2010

    
2011
    monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
2012
    for (i = 0; i < nb_numa_nodes; i++) {
2013
        monitor_printf(mon, "node %d cpus:", i);
2014
        for (env = first_cpu; env != NULL; env = env->next_cpu) {
2015
            if (env->numa_node == i) {
2016
                monitor_printf(mon, " %d", env->cpu_index);
2017
            }
2018
        }
2019
        monitor_printf(mon, "\n");
2020
        monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
2021
            node_mem[i] >> 20);
2022
    }
2023
}
2024

    
2025
#ifdef CONFIG_PROFILER
2026

    
2027
int64_t qemu_time;
2028
int64_t dev_time;
2029

    
2030
static void do_info_profile(Monitor *mon)
2031
{
2032
    int64_t total;
2033
    total = qemu_time;
2034
    if (total == 0)
2035
        total = 1;
2036
    monitor_printf(mon, "async time  %" PRId64 " (%0.3f)\n",
2037
                   dev_time, dev_time / (double)get_ticks_per_sec());
2038
    monitor_printf(mon, "qemu time   %" PRId64 " (%0.3f)\n",
2039
                   qemu_time, qemu_time / (double)get_ticks_per_sec());
2040
    qemu_time = 0;
2041
    dev_time = 0;
2042
}
2043
#else
2044
static void do_info_profile(Monitor *mon)
2045
{
2046
    monitor_printf(mon, "Internal profiler not compiled\n");
2047
}
2048
#endif
2049

    
2050
/* Capture support */
2051
static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2052

    
2053
static void do_info_capture(Monitor *mon)
2054
{
2055
    int i;
2056
    CaptureState *s;
2057

    
2058
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2059
        monitor_printf(mon, "[%d]: ", i);
2060
        s->ops.info (s->opaque);
2061
    }
2062
}
2063

    
2064
#ifdef HAS_AUDIO
2065
static void do_stop_capture(Monitor *mon, const QDict *qdict)
2066
{
2067
    int i;
2068
    int n = qdict_get_int(qdict, "n");
2069
    CaptureState *s;
2070

    
2071
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2072
        if (i == n) {
2073
            s->ops.destroy (s->opaque);
2074
            QLIST_REMOVE (s, entries);
2075
            qemu_free (s);
2076
            return;
2077
        }
2078
    }
2079
}
2080

    
2081
static void do_wav_capture(Monitor *mon, const QDict *qdict)
2082
{
2083
    const char *path = qdict_get_str(qdict, "path");
2084
    int has_freq = qdict_haskey(qdict, "freq");
2085
    int freq = qdict_get_try_int(qdict, "freq", -1);
2086
    int has_bits = qdict_haskey(qdict, "bits");
2087
    int bits = qdict_get_try_int(qdict, "bits", -1);
2088
    int has_channels = qdict_haskey(qdict, "nchannels");
2089
    int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2090
    CaptureState *s;
2091

    
2092
    s = qemu_mallocz (sizeof (*s));
2093

    
2094
    freq = has_freq ? freq : 44100;
2095
    bits = has_bits ? bits : 16;
2096
    nchannels = has_channels ? nchannels : 2;
2097

    
2098
    if (wav_start_capture (s, path, freq, bits, nchannels)) {
2099
        monitor_printf(mon, "Faied to add wave capture\n");
2100
        qemu_free (s);
2101
    }
2102
    QLIST_INSERT_HEAD (&capture_head, s, entries);
2103
}
2104
#endif
2105

    
2106
#if defined(TARGET_I386)
2107
static void do_inject_nmi(Monitor *mon, const QDict *qdict)
2108
{
2109
    CPUState *env;
2110
    int cpu_index = qdict_get_int(qdict, "cpu_index");
2111

    
2112
    for (env = first_cpu; env != NULL; env = env->next_cpu)
2113
        if (env->cpu_index == cpu_index) {
2114
            cpu_interrupt(env, CPU_INTERRUPT_NMI);
2115
            break;
2116
        }
2117
}
2118
#endif
2119

    
2120
static void do_info_status_print(Monitor *mon, const QObject *data)
2121
{
2122
    QDict *qdict;
2123

    
2124
    qdict = qobject_to_qdict(data);
2125

    
2126
    monitor_printf(mon, "VM status: ");
2127
    if (qdict_get_bool(qdict, "running")) {
2128
        monitor_printf(mon, "running");
2129
        if (qdict_get_bool(qdict, "singlestep")) {
2130
            monitor_printf(mon, " (single step mode)");
2131
        }
2132
    } else {
2133
        monitor_printf(mon, "paused");
2134
    }
2135

    
2136
    monitor_printf(mon, "\n");
2137
}
2138

    
2139
/**
2140
 * do_info_status(): VM status
2141
 *
2142
 * Return a QDict with the following information:
2143
 *
2144
 * - "running": true if the VM is running, or false if it is paused
2145
 * - "singlestep": true if the VM is in single step mode, false otherwise
2146
 *
2147
 * Example:
2148
 *
2149
 * { "running": true, "singlestep": false }
2150
 */
2151
static void do_info_status(Monitor *mon, QObject **ret_data)
2152
{
2153
    *ret_data = qobject_from_jsonf("{ 'running': %i, 'singlestep': %i }",
2154
                                    vm_running, singlestep);
2155
}
2156

    
2157
static void print_balloon_stat(const char *key, QObject *obj, void *opaque)
2158
{
2159
    Monitor *mon = opaque;
2160

    
2161
    if (strcmp(key, "actual"))
2162
        monitor_printf(mon, ",%s=%" PRId64, key,
2163
                       qint_get_int(qobject_to_qint(obj)));
2164
}
2165

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

    
2170
    qdict = qobject_to_qdict(data);
2171
    if (!qdict_haskey(qdict, "actual"))
2172
        return;
2173

    
2174
    monitor_printf(mon, "balloon: actual=%" PRId64,
2175
                   qdict_get_int(qdict, "actual") >> 20);
2176
    qdict_iter(qdict, print_balloon_stat, mon);
2177
    monitor_printf(mon, "\n");
2178
}
2179

    
2180
/**
2181
 * do_info_balloon(): Balloon information
2182
 *
2183
 * Make an asynchronous request for balloon info.  When the request completes
2184
 * a QDict will be returned according to the following specification:
2185
 *
2186
 * - "actual": current balloon value in bytes
2187
 * The following fields may or may not be present:
2188
 * - "mem_swapped_in": Amount of memory swapped in (bytes)
2189
 * - "mem_swapped_out": Amount of memory swapped out (bytes)
2190
 * - "major_page_faults": Number of major faults
2191
 * - "minor_page_faults": Number of minor faults
2192
 * - "free_mem": Total amount of free and unused memory (bytes)
2193
 * - "total_mem": Total amount of available memory (bytes)
2194
 *
2195
 * Example:
2196
 *
2197
 * { "actual": 1073741824, "mem_swapped_in": 0, "mem_swapped_out": 0,
2198
 *   "major_page_faults": 142, "minor_page_faults": 239245,
2199
 *   "free_mem": 1014185984, "total_mem": 1044668416 }
2200
 */
2201
static int do_info_balloon(Monitor *mon, MonitorCompletion cb, void *opaque)
2202
{
2203
    int ret;
2204

    
2205
    if (kvm_enabled() && !kvm_has_sync_mmu()) {
2206
        qemu_error_new(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
2207
        return -1;
2208
    }
2209

    
2210
    ret = qemu_balloon_status(cb, opaque);
2211
    if (!ret) {
2212
        qemu_error_new(QERR_DEVICE_NOT_ACTIVE, "balloon");
2213
        return -1;
2214
    }
2215

    
2216
    return 0;
2217
}
2218

    
2219
/**
2220
 * do_balloon(): Request VM to change its memory allocation
2221
 */
2222
static int do_balloon(Monitor *mon, const QDict *params,
2223
                       MonitorCompletion cb, void *opaque)
2224
{
2225
    int ret;
2226

    
2227
    if (kvm_enabled() && !kvm_has_sync_mmu()) {
2228
        qemu_error_new(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
2229
        return -1;
2230
    }
2231

    
2232
    ret = qemu_balloon(qdict_get_int(params, "value"), cb, opaque);
2233
    if (ret == 0) {
2234
        qemu_error_new(QERR_DEVICE_NOT_ACTIVE, "balloon");
2235
        return -1;
2236
    }
2237

    
2238
    return 0;
2239
}
2240

    
2241
static qemu_acl *find_acl(Monitor *mon, const char *name)
2242
{
2243
    qemu_acl *acl = qemu_acl_find(name);
2244

    
2245
    if (!acl) {
2246
        monitor_printf(mon, "acl: unknown list '%s'\n", name);
2247
    }
2248
    return acl;
2249
}
2250

    
2251
static void do_acl_show(Monitor *mon, const QDict *qdict)
2252
{
2253
    const char *aclname = qdict_get_str(qdict, "aclname");
2254
    qemu_acl *acl = find_acl(mon, aclname);
2255
    qemu_acl_entry *entry;
2256
    int i = 0;
2257

    
2258
    if (acl) {
2259
        monitor_printf(mon, "policy: %s\n",
2260
                       acl->defaultDeny ? "deny" : "allow");
2261
        QTAILQ_FOREACH(entry, &acl->entries, next) {
2262
            i++;
2263
            monitor_printf(mon, "%d: %s %s\n", i,
2264
                           entry->deny ? "deny" : "allow", entry->match);
2265
        }
2266
    }
2267
}
2268

    
2269
static void do_acl_reset(Monitor *mon, const QDict *qdict)
2270
{
2271
    const char *aclname = qdict_get_str(qdict, "aclname");
2272
    qemu_acl *acl = find_acl(mon, aclname);
2273

    
2274
    if (acl) {
2275
        qemu_acl_reset(acl);
2276
        monitor_printf(mon, "acl: removed all rules\n");
2277
    }
2278
}
2279

    
2280
static void do_acl_policy(Monitor *mon, const QDict *qdict)
2281
{
2282
    const char *aclname = qdict_get_str(qdict, "aclname");
2283
    const char *policy = qdict_get_str(qdict, "policy");
2284
    qemu_acl *acl = find_acl(mon, aclname);
2285

    
2286
    if (acl) {
2287
        if (strcmp(policy, "allow") == 0) {
2288
            acl->defaultDeny = 0;
2289
            monitor_printf(mon, "acl: policy set to 'allow'\n");
2290
        } else if (strcmp(policy, "deny") == 0) {
2291
            acl->defaultDeny = 1;
2292
            monitor_printf(mon, "acl: policy set to 'deny'\n");
2293
        } else {
2294
            monitor_printf(mon, "acl: unknown policy '%s', "
2295
                           "expected 'deny' or 'allow'\n", policy);
2296
        }
2297
    }
2298
}
2299

    
2300
static void do_acl_add(Monitor *mon, const QDict *qdict)
2301
{
2302
    const char *aclname = qdict_get_str(qdict, "aclname");
2303
    const char *match = qdict_get_str(qdict, "match");
2304
    const char *policy = qdict_get_str(qdict, "policy");
2305
    int has_index = qdict_haskey(qdict, "index");
2306
    int index = qdict_get_try_int(qdict, "index", -1);
2307
    qemu_acl *acl = find_acl(mon, aclname);
2308
    int deny, ret;
2309

    
2310
    if (acl) {
2311
        if (strcmp(policy, "allow") == 0) {
2312
            deny = 0;
2313
        } else if (strcmp(policy, "deny") == 0) {
2314
            deny = 1;
2315
        } else {
2316
            monitor_printf(mon, "acl: unknown policy '%s', "
2317
                           "expected 'deny' or 'allow'\n", policy);
2318
            return;
2319
        }
2320
        if (has_index)
2321
            ret = qemu_acl_insert(acl, deny, match, index);
2322
        else
2323
            ret = qemu_acl_append(acl, deny, match);
2324
        if (ret < 0)
2325
            monitor_printf(mon, "acl: unable to add acl entry\n");
2326
        else
2327
            monitor_printf(mon, "acl: added rule at position %d\n", ret);
2328
    }
2329
}
2330

    
2331
static void do_acl_remove(Monitor *mon, const QDict *qdict)
2332
{
2333
    const char *aclname = qdict_get_str(qdict, "aclname");
2334
    const char *match = qdict_get_str(qdict, "match");
2335
    qemu_acl *acl = find_acl(mon, aclname);
2336
    int ret;
2337

    
2338
    if (acl) {
2339
        ret = qemu_acl_remove(acl, match);
2340
        if (ret < 0)
2341
            monitor_printf(mon, "acl: no matching acl entry\n");
2342
        else
2343
            monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2344
    }
2345
}
2346

    
2347
#if defined(TARGET_I386)
2348
static void do_inject_mce(Monitor *mon, const QDict *qdict)
2349
{
2350
    CPUState *cenv;
2351
    int cpu_index = qdict_get_int(qdict, "cpu_index");
2352
    int bank = qdict_get_int(qdict, "bank");
2353
    uint64_t status = qdict_get_int(qdict, "status");
2354
    uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2355
    uint64_t addr = qdict_get_int(qdict, "addr");
2356
    uint64_t misc = qdict_get_int(qdict, "misc");
2357

    
2358
    for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu)
2359
        if (cenv->cpu_index == cpu_index && cenv->mcg_cap) {
2360
            cpu_inject_x86_mce(cenv, bank, status, mcg_status, addr, misc);
2361
            break;
2362
        }
2363
}
2364
#endif
2365

    
2366
static void do_getfd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2367
{
2368
    const char *fdname = qdict_get_str(qdict, "fdname");
2369
    mon_fd_t *monfd;
2370
    int fd;
2371

    
2372
    fd = qemu_chr_get_msgfd(mon->chr);
2373
    if (fd == -1) {
2374
        qemu_error_new(QERR_FD_NOT_SUPPLIED);
2375
        return;
2376
    }
2377

    
2378
    if (qemu_isdigit(fdname[0])) {
2379
        qemu_error_new(QERR_INVALID_PARAMETER, "fdname");
2380
        return;
2381
    }
2382

    
2383
    fd = dup(fd);
2384
    if (fd == -1) {
2385
        if (errno == EMFILE)
2386
            qemu_error_new(QERR_TOO_MANY_FILES);
2387
        else
2388
            qemu_error_new(QERR_UNDEFINED_ERROR);
2389
        return;
2390
    }
2391

    
2392
    QLIST_FOREACH(monfd, &mon->fds, next) {
2393
        if (strcmp(monfd->name, fdname) != 0) {
2394
            continue;
2395
        }
2396

    
2397
        close(monfd->fd);
2398
        monfd->fd = fd;
2399
        return;
2400
    }
2401

    
2402
    monfd = qemu_mallocz(sizeof(mon_fd_t));
2403
    monfd->name = qemu_strdup(fdname);
2404
    monfd->fd = fd;
2405

    
2406
    QLIST_INSERT_HEAD(&mon->fds, monfd, next);
2407
}
2408

    
2409
static void do_closefd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2410
{
2411
    const char *fdname = qdict_get_str(qdict, "fdname");
2412
    mon_fd_t *monfd;
2413

    
2414
    QLIST_FOREACH(monfd, &mon->fds, next) {
2415
        if (strcmp(monfd->name, fdname) != 0) {
2416
            continue;
2417
        }
2418

    
2419
        QLIST_REMOVE(monfd, next);
2420
        close(monfd->fd);
2421
        qemu_free(monfd->name);
2422
        qemu_free(monfd);
2423
        return;
2424
    }
2425

    
2426
    qemu_error_new(QERR_FD_NOT_FOUND, fdname);
2427
}
2428

    
2429
static void do_loadvm(Monitor *mon, const QDict *qdict)
2430
{
2431
    int saved_vm_running  = vm_running;
2432
    const char *name = qdict_get_str(qdict, "name");
2433

    
2434
    vm_stop(0);
2435

    
2436
    if (load_vmstate(mon, name) >= 0 && saved_vm_running)
2437
        vm_start();
2438
}
2439

    
2440
int monitor_get_fd(Monitor *mon, const char *fdname)
2441
{
2442
    mon_fd_t *monfd;
2443

    
2444
    QLIST_FOREACH(monfd, &mon->fds, next) {
2445
        int fd;
2446

    
2447
        if (strcmp(monfd->name, fdname) != 0) {
2448
            continue;
2449
        }
2450

    
2451
        fd = monfd->fd;
2452

    
2453
        /* caller takes ownership of fd */
2454
        QLIST_REMOVE(monfd, next);
2455
        qemu_free(monfd->name);
2456
        qemu_free(monfd);
2457

    
2458
        return fd;
2459
    }
2460

    
2461
    return -1;
2462
}
2463

    
2464
static const mon_cmd_t mon_cmds[] = {
2465
#include "qemu-monitor.h"
2466
    { NULL, NULL, },
2467
};
2468

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

    
2753
/*******************************************************************/
2754

    
2755
static const char *pch;
2756
static jmp_buf expr_env;
2757

    
2758
#define MD_TLONG 0
2759
#define MD_I32   1
2760

    
2761
typedef struct MonitorDef {
2762
    const char *name;
2763
    int offset;
2764
    target_long (*get_value)(const struct MonitorDef *md, int val);
2765
    int type;
2766
} MonitorDef;
2767

    
2768
#if defined(TARGET_I386)
2769
static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2770
{
2771
    CPUState *env = mon_get_cpu();
2772
    return env->eip + env->segs[R_CS].base;
2773
}
2774
#endif
2775

    
2776
#if defined(TARGET_PPC)
2777
static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2778
{
2779
    CPUState *env = mon_get_cpu();
2780
    unsigned int u;
2781
    int i;
2782

    
2783
    u = 0;
2784
    for (i = 0; i < 8; i++)
2785
        u |= env->crf[i] << (32 - (4 * i));
2786

    
2787
    return u;
2788
}
2789

    
2790
static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2791
{
2792
    CPUState *env = mon_get_cpu();
2793
    return env->msr;
2794
}
2795

    
2796
static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2797
{
2798
    CPUState *env = mon_get_cpu();
2799
    return env->xer;
2800
}
2801

    
2802
static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2803
{
2804
    CPUState *env = mon_get_cpu();
2805
    return cpu_ppc_load_decr(env);
2806
}
2807

    
2808
static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2809
{
2810
    CPUState *env = mon_get_cpu();
2811
    return cpu_ppc_load_tbu(env);
2812
}
2813

    
2814
static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2815
{
2816
    CPUState *env = mon_get_cpu();
2817
    return cpu_ppc_load_tbl(env);
2818
}
2819
#endif
2820

    
2821
#if defined(TARGET_SPARC)
2822
#ifndef TARGET_SPARC64
2823
static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2824
{
2825
    CPUState *env = mon_get_cpu();
2826
    return GET_PSR(env);
2827
}
2828
#endif
2829

    
2830
static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2831
{
2832
    CPUState *env = mon_get_cpu();
2833
    return env->regwptr[val];
2834
}
2835
#endif
2836

    
2837
static const MonitorDef monitor_defs[] = {
2838
#ifdef TARGET_I386
2839

    
2840
#define SEG(name, seg) \
2841
    { name, offsetof(CPUState, segs[seg].selector), NULL, MD_I32 },\
2842
    { name ".base", offsetof(CPUState, segs[seg].base) },\
2843
    { name ".limit", offsetof(CPUState, segs[seg].limit), NULL, MD_I32 },
2844

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

    
3078
static void expr_error(Monitor *mon, const char *msg)
3079
{
3080
    monitor_printf(mon, "%s\n", msg);
3081
    longjmp(expr_env, 1);
3082
}
3083

    
3084
/* return 0 if OK, -1 if not found */
3085
static int get_monitor_def(target_long *pval, const char *name)
3086
{
3087
    const MonitorDef *md;
3088
    void *ptr;
3089

    
3090
    for(md = monitor_defs; md->name != NULL; md++) {
3091
        if (compare_cmd(name, md->name)) {
3092
            if (md->get_value) {
3093
                *pval = md->get_value(md, md->offset);
3094
            } else {
3095
                CPUState *env = mon_get_cpu();
3096
                ptr = (uint8_t *)env + md->offset;
3097
                switch(md->type) {
3098
                case MD_I32:
3099
                    *pval = *(int32_t *)ptr;
3100
                    break;
3101
                case MD_TLONG:
3102
                    *pval = *(target_long *)ptr;
3103
                    break;
3104
                default:
3105
                    *pval = 0;
3106
                    break;
3107
                }
3108
            }
3109
            return 0;
3110
        }
3111
    }
3112
    return -1;
3113
}
3114

    
3115
static void next(void)
3116
{
3117
    if (*pch != '\0') {
3118
        pch++;
3119
        while (qemu_isspace(*pch))
3120
            pch++;
3121
    }
3122
}
3123

    
3124
static int64_t expr_sum(Monitor *mon);
3125

    
3126
static int64_t expr_unary(Monitor *mon)
3127
{
3128
    int64_t n;
3129
    char *p;
3130
    int ret;
3131

    
3132
    switch(*pch) {
3133
    case '+':
3134
        next();
3135
        n = expr_unary(mon);
3136
        break;
3137
    case '-':
3138
        next();
3139
        n = -expr_unary(mon);
3140
        break;
3141
    case '~':
3142
        next();
3143
        n = ~expr_unary(mon);
3144
        break;
3145
    case '(':
3146
        next();
3147
        n = expr_sum(mon);
3148
        if (*pch != ')') {
3149
            expr_error(mon, "')' expected");
3150
        }
3151
        next();
3152
        break;
3153
    case '\'':
3154
        pch++;
3155
        if (*pch == '\0')
3156
            expr_error(mon, "character constant expected");
3157
        n = *pch;
3158
        pch++;
3159
        if (*pch != '\'')
3160
            expr_error(mon, "missing terminating \' character");
3161
        next();
3162
        break;
3163
    case '$':
3164
        {
3165
            char buf[128], *q;
3166
            target_long reg=0;
3167

    
3168
            pch++;
3169
            q = buf;
3170
            while ((*pch >= 'a' && *pch <= 'z') ||
3171
                   (*pch >= 'A' && *pch <= 'Z') ||
3172
                   (*pch >= '0' && *pch <= '9') ||
3173
                   *pch == '_' || *pch == '.') {
3174
                if ((q - buf) < sizeof(buf) - 1)
3175
                    *q++ = *pch;
3176
                pch++;
3177
            }
3178
            while (qemu_isspace(*pch))
3179
                pch++;
3180
            *q = 0;
3181
            ret = get_monitor_def(&reg, buf);
3182
            if (ret < 0)
3183
                expr_error(mon, "unknown register");
3184
            n = reg;
3185
        }
3186
        break;
3187
    case '\0':
3188
        expr_error(mon, "unexpected end of expression");
3189
        n = 0;
3190
        break;
3191
    default:
3192
#if TARGET_PHYS_ADDR_BITS > 32
3193
        n = strtoull(pch, &p, 0);
3194
#else
3195
        n = strtoul(pch, &p, 0);
3196
#endif
3197
        if (pch == p) {
3198
            expr_error(mon, "invalid char in expression");
3199
        }
3200
        pch = p;
3201
        while (qemu_isspace(*pch))
3202
            pch++;
3203
        break;
3204
    }
3205
    return n;
3206
}
3207

    
3208

    
3209
static int64_t expr_prod(Monitor *mon)
3210
{
3211
    int64_t val, val2;
3212
    int op;
3213

    
3214
    val = expr_unary(mon);
3215
    for(;;) {
3216
        op = *pch;
3217
        if (op != '*' && op != '/' && op != '%')
3218
            break;
3219
        next();
3220
        val2 = expr_unary(mon);
3221
        switch(op) {
3222
        default:
3223
        case '*':
3224
            val *= val2;
3225
            break;
3226
        case '/':
3227
        case '%':
3228
            if (val2 == 0)
3229
                expr_error(mon, "division by zero");
3230
            if (op == '/')
3231
                val /= val2;
3232
            else
3233
                val %= val2;
3234
            break;
3235
        }
3236
    }
3237
    return val;
3238
}
3239

    
3240
static int64_t expr_logic(Monitor *mon)
3241
{
3242
    int64_t val, val2;
3243
    int op;
3244

    
3245
    val = expr_prod(mon);
3246
    for(;;) {
3247
        op = *pch;
3248
        if (op != '&' && op != '|' && op != '^')
3249
            break;
3250
        next();
3251
        val2 = expr_prod(mon);
3252
        switch(op) {
3253
        default:
3254
        case '&':
3255
            val &= val2;
3256
            break;
3257
        case '|':
3258
            val |= val2;
3259
            break;
3260
        case '^':
3261
            val ^= val2;
3262
            break;
3263
        }
3264
    }
3265
    return val;
3266
}
3267

    
3268
static int64_t expr_sum(Monitor *mon)
3269
{
3270
    int64_t val, val2;
3271
    int op;
3272

    
3273
    val = expr_logic(mon);
3274
    for(;;) {
3275
        op = *pch;
3276
        if (op != '+' && op != '-')
3277
            break;
3278
        next();
3279
        val2 = expr_logic(mon);
3280
        if (op == '+')
3281
            val += val2;
3282
        else
3283
            val -= val2;
3284
    }
3285
    return val;
3286
}
3287

    
3288
static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3289
{
3290
    pch = *pp;
3291
    if (setjmp(expr_env)) {
3292
        *pp = pch;
3293
        return -1;
3294
    }
3295
    while (qemu_isspace(*pch))
3296
        pch++;
3297
    *pval = expr_sum(mon);
3298
    *pp = pch;
3299
    return 0;
3300
}
3301

    
3302
static int get_str(char *buf, int buf_size, const char **pp)
3303
{
3304
    const char *p;
3305
    char *q;
3306
    int c;
3307

    
3308
    q = buf;
3309
    p = *pp;
3310
    while (qemu_isspace(*p))
3311
        p++;
3312
    if (*p == '\0') {
3313
    fail:
3314
        *q = '\0';
3315
        *pp = p;
3316
        return -1;
3317
    }
3318
    if (*p == '\"') {
3319
        p++;
3320
        while (*p != '\0' && *p != '\"') {
3321
            if (*p == '\\') {
3322
                p++;
3323
                c = *p++;
3324
                switch(c) {
3325
                case 'n':
3326
                    c = '\n';
3327
                    break;
3328
                case 'r':
3329
                    c = '\r';
3330
                    break;
3331
                case '\\':
3332
                case '\'':
3333
                case '\"':
3334
                    break;
3335
                default:
3336
                    qemu_printf("unsupported escape code: '\\%c'\n", c);
3337
                    goto fail;
3338
                }
3339
                if ((q - buf) < buf_size - 1) {
3340
                    *q++ = c;
3341
                }
3342
            } else {
3343
                if ((q - buf) < buf_size - 1) {
3344
                    *q++ = *p;
3345
                }
3346
                p++;
3347
            }
3348
        }
3349
        if (*p != '\"') {
3350
            qemu_printf("unterminated string\n");
3351
            goto fail;
3352
        }
3353
        p++;
3354
    } else {
3355
        while (*p != '\0' && !qemu_isspace(*p)) {
3356
            if ((q - buf) < buf_size - 1) {
3357
                *q++ = *p;
3358
            }
3359
            p++;
3360
        }
3361
    }
3362
    *q = '\0';
3363
    *pp = p;
3364
    return 0;
3365
}
3366

    
3367
/*
3368
 * Store the command-name in cmdname, and return a pointer to
3369
 * the remaining of the command string.
3370
 */
3371
static const char *get_command_name(const char *cmdline,
3372
                                    char *cmdname, size_t nlen)
3373
{
3374
    size_t len;
3375
    const char *p, *pstart;
3376

    
3377
    p = cmdline;
3378
    while (qemu_isspace(*p))
3379
        p++;
3380
    if (*p == '\0')
3381
        return NULL;
3382
    pstart = p;
3383
    while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3384
        p++;
3385
    len = p - pstart;
3386
    if (len > nlen - 1)
3387
        len = nlen - 1;
3388
    memcpy(cmdname, pstart, len);
3389
    cmdname[len] = '\0';
3390
    return p;
3391
}
3392

    
3393
/**
3394
 * Read key of 'type' into 'key' and return the current
3395
 * 'type' pointer.
3396
 */
3397
static char *key_get_info(const char *type, char **key)
3398
{
3399
    size_t len;
3400
    char *p, *str;
3401

    
3402
    if (*type == ',')
3403
        type++;
3404

    
3405
    p = strchr(type, ':');
3406
    if (!p) {
3407
        *key = NULL;
3408
        return NULL;
3409
    }
3410
    len = p - type;
3411

    
3412
    str = qemu_malloc(len + 1);
3413
    memcpy(str, type, len);
3414
    str[len] = '\0';
3415

    
3416
    *key = str;
3417
    return ++p;
3418
}
3419

    
3420
static int default_fmt_format = 'x';
3421
static int default_fmt_size = 4;
3422

    
3423
#define MAX_ARGS 16
3424

    
3425
static int is_valid_option(const char *c, const char *typestr)
3426
{
3427
    char option[3];
3428
  
3429
    option[0] = '-';
3430
    option[1] = *c;
3431
    option[2] = '\0';
3432
  
3433
    typestr = strstr(typestr, option);
3434
    return (typestr != NULL);
3435
}
3436

    
3437
static const mon_cmd_t *monitor_find_command(const char *cmdname)
3438
{
3439
    const mon_cmd_t *cmd;
3440

    
3441
    for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
3442
        if (compare_cmd(cmdname, cmd->name)) {
3443
            return cmd;
3444
        }
3445
    }
3446

    
3447
    return NULL;
3448
}
3449

    
3450
static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3451
                                              const char *cmdline,
3452
                                              QDict *qdict)
3453
{
3454
    const char *p, *typestr;
3455
    int c;
3456
    const mon_cmd_t *cmd;
3457
    char cmdname[256];
3458
    char buf[1024];
3459
    char *key;
3460

    
3461
#ifdef DEBUG
3462
    monitor_printf(mon, "command='%s'\n", cmdline);
3463
#endif
3464

    
3465
    /* extract the command name */
3466
    p = get_command_name(cmdline, cmdname, sizeof(cmdname));
3467
    if (!p)
3468
        return NULL;
3469

    
3470
    cmd = monitor_find_command(cmdname);
3471
    if (!cmd) {
3472
        monitor_printf(mon, "unknown command: '%s'\n", cmdname);
3473
        return NULL;
3474
    }
3475

    
3476
    /* parse the parameters */
3477
    typestr = cmd->args_type;
3478
    for(;;) {
3479
        typestr = key_get_info(typestr, &key);
3480
        if (!typestr)
3481
            break;
3482
        c = *typestr;
3483
        typestr++;
3484
        switch(c) {
3485
        case 'F':
3486
        case 'B':
3487
        case 's':
3488
            {
3489
                int ret;
3490

    
3491
                while (qemu_isspace(*p))
3492
                    p++;
3493
                if (*typestr == '?') {
3494
                    typestr++;
3495
                    if (*p == '\0') {
3496
                        /* no optional string: NULL argument */
3497
                        break;
3498
                    }
3499
                }
3500
                ret = get_str(buf, sizeof(buf), &p);
3501
                if (ret < 0) {
3502
                    switch(c) {
3503
                    case 'F':
3504
                        monitor_printf(mon, "%s: filename expected\n",
3505
                                       cmdname);
3506
                        break;
3507
                    case 'B':
3508
                        monitor_printf(mon, "%s: block device name expected\n",
3509
                                       cmdname);
3510
                        break;
3511
                    default:
3512
                        monitor_printf(mon, "%s: string expected\n", cmdname);
3513
                        break;
3514
                    }
3515
                    goto fail;
3516
                }
3517
                qdict_put(qdict, key, qstring_from_str(buf));
3518
            }
3519
            break;
3520
        case '/':
3521
            {
3522
                int count, format, size;
3523

    
3524
                while (qemu_isspace(*p))
3525
                    p++;
3526
                if (*p == '/') {
3527
                    /* format found */
3528
                    p++;
3529
                    count = 1;
3530
                    if (qemu_isdigit(*p)) {
3531
                        count = 0;
3532
                        while (qemu_isdigit(*p)) {
3533
                            count = count * 10 + (*p - '0');
3534
                            p++;
3535
                        }
3536
                    }
3537
                    size = -1;
3538
                    format = -1;
3539
                    for(;;) {
3540
                        switch(*p) {
3541
                        case 'o':
3542
                        case 'd':
3543
                        case 'u':
3544
                        case 'x':
3545
                        case 'i':
3546
                        case 'c':
3547
                            format = *p++;
3548
                            break;
3549
                        case 'b':
3550
                            size = 1;
3551
                            p++;
3552
                            break;
3553
                        case 'h':
3554
                            size = 2;
3555
                            p++;
3556
                            break;
3557
                        case 'w':
3558
                            size = 4;
3559
                            p++;
3560
                            break;
3561
                        case 'g':
3562
                        case 'L':
3563
                            size = 8;
3564
                            p++;
3565
                            break;
3566
                        default:
3567
                            goto next;
3568
                        }
3569
                    }
3570
                next:
3571
                    if (*p != '\0' && !qemu_isspace(*p)) {
3572
                        monitor_printf(mon, "invalid char in format: '%c'\n",
3573
                                       *p);
3574
                        goto fail;
3575
                    }
3576
                    if (format < 0)
3577
                        format = default_fmt_format;
3578
                    if (format != 'i') {
3579
                        /* for 'i', not specifying a size gives -1 as size */
3580
                        if (size < 0)
3581
                            size = default_fmt_size;
3582
                        default_fmt_size = size;
3583
                    }
3584
                    default_fmt_format = format;
3585
                } else {
3586
                    count = 1;
3587
                    format = default_fmt_format;
3588
                    if (format != 'i') {
3589
                        size = default_fmt_size;
3590
                    } else {
3591
                        size = -1;
3592
                    }
3593
                }
3594
                qdict_put(qdict, "count", qint_from_int(count));
3595
                qdict_put(qdict, "format", qint_from_int(format));
3596
                qdict_put(qdict, "size", qint_from_int(size));
3597
            }
3598
            break;
3599
        case 'i':
3600
        case 'l':
3601
        case 'M':
3602
            {
3603
                int64_t val;
3604

    
3605
                while (qemu_isspace(*p))
3606
                    p++;
3607
                if (*typestr == '?' || *typestr == '.') {
3608
                    if (*typestr == '?') {
3609
                        if (*p == '\0') {
3610
                            typestr++;
3611
                            break;
3612
                        }
3613
                    } else {
3614
                        if (*p == '.') {
3615
                            p++;
3616
                            while (qemu_isspace(*p))
3617
                                p++;
3618
                        } else {
3619
                            typestr++;
3620
                            break;
3621
                        }
3622
                    }
3623
                    typestr++;
3624
                }
3625
                if (get_expr(mon, &val, &p))
3626
                    goto fail;
3627
                /* Check if 'i' is greater than 32-bit */
3628
                if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3629
                    monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3630
                    monitor_printf(mon, "integer is for 32-bit values\n");
3631
                    goto fail;
3632
                } else if (c == 'M') {
3633
                    val <<= 20;
3634
                }
3635
                qdict_put(qdict, key, qint_from_int(val));
3636
            }
3637
            break;
3638
        case '-':
3639
            {
3640
                const char *tmp = p;
3641
                int has_option, skip_key = 0;
3642
                /* option */
3643

    
3644
                c = *typestr++;
3645
                if (c == '\0')
3646
                    goto bad_type;
3647
                while (qemu_isspace(*p))
3648
                    p++;
3649
                has_option = 0;
3650
                if (*p == '-') {
3651
                    p++;
3652
                    if(c != *p) {
3653
                        if(!is_valid_option(p, typestr)) {
3654
                  
3655
                            monitor_printf(mon, "%s: unsupported option -%c\n",
3656
                                           cmdname, *p);
3657
                            goto fail;
3658
                        } else {
3659
                            skip_key = 1;
3660
                        }
3661
                    }
3662
                    if(skip_key) {
3663
                        p = tmp;
3664
                    } else {
3665
                        p++;
3666
                        has_option = 1;
3667
                    }
3668
                }
3669
                qdict_put(qdict, key, qint_from_int(has_option));
3670
            }
3671
            break;
3672
        default:
3673
        bad_type:
3674
            monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
3675
            goto fail;
3676
        }
3677
        qemu_free(key);
3678
        key = NULL;
3679
    }
3680
    /* check that all arguments were parsed */
3681
    while (qemu_isspace(*p))
3682
        p++;
3683
    if (*p != '\0') {
3684
        monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3685
                       cmdname);
3686
        goto fail;
3687
    }
3688

    
3689
    return cmd;
3690

    
3691
fail:
3692
    qemu_free(key);
3693
    return NULL;
3694
}
3695

    
3696
static void monitor_print_error(Monitor *mon)
3697
{
3698
    qerror_print(mon->error);
3699
    QDECREF(mon->error);
3700
    mon->error = NULL;
3701
}
3702

    
3703
static int is_async_return(const QObject *data)
3704
{
3705
    if (data && qobject_type(data) == QTYPE_QDICT) {
3706
        return qdict_haskey(qobject_to_qdict(data), "__mon_async");
3707
    }
3708

    
3709
    return 0;
3710
}
3711

    
3712
static void monitor_call_handler(Monitor *mon, const mon_cmd_t *cmd,
3713
                                 const QDict *params)
3714
{
3715
    QObject *data = NULL;
3716

    
3717
    cmd->mhandler.cmd_new(mon, params, &data);
3718

    
3719
    if (is_async_return(data)) {
3720
        /*
3721
         * Asynchronous commands have no initial return data but they can
3722
         * generate errors.  Data is returned via the async completion handler.
3723
         */
3724
        if (monitor_ctrl_mode(mon) && monitor_has_error(mon)) {
3725
            monitor_protocol_emitter(mon, NULL);
3726
        }
3727
    } else if (monitor_ctrl_mode(mon)) {
3728
        /* Monitor Protocol */
3729
        monitor_protocol_emitter(mon, data);
3730
    } else {
3731
        /* User Protocol */
3732
         if (data)
3733
            cmd->user_print(mon, data);
3734
    }
3735

    
3736
    qobject_decref(data);
3737
}
3738

    
3739
static void handle_user_command(Monitor *mon, const char *cmdline)
3740
{
3741
    QDict *qdict;
3742
    const mon_cmd_t *cmd;
3743

    
3744
    qdict = qdict_new();
3745

    
3746
    cmd = monitor_parse_command(mon, cmdline, qdict);
3747
    if (!cmd)
3748
        goto out;
3749

    
3750
    qemu_errors_to_mon(mon);
3751

    
3752
    if (monitor_handler_is_async(cmd)) {
3753
        user_async_cmd_handler(mon, cmd, qdict);
3754
    } else if (monitor_handler_ported(cmd)) {
3755
        monitor_call_handler(mon, cmd, qdict);
3756
    } else {
3757
        cmd->mhandler.cmd(mon, qdict);
3758
    }
3759

    
3760
    if (monitor_has_error(mon))
3761
        monitor_print_error(mon);
3762

    
3763
    qemu_errors_to_previous();
3764

    
3765
out:
3766
    QDECREF(qdict);
3767
}
3768

    
3769
static void cmd_completion(const char *name, const char *list)
3770
{
3771
    const char *p, *pstart;
3772
    char cmd[128];
3773
    int len;
3774

    
3775
    p = list;
3776
    for(;;) {
3777
        pstart = p;
3778
        p = strchr(p, '|');
3779
        if (!p)
3780
            p = pstart + strlen(pstart);
3781
        len = p - pstart;
3782
        if (len > sizeof(cmd) - 2)
3783
            len = sizeof(cmd) - 2;
3784
        memcpy(cmd, pstart, len);
3785
        cmd[len] = '\0';
3786
        if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3787
            readline_add_completion(cur_mon->rs, cmd);
3788
        }
3789
        if (*p == '\0')
3790
            break;
3791
        p++;
3792
    }
3793
}
3794

    
3795
static void file_completion(const char *input)
3796
{
3797
    DIR *ffs;
3798
    struct dirent *d;
3799
    char path[1024];
3800
    char file[1024], file_prefix[1024];
3801
    int input_path_len;
3802
    const char *p;
3803

    
3804
    p = strrchr(input, '/');
3805
    if (!p) {
3806
        input_path_len = 0;
3807
        pstrcpy(file_prefix, sizeof(file_prefix), input);
3808
        pstrcpy(path, sizeof(path), ".");
3809
    } else {
3810
        input_path_len = p - input + 1;
3811
        memcpy(path, input, input_path_len);
3812
        if (input_path_len > sizeof(path) - 1)
3813
            input_path_len = sizeof(path) - 1;
3814
        path[input_path_len] = '\0';
3815
        pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3816
    }
3817
#ifdef DEBUG_COMPLETION
3818
    monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
3819
                   input, path, file_prefix);
3820
#endif
3821
    ffs = opendir(path);
3822
    if (!ffs)
3823
        return;
3824
    for(;;) {
3825
        struct stat sb;
3826
        d = readdir(ffs);
3827
        if (!d)
3828
            break;
3829
        if (strstart(d->d_name, file_prefix, NULL)) {
3830
            memcpy(file, input, input_path_len);
3831
            if (input_path_len < sizeof(file))
3832
                pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3833
                        d->d_name);
3834
            /* stat the file to find out if it's a directory.
3835
             * In that case add a slash to speed up typing long paths
3836
             */
3837
            stat(file, &sb);
3838
            if(S_ISDIR(sb.st_mode))
3839
                pstrcat(file, sizeof(file), "/");
3840
            readline_add_completion(cur_mon->rs, file);
3841
        }
3842
    }
3843
    closedir(ffs);
3844
}
3845

    
3846
static void block_completion_it(void *opaque, BlockDriverState *bs)
3847
{
3848
    const char *name = bdrv_get_device_name(bs);
3849
    const char *input = opaque;
3850

    
3851
    if (input[0] == '\0' ||
3852
        !strncmp(name, (char *)input, strlen(input))) {
3853
        readline_add_completion(cur_mon->rs, name);
3854
    }
3855
}
3856

    
3857
/* NOTE: this parser is an approximate form of the real command parser */
3858
static void parse_cmdline(const char *cmdline,
3859
                         int *pnb_args, char **args)
3860
{
3861
    const char *p;
3862
    int nb_args, ret;
3863
    char buf[1024];
3864

    
3865
    p = cmdline;
3866
    nb_args = 0;
3867
    for(;;) {
3868
        while (qemu_isspace(*p))
3869
            p++;
3870
        if (*p == '\0')
3871
            break;
3872
        if (nb_args >= MAX_ARGS)
3873
            break;
3874
        ret = get_str(buf, sizeof(buf), &p);
3875
        args[nb_args] = qemu_strdup(buf);
3876
        nb_args++;
3877
        if (ret < 0)
3878
            break;
3879
    }
3880
    *pnb_args = nb_args;
3881
}
3882

    
3883
static const char *next_arg_type(const char *typestr)
3884
{
3885
    const char *p = strchr(typestr, ':');
3886
    return (p != NULL ? ++p : typestr);
3887
}
3888

    
3889
static void monitor_find_completion(const char *cmdline)
3890
{
3891
    const char *cmdname;
3892
    char *args[MAX_ARGS];
3893
    int nb_args, i, len;
3894
    const char *ptype, *str;
3895
    const mon_cmd_t *cmd;
3896
    const KeyDef *key;
3897

    
3898
    parse_cmdline(cmdline, &nb_args, args);
3899
#ifdef DEBUG_COMPLETION
3900
    for(i = 0; i < nb_args; i++) {
3901
        monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
3902
    }
3903
#endif
3904

    
3905
    /* if the line ends with a space, it means we want to complete the
3906
       next arg */
3907
    len = strlen(cmdline);
3908
    if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3909
        if (nb_args >= MAX_ARGS)
3910
            return;
3911
        args[nb_args++] = qemu_strdup("");
3912
    }
3913
    if (nb_args <= 1) {
3914
        /* command completion */
3915
        if (nb_args == 0)
3916
            cmdname = "";
3917
        else
3918
            cmdname = args[0];
3919
        readline_set_completion_index(cur_mon->rs, strlen(cmdname));
3920
        for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
3921
            cmd_completion(cmdname, cmd->name);
3922
        }
3923
    } else {
3924
        /* find the command */
3925
        for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
3926
            if (compare_cmd(args[0], cmd->name))
3927
                goto found;
3928
        }
3929
        return;
3930
    found:
3931
        ptype = next_arg_type(cmd->args_type);
3932
        for(i = 0; i < nb_args - 2; i++) {
3933
            if (*ptype != '\0') {
3934
                ptype = next_arg_type(ptype);
3935
                while (*ptype == '?')
3936
                    ptype = next_arg_type(ptype);
3937
            }
3938
        }
3939
        str = args[nb_args - 1];
3940
        if (*ptype == '-' && ptype[1] != '\0') {
3941
            ptype += 2;
3942
        }
3943
        switch(*ptype) {
3944
        case 'F':
3945
            /* file completion */
3946
            readline_set_completion_index(cur_mon->rs, strlen(str));
3947
            file_completion(str);
3948
            break;
3949
        case 'B':
3950
            /* block device name completion */
3951
            readline_set_completion_index(cur_mon->rs, strlen(str));
3952
            bdrv_iterate(block_completion_it, (void *)str);
3953
            break;
3954
        case 's':
3955
            /* XXX: more generic ? */
3956
            if (!strcmp(cmd->name, "info")) {
3957
                readline_set_completion_index(cur_mon->rs, strlen(str));
3958
                for(cmd = info_cmds; cmd->name != NULL; cmd++) {
3959
                    cmd_completion(str, cmd->name);
3960
                }
3961
            } else if (!strcmp(cmd->name, "sendkey")) {
3962
                char *sep = strrchr(str, '-');
3963
                if (sep)
3964
                    str = sep + 1;
3965
                readline_set_completion_index(cur_mon->rs, strlen(str));
3966
                for(key = key_defs; key->name != NULL; key++) {
3967
                    cmd_completion(str, key->name);
3968
                }
3969
            } else if (!strcmp(cmd->name, "help|?")) {
3970
                readline_set_completion_index(cur_mon->rs, strlen(str));
3971
                for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
3972
                    cmd_completion(str, cmd->name);
3973
                }
3974
            }
3975
            break;
3976
        default:
3977
            break;
3978
        }
3979
    }
3980
    for(i = 0; i < nb_args; i++)
3981
        qemu_free(args[i]);
3982
}
3983

    
3984
static int monitor_can_read(void *opaque)
3985
{
3986
    Monitor *mon = opaque;
3987

    
3988
    return (mon->suspend_cnt == 0) ? 1 : 0;
3989
}
3990

    
3991
typedef struct CmdArgs {
3992
    QString *name;
3993
    int type;
3994
    int flag;
3995
    int optional;
3996
} CmdArgs;
3997

    
3998
static int check_opt(const CmdArgs *cmd_args, const char *name, QDict *args)
3999
{
4000
    if (!cmd_args->optional) {
4001
        qemu_error_new(QERR_MISSING_PARAMETER, name);
4002
        return -1;
4003
    }
4004

    
4005
    if (cmd_args->type == '-') {
4006
        /* handlers expect a value, they need to be changed */
4007
        qdict_put(args, name, qint_from_int(0));
4008
    }
4009

    
4010
    return 0;
4011
}
4012

    
4013
static int check_arg(const CmdArgs *cmd_args, QDict *args)
4014
{
4015
    QObject *value;
4016
    const char *name;
4017

    
4018
    name = qstring_get_str(cmd_args->name);
4019

    
4020
    if (!args) {
4021
        return check_opt(cmd_args, name, args);
4022
    }
4023

    
4024
    value = qdict_get(args, name);
4025
    if (!value) {
4026
        return check_opt(cmd_args, name, args);
4027
    }
4028

    
4029
    switch (cmd_args->type) {
4030
        case 'F':
4031
        case 'B':
4032
        case 's':
4033
            if (qobject_type(value) != QTYPE_QSTRING) {
4034
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "string");
4035
                return -1;
4036
            }
4037
            break;
4038
        case '/': {
4039
            int i;
4040
            const char *keys[] = { "count", "format", "size", NULL };
4041

    
4042
            for (i = 0; keys[i]; i++) {
4043
                QObject *obj = qdict_get(args, keys[i]);
4044
                if (!obj) {
4045
                    qemu_error_new(QERR_MISSING_PARAMETER, name);
4046
                    return -1;
4047
                }
4048
                if (qobject_type(obj) != QTYPE_QINT) {
4049
                    qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "int");
4050
                    return -1;
4051
                }
4052
            }
4053
            break;
4054
        }
4055
        case 'i':
4056
        case 'l':
4057
        case 'M':
4058
            if (qobject_type(value) != QTYPE_QINT) {
4059
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "int");
4060
                return -1;
4061
            }
4062
            break;
4063
        case '-':
4064
            if (qobject_type(value) != QTYPE_QINT &&
4065
                qobject_type(value) != QTYPE_QBOOL) {
4066
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "bool");
4067
                return -1;
4068
            }
4069
            if (qobject_type(value) == QTYPE_QBOOL) {
4070
                /* handlers expect a QInt, they need to be changed */
4071
                qdict_put(args, name,
4072
                         qint_from_int(qbool_get_int(qobject_to_qbool(value))));
4073
            }
4074
            break;
4075
        default:
4076
            /* impossible */
4077
            abort();
4078
    }
4079

    
4080
    return 0;
4081
}
4082

    
4083
static void cmd_args_init(CmdArgs *cmd_args)
4084
{
4085
    cmd_args->name = qstring_new();
4086
    cmd_args->type = cmd_args->flag = cmd_args->optional = 0;
4087
}
4088

    
4089
/*
4090
 * This is not trivial, we have to parse Monitor command's argument
4091
 * type syntax to be able to check the arguments provided by clients.
4092
 *
4093
 * In the near future we will be using an array for that and will be
4094
 * able to drop all this parsing...
4095
 */
4096
static int monitor_check_qmp_args(const mon_cmd_t *cmd, QDict *args)
4097
{
4098
    int err;
4099
    const char *p;
4100
    CmdArgs cmd_args;
4101

    
4102
    if (cmd->args_type == NULL) {
4103
        return (qdict_size(args) == 0 ? 0 : -1);
4104
    }
4105

    
4106
    err = 0;
4107
    cmd_args_init(&cmd_args);
4108

    
4109
    for (p = cmd->args_type;; p++) {
4110
        if (*p == ':') {
4111
            cmd_args.type = *++p;
4112
            p++;
4113
            if (cmd_args.type == '-') {
4114
                cmd_args.flag = *p++;
4115
                cmd_args.optional = 1;
4116
            } else if (*p == '?') {
4117
                cmd_args.optional = 1;
4118
                p++;
4119
            }
4120

    
4121
            assert(*p == ',' || *p == '\0');
4122
            err = check_arg(&cmd_args, args);
4123

    
4124
            QDECREF(cmd_args.name);
4125
            cmd_args_init(&cmd_args);
4126

    
4127
            if (err < 0) {
4128
                break;
4129
            }
4130
        } else {
4131
            qstring_append_chr(cmd_args.name, *p);
4132
        }
4133

    
4134
        if (*p == '\0') {
4135
            break;
4136
        }
4137
    }
4138

    
4139
    QDECREF(cmd_args.name);
4140
    return err;
4141
}
4142

    
4143
static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
4144
{
4145
    int err;
4146
    QObject *obj;
4147
    QDict *input, *args;
4148
    const mon_cmd_t *cmd;
4149
    Monitor *mon = cur_mon;
4150
    const char *cmd_name, *info_item;
4151

    
4152
    args = NULL;
4153
    qemu_errors_to_mon(mon);
4154

    
4155
    obj = json_parser_parse(tokens, NULL);
4156
    if (!obj) {
4157
        // FIXME: should be triggered in json_parser_parse()
4158
        qemu_error_new(QERR_JSON_PARSING);
4159
        goto err_out;
4160
    } else if (qobject_type(obj) != QTYPE_QDICT) {
4161
        qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "object");
4162
        qobject_decref(obj);
4163
        goto err_out;
4164
    }
4165

    
4166
    input = qobject_to_qdict(obj);
4167

    
4168
    mon->mc->id = qdict_get(input, "id");
4169
    qobject_incref(mon->mc->id);
4170

    
4171
    obj = qdict_get(input, "execute");
4172
    if (!obj) {
4173
        qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4174
        goto err_input;
4175
    } else if (qobject_type(obj) != QTYPE_QSTRING) {
4176
        qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "string");
4177
        goto err_input;
4178
    }
4179

    
4180
    cmd_name = qstring_get_str(qobject_to_qstring(obj));
4181

    
4182
    /*
4183
     * XXX: We need this special case until we get info handlers
4184
     * converted into 'query-' commands
4185
     */
4186
    if (compare_cmd(cmd_name, "info")) {
4187
        qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4188
        goto err_input;
4189
    } else if (strstart(cmd_name, "query-", &info_item)) {
4190
        cmd = monitor_find_command("info");
4191
        qdict_put_obj(input, "arguments",
4192
                      qobject_from_jsonf("{ 'item': %s }", info_item));
4193
    } else {
4194
        cmd = monitor_find_command(cmd_name);
4195
        if (!cmd || !monitor_handler_ported(cmd)) {
4196
            qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4197
            goto err_input;
4198
        }
4199
    }
4200

    
4201
    obj = qdict_get(input, "arguments");
4202
    if (!obj) {
4203
        args = qdict_new();
4204
    } else {
4205
        args = qobject_to_qdict(obj);
4206
        QINCREF(args);
4207
    }
4208

    
4209
    QDECREF(input);
4210

    
4211
    err = monitor_check_qmp_args(cmd, args);
4212
    if (err < 0) {
4213
        goto err_out;
4214
    }
4215

    
4216
    if (monitor_handler_is_async(cmd)) {
4217
        qmp_async_cmd_handler(mon, cmd, args);
4218
    } else {
4219
        monitor_call_handler(mon, cmd, args);
4220
    }
4221
    goto out;
4222

    
4223
err_input:
4224
    QDECREF(input);
4225
err_out:
4226
    monitor_protocol_emitter(mon, NULL);
4227
out:
4228
    QDECREF(args);
4229
    qemu_errors_to_previous();
4230
}
4231

    
4232
/**
4233
 * monitor_control_read(): Read and handle QMP input
4234
 */
4235
static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
4236
{
4237
    Monitor *old_mon = cur_mon;
4238

    
4239
    cur_mon = opaque;
4240

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

    
4243
    cur_mon = old_mon;
4244
}
4245

    
4246
static void monitor_read(void *opaque, const uint8_t *buf, int size)
4247
{
4248
    Monitor *old_mon = cur_mon;
4249
    int i;
4250

    
4251
    cur_mon = opaque;
4252

    
4253
    if (cur_mon->rs) {
4254
        for (i = 0; i < size; i++)
4255
            readline_handle_byte(cur_mon->rs, buf[i]);
4256
    } else {
4257
        if (size == 0 || buf[size - 1] != 0)
4258
            monitor_printf(cur_mon, "corrupted command\n");
4259
        else
4260
            handle_user_command(cur_mon, (char *)buf);
4261
    }
4262

    
4263
    cur_mon = old_mon;
4264
}
4265

    
4266
static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
4267
{
4268
    monitor_suspend(mon);
4269
    handle_user_command(mon, cmdline);
4270
    monitor_resume(mon);
4271
}
4272

    
4273
int monitor_suspend(Monitor *mon)
4274
{
4275
    if (!mon->rs)
4276
        return -ENOTTY;
4277
    mon->suspend_cnt++;
4278
    return 0;
4279
}
4280

    
4281
void monitor_resume(Monitor *mon)
4282
{
4283
    if (!mon->rs)
4284
        return;
4285
    if (--mon->suspend_cnt == 0)
4286
        readline_show_prompt(mon->rs);
4287
}
4288

    
4289
/**
4290
 * monitor_control_event(): Print QMP gretting
4291
 */
4292
static void monitor_control_event(void *opaque, int event)
4293
{
4294
    if (event == CHR_EVENT_OPENED) {
4295
        QObject *data;
4296
        Monitor *mon = opaque;
4297

    
4298
        json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4299

    
4300
        data = qobject_from_jsonf("{ 'QMP': { 'capabilities': [] } }");
4301
        assert(data != NULL);
4302

    
4303
        monitor_json_emitter(mon, data);
4304
        qobject_decref(data);
4305
    }
4306
}
4307

    
4308
static void monitor_event(void *opaque, int event)
4309
{
4310
    Monitor *mon = opaque;
4311

    
4312
    switch (event) {
4313
    case CHR_EVENT_MUX_IN:
4314
        mon->mux_out = 0;
4315
        if (mon->reset_seen) {
4316
            readline_restart(mon->rs);
4317
            monitor_resume(mon);
4318
            monitor_flush(mon);
4319
        } else {
4320
            mon->suspend_cnt = 0;
4321
        }
4322
        break;
4323

    
4324
    case CHR_EVENT_MUX_OUT:
4325
        if (mon->reset_seen) {
4326
            if (mon->suspend_cnt == 0) {
4327
                monitor_printf(mon, "\n");
4328
            }
4329
            monitor_flush(mon);
4330
            monitor_suspend(mon);
4331
        } else {
4332
            mon->suspend_cnt++;
4333
        }
4334
        mon->mux_out = 1;
4335
        break;
4336

    
4337
    case CHR_EVENT_OPENED:
4338
        monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4339
                       "information\n", QEMU_VERSION);
4340
        if (!mon->mux_out) {
4341
            readline_show_prompt(mon->rs);
4342
        }
4343
        mon->reset_seen = 1;
4344
        break;
4345
    }
4346
}
4347

    
4348

    
4349
/*
4350
 * Local variables:
4351
 *  c-indent-level: 4
4352
 *  c-basic-offset: 4
4353
 *  tab-width: 8
4354
 * End:
4355
 */
4356

    
4357
void monitor_init(CharDriverState *chr, int flags)
4358
{
4359
    static int is_first_init = 1;
4360
    Monitor *mon;
4361

    
4362
    if (is_first_init) {
4363
        key_timer = qemu_new_timer(vm_clock, release_keys, NULL);
4364
        is_first_init = 0;
4365
    }
4366

    
4367
    mon = qemu_mallocz(sizeof(*mon));
4368

    
4369
    mon->chr = chr;
4370
    mon->flags = flags;
4371
    if (flags & MONITOR_USE_READLINE) {
4372
        mon->rs = readline_init(mon, monitor_find_completion);
4373
        monitor_read_command(mon, 0);
4374
    }
4375

    
4376
    if (monitor_ctrl_mode(mon)) {
4377
        mon->mc = qemu_mallocz(sizeof(MonitorControl));
4378
        /* Control mode requires special handlers */
4379
        qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
4380
                              monitor_control_event, mon);
4381
    } else {
4382
        qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4383
                              monitor_event, mon);
4384
    }
4385

    
4386
    QLIST_INSERT_HEAD(&mon_list, mon, entry);
4387
    if (!cur_mon || (flags & MONITOR_IS_DEFAULT))
4388
        cur_mon = mon;
4389
}
4390

    
4391
static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
4392
{
4393
    BlockDriverState *bs = opaque;
4394
    int ret = 0;
4395

    
4396
    if (bdrv_set_key(bs, password) != 0) {
4397
        monitor_printf(mon, "invalid password\n");
4398
        ret = -EPERM;
4399
    }
4400
    if (mon->password_completion_cb)
4401
        mon->password_completion_cb(mon->password_opaque, ret);
4402

    
4403
    monitor_read_command(mon, 1);
4404
}
4405

    
4406
void monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4407
                                 BlockDriverCompletionFunc *completion_cb,
4408
                                 void *opaque)
4409
{
4410
    int err;
4411

    
4412
    if (!bdrv_key_required(bs)) {
4413
        if (completion_cb)
4414
            completion_cb(opaque, 0);
4415
        return;
4416
    }
4417

    
4418
    if (monitor_ctrl_mode(mon)) {
4419
        qemu_error_new(QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs));
4420
        return;
4421
    }
4422

    
4423
    monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4424
                   bdrv_get_encrypted_filename(bs));
4425

    
4426
    mon->password_completion_cb = completion_cb;
4427
    mon->password_opaque = opaque;
4428

    
4429
    err = monitor_read_password(mon, bdrv_password_cb, bs);
4430

    
4431
    if (err && completion_cb)
4432
        completion_cb(opaque, err);
4433
}
4434

    
4435
typedef struct QemuErrorSink QemuErrorSink;
4436
struct QemuErrorSink {
4437
    enum {
4438
        ERR_SINK_FILE,
4439
        ERR_SINK_MONITOR,
4440
    } dest;
4441
    union {
4442
        FILE    *fp;
4443
        Monitor *mon;
4444
    };
4445
    QemuErrorSink *previous;
4446
};
4447

    
4448
static QemuErrorSink *qemu_error_sink;
4449

    
4450
void qemu_errors_to_file(FILE *fp)
4451
{
4452
    QemuErrorSink *sink;
4453

    
4454
    sink = qemu_mallocz(sizeof(*sink));
4455
    sink->dest = ERR_SINK_FILE;
4456
    sink->fp = fp;
4457
    sink->previous = qemu_error_sink;
4458
    qemu_error_sink = sink;
4459
}
4460

    
4461
void qemu_errors_to_mon(Monitor *mon)
4462
{
4463
    QemuErrorSink *sink;
4464

    
4465
    sink = qemu_mallocz(sizeof(*sink));
4466
    sink->dest = ERR_SINK_MONITOR;
4467
    sink->mon = mon;
4468
    sink->previous = qemu_error_sink;
4469
    qemu_error_sink = sink;
4470
}
4471

    
4472
void qemu_errors_to_previous(void)
4473
{
4474
    QemuErrorSink *sink;
4475

    
4476
    assert(qemu_error_sink != NULL);
4477
    sink = qemu_error_sink;
4478
    qemu_error_sink = sink->previous;
4479
    qemu_free(sink);
4480
}
4481

    
4482
void qemu_error(const char *fmt, ...)
4483
{
4484
    va_list args;
4485

    
4486
    assert(qemu_error_sink != NULL);
4487
    switch (qemu_error_sink->dest) {
4488
    case ERR_SINK_FILE:
4489
        va_start(args, fmt);
4490
        vfprintf(qemu_error_sink->fp, fmt, args);
4491
        va_end(args);
4492
        break;
4493
    case ERR_SINK_MONITOR:
4494
        va_start(args, fmt);
4495
        monitor_vprintf(qemu_error_sink->mon, fmt, args);
4496
        va_end(args);
4497
        break;
4498
    }
4499
}
4500

    
4501
void qemu_error_internal(const char *file, int linenr, const char *func,
4502
                         const char *fmt, ...)
4503
{
4504
    va_list va;
4505
    QError *qerror;
4506

    
4507
    assert(qemu_error_sink != NULL);
4508

    
4509
    va_start(va, fmt);
4510
    qerror = qerror_from_info(file, linenr, func, fmt, &va);
4511
    va_end(va);
4512

    
4513
    switch (qemu_error_sink->dest) {
4514
    case ERR_SINK_FILE:
4515
        qerror_print(qerror);
4516
        QDECREF(qerror);
4517
        break;
4518
    case ERR_SINK_MONITOR:
4519
        assert(qemu_error_sink->mon->error == NULL);
4520
        qemu_error_sink->mon->error = qerror;
4521
        break;
4522
    }
4523
}