package: update version (2.8.0.7)
[sdk/emulator/qemu.git] / vl.c
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 #include "qemu/osdep.h"
25 #include "qemu-version.h"
26 #include "qemu/cutils.h"
27 #include "qemu/help_option.h"
28 #include "qemu/uuid.h"
29
30 #ifdef CONFIG_SECCOMP
31 #include "sysemu/seccomp.h"
32 #endif
33
34 #if defined(CONFIG_VDE)
35 #include <libvdeplug.h>
36 #endif
37
38 #ifdef CONFIG_SDL
39 #if defined(__APPLE__) || defined(main)
40 #include <SDL.h>
41 #ifndef CONFIG_MARU
42 int qemu_main(int argc, char **argv, char **envp);
43 int main(int argc, char **argv)
44 {
45     return qemu_main(argc, argv, NULL);
46 }
47 #undef main
48 #define main qemu_main
49 #endif
50 #endif
51 #endif /* CONFIG_SDL */
52
53 #ifdef CONFIG_COCOA
54 #undef main
55 #define main qemu_main
56 #endif /* CONFIG_COCOA */
57
58 #ifdef CONFIG_MARU
59 #ifdef main
60 #undef main
61 #endif
62 int qemu_main(int argc, char **argv, char **envp);
63 #define main qemu_main
64 #endif
65
66 #include "qemu/error-report.h"
67 #include "qemu/sockets.h"
68 #include "hw/hw.h"
69 #include "hw/boards.h"
70 #include "sysemu/accel.h"
71 #include "hw/usb.h"
72 #include "hw/i386/pc.h"
73 #include "hw/isa/isa.h"
74 #include "hw/bt.h"
75 #include "sysemu/watchdog.h"
76 #include "hw/smbios/smbios.h"
77 #include "hw/xen/xen.h"
78 #include "hw/qdev.h"
79 #include "hw/loader.h"
80 #include "monitor/qdev.h"
81 #include "sysemu/bt.h"
82 #include "net/net.h"
83 #include "net/slirp.h"
84 #include "monitor/monitor.h"
85 #include "ui/console.h"
86 #include "ui/input.h"
87 #include "sysemu/sysemu.h"
88 #include "sysemu/numa.h"
89 #include "exec/gdbstub.h"
90 #include "qemu/timer.h"
91 #include "sysemu/char.h"
92 #include "qemu/bitmap.h"
93 #include "qemu/log.h"
94 #include "sysemu/blockdev.h"
95 #include "hw/block/block.h"
96 #include "migration/block.h"
97 #include "sysemu/tpm.h"
98 #include "sysemu/dma.h"
99 #include "audio/audio.h"
100 #include "migration/migration.h"
101 #include "sysemu/cpus.h"
102 #include "migration/colo.h"
103 #include "sysemu/kvm.h"
104 #include "sysemu/hax.h"
105 #include "qapi/qmp/qjson.h"
106 #include "qemu/option.h"
107 #include "qemu/config-file.h"
108 #include "qemu-options.h"
109 #include "qmp-commands.h"
110 #include "qemu/main-loop.h"
111 #ifdef CONFIG_VIRTFS
112 #include "fsdev/qemu-fsdev.h"
113 #endif
114 #include "sysemu/qtest.h"
115
116 #include "disas/disas.h"
117
118
119 #include "slirp/libslirp.h"
120
121 #include "trace.h"
122 #include "trace/control.h"
123 #include "qemu/queue.h"
124 #include "sysemu/arch_init.h"
125
126 #include "ui/qemu-spice.h"
127 #include "qapi/string-input-visitor.h"
128 #include "qapi/opts-visitor.h"
129 #include "qom/object_interfaces.h"
130 #include "qapi-event.h"
131 #include "exec/semihost.h"
132 #include "crypto/init.h"
133 #include "sysemu/replay.h"
134 #include "qapi/qmp/qerror.h"
135 #include "sysemu/iothread.h"
136
137 #ifdef CONFIG_MARU
138 #include "tizen/src/emulator.h"
139 #include "tizen/src/emul_state.h"
140 #include "tizen/src/ui/qt5.h"
141 #include "tizen/src/util/ui_operations.h"
142 #include "tizen/src/ecs/ecs.h"
143 #include "tizen/src/util/error_handler.h"
144 #include "tizen/src/util/exported_strings.h"
145
146 inline static bool is_maru_machine(MachineClass *mc) {
147    return g_str_has_prefix(mc->name, "maru");
148 }
149 #endif
150
151 #define MAX_VIRTIO_CONSOLES 1
152 #define MAX_SCLP_CONSOLES 1
153
154 static const char *data_dir[16];
155 static int data_dir_idx;
156 const char *bios_name = NULL;
157 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
158 int request_opengl = -1;
159 int display_opengl;
160 const char* keyboard_layout = NULL;
161 ram_addr_t ram_size;
162 const char *mem_path = NULL;
163 int mem_prealloc = 0; /* force preallocation of physical target memory */
164 bool enable_mlock = false;
165 int nb_nics;
166 NICInfo nd_table[MAX_NICS];
167 int autostart;
168 static int rtc_utc = 1;
169 static int rtc_date_offset = -1; /* -1 means no change */
170 QEMUClockType rtc_clock;
171 int vga_interface_type = VGA_NONE;
172 static int full_screen = 0;
173 static int no_frame = 0;
174 int no_quit = 0;
175 static bool grab_on_hover;
176 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
177 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
178 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
179 CharDriverState *sclp_hds[MAX_SCLP_CONSOLES];
180 int win2k_install_hack = 0;
181 int singlestep = 0;
182 int smp_cpus = 1;
183 int max_cpus = 1;
184 int smp_cores = 1;
185 int smp_threads = 1;
186 int acpi_enabled = 1;
187 int no_hpet = 0;
188 int fd_bootchk = 1;
189 static int no_reboot;
190 int no_shutdown = 0;
191 int cursor_hide = 1;
192 int graphic_rotate = 0;
193 const char *watchdog;
194 QEMUOptionRom option_rom[MAX_OPTION_ROMS];
195 int nb_option_roms;
196 int old_param = 0;
197 const char *qemu_name;
198 int alt_grab = 0;
199 int ctrl_grab = 0;
200 unsigned int nb_prom_envs = 0;
201 const char *prom_envs[MAX_PROM_ENVS];
202 int boot_menu;
203 bool boot_strict;
204 uint8_t *boot_splash_filedata;
205 size_t boot_splash_filedata_size;
206 uint8_t qemu_extra_params_fw[2];
207
208 int icount_align_option;
209
210 /* The bytes in qemu_uuid are in the order specified by RFC4122, _not_ in the
211  * little-endian "wire format" described in the SMBIOS 2.6 specification.
212  */
213 QemuUUID qemu_uuid;
214 bool qemu_uuid_set;
215
216 static NotifierList exit_notifiers =
217     NOTIFIER_LIST_INITIALIZER(exit_notifiers);
218
219 static NotifierList machine_init_done_notifiers =
220     NOTIFIER_LIST_INITIALIZER(machine_init_done_notifiers);
221
222 bool xen_allowed;
223 uint32_t xen_domid;
224 enum xen_mode xen_mode = XEN_EMULATE;
225
226 static int has_defaults = 1;
227 static int default_serial = 1;
228 static int default_parallel = 1;
229 static int default_virtcon = 1;
230 static int default_sclp = 1;
231 static int default_monitor = 1;
232 static int default_floppy = 1;
233 static int default_cdrom = 1;
234 static int default_sdcard = 1;
235 static int default_vga = 1;
236 static int default_net = 1;
237
238 static struct {
239     const char *driver;
240     int *flag;
241 } default_list[] = {
242     { .driver = "isa-serial",           .flag = &default_serial    },
243     { .driver = "isa-parallel",         .flag = &default_parallel  },
244     { .driver = "isa-fdc",              .flag = &default_floppy    },
245     { .driver = "floppy",               .flag = &default_floppy    },
246     { .driver = "ide-cd",               .flag = &default_cdrom     },
247     { .driver = "ide-hd",               .flag = &default_cdrom     },
248     { .driver = "ide-drive",            .flag = &default_cdrom     },
249     { .driver = "scsi-cd",              .flag = &default_cdrom     },
250     { .driver = "virtio-serial-pci",    .flag = &default_virtcon   },
251     { .driver = "virtio-serial",        .flag = &default_virtcon   },
252     { .driver = "VGA",                  .flag = &default_vga       },
253     { .driver = "isa-vga",              .flag = &default_vga       },
254     { .driver = "cirrus-vga",           .flag = &default_vga       },
255     { .driver = "isa-cirrus-vga",       .flag = &default_vga       },
256     { .driver = "vmware-svga",          .flag = &default_vga       },
257     { .driver = "qxl-vga",              .flag = &default_vga       },
258     { .driver = "virtio-vga",           .flag = &default_vga       },
259 };
260
261 static QemuOptsList qemu_rtc_opts = {
262     .name = "rtc",
263     .head = QTAILQ_HEAD_INITIALIZER(qemu_rtc_opts.head),
264     .desc = {
265         {
266             .name = "base",
267             .type = QEMU_OPT_STRING,
268         },{
269             .name = "clock",
270             .type = QEMU_OPT_STRING,
271         },{
272             .name = "driftfix",
273             .type = QEMU_OPT_STRING,
274         },
275         { /* end of list */ }
276     },
277 };
278
279 static QemuOptsList qemu_sandbox_opts = {
280     .name = "sandbox",
281     .implied_opt_name = "enable",
282     .head = QTAILQ_HEAD_INITIALIZER(qemu_sandbox_opts.head),
283     .desc = {
284         {
285             .name = "enable",
286             .type = QEMU_OPT_BOOL,
287         },
288         { /* end of list */ }
289     },
290 };
291
292 static QemuOptsList qemu_option_rom_opts = {
293     .name = "option-rom",
294     .implied_opt_name = "romfile",
295     .head = QTAILQ_HEAD_INITIALIZER(qemu_option_rom_opts.head),
296     .desc = {
297         {
298             .name = "bootindex",
299             .type = QEMU_OPT_NUMBER,
300         }, {
301             .name = "romfile",
302             .type = QEMU_OPT_STRING,
303         },
304         { /* end of list */ }
305     },
306 };
307
308 static QemuOptsList qemu_machine_opts = {
309     .name = "machine",
310     .implied_opt_name = "type",
311     .merge_lists = true,
312     .head = QTAILQ_HEAD_INITIALIZER(qemu_machine_opts.head),
313     .desc = {
314         /*
315          * no elements => accept any
316          * sanity checking will happen later
317          * when setting machine properties
318          */
319         { }
320     },
321 };
322
323 static QemuOptsList qemu_boot_opts = {
324     .name = "boot-opts",
325     .implied_opt_name = "order",
326     .merge_lists = true,
327     .head = QTAILQ_HEAD_INITIALIZER(qemu_boot_opts.head),
328     .desc = {
329         {
330             .name = "order",
331             .type = QEMU_OPT_STRING,
332         }, {
333             .name = "once",
334             .type = QEMU_OPT_STRING,
335         }, {
336             .name = "menu",
337             .type = QEMU_OPT_BOOL,
338         }, {
339             .name = "splash",
340             .type = QEMU_OPT_STRING,
341         }, {
342             .name = "splash-time",
343             .type = QEMU_OPT_STRING,
344         }, {
345             .name = "reboot-timeout",
346             .type = QEMU_OPT_STRING,
347         }, {
348             .name = "strict",
349             .type = QEMU_OPT_BOOL,
350         },
351         { /*End of list */ }
352     },
353 };
354
355 static QemuOptsList qemu_add_fd_opts = {
356     .name = "add-fd",
357     .head = QTAILQ_HEAD_INITIALIZER(qemu_add_fd_opts.head),
358     .desc = {
359         {
360             .name = "fd",
361             .type = QEMU_OPT_NUMBER,
362             .help = "file descriptor of which a duplicate is added to fd set",
363         },{
364             .name = "set",
365             .type = QEMU_OPT_NUMBER,
366             .help = "ID of the fd set to add fd to",
367         },{
368             .name = "opaque",
369             .type = QEMU_OPT_STRING,
370             .help = "free-form string used to describe fd",
371         },
372         { /* end of list */ }
373     },
374 };
375
376 static QemuOptsList qemu_object_opts = {
377     .name = "object",
378     .implied_opt_name = "qom-type",
379     .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
380     .desc = {
381         { }
382     },
383 };
384
385 static QemuOptsList qemu_tpmdev_opts = {
386     .name = "tpmdev",
387     .implied_opt_name = "type",
388     .head = QTAILQ_HEAD_INITIALIZER(qemu_tpmdev_opts.head),
389     .desc = {
390         /* options are defined in the TPM backends */
391         { /* end of list */ }
392     },
393 };
394
395 static QemuOptsList qemu_realtime_opts = {
396     .name = "realtime",
397     .head = QTAILQ_HEAD_INITIALIZER(qemu_realtime_opts.head),
398     .desc = {
399         {
400             .name = "mlock",
401             .type = QEMU_OPT_BOOL,
402         },
403         { /* end of list */ }
404     },
405 };
406
407 static QemuOptsList qemu_msg_opts = {
408     .name = "msg",
409     .head = QTAILQ_HEAD_INITIALIZER(qemu_msg_opts.head),
410     .desc = {
411         {
412             .name = "timestamp",
413             .type = QEMU_OPT_BOOL,
414         },
415         { /* end of list */ }
416     },
417 };
418
419 static QemuOptsList qemu_name_opts = {
420     .name = "name",
421     .implied_opt_name = "guest",
422     .merge_lists = true,
423     .head = QTAILQ_HEAD_INITIALIZER(qemu_name_opts.head),
424     .desc = {
425         {
426             .name = "guest",
427             .type = QEMU_OPT_STRING,
428             .help = "Sets the name of the guest.\n"
429                     "This name will be displayed in the SDL window caption.\n"
430                     "The name will also be used for the VNC server",
431         }, {
432             .name = "process",
433             .type = QEMU_OPT_STRING,
434             .help = "Sets the name of the QEMU process, as shown in top etc",
435         }, {
436             .name = "debug-threads",
437             .type = QEMU_OPT_BOOL,
438             .help = "When enabled, name the individual threads; defaults off.\n"
439                     "NOTE: The thread names are for debugging and not a\n"
440                     "stable API.",
441         },
442         { /* End of list */ }
443     },
444 };
445
446 static QemuOptsList qemu_mem_opts = {
447     .name = "memory",
448     .implied_opt_name = "size",
449     .head = QTAILQ_HEAD_INITIALIZER(qemu_mem_opts.head),
450     .merge_lists = true,
451     .desc = {
452         {
453             .name = "size",
454             .type = QEMU_OPT_SIZE,
455         },
456         {
457             .name = "slots",
458             .type = QEMU_OPT_NUMBER,
459         },
460         {
461             .name = "maxmem",
462             .type = QEMU_OPT_SIZE,
463         },
464         { /* end of list */ }
465     },
466 };
467
468 static QemuOptsList qemu_icount_opts = {
469     .name = "icount",
470     .implied_opt_name = "shift",
471     .merge_lists = true,
472     .head = QTAILQ_HEAD_INITIALIZER(qemu_icount_opts.head),
473     .desc = {
474         {
475             .name = "shift",
476             .type = QEMU_OPT_STRING,
477         }, {
478             .name = "align",
479             .type = QEMU_OPT_BOOL,
480         }, {
481             .name = "sleep",
482             .type = QEMU_OPT_BOOL,
483         }, {
484             .name = "rr",
485             .type = QEMU_OPT_STRING,
486         }, {
487             .name = "rrfile",
488             .type = QEMU_OPT_STRING,
489         },
490         { /* end of list */ }
491     },
492 };
493
494 static QemuOptsList qemu_semihosting_config_opts = {
495     .name = "semihosting-config",
496     .implied_opt_name = "enable",
497     .head = QTAILQ_HEAD_INITIALIZER(qemu_semihosting_config_opts.head),
498     .desc = {
499         {
500             .name = "enable",
501             .type = QEMU_OPT_BOOL,
502         }, {
503             .name = "target",
504             .type = QEMU_OPT_STRING,
505         }, {
506             .name = "arg",
507             .type = QEMU_OPT_STRING,
508         },
509         { /* end of list */ }
510     },
511 };
512
513 static QemuOptsList qemu_fw_cfg_opts = {
514     .name = "fw_cfg",
515     .implied_opt_name = "name",
516     .head = QTAILQ_HEAD_INITIALIZER(qemu_fw_cfg_opts.head),
517     .desc = {
518         {
519             .name = "name",
520             .type = QEMU_OPT_STRING,
521             .help = "Sets the fw_cfg name of the blob to be inserted",
522         }, {
523             .name = "file",
524             .type = QEMU_OPT_STRING,
525             .help = "Sets the name of the file from which\n"
526                     "the fw_cfg blob will be loaded",
527         }, {
528             .name = "string",
529             .type = QEMU_OPT_STRING,
530             .help = "Sets content of the blob to be inserted from a string",
531         },
532         { /* end of list */ }
533     },
534 };
535
536 #ifdef CONFIG_LIBISCSI
537 static QemuOptsList qemu_iscsi_opts = {
538     .name = "iscsi",
539     .head = QTAILQ_HEAD_INITIALIZER(qemu_iscsi_opts.head),
540     .desc = {
541         {
542             .name = "user",
543             .type = QEMU_OPT_STRING,
544             .help = "username for CHAP authentication to target",
545         },{
546             .name = "password",
547             .type = QEMU_OPT_STRING,
548             .help = "password for CHAP authentication to target",
549         },{
550             .name = "password-secret",
551             .type = QEMU_OPT_STRING,
552             .help = "ID of the secret providing password for CHAP "
553                     "authentication to target",
554         },{
555             .name = "header-digest",
556             .type = QEMU_OPT_STRING,
557             .help = "HeaderDigest setting. "
558                     "{CRC32C|CRC32C-NONE|NONE-CRC32C|NONE}",
559         },{
560             .name = "initiator-name",
561             .type = QEMU_OPT_STRING,
562             .help = "Initiator iqn name to use when connecting",
563         },{
564             .name = "timeout",
565             .type = QEMU_OPT_NUMBER,
566             .help = "Request timeout in seconds (default 0 = no timeout)",
567         },
568         { /* end of list */ }
569     },
570 };
571 #endif
572
573 /**
574  * Get machine options
575  *
576  * Returns: machine options (never null).
577  */
578 QemuOpts *qemu_get_machine_opts(void)
579 {
580     return qemu_find_opts_singleton("machine");
581 }
582
583 const char *qemu_get_vm_name(void)
584 {
585     return qemu_name;
586 }
587
588 static void res_free(void)
589 {
590     g_free(boot_splash_filedata);
591     boot_splash_filedata = NULL;
592 }
593
594 static int default_driver_check(void *opaque, QemuOpts *opts, Error **errp)
595 {
596     const char *driver = qemu_opt_get(opts, "driver");
597     int i;
598
599     if (!driver)
600         return 0;
601     for (i = 0; i < ARRAY_SIZE(default_list); i++) {
602         if (strcmp(default_list[i].driver, driver) != 0)
603             continue;
604         *(default_list[i].flag) = 0;
605     }
606     return 0;
607 }
608
609 /***********************************************************/
610 /* QEMU state */
611
612 static RunState current_run_state = RUN_STATE_PRELAUNCH;
613
614 /* We use RUN_STATE__MAX but any invalid value will do */
615 static RunState vmstop_requested = RUN_STATE__MAX;
616 static QemuMutex vmstop_lock;
617
618 typedef struct {
619     RunState from;
620     RunState to;
621 } RunStateTransition;
622
623 static const RunStateTransition runstate_transitions_def[] = {
624     /*     from      ->     to      */
625     { RUN_STATE_DEBUG, RUN_STATE_RUNNING },
626     { RUN_STATE_DEBUG, RUN_STATE_FINISH_MIGRATE },
627     { RUN_STATE_DEBUG, RUN_STATE_PRELAUNCH },
628
629     { RUN_STATE_INMIGRATE, RUN_STATE_INTERNAL_ERROR },
630     { RUN_STATE_INMIGRATE, RUN_STATE_IO_ERROR },
631     { RUN_STATE_INMIGRATE, RUN_STATE_PAUSED },
632     { RUN_STATE_INMIGRATE, RUN_STATE_RUNNING },
633     { RUN_STATE_INMIGRATE, RUN_STATE_SHUTDOWN },
634     { RUN_STATE_INMIGRATE, RUN_STATE_SUSPENDED },
635     { RUN_STATE_INMIGRATE, RUN_STATE_WATCHDOG },
636     { RUN_STATE_INMIGRATE, RUN_STATE_GUEST_PANICKED },
637     { RUN_STATE_INMIGRATE, RUN_STATE_FINISH_MIGRATE },
638     { RUN_STATE_INMIGRATE, RUN_STATE_PRELAUNCH },
639     { RUN_STATE_INMIGRATE, RUN_STATE_POSTMIGRATE },
640     { RUN_STATE_INMIGRATE, RUN_STATE_COLO },
641
642     { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PAUSED },
643     { RUN_STATE_INTERNAL_ERROR, RUN_STATE_FINISH_MIGRATE },
644     { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PRELAUNCH },
645
646     { RUN_STATE_IO_ERROR, RUN_STATE_RUNNING },
647     { RUN_STATE_IO_ERROR, RUN_STATE_FINISH_MIGRATE },
648     { RUN_STATE_IO_ERROR, RUN_STATE_PRELAUNCH },
649
650     { RUN_STATE_PAUSED, RUN_STATE_RUNNING },
651     { RUN_STATE_PAUSED, RUN_STATE_FINISH_MIGRATE },
652     { RUN_STATE_PAUSED, RUN_STATE_PRELAUNCH },
653     { RUN_STATE_PAUSED, RUN_STATE_COLO},
654
655     { RUN_STATE_POSTMIGRATE, RUN_STATE_RUNNING },
656     { RUN_STATE_POSTMIGRATE, RUN_STATE_FINISH_MIGRATE },
657     { RUN_STATE_POSTMIGRATE, RUN_STATE_PRELAUNCH },
658
659     { RUN_STATE_PRELAUNCH, RUN_STATE_RUNNING },
660     { RUN_STATE_PRELAUNCH, RUN_STATE_FINISH_MIGRATE },
661     { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
662
663     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_RUNNING },
664     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_POSTMIGRATE },
665     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PRELAUNCH },
666     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_COLO},
667
668     { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
669     { RUN_STATE_RESTORE_VM, RUN_STATE_PRELAUNCH },
670
671     { RUN_STATE_COLO, RUN_STATE_RUNNING },
672
673     { RUN_STATE_RUNNING, RUN_STATE_DEBUG },
674     { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR },
675     { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR },
676     { RUN_STATE_RUNNING, RUN_STATE_PAUSED },
677     { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE },
678     { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM },
679     { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM },
680     { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
681     { RUN_STATE_RUNNING, RUN_STATE_WATCHDOG },
682     { RUN_STATE_RUNNING, RUN_STATE_GUEST_PANICKED },
683     { RUN_STATE_RUNNING, RUN_STATE_COLO},
684
685     { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
686
687     { RUN_STATE_SHUTDOWN, RUN_STATE_PAUSED },
688     { RUN_STATE_SHUTDOWN, RUN_STATE_FINISH_MIGRATE },
689     { RUN_STATE_SHUTDOWN, RUN_STATE_PRELAUNCH },
690
691     { RUN_STATE_DEBUG, RUN_STATE_SUSPENDED },
692     { RUN_STATE_RUNNING, RUN_STATE_SUSPENDED },
693     { RUN_STATE_SUSPENDED, RUN_STATE_RUNNING },
694     { RUN_STATE_SUSPENDED, RUN_STATE_FINISH_MIGRATE },
695     { RUN_STATE_SUSPENDED, RUN_STATE_PRELAUNCH },
696     { RUN_STATE_SUSPENDED, RUN_STATE_COLO},
697
698     { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING },
699     { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE },
700     { RUN_STATE_WATCHDOG, RUN_STATE_PRELAUNCH },
701     { RUN_STATE_WATCHDOG, RUN_STATE_COLO},
702
703     { RUN_STATE_GUEST_PANICKED, RUN_STATE_RUNNING },
704     { RUN_STATE_GUEST_PANICKED, RUN_STATE_FINISH_MIGRATE },
705     { RUN_STATE_GUEST_PANICKED, RUN_STATE_PRELAUNCH },
706
707     { RUN_STATE__MAX, RUN_STATE__MAX },
708 };
709
710 static bool runstate_valid_transitions[RUN_STATE__MAX][RUN_STATE__MAX];
711
712 bool runstate_check(RunState state)
713 {
714     return current_run_state == state;
715 }
716
717 bool runstate_store(char *str, size_t size)
718 {
719     const char *state = RunState_lookup[current_run_state];
720     size_t len = strlen(state) + 1;
721
722     if (len > size) {
723         return false;
724     }
725     memcpy(str, state, len);
726     return true;
727 }
728
729 static void runstate_init(void)
730 {
731     const RunStateTransition *p;
732
733     memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
734     for (p = &runstate_transitions_def[0]; p->from != RUN_STATE__MAX; p++) {
735         runstate_valid_transitions[p->from][p->to] = true;
736     }
737
738     qemu_mutex_init(&vmstop_lock);
739 }
740
741 /* This function will abort() on invalid state transitions */
742 void runstate_set(RunState new_state)
743 {
744     assert(new_state < RUN_STATE__MAX);
745
746     if (current_run_state == new_state) {
747         return;
748     }
749
750     if (!runstate_valid_transitions[current_run_state][new_state]) {
751         error_report("invalid runstate transition: '%s' -> '%s'",
752                      RunState_lookup[current_run_state],
753                      RunState_lookup[new_state]);
754         abort();
755     }
756     trace_runstate_set(new_state);
757     current_run_state = new_state;
758 }
759
760 int runstate_is_running(void)
761 {
762     return runstate_check(RUN_STATE_RUNNING);
763 }
764
765 bool runstate_needs_reset(void)
766 {
767     return runstate_check(RUN_STATE_INTERNAL_ERROR) ||
768         runstate_check(RUN_STATE_SHUTDOWN);
769 }
770
771 StatusInfo *qmp_query_status(Error **errp)
772 {
773     StatusInfo *info = g_malloc0(sizeof(*info));
774
775     info->running = runstate_is_running();
776     info->singlestep = singlestep;
777     info->status = current_run_state;
778
779     return info;
780 }
781
782 static bool qemu_vmstop_requested(RunState *r)
783 {
784     qemu_mutex_lock(&vmstop_lock);
785     *r = vmstop_requested;
786     vmstop_requested = RUN_STATE__MAX;
787     qemu_mutex_unlock(&vmstop_lock);
788     return *r < RUN_STATE__MAX;
789 }
790
791 void qemu_system_vmstop_request_prepare(void)
792 {
793     qemu_mutex_lock(&vmstop_lock);
794 }
795
796 void qemu_system_vmstop_request(RunState state)
797 {
798     vmstop_requested = state;
799     qemu_mutex_unlock(&vmstop_lock);
800     qemu_notify_event();
801 }
802
803 void vm_start(void)
804 {
805     RunState requested;
806
807     qemu_vmstop_requested(&requested);
808     if (runstate_is_running() && requested == RUN_STATE__MAX) {
809         return;
810     }
811
812     /* Ensure that a STOP/RESUME pair of events is emitted if a
813      * vmstop request was pending.  The BLOCK_IO_ERROR event, for
814      * example, according to documentation is always followed by
815      * the STOP event.
816      */
817     if (runstate_is_running()) {
818         qapi_event_send_stop(&error_abort);
819     } else {
820         replay_enable_events();
821         cpu_enable_ticks();
822         runstate_set(RUN_STATE_RUNNING);
823         vm_state_notify(1, RUN_STATE_RUNNING);
824         resume_all_vcpus();
825     }
826
827     qapi_event_send_resume(&error_abort);
828 }
829
830
831 /***********************************************************/
832 /* real time host monotonic timer */
833
834 static time_t qemu_time(void)
835 {
836     return qemu_clock_get_ms(QEMU_CLOCK_HOST) / 1000;
837 }
838
839 /***********************************************************/
840 /* host time/date access */
841 void qemu_get_timedate(struct tm *tm, int offset)
842 {
843     time_t ti = qemu_time();
844
845     ti += offset;
846     if (rtc_date_offset == -1) {
847         if (rtc_utc)
848             gmtime_r(&ti, tm);
849         else
850             localtime_r(&ti, tm);
851     } else {
852         ti -= rtc_date_offset;
853         gmtime_r(&ti, tm);
854     }
855 }
856
857 int qemu_timedate_diff(struct tm *tm)
858 {
859     time_t seconds;
860
861     if (rtc_date_offset == -1)
862         if (rtc_utc)
863             seconds = mktimegm(tm);
864         else {
865             struct tm tmp = *tm;
866             tmp.tm_isdst = -1; /* use timezone to figure it out */
867             seconds = mktime(&tmp);
868         }
869     else
870         seconds = mktimegm(tm) + rtc_date_offset;
871
872     return seconds - qemu_time();
873 }
874
875 static void configure_rtc_date_offset(const char *startdate, int legacy)
876 {
877     time_t rtc_start_date;
878     struct tm tm;
879
880     if (!strcmp(startdate, "now") && legacy) {
881         rtc_date_offset = -1;
882     } else {
883         if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
884                    &tm.tm_year,
885                    &tm.tm_mon,
886                    &tm.tm_mday,
887                    &tm.tm_hour,
888                    &tm.tm_min,
889                    &tm.tm_sec) == 6) {
890             /* OK */
891         } else if (sscanf(startdate, "%d-%d-%d",
892                           &tm.tm_year,
893                           &tm.tm_mon,
894                           &tm.tm_mday) == 3) {
895             tm.tm_hour = 0;
896             tm.tm_min = 0;
897             tm.tm_sec = 0;
898         } else {
899             goto date_fail;
900         }
901         tm.tm_year -= 1900;
902         tm.tm_mon--;
903         rtc_start_date = mktimegm(&tm);
904         if (rtc_start_date == -1) {
905         date_fail:
906             error_report("invalid date format");
907             error_printf("valid formats: "
908                          "'2006-06-17T16:01:21' or '2006-06-17'\n");
909             exit(1);
910         }
911         rtc_date_offset = qemu_time() - rtc_start_date;
912     }
913 }
914
915 static void configure_rtc(QemuOpts *opts)
916 {
917     const char *value;
918
919     value = qemu_opt_get(opts, "base");
920     if (value) {
921         if (!strcmp(value, "utc")) {
922             rtc_utc = 1;
923         } else if (!strcmp(value, "localtime")) {
924             Error *blocker = NULL;
925             rtc_utc = 0;
926             error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED,
927                       "-rtc base=localtime");
928             replay_add_blocker(blocker);
929         } else {
930             configure_rtc_date_offset(value, 0);
931         }
932     }
933     value = qemu_opt_get(opts, "clock");
934     if (value) {
935         if (!strcmp(value, "host")) {
936             rtc_clock = QEMU_CLOCK_HOST;
937         } else if (!strcmp(value, "rt")) {
938             rtc_clock = QEMU_CLOCK_REALTIME;
939         } else if (!strcmp(value, "vm")) {
940             rtc_clock = QEMU_CLOCK_VIRTUAL;
941         } else {
942             error_report("invalid option value '%s'", value);
943             exit(1);
944         }
945     }
946     value = qemu_opt_get(opts, "driftfix");
947     if (value) {
948         if (!strcmp(value, "slew")) {
949             static GlobalProperty slew_lost_ticks = {
950                 .driver   = "mc146818rtc",
951                 .property = "lost_tick_policy",
952                 .value    = "slew",
953             };
954
955             qdev_prop_register_global(&slew_lost_ticks);
956         } else if (!strcmp(value, "none")) {
957             /* discard is default */
958         } else {
959             error_report("invalid option value '%s'", value);
960             exit(1);
961         }
962     }
963 }
964
965 /***********************************************************/
966 /* Bluetooth support */
967 static int nb_hcis;
968 static int cur_hci;
969 static struct HCIInfo *hci_table[MAX_NICS];
970
971 struct HCIInfo *qemu_next_hci(void)
972 {
973     if (cur_hci == nb_hcis)
974         return &null_hci;
975
976     return hci_table[cur_hci++];
977 }
978
979 static int bt_hci_parse(const char *str)
980 {
981     struct HCIInfo *hci;
982     bdaddr_t bdaddr;
983
984     if (nb_hcis >= MAX_NICS) {
985         error_report("too many bluetooth HCIs (max %i)", MAX_NICS);
986         return -1;
987     }
988
989     hci = hci_init(str);
990     if (!hci)
991         return -1;
992
993     bdaddr.b[0] = 0x52;
994     bdaddr.b[1] = 0x54;
995     bdaddr.b[2] = 0x00;
996     bdaddr.b[3] = 0x12;
997     bdaddr.b[4] = 0x34;
998     bdaddr.b[5] = 0x56 + nb_hcis;
999     hci->bdaddr_set(hci, bdaddr.b);
1000
1001     hci_table[nb_hcis++] = hci;
1002
1003     return 0;
1004 }
1005
1006 static void bt_vhci_add(int vlan_id)
1007 {
1008     struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1009
1010     if (!vlan->slave)
1011         error_report("warning: adding a VHCI to an empty scatternet %i",
1012                      vlan_id);
1013
1014     bt_vhci_init(bt_new_hci(vlan));
1015 }
1016
1017 static struct bt_device_s *bt_device_add(const char *opt)
1018 {
1019     struct bt_scatternet_s *vlan;
1020     int vlan_id = 0;
1021     char *endp = strstr(opt, ",vlan=");
1022     int len = (endp ? endp - opt : strlen(opt)) + 1;
1023     char devname[10];
1024
1025     pstrcpy(devname, MIN(sizeof(devname), len), opt);
1026
1027     if (endp) {
1028         vlan_id = strtol(endp + 6, &endp, 0);
1029         if (*endp) {
1030             error_report("unrecognised bluetooth vlan Id");
1031             return 0;
1032         }
1033     }
1034
1035     vlan = qemu_find_bt_vlan(vlan_id);
1036
1037     if (!vlan->slave)
1038         error_report("warning: adding a slave device to an empty scatternet %i",
1039                      vlan_id);
1040
1041     if (!strcmp(devname, "keyboard"))
1042         return bt_keyboard_init(vlan);
1043
1044     error_report("unsupported bluetooth device '%s'", devname);
1045     return 0;
1046 }
1047
1048 static int bt_parse(const char *opt)
1049 {
1050     const char *endp, *p;
1051     int vlan;
1052
1053     if (strstart(opt, "hci", &endp)) {
1054         if (!*endp || *endp == ',') {
1055             if (*endp)
1056                 if (!strstart(endp, ",vlan=", 0))
1057                     opt = endp + 1;
1058
1059             return bt_hci_parse(opt);
1060        }
1061     } else if (strstart(opt, "vhci", &endp)) {
1062         if (!*endp || *endp == ',') {
1063             if (*endp) {
1064                 if (strstart(endp, ",vlan=", &p)) {
1065                     vlan = strtol(p, (char **) &endp, 0);
1066                     if (*endp) {
1067                         error_report("bad scatternet '%s'", p);
1068                         return 1;
1069                     }
1070                 } else {
1071                     error_report("bad parameter '%s'", endp + 1);
1072                     return 1;
1073                 }
1074             } else
1075                 vlan = 0;
1076
1077             bt_vhci_add(vlan);
1078             return 0;
1079         }
1080     } else if (strstart(opt, "device:", &endp))
1081         return !bt_device_add(endp);
1082
1083     error_report("bad bluetooth parameter '%s'", opt);
1084     return 1;
1085 }
1086
1087 static int parse_sandbox(void *opaque, QemuOpts *opts, Error **errp)
1088 {
1089     /* FIXME: change this to true for 1.3 */
1090     if (qemu_opt_get_bool(opts, "enable", false)) {
1091 #ifdef CONFIG_SECCOMP
1092         if (seccomp_start() < 0) {
1093             error_report("failed to install seccomp syscall filter "
1094                          "in the kernel");
1095             return -1;
1096         }
1097 #else
1098         error_report("seccomp support is disabled");
1099         return -1;
1100 #endif
1101     }
1102
1103     return 0;
1104 }
1105
1106 static int parse_name(void *opaque, QemuOpts *opts, Error **errp)
1107 {
1108     const char *proc_name;
1109
1110     if (qemu_opt_get(opts, "debug-threads")) {
1111         qemu_thread_naming(qemu_opt_get_bool(opts, "debug-threads", false));
1112     }
1113     qemu_name = qemu_opt_get(opts, "guest");
1114
1115     proc_name = qemu_opt_get(opts, "process");
1116     if (proc_name) {
1117         os_set_proc_name(proc_name);
1118     }
1119
1120     return 0;
1121 }
1122
1123 bool defaults_enabled(void)
1124 {
1125     return has_defaults;
1126 }
1127
1128 #ifndef _WIN32
1129 static int parse_add_fd(void *opaque, QemuOpts *opts, Error **errp)
1130 {
1131     int fd, dupfd, flags;
1132     int64_t fdset_id;
1133     const char *fd_opaque = NULL;
1134     AddfdInfo *fdinfo;
1135
1136     fd = qemu_opt_get_number(opts, "fd", -1);
1137     fdset_id = qemu_opt_get_number(opts, "set", -1);
1138     fd_opaque = qemu_opt_get(opts, "opaque");
1139
1140     if (fd < 0) {
1141         error_report("fd option is required and must be non-negative");
1142         return -1;
1143     }
1144
1145     if (fd <= STDERR_FILENO) {
1146         error_report("fd cannot be a standard I/O stream");
1147         return -1;
1148     }
1149
1150     /*
1151      * All fds inherited across exec() necessarily have FD_CLOEXEC
1152      * clear, while qemu sets FD_CLOEXEC on all other fds used internally.
1153      */
1154     flags = fcntl(fd, F_GETFD);
1155     if (flags == -1 || (flags & FD_CLOEXEC)) {
1156         error_report("fd is not valid or already in use");
1157         return -1;
1158     }
1159
1160     if (fdset_id < 0) {
1161         error_report("set option is required and must be non-negative");
1162         return -1;
1163     }
1164
1165 #ifdef F_DUPFD_CLOEXEC
1166     dupfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
1167 #else
1168     dupfd = dup(fd);
1169     if (dupfd != -1) {
1170         qemu_set_cloexec(dupfd);
1171     }
1172 #endif
1173     if (dupfd == -1) {
1174         error_report("error duplicating fd: %s", strerror(errno));
1175         return -1;
1176     }
1177
1178     /* add the duplicate fd, and optionally the opaque string, to the fd set */
1179     fdinfo = monitor_fdset_add_fd(dupfd, true, fdset_id, !!fd_opaque, fd_opaque,
1180                                   &error_abort);
1181     g_free(fdinfo);
1182
1183     return 0;
1184 }
1185
1186 static int cleanup_add_fd(void *opaque, QemuOpts *opts, Error **errp)
1187 {
1188     int fd;
1189
1190     fd = qemu_opt_get_number(opts, "fd", -1);
1191     close(fd);
1192
1193     return 0;
1194 }
1195 #endif
1196
1197 /***********************************************************/
1198 /* QEMU Block devices */
1199
1200 #define HD_OPTS "media=disk"
1201 #define CDROM_OPTS "media=cdrom"
1202 #define FD_OPTS ""
1203 #define PFLASH_OPTS ""
1204 #define MTD_OPTS ""
1205 #define SD_OPTS ""
1206
1207 static int drive_init_func(void *opaque, QemuOpts *opts, Error **errp)
1208 {
1209     BlockInterfaceType *block_default_type = opaque;
1210
1211     return drive_new(opts, *block_default_type) == NULL;
1212 }
1213
1214 static int drive_enable_snapshot(void *opaque, QemuOpts *opts, Error **errp)
1215 {
1216     if (qemu_opt_get(opts, "snapshot") == NULL) {
1217         qemu_opt_set(opts, "snapshot", "on", &error_abort);
1218     }
1219     return 0;
1220 }
1221
1222 static void default_drive(int enable, int snapshot, BlockInterfaceType type,
1223                           int index, const char *optstr)
1224 {
1225     QemuOpts *opts;
1226     DriveInfo *dinfo;
1227
1228     if (!enable || drive_get_by_index(type, index)) {
1229         return;
1230     }
1231
1232     opts = drive_add(type, index, NULL, optstr);
1233     if (snapshot) {
1234         drive_enable_snapshot(NULL, opts, NULL);
1235     }
1236
1237     dinfo = drive_new(opts, type);
1238     if (!dinfo) {
1239         exit(1);
1240     }
1241     dinfo->is_default = true;
1242
1243 }
1244
1245 static QemuOptsList qemu_smp_opts = {
1246     .name = "smp-opts",
1247     .implied_opt_name = "cpus",
1248     .merge_lists = true,
1249     .head = QTAILQ_HEAD_INITIALIZER(qemu_smp_opts.head),
1250     .desc = {
1251         {
1252             .name = "cpus",
1253             .type = QEMU_OPT_NUMBER,
1254         }, {
1255             .name = "sockets",
1256             .type = QEMU_OPT_NUMBER,
1257         }, {
1258             .name = "cores",
1259             .type = QEMU_OPT_NUMBER,
1260         }, {
1261             .name = "threads",
1262             .type = QEMU_OPT_NUMBER,
1263         }, {
1264             .name = "maxcpus",
1265             .type = QEMU_OPT_NUMBER,
1266         },
1267         { /*End of list */ }
1268     },
1269 };
1270
1271 static void smp_parse(QemuOpts *opts)
1272 {
1273     if (opts) {
1274         unsigned cpus    = qemu_opt_get_number(opts, "cpus", 0);
1275         unsigned sockets = qemu_opt_get_number(opts, "sockets", 0);
1276         unsigned cores   = qemu_opt_get_number(opts, "cores", 0);
1277         unsigned threads = qemu_opt_get_number(opts, "threads", 0);
1278
1279         /* compute missing values, prefer sockets over cores over threads */
1280         if (cpus == 0 || sockets == 0) {
1281             sockets = sockets > 0 ? sockets : 1;
1282             cores = cores > 0 ? cores : 1;
1283             threads = threads > 0 ? threads : 1;
1284             if (cpus == 0) {
1285                 cpus = cores * threads * sockets;
1286             }
1287         } else if (cores == 0) {
1288             threads = threads > 0 ? threads : 1;
1289             cores = cpus / (sockets * threads);
1290             cores = cores > 0 ? cores : 1;
1291         } else if (threads == 0) {
1292             threads = cpus / (cores * sockets);
1293             threads = threads > 0 ? threads : 1;
1294         } else if (sockets * cores * threads < cpus) {
1295             error_report("cpu topology: "
1296                          "sockets (%u) * cores (%u) * threads (%u) < "
1297                          "smp_cpus (%u)",
1298                          sockets, cores, threads, cpus);
1299             exit(1);
1300         }
1301
1302         max_cpus = qemu_opt_get_number(opts, "maxcpus", cpus);
1303
1304         if (max_cpus > MAX_CPUMASK_BITS) {
1305             error_report("unsupported number of maxcpus");
1306             exit(1);
1307         }
1308
1309         if (max_cpus < cpus) {
1310             error_report("maxcpus must be equal to or greater than smp");
1311             exit(1);
1312         }
1313
1314         if (sockets * cores * threads > max_cpus) {
1315             error_report("cpu topology: "
1316                          "sockets (%u) * cores (%u) * threads (%u) > "
1317                          "maxcpus (%u)",
1318                          sockets, cores, threads, max_cpus);
1319             exit(1);
1320         }
1321
1322         smp_cpus = cpus;
1323         smp_cores = cores;
1324         smp_threads = threads;
1325     }
1326
1327     if (smp_cpus > 1) {
1328         Error *blocker = NULL;
1329         error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED, "smp");
1330         replay_add_blocker(blocker);
1331     }
1332 }
1333
1334 static void realtime_init(void)
1335 {
1336     if (enable_mlock) {
1337         if (os_mlock() < 0) {
1338             error_report("locking memory failed");
1339             exit(1);
1340         }
1341     }
1342 }
1343
1344
1345 static void configure_msg(QemuOpts *opts)
1346 {
1347     enable_timestamp_msg = qemu_opt_get_bool(opts, "timestamp", true);
1348 }
1349
1350 /***********************************************************/
1351 /* Semihosting */
1352
1353 typedef struct SemihostingConfig {
1354     bool enabled;
1355     SemihostingTarget target;
1356     const char **argv;
1357     int argc;
1358     const char *cmdline; /* concatenated argv */
1359 } SemihostingConfig;
1360
1361 static SemihostingConfig semihosting;
1362
1363 bool semihosting_enabled(void)
1364 {
1365     return semihosting.enabled;
1366 }
1367
1368 SemihostingTarget semihosting_get_target(void)
1369 {
1370     return semihosting.target;
1371 }
1372
1373 const char *semihosting_get_arg(int i)
1374 {
1375     if (i >= semihosting.argc) {
1376         return NULL;
1377     }
1378     return semihosting.argv[i];
1379 }
1380
1381 int semihosting_get_argc(void)
1382 {
1383     return semihosting.argc;
1384 }
1385
1386 const char *semihosting_get_cmdline(void)
1387 {
1388     if (semihosting.cmdline == NULL && semihosting.argc > 0) {
1389         semihosting.cmdline = g_strjoinv(" ", (gchar **)semihosting.argv);
1390     }
1391     return semihosting.cmdline;
1392 }
1393
1394 static int add_semihosting_arg(void *opaque,
1395                                const char *name, const char *val,
1396                                Error **errp)
1397 {
1398     SemihostingConfig *s = opaque;
1399     if (strcmp(name, "arg") == 0) {
1400         s->argc++;
1401         /* one extra element as g_strjoinv() expects NULL-terminated array */
1402         s->argv = g_realloc(s->argv, (s->argc + 1) * sizeof(void *));
1403         s->argv[s->argc - 1] = val;
1404         s->argv[s->argc] = NULL;
1405     }
1406     return 0;
1407 }
1408
1409 /* Use strings passed via -kernel/-append to initialize semihosting.argv[] */
1410 static inline void semihosting_arg_fallback(const char *file, const char *cmd)
1411 {
1412     char *cmd_token;
1413
1414     /* argv[0] */
1415     add_semihosting_arg(&semihosting, "arg", file, NULL);
1416
1417     /* split -append and initialize argv[1..n] */
1418     cmd_token = strtok(g_strdup(cmd), " ");
1419     while (cmd_token) {
1420         add_semihosting_arg(&semihosting, "arg", cmd_token, NULL);
1421         cmd_token = strtok(NULL, " ");
1422     }
1423 }
1424
1425 /* Now we still need this for compatibility with XEN. */
1426 bool has_igd_gfx_passthru;
1427 static void igd_gfx_passthru(void)
1428 {
1429     has_igd_gfx_passthru = current_machine->igd_gfx_passthru;
1430 }
1431
1432 /***********************************************************/
1433 /* USB devices */
1434
1435 static int usb_device_add(const char *devname)
1436 {
1437     USBDevice *dev = NULL;
1438 #ifndef CONFIG_LINUX
1439     const char *p;
1440 #endif
1441
1442     if (!machine_usb(current_machine)) {
1443         return -1;
1444     }
1445
1446     /* drivers with .usbdevice_name entry in USBDeviceInfo */
1447     dev = usbdevice_create(devname);
1448     if (dev)
1449         goto done;
1450
1451     /* the other ones */
1452 #ifndef CONFIG_LINUX
1453     /* only the linux version is qdev-ified, usb-bsd still needs this */
1454     if (strstart(devname, "host:", &p)) {
1455         dev = usb_host_device_open(usb_bus_find(-1), p);
1456     }
1457 #endif
1458     if (!dev)
1459         return -1;
1460
1461 done:
1462     return 0;
1463 }
1464
1465 static int usb_device_del(const char *devname)
1466 {
1467     int bus_num, addr;
1468     const char *p;
1469
1470     if (strstart(devname, "host:", &p)) {
1471         return -1;
1472     }
1473
1474     if (!machine_usb(current_machine)) {
1475         return -1;
1476     }
1477
1478     p = strchr(devname, '.');
1479     if (!p)
1480         return -1;
1481     bus_num = strtoul(devname, NULL, 0);
1482     addr = strtoul(p + 1, NULL, 0);
1483
1484     return usb_device_delete_addr(bus_num, addr);
1485 }
1486
1487 static int usb_parse(const char *cmdline)
1488 {
1489     int r;
1490     r = usb_device_add(cmdline);
1491     if (r < 0) {
1492         error_report("could not add USB device '%s'", cmdline);
1493     }
1494     return r;
1495 }
1496
1497 void hmp_usb_add(Monitor *mon, const QDict *qdict)
1498 {
1499     const char *devname = qdict_get_str(qdict, "devname");
1500     if (usb_device_add(devname) < 0) {
1501         error_report("could not add USB device '%s'", devname);
1502     }
1503 }
1504
1505 void hmp_usb_del(Monitor *mon, const QDict *qdict)
1506 {
1507     const char *devname = qdict_get_str(qdict, "devname");
1508     if (usb_device_del(devname) < 0) {
1509         error_report("could not delete USB device '%s'", devname);
1510     }
1511 }
1512
1513 /***********************************************************/
1514 /* machine registration */
1515
1516 MachineState *current_machine;
1517
1518 static MachineClass *find_machine(const char *name)
1519 {
1520     GSList *el, *machines = object_class_get_list(TYPE_MACHINE, false);
1521     MachineClass *mc = NULL;
1522
1523     for (el = machines; el; el = el->next) {
1524         MachineClass *temp = el->data;
1525
1526         if (!strcmp(temp->name, name)) {
1527             mc = temp;
1528             break;
1529         }
1530         if (temp->alias &&
1531             !strcmp(temp->alias, name)) {
1532             mc = temp;
1533             break;
1534         }
1535     }
1536
1537     g_slist_free(machines);
1538     return mc;
1539 }
1540
1541 MachineClass *find_default_machine(void)
1542 {
1543     GSList *el, *machines = object_class_get_list(TYPE_MACHINE, false);
1544     MachineClass *mc = NULL;
1545
1546     for (el = machines; el; el = el->next) {
1547         MachineClass *temp = el->data;
1548
1549         if (temp->is_default) {
1550             mc = temp;
1551             break;
1552         }
1553     }
1554
1555     g_slist_free(machines);
1556     return mc;
1557 }
1558
1559 MachineInfoList *qmp_query_machines(Error **errp)
1560 {
1561     GSList *el, *machines = object_class_get_list(TYPE_MACHINE, false);
1562     MachineInfoList *mach_list = NULL;
1563
1564     for (el = machines; el; el = el->next) {
1565         MachineClass *mc = el->data;
1566         MachineInfoList *entry;
1567         MachineInfo *info;
1568
1569         info = g_malloc0(sizeof(*info));
1570         if (mc->is_default) {
1571             info->has_is_default = true;
1572             info->is_default = true;
1573         }
1574
1575         if (mc->alias) {
1576             info->has_alias = true;
1577             info->alias = g_strdup(mc->alias);
1578         }
1579
1580         info->name = g_strdup(mc->name);
1581         info->cpu_max = !mc->max_cpus ? 1 : mc->max_cpus;
1582         info->hotpluggable_cpus = !!mc->query_hotpluggable_cpus;
1583
1584         entry = g_malloc0(sizeof(*entry));
1585         entry->value = info;
1586         entry->next = mach_list;
1587         mach_list = entry;
1588     }
1589
1590     g_slist_free(machines);
1591     return mach_list;
1592 }
1593
1594 static int machine_help_func(QemuOpts *opts, MachineState *machine)
1595 {
1596     ObjectProperty *prop;
1597     ObjectPropertyIterator iter;
1598
1599     if (!qemu_opt_has_help_opt(opts)) {
1600         return 0;
1601     }
1602
1603     object_property_iter_init(&iter, OBJECT(machine));
1604     while ((prop = object_property_iter_next(&iter))) {
1605         if (!prop->set) {
1606             continue;
1607         }
1608
1609         error_printf("%s.%s=%s", MACHINE_GET_CLASS(machine)->name,
1610                      prop->name, prop->type);
1611         if (prop->description) {
1612             error_printf(" (%s)\n", prop->description);
1613         } else {
1614             error_printf("\n");
1615         }
1616     }
1617
1618     return 1;
1619 }
1620
1621 /***********************************************************/
1622 /* main execution loop */
1623
1624 struct vm_change_state_entry {
1625     VMChangeStateHandler *cb;
1626     void *opaque;
1627     QLIST_ENTRY (vm_change_state_entry) entries;
1628 };
1629
1630 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1631
1632 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1633                                                      void *opaque)
1634 {
1635     VMChangeStateEntry *e;
1636
1637     e = g_malloc0(sizeof (*e));
1638
1639     e->cb = cb;
1640     e->opaque = opaque;
1641     QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1642     return e;
1643 }
1644
1645 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1646 {
1647     QLIST_REMOVE (e, entries);
1648     g_free (e);
1649 }
1650
1651 void vm_state_notify(int running, RunState state)
1652 {
1653     VMChangeStateEntry *e, *next;
1654
1655     trace_vm_state_notify(running, state);
1656
1657     QLIST_FOREACH_SAFE(e, &vm_change_state_head, entries, next) {
1658         e->cb(e->opaque, running, state);
1659     }
1660 }
1661
1662 /* reset/shutdown handler */
1663
1664 typedef struct QEMUResetEntry {
1665     QTAILQ_ENTRY(QEMUResetEntry) entry;
1666     QEMUResetHandler *func;
1667     void *opaque;
1668 } QEMUResetEntry;
1669
1670 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1671     QTAILQ_HEAD_INITIALIZER(reset_handlers);
1672 static int reset_requested;
1673 static int shutdown_requested, shutdown_signal = -1;
1674 static pid_t shutdown_pid;
1675 static int powerdown_requested;
1676 static int debug_requested;
1677 static int suspend_requested;
1678 static WakeupReason wakeup_reason;
1679 static NotifierList powerdown_notifiers =
1680     NOTIFIER_LIST_INITIALIZER(powerdown_notifiers);
1681 static NotifierList suspend_notifiers =
1682     NOTIFIER_LIST_INITIALIZER(suspend_notifiers);
1683 static NotifierList wakeup_notifiers =
1684     NOTIFIER_LIST_INITIALIZER(wakeup_notifiers);
1685 static uint32_t wakeup_reason_mask = ~(1 << QEMU_WAKEUP_REASON_NONE);
1686
1687 int qemu_shutdown_requested_get(void)
1688 {
1689     return shutdown_requested;
1690 }
1691
1692 int qemu_reset_requested_get(void)
1693 {
1694     return reset_requested;
1695 }
1696
1697 static int qemu_shutdown_requested(void)
1698 {
1699     return atomic_xchg(&shutdown_requested, 0);
1700 }
1701
1702 static void qemu_kill_report(void)
1703 {
1704     if (!qtest_driver() && shutdown_signal != -1) {
1705         if (shutdown_pid == 0) {
1706             /* This happens for eg ^C at the terminal, so it's worth
1707              * avoiding printing an odd message in that case.
1708              */
1709             error_report("terminating on signal %d", shutdown_signal);
1710         } else {
1711             char *shutdown_cmd = qemu_get_pid_name(shutdown_pid);
1712
1713             error_report("terminating on signal %d from pid " FMT_pid " (%s)",
1714                          shutdown_signal, shutdown_pid,
1715                          shutdown_cmd ? shutdown_cmd : "<unknown process>");
1716             g_free(shutdown_cmd);
1717         }
1718         shutdown_signal = -1;
1719     }
1720 }
1721
1722 static int qemu_reset_requested(void)
1723 {
1724     int r = reset_requested;
1725     if (r && replay_checkpoint(CHECKPOINT_RESET_REQUESTED)) {
1726         reset_requested = 0;
1727         return r;
1728     }
1729     return false;
1730 }
1731
1732 static int qemu_suspend_requested(void)
1733 {
1734     int r = suspend_requested;
1735     if (r && replay_checkpoint(CHECKPOINT_SUSPEND_REQUESTED)) {
1736         suspend_requested = 0;
1737         return r;
1738     }
1739     return false;
1740 }
1741
1742 static WakeupReason qemu_wakeup_requested(void)
1743 {
1744     return wakeup_reason;
1745 }
1746
1747 static int qemu_powerdown_requested(void)
1748 {
1749     int r = powerdown_requested;
1750     powerdown_requested = 0;
1751     return r;
1752 }
1753
1754 static int qemu_debug_requested(void)
1755 {
1756     int r = debug_requested;
1757     debug_requested = 0;
1758     return r;
1759 }
1760
1761 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1762 {
1763     QEMUResetEntry *re = g_malloc0(sizeof(QEMUResetEntry));
1764
1765     re->func = func;
1766     re->opaque = opaque;
1767     QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1768 }
1769
1770 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1771 {
1772     QEMUResetEntry *re;
1773
1774     QTAILQ_FOREACH(re, &reset_handlers, entry) {
1775         if (re->func == func && re->opaque == opaque) {
1776             QTAILQ_REMOVE(&reset_handlers, re, entry);
1777             g_free(re);
1778             return;
1779         }
1780     }
1781 }
1782
1783 void qemu_devices_reset(void)
1784 {
1785     QEMUResetEntry *re, *nre;
1786
1787     /* reset all devices */
1788     QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1789         re->func(re->opaque);
1790     }
1791 }
1792
1793 void qemu_system_reset(bool report)
1794 {
1795     MachineClass *mc;
1796
1797     mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
1798
1799     cpu_synchronize_all_states();
1800
1801     if (mc && mc->reset) {
1802         mc->reset();
1803     } else {
1804         qemu_devices_reset();
1805     }
1806     if (report) {
1807         qapi_event_send_reset(&error_abort);
1808     }
1809     cpu_synchronize_all_post_reset();
1810 }
1811
1812 void qemu_system_guest_panicked(void)
1813 {
1814     if (current_cpu) {
1815         current_cpu->crash_occurred = true;
1816     }
1817     qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_PAUSE, &error_abort);
1818     vm_stop(RUN_STATE_GUEST_PANICKED);
1819     if (!no_shutdown) {
1820         qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_POWEROFF,
1821                                        &error_abort);
1822         qemu_system_shutdown_request();
1823     }
1824 }
1825
1826 void qemu_system_reset_request(void)
1827 {
1828     if (no_reboot) {
1829         shutdown_requested = 1;
1830     } else {
1831         reset_requested = 1;
1832     }
1833     cpu_stop_current();
1834     qemu_notify_event();
1835 }
1836
1837 static void qemu_system_suspend(void)
1838 {
1839     pause_all_vcpus();
1840     notifier_list_notify(&suspend_notifiers, NULL);
1841     runstate_set(RUN_STATE_SUSPENDED);
1842     qapi_event_send_suspend(&error_abort);
1843 }
1844
1845 void qemu_system_suspend_request(void)
1846 {
1847     if (runstate_check(RUN_STATE_SUSPENDED)) {
1848         return;
1849     }
1850     suspend_requested = 1;
1851     cpu_stop_current();
1852     qemu_notify_event();
1853 }
1854
1855 void qemu_register_suspend_notifier(Notifier *notifier)
1856 {
1857     notifier_list_add(&suspend_notifiers, notifier);
1858 }
1859
1860 void qemu_system_wakeup_request(WakeupReason reason)
1861 {
1862     trace_system_wakeup_request(reason);
1863
1864     if (!runstate_check(RUN_STATE_SUSPENDED)) {
1865         return;
1866     }
1867     if (!(wakeup_reason_mask & (1 << reason))) {
1868         return;
1869     }
1870     runstate_set(RUN_STATE_RUNNING);
1871     wakeup_reason = reason;
1872     qemu_notify_event();
1873 }
1874
1875 void qemu_system_wakeup_enable(WakeupReason reason, bool enabled)
1876 {
1877     if (enabled) {
1878         wakeup_reason_mask |= (1 << reason);
1879     } else {
1880         wakeup_reason_mask &= ~(1 << reason);
1881     }
1882 }
1883
1884 void qemu_register_wakeup_notifier(Notifier *notifier)
1885 {
1886     notifier_list_add(&wakeup_notifiers, notifier);
1887 }
1888
1889 void qemu_system_killed(int signal, pid_t pid)
1890 {
1891     shutdown_signal = signal;
1892     shutdown_pid = pid;
1893     no_shutdown = 0;
1894
1895 #ifdef CONFIG_MARU
1896     if (current_machine &&
1897             is_maru_machine(MACHINE_GET_CLASS(current_machine))) {
1898         qemu_system_graceful_shutdown_request(TIMEOUT_FOR_SHUTDOWN);
1899     }
1900 #else
1901     /* Cannot call qemu_system_shutdown_request directly because
1902      * we are in a signal handler.
1903      */
1904     shutdown_requested = 1;
1905     qemu_notify_event();
1906 #endif
1907 }
1908
1909 void qemu_system_shutdown_request(void)
1910 {
1911     trace_qemu_system_shutdown_request();
1912     replay_shutdown_request();
1913     shutdown_requested = 1;
1914     qemu_notify_event();
1915 }
1916
1917 static void qemu_system_powerdown(void)
1918 {
1919     qapi_event_send_powerdown(&error_abort);
1920     notifier_list_notify(&powerdown_notifiers, NULL);
1921 }
1922
1923 void qemu_system_powerdown_request(void)
1924 {
1925     trace_qemu_system_powerdown_request();
1926     powerdown_requested = 1;
1927     qemu_notify_event();
1928 }
1929
1930 void qemu_register_powerdown_notifier(Notifier *notifier)
1931 {
1932     notifier_list_add(&powerdown_notifiers, notifier);
1933 }
1934
1935 void qemu_system_debug_request(void)
1936 {
1937     debug_requested = 1;
1938     qemu_notify_event();
1939 }
1940
1941 static bool main_loop_should_exit(void)
1942 {
1943     RunState r;
1944     if (qemu_debug_requested()) {
1945         vm_stop(RUN_STATE_DEBUG);
1946     }
1947     if (qemu_suspend_requested()) {
1948         qemu_system_suspend();
1949     }
1950     if (qemu_shutdown_requested()) {
1951         qemu_kill_report();
1952         qapi_event_send_shutdown(&error_abort);
1953         if (no_shutdown) {
1954             vm_stop(RUN_STATE_SHUTDOWN);
1955         } else {
1956             return true;
1957         }
1958     }
1959     if (qemu_reset_requested()) {
1960         pause_all_vcpus();
1961         qemu_system_reset(VMRESET_REPORT);
1962         resume_all_vcpus();
1963         if (!runstate_check(RUN_STATE_RUNNING) &&
1964                 !runstate_check(RUN_STATE_INMIGRATE)) {
1965             runstate_set(RUN_STATE_PRELAUNCH);
1966         }
1967     }
1968     if (qemu_wakeup_requested()) {
1969         pause_all_vcpus();
1970         qemu_system_reset(VMRESET_SILENT);
1971         notifier_list_notify(&wakeup_notifiers, &wakeup_reason);
1972         wakeup_reason = QEMU_WAKEUP_REASON_NONE;
1973         resume_all_vcpus();
1974         qapi_event_send_wakeup(&error_abort);
1975     }
1976     if (qemu_powerdown_requested()) {
1977         qemu_system_powerdown();
1978     }
1979     if (qemu_vmstop_requested(&r)) {
1980         vm_stop(r);
1981     }
1982     return false;
1983 }
1984
1985 static void main_loop(void)
1986 {
1987     bool nonblocking;
1988     int last_io = 0;
1989 #ifdef CONFIG_PROFILER
1990     int64_t ti;
1991 #endif
1992
1993     hax_sync_vcpus();
1994
1995     do {
1996         nonblocking = !kvm_enabled() && !xen_enabled() && !hax_enabled() && last_io > 0;
1997 #ifdef CONFIG_PROFILER
1998         ti = profile_getclock();
1999 #endif
2000         last_io = main_loop_wait(nonblocking);
2001 #ifdef CONFIG_PROFILER
2002         dev_time += profile_getclock() - ti;
2003 #endif
2004     } while (!main_loop_should_exit());
2005 }
2006
2007 static void version(void)
2008 {
2009     printf("QEMU emulator version " QEMU_VERSION QEMU_PKGVERSION "\n"
2010            QEMU_COPYRIGHT "\n");
2011 }
2012
2013 static void help(int exitcode)
2014 {
2015     version();
2016     printf("usage: %s [options] [disk_image]\n\n"
2017            "'disk_image' is a raw hard disk image for IDE hard disk 0\n\n",
2018             error_get_progname());
2019
2020 #define QEMU_OPTIONS_GENERATE_HELP
2021 #include "qemu-options-wrapper.h"
2022
2023     printf("\nDuring emulation, the following keys are useful:\n"
2024            "ctrl-alt-f      toggle full screen\n"
2025            "ctrl-alt-n      switch to virtual console 'n'\n"
2026            "ctrl-alt        toggle mouse and keyboard grab\n"
2027            "\n"
2028            "When using -nographic, press 'ctrl-a h' to get some help.\n");
2029
2030     exit(exitcode);
2031 }
2032
2033 #define HAS_ARG 0x0001
2034
2035 typedef struct QEMUOption {
2036     const char *name;
2037     int flags;
2038     int index;
2039     uint32_t arch_mask;
2040 } QEMUOption;
2041
2042 static const QEMUOption qemu_options[] = {
2043     { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
2044 #define QEMU_OPTIONS_GENERATE_OPTIONS
2045 #include "qemu-options-wrapper.h"
2046     { NULL },
2047 };
2048
2049 typedef struct VGAInterfaceInfo {
2050     const char *opt_name;    /* option name */
2051     const char *name;        /* human-readable name */
2052     /* Class names indicating that support is available.
2053      * If no class is specified, the interface is always available */
2054     const char *class_names[2];
2055 } VGAInterfaceInfo;
2056
2057 static VGAInterfaceInfo vga_interfaces[VGA_TYPE_MAX] = {
2058     [VGA_NONE] = {
2059         .opt_name = "none",
2060     },
2061     [VGA_STD] = {
2062         .opt_name = "std",
2063         .name = "standard VGA",
2064         .class_names = { "VGA", "isa-vga" },
2065     },
2066     [VGA_CIRRUS] = {
2067         .opt_name = "cirrus",
2068         .name = "Cirrus VGA",
2069         .class_names = { "cirrus-vga", "isa-cirrus-vga" },
2070     },
2071     [VGA_VMWARE] = {
2072         .opt_name = "vmware",
2073         .name = "VMWare SVGA",
2074         .class_names = { "vmware-svga" },
2075     },
2076     [VGA_VIRTIO] = {
2077         .opt_name = "virtio",
2078         .name = "Virtio VGA",
2079         .class_names = { "virtio-vga" },
2080     },
2081     [VGA_QXL] = {
2082         .opt_name = "qxl",
2083         .name = "QXL VGA",
2084         .class_names = { "qxl-vga" },
2085     },
2086     [VGA_TCX] = {
2087         .opt_name = "tcx",
2088         .name = "TCX framebuffer",
2089         .class_names = { "SUNW,tcx" },
2090     },
2091     [VGA_CG3] = {
2092         .opt_name = "cg3",
2093         .name = "CG3 framebuffer",
2094         .class_names = { "cgthree" },
2095     },
2096     [VGA_XENFB] = {
2097         .opt_name = "xenfb",
2098     },
2099 };
2100
2101 static bool vga_interface_available(VGAInterfaceType t)
2102 {
2103     VGAInterfaceInfo *ti = &vga_interfaces[t];
2104
2105     assert(t < VGA_TYPE_MAX);
2106     return !ti->class_names[0] ||
2107            object_class_by_name(ti->class_names[0]) ||
2108            object_class_by_name(ti->class_names[1]);
2109 }
2110
2111 static void select_vgahw(const char *p)
2112 {
2113     const char *opts;
2114     int t;
2115
2116     assert(vga_interface_type == VGA_NONE);
2117     for (t = 0; t < VGA_TYPE_MAX; t++) {
2118         VGAInterfaceInfo *ti = &vga_interfaces[t];
2119         if (ti->opt_name && strstart(p, ti->opt_name, &opts)) {
2120             if (!vga_interface_available(t)) {
2121                 error_report("%s not available", ti->name);
2122                 exit(1);
2123             }
2124             vga_interface_type = t;
2125             break;
2126         }
2127     }
2128     if (t == VGA_TYPE_MAX) {
2129     invalid_vga:
2130         error_report("unknown vga type: %s", p);
2131         exit(1);
2132     }
2133     while (*opts) {
2134         const char *nextopt;
2135
2136         if (strstart(opts, ",retrace=", &nextopt)) {
2137             opts = nextopt;
2138             if (strstart(opts, "dumb", &nextopt))
2139                 vga_retrace_method = VGA_RETRACE_DUMB;
2140             else if (strstart(opts, "precise", &nextopt))
2141                 vga_retrace_method = VGA_RETRACE_PRECISE;
2142             else goto invalid_vga;
2143         } else goto invalid_vga;
2144         opts = nextopt;
2145     }
2146 }
2147
2148 typedef enum DisplayType {
2149     DT_DEFAULT,
2150     DT_CURSES,
2151     DT_SDL,
2152     DT_COCOA,
2153     DT_GTK,
2154 #ifdef CONFIG_MARU
2155     DT_MARU_REMOTE_SPICE,
2156 # ifdef CONFIG_QT
2157     DT_MARU_QT_ONSCREEN,
2158     DT_MARU_QT_OFFSCREEN,
2159 # endif
2160 #endif
2161     DT_NONE,
2162 } DisplayType;
2163
2164 static DisplayType select_display(const char *p)
2165 {
2166     const char *opts;
2167     DisplayType display = DT_DEFAULT;
2168
2169     if (strstart(p, "sdl", &opts)) {
2170 #ifdef CONFIG_SDL
2171         display = DT_SDL;
2172         while (*opts) {
2173             const char *nextopt;
2174
2175             if (strstart(opts, ",frame=", &nextopt)) {
2176                 opts = nextopt;
2177                 if (strstart(opts, "on", &nextopt)) {
2178                     no_frame = 0;
2179                 } else if (strstart(opts, "off", &nextopt)) {
2180                     no_frame = 1;
2181                 } else {
2182                     goto invalid_sdl_args;
2183                 }
2184             } else if (strstart(opts, ",alt_grab=", &nextopt)) {
2185                 opts = nextopt;
2186                 if (strstart(opts, "on", &nextopt)) {
2187                     alt_grab = 1;
2188                 } else if (strstart(opts, "off", &nextopt)) {
2189                     alt_grab = 0;
2190                 } else {
2191                     goto invalid_sdl_args;
2192                 }
2193             } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
2194                 opts = nextopt;
2195                 if (strstart(opts, "on", &nextopt)) {
2196                     ctrl_grab = 1;
2197                 } else if (strstart(opts, "off", &nextopt)) {
2198                     ctrl_grab = 0;
2199                 } else {
2200                     goto invalid_sdl_args;
2201                 }
2202             } else if (strstart(opts, ",window_close=", &nextopt)) {
2203                 opts = nextopt;
2204                 if (strstart(opts, "on", &nextopt)) {
2205                     no_quit = 0;
2206                 } else if (strstart(opts, "off", &nextopt)) {
2207                     no_quit = 1;
2208                 } else {
2209                     goto invalid_sdl_args;
2210                 }
2211             } else if (strstart(opts, ",gl=", &nextopt)) {
2212                 opts = nextopt;
2213                 if (strstart(opts, "on", &nextopt)) {
2214                     request_opengl = 1;
2215                 } else if (strstart(opts, "off", &nextopt)) {
2216                     request_opengl = 0;
2217                 } else {
2218                     goto invalid_sdl_args;
2219                 }
2220             } else {
2221             invalid_sdl_args:
2222                 error_report("invalid SDL option string");
2223                 exit(1);
2224             }
2225             opts = nextopt;
2226         }
2227 #else
2228         error_report("SDL support is disabled");
2229         exit(1);
2230 #endif
2231     } else if (strstart(p, "vnc", &opts)) {
2232         if (*opts == '=') {
2233             vnc_parse(opts + 1, &error_fatal);
2234         } else {
2235             error_report("VNC requires a display argument vnc=<display>");
2236             exit(1);
2237         }
2238     } else if (strstart(p, "curses", &opts)) {
2239 #ifdef CONFIG_CURSES
2240         display = DT_CURSES;
2241 #else
2242         error_report("curses support is disabled");
2243         exit(1);
2244 #endif
2245     } else if (strstart(p, "gtk", &opts)) {
2246 #ifdef CONFIG_GTK
2247         display = DT_GTK;
2248         while (*opts) {
2249             const char *nextopt;
2250
2251             if (strstart(opts, ",grab_on_hover=", &nextopt)) {
2252                 opts = nextopt;
2253                 if (strstart(opts, "on", &nextopt)) {
2254                     grab_on_hover = true;
2255                 } else if (strstart(opts, "off", &nextopt)) {
2256                     grab_on_hover = false;
2257                 } else {
2258                     goto invalid_gtk_args;
2259                 }
2260             } else if (strstart(opts, ",gl=", &nextopt)) {
2261                 opts = nextopt;
2262                 if (strstart(opts, "on", &nextopt)) {
2263                     request_opengl = 1;
2264                 } else if (strstart(opts, "off", &nextopt)) {
2265                     request_opengl = 0;
2266                 } else {
2267                     goto invalid_gtk_args;
2268                 }
2269             } else {
2270             invalid_gtk_args:
2271                 error_report("invalid GTK option string");
2272                 exit(1);
2273             }
2274             opts = nextopt;
2275         }
2276 #else
2277         error_report("GTK support is disabled");
2278         exit(1);
2279 #endif
2280 #ifdef CONFIG_MARU
2281     } else if (strstart(p, "maru_remote_spice", &opts)) {
2282 # ifdef CONFIG_SPICE
2283         display = DT_MARU_REMOTE_SPICE;
2284 # else
2285         fprintf(stderr, "maru_remote_spice is disabled\n");
2286         exit(1);
2287 # endif
2288     } else if (strstart(p, "maru_qt", &opts)) {
2289 # ifdef CONFIG_QT
2290         display = DT_MARU_QT_ONSCREEN;
2291         while (*opts) {
2292             const char *nextopt;
2293             if (strstart(opts, ",rendering=", &nextopt)) {
2294                 opts = nextopt;
2295                 if (strstart(opts, "onscreen", &nextopt)) {
2296                     display = DT_MARU_QT_ONSCREEN;
2297                 } else if (strstart(opts, "offscreen", &nextopt)) {
2298                     display = DT_MARU_QT_OFFSCREEN;
2299                 } else {
2300                     goto invalid_maru_qt_args;
2301                 }
2302             } else if (strstart(opts, ",resolution=", &nextopt)) {
2303                 opts = nextopt;
2304                 char *endptr = NULL;
2305                 // Resolution should be formed "640x480" or "640*480".
2306                 int width = (int)g_ascii_strtoll(opts, &endptr, 10);
2307                 int height = (int)g_ascii_strtoll(++endptr, &endptr, 10);
2308                 if (width <= 0 || height <= 0) {
2309                     goto invalid_maru_qt_args;
2310                 }
2311                 set_initial_display_resolution(width, height);
2312                 nextopt = endptr;
2313             } else if (strstart(opts, ",dpi=", &nextopt)) {
2314                 opts = nextopt;
2315                 char *endptr = NULL;
2316                 int dpi = (int)g_ascii_strtoll(opts, &endptr, 10);
2317                 if (dpi <= 0) {
2318                     goto invalid_maru_qt_args;
2319                 }
2320                 set_display_pixel_density(dpi);
2321                 nextopt = endptr;
2322             } else if (strstart(opts, ",forcelegacy", &nextopt)) {
2323                 opts = nextopt;
2324                 maru_qt5_set_force_legacy(true);
2325             } else {
2326             invalid_maru_qt_args:
2327                 error_report(FAILED_TO_DISPLAY_PARSING);
2328                 exit(1);
2329             }
2330             opts = nextopt;
2331         }
2332 # else
2333         error_report("maru_qt is disabled.\n");
2334
2335         exit(1);
2336 # endif
2337 #endif /* CONFIG_MARU */
2338     } else if (strstart(p, "none", &opts)) {
2339         display = DT_NONE;
2340     } else {
2341         error_report("unknown display type");
2342         exit(1);
2343     }
2344
2345     return display;
2346 }
2347
2348 static int balloon_parse(const char *arg)
2349 {
2350     QemuOpts *opts;
2351
2352     if (strcmp(arg, "none") == 0) {
2353         return 0;
2354     }
2355
2356     if (!strncmp(arg, "virtio", 6)) {
2357         if (arg[6] == ',') {
2358             /* have params -> parse them */
2359             opts = qemu_opts_parse_noisily(qemu_find_opts("device"), arg + 7,
2360                                            false);
2361             if (!opts)
2362                 return  -1;
2363         } else {
2364             /* create empty opts */
2365             opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
2366                                     &error_abort);
2367         }
2368         qemu_opt_set(opts, "driver", "virtio-balloon", &error_abort);
2369         return 0;
2370     }
2371
2372     return -1;
2373 }
2374
2375 char *qemu_find_file(int type, const char *name)
2376 {
2377     int i;
2378     const char *subdir;
2379     char *buf;
2380
2381     /* Try the name as a straight path first */
2382     if (access(name, R_OK) == 0) {
2383         trace_load_file(name, name);
2384         return g_strdup(name);
2385     }
2386
2387     switch (type) {
2388     case QEMU_FILE_TYPE_BIOS:
2389         subdir = "";
2390         break;
2391     case QEMU_FILE_TYPE_KEYMAP:
2392         subdir = "keymaps/";
2393         break;
2394     default:
2395         abort();
2396     }
2397
2398     for (i = 0; i < data_dir_idx; i++) {
2399         buf = g_strdup_printf("%s/%s%s", data_dir[i], subdir, name);
2400         if (access(buf, R_OK) == 0) {
2401             trace_load_file(name, buf);
2402             return buf;
2403         }
2404         g_free(buf);
2405     }
2406     return NULL;
2407 }
2408
2409 static inline bool nonempty_str(const char *str)
2410 {
2411     return str && *str;
2412 }
2413
2414 static int parse_fw_cfg(void *opaque, QemuOpts *opts, Error **errp)
2415 {
2416     gchar *buf;
2417     size_t size;
2418     const char *name, *file, *str;
2419     FWCfgState *fw_cfg = (FWCfgState *) opaque;
2420
2421     if (fw_cfg == NULL) {
2422         error_report("fw_cfg device not available");
2423         return -1;
2424     }
2425     name = qemu_opt_get(opts, "name");
2426     file = qemu_opt_get(opts, "file");
2427     str = qemu_opt_get(opts, "string");
2428
2429     /* we need name and either a file or the content string */
2430     if (!(nonempty_str(name) && (nonempty_str(file) || nonempty_str(str)))) {
2431         error_report("invalid argument(s)");
2432         return -1;
2433     }
2434     if (nonempty_str(file) && nonempty_str(str)) {
2435         error_report("file and string are mutually exclusive");
2436         return -1;
2437     }
2438     if (strlen(name) > FW_CFG_MAX_FILE_PATH - 1) {
2439         error_report("name too long (max. %d char)", FW_CFG_MAX_FILE_PATH - 1);
2440         return -1;
2441     }
2442     if (strncmp(name, "opt/", 4) != 0) {
2443         error_report("warning: externally provided fw_cfg item names "
2444                      "should be prefixed with \"opt/\"");
2445     }
2446     if (nonempty_str(str)) {
2447         size = strlen(str); /* NUL terminator NOT included in fw_cfg blob */
2448         buf = g_memdup(str, size);
2449     } else {
2450         if (!g_file_get_contents(file, &buf, &size, NULL)) {
2451             error_report("can't load %s", file);
2452             return -1;
2453         }
2454     }
2455     /* For legacy, keep user files in a specific global order. */
2456     fw_cfg_set_order_override(fw_cfg, FW_CFG_ORDER_OVERRIDE_USER);
2457     fw_cfg_add_file(fw_cfg, name, buf, size);
2458     fw_cfg_reset_order_override(fw_cfg);
2459     return 0;
2460 }
2461
2462 static int device_help_func(void *opaque, QemuOpts *opts, Error **errp)
2463 {
2464     return qdev_device_help(opts);
2465 }
2466
2467 static int device_init_func(void *opaque, QemuOpts *opts, Error **errp)
2468 {
2469     Error *err = NULL;
2470     DeviceState *dev;
2471
2472     dev = qdev_device_add(opts, &err);
2473     if (!dev) {
2474         error_report_err(err);
2475         return -1;
2476     }
2477     object_unref(OBJECT(dev));
2478     return 0;
2479 }
2480
2481 static int chardev_init_func(void *opaque, QemuOpts *opts, Error **errp)
2482 {
2483     Error *local_err = NULL;
2484
2485     qemu_chr_new_from_opts(opts, &local_err);
2486     if (local_err) {
2487         error_report_err(local_err);
2488         return -1;
2489     }
2490     return 0;
2491 }
2492
2493 #ifdef CONFIG_VIRTFS
2494 static int fsdev_init_func(void *opaque, QemuOpts *opts, Error **errp)
2495 {
2496     return qemu_fsdev_add(opts);
2497 }
2498 #endif
2499
2500 static int mon_init_func(void *opaque, QemuOpts *opts, Error **errp)
2501 {
2502     CharDriverState *chr;
2503     const char *chardev;
2504     const char *mode;
2505     int flags;
2506
2507     mode = qemu_opt_get(opts, "mode");
2508     if (mode == NULL) {
2509         mode = "readline";
2510     }
2511     if (strcmp(mode, "readline") == 0) {
2512         flags = MONITOR_USE_READLINE;
2513     } else if (strcmp(mode, "control") == 0) {
2514         flags = MONITOR_USE_CONTROL;
2515     } else {
2516         error_report("unknown monitor mode \"%s\"", mode);
2517         exit(1);
2518     }
2519
2520     if (qemu_opt_get_bool(opts, "pretty", 0))
2521         flags |= MONITOR_USE_PRETTY;
2522
2523     if (qemu_opt_get_bool(opts, "default", 0)) {
2524         error_report("option 'default' does nothing and is deprecated");
2525     }
2526
2527     chardev = qemu_opt_get(opts, "chardev");
2528     chr = qemu_chr_find(chardev);
2529     if (chr == NULL) {
2530         error_report("chardev \"%s\" not found", chardev);
2531         exit(1);
2532     }
2533
2534     monitor_init(chr, flags);
2535     return 0;
2536 }
2537
2538 static void monitor_parse(const char *optarg, const char *mode, bool pretty)
2539 {
2540     static int monitor_device_index = 0;
2541     QemuOpts *opts;
2542     const char *p;
2543     char label[32];
2544
2545     if (strstart(optarg, "chardev:", &p)) {
2546         snprintf(label, sizeof(label), "%s", p);
2547     } else {
2548         snprintf(label, sizeof(label), "compat_monitor%d",
2549                  monitor_device_index);
2550         opts = qemu_chr_parse_compat(label, optarg);
2551         if (!opts) {
2552             error_report("parse error: %s", optarg);
2553             exit(1);
2554         }
2555     }
2556
2557     opts = qemu_opts_create(qemu_find_opts("mon"), label, 1, &error_fatal);
2558     qemu_opt_set(opts, "mode", mode, &error_abort);
2559     qemu_opt_set(opts, "chardev", label, &error_abort);
2560     qemu_opt_set_bool(opts, "pretty", pretty, &error_abort);
2561     monitor_device_index++;
2562 }
2563
2564 struct device_config {
2565     enum {
2566         DEV_USB,       /* -usbdevice     */
2567         DEV_BT,        /* -bt            */
2568         DEV_SERIAL,    /* -serial        */
2569         DEV_PARALLEL,  /* -parallel      */
2570         DEV_VIRTCON,   /* -virtioconsole */
2571         DEV_DEBUGCON,  /* -debugcon */
2572         DEV_GDB,       /* -gdb, -s */
2573         DEV_SCLP,      /* s390 sclp */
2574     } type;
2575     const char *cmdline;
2576     Location loc;
2577     QTAILQ_ENTRY(device_config) next;
2578 };
2579
2580 static QTAILQ_HEAD(, device_config) device_configs =
2581     QTAILQ_HEAD_INITIALIZER(device_configs);
2582
2583 static void add_device_config(int type, const char *cmdline)
2584 {
2585     struct device_config *conf;
2586
2587     conf = g_malloc0(sizeof(*conf));
2588     conf->type = type;
2589     conf->cmdline = cmdline;
2590     loc_save(&conf->loc);
2591     QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2592 }
2593
2594 static int foreach_device_config(int type, int (*func)(const char *cmdline))
2595 {
2596     struct device_config *conf;
2597     int rc;
2598
2599     QTAILQ_FOREACH(conf, &device_configs, next) {
2600         if (conf->type != type)
2601             continue;
2602         loc_push_restore(&conf->loc);
2603         rc = func(conf->cmdline);
2604         loc_pop(&conf->loc);
2605         if (rc) {
2606             return rc;
2607         }
2608     }
2609     return 0;
2610 }
2611
2612 static int serial_parse(const char *devname)
2613 {
2614     static int index = 0;
2615     char label[32];
2616
2617     if (strcmp(devname, "none") == 0)
2618         return 0;
2619     if (index == MAX_SERIAL_PORTS) {
2620         error_report("too many serial ports");
2621         exit(1);
2622     }
2623     snprintf(label, sizeof(label), "serial%d", index);
2624     serial_hds[index] = qemu_chr_new(label, devname);
2625     if (!serial_hds[index]) {
2626         error_report("could not connect serial device"
2627                      " to character backend '%s'", devname);
2628         return -1;
2629     }
2630     index++;
2631     return 0;
2632 }
2633
2634 static int parallel_parse(const char *devname)
2635 {
2636     static int index = 0;
2637     char label[32];
2638
2639     if (strcmp(devname, "none") == 0)
2640         return 0;
2641     if (index == MAX_PARALLEL_PORTS) {
2642         error_report("too many parallel ports");
2643         exit(1);
2644     }
2645     snprintf(label, sizeof(label), "parallel%d", index);
2646     parallel_hds[index] = qemu_chr_new(label, devname);
2647     if (!parallel_hds[index]) {
2648         error_report("could not connect parallel device"
2649                      " to character backend '%s'", devname);
2650         return -1;
2651     }
2652     index++;
2653     return 0;
2654 }
2655
2656 static int virtcon_parse(const char *devname)
2657 {
2658     QemuOptsList *device = qemu_find_opts("device");
2659     static int index = 0;
2660     char label[32];
2661     QemuOpts *bus_opts, *dev_opts;
2662
2663     if (strcmp(devname, "none") == 0)
2664         return 0;
2665     if (index == MAX_VIRTIO_CONSOLES) {
2666         error_report("too many virtio consoles");
2667         exit(1);
2668     }
2669
2670     bus_opts = qemu_opts_create(device, NULL, 0, &error_abort);
2671     qemu_opt_set(bus_opts, "driver", "virtio-serial", &error_abort);
2672
2673     dev_opts = qemu_opts_create(device, NULL, 0, &error_abort);
2674     qemu_opt_set(dev_opts, "driver", "virtconsole", &error_abort);
2675
2676     snprintf(label, sizeof(label), "virtcon%d", index);
2677     virtcon_hds[index] = qemu_chr_new(label, devname);
2678     if (!virtcon_hds[index]) {
2679         error_report("could not connect virtio console"
2680                      " to character backend '%s'", devname);
2681         return -1;
2682     }
2683     qemu_opt_set(dev_opts, "chardev", label, &error_abort);
2684
2685     index++;
2686     return 0;
2687 }
2688
2689 static int sclp_parse(const char *devname)
2690 {
2691     QemuOptsList *device = qemu_find_opts("device");
2692     static int index = 0;
2693     char label[32];
2694     QemuOpts *dev_opts;
2695
2696     if (strcmp(devname, "none") == 0) {
2697         return 0;
2698     }
2699     if (index == MAX_SCLP_CONSOLES) {
2700         error_report("too many sclp consoles");
2701         exit(1);
2702     }
2703
2704     assert(arch_type == QEMU_ARCH_S390X);
2705
2706     dev_opts = qemu_opts_create(device, NULL, 0, NULL);
2707     qemu_opt_set(dev_opts, "driver", "sclpconsole", &error_abort);
2708
2709     snprintf(label, sizeof(label), "sclpcon%d", index);
2710     sclp_hds[index] = qemu_chr_new(label, devname);
2711     if (!sclp_hds[index]) {
2712         error_report("could not connect sclp console"
2713                      " to character backend '%s'", devname);
2714         return -1;
2715     }
2716     qemu_opt_set(dev_opts, "chardev", label, &error_abort);
2717
2718     index++;
2719     return 0;
2720 }
2721
2722 static int debugcon_parse(const char *devname)
2723 {
2724     QemuOpts *opts;
2725
2726     if (!qemu_chr_new("debugcon", devname)) {
2727         exit(1);
2728     }
2729     opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1, NULL);
2730     if (!opts) {
2731         error_report("already have a debugcon device");
2732         exit(1);
2733     }
2734     qemu_opt_set(opts, "driver", "isa-debugcon", &error_abort);
2735     qemu_opt_set(opts, "chardev", "debugcon", &error_abort);
2736     return 0;
2737 }
2738
2739 static gint machine_class_cmp(gconstpointer a, gconstpointer b)
2740 {
2741     const MachineClass *mc1 = a, *mc2 = b;
2742     int res;
2743
2744     if (mc1->family == NULL) {
2745         if (mc2->family == NULL) {
2746             /* Compare standalone machine types against each other; they sort
2747              * in increasing order.
2748              */
2749             return strcmp(object_class_get_name(OBJECT_CLASS(mc1)),
2750                           object_class_get_name(OBJECT_CLASS(mc2)));
2751         }
2752
2753         /* Standalone machine types sort after families. */
2754         return 1;
2755     }
2756
2757     if (mc2->family == NULL) {
2758         /* Families sort before standalone machine types. */
2759         return -1;
2760     }
2761
2762     /* Families sort between each other alphabetically increasingly. */
2763     res = strcmp(mc1->family, mc2->family);
2764     if (res != 0) {
2765         return res;
2766     }
2767
2768     /* Within the same family, machine types sort in decreasing order. */
2769     return strcmp(object_class_get_name(OBJECT_CLASS(mc2)),
2770                   object_class_get_name(OBJECT_CLASS(mc1)));
2771 }
2772
2773  static MachineClass *machine_parse(const char *name)
2774 {
2775     MachineClass *mc = NULL;
2776     GSList *el, *machines = object_class_get_list(TYPE_MACHINE, false);
2777
2778     if (name) {
2779         mc = find_machine(name);
2780     }
2781     if (mc) {
2782         g_slist_free(machines);
2783         return mc;
2784     }
2785     if (name && !is_help_option(name)) {
2786         error_report("unsupported machine type");
2787         error_printf("Use -machine help to list supported machines\n");
2788     } else {
2789         printf("Supported machines are:\n");
2790         machines = g_slist_sort(machines, machine_class_cmp);
2791         for (el = machines; el; el = el->next) {
2792             MachineClass *mc = el->data;
2793             if (mc->alias) {
2794                 printf("%-20s %s (alias of %s)\n", mc->alias, mc->desc, mc->name);
2795             }
2796             printf("%-20s %s%s\n", mc->name, mc->desc,
2797                    mc->is_default ? " (default)" : "");
2798         }
2799     }
2800
2801     g_slist_free(machines);
2802     exit(!name || !is_help_option(name));
2803 }
2804
2805 void qemu_add_exit_notifier(Notifier *notify)
2806 {
2807     notifier_list_add(&exit_notifiers, notify);
2808 }
2809
2810 void qemu_remove_exit_notifier(Notifier *notify)
2811 {
2812     notifier_remove(notify);
2813 }
2814
2815 static void qemu_run_exit_notifiers(void)
2816 {
2817     notifier_list_notify(&exit_notifiers, NULL);
2818 }
2819
2820 static bool machine_init_done;
2821
2822 void qemu_add_machine_init_done_notifier(Notifier *notify)
2823 {
2824     notifier_list_add(&machine_init_done_notifiers, notify);
2825     if (machine_init_done) {
2826         notify->notify(notify, NULL);
2827     }
2828 }
2829
2830 void qemu_remove_machine_init_done_notifier(Notifier *notify)
2831 {
2832     notifier_remove(notify);
2833 }
2834
2835 static void qemu_run_machine_init_done_notifiers(void)
2836 {
2837     notifier_list_notify(&machine_init_done_notifiers, NULL);
2838     machine_init_done = true;
2839 }
2840
2841 static const QEMUOption *lookup_opt(int argc, char **argv,
2842                                     const char **poptarg, int *poptind)
2843 {
2844     const QEMUOption *popt;
2845     int optind = *poptind;
2846     char *r = argv[optind];
2847     const char *optarg;
2848
2849     loc_set_cmdline(argv, optind, 1);
2850     optind++;
2851     /* Treat --foo the same as -foo.  */
2852     if (r[1] == '-')
2853         r++;
2854     popt = qemu_options;
2855     for(;;) {
2856         if (!popt->name) {
2857             error_report("invalid option");
2858             exit(1);
2859         }
2860         if (!strcmp(popt->name, r + 1))
2861             break;
2862         popt++;
2863     }
2864     if (popt->flags & HAS_ARG) {
2865         if (optind >= argc) {
2866             error_report("requires an argument");
2867             exit(1);
2868         }
2869         optarg = argv[optind++];
2870         loc_set_cmdline(argv, optind - 2, 2);
2871     } else {
2872         optarg = NULL;
2873     }
2874
2875     *poptarg = optarg;
2876     *poptind = optind;
2877
2878     return popt;
2879 }
2880
2881 static MachineClass *select_machine(void)
2882 {
2883     MachineClass *machine_class = find_default_machine();
2884     const char *optarg;
2885     QemuOpts *opts;
2886     Location loc;
2887
2888     loc_push_none(&loc);
2889
2890     opts = qemu_get_machine_opts();
2891     qemu_opts_loc_restore(opts);
2892
2893     optarg = qemu_opt_get(opts, "type");
2894     if (optarg) {
2895         machine_class = machine_parse(optarg);
2896     }
2897
2898     if (!machine_class) {
2899         error_report("No machine specified, and there is no default");
2900         error_printf("Use -machine help to list supported machines\n");
2901         exit(1);
2902     }
2903
2904     loc_pop(&loc);
2905     return machine_class;
2906 }
2907
2908 static int machine_set_property(void *opaque,
2909                                 const char *name, const char *value,
2910                                 Error **errp)
2911 {
2912     Object *obj = OBJECT(opaque);
2913     Error *local_err = NULL;
2914     char *p, *qom_name;
2915
2916     if (strcmp(name, "type") == 0) {
2917         return 0;
2918     }
2919
2920     qom_name = g_strdup(name);
2921     for (p = qom_name; *p; p++) {
2922         if (*p == '_') {
2923             *p = '-';
2924         }
2925     }
2926
2927     object_property_parse(obj, value, qom_name, &local_err);
2928     g_free(qom_name);
2929
2930     if (local_err) {
2931         error_report_err(local_err);
2932         return -1;
2933     }
2934
2935     return 0;
2936 }
2937
2938
2939 /*
2940  * Initial object creation happens before all other
2941  * QEMU data types are created. The majority of objects
2942  * can be created at this point. The rng-egd object
2943  * cannot be created here, as it depends on the chardev
2944  * already existing.
2945  */
2946 static bool object_create_initial(const char *type)
2947 {
2948     if (g_str_equal(type, "rng-egd")) {
2949         return false;
2950     }
2951
2952     /*
2953      * return false for concrete netfilters since
2954      * they depend on netdevs already existing
2955      */
2956     if (g_str_equal(type, "filter-buffer") ||
2957         g_str_equal(type, "filter-dump") ||
2958         g_str_equal(type, "filter-mirror") ||
2959         g_str_equal(type, "filter-redirector") ||
2960         g_str_equal(type, "colo-compare") ||
2961         g_str_equal(type, "filter-rewriter")) {
2962         return false;
2963     }
2964
2965     /* Memory allocation by backends needs to be done
2966      * after configure_accelerator() (due to the tcg_enabled()
2967      * checks at memory_region_init_*()).
2968      *
2969      * Also, allocation of large amounts of memory may delay
2970      * chardev initialization for too long, and trigger timeouts
2971      * on software that waits for a monitor socket to be created
2972      * (e.g. libvirt).
2973      */
2974     if (g_str_has_prefix(type, "memory-backend-")) {
2975         return false;
2976     }
2977
2978     return true;
2979 }
2980
2981
2982 /*
2983  * The remainder of object creation happens after the
2984  * creation of chardev, fsdev, net clients and device data types.
2985  */
2986 static bool object_create_delayed(const char *type)
2987 {
2988     return !object_create_initial(type);
2989 }
2990
2991
2992 static void set_memory_options(uint64_t *ram_slots, ram_addr_t *maxram_size,
2993                                MachineClass *mc)
2994 {
2995     uint64_t sz;
2996     const char *mem_str;
2997     const char *maxmem_str, *slots_str;
2998     const ram_addr_t default_ram_size = mc->default_ram_size;
2999     QemuOpts *opts = qemu_find_opts_singleton("memory");
3000     Location loc;
3001
3002     loc_push_none(&loc);
3003     qemu_opts_loc_restore(opts);
3004
3005     sz = 0;
3006     mem_str = qemu_opt_get(opts, "size");
3007     if (mem_str) {
3008         if (!*mem_str) {
3009             error_report("missing 'size' option value");
3010             exit(EXIT_FAILURE);
3011         }
3012
3013         sz = qemu_opt_get_size(opts, "size", ram_size);
3014
3015         /* Fix up legacy suffix-less format */
3016         if (g_ascii_isdigit(mem_str[strlen(mem_str) - 1])) {
3017             uint64_t overflow_check = sz;
3018
3019             sz <<= 20;
3020             if ((sz >> 20) != overflow_check) {
3021                 error_report("too large 'size' option value");
3022                 exit(EXIT_FAILURE);
3023             }
3024         }
3025     }
3026
3027     /* backward compatibility behaviour for case "-m 0" */
3028     if (sz == 0) {
3029         sz = default_ram_size;
3030     }
3031
3032     sz = QEMU_ALIGN_UP(sz, 8192);
3033     ram_size = sz;
3034     if (ram_size != sz) {
3035         error_report("ram size too large");
3036         exit(EXIT_FAILURE);
3037     }
3038
3039     /* store value for the future use */
3040     qemu_opt_set_number(opts, "size", ram_size, &error_abort);
3041     *maxram_size = ram_size;
3042
3043     maxmem_str = qemu_opt_get(opts, "maxmem");
3044     slots_str = qemu_opt_get(opts, "slots");
3045     if (maxmem_str && slots_str) {
3046         uint64_t slots;
3047
3048         sz = qemu_opt_get_size(opts, "maxmem", 0);
3049         slots = qemu_opt_get_number(opts, "slots", 0);
3050         if (sz < ram_size) {
3051             error_report("invalid value of -m option maxmem: "
3052                          "maximum memory size (0x%" PRIx64 ") must be at least "
3053                          "the initial memory size (0x" RAM_ADDR_FMT ")",
3054                          sz, ram_size);
3055             exit(EXIT_FAILURE);
3056         } else if (sz > ram_size) {
3057             if (!slots) {
3058                 error_report("invalid value of -m option: maxmem was "
3059                              "specified, but no hotplug slots were specified");
3060                 exit(EXIT_FAILURE);
3061             }
3062         } else if (slots) {
3063             error_report("invalid value of -m option maxmem: "
3064                          "memory slots were specified but maximum memory size "
3065                          "(0x%" PRIx64 ") is equal to the initial memory size "
3066                          "(0x" RAM_ADDR_FMT ")", sz, ram_size);
3067             exit(EXIT_FAILURE);
3068         }
3069
3070         *maxram_size = sz;
3071         *ram_slots = slots;
3072     } else if ((!maxmem_str && slots_str) ||
3073             (maxmem_str && !slots_str)) {
3074         error_report("invalid -m option value: missing "
3075                 "'%s' option", slots_str ? "maxmem" : "slots");
3076         exit(EXIT_FAILURE);
3077     }
3078
3079     loc_pop(&loc);
3080 }
3081
3082 static int global_init_func(void *opaque, QemuOpts *opts, Error **errp)
3083 {
3084     GlobalProperty *g;
3085
3086     g = g_malloc0(sizeof(*g));
3087     g->driver   = qemu_opt_get(opts, "driver");
3088     g->property = qemu_opt_get(opts, "property");
3089     g->value    = qemu_opt_get(opts, "value");
3090     g->user_provided = true;
3091     g->errp = &error_fatal;
3092     qdev_prop_register_global(g);
3093     return 0;
3094 }
3095
3096 #ifdef CONFIG_MARU
3097 // W/A for preserve larger continuous heap for RAM.
3098 extern void *preallocated_ram_ptr;
3099 extern int preallocated_ram_size;
3100 // FIXME
3101 extern bool nodisplay;
3102 #endif
3103
3104 int main(int argc, char **argv, char **envp)
3105 {
3106     int i;
3107     int snapshot, linux_boot;
3108     const char *initrd_filename;
3109     const char *kernel_filename, *kernel_cmdline;
3110     const char *boot_order = NULL;
3111     const char *boot_once = NULL;
3112     DisplayState *ds;
3113     int cyls, heads, secs, translation;
3114     QemuOpts *hda_opts = NULL, *opts, *machine_opts, *icount_opts = NULL;
3115     QemuOptsList *olist;
3116     int optind;
3117     const char *optarg;
3118     const char *loadvm = NULL;
3119     MachineClass *machine_class;
3120     const char *cpu_model;
3121     const char *vga_model = NULL;
3122     const char *qtest_chrdev = NULL;
3123     const char *qtest_log = NULL;
3124     const char *pid_file = NULL;
3125     const char *incoming = NULL;
3126     bool defconfig = true;
3127     bool userconfig = true;
3128     bool nographic = false;
3129     DisplayType display_type = DT_DEFAULT;
3130     int display_remote = 0;
3131     const char *log_mask = NULL;
3132     const char *log_file = NULL;
3133     char *trace_file = NULL;
3134     ram_addr_t maxram_size;
3135     uint64_t ram_slots = 0;
3136     FILE *vmstate_dump_file = NULL;
3137     Error *main_loop_err = NULL;
3138     Error *err = NULL;
3139     bool list_data_dirs = false;
3140 #ifdef CONFIG_YAGL
3141     static bool yagl_enabled = false;
3142 #endif /* CONFIG_YAGL */
3143 #ifdef CONFIG_VIGS
3144     static bool vigs_enabled = false;
3145     static char *vigs_backend = NULL;
3146 #endif /* CONFIG_VIGS */
3147
3148     module_call_init(MODULE_INIT_TRACE);
3149
3150     qemu_init_cpu_list();
3151     qemu_init_cpu_loop();
3152     qemu_mutex_lock_iothread();
3153
3154     atexit(qemu_run_exit_notifiers);
3155     error_set_progname(argv[0]);
3156     qemu_init_exec_dir(argv[0]);
3157
3158     module_call_init(MODULE_INIT_QOM);
3159     module_call_init(MODULE_INIT_QAPI);
3160
3161     qemu_add_opts(&qemu_drive_opts);
3162     qemu_add_drive_opts(&qemu_legacy_drive_opts);
3163     qemu_add_drive_opts(&qemu_common_drive_opts);
3164     qemu_add_drive_opts(&qemu_drive_opts);
3165     qemu_add_drive_opts(&bdrv_runtime_opts);
3166     qemu_add_opts(&qemu_chardev_opts);
3167     qemu_add_opts(&qemu_device_opts);
3168     qemu_add_opts(&qemu_netdev_opts);
3169     qemu_add_opts(&qemu_net_opts);
3170     qemu_add_opts(&qemu_rtc_opts);
3171     qemu_add_opts(&qemu_global_opts);
3172     qemu_add_opts(&qemu_mon_opts);
3173     qemu_add_opts(&qemu_trace_opts);
3174     qemu_add_opts(&qemu_option_rom_opts);
3175     qemu_add_opts(&qemu_machine_opts);
3176     qemu_add_opts(&qemu_mem_opts);
3177     qemu_add_opts(&qemu_smp_opts);
3178     qemu_add_opts(&qemu_boot_opts);
3179     qemu_add_opts(&qemu_sandbox_opts);
3180     qemu_add_opts(&qemu_add_fd_opts);
3181     qemu_add_opts(&qemu_object_opts);
3182     qemu_add_opts(&qemu_tpmdev_opts);
3183     qemu_add_opts(&qemu_realtime_opts);
3184     qemu_add_opts(&qemu_msg_opts);
3185     qemu_add_opts(&qemu_name_opts);
3186     qemu_add_opts(&qemu_numa_opts);
3187     qemu_add_opts(&qemu_icount_opts);
3188     qemu_add_opts(&qemu_semihosting_config_opts);
3189     qemu_add_opts(&qemu_fw_cfg_opts);
3190 #ifdef CONFIG_LIBISCSI
3191     qemu_add_opts(&qemu_iscsi_opts);
3192 #endif
3193     module_call_init(MODULE_INIT_OPTS);
3194
3195     runstate_init();
3196
3197     if (qcrypto_init(&err) < 0) {
3198         error_reportf_err(err, "cannot initialize crypto: ");
3199         exit(1);
3200     }
3201     rtc_clock = QEMU_CLOCK_HOST;
3202
3203     QLIST_INIT (&vm_change_state_head);
3204     os_setup_early_signal_handling();
3205
3206     cpu_model = NULL;
3207     snapshot = 0;
3208     cyls = heads = secs = 0;
3209     translation = BIOS_ATA_TRANSLATION_AUTO;
3210
3211     nb_nics = 0;
3212
3213     bdrv_init_with_whitelist();
3214
3215     autostart = 1;
3216
3217     /* first pass of option parsing */
3218     optind = 1;
3219     while (optind < argc) {
3220         if (argv[optind][0] != '-') {
3221             /* disk image */
3222             optind++;
3223         } else {
3224             const QEMUOption *popt;
3225
3226             popt = lookup_opt(argc, argv, &optarg, &optind);
3227             switch (popt->index) {
3228             case QEMU_OPTION_nodefconfig:
3229                 defconfig = false;
3230                 break;
3231             case QEMU_OPTION_nouserconfig:
3232                 userconfig = false;
3233                 break;
3234             }
3235         }
3236     }
3237
3238     if (defconfig) {
3239         int ret;
3240         ret = qemu_read_default_config_files(userconfig);
3241         if (ret < 0) {
3242             exit(1);
3243         }
3244     }
3245
3246     /* second pass of option parsing */
3247     optind = 1;
3248     for(;;) {
3249         if (optind >= argc)
3250             break;
3251         if (argv[optind][0] != '-') {
3252             hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
3253         } else {
3254             const QEMUOption *popt;
3255
3256             popt = lookup_opt(argc, argv, &optarg, &optind);
3257             if (!(popt->arch_mask & arch_type)) {
3258                 error_report("Option not supported for this target");
3259                 exit(1);
3260             }
3261             switch(popt->index) {
3262             case QEMU_OPTION_no_kvm_irqchip: {
3263                 olist = qemu_find_opts("machine");
3264                 qemu_opts_parse_noisily(olist, "kernel_irqchip=off", false);
3265                 break;
3266             }
3267             case QEMU_OPTION_cpu:
3268                 /* hw initialization will check this */
3269                 cpu_model = optarg;
3270                 break;
3271             case QEMU_OPTION_hda:
3272                 {
3273                     char buf[256];
3274                     if (cyls == 0)
3275                         snprintf(buf, sizeof(buf), "%s", HD_OPTS);
3276                     else
3277                         snprintf(buf, sizeof(buf),
3278                                  "%s,cyls=%d,heads=%d,secs=%d%s",
3279                                  HD_OPTS , cyls, heads, secs,
3280                                  translation == BIOS_ATA_TRANSLATION_LBA ?
3281                                  ",trans=lba" :
3282                                  translation == BIOS_ATA_TRANSLATION_NONE ?
3283                                  ",trans=none" : "");
3284                     drive_add(IF_DEFAULT, 0, optarg, buf);
3285                     break;
3286                 }
3287             case QEMU_OPTION_hdb:
3288             case QEMU_OPTION_hdc:
3289             case QEMU_OPTION_hdd:
3290                 drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
3291                           HD_OPTS);
3292                 break;
3293             case QEMU_OPTION_drive:
3294                 if (drive_def(optarg) == NULL) {
3295                     exit(1);
3296                 }
3297                 break;
3298             case QEMU_OPTION_set:
3299                 if (qemu_set_option(optarg) != 0)
3300                     exit(1);
3301                 break;
3302             case QEMU_OPTION_global:
3303                 if (qemu_global_option(optarg) != 0)
3304                     exit(1);
3305                 break;
3306             case QEMU_OPTION_mtdblock:
3307                 drive_add(IF_MTD, -1, optarg, MTD_OPTS);
3308                 break;
3309             case QEMU_OPTION_sd:
3310                 drive_add(IF_SD, -1, optarg, SD_OPTS);
3311                 break;
3312             case QEMU_OPTION_pflash:
3313                 drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
3314                 break;
3315             case QEMU_OPTION_snapshot:
3316                 snapshot = 1;
3317                 break;
3318             case QEMU_OPTION_hdachs:
3319                 {
3320                     const char *p;
3321                     p = optarg;
3322                     cyls = strtol(p, (char **)&p, 0);
3323                     if (cyls < 1 || cyls > 16383)
3324                         goto chs_fail;
3325                     if (*p != ',')
3326                         goto chs_fail;
3327                     p++;
3328                     heads = strtol(p, (char **)&p, 0);
3329                     if (heads < 1 || heads > 16)
3330                         goto chs_fail;
3331                     if (*p != ',')
3332                         goto chs_fail;
3333                     p++;
3334                     secs = strtol(p, (char **)&p, 0);
3335                     if (secs < 1 || secs > 63)
3336                         goto chs_fail;
3337                     if (*p == ',') {
3338                         p++;
3339                         if (!strcmp(p, "large")) {
3340                             translation = BIOS_ATA_TRANSLATION_LARGE;
3341                         } else if (!strcmp(p, "rechs")) {
3342                             translation = BIOS_ATA_TRANSLATION_RECHS;
3343                         } else if (!strcmp(p, "none")) {
3344                             translation = BIOS_ATA_TRANSLATION_NONE;
3345                         } else if (!strcmp(p, "lba")) {
3346                             translation = BIOS_ATA_TRANSLATION_LBA;
3347                         } else if (!strcmp(p, "auto")) {
3348                             translation = BIOS_ATA_TRANSLATION_AUTO;
3349                         } else {
3350                             goto chs_fail;
3351                         }
3352                     } else if (*p != '\0') {
3353                     chs_fail:
3354                         error_report("invalid physical CHS format");
3355                         exit(1);
3356                     }
3357                     if (hda_opts != NULL) {
3358                         qemu_opt_set_number(hda_opts, "cyls", cyls,
3359                                             &error_abort);
3360                         qemu_opt_set_number(hda_opts, "heads", heads,
3361                                             &error_abort);
3362                         qemu_opt_set_number(hda_opts, "secs", secs,
3363                                             &error_abort);
3364                         if (translation == BIOS_ATA_TRANSLATION_LARGE) {
3365                             qemu_opt_set(hda_opts, "trans", "large",
3366                                          &error_abort);
3367                         } else if (translation == BIOS_ATA_TRANSLATION_RECHS) {
3368                             qemu_opt_set(hda_opts, "trans", "rechs",
3369                                          &error_abort);
3370                         } else if (translation == BIOS_ATA_TRANSLATION_LBA) {
3371                             qemu_opt_set(hda_opts, "trans", "lba",
3372                                          &error_abort);
3373                         } else if (translation == BIOS_ATA_TRANSLATION_NONE) {
3374                             qemu_opt_set(hda_opts, "trans", "none",
3375                                          &error_abort);
3376                         }
3377                     }
3378                 }
3379                 break;
3380             case QEMU_OPTION_numa:
3381                 opts = qemu_opts_parse_noisily(qemu_find_opts("numa"),
3382                                                optarg, true);
3383                 if (!opts) {
3384                     exit(1);
3385                 }
3386                 break;
3387             case QEMU_OPTION_display:
3388                 display_type = select_display(optarg);
3389                 break;
3390             case QEMU_OPTION_nographic:
3391                 olist = qemu_find_opts("machine");
3392                 qemu_opts_parse_noisily(olist, "graphics=off", false);
3393                 nographic = true;
3394                 display_type = DT_NONE;
3395                 break;
3396             case QEMU_OPTION_curses:
3397 #ifdef CONFIG_CURSES
3398                 display_type = DT_CURSES;
3399 #else
3400                 error_report("curses support is disabled");
3401                 exit(1);
3402 #endif
3403                 break;
3404             case QEMU_OPTION_portrait:
3405                 graphic_rotate = 90;
3406                 break;
3407             case QEMU_OPTION_rotate:
3408                 graphic_rotate = strtol(optarg, (char **) &optarg, 10);
3409                 if (graphic_rotate != 0 && graphic_rotate != 90 &&
3410                     graphic_rotate != 180 && graphic_rotate != 270) {
3411                     error_report("only 90, 180, 270 deg rotation is available");
3412                     exit(1);
3413                 }
3414                 break;
3415             case QEMU_OPTION_kernel:
3416                 qemu_opts_set(qemu_find_opts("machine"), 0, "kernel", optarg,
3417                               &error_abort);
3418                 break;
3419             case QEMU_OPTION_initrd:
3420                 qemu_opts_set(qemu_find_opts("machine"), 0, "initrd", optarg,
3421                               &error_abort);
3422                 break;
3423             case QEMU_OPTION_append:
3424                 qemu_opts_set(qemu_find_opts("machine"), 0, "append", optarg,
3425                               &error_abort);
3426                 break;
3427             case QEMU_OPTION_dtb:
3428                 qemu_opts_set(qemu_find_opts("machine"), 0, "dtb", optarg,
3429                               &error_abort);
3430                 break;
3431             case QEMU_OPTION_cdrom:
3432                 drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
3433                 break;
3434             case QEMU_OPTION_boot:
3435                 opts = qemu_opts_parse_noisily(qemu_find_opts("boot-opts"),
3436                                                optarg, true);
3437                 if (!opts) {
3438                     exit(1);
3439                 }
3440                 break;
3441             case QEMU_OPTION_fda:
3442             case QEMU_OPTION_fdb:
3443                 drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
3444                           optarg, FD_OPTS);
3445                 break;
3446             case QEMU_OPTION_no_fd_bootchk:
3447                 fd_bootchk = 0;
3448                 break;
3449             case QEMU_OPTION_netdev:
3450                 default_net = 0;
3451                 if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
3452                     exit(1);
3453                 }
3454                 break;
3455             case QEMU_OPTION_net:
3456                 default_net = 0;
3457                 if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
3458                     exit(1);
3459                 }
3460                 break;
3461 #ifdef CONFIG_LIBISCSI
3462             case QEMU_OPTION_iscsi:
3463                 opts = qemu_opts_parse_noisily(qemu_find_opts("iscsi"),
3464                                                optarg, false);
3465                 if (!opts) {
3466                     exit(1);
3467                 }
3468                 break;
3469 #endif
3470 #ifdef CONFIG_SLIRP
3471             case QEMU_OPTION_tftp:
3472                 error_report("The -tftp option is deprecated. "
3473                              "Please use '-netdev user,tftp=...' instead.");
3474                 legacy_tftp_prefix = optarg;
3475                 break;
3476             case QEMU_OPTION_bootp:
3477                 error_report("The -bootp option is deprecated. "
3478                              "Please use '-netdev user,bootfile=...' instead.");
3479                 legacy_bootp_filename = optarg;
3480                 break;
3481             case QEMU_OPTION_redir:
3482                 error_report("The -redir option is deprecated. "
3483                              "Please use '-netdev user,hostfwd=...' instead.");
3484                 if (net_slirp_redir(optarg) < 0)
3485                     exit(1);
3486                 break;
3487 #endif
3488             case QEMU_OPTION_bt:
3489                 add_device_config(DEV_BT, optarg);
3490                 break;
3491             case QEMU_OPTION_audio_help:
3492                 AUD_help ();
3493                 exit (0);
3494                 break;
3495             case QEMU_OPTION_soundhw:
3496                 select_soundhw (optarg);
3497                 break;
3498             case QEMU_OPTION_h:
3499                 help(0);
3500                 break;
3501             case QEMU_OPTION_version:
3502                 version();
3503                 exit(0);
3504                 break;
3505             case QEMU_OPTION_m:
3506                 opts = qemu_opts_parse_noisily(qemu_find_opts("memory"),
3507                                                optarg, true);
3508                 if (!opts) {
3509                     exit(EXIT_FAILURE);
3510                 }
3511                 break;
3512 #ifdef CONFIG_TPM
3513             case QEMU_OPTION_tpmdev:
3514                 if (tpm_config_parse(qemu_find_opts("tpmdev"), optarg) < 0) {
3515                     exit(1);
3516                 }
3517                 break;
3518 #endif
3519             case QEMU_OPTION_mempath:
3520                 mem_path = optarg;
3521                 break;
3522             case QEMU_OPTION_mem_prealloc:
3523                 mem_prealloc = 1;
3524                 break;
3525             case QEMU_OPTION_d:
3526                 log_mask = optarg;
3527                 break;
3528             case QEMU_OPTION_D:
3529                 log_file = optarg;
3530                 break;
3531             case QEMU_OPTION_DFILTER:
3532                 qemu_set_dfilter_ranges(optarg, &error_fatal);
3533                 break;
3534             case QEMU_OPTION_s:
3535                 add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
3536                 break;
3537             case QEMU_OPTION_gdb:
3538                 add_device_config(DEV_GDB, optarg);
3539                 break;
3540             case QEMU_OPTION_L:
3541                 if (is_help_option(optarg)) {
3542                     list_data_dirs = true;
3543                 } else if (data_dir_idx < ARRAY_SIZE(data_dir)) {
3544                     data_dir[data_dir_idx++] = optarg;
3545                 }
3546                 break;
3547             case QEMU_OPTION_bios:
3548                 qemu_opts_set(qemu_find_opts("machine"), 0, "firmware", optarg,
3549                               &error_abort);
3550                 break;
3551             case QEMU_OPTION_singlestep:
3552                 singlestep = 1;
3553                 break;
3554             case QEMU_OPTION_S:
3555                 autostart = 0;
3556                 break;
3557             case QEMU_OPTION_k:
3558                 keyboard_layout = optarg;
3559                 break;
3560             case QEMU_OPTION_localtime:
3561                 rtc_utc = 0;
3562                 break;
3563             case QEMU_OPTION_vga:
3564                 vga_model = optarg;
3565                 default_vga = 0;
3566                 break;
3567             case QEMU_OPTION_g:
3568                 {
3569                     const char *p;
3570                     int w, h, depth;
3571                     p = optarg;
3572                     w = strtol(p, (char **)&p, 10);
3573                     if (w <= 0) {
3574                     graphic_error:
3575                         error_report("invalid resolution or depth");
3576                         exit(1);
3577                     }
3578                     if (*p != 'x')
3579                         goto graphic_error;
3580                     p++;
3581                     h = strtol(p, (char **)&p, 10);
3582                     if (h <= 0)
3583                         goto graphic_error;
3584                     if (*p == 'x') {
3585                         p++;
3586                         depth = strtol(p, (char **)&p, 10);
3587                         if (depth != 8 && depth != 15 && depth != 16 &&
3588                             depth != 24 && depth != 32)
3589                             goto graphic_error;
3590                     } else if (*p == '\0') {
3591                         depth = graphic_depth;
3592                     } else {
3593                         goto graphic_error;
3594                     }
3595
3596                     graphic_width = w;
3597                     graphic_height = h;
3598                     graphic_depth = depth;
3599                 }
3600                 break;
3601             case QEMU_OPTION_echr:
3602                 {
3603                     char *r;
3604                     term_escape_char = strtol(optarg, &r, 0);
3605                     if (r == optarg)
3606                         printf("Bad argument to echr\n");
3607                     break;
3608                 }
3609             case QEMU_OPTION_monitor:
3610                 default_monitor = 0;
3611                 if (strncmp(optarg, "none", 4)) {
3612                     monitor_parse(optarg, "readline", false);
3613                 }
3614                 break;
3615             case QEMU_OPTION_qmp:
3616                 monitor_parse(optarg, "control", false);
3617                 default_monitor = 0;
3618                 break;
3619             case QEMU_OPTION_qmp_pretty:
3620                 monitor_parse(optarg, "control", true);
3621                 default_monitor = 0;
3622                 break;
3623             case QEMU_OPTION_mon:
3624                 opts = qemu_opts_parse_noisily(qemu_find_opts("mon"), optarg,
3625                                                true);
3626                 if (!opts) {
3627                     exit(1);
3628                 }
3629                 default_monitor = 0;
3630                 break;
3631             case QEMU_OPTION_chardev:
3632                 opts = qemu_opts_parse_noisily(qemu_find_opts("chardev"),
3633                                                optarg, true);
3634                 if (!opts) {
3635                     exit(1);
3636                 }
3637                 break;
3638             case QEMU_OPTION_fsdev:
3639                 olist = qemu_find_opts("fsdev");
3640                 if (!olist) {
3641                     error_report("fsdev support is disabled");
3642                     exit(1);
3643                 }
3644                 opts = qemu_opts_parse_noisily(olist, optarg, true);
3645                 if (!opts) {
3646                     exit(1);
3647                 }
3648                 break;
3649             case QEMU_OPTION_virtfs: {
3650                 QemuOpts *fsdev;
3651                 QemuOpts *device;
3652                 const char *writeout, *sock_fd, *socket;
3653
3654                 olist = qemu_find_opts("virtfs");
3655                 if (!olist) {
3656                     error_report("virtfs support is disabled");
3657                     exit(1);
3658                 }
3659                 opts = qemu_opts_parse_noisily(olist, optarg, true);
3660                 if (!opts) {
3661                     exit(1);
3662                 }
3663
3664                 if (qemu_opt_get(opts, "fsdriver") == NULL ||
3665                     qemu_opt_get(opts, "mount_tag") == NULL) {
3666                     error_report("Usage: -virtfs fsdriver,mount_tag=tag");
3667                     exit(1);
3668                 }
3669                 fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
3670                                          qemu_opt_get(opts, "mount_tag"),
3671                                          1, NULL);
3672                 if (!fsdev) {
3673                     error_report("duplicate fsdev id: %s",
3674                                  qemu_opt_get(opts, "mount_tag"));
3675                     exit(1);
3676                 }
3677
3678                 writeout = qemu_opt_get(opts, "writeout");
3679                 if (writeout) {
3680 #ifdef CONFIG_SYNC_FILE_RANGE
3681                     qemu_opt_set(fsdev, "writeout", writeout, &error_abort);
3682 #else
3683                     error_report("writeout=immediate not supported "
3684                                  "on this platform");
3685                     exit(1);
3686 #endif
3687                 }
3688                 qemu_opt_set(fsdev, "fsdriver",
3689                              qemu_opt_get(opts, "fsdriver"), &error_abort);
3690                 qemu_opt_set(fsdev, "path", qemu_opt_get(opts, "path"),
3691                              &error_abort);
3692                 qemu_opt_set(fsdev, "security_model",
3693                              qemu_opt_get(opts, "security_model"),
3694                              &error_abort);
3695                 socket = qemu_opt_get(opts, "socket");
3696                 if (socket) {
3697                     qemu_opt_set(fsdev, "socket", socket, &error_abort);
3698                 }
3699                 sock_fd = qemu_opt_get(opts, "sock_fd");
3700                 if (sock_fd) {
3701                     qemu_opt_set(fsdev, "sock_fd", sock_fd, &error_abort);
3702                 }
3703
3704                 qemu_opt_set_bool(fsdev, "readonly",
3705                                   qemu_opt_get_bool(opts, "readonly", 0),
3706                                   &error_abort);
3707                 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3708                                           &error_abort);
3709                 qemu_opt_set(device, "driver", "virtio-9p-pci", &error_abort);
3710                 qemu_opt_set(device, "fsdev",
3711                              qemu_opt_get(opts, "mount_tag"), &error_abort);
3712                 qemu_opt_set(device, "mount_tag",
3713                              qemu_opt_get(opts, "mount_tag"), &error_abort);
3714                 break;
3715             }
3716             case QEMU_OPTION_virtfs_synth: {
3717                 QemuOpts *fsdev;
3718                 QemuOpts *device;
3719
3720                 fsdev = qemu_opts_create(qemu_find_opts("fsdev"), "v_synth",
3721                                          1, NULL);
3722                 if (!fsdev) {
3723                     error_report("duplicate option: %s", "virtfs_synth");
3724                     exit(1);
3725                 }
3726                 qemu_opt_set(fsdev, "fsdriver", "synth", &error_abort);
3727
3728                 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3729                                           &error_abort);
3730                 qemu_opt_set(device, "driver", "virtio-9p-pci", &error_abort);
3731                 qemu_opt_set(device, "fsdev", "v_synth", &error_abort);
3732                 qemu_opt_set(device, "mount_tag", "v_synth", &error_abort);
3733                 break;
3734             }
3735             case QEMU_OPTION_serial:
3736                 add_device_config(DEV_SERIAL, optarg);
3737                 default_serial = 0;
3738                 if (strncmp(optarg, "mon:", 4) == 0) {
3739                     default_monitor = 0;
3740                 }
3741                 break;
3742             case QEMU_OPTION_watchdog:
3743                 if (watchdog) {
3744                     error_report("only one watchdog option may be given");
3745                     return 1;
3746                 }
3747                 watchdog = optarg;
3748                 break;
3749             case QEMU_OPTION_watchdog_action:
3750                 if (select_watchdog_action(optarg) == -1) {
3751                     error_report("unknown -watchdog-action parameter");
3752                     exit(1);
3753                 }
3754                 break;
3755             case QEMU_OPTION_virtiocon:
3756                 add_device_config(DEV_VIRTCON, optarg);
3757                 default_virtcon = 0;
3758                 if (strncmp(optarg, "mon:", 4) == 0) {
3759                     default_monitor = 0;
3760                 }
3761                 break;
3762             case QEMU_OPTION_parallel:
3763                 add_device_config(DEV_PARALLEL, optarg);
3764                 default_parallel = 0;
3765                 if (strncmp(optarg, "mon:", 4) == 0) {
3766                     default_monitor = 0;
3767                 }
3768                 break;
3769             case QEMU_OPTION_debugcon:
3770                 add_device_config(DEV_DEBUGCON, optarg);
3771                 break;
3772             case QEMU_OPTION_loadvm:
3773                 loadvm = optarg;
3774                 break;
3775             case QEMU_OPTION_full_screen:
3776                 full_screen = 1;
3777                 break;
3778             case QEMU_OPTION_no_frame:
3779                 no_frame = 1;
3780                 break;
3781             case QEMU_OPTION_alt_grab:
3782                 alt_grab = 1;
3783                 break;
3784             case QEMU_OPTION_ctrl_grab:
3785                 ctrl_grab = 1;
3786                 break;
3787             case QEMU_OPTION_no_quit:
3788                 no_quit = 1;
3789                 break;
3790             case QEMU_OPTION_sdl:
3791 #ifdef CONFIG_SDL
3792                 display_type = DT_SDL;
3793                 break;
3794 #else
3795                 error_report("SDL support is disabled");
3796                 exit(1);
3797 #endif
3798             case QEMU_OPTION_pidfile:
3799                 pid_file = optarg;
3800                 break;
3801             case QEMU_OPTION_win2k_hack:
3802                 win2k_install_hack = 1;
3803                 break;
3804             case QEMU_OPTION_rtc_td_hack: {
3805                 static GlobalProperty slew_lost_ticks = {
3806                     .driver   = "mc146818rtc",
3807                     .property = "lost_tick_policy",
3808                     .value    = "slew",
3809                 };
3810
3811                 qdev_prop_register_global(&slew_lost_ticks);
3812                 break;
3813             }
3814             case QEMU_OPTION_acpitable:
3815                 opts = qemu_opts_parse_noisily(qemu_find_opts("acpi"),
3816                                                optarg, true);
3817                 if (!opts) {
3818                     exit(1);
3819                 }
3820                 do_acpitable_option(opts);
3821                 break;
3822             case QEMU_OPTION_smbios:
3823                 opts = qemu_opts_parse_noisily(qemu_find_opts("smbios"),
3824                                                optarg, false);
3825                 if (!opts) {
3826                     exit(1);
3827                 }
3828                 do_smbios_option(opts);
3829                 break;
3830             case QEMU_OPTION_fwcfg:
3831                 opts = qemu_opts_parse_noisily(qemu_find_opts("fw_cfg"),
3832                                                optarg, true);
3833                 if (opts == NULL) {
3834                     exit(1);
3835                 }
3836                 break;
3837             case QEMU_OPTION_enable_kvm:
3838                 olist = qemu_find_opts("machine");
3839                 qemu_opts_parse_noisily(olist, "accel=kvm", false);
3840                 break;
3841            case QEMU_OPTION_enable_yagl:
3842 #if defined(CONFIG_YAGL)
3843                 yagl_enabled = true;
3844 #else
3845                 fprintf(stderr, "YaGL openGLES passthrough support is disabled,"
3846                     " ignoring -enable-yagl\n");
3847 #endif
3848                 break;
3849            case QEMU_OPTION_enable_vigs:
3850 #if defined(CONFIG_VIGS)
3851                 vigs_enabled = true;
3852 #else
3853                 fprintf(stderr, "VIGS support is disabled,"
3854                     " ignoring -enable-vigs\n");
3855 #endif
3856                 break;
3857            case QEMU_OPTION_vigs_backend:
3858 #if defined(CONFIG_VIGS)
3859                 vigs_backend = g_strdup(optarg);
3860 #else
3861                 fprintf(stderr, "VIGS support is disabled,"
3862                     " ignoring -vigs-backend\n");
3863 #endif
3864                 break;
3865             case QEMU_OPTION_M:
3866             case QEMU_OPTION_machine:
3867                 olist = qemu_find_opts("machine");
3868                 opts = qemu_opts_parse_noisily(olist, optarg, true);
3869                 if (!opts) {
3870                     exit(1);
3871                 }
3872                 break;
3873              case QEMU_OPTION_no_kvm:
3874                 olist = qemu_find_opts("machine");
3875                 qemu_opts_parse_noisily(olist, "accel=tcg", false);
3876                 break;
3877             case QEMU_OPTION_no_kvm_pit: {
3878                 error_report("warning: ignoring deprecated option");
3879                 break;
3880             }
3881             case QEMU_OPTION_no_kvm_pit_reinjection: {
3882                 static GlobalProperty kvm_pit_lost_tick_policy = {
3883                     .driver   = "kvm-pit",
3884                     .property = "lost_tick_policy",
3885                     .value    = "discard",
3886                 };
3887
3888                 error_report("warning: deprecated, replaced by "
3889                              "-global kvm-pit.lost_tick_policy=discard");
3890                 qdev_prop_register_global(&kvm_pit_lost_tick_policy);
3891                 break;
3892             }
3893             case QEMU_OPTION_usb:
3894                 olist = qemu_find_opts("machine");
3895                 qemu_opts_parse_noisily(olist, "usb=on", false);
3896                 break;
3897             case QEMU_OPTION_usbdevice:
3898                 olist = qemu_find_opts("machine");
3899                 qemu_opts_parse_noisily(olist, "usb=on", false);
3900                 add_device_config(DEV_USB, optarg);
3901                 break;
3902             case QEMU_OPTION_device:
3903                 if (!qemu_opts_parse_noisily(qemu_find_opts("device"),
3904                                              optarg, true)) {
3905                     exit(1);
3906                 }
3907                 break;
3908             case QEMU_OPTION_smp:
3909                 if (!qemu_opts_parse_noisily(qemu_find_opts("smp-opts"),
3910                                              optarg, true)) {
3911                     exit(1);
3912                 }
3913                 break;
3914             case QEMU_OPTION_vnc:
3915                 vnc_parse(optarg, &error_fatal);
3916                 break;
3917             case QEMU_OPTION_no_acpi:
3918                 acpi_enabled = 0;
3919                 break;
3920             case QEMU_OPTION_no_hpet:
3921                 no_hpet = 1;
3922                 break;
3923             case QEMU_OPTION_balloon:
3924                 if (balloon_parse(optarg) < 0) {
3925                     error_report("unknown -balloon argument %s", optarg);
3926                     exit(1);
3927                 }
3928                 break;
3929             case QEMU_OPTION_no_reboot:
3930                 no_reboot = 1;
3931                 break;
3932             case QEMU_OPTION_no_shutdown:
3933                 no_shutdown = 1;
3934                 break;
3935             case QEMU_OPTION_show_cursor:
3936                 cursor_hide = 0;
3937                 break;
3938             case QEMU_OPTION_uuid:
3939                 if (qemu_uuid_parse(optarg, &qemu_uuid) < 0) {
3940                     error_report("failed to parse UUID string: wrong format");
3941                     exit(1);
3942                 }
3943                 qemu_uuid_set = true;
3944                 break;
3945             case QEMU_OPTION_option_rom:
3946                 if (nb_option_roms >= MAX_OPTION_ROMS) {
3947                     error_report("too many option ROMs");
3948                     exit(1);
3949                 }
3950                 opts = qemu_opts_parse_noisily(qemu_find_opts("option-rom"),
3951                                                optarg, true);
3952                 if (!opts) {
3953                     exit(1);
3954                 }
3955                 option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
3956                 option_rom[nb_option_roms].bootindex =
3957                     qemu_opt_get_number(opts, "bootindex", -1);
3958                 if (!option_rom[nb_option_roms].name) {
3959                     error_report("Option ROM file is not specified");
3960                     exit(1);
3961                 }
3962                 nb_option_roms++;
3963                 break;
3964             case QEMU_OPTION_semihosting:
3965                 semihosting.enabled = true;
3966                 semihosting.target = SEMIHOSTING_TARGET_AUTO;
3967                 break;
3968             case QEMU_OPTION_semihosting_config:
3969                 semihosting.enabled = true;
3970                 opts = qemu_opts_parse_noisily(qemu_find_opts("semihosting-config"),
3971                                                optarg, false);
3972                 if (opts != NULL) {
3973                     semihosting.enabled = qemu_opt_get_bool(opts, "enable",
3974                                                             true);
3975                     const char *target = qemu_opt_get(opts, "target");
3976                     if (target != NULL) {
3977                         if (strcmp("native", target) == 0) {
3978                             semihosting.target = SEMIHOSTING_TARGET_NATIVE;
3979                         } else if (strcmp("gdb", target) == 0) {
3980                             semihosting.target = SEMIHOSTING_TARGET_GDB;
3981                         } else  if (strcmp("auto", target) == 0) {
3982                             semihosting.target = SEMIHOSTING_TARGET_AUTO;
3983                         } else {
3984                             error_report("unsupported semihosting-config %s",
3985                                          optarg);
3986                             exit(1);
3987                         }
3988                     } else {
3989                         semihosting.target = SEMIHOSTING_TARGET_AUTO;
3990                     }
3991                     /* Set semihosting argument count and vector */
3992                     qemu_opt_foreach(opts, add_semihosting_arg,
3993                                      &semihosting, NULL);
3994                 } else {
3995                     error_report("unsupported semihosting-config %s", optarg);
3996                     exit(1);
3997                 }
3998                 break;
3999             case QEMU_OPTION_tdf:
4000                 error_report("warning: ignoring deprecated option");
4001                 break;
4002             case QEMU_OPTION_name:
4003                 opts = qemu_opts_parse_noisily(qemu_find_opts("name"),
4004                                                optarg, true);
4005                 if (!opts) {
4006                     exit(1);
4007                 }
4008                 break;
4009             case QEMU_OPTION_prom_env:
4010                 if (nb_prom_envs >= MAX_PROM_ENVS) {
4011                     error_report("too many prom variables");
4012                     exit(1);
4013                 }
4014                 prom_envs[nb_prom_envs] = optarg;
4015                 nb_prom_envs++;
4016                 break;
4017             case QEMU_OPTION_old_param:
4018                 old_param = 1;
4019                 break;
4020             case QEMU_OPTION_clock:
4021                 /* Clock options no longer exist.  Keep this option for
4022                  * backward compatibility.
4023                  */
4024                 break;
4025             case QEMU_OPTION_startdate:
4026                 configure_rtc_date_offset(optarg, 1);
4027                 break;
4028             case QEMU_OPTION_rtc:
4029                 opts = qemu_opts_parse_noisily(qemu_find_opts("rtc"), optarg,
4030                                                false);
4031                 if (!opts) {
4032                     exit(1);
4033                 }
4034                 configure_rtc(opts);
4035                 break;
4036             case QEMU_OPTION_tb_size:
4037                 tcg_tb_size = strtol(optarg, NULL, 0);
4038                 if (tcg_tb_size < 0) {
4039                     tcg_tb_size = 0;
4040                 }
4041                 break;
4042             case QEMU_OPTION_icount:
4043                 icount_opts = qemu_opts_parse_noisily(qemu_find_opts("icount"),
4044                                                       optarg, true);
4045                 if (!icount_opts) {
4046                     exit(1);
4047                 }
4048                 break;
4049             case QEMU_OPTION_incoming:
4050                 if (!incoming) {
4051                     runstate_set(RUN_STATE_INMIGRATE);
4052                 }
4053                 incoming = optarg;
4054                 break;
4055             case QEMU_OPTION_nodefaults:
4056                 has_defaults = 0;
4057                 break;
4058             case QEMU_OPTION_xen_domid:
4059                 if (!(xen_available())) {
4060                     error_report("Option not supported for this target");
4061                     exit(1);
4062                 }
4063                 xen_domid = atoi(optarg);
4064                 break;
4065             case QEMU_OPTION_xen_create:
4066                 if (!(xen_available())) {
4067                     error_report("Option not supported for this target");
4068                     exit(1);
4069                 }
4070                 xen_mode = XEN_CREATE;
4071                 break;
4072             case QEMU_OPTION_xen_attach:
4073                 if (!(xen_available())) {
4074                     error_report("Option not supported for this target");
4075                     exit(1);
4076                 }
4077                 xen_mode = XEN_ATTACH;
4078                 break;
4079             case QEMU_OPTION_trace:
4080                 g_free(trace_file);
4081                 trace_file = trace_opt_parse(optarg);
4082                 break;
4083             case QEMU_OPTION_readconfig:
4084                 {
4085                     int ret = qemu_read_config_file(optarg);
4086                     if (ret < 0) {
4087                         error_report("read config %s: %s", optarg,
4088                                      strerror(-ret));
4089                         exit(1);
4090                     }
4091                     break;
4092                 }
4093             case QEMU_OPTION_spice:
4094                 olist = qemu_find_opts("spice");
4095                 if (!olist) {
4096                     error_report("spice support is disabled");
4097                     exit(1);
4098                 }
4099                 opts = qemu_opts_parse_noisily(olist, optarg, false);
4100                 if (!opts) {
4101                     exit(1);
4102                 }
4103                 display_remote++;
4104                 break;
4105             case QEMU_OPTION_writeconfig:
4106                 {
4107                     FILE *fp;
4108                     if (strcmp(optarg, "-") == 0) {
4109                         fp = stdout;
4110                     } else {
4111                         fp = fopen(optarg, "w");
4112                         if (fp == NULL) {
4113                             error_report("open %s: %s", optarg,
4114                                          strerror(errno));
4115                             exit(1);
4116                         }
4117                     }
4118                     qemu_config_write(fp);
4119                     if (fp != stdout) {
4120                         fclose(fp);
4121                     }
4122                     break;
4123                 }
4124             case QEMU_OPTION_qtest:
4125                 qtest_chrdev = optarg;
4126                 break;
4127             case QEMU_OPTION_qtest_log:
4128                 qtest_log = optarg;
4129                 break;
4130             case QEMU_OPTION_sandbox:
4131                 opts = qemu_opts_parse_noisily(qemu_find_opts("sandbox"),
4132                                                optarg, true);
4133                 if (!opts) {
4134                     exit(1);
4135                 }
4136                 break;
4137             case QEMU_OPTION_enable_hax:
4138                 olist = qemu_find_opts("machine");
4139                 qemu_opts_parse_noisily(olist, "accel=hax", false);
4140                 break;
4141             case QEMU_OPTION_add_fd:
4142 #ifndef _WIN32
4143                 opts = qemu_opts_parse_noisily(qemu_find_opts("add-fd"),
4144                                                optarg, false);
4145                 if (!opts) {
4146                     exit(1);
4147                 }
4148 #else
4149                 error_report("File descriptor passing is disabled on this "
4150                              "platform");
4151                 exit(1);
4152 #endif
4153                 break;
4154 #if defined(CONFIG_MARU)
4155             case QEMU_OPTION_enable_suspend:
4156                 ecs_set_suspend_state(SUSPEND_UNLOCK);
4157                 break;
4158 #endif
4159             case QEMU_OPTION_object:
4160                 opts = qemu_opts_parse_noisily(qemu_find_opts("object"),
4161                                                optarg, true);
4162                 if (!opts) {
4163                     exit(1);
4164                 }
4165                 break;
4166             case QEMU_OPTION_realtime:
4167                 opts = qemu_opts_parse_noisily(qemu_find_opts("realtime"),
4168                                                optarg, false);
4169                 if (!opts) {
4170                     exit(1);
4171                 }
4172                 enable_mlock = qemu_opt_get_bool(opts, "mlock", true);
4173                 break;
4174             case QEMU_OPTION_msg:
4175                 opts = qemu_opts_parse_noisily(qemu_find_opts("msg"), optarg,
4176                                                false);
4177                 if (!opts) {
4178                     exit(1);
4179                 }
4180                 configure_msg(opts);
4181                 break;
4182             case QEMU_OPTION_dump_vmstate:
4183                 if (vmstate_dump_file) {
4184                     error_report("only one '-dump-vmstate' "
4185                                  "option may be given");
4186                     exit(1);
4187                 }
4188                 vmstate_dump_file = fopen(optarg, "w");
4189                 if (vmstate_dump_file == NULL) {
4190                     error_report("open %s: %s", optarg, strerror(errno));
4191                     exit(1);
4192                 }
4193                 break;
4194             default:
4195                 os_parse_cmd_args(popt->index, optarg);
4196             }
4197         }
4198     }
4199     /*
4200      * Clear error location left behind by the loop.
4201      * Best done right after the loop.  Do not insert code here!
4202      */
4203     loc_set_none();
4204
4205     replay_configure(icount_opts);
4206
4207     machine_class = select_machine();
4208
4209 #if defined(CONFIG_MARU)
4210     if (is_maru_machine(machine_class)) {
4211         preallocated_ram_ptr = qemu_anon_ram_alloc(ram_size, NULL);
4212         if (preallocated_ram_ptr) {
4213             preallocated_ram_size = ram_size;
4214         }
4215     }
4216 #endif
4217
4218     set_memory_options(&ram_slots, &maxram_size, machine_class);
4219
4220     os_daemonize();
4221
4222     if (pid_file && qemu_create_pidfile(pid_file) != 0) {
4223         error_report("could not acquire pid file: %s", strerror(errno));
4224         exit(1);
4225     }
4226
4227     if (qemu_init_main_loop(&main_loop_err)) {
4228         error_report_err(main_loop_err);
4229         exit(1);
4230     }
4231
4232     if (qemu_opts_foreach(qemu_find_opts("sandbox"),
4233                           parse_sandbox, NULL, NULL)) {
4234         exit(1);
4235     }
4236
4237     if (qemu_opts_foreach(qemu_find_opts("name"),
4238                           parse_name, NULL, NULL)) {
4239         exit(1);
4240     }
4241
4242 #ifndef _WIN32
4243     if (qemu_opts_foreach(qemu_find_opts("add-fd"),
4244                           parse_add_fd, NULL, NULL)) {
4245         exit(1);
4246     }
4247
4248     if (qemu_opts_foreach(qemu_find_opts("add-fd"),
4249                           cleanup_add_fd, NULL, NULL)) {
4250         exit(1);
4251     }
4252 #endif
4253
4254     current_machine = MACHINE(object_new(object_class_get_name(
4255                           OBJECT_CLASS(machine_class))));
4256     if (machine_help_func(qemu_get_machine_opts(), current_machine)) {
4257         exit(0);
4258     }
4259     object_property_add_child(object_get_root(), "machine",
4260                               OBJECT(current_machine), &error_abort);
4261
4262     if (machine_class->minimum_page_bits) {
4263         if (!set_preferred_target_page_bits(machine_class->minimum_page_bits)) {
4264             /* This would be a board error: specifying a minimum smaller than
4265              * a target's compile-time fixed setting.
4266              */
4267             g_assert_not_reached();
4268         }
4269     }
4270
4271     cpu_exec_init_all();
4272
4273     if (machine_class->hw_version) {
4274         qemu_set_hw_version(machine_class->hw_version);
4275     }
4276
4277     if (cpu_model && is_help_option(cpu_model)) {
4278         list_cpus(stdout, &fprintf, cpu_model);
4279         exit(0);
4280     }
4281
4282     if (!trace_init_backends()) {
4283         exit(1);
4284     }
4285     trace_init_file(trace_file);
4286
4287     /* Open the logfile at this point and set the log mask if necessary.
4288      */
4289     if (log_file) {
4290         qemu_set_log_filename(log_file, &error_fatal);
4291     }
4292
4293     if (log_mask) {
4294         int mask;
4295         mask = qemu_str_to_log_mask(log_mask);
4296         if (!mask) {
4297             qemu_print_log_usage(stdout);
4298             exit(1);
4299         }
4300         qemu_set_log(mask);
4301     } else {
4302         qemu_set_log(0);
4303     }
4304
4305     /* If no data_dir is specified then try to find it relative to the
4306        executable path.  */
4307     if (data_dir_idx < ARRAY_SIZE(data_dir)) {
4308         data_dir[data_dir_idx] = os_find_datadir();
4309         if (data_dir[data_dir_idx] != NULL) {
4310             data_dir_idx++;
4311         }
4312     }
4313     /* If all else fails use the install path specified when building. */
4314     if (data_dir_idx < ARRAY_SIZE(data_dir)) {
4315         data_dir[data_dir_idx++] = CONFIG_QEMU_DATADIR;
4316     }
4317
4318     /* -L help lists the data directories and exits. */
4319     if (list_data_dirs) {
4320         for (i = 0; i < data_dir_idx; i++) {
4321             printf("%s\n", data_dir[i]);
4322         }
4323         exit(0);
4324     }
4325
4326     smp_parse(qemu_opts_find(qemu_find_opts("smp-opts"), NULL));
4327
4328     machine_class->max_cpus = machine_class->max_cpus ?: 1; /* Default to UP */
4329     if (max_cpus > machine_class->max_cpus) {
4330         error_report("Number of SMP CPUs requested (%d) exceeds max CPUs "
4331                      "supported by machine '%s' (%d)", max_cpus,
4332                      machine_class->name, machine_class->max_cpus);
4333         exit(1);
4334     }
4335
4336     /*
4337      * Get the default machine options from the machine if it is not already
4338      * specified either by the configuration file or by the command line.
4339      */
4340     if (machine_class->default_machine_opts) {
4341         qemu_opts_set_defaults(qemu_find_opts("machine"),
4342                                machine_class->default_machine_opts, 0);
4343     }
4344
4345     qemu_opts_foreach(qemu_find_opts("device"),
4346                       default_driver_check, NULL, NULL);
4347     qemu_opts_foreach(qemu_find_opts("global"),
4348                       default_driver_check, NULL, NULL);
4349
4350     if (!vga_model && !default_vga) {
4351         vga_interface_type = VGA_DEVICE;
4352     }
4353     if (!has_defaults || machine_class->no_serial) {
4354         default_serial = 0;
4355     }
4356     if (!has_defaults || machine_class->no_parallel) {
4357         default_parallel = 0;
4358     }
4359     if (!has_defaults || !machine_class->use_virtcon) {
4360         default_virtcon = 0;
4361     }
4362     if (!has_defaults || !machine_class->use_sclp) {
4363         default_sclp = 0;
4364     }
4365     if (!has_defaults || machine_class->no_floppy) {
4366         default_floppy = 0;
4367     }
4368     if (!has_defaults || machine_class->no_cdrom) {
4369         default_cdrom = 0;
4370     }
4371     if (!has_defaults || machine_class->no_sdcard) {
4372         default_sdcard = 0;
4373     }
4374     if (!has_defaults) {
4375         default_monitor = 0;
4376         default_net = 0;
4377         default_vga = 0;
4378     }
4379
4380     if (is_daemonized()) {
4381         /* According to documentation and historically, -nographic redirects
4382          * serial port, parallel port and monitor to stdio, which does not work
4383          * with -daemonize.  We can redirect these to null instead, but since
4384          * -nographic is legacy, let's just error out.
4385          * We disallow -nographic only if all other ports are not redirected
4386          * explicitly, to not break existing legacy setups which uses
4387          * -nographic _and_ redirects all ports explicitly - this is valid
4388          * usage, -nographic is just a no-op in this case.
4389          */
4390         if (nographic
4391             && (default_parallel || default_serial
4392                 || default_monitor || default_virtcon)) {
4393             error_report("-nographic cannot be used with -daemonize");
4394             exit(1);
4395         }
4396 #ifdef CONFIG_CURSES
4397         if (display_type == DT_CURSES) {
4398             error_report("curses display cannot be used with -daemonize");
4399             exit(1);
4400         }
4401 #endif
4402     }
4403
4404     if (nographic) {
4405         if (default_parallel)
4406             add_device_config(DEV_PARALLEL, "null");
4407         if (default_serial && default_monitor) {
4408             add_device_config(DEV_SERIAL, "mon:stdio");
4409         } else if (default_virtcon && default_monitor) {
4410             add_device_config(DEV_VIRTCON, "mon:stdio");
4411         } else if (default_sclp && default_monitor) {
4412             add_device_config(DEV_SCLP, "mon:stdio");
4413         } else {
4414             if (default_serial)
4415                 add_device_config(DEV_SERIAL, "stdio");
4416             if (default_virtcon)
4417                 add_device_config(DEV_VIRTCON, "stdio");
4418             if (default_sclp) {
4419                 add_device_config(DEV_SCLP, "stdio");
4420             }
4421             if (default_monitor)
4422                 monitor_parse("stdio", "readline", false);
4423         }
4424     } else {
4425         if (default_serial)
4426             add_device_config(DEV_SERIAL, "vc:80Cx24C");
4427         if (default_parallel)
4428             add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4429         if (default_monitor)
4430             monitor_parse("vc:80Cx24C", "readline", false);
4431         if (default_virtcon)
4432             add_device_config(DEV_VIRTCON, "vc:80Cx24C");
4433         if (default_sclp) {
4434             add_device_config(DEV_SCLP, "vc:80Cx24C");
4435         }
4436     }
4437
4438 #if defined(CONFIG_VNC)
4439     if (!QTAILQ_EMPTY(&(qemu_find_opts("vnc")->head))) {
4440         display_remote++;
4441     }
4442 #endif
4443     if (display_type == DT_DEFAULT && !display_remote) {
4444 #if defined(CONFIG_GTK)
4445         display_type = DT_GTK;
4446 #elif defined(CONFIG_SDL)
4447         display_type = DT_SDL;
4448 #elif defined(CONFIG_COCOA)
4449         display_type = DT_COCOA;
4450 #elif defined(CONFIG_VNC)
4451         vnc_parse("localhost:0,to=99,id=default", &error_abort);
4452 #else
4453         display_type = DT_NONE;
4454 #endif
4455     }
4456
4457     if ((no_frame || alt_grab || ctrl_grab) && display_type != DT_SDL) {
4458         error_report("-no-frame, -alt-grab and -ctrl-grab are only valid "
4459                      "for SDL, ignoring option");
4460     }
4461     if (no_quit && (display_type != DT_GTK && display_type != DT_SDL)) {
4462         error_report("-no-quit is only valid for GTK and SDL, "
4463                      "ignoring option");
4464     }
4465
4466     if (display_type == DT_GTK) {
4467         early_gtk_display_init(request_opengl);
4468     }
4469
4470     if (display_type == DT_SDL) {
4471         sdl_display_early_init(request_opengl);
4472     }
4473
4474     if (request_opengl == 1 && display_opengl == 0) {
4475 #if defined(CONFIG_OPENGL)
4476         error_report("OpenGL is not supported by the display");
4477 #else
4478         error_report("OpenGL support is disabled");
4479 #endif
4480         exit(1);
4481     }
4482
4483 #ifdef CONFIG_MARU
4484 # if defined(CONFIG_QT)
4485     if (display_type == DT_MARU_QT_ONSCREEN) {
4486         maru_early_qt5_display_init(true);
4487     } else if (display_type == DT_MARU_QT_OFFSCREEN) {
4488         maru_early_qt5_display_init(false);
4489     }
4490 # endif
4491 #endif
4492
4493     page_size_init();
4494     socket_init();
4495
4496     if (qemu_opts_foreach(qemu_find_opts("object"),
4497                           user_creatable_add_opts_foreach,
4498                           object_create_initial, NULL)) {
4499         exit(1);
4500     }
4501
4502     if (qemu_opts_foreach(qemu_find_opts("chardev"),
4503                           chardev_init_func, NULL, NULL)) {
4504         exit(1);
4505     }
4506
4507 #ifdef CONFIG_VIRTFS
4508     if (qemu_opts_foreach(qemu_find_opts("fsdev"),
4509                           fsdev_init_func, NULL, NULL)) {
4510         exit(1);
4511     }
4512 #endif
4513
4514     if (qemu_opts_foreach(qemu_find_opts("device"),
4515                           device_help_func, NULL, NULL)) {
4516         exit(0);
4517     }
4518
4519     machine_opts = qemu_get_machine_opts();
4520     if (qemu_opt_foreach(machine_opts, machine_set_property, current_machine,
4521                          NULL)) {
4522         object_unref(OBJECT(current_machine));
4523         exit(1);
4524     }
4525
4526     if (qtest_chrdev) {
4527         qtest_init(qtest_chrdev, qtest_log, &error_fatal);
4528     }
4529
4530     machine_opts = qemu_get_machine_opts();
4531     kernel_filename = qemu_opt_get(machine_opts, "kernel");
4532     initrd_filename = qemu_opt_get(machine_opts, "initrd");
4533     kernel_cmdline = qemu_opt_get(machine_opts, "append");
4534     bios_name = qemu_opt_get(machine_opts, "firmware");
4535
4536     opts = qemu_opts_find(qemu_find_opts("boot-opts"), NULL);
4537     if (opts) {
4538         boot_order = qemu_opt_get(opts, "order");
4539         if (boot_order) {
4540             validate_bootdevices(boot_order, &error_fatal);
4541         }
4542
4543         boot_once = qemu_opt_get(opts, "once");
4544         if (boot_once) {
4545             validate_bootdevices(boot_once, &error_fatal);
4546         }
4547
4548         boot_menu = qemu_opt_get_bool(opts, "menu", boot_menu);
4549         boot_strict = qemu_opt_get_bool(opts, "strict", false);
4550     }
4551
4552     if (!boot_order) {
4553         boot_order = machine_class->default_boot_order;
4554     }
4555
4556     if (!kernel_cmdline) {
4557         kernel_cmdline = "";
4558         current_machine->kernel_cmdline = (char *)kernel_cmdline;
4559     }
4560
4561     linux_boot = (kernel_filename != NULL);
4562
4563     if (!linux_boot && *kernel_cmdline != '\0') {
4564         error_report("-append only allowed with -kernel option");
4565         exit(1);
4566     }
4567
4568     if (!linux_boot && initrd_filename != NULL) {
4569         error_report("-initrd only allowed with -kernel option");
4570         exit(1);
4571     }
4572
4573     if (semihosting_enabled() && !semihosting_get_argc() && kernel_filename) {
4574         /* fall back to the -kernel/-append */
4575         semihosting_arg_fallback(kernel_filename, kernel_cmdline);
4576     }
4577
4578     os_set_line_buffering();
4579
4580     /* spice needs the timers to be initialized by this point */
4581     qemu_spice_init();
4582
4583     cpu_ticks_init();
4584     if (icount_opts) {
4585         if (kvm_enabled() || xen_enabled() || hax_enabled()) {
4586             error_report("-icount is not allowed with kvm or xen");
4587             exit(1);
4588         }
4589         configure_icount(icount_opts, &error_abort);
4590         qemu_opts_del(icount_opts);
4591     }
4592
4593     if (default_net) {
4594         QemuOptsList *net = qemu_find_opts("net");
4595         qemu_opts_set(net, NULL, "type", "nic", &error_abort);
4596 #ifdef CONFIG_SLIRP
4597         qemu_opts_set(net, NULL, "type", "user", &error_abort);
4598 #endif
4599     }
4600
4601     colo_info_init();
4602
4603     if (net_init_clients() < 0) {
4604         exit(1);
4605     }
4606
4607     if (qemu_opts_foreach(qemu_find_opts("object"),
4608                           user_creatable_add_opts_foreach,
4609                           object_create_delayed, NULL)) {
4610         exit(1);
4611     }
4612
4613 #ifdef CONFIG_TPM
4614     if (tpm_init() < 0) {
4615         exit(1);
4616     }
4617 #endif
4618
4619     /* init the bluetooth world */
4620     if (foreach_device_config(DEV_BT, bt_parse))
4621         exit(1);
4622
4623     if (!xen_enabled()) {
4624         /* On 32-bit hosts, QEMU is limited by virtual address space */
4625         if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
4626             error_report("at most 2047 MB RAM can be simulated");
4627             exit(1);
4628         }
4629     }
4630
4631     blk_mig_init();
4632     ram_mig_init();
4633
4634     /* If the currently selected machine wishes to override the units-per-bus
4635      * property of its default HBA interface type, do so now. */
4636     if (machine_class->units_per_default_bus) {
4637         override_max_devs(machine_class->block_default_type,
4638                           machine_class->units_per_default_bus);
4639     }
4640
4641     /* open the virtual block devices */
4642     if (snapshot || replay_mode != REPLAY_MODE_NONE) {
4643         qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot,
4644                           NULL, NULL);
4645     }
4646     if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func,
4647                           &machine_class->block_default_type, NULL)) {
4648         exit(1);
4649     }
4650
4651     default_drive(default_cdrom, snapshot, machine_class->block_default_type, 2,
4652                   CDROM_OPTS);
4653     default_drive(default_floppy, snapshot, IF_FLOPPY, 0, FD_OPTS);
4654     default_drive(default_sdcard, snapshot, IF_SD, 0, SD_OPTS);
4655
4656     parse_numa_opts(machine_class);
4657
4658     if (qemu_opts_foreach(qemu_find_opts("mon"),
4659                           mon_init_func, NULL, NULL)) {
4660         exit(1);
4661     }
4662
4663     if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4664         exit(1);
4665     if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4666         exit(1);
4667     if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
4668         exit(1);
4669     if (foreach_device_config(DEV_SCLP, sclp_parse) < 0) {
4670         exit(1);
4671     }
4672     if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4673         exit(1);
4674
4675     /* If no default VGA is requested, the default is "none".  */
4676     if (default_vga) {
4677         if (machine_class->default_display) {
4678             vga_model = machine_class->default_display;
4679         } else if (vga_interface_available(VGA_CIRRUS)) {
4680             vga_model = "cirrus";
4681         } else if (vga_interface_available(VGA_STD)) {
4682             vga_model = "std";
4683         }
4684     }
4685     if (vga_model) {
4686         select_vgahw(vga_model);
4687     }
4688
4689     if (watchdog) {
4690         i = select_watchdog(watchdog);
4691         if (i > 0)
4692             exit (i == 1 ? 1 : 0);
4693     }
4694
4695     machine_register_compat_props(current_machine);
4696
4697     qemu_opts_foreach(qemu_find_opts("global"),
4698                       global_init_func, NULL, NULL);
4699
4700     /* This checkpoint is required by replay to separate prior clock
4701        reading from the other reads, because timer polling functions query
4702        clock values from the log. */
4703     replay_checkpoint(CHECKPOINT_INIT);
4704     qdev_machine_init();
4705
4706     current_machine->ram_size = ram_size;
4707     current_machine->maxram_size = maxram_size;
4708     current_machine->ram_slots = ram_slots;
4709     current_machine->boot_order = boot_order;
4710     current_machine->cpu_model = cpu_model;
4711
4712     configure_accelerator(current_machine);
4713
4714 #if defined(CONFIG_MARU)
4715     if (is_maru_machine(machine_class)) {
4716         kernel_cmdline = qemu_opt_get(machine_opts, "append");
4717         // Returned variable points different address from input variable.
4718         kernel_cmdline = prepare_maru(kernel_cmdline);
4719         qemu_opt_set(qemu_get_machine_opts(), "append",
4720                 kernel_cmdline, &error_abort);
4721
4722         current_machine->kernel_cmdline = (char *)kernel_cmdline;
4723         if (display_type == DT_NONE) {
4724             nodisplay = true;
4725         }
4726     }
4727 #endif
4728
4729     machine_class->init(current_machine);
4730
4731     realtime_init();
4732
4733     // TODO: Check about it...
4734     audio_init();
4735
4736     cpu_synchronize_all_post_init();
4737
4738     numa_post_machine_init();
4739
4740     if (qemu_opts_foreach(qemu_find_opts("fw_cfg"),
4741                           parse_fw_cfg, fw_cfg_find(), NULL) != 0) {
4742         exit(1);
4743     }
4744
4745     if (hax_enabled()) {
4746         hax_sync_vcpus();
4747     }
4748
4749     /* init USB devices */
4750     if (machine_usb(current_machine)) {
4751         if (foreach_device_config(DEV_USB, usb_parse) < 0)
4752             exit(1);
4753     }
4754
4755     /* Check if IGD GFX passthrough. */
4756     igd_gfx_passthru();
4757
4758     /* init generic devices */
4759     rom_set_order_override(FW_CFG_ORDER_OVERRIDE_DEVICE);
4760     if (qemu_opts_foreach(qemu_find_opts("device"),
4761                           device_init_func, NULL, NULL)) {
4762         exit(1);
4763     }
4764     rom_reset_order_override();
4765
4766 #if defined(CONFIG_MARU)
4767     if (is_maru_machine(machine_class)) {
4768         prepare_maru_after_device_init();
4769     }
4770 #endif
4771 #ifdef CONFIG_VIGS
4772     // To support legacy VIGS options
4773     if (vigs_enabled) {
4774         PCIBus *pci_bus = (PCIBus *) object_resolve_path_type("", TYPE_PCI_BUS, NULL);
4775         PCIDevice *pci_dev = pci_create(pci_bus, -1, "vigs");
4776         if (vigs_backend) {
4777             qdev_prop_set_string(&pci_dev->qdev, "backend", vigs_backend);
4778         } else {
4779             qdev_prop_set_string(&pci_dev->qdev, "backend", "gl");
4780         }
4781         qdev_prop_set_string(&pci_dev->qdev, "wsi", "wsi0");
4782         qdev_init_nofail(&pci_dev->qdev);
4783     }
4784 #endif
4785 #ifdef CONFIG_YAGL
4786     // To support legacy YaGL options
4787     if (yagl_enabled) {
4788         PCIBus *pci_bus = (PCIBus *) object_resolve_path_type("", TYPE_PCI_BUS, NULL);
4789         PCIDevice *pci_dev = pci_create(pci_bus, -1, "yagl");
4790         if (vigs_enabled) {
4791             qdev_prop_set_string(&pci_dev->qdev, "wsi", "wsi0");
4792         }
4793         qdev_init_nofail(&pci_dev->qdev);
4794     }
4795 #endif
4796
4797     /* Did we create any drives that we failed to create a device for? */
4798     drive_check_orphaned();
4799
4800     /* Don't warn about the default network setup that you get if
4801      * no command line -net or -netdev options are specified. There
4802      * are two cases that we would otherwise complain about:
4803      * (1) board doesn't support a NIC but the implicit "-net nic"
4804      * requested one
4805      * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
4806      * sets up a nic that isn't connected to anything.
4807      */
4808     if (!default_net) {
4809         net_check_clients();
4810     }
4811
4812
4813     if (boot_once) {
4814         qemu_boot_set(boot_once, &error_fatal);
4815         qemu_register_reset(restore_boot_order, g_strdup(boot_order));
4816     }
4817
4818     ds = init_displaystate();
4819
4820     /* init local displays */
4821     switch (display_type) {
4822     case DT_CURSES:
4823         curses_display_init(ds, full_screen);
4824         break;
4825     case DT_SDL:
4826         sdl_display_init(ds, full_screen, no_frame);
4827         break;
4828     case DT_COCOA:
4829         cocoa_display_init(ds, full_screen);
4830         break;
4831     case DT_GTK:
4832         gtk_display_init(ds, full_screen, grab_on_hover);
4833         break;
4834 #if defined(CONFIG_MARU)
4835  #if defined(CONFIG_QT)
4836     case DT_MARU_QT_ONSCREEN:
4837     case DT_MARU_QT_OFFSCREEN:
4838         if (!is_maru_machine(machine_class)) {
4839             error_report("maru_qt can not work"
4840                     " without maru machine");
4841             exit(1);
4842         }
4843         maru_qt5_display_init(ds, full_screen);
4844         break;
4845  #endif
4846 #endif
4847     default:
4848         break;
4849     }
4850
4851     /* must be after terminal init, SDL library changes signal handlers */
4852     os_setup_signal_handling();
4853
4854     /* init remote displays */
4855 #ifdef CONFIG_VNC
4856     qemu_opts_foreach(qemu_find_opts("vnc"),
4857                       vnc_init_func, NULL, NULL);
4858 #endif
4859
4860     if (using_spice) {
4861         qemu_spice_display_init();
4862     }
4863
4864     if (foreach_device_config(DEV_GDB, gdbserver_start) < 0) {
4865         exit(1);
4866     }
4867
4868     qdev_machine_creation_done();
4869
4870     /* TODO: once all bus devices are qdevified, this should be done
4871      * when bus is created by qdev.c */
4872     qemu_register_reset(qbus_reset_all_fn, sysbus_get_default());
4873     qemu_run_machine_init_done_notifiers();
4874
4875     if (rom_check_and_register_reset() != 0) {
4876         error_report("rom check and register reset failed");
4877         exit(1);
4878     }
4879
4880     replay_start();
4881
4882     /* This checkpoint is required by replay to separate prior clock
4883        reading from the other reads, because timer polling functions query
4884        clock values from the log. */
4885     replay_checkpoint(CHECKPOINT_RESET);
4886     qemu_system_reset(VMRESET_SILENT);
4887     register_global_state();
4888     if (loadvm) {
4889         if (load_vmstate(loadvm) < 0) {
4890             autostart = 0;
4891         }
4892     }
4893
4894     qdev_prop_check_globals();
4895     if (vmstate_dump_file) {
4896         /* dump and exit */
4897         dump_vmstate_json_to_file(vmstate_dump_file);
4898         return 0;
4899     }
4900
4901     if (incoming) {
4902         Error *local_err = NULL;
4903         qemu_start_incoming_migration(incoming, &local_err);
4904         if (local_err) {
4905             error_reportf_err(local_err, "-incoming %s: ", incoming);
4906             exit(1);
4907         }
4908     } else if (autostart) {
4909         vm_start();
4910     }
4911
4912     os_setup_post();
4913
4914 #ifdef CONFIG_MARU
4915     enable_print_backtrace_at_normal_exit();
4916 #endif
4917     main_loop();
4918     replay_disable_events();
4919     iothread_stop_all();
4920
4921     bdrv_close_all();
4922     pause_all_vcpus();
4923     res_free();
4924
4925     /* vhost-user must be cleaned up before chardevs.  */
4926     net_cleanup();
4927     audio_cleanup();
4928     monitor_cleanup();
4929     qemu_chr_cleanup();
4930
4931 #if defined(CONFIG_MARU) && defined(CONFIG_QT)
4932     switch (display_type) {
4933     case DT_MARU_QT_ONSCREEN:
4934     case DT_MARU_QT_OFFSCREEN:
4935         maru_qt5_display_fini();
4936         break;
4937     default:
4938         break;
4939     }
4940 #endif
4941
4942     return 0;
4943 }