Statistics
| Branch: | Revision:

root / monitor.c @ 83fb1de2

History | View | Annotate | Download (92.1 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 "qemu-char.h"
36
#include "sysemu.h"
37
#include "monitor.h"
38
#include "readline.h"
39
#include "console.h"
40
#include "block.h"
41
#include "audio/audio.h"
42
#include "disas.h"
43
#include "balloon.h"
44
#include "qemu-timer.h"
45
#include "migration.h"
46
#include "kvm.h"
47
#include "acl.h"
48
#include "qint.h"
49
#include "qdict.h"
50
#include "qstring.h"
51

    
52
//#define DEBUG
53
//#define DEBUG_COMPLETION
54

    
55
/*
56
 * Supported types:
57
 *
58
 * 'F'          filename
59
 * 'B'          block device name
60
 * 's'          string (accept optional quote)
61
 * 'i'          32 bit integer
62
 * 'l'          target long (32 or 64 bit)
63
 * '/'          optional gdb-like print format (like "/10x")
64
 *
65
 * '?'          optional type (for all types, except '/')
66
 * '.'          other form of optional type (for 'i' and 'l')
67
 * '-'          optional parameter (eg. '-f')
68
 *
69
 */
70

    
71
typedef struct mon_cmd_t {
72
    const char *name;
73
    const char *args_type;
74
    const char *params;
75
    const char *help;
76
    void (*user_print)(Monitor *mon, const QObject *data);
77
    union {
78
        void (*info)(Monitor *mon);
79
        void (*info_new)(Monitor *mon, QObject **ret_data);
80
        void (*cmd)(Monitor *mon, const QDict *qdict);
81
        void (*cmd_new)(Monitor *mon, const QDict *params, QObject **ret_data);
82
    } mhandler;
83
} mon_cmd_t;
84

    
85
/* file descriptors passed via SCM_RIGHTS */
86
typedef struct mon_fd_t mon_fd_t;
87
struct mon_fd_t {
88
    char *name;
89
    int fd;
90
    QLIST_ENTRY(mon_fd_t) next;
91
};
92

    
93
struct Monitor {
94
    CharDriverState *chr;
95
    int mux_out;
96
    int reset_seen;
97
    int flags;
98
    int suspend_cnt;
99
    uint8_t outbuf[1024];
100
    int outbuf_index;
101
    ReadLineState *rs;
102
    CPUState *mon_cpu;
103
    BlockDriverCompletionFunc *password_completion_cb;
104
    void *password_opaque;
105
    QLIST_HEAD(,mon_fd_t) fds;
106
    QLIST_ENTRY(Monitor) entry;
107
};
108

    
109
static QLIST_HEAD(mon_list, Monitor) mon_list;
110

    
111
static const mon_cmd_t mon_cmds[];
112
static const mon_cmd_t info_cmds[];
113

    
114
Monitor *cur_mon = NULL;
115

    
116
static void monitor_command_cb(Monitor *mon, const char *cmdline,
117
                               void *opaque);
118

    
119
static void monitor_read_command(Monitor *mon, int show_prompt)
120
{
121
    readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);
122
    if (show_prompt)
123
        readline_show_prompt(mon->rs);
124
}
125

    
126
static int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,
127
                                 void *opaque)
128
{
129
    if (mon->rs) {
130
        readline_start(mon->rs, "Password: ", 1, readline_func, opaque);
131
        /* prompt is printed on return from the command handler */
132
        return 0;
133
    } else {
134
        monitor_printf(mon, "terminal does not support password prompting\n");
135
        return -ENOTTY;
136
    }
137
}
138

    
139
void monitor_flush(Monitor *mon)
140
{
141
    if (mon && mon->outbuf_index != 0 && !mon->mux_out) {
142
        qemu_chr_write(mon->chr, mon->outbuf, mon->outbuf_index);
143
        mon->outbuf_index = 0;
144
    }
145
}
146

    
147
/* flush at every end of line or if the buffer is full */
148
static void monitor_puts(Monitor *mon, const char *str)
149
{
150
    char c;
151

    
152
    if (!mon)
153
        return;
154

    
155
    for(;;) {
156
        c = *str++;
157
        if (c == '\0')
158
            break;
159
        if (c == '\n')
160
            mon->outbuf[mon->outbuf_index++] = '\r';
161
        mon->outbuf[mon->outbuf_index++] = c;
162
        if (mon->outbuf_index >= (sizeof(mon->outbuf) - 1)
163
            || c == '\n')
164
            monitor_flush(mon);
165
    }
166
}
167

    
168
void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
169
{
170
    char buf[4096];
171
    vsnprintf(buf, sizeof(buf), fmt, ap);
172
    monitor_puts(mon, buf);
173
}
174

    
175
void monitor_printf(Monitor *mon, const char *fmt, ...)
176
{
177
    va_list ap;
178
    va_start(ap, fmt);
179
    monitor_vprintf(mon, fmt, ap);
180
    va_end(ap);
181
}
182

    
183
void monitor_print_filename(Monitor *mon, const char *filename)
184
{
185
    int i;
186

    
187
    for (i = 0; filename[i]; i++) {
188
        switch (filename[i]) {
189
        case ' ':
190
        case '"':
191
        case '\\':
192
            monitor_printf(mon, "\\%c", filename[i]);
193
            break;
194
        case '\t':
195
            monitor_printf(mon, "\\t");
196
            break;
197
        case '\r':
198
            monitor_printf(mon, "\\r");
199
            break;
200
        case '\n':
201
            monitor_printf(mon, "\\n");
202
            break;
203
        default:
204
            monitor_printf(mon, "%c", filename[i]);
205
            break;
206
        }
207
    }
208
}
209

    
210
static int monitor_fprintf(FILE *stream, const char *fmt, ...)
211
{
212
    va_list ap;
213
    va_start(ap, fmt);
214
    monitor_vprintf((Monitor *)stream, fmt, ap);
215
    va_end(ap);
216
    return 0;
217
}
218

    
219
static void monitor_user_noop(Monitor *mon, const QObject *data) { }
220

    
221
static inline int monitor_handler_ported(const mon_cmd_t *cmd)
222
{
223
    return cmd->user_print != NULL;
224
}
225

    
226
static int compare_cmd(const char *name, const char *list)
227
{
228
    const char *p, *pstart;
229
    int len;
230
    len = strlen(name);
231
    p = list;
232
    for(;;) {
233
        pstart = p;
234
        p = strchr(p, '|');
235
        if (!p)
236
            p = pstart + strlen(pstart);
237
        if ((p - pstart) == len && !memcmp(pstart, name, len))
238
            return 1;
239
        if (*p == '\0')
240
            break;
241
        p++;
242
    }
243
    return 0;
244
}
245

    
246
static void help_cmd_dump(Monitor *mon, const mon_cmd_t *cmds,
247
                          const char *prefix, const char *name)
248
{
249
    const mon_cmd_t *cmd;
250

    
251
    for(cmd = cmds; cmd->name != NULL; cmd++) {
252
        if (!name || !strcmp(name, cmd->name))
253
            monitor_printf(mon, "%s%s %s -- %s\n", prefix, cmd->name,
254
                           cmd->params, cmd->help);
255
    }
256
}
257

    
258
static void help_cmd(Monitor *mon, const char *name)
259
{
260
    if (name && !strcmp(name, "info")) {
261
        help_cmd_dump(mon, info_cmds, "info ", NULL);
262
    } else {
263
        help_cmd_dump(mon, mon_cmds, "", name);
264
        if (name && !strcmp(name, "log")) {
265
            const CPULogItem *item;
266
            monitor_printf(mon, "Log items (comma separated):\n");
267
            monitor_printf(mon, "%-10s %s\n", "none", "remove all logs");
268
            for(item = cpu_log_items; item->mask != 0; item++) {
269
                monitor_printf(mon, "%-10s %s\n", item->name, item->help);
270
            }
271
        }
272
    }
273
}
274

    
275
static void do_help_cmd(Monitor *mon, const QDict *qdict)
276
{
277
    help_cmd(mon, qdict_get_try_str(qdict, "name"));
278
}
279

    
280
static void do_commit(Monitor *mon, const QDict *qdict)
281
{
282
    int all_devices;
283
    DriveInfo *dinfo;
284
    const char *device = qdict_get_str(qdict, "device");
285

    
286
    all_devices = !strcmp(device, "all");
287
    QTAILQ_FOREACH(dinfo, &drives, next) {
288
        if (!all_devices)
289
            if (strcmp(bdrv_get_device_name(dinfo->bdrv), device))
290
                continue;
291
        bdrv_commit(dinfo->bdrv);
292
    }
293
}
294

    
295
static void do_info(Monitor *mon, const QDict *qdict, QObject **ret_data)
296
{
297
    const mon_cmd_t *cmd;
298
    const char *item = qdict_get_try_str(qdict, "item");
299

    
300
    if (!item)
301
        goto help;
302

    
303
    for (cmd = info_cmds; cmd->name != NULL; cmd++) {
304
        if (compare_cmd(item, cmd->name))
305
            break;
306
    }
307

    
308
    if (cmd->name == NULL)
309
        goto help;
310

    
311
    if (monitor_handler_ported(cmd)) {
312
        cmd->mhandler.info_new(mon, ret_data);
313
        if (*ret_data)
314
            cmd->user_print(mon, *ret_data);
315
    } else {
316
        cmd->mhandler.info(mon);
317
    }
318

    
319
    return;
320

    
321
help:
322
    help_cmd(mon, "info");
323
}
324

    
325
static void do_info_version(Monitor *mon)
326
{
327
    monitor_printf(mon, "%s\n", QEMU_VERSION QEMU_PKGVERSION);
328
}
329

    
330
static void do_info_name(Monitor *mon)
331
{
332
    if (qemu_name)
333
        monitor_printf(mon, "%s\n", qemu_name);
334
}
335

    
336
#if defined(TARGET_I386)
337
static void do_info_hpet(Monitor *mon)
338
{
339
    monitor_printf(mon, "HPET is %s by QEMU\n",
340
                   (no_hpet) ? "disabled" : "enabled");
341
}
342
#endif
343

    
344
static void do_info_uuid(Monitor *mon)
345
{
346
    monitor_printf(mon, UUID_FMT "\n", qemu_uuid[0], qemu_uuid[1],
347
                   qemu_uuid[2], qemu_uuid[3], qemu_uuid[4], qemu_uuid[5],
348
                   qemu_uuid[6], qemu_uuid[7], qemu_uuid[8], qemu_uuid[9],
349
                   qemu_uuid[10], qemu_uuid[11], qemu_uuid[12], qemu_uuid[13],
350
                   qemu_uuid[14], qemu_uuid[15]);
351
}
352

    
353
/* get the current CPU defined by the user */
354
static int mon_set_cpu(int cpu_index)
355
{
356
    CPUState *env;
357

    
358
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
359
        if (env->cpu_index == cpu_index) {
360
            cur_mon->mon_cpu = env;
361
            return 0;
362
        }
363
    }
364
    return -1;
365
}
366

    
367
static CPUState *mon_get_cpu(void)
368
{
369
    if (!cur_mon->mon_cpu) {
370
        mon_set_cpu(0);
371
    }
372
    cpu_synchronize_state(cur_mon->mon_cpu);
373
    return cur_mon->mon_cpu;
374
}
375

    
376
static void do_info_registers(Monitor *mon)
377
{
378
    CPUState *env;
379
    env = mon_get_cpu();
380
    if (!env)
381
        return;
382
#ifdef TARGET_I386
383
    cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
384
                   X86_DUMP_FPU);
385
#else
386
    cpu_dump_state(env, (FILE *)mon, monitor_fprintf,
387
                   0);
388
#endif
389
}
390

    
391
static void do_info_cpus(Monitor *mon)
392
{
393
    CPUState *env;
394

    
395
    /* just to set the default cpu if not already done */
396
    mon_get_cpu();
397

    
398
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
399
        cpu_synchronize_state(env);
400
        monitor_printf(mon, "%c CPU #%d:",
401
                       (env == mon->mon_cpu) ? '*' : ' ',
402
                       env->cpu_index);
403
#if defined(TARGET_I386)
404
        monitor_printf(mon, " pc=0x" TARGET_FMT_lx,
405
                       env->eip + env->segs[R_CS].base);
406
#elif defined(TARGET_PPC)
407
        monitor_printf(mon, " nip=0x" TARGET_FMT_lx, env->nip);
408
#elif defined(TARGET_SPARC)
409
        monitor_printf(mon, " pc=0x" TARGET_FMT_lx " npc=0x" TARGET_FMT_lx,
410
                       env->pc, env->npc);
411
#elif defined(TARGET_MIPS)
412
        monitor_printf(mon, " PC=0x" TARGET_FMT_lx, env->active_tc.PC);
413
#endif
414
        if (env->halted)
415
            monitor_printf(mon, " (halted)");
416
        monitor_printf(mon, "\n");
417
    }
418
}
419

    
420
static void do_cpu_set(Monitor *mon, const QDict *qdict)
421
{
422
    int index = qdict_get_int(qdict, "index");
423
    if (mon_set_cpu(index) < 0)
424
        monitor_printf(mon, "Invalid CPU index\n");
425
}
426

    
427
static void do_info_jit(Monitor *mon)
428
{
429
    dump_exec_info((FILE *)mon, monitor_fprintf);
430
}
431

    
432
static void do_info_history(Monitor *mon)
433
{
434
    int i;
435
    const char *str;
436

    
437
    if (!mon->rs)
438
        return;
439
    i = 0;
440
    for(;;) {
441
        str = readline_get_history(mon->rs, i);
442
        if (!str)
443
            break;
444
        monitor_printf(mon, "%d: '%s'\n", i, str);
445
        i++;
446
    }
447
}
448

    
449
#if defined(TARGET_PPC)
450
/* XXX: not implemented in other targets */
451
static void do_info_cpu_stats(Monitor *mon)
452
{
453
    CPUState *env;
454

    
455
    env = mon_get_cpu();
456
    cpu_dump_statistics(env, (FILE *)mon, &monitor_fprintf, 0);
457
}
458
#endif
459

    
460
/**
461
 * do_quit(): Quit QEMU execution
462
 */
463
static void do_quit(Monitor *mon, const QDict *qdict, QObject **ret_data)
464
{
465
    exit(0);
466
}
467

    
468
static int eject_device(Monitor *mon, BlockDriverState *bs, int force)
469
{
470
    if (bdrv_is_inserted(bs)) {
471
        if (!force) {
472
            if (!bdrv_is_removable(bs)) {
473
                monitor_printf(mon, "device is not removable\n");
474
                return -1;
475
            }
476
            if (bdrv_is_locked(bs)) {
477
                monitor_printf(mon, "device is locked\n");
478
                return -1;
479
            }
480
        }
481
        bdrv_close(bs);
482
    }
483
    return 0;
484
}
485

    
486
static void do_eject(Monitor *mon, const QDict *qdict)
487
{
488
    BlockDriverState *bs;
489
    int force = qdict_get_int(qdict, "force");
490
    const char *filename = qdict_get_str(qdict, "filename");
491

    
492
    bs = bdrv_find(filename);
493
    if (!bs) {
494
        monitor_printf(mon, "device not found\n");
495
        return;
496
    }
497
    eject_device(mon, bs, force);
498
}
499

    
500
static void do_change_block(Monitor *mon, const char *device,
501
                            const char *filename, const char *fmt)
