Statistics
| Branch: | Revision:

root / monitor.c @ cc0c4185

History | View | Annotate | Download (120.8 kB)

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

    
61
//#define DEBUG
62
//#define DEBUG_COMPLETION
63

    
64
/*
65
 * Supported types:
66
 *
67
 * 'F'          filename
68
 * 'B'          block device name
69
 * 's'          string (accept optional quote)
70
 * 'i'          32 bit integer
71
 * 'l'          target long (32 or 64 bit)
72
 * 'M'          just like 'l', except in user mode the value is
73
 *              multiplied by 2^20 (think Mebibyte)
74
 * 'b'          double
75
 *              user mode accepts an optional G, g, M, m, K, k suffix,
76
 *              which multiplies the value by 2^30 for suffixes G and
77
 *              g, 2^20 for M and m, 2^10 for K and k
78
 * 'T'          double
79
 *              user mode accepts an optional ms, us, ns suffix,
80
 *              which divides the value by 1e3, 1e6, 1e9, respectively
81
 * '/'          optional gdb-like print format (like "/10x")
82
 *
83
 * '?'          optional type (for all types, except '/')
84
 * '.'          other form of optional type (for 'i' and 'l')
85
 * '-'          optional parameter (eg. '-f')
86
 *
87
 */
88

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

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

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

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

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

    
145
static QLIST_HEAD(mon_list, Monitor) mon_list;
146

    
147
static const mon_cmd_t mon_cmds[];
148
static const mon_cmd_t info_cmds[];
149

    
150
Monitor *cur_mon = NULL;
151

    
152
static void monitor_command_cb(Monitor *mon, const char *cmdline,
153
                               void *opaque);
154

    
155
/* Return true if in control mode, false otherwise */
156
static inline int monitor_ctrl_mode(const Monitor *mon)
157
{
158
    return (mon->flags & MONITOR_USE_CONTROL);
159
}
160

    
161
static void monitor_read_command(Monitor *mon, int show_prompt)
162
{
163
    if (!mon->rs)
164
        return;
165

    
166
    readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
167
    if (show_prompt)
168
        readline_show_prompt(mon->rs);
169
}
170

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

    
187
void monitor_flush(Monitor *mon)
188
{
189
    if (mon && mon->outbuf_index != 0 && !mon->mux_out) {
190
        qemu_chr_write(mon->chr, mon->outbuf, mon->outbuf_index);
191
        mon->outbuf_index = 0;
192
    }
193
}
194

    
195
/* flush at every end of line or if the buffer is full */
196
static void monitor_puts(Monitor *mon, const char *str)
197
{
198
    char c;
199

    
200
    for(;;) {
201
        c = *str++;
202
        if (c == '\0')
203
            break;
204
        if (c == '\n')
205
            mon->outbuf[mon->outbuf_index++] = '\r';
206
        mon->outbuf[mon->outbuf_index++] = c;
207
        if (mon->outbuf_index >= (sizeof(mon->outbuf) - 1)
208
            || c == '\n')
209
            monitor_flush(mon);
210
    }
211
}
212

    
213
void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
214
{
215
    if (!mon)
216
        return;
217

    
218
    if (mon->mc && !mon->mc->print_enabled) {
219
        qemu_error_new(QERR_UNDEFINED_ERROR);
220
    } else {
221
        char buf[4096];
222
        vsnprintf(buf, sizeof(buf), fmt, ap);
223
        monitor_puts(mon, buf);
224
    }
225
}
226

    
227
void monitor_printf(Monitor *mon, const char *fmt, ...)
228
{
229
    va_list ap;
230
    va_start(ap, fmt);
231
    monitor_vprintf(mon, fmt, ap);
232
    va_end(ap);
233
}
234

    
235
void monitor_print_filename(Monitor *mon, const char *filename)
236
{
237
    int i;
238

    
239
    for (i = 0; filename[i]; i++) {
240
        switch (filename[i]) {
241
        case ' ':
242
        case '"':
243
        case '\\':
244
            monitor_printf(mon, "\\%c", filename[i]);
245
            break;
246
        case '\t':
247
            monitor_printf(mon, "\\t");
248
            break;
249
        case '\r':
250
            monitor_printf(mon, "\\r");
251
            break;
252
        case '\n':
253
            monitor_printf(mon, "\\n");
254
            break;
255
        default:
256
            monitor_printf(mon, "%c", filename[i]);
257
            break;
258
        }
259
    }
260
}
261

    
262
static int monitor_fprintf(FILE *stream, const char *fmt, ...)
263
{
264
    va_list ap;
265
    va_start(ap, fmt);
266
    monitor_vprintf((Monitor *)stream, fmt, ap);
267
    va_end(ap);
268
    return 0;
269
}
270

    
271
static void monitor_user_noop(Monitor *mon, const QObject *data) { }
272

    
273
static inline int monitor_handler_ported(const mon_cmd_t *cmd)
274
{
275
    return cmd->user_print != NULL;
276
}
277

    
278
static inline bool monitor_handler_is_async(const mon_cmd_t *cmd)
279
{
280
    return cmd->async != 0;
281
}
282

    
283
static inline int monitor_has_error(const Monitor *mon)
284
{
285
    return mon->error != NULL;
286
}
287

    
288
static void monitor_json_emitter(Monitor *mon, const QObject *data)
289
{
290
    QString *json;
291

    
292
    json = qobject_to_json(data);
293
    assert(json != NULL);
294

    
295
    mon->mc->print_enabled = 1;
296
    monitor_printf(mon, "%s\n", qstring_get_str(json));
297
    mon->mc->print_enabled = 0;
298

    
299
    QDECREF(json);
300
}
301

    
302
static void monitor_protocol_emitter(Monitor *mon, QObject *data)
303
{
304
    QDict *qmp;
305

    
306
    qmp = qdict_new();
307

    
308
    if (!monitor_has_error(mon)) {
309
        /* success response */
310
        if (data) {
311
            qobject_incref(data);
312
            qdict_put_obj(qmp, "return", data);
313
        } else {
314
            /* return an empty QDict by default */
315
            qdict_put(qmp, "return", qdict_new());
316
        }
317
    } else {
318
        /* error response */
319
        qdict_put(mon->error->error, "desc", qerror_human(mon->error));
320
        qdict_put(qmp, "error", mon->error->error);
321
        QINCREF(mon->error->error);
322
        QDECREF(mon->error);
323
        mon->error = NULL;
324
    }
325

    
326
    if (mon->mc->id) {
327
        qdict_put_obj(qmp, "id", mon->mc->id);
328
        mon->mc->id = NULL;
329
    }
330

    
331
    monitor_json_emitter(mon, QOBJECT(qmp));
332
    QDECREF(qmp);
333
}
334

    
335
static void timestamp_put(QDict *qdict)
336
{
337
    int err;
338
    QObject *obj;
339
    qemu_timeval tv;
340

    
341
    err = qemu_gettimeofday(&tv);
342
    if (err < 0)
343
        return;
344

    
345
    obj = qobject_from_jsonf("{ 'seconds': %" PRId64 ", "
346
                                "'microseconds': %" PRId64 " }",
347
                                (int64_t) tv.tv_sec, (int64_t) tv.tv_usec);
348
    assert(obj != NULL);
349

    
350
    qdict_put_obj(qdict, "timestamp", obj);
351
}
352

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

    
364
    assert(event < QEVENT_MAX);
365

    
366
    switch (event) {
367
        case QEVENT_DEBUG:
368
            event_name = "DEBUG";
369
            break;
370
        case QEVENT_SHUTDOWN:
371
            event_name = "SHUTDOWN";
372
            break;
373
        case QEVENT_RESET:
374
            event_name = "RESET";
375
            break;
376
        case QEVENT_POWERDOWN:
377
            event_name = "POWERDOWN";
378
            break;
379
        case QEVENT_STOP:
380
            event_name = "STOP";
381
            break;
382
        case QEVENT_VNC_CONNECTED:
383
            event_name = "VNC_CONNECTED";
384
            break;
385
        case QEVENT_VNC_INITIALIZED:
386
            event_name = "VNC_INITIALIZED";
387
            break;
388
        case QEVENT_VNC_DISCONNECTED:
389
            event_name = "VNC_DISCONNECTED";
390
            break;
391
        default:
392
            abort();
393
            break;
394
    }
395

    
396
    qmp = qdict_new();
397
    timestamp_put(qmp);
398
    qdict_put(qmp, "event", qstring_from_str(event_name));
399
    if (data) {
400
        qobject_incref(data);
401
        qdict_put_obj(qmp, "data", data);
402
    }
403

    
404
    QLIST_FOREACH(mon, &mon_list, entry) {
405
        if (monitor_ctrl_mode(mon)) {
406
            monitor_json_emitter(mon, QOBJECT(qmp));
407
        }
408
    }
409
    QDECREF(qmp);
410
}
411

    
412
static int compare_cmd(const char *name, const char *list)
413
{
414
    const char *p, *pstart;
415
    int len;
416
    len = strlen(name);
417
    p = list;
418
    for(;;) {
419
        pstart = p;
420
        p = strchr(p, '|');
421
        if (!p)
422
            p = pstart + strlen(pstart);
423
        if ((p - pstart) == len && !memcmp(pstart, name, len))
424
            return 1;
425
        if (*p == '\0')
426
            break;
427
        p++;
428
    }
429
    return 0;
430
}
431

    
432
static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
433
                          const char *prefix, const char *name)
434
{
435
    const mon_cmd_t *cmd;
436

    
437
    for(cmd = cmds; cmd->name != NULL; cmd++) {
438
        if (!name || !strcmp(name, cmd->name))
439
            monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
440
                           cmd->params, cmd->help);
441
    }
442
}
443

    
444
static void help_cmd(Monitor *mon, const char *name)
445
{
446
    if (name && !strcmp(name, "info")) {
447
        help_cmd_dump(mon, info_cmds, "info ", NULL);
448
    } else {
449
        help_cmd_dump(mon, mon_cmds, "", name);
450
        if (name && !strcmp(name, "log")) {
451
            const CPULogItem *item;
452
            monitor_printf(mon, "Log items (comma separated):\n");
453
            monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
454
            for(item = cpu_log_items; item->mask != 0; item++) {
455
                monitor_printf(mon, "%-10s %s\n", item->name, item->help);
456
            }
457
        }
458
    }
459
}
460

    
461
static void do_help_cmd(Monitor *mon, const QDict *qdict)
462
{
463
    help_cmd(mon, qdict_get_try_str(qdict, "name"));
464
}
465

    
466
static void do_commit(Monitor *mon, const QDict *qdict)
467
{
468
    int all_devices;
469
    DriveInfo *dinfo;
470
    const char *device = qdict_get_str(qdict, "device");
471

    
472
    all_devices = !strcmp(device, "all");
473
    QTAILQ_FOREACH(dinfo, &drives, next) {
474
        if (!all_devices)
475
            if (strcmp(bdrv_get_device_name(dinfo->bdrv), device))
476
                continue;
477
        bdrv_commit(dinfo->bdrv);
478
    }
479
}
480

    
481
static void user_monitor_complete(void *opaque, QObject *ret_data)
482
{
483
    MonitorCompletionData *data = (MonitorCompletionData *)opaque; 
484

    
485
    if (ret_data) {
486
        data->user_print(data->mon, ret_data);
487
    }
488
    monitor_resume(data->mon);
489
    qemu_free(data);
490
}
491

    
492
static void qmp_monitor_complete(void *opaque, QObject *ret_data)
493
{
494
    monitor_protocol_emitter(opaque, ret_data);
495
}
496

    
497
static void qmp_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
498
                                  const QDict *params)
499
{
500
    cmd->mhandler.cmd_async(mon, params, qmp_monitor_complete, mon);
501
}
502

    
503
static void qmp_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
504
{
505
    cmd->mhandler.info_async(mon, qmp_monitor_complete, mon);
506
}
507

    
508
static void user_async_cmd_handler(Monitor *mon, const mon_cmd_t *cmd,
509
                                   const QDict *params)
510
{
511
    int ret;
512

    
513
    MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
514
    cb_data->mon = mon;
515
    cb_data->user_print = cmd->user_print;
516
    monitor_suspend(mon);
517
    ret = cmd->mhandler.cmd_async(mon, params,
518
                                  user_monitor_complete, cb_data);
519
    if (ret < 0) {
520
        monitor_resume(mon);
521
        qemu_free(cb_data);
522
    }
523
}
524

    
525
static void user_async_info_handler(Monitor *mon, const mon_cmd_t *cmd)
526
{
527
    int ret;
528

    
529
    MonitorCompletionData *cb_data = qemu_malloc(sizeof(*cb_data));
530
    cb_data->mon = mon;
531
    cb_data->user_print = cmd->user_print;
532
    monitor_suspend(mon);
533
    ret = cmd->mhandler.info_async(mon, user_monitor_complete, cb_data);
534
    if (ret < 0) {
535
        monitor_resume(mon);
536
        qemu_free(cb_data);
537
    }
538
}
539

    
540
static void do_info(Monitor *mon, const QDict *qdict, QObject **ret_data)
541
{
542
    const mon_cmd_t *cmd;
543
    const char *item = qdict_get_try_str(qdict, "item");
544

    
545
    if (!item) {
546
        assert(monitor_ctrl_mode(mon) == 0);
547
        goto help;
548
    }
549

    
550
    for (cmd = info_cmds; cmd->name != NULL; cmd++) {
551
        if (compare_cmd(item, cmd->name))
552
            break;
553
    }
554

    
555
    if (cmd->name == NULL) {
556
        if (monitor_ctrl_mode(mon)) {
557
            qemu_error_new(QERR_COMMAND_NOT_FOUND, item);
558
            return;
559
        }
560
        goto help;
561
    }
562

    
563
    if (monitor_handler_is_async(cmd)) {
564
        if (monitor_ctrl_mode(mon)) {
565
            qmp_async_info_handler(mon, cmd);
566
        } else {
567
            user_async_info_handler(mon, cmd);
568
        }
569
        /*
570
         * Indicate that this command is asynchronous and will not return any
571
         * data (not even empty).  Instead, the data will be returned via a
572
         * completion callback.
573
         */
574
        *ret_data = qobject_from_jsonf("{ '__mon_async': 'return' }");
575
    } else if (monitor_handler_ported(cmd)) {
576
        cmd->mhandler.info_new(mon, ret_data);
577

    
578
        if (!monitor_ctrl_mode(mon)) {
579
            /*
580
             * User Protocol function is called here, Monitor Protocol is
581
             * handled by monitor_call_handler()
582
             */
583
            if (*ret_data)
584
                cmd->user_print(mon, *ret_data);
585
        }
586
    } else {
587
        if (monitor_ctrl_mode(mon)) {
588
            /* handler not converted yet */
589
            qemu_error_new(QERR_COMMAND_NOT_FOUND, item);
590
        } else {
591
            cmd->mhandler.info(mon);
592
        }
593
    }
594

    
595
    return;
596

    
597
help:
598
    help_cmd(mon, "info");
599
}
600

    
601
static void do_info_version_print(Monitor *mon, const QObject *data)
602
{
603
    QDict *qdict;
604

    
605
    qdict = qobject_to_qdict(data);
606

    
607
    monitor_printf(mon, "%s%s\n", qdict_get_str(qdict, "qemu"),
608
                                  qdict_get_str(qdict, "package"));
609
}
610

    
611
/**
612
 * do_info_version(): Show QEMU version
613
 *
614
 * Return a QDict with the following information:
615
 *
616
 * - "qemu": QEMU's version
617
 * - "package": package's version
618
 *
619
 * Example:
620
 *
621
 * { "qemu": "0.11.50", "package": "" }
622
 */
