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