502
{
503
    BlockDriverState *bs;
504
    BlockDriver *drv = NULL;
505

    
506
    bs = bdrv_find(device);
507
    if (!bs) {
508
        monitor_printf(mon, "device not found\n");
509
        return;
510
    }
511
    if (fmt) {
512
        drv = bdrv_find_format(fmt);
513
        if (!drv) {
514
            monitor_printf(mon, "invalid format %s\n", fmt);
515
            return;
516
        }
517
    }
518
    if (eject_device(mon, bs, 0) < 0)
519
        return;
520
    bdrv_open2(bs, filename, 0, drv);
521
    monitor_read_bdrv_key_start(mon, bs, NULL, NULL);
522
}
523

    
524
static void change_vnc_password_cb(Monitor *mon, const char *password,
525
                                   void *opaque)
526
{
527
    if (vnc_display_password(NULL, password) < 0)
528
        monitor_printf(mon, "could not set VNC server password\n");
529

    
530
    monitor_read_command(mon, 1);
531
}
532

    
533
static void do_change_vnc(Monitor *mon, const char *target, const char *arg)
534
{
535
    if (strcmp(target, "passwd") == 0 ||
536
        strcmp(target, "password") == 0) {
537
        if (arg) {
538
            char password[9];
539
            strncpy(password, arg, sizeof(password));
540
            password[sizeof(password) - 1] = '\0';
541
            change_vnc_password_cb(mon, password, NULL);
542
        } else {
543
            monitor_read_password(mon, change_vnc_password_cb, NULL);
544
        }
545
    } else {
546
        if (vnc_display_open(NULL, target) < 0)
547
            monitor_printf(mon, "could not start VNC server on %s\n", target);
548
    }
549
}
550

    
551
static void do_change(Monitor *mon, const QDict *qdict)
552
{
553
    const char *device = qdict_get_str(qdict, "device");
554
    const char *target = qdict_get_str(qdict, "target");
555
    const char *arg = qdict_get_try_str(qdict, "arg");
556
    if (strcmp(device, "vnc") == 0) {
557
        do_change_vnc(mon, target, arg);
558
    } else {
559
        do_change_block(mon, device, target, arg);
560
    }
561
}
562

    
563
static void do_screen_dump(Monitor *mon, const QDict *qdict)
564
{
565
    vga_hw_screen_dump(qdict_get_str(qdict, "filename"));
566
}
567

    
568
static void do_logfile(Monitor *mon, const QDict *qdict)
569
{
570
    cpu_set_log_filename(qdict_get_str(qdict, "filename"));
571
}
572

    
573
static void do_log(Monitor *mon, const QDict *qdict)
574
{
575
    int mask;
576
    const char *items = qdict_get_str(qdict, "items");
577

    
578
    if (!strcmp(items, "none")) {
579
        mask = 0;
580
    } else {
581
        mask = cpu_str_to_log_mask(items);
582
        if (!mask) {
583
            help_cmd(mon, "log");
584
            return;
585
        }
586
    }
587
    cpu_set_log(mask);
588
}
589

    
590
static void do_singlestep(Monitor *mon, const QDict *qdict)
591
{
592
    const char *option = qdict_get_try_str(qdict, "option");
593
    if (!option || !strcmp(option, "on")) {
594
        singlestep = 1;
595
    } else if (!strcmp(option, "off")) {
596
        singlestep = 0;
597
    } else {
598
        monitor_printf(mon, "unexpected option %s\n", option);
599
    }
600
}
601

    
602
/**
603
 * do_stop(): Stop VM execution
604
 */
605
static void do_stop(Monitor *mon, const QDict *qdict, QObject **ret_data)
606
{
607
    vm_stop(EXCP_INTERRUPT);
608
}
609

    
610
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs);
611

    
612
struct bdrv_iterate_context {
613
    Monitor *mon;
614
    int err;
615
};
616

    
617
/**
618
 * do_cont(): Resume emulation.
619
 */
620
static void do_cont(Monitor *mon, const QDict *qdict, QObject **ret_data)
621
{
622
    struct bdrv_iterate_context context = { mon, 0 };
623

    
624
    bdrv_iterate(encrypted_bdrv_it, &context);
625
    /* only resume the vm if all keys are set and valid */
626
    if (!context.err)
627
        vm_start();
628
}
629

    
630
static void bdrv_key_cb(void *opaque, int err)
631
{
632
    Monitor *mon = opaque;
633

    
634
    /* another key was set successfully, retry to continue */
635
    if (!err)
636
        do_cont(mon, NULL, NULL);
637
}
638

    
639
static void encrypted_bdrv_it(void *opaque, BlockDriverState *bs)
640
{
641
    struct bdrv_iterate_context *context = opaque;
642

    
643
    if (!context->err && bdrv_key_required(bs)) {
644
        context->err = -EBUSY;
645
        monitor_read_bdrv_key_start(context->mon, bs, bdrv_key_cb,
646
                                    context->mon);
647
    }
648
}
649

    
650
static void do_gdbserver(Monitor *mon, const QDict *qdict)
651
{
652
    const char *device = qdict_get_try_str(qdict, "device");
653
    if (!device)
654
        device = "tcp::" DEFAULT_GDBSTUB_PORT;
655
    if (gdbserver_start(device) < 0) {
656
        monitor_printf(mon, "Could not open gdbserver on device '%s'\n",
657
                       device);
658
    } else if (strcmp(device, "none") == 0) {
659
        monitor_printf(mon, "Disabled gdbserver\n");
660
    } else {
661
        monitor_printf(mon, "Waiting for gdb connection on device '%s'\n",
662
                       device);
663
    }
664
}
665

    
666
static void do_watchdog_action(Monitor *mon, const QDict *qdict)
667
{
668
    const char *action = qdict_get_str(qdict, "action");
669
    if (select_watchdog_action(action) == -1) {
670
        monitor_printf(mon, "Unknown watchdog action '%s'\n", action);
671
    }
672
}
673

    
674
static void monitor_printc(Monitor *mon, int c)
675
{
676
    monitor_printf(mon, "'");
677
    switch(c) {
678
    case '\'':
679
        monitor_printf(mon, "\\'");
680
        break;
681
    case '\\':
682
        monitor_printf(mon, "\\\\");
683
        break;
684
    case '\n':
685
        monitor_printf(mon, "\\n");
686
        break;
687
    case '\r':
688
        monitor_printf(mon, "\\r");
689
        break;
690
    default:
691
        if (c >= 32 && c <= 126) {
692
            monitor_printf(mon, "%c", c);
693
        } else {
694
            monitor_printf(mon, "\\x%02x", c);
695
        }
696
        break;
697
    }
698
    monitor_printf(mon, "'");
699
}
700

    
701
static void memory_dump(Monitor *mon, int count, int format, int wsize,
702
                        target_phys_addr_t addr, int is_physical)
703
{
704
    CPUState *env;
705
    int nb_per_line, l, line_size, i, max_digits, len;
706
    uint8_t buf[16];
707
    uint64_t v;
708

    
709
    if (format == 'i') {
710
        int flags;
711
        flags = 0;
712
        env = mon_get_cpu();
713
        if (!env && !is_physical)
714
            return;
715
#ifdef TARGET_I386
716
        if (wsize == 2) {
717
            flags = 1;
718
        } else if (wsize == 4) {
719
            flags = 0;
720
        } else {
721
            /* as default we use the current CS size */
722
            flags = 0;
723
            if (env) {
724
#ifdef TARGET_X86_64
725
                if ((env->efer & MSR_EFER_LMA) &&
726
                    (env->segs[R_CS].flags & DESC_L_MASK))
727
                    flags = 2;
728
                else
729
#endif
730
                if (!(env->segs[R_CS].flags & DESC_B_MASK))
731
                    flags = 1;
732
            }
733
        }
734
#endif
735
        monitor_disas(mon, env, addr, count, is_physical, flags);
736
        return;
737
    }
738

    
739
    len = wsize * count;
740
    if (wsize == 1)
741
        line_size = 8;
742
    else
743
        line_size = 16;
744
    nb_per_line = line_size / wsize;
745
    max_digits = 0;
746

    
747
    switch(format) {
748
    case 'o':
749
        max_digits = (wsize * 8 + 2) / 3;
750
        break;
751
    default:
752
    case 'x':
753
        max_digits = (wsize * 8) / 4;
754
        break;
755
    case 'u':
756
    case 'd':
757
        max_digits = (wsize * 8 * 10 + 32) / 33;
758
        break;
759
    case 'c':
760
        wsize = 1;
761
        break;
762
    }
763

    
764
    while (len > 0) {
765
        if (is_physical)
766
            monitor_printf(mon, TARGET_FMT_plx ":", addr);
767
        else
768
            monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);
769
        l = len;
770
        if (l > line_size)
771
            l = line_size;
772
        if (is_physical) {
773
            cpu_physical_memory_rw(addr, buf, l, 0);
774
        } else {
775
            env = mon_get_cpu();
776
            if (!env)
777
                break;
778
            if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {
779
                monitor_printf(mon, " Cannot access memory\n");
780
                break;
781
            }
782
        }
783
        i = 0;
784
        while (i < l) {
785
            switch(wsize) {
786
            default:
787
            case 1:
788
                v = ldub_raw(buf + i);
789
                break;
790
            case 2:
791
                v = lduw_raw(buf + i);
792
                break;
793
            case 4:
794
                v = (uint32_t)ldl_raw(buf + i);
795
                break;
796
            case 8:
797
                v = ldq_raw(buf + i);
798
                break;
799
            }
800
            monitor_printf(mon, " ");
801
            switch(format) {
802
            case 'o':
803
                monitor_printf(mon, "%#*" PRIo64, max_digits, v);
804
                break;
805
            case 'x':
806
                monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);
807
                break;
808
            case 'u':
809
                monitor_printf(mon, "%*" PRIu64, max_digits, v);
810
                break;
811
            case 'd':
812
                monitor_printf(mon, "%*" PRId64, max_digits, v);
813
                break;
814
            case 'c':
815
                monitor_printc(mon, v);
816
                break;
817
            }
818
            i += wsize;
819
        }
820
        monitor_printf(mon, "\n");
821
        addr += l;
822
        len -= l;
823
    }
