xref: /qemu/system/vl.c (revision 513823e7521a09ed7ad1e32e6454bac3b2cbf52d)
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_BOOL,
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 (enable_mlock) {
801         if (os_mlock() < 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 /*
1880  * Very early object creation, before the sandbox options have been activated.
1881  */
1882 static bool object_create_pre_sandbox(const char *type)
1883 {
1884     /*
1885      * Objects should in general not get initialized "too early" without
1886      * a reason. If you add one, state the reason in a comment!
1887      */
1888 
1889     /*
1890      * Reason: -sandbox on,resourcecontrol=deny disallows setting CPU
1891      * affinity of threads.
1892      */
1893     if (g_str_equal(type, "thread-context")) {
1894         return true;
1895     }
1896 
1897     return false;
1898 }
1899 
1900 /*
1901  * Initial object creation happens before all other
1902  * QEMU data types are created. The majority of objects
1903  * can be created at this point. The rng-egd object
1904  * cannot be created here, as it depends on the chardev
1905  * already existing.
1906  */
1907 static bool object_create_early(const char *type)
1908 {
1909     /*
1910      * Objects should not be made "delayed" without a reason.  If you
1911      * add one, state the reason in a comment!
1912      */
1913 
1914     /* Reason: already created. */
1915     if (object_create_pre_sandbox(type)) {
1916         return false;
1917     }
1918 
1919     /* Reason: property "chardev" */
1920     if (g_str_equal(type, "rng-egd") ||
1921         g_str_equal(type, "qtest")) {
1922         return false;
1923     }
1924 
1925 #if defined(CONFIG_VHOST_USER) && defined(CONFIG_LINUX)
1926     /* Reason: cryptodev-vhost-user property "chardev" */
1927     if (g_str_equal(type, "cryptodev-vhost-user")) {
1928         return false;
1929     }
1930 #endif
1931 
1932     /* Reason: vhost-user-blk-server property "node-name" */
1933     if (g_str_equal(type, "vhost-user-blk-server")) {
1934         return false;
1935     }
1936     /*
1937      * Reason: filter-* property "netdev" etc.
1938      */
1939     if (g_str_equal(type, "filter-buffer") ||
1940         g_str_equal(type, "filter-dump") ||
1941         g_str_equal(type, "filter-mirror") ||
1942         g_str_equal(type, "filter-redirector") ||
1943         g_str_equal(type, "colo-compare") ||
1944         g_str_equal(type, "filter-rewriter") ||
1945         g_str_equal(type, "filter-replay")) {
1946         return false;
1947     }
1948 
1949     /*
1950      * Allocation of large amounts of memory may delay
1951      * chardev initialization for too long, and trigger timeouts
1952      * on software that waits for a monitor socket to be created
1953      */
1954     if (g_str_has_prefix(type, "memory-backend-")) {
1955         return false;
1956     }
1957 
1958     return true;
1959 }
1960 
1961 static void qemu_apply_machine_options(QDict *qdict)
1962 {
1963     object_set_properties_from_keyval(OBJECT(current_machine), qdict, false, &error_fatal);
1964 
1965     if (semihosting_enabled(false) && !semihosting_get_argc()) {
1966         /* fall back to the -kernel/-append */
1967         semihosting_arg_fallback(current_machine->kernel_filename, current_machine->kernel_cmdline);
1968     }
1969 
1970     if (current_machine->smp.cpus > 1) {
1971         replay_add_blocker("multiple CPUs");
1972     }
1973 }
1974 
1975 static void qemu_create_early_backends(void)
1976 {
1977     MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
1978 #if defined(CONFIG_SDL)
1979     const bool use_sdl = (dpy.type == DISPLAY_TYPE_SDL);
1980 #else
1981     const bool use_sdl = false;
1982 #endif
1983 #if defined(CONFIG_GTK)
1984     const bool use_gtk = (dpy.type == DISPLAY_TYPE_GTK);
1985 #else
1986     const bool use_gtk = false;
1987 #endif
1988 
1989     if (dpy.has_window_close && !use_gtk && !use_sdl) {
1990         error_report("window-close is only valid for GTK and SDL, "
1991                      "ignoring option");
1992     }
1993 
1994     qemu_console_early_init();
1995 
1996     if (dpy.has_gl && dpy.gl != DISPLAY_GL_MODE_OFF && display_opengl == 0) {
1997 #if defined(CONFIG_OPENGL)
1998         error_report("OpenGL is not supported by display backend '%s'",
1999                      DisplayType_str(dpy.type));
2000 #else
2001         error_report("OpenGL support was not enabled in this build of QEMU");
2002 #endif
2003         exit(1);
2004     }
2005 
2006     object_option_foreach_add(object_create_early);
2007 
2008     /* spice needs the timers to be initialized by this point */
2009     /* spice must initialize before audio as it changes the default audiodev */
2010     /* spice must initialize before chardevs (for spicevmc and spiceport) */
2011     qemu_spice.init();
2012 
2013     qemu_opts_foreach(qemu_find_opts("chardev"),
2014                       chardev_init_func, NULL, &error_fatal);
2015 
2016 #ifdef CONFIG_VIRTFS
2017     qemu_opts_foreach(qemu_find_opts("fsdev"),
2018                       fsdev_init_func, NULL, &error_fatal);
2019 #endif
2020 
2021     /*
2022      * Note: we need to create audio and block backends before
2023      * setting machine properties, so they can be referred to.
2024      */
2025     configure_blockdev(&bdo_queue, machine_class, snapshot);
2026     audio_init_audiodevs();
2027     if (default_audio) {
2028         audio_create_default_audiodevs();
2029     }
2030 }
2031 
2032 
2033 /*
2034  * The remainder of object creation happens after the
2035  * creation of chardev, fsdev, net clients and device data types.
2036  */
2037 static bool object_create_late(const char *type)
2038 {
2039     return !object_create_early(type) && !object_create_pre_sandbox(type);
2040 }
2041 
2042 static void qemu_create_late_backends(void)
2043 {
2044     if (qtest_chrdev) {
2045         qtest_server_init(qtest_chrdev, qtest_log, &error_fatal);
2046     }
2047 
2048     net_init_clients();
2049 
2050     object_option_foreach_add(object_create_late);
2051 
2052     /*
2053      * Wait for any outstanding memory prealloc from created memory
2054      * backends to complete.
2055      */
2056     if (!qemu_finish_async_prealloc_mem(&error_fatal)) {
2057         exit(1);
2058     }
2059 
2060     if (tpm_init() < 0) {
2061         exit(1);
2062     }
2063 
2064     qemu_opts_foreach(qemu_find_opts("mon"),
2065                       mon_init_func, NULL, &error_fatal);
2066 
2067     foreach_device_config_or_exit(DEV_SERIAL, serial_parse);
2068     foreach_device_config_or_exit(DEV_PARALLEL, parallel_parse);
2069     foreach_device_config_or_exit(DEV_DEBUGCON, debugcon_parse);
2070 
2071     /* now chardevs have been created we may have semihosting to connect */
2072     qemu_semihosting_chardev_init();
2073 }
2074 
2075 static void qemu_resolve_machine_memdev(void)
2076 {
2077     if (ram_memdev_id) {
2078         Object *backend;
2079         ram_addr_t backend_size;
2080 
2081         backend = object_resolve_path_type(ram_memdev_id,
2082                                            TYPE_MEMORY_BACKEND, NULL);
2083         if (!backend) {
2084             error_report("Memory backend '%s' not found", ram_memdev_id);
2085             exit(EXIT_FAILURE);
2086         }
2087         if (!have_custom_ram_size) {
2088             backend_size = object_property_get_uint(backend, "size",  &error_abort);
2089             current_machine->ram_size = backend_size;
2090         }
2091         object_property_set_link(OBJECT(current_machine),
2092                                  "memory-backend", backend, &error_fatal);
2093     }
2094 }
2095 
2096 static void parse_memory_options(void)
2097 {
2098     QemuOpts *opts = qemu_find_opts_singleton("memory");
2099     QDict *dict, *prop;
2100     const char *mem_str;
2101     Location loc;
2102 
2103     loc_push_none(&loc);
2104     qemu_opts_loc_restore(opts);
2105 
2106     prop = qdict_new();
2107 
2108     if (qemu_opt_get_size(opts, "size", 0) != 0) {
2109         /* Fix up legacy suffix-less format */
2110         mem_str = qemu_opt_get(opts, "size");
2111         if (g_ascii_isdigit(mem_str[strlen(mem_str) - 1])) {
2112             g_autofree char *mib_str = g_strdup_printf("%sM", mem_str);
2113             qdict_put_str(prop, "size", mib_str);
2114         } else {
2115             qdict_put_str(prop, "size", mem_str);
2116         }
2117     }
2118 
2119     if (qemu_opt_get(opts, "maxmem")) {
2120         qdict_put_str(prop, "max-size", qemu_opt_get(opts, "maxmem"));
2121     }
2122     if (qemu_opt_get(opts, "slots")) {
2123         qdict_put_str(prop, "slots", qemu_opt_get(opts, "slots"));
2124     }
2125 
2126     dict = qdict_new();
2127     qdict_put(dict, "memory", prop);
2128     keyval_merge(machine_opts_dict, dict, &error_fatal);
2129     qobject_unref(dict);
2130     loc_pop(&loc);
2131 }
2132 
2133 static void qemu_create_machine_containers(Object *machine)
2134 {
2135     static const char *const containers[] = {
2136         "unattached",
2137         "peripheral",
2138         "peripheral-anon",
2139     };
2140 
2141     for (unsigned i = 0; i < ARRAY_SIZE(containers); i++) {
2142         object_property_add_new_container(machine, containers[i]);
2143     }
2144 }
2145 
2146 static void qemu_create_machine(QDict *qdict)
2147 {
2148     MachineClass *machine_class = select_machine(qdict, &error_fatal);
2149     object_set_machine_compat_props(machine_class->compat_props);
2150 
2151     current_machine = MACHINE(object_new_with_class(OBJECT_CLASS(machine_class)));
2152     object_property_add_child(object_get_root(), "machine",
2153                               OBJECT(current_machine));
2154     qemu_create_machine_containers(OBJECT(current_machine));
2155     object_property_add_child(machine_get_container("unattached"),
2156                               "sysbus", OBJECT(sysbus_get_default()));
2157 
2158     if (machine_class->minimum_page_bits) {
2159         if (!set_preferred_target_page_bits(machine_class->minimum_page_bits)) {
2160             /* This would be a board error: specifying a minimum smaller than
2161              * a target's compile-time fixed setting.
2162              */
2163             g_assert_not_reached();
2164         }
2165     }
2166 
2167     cpu_exec_init_all();
2168 
2169     if (machine_class->hw_version) {
2170         qemu_set_hw_version(machine_class->hw_version);
2171     }
2172 
2173     /*
2174      * Get the default machine options from the machine if it is not already
2175      * specified either by the configuration file or by the command line.
2176      */
2177     if (machine_class->default_machine_opts) {
2178         QDict *default_opts =
2179             keyval_parse(machine_class->default_machine_opts, NULL, NULL,
2180                          &error_abort);
2181         qemu_apply_legacy_machine_options(default_opts);
2182         object_set_properties_from_keyval(OBJECT(current_machine), default_opts,
2183                                           false, &error_abort);
2184         qobject_unref(default_opts);
2185     }
2186 }
2187 
2188 static int global_init_func(void *opaque, QemuOpts *opts, Error **errp)
2189 {
2190     GlobalProperty *g;
2191 
2192     g = g_malloc0(sizeof(*g));
2193     g->driver   = qemu_opt_get(opts, "driver");
2194     g->property = qemu_opt_get(opts, "property");
2195     g->value    = qemu_opt_get(opts, "value");
2196     qdev_prop_register_global(g);
2197     return 0;
2198 }
2199 
2200 /*
2201  * Return whether configuration group @group is stored in QemuOpts, or
2202  * recorded as one or more QDicts by qemu_record_config_group.
2203  */
2204 static bool is_qemuopts_group(const char *group)
2205 {
2206     if (g_str_equal(group, "object") ||
2207         g_str_equal(group, "audiodev") ||
2208         g_str_equal(group, "machine") ||
2209         g_str_equal(group, "smp-opts") ||
2210         g_str_equal(group, "boot-opts")) {
2211         return false;
2212     }
2213     return true;
2214 }
2215 
2216 static void qemu_record_config_group(const char *group, QDict *dict,
2217                                      bool from_json, Error **errp)
2218 {
2219     if (g_str_equal(group, "object")) {
2220         Visitor *v = qobject_input_visitor_new_keyval(QOBJECT(dict));
2221         object_option_add_visitor(v);
2222         visit_free(v);
2223 
2224     } else if (g_str_equal(group, "audiodev")) {
2225         Audiodev *dev = NULL;
2226         Visitor *v = qobject_input_visitor_new_keyval(QOBJECT(dict));
2227         if (visit_type_Audiodev(v, NULL, &dev, errp)) {
2228             audio_define(dev);
2229         }
2230         visit_free(v);
2231 
2232     } else if (g_str_equal(group, "machine")) {
2233         /*
2234          * Cannot merge string-valued and type-safe dictionaries, so JSON
2235          * is not accepted yet for -M.
2236          */
2237         assert(!from_json);
2238         keyval_merge(machine_opts_dict, dict, errp);
2239     } else if (g_str_equal(group, "smp-opts")) {
2240         machine_merge_property("smp", dict, &error_fatal);
2241     } else if (g_str_equal(group, "boot-opts")) {
2242         machine_merge_property("boot", dict, &error_fatal);
2243     } else {
2244         abort();
2245     }
2246 }
2247 
2248 /*
2249  * Parse non-QemuOpts config file groups, pass the rest to
2250  * qemu_config_do_parse.
2251  */
2252 static void qemu_parse_config_group(const char *group, QDict *qdict,
2253                                     void *opaque, Error **errp)
2254 {
2255     QObject *crumpled;
2256     if (is_qemuopts_group(group)) {
2257         qemu_config_do_parse(group, qdict, opaque, errp);
2258         return;
2259     }
2260 
2261     crumpled = qdict_crumple(qdict, errp);
2262     if (!crumpled) {
2263         return;
2264     }
2265     switch (qobject_type(crumpled)) {
2266     case QTYPE_QDICT:
2267         qemu_record_config_group(group, qobject_to(QDict, crumpled), false, errp);
2268         break;
2269     case QTYPE_QLIST:
2270         error_setg(errp, "Lists cannot be at top level of a configuration section");
2271         break;
2272     default:
2273         g_assert_not_reached();
2274     }
2275     qobject_unref(crumpled);
2276 }
2277 
2278 static void qemu_read_default_config_file(Error **errp)
2279 {
2280     ERRP_GUARD();
2281     int ret;
2282     g_autofree char *file = get_relocated_path(CONFIG_QEMU_CONFDIR "/qemu.conf");
2283 
2284     ret = qemu_read_config_file(file, qemu_parse_config_group, errp);
2285     if (ret < 0) {
2286         if (ret == -ENOENT) {
2287             error_free(*errp);
2288             *errp = NULL;
2289         }
2290     }
2291 }
2292 
2293 static void qemu_set_option(const char *str, Error **errp)
2294 {
2295     char group[64], id[64], arg[64];
2296     QemuOptsList *list;
2297     QemuOpts *opts;
2298     int rc, offset;
2299 
2300     rc = sscanf(str, "%63[^.].%63[^.].%63[^=]%n", group, id, arg, &offset);
2301     if (rc < 3 || str[offset] != '=') {
2302         error_setg(errp, "can't parse: \"%s\"", str);
2303         return;
2304     }
2305 
2306     if (!is_qemuopts_group(group)) {
2307         error_setg(errp, "-set is not supported with %s", group);
2308     } else {
2309         list = qemu_find_opts_err(group, errp);
2310         if (list) {
2311             opts = qemu_opts_find(list, id);
2312             if (!opts) {
2313                 error_setg(errp, "there is no %s \"%s\" defined", group, id);
2314                 return;
2315             }
2316             qemu_opt_set(opts, arg, str + offset + 1, errp);
2317         }
2318     }
2319 }
2320 
2321 static void user_register_global_props(void)
2322 {
2323     qemu_opts_foreach(qemu_find_opts("global"),
2324                       global_init_func, NULL, NULL);
2325 }
2326 
2327 static int do_configure_icount(void *opaque, QemuOpts *opts, Error **errp)
2328 {
2329     return !icount_configure(opts, errp);
2330 }
2331 
2332 static int accelerator_set_property(void *opaque,
2333                                 const char *name, const char *value,
2334                                 Error **errp)
2335 {
2336     return object_parse_property_opt(opaque, name, value, "accel", errp);
2337 }
2338 
2339 static int do_configure_accelerator(void *opaque, QemuOpts *opts, Error **errp)
2340 {
2341     bool *p_init_failed = opaque;
2342     const char *acc = qemu_opt_get(opts, "accel");
2343     AccelClass *ac = accel_find(acc);
2344     AccelState *accel;
2345     int ret;
2346     bool qtest_with_kvm;
2347 
2348     if (!acc) {
2349         error_setg(errp, QERR_MISSING_PARAMETER, "accel");
2350         goto bad;
2351     }
2352 
2353     qtest_with_kvm = g_str_equal(acc, "kvm") && qtest_chrdev != NULL;
2354 
2355     if (!ac) {
2356         if (!qtest_with_kvm) {
2357             error_report("invalid accelerator %s", acc);
2358         }
2359         goto bad;
2360     }
2361     accel = ACCEL(object_new_with_class(OBJECT_CLASS(ac)));
2362     object_apply_compat_props(OBJECT(accel));
2363     qemu_opt_foreach(opts, accelerator_set_property,
2364                      accel,
2365                      &error_fatal);
2366 
2367     ret = accel_init_machine(accel, current_machine);
2368     if (ret < 0) {
2369         if (!qtest_with_kvm || ret != -ENOENT) {
2370             error_report("failed to initialize %s: %s", acc, strerror(-ret));
2371         }
2372         goto bad;
2373     }
2374 
2375     return 1;
2376 
2377 bad:
2378     *p_init_failed = true;
2379     return 0;
2380 }
2381 
2382 static void configure_accelerators(const char *progname)
2383 {
2384     bool init_failed = false;
2385 
2386     qemu_opts_foreach(qemu_find_opts("icount"),
2387                       do_configure_icount, NULL, &error_fatal);
2388 
2389     if (QTAILQ_EMPTY(&qemu_accel_opts.head)) {
2390         char **accel_list, **tmp;
2391 
2392         if (accelerators == NULL) {
2393             /* Select the default accelerator */
2394             bool have_tcg = accel_find("tcg");
2395             bool have_kvm = accel_find("kvm");
2396             bool have_hvf = accel_find("hvf");
2397 
2398             if (have_tcg && have_kvm) {
2399                 if (g_str_has_suffix(progname, "kvm")) {
2400                     /* If the program name ends with "kvm", we prefer KVM */
2401                     accelerators = "kvm:tcg";
2402                 } else {
2403                     accelerators = "tcg:kvm";
2404                 }
2405             } else if (have_kvm) {
2406                 accelerators = "kvm";
2407             } else if (have_tcg) {
2408                 accelerators = "tcg";
2409             } else if (have_hvf) {
2410                 accelerators = "hvf";
2411             } else {
2412                 error_report("No accelerator selected and"
2413                              " no default accelerator available");
2414                 exit(1);
2415             }
2416         }
2417         accel_list = g_strsplit(accelerators, ":", 0);
2418 
2419         for (tmp = accel_list; *tmp; tmp++) {
2420             /*
2421              * Filter invalid accelerators here, to prevent obscenities
2422              * such as "-machine accel=tcg,,thread=single".
2423              */
2424             if (accel_find(*tmp)) {
2425                 qemu_opts_parse_noisily(qemu_find_opts("accel"), *tmp, true);
2426             } else {
2427                 init_failed = true;
2428                 error_report("invalid accelerator %s", *tmp);
2429             }
2430         }
2431         g_strfreev(accel_list);
2432     } else {
2433         if (accelerators != NULL) {
2434             error_report("The -accel and \"-machine accel=\" options are incompatible");
2435             exit(1);
2436         }
2437     }
2438 
2439     if (!qemu_opts_foreach(qemu_find_opts("accel"),
2440                            do_configure_accelerator, &init_failed, &error_fatal)) {
2441         if (!init_failed) {
2442             error_report("no accelerator found");
2443         }
2444         exit(1);
2445     }
2446 
2447     if (init_failed && !qtest_chrdev) {
2448         error_report("falling back to %s", current_accel_name());
2449     }
2450 
2451     if (icount_enabled() && !tcg_enabled()) {
2452         error_report("-icount is not allowed with hardware virtualization");
2453         exit(1);
2454     }
2455 }
2456 
2457 static void qemu_validate_options(const QDict *machine_opts)
2458 {
2459     const char *kernel_filename = qdict_get_try_str(machine_opts, "kernel");
2460     const char *shim_filename = qdict_get_try_str(machine_opts, "shim");
2461     const char *initrd_filename = qdict_get_try_str(machine_opts, "initrd");
2462     const char *kernel_cmdline = qdict_get_try_str(machine_opts, "append");
2463 
2464     if (kernel_filename == NULL) {
2465         if (kernel_cmdline != NULL) {
2466             error_report("-append only allowed with -kernel option");
2467             exit(1);
2468         }
2469 
2470         if (shim_filename != NULL) {
2471             error_report("-shim only allowed with -kernel option");
2472             exit(1);
2473         }
2474 
2475         if (initrd_filename != NULL) {
2476             error_report("-initrd only allowed with -kernel option");
2477             exit(1);
2478         }
2479     }
2480 
2481     if (loadvm && incoming) {
2482         error_report("'incoming' and 'loadvm' options are mutually exclusive");
2483         exit(EXIT_FAILURE);
2484     }
2485     if (loadvm && preconfig_requested) {
2486         error_report("'preconfig' and 'loadvm' options are "
2487                      "mutually exclusive");
2488         exit(EXIT_FAILURE);
2489     }
2490     if (incoming && preconfig_requested && strcmp(incoming, "defer") != 0) {
2491         error_report("'preconfig' supports '-incoming defer' only");
2492         exit(EXIT_FAILURE);
2493     }
2494 
2495 #ifdef CONFIG_CURSES
2496     if (is_daemonized() && dpy.type == DISPLAY_TYPE_CURSES) {
2497         error_report("curses display cannot be used with -daemonize");
2498         exit(1);
2499     }
2500 #endif
2501 }
2502 
2503 static void qemu_process_sugar_options(void)
2504 {
2505     if (mem_prealloc) {
2506         QObject *smp = qdict_get(machine_opts_dict, "smp");
2507         if (smp && qobject_type(smp) == QTYPE_QDICT) {
2508             QObject *cpus = qdict_get(qobject_to(QDict, smp), "cpus");
2509             if (cpus && qobject_type(cpus) == QTYPE_QSTRING) {
2510                 const char *val = qstring_get_str(qobject_to(QString, cpus));
2511                 object_register_sugar_prop("memory-backend", "prealloc-threads",
2512                                            val, false);
2513             }
2514         }
2515         object_register_sugar_prop("memory-backend", "prealloc", "on", false);
2516     }
2517 }
2518 
2519 /* -action processing */
2520 
2521 /*
2522  * Process all the -action parameters parsed from cmdline.
2523  */
2524 static int process_runstate_actions(void *opaque, QemuOpts *opts, Error **errp)
2525 {
2526     Error *local_err = NULL;
2527     QDict *qdict = qemu_opts_to_qdict(opts, NULL);
2528     QObject *ret = NULL;
2529     qmp_marshal_set_action(qdict, &ret, &local_err);
2530     qobject_unref(ret);
2531     qobject_unref(qdict);
2532     if (local_err) {
2533         error_propagate(errp, local_err);
2534         return 1;
2535     }
2536     return 0;
2537 }
2538 
2539 static void qemu_process_early_options(void)
2540 {
2541     qemu_opts_foreach(qemu_find_opts("name"),
2542                       parse_name, NULL, &error_fatal);
2543 
2544     object_option_foreach_add(object_create_pre_sandbox);
2545 
2546 #ifdef CONFIG_SECCOMP
2547     QemuOptsList *olist = qemu_find_opts_err("sandbox", NULL);
2548     if (olist) {
2549         qemu_opts_foreach(olist, parse_sandbox, NULL, &error_fatal);
2550     }
2551 #endif
2552 
2553     if (qemu_opts_foreach(qemu_find_opts("action"),
2554                           process_runstate_actions, NULL, &error_fatal)) {
2555         exit(1);
2556     }
2557 
2558 #ifndef _WIN32
2559     qemu_opts_foreach(qemu_find_opts("add-fd"),
2560                       parse_add_fd, NULL, &error_fatal);
2561 
2562     qemu_opts_foreach(qemu_find_opts("add-fd"),
2563                       cleanup_add_fd, NULL, &error_fatal);
2564 #endif
2565 
2566     /* Open the logfile at this point and set the log mask if necessary.  */
2567     {
2568         int mask = 0;
2569         if (log_mask) {
2570             mask = qemu_str_to_log_mask(log_mask);
2571             if (!mask) {
2572                 qemu_print_log_usage(stdout);
2573                 exit(1);
2574             }
2575         }
2576         qemu_set_log_filename_flags(log_file, mask, &error_fatal);
2577     }
2578 
2579     qemu_add_default_firmwarepath();
2580 }
2581 
2582 static void qemu_process_help_options(void)
2583 {
2584     /*
2585      * Check for -cpu help and -device help before we call select_machine(),
2586      * which will return an error if the architecture has no default machine
2587      * type and the user did not specify one, so that the user doesn't need
2588      * to say '-cpu help -machine something'.
2589      */
2590     if (cpu_option && is_help_option(cpu_option)) {
2591         list_cpus();
2592         exit(0);
2593     }
2594 
2595     if (qemu_opts_foreach(qemu_find_opts("device"),
2596                           device_help_func, NULL, NULL)) {
2597         exit(0);
2598     }
2599 
2600     /* -L help lists the data directories and exits. */
2601     if (list_data_dirs) {
2602         qemu_list_data_dirs();
2603         exit(0);
2604     }
2605 }
2606 
2607 static void qemu_maybe_daemonize(const char *pid_file)
2608 {
2609     Error *err = NULL;
2610 
2611     os_daemonize();
2612     rcu_disable_atfork();
2613 
2614     if (pid_file) {
2615         char *pid_file_realpath = NULL;
2616 
2617         if (!qemu_write_pidfile(pid_file, &err)) {
2618             error_reportf_err(err, "cannot create PID file: ");
2619             exit(1);
2620         }
2621 
2622         pid_file_realpath = g_malloc0(PATH_MAX);
2623         if (!realpath(pid_file, pid_file_realpath)) {
2624             if (errno != ENOENT) {
2625                 warn_report("not removing PID file on exit: cannot resolve PID "
2626                             "file path: %s: %s", pid_file, strerror(errno));
2627             }
2628             return;
2629         }
2630 
2631         qemu_unlink_pidfile_notifier = (struct UnlinkPidfileNotifier) {
2632             .notifier = {
2633                 .notify = qemu_unlink_pidfile,
2634             },
2635             .pid_file_realpath = pid_file_realpath,
2636         };
2637         qemu_add_exit_notifier(&qemu_unlink_pidfile_notifier.notifier);
2638     }
2639 }
2640 
2641 static void qemu_init_displays(void)
2642 {
2643     DisplayState *ds;
2644 
2645     /* init local displays */
2646     ds = init_displaystate();
2647     qemu_display_init(ds, &dpy);
2648 
2649     /* must be after terminal init, SDL library changes signal handlers */
2650     os_setup_signal_handling();
2651 
2652     /* init remote displays */
2653 #ifdef CONFIG_VNC
2654     qemu_opts_foreach(qemu_find_opts("vnc"),
2655                       vnc_init_func, NULL, &error_fatal);
2656 #endif
2657 
2658     if (using_spice) {
2659         qemu_spice.display_init();
2660     }
2661 }
2662 
2663 static void qemu_init_board(void)
2664 {
2665     MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2666 
2667     /* process plugin before CPUs are created, but once -smp has been parsed */
2668     qemu_plugin_load_list(&plugin_list, &error_fatal);
2669 
2670     /* From here on we enter MACHINE_PHASE_INITIALIZED.  */
2671     machine_run_board_init(current_machine, mem_path, &error_fatal);
2672 
2673     if (machine_class->auto_create_sdcard) {
2674         bool ambigous;
2675 
2676         /* Ensure there is a SD bus available to create SD card on */
2677         Object *obj = object_resolve_path_type("", TYPE_SD_BUS, &ambigous);
2678         if (!obj && !ambigous) {
2679             fprintf(stderr, "Can not create sd-card on '%s' machine"
2680                             " because it lacks a sd-bus\n",
2681                             machine_class->name);
2682             abort();
2683         }
2684     }
2685 
2686     drive_check_orphaned();
2687 
2688     realtime_init();
2689 }
2690 
2691 static void qemu_create_cli_devices(void)
2692 {
2693     DeviceOption *opt;
2694 
2695     soundhw_init();
2696 
2697     qemu_opts_foreach(qemu_find_opts("fw_cfg"),
2698                       parse_fw_cfg, fw_cfg_find(), &error_fatal);
2699 
2700     /* init USB devices */
2701     if (machine_usb(current_machine)) {
2702         foreach_device_config_or_exit(DEV_USB, usb_parse);
2703     }
2704 
2705     /* init generic devices */
2706     rom_set_order_override(FW_CFG_ORDER_OVERRIDE_DEVICE);
2707     qemu_opts_foreach(qemu_find_opts("device"),
2708                       device_init_func, NULL, &error_fatal);
2709     QTAILQ_FOREACH(opt, &device_opts, next) {
2710         QObject *ret_data = NULL;
2711 
2712         loc_push_restore(&opt->loc);
2713         qmp_device_add(opt->opts, &ret_data, &error_fatal);
2714         assert(ret_data == NULL); /* error_fatal aborts */
2715         loc_pop(&opt->loc);
2716     }
2717     rom_reset_order_override();
2718 }
2719 
2720 static bool qemu_machine_creation_done(Error **errp)
2721 {
2722     MachineState *machine = MACHINE(qdev_get_machine());
2723 
2724     /* Did we create any drives that we failed to create a device for? */
2725     drive_check_orphaned();
2726 
2727     /* Don't warn about the default network setup that you get if
2728      * no command line -net or -netdev options are specified. There
2729      * are two cases that we would otherwise complain about:
2730      * (1) board doesn't support a NIC but the implicit "-net nic"
2731      * requested one
2732      * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
2733      * sets up a nic that isn't connected to anything.
2734      */
2735     if (!default_net && (!qtest_enabled() || has_defaults)) {
2736         net_check_clients();
2737     }
2738 
2739     qdev_prop_check_globals();
2740 
2741     qdev_machine_creation_done();
2742 
2743     if (machine->cgs && !machine->cgs->ready) {
2744         error_setg(errp, "accelerator does not support confidential guest %s",
2745                    object_get_typename(OBJECT(machine->cgs)));
2746         exit(1);
2747     }
2748 
2749     foreach_device_config_or_exit(DEV_GDB, gdbserver_start);
2750 
2751     if (!vga_interface_created && !default_vga &&
2752         vga_interface_type != VGA_NONE) {
2753         warn_report("A -vga option was passed but this machine "
2754                     "type does not use that option; "
2755                     "No VGA device has been created");
2756     }
2757     return true;
2758 }
2759 
2760 void qmp_x_exit_preconfig(Error **errp)
2761 {
2762     if (phase_check(PHASE_MACHINE_INITIALIZED)) {
2763         error_setg(errp, "The command is permitted only before machine initialization");
2764         return;
2765     }
2766 
2767     qemu_init_board();
2768     qemu_create_cli_devices();
2769     if (!qemu_machine_creation_done(errp)) {
2770         return;
2771     }
2772 
2773     if (loadvm) {
2774         RunState state = autostart ? RUN_STATE_RUNNING : runstate_get();
2775         load_snapshot(loadvm, NULL, false, NULL, &error_fatal);
2776         load_snapshot_resume(state);
2777     }
2778     if (replay_mode != REPLAY_MODE_NONE) {
2779         replay_vmstate_init();
2780     }
2781 
2782     if (incoming) {
2783         Error *local_err = NULL;
2784         if (strcmp(incoming, "defer") != 0) {
2785             g_autofree MigrationChannelList *channels =
2786                 g_new0(MigrationChannelList, 1);
2787 
2788             channels->value = incoming_channels[MIGRATION_CHANNEL_TYPE_MAIN];
2789             qmp_migrate_incoming(NULL, true, channels, true, true, &local_err);
2790             if (local_err) {
2791                 error_reportf_err(local_err, "-incoming %s: ", incoming);
2792                 exit(1);
2793             }
2794         }
2795     } else if (autostart) {
2796         qmp_cont(NULL);
2797     }
2798 }
2799 
2800 void qemu_init(int argc, char **argv)
2801 {
2802     QemuOpts *opts;
2803     QemuOpts *icount_opts = NULL, *accel_opts = NULL;
2804     QemuOptsList *olist;
2805     int optind;
2806     const char *optarg;
2807     MachineClass *machine_class;
2808     bool userconfig = true;
2809     FILE *vmstate_dump_file = NULL;
2810 
2811     qemu_add_opts(&qemu_drive_opts);
2812     qemu_add_drive_opts(&qemu_legacy_drive_opts);
2813     qemu_add_drive_opts(&qemu_common_drive_opts);
2814     qemu_add_drive_opts(&qemu_drive_opts);
2815     qemu_add_drive_opts(&bdrv_runtime_opts);
2816     qemu_add_opts(&qemu_chardev_opts);
2817     qemu_add_opts(&qemu_device_opts);
2818     qemu_add_opts(&qemu_netdev_opts);
2819     qemu_add_opts(&qemu_nic_opts);
2820     qemu_add_opts(&qemu_net_opts);
2821     qemu_add_opts(&qemu_rtc_opts);
2822     qemu_add_opts(&qemu_global_opts);
2823     qemu_add_opts(&qemu_mon_opts);
2824     qemu_add_opts(&qemu_trace_opts);
2825     qemu_plugin_add_opts();
2826     qemu_add_opts(&qemu_option_rom_opts);
2827     qemu_add_opts(&qemu_accel_opts);
2828     qemu_add_opts(&qemu_mem_opts);
2829     qemu_add_opts(&qemu_smp_opts);
2830     qemu_add_opts(&qemu_boot_opts);
2831     qemu_add_opts(&qemu_add_fd_opts);
2832     qemu_add_opts(&qemu_object_opts);
2833     qemu_add_opts(&qemu_tpmdev_opts);
2834     qemu_add_opts(&qemu_overcommit_opts);
2835     qemu_add_opts(&qemu_msg_opts);
2836     qemu_add_opts(&qemu_name_opts);
2837     qemu_add_opts(&qemu_numa_opts);
2838     qemu_add_opts(&qemu_icount_opts);
2839     qemu_add_opts(&qemu_semihosting_config_opts);
2840     qemu_add_opts(&qemu_fw_cfg_opts);
2841     qemu_add_opts(&qemu_action_opts);
2842     qemu_add_run_with_opts();
2843     module_call_init(MODULE_INIT_OPTS);
2844 
2845     error_init(argv[0]);
2846     qemu_init_exec_dir(argv[0]);
2847 
2848     os_setup_limits();
2849 
2850     qemu_init_arch_modules();
2851 
2852     qemu_init_subsystems();
2853 
2854     /* first pass of option parsing */
2855     optind = 1;
2856     while (optind < argc) {
2857         if (argv[optind][0] != '-') {
2858             /* disk image */
2859             optind++;
2860         } else {
2861             const QEMUOption *popt;
2862 
2863             popt = lookup_opt(argc, argv, &optarg, &optind);
2864             switch (popt->index) {
2865             case QEMU_OPTION_nouserconfig:
2866                 userconfig = false;
2867                 break;
2868             }
2869         }
2870     }
2871 
2872     machine_opts_dict = qdict_new();
2873     if (userconfig) {
2874         qemu_read_default_config_file(&error_fatal);
2875     }
2876 
2877     /* second pass of option parsing */
2878     optind = 1;
2879     for(;;) {
2880         if (optind >= argc)
2881             break;
2882         if (argv[optind][0] != '-') {
2883             loc_set_cmdline(argv, optind, 1);
2884             drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
2885         } else {
2886             const QEMUOption *popt;
2887 
2888             popt = lookup_opt(argc, argv, &optarg, &optind);
2889             if (!(popt->arch_mask & arch_type)) {
2890                 error_report("Option not supported for this target");
2891                 exit(1);
2892             }
2893             switch(popt->index) {
2894             case QEMU_OPTION_cpu:
2895                 /* hw initialization will check this */
2896                 cpu_option = optarg;
2897                 break;
2898             case QEMU_OPTION_hda:
2899             case QEMU_OPTION_hdb:
2900             case QEMU_OPTION_hdc:
2901             case QEMU_OPTION_hdd:
2902                 drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
2903                           HD_OPTS);
2904                 break;
2905             case QEMU_OPTION_blockdev:
2906                 {
2907                     Visitor *v;
2908                     BlockdevOptionsQueueEntry *bdo;
2909 
2910                     v = qobject_input_visitor_new_str(optarg, "driver",
2911                                                       &error_fatal);
2912 
2913                     bdo = g_new(BlockdevOptionsQueueEntry, 1);
2914                     visit_type_BlockdevOptions(v, NULL, &bdo->bdo,
2915                                                &error_fatal);
2916                     visit_free(v);
2917                     loc_save(&bdo->loc);
2918                     QSIMPLEQ_INSERT_TAIL(&bdo_queue, bdo, entry);
2919                     break;
2920                 }
2921             case QEMU_OPTION_drive:
2922                 opts = qemu_opts_parse_noisily(qemu_find_opts("drive"),
2923                                                optarg, false);
2924                 if (opts == NULL) {
2925                     exit(1);
2926                 }
2927                 break;
2928             case QEMU_OPTION_set:
2929                 qemu_set_option(optarg, &error_fatal);
2930                 break;
2931             case QEMU_OPTION_global:
2932                 if (qemu_global_option(optarg) != 0)
2933                     exit(1);
2934                 break;
2935             case QEMU_OPTION_mtdblock:
2936                 drive_add(IF_MTD, -1, optarg, MTD_OPTS);
2937                 break;
2938             case QEMU_OPTION_sd:
2939                 drive_add(IF_SD, -1, optarg, SD_OPTS);
2940                 break;
2941             case QEMU_OPTION_pflash:
2942                 drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
2943                 break;
2944             case QEMU_OPTION_snapshot:
2945                 snapshot = 1;
2946                 replay_add_blocker("-snapshot");
2947                 break;
2948             case QEMU_OPTION_numa:
2949                 opts = qemu_opts_parse_noisily(qemu_find_opts("numa"),
2950                                                optarg, true);
2951                 if (!opts) {
2952                     exit(1);
2953                 }
2954                 break;
2955             case QEMU_OPTION_display:
2956                 parse_display(optarg);
2957                 break;
2958             case QEMU_OPTION_nographic:
2959                 qdict_put_str(machine_opts_dict, "graphics", "off");
2960                 nographic = true;
2961                 dpy.type = DISPLAY_TYPE_NONE;
2962                 break;
2963             case QEMU_OPTION_kernel:
2964                 qdict_put_str(machine_opts_dict, "kernel", optarg);
2965                 break;
2966             case QEMU_OPTION_shim:
2967                 qdict_put_str(machine_opts_dict, "shim", optarg);
2968                 break;
2969             case QEMU_OPTION_initrd:
2970                 qdict_put_str(machine_opts_dict, "initrd", optarg);
2971                 break;
2972             case QEMU_OPTION_append:
2973                 qdict_put_str(machine_opts_dict, "append", optarg);
2974                 break;
2975             case QEMU_OPTION_dtb:
2976                 qdict_put_str(machine_opts_dict, "dtb", optarg);
2977                 break;
2978             case QEMU_OPTION_cdrom:
2979                 drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
2980                 break;
2981             case QEMU_OPTION_boot:
2982                 machine_parse_property_opt(qemu_find_opts("boot-opts"), "boot", optarg);
2983                 break;
2984             case QEMU_OPTION_fda:
2985             case QEMU_OPTION_fdb:
2986                 drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
2987                           optarg, FD_OPTS);
2988                 break;
2989             case QEMU_OPTION_no_fd_bootchk:
2990                 qdict_put_str(machine_opts_dict, "fd-bootchk", "off");
2991                 break;
2992             case QEMU_OPTION_netdev:
2993                 default_net = 0;
2994                 if (netdev_is_modern(optarg)) {
2995                     netdev_parse_modern(optarg);
2996                 } else {
2997                     net_client_parse(qemu_find_opts("netdev"), optarg);
2998                 }
2999                 break;
3000             case QEMU_OPTION_nic:
3001                 default_net = 0;
3002                 net_client_parse(qemu_find_opts("nic"), optarg);
3003                 break;
3004             case QEMU_OPTION_net:
3005                 default_net = 0;
3006                 net_client_parse(qemu_find_opts("net"), optarg);
3007                 break;
3008 #ifdef CONFIG_LIBISCSI
3009             case QEMU_OPTION_iscsi:
3010                 opts = qemu_opts_parse_noisily(qemu_find_opts("iscsi"),
3011                                                optarg, false);
3012                 if (!opts) {
3013                     exit(1);
3014                 }
3015                 break;
3016 #endif
3017             case QEMU_OPTION_audiodev:
3018                 default_audio = 0;
3019                 audio_parse_option(optarg);
3020                 break;
3021             case QEMU_OPTION_audio: {
3022                 bool help;
3023                 char *model = NULL;
3024                 Audiodev *dev = NULL;
3025                 Visitor *v;
3026                 QDict *dict = keyval_parse(optarg, "driver", &help, &error_fatal);
3027                 default_audio = 0;
3028                 if (help || (qdict_haskey(dict, "driver") &&
3029                              is_help_option(qdict_get_str(dict, "driver")))) {
3030                     audio_help();
3031                     exit(EXIT_SUCCESS);
3032                 }
3033                 if (!qdict_haskey(dict, "id")) {
3034                     qdict_put_str(dict, "id", "audiodev0");
3035                 }
3036                 if (qdict_haskey(dict, "model")) {
3037                     model = g_strdup(qdict_get_str(dict, "model"));
3038                     qdict_del(dict, "model");
3039                     if (is_help_option(model)) {
3040                         show_valid_soundhw();
3041                         exit(0);
3042                     }
3043                 }
3044                 v = qobject_input_visitor_new_keyval(QOBJECT(dict));
3045                 qobject_unref(dict);
3046                 visit_type_Audiodev(v, NULL, &dev, &error_fatal);
3047                 visit_free(v);
3048                 if (model) {
3049                     audio_define(dev);
3050                     select_soundhw(model, dev->id);
3051                     g_free(model);
3052                 } else {
3053                     audio_define_default(dev, &error_fatal);
3054                 }
3055                 break;
3056             }
3057             case QEMU_OPTION_h:
3058                 help(0);
3059                 break;
3060             case QEMU_OPTION_version:
3061                 version();
3062                 exit(0);
3063                 break;
3064             case QEMU_OPTION_m:
3065                 opts = qemu_opts_parse_noisily(qemu_find_opts("memory"), optarg, true);
3066                 if (opts == NULL) {
3067                     exit(1);
3068                 }
3069                 break;
3070 #ifdef CONFIG_TPM
3071             case QEMU_OPTION_tpmdev:
3072                 if (tpm_config_parse(qemu_find_opts("tpmdev"), optarg) < 0) {
3073                     exit(1);
3074                 }
3075                 break;
3076 #endif
3077             case QEMU_OPTION_mempath:
3078                 mem_path = optarg;
3079                 break;
3080             case QEMU_OPTION_mem_prealloc:
3081                 mem_prealloc = 1;
3082                 break;
3083             case QEMU_OPTION_d:
3084                 log_mask = optarg;
3085                 break;
3086             case QEMU_OPTION_D:
3087                 log_file = optarg;
3088                 break;
3089             case QEMU_OPTION_DFILTER:
3090                 qemu_set_dfilter_ranges(optarg, &error_fatal);
3091                 break;
3092 #if defined(CONFIG_TCG) && defined(CONFIG_LINUX)
3093             case QEMU_OPTION_perfmap:
3094                 perf_enable_perfmap();
3095                 break;
3096             case QEMU_OPTION_jitdump:
3097                 perf_enable_jitdump();
3098                 break;
3099 #endif
3100             case QEMU_OPTION_seed:
3101                 qemu_guest_random_seed_main(optarg, &error_fatal);
3102                 break;
3103             case QEMU_OPTION_s:
3104                 add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
3105                 break;
3106             case QEMU_OPTION_gdb:
3107                 add_device_config(DEV_GDB, optarg);
3108                 break;
3109             case QEMU_OPTION_L:
3110                 if (is_help_option(optarg)) {
3111                     list_data_dirs = true;
3112                 } else {
3113                     qemu_add_data_dir(g_strdup(optarg));
3114                 }
3115                 break;
3116             case QEMU_OPTION_bios:
3117                 qdict_put_str(machine_opts_dict, "firmware", optarg);
3118                 break;
3119             case QEMU_OPTION_S:
3120                 autostart = 0;
3121                 break;
3122             case QEMU_OPTION_k:
3123                 keyboard_layout = optarg;
3124                 break;
3125             case QEMU_OPTION_vga:
3126                 vga_model = optarg;
3127                 default_vga = 0;
3128                 break;
3129             case QEMU_OPTION_g:
3130                 {
3131                     const char *p;
3132                     int w, h, depth;
3133                     p = optarg;
3134                     w = strtol(p, (char **)&p, 10);
3135                     if (w <= 0) {
3136                     graphic_error:
3137                         error_report("invalid resolution or depth");
3138                         exit(1);
3139                     }
3140                     if (*p != 'x')
3141                         goto graphic_error;
3142                     p++;
3143                     h = strtol(p, (char **)&p, 10);
3144                     if (h <= 0)
3145                         goto graphic_error;
3146                     if (*p == 'x') {
3147                         p++;
3148                         depth = strtol(p, (char **)&p, 10);
3149                         if (depth != 1 && depth != 2 && depth != 4 &&
3150                             depth != 8 && depth != 15 && depth != 16 &&
3151                             depth != 24 && depth != 32)
3152                             goto graphic_error;
3153                     } else if (*p == '\0') {
3154                         depth = graphic_depth;
3155                     } else {
3156                         goto graphic_error;
3157                     }
3158 
3159                     graphic_width = w;
3160                     graphic_height = h;
3161                     graphic_depth = depth;
3162                 }
3163                 break;
3164             case QEMU_OPTION_echr:
3165                 {
3166                     char *r;
3167                     term_escape_char = strtol(optarg, &r, 0);
3168                     if (r == optarg)
3169                         printf("Bad argument to echr\n");
3170                     break;
3171                 }
3172             case QEMU_OPTION_monitor:
3173                 default_monitor = 0;
3174                 if (strncmp(optarg, "none", 4)) {
3175                     monitor_parse(optarg, "readline", false);
3176                 }
3177                 break;
3178             case QEMU_OPTION_qmp:
3179                 monitor_parse(optarg, "control", false);
3180                 default_monitor = 0;
3181                 break;
3182             case QEMU_OPTION_qmp_pretty:
3183                 monitor_parse(optarg, "control", true);
3184                 default_monitor = 0;
3185                 break;
3186             case QEMU_OPTION_mon:
3187                 opts = qemu_opts_parse_noisily(qemu_find_opts("mon"), optarg,
3188                                                true);
3189                 if (!opts) {
3190                     exit(1);
3191                 }
3192                 default_monitor = 0;
3193                 break;
3194             case QEMU_OPTION_chardev:
3195                 opts = qemu_opts_parse_noisily(qemu_find_opts("chardev"),
3196                                                optarg, true);
3197                 if (!opts) {
3198                     exit(1);
3199                 }
3200                 break;
3201             case QEMU_OPTION_fsdev:
3202                 olist = qemu_find_opts("fsdev");
3203                 if (!olist) {
3204                     error_report("fsdev support is disabled");
3205                     exit(1);
3206                 }
3207                 opts = qemu_opts_parse_noisily(olist, optarg, true);
3208                 if (!opts) {
3209                     exit(1);
3210                 }
3211                 break;
3212             case QEMU_OPTION_virtfs: {
3213                 QemuOpts *fsdev;
3214                 QemuOpts *device;
3215                 const char *writeout, *sock_fd, *socket, *path, *security_model,
3216                            *multidevs;
3217 
3218                 olist = qemu_find_opts("virtfs");
3219                 if (!olist) {
3220                     error_report("virtfs support is disabled");
3221                     exit(1);
3222                 }
3223                 opts = qemu_opts_parse_noisily(olist, optarg, true);
3224                 if (!opts) {
3225                     exit(1);
3226                 }
3227 
3228                 if (qemu_opt_get(opts, "fsdriver") == NULL ||
3229                     qemu_opt_get(opts, "mount_tag") == NULL) {
3230                     error_report("Usage: -virtfs fsdriver,mount_tag=tag");
3231                     exit(1);
3232                 }
3233                 fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
3234                                          qemu_opts_id(opts) ?:
3235                                          qemu_opt_get(opts, "mount_tag"),
3236                                          1, NULL);
3237                 if (!fsdev) {
3238                     error_report("duplicate or invalid fsdev id: %s",
3239                                  qemu_opt_get(opts, "mount_tag"));
3240                     exit(1);
3241                 }
3242 
3243                 writeout = qemu_opt_get(opts, "writeout");
3244                 if (writeout) {
3245 #ifdef CONFIG_SYNC_FILE_RANGE
3246                     qemu_opt_set(fsdev, "writeout", writeout, &error_abort);
3247 #else
3248                     error_report("writeout=immediate not supported "
3249                                  "on this platform");
3250                     exit(1);
3251 #endif
3252                 }
3253                 qemu_opt_set(fsdev, "fsdriver",
3254                              qemu_opt_get(opts, "fsdriver"), &error_abort);
3255                 path = qemu_opt_get(opts, "path");
3256                 if (path) {
3257                     qemu_opt_set(fsdev, "path", path, &error_abort);
3258                 }
3259                 security_model = qemu_opt_get(opts, "security_model");
3260                 if (security_model) {
3261                     qemu_opt_set(fsdev, "security_model", security_model,
3262                                  &error_abort);
3263                 }
3264                 socket = qemu_opt_get(opts, "socket");
3265                 if (socket) {
3266                     qemu_opt_set(fsdev, "socket", socket, &error_abort);
3267                 }
3268                 sock_fd = qemu_opt_get(opts, "sock_fd");
3269                 if (sock_fd) {
3270                     qemu_opt_set(fsdev, "sock_fd", sock_fd, &error_abort);
3271                 }
3272 
3273                 qemu_opt_set_bool(fsdev, "readonly",
3274                                   qemu_opt_get_bool(opts, "readonly", 0),
3275                                   &error_abort);
3276                 multidevs = qemu_opt_get(opts, "multidevs");
3277                 if (multidevs) {
3278                     qemu_opt_set(fsdev, "multidevs", multidevs, &error_abort);
3279                 }
3280                 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3281                                           &error_abort);
3282                 qemu_opt_set(device, "driver", "virtio-9p-pci", &error_abort);
3283                 qemu_opt_set(device, "fsdev",
3284                              qemu_opts_id(fsdev), &error_abort);
3285                 qemu_opt_set(device, "mount_tag",
3286                              qemu_opt_get(opts, "mount_tag"), &error_abort);
3287                 break;
3288             }
3289             case QEMU_OPTION_serial:
3290                 add_device_config(DEV_SERIAL, optarg);
3291                 default_serial = 0;
3292                 if (strncmp(optarg, "mon:", 4) == 0) {
3293                     default_monitor = 0;
3294                 }
3295                 break;
3296             case QEMU_OPTION_action:
3297                 olist = qemu_find_opts("action");
3298                 if (!qemu_opts_parse_noisily(olist, optarg, false)) {
3299                      exit(1);
3300                 }
3301                 break;
3302             case QEMU_OPTION_watchdog_action: {
3303                 opts = qemu_opts_create(qemu_find_opts("action"), NULL, 0, &error_abort);
3304                 qemu_opt_set(opts, "watchdog", optarg, &error_abort);
3305                 break;
3306             }
3307             case QEMU_OPTION_parallel:
3308                 add_device_config(DEV_PARALLEL, optarg);
3309                 default_parallel = 0;
3310                 if (strncmp(optarg, "mon:", 4) == 0) {
3311                     default_monitor = 0;
3312                 }
3313                 break;
3314             case QEMU_OPTION_debugcon:
3315                 add_device_config(DEV_DEBUGCON, optarg);
3316                 break;
3317             case QEMU_OPTION_loadvm:
3318                 loadvm = optarg;
3319                 break;
3320             case QEMU_OPTION_full_screen:
3321                 dpy.has_full_screen = true;
3322                 dpy.full_screen = true;
3323                 break;
3324             case QEMU_OPTION_pidfile:
3325                 pid_file = optarg;
3326                 break;
3327             case QEMU_OPTION_win2k_hack:
3328                 object_register_sugar_prop("ide-device", "win2k-install-hack", "true", true);
3329                 break;
3330             case QEMU_OPTION_acpitable:
3331                 opts = qemu_opts_parse_noisily(qemu_find_opts("acpi"),
3332                                                optarg, true);
3333                 if (!opts) {
3334                     exit(1);
3335                 }
3336                 acpi_table_add(opts, &error_fatal);
3337                 break;
3338             case QEMU_OPTION_smbios:
3339                 opts = qemu_opts_parse_noisily(qemu_find_opts("smbios"),
3340                                                optarg, false);
3341                 if (!opts) {
3342                     exit(1);
3343                 }
3344                 smbios_entry_add(opts, &error_fatal);
3345                 break;
3346             case QEMU_OPTION_fwcfg:
3347                 opts = qemu_opts_parse_noisily(qemu_find_opts("fw_cfg"),
3348                                                optarg, true);
3349                 if (opts == NULL) {
3350                     exit(1);
3351                 }
3352                 break;
3353             case QEMU_OPTION_preconfig:
3354                 preconfig_requested = true;
3355                 break;
3356             case QEMU_OPTION_enable_kvm:
3357                 qdict_put_str(machine_opts_dict, "accel", "kvm");
3358                 break;
3359             case QEMU_OPTION_M:
3360             case QEMU_OPTION_machine:
3361                 {
3362                     bool help;
3363 
3364                     keyval_parse_into(machine_opts_dict, optarg, "type", &help, &error_fatal);
3365                     if (help) {
3366                         machine_help_func(machine_opts_dict);
3367                         exit(EXIT_SUCCESS);
3368                     }
3369                     break;
3370                 }
3371             case QEMU_OPTION_accel:
3372                 accel_opts = qemu_opts_parse_noisily(qemu_find_opts("accel"),
3373                                                      optarg, true);
3374                 optarg = qemu_opt_get(accel_opts, "accel");
3375                 if (!optarg || is_help_option(optarg)) {
3376                     printf("Accelerators supported in QEMU binary:\n");
3377                     GSList *el, *accel_list = object_class_get_list(TYPE_ACCEL,
3378                                                                     false);
3379                     for (el = accel_list; el; el = el->next) {
3380                         gchar *typename = g_strdup(object_class_get_name(
3381                                                    OBJECT_CLASS(el->data)));
3382                         /* omit qtest which is used for tests only */
3383                         if (g_strcmp0(typename, ACCEL_CLASS_NAME("qtest")) &&
3384                             g_str_has_suffix(typename, ACCEL_CLASS_SUFFIX)) {
3385                             gchar **optname = g_strsplit(typename,
3386                                                          ACCEL_CLASS_SUFFIX, 0);
3387                             printf("%s\n", optname[0]);
3388                             g_strfreev(optname);
3389                         }
3390                         g_free(typename);
3391                     }
3392                     g_slist_free(accel_list);
3393                     exit(0);
3394                 }
3395                 break;
3396             case QEMU_OPTION_usb:
3397                 qdict_put_str(machine_opts_dict, "usb", "on");
3398                 break;
3399             case QEMU_OPTION_usbdevice:
3400                 qdict_put_str(machine_opts_dict, "usb", "on");
3401                 add_device_config(DEV_USB, optarg);
3402                 break;
3403             case QEMU_OPTION_device:
3404                 if (optarg[0] == '{') {
3405                     QObject *obj = qobject_from_json(optarg, &error_fatal);
3406                     DeviceOption *opt = g_new0(DeviceOption, 1);
3407                     opt->opts = qobject_to(QDict, obj);
3408                     loc_save(&opt->loc);
3409                     assert(opt->opts != NULL);
3410                     QTAILQ_INSERT_TAIL(&device_opts, opt, next);
3411                 } else {
3412                     if (!qemu_opts_parse_noisily(qemu_find_opts("device"),
3413                                                  optarg, true)) {
3414                         exit(1);
3415                     }
3416                 }
3417                 break;
3418             case QEMU_OPTION_smp:
3419                 machine_parse_property_opt(qemu_find_opts("smp-opts"),
3420                                            "smp", optarg);
3421                 break;
3422 #ifdef CONFIG_VNC
3423             case QEMU_OPTION_vnc:
3424                 vnc_parse(optarg);
3425                 display_remote++;
3426                 break;
3427 #endif
3428             case QEMU_OPTION_no_reboot:
3429                 olist = qemu_find_opts("action");
3430                 qemu_opts_parse_noisily(olist, "reboot=shutdown", false);
3431                 break;
3432             case QEMU_OPTION_no_shutdown:
3433                 olist = qemu_find_opts("action");
3434                 qemu_opts_parse_noisily(olist, "shutdown=pause", false);
3435                 break;
3436             case QEMU_OPTION_uuid:
3437                 if (qemu_uuid_parse(optarg, &qemu_uuid) < 0) {
3438                     error_report("failed to parse UUID string: wrong format");
3439                     exit(1);
3440                 }
3441                 qemu_uuid_set = true;
3442                 break;
3443             case QEMU_OPTION_option_rom:
3444                 if (nb_option_roms >= MAX_OPTION_ROMS) {
3445                     error_report("too many option ROMs");
3446                     exit(1);
3447                 }
3448                 opts = qemu_opts_parse_noisily(qemu_find_opts("option-rom"),
3449                                                optarg, true);
3450                 if (!opts) {
3451                     exit(1);
3452                 }
3453                 option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
3454                 option_rom[nb_option_roms].bootindex =
3455                     qemu_opt_get_number(opts, "bootindex", -1);
3456                 if (!option_rom[nb_option_roms].name) {
3457                     error_report("Option ROM file is not specified");
3458                     exit(1);
3459                 }
3460                 nb_option_roms++;
3461                 break;
3462             case QEMU_OPTION_semihosting:
3463                 qemu_semihosting_enable();
3464                 break;
3465             case QEMU_OPTION_semihosting_config:
3466                 if (qemu_semihosting_config_options(optarg) != 0) {
3467                     exit(1);
3468                 }
3469                 break;
3470             case QEMU_OPTION_name:
3471                 opts = qemu_opts_parse_noisily(qemu_find_opts("name"),
3472                                                optarg, true);
3473                 if (!opts) {
3474                     exit(1);
3475                 }
3476                 /* Capture guest name if -msg guest-name is used later */
3477                 error_guest_name = qemu_opt_get(opts, "guest");
3478                 break;
3479             case QEMU_OPTION_prom_env:
3480                 if (nb_prom_envs >= MAX_PROM_ENVS) {
3481                     error_report("too many prom variables");
3482                     exit(1);
3483                 }
3484                 prom_envs[nb_prom_envs] = optarg;
3485                 nb_prom_envs++;
3486                 break;
3487             case QEMU_OPTION_old_param:
3488                 warn_report("-old-param is deprecated");
3489                 old_param = 1;
3490                 break;
3491             case QEMU_OPTION_rtc:
3492                 opts = qemu_opts_parse_noisily(qemu_find_opts("rtc"), optarg,
3493                                                false);
3494                 if (!opts) {
3495                     exit(1);
3496                 }
3497                 break;
3498             case QEMU_OPTION_icount:
3499                 icount_opts = qemu_opts_parse_noisily(qemu_find_opts("icount"),
3500                                                       optarg, true);
3501                 if (!icount_opts) {
3502                     exit(1);
3503                 }
3504                 break;
3505             case QEMU_OPTION_incoming:
3506                 if (!incoming) {
3507                     runstate_set(RUN_STATE_INMIGRATE);
3508                 }
3509                 incoming_option_parse(optarg);
3510                 break;
3511             case QEMU_OPTION_only_migratable:
3512                 only_migratable = 1;
3513                 break;
3514             case QEMU_OPTION_nodefaults:
3515                 has_defaults = 0;
3516                 break;
3517             case QEMU_OPTION_xen_domid:
3518                 if (!(accel_find("xen")) && !(accel_find("kvm"))) {
3519                     error_report("Option not supported for this target");
3520                     exit(1);
3521                 }
3522                 xen_domid = atoi(optarg);
3523                 break;
3524             case QEMU_OPTION_xen_attach:
3525                 if (!(accel_find("xen"))) {
3526                     error_report("Option not supported for this target");
3527                     exit(1);
3528                 }
3529                 xen_mode = XEN_ATTACH;
3530                 break;
3531             case QEMU_OPTION_xen_domid_restrict:
3532                 if (!(accel_find("xen"))) {
3533                     error_report("Option not supported for this target");
3534                     exit(1);
3535                 }
3536                 xen_domid_restrict = true;
3537                 break;
3538             case QEMU_OPTION_trace:
3539                 trace_opt_parse(optarg);
3540                 break;
3541             case QEMU_OPTION_plugin:
3542                 qemu_plugin_opt_parse(optarg, &plugin_list);
3543                 break;
3544             case QEMU_OPTION_readconfig:
3545                 qemu_read_config_file(optarg, qemu_parse_config_group, &error_fatal);
3546                 break;
3547 #ifdef CONFIG_SPICE
3548             case QEMU_OPTION_spice:
3549                 opts = qemu_opts_parse_noisily(qemu_find_opts("spice"), optarg, false);
3550                 if (!opts) {
3551                     exit(1);
3552                 }
3553                 display_remote++;
3554                 break;
3555 #endif
3556             case QEMU_OPTION_qtest:
3557                 qtest_chrdev = optarg;
3558                 break;
3559             case QEMU_OPTION_qtest_log:
3560                 qtest_log = optarg;
3561                 break;
3562             case QEMU_OPTION_sandbox:
3563                 olist = qemu_find_opts("sandbox");
3564                 if (!olist) {
3565 #ifndef CONFIG_SECCOMP
3566                     error_report("-sandbox support is not enabled "
3567                                  "in this QEMU binary");
3568 #endif
3569                     exit(1);
3570                 }
3571 
3572                 opts = qemu_opts_parse_noisily(olist, optarg, true);
3573                 if (!opts) {
3574                     exit(1);
3575                 }
3576                 break;
3577             case QEMU_OPTION_add_fd:
3578 #ifndef _WIN32
3579                 opts = qemu_opts_parse_noisily(qemu_find_opts("add-fd"),
3580                                                optarg, false);
3581                 if (!opts) {
3582                     exit(1);
3583                 }
3584 #else
3585                 error_report("File descriptor passing is disabled on this "
3586                              "platform");
3587                 exit(1);
3588 #endif
3589                 break;
3590             case QEMU_OPTION_object:
3591                 object_option_parse(optarg);
3592                 break;
3593             case QEMU_OPTION_overcommit:
3594                 opts = qemu_opts_parse_noisily(qemu_find_opts("overcommit"),
3595                                                optarg, false);
3596                 if (!opts) {
3597                     exit(1);
3598                 }
3599                 enable_mlock = qemu_opt_get_bool(opts, "mem-lock", enable_mlock);
3600                 enable_cpu_pm = qemu_opt_get_bool(opts, "cpu-pm", enable_cpu_pm);
3601                 break;
3602             case QEMU_OPTION_compat:
3603                 {
3604                     CompatPolicy *opts_policy;
3605                     Visitor *v;
3606 
3607                     v = qobject_input_visitor_new_str(optarg, NULL,
3608                                                       &error_fatal);
3609 
3610                     visit_type_CompatPolicy(v, NULL, &opts_policy, &error_fatal);
3611                     QAPI_CLONE_MEMBERS(CompatPolicy, &compat_policy, opts_policy);
3612 
3613                     qapi_free_CompatPolicy(opts_policy);
3614                     visit_free(v);
3615                     break;
3616                 }
3617             case QEMU_OPTION_msg:
3618                 opts = qemu_opts_parse_noisily(qemu_find_opts("msg"), optarg,
3619                                                false);
3620                 if (!opts) {
3621                     exit(1);
3622                 }
3623                 configure_msg(opts);
3624                 break;
3625             case QEMU_OPTION_dump_vmstate:
3626                 if (vmstate_dump_file) {
3627                     error_report("only one '-dump-vmstate' "
3628                                  "option may be given");
3629                     exit(1);
3630                 }
3631                 vmstate_dump_file = fopen(optarg, "w");
3632                 if (vmstate_dump_file == NULL) {
3633                     error_report("open %s: %s", optarg, strerror(errno));
3634                     exit(1);
3635                 }
3636                 break;
3637             case QEMU_OPTION_enable_sync_profile:
3638                 qsp_enable();
3639                 break;
3640             case QEMU_OPTION_nouserconfig:
3641                 /* Nothing to be parsed here. Especially, do not error out below. */
3642                 break;
3643 #if defined(CONFIG_POSIX)
3644             case QEMU_OPTION_daemonize:
3645                 os_set_daemonize(true);
3646                 break;
3647             case QEMU_OPTION_run_with: {
3648                 const char *str;
3649                 opts = qemu_opts_parse_noisily(qemu_find_opts("run-with"),
3650                                                          optarg, false);
3651                 if (!opts) {
3652                     exit(1);
3653                 }
3654 #if defined(CONFIG_LINUX)
3655                 if (qemu_opt_get_bool(opts, "async-teardown", false)) {
3656                     init_async_teardown();
3657                 }
3658 #endif
3659                 str = qemu_opt_get(opts, "chroot");
3660                 if (str) {
3661                     os_set_chroot(str);
3662                 }
3663                 str = qemu_opt_get(opts, "user");
3664                 if (str) {
3665                     if (!os_set_runas(str)) {
3666                         error_report("User \"%s\" doesn't exist"
3667                                      " (and is not <uid>:<gid>)",
3668                                      optarg);
3669                         exit(1);
3670                     }
3671                 }
3672 
3673                 break;
3674             }
3675 #endif /* CONFIG_POSIX */
3676 
3677             default:
3678                 error_report("Option not supported in this build");
3679                 exit(1);
3680             }
3681         }
3682     }
3683     /*
3684      * Clear error location left behind by the loop.
3685      * Best done right after the loop.  Do not insert code here!
3686      */
3687     loc_set_none();
3688 
3689     qemu_validate_options(machine_opts_dict);
3690     qemu_process_sugar_options();
3691 
3692     /*
3693      * These options affect everything else and should be processed
3694      * before daemonizing.
3695      */
3696     qemu_process_early_options();
3697 
3698     qemu_process_help_options();
3699     qemu_maybe_daemonize(pid_file);
3700 
3701     /*
3702      * The trace backend must be initialized after daemonizing.
3703      * trace_init_backends() will call st_init(), which will create the
3704      * trace thread in the parent, and also register st_flush_trace_buffer()
3705      * in atexit(). This function will force the parent to wait for the
3706      * writeout thread to finish, which will not occur, and the parent
3707      * process will be left in the host.
3708      */
3709     if (!trace_init_backends()) {
3710         exit(1);
3711     }
3712     trace_init_file();
3713 
3714     qemu_init_main_loop(&error_fatal);
3715     cpu_timers_init();
3716 
3717     user_register_global_props();
3718     replay_configure(icount_opts);
3719 
3720     configure_rtc(qemu_find_opts_singleton("rtc"));
3721 
3722     /* Transfer QemuOpts options into machine options */
3723     parse_memory_options();
3724 
3725     qemu_create_machine(machine_opts_dict);
3726 
3727     /*
3728      * Load incoming CPR state before any devices are created, because it
3729      * contains file descriptors that are needed in device initialization code.
3730      */
3731     cpr_state_load(incoming_channels[MIGRATION_CHANNEL_TYPE_CPR], &error_fatal);
3732 
3733     suspend_mux_open();
3734 
3735     qemu_disable_default_devices();
3736     qemu_setup_display();
3737     qemu_create_default_devices();
3738     qemu_create_early_backends();
3739 
3740     qemu_apply_legacy_machine_options(machine_opts_dict);
3741     qemu_apply_machine_options(machine_opts_dict);
3742     qobject_unref(machine_opts_dict);
3743     phase_advance(PHASE_MACHINE_CREATED);
3744 
3745     /*
3746      * Note: uses machine properties such as kernel-irqchip, must run
3747      * after qemu_apply_machine_options.
3748      */
3749     configure_accelerators(argv[0]);
3750     phase_advance(PHASE_ACCEL_CREATED);
3751 
3752     /*
3753      * Beware, QOM objects created before this point miss global and
3754      * compat properties.
3755      *
3756      * Global properties get set up by qdev_prop_register_global(),
3757      * called from user_register_global_props(), and certain option
3758      * desugaring.  Also in CPU feature desugaring (buried in
3759      * parse_cpu_option()), which happens below this point, but may
3760      * only target the CPU type, which can only be created after
3761      * parse_cpu_option() returned the type.
3762      *
3763      * Machine compat properties: object_set_machine_compat_props().
3764      * Accelerator compat props: object_set_accelerator_compat_props(),
3765      * called from do_configure_accelerator().
3766      */
3767 
3768     machine_class = MACHINE_GET_CLASS(current_machine);
3769     if (!qtest_enabled() && machine_class->deprecation_reason) {
3770         warn_report("Machine type '%s' is deprecated: %s",
3771                      machine_class->name, machine_class->deprecation_reason);
3772     }
3773 
3774     /*
3775      * Create backends before creating migration objects, so that it can
3776      * check against compatibilities on the backend memories (e.g. postcopy
3777      * over memory-backend-file objects).
3778      */
3779     qemu_create_late_backends();
3780     phase_advance(PHASE_LATE_BACKENDS_CREATED);
3781 
3782     /*
3783      * Note: creates a QOM object, must run only after global and
3784      * compat properties have been set up.
3785      */
3786     migration_object_init();
3787 
3788     /* parse features once if machine provides default cpu_type */
3789     current_machine->cpu_type = machine_class_default_cpu_type(machine_class);
3790     if (cpu_option) {
3791         current_machine->cpu_type = parse_cpu_option(cpu_option);
3792     }
3793     /* NB: for machine none cpu_type could STILL be NULL here! */
3794 
3795     qemu_resolve_machine_memdev();
3796     parse_numa_opts(current_machine);
3797 
3798     if (vmstate_dump_file) {
3799         /* dump and exit */
3800         module_load_qom_all();
3801         dump_vmstate_json_to_file(vmstate_dump_file);
3802         exit(0);
3803     }
3804 
3805     if (!preconfig_requested) {
3806         qmp_x_exit_preconfig(&error_fatal);
3807     }
3808     qemu_init_displays();
3809     accel_setup_post(current_machine);
3810     os_setup_post();
3811     resume_mux_open();
3812 }
3813