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