824
}
825

    
826
static void do_memory_dump(Monitor *mon, const QDict *qdict)
827
{
828
    int count = qdict_get_int(qdict, "count");
829
    int format = qdict_get_int(qdict, "format");
830
    int size = qdict_get_int(qdict, "size");
831
    target_long addr = qdict_get_int(qdict, "addr");
832

    
833
    memory_dump(mon, count, format, size, addr, 0);
834
}
835

    
836
static void do_physical_memory_dump(Monitor *mon, const QDict *qdict)
837
{
838
    int count = qdict_get_int(qdict, "count");
839
    int format = qdict_get_int(qdict, "format");
840
    int size = qdict_get_int(qdict, "size");
841
    target_phys_addr_t addr = qdict_get_int(qdict, "addr");
842

    
843
    memory_dump(mon, count, format, size, addr, 1);
844
}
845

    
846
static void do_print(Monitor *mon, const QDict *qdict)
847
{
848
    int format = qdict_get_int(qdict, "format");
849
    target_phys_addr_t val = qdict_get_int(qdict, "val");
850

    
851
#if TARGET_PHYS_ADDR_BITS == 32
852
    switch(format) {
853
    case 'o':
854
        monitor_printf(mon, "%#o", val);
855
        break;
856
    case 'x':
857
        monitor_printf(mon, "%#x", val);
858
        break;
859
    case 'u':
860
        monitor_printf(mon, "%u", val);
861
        break;
862
    default:
863
    case 'd':
864
        monitor_printf(mon, "%d", val);
865
        break;
866
    case 'c':
867
        monitor_printc(mon, val);
868
        break;
869
    }
870
#else
871
    switch(format) {
872
    case 'o':
873
        monitor_printf(mon, "%#" PRIo64, val);
874
        break;
875
    case 'x':
876
        monitor_printf(mon, "%#" PRIx64, val);
877
        break;
878
    case 'u':
879
        monitor_printf(mon, "%" PRIu64, val);
880
        break;
881
    default:
882
    case 'd':
883
        monitor_printf(mon, "%" PRId64, val);
884
        break;
885
    case 'c':
886
        monitor_printc(mon, val);
887
        break;
888
    }
889
#endif
890
    monitor_printf(mon, "\n");
891
}
892

    
893
static void do_memory_save(Monitor *mon, const QDict *qdict)
894
{
895
    FILE *f;
896
    uint32_t size = qdict_get_int(qdict, "size");
897
    const char *filename = qdict_get_str(qdict, "filename");
898
    target_long addr = qdict_get_int(qdict, "val");
899
    uint32_t l;
900
    CPUState *env;
901
    uint8_t buf[1024];
902

    
903
    env = mon_get_cpu();
904
    if (!env)
905
        return;
906

    
907
    f = fopen(filename, "wb");
908
    if (!f) {
909
        monitor_printf(mon, "could not open '%s'\n", filename);
910
        return;
911
    }
912
    while (size != 0) {
913
        l = sizeof(buf);
914
        if (l > size)
915
            l = size;
916
        cpu_memory_rw_debug(env, addr, buf, l, 0);
917
        fwrite(buf, 1, l, f);
918
        addr += l;
919
        size -= l;
920
    }
921
    fclose(f);
922
}
923

    
924
static void do_physical_memory_save(Monitor *mon, const QDict *qdict)
925
{
926
    FILE *f;
927
    uint32_t l;
928
    uint8_t buf[1024];
929
    uint32_t size = qdict_get_int(qdict, "size");
930
    const char *filename = qdict_get_str(qdict, "filename");
931
    target_phys_addr_t addr = qdict_get_int(qdict, "val");
932

    
933
    f = fopen(filename, "wb");
934
    if (!f) {
935
        monitor_printf(mon, "could not open '%s'\n", filename);
936
        return;
937
    }
938
    while (size != 0) {
939
        l = sizeof(buf);
940
        if (l > size)
941
            l = size;
942
        cpu_physical_memory_rw(addr, buf, l, 0);
943
        fwrite(buf, 1, l, f);
944
        fflush(f);
945
        addr += l;
946
        size -= l;
947
    }
948
    fclose(f);
949
}
950

    
951
static void do_sum(Monitor *mon, const QDict *qdict)
952
{
953
    uint32_t addr;
954
    uint8_t buf[1];
955
    uint16_t sum;
956
    uint32_t start = qdict_get_int(qdict, "start");
957
    uint32_t size = qdict_get_int(qdict, "size");
958

    
959
    sum = 0;
960
    for(addr = start; addr < (start + size); addr++) {
961
        cpu_physical_memory_rw(addr, buf, 1, 0);
962
        /* BSD sum algorithm ('sum' Unix command) */
963
        sum = (sum >> 1) | (sum << 15);
964
        sum += buf[0];
965
    }
966
    monitor_printf(mon, "%05d\n", sum);
967
}
968

    
969
typedef struct {
970
    int keycode;
971
    const char *name;
972
} KeyDef;
973

    
974
static const KeyDef key_defs[] = {
975
    { 0x2a, "shift" },
976
    { 0x36, "shift_r" },
977

    
978
    { 0x38, "alt" },
979
    { 0xb8, "alt_r" },
980
    { 0x64, "altgr" },
981
    { 0xe4, "altgr_r" },
982
    { 0x1d, "ctrl" },
983
    { 0x9d, "ctrl_r" },
984

    
985
    { 0xdd, "menu" },
986

    
987
    { 0x01, "esc" },
988

    
989
    { 0x02, "1" },
990
    { 0x03, "2" },
991
    { 0x04, "3" },
992
    { 0x05, "4" },
993
    { 0x06, "5" },
994
    { 0x07, "6" },
995
    { 0x08, "7" },
996
    { 0x09, "8" },
997
    { 0x0a, "9" },
998
    { 0x0b, "0" },
999
    { 0x0c, "minus" },
1000
    { 0x0d, "equal" },
1001
    { 0x0e, "backspace" },
1002

    
1003
    { 0x0f, "tab" },
1004
    { 0x10, "q" },
1005
    { 0x11, "w" },
1006
    { 0x12, "e" },
1007
    { 0x13, "r" },
1008
    { 0x14, "t" },
1009
    { 0x15, "y" },
1010
    { 0x16, "u" },
1011
    { 0x17, "i" },
1012
    { 0x18, "o" },
1013
    { 0x19, "p" },
1014

    
1015
    { 0x1c, "ret" },
1016

    
1017
    { 0x1e, "a" },
1018
    { 0x1f, "s" },
1019
    { 0x20, "d" },
1020
    { 0x21, "f" },
1021
    { 0x22, "g" },
1022
    { 0x23, "h" },
1023
    { 0x24, "j" },
1024
    { 0x25, "k" },
1025
    { 0x26, "l" },
1026

    
1027
    { 0x2c, "z" },
1028
    { 0x2d, "x" },
1029
    { 0x2e, "c" },
1030
    { 0x2f, "v" },
1031
    { 0x30, "b" },
1032
    { 0x31, "n" },
1033
    { 0x32, "m" },
1034
    { 0x33, "comma" },
1035
    { 0x34, "dot" },
1036
    { 0x35, "slash" },
1037

    
1038
    { 0x37, "asterisk" },
1039

    
1040
    { 0x39, "spc" },
1041
    { 0x3a, "caps_lock" },
1042
    { 0x3b, "f1" },
1043
    { 0x3c, "f2" },
1044
    { 0x3d, "f3" },
1045
    { 0x3e, "f4" },
1046
    { 0x3f, "f5" },
1047
    { 0x40, "f6" },
1048
    { 0x41, "f7" },
1049
    { 0x42, "f8" },
1050
    { 0x43, "f9" },
1051
    { 0x44, "f10" },
1052
    { 0x45, "num_lock" },
1053
    { 0x46, "scroll_lock" },
1054

    
1055
    { 0xb5, "kp_divide" },
1056
    { 0x37, "kp_multiply" },
1057
    { 0x4a, "kp_subtract" },
1058
    { 0x4e, "kp_add" },
1059
    { 0x9c, "kp_enter" },
1060
    { 0x53, "kp_decimal" },
1061
    { 0x54, "sysrq" },
1062

    
1063
    { 0x52, "kp_0" },
1064
    { 0x4f, "kp_1" },
1065
    { 0x50, "kp_2" },
1066
    { 0x51, "kp_3" },
1067
    { 0x4b, "kp_4" },
1068
    { 0x4c, "kp_5" },
1069
    { 0x4d, "kp_6" },
1070
    { 0x47, "kp_7" },
1071
    { 0x48, "kp_8" },
1072
    { 0x49, "kp_9" },
1073

    
1074
    { 0x56, "<" },
1075

    
1076
    { 0x57, "f11" },
1077
    { 0x58, "f12" },
1078

    
1079
    { 0xb7, "print" },
1080

    
1081
    { 0xc7, "home" },
1082
    { 0xc9, "pgup" },
1083
    { 0xd1, "pgdn" },
1084
    { 0xcf, "end" },
1085

    
1086
    { 0xcb, "left" },
1087
    { 0xc8, "up" },
1088
    { 0xd0, "down" },
1089
    { 0xcd, "right" },
1090

    
1091
    { 0xd2, "insert" },
1092
    { 0xd3, "delete" },
1093
#if defined(TARGET_SPARC) && !defined(TARGET_SPARC64)
1094
    { 0xf0, "stop" },
1095
    { 0xf1, "again" },
1096
    { 0xf2, "props" },
1097
    { 0xf3, "undo" },
1098
    { 0xf4, "front" },
1099
    { 0xf5, "copy" },
1100
    { 0xf6, "open" },
1101
    { 0xf7, "paste" },
1102
    { 0xf8, "find" },
1103
    { 0xf9, "cut" },
1104
    { 0xfa, "lf" },
1105
    { 0xfb, "help" },
1106
    { 0xfc, "meta_l" },
1107
    { 0xfd, "meta_r" },
1108
    { 0xfe, "compose" },
1109
#endif
1110
    { 0, NULL },
1111
};
1112

    
1113
static int get_keycode(const char *key)
1114
{
1115
    const KeyDef *p;
1116
    char *endp;
1117
    int ret;
1118

    
1119
    for(p = key_defs; p->name != NULL; p++) {
1120
        if (!strcmp(key, p->name))
1121
            return p->keycode;
1122
    }
1123
    if (strstart(key, "0x", NULL)) {
1124
        ret = strtoul(key, &endp, 0);
1125
        if (*endp == '\0' && ret >= 0x01 && ret <= 0xff)
1126
            return ret;
1127
    }
1128
    return -1;
1129
}
1130

    
1131
#define MAX_KEYCODES 16
1132
static uint8_t keycodes[MAX_KEYCODES];
1133
static int nb_pending_keycodes;
1134
static QEMUTimer *key_timer;
1135

    
1136
static void release_keys(void *opaque)
1137
{
1138
    int keycode;
1139

    
1140
    while (nb_pending_keycodes > 0) {
1141
        nb_pending_keycodes--;
1142
        keycode = keycodes[nb_pending_keycodes];
1143
        if (keycode & 0x80)
1144
            kbd_put_keycode(0xe0);
1145
        kbd_put_keycode(keycode | 0x80);
1146
    }
1147
}
1148

    
1149
static void do_sendkey(Monitor *mon, const QDict *qdict)
1150
{
1151
    char keyname_buf[16];
1152
    char *separator;
1153
    int keyname_len, keycode, i;
1154
    const char *string = qdict_get_str(qdict, "string");
1155
    int has_hold_time = qdict_haskey(qdict, "hold_time");
1156
    int hold_time = qdict_get_try_int(qdict, "hold_time", -1);
1157

    
1158
    if (nb_pending_keycodes > 0) {
1159
        qemu_del_timer(key_timer);
1160
        release_keys(NULL);
1161
    }
1162
    if (!has_hold_time)
1163
        hold_time = 100;
1164
    i = 0;
1165
    while (1) {
1166
        separator = strchr(string, '-');
1167
        keyname_len = separator ? separator - string : strlen(string);
1168
        if (keyname_len > 0) {
1169
            pstrcpy(keyname_buf, sizeof(keyname_buf), string);
1170
            if (keyname_len > sizeof(keyname_buf) - 1) {
1171
                monitor_printf(mon, "invalid key: '%s...'\n", keyname_buf);
1172
                return;
1173
            }
1174
            if (i == MAX_KEYCODES) {
1175
                monitor_printf(mon, "too many keys\n");
1176
                return;
1177
            }
1178
            keyname_buf[keyname_len] = 0;
1179
            keycode = get_keycode(keyname_buf);
1180
            if (keycode < 0) {
1181
                monitor_printf(mon, "unknown key: '%s'\n", keyname_buf);
1182
                return;
1183
            }
1184
            keycodes[i++] = keycode;
1185
        }
1186
        if (!separator)
1187
            break;
1188
        string = separator + 1;
1189
    }
1190
    nb_pending_keycodes = i;
1191
    /* key down events */
1192
    for (i = 0; i < nb_pending_keycodes; i++) {
1193
        keycode = keycodes[i];
1194
        if (keycode & 0x80)
1195
            kbd_put_keycode(0xe0);
1196
        kbd_put_keycode(keycode & 0x7f);
1197
    }
1198
    /* delayed key up events */
1199
    qemu_mod_timer(key_timer, qemu_get_clock(vm_clock) +
1200
                   muldiv64(get_ticks_per_sec(), hold_time, 1000));
1201
}
1202

    
1203
static int mouse_button_state;
1204

    
1205
static void do_mouse_move(Monitor *mon, const QDict *qdict)
1206
{
1207
    int dx, dy, dz;
1208
    const char *dx_str = qdict_get_str(qdict, "dx_str");
1209
    const char *dy_str = qdict_get_str(qdict, "dy_str");
1210
    const char *dz_str = qdict_get_try_str(qdict, "dz_str");
1211
    dx = strtol(dx_str, NULL, 0);
1212
    dy = strtol(dy_str, NULL, 0);
1213
    dz = 0;
1214
    if (dz_str)
1215
        dz = strtol(dz_str, NULL, 0);
1216
    kbd_mouse_event(dx, dy, dz, mouse_button_state);
1217
}
1218

    
1219
static void do_mouse_button(Monitor *mon, const QDict *qdict)
1220
{
1221
    int button_state = qdict_get_int(qdict, "button_state");
1222
    mouse_button_state = button_state;
1223
    kbd_mouse_event(0, 0, 0, mouse_button_state);
1224
}
1225

    
1226
static void do_ioport_read(Monitor *mon, const QDict *qdict)
1227
{
1228
    int size = qdict_get_int(qdict, "size");
1229
    int addr = qdict_get_int(qdict, "addr");
1230
    int has_index = qdict_haskey(qdict, "index");
1231
    uint32_t val;
1232
    int suffix;
1233

    
1234
    if (has_index) {
1235
        int index = qdict_get_int(qdict, "index");
1236
        cpu_outb(addr & IOPORTS_MASK, index & 0xff);
1237
        addr++;
1238
    }
1239
    addr &= 0xffff;
1240

    
1241
    switch(size) {
1242
    default:
1243
    case 1:
1244
        val = cpu_inb(addr);
1245
        suffix = 'b';
1246
        break;
1247
    case 2:
1248
        val = cpu_inw(addr);
1249
        suffix = 'w';
1250
        break;
1251
    case 4:
1252
        val = cpu_inl(addr);
1253
        suffix = 'l';
1254
        break;
1255
    }
1256
    monitor_printf(mon, "port%c[0x%04x] = %#0*x\n",
1257
                   suffix, addr, size * 2, val);
1258
}
1259

    
1260
static void do_ioport_write(Monitor *mon, const QDict *qdict)
1261
{
1262
    int size = qdict_get_int(qdict, "size");
1263
    int addr = qdict_get_int(qdict, "addr");
1264
    int val = qdict_get_int(qdict, "val");
1265

    
1266
    addr &= IOPORTS_MASK;
1267

    
1268
    switch (size) {
1269
    default:
1270
    case 1:
1271
        cpu_outb(addr, val);
1272
        break;
1273
    case 2:
1274
        cpu_outw(addr, val);
1275
        break;
1276
    case 4:
1277
        cpu_outl(addr, val);
1278
        break;
1279
    }
1280
}
1281

    
1282
static void do_boot_set(Monitor *mon, const QDict *qdict)
1283
{
1284
    int res;
1285
    const char *bootdevice = qdict_get_str(qdict, "bootdevice");
1286

    
1287
    res = qemu_boot_set(bootdevice);
1288
    if (res == 0) {
1289
        monitor_printf(mon, "boot device list now set to %s\n", bootdevice);
1290
    } else if (res > 0) {
1291
        monitor_printf(mon, "setting boot device list failed\n");
1292
    } else {
1293
        monitor_printf(mon, "no function defined to set boot device list for "
1294
                       "this architecture\n");
1295
    }
1296
}
1297

    
1298
/**
1299
 * do_system_reset(): Issue a machine reset
1300
 */
1301
static void do_system_reset(Monitor *mon, const QDict *qdict,
1302
                            QObject **ret_data)
1303
{
1304
    qemu_system_reset_request();
1305
}
1306

    
1307
/**
1308
 * do_system_powerdown(): Issue a machine powerdown
1309
 */
1310
static void do_system_powerdown(Monitor *mon, const QDict *qdict,
1311
                                QObject **ret_data)
1312
{
1313
    qemu_system_powerdown_request();
1314
}
1315

    
1316
#if defined(TARGET_I386)
1317
static void print_pte(Monitor *mon, uint32_t addr, uint32_t pte, uint32_t mask)
1318
{
1319
    monitor_printf(mon, "%08x: %08x %c%c%c%c%c%c%c%c\n",
1320
                   addr,
1321
                   pte & mask,
1322
                   pte & PG_GLOBAL_MASK ? 'G' : '-',
1323
                   pte & PG_PSE_MASK ? 'P' : '-',
1324
                   pte & PG_DIRTY_MASK ? 'D' : '-',
1325
                   pte & PG_ACCESSED_MASK ? 'A' : '-',
1326
                   pte & PG_PCD_MASK ? 'C' : '-',
1327
                   pte & PG_PWT_MASK ? 'T' : '-',
1328
                   pte & PG_USER_MASK ? 'U' : '-',
1329
                   pte & PG_RW_MASK ? 'W' : '-');
1330
}
1331

    
1332
static void tlb_info(Monitor *mon)
1333
{
1334
    CPUState *env;
1335
    int l1, l2;
1336
    uint32_t pgd, pde, pte;
1337

    
1338
    env = mon_get_cpu();
1339
    if (!env)
1340
        return;
1341

    
1342
    if (!(env->cr[0] & CR0_PG_MASK)) {
1343
        monitor_printf(mon, "PG disabled\n");
1344
        return;
1345
    }
1346
    pgd = env->cr[3] & ~0xfff;
1347
    for(l1 = 0; l1 < 1024; l1++) {
1348
        cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1349
        pde = le32_to_cpu(pde);
1350
        if (pde & PG_PRESENT_MASK) {
1351
            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1352
                print_pte(mon, (l1 << 22), pde, ~((1 << 20) - 1));
1353
            } else {
1354
                for(l2 = 0; l2 < 1024; l2++) {
1355
                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1356
                                             (uint8_t *)&pte, 4);
1357
                    pte = le32_to_cpu(pte);
1358
                    if (pte & PG_PRESENT_MASK) {
1359
                        print_pte(mon, (l1 << 22) + (l2 << 12),
1360
                                  pte & ~PG_PSE_MASK,
1361
                                  ~0xfff);
1362
                    }
1363
                }
1364
            }
1365
        }
1366
    }
1367
}
1368

    
1369
static void mem_print(Monitor *mon, uint32_t *pstart, int *plast_prot,
1370
                      uint32_t end, int prot)
