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