623
static void do_info_version(Monitor *mon, QObject **ret_data)
624
{
625
    *ret_data = qobject_from_jsonf("{ 'qemu': %s, 'package': %s }",
626
                                   QEMU_VERSION, QEMU_PKGVERSION);
627
}
628

    
629
static void do_info_name_print(Monitor *mon, const QObject *data)
630
{
631
    QDict *qdict;
632

    
633
    qdict = qobject_to_qdict(data);
634
    if (qdict_size(qdict) == 0) {
635
        return;
636
    }
637

    
638
    monitor_printf(mon, "%s\n", qdict_get_str(qdict, "name"));
639
}
640

    
641
/**
642
 * do_info_name(): Show VM name
643
 *
644
 * Return a QDict with the following information:
645
 *
646
 * - "name": VM's name (optional)
647
 *
648
 * Example:
649
 *
650
 * { "name": "qemu-name" }
651
 */
652
static void do_info_name(Monitor *mon, QObject **ret_data)
653
{
654
    *ret_data = qemu_name ? qobject_from_jsonf("{'name': %s }", qemu_name) :
655
                            qobject_from_jsonf("{}");
656
}
657

    
658
static QObject *get_cmd_dict(const char *name)
659
{
660
    const char *p;
661

    
662
    /* Remove '|' from some commands */
663
    p = strchr(name, '|');
664
    if (p) {
665
        p++;
666
    } else {
667
        p = name;
668
    }
669

    
670
    return qobject_from_jsonf("{ 'name': %s }", p);
671
}
672

    
673
/**
674
 * do_info_commands(): List QMP available commands
675
 *
676
 * Each command is represented by a QDict, the returned QObject is a QList
677
 * of all commands.
678
 *
679
 * The QDict contains:
680
 *
681
 * - "name": command's name
682
 *
683
 * Example:
684
 *
685
 * { [ { "name": "query-balloon" }, { "name": "system_powerdown" } ] }
686
 */
687
static void do_info_commands(Monitor *mon, QObject **ret_data)
688
{
689
    QList *cmd_list;
690
    const mon_cmd_t *cmd;
691

    
692
    cmd_list = qlist_new();
693

    
694
    for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
695
        if (monitor_handler_ported(cmd) && !compare_cmd(cmd->name, "info")) {
696
            qlist_append_obj(cmd_list, get_cmd_dict(cmd->name));
697
        }
698
    }
699

    
700
    for (cmd = info_cmds; cmd->name != NULL; cmd++) {
701
        if (monitor_handler_ported(cmd)) {
702
            char buf[128];
703
            snprintf(buf, sizeof(buf), "query-%s", cmd->name);
704
            qlist_append_obj(cmd_list, get_cmd_dict(buf));
705
        }
706
    }
707

    
708
    *ret_data = QOBJECT(cmd_list);
709
}
710

    
711
#if defined(TARGET_I386)
712
static void do_info_hpet_print(Monitor *mon, const QObject *data)
713
{
714
    monitor_printf(mon, "HPET is %s by QEMU\n",
715
                   qdict_get_bool(qobject_to_qdict(data), "enabled") ?
716
                   "enabled" : "disabled");
717
}
718

    
719
/**
720
 * do_info_hpet(): Show HPET state
721
 *
722
 * Return a QDict with the following information:
723
 *
724
 * - "enabled": true if hpet if enabled, false otherwise
725
 *
726
 * Example:
727
 *
728
 * { "enabled": true }
729
 */
730
static void do_info_hpet(Monitor *mon, QObject **ret_data)
731
{
732
    *ret_data = qobject_from_jsonf("{ 'enabled': %i }", !no_hpet);
733
}
734
#endif
735

    
736
static void do_info_uuid_print(Monitor *mon, const QObject *data)
737
{
738
    monitor_printf(mon, "%s\n", qdict_get_str(qobject_to_qdict(data), "UUID"));
739
}
740

    
741
/**
742
 * do_info_uuid(): Show VM UUID
743
 *
744
 * Return a QDict with the following information:
745
 *
746
 * - "UUID": Universally Unique Identifier
747
 *
748
 * Example:
749
 *
750
 * { "UUID": "550e8400-e29b-41d4-a716-446655440000" }
751
 */
752
static void do_info_uuid(Monitor *mon, QObject **ret_data)
753
{
754
    char uuid[64];
755

    
756
    snprintf(uuid, sizeof(uuid), UUID_FMT, qemu_uuid[0], qemu_uuid[1],
757
                   qemu_uuid[2], qemu_uuid[3], qemu_uuid[4], qemu_uuid[5],
758
                   qemu_uuid[6], qemu_uuid[7], qemu_uuid[8], qemu_uuid[9],
759
                   qemu_uuid[10], qemu_uuid[11], qemu_uuid[12], qemu_uuid[13],
760
                   qemu_uuid[14], qemu_uuid[15]);
761
    *ret_data = qobject_from_jsonf("{ 'UUID': %s }", uuid);
762
}
763

    
764
/* get the current CPU defined by the user */
765
static int mon_set_cpu(int cpu_index)
766
{
767
    CPUState *env;
768

    
769
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
770
        if (env->cpu_index == cpu_index) {
771
            cur_mon->mon_cpu = env;
772
            return 0;
773
        }
774
    }
775
    return -1;
776
}
777

    
778
static CPUState *mon_get_cpu(void)
779
{
780
    if (!cur_mon->mon_cpu) {
781
        mon_set_cpu(0);
782
    }
783
    cpu_synchronize_state(cur_mon->mon_cpu);
784
    return cur_mon->mon_cpu;
785
}
786

    
787
static void do_info_registers(Monitor *mon)
788
{
789
    CPUState *env;
790
    env = mon_get_cpu();
791
#ifdef TARGET_I386
792
    cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
793
                   X86_DUMP_FPU);
794
#else
795
    cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
796
                   0);
797
#endif
798
}
799

    
800
static void print_cpu_iter(QObject *obj, void *opaque)
801
{
802
    QDict *cpu;
803
    int active = ' ';
804
    Monitor *mon = opaque;
805

    
806
    assert(qobject_type(obj) == QTYPE_QDICT);
807
    cpu = qobject_to_qdict(obj);
808

    
809
    if (qdict_get_bool(cpu, "current")) {
810
        active = '*';
811
    }
812

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

    
815
#if defined(TARGET_I386)
816
    monitor_printf(mon, "pc=0x" TARGET_FMT_lx,
817
                   (target_ulong) qdict_get_int(cpu, "pc"));
818
#elif defined(TARGET_PPC)
819
    monitor_printf(mon, "nip=0x" TARGET_FMT_lx,
820
                   (target_long) qdict_get_int(cpu, "nip"));
821
#elif defined(TARGET_SPARC)
822
    monitor_printf(mon, "pc=0x " TARGET_FMT_lx,
823
                   (target_long) qdict_get_int(cpu, "pc"));
824
    monitor_printf(mon, "npc=0x" TARGET_FMT_lx,
825
                   (target_long) qdict_get_int(cpu, "npc"));
826
#elif defined(TARGET_MIPS)
827
    monitor_printf(mon, "PC=0x" TARGET_FMT_lx,
828
                   (target_long) qdict_get_int(cpu, "PC"));
829
#endif
830

    
831
    if (qdict_get_bool(cpu, "halted")) {
832
        monitor_printf(mon, " (halted)");
833
    }
834

    
835
    monitor_printf(mon, "\n");
836
}
837

    
838
static void monitor_print_cpus(Monitor *mon, const QObject *data)
839
{
840
    QList *cpu_list;
841

    
842
    assert(qobject_type(data) == QTYPE_QLIST);
843
    cpu_list = qobject_to_qlist(data);
844
    qlist_iter(cpu_list, print_cpu_iter, mon);
845
}
846

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

    
871
    cpu_list = qlist_new();
872

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

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

    
880
        cpu_synchronize_state(env);
881

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

    
887
        cpu = qobject_to_qdict(obj);
888

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

    
900
        qlist_append(cpu_list, cpu);
901
    }
902

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

    
906
static void do_cpu_set(Monitor *mon, const QDict *qdict, QObject **ret_data)
907
{
908
    int index = qdict_get_int(qdict, "index");
909
    if (mon_set_cpu(index) < 0)
910
        qemu_error_new(QERR_INVALID_PARAMETER, "index");
911
}
912

    
913
static void do_info_jit(Monitor *mon)
914
{
915
    dump_exec_info((FILE *)mon, monitor_fprintf);
916
}
917

    
918
static void do_info_history(Monitor *mon)
919
{
920
    int i;
921
    const char *str;
922

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

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

    
941
    env = mon_get_cpu();
942
    cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
943
}
944
#endif
945

    
946
/**
947
 * do_quit(): Quit QEMU execution
948
 */
949
static void do_quit(Monitor *mon, const QDict *qdict, QObject **ret_data)
950
{
951
    exit(0);
952
}
953

    
954
static int eject_device(Monitor *mon, BlockDriverState *bs, int force)
955
{
956
    if (bdrv_is_inserted(bs)) {
957
        if (!force) {
958
            if (!bdrv_is_removable(bs)) {
959
                qemu_error_new(QERR_DEVICE_NOT_REMOVABLE,
960
                               bdrv_get_device_name(bs));
961
                return -1;
962
            }
963
            if (bdrv_is_locked(bs)) {
964
                qemu_error_new(QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));
965
                return -1;
966
            }
967
        }
968
        bdrv_close(bs);
969
    }
970
    return 0;
971
}
972

    
973
static void do_eject(Monitor *mon, const QDict *qdict, QObject **ret_data)
974
{
975
    BlockDriverState *bs;
976
    int force = qdict_get_int(qdict, "force");
977
    const char *filename = qdict_get_str(qdict, "device");
978

    
979
    bs = bdrv_find(filename);
980
    if (!bs) {
981
        qemu_error_new(QERR_DEVICE_NOT_FOUND, filename);
982
        return;
983
    }
984
    eject_device(mon, bs, force);
985
}
986

    
987
static void do_block_set_passwd(Monitor *mon, const QDict *qdict,
988
                                QObject **ret_data)
989
{
990
    BlockDriverState *bs;
991

    
992
    bs = bdrv_find(qdict_get_str(qdict, "device"));
993
    if (!bs) {
994
        qemu_error_new(QERR_DEVICE_NOT_FOUND, qdict_get_str(qdict, "device"));
995
        return;
996
    }
997

    
998
    if (bdrv_set_key(bs, qdict_get_str(qdict, "password")) < 0) {
999
        qemu_error_new(QERR_INVALID_PASSWORD);
1000
    }
1001
}
1002

    
1003
static void do_change_block(Monitor *mon, const char *device,
1004
                            const char *filename, const char *fmt)
1005
{
1006
    BlockDriverState *bs;
1007
    BlockDriver *drv = NULL;
1008

    
1009
    bs = bdrv_find(device);
1010
    if (!bs) {
1011
        qemu_error_new(QERR_DEVICE_NOT_FOUND, device);
1012
        return;
1013
    }
1014
    if (fmt) {
1015
        drv = bdrv_find_whitelisted_format(fmt);
1016
        if (!drv) {
1017
            qemu_error_new(QERR_INVALID_BLOCK_FORMAT, fmt);
1018
            return;
1019
        }
1020
    }
1021
    if (eject_device(mon, bs, 0) < 0)
1022
        return;
1023
    bdrv_open2(bs, filename, BDRV_O_RDWR, drv);
1024
    monitor_read_bdrv_key_start(mon, bs, NULL, NULL);
1025
}
1026

    
1027
static void change_vnc_password(const char *password)
1028
{
1029
    if (vnc_display_password(NULL, password) < 0)
1030
        qemu_error_new(QERR_SET_PASSWD_FAILED);
1031

    
1032
}
1033

    
1034
static void change_vnc_password_cb(Monitor *mon, const char *password,
1035
                                   void *opaque)
1036
{
1037
    change_vnc_password(password);
1038
    monitor_read_command(mon, 1);
1039
}
1040

    
1041
static void do_change_vnc(Monitor *mon, const char *target, const char *arg)
1042
{
1043
    if (strcmp(target, "passwd") == 0 ||
1044
        strcmp(target, "password") == 0) {
1045
        if (arg) {
1046
            char password[9];
1047
            strncpy(password, arg, sizeof(password));
1048
            password[sizeof(password) - 1] = '\0';
1049
            change_vnc_password(password);
1050
        } else {
1051
            monitor_read_password(mon, change_vnc_password_cb, NULL);
1052
        }
1053
    } else {
1054
        if (vnc_display_open(NULL, target) < 0)
1055
            qemu_error_new(QERR_VNC_SERVER_FAILED, target);
1056
    }
1057
}
1058

    
1059
/**
1060
 * do_change(): Change a removable medium, or VNC configuration
1061
 */