1371
{
1372
    int prot1;
1373
    prot1 = *plast_prot;
1374
    if (prot != prot1) {
1375
        if (*pstart != -1) {
1376
            monitor_printf(mon, "%08x-%08x %08x %c%c%c\n",
1377
                           *pstart, end, end - *pstart,
1378
                           prot1 & PG_USER_MASK ? 'u' : '-',
1379
                           'r',
1380
                           prot1 & PG_RW_MASK ? 'w' : '-');
1381
        }
1382
        if (prot != 0)
1383
            *pstart = end;
1384
        else
1385
            *pstart = -1;
1386
        *plast_prot = prot;
1387
    }
1388
}
1389

    
1390
static void mem_info(Monitor *mon)
1391
{
1392
    CPUState *env;
1393
    int l1, l2, prot, last_prot;
1394
    uint32_t pgd, pde, pte, start, end;
1395

    
1396
    env = mon_get_cpu();
1397
    if (!env)
1398
        return;
1399

    
1400
    if (!(env->cr[0] & CR0_PG_MASK)) {
1401
        monitor_printf(mon, "PG disabled\n");
1402
        return;
1403
    }
1404
    pgd = env->cr[3] & ~0xfff;
1405
    last_prot = 0;
1406
    start = -1;
1407
    for(l1 = 0; l1 < 1024; l1++) {
1408
        cpu_physical_memory_read(pgd + l1 * 4, (uint8_t *)&pde, 4);
1409
        pde = le32_to_cpu(pde);
1410
        end = l1 << 22;
1411
        if (pde & PG_PRESENT_MASK) {
1412
            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
1413
                prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1414
                mem_print(mon, &start, &last_prot, end, prot);
1415
            } else {
1416
                for(l2 = 0; l2 < 1024; l2++) {
1417
                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4,
1418
                                             (uint8_t *)&pte, 4);
1419
                    pte = le32_to_cpu(pte);
1420
                    end = (l1 << 22) + (l2 << 12);
1421
                    if (pte & PG_PRESENT_MASK) {
1422
                        prot = pte & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);
1423
                    } else {
1424
                        prot = 0;
1425
                    }
1426
                    mem_print(mon, &start, &last_prot, end, prot);
1427
                }
1428
            }
1429
        } else {
1430
            prot = 0;
1431
            mem_print(mon, &start, &last_prot, end, prot);
1432
        }
1433
    }
1434
}
1435
#endif
1436

    
1437
#if defined(TARGET_SH4)
1438

    
1439
static void print_tlb(Monitor *mon, int idx, tlb_t *tlb)
1440
{
1441
    monitor_printf(mon, " tlb%i:\t"
1442
                   "asid=%hhu vpn=%x\tppn=%x\tsz=%hhu size=%u\t"
1443
                   "v=%hhu shared=%hhu cached=%hhu prot=%hhu "
1444
                   "dirty=%hhu writethrough=%hhu\n",
1445
                   idx,
1446
                   tlb->asid, tlb->vpn, tlb->ppn, tlb->sz, tlb->size,
1447
                   tlb->v, tlb->sh, tlb->c, tlb->pr,
1448
                   tlb->d, tlb->wt);
1449
}
1450

    
1451
static void tlb_info(Monitor *mon)
1452
{
1453
    CPUState *env = mon_get_cpu();
1454
    int i;
1455

    
1456
    monitor_printf (mon, "ITLB:\n");
1457
    for (i = 0 ; i < ITLB_SIZE ; i++)
1458
        print_tlb (mon, i, &env->itlb[i]);
1459
    monitor_printf (mon, "UTLB:\n");
1460
    for (i = 0 ; i < UTLB_SIZE ; i++)
1461
        print_tlb (mon, i, &env->utlb[i]);
1462
}
1463

    
1464
#endif
1465

    
1466
static void do_info_kvm(Monitor *mon)
1467
{
1468
#ifdef CONFIG_KVM
1469
    monitor_printf(mon, "kvm support: ");
1470
    if (kvm_enabled())
1471
        monitor_printf(mon, "enabled\n");
1472
    else
1473
        monitor_printf(mon, "disabled\n");
1474
#else
1475
    monitor_printf(mon, "kvm support: not compiled\n");
1476
#endif
1477
}
1478

    
1479
static void do_info_numa(Monitor *mon)
1480
{
1481
    int i;
1482
    CPUState *env;
1483

    
1484
    monitor_printf(mon, "%d nodes\n", nb_numa_nodes);
1485
    for (i = 0; i < nb_numa_nodes; i++) {
1486
        monitor_printf(mon, "node %d cpus:", i);
1487
        for (env = first_cpu; env != NULL; env = env->next_cpu) {
1488
            if (env->numa_node == i) {
1489
                monitor_printf(mon, " %d", env->cpu_index);
1490
            }
1491
        }
1492
        monitor_printf(mon, "\n");
1493
        monitor_printf(mon, "node %d size: %" PRId64 " MB\n", i,
1494
            node_mem[i] >> 20);
1495
    }
1496
}
1497

    
1498
#ifdef CONFIG_PROFILER
1499

    
1500
int64_t qemu_time;
1501
int64_t dev_time;
1502

    
1503
static void do_info_profile(Monitor *mon)
1504
{
1505
    int64_t total;
1506
    total = qemu_time;
1507
    if (total == 0)
1508
        total = 1;
1509
    monitor_printf(mon, "async time  %" PRId64 " (%0.3f)\n",
1510
                   dev_time, dev_time / (double)get_ticks_per_sec());
1511
    monitor_printf(mon, "qemu time   %" PRId64 " (%0.3f)\n",
1512
                   qemu_time, qemu_time / (double)get_ticks_per_sec());
1513
    qemu_time = 0;
1514
    dev_time = 0;
1515
}
1516
#else
1517
static void do_info_profile(Monitor *mon)
1518
{
1519
    monitor_printf(mon, "Internal profiler not compiled\n");
1520
}
1521
#endif
1522

    
1523
/* Capture support */
1524
static QLIST_HEAD (capture_list_head, CaptureState) capture_head;
1525

    
1526
static void do_info_capture(Monitor *mon)
1527
{
1528
    int i;
1529
    CaptureState *s;
1530

    
1531
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1532
        monitor_printf(mon, "[%d]: ", i);
1533
        s->ops.info (s->opaque);
1534
    }
1535
}
1536

    
1537
#ifdef HAS_AUDIO
1538
static void do_stop_capture(Monitor *mon, const QDict *qdict)
1539
{
1540
    int i;
1541
    int n = qdict_get_int(qdict, "n");
1542
    CaptureState *s;
1543

    
1544
    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {
1545
        if (i == n) {
1546
            s->ops.destroy (s->opaque);
1547
            QLIST_REMOVE (s, entries);
1548
            qemu_free (s);
1549
            return;
1550
        }
1551
    }
1552
}
1553

    
1554
static void do_wav_capture(Monitor *mon, const QDict *qdict)
1555
{
1556
    const char *path = qdict_get_str(qdict, "path");
1557
    int has_freq = qdict_haskey(qdict, "freq");
1558
    int freq = qdict_get_try_int(qdict, "freq", -1);
1559
    int has_bits = qdict_haskey(qdict, "bits");
1560
    int bits = qdict_get_try_int(qdict, "bits", -1);
1561
    int has_channels = qdict_haskey(qdict, "nchannels");
1562
    int nchannels = qdict_get_try_int(qdict, "nchannels", -1);
1563
    CaptureState *s;
1564

    
1565
    s = qemu_mallocz (sizeof (*s));
1566

    
1567
    freq = has_freq ? freq : 44100;
1568
    bits = has_bits ? bits : 16;
1569
    nchannels = has_channels ? nchannels : 2;
1570

    
1571
    if (wav_start_capture (s, path, freq, bits, nchannels)) {
1572
        monitor_printf(mon, "Faied to add wave capture\n");
1573
        qemu_free (s);
1574
    }
1575
    QLIST_INSERT_HEAD (&capture_head, s, entries);
1576
}
1577
#endif
1578

    
1579
#if defined(TARGET_I386)
1580
static void do_inject_nmi(Monitor *mon, const QDict *qdict)
1581
{
1582
    CPUState *env;
1583
    int cpu_index = qdict_get_int(qdict, "cpu_index");
1584

    
1585
    for (env = first_cpu; env != NULL; env = env->next_cpu)
1586
        if (env->cpu_index == cpu_index) {
1587
            cpu_interrupt(env, CPU_INTERRUPT_NMI);
1588
            break;
1589
        }
1590
}
1591
#endif
1592

    
1593
static void do_info_status(Monitor *mon)
1594
{
1595
    if (vm_running) {
1596
        if (singlestep) {
1597
            monitor_printf(mon, "VM status: running (single step mode)\n");
1598
        } else {
1599
            monitor_printf(mon, "VM status: running\n");
1600
        }
1601
    } else
1602
       monitor_printf(mon, "VM status: paused\n");
1603
}
1604

    
1605
/**
1606
 * do_balloon(): Request VM to change its memory allocation
1607
 */
1608
static void do_balloon(Monitor *mon, const QDict *qdict, QObject **ret_data)
1609
{
1610
    int value = qdict_get_int(qdict, "value");
1611
    ram_addr_t target = value;
1612
    qemu_balloon(target << 20);
1613
}
1614

    
1615
static void do_info_balloon(Monitor *mon)
1616
{
1617
    ram_addr_t actual;
1618

    
1619
    actual = qemu_balloon_status();
1620
    if (kvm_enabled() && !kvm_has_sync_mmu())
1621
        monitor_printf(mon, "Using KVM without synchronous MMU, "
1622
                       "ballooning disabled\n");
1623
    else if (actual == 0)
1624
        monitor_printf(mon, "Ballooning not activated in VM\n");
1625
    else
1626
        monitor_printf(mon, "balloon: actual=%d\n", (int)(actual >> 20));
1627
}
1628

    
1629
static qemu_acl *find_acl(Monitor *mon, const char *name)
1630
{
1631
    qemu_acl *acl = qemu_acl_find(name);
1632

    
1633
    if (!acl) {
1634
        monitor_printf(mon, "acl: unknown list '%s'\n", name);
1635
    }
1636
    return acl;
1637
}
1638

    
1639
static void do_acl_show(Monitor *mon, const QDict *qdict)
1640
{
1641
    const char *aclname = qdict_get_str(qdict, "aclname");
1642
    qemu_acl *acl = find_acl(mon, aclname);
1643
    qemu_acl_entry *entry;
1644
    int i = 0;
1645

    
1646
    if (acl) {
1647
        monitor_printf(mon, "policy: %s\n",
1648
                       acl->defaultDeny ? "deny" : "allow");
1649
        QTAILQ_FOREACH(entry, &acl->entries, next) {
1650
            i++;
1651
            monitor_printf(mon, "%d: %s %s\n", i,
1652
                           entry->deny ? "deny" : "allow", entry->match);
1653
        }
1654
    }
1655
}
1656

    
1657
static void do_acl_reset(Monitor *mon, const QDict *qdict)
1658
{
1659
    const char *aclname = qdict_get_str(qdict, "aclname");
1660
    qemu_acl *acl = find_acl(mon, aclname);
1661

    
1662
    if (acl) {
1663
        qemu_acl_reset(acl);
1664
        monitor_printf(mon, "acl: removed all rules\n");
1665
    }
1666
}
1667

    
1668
static void do_acl_policy(Monitor *mon, const QDict *qdict)
1669
{
1670
    const char *aclname = qdict_get_str(qdict, "aclname");
1671
    const char *policy = qdict_get_str(qdict, "policy");
1672
    qemu_acl *acl = find_acl(mon, aclname);
1673

    
1674
    if (acl) {
1675
        if (strcmp(policy, "allow") == 0) {
1676
            acl->defaultDeny = 0;
1677
            monitor_printf(mon, "acl: policy set to 'allow'\n");
1678
        } else if (strcmp(policy, "deny") == 0) {
1679
            acl->defaultDeny = 1;
1680
            monitor_printf(mon, "acl: policy set to 'deny'\n");
1681
        } else {
1682
            monitor_printf(mon, "acl: unknown policy '%s', "
1683
                           "expected 'deny' or 'allow'\n", policy);
1684
        }
1685
    }
1686
}
1687

    
1688
static void do_acl_add(Monitor *mon, const QDict *qdict)
1689
{
1690
    const char *aclname = qdict_get_str(qdict, "aclname");
1691
    const char *match = qdict_get_str(qdict, "match");
1692
    const char *policy = qdict_get_str(qdict, "policy");
1693
    int has_index = qdict_haskey(qdict, "index");
1694
    int index = qdict_get_try_int(qdict, "index", -1);
1695
    qemu_acl *acl = find_acl(mon, aclname);
1696
    int deny, ret;
1697

    
1698
    if (acl) {
1699
        if (strcmp(policy, "allow") == 0) {
1700
            deny = 0;
1701
        } else if (strcmp(policy, "deny") == 0) {
1702
            deny = 1;
1703
        } else {
1704
            monitor_printf(mon, "acl: unknown policy '%s', "
1705
                           "expected 'deny' or 'allow'\n", policy);
1706
            return;
1707
        }
1708
        if (has_index)
1709
            ret = qemu_acl_insert(acl, deny, match, index);
1710
        else
1711
            ret = qemu_acl_append(acl, deny, match);
1712
        if (ret < 0)
1713
            monitor_printf(mon, "acl: unable to add acl entry\n");
1714
        else
1715
            monitor_printf(mon, "acl: added rule at position %d\n", ret);
1716
    }
1717
}
1718

    
1719
static void do_acl_remove(Monitor *mon, const QDict *qdict)
1720
{
1721
    const char *aclname = qdict_get_str(qdict, "aclname");
1722
    const char *match = qdict_get_str(qdict, "match");
1723
    qemu_acl *acl = find_acl(mon, aclname);
1724
    int ret;
1725

    
1726
    if (acl) {
1727
        ret = qemu_acl_remove(acl, match);
1728
        if (ret < 0)
1729
            monitor_printf(mon, "acl: no matching acl entry\n");
1730
        else
1731
            monitor_printf(mon, "acl: removed rule at position %d\n", ret);
1732
    }
1733
}
1734

    
1735
#if defined(TARGET_I386)
1736
static void do_inject_mce(Monitor *mon, const QDict *qdict)
1737
{
1738
    CPUState *cenv;
1739
    int cpu_index = qdict_get_int(qdict, "cpu_index");
1740
    int bank = qdict_get_int(qdict, "bank");
1741
    uint64_t status = qdict_get_int(qdict, "status");
1742
    uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");
1743
    uint64_t addr = qdict_get_int(qdict, "addr");
1744
    uint64_t misc = qdict_get_int(qdict, "misc");
1745

    
1746
    for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu)
1747
        if (cenv->cpu_index == cpu_index && cenv->mcg_cap) {
1748
            cpu_inject_x86_mce(cenv, bank, status, mcg_status, addr, misc);
1749
            break;
1750
        }
