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