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