1751
}
1752
#endif
1753

    
1754
static void do_getfd(Monitor *mon, const QDict *qdict)
1755
{
1756
    const char *fdname = qdict_get_str(qdict, "fdname");
1757
    mon_fd_t *monfd;
1758
    int fd;
1759

    
1760
    fd = qemu_chr_get_msgfd(mon->chr);
1761
    if (fd == -1) {
1762
        monitor_printf(mon, "getfd: no file descriptor supplied via SCM_RIGHTS\n");
1763
        return;
1764
    }
1765

    
1766
    if (qemu_isdigit(fdname[0])) {
1767
        monitor_printf(mon, "getfd: monitor names may not begin with a number\n");
1768
        return;
1769
    }
1770

    
1771
    fd = dup(fd);
1772
    if (fd == -1) {
1773
        monitor_printf(mon, "Failed to dup() file descriptor: %s\n",
1774
                       strerror(errno));
1775
        return;
1776
    }
1777

    
1778
    QLIST_FOREACH(monfd, &mon->fds, next) {
1779
        if (strcmp(monfd->name, fdname) != 0) {
1780
            continue;
1781
        }
1782

    
1783
        close(monfd->fd);
1784
        monfd->fd = fd;
1785
        return;
1786
    }
1787

    
1788
    monfd = qemu_mallocz(sizeof(mon_fd_t));
1789
    monfd->name = qemu_strdup(fdname);
1790
    monfd->fd = fd;
1791

    
1792
    QLIST_INSERT_HEAD(&mon->fds, monfd, next);
1793
}
1794

    
1795
static void do_closefd(Monitor *mon, const QDict *qdict)
1796
{
1797
    const char *fdname = qdict_get_str(qdict, "fdname");
1798
    mon_fd_t *monfd;
1799

    
1800
    QLIST_FOREACH(monfd, &mon->fds, next) {
1801
        if (strcmp(monfd->name, fdname) != 0) {
1802
            continue;
1803
        }
1804

    
1805
        QLIST_REMOVE(monfd, next);
1806
        close(monfd->fd);
1807
        qemu_free(monfd->name);
1808
        qemu_free(monfd);
1809
        return;
1810
    }
1811

    
1812
    monitor_printf(mon, "Failed to find file descriptor named %s\n",
1813
                   fdname);
1814
}
1815

    
1816
static void do_loadvm(Monitor *mon, const QDict *qdict)
1817
{
1818
    int saved_vm_running  = vm_running;
1819
    const char *name = qdict_get_str(qdict, "name");
1820

    
1821
    vm_stop(0);
1822

    
1823
    if (load_vmstate(mon, name) >= 0 && saved_vm_running)
1824
        vm_start();
1825
}
1826

    
1827
int monitor_get_fd(Monitor *mon, const char *fdname)
1828
{
1829
    mon_fd_t *monfd;
1830

    
1831
    QLIST_FOREACH(monfd, &mon->fds, next) {
1832
        int fd;
1833

    
1834
        if (strcmp(monfd->name, fdname) != 0) {
1835
            continue;
1836
        }
1837

    
1838
        fd = monfd->fd;
1839

    
1840
        /* caller takes ownership of fd */
1841
        QLIST_REMOVE(monfd, next);
1842
        qemu_free(monfd->name);
1843
        qemu_free(monfd);
1844

    
1845
        return fd;
1846
    }
1847

    
1848
    return -1;
1849
}
1850

    
1851
static const mon_cmd_t mon_cmds[] = {
1852
#include "qemu-monitor.h"
1853
    { NULL, NULL, },
1854
};
1855

    
1856
/* Please update qemu-monitor.hx when adding or changing commands */
1857
static const mon_cmd_t info_cmds[] = {
1858
    {
1859
        .name       = "version",
1860
        .args_type  = "",
1861
        .params     = "",
1862
        .help       = "show the version of QEMU",
1863
        .mhandler.info = do_info_version,
1864
    },
1865
    {
1866
        .name       = "network",
1867
        .args_type  = "",
1868
        .params     = "",
1869
        .help       = "show the network state",
1870
        .mhandler.info = do_info_network,
1871
    },
1872
    {
1873
        .name       = "chardev",
1874
        .args_type  = "",
1875
        .params     = "",
1876
        .help       = "show the character devices",
1877
        .mhandler.info = qemu_chr_info,
1878
    },
1879
    {
1880
        .name       = "block",
1881
        .args_type  = "",
1882
        .params     = "",
1883
        .help       = "show the block devices",
1884
        .mhandler.info = bdrv_info,
1885
    },
1886
    {
1887
        .name       = "blockstats",
1888
        .args_type  = "",
1889
        .params     = "",
1890
        .help       = "show block device statistics",
1891
        .mhandler.info = bdrv_info_stats,
1892
    },
1893
    {
1894
        .name       = "registers",
1895
        .args_type  = "",
1896
        .params     = "",
1897
        .help       = "show the cpu registers",
1898
        .mhandler.info = do_info_registers,
1899
    },
1900
    {
1901
        .name       = "cpus",
1902
        .args_type  = "",
1903
        .params     = "",
1904
        .help       = "show infos for each CPU",
1905
        .mhandler.info = do_info_cpus,
1906
    },
1907
    {
1908
        .name       = "history",
1909
        .args_type  = "",
1910
        .params     = "",
1911
        .help       = "show the command line history",
1912
        .mhandler.info = do_info_history,
1913
    },
1914
    {
1915
        .name       = "irq",
1916
        .args_type  = "",
1917
        .params     = "",
1918
        .help       = "show the interrupts statistics (if available)",
1919
        .mhandler.info = irq_info,
1920
    },
1921
    {
1922
        .name       = "pic",
1923
        .args_type  = "",
1924
        .params     = "",
1925
        .help       = "show i8259 (PIC) state",
1926
        .mhandler.info = pic_info,
1927
    },
1928
    {
1929
        .name       = "pci",
1930
        .args_type  = "",
1931
        .params     = "",
1932
        .help       = "show PCI info",
1933
        .mhandler.info = pci_info,
1934
    },
1935
#if defined(TARGET_I386) || defined(TARGET_SH4)
1936
    {
1937
        .name       = "tlb",
1938
        .args_type  = "",
1939
        .params     = "",
1940
        .help       = "show virtual to physical memory mappings",
1941
        .mhandler.info = tlb_info,
1942
    },
1943
#endif
1944
#if defined(TARGET_I386)
1945
    {
1946
        .name       = "mem",
1947
        .args_type  = "",
1948
        .params     = "",
1949
        .help       = "show the active virtual memory mappings",
1950
        .mhandler.info = mem_info,
1951
    },
1952
    {
1953
        .name       = "hpet",
1954
        .args_type  = "",
1955
        .params     = "",
1956
        .help       = "show state of HPET",
1957
        .mhandler.info = do_info_hpet,
1958
    },
1959
#endif
1960
    {
1961
        .name       = "jit",
1962
        .args_type  = "",
1963
        .params     = "",
1964
        .help       = "show dynamic compiler info",
1965
        .mhandler.info = do_info_jit,
1966
    },
1967
    {
1968
        .name       = "kvm",
1969
        .args_type  = "",
1970
        .params     = "",
1971
        .help       = "show KVM information",
1972
        .mhandler.info = do_info_kvm,
1973
    },
1974
    {
1975
        .name       = "numa",
1976
        .args_type  = "",
1977
        .params     = "",
1978
        .help       = "show NUMA information",
1979
        .mhandler.info = do_info_numa,
1980
    },
1981
    {
1982
        .name       = "usb",
1983
        .args_type  = "",
1984
        .params     = "",
1985
        .help       = "show guest USB devices",
1986
        .mhandler.info = usb_info,
1987
    },
1988
    {
1989
        .name       = "usbhost",
1990
        .args_type  = "",
1991
        .params     = "",
1992
        .help       = "show host USB devices",
1993
        .mhandler.info = usb_host_info,
1994
    },
1995
    {
1996
        .name       = "profile",
1997
        .args_type  = "",
1998
        .params     = "",
1999
        .help       = "show profiling information",
2000
        .mhandler.info = do_info_profile,
2001
    },
2002
    {
2003
        .name       = "capture",
2004
        .args_type  = "",
2005
        .params     = "",
2006
        .help       = "show capture information",
2007
        .mhandler.info = do_info_capture,
2008
    },
2009
    {
2010
        .name       = "snapshots",
2011
        .args_type  = "",
2012
        .params     = "",
2013
        .help       = "show the currently saved VM snapshots",
2014
        .mhandler.info = do_info_snapshots,
2015
    },
2016
    {
2017
        .name       = "status",
2018
        .args_type  = "",
2019
        .params     = "",
2020
        .help       = "show the current VM status (running|paused)",
2021
        .mhandler.info = do_info_status,
2022
    },
2023
    {
2024
        .name       = "pcmcia",
2025
        .args_type  = "",
2026
        .params     = "",
2027
        .help       = "show guest PCMCIA status",
2028
        .mhandler.info = pcmcia_info,
2029
    },
2030
    {
2031
        .name       = "mice",
2032
        .args_type  = "",
2033
        .params     = "",
2034
        .help       = "show which guest mouse is receiving events",
2035
        .mhandler.info = do_info_mice,
2036
    },
2037
    {
2038
        .name       = "vnc",
2039
        .args_type  = "",
2040
        .params     = "",
2041
        .help       = "show the vnc server status",
2042
        .mhandler.info = do_info_vnc,
2043
    },
2044
    {
2045
        .name       = "name",
2046
        .args_type  = "",
2047
        .params     = "",
2048
        .help       = "show the current VM name",
2049
        .mhandler.info = do_info_name,
2050
    },
2051
    {
2052
        .name       = "uuid",
2053
        .args_type  = "",
2054
        .params     = "",
2055
        .help       = "show the current VM UUID",
2056
        .mhandler.info = do_info_uuid,
2057
    },
2058
#if defined(TARGET_PPC)
2059
    {
2060
        .name       = "cpustats",
2061
        .args_type  = "",
2062
        .params     = "",
2063
        .help       = "show CPU statistics",
2064
        .mhandler.info = do_info_cpu_stats,
2065
    },
2066
#endif
2067
#if defined(CONFIG_SLIRP)
2068
    {
2069
        .name       = "usernet",
2070
        .args_type  = "",
2071
        .params     = "",
2072
        .help       = "show user network stack connection states",
2073
        .mhandler.info = do_info_usernet,
2074
    },
2075
#endif
2076
    {
2077
        .name       = "migrate",
2078
        .args_type  = "",
2079
        .params     = "",
2080
        .help       = "show migration status",
2081
        .mhandler.info = do_info_migrate,
2082
    },
2083
    {
2084
        .name       = "balloon",
2085
        .args_type  = "",
2086
        .params     = "",
2087
        .help       = "show balloon information",
2088
        .mhandler.info = do_info_balloon,
2089
    },
2090
    {
2091
        .name       = "qtree",
2092
        .args_type  = "",
2093
        .params     = "",
2094
        .help       = "show device tree",
2095
        .mhandler.info = do_info_qtree,
2096
    },
2097
    {
2098
        .name       = "qdm",
2099
        .args_type  = "",
2100
        .params     = "",
2101
        .help       = "show qdev device model list",
2102
        .mhandler.info = do_info_qdm,
2103
    },
2104
    {
2105
        .name       = "roms",
2106
        .args_type  = "",
2107
        .params     = "",
2108
        .help       = "show roms",
2109
        .mhandler.info = do_info_roms,
2110
    },
2111
    {
2112
        .name       = NULL,
2113
    },
2114
};
2115

    
2116
/*******************************************************************/
2117

    
2118
static const char *pch;
2119
static jmp_buf expr_env;
2120

    
2121
#define MD_TLONG 0
2122
#define MD_I32   1
2123

    
2124
typedef struct MonitorDef {
2125
    const char *name;
2126
    int offset;
2127
    target_long (*get_value)(const struct MonitorDef *md, int val);
2128
    int type;
2129
} MonitorDef;
2130

    
2131
#if defined(TARGET_I386)
2132
static target_long monitor_get_pc (const struct MonitorDef *md, int val)
2133
{
2134
    CPUState *env = mon_get_cpu();
2135
    if (!env)
2136
        return 0;
2137
    return env->eip + env->segs[R_CS].base;
2138
}
2139
#endif
2140

    
2141
#if defined(TARGET_PPC)
2142
static target_long monitor_get_ccr (const struct MonitorDef *md, int val)
2143
{
2144
    CPUState *env = mon_get_cpu();
2145
    unsigned int u;
2146
    int i;
2147

    
2148
    if (!env)
2149
        return 0;
2150

    
2151
    u = 0;
2152
    for (i = 0; i < 8; i++)
2153
        u |= env->crf[i] << (32 - (4 * i));
2154

    
2155
    return u;
2156
}
2157

    
2158
static target_long monitor_get_msr (const struct MonitorDef *md, int val)
2159
{
2160
    CPUState *env = mon_get_cpu();
2161
    if (!env)
2162
        return 0;
2163
    return env->msr;
2164
}
2165

    
2166
static target_long monitor_get_xer (const struct MonitorDef *md, int val)
2167
{
2168
    CPUState *env = mon_get_cpu();
2169
    if (!env)
2170
        return 0;
2171
    return env->xer;
2172
}
2173

    
2174
static target_long monitor_get_decr (const struct MonitorDef *md, int val)
2175
{
2176
    CPUState *env = mon_get_cpu();
2177
    if (!env)
2178
        return 0;
2179
    return cpu_ppc_load_decr(env);
2180
}
2181

    
2182
static target_long monitor_get_tbu (const struct MonitorDef *md, int val)
2183
{
2184
    CPUState *env = mon_get_cpu();
2185
    if (!env)
2186
        return 0;
2187
    return cpu_ppc_load_tbu(env);
2188
}
2189

    
2190
static target_long monitor_get_tbl (const struct MonitorDef *md, int val)
2191
{
2192
    CPUState *env = mon_get_cpu();
2193
    if (!env)
2194
        return 0;
2195
    return cpu_ppc_load_tbl(env);
2196
}
2197
#endif
2198

    
2199
#if defined(TARGET_SPARC)
2200
#ifndef TARGET_SPARC64
2201
static target_long monitor_get_psr (const struct MonitorDef *md, int val)
2202
{
2203
    CPUState *env = mon_get_cpu();
2204
    if (!env)
2205
        return 0;
2206
    return GET_PSR(env);
2207
}
2208
#endif
2209

    
2210
static target_long monitor_get_reg(const struct MonitorDef *md, int val)
2211
{
2212
    CPUState *env = mon_get_cpu();
2213
    if (!env)
2214
        return 0;
2215
    return env->regwptr[val];
2216
}
2217
#endif
2218

    
2219
static const MonitorDef monitor_defs[] = {
2220
#ifdef TARGET_I386
2221

    
2222
#define SEG(name, seg) \
2223
    { name, offsetof(CPUState, segs[seg].selector), NULL, MD_I32 },\
2224
    { name ".base", offsetof(CPUState, segs[seg].base) },\
2225
    { name ".limit", offsetof(CPUState, segs[seg].limit), NULL, MD_I32 },
2226

    
2227
    { "eax", offsetof(CPUState, regs[0]) },
2228
    { "ecx", offsetof(CPUState, regs[1]) },
2229
    { "edx", offsetof(CPUState, regs[2]) },
2230
    { "ebx", offsetof(CPUState, regs[3]) },
2231
    { "esp|sp", offsetof(CPUState, regs[4]) },
2232
    { "ebp|fp", offsetof(CPUState, regs[5]) },
2233
    { "esi", offsetof(CPUState, regs[6]) },
2234
    { "edi", offsetof(CPUState, regs[7]) },
2235
#ifdef TARGET_X86_64
2236
    { "r8", offsetof(CPUState, regs[8]) },
2237
    { "r9", offsetof(CPUState, regs[9]) },
2238
    { "r10", offsetof(CPUState, regs[10]) },
2239
    { "r11", offsetof(CPUState, regs[11]) },
2240
    { "r12", offsetof(CPUState, regs[12]) },
2241
    { "r13", offsetof(CPUState, regs[13]) },
2242
    { "r14", offsetof(CPUState, regs[14]) },
2243
    { "r15", offsetof(CPUState, regs[15]) },
2244
#endif
2245
    { "eflags", offsetof(CPUState, eflags) },
2246
    { "eip", offsetof(CPUState, eip) },
2247
    SEG("cs", R_CS)
2248
    SEG("ds", R_DS)
2249
    SEG("es", R_ES)
2250
    SEG("ss", R_SS)
2251
    SEG("fs", R_FS)
2252
    SEG("gs", R_GS)
2253
    { "pc", 0, monitor_get_pc, },
2254
#elif defined(TARGET_PPC)
2255
    /* General purpose registers */
2256
    { "r0", offsetof(CPUState, gpr[0]) },
2257
    { "r1", offsetof(CPUState, gpr[1]) },
2258
    { "r2", offsetof(CPUState, gpr[2]) },
2259
    { "r3", offsetof(CPUState, gpr[3]) },
2260
    { "r4", offsetof(CPUState, gpr[4]) },
2261
    { "r5", offsetof(CPUState, gpr[5]) },
2262
    { "r6", offsetof(CPUState, gpr[6]) },
2263
    { "r7", offsetof(CPUState, gpr[7]) },
2264
    { "r8", offsetof(CPUState, gpr[8]) },
2265
    { "r9", offsetof(CPUState, gpr[9]) },
2266
    { "r10", offsetof(CPUState, gpr[10]) },
2267
    { "r11", offsetof(CPUState, gpr[11]) },
2268
    { "r12", offsetof(CPUState, gpr[12]) },
2269
    { "r13", offsetof(CPUState, gpr[13]) },
2270
    { "r14", offsetof(CPUState, gpr[14]) },
2271
    { "r15", offsetof(CPUState, gpr[15]) },
2272
    { "r16", offsetof(CPUState, gpr[16]) },
2273
    { "r17", offsetof(CPUState, gpr[17]) },
2274
    { "r18", offsetof(CPUState, gpr[18]) },
2275
    { "r19", offsetof(CPUState, gpr[19]) },
2276
    { "r20", offsetof(CPUState, gpr[20]) },
2277
    { "r21", offsetof(CPUState, gpr[21]) },
2278
    { "r22", offsetof(CPUState, gpr[22]) },
2279
    { "r23", offsetof(CPUState, gpr[23]) },
2280
    { "r24", offsetof(CPUState, gpr[24]) },
2281
    { "r25", offsetof(CPUState, gpr[25]) },
2282
    { "r26", offsetof(CPUState, gpr[26]) },
2283
    { "r27", offsetof(CPUState, gpr[27]) },
2284
    { "r28", offsetof(CPUState, gpr[28]) },
2285
    { "r29", offsetof(CPUState, gpr[29]) },
2286
    { "r30", offsetof(CPUState, gpr[30]) },
2287
    { "r31", offsetof(CPUState, gpr[31]) },
2288
    /* Floating point registers */
2289
    { "f0", offsetof(CPUState, fpr[0]) },
2290
    { "f1", offsetof(CPUState, fpr[1]) },
2291
    { "f2", offsetof(CPUState, fpr[2]) },
2292
    { "f3", offsetof(CPUState, fpr[3]) },
2293
    { "f4", offsetof(CPUState, fpr[4]) },
2294
    { "f5", offsetof(CPUState, fpr[5]) },
2295
    { "f6", offsetof(CPUState, fpr[6]) },
2296
    { "f7", offsetof(CPUState, fpr[7]) },
2297
    { "f8", offsetof(CPUState, fpr[8]) },
2298
    { "f9", offsetof(CPUState, fpr[9]) },
2299
    { "f10", offsetof(CPUState, fpr[10]) },
2300
    { "f11", offsetof(CPUState, fpr[11]) },
2301
    { "f12", offsetof(CPUState, fpr[12]) },
2302
    { "f13", offsetof(CPUState, fpr[13]) },
2303
    { "f14", offsetof(CPUState, fpr[14]) },
2304
    { "f15", offsetof(CPUState, fpr[15]) },
2305
    { "f16", offsetof(CPUState, fpr[16]) },
2306
    { "f17", offsetof(CPUState, fpr[17]) },
2307
    { "f18", offsetof(CPUState, fpr[18]) },
2308
    { "f19", offsetof(CPUState, fpr[19]) },
2309
    { "f20", offsetof(CPUState, fpr[20]) },
2310
    { "f21", offsetof(CPUState, fpr[21]) },
2311
    { "f22", offsetof(CPUState, fpr[22]) },
2312
    { "f23", offsetof(CPUState, fpr[23]) },
2313
    { "f24", offsetof(CPUState, fpr[24]) },
2314
    { "f25", offsetof(CPUState, fpr[25]) },
2315
    { "f26", offsetof(CPUState, fpr[26]) },
2316
    { "f27", offsetof(CPUState, fpr[27]) },
2317
    { "f28", offsetof(CPUState, fpr[28]) },
2318
    { "f29", offsetof(CPUState, fpr[29]) },
2319
    { "f30", offsetof(CPUState, fpr[30]) },
2320
    { "f31", offsetof(CPUState, fpr[31]) },
2321
    { "fpscr", offsetof(CPUState, fpscr) },
2322
    /* Next instruction pointer */
2323
    { "nip|pc", offsetof(CPUState, nip) },
2324
    { "lr", offsetof(CPUState, lr) },
2325
    { "ctr", offsetof(CPUState, ctr) },
2326
    { "decr", 0, &monitor_get_decr, },
2327
    { "ccr", 0, &monitor_get_ccr, },
2328
    /* Machine state register */
2329
    { "msr", 0, &monitor_get_msr, },
2330
    { "xer", 0, &monitor_get_xer, },
2331
    { "tbu", 0, &monitor_get_tbu, },
2332
    { "tbl", 0, &monitor_get_tbl, },
2333
#if defined(TARGET_PPC64)
2334
    /* Address space register */
2335
    { "asr", offsetof(CPUState, asr) },
2336
#endif
2337
    /* Segment registers */
2338
    { "sdr1", offsetof(CPUState, sdr1) },
2339
    { "sr0", offsetof(CPUState, sr[0]) },
2340
    { "sr1", offsetof(CPUState, sr[1]) },
2341
    { "sr2", offsetof(CPUState, sr[2]) },
2342
    { "sr3", offsetof(CPUState, sr[3]) },
2343
    { "sr4", offsetof(CPUState, sr[4]) },
2344
    { "sr5", offsetof(CPUState, sr[5]) },
2345
    { "sr6", offsetof(CPUState, sr[6]) },
2346
    { "sr7", offsetof(CPUState, sr[7]) },
2347
    { "sr8", offsetof(CPUState, sr[8]) },
2348
    { "sr9", offsetof(CPUState, sr[9]) },
2349
    { "sr10", offsetof(CPUState, sr[10]) },
2350
    { "sr11", offsetof(CPUState, sr[11]) },
2351
    { "sr12", offsetof(CPUState, sr[12]) },
2352
    { "sr13", offsetof(CPUState, sr[13]) },
2353
    { "sr14", offsetof(CPUState, sr[14]) },
2354
    { "sr15", offsetof(CPUState, sr[15]) },
2355
    /* Too lazy to put BATs and SPRs ... */
2356
#elif defined(TARGET_SPARC)
2357
    { "g0", offsetof(CPUState, gregs[0]) },
2358
    { "g1", offsetof(CPUState, gregs[1]) },
2359
    { "g2", offsetof(CPUState, gregs[2]) },
2360
    { "g3", offsetof(CPUState, gregs[3]) },
2361
    { "g4", offsetof(CPUState, gregs[4]) },
2362
    { "g5", offsetof(CPUState, gregs[5]) },
2363
    { "g6", offsetof(CPUState, gregs[6]) },
2364
    { "g7", offsetof(CPUState, gregs[7]) },
2365
    { "o0", 0, monitor_get_reg },
2366
    { "o1", 1, monitor_get_reg },
2367
    { "o2", 2, monitor_get_reg },
2368
    { "o3", 3, monitor_get_reg },
2369
    { "o4", 4, monitor_get_reg },
2370
    { "o5", 5, monitor_get_reg },
2371
    { "o6", 6, monitor_get_reg },
2372
    { "o7", 7, monitor_get_reg },
2373
    { "l0", 8, monitor_get_reg },
2374
    { "l1", 9, monitor_get_reg },
2375
    { "l2", 10, monitor_get_reg },
2376
    { "l3", 11, monitor_get_reg },
2377
    { "l4", 12, monitor_get_reg },
2378
    { "l5", 13, monitor_get_reg },
2379
    { "l6", 14, monitor_get_reg },
2380
    { "l7", 15, monitor_get_reg },
2381
    { "i0", 16, monitor_get_reg },
2382
    { "i1", 17, monitor_get_reg },
2383
    { "i2", 18, monitor_get_reg },
2384
    { "i3", 19, monitor_get_reg },
2385
    { "i4", 20, monitor_get_reg },
2386
    { "i5", 21, monitor_get_reg },
2387
    { "i6", 22, monitor_get_reg },
2388
    { "i7", 23, monitor_get_reg },
2389
    { "pc", offsetof(CPUState, pc) },
2390
    { "npc", offsetof(CPUState, npc) },
2391
    { "y", offsetof(CPUState, y) },
2392
#ifndef TARGET_SPARC64
2393
    { "psr", 0, &monitor_get_psr, },
2394
    { "wim", offsetof(CPUState, wim) },
2395
#endif
2396
    { "tbr", offsetof(CPUState, tbr) },
2397
    { "fsr", offsetof(CPUState, fsr) },
2398
    { "f0", offsetof(CPUState, fpr[0]) },
2399
    { "f1", offsetof(CPUState, fpr[1]) },
2400
    { "f2", offsetof(CPUState, fpr[2]) },
2401
    { "f3", offsetof(CPUState, fpr[3]) },
2402
    { "f4", offsetof(CPUState, fpr[4]) },
2403
    { "f5", offsetof(CPUState, fpr[5]) },
2404
    { "f6", offsetof(CPUState, fpr[6]) },
2405
    { "f7", offsetof(CPUState, fpr[7]) },
2406
    { "f8", offsetof(CPUState, fpr[8]) },
2407
    { "f9", offsetof(CPUState, fpr[9]) },
2408
    { "f10", offsetof(CPUState, fpr[10]) },
2409
    { "f11", offsetof(CPUState, fpr[11]) },
2410
    { "f12", offsetof(CPUState, fpr[12]) },
2411
    { "f13", offsetof(CPUState, fpr[13]) },
2412
    { "f14", offsetof(CPUState, fpr[14]) },
2413
    { "f15", offsetof(CPUState, fpr[15]) },
2414
    { "f16", offsetof(CPUState, fpr[16]) },
2415
    { "f17", offsetof(CPUState, fpr[17]) },
2416
    { "f18", offsetof(CPUState, fpr[18]) },
2417
    { "f19", offsetof(CPUState, fpr[19]) },
2418
    { "f20", offsetof(CPUState, fpr[20]) },
2419
    { "f21", offsetof(CPUState, fpr[21]) },
2420
    { "f22", offsetof(CPUState, fpr[22]) },
2421
    { "f23", offsetof(CPUState, fpr[23]) },
2422
    { "f24", offsetof(CPUState, fpr[24]) },
2423
    { "f25", offsetof(CPUState, fpr[25]) },
2424
    { "f26", offsetof(CPUState, fpr[26]) },
2425
    { "f27", offsetof(CPUState, fpr[27]) },
2426
    { "f28", offsetof(CPUState, fpr[28]) },
2427
    { "f29", offsetof(CPUState, fpr[29]) },
2428
    { "f30", offsetof(CPUState, fpr[30]) },
2429
    { "f31", offsetof(CPUState, fpr[31]) },
2430
#ifdef TARGET_SPARC64
2431
    { "f32", offsetof(CPUState, fpr[32]) },
2432
    { "f34", offsetof(CPUState, fpr[34]) },
2433
    { "f36", offsetof(CPUState, fpr[36]) },
2434
    { "f38", offsetof(CPUState, fpr[38]) },
2435
    { "f40", offsetof(CPUState, fpr[40]) },
2436
    { "f42", offsetof(CPUState, fpr[42]) },
2437
    { "f44", offsetof(CPUState, fpr[44]) },
2438
    { "f46", offsetof(CPUState, fpr[46]) },
2439
    { "f48", offsetof(CPUState, fpr[48]) },
2440
    { "f50", offsetof(CPUState, fpr[50]) },
2441
    { "f52", offsetof(CPUState, fpr[52]) },
2442
    { "f54", offsetof(CPUState, fpr[54]) },
2443
    { "f56", offsetof(CPUState, fpr[56]) },
2444
    { "f58", offsetof(CPUState, fpr[58]) },
2445
    { "f60", offsetof(CPUState, fpr[60]) },
2446
    { "f62", offsetof(CPUState, fpr[62]) },
2447
    { "asi", offsetof(CPUState, asi) },
2448
    { "pstate", offsetof(CPUState, pstate) },
2449
    { "cansave", offsetof(CPUState, cansave) },
2450
    { "canrestore", offsetof(CPUState, canrestore) },
2451
    { "otherwin", offsetof(CPUState, otherwin) },
2452
    { "wstate", offsetof(CPUState, wstate) },
2453
    { "cleanwin", offsetof(CPUState, cleanwin) },
2454
    { "fprs", offsetof(CPUState, fprs) },
2455
#endif
2456
#endif
2457
    { NULL },
2458
};
2459

    
2460
static void expr_error(Monitor *mon, const char *msg)
2461
{
2462
    monitor_printf(mon, "%s\n", msg);
2463
    longjmp(expr_env, 1);
2464
}
2465

    
2466
/* return 0 if OK, -1 if not found, -2 if no CPU defined */
2467
static int get_monitor_def(target_long *pval, const char *name)
2468
{
2469
    const MonitorDef *md;
2470
    void *ptr;
2471

    
2472
    for(md = monitor_defs; md->name != NULL; md++) {
2473
        if (compare_cmd(name, md->name)) {
2474
            if (md->get_value) {
2475
                *pval = md->get_value(md, md->offset);
2476
            } else {
2477
                CPUState *env = mon_get_cpu();
2478
                if (!env)
2479
                    return -2;
2480
                ptr = (uint8_t *)env + md->offset;
2481
                switch(md->type) {
2482
                case MD_I32:
2483
                    *pval = *(int32_t *)ptr;
2484
                    break;
2485
                case MD_TLONG:
2486
                    *pval = *(target_long *)ptr;
2487
                    break;
2488
                default:
2489
                    *pval = 0;
2490
                    break;
2491
                }
2492
            }
2493
            return 0;
2494
        }
2495
    }
2496
    return -1;
2497
}
2498

    
2499
static void next(void)
2500
{
2501
    if (*pch != '\0') {
2502
        pch++;
2503
        while (qemu_isspace(*pch))
2504
            pch++;
2505
    }
2506
}
2507

    
2508
static int64_t expr_sum(Monitor *mon);
2509

    
2510
static int64_t expr_unary(Monitor *mon)
2511
{
2512
    int64_t n;
2513
    char *p;
2514
    int ret;
2515

    
2516
    switch(*pch) {
2517
    case '+':
2518
        next();
2519
        n = expr_unary(mon);
2520
        break;
2521
    case '-':
2522
        next();
2523
        n = -expr_unary(mon);
2524
        break;
2525
    case '~':
2526
        next();
2527
        n = ~expr_unary(mon);
2528
        break;
2529
    case '(':
2530
        next();
2531
        n = expr_sum(mon);
2532
        if (*pch != ')') {
2533
            expr_error(mon, "')' expected");
2534
        }
2535
        next();
2536
        break;
2537
    case '\'':
2538
        pch++;
2539
        if (*pch == '\0')
2540
            expr_error(mon, "character constant expected");
2541
        n = *pch;
2542
        pch++;
2543
        if (*pch != '\'')
2544
            expr_error(mon, "missing terminating \' character");
2545
        next();
2546
        break;
2547
    case '$':
2548
        {
2549
            char buf[128], *q;
2550
            target_long reg=0;
2551

    
2552
            pch++;
2553
            q = buf;
2554
            while ((*pch >= 'a' && *pch <= 'z') ||
2555
                   (*pch >= 'A' && *pch <= 'Z') ||
2556
                   (*pch >= '0' && *pch <= '9') ||
2557
                   *pch == '_' || *pch == '.') {
2558
                if ((q - buf) < sizeof(buf) - 1)
2559
                    *q++ = *pch;
2560
                pch++;
2561
            }
2562
            while (qemu_isspace(*pch))
2563
                pch++;
2564
            *q = 0;
2565
            ret = get_monitor_def(&reg, buf);
2566
            if (ret == -1)
2567
                expr_error(mon, "unknown register");
2568
            else if (ret == -2)
2569
                expr_error(mon, "no cpu defined");
2570
            n = reg;
2571
        }
2572
        break;
2573
    case '\0':
2574
        expr_error(mon, "unexpected end of expression");
2575
        n = 0;
2576
        break;
2577
    default:
2578
#if TARGET_PHYS_ADDR_BITS > 32
2579
        n = strtoull(pch, &p, 0);
2580
#else
2581
        n = strtoul(pch, &p, 0);
2582
#endif
2583
        if (pch == p) {
2584
            expr_error(mon, "invalid char in expression");
2585
        }
2586
        pch = p;
2587
        while (qemu_isspace(*pch))
2588
            pch++;
2589
        break;
2590
    }
2591
    return n;
2592
}
2593

    
2594

    
2595
static int64_t expr_prod(Monitor *mon)
2596
{
2597
    int64_t val, val2;
2598
    int op;
2599

    
2600
    val = expr_unary(mon);
2601
    for(;;) {
2602
        op = *pch;
2603
        if (op != '*' && op != '/' && op != '%')
2604
            break;
2605
        next();
2606
        val2 = expr_unary(mon);
2607
        switch(op) {
2608
        default:
2609
        case '*':
2610
            val *= val2;
2611
            break;
2612
        case '/':
2613
        case '%':
2614
            if (val2 == 0)
2615
                expr_error(mon, "division by zero");
2616
            if (op == '/')
2617
                val /= val2;
2618
            else
2619
                val %= val2;
2620
            break;
2621
        }
2622
    }
2623
    return val;
2624
}
2625

    
2626
static int64_t expr_logic(Monitor *mon)
2627
{
2628
    int64_t val, val2;
2629
    int op;
2630

    
2631
    val = expr_prod(mon);
2632
    for(;;) {
2633
        op = *pch;
2634
        if (op != '&' && op != '|' && op != '^')
2635
            break;
2636
        next();
2637
        val2 = expr_prod(mon);
2638
        switch(op) {
2639
        default:
2640
        case '&':
2641
            val &= val2;
2642
            break;
2643
        case '|':
2644
            val |= val2;
2645
            break;
2646
        case '^':
2647
            val ^= val2;
2648
            break;
2649
        }
2650
    }
2651
    return val;
2652
}
2653

    
2654
static int64_t expr_sum(Monitor *mon)
2655
{
2656
    int64_t val, val2;
2657
    int op;
2658

    
2659
    val = expr_logic(mon);
2660
    for(;;) {
2661
        op = *pch;
2662
        if (op != '+' && op != '-')
2663
            break;
2664
        next();
2665
        val2 = expr_logic(mon);
2666
        if (op == '+')
2667
            val += val2;
2668
        else
2669
            val -= val2;
2670
    }
2671
    return val;
2672
}
2673

    
2674
static int get_expr(Monitor *mon, int64_t *pval, const char **pp)
2675
{
2676
    pch = *pp;
2677
    if (setjmp(expr_env)) {
2678
        *pp = pch;
2679
        return -1;
2680
    }
2681
    while (qemu_isspace(*pch))
2682
        pch++;
2683
    *pval = expr_sum(mon);
2684
    *pp = pch;
2685
    return 0;
2686
}
2687

    
2688
static int get_str(char *buf, int buf_size, const char **pp)
2689
{
2690
    const char *p;
2691
    char *q;
2692
    int c;
2693

    
2694
    q = buf;
2695
    p = *pp;
2696
    while (qemu_isspace(*p))
2697
        p++;
2698
    if (*p == '\0') {
2699
    fail:
2700
        *q = '\0';
2701
        *pp = p;
2702
        return -1;
2703
    }
2704
    if (*p == '\"') {
2705
        p++;
2706
        while (*p != '\0' && *p != '\"') {
2707
            if (*p == '\\') {
2708
                p++;
2709
                c = *p++;
2710
                switch(c) {
2711
                case 'n':
2712
                    c = '\n';
2713
                    break;
2714
                case 'r':
2715
                    c = '\r';
2716
                    break;
2717
                case '\\':
2718
                case '\'':
2719
                case '\"':
2720
                    break;
2721
                default:
2722
                    qemu_printf("unsupported escape code: '\\%c'\n", c);
2723
                    goto fail;
2724
                }
2725
                if ((q - buf) < buf_size - 1) {
2726
                    *q++ = c;
2727
                }
2728
            } else {
2729
                if ((q - buf) < buf_size - 1) {
2730
                    *q++ = *p;
2731
                }
2732
                p++;
2733
            }
2734
        }
2735
        if (*p != '\"') {
2736
            qemu_printf("unterminated string\n");
2737
            goto fail;
2738
        }
2739
        p++;
2740
    } else {
2741
        while (*p != '\0' && !qemu_isspace(*p)) {
2742
            if ((q - buf) < buf_size - 1) {
2743
                *q++ = *p;
2744
            }
2745
            p++;
2746
        }
2747
    }
2748
    *q = '\0';
2749
    *pp = p;
2750
    return 0;
2751
}
2752

    
2753
/*
2754
 * Store the command-name in cmdname, and return a pointer to
2755
 * the remaining of the command string.
2756
 */