1062
static void do_change(Monitor *mon, const QDict *qdict, QObject **ret_data)
1063
{
1064
    const char *device = qdict_get_str(qdict, "device");
1065
    const char *target = qdict_get_str(qdict, "target");
1066
    const char *arg = qdict_get_try_str(qdict, "arg");
1067
    if (strcmp(device, "vnc") == 0) {
1068
        do_change_vnc(mon, target, arg);
1069
    } else {
1070
        do_change_block(mon, device, target, arg);
1071
    }
1072
}
1073

    
1074
static void do_screen_dump(Monitor *mon, const QDict *qdict)
1075
{
1076
    vga_hw_screen_dump(qdict_get_str(qdict, "filename"));
1077
}
1078

    
1079
static void do_logfile(Monitor *mon, const QDict *qdict)
1080
{
1081
    cpu_set_log_filename(qdict_get_str(qdict, "filename"));
1082
}
1083

    
1084
static void do_log(Monitor *mon, const QDict *qdict)
1085
{
1086
    int mask;
1087
    const char *items = qdict_get_str(qdict, "items");
1088

    
1089
    if (!strcmp(items, "none")) {
1090
        mask = 0;
1091
    } else {
1092
        mask = cpu_str_to_log_mask(items);
1093
        if (!mask) {
1094
            help_cmd(mon, "log");
1095
            return;
1096
        }
1097
    }
1098
    cpu_set_log(mask);
1099
}
1100

    
1101
static void do_singlestep(Monitor *mon, const QDict *qdict)
1102
{
1103
    const char *option = qdict_get_try_str(qdict, "option");
1104
    if (!option || !strcmp(option, "on")) {
1105
        singlestep = 1;
1106
    } else if (!strcmp(option, "off")) {
1107
        singlestep = 0;
1108
    } else {
1109
        monitor_printf(mon, "unexpected option %s\n", option);
1110
    }
1111
}
1112

    
1113
/**
1114
 * do_stop(): Stop VM execution
1115
 */
1116
static void do_stop(Monitor *mon, const QDict *qdict, QObject **ret_data)
1117
{
1118
    vm_stop(EXCP_INTERRUPT);
1119
}
1120

    
1121
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs);
1122

    
1123
struct bdrv_iterate_context {
1124
    Monitor *mon;
1125
    int err;
1126
};
1127

    
1128
/**
1129
 * do_cont(): Resume emulation.
1130
 */
1131
static void do_cont(Monitor *mon, const QDict *qdict, QObject **ret_data)
1132
{
1133
    struct bdrv_iterate_context context = { mon, 0 };
1134

    
1135
    bdrv_iterate(encrypted_bdrv_it, &context);
1136
    /* only resume the vm if all keys are set and valid */
1137
    if (!context.err)
1138
        vm_start();
1139
}
1140

    
1141
static void bdrv_key_cb(void *opaque, int err)
1142
{
1143
    Monitor *mon = opaque;
1144

    
1145
    /* another key was set successfully, retry to continue */
1146
    if (!err)
1147
        do_cont(mon, NULL, NULL);
1148
}
1149

    
1150
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs)
1151
{
1152
    struct bdrv_iterate_context *context = opaque;
1153

    
1154
    if (!context->err && bdrv_key_required(bs)) {
1155
        context->err = -EBUSY;
1156
        monitor_read_bdrv_key_start(context->mon, bs, bdrv_key_cb,
1157
                                    context->mon);
1158
    }
1159
}
1160

    
1161
static void do_gdbserver(Monitor *mon, const QDict *qdict)
1162
{
1163
    const char *device = qdict_get_try_str(qdict, "device");
1164
    if (!device)
1165
        device = "tcp::" DEFAULT_GDBSTUB_PORT;
1166
    if (gdbserver_start(device) < 0) {
1167
        monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
1168
                       device);
1169
    } else if (strcmp(device, "none") == 0) {
1170
        monitor_printf(mon, "Disabled gdbserver\n");
1171
    } else {
1172
        monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
1173
                       device);
1174
    }
1175
}
1176

    
1177
static void do_watchdog_action(Monitor *mon, const QDict *qdict)
1178
{
1179
    const char *action = qdict_get_str(qdict, "action");
1180
    if (select_watchdog_action(action) == -1) {
1181
        monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
1182
    }
1183
}
1184

    
1185
static void monitor_printc(Monitor *mon, int c)
1186
{
1187
    monitor_printf(mon, "'");
1188
    switch(c) {
1189
    case '\'':
1190
        monitor_printf(mon, "\\'");
1191
        break;
1192
    case '\\':
1193
        monitor_printf(mon, "\\\\");
1194
        break;
1195
    case '\n':
1196
        monitor_printf(mon, "\\n");
1197
        break;
1198
    case '\r':
1199
        monitor_printf(mon, "\\r");
1200
        break;
1201
    default:
1202
        if (c >= 32 && c <= 126) {
1203
            monitor_printf(mon, "%c", c);
1204
        } else {
1205
            monitor_printf(mon, "\\x%02x", c);
1206
        }
1207
        break;
1208
    }
1209
    monitor_printf(mon, "'");
1210
}
1211

    
1212
static void memory_dump(Monitor *mon, int count, int format, int wsize,
1213
                        target_phys_addr_t addr, int is_physical)
