cachepc-qemu

Fork of AMDESE/qemu with changes for cachepc side-channel attack
git clone https://git.sinitax.com/sinitax/cachepc-qemu
Log | Files | Refs | Submodules | LICENSE | sfeed.txt

vl.c (117403B)


      1/*
      2 * QEMU System Emulator
      3 *
      4 * Copyright (c) 2003-2008 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
     25#include "qemu/osdep.h"
     26#include "qemu-common.h"
     27#include "qemu/datadir.h"
     28#include "qemu/units.h"
     29#include "exec/cpu-common.h"
     30#include "hw/qdev-properties.h"
     31#include "qapi/compat-policy.h"
     32#include "qapi/error.h"
     33#include "qapi/qmp/qdict.h"
     34#include "qapi/qmp/qstring.h"
     35#include "qapi/qmp/qjson.h"
     36#include "qemu-version.h"
     37#include "qemu/cutils.h"
     38#include "qemu/help_option.h"
     39#include "qemu/uuid.h"
     40#include "sysemu/reset.h"
     41#include "sysemu/runstate.h"
     42#include "sysemu/runstate-action.h"
     43#include "sysemu/seccomp.h"
     44#include "sysemu/tcg.h"
     45#include "sysemu/xen.h"
     46
     47#include "qemu/error-report.h"
     48#include "qemu/sockets.h"
     49#include "qemu/accel.h"
     50#include "hw/usb.h"
     51#include "hw/isa/isa.h"
     52#include "hw/scsi/scsi.h"
     53#include "hw/display/vga.h"
     54#include "sysemu/watchdog.h"
     55#include "hw/firmware/smbios.h"
     56#include "hw/acpi/acpi.h"
     57#include "hw/xen/xen.h"
     58#include "hw/loader.h"
     59#include "monitor/qdev.h"
     60#include "net/net.h"
     61#include "net/slirp.h"
     62#include "monitor/monitor.h"
     63#include "ui/console.h"
     64#include "ui/input.h"
     65#include "sysemu/sysemu.h"
     66#include "sysemu/numa.h"
     67#include "sysemu/hostmem.h"
     68#include "exec/gdbstub.h"
     69#include "qemu/timer.h"
     70#include "chardev/char.h"
     71#include "qemu/bitmap.h"
     72#include "qemu/log.h"
     73#include "sysemu/blockdev.h"
     74#include "hw/block/block.h"
     75#include "hw/i386/x86.h"
     76#include "hw/i386/pc.h"
     77#include "migration/misc.h"
     78#include "migration/snapshot.h"
     79#include "sysemu/tpm.h"
     80#include "sysemu/dma.h"
     81#include "hw/audio/soundhw.h"
     82#include "audio/audio.h"
     83#include "sysemu/cpus.h"
     84#include "sysemu/cpu-timers.h"
     85#include "migration/colo.h"
     86#include "migration/postcopy-ram.h"
     87#include "sysemu/kvm.h"
     88#include "sysemu/hax.h"
     89#include "qapi/qobject-input-visitor.h"
     90#include "qemu/option.h"
     91#include "qemu/config-file.h"
     92#include "qemu/qemu-options.h"
     93#include "qemu/main-loop.h"
     94#ifdef CONFIG_VIRTFS
     95#include "fsdev/qemu-fsdev.h"
     96#endif
     97#include "sysemu/qtest.h"
     98
     99#include "disas/disas.h"
    100
    101#include "trace.h"
    102#include "trace/control.h"
    103#include "qemu/plugin.h"
    104#include "qemu/queue.h"
    105#include "sysemu/arch_init.h"
    106#include "exec/confidential-guest-support.h"
    107
    108#include "ui/qemu-spice.h"
    109#include "qapi/string-input-visitor.h"
    110#include "qapi/opts-visitor.h"
    111#include "qapi/clone-visitor.h"
    112#include "qom/object_interfaces.h"
    113#include "semihosting/semihost.h"
    114#include "crypto/init.h"
    115#include "sysemu/replay.h"
    116#include "qapi/qapi-events-run-state.h"
    117#include "qapi/qapi-visit-block-core.h"
    118#include "qapi/qapi-visit-compat.h"
    119#include "qapi/qapi-visit-ui.h"
    120#include "qapi/qapi-commands-block-core.h"
    121#include "qapi/qapi-commands-migration.h"
    122#include "qapi/qapi-commands-misc.h"
    123#include "qapi/qapi-visit-qom.h"
    124#include "qapi/qapi-commands-ui.h"
    125#include "qapi/qmp/qdict.h"
    126#include "qapi/qmp/qerror.h"
    127#include "sysemu/iothread.h"
    128#include "qemu/guest-random.h"
    129
    130#include "config-host.h"
    131
    132#define MAX_VIRTIO_CONSOLES 1
    133
    134typedef struct BlockdevOptionsQueueEntry {
    135    BlockdevOptions *bdo;
    136    Location loc;
    137    QSIMPLEQ_ENTRY(BlockdevOptionsQueueEntry) entry;
    138} BlockdevOptionsQueueEntry;
    139
    140typedef QSIMPLEQ_HEAD(, BlockdevOptionsQueueEntry) BlockdevOptionsQueue;
    141
    142typedef struct ObjectOption {
    143    ObjectOptions *opts;
    144    QTAILQ_ENTRY(ObjectOption) next;
    145} ObjectOption;
    146
    147static const char *cpu_option;
    148static const char *mem_path;
    149static const char *incoming;
    150static const char *loadvm;
    151static const char *accelerators;
    152static QDict *machine_opts_dict;
    153static QTAILQ_HEAD(, ObjectOption) object_opts = QTAILQ_HEAD_INITIALIZER(object_opts);
    154static ram_addr_t maxram_size;
    155static uint64_t ram_slots;
    156static int display_remote;
    157static int snapshot;
    158static bool preconfig_requested;
    159static QemuPluginList plugin_list = QTAILQ_HEAD_INITIALIZER(plugin_list);
    160static BlockdevOptionsQueue bdo_queue = QSIMPLEQ_HEAD_INITIALIZER(bdo_queue);
    161static bool nographic = false;
    162static int mem_prealloc; /* force preallocation of physical target memory */
    163static ram_addr_t ram_size;
    164static const char *vga_model = NULL;
    165static DisplayOptions dpy;
    166static int num_serial_hds;
    167static Chardev **serial_hds;
    168static const char *log_mask;
    169static const char *log_file;
    170static bool list_data_dirs;
    171static const char *watchdog;
    172static const char *qtest_chrdev;
    173static const char *qtest_log;
    174
    175static int has_defaults = 1;
    176static int default_serial = 1;
    177static int default_parallel = 1;
    178static int default_monitor = 1;
    179static int default_floppy = 1;
    180static int default_cdrom = 1;
    181static int default_sdcard = 1;
    182static int default_vga = 1;
    183static int default_net = 1;
    184
    185static struct {
    186    const char *driver;
    187    int *flag;
    188} default_list[] = {
    189    { .driver = "isa-serial",           .flag = &default_serial    },
    190    { .driver = "isa-parallel",         .flag = &default_parallel  },
    191    { .driver = "isa-fdc",              .flag = &default_floppy    },
    192    { .driver = "floppy",               .flag = &default_floppy    },
    193    { .driver = "ide-cd",               .flag = &default_cdrom     },
    194    { .driver = "ide-hd",               .flag = &default_cdrom     },
    195    { .driver = "scsi-cd",              .flag = &default_cdrom     },
    196    { .driver = "scsi-hd",              .flag = &default_cdrom     },
    197    { .driver = "VGA",                  .flag = &default_vga       },
    198    { .driver = "isa-vga",              .flag = &default_vga       },
    199    { .driver = "cirrus-vga",           .flag = &default_vga       },
    200    { .driver = "isa-cirrus-vga",       .flag = &default_vga       },
    201    { .driver = "vmware-svga",          .flag = &default_vga       },
    202    { .driver = "qxl-vga",              .flag = &default_vga       },
    203    { .driver = "virtio-vga",           .flag = &default_vga       },
    204    { .driver = "ati-vga",              .flag = &default_vga       },
    205    { .driver = "vhost-user-vga",       .flag = &default_vga       },
    206    { .driver = "virtio-vga-gl",        .flag = &default_vga       },
    207};
    208
    209static QemuOptsList qemu_rtc_opts = {
    210    .name = "rtc",
    211    .head = QTAILQ_HEAD_INITIALIZER(qemu_rtc_opts.head),
    212    .merge_lists = true,
    213    .desc = {
    214        {
    215            .name = "base",
    216            .type = QEMU_OPT_STRING,
    217        },{
    218            .name = "clock",
    219            .type = QEMU_OPT_STRING,
    220        },{
    221            .name = "driftfix",
    222            .type = QEMU_OPT_STRING,
    223        },
    224        { /* end of list */ }
    225    },
    226};
    227
    228static QemuOptsList qemu_option_rom_opts = {
    229    .name = "option-rom",
    230    .implied_opt_name = "romfile",
    231    .head = QTAILQ_HEAD_INITIALIZER(qemu_option_rom_opts.head),
    232    .desc = {
    233        {
    234            .name = "bootindex",
    235            .type = QEMU_OPT_NUMBER,
    236        }, {
    237            .name = "romfile",
    238            .type = QEMU_OPT_STRING,
    239        },
    240        { /* end of list */ }
    241    },
    242};
    243
    244static QemuOptsList qemu_accel_opts = {
    245    .name = "accel",
    246    .implied_opt_name = "accel",
    247    .head = QTAILQ_HEAD_INITIALIZER(qemu_accel_opts.head),
    248    .desc = {
    249        /*
    250         * no elements => accept any
    251         * sanity checking will happen later
    252         * when setting accelerator properties
    253         */
    254        { }
    255    },
    256};
    257
    258static QemuOptsList qemu_boot_opts = {
    259    .name = "boot-opts",
    260    .implied_opt_name = "order",
    261    .merge_lists = true,
    262    .head = QTAILQ_HEAD_INITIALIZER(qemu_boot_opts.head),
    263    .desc = {
    264        {
    265            .name = "order",
    266            .type = QEMU_OPT_STRING,
    267        }, {
    268            .name = "once",
    269            .type = QEMU_OPT_STRING,
    270        }, {
    271            .name = "menu",
    272            .type = QEMU_OPT_BOOL,
    273        }, {
    274            .name = "splash",
    275            .type = QEMU_OPT_STRING,
    276        }, {
    277            .name = "splash-time",
    278            .type = QEMU_OPT_NUMBER,
    279        }, {
    280            .name = "reboot-timeout",
    281            .type = QEMU_OPT_NUMBER,
    282        }, {
    283            .name = "strict",
    284            .type = QEMU_OPT_BOOL,
    285        },
    286        { /*End of list */ }
    287    },
    288};
    289
    290static QemuOptsList qemu_add_fd_opts = {
    291    .name = "add-fd",
    292    .head = QTAILQ_HEAD_INITIALIZER(qemu_add_fd_opts.head),
    293    .desc = {
    294        {
    295            .name = "fd",
    296            .type = QEMU_OPT_NUMBER,
    297            .help = "file descriptor of which a duplicate is added to fd set",
    298        },{
    299            .name = "set",
    300            .type = QEMU_OPT_NUMBER,
    301            .help = "ID of the fd set to add fd to",
    302        },{
    303            .name = "opaque",
    304            .type = QEMU_OPT_STRING,
    305            .help = "free-form string used to describe fd",
    306        },
    307        { /* end of list */ }
    308    },
    309};
    310
    311static QemuOptsList qemu_object_opts = {
    312    .name = "object",
    313    .implied_opt_name = "qom-type",
    314    .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
    315    .desc = {
    316        { }
    317    },
    318};
    319
    320static QemuOptsList qemu_tpmdev_opts = {
    321    .name = "tpmdev",
    322    .implied_opt_name = "type",
    323    .head = QTAILQ_HEAD_INITIALIZER(qemu_tpmdev_opts.head),
    324    .desc = {
    325        /* options are defined in the TPM backends */
    326        { /* end of list */ }
    327    },
    328};
    329
    330static QemuOptsList qemu_overcommit_opts = {
    331    .name = "overcommit",
    332    .head = QTAILQ_HEAD_INITIALIZER(qemu_overcommit_opts.head),
    333    .desc = {
    334        {
    335            .name = "mem-lock",
    336            .type = QEMU_OPT_BOOL,
    337        },
    338        {
    339            .name = "cpu-pm",
    340            .type = QEMU_OPT_BOOL,
    341        },
    342        { /* end of list */ }
    343    },
    344};
    345
    346static QemuOptsList qemu_msg_opts = {
    347    .name = "msg",
    348    .head = QTAILQ_HEAD_INITIALIZER(qemu_msg_opts.head),
    349    .desc = {
    350        {
    351            .name = "timestamp",
    352            .type = QEMU_OPT_BOOL,
    353        },
    354        {
    355            .name = "guest-name",
    356            .type = QEMU_OPT_BOOL,
    357            .help = "Prepends guest name for error messages but only if "
    358                    "-name guest is set otherwise option is ignored\n",
    359        },
    360        { /* end of list */ }
    361    },
    362};
    363
    364static QemuOptsList qemu_name_opts = {
    365    .name = "name",
    366    .implied_opt_name = "guest",
    367    .merge_lists = true,
    368    .head = QTAILQ_HEAD_INITIALIZER(qemu_name_opts.head),
    369    .desc = {
    370        {
    371            .name = "guest",
    372            .type = QEMU_OPT_STRING,
    373            .help = "Sets the name of the guest.\n"
    374                    "This name will be displayed in the SDL window caption.\n"
    375                    "The name will also be used for the VNC server",
    376        }, {
    377            .name = "process",
    378            .type = QEMU_OPT_STRING,
    379            .help = "Sets the name of the QEMU process, as shown in top etc",
    380        }, {
    381            .name = "debug-threads",
    382            .type = QEMU_OPT_BOOL,
    383            .help = "When enabled, name the individual threads; defaults off.\n"
    384                    "NOTE: The thread names are for debugging and not a\n"
    385                    "stable API.",
    386        },
    387        { /* End of list */ }
    388    },
    389};
    390
    391static QemuOptsList qemu_mem_opts = {
    392    .name = "memory",
    393    .implied_opt_name = "size",
    394    .head = QTAILQ_HEAD_INITIALIZER(qemu_mem_opts.head),
    395    .merge_lists = true,
    396    .desc = {
    397        {
    398            .name = "size",
    399            .type = QEMU_OPT_SIZE,
    400        },
    401        {
    402            .name = "slots",
    403            .type = QEMU_OPT_NUMBER,
    404        },
    405        {
    406            .name = "maxmem",
    407            .type = QEMU_OPT_SIZE,
    408        },
    409        { /* end of list */ }
    410    },
    411};
    412
    413static QemuOptsList qemu_icount_opts = {
    414    .name = "icount",
    415    .implied_opt_name = "shift",
    416    .merge_lists = true,
    417    .head = QTAILQ_HEAD_INITIALIZER(qemu_icount_opts.head),
    418    .desc = {
    419        {
    420            .name = "shift",
    421            .type = QEMU_OPT_STRING,
    422        }, {
    423            .name = "align",
    424            .type = QEMU_OPT_BOOL,
    425        }, {
    426            .name = "sleep",
    427            .type = QEMU_OPT_BOOL,
    428        }, {
    429            .name = "rr",
    430            .type = QEMU_OPT_STRING,
    431        }, {
    432            .name = "rrfile",
    433            .type = QEMU_OPT_STRING,
    434        }, {
    435            .name = "rrsnapshot",
    436            .type = QEMU_OPT_STRING,
    437        },
    438        { /* end of list */ }
    439    },
    440};
    441
    442static QemuOptsList qemu_fw_cfg_opts = {
    443    .name = "fw_cfg",
    444    .implied_opt_name = "name",
    445    .head = QTAILQ_HEAD_INITIALIZER(qemu_fw_cfg_opts.head),
    446    .desc = {
    447        {
    448            .name = "name",
    449            .type = QEMU_OPT_STRING,
    450            .help = "Sets the fw_cfg name of the blob to be inserted",
    451        }, {
    452            .name = "file",
    453            .type = QEMU_OPT_STRING,
    454            .help = "Sets the name of the file from which "
    455                    "the fw_cfg blob will be loaded",
    456        }, {
    457            .name = "string",
    458            .type = QEMU_OPT_STRING,
    459            .help = "Sets content of the blob to be inserted from a string",
    460        }, {
    461            .name = "gen_id",
    462            .type = QEMU_OPT_STRING,
    463            .help = "Sets id of the object generating the fw_cfg blob "
    464                    "to be inserted",
    465        },
    466        { /* end of list */ }
    467    },
    468};
    469
    470static QemuOptsList qemu_action_opts = {
    471    .name = "action",
    472    .merge_lists = true,
    473    .head = QTAILQ_HEAD_INITIALIZER(qemu_action_opts.head),
    474    .desc = {
    475        {
    476            .name = "shutdown",
    477            .type = QEMU_OPT_STRING,
    478        },{
    479            .name = "reboot",
    480            .type = QEMU_OPT_STRING,
    481        },{
    482            .name = "panic",
    483            .type = QEMU_OPT_STRING,
    484        },{
    485            .name = "watchdog",
    486            .type = QEMU_OPT_STRING,
    487        },
    488        { /* end of list */ }
    489    },
    490};
    491
    492const char *qemu_get_vm_name(void)
    493{
    494    return qemu_name;
    495}
    496
    497static int default_driver_check(void *opaque, QemuOpts *opts, Error **errp)
    498{
    499    const char *driver = qemu_opt_get(opts, "driver");
    500    int i;
    501
    502    if (!driver)
    503        return 0;
    504    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
    505        if (strcmp(default_list[i].driver, driver) != 0)
    506            continue;
    507        *(default_list[i].flag) = 0;
    508    }
    509    return 0;
    510}
    511
    512static int parse_name(void *opaque, QemuOpts *opts, Error **errp)
    513{
    514    const char *proc_name;
    515
    516    if (qemu_opt_get(opts, "debug-threads")) {
    517        qemu_thread_naming(qemu_opt_get_bool(opts, "debug-threads", false));
    518    }
    519    qemu_name = qemu_opt_get(opts, "guest");
    520
    521    proc_name = qemu_opt_get(opts, "process");
    522    if (proc_name) {
    523        os_set_proc_name(proc_name);
    524    }
    525
    526    return 0;
    527}
    528
    529bool defaults_enabled(void)
    530{
    531    return has_defaults;
    532}
    533
    534#ifndef _WIN32
    535static int parse_add_fd(void *opaque, QemuOpts *opts, Error **errp)
    536{
    537    int fd, dupfd, flags;
    538    int64_t fdset_id;
    539    const char *fd_opaque = NULL;
    540    AddfdInfo *fdinfo;
    541
    542    fd = qemu_opt_get_number(opts, "fd", -1);
    543    fdset_id = qemu_opt_get_number(opts, "set", -1);
    544    fd_opaque = qemu_opt_get(opts, "opaque");
    545
    546    if (fd < 0) {
    547        error_setg(errp, "fd option is required and must be non-negative");
    548        return -1;
    549    }
    550
    551    if (fd <= STDERR_FILENO) {
    552        error_setg(errp, "fd cannot be a standard I/O stream");
    553        return -1;
    554    }
    555
    556    /*
    557     * All fds inherited across exec() necessarily have FD_CLOEXEC
    558     * clear, while qemu sets FD_CLOEXEC on all other fds used internally.
    559     */
    560    flags = fcntl(fd, F_GETFD);
    561    if (flags == -1 || (flags & FD_CLOEXEC)) {
    562        error_setg(errp, "fd is not valid or already in use");
    563        return -1;
    564    }
    565
    566    if (fdset_id < 0) {
    567        error_setg(errp, "set option is required and must be non-negative");
    568        return -1;
    569    }
    570
    571#ifdef F_DUPFD_CLOEXEC
    572    dupfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
    573#else
    574    dupfd = dup(fd);
    575    if (dupfd != -1) {
    576        qemu_set_cloexec(dupfd);
    577    }
    578#endif
    579    if (dupfd == -1) {
    580        error_setg(errp, "error duplicating fd: %s", strerror(errno));
    581        return -1;
    582    }
    583
    584    /* add the duplicate fd, and optionally the opaque string, to the fd set */
    585    fdinfo = monitor_fdset_add_fd(dupfd, true, fdset_id, !!fd_opaque, fd_opaque,
    586                                  &error_abort);
    587    g_free(fdinfo);
    588
    589    return 0;
    590}
    591
    592static int cleanup_add_fd(void *opaque, QemuOpts *opts, Error **errp)
    593{
    594    int fd;
    595
    596    fd = qemu_opt_get_number(opts, "fd", -1);
    597    close(fd);
    598
    599    return 0;
    600}
    601#endif
    602
    603/***********************************************************/
    604/* QEMU Block devices */
    605
    606#define HD_OPTS "media=disk"
    607#define CDROM_OPTS "media=cdrom"
    608#define FD_OPTS ""
    609#define PFLASH_OPTS ""
    610#define MTD_OPTS ""
    611#define SD_OPTS ""
    612
    613static int drive_init_func(void *opaque, QemuOpts *opts, Error **errp)
    614{
    615    BlockInterfaceType *block_default_type = opaque;
    616
    617    return drive_new(opts, *block_default_type, errp) == NULL;
    618}
    619
    620static int drive_enable_snapshot(void *opaque, QemuOpts *opts, Error **errp)
    621{
    622    if (qemu_opt_get(opts, "snapshot") == NULL) {
    623        qemu_opt_set(opts, "snapshot", "on", &error_abort);
    624    }
    625    return 0;
    626}
    627
    628static void default_drive(int enable, int snapshot, BlockInterfaceType type,
    629                          int index, const char *optstr)
    630{
    631    QemuOpts *opts;
    632    DriveInfo *dinfo;
    633
    634    if (!enable || drive_get_by_index(type, index)) {
    635        return;
    636    }
    637
    638    opts = drive_add(type, index, NULL, optstr);
    639    if (snapshot) {
    640        drive_enable_snapshot(NULL, opts, NULL);
    641    }
    642
    643    dinfo = drive_new(opts, type, &error_abort);
    644    dinfo->is_default = true;
    645
    646}
    647
    648static void configure_blockdev(BlockdevOptionsQueue *bdo_queue,
    649                               MachineClass *machine_class, int snapshot)
    650{
    651    /*
    652     * If the currently selected machine wishes to override the
    653     * units-per-bus property of its default HBA interface type, do so
    654     * now.
    655     */
    656    if (machine_class->units_per_default_bus) {
    657        override_max_devs(machine_class->block_default_type,
    658                          machine_class->units_per_default_bus);
    659    }
    660
    661    /* open the virtual block devices */
    662    while (!QSIMPLEQ_EMPTY(bdo_queue)) {
    663        BlockdevOptionsQueueEntry *bdo = QSIMPLEQ_FIRST(bdo_queue);
    664
    665        QSIMPLEQ_REMOVE_HEAD(bdo_queue, entry);
    666        loc_push_restore(&bdo->loc);
    667        qmp_blockdev_add(bdo->bdo, &error_fatal);
    668        loc_pop(&bdo->loc);
    669        qapi_free_BlockdevOptions(bdo->bdo);
    670        g_free(bdo);
    671    }
    672    if (snapshot) {
    673        qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot,
    674                          NULL, NULL);
    675    }
    676    if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func,
    677                          &machine_class->block_default_type, &error_fatal)) {
    678        /* We printed help */
    679        exit(0);
    680    }
    681
    682    default_drive(default_cdrom, snapshot, machine_class->block_default_type, 2,
    683                  CDROM_OPTS);
    684    default_drive(default_floppy, snapshot, IF_FLOPPY, 0, FD_OPTS);
    685    default_drive(default_sdcard, snapshot, IF_SD, 0, SD_OPTS);
    686
    687}
    688
    689static QemuOptsList qemu_smp_opts = {
    690    .name = "smp-opts",
    691    .implied_opt_name = "cpus",
    692    .merge_lists = true,
    693    .head = QTAILQ_HEAD_INITIALIZER(qemu_smp_opts.head),
    694    .desc = {
    695        {
    696            .name = "cpus",
    697            .type = QEMU_OPT_NUMBER,
    698        }, {
    699            .name = "sockets",
    700            .type = QEMU_OPT_NUMBER,
    701        }, {
    702            .name = "dies",
    703            .type = QEMU_OPT_NUMBER,
    704        }, {
    705            .name = "cores",
    706            .type = QEMU_OPT_NUMBER,
    707        }, {
    708            .name = "threads",
    709            .type = QEMU_OPT_NUMBER,
    710        }, {
    711            .name = "maxcpus",
    712            .type = QEMU_OPT_NUMBER,
    713        },
    714        { /*End of list */ }
    715    },
    716};
    717
    718static void realtime_init(void)
    719{
    720    if (enable_mlock) {
    721        if (os_mlock() < 0) {
    722            error_report("locking memory failed");
    723            exit(1);
    724        }
    725    }
    726}
    727
    728
    729static void configure_msg(QemuOpts *opts)
    730{
    731    message_with_timestamp = qemu_opt_get_bool(opts, "timestamp", false);
    732    error_with_guestname = qemu_opt_get_bool(opts, "guest-name", false);
    733}
    734
    735
    736/***********************************************************/
    737/* USB devices */
    738
    739static int usb_device_add(const char *devname)
    740{
    741    USBDevice *dev = NULL;
    742
    743    if (!machine_usb(current_machine)) {
    744        return -1;
    745    }
    746
    747    dev = usbdevice_create(devname);
    748    if (!dev)
    749        return -1;
    750
    751    return 0;
    752}
    753
    754static int usb_parse(const char *cmdline)
    755{
    756    int r;
    757    r = usb_device_add(cmdline);
    758    if (r < 0) {
    759        error_report("could not add USB device '%s'", cmdline);
    760    }
    761    return r;
    762}
    763
    764/***********************************************************/
    765/* machine registration */
    766
    767static MachineClass *find_machine(const char *name, GSList *machines)
    768{
    769    GSList *el;
    770
    771    for (el = machines; el; el = el->next) {
    772        MachineClass *mc = el->data;
    773
    774        if (!strcmp(mc->name, name) || !g_strcmp0(mc->alias, name)) {
    775            return mc;
    776        }
    777    }
    778
    779    return NULL;
    780}
    781
    782static MachineClass *find_default_machine(GSList *machines)
    783{
    784    GSList *el;
    785    MachineClass *default_machineclass = NULL;
    786
    787    for (el = machines; el; el = el->next) {
    788        MachineClass *mc = el->data;
    789
    790        if (mc->is_default) {
    791            assert(default_machineclass == NULL && "Multiple default machines");
    792            default_machineclass = mc;
    793        }
    794    }
    795
    796    return default_machineclass;
    797}
    798
    799static void version(void)
    800{
    801    printf("QEMU emulator version " QEMU_FULL_VERSION "\n"
    802           QEMU_COPYRIGHT "\n");
    803}
    804
    805static void help(int exitcode)
    806{
    807    version();
    808    printf("usage: %s [options] [disk_image]\n\n"
    809           "'disk_image' is a raw hard disk image for IDE hard disk 0\n\n",
    810            error_get_progname());
    811
    812#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)    \
    813    if ((arch_mask) & arch_type)                               \
    814        fputs(opt_help, stdout);
    815
    816#define ARCHHEADING(text, arch_mask) \
    817    if ((arch_mask) & arch_type)    \
    818        puts(stringify(text));
    819
    820#define DEFHEADING(text) ARCHHEADING(text, QEMU_ARCH_ALL)
    821
    822#include "qemu-options.def"
    823
    824    printf("\nDuring emulation, the following keys are useful:\n"
    825           "ctrl-alt-f      toggle full screen\n"
    826           "ctrl-alt-n      switch to virtual console 'n'\n"
    827           "ctrl-alt        toggle mouse and keyboard grab\n"
    828           "\n"
    829           "When using -nographic, press 'ctrl-a h' to get some help.\n"
    830           "\n"
    831           QEMU_HELP_BOTTOM "\n");
    832
    833    exit(exitcode);
    834}
    835
    836#define HAS_ARG 0x0001
    837
    838typedef struct QEMUOption {
    839    const char *name;
    840    int flags;
    841    int index;
    842    uint32_t arch_mask;
    843} QEMUOption;
    844
    845static const QEMUOption qemu_options[] = {
    846    { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
    847
    848#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
    849    { option, opt_arg, opt_enum, arch_mask },
    850#define DEFHEADING(text)
    851#define ARCHHEADING(text, arch_mask)
    852
    853#include "qemu-options.def"
    854    { NULL },
    855};
    856
    857typedef struct VGAInterfaceInfo {
    858    const char *opt_name;    /* option name */
    859    const char *name;        /* human-readable name */
    860    /* Class names indicating that support is available.
    861     * If no class is specified, the interface is always available */
    862    const char *class_names[2];
    863} VGAInterfaceInfo;
    864
    865static const VGAInterfaceInfo vga_interfaces[VGA_TYPE_MAX] = {
    866    [VGA_NONE] = {
    867        .opt_name = "none",
    868        .name = "no graphic card",
    869    },
    870    [VGA_STD] = {
    871        .opt_name = "std",
    872        .name = "standard VGA",
    873        .class_names = { "VGA", "isa-vga" },
    874    },
    875    [VGA_CIRRUS] = {
    876        .opt_name = "cirrus",
    877        .name = "Cirrus VGA",
    878        .class_names = { "cirrus-vga", "isa-cirrus-vga" },
    879    },
    880    [VGA_VMWARE] = {
    881        .opt_name = "vmware",
    882        .name = "VMWare SVGA",
    883        .class_names = { "vmware-svga" },
    884    },
    885    [VGA_VIRTIO] = {
    886        .opt_name = "virtio",
    887        .name = "Virtio VGA",
    888        .class_names = { "virtio-vga" },
    889    },
    890    [VGA_QXL] = {
    891        .opt_name = "qxl",
    892        .name = "QXL VGA",
    893        .class_names = { "qxl-vga" },
    894    },
    895    [VGA_TCX] = {
    896        .opt_name = "tcx",
    897        .name = "TCX framebuffer",
    898        .class_names = { "sun-tcx" },
    899    },
    900    [VGA_CG3] = {
    901        .opt_name = "cg3",
    902        .name = "CG3 framebuffer",
    903        .class_names = { "cgthree" },
    904    },
    905    [VGA_XENFB] = {
    906        .opt_name = "xenfb",
    907        .name = "Xen paravirtualized framebuffer",
    908    },
    909};
    910
    911static bool vga_interface_available(VGAInterfaceType t)
    912{
    913    const VGAInterfaceInfo *ti = &vga_interfaces[t];
    914
    915    assert(t < VGA_TYPE_MAX);
    916    return !ti->class_names[0] ||
    917           module_object_class_by_name(ti->class_names[0]) ||
    918           module_object_class_by_name(ti->class_names[1]);
    919}
    920
    921static const char *
    922get_default_vga_model(const MachineClass *machine_class)
    923{
    924    if (machine_class->default_display) {
    925        return machine_class->default_display;
    926    } else if (vga_interface_available(VGA_CIRRUS)) {
    927        return "cirrus";
    928    } else if (vga_interface_available(VGA_STD)) {
    929        return "std";
    930    }
    931
    932    return NULL;
    933}
    934
    935static void select_vgahw(const MachineClass *machine_class, const char *p)
    936{
    937    const char *opts;
    938    int t;
    939
    940    if (g_str_equal(p, "help")) {
    941        const char *def = get_default_vga_model(machine_class);
    942
    943        for (t = 0; t < VGA_TYPE_MAX; t++) {
    944            const VGAInterfaceInfo *ti = &vga_interfaces[t];
    945
    946            if (vga_interface_available(t) && ti->opt_name) {
    947                printf("%-20s %s%s\n", ti->opt_name, ti->name ?: "",
    948                       g_str_equal(ti->opt_name, def) ? " (default)" : "");
    949            }
    950        }
    951        exit(0);
    952    }
    953
    954    assert(vga_interface_type == VGA_NONE);
    955    for (t = 0; t < VGA_TYPE_MAX; t++) {
    956        const VGAInterfaceInfo *ti = &vga_interfaces[t];
    957        if (ti->opt_name && strstart(p, ti->opt_name, &opts)) {
    958            if (!vga_interface_available(t)) {
    959                error_report("%s not available", ti->name);
    960                exit(1);
    961            }
    962            vga_interface_type = t;
    963            break;
    964        }
    965    }
    966    if (t == VGA_TYPE_MAX) {
    967    invalid_vga:
    968        error_report("unknown vga type: %s", p);
    969        exit(1);
    970    }
    971    while (*opts) {
    972        const char *nextopt;
    973
    974        if (strstart(opts, ",retrace=", &nextopt)) {
    975            opts = nextopt;
    976            if (strstart(opts, "dumb", &nextopt))
    977                vga_retrace_method = VGA_RETRACE_DUMB;
    978            else if (strstart(opts, "precise", &nextopt))
    979                vga_retrace_method = VGA_RETRACE_PRECISE;
    980            else goto invalid_vga;
    981        } else goto invalid_vga;
    982        opts = nextopt;
    983    }
    984}
    985
    986static void parse_display_qapi(const char *optarg)
    987{
    988    DisplayOptions *opts;
    989    Visitor *v;
    990
    991    v = qobject_input_visitor_new_str(optarg, "type", &error_fatal);
    992
    993    visit_type_DisplayOptions(v, NULL, &opts, &error_fatal);
    994    QAPI_CLONE_MEMBERS(DisplayOptions, &dpy, opts);
    995
    996    qapi_free_DisplayOptions(opts);
    997    visit_free(v);
    998}
    999
   1000DisplayOptions *qmp_query_display_options(Error **errp)
   1001{
   1002    return QAPI_CLONE(DisplayOptions, &dpy);
   1003}
   1004
   1005static void parse_display(const char *p)
   1006{
   1007    const char *opts;
   1008
   1009    if (is_help_option(p)) {
   1010        qemu_display_help();
   1011        exit(0);
   1012    }
   1013
   1014    if (strstart(p, "sdl", &opts)) {
   1015        /*
   1016         * sdl DisplayType needs hand-crafted parser instead of
   1017         * parse_display_qapi() due to some options not in
   1018         * DisplayOptions, specifically:
   1019         *   - ctrl_grab + alt_grab
   1020         *     They can't be moved into the QAPI since they use underscores,
   1021         *     thus they will get replaced by "grab-mod" in the long term
   1022         */
   1023#if defined(CONFIG_SDL)
   1024        dpy.type = DISPLAY_TYPE_SDL;
   1025        while (*opts) {
   1026            const char *nextopt;
   1027
   1028            if (strstart(opts, ",grab-mod=", &nextopt)) {
   1029                opts = nextopt;
   1030                if (strstart(opts, "lshift-lctrl-lalt", &nextopt)) {
   1031                    alt_grab = 1;
   1032                } else if (strstart(opts, "rctrl", &nextopt)) {
   1033                    ctrl_grab = 1;
   1034                } else {
   1035                    goto invalid_sdl_args;
   1036                }
   1037            } else if (strstart(opts, ",alt_grab=", &nextopt)) {
   1038                opts = nextopt;
   1039                if (strstart(opts, "on", &nextopt)) {
   1040                    alt_grab = 1;
   1041                } else if (strstart(opts, "off", &nextopt)) {
   1042                    alt_grab = 0;
   1043                } else {
   1044                    goto invalid_sdl_args;
   1045                }
   1046                warn_report("alt_grab is deprecated, use grab-mod instead.");
   1047            } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
   1048                opts = nextopt;
   1049                if (strstart(opts, "on", &nextopt)) {
   1050                    ctrl_grab = 1;
   1051                } else if (strstart(opts, "off", &nextopt)) {
   1052                    ctrl_grab = 0;
   1053                } else {
   1054                    goto invalid_sdl_args;
   1055                }
   1056                warn_report("ctrl_grab is deprecated, use grab-mod instead.");
   1057            } else if (strstart(opts, ",window_close=", &nextopt) ||
   1058                       strstart(opts, ",window-close=", &nextopt)) {
   1059                if (strstart(opts, ",window_close=", NULL)) {
   1060                    warn_report("window_close with an underscore is deprecated,"
   1061                                " please use window-close instead.");
   1062                }
   1063                opts = nextopt;
   1064                dpy.has_window_close = true;
   1065                if (strstart(opts, "on", &nextopt)) {
   1066                    dpy.window_close = true;
   1067                } else if (strstart(opts, "off", &nextopt)) {
   1068                    dpy.window_close = false;
   1069                } else {
   1070                    goto invalid_sdl_args;
   1071                }
   1072            } else if (strstart(opts, ",show-cursor=", &nextopt)) {
   1073                opts = nextopt;
   1074                dpy.has_show_cursor = true;
   1075                if (strstart(opts, "on", &nextopt)) {
   1076                    dpy.show_cursor = true;
   1077                } else if (strstart(opts, "off", &nextopt)) {
   1078                    dpy.show_cursor = false;
   1079                } else {
   1080                    goto invalid_sdl_args;
   1081                }
   1082            } else if (strstart(opts, ",gl=", &nextopt)) {
   1083                opts = nextopt;
   1084                dpy.has_gl = true;
   1085                if (strstart(opts, "on", &nextopt)) {
   1086                    dpy.gl = DISPLAYGL_MODE_ON;
   1087                } else if (strstart(opts, "core", &nextopt)) {
   1088                    dpy.gl = DISPLAYGL_MODE_CORE;
   1089                } else if (strstart(opts, "es", &nextopt)) {
   1090                    dpy.gl = DISPLAYGL_MODE_ES;
   1091                } else if (strstart(opts, "off", &nextopt)) {
   1092                    dpy.gl = DISPLAYGL_MODE_OFF;
   1093                } else {
   1094                    goto invalid_sdl_args;
   1095                }
   1096            } else {
   1097            invalid_sdl_args:
   1098                error_report("invalid SDL option string");
   1099                exit(1);
   1100            }
   1101            opts = nextopt;
   1102        }
   1103#else
   1104        error_report("SDL display supported is not available in this binary");
   1105        exit(1);
   1106#endif
   1107    } else if (strstart(p, "vnc", &opts)) {
   1108        /*
   1109         * vnc isn't a (local) DisplayType but a protocol for remote
   1110         * display access.
   1111         */
   1112        if (*opts == '=') {
   1113            vnc_parse(opts + 1);
   1114        } else {
   1115            error_report("VNC requires a display argument vnc=<display>");
   1116            exit(1);
   1117        }
   1118    } else {
   1119        parse_display_qapi(p);
   1120    }
   1121}
   1122
   1123static inline bool nonempty_str(const char *str)
   1124{
   1125    return str && *str;
   1126}
   1127
   1128static int parse_fw_cfg(void *opaque, QemuOpts *opts, Error **errp)
   1129{
   1130    gchar *buf;
   1131    size_t size;
   1132    const char *name, *file, *str, *gen_id;
   1133    FWCfgState *fw_cfg = (FWCfgState *) opaque;
   1134
   1135    if (fw_cfg == NULL) {
   1136        error_setg(errp, "fw_cfg device not available");
   1137        return -1;
   1138    }
   1139    name = qemu_opt_get(opts, "name");
   1140    file = qemu_opt_get(opts, "file");
   1141    str = qemu_opt_get(opts, "string");
   1142    gen_id = qemu_opt_get(opts, "gen_id");
   1143
   1144    /* we need the name, and exactly one of: file, content string, gen_id */
   1145    if (!nonempty_str(name) ||
   1146        nonempty_str(file) + nonempty_str(str) + nonempty_str(gen_id) != 1) {
   1147        error_setg(errp, "name, plus exactly one of file,"
   1148                         " string and gen_id, are needed");
   1149        return -1;
   1150    }
   1151    if (strlen(name) > FW_CFG_MAX_FILE_PATH - 1) {
   1152        error_setg(errp, "name too long (max. %d char)",
   1153                   FW_CFG_MAX_FILE_PATH - 1);
   1154        return -1;
   1155    }
   1156    if (nonempty_str(gen_id)) {
   1157        /*
   1158         * In this particular case where the content is populated
   1159         * internally, the "etc/" namespace protection is relaxed,
   1160         * so do not emit a warning.
   1161         */
   1162    } else if (strncmp(name, "opt/", 4) != 0) {
   1163        warn_report("externally provided fw_cfg item names "
   1164                    "should be prefixed with \"opt/\"");
   1165    }
   1166    if (nonempty_str(str)) {
   1167        size = strlen(str); /* NUL terminator NOT included in fw_cfg blob */
   1168        buf = g_memdup(str, size);
   1169    } else if (nonempty_str(gen_id)) {
   1170        if (!fw_cfg_add_from_generator(fw_cfg, name, gen_id, errp)) {
   1171            return -1;
   1172        }
   1173        return 0;
   1174    } else {
   1175        GError *err = NULL;
   1176        if (!g_file_get_contents(file, &buf, &size, &err)) {
   1177            error_setg(errp, "can't load %s: %s", file, err->message);
   1178            g_error_free(err);
   1179            return -1;
   1180        }
   1181    }
   1182    /* For legacy, keep user files in a specific global order. */
   1183    fw_cfg_set_order_override(fw_cfg, FW_CFG_ORDER_OVERRIDE_USER);
   1184    fw_cfg_add_file(fw_cfg, name, buf, size);
   1185    fw_cfg_reset_order_override(fw_cfg);
   1186    return 0;
   1187}
   1188
   1189static int device_help_func(void *opaque, QemuOpts *opts, Error **errp)
   1190{
   1191    return qdev_device_help(opts);
   1192}
   1193
   1194static int device_init_func(void *opaque, QemuOpts *opts, Error **errp)
   1195{
   1196    DeviceState *dev;
   1197
   1198    dev = qdev_device_add(opts, errp);
   1199    if (!dev && *errp) {
   1200        error_report_err(*errp);
   1201        return -1;
   1202    } else if (dev) {
   1203        object_unref(OBJECT(dev));
   1204    }
   1205    return 0;
   1206}
   1207
   1208static int chardev_init_func(void *opaque, QemuOpts *opts, Error **errp)
   1209{
   1210    Error *local_err = NULL;
   1211
   1212    if (!qemu_chr_new_from_opts(opts, NULL, &local_err)) {
   1213        if (local_err) {
   1214            error_propagate(errp, local_err);
   1215            return -1;
   1216        }
   1217        exit(0);
   1218    }
   1219    return 0;
   1220}
   1221
   1222#ifdef CONFIG_VIRTFS
   1223static int fsdev_init_func(void *opaque, QemuOpts *opts, Error **errp)
   1224{
   1225    return qemu_fsdev_add(opts, errp);
   1226}
   1227#endif
   1228
   1229static int mon_init_func(void *opaque, QemuOpts *opts, Error **errp)
   1230{
   1231    return monitor_init_opts(opts, errp);
   1232}
   1233
   1234static void monitor_parse(const char *optarg, const char *mode, bool pretty)
   1235{
   1236    static int monitor_device_index = 0;
   1237    QemuOpts *opts;
   1238    const char *p;
   1239    char label[32];
   1240
   1241    if (strstart(optarg, "chardev:", &p)) {
   1242        snprintf(label, sizeof(label), "%s", p);
   1243    } else {
   1244        snprintf(label, sizeof(label), "compat_monitor%d",
   1245                 monitor_device_index);
   1246        opts = qemu_chr_parse_compat(label, optarg, true);
   1247        if (!opts) {
   1248            error_report("parse error: %s", optarg);
   1249            exit(1);
   1250        }
   1251    }
   1252
   1253    opts = qemu_opts_create(qemu_find_opts("mon"), label, 1, &error_fatal);
   1254    qemu_opt_set(opts, "mode", mode, &error_abort);
   1255    qemu_opt_set(opts, "chardev", label, &error_abort);
   1256    if (!strcmp(mode, "control")) {
   1257        qemu_opt_set_bool(opts, "pretty", pretty, &error_abort);
   1258    } else {
   1259        assert(pretty == false);
   1260    }
   1261    monitor_device_index++;
   1262}
   1263
   1264struct device_config {
   1265    enum {
   1266        DEV_USB,       /* -usbdevice     */
   1267        DEV_SERIAL,    /* -serial        */
   1268        DEV_PARALLEL,  /* -parallel      */
   1269        DEV_DEBUGCON,  /* -debugcon */
   1270        DEV_GDB,       /* -gdb, -s */
   1271        DEV_SCLP,      /* s390 sclp */
   1272    } type;
   1273    const char *cmdline;
   1274    Location loc;
   1275    QTAILQ_ENTRY(device_config) next;
   1276};
   1277
   1278static QTAILQ_HEAD(, device_config) device_configs =
   1279    QTAILQ_HEAD_INITIALIZER(device_configs);
   1280
   1281static void add_device_config(int type, const char *cmdline)
   1282{
   1283    struct device_config *conf;
   1284
   1285    conf = g_malloc0(sizeof(*conf));
   1286    conf->type = type;
   1287    conf->cmdline = cmdline;
   1288    loc_save(&conf->loc);
   1289    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
   1290}
   1291
   1292static int foreach_device_config(int type, int (*func)(const char *cmdline))
   1293{
   1294    struct device_config *conf;
   1295    int rc;
   1296
   1297    QTAILQ_FOREACH(conf, &device_configs, next) {
   1298        if (conf->type != type)
   1299            continue;
   1300        loc_push_restore(&conf->loc);
   1301        rc = func(conf->cmdline);
   1302        loc_pop(&conf->loc);
   1303        if (rc) {
   1304            return rc;
   1305        }
   1306    }
   1307    return 0;
   1308}
   1309
   1310static void qemu_disable_default_devices(void)
   1311{
   1312    MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
   1313
   1314    qemu_opts_foreach(qemu_find_opts("device"),
   1315                      default_driver_check, NULL, NULL);
   1316    qemu_opts_foreach(qemu_find_opts("global"),
   1317                      default_driver_check, NULL, NULL);
   1318
   1319    if (!vga_model && !default_vga) {
   1320        vga_interface_type = VGA_DEVICE;
   1321    }
   1322    if (!has_defaults || machine_class->no_serial) {
   1323        default_serial = 0;
   1324    }
   1325    if (!has_defaults || machine_class->no_parallel) {
   1326        default_parallel = 0;
   1327    }
   1328    if (!has_defaults || machine_class->no_floppy) {
   1329        default_floppy = 0;
   1330    }
   1331    if (!has_defaults || machine_class->no_cdrom) {
   1332        default_cdrom = 0;
   1333    }
   1334    if (!has_defaults || machine_class->no_sdcard) {
   1335        default_sdcard = 0;
   1336    }
   1337    if (!has_defaults) {
   1338        default_monitor = 0;
   1339        default_net = 0;
   1340        default_vga = 0;
   1341    }
   1342}
   1343
   1344static void qemu_create_default_devices(void)
   1345{
   1346    MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
   1347
   1348    if (is_daemonized()) {
   1349        /* According to documentation and historically, -nographic redirects
   1350         * serial port, parallel port and monitor to stdio, which does not work
   1351         * with -daemonize.  We can redirect these to null instead, but since
   1352         * -nographic is legacy, let's just error out.
   1353         * We disallow -nographic only if all other ports are not redirected
   1354         * explicitly, to not break existing legacy setups which uses
   1355         * -nographic _and_ redirects all ports explicitly - this is valid
   1356         * usage, -nographic is just a no-op in this case.
   1357         */
   1358        if (nographic
   1359            && (default_parallel || default_serial || default_monitor)) {
   1360            error_report("-nographic cannot be used with -daemonize");
   1361            exit(1);
   1362        }
   1363    }
   1364
   1365    if (nographic) {
   1366        if (default_parallel)
   1367            add_device_config(DEV_PARALLEL, "null");
   1368        if (default_serial && default_monitor) {
   1369            add_device_config(DEV_SERIAL, "mon:stdio");
   1370        } else {
   1371            if (default_serial)
   1372                add_device_config(DEV_SERIAL, "stdio");
   1373            if (default_monitor)
   1374                monitor_parse("stdio", "readline", false);
   1375        }
   1376    } else {
   1377        if (default_serial)
   1378            add_device_config(DEV_SERIAL, "vc:80Cx24C");
   1379        if (default_parallel)
   1380            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
   1381        if (default_monitor)
   1382            monitor_parse("vc:80Cx24C", "readline", false);
   1383    }
   1384
   1385    if (default_net) {
   1386        QemuOptsList *net = qemu_find_opts("net");
   1387        qemu_opts_parse(net, "nic", true, &error_abort);
   1388#ifdef CONFIG_SLIRP
   1389        qemu_opts_parse(net, "user", true, &error_abort);
   1390#endif
   1391    }
   1392
   1393#if defined(CONFIG_VNC)
   1394    if (!QTAILQ_EMPTY(&(qemu_find_opts("vnc")->head))) {
   1395        display_remote++;
   1396    }
   1397#endif
   1398    if (dpy.type == DISPLAY_TYPE_DEFAULT && !display_remote) {
   1399        if (!qemu_display_find_default(&dpy)) {
   1400            dpy.type = DISPLAY_TYPE_NONE;
   1401#if defined(CONFIG_VNC)
   1402            vnc_parse("localhost:0,to=99,id=default");
   1403#endif
   1404        }
   1405    }
   1406    if (dpy.type == DISPLAY_TYPE_DEFAULT) {
   1407        dpy.type = DISPLAY_TYPE_NONE;
   1408    }
   1409
   1410    /* If no default VGA is requested, the default is "none".  */
   1411    if (default_vga) {
   1412        vga_model = get_default_vga_model(machine_class);
   1413    }
   1414    if (vga_model) {
   1415        select_vgahw(machine_class, vga_model);
   1416    }
   1417}
   1418
   1419static int serial_parse(const char *devname)
   1420{
   1421    int index = num_serial_hds;
   1422    char label[32];
   1423
   1424    if (strcmp(devname, "none") == 0)
   1425        return 0;
   1426    snprintf(label, sizeof(label), "serial%d", index);
   1427    serial_hds = g_renew(Chardev *, serial_hds, index + 1);
   1428
   1429    serial_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
   1430    if (!serial_hds[index]) {
   1431        error_report("could not connect serial device"
   1432                     " to character backend '%s'", devname);
   1433        return -1;
   1434    }
   1435    num_serial_hds++;
   1436    return 0;
   1437}
   1438
   1439Chardev *serial_hd(int i)
   1440{
   1441    assert(i >= 0);
   1442    if (i < num_serial_hds) {
   1443        return serial_hds[i];
   1444    }
   1445    return NULL;
   1446}
   1447
   1448static int parallel_parse(const char *devname)
   1449{
   1450    static int index = 0;
   1451    char label[32];
   1452
   1453    if (strcmp(devname, "none") == 0)
   1454        return 0;
   1455    if (index == MAX_PARALLEL_PORTS) {
   1456        error_report("too many parallel ports");
   1457        exit(1);
   1458    }
   1459    snprintf(label, sizeof(label), "parallel%d", index);
   1460    parallel_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
   1461    if (!parallel_hds[index]) {
   1462        error_report("could not connect parallel device"
   1463                     " to character backend '%s'", devname);
   1464        return -1;
   1465    }
   1466    index++;
   1467    return 0;
   1468}
   1469
   1470static int debugcon_parse(const char *devname)
   1471{
   1472    QemuOpts *opts;
   1473
   1474    if (!qemu_chr_new_mux_mon("debugcon", devname, NULL)) {
   1475        error_report("invalid character backend '%s'", devname);
   1476        exit(1);
   1477    }
   1478    opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1, NULL);
   1479    if (!opts) {
   1480        error_report("already have a debugcon device");
   1481        exit(1);
   1482    }
   1483    qemu_opt_set(opts, "driver", "isa-debugcon", &error_abort);
   1484    qemu_opt_set(opts, "chardev", "debugcon", &error_abort);
   1485    return 0;
   1486}
   1487
   1488static gint machine_class_cmp(gconstpointer a, gconstpointer b)
   1489{
   1490    const MachineClass *mc1 = a, *mc2 = b;
   1491    int res;
   1492
   1493    if (mc1->family == NULL) {
   1494        if (mc2->family == NULL) {
   1495            /* Compare standalone machine types against each other; they sort
   1496             * in increasing order.
   1497             */
   1498            return strcmp(object_class_get_name(OBJECT_CLASS(mc1)),
   1499                          object_class_get_name(OBJECT_CLASS(mc2)));
   1500        }
   1501
   1502        /* Standalone machine types sort after families. */
   1503        return 1;
   1504    }
   1505
   1506    if (mc2->family == NULL) {
   1507        /* Families sort before standalone machine types. */
   1508        return -1;
   1509    }
   1510
   1511    /* Families sort between each other alphabetically increasingly. */
   1512    res = strcmp(mc1->family, mc2->family);
   1513    if (res != 0) {
   1514        return res;
   1515    }
   1516
   1517    /* Within the same family, machine types sort in decreasing order. */
   1518    return strcmp(object_class_get_name(OBJECT_CLASS(mc2)),
   1519                  object_class_get_name(OBJECT_CLASS(mc1)));
   1520}
   1521
   1522static void machine_help_func(const QDict *qdict)
   1523{
   1524    GSList *machines, *el;
   1525    const char *type = qdict_get_try_str(qdict, "type");
   1526
   1527    machines = object_class_get_list(TYPE_MACHINE, false);
   1528    if (type) {
   1529        ObjectClass *machine_class = OBJECT_CLASS(find_machine(type, machines));
   1530        if (machine_class) {
   1531            type_print_class_properties(object_class_get_name(machine_class));
   1532            return;
   1533        }
   1534    }
   1535
   1536    printf("Supported machines are:\n");
   1537    machines = g_slist_sort(machines, machine_class_cmp);
   1538    for (el = machines; el; el = el->next) {
   1539        MachineClass *mc = el->data;
   1540        if (mc->alias) {
   1541            printf("%-20s %s (alias of %s)\n", mc->alias, mc->desc, mc->name);
   1542        }
   1543        printf("%-20s %s%s%s\n", mc->name, mc->desc,
   1544               mc->is_default ? " (default)" : "",
   1545               mc->deprecation_reason ? " (deprecated)" : "");
   1546    }
   1547}
   1548
   1549static void
   1550machine_merge_property(const char *propname, QDict *prop, Error **errp)
   1551{
   1552    QDict *opts;
   1553
   1554    opts = qdict_new();
   1555    /* Preserve the caller's reference to prop.  */
   1556    qobject_ref(prop);
   1557    qdict_put(opts, propname, prop);
   1558    keyval_merge(machine_opts_dict, opts, errp);
   1559    qobject_unref(opts);
   1560}
   1561
   1562static void
   1563machine_parse_property_opt(QemuOptsList *opts_list, const char *propname,
   1564                           const char *arg)
   1565{
   1566    QDict *prop = NULL;
   1567    bool help = false;
   1568
   1569    prop = keyval_parse(arg, opts_list->implied_opt_name, &help, &error_fatal);
   1570    if (help) {
   1571        qemu_opts_print_help(opts_list, true);
   1572        exit(0);
   1573    }
   1574    machine_merge_property(propname, prop, &error_fatal);
   1575    qobject_unref(prop);
   1576}
   1577
   1578static const char *pid_file;
   1579static Notifier qemu_unlink_pidfile_notifier;
   1580
   1581static void qemu_unlink_pidfile(Notifier *n, void *data)
   1582{
   1583    if (pid_file) {
   1584        unlink(pid_file);
   1585    }
   1586}
   1587
   1588static const QEMUOption *lookup_opt(int argc, char **argv,
   1589                                    const char **poptarg, int *poptind)
   1590{
   1591    const QEMUOption *popt;
   1592    int optind = *poptind;
   1593    char *r = argv[optind];
   1594    const char *optarg;
   1595
   1596    loc_set_cmdline(argv, optind, 1);
   1597    optind++;
   1598    /* Treat --foo the same as -foo.  */
   1599    if (r[1] == '-')
   1600        r++;
   1601    popt = qemu_options;
   1602    for(;;) {
   1603        if (!popt->name) {
   1604            error_report("invalid option");
   1605            exit(1);
   1606        }
   1607        if (!strcmp(popt->name, r + 1))
   1608            break;
   1609        popt++;
   1610    }
   1611    if (popt->flags & HAS_ARG) {
   1612        if (optind >= argc) {
   1613            error_report("requires an argument");
   1614            exit(1);
   1615        }
   1616        optarg = argv[optind++];
   1617        loc_set_cmdline(argv, optind - 2, 2);
   1618    } else {
   1619        optarg = NULL;
   1620    }
   1621
   1622    *poptarg = optarg;
   1623    *poptind = optind;
   1624
   1625    return popt;
   1626}
   1627
   1628static MachineClass *select_machine(QDict *qdict, Error **errp)
   1629{
   1630    const char *optarg = qdict_get_try_str(qdict, "type");
   1631    GSList *machines = object_class_get_list(TYPE_MACHINE, false);
   1632    MachineClass *machine_class;
   1633    Error *local_err = NULL;
   1634
   1635    if (optarg) {
   1636        machine_class = find_machine(optarg, machines);
   1637        qdict_del(qdict, "type");
   1638        if (!machine_class) {
   1639            error_setg(&local_err, "unsupported machine type");
   1640        }
   1641    } else {
   1642        machine_class = find_default_machine(machines);
   1643        if (!machine_class) {
   1644            error_setg(&local_err, "No machine specified, and there is no default");
   1645        }
   1646    }
   1647
   1648    g_slist_free(machines);
   1649    if (local_err) {
   1650        error_append_hint(&local_err, "Use -machine help to list supported machines\n");
   1651        error_propagate(errp, local_err);
   1652    }
   1653    return machine_class;
   1654}
   1655
   1656static int object_parse_property_opt(Object *obj,
   1657                                     const char *name, const char *value,
   1658                                     const char *skip, Error **errp)
   1659{
   1660    if (g_str_equal(name, skip)) {
   1661        return 0;
   1662    }
   1663
   1664    if (!object_property_parse(obj, name, value, errp)) {
   1665        return -1;
   1666    }
   1667
   1668    return 0;
   1669}
   1670
   1671/* *Non*recursively replace underscores with dashes in QDict keys.  */
   1672static void keyval_dashify(QDict *qdict, Error **errp)
   1673{
   1674    const QDictEntry *ent, *next;
   1675    char *p;
   1676
   1677    for (ent = qdict_first(qdict); ent; ent = next) {
   1678        g_autofree char *new_key = NULL;
   1679
   1680        next = qdict_next(qdict, ent);
   1681        if (!strchr(ent->key, '_')) {
   1682            continue;
   1683        }
   1684        new_key = g_strdup(ent->key);
   1685        for (p = new_key; *p; p++) {
   1686            if (*p == '_') {
   1687                *p = '-';
   1688            }
   1689        }
   1690        if (qdict_haskey(qdict, new_key)) {
   1691            error_setg(errp, "Conflict between '%s' and '%s'", ent->key, new_key);
   1692            return;
   1693        }
   1694        qobject_ref(ent->value);
   1695        qdict_put_obj(qdict, new_key, ent->value);
   1696        qdict_del(qdict, ent->key);
   1697    }
   1698}
   1699
   1700static void qemu_apply_legacy_machine_options(QDict *qdict)
   1701{
   1702    const char *value;
   1703
   1704    keyval_dashify(qdict, &error_fatal);
   1705
   1706    /* Legacy options do not correspond to MachineState properties.  */
   1707    value = qdict_get_try_str(qdict, "accel");
   1708    if (value) {
   1709        accelerators = g_strdup(value);
   1710        qdict_del(qdict, "accel");
   1711    }
   1712
   1713    value = qdict_get_try_str(qdict, "igd-passthru");
   1714    if (value) {
   1715        object_register_sugar_prop(ACCEL_CLASS_NAME("xen"), "igd-passthru", value,
   1716                                   false);
   1717        qdict_del(qdict, "igd-passthru");
   1718    }
   1719
   1720    value = qdict_get_try_str(qdict, "kvm-shadow-mem");
   1721    if (value) {
   1722        object_register_sugar_prop(ACCEL_CLASS_NAME("kvm"), "kvm-shadow-mem", value,
   1723                                   false);
   1724        qdict_del(qdict, "kvm-shadow-mem");
   1725    }
   1726
   1727    value = qdict_get_try_str(qdict, "kernel-irqchip");
   1728    if (value) {
   1729        object_register_sugar_prop(ACCEL_CLASS_NAME("kvm"), "kernel-irqchip", value,
   1730                                   false);
   1731        object_register_sugar_prop(ACCEL_CLASS_NAME("whpx"), "kernel-irqchip", value,
   1732                                   false);
   1733        qdict_del(qdict, "kernel-irqchip");
   1734    }
   1735}
   1736
   1737static void object_option_foreach_add(bool (*type_opt_predicate)(const char *))
   1738{
   1739    ObjectOption *opt, *next;
   1740
   1741    QTAILQ_FOREACH_SAFE(opt, &object_opts, next, next) {
   1742        const char *type = ObjectType_str(opt->opts->qom_type);
   1743        if (type_opt_predicate(type)) {
   1744            user_creatable_add_qapi(opt->opts, &error_fatal);
   1745            qapi_free_ObjectOptions(opt->opts);
   1746            QTAILQ_REMOVE(&object_opts, opt, next);
   1747            g_free(opt);
   1748        }
   1749    }
   1750}
   1751
   1752static void object_option_add_visitor(Visitor *v)
   1753{
   1754    ObjectOption *opt = g_new0(ObjectOption, 1);
   1755    visit_type_ObjectOptions(v, NULL, &opt->opts, &error_fatal);
   1756    QTAILQ_INSERT_TAIL(&object_opts, opt, next);
   1757}
   1758
   1759static void object_option_parse(const char *optarg)
   1760{
   1761    QemuOpts *opts;
   1762    const char *type;
   1763    Visitor *v;
   1764
   1765    if (optarg[0] == '{') {
   1766        QObject *obj = qobject_from_json(optarg, &error_fatal);
   1767
   1768        v = qobject_input_visitor_new(obj);
   1769        qobject_unref(obj);
   1770    } else {
   1771        opts = qemu_opts_parse_noisily(qemu_find_opts("object"),
   1772                                       optarg, true);
   1773        if (!opts) {
   1774            exit(1);
   1775        }
   1776
   1777        type = qemu_opt_get(opts, "qom-type");
   1778        if (!type) {
   1779            error_setg(&error_fatal, QERR_MISSING_PARAMETER, "qom-type");
   1780        }
   1781        if (user_creatable_print_help(type, opts)) {
   1782            exit(0);
   1783        }
   1784
   1785        v = opts_visitor_new(opts);
   1786    }
   1787
   1788    object_option_add_visitor(v);
   1789    visit_free(v);
   1790}
   1791
   1792/*
   1793 * Initial object creation happens before all other
   1794 * QEMU data types are created. The majority of objects
   1795 * can be created at this point. The rng-egd object
   1796 * cannot be created here, as it depends on the chardev
   1797 * already existing.
   1798 */
   1799static bool object_create_early(const char *type)
   1800{
   1801    /*
   1802     * Objects should not be made "delayed" without a reason.  If you
   1803     * add one, state the reason in a comment!
   1804     */
   1805
   1806    /* Reason: property "chardev" */
   1807    if (g_str_equal(type, "rng-egd") ||
   1808        g_str_equal(type, "qtest")) {
   1809        return false;
   1810    }
   1811
   1812#if defined(CONFIG_VHOST_USER) && defined(CONFIG_LINUX)
   1813    /* Reason: cryptodev-vhost-user property "chardev" */
   1814    if (g_str_equal(type, "cryptodev-vhost-user")) {
   1815        return false;
   1816    }
   1817#endif
   1818
   1819    /* Reason: vhost-user-blk-server property "node-name" */
   1820    if (g_str_equal(type, "vhost-user-blk-server")) {
   1821        return false;
   1822    }
   1823    /*
   1824     * Reason: filter-* property "netdev" etc.
   1825     */
   1826    if (g_str_equal(type, "filter-buffer") ||
   1827        g_str_equal(type, "filter-dump") ||
   1828        g_str_equal(type, "filter-mirror") ||
   1829        g_str_equal(type, "filter-redirector") ||
   1830        g_str_equal(type, "colo-compare") ||
   1831        g_str_equal(type, "filter-rewriter") ||
   1832        g_str_equal(type, "filter-replay")) {
   1833        return false;
   1834    }
   1835
   1836    /*
   1837     * Allocation of large amounts of memory may delay
   1838     * chardev initialization for too long, and trigger timeouts
   1839     * on software that waits for a monitor socket to be created
   1840     * (e.g. libvirt).
   1841     */
   1842    if (g_str_has_prefix(type, "memory-backend-")) {
   1843        return false;
   1844    }
   1845
   1846    return true;
   1847}
   1848
   1849static void qemu_apply_machine_options(QDict *qdict)
   1850{
   1851    MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
   1852    const char *boot_order = NULL;
   1853    const char *boot_once = NULL;
   1854    QemuOpts *opts;
   1855
   1856    object_set_properties_from_keyval(OBJECT(current_machine), qdict, false, &error_fatal);
   1857    current_machine->ram_size = ram_size;
   1858    current_machine->maxram_size = maxram_size;
   1859    current_machine->ram_slots = ram_slots;
   1860
   1861    opts = qemu_opts_find(qemu_find_opts("boot-opts"), NULL);
   1862    if (opts) {
   1863        boot_order = qemu_opt_get(opts, "order");
   1864        if (boot_order) {
   1865            validate_bootdevices(boot_order, &error_fatal);
   1866        }
   1867
   1868        boot_once = qemu_opt_get(opts, "once");
   1869        if (boot_once) {
   1870            validate_bootdevices(boot_once, &error_fatal);
   1871        }
   1872
   1873        boot_menu = qemu_opt_get_bool(opts, "menu", boot_menu);
   1874        boot_strict = qemu_opt_get_bool(opts, "strict", false);
   1875    }
   1876
   1877    if (!boot_order) {
   1878        boot_order = machine_class->default_boot_order;
   1879    }
   1880
   1881    current_machine->boot_order = boot_order;
   1882    current_machine->boot_once = boot_once;
   1883
   1884    if (semihosting_enabled() && !semihosting_get_argc()) {
   1885        /* fall back to the -kernel/-append */
   1886        semihosting_arg_fallback(current_machine->kernel_filename, current_machine->kernel_cmdline);
   1887    }
   1888
   1889    if (current_machine->smp.cpus > 1) {
   1890        Error *blocker = NULL;
   1891        error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED, "smp");
   1892        replay_add_blocker(blocker);
   1893    }
   1894}
   1895
   1896static void qemu_create_early_backends(void)
   1897{
   1898    MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
   1899#if defined(CONFIG_SDL)
   1900    const bool use_sdl = (dpy.type == DISPLAY_TYPE_SDL);
   1901#else
   1902    const bool use_sdl = false;
   1903#endif
   1904#if defined(CONFIG_GTK)
   1905    const bool use_gtk = (dpy.type == DISPLAY_TYPE_GTK);
   1906#else
   1907    const bool use_gtk = false;
   1908#endif
   1909
   1910    if ((alt_grab || ctrl_grab) && !use_sdl) {
   1911        error_report("-alt-grab and -ctrl-grab are only valid "
   1912                     "for SDL, ignoring option");
   1913    }
   1914    if (dpy.has_window_close && !use_gtk && !use_sdl) {
   1915        error_report("-no-quit is only valid for GTK and SDL, "
   1916                     "ignoring option");
   1917    }
   1918
   1919    qemu_display_early_init(&dpy);
   1920    qemu_console_early_init();
   1921
   1922    if (dpy.has_gl && dpy.gl != DISPLAYGL_MODE_OFF && display_opengl == 0) {
   1923#if defined(CONFIG_OPENGL)
   1924        error_report("OpenGL is not supported by the display");
   1925#else
   1926        error_report("OpenGL support is disabled");
   1927#endif
   1928        exit(1);
   1929    }
   1930
   1931    object_option_foreach_add(object_create_early);
   1932
   1933    /* spice needs the timers to be initialized by this point */
   1934    /* spice must initialize before audio as it changes the default auiodev */
   1935    /* spice must initialize before chardevs (for spicevmc and spiceport) */
   1936    qemu_spice.init();
   1937
   1938    qemu_opts_foreach(qemu_find_opts("chardev"),
   1939                      chardev_init_func, NULL, &error_fatal);
   1940
   1941#ifdef CONFIG_VIRTFS
   1942    qemu_opts_foreach(qemu_find_opts("fsdev"),
   1943                      fsdev_init_func, NULL, &error_fatal);
   1944#endif
   1945
   1946    /*
   1947     * Note: we need to create audio and block backends before
   1948     * setting machine properties, so they can be referred to.
   1949     */
   1950    configure_blockdev(&bdo_queue, machine_class, snapshot);
   1951    audio_init_audiodevs();
   1952}
   1953
   1954
   1955/*
   1956 * The remainder of object creation happens after the
   1957 * creation of chardev, fsdev, net clients and device data types.
   1958 */
   1959static bool object_create_late(const char *type)
   1960{
   1961    return !object_create_early(type);
   1962}
   1963
   1964static void qemu_create_late_backends(void)
   1965{
   1966    if (qtest_chrdev) {
   1967        qtest_server_init(qtest_chrdev, qtest_log, &error_fatal);
   1968    }
   1969
   1970    net_init_clients(&error_fatal);
   1971
   1972    object_option_foreach_add(object_create_late);
   1973
   1974    if (tpm_init() < 0) {
   1975        exit(1);
   1976    }
   1977
   1978    qemu_opts_foreach(qemu_find_opts("mon"),
   1979                      mon_init_func, NULL, &error_fatal);
   1980
   1981    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
   1982        exit(1);
   1983    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
   1984        exit(1);
   1985    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
   1986        exit(1);
   1987
   1988    /* now chardevs have been created we may have semihosting to connect */
   1989    qemu_semihosting_connect_chardevs();
   1990    qemu_semihosting_console_init();
   1991}
   1992
   1993static bool have_custom_ram_size(void)
   1994{
   1995    QemuOpts *opts = qemu_find_opts_singleton("memory");
   1996    return !!qemu_opt_get_size(opts, "size", 0);
   1997}
   1998
   1999static void qemu_resolve_machine_memdev(void)
   2000{
   2001    if (current_machine->ram_memdev_id) {
   2002        Object *backend;
   2003        ram_addr_t backend_size;
   2004
   2005        backend = object_resolve_path_type(current_machine->ram_memdev_id,
   2006                                           TYPE_MEMORY_BACKEND, NULL);
   2007        if (!backend) {
   2008            error_report("Memory backend '%s' not found",
   2009                         current_machine->ram_memdev_id);
   2010            exit(EXIT_FAILURE);
   2011        }
   2012        backend_size = object_property_get_uint(backend, "size",  &error_abort);
   2013        if (have_custom_ram_size() && backend_size != ram_size) {
   2014                error_report("Size specified by -m option must match size of "
   2015                             "explicitly specified 'memory-backend' property");
   2016                exit(EXIT_FAILURE);
   2017        }
   2018        if (mem_path) {
   2019            error_report("'-mem-path' can't be used together with"
   2020                         "'-machine memory-backend'");
   2021            exit(EXIT_FAILURE);
   2022        }
   2023        ram_size = backend_size;
   2024    }
   2025
   2026    if (!xen_enabled()) {
   2027        /* On 32-bit hosts, QEMU is limited by virtual address space */
   2028        if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
   2029            error_report("at most 2047 MB RAM can be simulated");
   2030            exit(1);
   2031        }
   2032    }
   2033}
   2034
   2035static void set_memory_options(MachineClass *mc)
   2036{
   2037    uint64_t sz;
   2038    const char *mem_str;
   2039    const ram_addr_t default_ram_size = mc->default_ram_size;
   2040    QemuOpts *opts = qemu_find_opts_singleton("memory");
   2041    Location loc;
   2042
   2043    loc_push_none(&loc);
   2044    qemu_opts_loc_restore(opts);
   2045
   2046    sz = 0;
   2047    mem_str = qemu_opt_get(opts, "size");
   2048    if (mem_str) {
   2049        if (!*mem_str) {
   2050            error_report("missing 'size' option value");
   2051            exit(EXIT_FAILURE);
   2052        }
   2053
   2054        sz = qemu_opt_get_size(opts, "size", ram_size);
   2055
   2056        /* Fix up legacy suffix-less format */
   2057        if (g_ascii_isdigit(mem_str[strlen(mem_str) - 1])) {
   2058            uint64_t overflow_check = sz;
   2059
   2060            sz *= MiB;
   2061            if (sz / MiB != overflow_check) {
   2062                error_report("too large 'size' option value");
   2063                exit(EXIT_FAILURE);
   2064            }
   2065        }
   2066    }
   2067
   2068    /* backward compatibility behaviour for case "-m 0" */
   2069    if (sz == 0) {
   2070        sz = default_ram_size;
   2071    }
   2072
   2073    sz = QEMU_ALIGN_UP(sz, 8192);
   2074    if (mc->fixup_ram_size) {
   2075        sz = mc->fixup_ram_size(sz);
   2076    }
   2077    ram_size = sz;
   2078    if (ram_size != sz) {
   2079        error_report("ram size too large");
   2080        exit(EXIT_FAILURE);
   2081    }
   2082
   2083    maxram_size = ram_size;
   2084
   2085    if (qemu_opt_get(opts, "maxmem")) {
   2086        uint64_t slots;
   2087
   2088        sz = qemu_opt_get_size(opts, "maxmem", 0);
   2089        slots = qemu_opt_get_number(opts, "slots", 0);
   2090        if (sz < ram_size) {
   2091            error_report("invalid value of -m option maxmem: "
   2092                         "maximum memory size (0x%" PRIx64 ") must be at least "
   2093                         "the initial memory size (0x" RAM_ADDR_FMT ")",
   2094                         sz, ram_size);
   2095            exit(EXIT_FAILURE);
   2096        } else if (slots && sz == ram_size) {
   2097            error_report("invalid value of -m option maxmem: "
   2098                         "memory slots were specified but maximum memory size "
   2099                         "(0x%" PRIx64 ") is equal to the initial memory size "
   2100                         "(0x" RAM_ADDR_FMT ")", sz, ram_size);
   2101            exit(EXIT_FAILURE);
   2102        }
   2103
   2104        maxram_size = sz;
   2105        ram_slots = slots;
   2106    } else if (qemu_opt_get(opts, "slots")) {
   2107        error_report("invalid -m option value: missing 'maxmem' option");
   2108        exit(EXIT_FAILURE);
   2109    }
   2110
   2111    loc_pop(&loc);
   2112}
   2113
   2114static void qemu_create_machine(QDict *qdict)
   2115{
   2116    MachineClass *machine_class = select_machine(qdict, &error_fatal);
   2117    object_set_machine_compat_props(machine_class->compat_props);
   2118
   2119    set_memory_options(machine_class);
   2120
   2121    current_machine = MACHINE(object_new_with_class(OBJECT_CLASS(machine_class)));
   2122    object_property_add_child(object_get_root(), "machine",
   2123                              OBJECT(current_machine));
   2124    object_property_add_child(container_get(OBJECT(current_machine),
   2125                                            "/unattached"),
   2126                              "sysbus", OBJECT(sysbus_get_default()));
   2127
   2128    if (machine_class->minimum_page_bits) {
   2129        if (!set_preferred_target_page_bits(machine_class->minimum_page_bits)) {
   2130            /* This would be a board error: specifying a minimum smaller than
   2131             * a target's compile-time fixed setting.
   2132             */
   2133            g_assert_not_reached();
   2134        }
   2135    }
   2136
   2137    cpu_exec_init_all();
   2138    page_size_init();
   2139
   2140    if (machine_class->hw_version) {
   2141        qemu_set_hw_version(machine_class->hw_version);
   2142    }
   2143
   2144    /*
   2145     * Get the default machine options from the machine if it is not already
   2146     * specified either by the configuration file or by the command line.
   2147     */
   2148    if (machine_class->default_machine_opts) {
   2149        QDict *default_opts =
   2150            keyval_parse(machine_class->default_machine_opts, NULL, NULL,
   2151                         &error_abort);
   2152        qemu_apply_legacy_machine_options(default_opts);
   2153        object_set_properties_from_keyval(OBJECT(current_machine), default_opts,
   2154                                          false, &error_abort);
   2155        qobject_unref(default_opts);
   2156    }
   2157}
   2158
   2159static int global_init_func(void *opaque, QemuOpts *opts, Error **errp)
   2160{
   2161    GlobalProperty *g;
   2162
   2163    g = g_malloc0(sizeof(*g));
   2164    g->driver   = qemu_opt_get(opts, "driver");
   2165    g->property = qemu_opt_get(opts, "property");
   2166    g->value    = qemu_opt_get(opts, "value");
   2167    qdev_prop_register_global(g);
   2168    return 0;
   2169}
   2170
   2171/*
   2172 * Return whether configuration group @group is stored in QemuOpts, or
   2173 * recorded as one or more QDicts by qemu_record_config_group.
   2174 */
   2175static bool is_qemuopts_group(const char *group)
   2176{
   2177    if (g_str_equal(group, "object") ||
   2178        g_str_equal(group, "machine") ||
   2179        g_str_equal(group, "smp-opts")) {
   2180        return false;
   2181    }
   2182    return true;
   2183}
   2184
   2185static void qemu_record_config_group(const char *group, QDict *dict,
   2186                                     bool from_json, Error **errp)
   2187{
   2188    if (g_str_equal(group, "object")) {
   2189        Visitor *v = qobject_input_visitor_new_keyval(QOBJECT(dict));
   2190        object_option_add_visitor(v);
   2191        visit_free(v);
   2192    } else if (g_str_equal(group, "machine")) {
   2193        /*
   2194         * Cannot merge string-valued and type-safe dictionaries, so JSON
   2195         * is not accepted yet for -M.
   2196         */
   2197        assert(!from_json);
   2198        keyval_merge(machine_opts_dict, dict, errp);
   2199    } else if (g_str_equal(group, "smp-opts")) {
   2200        machine_merge_property("smp", dict, &error_fatal);
   2201    } else {
   2202        abort();
   2203    }
   2204}
   2205
   2206/*
   2207 * Parse non-QemuOpts config file groups, pass the rest to
   2208 * qemu_config_do_parse.
   2209 */
   2210static void qemu_parse_config_group(const char *group, QDict *qdict,
   2211                                    void *opaque, Error **errp)
   2212{
   2213    QObject *crumpled;
   2214    if (is_qemuopts_group(group)) {
   2215        qemu_config_do_parse(group, qdict, opaque, errp);
   2216        return;
   2217    }
   2218
   2219    crumpled = qdict_crumple(qdict, errp);
   2220    if (!crumpled) {
   2221        return;
   2222    }
   2223    switch (qobject_type(crumpled)) {
   2224    case QTYPE_QDICT:
   2225        qemu_record_config_group(group, qobject_to(QDict, crumpled), false, errp);
   2226        break;
   2227    case QTYPE_QLIST:
   2228        error_setg(errp, "Lists cannot be at top level of a configuration section");
   2229        break;
   2230    default:
   2231        g_assert_not_reached();
   2232    }
   2233    qobject_unref(crumpled);
   2234}
   2235
   2236static void qemu_read_default_config_file(Error **errp)
   2237{
   2238    ERRP_GUARD();
   2239    int ret;
   2240    g_autofree char *file = get_relocated_path(CONFIG_QEMU_CONFDIR "/qemu.conf");
   2241
   2242    ret = qemu_read_config_file(file, qemu_parse_config_group, errp);
   2243    if (ret < 0) {
   2244        if (ret == -ENOENT) {
   2245            error_free(*errp);
   2246            *errp = NULL;
   2247        }
   2248    }
   2249}
   2250
   2251static void qemu_set_option(const char *str, Error **errp)
   2252{
   2253    char group[64], id[64], arg[64];
   2254    QemuOptsList *list;
   2255    QemuOpts *opts;
   2256    int rc, offset;
   2257
   2258    rc = sscanf(str, "%63[^.].%63[^.].%63[^=]%n", group, id, arg, &offset);
   2259    if (rc < 3 || str[offset] != '=') {
   2260        error_setg(errp, "can't parse: \"%s\"", str);
   2261        return;
   2262    }
   2263
   2264    if (!is_qemuopts_group(group)) {
   2265        error_setg(errp, "-set is not supported with %s", group);
   2266    } else {
   2267        list = qemu_find_opts_err(group, errp);
   2268        if (list) {
   2269            opts = qemu_opts_find(list, id);
   2270            if (!opts) {
   2271                error_setg(errp, "there is no %s \"%s\" defined", group, id);
   2272                return;
   2273            }
   2274            qemu_opt_set(opts, arg, str + offset + 1, errp);
   2275        }
   2276    }
   2277}
   2278
   2279static void user_register_global_props(void)
   2280{
   2281    qemu_opts_foreach(qemu_find_opts("global"),
   2282                      global_init_func, NULL, NULL);
   2283}
   2284
   2285static int do_configure_icount(void *opaque, QemuOpts *opts, Error **errp)
   2286{
   2287    icount_configure(opts, errp);
   2288    return 0;
   2289}
   2290
   2291static int accelerator_set_property(void *opaque,
   2292                                const char *name, const char *value,
   2293                                Error **errp)
   2294{
   2295    return object_parse_property_opt(opaque, name, value, "accel", errp);
   2296}
   2297
   2298static int do_configure_accelerator(void *opaque, QemuOpts *opts, Error **errp)
   2299{
   2300    bool *p_init_failed = opaque;
   2301    const char *acc = qemu_opt_get(opts, "accel");
   2302    AccelClass *ac = accel_find(acc);
   2303    AccelState *accel;
   2304    int ret;
   2305    bool qtest_with_kvm;
   2306
   2307    qtest_with_kvm = g_str_equal(acc, "kvm") && qtest_chrdev != NULL;
   2308
   2309    if (!ac) {
   2310        *p_init_failed = true;
   2311        if (!qtest_with_kvm) {
   2312            error_report("invalid accelerator %s", acc);
   2313        }
   2314        return 0;
   2315    }
   2316    accel = ACCEL(object_new_with_class(OBJECT_CLASS(ac)));
   2317    object_apply_compat_props(OBJECT(accel));
   2318    qemu_opt_foreach(opts, accelerator_set_property,
   2319                     accel,
   2320                     &error_fatal);
   2321
   2322    ret = accel_init_machine(accel, current_machine);
   2323    if (ret < 0) {
   2324        *p_init_failed = true;
   2325        if (!qtest_with_kvm || ret != -ENOENT) {
   2326            error_report("failed to initialize %s: %s", acc, strerror(-ret));
   2327        }
   2328        return 0;
   2329    }
   2330
   2331    return 1;
   2332}
   2333
   2334static void configure_accelerators(const char *progname)
   2335{
   2336    bool init_failed = false;
   2337
   2338    qemu_opts_foreach(qemu_find_opts("icount"),
   2339                      do_configure_icount, NULL, &error_fatal);
   2340
   2341    if (QTAILQ_EMPTY(&qemu_accel_opts.head)) {
   2342        char **accel_list, **tmp;
   2343
   2344        if (accelerators == NULL) {
   2345            /* Select the default accelerator */
   2346            bool have_tcg = accel_find("tcg");
   2347            bool have_kvm = accel_find("kvm");
   2348
   2349            if (have_tcg && have_kvm) {
   2350                if (g_str_has_suffix(progname, "kvm")) {
   2351                    /* If the program name ends with "kvm", we prefer KVM */
   2352                    accelerators = "kvm:tcg";
   2353                } else {
   2354                    accelerators = "tcg:kvm";
   2355                }
   2356            } else if (have_kvm) {
   2357                accelerators = "kvm";
   2358            } else if (have_tcg) {
   2359                accelerators = "tcg";
   2360            } else {
   2361                error_report("No accelerator selected and"
   2362                             " no default accelerator available");
   2363                exit(1);
   2364            }
   2365        }
   2366        accel_list = g_strsplit(accelerators, ":", 0);
   2367
   2368        for (tmp = accel_list; *tmp; tmp++) {
   2369            /*
   2370             * Filter invalid accelerators here, to prevent obscenities
   2371             * such as "-machine accel=tcg,,thread=single".
   2372             */
   2373            if (accel_find(*tmp)) {
   2374                qemu_opts_parse_noisily(qemu_find_opts("accel"), *tmp, true);
   2375            } else {
   2376                init_failed = true;
   2377                error_report("invalid accelerator %s", *tmp);
   2378            }
   2379        }
   2380        g_strfreev(accel_list);
   2381    } else {
   2382        if (accelerators != NULL) {
   2383            error_report("The -accel and \"-machine accel=\" options are incompatible");
   2384            exit(1);
   2385        }
   2386    }
   2387
   2388    if (!qemu_opts_foreach(qemu_find_opts("accel"),
   2389                           do_configure_accelerator, &init_failed, &error_fatal)) {
   2390        if (!init_failed) {
   2391            error_report("no accelerator found");
   2392        }
   2393        exit(1);
   2394    }
   2395
   2396    if (init_failed && !qtest_chrdev) {
   2397        AccelClass *ac = ACCEL_GET_CLASS(current_accel());
   2398        error_report("falling back to %s", ac->name);
   2399    }
   2400
   2401    if (icount_enabled() && !tcg_enabled()) {
   2402        error_report("-icount is not allowed with hardware virtualization");
   2403        exit(1);
   2404    }
   2405}
   2406
   2407static void create_default_memdev(MachineState *ms, const char *path)
   2408{
   2409    Object *obj;
   2410    MachineClass *mc = MACHINE_GET_CLASS(ms);
   2411
   2412    obj = object_new(path ? TYPE_MEMORY_BACKEND_FILE : TYPE_MEMORY_BACKEND_RAM);
   2413    if (path) {
   2414        object_property_set_str(obj, "mem-path", path, &error_fatal);
   2415    }
   2416    object_property_set_int(obj, "size", ms->ram_size, &error_fatal);
   2417    object_property_add_child(object_get_objects_root(), mc->default_ram_id,
   2418                              obj);
   2419    /* Ensure backend's memory region name is equal to mc->default_ram_id */
   2420    object_property_set_bool(obj, "x-use-canonical-path-for-ramblock-id",
   2421                             false, &error_fatal);
   2422    user_creatable_complete(USER_CREATABLE(obj), &error_fatal);
   2423    object_unref(obj);
   2424    object_property_set_str(OBJECT(ms), "memory-backend", mc->default_ram_id,
   2425                            &error_fatal);
   2426}
   2427
   2428static void qemu_validate_options(const QDict *machine_opts)
   2429{
   2430    const char *kernel_filename = qdict_get_try_str(machine_opts, "kernel");
   2431    const char *initrd_filename = qdict_get_try_str(machine_opts, "initrd");
   2432    const char *kernel_cmdline = qdict_get_try_str(machine_opts, "append");
   2433
   2434    if (kernel_filename == NULL) {
   2435         if (kernel_cmdline != NULL) {
   2436              error_report("-append only allowed with -kernel option");
   2437              exit(1);
   2438          }
   2439
   2440          if (initrd_filename != NULL) {
   2441              error_report("-initrd only allowed with -kernel option");
   2442              exit(1);
   2443          }
   2444    }
   2445
   2446    if (loadvm && preconfig_requested) {
   2447        error_report("'preconfig' and 'loadvm' options are "
   2448                     "mutually exclusive");
   2449        exit(EXIT_FAILURE);
   2450    }
   2451    if (incoming && preconfig_requested && strcmp(incoming, "defer") != 0) {
   2452        error_report("'preconfig' supports '-incoming defer' only");
   2453        exit(EXIT_FAILURE);
   2454    }
   2455
   2456#ifdef CONFIG_CURSES
   2457    if (is_daemonized() && dpy.type == DISPLAY_TYPE_CURSES) {
   2458        error_report("curses display cannot be used with -daemonize");
   2459        exit(1);
   2460    }
   2461#endif
   2462}
   2463
   2464static void qemu_process_sugar_options(void)
   2465{
   2466    if (mem_prealloc) {
   2467        QObject *smp = qdict_get(machine_opts_dict, "smp");
   2468        if (smp && qobject_type(smp) == QTYPE_QDICT) {
   2469            QObject *cpus = qdict_get(qobject_to(QDict, smp), "cpus");
   2470            if (cpus && qobject_type(cpus) == QTYPE_QSTRING) {
   2471                const char *val = qstring_get_str(qobject_to(QString, cpus));
   2472                object_register_sugar_prop("memory-backend", "prealloc-threads",
   2473                                           val, false);
   2474            }
   2475        }
   2476        object_register_sugar_prop("memory-backend", "prealloc", "on", false);
   2477    }
   2478
   2479    if (watchdog) {
   2480        int i = select_watchdog(watchdog);
   2481        if (i > 0)
   2482            exit (i == 1 ? 1 : 0);
   2483    }
   2484}
   2485
   2486/* -action processing */
   2487
   2488/*
   2489 * Process all the -action parameters parsed from cmdline.
   2490 */
   2491static int process_runstate_actions(void *opaque, QemuOpts *opts, Error **errp)
   2492{
   2493    Error *local_err = NULL;
   2494    QDict *qdict = qemu_opts_to_qdict(opts, NULL);
   2495    QObject *ret = NULL;
   2496    qmp_marshal_set_action(qdict, &ret, &local_err);
   2497    qobject_unref(ret);
   2498    qobject_unref(qdict);
   2499    if (local_err) {
   2500        error_propagate(errp, local_err);
   2501        return 1;
   2502    }
   2503    return 0;
   2504}
   2505
   2506static void qemu_process_early_options(void)
   2507{
   2508#ifdef CONFIG_SECCOMP
   2509    QemuOptsList *olist = qemu_find_opts_err("sandbox", NULL);
   2510    if (olist) {
   2511        qemu_opts_foreach(olist, parse_sandbox, NULL, &error_fatal);
   2512    }
   2513#endif
   2514
   2515    qemu_opts_foreach(qemu_find_opts("name"),
   2516                      parse_name, NULL, &error_fatal);
   2517
   2518    if (qemu_opts_foreach(qemu_find_opts("action"),
   2519                          process_runstate_actions, NULL, &error_fatal)) {
   2520        exit(1);
   2521    }
   2522
   2523#ifndef _WIN32
   2524    qemu_opts_foreach(qemu_find_opts("add-fd"),
   2525                      parse_add_fd, NULL, &error_fatal);
   2526
   2527    qemu_opts_foreach(qemu_find_opts("add-fd"),
   2528                      cleanup_add_fd, NULL, &error_fatal);
   2529#endif
   2530
   2531    /* Open the logfile at this point and set the log mask if necessary.  */
   2532    if (log_file) {
   2533        qemu_set_log_filename(log_file, &error_fatal);
   2534    }
   2535    if (log_mask) {
   2536        int mask;
   2537        mask = qemu_str_to_log_mask(log_mask);
   2538        if (!mask) {
   2539            qemu_print_log_usage(stdout);
   2540            exit(1);
   2541        }
   2542        qemu_set_log(mask);
   2543    } else {
   2544        qemu_set_log(0);
   2545    }
   2546
   2547    qemu_add_default_firmwarepath();
   2548}
   2549
   2550static void qemu_process_help_options(void)
   2551{
   2552    /*
   2553     * Check for -cpu help and -device help before we call select_machine(),
   2554     * which will return an error if the architecture has no default machine
   2555     * type and the user did not specify one, so that the user doesn't need
   2556     * to say '-cpu help -machine something'.
   2557     */
   2558    if (cpu_option && is_help_option(cpu_option)) {
   2559        list_cpus(cpu_option);
   2560        exit(0);
   2561    }
   2562
   2563    if (qemu_opts_foreach(qemu_find_opts("device"),
   2564                          device_help_func, NULL, NULL)) {
   2565        exit(0);
   2566    }
   2567
   2568    /* -L help lists the data directories and exits. */
   2569    if (list_data_dirs) {
   2570        qemu_list_data_dirs();
   2571        exit(0);
   2572    }
   2573}
   2574
   2575static void qemu_maybe_daemonize(const char *pid_file)
   2576{
   2577    Error *err = NULL;
   2578
   2579    os_daemonize();
   2580    rcu_disable_atfork();
   2581
   2582    if (pid_file && !qemu_write_pidfile(pid_file, &err)) {
   2583        error_reportf_err(err, "cannot create PID file: ");
   2584        exit(1);
   2585    }
   2586
   2587    qemu_unlink_pidfile_notifier.notify = qemu_unlink_pidfile;
   2588    qemu_add_exit_notifier(&qemu_unlink_pidfile_notifier);
   2589}
   2590
   2591static void qemu_init_displays(void)
   2592{
   2593    DisplayState *ds;
   2594
   2595    /* init local displays */
   2596    ds = init_displaystate();
   2597    qemu_display_init(ds, &dpy);
   2598
   2599    /* must be after terminal init, SDL library changes signal handlers */
   2600    os_setup_signal_handling();
   2601
   2602    /* init remote displays */
   2603#ifdef CONFIG_VNC
   2604    qemu_opts_foreach(qemu_find_opts("vnc"),
   2605                      vnc_init_func, NULL, &error_fatal);
   2606#endif
   2607
   2608    if (using_spice) {
   2609        qemu_spice.display_init();
   2610    }
   2611}
   2612
   2613static void qemu_init_board(void)
   2614{
   2615    MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
   2616
   2617    if (machine_class->default_ram_id && current_machine->ram_size &&
   2618        numa_uses_legacy_mem() && !current_machine->ram_memdev_id) {
   2619        create_default_memdev(current_machine, mem_path);
   2620    }
   2621
   2622    /* process plugin before CPUs are created, but once -smp has been parsed */
   2623    qemu_plugin_load_list(&plugin_list, &error_fatal);
   2624
   2625    /* From here on we enter MACHINE_PHASE_INITIALIZED.  */
   2626    machine_run_board_init(current_machine);
   2627
   2628    drive_check_orphaned();
   2629
   2630    realtime_init();
   2631
   2632    if (hax_enabled()) {
   2633        /* FIXME: why isn't cpu_synchronize_all_post_init enough? */
   2634        hax_sync_vcpus();
   2635    }
   2636}
   2637
   2638static void qemu_create_cli_devices(void)
   2639{
   2640    soundhw_init();
   2641
   2642    qemu_opts_foreach(qemu_find_opts("fw_cfg"),
   2643                      parse_fw_cfg, fw_cfg_find(), &error_fatal);
   2644
   2645    /* init USB devices */
   2646    if (machine_usb(current_machine)) {
   2647        if (foreach_device_config(DEV_USB, usb_parse) < 0)
   2648            exit(1);
   2649    }
   2650
   2651    /* init generic devices */
   2652    rom_set_order_override(FW_CFG_ORDER_OVERRIDE_DEVICE);
   2653    qemu_opts_foreach(qemu_find_opts("device"),
   2654                      device_init_func, NULL, &error_fatal);
   2655    rom_reset_order_override();
   2656}
   2657
   2658static void qemu_machine_creation_done(void)
   2659{
   2660    MachineState *machine = MACHINE(qdev_get_machine());
   2661
   2662    /* Did we create any drives that we failed to create a device for? */
   2663    drive_check_orphaned();
   2664
   2665    /* Don't warn about the default network setup that you get if
   2666     * no command line -net or -netdev options are specified. There
   2667     * are two cases that we would otherwise complain about:
   2668     * (1) board doesn't support a NIC but the implicit "-net nic"
   2669     * requested one
   2670     * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
   2671     * sets up a nic that isn't connected to anything.
   2672     */
   2673    if (!default_net && (!qtest_enabled() || has_defaults)) {
   2674        net_check_clients();
   2675    }
   2676
   2677    qdev_prop_check_globals();
   2678
   2679    qdev_machine_creation_done();
   2680
   2681    if (machine->cgs) {
   2682        /*
   2683         * Verify that Confidential Guest Support has actually been initialized
   2684         */
   2685        assert(machine->cgs->ready);
   2686    }
   2687
   2688    if (foreach_device_config(DEV_GDB, gdbserver_start) < 0) {
   2689        exit(1);
   2690    }
   2691}
   2692
   2693void qmp_x_exit_preconfig(Error **errp)
   2694{
   2695    if (phase_check(PHASE_MACHINE_INITIALIZED)) {
   2696        error_setg(errp, "The command is permitted only before machine initialization");
   2697        return;
   2698    }
   2699
   2700    qemu_init_board();
   2701    qemu_create_cli_devices();
   2702    qemu_machine_creation_done();
   2703
   2704    if (loadvm) {
   2705        load_snapshot(loadvm, NULL, false, NULL, &error_fatal);
   2706    }
   2707    if (replay_mode != REPLAY_MODE_NONE) {
   2708        replay_vmstate_init();
   2709    }
   2710
   2711    if (incoming) {
   2712        Error *local_err = NULL;
   2713        if (strcmp(incoming, "defer") != 0) {
   2714            qmp_migrate_incoming(incoming, &local_err);
   2715            if (local_err) {
   2716                error_reportf_err(local_err, "-incoming %s: ", incoming);
   2717                exit(1);
   2718            }
   2719        }
   2720    } else if (autostart) {
   2721        qmp_cont(NULL);
   2722    }
   2723}
   2724
   2725void qemu_init(int argc, char **argv, char **envp)
   2726{
   2727    QemuOpts *opts;
   2728    QemuOpts *icount_opts = NULL, *accel_opts = NULL;
   2729    QemuOptsList *olist;
   2730    int optind;
   2731    const char *optarg;
   2732    MachineClass *machine_class;
   2733    bool userconfig = true;
   2734    FILE *vmstate_dump_file = NULL;
   2735
   2736    qemu_add_opts(&qemu_drive_opts);
   2737    qemu_add_drive_opts(&qemu_legacy_drive_opts);
   2738    qemu_add_drive_opts(&qemu_common_drive_opts);
   2739    qemu_add_drive_opts(&qemu_drive_opts);
   2740    qemu_add_drive_opts(&bdrv_runtime_opts);
   2741    qemu_add_opts(&qemu_chardev_opts);
   2742    qemu_add_opts(&qemu_device_opts);
   2743    qemu_add_opts(&qemu_netdev_opts);
   2744    qemu_add_opts(&qemu_nic_opts);
   2745    qemu_add_opts(&qemu_net_opts);
   2746    qemu_add_opts(&qemu_rtc_opts);
   2747    qemu_add_opts(&qemu_global_opts);
   2748    qemu_add_opts(&qemu_mon_opts);
   2749    qemu_add_opts(&qemu_trace_opts);
   2750    qemu_plugin_add_opts();
   2751    qemu_add_opts(&qemu_option_rom_opts);
   2752    qemu_add_opts(&qemu_accel_opts);
   2753    qemu_add_opts(&qemu_mem_opts);
   2754    qemu_add_opts(&qemu_smp_opts);
   2755    qemu_add_opts(&qemu_boot_opts);
   2756    qemu_add_opts(&qemu_add_fd_opts);
   2757    qemu_add_opts(&qemu_object_opts);
   2758    qemu_add_opts(&qemu_tpmdev_opts);
   2759    qemu_add_opts(&qemu_overcommit_opts);
   2760    qemu_add_opts(&qemu_msg_opts);
   2761    qemu_add_opts(&qemu_name_opts);
   2762    qemu_add_opts(&qemu_numa_opts);
   2763    qemu_add_opts(&qemu_icount_opts);
   2764    qemu_add_opts(&qemu_semihosting_config_opts);
   2765    qemu_add_opts(&qemu_fw_cfg_opts);
   2766    qemu_add_opts(&qemu_action_opts);
   2767    module_call_init(MODULE_INIT_OPTS);
   2768
   2769    error_init(argv[0]);
   2770    qemu_init_exec_dir(argv[0]);
   2771
   2772#ifdef CONFIG_MODULES
   2773    module_init_info(qemu_modinfo);
   2774    module_allow_arch(TARGET_NAME);
   2775#endif
   2776
   2777    qemu_init_subsystems();
   2778
   2779    /* first pass of option parsing */
   2780    optind = 1;
   2781    while (optind < argc) {
   2782        if (argv[optind][0] != '-') {
   2783            /* disk image */
   2784            optind++;
   2785        } else {
   2786            const QEMUOption *popt;
   2787
   2788            popt = lookup_opt(argc, argv, &optarg, &optind);
   2789            switch (popt->index) {
   2790            case QEMU_OPTION_nouserconfig:
   2791                userconfig = false;
   2792                break;
   2793            }
   2794        }
   2795    }
   2796
   2797    machine_opts_dict = qdict_new();
   2798    if (userconfig) {
   2799        qemu_read_default_config_file(&error_fatal);
   2800    }
   2801
   2802    /* second pass of option parsing */
   2803    optind = 1;
   2804    for(;;) {
   2805        if (optind >= argc)
   2806            break;
   2807        if (argv[optind][0] != '-') {
   2808            loc_set_cmdline(argv, optind, 1);
   2809            drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
   2810        } else {
   2811            const QEMUOption *popt;
   2812
   2813            popt = lookup_opt(argc, argv, &optarg, &optind);
   2814            if (!(popt->arch_mask & arch_type)) {
   2815                error_report("Option not supported for this target");
   2816                exit(1);
   2817            }
   2818            switch(popt->index) {
   2819            case QEMU_OPTION_cpu:
   2820                /* hw initialization will check this */
   2821                cpu_option = optarg;
   2822                break;
   2823            case QEMU_OPTION_hda:
   2824            case QEMU_OPTION_hdb:
   2825            case QEMU_OPTION_hdc:
   2826            case QEMU_OPTION_hdd:
   2827                drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
   2828                          HD_OPTS);
   2829                break;
   2830            case QEMU_OPTION_blockdev:
   2831                {
   2832                    Visitor *v;
   2833                    BlockdevOptionsQueueEntry *bdo;
   2834
   2835                    v = qobject_input_visitor_new_str(optarg, "driver",
   2836                                                      &error_fatal);
   2837
   2838                    bdo = g_new(BlockdevOptionsQueueEntry, 1);
   2839                    visit_type_BlockdevOptions(v, NULL, &bdo->bdo,
   2840                                               &error_fatal);
   2841                    visit_free(v);
   2842                    loc_save(&bdo->loc);
   2843                    QSIMPLEQ_INSERT_TAIL(&bdo_queue, bdo, entry);
   2844                    break;
   2845                }
   2846            case QEMU_OPTION_drive:
   2847                if (drive_def(optarg) == NULL) {
   2848                    exit(1);
   2849                }
   2850                break;
   2851            case QEMU_OPTION_set:
   2852                qemu_set_option(optarg, &error_fatal);
   2853                break;
   2854            case QEMU_OPTION_global:
   2855                if (qemu_global_option(optarg) != 0)
   2856                    exit(1);
   2857                break;
   2858            case QEMU_OPTION_mtdblock:
   2859                drive_add(IF_MTD, -1, optarg, MTD_OPTS);
   2860                break;
   2861            case QEMU_OPTION_sd:
   2862                drive_add(IF_SD, -1, optarg, SD_OPTS);
   2863                break;
   2864            case QEMU_OPTION_pflash:
   2865                drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
   2866                break;
   2867            case QEMU_OPTION_snapshot:
   2868                {
   2869                    Error *blocker = NULL;
   2870                    snapshot = 1;
   2871                    error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED,
   2872                               "-snapshot");
   2873                    replay_add_blocker(blocker);
   2874                }
   2875                break;
   2876            case QEMU_OPTION_numa:
   2877                opts = qemu_opts_parse_noisily(qemu_find_opts("numa"),
   2878                                               optarg, true);
   2879                if (!opts) {
   2880                    exit(1);
   2881                }
   2882                break;
   2883            case QEMU_OPTION_display:
   2884                parse_display(optarg);
   2885                break;
   2886            case QEMU_OPTION_nographic:
   2887                qdict_put_str(machine_opts_dict, "graphics", "off");
   2888                nographic = true;
   2889                dpy.type = DISPLAY_TYPE_NONE;
   2890                break;
   2891            case QEMU_OPTION_curses:
   2892                warn_report("-curses is deprecated, "
   2893                            "use -display curses instead.");
   2894#ifdef CONFIG_CURSES
   2895                dpy.type = DISPLAY_TYPE_CURSES;
   2896#else
   2897                error_report("curses or iconv support is disabled");
   2898                exit(1);
   2899#endif
   2900                break;
   2901            case QEMU_OPTION_portrait:
   2902                graphic_rotate = 90;
   2903                break;
   2904            case QEMU_OPTION_rotate:
   2905                graphic_rotate = strtol(optarg, (char **) &optarg, 10);
   2906                if (graphic_rotate != 0 && graphic_rotate != 90 &&
   2907                    graphic_rotate != 180 && graphic_rotate != 270) {
   2908                    error_report("only 90, 180, 270 deg rotation is available");
   2909                    exit(1);
   2910                }
   2911                break;
   2912            case QEMU_OPTION_kernel:
   2913                qdict_put_str(machine_opts_dict, "kernel", optarg);
   2914                break;
   2915            case QEMU_OPTION_initrd:
   2916                qdict_put_str(machine_opts_dict, "initrd", optarg);
   2917                break;
   2918            case QEMU_OPTION_append:
   2919                qdict_put_str(machine_opts_dict, "append", optarg);
   2920                break;
   2921            case QEMU_OPTION_dtb:
   2922                qdict_put_str(machine_opts_dict, "dtb", optarg);
   2923                break;
   2924            case QEMU_OPTION_cdrom:
   2925                drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
   2926                break;
   2927            case QEMU_OPTION_boot:
   2928                opts = qemu_opts_parse_noisily(qemu_find_opts("boot-opts"),
   2929                                               optarg, true);
   2930                if (!opts) {
   2931                    exit(1);
   2932                }
   2933                break;
   2934            case QEMU_OPTION_fda:
   2935            case QEMU_OPTION_fdb:
   2936                drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
   2937                          optarg, FD_OPTS);
   2938                break;
   2939            case QEMU_OPTION_no_fd_bootchk:
   2940                fd_bootchk = 0;
   2941                break;
   2942            case QEMU_OPTION_netdev:
   2943                default_net = 0;
   2944                if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
   2945                    exit(1);
   2946                }
   2947                break;
   2948            case QEMU_OPTION_nic:
   2949                default_net = 0;
   2950                if (net_client_parse(qemu_find_opts("nic"), optarg) == -1) {
   2951                    exit(1);
   2952                }
   2953                break;
   2954            case QEMU_OPTION_net:
   2955                default_net = 0;
   2956                if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
   2957                    exit(1);
   2958                }
   2959                break;
   2960#ifdef CONFIG_LIBISCSI
   2961            case QEMU_OPTION_iscsi:
   2962                opts = qemu_opts_parse_noisily(qemu_find_opts("iscsi"),
   2963                                               optarg, false);
   2964                if (!opts) {
   2965                    exit(1);
   2966                }
   2967                break;
   2968#endif
   2969            case QEMU_OPTION_audio_help:
   2970                audio_legacy_help();
   2971                exit (0);
   2972                break;
   2973            case QEMU_OPTION_audiodev:
   2974                audio_parse_option(optarg);
   2975                break;
   2976            case QEMU_OPTION_soundhw:
   2977                select_soundhw (optarg);
   2978                break;
   2979            case QEMU_OPTION_h:
   2980                help(0);
   2981                break;
   2982            case QEMU_OPTION_version:
   2983                version();
   2984                exit(0);
   2985                break;
   2986            case QEMU_OPTION_m:
   2987                opts = qemu_opts_parse_noisily(qemu_find_opts("memory"),
   2988                                               optarg, true);
   2989                if (!opts) {
   2990                    exit(EXIT_FAILURE);
   2991                }
   2992                break;
   2993#ifdef CONFIG_TPM
   2994            case QEMU_OPTION_tpmdev:
   2995                if (tpm_config_parse(qemu_find_opts("tpmdev"), optarg) < 0) {
   2996                    exit(1);
   2997                }
   2998                break;
   2999#endif
   3000            case QEMU_OPTION_mempath:
   3001                mem_path = optarg;
   3002                break;
   3003            case QEMU_OPTION_mem_prealloc:
   3004                mem_prealloc = 1;
   3005                break;
   3006            case QEMU_OPTION_d:
   3007                log_mask = optarg;
   3008                break;
   3009            case QEMU_OPTION_D:
   3010                log_file = optarg;
   3011                break;
   3012            case QEMU_OPTION_DFILTER:
   3013                qemu_set_dfilter_ranges(optarg, &error_fatal);
   3014                break;
   3015            case QEMU_OPTION_seed:
   3016                qemu_guest_random_seed_main(optarg, &error_fatal);
   3017                break;
   3018            case QEMU_OPTION_s:
   3019                add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
   3020                break;
   3021            case QEMU_OPTION_gdb:
   3022                add_device_config(DEV_GDB, optarg);
   3023                break;
   3024            case QEMU_OPTION_L:
   3025                if (is_help_option(optarg)) {
   3026                    list_data_dirs = true;
   3027                } else {
   3028                    qemu_add_data_dir(g_strdup(optarg));
   3029                }
   3030                break;
   3031            case QEMU_OPTION_bios:
   3032                qdict_put_str(machine_opts_dict, "firmware", optarg);
   3033                break;
   3034            case QEMU_OPTION_singlestep:
   3035                singlestep = 1;
   3036                break;
   3037            case QEMU_OPTION_S:
   3038                autostart = 0;
   3039                break;
   3040            case QEMU_OPTION_k:
   3041                keyboard_layout = optarg;
   3042                break;
   3043            case QEMU_OPTION_vga:
   3044                vga_model = optarg;
   3045                default_vga = 0;
   3046                break;
   3047            case QEMU_OPTION_g:
   3048                {
   3049                    const char *p;
   3050                    int w, h, depth;
   3051                    p = optarg;
   3052                    w = strtol(p, (char **)&p, 10);
   3053                    if (w <= 0) {
   3054                    graphic_error:
   3055                        error_report("invalid resolution or depth");
   3056                        exit(1);
   3057                    }
   3058                    if (*p != 'x')
   3059                        goto graphic_error;
   3060                    p++;
   3061                    h = strtol(p, (char **)&p, 10);
   3062                    if (h <= 0)
   3063                        goto graphic_error;
   3064                    if (*p == 'x') {
   3065                        p++;
   3066                        depth = strtol(p, (char **)&p, 10);
   3067                        if (depth != 1 && depth != 2 && depth != 4 &&
   3068                            depth != 8 && depth != 15 && depth != 16 &&
   3069                            depth != 24 && depth != 32)
   3070                            goto graphic_error;
   3071                    } else if (*p == '\0') {
   3072                        depth = graphic_depth;
   3073                    } else {
   3074                        goto graphic_error;
   3075                    }
   3076
   3077                    graphic_width = w;
   3078                    graphic_height = h;
   3079                    graphic_depth = depth;
   3080                }
   3081                break;
   3082            case QEMU_OPTION_echr:
   3083                {
   3084                    char *r;
   3085                    term_escape_char = strtol(optarg, &r, 0);
   3086                    if (r == optarg)
   3087                        printf("Bad argument to echr\n");
   3088                    break;
   3089                }
   3090            case QEMU_OPTION_monitor:
   3091                default_monitor = 0;
   3092                if (strncmp(optarg, "none", 4)) {
   3093                    monitor_parse(optarg, "readline", false);
   3094                }
   3095                break;
   3096            case QEMU_OPTION_qmp:
   3097                monitor_parse(optarg, "control", false);
   3098                default_monitor = 0;
   3099                break;
   3100            case QEMU_OPTION_qmp_pretty:
   3101                monitor_parse(optarg, "control", true);
   3102                default_monitor = 0;
   3103                break;
   3104            case QEMU_OPTION_mon:
   3105                opts = qemu_opts_parse_noisily(qemu_find_opts("mon"), optarg,
   3106                                               true);
   3107                if (!opts) {
   3108                    exit(1);
   3109                }
   3110                default_monitor = 0;
   3111                break;
   3112            case QEMU_OPTION_chardev:
   3113                opts = qemu_opts_parse_noisily(qemu_find_opts("chardev"),
   3114                                               optarg, true);
   3115                if (!opts) {
   3116                    exit(1);
   3117                }
   3118                break;
   3119            case QEMU_OPTION_fsdev:
   3120                olist = qemu_find_opts("fsdev");
   3121                if (!olist) {
   3122                    error_report("fsdev support is disabled");
   3123                    exit(1);
   3124                }
   3125                opts = qemu_opts_parse_noisily(olist, optarg, true);
   3126                if (!opts) {
   3127                    exit(1);
   3128                }
   3129                break;
   3130            case QEMU_OPTION_virtfs: {
   3131                QemuOpts *fsdev;
   3132                QemuOpts *device;
   3133                const char *writeout, *sock_fd, *socket, *path, *security_model,
   3134                           *multidevs;
   3135
   3136                olist = qemu_find_opts("virtfs");
   3137                if (!olist) {
   3138                    error_report("virtfs support is disabled");
   3139                    exit(1);
   3140                }
   3141                opts = qemu_opts_parse_noisily(olist, optarg, true);
   3142                if (!opts) {
   3143                    exit(1);
   3144                }
   3145
   3146                if (qemu_opt_get(opts, "fsdriver") == NULL ||
   3147                    qemu_opt_get(opts, "mount_tag") == NULL) {
   3148                    error_report("Usage: -virtfs fsdriver,mount_tag=tag");
   3149                    exit(1);
   3150                }
   3151                fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
   3152                                         qemu_opts_id(opts) ?:
   3153                                         qemu_opt_get(opts, "mount_tag"),
   3154                                         1, NULL);
   3155                if (!fsdev) {
   3156                    error_report("duplicate or invalid fsdev id: %s",
   3157                                 qemu_opt_get(opts, "mount_tag"));
   3158                    exit(1);
   3159                }
   3160
   3161                writeout = qemu_opt_get(opts, "writeout");
   3162                if (writeout) {
   3163#ifdef CONFIG_SYNC_FILE_RANGE
   3164                    qemu_opt_set(fsdev, "writeout", writeout, &error_abort);
   3165#else
   3166                    error_report("writeout=immediate not supported "
   3167                                 "on this platform");
   3168                    exit(1);
   3169#endif
   3170                }
   3171                qemu_opt_set(fsdev, "fsdriver",
   3172                             qemu_opt_get(opts, "fsdriver"), &error_abort);
   3173                path = qemu_opt_get(opts, "path");
   3174                if (path) {
   3175                    qemu_opt_set(fsdev, "path", path, &error_abort);
   3176                }
   3177                security_model = qemu_opt_get(opts, "security_model");
   3178                if (security_model) {
   3179                    qemu_opt_set(fsdev, "security_model", security_model,
   3180                                 &error_abort);
   3181                }
   3182                socket = qemu_opt_get(opts, "socket");
   3183                if (socket) {
   3184                    qemu_opt_set(fsdev, "socket", socket, &error_abort);
   3185                }
   3186                sock_fd = qemu_opt_get(opts, "sock_fd");
   3187                if (sock_fd) {
   3188                    qemu_opt_set(fsdev, "sock_fd", sock_fd, &error_abort);
   3189                }
   3190
   3191                qemu_opt_set_bool(fsdev, "readonly",
   3192                                  qemu_opt_get_bool(opts, "readonly", 0),
   3193                                  &error_abort);
   3194                multidevs = qemu_opt_get(opts, "multidevs");
   3195                if (multidevs) {
   3196                    qemu_opt_set(fsdev, "multidevs", multidevs, &error_abort);
   3197                }
   3198                device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
   3199                                          &error_abort);
   3200                qemu_opt_set(device, "driver", "virtio-9p-pci", &error_abort);
   3201                qemu_opt_set(device, "fsdev",
   3202                             qemu_opts_id(fsdev), &error_abort);
   3203                qemu_opt_set(device, "mount_tag",
   3204                             qemu_opt_get(opts, "mount_tag"), &error_abort);
   3205                break;
   3206            }
   3207            case QEMU_OPTION_serial:
   3208                add_device_config(DEV_SERIAL, optarg);
   3209                default_serial = 0;
   3210                if (strncmp(optarg, "mon:", 4) == 0) {
   3211                    default_monitor = 0;
   3212                }
   3213                break;
   3214            case QEMU_OPTION_watchdog:
   3215                if (watchdog) {
   3216                    error_report("only one watchdog option may be given");
   3217                    exit(1);
   3218                }
   3219                watchdog = optarg;
   3220                break;
   3221            case QEMU_OPTION_action:
   3222                olist = qemu_find_opts("action");
   3223                if (!qemu_opts_parse_noisily(olist, optarg, false)) {
   3224                     exit(1);
   3225                }
   3226                break;
   3227            case QEMU_OPTION_watchdog_action:
   3228                if (select_watchdog_action(optarg) == -1) {
   3229                    error_report("unknown -watchdog-action parameter");
   3230                    exit(1);
   3231                }
   3232                break;
   3233            case QEMU_OPTION_parallel:
   3234                add_device_config(DEV_PARALLEL, optarg);
   3235                default_parallel = 0;
   3236                if (strncmp(optarg, "mon:", 4) == 0) {
   3237                    default_monitor = 0;
   3238                }
   3239                break;
   3240            case QEMU_OPTION_debugcon:
   3241                add_device_config(DEV_DEBUGCON, optarg);
   3242                break;
   3243            case QEMU_OPTION_loadvm:
   3244                loadvm = optarg;
   3245                break;
   3246            case QEMU_OPTION_full_screen:
   3247                dpy.has_full_screen = true;
   3248                dpy.full_screen = true;
   3249                break;
   3250            case QEMU_OPTION_alt_grab:
   3251                alt_grab = 1;
   3252                warn_report("-alt-grab is deprecated, please use "
   3253                            "-display sdl,grab-mod=lshift-lctrl-lalt instead.");
   3254                break;
   3255            case QEMU_OPTION_ctrl_grab:
   3256                ctrl_grab = 1;
   3257                warn_report("-ctrl-grab is deprecated, please use "
   3258                            "-display sdl,grab-mod=rctrl instead.");
   3259                break;
   3260            case QEMU_OPTION_no_quit:
   3261                dpy.has_window_close = true;
   3262                dpy.window_close = false;
   3263                warn_report("-no-quit is deprecated, please use "
   3264                            "-display ...,window-close=off instead.");
   3265                break;
   3266            case QEMU_OPTION_sdl:
   3267                warn_report("-sdl is deprecated, use -display sdl instead.");
   3268#ifdef CONFIG_SDL
   3269                dpy.type = DISPLAY_TYPE_SDL;
   3270                break;
   3271#else
   3272                error_report("SDL support is disabled");
   3273                exit(1);
   3274#endif
   3275            case QEMU_OPTION_pidfile:
   3276                pid_file = optarg;
   3277                break;
   3278            case QEMU_OPTION_win2k_hack:
   3279                win2k_install_hack = 1;
   3280                break;
   3281            case QEMU_OPTION_acpitable:
   3282                opts = qemu_opts_parse_noisily(qemu_find_opts("acpi"),
   3283                                               optarg, true);
   3284                if (!opts) {
   3285                    exit(1);
   3286                }
   3287                acpi_table_add(opts, &error_fatal);
   3288                break;
   3289            case QEMU_OPTION_smbios:
   3290                opts = qemu_opts_parse_noisily(qemu_find_opts("smbios"),
   3291                                               optarg, false);
   3292                if (!opts) {
   3293                    exit(1);
   3294                }
   3295                smbios_entry_add(opts, &error_fatal);
   3296                break;
   3297            case QEMU_OPTION_fwcfg:
   3298                opts = qemu_opts_parse_noisily(qemu_find_opts("fw_cfg"),
   3299                                               optarg, true);
   3300                if (opts == NULL) {
   3301                    exit(1);
   3302                }
   3303                break;
   3304            case QEMU_OPTION_preconfig:
   3305                preconfig_requested = true;
   3306                break;
   3307            case QEMU_OPTION_enable_kvm:
   3308                qdict_put_str(machine_opts_dict, "accel", "kvm");
   3309                break;
   3310            case QEMU_OPTION_M:
   3311            case QEMU_OPTION_machine:
   3312                {
   3313                    bool help;
   3314
   3315                    keyval_parse_into(machine_opts_dict, optarg, "type", &help, &error_fatal);
   3316                    if (help) {
   3317                        machine_help_func(machine_opts_dict);
   3318                        exit(EXIT_SUCCESS);
   3319                    }
   3320                    break;
   3321                }
   3322            case QEMU_OPTION_accel:
   3323                accel_opts = qemu_opts_parse_noisily(qemu_find_opts("accel"),
   3324                                                     optarg, true);
   3325                optarg = qemu_opt_get(accel_opts, "accel");
   3326                if (!optarg || is_help_option(optarg)) {
   3327                    printf("Accelerators supported in QEMU binary:\n");
   3328                    GSList *el, *accel_list = object_class_get_list(TYPE_ACCEL,
   3329                                                                    false);
   3330                    for (el = accel_list; el; el = el->next) {
   3331                        gchar *typename = g_strdup(object_class_get_name(
   3332                                                   OBJECT_CLASS(el->data)));
   3333                        /* omit qtest which is used for tests only */
   3334                        if (g_strcmp0(typename, ACCEL_CLASS_NAME("qtest")) &&
   3335                            g_str_has_suffix(typename, ACCEL_CLASS_SUFFIX)) {
   3336                            gchar **optname = g_strsplit(typename,
   3337                                                         ACCEL_CLASS_SUFFIX, 0);
   3338                            printf("%s\n", optname[0]);
   3339                            g_strfreev(optname);
   3340                        }
   3341                        g_free(typename);
   3342                    }
   3343                    g_slist_free(accel_list);
   3344                    exit(0);
   3345                }
   3346                break;
   3347            case QEMU_OPTION_usb:
   3348                qdict_put_str(machine_opts_dict, "usb", "on");
   3349                break;
   3350            case QEMU_OPTION_usbdevice:
   3351                qdict_put_str(machine_opts_dict, "usb", "on");
   3352                add_device_config(DEV_USB, optarg);
   3353                break;
   3354            case QEMU_OPTION_device:
   3355                if (!qemu_opts_parse_noisily(qemu_find_opts("device"),
   3356                                             optarg, true)) {
   3357                    exit(1);
   3358                }
   3359                break;
   3360            case QEMU_OPTION_smp:
   3361                machine_parse_property_opt(qemu_find_opts("smp-opts"),
   3362                                           "smp", optarg);
   3363                break;
   3364            case QEMU_OPTION_vnc:
   3365                vnc_parse(optarg);
   3366                break;
   3367            case QEMU_OPTION_no_acpi:
   3368                qdict_put_str(machine_opts_dict, "acpi", "off");
   3369                break;
   3370            case QEMU_OPTION_no_hpet:
   3371                qdict_put_str(machine_opts_dict, "hpet", "off");
   3372                break;
   3373            case QEMU_OPTION_no_reboot:
   3374                olist = qemu_find_opts("action");
   3375                qemu_opts_parse_noisily(olist, "reboot=shutdown", false);
   3376                break;
   3377            case QEMU_OPTION_no_shutdown:
   3378                olist = qemu_find_opts("action");
   3379                qemu_opts_parse_noisily(olist, "shutdown=pause", false);
   3380                break;
   3381            case QEMU_OPTION_uuid:
   3382                if (qemu_uuid_parse(optarg, &qemu_uuid) < 0) {
   3383                    error_report("failed to parse UUID string: wrong format");
   3384                    exit(1);
   3385                }
   3386                qemu_uuid_set = true;
   3387                break;
   3388            case QEMU_OPTION_option_rom:
   3389                if (nb_option_roms >= MAX_OPTION_ROMS) {
   3390                    error_report("too many option ROMs");
   3391                    exit(1);
   3392                }
   3393                opts = qemu_opts_parse_noisily(qemu_find_opts("option-rom"),
   3394                                               optarg, true);
   3395                if (!opts) {
   3396                    exit(1);
   3397                }
   3398                option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
   3399                option_rom[nb_option_roms].bootindex =
   3400                    qemu_opt_get_number(opts, "bootindex", -1);
   3401                if (!option_rom[nb_option_roms].name) {
   3402                    error_report("Option ROM file is not specified");
   3403                    exit(1);
   3404                }
   3405                nb_option_roms++;
   3406                break;
   3407            case QEMU_OPTION_semihosting:
   3408                qemu_semihosting_enable();
   3409                break;
   3410            case QEMU_OPTION_semihosting_config:
   3411                if (qemu_semihosting_config_options(optarg) != 0) {
   3412                    exit(1);
   3413                }
   3414                break;
   3415            case QEMU_OPTION_name:
   3416                opts = qemu_opts_parse_noisily(qemu_find_opts("name"),
   3417                                               optarg, true);
   3418                if (!opts) {
   3419                    exit(1);
   3420                }
   3421                /* Capture guest name if -msg guest-name is used later */
   3422                error_guest_name = qemu_opt_get(opts, "guest");
   3423                break;
   3424            case QEMU_OPTION_prom_env:
   3425                if (nb_prom_envs >= MAX_PROM_ENVS) {
   3426                    error_report("too many prom variables");
   3427                    exit(1);
   3428                }
   3429                prom_envs[nb_prom_envs] = optarg;
   3430                nb_prom_envs++;
   3431                break;
   3432            case QEMU_OPTION_old_param:
   3433                old_param = 1;
   3434                break;
   3435            case QEMU_OPTION_rtc:
   3436                opts = qemu_opts_parse_noisily(qemu_find_opts("rtc"), optarg,
   3437                                               false);
   3438                if (!opts) {
   3439                    exit(1);
   3440                }
   3441                break;
   3442            case QEMU_OPTION_icount:
   3443                icount_opts = qemu_opts_parse_noisily(qemu_find_opts("icount"),
   3444                                                      optarg, true);
   3445                if (!icount_opts) {
   3446                    exit(1);
   3447                }
   3448                break;
   3449            case QEMU_OPTION_incoming:
   3450                if (!incoming) {
   3451                    runstate_set(RUN_STATE_INMIGRATE);
   3452                }
   3453                incoming = optarg;
   3454                break;
   3455            case QEMU_OPTION_only_migratable:
   3456                only_migratable = 1;
   3457                break;
   3458            case QEMU_OPTION_nodefaults:
   3459                has_defaults = 0;
   3460                break;
   3461            case QEMU_OPTION_xen_domid:
   3462                if (!(accel_find("xen"))) {
   3463                    error_report("Option not supported for this target");
   3464                    exit(1);
   3465                }
   3466                xen_domid = atoi(optarg);
   3467                break;
   3468            case QEMU_OPTION_xen_attach:
   3469                if (!(accel_find("xen"))) {
   3470                    error_report("Option not supported for this target");
   3471                    exit(1);
   3472                }
   3473                xen_mode = XEN_ATTACH;
   3474                break;
   3475            case QEMU_OPTION_xen_domid_restrict:
   3476                if (!(accel_find("xen"))) {
   3477                    error_report("Option not supported for this target");
   3478                    exit(1);
   3479                }
   3480                xen_domid_restrict = true;
   3481                break;
   3482            case QEMU_OPTION_trace:
   3483                trace_opt_parse(optarg);
   3484                break;
   3485            case QEMU_OPTION_plugin:
   3486                qemu_plugin_opt_parse(optarg, &plugin_list);
   3487                break;
   3488            case QEMU_OPTION_readconfig:
   3489                qemu_read_config_file(optarg, qemu_parse_config_group, &error_fatal);
   3490                break;
   3491            case QEMU_OPTION_spice:
   3492                olist = qemu_find_opts_err("spice", NULL);
   3493                if (!olist) {
   3494                    error_report("spice support is disabled");
   3495                    exit(1);
   3496                }
   3497                opts = qemu_opts_parse_noisily(olist, optarg, false);
   3498                if (!opts) {
   3499                    exit(1);
   3500                }
   3501                display_remote++;
   3502                break;
   3503            case QEMU_OPTION_writeconfig:
   3504                {
   3505                    FILE *fp;
   3506                    warn_report("-writeconfig is deprecated and will go away without a replacement");
   3507                    if (strcmp(optarg, "-") == 0) {
   3508                        fp = stdout;
   3509                    } else {
   3510                        fp = fopen(optarg, "w");
   3511                        if (fp == NULL) {
   3512                            error_report("open %s: %s", optarg,
   3513                                         strerror(errno));
   3514                            exit(1);
   3515                        }
   3516                    }
   3517                    qemu_config_write(fp);
   3518                    if (fp != stdout) {
   3519                        fclose(fp);
   3520                    }
   3521                    break;
   3522                }
   3523            case QEMU_OPTION_qtest:
   3524                qtest_chrdev = optarg;
   3525                break;
   3526            case QEMU_OPTION_qtest_log:
   3527                qtest_log = optarg;
   3528                break;
   3529            case QEMU_OPTION_sandbox:
   3530                olist = qemu_find_opts("sandbox");
   3531                if (!olist) {
   3532#ifndef CONFIG_SECCOMP
   3533                    error_report("-sandbox support is not enabled "
   3534                                 "in this QEMU binary");
   3535#endif
   3536                    exit(1);
   3537                }
   3538
   3539                opts = qemu_opts_parse_noisily(olist, optarg, true);
   3540                if (!opts) {
   3541                    exit(1);
   3542                }
   3543                break;
   3544            case QEMU_OPTION_add_fd:
   3545#ifndef _WIN32
   3546                opts = qemu_opts_parse_noisily(qemu_find_opts("add-fd"),
   3547                                               optarg, false);
   3548                if (!opts) {
   3549                    exit(1);
   3550                }
   3551#else
   3552                error_report("File descriptor passing is disabled on this "
   3553                             "platform");
   3554                exit(1);
   3555#endif
   3556                break;
   3557            case QEMU_OPTION_object:
   3558                object_option_parse(optarg);
   3559                break;
   3560            case QEMU_OPTION_overcommit:
   3561                opts = qemu_opts_parse_noisily(qemu_find_opts("overcommit"),
   3562                                               optarg, false);
   3563                if (!opts) {
   3564                    exit(1);
   3565                }
   3566                enable_mlock = qemu_opt_get_bool(opts, "mem-lock", false);
   3567                enable_cpu_pm = qemu_opt_get_bool(opts, "cpu-pm", false);
   3568                break;
   3569            case QEMU_OPTION_compat:
   3570                {
   3571                    CompatPolicy *opts;
   3572                    Visitor *v;
   3573
   3574                    v = qobject_input_visitor_new_str(optarg, NULL,
   3575                                                      &error_fatal);
   3576
   3577                    visit_type_CompatPolicy(v, NULL, &opts, &error_fatal);
   3578                    QAPI_CLONE_MEMBERS(CompatPolicy, &compat_policy, opts);
   3579
   3580                    qapi_free_CompatPolicy(opts);
   3581                    visit_free(v);
   3582                    break;
   3583                }
   3584            case QEMU_OPTION_msg:
   3585                opts = qemu_opts_parse_noisily(qemu_find_opts("msg"), optarg,
   3586                                               false);
   3587                if (!opts) {
   3588                    exit(1);
   3589                }
   3590                configure_msg(opts);
   3591                break;
   3592            case QEMU_OPTION_dump_vmstate:
   3593                if (vmstate_dump_file) {
   3594                    error_report("only one '-dump-vmstate' "
   3595                                 "option may be given");
   3596                    exit(1);
   3597                }
   3598                vmstate_dump_file = fopen(optarg, "w");
   3599                if (vmstate_dump_file == NULL) {
   3600                    error_report("open %s: %s", optarg, strerror(errno));
   3601                    exit(1);
   3602                }
   3603                break;
   3604            case QEMU_OPTION_enable_sync_profile:
   3605                qsp_enable();
   3606                break;
   3607            case QEMU_OPTION_nouserconfig:
   3608                /* Nothing to be parsed here. Especially, do not error out below. */
   3609                break;
   3610            default:
   3611                if (os_parse_cmd_args(popt->index, optarg)) {
   3612                    error_report("Option not supported in this build");
   3613                    exit(1);
   3614                }
   3615            }
   3616        }
   3617    }
   3618    /*
   3619     * Clear error location left behind by the loop.
   3620     * Best done right after the loop.  Do not insert code here!
   3621     */
   3622    loc_set_none();
   3623
   3624    qemu_validate_options(machine_opts_dict);
   3625    qemu_process_sugar_options();
   3626
   3627    /*
   3628     * These options affect everything else and should be processed
   3629     * before daemonizing.
   3630     */
   3631    qemu_process_early_options();
   3632
   3633    qemu_process_help_options();
   3634    qemu_maybe_daemonize(pid_file);
   3635
   3636    /*
   3637     * The trace backend must be initialized after daemonizing.
   3638     * trace_init_backends() will call st_init(), which will create the
   3639     * trace thread in the parent, and also register st_flush_trace_buffer()
   3640     * in atexit(). This function will force the parent to wait for the
   3641     * writeout thread to finish, which will not occur, and the parent
   3642     * process will be left in the host.
   3643     */
   3644    if (!trace_init_backends()) {
   3645        exit(1);
   3646    }
   3647    trace_init_file();
   3648
   3649    qemu_init_main_loop(&error_fatal);
   3650    cpu_timers_init();
   3651
   3652    user_register_global_props();
   3653    replay_configure(icount_opts);
   3654
   3655    configure_rtc(qemu_find_opts_singleton("rtc"));
   3656
   3657    qemu_create_machine(machine_opts_dict);
   3658
   3659    suspend_mux_open();
   3660
   3661    qemu_disable_default_devices();
   3662    qemu_create_default_devices();
   3663    qemu_create_early_backends();
   3664
   3665    qemu_apply_legacy_machine_options(machine_opts_dict);
   3666    qemu_apply_machine_options(machine_opts_dict);
   3667    qobject_unref(machine_opts_dict);
   3668    phase_advance(PHASE_MACHINE_CREATED);
   3669
   3670    /*
   3671     * Note: uses machine properties such as kernel-irqchip, must run
   3672     * after qemu_apply_machine_options.
   3673     */
   3674    configure_accelerators(argv[0]);
   3675    phase_advance(PHASE_ACCEL_CREATED);
   3676
   3677    /*
   3678     * Beware, QOM objects created before this point miss global and
   3679     * compat properties.
   3680     *
   3681     * Global properties get set up by qdev_prop_register_global(),
   3682     * called from user_register_global_props(), and certain option
   3683     * desugaring.  Also in CPU feature desugaring (buried in
   3684     * parse_cpu_option()), which happens below this point, but may
   3685     * only target the CPU type, which can only be created after
   3686     * parse_cpu_option() returned the type.
   3687     *
   3688     * Machine compat properties: object_set_machine_compat_props().
   3689     * Accelerator compat props: object_set_accelerator_compat_props(),
   3690     * called from do_configure_accelerator().
   3691     */
   3692
   3693    machine_class = MACHINE_GET_CLASS(current_machine);
   3694    if (!qtest_enabled() && machine_class->deprecation_reason) {
   3695        error_report("Machine type '%s' is deprecated: %s",
   3696                     machine_class->name, machine_class->deprecation_reason);
   3697    }
   3698
   3699    /*
   3700     * Note: creates a QOM object, must run only after global and
   3701     * compat properties have been set up.
   3702     */
   3703    migration_object_init();
   3704
   3705    qemu_create_late_backends();
   3706
   3707    /* parse features once if machine provides default cpu_type */
   3708    current_machine->cpu_type = machine_class->default_cpu_type;
   3709    if (cpu_option) {
   3710        current_machine->cpu_type = parse_cpu_option(cpu_option);
   3711    }
   3712    /* NB: for machine none cpu_type could STILL be NULL here! */
   3713
   3714    qemu_resolve_machine_memdev();
   3715    parse_numa_opts(current_machine);
   3716
   3717    if (vmstate_dump_file) {
   3718        /* dump and exit */
   3719        dump_vmstate_json_to_file(vmstate_dump_file);
   3720        exit(0);
   3721    }
   3722
   3723    if (!preconfig_requested) {
   3724        qmp_x_exit_preconfig(&error_fatal);
   3725    }
   3726    qemu_init_displays();
   3727    accel_setup_post(current_machine);
   3728    os_setup_post();
   3729    resume_mux_open();
   3730}