2757
static const char *get_command_name(const char *cmdline,
2758
                                    char *cmdname, size_t nlen)
2759
{
2760
    size_t len;
2761
    const char *p, *pstart;
2762

    
2763
    p = cmdline;
2764
    while (qemu_isspace(*p))
2765
        p++;
2766
    if (*p == '\0')
2767
        return NULL;
2768
    pstart = p;
2769
    while (*p != '\0' && *p != '/' && !qemu_isspace(*p))
2770
        p++;
2771
    len = p - pstart;
2772
    if (len > nlen - 1)
2773
        len = nlen - 1;
2774
    memcpy(cmdname, pstart, len);
2775
    cmdname[len] = '\0';
2776
    return p;
2777
}
2778

    
2779
/**
2780
 * Read key of 'type' into 'key' and return the current
2781
 * 'type' pointer.
2782
 */
2783
static char *key_get_info(const char *type, char **key)
2784
{
2785
    size_t len;
2786
    char *p, *str;
2787

    
2788
    if (*type == ',')
2789
        type++;
2790

    
2791
    p = strchr(type, ':');
2792
    if (!p) {
2793
        *key = NULL;
2794
        return NULL;
2795
    }
2796
    len = p - type;
2797

    
2798
    str = qemu_malloc(len + 1);
2799
    memcpy(str, type, len);
2800
    str[len] = '\0';
2801

    
2802
    *key = str;
2803
    return ++p;
2804
}
2805

    
2806
static int default_fmt_format = 'x';
2807
static int default_fmt_size = 4;
2808

    
2809
#define MAX_ARGS 16
2810

    
2811
static const mon_cmd_t *monitor_parse_command(Monitor *mon,
2812
                                              const char *cmdline,
2813
                                              QDict *qdict)