1214
{
1215
    CPUState *env;
1216
    int l, line_size, i, max_digits, len;
1217
    uint8_t buf[16];
1218
    uint64_t v;
1219

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

    
1250
    len = wsize * count;
1251
    if (wsize == 1)
1252
        line_size = 8;
1253
    else
1254
        line_size = 16;
1255
    max_digits = 0;
1256

    
1257
    switch(format) {
1258
    case 'o':
1259
        max_digits = (wsize * 8 + 2) / 3;
1260
        break;
1261
    default:
1262
    case 'x':
1263
        max_digits = (wsize * 8) / 4;
1264
        break;
1265
    case 'u':
1266
    case 'd':
1267
        max_digits = (wsize * 8 * 10 + 32) / 33;
1268
        break;
1269
    case 'c':
1270
        wsize = 1;
1271
        break;
1272
    }
1273

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

    
1334
static void do_memory_dump(Monitor *mon, const QDict *qdict)
1335
{
1336
    int count = qdict_get_int(qdict, "count");
1337
    int format = qdict_get_int(qdict, "format");
1338
    int size = qdict_get_int(qdict, "size");
1339
    target_long addr = qdict_get_int(qdict, "addr");
1340

    
1341
    memory_dump(mon, count, format, size, addr, 0);
1342
}
1343

    
1344
static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
1345
{
1346
    int count = qdict_get_int(qdict, "count");
1347
    int format = qdict_get_int(qdict, "format");
1348
    int size = qdict_get_int(qdict, "size");
1349
    target_phys_addr_t addr = qdict_get_int(qdict, "addr");
1350

    
1351
    memory_dump(mon, count, format, size, addr, 1);
1352
}
1353

    
1354
static void do_print(Monitor *mon, const QDict *qdict)
1355
{
1356
    int format = qdict_get_int(qdict, "format");
1357
    target_phys_addr_t val = qdict_get_int(qdict, "val");
1358

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

    
1401
static void do_memory_save(Monitor *mon, const QDict *qdict, QObject **ret_data)
1402
{
1403
    FILE *f;
1404
    uint32_t size = qdict_get_int(qdict, "size");
1405
    const char *filename = qdict_get_str(qdict, "filename");
1406
    target_long addr = qdict_get_int(qdict, "val");
1407
    uint32_t l;
1408
    CPUState *env;
1409
    uint8_t buf[1024];
1410

    
1411
    env = mon_get_cpu();
1412

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

    
1434
static void do_physical_memory_save(Monitor *mon, const QDict *qdict,
1435
                                    QObject **ret_data)
1436
{
1437
    FILE *f;
1438
    uint32_t l;
1439
    uint8_t buf[1024];
1440
    uint32_t size = qdict_get_int(qdict, "size");
1441
    const char *filename = qdict_get_str(qdict, "filename");
1442
    target_phys_addr_t addr = qdict_get_int(qdict, "val");
1443

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

    
1466
static void do_sum(Monitor *mon, const QDict *qdict)
1467
{
1468
    uint32_t addr;
1469
    uint8_t buf[1];
1470
    uint16_t sum;
1471
    uint32_t start = qdict_get_int(qdict, "start");
1472
    uint32_t size = qdict_get_int(qdict, "size");
1473

    
1474
    sum = 0;
1475
    for(addr = start; addr < (start + size); addr++) {
1476
        cpu_physical_memory_rw(addr, buf, 1, 0);
1477
        /* BSD sum algorithm ('sum' Unix command) */
1478
        sum = (sum >> 1) | (sum << 15);
1479
        sum += buf[0];
1480
    }
1481
    monitor_printf(mon, "%05d\n", sum);
1482
}
1483

    
1484
typedef struct {
1485
    int keycode;
1486
    const char *name;
1487
} KeyDef;
1488

    
1489
static const KeyDef key_defs[] = {
1490
    { 0x2a, "shift" },
1491
    { 0x36, "shift_r" },
1492

    
1493
    { 0x38, "alt" },
1494
    { 0xb8, "alt_r" },
1495
    { 0x64, "altgr" },
1496
    { 0xe4, "altgr_r" },
1497
    { 0x1d, "ctrl" },
1498
    { 0x9d, "ctrl_r" },
1499

    
1500
    { 0xdd, "menu" },
1501

    
1502
    { 0x01, "esc" },
1503

    
1504
    { 0x02, "1" },
1505
    { 0x03, "2" },
1506
    { 0x04, "3" },
1507
    { 0x05, "4" },
1508
    { 0x06, "5" },
1509
    { 0x07, "6" },
1510
    { 0x08, "7" },
1511
    { 0x09, "8" },
1512
    { 0x0a, "9" },
1513
    { 0x0b, "0" },
1514
    { 0x0c, "minus" },
1515
    { 0x0d, "equal" },
1516
    { 0x0e, "backspace" },
1517

    
1518
    { 0x0f, "tab" },
1519
    { 0x10, "q" },
1520
    { 0x11, "w" },
1521
    { 0x12, "e" },
1522
    { 0x13, "r" },
1523
    { 0x14, "t" },
1524
    { 0x15, "y" },
1525
    { 0x16, "u" },
1526
    { 0x17, "i" },
1527
    { 0x18, "o" },
1528
    { 0x19, "p" },
1529

    
1530
    { 0x1c, "ret" },
1531

    
1532
    { 0x1e, "a" },
1533
    { 0x1f, "s" },
1534
    { 0x20, "d" },
1535
    { 0x21, "f" },
1536
    { 0x22, "g" },
1537
    { 0x23, "h" },
1538
    { 0x24, "j" },
1539
    { 0x25, "k" },
1540
    { 0x26, "l" },
1541

    
1542
    { 0x2c, "z" },
1543
    { 0x2d, "x" },
1544
    { 0x2e, "c" },
1545
    { 0x2f, "v" },
1546
    { 0x30, "b" },
1547
    { 0x31, "n" },
1548
    { 0x32, "m" },
1549
    { 0x33, "comma" },
1550
    { 0x34, "dot" },
1551
    { 0x35, "slash" },
1552

    
1553
    { 0x37, "asterisk" },
1554

    
1555
    { 0x39, "spc" },
1556
    { 0x3a, "caps_lock" },
1557
    { 0x3b, "f1" },
1558
    { 0x3c, "f2" },
1559
    { 0x3d, "f3" },
1560
    { 0x3e, "f4" },
1561
    { 0x3f, "f5" },
1562
    { 0x40, "f6" },
1563
    { 0x41, "f7" },
1564
    { 0x42, "f8" },
1565
    { 0x43, "f9" },
1566
    { 0x44, "f10" },
1567
    { 0x45, "num_lock" },
1568
    { 0x46, "scroll_lock" },
1569

    
1570
    { 0xb5, "kp_divide" },
1571
    { 0x37, "kp_multiply" },
1572
    { 0x4a, "kp_subtract" },
1573
    { 0x4e, "kp_add" },
1574
    { 0x9c, "kp_enter" },
1575
    { 0x53, "kp_decimal" },
1576
    { 0x54, "sysrq" },
1577

    
1578
    { 0x52, "kp_0" },
1579
    { 0x4f, "kp_1" },
1580
    { 0x50, "kp_2" },
1581
    { 0x51, "kp_3" },
1582
    { 0x4b, "kp_4" },
1583
    { 0x4c, "kp_5" },
1584
    { 0x4d, "kp_6" },
1585
    { 0x47, "kp_7" },
1586
    { 0x48, "kp_8" },
1587
    { 0x49, "kp_9" },
1588

    
1589
    { 0x56, "<" },
1590

    
1591
    { 0x57, "f11" },
1592
    { 0x58, "f12" },
1593

    
1594
    { 0xb7, "print" },
1595

    
1596
    { 0xc7, "home" },
1597
    { 0xc9, "pgup" },
1598
    { 0xd1, "pgdn" },
1599
    { 0xcf, "end" },
1600

    
1601
    { 0xcb, "left" },
1602
    { 0xc8, "up" },
1603
    { 0xd0, "down" },
1604
    { 0xcd, "right" },
1605

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

    
1628
static int get_keycode(const char *key)
1629
{
1630
    const KeyDef *p;
1631
    char *endp;
1632
    int ret;
1633

    
1634
    for(p = key_defs; p->name != NULL; p++) {
1635
        if (!strcmp(key, p->name))
1636
            return p->keycode;
1637
    }
1638
    if (strstart(key, "0x", NULL)) {
1639
        ret = strtoul(key, &endp, 0);
1640
        if (*endp == '\0' && ret >= 0x01 && ret <= 0xff)
1641
            return ret;
1642
    }
1643
    return -1;
1644
}
1645

    
1646
#define MAX_KEYCODES 16
1647
static uint8_t keycodes[MAX_KEYCODES];
1648
static int nb_pending_keycodes;
1649
static QEMUTimer *key_timer;
1650

    
1651
static void release_keys(void *opaque)
1652
{
1653
    int keycode;
1654

    
1655
    while (nb_pending_keycodes > 0) {
1656
        nb_pending_keycodes--;
1657
        keycode = keycodes[nb_pending_keycodes];
1658
        if (keycode & 0x80)
1659
            kbd_put_keycode(0xe0);
1660
        kbd_put_keycode(keycode | 0x80);
1661
    }
1662
}
1663

    
1664
static void do_sendkey(Monitor *mon, const QDict *qdict)
1665
{
1666
    char keyname_buf[16];
1667
    char *separator;
1668
    int keyname_len, keycode, i;
1669
    const char *string = qdict_get_str(qdict, "string");
1670
    int has_hold_time = qdict_haskey(qdict, "hold_time");
1671
    int hold_time = qdict_get_try_int(qdict, "hold_time", -1);
1672

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

    
1718
static int mouse_button_state;
1719

    
1720
static void do_mouse_move(Monitor *mon, const QDict *qdict)
1721
{
1722
    int dx, dy, dz;
1723
    const char *dx_str = qdict_get_str(qdict, "dx_str");
1724
    const char *dy_str = qdict_get_str(qdict, "dy_str");
1725
    const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1726
    dx = strtol(dx_str, NULL, 0);
1727
    dy = strtol(dy_str, NULL, 0);
1728
    dz = 0;
1729
    if (dz_str)
1730
        dz = strtol(dz_str, NULL, 0);
1731
    kbd_mouse_event(dx, dy, dz, mouse_button_state);
1732
}
1733

    
1734
static void do_mouse_button(Monitor *mon, const QDict *qdict)
1735
{
1736
    int button_state = qdict_get_int(qdict, "button_state");
1737
    mouse_button_state = button_state;
1738
    kbd_mouse_event(0, 0, 0, mouse_button_state);
1739
}
1740

    
1741
static void do_ioport_read(Monitor *mon, const QDict *qdict)
1742
{
1743
    int size = qdict_get_int(qdict, "size");
1744
    int addr = qdict_get_int(qdict, "addr");
1745
    int has_index = qdict_haskey(qdict, "index");
1746
    uint32_t val;
1747
    int suffix;
1748

    
1749
    if (has_index) {
1750
        int index = qdict_get_int(qdict, "index");
1751
        cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1752
        addr++;
1753
    }
1754
    addr &= 0xffff;
1755

    
1756
    switch(size) {
1757
    default:
1758
    case 1:
1759
        val = cpu_inb(addr);
1760
        suffix = 'b';
1761
        break;
1762
    case 2:
1763
        val = cpu_inw(addr);
1764
        suffix = 'w';
1765
        break;
1766
    case 4:
1767
        val = cpu_inl(addr);
1768
        suffix = 'l';
1769
        break;
1770
    }
1771
    monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1772
                   suffix, addr, size * 2, val);
1773
}
1774

    
1775
static void do_ioport_write(Monitor *mon, const QDict *qdict)
1776
{
1777
    int size = qdict_get_int(qdict, "size");
1778
    int addr = qdict_get_int(qdict, "addr");
1779
    int val = qdict_get_int(qdict, "val");
1780

    
1781
    addr &= IOPORTS_MASK;
1782

    
1783
    switch (size) {
1784
    default:
1785
    case 1:
1786
        cpu_outb(addr, val);
1787
        break;
1788
    case 2:
1789
        cpu_outw(addr, val);
1790
        break;
1791
    case 4:
1792
        cpu_outl(addr, val);
1793
        break;
1794
    }
1795
}
1796

    
1797
static void do_boot_set(Monitor *mon, const QDict *qdict)
1798
{
1799
    int res;
1800
    const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1801

    
1802
    res = qemu_boot_set(bootdevice);
1803
    if (res == 0) {
1804
        monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1805
    } else if (res > 0) {
1806
        monitor_printf(mon, "setting boot device list failed\n");
1807
    } else {
1808
        monitor_printf(mon, "no function defined to set boot device list for "
1809
                       "this architecture\n");
1810
    }
1811
}
1812

    
1813
/**
1814
 * do_system_reset(): Issue a machine reset
1815
 */
1816
static void do_system_reset(Monitor *mon, const QDict *qdict,
1817
                            QObject **ret_data)
1818
{
1819
    qemu_system_reset_request();
1820
}
1821

    
1822
/**
1823
 * do_system_powerdown(): Issue a machine powerdown
1824
 */
1825
static void do_system_powerdown(Monitor *mon, const QDict *qdict,
1826
                                QObject **ret_data)
1827
{
1828
    qemu_system_powerdown_request();
1829
}
1830

    
1831
#if defined(TARGET_I386)
1832
static void print_pte(Monitor *mon, uint32_t addr, uint32_t pte, uint32_t mask)
1833
{
1834
    monitor_printf(mon, "%08x: %08x %c%c%c%c%c%c%c%c\n",
1835
                   addr,
1836
                   pte & mask,
1837
                   pte & PG_GLOBAL_MASK ? 'G' : '-',
1838
                   pte & PG_PSE_MASK ? 'P' : '-',
1839
                   pte & PG_DIRTY_MASK ? 'D' : '-',
1840
                   pte & PG_ACCESSED_MASK ? 'A' : '-',
1841
                   pte & PG_PCD_MASK ? 'C' : '-',
1842
                   pte & PG_PWT_MASK ? 'T' : '-',
1843
                   pte & PG_USER_MASK ? 'U' : '-',
1844
                   pte & PG_RW_MASK ? 'W' : '-');
1845
}
1846

    
1847
static void tlb_info(Monitor *mon)
1848
{
1849
    CPUState *env;
1850
    int l1, l2;
1851
    uint32_t pgd, pde, pte;
1852

    
1853
    env = mon_get_cpu();
1854

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

    
1882
static void mem_print(Monitor *mon, uint32_t *pstart, int *plast_prot,
1883
                      uint32_t end, int prot)
1884
{
1885
    int prot1;
1886
    prot1 = *plast_prot;
1887
    if (prot != prot1) {
1888
        if (*pstart != -1) {
1889
            monitor_printf(mon, "%08x-%08x %08x %c%c%c\n",
1890
                           *pstart, end, end - *pstart,
1891
                           prot1 & PG_USER_MASK ? 'u' : '-',
1892
                           'r',
1893
                           prot1 & PG_RW_MASK ? 'w' : '-');
1894
        }
1895
        if (prot != 0)
1896
            *pstart = end;
1897
        else
1898
            *pstart = -1;
1899
        *plast_prot = prot;
1900
    }
1901
}
1902

    
1903
static void mem_info(Monitor *mon)
1904
{
1905
    CPUState *env;
1906
    int l1, l2, prot, last_prot;
1907
    uint32_t pgd, pde, pte, start, end;
1908

    
1909
    env = mon_get_cpu();
1910

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

    
1948
#if defined(TARGET_SH4)
1949

    
1950
static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1951
{
1952
    monitor_printf(mon, " tlb%i:\t"
1953
                   "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1954
                   "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1955
                   "dirty=%hhu writethrough=%hhu\n",
1956
                   idx,
1957
                   tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1958
                   tlb->v, tlb->sh, tlb->c, tlb->pr,
1959
                   tlb->d, tlb->wt);
1960
}
1961

    
1962
static void tlb_info(Monitor *mon)
1963
{
1964
    CPUState *env = mon_get_cpu();
1965
    int i;
1966

    
1967
    monitor_printf (mon, "ITLB:\n");
1968
    for (i = 0 ; i < ITLB_SIZE ; i++)
1969
        print_tlb (mon, i, &env->itlb[i]);
1970
    monitor_printf (mon, "UTLB:\n");
1971
    for (i = 0 ; i < UTLB_SIZE ; i++)
1972
        print_tlb (mon, i, &env->utlb[i]);
1973
}
1974

    
1975
#endif
1976

    
1977
static void do_info_kvm_print(Monitor *mon, const QObject *data)
1978
{
1979
    QDict *qdict;
1980

    
1981
    qdict = qobject_to_qdict(data);
1982

    
1983
    monitor_printf(mon, "kvm support: ");
1984
    if (qdict_get_bool(qdict, "present")) {
1985
        monitor_printf(mon, "%s\n", qdict_get_bool(qdict, "enabled") ?
1986
                                    "enabled" : "disabled");
1987
    } else {
1988
        monitor_printf(mon, "not compiled\n");
1989
    }
1990
}
1991

    
1992
/**
1993
 * do_info_kvm(): Show KVM information
1994
 *
1995
 * Return a QDict with the following information:
1996
 *
1997
 * - "enabled": true if KVM support is enabled, false otherwise
1998
 * - "present": true if QEMU has KVM support, false otherwise
1999
 *
2000
 * Example:
2001
 *
2002
 * { "enabled": true, "present": true }
2003
 */
2004
static void do_info_kvm(Monitor *mon, QObject **ret_data)
2005
{
2006
#ifdef CONFIG_KVM
2007
    *ret_data = qobject_from_jsonf("{ 'enabled': %i, 'present': true }",
2008
                                   kvm_enabled());
2009
#else
2010
    *ret_data = qobject_from_jsonf("{ 'enabled': false, 'present': false }");
2011
#endif
2012
}
2013

    
2014
static void do_info_numa(Monitor *mon)
2015
{
2016
    int i;
2017
    CPUState *env;
2018

    
2019
    monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
2020
    for (i = 0; i < nb_numa_nodes; i++) {
2021
        monitor_printf(mon, "node %d cpus:", i);
2022
        for (env = first_cpu; env != NULL; env = env->next_cpu) {
2023
            if (env->numa_node == i) {
2024
                monitor_printf(mon, " %d", env->cpu_index);
2025
            }
2026
        }
2027
        monitor_printf(mon, "\n");
2028
        monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
2029
            node_mem[i] >> 20);
2030
    }
2031
}
2032

    
2033
#ifdef CONFIG_PROFILER
2034

    
2035
int64_t qemu_time;
2036
int64_t dev_time;
2037

    
2038
static void do_info_profile(Monitor *mon)
2039
{
2040
    int64_t total;
2041
    total = qemu_time;
2042
    if (total == 0)
2043
        total = 1;
2044
    monitor_printf(mon, "async time  %" PRId64 " (%0.3f)\n",
2045
                   dev_time, dev_time / (double)get_ticks_per_sec());
2046
    monitor_printf(mon, "qemu time   %" PRId64 " (%0.3f)\n",
2047
                   qemu_time, qemu_time / (double)get_ticks_per_sec());
2048
    qemu_time = 0;
2049
    dev_time = 0;
2050
}
2051
#else
2052
static void do_info_profile(Monitor *mon)
2053
{
2054
    monitor_printf(mon, "Internal profiler not compiled\n");
2055
}
2056
#endif
2057

    
2058
/* Capture support */
2059
static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
2060

    
2061
static void do_info_capture(Monitor *mon)
2062
{
2063
    int i;
2064
    CaptureState *s;
2065

    
2066
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2067
        monitor_printf(mon, "[%d]: ", i);
2068
        s->ops.info (s->opaque);
2069
    }
2070
}
2071

    
2072
#ifdef HAS_AUDIO
2073
static void do_stop_capture(Monitor *mon, const QDict *qdict)
2074
{
2075
    int i;
2076
    int n = qdict_get_int(qdict, "n");
2077
    CaptureState *s;
2078

    
2079
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
2080
        if (i == n) {
2081
            s->ops.destroy (s->opaque);
2082
            QLIST_REMOVE (s, entries);
2083
            qemu_free (s);
2084
            return;
2085
        }
2086
    }
2087
}
2088

    
2089
static void do_wav_capture(Monitor *mon, const QDict *qdict)
2090
{
2091
    const char *path = qdict_get_str(qdict, "path");
2092
    int has_freq = qdict_haskey(qdict, "freq");
2093
    int freq = qdict_get_try_int(qdict, "freq", -1);
2094
    int has_bits = qdict_haskey(qdict, "bits");
2095
    int bits = qdict_get_try_int(qdict, "bits", -1);
2096
    int has_channels = qdict_haskey(qdict, "nchannels");
2097
    int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
2098
    CaptureState *s;
2099

    
2100
    s = qemu_mallocz (sizeof (*s));
2101

    
2102
    freq = has_freq ? freq : 44100;
2103
    bits = has_bits ? bits : 16;
2104
    nchannels = has_channels ? nchannels : 2;
2105

    
2106
    if (wav_start_capture (s, path, freq, bits, nchannels)) {
2107
        monitor_printf(mon, "Faied to add wave capture\n");
2108
        qemu_free (s);
2109
    }
2110
    QLIST_INSERT_HEAD (&capture_head, s, entries);
2111
}
2112
#endif
2113

    
2114
#if defined(TARGET_I386)
2115
static void do_inject_nmi(Monitor *mon, const QDict *qdict)
2116
{
2117
    CPUState *env;
2118
    int cpu_index = qdict_get_int(qdict, "cpu_index");
2119

    
2120
    for (env = first_cpu; env != NULL; env = env->next_cpu)
2121
        if (env->cpu_index == cpu_index) {
2122
            cpu_interrupt(env, CPU_INTERRUPT_NMI);
2123
            break;
2124
        }
2125
}
2126
#endif
2127

    
2128
static void do_info_status_print(Monitor *mon, const QObject *data)
2129
{
2130
    QDict *qdict;
2131

    
2132
    qdict = qobject_to_qdict(data);
2133

    
2134
    monitor_printf(mon, "VM status: ");
2135
    if (qdict_get_bool(qdict, "running")) {
2136
        monitor_printf(mon, "running");
2137
        if (qdict_get_bool(qdict, "singlestep")) {
2138
            monitor_printf(mon, " (single step mode)");
2139
        }
2140
    } else {
2141
        monitor_printf(mon, "paused");
2142
    }
2143

    
2144
    monitor_printf(mon, "\n");
2145
}
2146

    
2147
/**
2148
 * do_info_status(): VM status
2149
 *
2150
 * Return a QDict with the following information:
2151
 *
2152
 * - "running": true if the VM is running, or false if it is paused
2153
 * - "singlestep": true if the VM is in single step mode, false otherwise
2154
 *
2155
 * Example:
2156
 *
2157
 * { "running": true, "singlestep": false }
2158
 */
2159
static void do_info_status(Monitor *mon, QObject **ret_data)
2160
{
2161
    *ret_data = qobject_from_jsonf("{ 'running': %i, 'singlestep': %i }",
2162
                                    vm_running, singlestep);
2163
}
2164

    
2165
static void print_balloon_stat(const char *key, QObject *obj, void *opaque)
2166
{
2167
    Monitor *mon = opaque;
2168

    
2169
    if (strcmp(key, "actual"))
2170
        monitor_printf(mon, ",%s=%" PRId64, key,
2171
                       qint_get_int(qobject_to_qint(obj)));
2172
}
2173

    
2174
static void monitor_print_balloon(Monitor *mon, const QObject *data)
2175
{
2176
    QDict *qdict;
2177

    
2178
    qdict = qobject_to_qdict(data);
2179
    if (!qdict_haskey(qdict, "actual"))
2180
        return;
2181

    
2182
    monitor_printf(mon, "balloon: actual=%" PRId64,
2183
                   qdict_get_int(qdict, "actual") >> 20);
2184
    qdict_iter(qdict, print_balloon_stat, mon);
2185
    monitor_printf(mon, "\n");
2186
}
2187

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

    
2213
    if (kvm_enabled() && !kvm_has_sync_mmu()) {
2214
        qemu_error_new(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
2215
        return -1;
2216
    }
2217

    
2218
    ret = qemu_balloon_status(cb, opaque);
2219
    if (!ret) {
2220
        qemu_error_new(QERR_DEVICE_NOT_ACTIVE, "balloon");
2221
        return -1;
2222
    }
2223

    
2224
    return 0;
2225
}
2226

    
2227
/**
2228
 * do_balloon(): Request VM to change its memory allocation
2229
 */
2230
static int do_balloon(Monitor *mon, const QDict *params,
2231
                       MonitorCompletion cb, void *opaque)
2232
{
2233
    int ret;
2234

    
2235
    if (kvm_enabled() && !kvm_has_sync_mmu()) {
2236
        qemu_error_new(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");
2237
        return -1;
2238
    }
2239

    
2240
    ret = qemu_balloon(qdict_get_int(params, "value"), cb, opaque);
2241
    if (ret == 0) {
2242
        qemu_error_new(QERR_DEVICE_NOT_ACTIVE, "balloon");
2243
        return -1;
2244
    }
2245

    
2246
    return 0;
2247
}
2248

    
2249
static qemu_acl *find_acl(Monitor *mon, const char *name)
2250
{
2251
    qemu_acl *acl = qemu_acl_find(name);
2252

    
2253
    if (!acl) {
2254
        monitor_printf(mon, "acl: unknown list '%s'\n", name);
2255
    }
2256
    return acl;
2257
}
2258

    
2259
static void do_acl_show(Monitor *mon, const QDict *qdict)
2260
{
2261
    const char *aclname = qdict_get_str(qdict, "aclname");
2262
    qemu_acl *acl = find_acl(mon, aclname);
2263
    qemu_acl_entry *entry;
2264
    int i = 0;
2265

    
2266
    if (acl) {
2267
        monitor_printf(mon, "policy: %s\n",
2268
                       acl->defaultDeny ? "deny" : "allow");
2269
        QTAILQ_FOREACH(entry, &acl->entries, next) {
2270
            i++;
2271
            monitor_printf(mon, "%d: %s %s\n", i,
2272
                           entry->deny ? "deny" : "allow", entry->match);
2273
        }
2274
    }
2275
}
2276

    
2277
static void do_acl_reset(Monitor *mon, const QDict *qdict)
2278
{
2279
    const char *aclname = qdict_get_str(qdict, "aclname");
2280
    qemu_acl *acl = find_acl(mon, aclname);
2281

    
2282
    if (acl) {
2283
        qemu_acl_reset(acl);
2284
        monitor_printf(mon, "acl: removed all rules\n");
2285
    }
2286
}
2287

    
2288
static void do_acl_policy(Monitor *mon, const QDict *qdict)
2289
{
2290
    const char *aclname = qdict_get_str(qdict, "aclname");
2291
    const char *policy = qdict_get_str(qdict, "policy");
2292
    qemu_acl *acl = find_acl(mon, aclname);
2293

    
2294
    if (acl) {
2295
        if (strcmp(policy, "allow") == 0) {
2296
            acl->defaultDeny = 0;
2297
            monitor_printf(mon, "acl: policy set to 'allow'\n");
2298
        } else if (strcmp(policy, "deny") == 0) {
2299
            acl->defaultDeny = 1;
2300
            monitor_printf(mon, "acl: policy set to 'deny'\n");
2301
        } else {
2302
            monitor_printf(mon, "acl: unknown policy '%s', "
2303
                           "expected 'deny' or 'allow'\n", policy);
2304
        }
2305
    }
2306
}
2307

    
2308
static void do_acl_add(Monitor *mon, const QDict *qdict)
2309
{
2310
    const char *aclname = qdict_get_str(qdict, "aclname");
2311
    const char *match = qdict_get_str(qdict, "match");
2312
    const char *policy = qdict_get_str(qdict, "policy");
2313
    int has_index = qdict_haskey(qdict, "index");
2314
    int index = qdict_get_try_int(qdict, "index", -1);
2315
    qemu_acl *acl = find_acl(mon, aclname);
2316
    int deny, ret;
2317

    
2318
    if (acl) {
2319
        if (strcmp(policy, "allow") == 0) {
2320
            deny = 0;
2321
        } else if (strcmp(policy, "deny") == 0) {
2322
            deny = 1;
2323
        } else {
2324
            monitor_printf(mon, "acl: unknown policy '%s', "
2325
                           "expected 'deny' or 'allow'\n", policy);
2326
            return;
2327
        }
2328
        if (has_index)
2329
            ret = qemu_acl_insert(acl, deny, match, index);
2330
        else
2331
            ret = qemu_acl_append(acl, deny, match);
2332
        if (ret < 0)
2333
            monitor_printf(mon, "acl: unable to add acl entry\n");
2334
        else
2335
            monitor_printf(mon, "acl: added rule at position %d\n", ret);
2336
    }
2337
}
2338

    
2339
static void do_acl_remove(Monitor *mon, const QDict *qdict)
2340
{
2341
    const char *aclname = qdict_get_str(qdict, "aclname");
2342
    const char *match = qdict_get_str(qdict, "match");
2343
    qemu_acl *acl = find_acl(mon, aclname);
2344
    int ret;
2345

    
2346
    if (acl) {
2347
        ret = qemu_acl_remove(acl, match);
2348
        if (ret < 0)
2349
            monitor_printf(mon, "acl: no matching acl entry\n");
2350
        else
2351
            monitor_printf(mon, "acl: removed rule at position %d\n", ret);
2352
    }
2353
}
2354

    
2355
#if defined(TARGET_I386)
2356
static void do_inject_mce(Monitor *mon, const QDict *qdict)
2357
{
2358
    CPUState *cenv;
2359
    int cpu_index = qdict_get_int(qdict, "cpu_index");
2360
    int bank = qdict_get_int(qdict, "bank");
2361
    uint64_t status = qdict_get_int(qdict, "status");
2362
    uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
2363
    uint64_t addr = qdict_get_int(qdict, "addr");
2364
    uint64_t misc = qdict_get_int(qdict, "misc");
2365

    
2366
    for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu)
2367
        if (cenv->cpu_index == cpu_index && cenv->mcg_cap) {
2368
            cpu_inject_x86_mce(cenv, bank, status, mcg_status, addr, misc);
2369
            break;
2370
        }
2371
}
2372
#endif
2373

    
2374
static void do_getfd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2375
{
2376
    const char *fdname = qdict_get_str(qdict, "fdname");
2377
    mon_fd_t *monfd;
2378
    int fd;
2379

    
2380
    fd = qemu_chr_get_msgfd(mon->chr);
2381
    if (fd == -1) {
2382
        qemu_error_new(QERR_FD_NOT_SUPPLIED);
2383
        return;
2384
    }
2385

    
2386
    if (qemu_isdigit(fdname[0])) {
2387
        qemu_error_new(QERR_INVALID_PARAMETER, "fdname");
2388
        return;
2389
    }
2390

    
2391
    fd = dup(fd);
2392
    if (fd == -1) {
2393
        if (errno == EMFILE)
2394
            qemu_error_new(QERR_TOO_MANY_FILES);
2395
        else
2396
            qemu_error_new(QERR_UNDEFINED_ERROR);
2397
        return;
2398
    }
2399

    
2400
    QLIST_FOREACH(monfd, &mon->fds, next) {
2401
        if (strcmp(monfd->name, fdname) != 0) {
2402
            continue;
2403
        }
2404

    
2405
        close(monfd->fd);
2406
        monfd->fd = fd;
2407
        return;
2408
    }
2409

    
2410
    monfd = qemu_mallocz(sizeof(mon_fd_t));
2411
    monfd->name = qemu_strdup(fdname);
2412
    monfd->fd = fd;
2413

    
2414
    QLIST_INSERT_HEAD(&mon->fds, monfd, next);
2415
}
2416

    
2417
static void do_closefd(Monitor *mon, const QDict *qdict, QObject **ret_data)
2418
{
2419
    const char *fdname = qdict_get_str(qdict, "fdname");
2420
    mon_fd_t *monfd;
2421

    
2422
    QLIST_FOREACH(monfd, &mon->fds, next) {
2423
        if (strcmp(monfd->name, fdname) != 0) {
2424
            continue;
2425
        }
2426

    
2427
        QLIST_REMOVE(monfd, next);
2428
        close(monfd->fd);
2429
        qemu_free(monfd->name);
2430
        qemu_free(monfd);
2431
        return;
2432
    }
2433

    
2434
    qemu_error_new(QERR_FD_NOT_FOUND, fdname);
2435
}
2436

    
2437
static void do_loadvm(Monitor *mon, const QDict *qdict)
2438
{
2439
    int saved_vm_running  = vm_running;
2440
    const char *name = qdict_get_str(qdict, "name");
2441

    
2442
    vm_stop(0);
2443

    
2444
    if (load_vmstate(mon, name) >= 0 && saved_vm_running)
2445
        vm_start();
2446
}
2447

    
2448
int monitor_get_fd(Monitor *mon, const char *fdname)
2449
{
2450
    mon_fd_t *monfd;
2451

    
2452
    QLIST_FOREACH(monfd, &mon->fds, next) {
2453
        int fd;
2454

    
2455
        if (strcmp(monfd->name, fdname) != 0) {
2456
            continue;
2457
        }
2458

    
2459
        fd = monfd->fd;
2460

    
2461
        /* caller takes ownership of fd */
2462
        QLIST_REMOVE(monfd, next);
2463
        qemu_free(monfd->name);
2464
        qemu_free(monfd);
2465

    
2466
        return fd;
2467
    }
2468

    
2469
    return -1;
2470
}
2471

    
2472
static const mon_cmd_t mon_cmds[] = {
2473
#include "qemu-monitor.h"
2474
    { NULL, NULL, },
2475
};
2476

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

    
2761
/*******************************************************************/
2762

    
2763
static const char *pch;
2764
static jmp_buf expr_env;
2765

    
2766
#define MD_TLONG 0
2767
#define MD_I32   1
2768

    
2769
typedef struct MonitorDef {
2770
    const char *name;
2771
    int offset;
2772
    target_long (*get_value)(const struct MonitorDef *md, int val);
2773
    int type;
2774
} MonitorDef;
2775

    
2776
#if defined(TARGET_I386)
2777
static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2778
{
2779
    CPUState *env = mon_get_cpu();
2780
    return env->eip + env->segs[R_CS].base;
2781
}
2782
#endif
2783

    
2784
#if defined(TARGET_PPC)
2785
static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2786
{
2787
    CPUState *env = mon_get_cpu();
2788
    unsigned int u;
2789
    int i;
2790

    
2791
    u = 0;
2792
    for (i = 0; i < 8; i++)
2793
        u |= env->crf[i] << (32 - (4 * i));
2794

    
2795
    return u;
2796
}
2797

    
2798
static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2799
{
2800
    CPUState *env = mon_get_cpu();
2801
    return env->msr;
2802
}
2803

    
2804
static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2805
{
2806
    CPUState *env = mon_get_cpu();
2807
    return env->xer;
2808
}
2809

    
2810
static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2811
{
2812
    CPUState *env = mon_get_cpu();
2813
    return cpu_ppc_load_decr(env);
2814
}
2815

    
2816
static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2817
{
2818
    CPUState *env = mon_get_cpu();
2819
    return cpu_ppc_load_tbu(env);
2820
}
2821

    
2822
static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2823
{
2824
    CPUState *env = mon_get_cpu();
2825
    return cpu_ppc_load_tbl(env);
2826
}
2827
#endif
2828

    
2829
#if defined(TARGET_SPARC)
2830
#ifndef TARGET_SPARC64
2831
static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2832
{
2833
    CPUState *env = mon_get_cpu();
2834
    return GET_PSR(env);
2835
}
2836
#endif
2837

    
2838
static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2839
{
2840
    CPUState *env = mon_get_cpu();
2841
    return env->regwptr[val];
2842
}
2843
#endif
2844

    
2845
static const MonitorDef monitor_defs[] = {
2846
#ifdef TARGET_I386
2847

    
2848
#define SEG(name, seg) \
2849
    { name, offsetof(CPUState, segs[seg].selector), NULL, MD_I32 },\
2850
    { name ".base", offsetof(CPUState, segs[seg].base) },\
2851
    { name ".limit", offsetof(CPUState, segs[seg].limit), NULL, MD_I32 },
2852

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

    
3086
static void expr_error(Monitor *mon, const char *msg)
3087
{
3088
    monitor_printf(mon, "%s\n", msg);
3089
    longjmp(expr_env, 1);
3090
}
3091

    
3092
/* return 0 if OK, -1 if not found */
3093
static int get_monitor_def(target_long *pval, const char *name)
3094
{
3095
    const MonitorDef *md;
3096
    void *ptr;
3097

    
3098
    for(md = monitor_defs; md->name != NULL; md++) {
3099
        if (compare_cmd(name, md->name)) {
3100
            if (md->get_value) {
3101
                *pval = md->get_value(md, md->offset);
3102
            } else {
3103
                CPUState *env = mon_get_cpu();
3104
                ptr = (uint8_t *)env + md->offset;
3105
                switch(md->type) {
3106
                case MD_I32:
3107
                    *pval = *(int32_t *)ptr;
3108
                    break;
3109
                case MD_TLONG:
3110
                    *pval = *(target_long *)ptr;
3111
                    break;
3112
                default:
3113
                    *pval = 0;
3114
                    break;
3115
                }
3116
            }
3117
            return 0;
3118
        }
3119
    }
3120
    return -1;
3121
}
3122

    
3123
static void next(void)
3124
{
3125
    if (*pch != '\0') {
3126
        pch++;
3127
        while (qemu_isspace(*pch))
3128
            pch++;
3129
    }
3130
}
3131

    
3132
static int64_t expr_sum(Monitor *mon);
3133

    
3134
static int64_t expr_unary(Monitor *mon)
3135
{
3136
    int64_t n;
3137
    char *p;
3138
    int ret;
3139

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

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

    
3216

    
3217
static int64_t expr_prod(Monitor *mon)
3218
{
3219
    int64_t val, val2;
3220
    int op;
3221

    
3222
    val = expr_unary(mon);
3223
    for(;;) {
3224
        op = *pch;
3225
        if (op != '*' && op != '/' && op != '%')
3226
            break;
3227
        next();
3228
        val2 = expr_unary(mon);
3229
        switch(op) {
3230
        default:
3231
        case '*':
3232
            val *= val2;
3233
            break;
3234
        case '/':
3235
        case '%':
3236
            if (val2 == 0)
3237
                expr_error(mon, "division by zero");
3238
            if (op == '/')
3239
                val /= val2;
3240
            else
3241
                val %= val2;
3242
            break;
3243
        }
3244
    }
3245
    return val;
3246
}
3247

    
3248
static int64_t expr_logic(Monitor *mon)
3249
{
3250
    int64_t val, val2;
3251
    int op;
3252

    
3253
    val = expr_prod(mon);
3254
    for(;;) {
3255
        op = *pch;
3256
        if (op != '&' && op != '|' && op != '^')
3257
            break;
3258
        next();
3259
        val2 = expr_prod(mon);
3260
        switch(op) {
3261
        default:
3262
        case '&':
3263
            val &= val2;
3264
            break;
3265
        case '|':
3266
            val |= val2;
3267
            break;
3268
        case '^':
3269
            val ^= val2;
3270
            break;
3271
        }
3272
    }
3273
    return val;
3274
}
3275

    
3276
static int64_t expr_sum(Monitor *mon)
3277
{
3278
    int64_t val, val2;
3279
    int op;
3280

    
3281
    val = expr_logic(mon);
3282
    for(;;) {
3283
        op = *pch;
3284
        if (op != '+' && op != '-')
3285
            break;
3286
        next();
3287
        val2 = expr_logic(mon);
3288
        if (op == '+')
3289
            val += val2;
3290
        else
3291
            val -= val2;
3292
    }
3293
    return val;
3294
}
3295

    
3296
static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
3297
{
3298
    pch = *pp;
3299
    if (setjmp(expr_env)) {
3300
        *pp = pch;
3301
        return -1;
3302
    }
3303
    while (qemu_isspace(*pch))
3304
        pch++;
3305
    *pval = expr_sum(mon);
3306
    *pp = pch;
3307
    return 0;
3308
}
3309

    
3310
static int get_double(Monitor *mon, double *pval, const char **pp)
3311
{
3312
    const char *p = *pp;
3313
    char *tailp;
3314
    double d;
3315

    
3316
    d = strtod(p, &tailp);
3317
    if (tailp == p) {
3318
        monitor_printf(mon, "Number expected\n");
3319
        return -1;
3320
    }
3321
    if (d != d || d - d != 0) {
3322
        /* NaN or infinity */
3323
        monitor_printf(mon, "Bad number\n");
3324
        return -1;
3325
    }
3326
    *pval = d;
3327
    *pp = tailp;
3328
    return 0;
3329
}
3330

    
3331
static int get_str(char *buf, int buf_size, const char **pp)
3332
{
3333
    const char *p;
3334
    char *q;
3335
    int c;
3336

    
3337
    q = buf;
3338
    p = *pp;
3339
    while (qemu_isspace(*p))
3340
        p++;
3341
    if (*p == '\0') {
3342
    fail:
3343
        *q = '\0';
3344
        *pp = p;
3345
        return -1;
3346
    }
3347
    if (*p == '\"') {
3348
        p++;
3349
        while (*p != '\0' && *p != '\"') {
3350
            if (*p == '\\') {
3351
                p++;
3352
                c = *p++;
3353
                switch(c) {
3354
                case 'n':
3355
                    c = '\n';
3356
                    break;
3357
                case 'r':
3358
                    c = '\r';
3359
                    break;
3360
                case '\\':
3361
                case '\'':
3362
                case '\"':
3363
                    break;
3364
                default:
3365
                    qemu_printf("unsupported escape code: '\\%c'\n", c);
3366
                    goto fail;
3367
                }
3368
                if ((q - buf) < buf_size - 1) {
3369
                    *q++ = c;
3370
                }
3371
            } else {
3372
                if ((q - buf) < buf_size - 1) {
3373
                    *q++ = *p;
3374
                }
3375
                p++;
3376
            }
3377
        }
3378
        if (*p != '\"') {
3379
            qemu_printf("unterminated string\n");
3380
            goto fail;
3381
        }
3382
        p++;
3383
    } else {
3384
        while (*p != '\0' && !qemu_isspace(*p)) {
3385
            if ((q - buf) < buf_size - 1) {
3386
                *q++ = *p;
3387
            }
3388
            p++;
3389
        }
3390
    }
3391
    *q = '\0';
3392
    *pp = p;
3393
    return 0;
3394
}
3395

    
3396
/*
3397
 * Store the command-name in cmdname, and return a pointer to
3398
 * the remaining of the command string.
3399
 */
3400
static const char *get_command_name(const char *cmdline,
3401
                                    char *cmdname, size_t nlen)
3402
{
3403
    size_t len;
3404
    const char *p, *pstart;
3405

    
3406
    p = cmdline;
3407
    while (qemu_isspace(*p))
3408
        p++;
3409
    if (*p == '\0')
3410
        return NULL;
3411
    pstart = p;
3412
    while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
3413
        p++;
3414
    len = p - pstart;
3415
    if (len > nlen - 1)
3416
        len = nlen - 1;
3417
    memcpy(cmdname, pstart, len);
3418
    cmdname[len] = '\0';
3419
    return p;
3420
}
3421

    
3422
/**
3423
 * Read key of 'type' into 'key' and return the current
3424
 * 'type' pointer.
3425
 */
3426
static char *key_get_info(const char *type, char **key)
3427
{
3428
    size_t len;
3429
    char *p, *str;
3430

    
3431
    if (*type == ',')
3432
        type++;
3433

    
3434
    p = strchr(type, ':');
3435
    if (!p) {
3436
        *key = NULL;
3437
        return NULL;
3438
    }
3439
    len = p - type;
3440

    
3441
    str = qemu_malloc(len + 1);
3442
    memcpy(str, type, len);
3443
    str[len] = '\0';
3444

    
3445
    *key = str;
3446
    return ++p;
3447
}
3448

    
3449
static int default_fmt_format = 'x';
3450
static int default_fmt_size = 4;
3451

    
3452
#define MAX_ARGS 16
3453

    
3454
static int is_valid_option(const char *c, const char *typestr)
3455
{
3456
    char option[3];
3457
  
3458
    option[0] = '-';
3459
    option[1] = *c;
3460
    option[2] = '\0';
3461
  
3462
    typestr = strstr(typestr, option);
3463
    return (typestr != NULL);
3464
}
3465

    
3466
static const mon_cmd_t *monitor_find_command(const char *cmdname)
3467
{
3468
    const mon_cmd_t *cmd;
3469

    
3470
    for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
3471
        if (compare_cmd(cmdname, cmd->name)) {
3472
            return cmd;
3473
        }
3474
    }
3475

    
3476
    return NULL;
3477
}
3478

    
3479
static const mon_cmd_t *monitor_parse_command(Monitor *mon,
3480
                                              const char *cmdline,
3481
                                              QDict *qdict)
3482
{
3483
    const char *p, *typestr;
3484
    int c;
3485
    const mon_cmd_t *cmd;
3486
    char cmdname[256];
3487
    char buf[1024];
3488
    char *key;
3489

    
3490
#ifdef DEBUG
3491
    monitor_printf(mon, "command='%s'\n", cmdline);
3492
#endif
3493

    
3494
    /* extract the command name */
3495
    p = get_command_name(cmdline, cmdname, sizeof(cmdname));
3496
    if (!p)
3497
        return NULL;
3498

    
3499
    cmd = monitor_find_command(cmdname);
3500
    if (!cmd) {
3501
        monitor_printf(mon, "unknown command: '%s'\n", cmdname);
3502
        return NULL;
3503
    }
3504

    
3505
    /* parse the parameters */
3506
    typestr = cmd->args_type;
3507
    for(;;) {
3508
        typestr = key_get_info(typestr, &key);
3509
        if (!typestr)
3510
            break;
3511
        c = *typestr;
3512
        typestr++;
3513
        switch(c) {
3514
        case 'F':
3515
        case 'B':
3516
        case 's':
3517
            {
3518
                int ret;
3519

    
3520
                while (qemu_isspace(*p))
3521
                    p++;
3522
                if (*typestr == '?') {
3523
                    typestr++;
3524
                    if (*p == '\0') {
3525
                        /* no optional string: NULL argument */
3526
                        break;
3527
                    }
3528
                }
3529
                ret = get_str(buf, sizeof(buf), &p);
3530
                if (ret < 0) {
3531
                    switch(c) {
3532
                    case 'F':
3533
                        monitor_printf(mon, "%s: filename expected\n",
3534
                                       cmdname);
3535
                        break;
3536
                    case 'B':
3537
                        monitor_printf(mon, "%s: block device name expected\n",
3538
                                       cmdname);
3539
                        break;
3540
                    default:
3541
                        monitor_printf(mon, "%s: string expected\n", cmdname);
3542
                        break;
3543
                    }
3544
                    goto fail;
3545
                }
3546
                qdict_put(qdict, key, qstring_from_str(buf));
3547
            }
3548
            break;
3549
        case '/':
3550
            {
3551
                int count, format, size;
3552

    
3553
                while (qemu_isspace(*p))
3554
                    p++;
3555
                if (*p == '/') {
3556
                    /* format found */
3557
                    p++;
3558
                    count = 1;
3559
                    if (qemu_isdigit(*p)) {
3560
                        count = 0;
3561
                        while (qemu_isdigit(*p)) {
3562
                            count = count * 10 + (*p - '0');
3563
                            p++;
3564
                        }
3565
                    }
3566
                    size = -1;
3567
                    format = -1;
3568
                    for(;;) {
3569
                        switch(*p) {
3570
                        case 'o':
3571
                        case 'd':
3572
                        case 'u':
3573
                        case 'x':
3574
                        case 'i':
3575
                        case 'c':
3576
                            format = *p++;
3577
                            break;
3578
                        case 'b':
3579
                            size = 1;
3580
                            p++;
3581
                            break;
3582
                        case 'h':
3583
                            size = 2;
3584
                            p++;
3585
                            break;
3586
                        case 'w':
3587
                            size = 4;
3588
                            p++;
3589
                            break;
3590
                        case 'g':
3591
                        case 'L':
3592
                            size = 8;
3593
                            p++;
3594
                            break;
3595
                        default:
3596
                            goto next;
3597
                        }
3598
                    }
3599
                next:
3600
                    if (*p != '\0' && !qemu_isspace(*p)) {
3601
                        monitor_printf(mon, "invalid char in format: '%c'\n",
3602
                                       *p);
3603
                        goto fail;
3604
                    }
3605
                    if (format < 0)
3606
                        format = default_fmt_format;
3607
                    if (format != 'i') {
3608
                        /* for 'i', not specifying a size gives -1 as size */
3609
                        if (size < 0)
3610
                            size = default_fmt_size;
3611
                        default_fmt_size = size;
3612
                    }
3613
                    default_fmt_format = format;
3614
                } else {
3615
                    count = 1;
3616
                    format = default_fmt_format;
3617
                    if (format != 'i') {
3618
                        size = default_fmt_size;
3619
                    } else {
3620
                        size = -1;
3621
                    }
3622
                }
3623
                qdict_put(qdict, "count", qint_from_int(count));
3624
                qdict_put(qdict, "format", qint_from_int(format));
3625
                qdict_put(qdict, "size", qint_from_int(size));
3626
            }
3627
            break;
3628
        case 'i':
3629
        case 'l':
3630
        case 'M':
3631
            {
3632
                int64_t val;
3633

    
3634
                while (qemu_isspace(*p))
3635
                    p++;
3636
                if (*typestr == '?' || *typestr == '.') {
3637
                    if (*typestr == '?') {
3638
                        if (*p == '\0') {
3639
                            typestr++;
3640
                            break;
3641
                        }
3642
                    } else {
3643
                        if (*p == '.') {
3644
                            p++;
3645
                            while (qemu_isspace(*p))
3646
                                p++;
3647
                        } else {
3648
                            typestr++;
3649
                            break;
3650
                        }
3651
                    }
3652
                    typestr++;
3653
                }
3654
                if (get_expr(mon, &val, &p))
3655
                    goto fail;
3656
                /* Check if 'i' is greater than 32-bit */
3657
                if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
3658
                    monitor_printf(mon, "\'%s\' has failed: ", cmdname);
3659
                    monitor_printf(mon, "integer is for 32-bit values\n");
3660
                    goto fail;
3661
                } else if (c == 'M') {
3662
                    val <<= 20;
3663
                }
3664
                qdict_put(qdict, key, qint_from_int(val));
3665
            }
3666
            break;
3667
        case 'b':
3668
        case 'T':
3669
            {
3670
                double val;
3671

    
3672
                while (qemu_isspace(*p))
3673
                    p++;
3674
                if (*typestr == '?') {
3675
                    typestr++;
3676
                    if (*p == '\0') {
3677
                        break;
3678
                    }
3679
                }
3680
                if (get_double(mon, &val, &p) < 0) {
3681
                    goto fail;
3682
                }
3683
                if (c == 'b' && *p) {
3684
                    switch (*p) {
3685
                    case 'K': case 'k':
3686
                        val *= 1 << 10; p++; break;
3687
                    case 'M': case 'm':
3688
                        val *= 1 << 20; p++; break;
3689
                    case 'G': case 'g':
3690
                        val *= 1 << 30; p++; break;
3691
                    }
3692
                }
3693
                if (c == 'T' && p[0] && p[1] == 's') {
3694
                    switch (*p) {
3695
                    case 'm':
3696
                        val /= 1e3; p += 2; break;
3697
                    case 'u':
3698
                        val /= 1e6; p += 2; break;
3699
                    case 'n':
3700
                        val /= 1e9; p += 2; break;
3701
                    }
3702
                }
3703
                if (*p && !qemu_isspace(*p)) {
3704
                    monitor_printf(mon, "Unknown unit suffix\n");
3705
                    goto fail;
3706
                }
3707
                qdict_put(qdict, key, qfloat_from_double(val));
3708
            }
3709
            break;
3710
        case '-':
3711
            {
3712
                const char *tmp = p;
3713
                int has_option, skip_key = 0;
3714
                /* option */
3715

    
3716
                c = *typestr++;
3717
                if (c == '\0')
3718
                    goto bad_type;
3719
                while (qemu_isspace(*p))
3720
                    p++;
3721
                has_option = 0;
3722
                if (*p == '-') {
3723
                    p++;
3724
                    if(c != *p) {
3725
                        if(!is_valid_option(p, typestr)) {
3726
                  
3727
                            monitor_printf(mon, "%s: unsupported option -%c\n",
3728
                                           cmdname, *p);
3729
                            goto fail;
3730
                        } else {
3731
                            skip_key = 1;
3732
                        }
3733
                    }
3734
                    if(skip_key) {
3735
                        p = tmp;
3736
                    } else {
3737
                        p++;
3738
                        has_option = 1;
3739
                    }
3740
                }
3741
                qdict_put(qdict, key, qint_from_int(has_option));
3742
            }
3743
            break;
3744
        default:
3745
        bad_type:
3746
            monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
3747
            goto fail;
3748
        }
3749
        qemu_free(key);
3750
        key = NULL;
3751
    }
3752
    /* check that all arguments were parsed */
3753
    while (qemu_isspace(*p))
3754
        p++;
3755
    if (*p != '\0') {
3756
        monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3757
                       cmdname);
3758
        goto fail;
3759
    }
3760

    
3761
    return cmd;
3762

    
3763
fail:
3764
    qemu_free(key);
3765
    return NULL;
3766
}
3767

    
3768
static void monitor_print_error(Monitor *mon)
3769
{
3770
    qerror_print(mon->error);
3771
    QDECREF(mon->error);
3772
    mon->error = NULL;
3773
}
3774

    
3775
static int is_async_return(const QObject *data)
3776
{
3777
    if (data && qobject_type(data) == QTYPE_QDICT) {
3778
        return qdict_haskey(qobject_to_qdict(data), "__mon_async");
3779
    }
3780

    
3781
    return 0;
3782
}
3783

    
3784
static void monitor_call_handler(Monitor *mon, const mon_cmd_t *cmd,
3785
                                 const QDict *params)
3786
{
3787
    QObject *data = NULL;
3788

    
3789
    cmd->mhandler.cmd_new(mon, params, &data);
3790

    
3791
    if (is_async_return(data)) {
3792
        /*
3793
         * Asynchronous commands have no initial return data but they can
3794
         * generate errors.  Data is returned via the async completion handler.
3795
         */
3796
        if (monitor_ctrl_mode(mon) && monitor_has_error(mon)) {
3797
            monitor_protocol_emitter(mon, NULL);
3798
        }
3799
    } else if (monitor_ctrl_mode(mon)) {
3800
        /* Monitor Protocol */
3801
        monitor_protocol_emitter(mon, data);
3802
    } else {
3803
        /* User Protocol */
3804
         if (data)
3805
            cmd->user_print(mon, data);
3806
    }
3807

    
3808
    qobject_decref(data);
3809
}
3810

    
3811
static void handle_user_command(Monitor *mon, const char *cmdline)
3812
{
3813
    QDict *qdict;
3814
    const mon_cmd_t *cmd;
3815

    
3816
    qdict = qdict_new();
3817

    
3818
    cmd = monitor_parse_command(mon, cmdline, qdict);
3819
    if (!cmd)
3820
        goto out;
3821

    
3822
    qemu_errors_to_mon(mon);
3823

    
3824
    if (monitor_handler_is_async(cmd)) {
3825
        user_async_cmd_handler(mon, cmd, qdict);
3826
    } else if (monitor_handler_ported(cmd)) {
3827
        monitor_call_handler(mon, cmd, qdict);
3828
    } else {
3829
        cmd->mhandler.cmd(mon, qdict);
3830
    }
3831

    
3832
    if (monitor_has_error(mon))
3833
        monitor_print_error(mon);
3834

    
3835
    qemu_errors_to_previous();
3836

    
3837
out:
3838
    QDECREF(qdict);
3839
}
3840

    
3841
static void cmd_completion(const char *name, const char *list)
3842
{
3843
    const char *p, *pstart;
3844
    char cmd[128];
3845
    int len;
3846

    
3847
    p = list;
3848
    for(;;) {
3849
        pstart = p;
3850
        p = strchr(p, '|');
3851
        if (!p)
3852
            p = pstart + strlen(pstart);
3853
        len = p - pstart;
3854
        if (len > sizeof(cmd) - 2)
3855
            len = sizeof(cmd) - 2;
3856
        memcpy(cmd, pstart, len);
3857
        cmd[len] = '\0';
3858
        if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3859
            readline_add_completion(cur_mon->rs, cmd);
3860
        }
3861
        if (*p == '\0')
3862
            break;
3863
        p++;
3864
    }
3865
}
3866

    
3867
static void file_completion(const char *input)
3868
{
3869
    DIR *ffs;
3870
    struct dirent *d;
3871
    char path[1024];
3872
    char file[1024], file_prefix[1024];
3873
    int input_path_len;
3874
    const char *p;
3875

    
3876
    p = strrchr(input, '/');
3877
    if (!p) {
3878
        input_path_len = 0;
3879
        pstrcpy(file_prefix, sizeof(file_prefix), input);
3880
        pstrcpy(path, sizeof(path), ".");
3881
    } else {
3882
        input_path_len = p - input + 1;
3883
        memcpy(path, input, input_path_len);
3884
        if (input_path_len > sizeof(path) - 1)
3885
            input_path_len = sizeof(path) - 1;
3886
        path[input_path_len] = '\0';
3887
        pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3888
    }
3889
#ifdef DEBUG_COMPLETION
3890
    monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
3891
                   input, path, file_prefix);
3892
#endif
3893
    ffs = opendir(path);
3894
    if (!ffs)
3895
        return;
3896
    for(;;) {
3897
        struct stat sb;
3898
        d = readdir(ffs);
3899
        if (!d)
3900
            break;
3901
        if (strstart(d->d_name, file_prefix, NULL)) {
3902
            memcpy(file, input, input_path_len);
3903
            if (input_path_len < sizeof(file))
3904
                pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3905
                        d->d_name);
3906
            /* stat the file to find out if it's a directory.
3907
             * In that case add a slash to speed up typing long paths
3908
             */
3909
            stat(file, &sb);
3910
            if(S_ISDIR(sb.st_mode))
3911
                pstrcat(file, sizeof(file), "/");
3912
            readline_add_completion(cur_mon->rs, file);
3913
        }
3914
    }
3915
    closedir(ffs);
3916
}
3917

    
3918
static void block_completion_it(void *opaque, BlockDriverState *bs)
3919
{
3920
    const char *name = bdrv_get_device_name(bs);
3921
    const char *input = opaque;
3922

    
3923
    if (input[0] == '\0' ||
3924
        !strncmp(name, (char *)input, strlen(input))) {
3925
        readline_add_completion(cur_mon->rs, name);
3926
    }
3927
}
3928

    
3929
/* NOTE: this parser is an approximate form of the real command parser */
3930
static void parse_cmdline(const char *cmdline,
3931
                         int *pnb_args, char **args)
3932
{
3933
    const char *p;
3934
    int nb_args, ret;
3935
    char buf[1024];
3936

    
3937
    p = cmdline;
3938
    nb_args = 0;
3939
    for(;;) {
3940
        while (qemu_isspace(*p))
3941
            p++;
3942
        if (*p == '\0')
3943
            break;
3944
        if (nb_args >= MAX_ARGS)
3945
            break;
3946
        ret = get_str(buf, sizeof(buf), &p);
3947
        args[nb_args] = qemu_strdup(buf);
3948
        nb_args++;
3949
        if (ret < 0)
3950
            break;
3951
    }
3952
    *pnb_args = nb_args;
3953
}
3954

    
3955
static const char *next_arg_type(const char *typestr)
3956
{
3957
    const char *p = strchr(typestr, ':');
3958
    return (p != NULL ? ++p : typestr);
3959
}
3960

    
3961
static void monitor_find_completion(const char *cmdline)
3962
{
3963
    const char *cmdname;
3964
    char *args[MAX_ARGS];
3965
    int nb_args, i, len;
3966
    const char *ptype, *str;
3967
    const mon_cmd_t *cmd;
3968
    const KeyDef *key;
3969

    
3970
    parse_cmdline(cmdline, &nb_args, args);
3971
#ifdef DEBUG_COMPLETION
3972
    for(i = 0; i < nb_args; i++) {
3973
        monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
3974
    }
3975
#endif
3976

    
3977
    /* if the line ends with a space, it means we want to complete the
3978
       next arg */
3979
    len = strlen(cmdline);
3980
    if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3981
        if (nb_args >= MAX_ARGS)
3982
            return;
3983
        args[nb_args++] = qemu_strdup("");
3984
    }