2814
{
2815
    const char *p, *typestr;
2816
    int c;
2817
    const mon_cmd_t *cmd;
2818
    char cmdname[256];
2819
    char buf[1024];
2820
    char *key;
2821

    
2822
#ifdef DEBUG
2823
    monitor_printf(mon, "command='%s'\n", cmdline);
2824
#endif
2825

    
2826
    /* extract the command name */
2827
    p = get_command_name(cmdline, cmdname, sizeof(cmdname));
2828
    if (!p)
2829
        return NULL;
2830

    
2831
    /* find the command */
2832
    for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
2833
        if (compare_cmd(cmdname, cmd->name))
2834
            break;
2835
    }
2836

    
2837
    if (cmd->name == NULL) {
2838
        monitor_printf(mon, "unknown command: '%s'\n", cmdname);
2839
        return NULL;
2840
    }
2841

    
2842
    /* parse the parameters */
2843
    typestr = cmd->args_type;
2844
    for(;;) {
2845
        typestr = key_get_info(typestr, &key);
2846
        if (!typestr)
2847
            break;
2848
        c = *typestr;
2849
        typestr++;
2850
        switch(c) {
2851
        case 'F':
2852
        case 'B':
2853
        case 's':
2854
            {
2855
                int ret;
2856

    
2857
                while (qemu_isspace(*p))
2858
                    p++;
2859
                if (*typestr == '?') {
2860
                    typestr++;
2861
                    if (*p == '\0') {
2862
                        /* no optional string: NULL argument */
2863
                        break;
2864
                    }
2865
                }
2866
                ret = get_str(buf, sizeof(buf), &p);
2867
                if (ret < 0) {
2868
                    switch(c) {
2869
                    case 'F':
2870
                        monitor_printf(mon, "%s: filename expected\n",
2871
                                       cmdname);
2872
                        break;
2873
                    case 'B':
2874
                        monitor_printf(mon, "%s: block device name expected\n",
2875
                                       cmdname);
2876
                        break;
2877
                    default:
2878
                        monitor_printf(mon, "%s: string expected\n", cmdname);
2879
                        break;
2880
                    }
2881
                    goto fail;
2882
                }
2883
                qdict_put(qdict, key, qstring_from_str(buf));
2884
            }
2885
            break;
2886
        case '/':
2887
            {
2888
                int count, format, size;
2889

    
2890
                while (qemu_isspace(*p))
2891
                    p++;
2892
                if (*p == '/') {
2893
                    /* format found */
2894
                    p++;
2895
                    count = 1;
2896
                    if (qemu_isdigit(*p)) {
2897
                        count = 0;
2898
                        while (qemu_isdigit(*p)) {
2899
                            count = count * 10 + (*p - '0');
2900
                            p++;
2901
                        }
2902
                    }
2903
                    size = -1;
2904
                    format = -1;
2905
                    for(;;) {
2906
                        switch(*p) {
2907
                        case 'o':
2908
                        case 'd':
2909
                        case 'u':
2910
                        case 'x':
2911
                        case 'i':
2912
                        case 'c':
2913
                            format = *p++;
2914
                            break;
2915
                        case 'b':
2916
                            size = 1;
2917
                            p++;
2918
                            break;
2919
                        case 'h':
2920
                            size = 2;
2921
                            p++;
2922
                            break;
2923
                        case 'w':
2924
                            size = 4;
2925
                            p++;
2926
                            break;
2927
                        case 'g':
2928
                        case 'L':
2929
                            size = 8;
2930
                            p++;
2931
                            break;
2932
                        default:
2933
                            goto next;
2934
                        }
2935
                    }
2936
                next:
2937
                    if (*p != '\0' && !qemu_isspace(*p)) {
2938
                        monitor_printf(mon, "invalid char in format: '%c'\n",
2939
                                       *p);
2940
                        goto fail;
2941
                    }
2942
                    if (format < 0)
2943
                        format = default_fmt_format;
2944
                    if (format != 'i') {
2945
                        /* for 'i', not specifying a size gives -1 as size */
2946
                        if (size < 0)
2947
                            size = default_fmt_size;
2948
                        default_fmt_size = size;
2949
                    }
2950
                    default_fmt_format = format;
2951
                } else {
2952
                    count = 1;
2953
                    format = default_fmt_format;
2954
                    if (format != 'i') {
2955
                        size = default_fmt_size;
2956
                    } else {
2957
                        size = -1;
2958
                    }
2959
                }
2960
                qdict_put(qdict, "count", qint_from_int(count));
2961
                qdict_put(qdict, "format", qint_from_int(format));
2962
                qdict_put(qdict, "size", qint_from_int(size));
2963
            }
2964
            break;
2965
        case 'i':
2966
        case 'l':
2967
            {
2968
                int64_t val;
2969

    
2970
                while (qemu_isspace(*p))
2971
                    p++;
2972
                if (*typestr == '?' || *typestr == '.') {
2973
                    if (*typestr == '?') {
2974
                        if (*p == '\0') {
2975
                            typestr++;
2976
                            break;
2977
                        }
2978
                    } else {
2979
                        if (*p == '.') {
2980
                            p++;
2981
                            while (qemu_isspace(*p))
2982
                                p++;
2983
                        } else {
2984
                            typestr++;
2985
                            break;
2986
                        }
2987
                    }
2988
                    typestr++;
2989
                }
2990
                if (get_expr(mon, &val, &p))
2991
                    goto fail;
2992
                /* Check if 'i' is greater than 32-bit */
2993
                if ((c == 'i') && ((val >> 32) & 0xffffffff)) {
2994
                    monitor_printf(mon, "\'%s\' has failed: ", cmdname);
2995
                    monitor_printf(mon, "integer is for 32-bit values\n");
2996
                    goto fail;
2997
                }
2998
                qdict_put(qdict, key, qint_from_int(val));
2999
            }
3000
            break;
3001
        case '-':
3002
            {
3003
                int has_option;
3004
                /* option */
3005

    
3006
                c = *typestr++;
3007
                if (c == '\0')
3008
                    goto bad_type;
3009
                while (qemu_isspace(*p))
3010
                    p++;
3011
                has_option = 0;
3012
                if (*p == '-') {
3013
                    p++;
3014
                    if (*p != c) {
3015
                        monitor_printf(mon, "%s: unsupported option -%c\n",
3016
                                       cmdname, *p);
3017
                        goto fail;
3018
                    }
3019
                    p++;
3020
                    has_option = 1;
3021
                }
3022
                qdict_put(qdict, key, qint_from_int(has_option));
3023
            }
3024
            break;
3025
        default:
3026
        bad_type:
3027
            monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);
3028
            goto fail;
3029
        }
3030
        qemu_free(key);
3031
        key = NULL;
3032
    }
3033
    /* check that all arguments were parsed */
3034
    while (qemu_isspace(*p))
3035
        p++;
3036
    if (*p != '\0') {
3037
        monitor_printf(mon, "%s: extraneous characters at the end of line\n",
3038
                       cmdname);
3039
        goto fail;
3040
    }
3041

    
3042
    return cmd;
3043

    
3044
fail:
3045
    qemu_free(key);
3046
    return NULL;