3985
    if (nb_args <= 1) {
3986
        /* command completion */
3987
        if (nb_args == 0)
3988
            cmdname = "";
3989
        else
3990
            cmdname = args[0];
3991
        readline_set_completion_index(cur_mon->rs, strlen(cmdname));
3992
        for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
3993
            cmd_completion(cmdname, cmd->name);
3994
        }
3995
    } else {
3996
        /* find the command */
3997
        for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
3998
            if (compare_cmd(args[0], cmd->name))
3999
                goto found;
4000
        }
4001
        return;
4002
    found:
4003
        ptype = next_arg_type(cmd->args_type);
4004
        for(i = 0; i < nb_args - 2; i++) {
4005
            if (*ptype != '\0') {
4006
                ptype = next_arg_type(ptype);
4007
                while (*ptype == '?')
4008
                    ptype = next_arg_type(ptype);
4009
            }
4010
        }
4011
        str = args[nb_args - 1];
4012
        if (*ptype == '-' && ptype[1] != '\0') {
4013
            ptype += 2;
4014
        }
4015
        switch(*ptype) {
4016
        case 'F':
4017
            /* file completion */
4018
            readline_set_completion_index(cur_mon->rs, strlen(str));
4019
            file_completion(str);
4020
            break;
4021
        case 'B':
4022
            /* block device name completion */
4023
            readline_set_completion_index(cur_mon->rs, strlen(str));
4024
            bdrv_iterate(block_completion_it, (void *)str);
4025
            break;
4026
        case 's':
4027
            /* XXX: more generic ? */
4028
            if (!strcmp(cmd->name, "info")) {
4029
                readline_set_completion_index(cur_mon->rs, strlen(str));
4030
                for(cmd = info_cmds; cmd->name != NULL; cmd++) {
4031
                    cmd_completion(str, cmd->name);
4032
                }
4033
            } else if (!strcmp(cmd->name, "sendkey")) {
4034
                char *sep = strrchr(str, '-');
4035
                if (sep)
4036
                    str = sep + 1;
4037
                readline_set_completion_index(cur_mon->rs, strlen(str));
4038
                for(key = key_defs; key->name != NULL; key++) {
4039
                    cmd_completion(str, key->name);
4040
                }
4041
            } else if (!strcmp(cmd->name, "help|?")) {
4042
                readline_set_completion_index(cur_mon->rs, strlen(str));
4043
                for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
4044
                    cmd_completion(str, cmd->name);
4045
                }
4046
            }
4047
            break;
4048
        default:
4049
            break;
4050
        }
4051
    }
4052
    for(i = 0; i < nb_args; i++)
4053
        qemu_free(args[i]);
4054
}
4055

    
4056
static int monitor_can_read(void *opaque)
4057
{
4058
    Monitor *mon = opaque;
4059

    
4060
    return (mon->suspend_cnt == 0) ? 1 : 0;
4061
}
4062

    
4063
typedef struct CmdArgs {
4064
    QString *name;
4065
    int type;
4066
    int flag;
4067
    int optional;
4068
} CmdArgs;
4069

    
4070
static int check_opt(const CmdArgs *cmd_args, const char *name, QDict *args)
4071
{
4072
    if (!cmd_args->optional) {
4073
        qemu_error_new(QERR_MISSING_PARAMETER, name);
4074
        return -1;
4075
    }
4076

    
4077
    if (cmd_args->type == '-') {
4078
        /* handlers expect a value, they need to be changed */
4079
        qdict_put(args, name, qint_from_int(0));
4080
    }
4081

    
4082
    return 0;
4083
}
4084

    
4085
static int check_arg(const CmdArgs *cmd_args, QDict *args)
4086
{
4087
    QObject *value;
4088
    const char *name;
4089

    
4090
    name = qstring_get_str(cmd_args->name);
4091

    
4092
    if (!args) {
4093
        return check_opt(cmd_args, name, args);
4094
    }
4095

    
4096
    value = qdict_get(args, name);
4097
    if (!value) {
4098
        return check_opt(cmd_args, name, args);
4099
    }
4100

    
4101
    switch (cmd_args->type) {
4102
        case 'F':
4103
        case 'B':
4104
        case 's':
4105
            if (qobject_type(value) != QTYPE_QSTRING) {
4106
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "string");
4107
                return -1;
4108
            }
4109
            break;
4110
        case '/': {
4111
            int i;
4112
            const char *keys[] = { "count", "format", "size", NULL };
4113

    
4114
            for (i = 0; keys[i]; i++) {
4115
                QObject *obj = qdict_get(args, keys[i]);
4116
                if (!obj) {
4117
                    qemu_error_new(QERR_MISSING_PARAMETER, name);
4118
                    return -1;
4119
                }
4120
                if (qobject_type(obj) != QTYPE_QINT) {
4121
                    qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "int");
4122
                    return -1;
4123
                }
4124
            }
4125
            break;
4126
        }
4127
        case 'i':
4128
        case 'l':
4129
        case 'M':
4130
            if (qobject_type(value) != QTYPE_QINT) {
4131
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "int");
4132
                return -1;
4133
            }
4134
            break;
4135
        case 'b':
4136
        case 'T':
4137
            if (qobject_type(value) != QTYPE_QINT && qobject_type(value) != QTYPE_QFLOAT) {
4138
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "number");
4139
                return -1;
4140
            }
4141
            break;
4142
        case '-':
4143
            if (qobject_type(value) != QTYPE_QINT &&
4144
                qobject_type(value) != QTYPE_QBOOL) {
4145
                qemu_error_new(QERR_INVALID_PARAMETER_TYPE, name, "bool");
4146
                return -1;
4147
            }
4148
            if (qobject_type(value) == QTYPE_QBOOL) {
4149
                /* handlers expect a QInt, they need to be changed */
4150
                qdict_put(args, name,
4151
                         qint_from_int(qbool_get_int(qobject_to_qbool(value))));
4152
            }
4153
            break;
4154
        default:
4155
            /* impossible */
4156
            abort();
4157
    }
4158

    
4159
    return 0;