3047
}
3048

    
3049
static void monitor_handle_command(Monitor *mon, const char *cmdline)
3050
{
3051
    QDict *qdict;
3052
    const mon_cmd_t *cmd;
3053

    
3054
    qdict = qdict_new();
3055

    
3056
    cmd = monitor_parse_command(mon, cmdline, qdict);
3057
    if (!cmd)
3058
        goto out;
3059

    
3060
    qemu_errors_to_mon(mon);
3061

    
3062
    if (monitor_handler_ported(cmd)) {
3063
        QObject *data = NULL;
3064

    
3065
        cmd->mhandler.cmd_new(mon, qdict, &data);
3066
        if (data)
3067
            cmd->user_print(mon, data);
3068

    
3069
        qobject_decref(data);
3070
    } else {
3071
        cmd->mhandler.cmd(mon, qdict);
3072
    }
3073

    
3074
   qemu_errors_to_previous();
3075

    
3076
out:
3077
    QDECREF(qdict);
3078
}
3079

    
3080
static void cmd_completion(const char *name, const char *list)
3081
{
3082
    const char *p, *pstart;
3083
    char cmd[128];
3084
    int len;
3085

    
3086
    p = list;
3087
    for(;;) {
3088
        pstart = p;
3089
        p = strchr(p, '|');
3090
        if (!p)
3091
            p = pstart + strlen(pstart);
3092
        len = p - pstart;
3093
        if (len > sizeof(cmd) - 2)
3094
            len = sizeof(cmd) - 2;
3095
        memcpy(cmd, pstart, len);
3096
        cmd[len] = '\0';
3097
        if (name[0] == '\0' || !strncmp(name, cmd, strlen(name))) {
3098
            readline_add_completion(cur_mon->rs, cmd);
3099
        }
3100
        if (*p == '\0')
3101
            break;
3102
        p++;
3103
    }
3104
}
3105

    
3106
static void file_completion(const char *input)
3107
{
3108
    DIR *ffs;
3109
    struct dirent *d;
3110
    char path[1024];
3111
    char file[1024], file_prefix[1024];
3112
    int input_path_len;
3113
    const char *p;
3114

    
3115
    p = strrchr(input, '/');
3116
    if (!p) {
3117
        input_path_len = 0;
3118
        pstrcpy(file_prefix, sizeof(file_prefix), input);
3119
        pstrcpy(path, sizeof(path), ".");
3120
    } else {
3121
        input_path_len = p - input + 1;
3122
        memcpy(path, input, input_path_len);
3123
        if (input_path_len > sizeof(path) - 1)
3124
            input_path_len = sizeof(path) - 1;
3125
        path[input_path_len] = '\0';
3126
        pstrcpy(file_prefix, sizeof(file_prefix), p + 1);
3127
    }
3128
#ifdef DEBUG_COMPLETION
3129
    monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",
3130
                   input, path, file_prefix);
3131
#endif
3132
    ffs = opendir(path);
3133
    if (!ffs)
3134
        return;
3135
    for(;;) {
3136
        struct stat sb;
3137
        d = readdir(ffs);
3138
        if (!d)
3139
            break;
3140
        if (strstart(d->d_name, file_prefix, NULL)) {
3141
            memcpy(file, input, input_path_len);
3142
            if (input_path_len < sizeof(file))
3143
                pstrcpy(file + input_path_len, sizeof(file) - input_path_len,
3144
                        d->d_name);
3145
            /* stat the file to find out if it's a directory.
3146
             * In that case add a slash to speed up typing long paths
3147
             */
3148
            stat(file, &sb);
3149
            if(S_ISDIR(sb.st_mode))
3150
                pstrcat(file, sizeof(file), "/");
3151
            readline_add_completion(cur_mon->rs, file);
3152
        }
3153
    }
3154
    closedir(ffs);
3155
}
3156

    
3157
static void block_completion_it(void *opaque, BlockDriverState *bs)
3158
{
3159
    const char *name = bdrv_get_device_name(bs);
3160
    const char *input = opaque;
3161

    
3162
    if (input[0] == '\0' ||
3163
        !strncmp(name, (char *)input, strlen(input))) {
3164
        readline_add_completion(cur_mon->rs, name);
3165
    }
3166
}
3167

    
3168
/* NOTE: this parser is an approximate form of the real command parser */
3169
static void parse_cmdline(const char *cmdline,
3170
                         int *pnb_args, char **args)
3171
{
3172
    const char *p;
3173
    int nb_args, ret;
3174
    char buf[1024];
3175

    
3176
    p = cmdline;
3177
    nb_args = 0;
3178
    for(;;) {
3179
        while (qemu_isspace(*p))
3180
            p++;
3181
        if (*p == '\0')
3182
            break;
3183
        if (nb_args >= MAX_ARGS)
3184
            break;
3185
        ret = get_str(buf, sizeof(buf), &p);
3186
        args[nb_args] = qemu_strdup(buf);
3187
        nb_args++;
3188
        if (ret < 0)
3189
            break;
3190
    }
3191
    *pnb_args = nb_args;
3192
}
3193

    
3194
static const char *next_arg_type(const char *typestr)
3195
{
3196
    const char *p = strchr(typestr, ':');
3197
    return (p != NULL ? ++p : typestr);
3198
}
3199

    
3200
static void monitor_find_completion(const char *cmdline)
3201
{
3202
    const char *cmdname;
3203
    char *args[MAX_ARGS];
3204
    int nb_args, i, len;
3205
    const char *ptype, *str;
3206
    const mon_cmd_t *cmd;
3207
    const KeyDef *key;
3208

    
3209
    parse_cmdline(cmdline, &nb_args, args);
3210
#ifdef DEBUG_COMPLETION
3211
    for(i = 0; i < nb_args; i++) {
3212
        monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);
3213
    }
3214
#endif
3215

    
3216
    /* if the line ends with a space, it means we want to complete the
3217
       next arg */
3218
    len = strlen(cmdline);
3219
    if (len > 0 && qemu_isspace(cmdline[len - 1])) {
3220
        if (nb_args >= MAX_ARGS)
3221
            return;
3222
        args[nb_args++] = qemu_strdup("");
3223
    }
3224
    if (nb_args <= 1) {
3225
        /* command completion */
3226
        if (nb_args == 0)
3227
            cmdname = "";
3228
        else
3229
            cmdname = args[0];
3230
        readline_set_completion_index(cur_mon->rs, strlen(cmdname));
3231
        for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
3232
            cmd_completion(cmdname, cmd->name);
3233
        }
3234
    } else {
3235
        /* find the command */
3236
        for(cmd = mon_cmds; cmd->name != NULL; cmd++) {
3237
            if (compare_cmd(args[0], cmd->name))
3238
                goto found;
3239
        }
3240
        return;
3241
    found:
3242
        ptype = next_arg_type(cmd->args_type);
3243
        for(i = 0; i < nb_args - 2; i++) {
3244
            if (*ptype != '\0') {
3245
                ptype = next_arg_type(ptype);
3246
                while (*ptype == '?')
3247
                    ptype = next_arg_type(ptype);
3248
            }
3249
        }
3250
        str = args[nb_args - 1];
3251
        if (*ptype == '-' && ptype[1] != '\0') {
3252
            ptype += 2;
3253
        }
3254
        switch(*ptype) {
3255
        case 'F':
3256
            /* file completion */
3257
            readline_set_completion_index(cur_mon->rs, strlen(str));
3258
            file_completion(str);
3259
            break;
3260
        case 'B':
3261
            /* block device name completion */
3262
            readline_set_completion_index(cur_mon->rs, strlen(str));
3263
            bdrv_iterate(block_completion_it, (void *)str);
3264
            break;
3265
        case 's':
3266
            /* XXX: more generic ? */
3267
            if (!strcmp(cmd->name, "info")) {
3268
                readline_set_completion_index(cur_mon->rs, strlen(str));
3269
                for(cmd = info_cmds; cmd->name != NULL; cmd++) {
3270
                    cmd_completion(str, cmd->name);
3271
                }
3272
            } else if (!strcmp(cmd->name, "sendkey")) {
3273
                char *sep = strrchr(str, '-');
3274
                if (sep)
3275
                    str = sep + 1;
3276
                readline_set_completion_index(cur_mon->rs, strlen(str));
3277
                for(key = key_defs; key->name != NULL; key++) {
3278
                    cmd_completion(str, key->name);
3279
                }
3280
            } else if (!strcmp(cmd->name, "help|?")) {
3281
                readline_set_completion_index(cur_mon->rs, strlen(str));
3282
                for (cmd = mon_cmds; cmd->name != NULL; cmd++) {
3283
                    cmd_completion(str, cmd->name);
3284
                }
3285
            }
3286
            break;
3287
        default:
3288
            break;
3289
        }
3290
    }
3291
    for(i = 0; i < nb_args; i++)
3292
        qemu_free(args[i]);
3293
}
3294

    
3295
static int monitor_can_read(void *opaque)
3296
{
3297
    Monitor *mon = opaque;
3298

    
3299
    return (mon->suspend_cnt == 0) ? 128 : 0;
3300
}
3301

    
3302
static void monitor_read(void *opaque, const uint8_t *buf, int size)
3303
{
3304
    Monitor *old_mon = cur_mon;
3305
    int i;
3306

    
3307
    cur_mon = opaque;
3308

    
3309
    if (cur_mon->rs) {
3310
        for (i = 0; i < size; i++)
3311
            readline_handle_byte(cur_mon->rs, buf[i]);
3312
    } else {
3313
        if (size == 0 || buf[size - 1] != 0)
3314
            monitor_printf(cur_mon, "corrupted command\n");
3315
        else
3316
            monitor_handle_command(cur_mon, (char *)buf);
3317
    }
3318

    
3319
    cur_mon = old_mon;
3320
}
3321

    
3322
static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)
3323
{
3324
    monitor_suspend(mon);
3325
    monitor_handle_command(mon, cmdline);
3326
    monitor_resume(mon);
3327
}
3328

    
3329
int monitor_suspend(Monitor *mon)
3330
{
3331
    if (!mon->rs)
3332
        return -ENOTTY;
3333
    mon->suspend_cnt++;
3334
    return 0;
3335
}
3336

    
3337
void monitor_resume(Monitor *mon)
3338
{
3339
    if (!mon->rs)
3340
        return;
3341
    if (--mon->suspend_cnt == 0)
3342
        readline_show_prompt(mon->rs);
3343
}
3344

    
3345
static void monitor_event(void *opaque, int event)
3346
{
3347
    Monitor *mon = opaque;
3348

    
3349
    switch (event) {
3350
    case CHR_EVENT_MUX_IN:
3351
        mon->mux_out = 0;
3352
        if (mon->reset_seen) {
3353
            readline_restart(mon->rs);
3354
            monitor_resume(mon);
3355
            monitor_flush(mon);
3356
        } else {
3357
            mon->suspend_cnt = 0;
3358
        }
3359
        break;
3360

    
3361
    case CHR_EVENT_MUX_OUT:
3362
        if (mon->reset_seen) {
3363
            if (mon->suspend_cnt == 0) {
3364
                monitor_printf(mon, "\n");
3365
            }
3366
            monitor_flush(mon);
3367
            monitor_suspend(mon);
3368
        } else {
3369
            mon->suspend_cnt++;
3370
        }
3371
        mon->mux_out = 1;
3372
        break;
3373

    
3374
    case CHR_EVENT_RESET:
3375
        monitor_printf(mon, "QEMU %s monitor - type 'help' for more "
3376
                       "information\n", QEMU_VERSION);
3377
        if (!mon->mux_out) {
3378
            readline_show_prompt(mon->rs);
3379
        }
3380
        mon->reset_seen = 1;
3381
        break;
3382
    }
3383
}
3384

    
3385

    
3386
/*
3387
 * Local variables:
3388
 *  c-indent-level: 4
3389
 *  c-basic-offset: 4
3390
 *  tab-width: 8
3391
 * End:
3392
 */
3393

    
3394
void monitor_init(CharDriverState *chr, int flags)
3395
{
3396
    static int is_first_init = 1;
3397
    Monitor *mon;
3398

    
3399
    if (is_first_init) {
3400
        key_timer = qemu_new_timer(vm_clock, release_keys, NULL);
3401
        is_first_init = 0;
3402
    }
3403

    
3404
    mon = qemu_mallocz(sizeof(*mon));
3405

    
3406
    mon->chr = chr;
3407
    mon->flags = flags;
3408
    if (flags & MONITOR_USE_READLINE) {
3409
        mon->rs = readline_init(mon, monitor_find_completion);
3410
        monitor_read_command(mon, 0);
3411
    }
3412

    
3413
    qemu_chr_add_handlers(chr, monitor_can_read, monitor_read, monitor_event,
3414
                          mon);
3415

    
3416
    QLIST_INSERT_HEAD(&mon_list, mon, entry);
3417
    if (!cur_mon || (flags & MONITOR_IS_DEFAULT))
3418
        cur_mon = mon;
3419
}
3420

    
3421
static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque)
3422
{
3423
    BlockDriverState *bs = opaque;
3424
    int ret = 0;
3425

    
3426
    if (bdrv_set_key(bs, password) != 0) {
3427
        monitor_printf(mon, "invalid password\n");
3428
        ret = -EPERM;
3429
    }
3430
    if (mon->password_completion_cb)
3431
        mon->password_completion_cb(mon->password_opaque, ret);
3432

    
3433
    monitor_read_command(mon, 1);
3434
}
3435

    
3436
void monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
3437
                                 BlockDriverCompletionFunc *completion_cb,
3438
                                 void *opaque)
3439
{
3440
    int err;
3441

    
3442
    if (!bdrv_key_required(bs)) {
3443
        if (completion_cb)
3444
            completion_cb(opaque, 0);
3445
        return;
3446
    }
3447

    
3448
    monitor_printf(mon, "%s (%s) is encrypted.\n", bdrv_get_device_name(bs),
3449
                   bdrv_get_encrypted_filename(bs));
3450

    
3451
    mon->password_completion_cb = completion_cb;
3452
    mon->password_opaque = opaque;
3453

    
3454
    err = monitor_read_password(mon, bdrv_password_cb, bs);
3455

    
3456
    if (err && completion_cb)
3457
        completion_cb(opaque, err);
3458
}
3459

    
3460
typedef struct QemuErrorSink QemuErrorSink;
3461
struct QemuErrorSink {
3462
    enum {
3463
        ERR_SINK_FILE,
3464
        ERR_SINK_MONITOR,
3465
    } dest;
3466
    union {
3467
        FILE    *fp;
3468
        Monitor *mon;
3469
    };
3470
    QemuErrorSink *previous;
3471
};
3472

    
3473
static QemuErrorSink *qemu_error_sink;
3474

    
3475
void qemu_errors_to_file(FILE *fp)
3476
{
3477
    QemuErrorSink *sink;
3478

    
3479
    sink = qemu_mallocz(sizeof(*sink));
3480
    sink->dest = ERR_SINK_FILE;
3481
    sink->fp = fp;
3482
    sink->previous = qemu_error_sink;
3483
    qemu_error_sink = sink;
3484
}
3485

    
3486
void qemu_errors_to_mon(Monitor *mon)
3487
{
3488
    QemuErrorSink *sink;
3489

    
3490
    sink = qemu_mallocz(sizeof(*sink));
3491
    sink->dest = ERR_SINK_MONITOR;
3492
    sink->mon = mon;
3493
    sink->previous = qemu_error_sink;
3494
    qemu_error_sink = sink;
3495
}
3496

    
3497
void qemu_errors_to_previous(void)
3498
{
3499
    QemuErrorSink *sink;
3500

    
3501
    assert(qemu_error_sink != NULL);
3502
    sink = qemu_error_sink;
3503
    qemu_error_sink = sink->previous;
3504
    qemu_free(sink);
3505
}
3506

    
3507
void qemu_error(const char *fmt, ...)
3508
{
3509
    va_list args;
3510

    
3511
    assert(qemu_error_sink != NULL);
3512
    switch (qemu_error_sink->dest) {
3513
    case ERR_SINK_FILE:
3514
        va_start(args, fmt);
3515
        vfprintf(qemu_error_sink->fp, fmt, args);
3516
        va_end(args);
3517
        break;
3518
    case ERR_SINK_MONITOR:
3519
        va_start(args, fmt);
3520
        monitor_vprintf(qemu_error_sink->mon, fmt, args);
3521
        va_end(args);
3522
        break;
3523
    }
3524
}