4160
}
4161

    
4162
static void cmd_args_init(CmdArgs *cmd_args)
4163
{
4164
    cmd_args->name = qstring_new();
4165
    cmd_args->type = cmd_args->flag = cmd_args->optional = 0;
4166
}
4167

    
4168
/*
4169
 * This is not trivial, we have to parse Monitor command's argument
4170
 * type syntax to be able to check the arguments provided by clients.
4171
 *
4172
 * In the near future we will be using an array for that and will be
4173
 * able to drop all this parsing...
4174
 */
4175
static int monitor_check_qmp_args(const mon_cmd_t *cmd, QDict *args)
4176
{
4177
    int err;
4178
    const char *p;
4179
    CmdArgs cmd_args;
4180

    
4181
    if (cmd->args_type == NULL) {
4182
        return (qdict_size(args) == 0 ? 0 : -1);
4183
    }
4184

    
4185
    err = 0;
4186
    cmd_args_init(&cmd_args);
4187

    
4188
    for (p = cmd->args_type;; p++) {
4189
        if (*p == ':') {
4190
            cmd_args.type = *++p;
4191
            p++;
4192
            if (cmd_args.type == '-') {
4193
                cmd_args.flag = *p++;
4194
                cmd_args.optional = 1;
4195
            } else if (*p == '?') {
4196
                cmd_args.optional = 1;
4197
                p++;
4198
            }
4199

    
4200
            assert(*p == ',' || *p == '\0');
4201
            err = check_arg(&cmd_args, args);
4202

    
4203
            QDECREF(cmd_args.name);
4204
            cmd_args_init(&cmd_args);
4205

    
4206
            if (err < 0) {
4207
                break;
4208
            }
4209
        } else {
4210
            qstring_append_chr(cmd_args.name, *p);
4211
        }
4212

    
4213
        if (*p == '\0') {
4214
            break;
4215
        }
4216
    }
4217

    
4218
    QDECREF(cmd_args.name);
4219
    return err;
4220
}
4221

    
4222
static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)
4223
{
4224
    int err;
4225
    QObject *obj;
4226
    QDict *input, *args;
4227
    const mon_cmd_t *cmd;
4228
    Monitor *mon = cur_mon;
4229
    const char *cmd_name, *info_item;
4230

    
4231
    args = NULL;
4232
    qemu_errors_to_mon(mon);
4233

    
4234
    obj = json_parser_parse(tokens, NULL);
4235
    if (!obj) {
4236
        // FIXME: should be triggered in json_parser_parse()
4237
        qemu_error_new(QERR_JSON_PARSING);
4238
        goto err_out;
4239
    } else if (qobject_type(obj) != QTYPE_QDICT) {
4240
        qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "object");
4241
        qobject_decref(obj);
4242
        goto err_out;
4243
    }
4244

    
4245
    input = qobject_to_qdict(obj);
4246

    
4247
    mon->mc->id = qdict_get(input, "id");
4248
    qobject_incref(mon->mc->id);
4249

    
4250
    obj = qdict_get(input, "execute");
4251
    if (!obj) {
4252
        qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "execute");
4253
        goto err_input;
4254
    } else if (qobject_type(obj) != QTYPE_QSTRING) {
4255
        qemu_error_new(QERR_QMP_BAD_INPUT_OBJECT, "string");
4256
        goto err_input;
4257
    }
4258

    
4259
    cmd_name = qstring_get_str(qobject_to_qstring(obj));
4260

    
4261
    /*
4262
     * XXX: We need this special case until we get info handlers
4263
     * converted into 'query-' commands
4264
     */
4265
    if (compare_cmd(cmd_name, "info")) {
4266
        qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4267
        goto err_input;
4268
    } else if (strstart(cmd_name, "query-", &info_item)) {
4269
        cmd = monitor_find_command("info");
4270
        qdict_put_obj(input, "arguments",
4271
                      qobject_from_jsonf("{ 'item': %s }", info_item));
4272
    } else {
4273
        cmd = monitor_find_command(cmd_name);
4274
        if (!cmd || !monitor_handler_ported(cmd)) {
4275
            qemu_error_new(QERR_COMMAND_NOT_FOUND, cmd_name);
4276
            goto err_input;
4277
        }
4278
    }
4279

    
4280
    obj = qdict_get(input, "arguments");
4281
    if (!obj) {
4282
        args = qdict_new();
4283
    } else {
4284
        args = qobject_to_qdict(obj);
4285
        QINCREF(args);
4286
    }
4287

    
4288
    QDECREF(input);
4289

    
4290
    err = monitor_check_qmp_args(cmd, args);
4291
    if (err < 0) {
4292
        goto err_out;
4293
    }
4294

    
4295
    if (monitor_handler_is_async(cmd)) {
4296
        qmp_async_cmd_handler(mon, cmd, args);
4297
    } else {
4298
        monitor_call_handler(mon, cmd, args);
4299
    }
4300
    goto out;
4301

    
4302
err_input:
4303
    QDECREF(input);
4304
err_out:
4305
    monitor_protocol_emitter(mon, NULL);
4306
out:
4307
    QDECREF(args);
4308
    qemu_errors_to_previous();
4309
}
4310

    
4311
/**
4312
 * monitor_control_read(): Read and handle QMP input
4313
 */
4314
static void monitor_control_read(void *opaque, const uint8_t *buf, int size)
4315
{
4316
    Monitor *old_mon = cur_mon;
4317

    
4318
    cur_mon = opaque;
4319

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

    
4322
    cur_mon = old_mon;
4323
}
4324

    
4325
static void monitor_read(void *opaque, const uint8_t *buf, int size)
4326
{
4327
    Monitor *old_mon = cur_mon;
4328
    int i;
4329

    
4330
    cur_mon = opaque;
4331

    
4332
    if (cur_mon->rs) {
4333
        for (i = 0; i < size; i++)
4334
            readline_handle_byte(cur_mon->rs, buf[i]);
4335
    } else {
4336
        if (size == 0 || buf[size - 1] != 0)
4337
            monitor_printf(cur_mon, "corrupted command\n");
4338
        else
4339
            handle_user_command(cur_mon, (char *)buf);
4340
    }
4341

    
4342
    cur_mon = old_mon;
4343
}
4344

    
4345
static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
4346
{
4347
    monitor_suspend(mon);
4348
    handle_user_command(mon, cmdline);
4349
    monitor_resume(mon);
4350
}
4351

    
4352
int monitor_suspend(Monitor *mon)
4353
{
4354
    if (!mon->rs)
4355
        return -ENOTTY;
4356
    mon->suspend_cnt++;
4357
    return 0;
4358
}
4359

    
4360
void monitor_resume(Monitor *mon)
4361
{
4362
    if (!mon->rs)
4363
        return;
4364
    if (--mon->suspend_cnt == 0)
4365
        readline_show_prompt(mon->rs);
4366
}
4367

    
4368
/**
4369
 * monitor_control_event(): Print QMP gretting
4370
 */
4371
static void monitor_control_event(void *opaque, int event)
4372
{
4373
    if (event == CHR_EVENT_OPENED) {
4374
        QObject *data;
4375
        Monitor *mon = opaque;
4376

    
4377
        json_message_parser_init(&mon->mc->parser, handle_qmp_command);
4378

    
4379
        data = qobject_from_jsonf("{ 'QMP': { 'capabilities': [] } }");
4380
        assert(data != NULL);
4381

    
4382
        monitor_json_emitter(mon, data);
4383
        qobject_decref(data);
4384
    }
4385
}
4386

    
4387
static void monitor_event(void *opaque, int event)
4388
{
4389
    Monitor *mon = opaque;
4390

    
4391
    switch (event) {
4392
    case CHR_EVENT_MUX_IN:
4393
        mon->mux_out = 0;
4394
        if (mon->reset_seen) {
4395
            readline_restart(mon->rs);
4396
            monitor_resume(mon);
4397
            monitor_flush(mon);
4398
        } else {
4399
            mon->suspend_cnt = 0;
4400
        }
4401
        break;
4402

    
4403
    case CHR_EVENT_MUX_OUT:
4404
        if (mon->reset_seen) {
4405
            if (mon->suspend_cnt == 0) {
4406
                monitor_printf(mon, "\n");
4407
            }
4408
            monitor_flush(mon);
4409
            monitor_suspend(mon);
4410
        } else {
4411
            mon->suspend_cnt++;
4412
        }
4413
        mon->mux_out = 1;
4414
        break;
4415

    
4416
    case CHR_EVENT_OPENED:
4417
        monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
4418
                       "information\n", QEMU_VERSION);
4419
        if (!mon->mux_out) {
4420
            readline_show_prompt(mon->rs);
4421
        }
4422
        mon->reset_seen = 1;
4423
        break;
4424
    }
4425
}
4426

    
4427

    
4428
/*
4429
 * Local variables:
4430
 *  c-indent-level: 4
4431
 *  c-basic-offset: 4
4432
 *  tab-width: 8
4433
 * End:
4434
 */
4435

    
4436
void monitor_init(CharDriverState *chr, int flags)
4437
{
4438
    static int is_first_init = 1;
4439
    Monitor *mon;
4440

    
4441
    if (is_first_init) {
4442
        key_timer = qemu_new_timer(vm_clock, release_keys, NULL);
4443
        is_first_init = 0;
4444
    }
4445

    
4446
    mon = qemu_mallocz(sizeof(*mon));
4447

    
4448
    mon->chr = chr;
4449
    mon->flags = flags;
4450
    if (flags & MONITOR_USE_READLINE) {
4451
        mon->rs = readline_init(mon, monitor_find_completion);
4452
        monitor_read_command(mon, 0);
4453
    }
4454

    
4455
    if (monitor_ctrl_mode(mon)) {
4456
        mon->mc = qemu_mallocz(sizeof(MonitorControl));
4457
        /* Control mode requires special handlers */
4458
        qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
4459
                              monitor_control_event, mon);
4460
    } else {
4461
        qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
4462
                              monitor_event, mon);
4463
    }
4464

    
4465
    QLIST_INSERT_HEAD(&mon_list, mon, entry);
4466
    if (!cur_mon || (flags & MONITOR_IS_DEFAULT))
4467
        cur_mon = mon;
4468
}
4469

    
4470
static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
4471
{
4472
    BlockDriverState *bs = opaque;
4473
    int ret = 0;
4474

    
4475
    if (bdrv_set_key(bs, password) != 0) {
4476
        monitor_printf(mon, "invalid password\n");
4477
        ret = -EPERM;
4478
    }
4479
    if (mon->password_completion_cb)
4480
        mon->password_completion_cb(mon->password_opaque, ret);
4481

    
4482
    monitor_read_command(mon, 1);
4483
}
4484

    
4485
void monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
4486
                                 BlockDriverCompletionFunc *completion_cb,
4487
                                 void *opaque)
4488
{
4489
    int err;
4490

    
4491
    if (!bdrv_key_required(bs)) {
4492
        if (completion_cb)
4493
            completion_cb(opaque, 0);
4494
        return;
4495
    }
4496

    
4497
    if (monitor_ctrl_mode(mon)) {
4498
        qemu_error_new(QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs));
4499
        return;
4500
    }
4501

    
4502
    monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
4503
                   bdrv_get_encrypted_filename(bs));
4504

    
4505
    mon->password_completion_cb = completion_cb;
4506
    mon->password_opaque = opaque;
4507

    
4508
    err = monitor_read_password(mon, bdrv_password_cb, bs);
4509

    
4510
    if (err && completion_cb)
4511
        completion_cb(opaque, err);
4512
}
4513

    
4514
typedef struct QemuErrorSink QemuErrorSink;
4515
struct QemuErrorSink {
4516
    enum {
4517
        ERR_SINK_FILE,
4518
        ERR_SINK_MONITOR,
4519
    } dest;
4520
    union {
4521
        FILE    *fp;
4522
        Monitor *mon;
4523
    };
4524
    QemuErrorSink *previous;
4525
};
4526

    
4527
static QemuErrorSink *qemu_error_sink;
4528

    
4529
void qemu_errors_to_file(FILE *fp)
4530
{
4531
    QemuErrorSink *sink;
4532

    
4533
    sink = qemu_mallocz(sizeof(*sink));
4534
    sink->dest = ERR_SINK_FILE;
4535
    sink->fp = fp;
4536
    sink->previous = qemu_error_sink;
4537
    qemu_error_sink = sink;
4538
}
4539

    
4540
void qemu_errors_to_mon(Monitor *mon)
4541
{
4542
    QemuErrorSink *sink;
4543

    
4544
    sink = qemu_mallocz(sizeof(*sink));
4545
    sink->dest = ERR_SINK_MONITOR;
4546
    sink->mon = mon;
4547
    sink->previous = qemu_error_sink;
4548
    qemu_error_sink = sink;
4549
}
4550

    
4551
void qemu_errors_to_previous(void)
4552
{
4553
    QemuErrorSink *sink;
4554

    
4555
    assert(qemu_error_sink != NULL);
4556
    sink = qemu_error_sink;
4557
    qemu_error_sink = sink->previous;
4558
    qemu_free(sink);
4559
}
4560

    
4561
void qemu_error(const char *fmt, ...)
4562
{
4563
    va_list args;
4564

    
4565
    assert(qemu_error_sink != NULL);
4566
    switch (qemu_error_sink->dest) {
4567
    case ERR_SINK_FILE:
4568
        va_start(args, fmt);
4569
        vfprintf(qemu_error_sink->fp, fmt, args);
4570
        va_end(args);
4571
        break;
4572
    case ERR_SINK_MONITOR:
4573
        va_start(args, fmt);
4574
        monitor_vprintf(qemu_error_sink->mon, fmt, args);
4575
        va_end(args);
4576
        break;
4577
    }
4578
}
4579

    
4580
void qemu_error_internal(const char *file, int linenr, const char *func,
4581
                         const char *fmt, ...)
4582
{
4583
    va_list va;
4584
    QError *qerror;
4585

    
4586
    assert(qemu_error_sink != NULL);
4587

    
4588
    va_start(va, fmt);
4589
    qerror = qerror_from_info(file, linenr, func, fmt, &va);
4590
    va_end(va);
4591

    
4592
    switch (qemu_error_sink->dest) {
4593
    case ERR_SINK_FILE:
4594
        qerror_print(qerror);
4595
        QDECREF(qerror);
4596
        break;
4597
    case ERR_SINK_MONITOR:
4598
        assert(qemu_error_sink->mon->error == NULL);
4599
        qemu_error_sink->mon->error = qerror;
4600
        break;
4601
    }
4602
}