Home | History | Annotate | Download | only in qemu
      1 /*
      2  * QEMU System Emulator
      3  *
      4  * Copyright (c) 2003-2008 Fabrice Bellard
      5  *
      6  * Permission is hereby granted, free of charge, to any person obtaining a copy
      7  * of this software and associated documentation files (the "Software"), to deal
      8  * in the Software without restriction, including without limitation the rights
      9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     10  * copies of the Software, and to permit persons to whom the Software is
     11  * furnished to do so, subject to the following conditions:
     12  *
     13  * The above copyright notice and this permission notice shall be included in
     14  * all copies or substantial portions of the Software.
     15  *
     16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
     19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
     22  * THE SOFTWARE.
     23  */
     24 
     25 /* the following is needed on Linux to define ptsname() in stdlib.h */
     26 #if defined(__linux__)
     27 #define _GNU_SOURCE 1
     28 #endif
     29 
     30 #include "qemu-common.h"
     31 #include "hw/hw.h"
     32 #include "hw/boards.h"
     33 #include "hw/usb.h"
     34 #include "hw/pcmcia.h"
     35 #include "hw/i386/pc.h"
     36 #include "hw/audiodev.h"
     37 #include "hw/isa/isa.h"
     38 #include "hw/loader.h"
     39 #include "hw/baum.h"
     40 #include "hw/android/goldfish/nand.h"
     41 #include "net/net.h"
     42 #include "ui/console.h"
     43 #include "sysemu/sysemu.h"
     44 #include "exec/gdbstub.h"
     45 #include "qemu/log.h"
     46 #include "qemu/timer.h"
     47 #include "sysemu/char.h"
     48 #include "sysemu/blockdev.h"
     49 #include "audio/audio.h"
     50 
     51 #include "migration/qemu-file.h"
     52 #include "android/android.h"
     53 #include "android/charpipe.h"
     54 #include "android/log-rotate.h"
     55 #include "modem_driver.h"
     56 #include "android/filesystems/ext4_utils.h"
     57 #include "android/filesystems/fstab_parser.h"
     58 #include "android/filesystems/partition_types.h"
     59 #include "android/filesystems/ramdisk_extractor.h"
     60 #include "android/gps.h"
     61 #include "android/hw-kmsg.h"
     62 #include "android/hw-pipe-net.h"
     63 #include "android/hw-qemud.h"
     64 #include "android/camera/camera-service.h"
     65 #include "android/multitouch-port.h"
     66 #include "android/charmap.h"
     67 #include "android/globals.h"
     68 #include "android/utils/bufprint.h"
     69 #include "android/utils/debug.h"
     70 #include "android/utils/filelock.h"
     71 #include "android/utils/path.h"
     72 #include "android/utils/stralloc.h"
     73 #include "android/utils/tempfile.h"
     74 #include "android/display-core.h"
     75 #include "android/utils/timezone.h"
     76 #include "android/snapshot.h"
     77 #include "android/opengles.h"
     78 #include "android/multitouch-screen.h"
     79 #include "exec/hwaddr.h"
     80 #include "android/tcpdump.h"
     81 
     82 #include <unistd.h>
     83 #include <fcntl.h>
     84 #include <signal.h>
     85 #include <time.h>
     86 #include <errno.h>
     87 #include <sys/time.h>
     88 #include <zlib.h>
     89 
     90 /* Needed early for CONFIG_BSD etc. */
     91 #include "config-host.h"
     92 
     93 #ifndef _WIN32
     94 #include <libgen.h>
     95 #include <sys/times.h>
     96 #include <sys/wait.h>
     97 #include <termios.h>
     98 #include <sys/mman.h>
     99 #include <sys/ioctl.h>
    100 #include <sys/resource.h>
    101 #include <sys/socket.h>
    102 #include <netinet/in.h>
    103 #include <net/if.h>
    104 #if defined(__NetBSD__)
    105 #include <net/if_tap.h>
    106 #endif
    107 #ifdef __linux__
    108 #include <linux/if_tun.h>
    109 #endif
    110 #include <arpa/inet.h>
    111 #include <dirent.h>
    112 #include <netdb.h>
    113 #include <sys/select.h>
    114 #ifdef CONFIG_BSD
    115 #include <sys/stat.h>
    116 #if defined(__FreeBSD__) || defined(__DragonFly__)
    117 #include <libutil.h>
    118 #else
    119 #include <util.h>
    120 #endif
    121 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
    122 #include <freebsd/stdlib.h>
    123 #else
    124 #ifdef __linux__
    125 #include <pty.h>
    126 #include <malloc.h>
    127 #include <linux/rtc.h>
    128 
    129 /* For the benefit of older linux systems which don't supply it,
    130    we use a local copy of hpet.h. */
    131 /* #include <linux/hpet.h> */
    132 #include "hw/timer/hpet.h"
    133 
    134 #include <linux/ppdev.h>
    135 #include <linux/parport.h>
    136 #endif
    137 #ifdef __sun__
    138 #include <sys/stat.h>
    139 #include <sys/ethernet.h>
    140 #include <sys/sockio.h>
    141 #include <netinet/arp.h>
    142 #include <netinet/in.h>
    143 #include <netinet/in_systm.h>
    144 #include <netinet/ip.h>
    145 #include <netinet/ip_icmp.h> // must come after ip.h
    146 #include <netinet/udp.h>
    147 #include <netinet/tcp.h>
    148 #include <net/if.h>
    149 #include <syslog.h>
    150 #include <stropts.h>
    151 #endif
    152 #endif
    153 #endif
    154 
    155 #if defined(__OpenBSD__)
    156 #include <util.h>
    157 #endif
    158 
    159 #if defined(CONFIG_VDE)
    160 #include <libvdeplug.h>
    161 #endif
    162 
    163 #ifdef _WIN32
    164 #include <windows.h>
    165 #include <malloc.h>
    166 #include <sys/timeb.h>
    167 #include <mmsystem.h>
    168 #define getopt_long_only getopt_long
    169 #define memalign(align, size) malloc(size)
    170 #endif
    171 
    172 #include "sysemu/cpus.h"
    173 #include "sysemu/arch_init.h"
    174 
    175 #ifdef CONFIG_COCOA
    176 int qemu_main(int argc, char **argv, char **envp);
    177 #undef main
    178 #define main qemu_main
    179 #endif /* CONFIG_COCOA */
    180 
    181 #include "hw/hw.h"
    182 #include "hw/boards.h"
    183 #include "hw/usb.h"
    184 #include "hw/pcmcia.h"
    185 #include "hw/i386/pc.h"
    186 #include "hw/isa/isa.h"
    187 #include "hw/baum.h"
    188 #include "hw/bt.h"
    189 #include "sysemu/watchdog.h"
    190 #include "hw/i386/smbios.h"
    191 #include "hw/xen/xen.h"
    192 #include "sysemu/bt.h"
    193 #include "net/net.h"
    194 #include "monitor/monitor.h"
    195 #include "ui/console.h"
    196 #include "sysemu/sysemu.h"
    197 #include "exec/gdbstub.h"
    198 #include "qemu/timer.h"
    199 #include "sysemu/char.h"
    200 #include "qemu/cache-utils.h"
    201 #include "block/block.h"
    202 #include "sysemu/dma.h"
    203 #include "audio/audio.h"
    204 #include "migration/migration.h"
    205 #include "sysemu/kvm.h"
    206 #include "exec/hax.h"
    207 #ifdef CONFIG_KVM
    208 #include "android/kvm.h"
    209 #endif
    210 #include "sysemu/balloon.h"
    211 #include "android/hw-lcd.h"
    212 #include "android/boot-properties.h"
    213 #include "android/hw-control.h"
    214 #include "android/core-init-utils.h"
    215 #include "android/audio-test.h"
    216 
    217 #include "android/snaphost-android.h"
    218 
    219 #if !defined(CONFIG_STANDALONE_CORE)
    220 /* in android/qemulator.c */
    221 extern void  android_emulator_set_base_port(int  port);
    222 #endif
    223 
    224 #if defined(CONFIG_SKINS) && !defined(CONFIG_STANDALONE_CORE)
    225 #undef main
    226 #define main qemu_main
    227 #endif
    228 
    229 #include "disas/disas.h"
    230 
    231 #include "qemu/sockets.h"
    232 
    233 #if defined(CONFIG_SLIRP)
    234 #include "libslirp.h"
    235 #endif
    236 
    237 #define DEFAULT_RAM_SIZE 128
    238 
    239 /* Max number of USB devices that can be specified on the commandline.  */
    240 #define MAX_USB_CMDLINE 8
    241 
    242 /* Max number of bluetooth switches on the commandline.  */
    243 #define MAX_BT_CMDLINE 10
    244 
    245 /* XXX: use a two level table to limit memory usage */
    246 
    247 static const char *data_dir;
    248 const char *bios_name = NULL;
    249 static void *ioport_opaque[MAX_IOPORTS];
    250 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
    251 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
    252 #ifdef MAX_DRIVES
    253 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
    254    to store the VM snapshots */
    255 DriveInfo drives_table[MAX_DRIVES+1];
    256 int nb_drives;
    257 #endif
    258 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
    259 DisplayType display_type = DT_DEFAULT;
    260 const char* keyboard_layout = NULL;
    261 int64_t ticks_per_sec;
    262 ram_addr_t ram_size;
    263 bool xen_allowed;
    264 const char *mem_path = NULL;
    265 #ifdef MAP_POPULATE
    266 int mem_prealloc = 0; /* force preallocation of physical target memory */
    267 #endif
    268 int nb_nics;
    269 NICInfo nd_table[MAX_NICS];
    270 int vm_running;
    271 int autostart;
    272 static int rtc_utc = 1;
    273 static int rtc_date_offset = -1; /* -1 means no change */
    274 int cirrus_vga_enabled = 1;
    275 int std_vga_enabled = 0;
    276 int vmsvga_enabled = 0;
    277 int xenfb_enabled = 0;
    278 static int full_screen = 0;
    279 #ifdef CONFIG_SDL
    280 static int no_frame = 0;
    281 #endif
    282 int no_quit = 0;
    283 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
    284 int              serial_hds_count;
    285 
    286 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
    287 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
    288 #ifdef TARGET_I386
    289 int win2k_install_hack = 0;
    290 int rtc_td_hack = 0;
    291 #endif
    292 int usb_enabled = 0;
    293 int singlestep = 0;
    294 int smp_cpus = 1;
    295 const char *vnc_display;
    296 int acpi_enabled = 1;
    297 int no_hpet = 0;
    298 int hax_disabled = 1;
    299 int no_virtio_balloon = 0;
    300 int fd_bootchk = 1;
    301 int no_reboot = 0;
    302 int no_shutdown = 0;
    303 int cursor_hide = 1;
    304 int graphic_rotate = 0;
    305 WatchdogTimerModel *watchdog = NULL;
    306 int watchdog_action = WDT_RESET;
    307 const char *option_rom[MAX_OPTION_ROMS];
    308 int nb_option_roms;
    309 int semihosting_enabled = 0;
    310 #ifdef TARGET_ARM
    311 int old_param = 0;
    312 #endif
    313 const char *qemu_name;
    314 int alt_grab = 0;
    315 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
    316 unsigned int nb_prom_envs = 0;
    317 const char *prom_envs[MAX_PROM_ENVS];
    318 #endif
    319 #ifdef MAX_DRIVES
    320 int nb_drives_opt;
    321 struct drive_opt drives_opt[MAX_DRIVES];
    322 #endif
    323 int nb_numa_nodes;
    324 uint64_t node_mem[MAX_NODES];
    325 uint64_t node_cpumask[MAX_NODES];
    326 
    327 static QEMUTimer *nographic_timer;
    328 
    329 uint8_t qemu_uuid[16];
    330 
    331 
    332 int   qemu_cpu_delay;
    333 extern char* audio_input_source;
    334 
    335 extern char* android_op_ports;
    336 extern char* android_op_port;
    337 extern char* android_op_report_console;
    338 extern char* op_http_proxy;
    339 // Path to the file containing specific key character map.
    340 char* op_charmap_file = NULL;
    341 
    342 /* Path to hardware initialization file passed with -android-hw option. */
    343 char* android_op_hwini = NULL;
    344 
    345 /* Memory checker options. */
    346 char* android_op_memcheck = NULL;
    347 
    348 /* -dns-server option value. */
    349 char* android_op_dns_server = NULL;
    350 
    351 /* -radio option value. */
    352 char* android_op_radio = NULL;
    353 
    354 /* -gps option value. */
    355 char* android_op_gps = NULL;
    356 
    357 /* -audio option value. */
    358 char* android_op_audio = NULL;
    359 
    360 /* -cpu-delay option value. */
    361 char* android_op_cpu_delay = NULL;
    362 
    363 #ifdef CONFIG_NAND_LIMITS
    364 /* -nand-limits option value. */
    365 char* android_op_nand_limits = NULL;
    366 #endif  // CONFIG_NAND_LIMITS
    367 
    368 /* -netspeed option value. */
    369 char* android_op_netspeed = NULL;
    370 
    371 /* -netdelay option value. */
    372 char* android_op_netdelay = NULL;
    373 
    374 /* -netfast option value. */
    375 int android_op_netfast = 0;
    376 
    377 /* -tcpdump option value. */
    378 char* android_op_tcpdump = NULL;
    379 
    380 /* -lcd-density option value. */
    381 char* android_op_lcd_density = NULL;
    382 
    383 /* -ui-port option value. This port will be used to report the core
    384  * initialization completion.
    385  */
    386 char* android_op_ui_port = NULL;
    387 
    388 /* -ui-settings option value. This value will be passed to the UI when new UI
    389  * process is attaching to the core.
    390  */
    391 char* android_op_ui_settings = NULL;
    392 
    393 /* -android-avdname option value. */
    394 char* android_op_avd_name = "unknown";
    395 
    396 bool android_op_wipe_data = false;
    397 
    398 extern int android_display_width;
    399 extern int android_display_height;
    400 extern int android_display_bpp;
    401 
    402 extern void  dprint( const char* format, ... );
    403 
    404 const char* dns_log_filename = NULL;
    405 const char* drop_log_filename = NULL;
    406 
    407 const char* savevm_on_exit = NULL;
    408 
    409 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
    410 
    411 /* Reports the core initialization failure to the error stdout and to the UI
    412  * socket before exiting the application.
    413  * Parameters that are passed to this macro are used to format the error
    414  * mesage using sprintf routine.
    415  */
    416 #ifdef CONFIG_ANDROID
    417 #define  PANIC(...) android_core_init_failure(__VA_ARGS__)
    418 #else
    419 #define  PANIC(...) do { fprintf(stderr, __VA_ARGS__);  \
    420                          exit(1);                       \
    421                     } while (0)
    422 #endif  // CONFIG_ANDROID
    423 
    424 /* Exits the core during initialization. */
    425 #ifdef CONFIG_ANDROID
    426 #define  QEMU_EXIT(exit_code) android_core_init_exit(exit_code)
    427 #else
    428 #define  QEMU_EXIT(exit_code) exit(exit_code)
    429 #endif  // CONFIG_ANDROID
    430 
    431 /***********************************************************/
    432 /* x86 ISA bus support */
    433 
    434 hwaddr isa_mem_base = 0;
    435 PicState2 *isa_pic;
    436 
    437 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
    438 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
    439 
    440 static uint32_t ioport_read(int index, uint32_t address)
    441 {
    442     static IOPortReadFunc *default_func[3] = {
    443         default_ioport_readb,
    444         default_ioport_readw,
    445         default_ioport_readl
    446     };
    447     IOPortReadFunc *func = ioport_read_table[index][address];
    448     if (!func)
    449         func = default_func[index];
    450     return func(ioport_opaque[address], address);
    451 }
    452 
    453 static void ioport_write(int index, uint32_t address, uint32_t data)
    454 {
    455     static IOPortWriteFunc *default_func[3] = {
    456         default_ioport_writeb,
    457         default_ioport_writew,
    458         default_ioport_writel
    459     };
    460     IOPortWriteFunc *func = ioport_write_table[index][address];
    461     if (!func)
    462         func = default_func[index];
    463     func(ioport_opaque[address], address, data);
    464 }
    465 
    466 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
    467 {
    468 #ifdef DEBUG_UNUSED_IOPORT
    469     fprintf(stderr, "unused inb: port=0x%04x\n", address);
    470 #endif
    471     return 0xff;
    472 }
    473 
    474 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
    475 {
    476 #ifdef DEBUG_UNUSED_IOPORT
    477     fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
    478 #endif
    479 }
    480 
    481 /* default is to make two byte accesses */
    482 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
    483 {
    484     uint32_t data;
    485     data = ioport_read(0, address);
    486     address = (address + 1) & (MAX_IOPORTS - 1);
    487     data |= ioport_read(0, address) << 8;
    488     return data;
    489 }
    490 
    491 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
    492 {
    493     ioport_write(0, address, data & 0xff);
    494     address = (address + 1) & (MAX_IOPORTS - 1);
    495     ioport_write(0, address, (data >> 8) & 0xff);
    496 }
    497 
    498 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
    499 {
    500 #ifdef DEBUG_UNUSED_IOPORT
    501     fprintf(stderr, "unused inl: port=0x%04x\n", address);
    502 #endif
    503     return 0xffffffff;
    504 }
    505 
    506 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
    507 {
    508 #ifdef DEBUG_UNUSED_IOPORT
    509     fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
    510 #endif
    511 }
    512 
    513 /***************/
    514 /* ballooning */
    515 
    516 static QEMUBalloonEvent *qemu_balloon_event;
    517 void *qemu_balloon_event_opaque;
    518 
    519 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
    520 {
    521     qemu_balloon_event = func;
    522     qemu_balloon_event_opaque = opaque;
    523 }
    524 
    525 void qemu_balloon(ram_addr_t target)
    526 {
    527     if (qemu_balloon_event)
    528         qemu_balloon_event(qemu_balloon_event_opaque, target);
    529 }
    530 
    531 ram_addr_t qemu_balloon_status(void)
    532 {
    533     if (qemu_balloon_event)
    534         return qemu_balloon_event(qemu_balloon_event_opaque, 0);
    535     return 0;
    536 }
    537 
    538 /***********************************************************/
    539 /* host time/date access */
    540 void qemu_get_timedate(struct tm *tm, int offset)
    541 {
    542     time_t ti;
    543     struct tm *ret;
    544 
    545     time(&ti);
    546     ti += offset;
    547     if (rtc_date_offset == -1) {
    548         if (rtc_utc)
    549             ret = gmtime(&ti);
    550         else
    551             ret = localtime(&ti);
    552     } else {
    553         ti -= rtc_date_offset;
    554         ret = gmtime(&ti);
    555     }
    556 
    557     memcpy(tm, ret, sizeof(struct tm));
    558 }
    559 
    560 int qemu_timedate_diff(struct tm *tm)
    561 {
    562     time_t seconds;
    563 
    564     if (rtc_date_offset == -1)
    565         if (rtc_utc)
    566             seconds = mktimegm(tm);
    567         else
    568             seconds = mktime(tm);
    569     else
    570         seconds = mktimegm(tm) + rtc_date_offset;
    571 
    572     return seconds - time(NULL);
    573 }
    574 
    575 /***********************************************************/
    576 /* QEMU Block devices */
    577 
    578 #define HD_ALIAS "index=%d,media=disk"
    579 #define CDROM_ALIAS "index=2,media=cdrom"
    580 #define FD_ALIAS "index=%d,if=floppy"
    581 #define PFLASH_ALIAS "if=pflash"
    582 #define MTD_ALIAS "if=mtd"
    583 #define SD_ALIAS "index=0,if=sd"
    584 
    585 static int drive_init_func(QemuOpts *opts, void *opaque)
    586 {
    587     int *use_scsi = opaque;
    588     int fatal_error = 0;
    589 
    590     if (drive_init(opts, *use_scsi, &fatal_error) == NULL) {
    591         if (fatal_error)
    592             return 1;
    593     }
    594     return 0;
    595 }
    596 
    597 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
    598 {
    599     if (NULL == qemu_opt_get(opts, "snapshot")) {
    600         qemu_opt_set(opts, "snapshot", "on");
    601     }
    602     return 0;
    603 }
    604 
    605 #ifdef MAX_DRIVES
    606 static int drive_opt_get_free_idx(void)
    607 {
    608     int index;
    609 
    610     for (index = 0; index < MAX_DRIVES; index++)
    611         if (!drives_opt[index].used) {
    612             drives_opt[index].used = 1;
    613             return index;
    614         }
    615 
    616     return -1;
    617 }
    618 
    619 static int drive_get_free_idx(void)
    620 {
    621     int index;
    622 
    623     for (index = 0; index < MAX_DRIVES; index++)
    624         if (!drives_table[index].used) {
    625             drives_table[index].used = 1;
    626             return index;
    627         }
    628 
    629     return -1;
    630 }
    631 
    632 int drive_add(const char *file, const char *fmt, ...)
    633 {
    634     va_list ap;
    635     int index = drive_opt_get_free_idx();
    636 
    637     if (nb_drives_opt >= MAX_DRIVES || index == -1) {
    638         fprintf(stderr, "qemu: too many drives\n");
    639         return -1;
    640     }
    641 
    642     drives_opt[index].file = file;
    643     va_start(ap, fmt);
    644     vsnprintf(drives_opt[index].opt,
    645               sizeof(drives_opt[0].opt), fmt, ap);
    646     va_end(ap);
    647 
    648     nb_drives_opt++;
    649     return index;
    650 }
    651 
    652 void drive_remove(int index)
    653 {
    654     drives_opt[index].used = 0;
    655     nb_drives_opt--;
    656 }
    657 
    658 int drive_get_index(BlockInterfaceType type, int bus, int unit)
    659 {
    660     int index;
    661 
    662     /* seek interface, bus and unit */
    663 
    664     for (index = 0; index < MAX_DRIVES; index++)
    665         if (drives_table[index].type == type &&
    666 	    drives_table[index].bus == bus &&
    667 	    drives_table[index].unit == unit &&
    668 	    drives_table[index].used)
    669         return index;
    670 
    671     return -1;
    672 }
    673 
    674 int drive_get_max_bus(BlockInterfaceType type)
    675 {
    676     int max_bus;
    677     int index;
    678 
    679     max_bus = -1;
    680     for (index = 0; index < nb_drives; index++) {
    681         if(drives_table[index].type == type &&
    682            drives_table[index].bus > max_bus)
    683             max_bus = drives_table[index].bus;
    684     }
    685     return max_bus;
    686 }
    687 
    688 const char *drive_get_serial(BlockDriverState *bdrv)
    689 {
    690     int index;
    691 
    692     for (index = 0; index < nb_drives; index++)
    693         if (drives_table[index].bdrv == bdrv)
    694             return drives_table[index].serial;
    695 
    696     return "\0";
    697 }
    698 
    699 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
    700 {
    701     int index;
    702 
    703     for (index = 0; index < nb_drives; index++)
    704         if (drives_table[index].bdrv == bdrv)
    705             return drives_table[index].onerror;
    706 
    707     return BLOCK_ERR_STOP_ENOSPC;
    708 }
    709 
    710 static void bdrv_format_print(void *opaque, const char *name)
    711 {
    712     fprintf(stderr, " %s", name);
    713 }
    714 
    715 void drive_uninit(BlockDriverState *bdrv)
    716 {
    717     int i;
    718 
    719     for (i = 0; i < MAX_DRIVES; i++)
    720         if (drives_table[i].bdrv == bdrv) {
    721             drives_table[i].bdrv = NULL;
    722             drives_table[i].used = 0;
    723             drive_remove(drives_table[i].drive_opt_idx);
    724             nb_drives--;
    725             break;
    726         }
    727 }
    728 
    729 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
    730 {
    731     char buf[128];
    732     char file[1024];
    733     char devname[128];
    734     char serial[21];
    735     const char *mediastr = "";
    736     BlockInterfaceType type;
    737     enum { MEDIA_DISK, MEDIA_CDROM } media;
    738     int bus_id, unit_id;
    739     int cyls, heads, secs, translation;
    740     BlockDriverState *bdrv;
    741     BlockDriver *drv = NULL;
    742     QEMUMachine *machine = opaque;
    743     int max_devs;
    744     int index;
    745     int cache;
    746     int bdrv_flags, onerror;
    747     int drives_table_idx;
    748     char *str = arg->opt;
    749     static const char * const params[] = { "bus", "unit", "if", "index",
    750                                            "cyls", "heads", "secs", "trans",
    751                                            "media", "snapshot", "file",
    752                                            "cache", "format", "serial", "werror",
    753                                            NULL };
    754 
    755     if (check_params(buf, sizeof(buf), params, str) < 0) {
    756          fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
    757                          buf, str);
    758          return -1;
    759     }
    760 
    761     file[0] = 0;
    762     cyls = heads = secs = 0;
    763     bus_id = 0;
    764     unit_id = -1;
    765     translation = BIOS_ATA_TRANSLATION_AUTO;
    766     index = -1;
    767     cache = 3;
    768 
    769     if (machine->use_scsi) {
    770         type = IF_SCSI;
    771         max_devs = MAX_SCSI_DEVS;
    772         pstrcpy(devname, sizeof(devname), "scsi");
    773     } else {
    774         type = IF_IDE;
    775         max_devs = MAX_IDE_DEVS;
    776         pstrcpy(devname, sizeof(devname), "ide");
    777     }
    778     media = MEDIA_DISK;
    779 
    780     /* extract parameters */
    781 
    782     if (get_param_value(buf, sizeof(buf), "bus", str)) {
    783         bus_id = strtol(buf, NULL, 0);
    784 	if (bus_id < 0) {
    785 	    fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
    786 	    return -1;
    787 	}
    788     }
    789 
    790     if (get_param_value(buf, sizeof(buf), "unit", str)) {
    791         unit_id = strtol(buf, NULL, 0);
    792 	if (unit_id < 0) {
    793 	    fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
    794 	    return -1;
    795 	}
    796     }
    797 
    798     if (get_param_value(buf, sizeof(buf), "if", str)) {
    799         pstrcpy(devname, sizeof(devname), buf);
    800         if (!strcmp(buf, "ide")) {
    801 	    type = IF_IDE;
    802             max_devs = MAX_IDE_DEVS;
    803         } else if (!strcmp(buf, "scsi")) {
    804 	    type = IF_SCSI;
    805             max_devs = MAX_SCSI_DEVS;
    806         } else if (!strcmp(buf, "floppy")) {
    807 	    type = IF_FLOPPY;
    808             max_devs = 0;
    809         } else if (!strcmp(buf, "pflash")) {
    810 	    type = IF_PFLASH;
    811             max_devs = 0;
    812 	} else if (!strcmp(buf, "mtd")) {
    813 	    type = IF_MTD;
    814             max_devs = 0;
    815 	} else if (!strcmp(buf, "sd")) {
    816 	    type = IF_SD;
    817             max_devs = 0;
    818         } else if (!strcmp(buf, "virtio")) {
    819             type = IF_VIRTIO;
    820             max_devs = 0;
    821 	} else if (!strcmp(buf, "xen")) {
    822 	    type = IF_XEN;
    823             max_devs = 0;
    824 	} else {
    825             fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
    826             return -1;
    827 	}
    828     }
    829 
    830     if (get_param_value(buf, sizeof(buf), "index", str)) {
    831         index = strtol(buf, NULL, 0);
    832 	if (index < 0) {
    833 	    fprintf(stderr, "qemu: '%s' invalid index\n", str);
    834 	    return -1;
    835 	}
    836     }
    837 
    838     if (get_param_value(buf, sizeof(buf), "cyls", str)) {
    839         cyls = strtol(buf, NULL, 0);
    840     }
    841 
    842     if (get_param_value(buf, sizeof(buf), "heads", str)) {
    843         heads = strtol(buf, NULL, 0);
    844     }
    845 
    846     if (get_param_value(buf, sizeof(buf), "secs", str)) {
    847         secs = strtol(buf, NULL, 0);
    848     }
    849 
    850     if (cyls || heads || secs) {
    851         if (cyls < 1 || cyls > 16383) {
    852             fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
    853 	    return -1;
    854 	}
    855         if (heads < 1 || heads > 16) {
    856             fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
    857 	    return -1;
    858 	}
    859         if (secs < 1 || secs > 63) {
    860             fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
    861 	    return -1;
    862 	}
    863     }
    864 
    865     if (get_param_value(buf, sizeof(buf), "trans", str)) {
    866         if (!cyls) {
    867             fprintf(stderr,
    868                     "qemu: '%s' trans must be used with cyls,heads and secs\n",
    869                     str);
    870             return -1;
    871         }
    872         if (!strcmp(buf, "none"))
    873             translation = BIOS_ATA_TRANSLATION_NONE;
    874         else if (!strcmp(buf, "lba"))
    875             translation = BIOS_ATA_TRANSLATION_LBA;
    876         else if (!strcmp(buf, "auto"))
    877             translation = BIOS_ATA_TRANSLATION_AUTO;
    878 	else {
    879             fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
    880 	    return -1;
    881 	}
    882     }
    883 
    884     if (get_param_value(buf, sizeof(buf), "media", str)) {
    885         if (!strcmp(buf, "disk")) {
    886 	    media = MEDIA_DISK;
    887 	} else if (!strcmp(buf, "cdrom")) {
    888             if (cyls || secs || heads) {
    889                 fprintf(stderr,
    890                         "qemu: '%s' invalid physical CHS format\n", str);
    891 	        return -1;
    892             }
    893 	    media = MEDIA_CDROM;
    894 	} else {
    895 	    fprintf(stderr, "qemu: '%s' invalid media\n", str);
    896 	    return -1;
    897 	}
    898     }
    899 
    900     if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
    901         if (!strcmp(buf, "on"))
    902 	    snapshot = 1;
    903         else if (!strcmp(buf, "off"))
    904 	    snapshot = 0;
    905 	else {
    906 	    fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
    907 	    return -1;
    908 	}
    909     }
    910 
    911     if (get_param_value(buf, sizeof(buf), "cache", str)) {
    912         if (!strcmp(buf, "off") || !strcmp(buf, "none"))
    913             cache = 0;
    914         else if (!strcmp(buf, "writethrough"))
    915             cache = 1;
    916         else if (!strcmp(buf, "writeback"))
    917             cache = 2;
    918         else {
    919            fprintf(stderr, "qemu: invalid cache option\n");
    920            return -1;
    921         }
    922     }
    923 
    924     if (get_param_value(buf, sizeof(buf), "format", str)) {
    925        if (strcmp(buf, "?") == 0) {
    926             fprintf(stderr, "qemu: Supported formats:");
    927             bdrv_iterate_format(bdrv_format_print, NULL);
    928             fprintf(stderr, "\n");
    929 	    return -1;
    930         }
    931         drv = bdrv_find_format(buf);
    932         if (!drv) {
    933             fprintf(stderr, "qemu: '%s' invalid format\n", buf);
    934             return -1;
    935         }
    936     }
    937 
    938     if (arg->file == NULL)
    939         get_param_value(file, sizeof(file), "file", str);
    940     else
    941         pstrcpy(file, sizeof(file), arg->file);
    942 
    943     if (!get_param_value(serial, sizeof(serial), "serial", str))
    944 	    memset(serial, 0,  sizeof(serial));
    945 
    946     onerror = BLOCK_ERR_STOP_ENOSPC;
    947     if (get_param_value(buf, sizeof(serial), "werror", str)) {
    948         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
    949             fprintf(stderr, "werror is no supported by this format\n");
    950             return -1;
    951         }
    952         if (!strcmp(buf, "ignore"))
    953             onerror = BLOCK_ERR_IGNORE;
    954         else if (!strcmp(buf, "enospc"))
    955             onerror = BLOCK_ERR_STOP_ENOSPC;
    956         else if (!strcmp(buf, "stop"))
    957             onerror = BLOCK_ERR_STOP_ANY;
    958         else if (!strcmp(buf, "report"))
    959             onerror = BLOCK_ERR_REPORT;
    960         else {
    961             fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
    962             return -1;
    963         }
    964     }
    965 
    966     /* compute bus and unit according index */
    967 
    968     if (index != -1) {
    969         if (bus_id != 0 || unit_id != -1) {
    970             fprintf(stderr,
    971                     "qemu: '%s' index cannot be used with bus and unit\n", str);
    972             return -1;
    973         }
    974         if (max_devs == 0)
    975         {
    976             unit_id = index;
    977             bus_id = 0;
    978         } else {
    979             unit_id = index % max_devs;
    980             bus_id = index / max_devs;
    981         }
    982     }
    983 
    984     /* if user doesn't specify a unit_id,
    985      * try to find the first free
    986      */
    987 
    988     if (unit_id == -1) {
    989        unit_id = 0;
    990        while (drive_get_index(type, bus_id, unit_id) != -1) {
    991            unit_id++;
    992            if (max_devs && unit_id >= max_devs) {
    993                unit_id -= max_devs;
    994                bus_id++;
    995            }
    996        }
    997     }
    998 
    999     /* check unit id */
   1000 
   1001     if (max_devs && unit_id >= max_devs) {
   1002         fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
   1003                         str, unit_id, max_devs - 1);
   1004         return -1;
   1005     }
   1006 
   1007     /*
   1008      * ignore multiple definitions
   1009      */
   1010 
   1011     if (drive_get_index(type, bus_id, unit_id) != -1)
   1012         return -2;
   1013 
   1014     /* init */
   1015 
   1016     if (type == IF_IDE || type == IF_SCSI)
   1017         mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
   1018     if (max_devs)
   1019         snprintf(buf, sizeof(buf), "%s%i%s%i",
   1020                  devname, bus_id, mediastr, unit_id);
   1021     else
   1022         snprintf(buf, sizeof(buf), "%s%s%i",
   1023                  devname, mediastr, unit_id);
   1024     bdrv = bdrv_new(buf);
   1025     drives_table_idx = drive_get_free_idx();
   1026     drives_table[drives_table_idx].bdrv = bdrv;
   1027     drives_table[drives_table_idx].type = type;
   1028     drives_table[drives_table_idx].bus = bus_id;
   1029     drives_table[drives_table_idx].unit = unit_id;
   1030     drives_table[drives_table_idx].onerror = onerror;
   1031     drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
   1032     strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
   1033     nb_drives++;
   1034 
   1035     switch(type) {
   1036     case IF_IDE:
   1037     case IF_SCSI:
   1038     case IF_XEN:
   1039         switch(media) {
   1040 	case MEDIA_DISK:
   1041             if (cyls != 0) {
   1042                 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
   1043                 bdrv_set_translation_hint(bdrv, translation);
   1044             }
   1045 	    break;
   1046 	case MEDIA_CDROM:
   1047             bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
   1048 	    break;
   1049 	}
   1050         break;
   1051     case IF_SD:
   1052         /* FIXME: This isn't really a floppy, but it's a reasonable
   1053            approximation.  */
   1054     case IF_FLOPPY:
   1055         bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
   1056         break;
   1057     case IF_PFLASH:
   1058     case IF_MTD:
   1059     case IF_VIRTIO:
   1060         break;
   1061     case IF_COUNT:
   1062     case IF_NONE:
   1063         abort();
   1064     }
   1065     if (!file[0])
   1066         return -2;
   1067     bdrv_flags = 0;
   1068     if (snapshot) {
   1069         bdrv_flags |= BDRV_O_SNAPSHOT;
   1070         cache = 2; /* always use write-back with snapshot */
   1071     }
   1072     if (cache == 0) /* no caching */
   1073         bdrv_flags |= BDRV_O_NOCACHE;
   1074     else if (cache == 2) /* write-back */
   1075         bdrv_flags |= BDRV_O_CACHE_WB;
   1076     else if (cache == 3) /* not specified */
   1077         bdrv_flags |= BDRV_O_CACHE_DEF;
   1078     if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
   1079         fprintf(stderr, "qemu: could not open disk image %s\n",
   1080                         file);
   1081         return -1;
   1082     }
   1083     if (bdrv_key_required(bdrv))
   1084         autostart = 0;
   1085     return drives_table_idx;
   1086 }
   1087 #endif /* MAX_DRIVES */
   1088 
   1089 static void numa_add(const char *optarg)
   1090 {
   1091     char option[128];
   1092     char *endptr;
   1093     unsigned long long value, endvalue;
   1094     int nodenr;
   1095 
   1096     optarg = get_opt_name(option, 128, optarg, ',') + 1;
   1097     if (!strcmp(option, "node")) {
   1098         if (get_param_value(option, 128, "nodeid", optarg) == 0) {
   1099             nodenr = nb_numa_nodes;
   1100         } else {
   1101             nodenr = strtoull(option, NULL, 10);
   1102         }
   1103 
   1104         if (get_param_value(option, 128, "mem", optarg) == 0) {
   1105             node_mem[nodenr] = 0;
   1106         } else {
   1107             value = strtoull(option, &endptr, 0);
   1108             switch (*endptr) {
   1109             case 0: case 'M': case 'm':
   1110                 value <<= 20;
   1111                 break;
   1112             case 'G': case 'g':
   1113                 value <<= 30;
   1114                 break;
   1115             }
   1116             node_mem[nodenr] = value;
   1117         }
   1118         if (get_param_value(option, 128, "cpus", optarg) == 0) {
   1119             node_cpumask[nodenr] = 0;
   1120         } else {
   1121             value = strtoull(option, &endptr, 10);
   1122             if (value >= 64) {
   1123                 value = 63;
   1124                 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
   1125             } else {
   1126                 if (*endptr == '-') {
   1127                     endvalue = strtoull(endptr+1, &endptr, 10);
   1128                     if (endvalue >= 63) {
   1129                         endvalue = 62;
   1130                         fprintf(stderr,
   1131                             "only 63 CPUs in NUMA mode supported.\n");
   1132                     }
   1133                     value = (1 << (endvalue + 1)) - (1 << value);
   1134                 } else {
   1135                     value = 1 << value;
   1136                 }
   1137             }
   1138             node_cpumask[nodenr] = value;
   1139         }
   1140         nb_numa_nodes++;
   1141     }
   1142     return;
   1143 }
   1144 
   1145 /***********************************************************/
   1146 /* PCMCIA/Cardbus */
   1147 
   1148 static struct pcmcia_socket_entry_s {
   1149     PCMCIASocket *socket;
   1150     struct pcmcia_socket_entry_s *next;
   1151 } *pcmcia_sockets = 0;
   1152 
   1153 void pcmcia_socket_register(PCMCIASocket *socket)
   1154 {
   1155     struct pcmcia_socket_entry_s *entry;
   1156 
   1157     entry = g_malloc(sizeof(struct pcmcia_socket_entry_s));
   1158     entry->socket = socket;
   1159     entry->next = pcmcia_sockets;
   1160     pcmcia_sockets = entry;
   1161 }
   1162 
   1163 void pcmcia_socket_unregister(PCMCIASocket *socket)
   1164 {
   1165     struct pcmcia_socket_entry_s *entry, **ptr;
   1166 
   1167     ptr = &pcmcia_sockets;
   1168     for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
   1169         if (entry->socket == socket) {
   1170             *ptr = entry->next;
   1171             g_free(entry);
   1172         }
   1173 }
   1174 
   1175 void pcmcia_info(Monitor *mon)
   1176 {
   1177     struct pcmcia_socket_entry_s *iter;
   1178 
   1179     if (!pcmcia_sockets)
   1180         monitor_printf(mon, "No PCMCIA sockets\n");
   1181 
   1182     for (iter = pcmcia_sockets; iter; iter = iter->next)
   1183         monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
   1184                        iter->socket->attached ? iter->socket->card_string :
   1185                        "Empty");
   1186 }
   1187 
   1188 /***********************************************************/
   1189 /* machine registration */
   1190 
   1191 static QEMUMachine *first_machine = NULL;
   1192 QEMUMachine *current_machine = NULL;
   1193 
   1194 int qemu_register_machine(QEMUMachine *m)
   1195 {
   1196     QEMUMachine **pm;
   1197     pm = &first_machine;
   1198     while (*pm != NULL)
   1199         pm = &(*pm)->next;
   1200     m->next = NULL;
   1201     *pm = m;
   1202     return 0;
   1203 }
   1204 
   1205 static QEMUMachine *find_machine(const char *name)
   1206 {
   1207     QEMUMachine *m;
   1208 
   1209     for(m = first_machine; m != NULL; m = m->next) {
   1210         if (!strcmp(m->name, name))
   1211             return m;
   1212     }
   1213     return NULL;
   1214 }
   1215 
   1216 static QEMUMachine *find_default_machine(void)
   1217 {
   1218     QEMUMachine *m;
   1219 
   1220     for(m = first_machine; m != NULL; m = m->next) {
   1221         if (m->is_default) {
   1222             return m;
   1223         }
   1224     }
   1225     return NULL;
   1226 }
   1227 
   1228 /***********************************************************/
   1229 /* main execution loop */
   1230 
   1231 static void gui_update(void *opaque)
   1232 {
   1233     uint64_t interval = GUI_REFRESH_INTERVAL;
   1234     DisplayState *ds = opaque;
   1235     DisplayChangeListener *dcl = ds->listeners;
   1236 
   1237     dpy_refresh(ds);
   1238 
   1239     while (dcl != NULL) {
   1240         if (dcl->gui_timer_interval &&
   1241             dcl->gui_timer_interval < interval)
   1242             interval = dcl->gui_timer_interval;
   1243         dcl = dcl->next;
   1244     }
   1245     timer_mod(ds->gui_timer, interval + qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
   1246 }
   1247 
   1248 static void nographic_update(void *opaque)
   1249 {
   1250     uint64_t interval = GUI_REFRESH_INTERVAL;
   1251 
   1252     timer_mod(nographic_timer, interval + qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
   1253 }
   1254 
   1255 struct vm_change_state_entry {
   1256     VMChangeStateHandler *cb;
   1257     void *opaque;
   1258     QLIST_ENTRY (vm_change_state_entry) entries;
   1259 };
   1260 
   1261 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
   1262 
   1263 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
   1264                                                      void *opaque)
   1265 {
   1266     VMChangeStateEntry *e;
   1267 
   1268     e = g_malloc0(sizeof (*e));
   1269 
   1270     e->cb = cb;
   1271     e->opaque = opaque;
   1272     QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
   1273     return e;
   1274 }
   1275 
   1276 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
   1277 {
   1278     QLIST_REMOVE (e, entries);
   1279     g_free (e);
   1280 }
   1281 
   1282 void vm_state_notify(int running, int reason)
   1283 {
   1284     VMChangeStateEntry *e;
   1285 
   1286     for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
   1287         e->cb(e->opaque, running, reason);
   1288     }
   1289 }
   1290 
   1291 void vm_start(void)
   1292 {
   1293     if (!vm_running) {
   1294         cpu_enable_ticks();
   1295         vm_running = 1;
   1296         vm_state_notify(1, 0);
   1297         //qemu_rearm_alarm_timer(alarm_timer);
   1298         resume_all_vcpus();
   1299     }
   1300 }
   1301 
   1302 /* reset/shutdown handler */
   1303 
   1304 typedef struct QEMUResetEntry {
   1305     QEMUResetHandler *func;
   1306     void *opaque;
   1307     int order;
   1308     struct QEMUResetEntry *next;
   1309 } QEMUResetEntry;
   1310 
   1311 static QEMUResetEntry *first_reset_entry;
   1312 static int reset_requested;
   1313 static int shutdown_requested, shutdown_signal = -1;
   1314 static pid_t shutdown_pid;
   1315 static int powerdown_requested;
   1316 int debug_requested;
   1317 static int vmstop_requested;
   1318 
   1319 int qemu_shutdown_requested(void)
   1320 {
   1321     int r = shutdown_requested;
   1322     shutdown_requested = 0;
   1323     return r;
   1324 }
   1325 
   1326 int qemu_reset_requested(void)
   1327 {
   1328     int r = reset_requested;
   1329     reset_requested = 0;
   1330     return r;
   1331 }
   1332 
   1333 int qemu_powerdown_requested(void)
   1334 {
   1335     int r = powerdown_requested;
   1336     powerdown_requested = 0;
   1337     return r;
   1338 }
   1339 
   1340 int qemu_debug_requested(void)
   1341 {
   1342     int r = debug_requested;
   1343     debug_requested = 0;
   1344     return r;
   1345 }
   1346 
   1347 int qemu_vmstop_requested(void)
   1348 {
   1349     int r = vmstop_requested;
   1350     vmstop_requested = 0;
   1351     return r;
   1352 }
   1353 
   1354 void qemu_register_reset(QEMUResetHandler *func, int order, void *opaque)
   1355 {
   1356     QEMUResetEntry **pre, *re;
   1357 
   1358     pre = &first_reset_entry;
   1359     while (*pre != NULL && (*pre)->order >= order) {
   1360         pre = &(*pre)->next;
   1361     }
   1362     re = g_malloc0(sizeof(QEMUResetEntry));
   1363     re->func = func;
   1364     re->opaque = opaque;
   1365     re->order = order;
   1366     re->next = NULL;
   1367     *pre = re;
   1368 }
   1369 
   1370 void qemu_system_reset(void)
   1371 {
   1372     QEMUResetEntry *re;
   1373 
   1374     /* reset all devices */
   1375     for(re = first_reset_entry; re != NULL; re = re->next) {
   1376         re->func(re->opaque);
   1377     }
   1378 }
   1379 
   1380 void qemu_system_reset_request(void)
   1381 {
   1382     if (no_reboot) {
   1383         shutdown_requested = 1;
   1384     } else {
   1385         reset_requested = 1;
   1386     }
   1387     qemu_notify_event();
   1388 }
   1389 
   1390 void qemu_system_killed(int signal, pid_t pid)
   1391 {
   1392     shutdown_signal = signal;
   1393     shutdown_pid = pid;
   1394     qemu_system_shutdown_request();
   1395 }
   1396 
   1397 void qemu_system_shutdown_request(void)
   1398 {
   1399     shutdown_requested = 1;
   1400     qemu_notify_event();
   1401 }
   1402 
   1403 void qemu_system_powerdown_request(void)
   1404 {
   1405     powerdown_requested = 1;
   1406     qemu_notify_event();
   1407 }
   1408 
   1409 int vm_can_run(void)
   1410 {
   1411     if (powerdown_requested)
   1412         return 0;
   1413     if (reset_requested)
   1414         return 0;
   1415     if (shutdown_requested)
   1416         return 0;
   1417     if (debug_requested)
   1418         return 0;
   1419     return 1;
   1420 }
   1421 
   1422 void version(void)
   1423 {
   1424     printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
   1425 }
   1426 
   1427 void qemu_help(int exitcode)
   1428 {
   1429     version();
   1430     printf("usage: %s [options] [disk_image]\n"
   1431            "\n"
   1432            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
   1433            "\n"
   1434 #define DEF(option, opt_arg, opt_enum, opt_help)        \
   1435            opt_help
   1436 #define DEFHEADING(text) stringify(text) "\n"
   1437 #include "qemu-options.def"
   1438 #undef DEF
   1439 #undef DEFHEADING
   1440 #undef GEN_DOCS
   1441            "\n"
   1442            "During emulation, the following keys are useful:\n"
   1443            "ctrl-alt-f      toggle full screen\n"
   1444            "ctrl-alt-n      switch to virtual console 'n'\n"
   1445            "ctrl-alt        toggle mouse and keyboard grab\n"
   1446            "\n"
   1447            "When using -nographic, press 'ctrl-a h' to get some help.\n"
   1448            ,
   1449            "qemu",
   1450            DEFAULT_RAM_SIZE,
   1451 #ifndef _WIN32
   1452            DEFAULT_NETWORK_SCRIPT,
   1453            DEFAULT_NETWORK_DOWN_SCRIPT,
   1454 #endif
   1455            DEFAULT_GDBSTUB_PORT,
   1456            "/tmp/qemu.log");
   1457     QEMU_EXIT(exitcode);
   1458 }
   1459 
   1460 #define HAS_ARG 0x0001
   1461 
   1462 enum {
   1463 #define DEF(option, opt_arg, opt_enum, opt_help)        \
   1464     opt_enum,
   1465 #define DEFHEADING(text)
   1466 #include "qemu-options.def"
   1467 #undef DEF
   1468 #undef DEFHEADING
   1469 #undef GEN_DOCS
   1470 };
   1471 
   1472 typedef struct QEMUOption {
   1473     const char *name;
   1474     int flags;
   1475     int index;
   1476 } QEMUOption;
   1477 
   1478 static const QEMUOption qemu_options[] = {
   1479     { "h", 0, QEMU_OPTION_h },
   1480 #define DEF(option, opt_arg, opt_enum, opt_help)        \
   1481     { option, opt_arg, opt_enum },
   1482 #define DEFHEADING(text)
   1483 #include "qemu-options.def"
   1484 #undef DEF
   1485 #undef DEFHEADING
   1486 #undef GEN_DOCS
   1487     { NULL, 0, 0 },
   1488 };
   1489 
   1490 static void select_vgahw (const char *p)
   1491 {
   1492     const char *opts;
   1493 
   1494     cirrus_vga_enabled = 0;
   1495     std_vga_enabled = 0;
   1496     vmsvga_enabled = 0;
   1497     xenfb_enabled = 0;
   1498     if (strstart(p, "std", &opts)) {
   1499         std_vga_enabled = 1;
   1500     } else if (strstart(p, "cirrus", &opts)) {
   1501         cirrus_vga_enabled = 1;
   1502     } else if (strstart(p, "vmware", &opts)) {
   1503         vmsvga_enabled = 1;
   1504     } else if (strstart(p, "xenfb", &opts)) {
   1505         xenfb_enabled = 1;
   1506     } else if (!strstart(p, "none", &opts)) {
   1507     invalid_vga:
   1508         PANIC("Unknown vga type: %s", p);
   1509     }
   1510     while (*opts) {
   1511         const char *nextopt;
   1512 
   1513         if (strstart(opts, ",retrace=", &nextopt)) {
   1514             opts = nextopt;
   1515             if (strstart(opts, "dumb", &nextopt))
   1516                 vga_retrace_method = VGA_RETRACE_DUMB;
   1517             else if (strstart(opts, "precise", &nextopt))
   1518                 vga_retrace_method = VGA_RETRACE_PRECISE;
   1519             else goto invalid_vga;
   1520         } else goto invalid_vga;
   1521         opts = nextopt;
   1522     }
   1523 }
   1524 
   1525 #define MAX_NET_CLIENTS 32
   1526 
   1527 #ifdef _WIN32
   1528 /* Look for support files in the same directory as the executable.  */
   1529 static char *find_datadir(const char *argv0)
   1530 {
   1531     char *p;
   1532     char buf[MAX_PATH];
   1533     DWORD len;
   1534 
   1535     len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
   1536     if (len == 0) {
   1537         return NULL;
   1538     }
   1539 
   1540     buf[len] = 0;
   1541     p = buf + len - 1;
   1542     while (p != buf && *p != '\\')
   1543         p--;
   1544     *p = 0;
   1545     if (access(buf, R_OK) == 0) {
   1546         return g_strdup(buf);
   1547     }
   1548     return NULL;
   1549 }
   1550 #else /* !_WIN32 */
   1551 
   1552 /* Similarly, return the location of the executable */
   1553 static char *find_datadir(const char *argv0)
   1554 {
   1555     char *p = NULL;
   1556     char buf[PATH_MAX];
   1557 
   1558 #if defined(__linux__)
   1559     {
   1560         int len;
   1561         len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
   1562         if (len > 0) {
   1563             buf[len] = 0;
   1564             p = buf;
   1565         }
   1566     }
   1567 #elif defined(__FreeBSD__)
   1568     {
   1569         int len;
   1570         len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
   1571         if (len > 0) {
   1572             buf[len] = 0;
   1573             p = buf;
   1574         }
   1575     }
   1576 #endif
   1577     /* If we don't have any way of figuring out the actual executable
   1578        location then try argv[0].  */
   1579     if (!p) {
   1580         p = realpath(argv0, buf);
   1581         if (!p) {
   1582             return NULL;
   1583         }
   1584     }
   1585 
   1586     return g_strdup(dirname(buf));
   1587 }
   1588 #endif
   1589 
   1590 static char*
   1591 qemu_find_file_with_subdir(const char* data_dir, const char* subdir, const char* name)
   1592 {
   1593     int   len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
   1594     char* buf = g_malloc0(len);
   1595 
   1596     snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
   1597     VERBOSE_PRINT(init,"    trying to find: %s\n", buf);
   1598     if (access(buf, R_OK)) {
   1599         g_free(buf);
   1600         return NULL;
   1601     }
   1602     return buf;
   1603 }
   1604 
   1605 char *qemu_find_file(int type, const char *name)
   1606 {
   1607     const char *subdir;
   1608     char *buf;
   1609 
   1610     /* If name contains path separators then try it as a straight path.  */
   1611     if ((strchr(name, '/') || strchr(name, '\\'))
   1612         && access(name, R_OK) == 0) {
   1613         return strdup(name);
   1614     }
   1615     switch (type) {
   1616     case QEMU_FILE_TYPE_BIOS:
   1617         subdir = "";
   1618         break;
   1619     case QEMU_FILE_TYPE_KEYMAP:
   1620         subdir = "keymaps/";
   1621         break;
   1622     default:
   1623         abort();
   1624     }
   1625     buf = qemu_find_file_with_subdir(data_dir, subdir, name);
   1626 #ifdef CONFIG_ANDROID
   1627     if (type == QEMU_FILE_TYPE_BIOS) {
   1628         /* This case corresponds to the emulator being used as part of an
   1629          * SDK installation. NOTE: data_dir is really $bindir. */
   1630         if (buf == NULL)
   1631             buf = qemu_find_file_with_subdir(data_dir, "lib/pc-bios/", name);
   1632         /* This case corresponds to platform builds. */
   1633         if (buf == NULL)
   1634             buf = qemu_find_file_with_subdir(data_dir, "../usr/share/pc-bios/", name);
   1635         /* Finally, try this for standalone builds under external/qemu */
   1636         if (buf == NULL)
   1637             buf = qemu_find_file_with_subdir(data_dir, "../../../prebuilts/qemu-kernel/x86/pc-bios/", name);
   1638     }
   1639 #endif
   1640     return buf;
   1641 }
   1642 
   1643 static int
   1644 add_dns_server( const char*  server_name )
   1645 {
   1646     SockAddress   addr;
   1647 
   1648     if (sock_address_init_resolve( &addr, server_name, 55, 0 ) < 0) {
   1649         fprintf(stdout,
   1650                 "### WARNING: can't resolve DNS server name '%s'\n",
   1651                 server_name );
   1652         return -1;
   1653     }
   1654 
   1655     fprintf(stderr,
   1656             "DNS server name '%s' resolved to %s\n", server_name, sock_address_to_string(&addr) );
   1657 
   1658     if ( slirp_add_dns_server( &addr ) < 0 ) {
   1659         fprintf(stderr,
   1660                 "### WARNING: could not add DNS server '%s' to the network stack\n", server_name);
   1661         return -1;
   1662     }
   1663     return 0;
   1664 }
   1665 
   1666 /* Parses an integer
   1667  * Pararm:
   1668  *  str      String containing a number to be parsed.
   1669  *  result   Passes the parsed integer in this argument
   1670  *  returns  0 if ok, -1 if failed
   1671  */
   1672 int
   1673 parse_int(const char *str, int *result)
   1674 {
   1675     char* r;
   1676     *result = strtol(str, &r, 0);
   1677     if (r == NULL || *r != '\0')
   1678       return -1;
   1679 
   1680     return 0;
   1681 }
   1682 
   1683 /* parses a null-terminated string specifying a network port (e.g., "80") or
   1684  * port range (e.g., "[6666-7000]"). In case of a single port, lport and hport
   1685  * are the same. Returns 0 on success, -1 on error. */
   1686 
   1687 int parse_port_range(const char *str, unsigned short *lport,
   1688                      unsigned short *hport) {
   1689 
   1690   unsigned int low = 0, high = 0;
   1691   char *p, *arg = strdup(str);
   1692 
   1693   if ((*arg == '[') && ((p = strrchr(arg, ']')) != NULL)) {
   1694     p = arg + 1;   /* skip '[' */
   1695     low  = atoi(strtok(p, "-"));
   1696     high = atoi(strtok(NULL, "-"));
   1697     if ((low > 0) && (high > 0) && (low < high) && (high < 65535)) {
   1698       *lport = low;
   1699       *hport = high;
   1700     }
   1701   }
   1702   else {
   1703     low = atoi(arg);
   1704     if ((0 < low) && (low < 65535)) {
   1705       *lport = low;
   1706       *hport = low;
   1707     }
   1708   }
   1709   free(arg);
   1710   if (low != 0)
   1711     return 0;
   1712   return -1;
   1713 }
   1714 
   1715 /*
   1716  * Implements the generic port forwarding option
   1717  */
   1718 void
   1719 net_slirp_forward(const char *optarg)
   1720 {
   1721     /*
   1722      * we expect the following format:
   1723      * dst_net:dst_mask:dst_port:redirect_ip:redirect_port OR
   1724      * dst_net:dst_mask:[dp_range_start-dp_range_end]:redirect_ip:redirect_port
   1725      */
   1726     char *argument = strdup(optarg), *p = argument;
   1727     char *dst_net, *dst_mask, *dst_port;
   1728     char *redirect_ip, *redirect_port;
   1729     uint32_t dnet, dmask, rip;
   1730     unsigned short dlport = 0, dhport = 0, rport;
   1731 
   1732 
   1733     dst_net = strtok(p, ":");
   1734     dst_mask = strtok(NULL, ":");
   1735     dst_port = strtok(NULL, ":");
   1736     redirect_ip = strtok(NULL, ":");
   1737     redirect_port = strtok(NULL, ":");
   1738 
   1739     if (dst_net == NULL || dst_mask == NULL || dst_port == NULL ||
   1740         redirect_ip == NULL || redirect_port == NULL) {
   1741         fprintf(stderr,
   1742                 "Invalid argument for -net-forward, we expect "
   1743                 "dst_net:dst_mask:dst_port:redirect_ip:redirect_port or "
   1744                 "dst_net:dst_mask:[dp_range_start-dp_range_end]"
   1745                 ":redirect_ip:redirect_port: %s\n",
   1746                 optarg);
   1747         exit(1);
   1748     }
   1749 
   1750     /* inet_strtoip converts dotted address to host byte order */
   1751     if (inet_strtoip(dst_net, &dnet) == -1) {
   1752         fprintf(stderr, "Invalid destination IP net: %s\n", dst_net);
   1753         exit(1);
   1754     }
   1755     if (inet_strtoip(dst_mask, &dmask) == -1) {
   1756         fprintf(stderr, "Invalid destination IP mask: %s\n", dst_mask);
   1757         exit(1);
   1758     }
   1759     if (inet_strtoip(redirect_ip, &rip) == -1) {
   1760         fprintf(stderr, "Invalid redirect IP address: %s\n", redirect_ip);
   1761         exit(1);
   1762     }
   1763 
   1764     if (parse_port_range(dst_port, &dlport, &dhport) == -1) {
   1765         fprintf(stderr, "Invalid destination port or port range\n");
   1766         exit(1);
   1767     }
   1768 
   1769     rport = atoi(redirect_port);
   1770     if (!rport) {
   1771         fprintf(stderr, "Invalid redirect port: %s\n", redirect_port);
   1772         exit(1);
   1773     }
   1774 
   1775     dnet &= dmask;
   1776 
   1777     slirp_add_net_forward(dnet, dmask, dlport, dhport,
   1778                           rip, rport);
   1779 
   1780     free(argument);
   1781 }
   1782 
   1783 
   1784 /* Parses an -allow-tcp or -allow-udp argument and inserts a corresponding
   1785  * entry in the allows list */
   1786 void
   1787 slirp_allow(const char *optarg, u_int8_t proto)
   1788 {
   1789   /*
   1790    * we expect the following format:
   1791    * dst_ip:dst_port OR dst_ip:[dst_lport-dst_hport]
   1792    */
   1793   char *argument = strdup(optarg), *p = argument;
   1794   char *dst_ip_str, *dst_port_str;
   1795   uint32_t dst_ip;
   1796   unsigned short dst_lport = 0, dst_hport = 0;
   1797 
   1798   dst_ip_str = strtok(p, ":");
   1799   dst_port_str = strtok(NULL, ":");
   1800 
   1801   if (dst_ip_str == NULL || dst_port_str == NULL) {
   1802     fprintf(stderr,
   1803             "Invalid argument %s for -allow. We expect "
   1804             "dst_ip:dst_port or dst_ip:[dst_lport-dst_hport]\n",
   1805             optarg);
   1806     exit(1);
   1807   }
   1808 
   1809   if (inet_strtoip(dst_ip_str, &dst_ip) == -1) {
   1810     fprintf(stderr, "Invalid destination IP address: %s\n", dst_ip_str);
   1811     exit(1);
   1812   }
   1813   if (parse_port_range(dst_port_str, &dst_lport, &dst_hport) == -1) {
   1814     fprintf(stderr, "Invalid destination port or port range\n");
   1815     exit(1);
   1816   }
   1817 
   1818   slirp_add_allow(dst_ip, dst_lport, dst_hport, proto);
   1819 
   1820   free(argument);
   1821 }
   1822 
   1823 /* Add a serial device at a given location in the emulated hardware table.
   1824  * On failure, this function aborts the program with an error message.
   1825  */
   1826 static void
   1827 serial_hds_add_at(int  index, const char* devname)
   1828 {
   1829     char label[32];
   1830 
   1831     if (!devname || !strcmp(devname,"none"))
   1832         return;
   1833 
   1834     if (index >= MAX_SERIAL_PORTS) {
   1835         PANIC("qemu: invalid serial index for %s (%d >= %d)",
   1836               devname, index, MAX_SERIAL_PORTS);
   1837     }
   1838     if (serial_hds[index] != NULL) {
   1839         PANIC("qemu: invalid serial index for %s (%d: already taken!)",
   1840               devname, index);
   1841     }
   1842     snprintf(label, sizeof(label), "serial%d", index);
   1843     serial_hds[index] = qemu_chr_open(label, devname, NULL);
   1844     if (!serial_hds[index]) {
   1845         PANIC("qemu: could not open serial device '%s'", devname);
   1846     }
   1847 }
   1848 
   1849 
   1850 /* Find a free slot in the emulated serial device table, and register
   1851  * it. Return the allocated table index.
   1852  */
   1853 static int
   1854 serial_hds_add(const char* devname)
   1855 {
   1856     int  index;
   1857 
   1858     /* Find first free slot */
   1859     for (index = 0; index < MAX_SERIAL_PORTS; index++) {
   1860         if (serial_hds[index] == NULL) {
   1861             serial_hds_add_at(index, devname);
   1862             return index;
   1863         }
   1864     }
   1865 
   1866     PANIC("qemu: too many serial devices registered (%d)", index);
   1867     return -1;  /* shouldn't happen */
   1868 }
   1869 
   1870 
   1871 // Extract the partition type/format of a given partition image
   1872 // from the content of fstab.goldfish.
   1873 // |fstab| is the address of the fstab.goldfish data in memory.
   1874 // |fstabSize| is its size in bytes.
   1875 // |partitionName| is the name of the partition for debugging
   1876 // purposes (e.g. 'userdata').
   1877 // |partitionPath| is the partition path as it appears in the
   1878 // fstab file (e.g. '/data').
   1879 // On success, sets |*partitionType| to an appropriate value,
   1880 // on failure (i.e. |partitionPath| does not appear in the fstab
   1881 // file), leave the value untouched.
   1882 void android_extractPartitionFormat(const char* fstab,
   1883                                     size_t fstabSize,
   1884                                     const char* partitionName,
   1885                                     const char* partitionPath,
   1886                                     AndroidPartitionType* partitionType) {
   1887     char* partFormat = NULL;
   1888     if (!android_parseFstabPartitionFormat(fstab, fstabSize, partitionPath,
   1889                                            &partFormat)) {
   1890         VERBOSE_PRINT(init, "Could not extract format of %s partition!",
   1891                       partitionName);
   1892         return;
   1893     }
   1894     VERBOSE_PRINT(init, "Found format of %s partition: '%s'",
   1895                   partitionName, partFormat);
   1896     *partitionType = androidPartitionType_fromString(partFormat);
   1897     free(partFormat);
   1898 }
   1899 
   1900 
   1901 // List of value describing how to handle partition images in
   1902 // android_nand_add_image() below, when no initiali partition image
   1903 // file is provided.
   1904 //
   1905 // MUST_EXIST means that the partition image must exist, otherwise
   1906 // dump an error message and exit.
   1907 //
   1908 // CREATE_IF_NEEDED means that if the partition image doesn't exist, an
   1909 // empty partition file should be created on demand.
   1910 //
   1911 // MUST_WIPE means that the partition image should be wiped cleaned,
   1912 // even if it exists. This is useful to implement the -wipe-data option.
   1913 typedef enum {
   1914     ANDROID_PARTITION_OPEN_MODE_MUST_EXIST,
   1915     ANDROID_PARTITION_OPEN_MODE_CREATE_IF_NEEDED,
   1916     ANDROID_PARTITION_OPEN_MODE_MUST_WIPE,
   1917 } AndroidPartitionOpenMode;
   1918 
   1919 // Add a NAND partition image to the hardware configuration.
   1920 // |part_name| is a string indicating the type of partition, i.e. "system",
   1921 // "userdata" or "cache".
   1922 // |part_type| is an enum describing the type of partition. If it is
   1923 // DISK_PARTITION_TYPE_PROBE, then try to auto-detect the type directly
   1924 // from the content of |part_file| or |part_init_file|.
   1925 // |part_size| is the partition size in bytes.
   1926 // |part_file| is the partition file path, can be NULL if |path_init_file|
   1927 // is not NULL.
   1928 // |part_init_file| is an optional path to the initialization partition file.
   1929 // |is_ext4| is true if the partition is formatted as EXT4, false for YAFFS2.
   1930 //
   1931 // The NAND partition will be backed by |path_file|, except in the following
   1932 // cases:
   1933 //    - |part_file| is NULL, or its value is "<temp>", indicating that a
   1934 //      new temporary image file must be used instead.
   1935 //
   1936 //    - |part_file| is not NULL, but the function fails to lock the file,
   1937 //      indicating it's already used by another instance. A warning should
   1938 //      be printed to warn the user, and a new temporary image should be
   1939 //      used.
   1940 //
   1941 // If |part_file| is not NULL and can be locked, if the partition image does
   1942 // not exit, then the file must be created as an empty partition.
   1943 //
   1944 // When a new partition image is created, what happens depends on the
   1945 // value of |is_ext4|:
   1946 //
   1947 //    - If |is_ext4| is false, a simple empty file is created, since that's
   1948 //      enough to create an empty YAFFS2 partition.
   1949 //
   1950 //    - If |is_ext4| is true, an "empty ext4" partition image is created
   1951 //      instead, which will _not_ be backed by an empty file.
   1952 //
   1953 // If |part_init_file| is not NULL, its content will be used to erase
   1954 // the content of the main partition image. This is automatically handled
   1955 // by the NAND code though.
   1956 //
   1957 void android_nand_add_image(const char* part_name,
   1958                             AndroidPartitionType part_type,
   1959                             AndroidPartitionOpenMode part_mode,
   1960                             uint64_t part_size,
   1961                             const char* part_file,
   1962                             const char* part_init_file)
   1963 {
   1964     char tmp[PATH_MAX * 2 + 32];
   1965 
   1966     // Sanitize parameters, an empty string must be the same as NULL.
   1967     if (part_file && !*part_file) {
   1968         part_file = NULL;
   1969     }
   1970     if (part_init_file && !*part_init_file) {
   1971         part_init_file = NULL;
   1972     }
   1973 
   1974     // Sanity checks.
   1975     if (part_size == 0) {
   1976         PANIC("Invalid %s partition size 0x%" PRIx64, part_size);
   1977     }
   1978 
   1979     if (part_init_file && !path_exists(part_init_file)) {
   1980         PANIC("Missing initial %s image: %s", part_name, part_init_file);
   1981     }
   1982 
   1983     // As a special case, a |part_file| of '<temp>' means a temporary
   1984     // partition is needed.
   1985     if (part_file && !strcmp(part_file, "<temp>")) {
   1986         part_file = NULL;
   1987     }
   1988 
   1989     // Verify partition type, or probe it if needed.
   1990     {
   1991         const char* image_file = NULL;
   1992         if (part_file && path_exists(part_file)) {
   1993             image_file = part_file;
   1994         } else if (part_init_file) {
   1995             image_file = part_init_file;
   1996         } else if (part_type == ANDROID_PARTITION_TYPE_UNKNOWN) {
   1997             PANIC("Cannot determine type of %s partition: no image files!",
   1998                   part_name);
   1999         }
   2000 
   2001         if (part_type == ANDROID_PARTITION_TYPE_UNKNOWN) {
   2002             VERBOSE_PRINT(init, "Probing %s image file for partition type: %s",
   2003                         part_name, image_file);
   2004 
   2005             part_type = androidPartitionType_probeFile(image_file);
   2006         } else {
   2007             // Probe the current image file to check that it is of the
   2008             // right partition format.
   2009             if (image_file) {
   2010                 AndroidPartitionType image_type =
   2011                         androidPartitionType_probeFile(image_file);
   2012                 if (image_type == ANDROID_PARTITION_TYPE_UNKNOWN) {
   2013                     PANIC("Cannot determine %s partition type of: %s",
   2014                           part_name,
   2015                           image_file);
   2016                 }
   2017 
   2018                 if (image_type != part_type) {
   2019                     PANIC("Invalid %s partition image type: %s (expected %s)",
   2020                         part_name,
   2021                         androidPartitionType_toString(image_type),
   2022                         androidPartitionType_toString(part_type));
   2023                 }
   2024             }
   2025         }
   2026     }
   2027 
   2028     VERBOSE_PRINT(init, "%s partition format: %s", part_name,
   2029                   androidPartitionType_toString(part_type));
   2030 
   2031     snprintf(tmp, sizeof tmp, "%s,size=0x%" PRIx64, part_name, part_size);
   2032 
   2033     bool need_temp_partition = true;
   2034     bool need_make_empty =
   2035             (part_mode == ANDROID_PARTITION_OPEN_MODE_MUST_WIPE);
   2036 
   2037     if (part_file) {
   2038         if (filelock_create(part_file) == NULL) {
   2039             fprintf(stderr,
   2040                     "WARNING: %s image already in use, changes will not persist!\n",
   2041                     part_name);
   2042         } else {
   2043             need_temp_partition = false;
   2044 
   2045             // If the partition image is missing, create it.
   2046             if (!path_exists(part_file)) {
   2047                 if (part_mode == ANDROID_PARTITION_OPEN_MODE_MUST_EXIST) {
   2048                     PANIC("Missing %s partition image: %s", part_name,
   2049                           part_file);
   2050                 }
   2051                 if (path_empty_file(part_file) < 0) {
   2052                     PANIC("Cannot create %s image file at %s: %s",
   2053                           part_name,
   2054                           part_file,
   2055                           strerror(errno));
   2056                 }
   2057                 need_make_empty = true;
   2058             }
   2059         }
   2060     }
   2061 
   2062     // Do we need a temporary partition image ?
   2063     if (need_temp_partition) {
   2064         TempFile* temp_file = tempfile_create();
   2065         if (temp_file == NULL) {
   2066             PANIC("Could not create temp file for %s partition image: %s\n",
   2067                    part_name);
   2068         }
   2069         part_file = tempfile_path(temp_file);
   2070         VERBOSE_PRINT(init,
   2071                       "Mapping '%s' partition image to %s",
   2072                       part_name,
   2073                       part_file);
   2074 
   2075         need_make_empty = true;
   2076     }
   2077 
   2078     pstrcat(tmp, sizeof tmp, ",file=");
   2079     pstrcat(tmp, sizeof tmp, part_file);
   2080 
   2081     // Do we need to make the partition image empty?
   2082     // Do not do it if there is an initial file though since it will
   2083     // get copied directly by the NAND code into the image.
   2084     if (need_make_empty && !part_init_file) {
   2085         VERBOSE_PRINT(init,
   2086                       "Creating empty %s partition image at: %s",
   2087                       part_name,
   2088                       part_file);
   2089         int ret = androidPartitionType_makeEmptyFile(part_type,
   2090                                                      part_size,
   2091                                                      part_file);
   2092         if (ret < 0) {
   2093             PANIC("Could not create %s image file at %s: %s",
   2094                   part_name,
   2095                   part_file,
   2096                   strerror(-ret));
   2097         }
   2098     }
   2099 
   2100     if (part_init_file) {
   2101         pstrcat(tmp, sizeof tmp, ",initfile=");
   2102         pstrcat(tmp, sizeof tmp, part_init_file);
   2103     }
   2104 
   2105     if (part_type == ANDROID_PARTITION_TYPE_EXT4) {
   2106         // Using a nand device to approximate a block device until full
   2107         // support is added.
   2108         pstrcat(tmp, sizeof tmp,",pagesize=512,extrasize=0");
   2109     }
   2110 
   2111     nand_add_dev(tmp);
   2112 }
   2113 
   2114 
   2115 int main(int argc, char **argv, char **envp)
   2116 {
   2117     const char *gdbstub_dev = NULL;
   2118     uint32_t boot_devices_bitmap = 0;
   2119     int i;
   2120     int snapshot, linux_boot, __attribute__((unused)) net_boot;
   2121     const char *icount_option = NULL;
   2122     const char *initrd_filename;
   2123     const char *kernel_filename, *kernel_cmdline;
   2124     const char *boot_devices = "";
   2125     DisplayState *ds;
   2126     DisplayChangeListener *dcl;
   2127     int cyls, heads, secs, translation;
   2128     QemuOpts *hda_opts = NULL;
   2129     QemuOpts *hdb_opts = NULL;
   2130     const char *net_clients[MAX_NET_CLIENTS];
   2131     int nb_net_clients;
   2132     int optind;
   2133     const char *r, *optarg;
   2134     CharDriverState *monitor_hd = NULL;
   2135     const char *monitor_device;
   2136     const char *serial_devices[MAX_SERIAL_PORTS];
   2137     int serial_device_index;
   2138     const char *parallel_devices[MAX_PARALLEL_PORTS];
   2139     int parallel_device_index;
   2140     const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
   2141     int virtio_console_index;
   2142     const char *loadvm = NULL;
   2143     QEMUMachine *machine;
   2144     const char *cpu_model;
   2145     int tb_size;
   2146     const char *pid_file = NULL;
   2147     const char *incoming = NULL;
   2148     const char* log_mask = NULL;
   2149     const char* log_file = NULL;
   2150     CPUState *cpu;
   2151     int show_vnc_port = 0;
   2152     IniFile*  hw_ini = NULL;
   2153     STRALLOC_DEFINE(kernel_params);
   2154     STRALLOC_DEFINE(kernel_config);
   2155     int    dns_count = 0;
   2156 
   2157     /* Initialize sockets before anything else, so we can properly report
   2158      * initialization failures back to the UI. */
   2159 #ifdef _WIN32
   2160     socket_init();
   2161 #endif
   2162 
   2163     init_clocks();
   2164 
   2165     qemu_cache_utils_init();
   2166 
   2167     QLIST_INIT (&vm_change_state_head);
   2168     os_setup_early_signal_handling();
   2169 
   2170     module_call_init(MODULE_INIT_MACHINE);
   2171     machine = find_default_machine();
   2172     cpu_model = NULL;
   2173     initrd_filename = NULL;
   2174     ram_size = 0;
   2175     snapshot = 0;
   2176     kernel_filename = NULL;
   2177     kernel_cmdline = "";
   2178 
   2179     cyls = heads = secs = 0;
   2180     translation = BIOS_ATA_TRANSLATION_AUTO;
   2181     monitor_device = "vc:80Cx24C";
   2182 
   2183     serial_devices[0] = "vc:80Cx24C";
   2184     for(i = 1; i < MAX_SERIAL_PORTS; i++)
   2185         serial_devices[i] = NULL;
   2186     serial_device_index = 0;
   2187 
   2188     parallel_devices[0] = "vc:80Cx24C";
   2189     for(i = 1; i < MAX_PARALLEL_PORTS; i++)
   2190         parallel_devices[i] = NULL;
   2191     parallel_device_index = 0;
   2192 
   2193     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
   2194         virtio_consoles[i] = NULL;
   2195     virtio_console_index = 0;
   2196 
   2197     for (i = 0; i < MAX_NODES; i++) {
   2198         node_mem[i] = 0;
   2199         node_cpumask[i] = 0;
   2200     }
   2201 
   2202     nb_net_clients = 0;
   2203 #ifdef MAX_DRIVES
   2204     nb_drives = 0;
   2205     nb_drives_opt = 0;
   2206 #endif
   2207     nb_numa_nodes = 0;
   2208 
   2209     nb_nics = 0;
   2210 
   2211     tb_size = 0;
   2212     autostart= 1;
   2213 
   2214     register_watchdogs();
   2215 
   2216     /* Initialize boot properties. */
   2217     boot_property_init_service();
   2218     android_hw_control_init();
   2219     android_net_pipes_init();
   2220 
   2221 #ifdef CONFIG_KVM
   2222     /* By default, force auto-detection for kvm */
   2223     kvm_allowed = -1;
   2224 #endif
   2225 
   2226     optind = 1;
   2227     for(;;) {
   2228         if (optind >= argc)
   2229             break;
   2230         r = argv[optind];
   2231         if (r[0] != '-') {
   2232             hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
   2233         } else {
   2234             const QEMUOption *popt;
   2235 
   2236             optind++;
   2237             /* Treat --foo the same as -foo.  */
   2238             if (r[1] == '-')
   2239                 r++;
   2240             popt = qemu_options;
   2241             for(;;) {
   2242                 if (!popt->name) {
   2243                     PANIC("%s: invalid option -- '%s'",
   2244                                       argv[0], r);
   2245                 }
   2246                 if (!strcmp(popt->name, r + 1))
   2247                     break;
   2248                 popt++;
   2249             }
   2250             if (popt->flags & HAS_ARG) {
   2251                 if (optind >= argc) {
   2252                     PANIC("%s: option '%s' requires an argument",
   2253                                       argv[0], r);
   2254                 }
   2255                 optarg = argv[optind++];
   2256             } else {
   2257                 optarg = NULL;
   2258             }
   2259 
   2260             switch(popt->index) {
   2261             case QEMU_OPTION_M:
   2262                 machine = find_machine(optarg);
   2263                 if (!machine) {
   2264                     QEMUMachine *m;
   2265                     printf("Supported machines are:\n");
   2266                     for(m = first_machine; m != NULL; m = m->next) {
   2267                         printf("%-10s %s%s\n",
   2268                                m->name, m->desc,
   2269                                m->is_default ? " (default)" : "");
   2270                     }
   2271                     if (*optarg != '?') {
   2272                         PANIC("Invalid machine parameter: %s",
   2273                                           optarg);
   2274                     } else {
   2275                         QEMU_EXIT(0);
   2276                     }
   2277                 }
   2278                 break;
   2279             case QEMU_OPTION_cpu:
   2280                 /* hw initialization will check this */
   2281                 if (*optarg == '?') {
   2282 /* XXX: implement xxx_cpu_list for targets that still miss it */
   2283 #if defined(cpu_list)
   2284                     cpu_list(stdout, &fprintf);
   2285 #endif
   2286                     QEMU_EXIT(0);
   2287                 } else {
   2288                     cpu_model = optarg;
   2289                 }
   2290                 break;
   2291             case QEMU_OPTION_initrd:
   2292                 initrd_filename = optarg;
   2293                 break;
   2294             case QEMU_OPTION_hda:
   2295                 if (cyls == 0)
   2296                     hda_opts = drive_add(optarg, HD_ALIAS, 0);
   2297                 else
   2298                     hda_opts = drive_add(optarg, HD_ALIAS
   2299 			     ",cyls=%d,heads=%d,secs=%d%s",
   2300                              0, cyls, heads, secs,
   2301                              translation == BIOS_ATA_TRANSLATION_LBA ?
   2302                                  ",trans=lba" :
   2303                              translation == BIOS_ATA_TRANSLATION_NONE ?
   2304                                  ",trans=none" : "");
   2305                  break;
   2306             case QEMU_OPTION_hdb:
   2307                 hdb_opts = drive_add(optarg, HD_ALIAS, 1);
   2308                 break;
   2309 
   2310             case QEMU_OPTION_hdc:
   2311             case QEMU_OPTION_hdd:
   2312                 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
   2313                 break;
   2314             case QEMU_OPTION_drive:
   2315                 drive_add(NULL, "%s", optarg);
   2316 	        break;
   2317             case QEMU_OPTION_mtdblock:
   2318                 drive_add(optarg, MTD_ALIAS);
   2319                 break;
   2320             case QEMU_OPTION_sd:
   2321                 drive_add(optarg, SD_ALIAS);
   2322                 break;
   2323             case QEMU_OPTION_pflash:
   2324                 drive_add(optarg, PFLASH_ALIAS);
   2325                 break;
   2326             case QEMU_OPTION_snapshot:
   2327                 snapshot = 1;
   2328                 break;
   2329             case QEMU_OPTION_hdachs:
   2330                 {
   2331                     const char *p;
   2332                     p = optarg;
   2333                     cyls = strtol(p, (char **)&p, 0);
   2334                     if (cyls < 1 || cyls > 16383)
   2335                         goto chs_fail;
   2336                     if (*p != ',')
   2337                         goto chs_fail;
   2338                     p++;
   2339                     heads = strtol(p, (char **)&p, 0);
   2340                     if (heads < 1 || heads > 16)
   2341                         goto chs_fail;
   2342                     if (*p != ',')
   2343                         goto chs_fail;
   2344                     p++;
   2345                     secs = strtol(p, (char **)&p, 0);
   2346                     if (secs < 1 || secs > 63)
   2347                         goto chs_fail;
   2348                     if (*p == ',') {
   2349                         p++;
   2350                         if (!strcmp(p, "none"))
   2351                             translation = BIOS_ATA_TRANSLATION_NONE;
   2352                         else if (!strcmp(p, "lba"))
   2353                             translation = BIOS_ATA_TRANSLATION_LBA;
   2354                         else if (!strcmp(p, "auto"))
   2355                             translation = BIOS_ATA_TRANSLATION_AUTO;
   2356                         else
   2357                             goto chs_fail;
   2358                     } else if (*p != '\0') {
   2359                     chs_fail:
   2360                         PANIC("qemu: invalid physical CHS format");
   2361                     }
   2362 		    if (hda_opts != NULL) {
   2363                         char num[16];
   2364                         snprintf(num, sizeof(num), "%d", cyls);
   2365                         qemu_opt_set(hda_opts, "cyls", num);
   2366                         snprintf(num, sizeof(num), "%d", heads);
   2367                         qemu_opt_set(hda_opts, "heads", num);
   2368                         snprintf(num, sizeof(num), "%d", secs);
   2369                         qemu_opt_set(hda_opts, "secs", num);
   2370                         if (translation == BIOS_ATA_TRANSLATION_LBA)
   2371                             qemu_opt_set(hda_opts, "trans", "lba");
   2372                         if (translation == BIOS_ATA_TRANSLATION_NONE)
   2373                             qemu_opt_set(hda_opts, "trans", "none");
   2374                     }
   2375                 }
   2376                 break;
   2377             case QEMU_OPTION_numa:
   2378                 if (nb_numa_nodes >= MAX_NODES) {
   2379                     PANIC("qemu: too many NUMA nodes");
   2380                 }
   2381                 numa_add(optarg);
   2382                 break;
   2383             case QEMU_OPTION_nographic:
   2384                 display_type = DT_NOGRAPHIC;
   2385                 break;
   2386 #ifdef CONFIG_CURSES
   2387             case QEMU_OPTION_curses:
   2388                 display_type = DT_CURSES;
   2389                 break;
   2390 #endif
   2391             case QEMU_OPTION_portrait:
   2392                 graphic_rotate = 1;
   2393                 break;
   2394             case QEMU_OPTION_kernel:
   2395                 kernel_filename = optarg;
   2396                 break;
   2397             case QEMU_OPTION_append:
   2398                 kernel_cmdline = optarg;
   2399                 break;
   2400             case QEMU_OPTION_cdrom:
   2401                 drive_add(optarg, CDROM_ALIAS);
   2402                 break;
   2403             case QEMU_OPTION_boot:
   2404                 boot_devices = optarg;
   2405                 /* We just do some generic consistency checks */
   2406                 {
   2407                     /* Could easily be extended to 64 devices if needed */
   2408                     const char *p;
   2409 
   2410                     boot_devices_bitmap = 0;
   2411                     for (p = boot_devices; *p != '\0'; p++) {
   2412                         /* Allowed boot devices are:
   2413                          * a b     : floppy disk drives
   2414                          * c ... f : IDE disk drives
   2415                          * g ... m : machine implementation dependant drives
   2416                          * n ... p : network devices
   2417                          * It's up to each machine implementation to check
   2418                          * if the given boot devices match the actual hardware
   2419                          * implementation and firmware features.
   2420                          */
   2421                         if (*p < 'a' || *p > 'q') {
   2422                             PANIC("Invalid boot device '%c'", *p);
   2423                         }
   2424                         if (boot_devices_bitmap & (1 << (*p - 'a'))) {
   2425                             PANIC(
   2426                                     "Boot device '%c' was given twice",*p);
   2427                         }
   2428                         boot_devices_bitmap |= 1 << (*p - 'a');
   2429                     }
   2430                 }
   2431                 break;
   2432             case QEMU_OPTION_fda:
   2433             case QEMU_OPTION_fdb:
   2434                 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
   2435                 break;
   2436 #ifdef TARGET_I386
   2437             case QEMU_OPTION_no_fd_bootchk:
   2438                 fd_bootchk = 0;
   2439                 break;
   2440 #endif
   2441             case QEMU_OPTION_net:
   2442                 if (nb_net_clients >= MAX_NET_CLIENTS) {
   2443                     PANIC("qemu: too many network clients");
   2444                 }
   2445                 net_clients[nb_net_clients] = optarg;
   2446                 nb_net_clients++;
   2447                 break;
   2448 #ifdef CONFIG_SLIRP
   2449             case QEMU_OPTION_tftp:
   2450 		tftp_prefix = optarg;
   2451                 break;
   2452             case QEMU_OPTION_bootp:
   2453                 bootp_filename = optarg;
   2454                 break;
   2455             case QEMU_OPTION_redir:
   2456                 net_slirp_redir(NULL, optarg, NULL);
   2457                 break;
   2458 #endif
   2459 #ifdef HAS_AUDIO
   2460             case QEMU_OPTION_audio_help:
   2461                 AUD_help ();
   2462                 QEMU_EXIT(0);
   2463                 break;
   2464             case QEMU_OPTION_soundhw:
   2465                 select_soundhw (optarg);
   2466                 break;
   2467 #endif
   2468             case QEMU_OPTION_h:
   2469                 qemu_help(0);
   2470                 break;
   2471             case QEMU_OPTION_version:
   2472                 version();
   2473                 QEMU_EXIT(0);
   2474                 break;
   2475             case QEMU_OPTION_m: {
   2476                 uint64_t value;
   2477                 char *ptr;
   2478 
   2479                 value = strtoul(optarg, &ptr, 10);
   2480                 switch (*ptr) {
   2481                 case 0: case 'M': case 'm':
   2482                     value <<= 20;
   2483                     break;
   2484                 case 'G': case 'g':
   2485                     value <<= 30;
   2486                     break;
   2487                 default:
   2488                     PANIC("qemu: invalid ram size: %s", optarg);
   2489                 }
   2490 
   2491                 /* On 32-bit hosts, QEMU is limited by virtual address space */
   2492                 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
   2493                     PANIC("qemu: at most 2047 MB RAM can be simulated");
   2494                 }
   2495                 if (value != (uint64_t)(ram_addr_t)value) {
   2496                     PANIC("qemu: ram size too large");
   2497                 }
   2498                 ram_size = value;
   2499                 break;
   2500             }
   2501             case QEMU_OPTION_d:
   2502                 log_mask = optarg;
   2503                 break;
   2504             case QEMU_OPTION_s:
   2505                 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
   2506                 break;
   2507             case QEMU_OPTION_gdb:
   2508                 gdbstub_dev = optarg;
   2509                 break;
   2510             case QEMU_OPTION_L:
   2511                 data_dir = optarg;
   2512                 break;
   2513             case QEMU_OPTION_bios:
   2514                 bios_name = optarg;
   2515                 break;
   2516             case QEMU_OPTION_singlestep:
   2517                 singlestep = 1;
   2518                 break;
   2519             case QEMU_OPTION_S:
   2520                 autostart = 0;
   2521                 break;
   2522 #ifndef _WIN32
   2523 	    case QEMU_OPTION_k:
   2524 		keyboard_layout = optarg;
   2525 		break;
   2526 #endif
   2527             case QEMU_OPTION_localtime:
   2528                 rtc_utc = 0;
   2529                 break;
   2530             case QEMU_OPTION_vga:
   2531                 select_vgahw (optarg);
   2532                 break;
   2533 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
   2534             case QEMU_OPTION_g:
   2535                 {
   2536                     const char *p;
   2537                     int w, h, depth;
   2538                     p = optarg;
   2539                     w = strtol(p, (char **)&p, 10);
   2540                     if (w <= 0) {
   2541                     graphic_error:
   2542                         PANIC("qemu: invalid resolution or depth");
   2543                     }
   2544                     if (*p != 'x')
   2545                         goto graphic_error;
   2546                     p++;
   2547                     h = strtol(p, (char **)&p, 10);
   2548                     if (h <= 0)
   2549                         goto graphic_error;
   2550                     if (*p == 'x') {
   2551                         p++;
   2552                         depth = strtol(p, (char **)&p, 10);
   2553                         if (depth != 8 && depth != 15 && depth != 16 &&
   2554                             depth != 24 && depth != 32)
   2555                             goto graphic_error;
   2556                     } else if (*p == '\0') {
   2557                         depth = graphic_depth;
   2558                     } else {
   2559                         goto graphic_error;
   2560                     }
   2561 
   2562                     graphic_width = w;
   2563                     graphic_height = h;
   2564                     graphic_depth = depth;
   2565                 }
   2566                 break;
   2567 #endif
   2568             case QEMU_OPTION_echr:
   2569                 {
   2570                     char *r;
   2571                     term_escape_char = strtol(optarg, &r, 0);
   2572                     if (r == optarg)
   2573                         printf("Bad argument to echr\n");
   2574                     break;
   2575                 }
   2576             case QEMU_OPTION_monitor:
   2577                 monitor_device = optarg;
   2578                 break;
   2579             case QEMU_OPTION_serial:
   2580                 if (serial_device_index >= MAX_SERIAL_PORTS) {
   2581                     PANIC("qemu: too many serial ports");
   2582                 }
   2583                 serial_devices[serial_device_index] = optarg;
   2584                 serial_device_index++;
   2585                 break;
   2586             case QEMU_OPTION_watchdog:
   2587                 i = select_watchdog(optarg);
   2588                 if (i > 0) {
   2589                     if (i == 1) {
   2590                         PANIC("Invalid watchdog parameter: %s",
   2591                                           optarg);
   2592                     } else {
   2593                         QEMU_EXIT(0);
   2594                     }
   2595                 }
   2596                 break;
   2597             case QEMU_OPTION_watchdog_action:
   2598                 if (select_watchdog_action(optarg) == -1) {
   2599                     PANIC("Unknown -watchdog-action parameter");
   2600                 }
   2601                 break;
   2602             case QEMU_OPTION_virtiocon:
   2603                 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
   2604                     PANIC("qemu: too many virtio consoles");
   2605                 }
   2606                 virtio_consoles[virtio_console_index] = optarg;
   2607                 virtio_console_index++;
   2608                 break;
   2609             case QEMU_OPTION_parallel:
   2610                 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
   2611                     PANIC("qemu: too many parallel ports");
   2612                 }
   2613                 parallel_devices[parallel_device_index] = optarg;
   2614                 parallel_device_index++;
   2615                 break;
   2616             case QEMU_OPTION_loadvm:
   2617                 loadvm = optarg;
   2618                 break;
   2619             case QEMU_OPTION_savevm_on_exit:
   2620                 savevm_on_exit = optarg;
   2621                 break;
   2622             case QEMU_OPTION_full_screen:
   2623                 full_screen = 1;
   2624                 break;
   2625 #ifdef CONFIG_SDL
   2626             case QEMU_OPTION_no_frame:
   2627                 no_frame = 1;
   2628                 break;
   2629             case QEMU_OPTION_alt_grab:
   2630                 alt_grab = 1;
   2631                 break;
   2632             case QEMU_OPTION_no_quit:
   2633                 no_quit = 1;
   2634                 break;
   2635             case QEMU_OPTION_sdl:
   2636                 display_type = DT_SDL;
   2637                 break;
   2638 #endif
   2639             case QEMU_OPTION_pidfile:
   2640                 pid_file = optarg;
   2641                 break;
   2642 #ifdef TARGET_I386
   2643             case QEMU_OPTION_win2k_hack:
   2644                 win2k_install_hack = 1;
   2645                 break;
   2646             case QEMU_OPTION_rtc_td_hack:
   2647                 rtc_td_hack = 1;
   2648                 break;
   2649 #ifndef CONFIG_ANDROID
   2650             case QEMU_OPTION_acpitable:
   2651                 if(acpi_table_add(optarg) < 0) {
   2652                     PANIC("Wrong acpi table provided");
   2653                 }
   2654                 break;
   2655 #endif
   2656             case QEMU_OPTION_smbios:
   2657                 do_smbios_option(optarg);
   2658                 break;
   2659 #endif
   2660 #ifdef CONFIG_KVM
   2661             case QEMU_OPTION_enable_kvm:
   2662                 kvm_allowed = 1;
   2663                 break;
   2664             case QEMU_OPTION_disable_kvm:
   2665                 kvm_allowed = 0;
   2666                 break;
   2667 #endif /* CONFIG_KVM */
   2668             case QEMU_OPTION_smp:
   2669                 smp_cpus = atoi(optarg);
   2670                 if (smp_cpus < 1) {
   2671                     PANIC("Invalid number of CPUs");
   2672                 }
   2673                 break;
   2674 	    case QEMU_OPTION_vnc:
   2675                 display_type = DT_VNC;
   2676 		vnc_display = optarg;
   2677 		break;
   2678 #ifdef TARGET_I386
   2679             case QEMU_OPTION_no_acpi:
   2680                 acpi_enabled = 0;
   2681                 break;
   2682             case QEMU_OPTION_no_hpet:
   2683                 no_hpet = 1;
   2684                 break;
   2685             case QEMU_OPTION_no_virtio_balloon:
   2686                 no_virtio_balloon = 1;
   2687                 break;
   2688 #endif
   2689             case QEMU_OPTION_no_reboot:
   2690                 no_reboot = 1;
   2691                 break;
   2692             case QEMU_OPTION_no_shutdown:
   2693                 no_shutdown = 1;
   2694                 break;
   2695             case QEMU_OPTION_show_cursor:
   2696                 cursor_hide = 0;
   2697                 break;
   2698             case QEMU_OPTION_uuid:
   2699                 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
   2700                     PANIC("Fail to parse UUID string. Wrong format.");
   2701                 }
   2702                 break;
   2703 	    case QEMU_OPTION_option_rom:
   2704 		if (nb_option_roms >= MAX_OPTION_ROMS) {
   2705 		    PANIC("Too many option ROMs");
   2706 		}
   2707 		option_rom[nb_option_roms] = optarg;
   2708 		nb_option_roms++;
   2709 		break;
   2710 #if defined(TARGET_ARM) || defined(TARGET_M68K)
   2711             case QEMU_OPTION_semihosting:
   2712                 semihosting_enabled = 1;
   2713                 break;
   2714 #endif
   2715             case QEMU_OPTION_name:
   2716                 qemu_name = optarg;
   2717                 break;
   2718 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
   2719             case QEMU_OPTION_prom_env:
   2720                 if (nb_prom_envs >= MAX_PROM_ENVS) {
   2721                     PANIC("Too many prom variables");
   2722                 }
   2723                 prom_envs[nb_prom_envs] = optarg;
   2724                 nb_prom_envs++;
   2725                 break;
   2726 #endif
   2727 #ifdef TARGET_ARM
   2728             case QEMU_OPTION_old_param:
   2729                 old_param = 1;
   2730                 break;
   2731 #endif
   2732             case QEMU_OPTION_clock:
   2733                 configure_alarms(optarg);
   2734                 break;
   2735             case QEMU_OPTION_startdate:
   2736                 {
   2737                     struct tm tm;
   2738                     time_t rtc_start_date = 0;
   2739                     if (!strcmp(optarg, "now")) {
   2740                         rtc_date_offset = -1;
   2741                     } else {
   2742                         if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
   2743                                &tm.tm_year,
   2744                                &tm.tm_mon,
   2745                                &tm.tm_mday,
   2746                                &tm.tm_hour,
   2747                                &tm.tm_min,
   2748                                &tm.tm_sec) == 6) {
   2749                             /* OK */
   2750                         } else if (sscanf(optarg, "%d-%d-%d",
   2751                                           &tm.tm_year,
   2752                                           &tm.tm_mon,
   2753                                           &tm.tm_mday) == 3) {
   2754                             tm.tm_hour = 0;
   2755                             tm.tm_min = 0;
   2756                             tm.tm_sec = 0;
   2757                         } else {
   2758                             goto date_fail;
   2759                         }
   2760                         tm.tm_year -= 1900;
   2761                         tm.tm_mon--;
   2762                         rtc_start_date = mktimegm(&tm);
   2763                         if (rtc_start_date == -1) {
   2764                         date_fail:
   2765                             PANIC("Invalid date format. Valid format are:\n"
   2766                                     "'now' or '2006-06-17T16:01:21' or '2006-06-17'");
   2767                         }
   2768                         rtc_date_offset = time(NULL) - rtc_start_date;
   2769                     }
   2770                 }
   2771                 break;
   2772 
   2773             /* -------------------------------------------------------*/
   2774             /* User mode network stack restrictions */
   2775             case QEMU_OPTION_drop_udp:
   2776                 slirp_drop_udp();
   2777                 break;
   2778             case QEMU_OPTION_drop_tcp:
   2779                 slirp_drop_tcp();
   2780                 break;
   2781             case QEMU_OPTION_allow_tcp:
   2782                 slirp_allow(optarg, IPPROTO_TCP);
   2783                 break;
   2784             case QEMU_OPTION_allow_udp:
   2785                 slirp_allow(optarg, IPPROTO_UDP);
   2786                 break;
   2787              case QEMU_OPTION_drop_log:
   2788                 {
   2789                     FILE* drop_log_fd;
   2790                     drop_log_filename = optarg;
   2791                     drop_log_fd = fopen(optarg, "w+");
   2792 
   2793                     if (!drop_log_fd) {
   2794                         fprintf(stderr, "Cannot open drop log: %s\n", optarg);
   2795                         exit(1);
   2796                     }
   2797 
   2798                     slirp_drop_log_fd(drop_log_fd);
   2799                 }
   2800                 break;
   2801 
   2802             case QEMU_OPTION_dns_log:
   2803                 {
   2804                     FILE* dns_log_fd;
   2805                     dns_log_filename = optarg;
   2806                     dns_log_fd = fopen(optarg, "wb+");
   2807 
   2808                     if (dns_log_fd == NULL) {
   2809                         fprintf(stderr, "Cannot open dns log: %s\n", optarg);
   2810                         exit(1);
   2811                     }
   2812 
   2813                     slirp_dns_log_fd(dns_log_fd);
   2814                 }
   2815                 break;
   2816 
   2817 
   2818             case QEMU_OPTION_max_dns_conns:
   2819                 {
   2820                     int max_dns_conns = 0;
   2821                     if (parse_int(optarg, &max_dns_conns)) {
   2822                       fprintf(stderr,
   2823                               "qemu: syntax: -max-dns-conns max_connections\n");
   2824                       exit(1);
   2825                     }
   2826                     if (max_dns_conns <= 0 ||  max_dns_conns == LONG_MAX) {
   2827                       fprintf(stderr,
   2828                               "Invalid arg for max dns connections: %s\n",
   2829                               optarg);
   2830                       exit(1);
   2831                     }
   2832                     slirp_set_max_dns_conns(max_dns_conns);
   2833                 }
   2834                 break;
   2835 
   2836             case QEMU_OPTION_net_forward:
   2837                 net_slirp_forward(optarg);
   2838                 break;
   2839             case QEMU_OPTION_net_forward_tcp2sink:
   2840                 {
   2841                     SockAddress saddr;
   2842 
   2843                     if (parse_host_port(&saddr, optarg)) {
   2844                         fprintf(stderr,
   2845                                 "Invalid ip/port %s for "
   2846                                 "-forward-dropped-tcp2sink. "
   2847                                 "We expect 'sink_ip:sink_port'\n",
   2848                                 optarg);
   2849                         exit(1);
   2850                     }
   2851                     slirp_forward_dropped_tcp2sink(saddr.u.inet.address,
   2852                                                    saddr.u.inet.port);
   2853                 }
   2854                 break;
   2855             /* -------------------------------------------------------*/
   2856 
   2857             case QEMU_OPTION_tb_size:
   2858                 tb_size = strtol(optarg, NULL, 0);
   2859                 if (tb_size < 0)
   2860                     tb_size = 0;
   2861                 break;
   2862             case QEMU_OPTION_icount:
   2863                 icount_option = optarg;
   2864                 break;
   2865             case QEMU_OPTION_incoming:
   2866                 incoming = optarg;
   2867                 break;
   2868 #ifdef CONFIG_XEN
   2869             case QEMU_OPTION_xen_domid:
   2870                 xen_domid = atoi(optarg);
   2871                 break;
   2872             case QEMU_OPTION_xen_create:
   2873                 xen_mode = XEN_CREATE;
   2874                 break;
   2875             case QEMU_OPTION_xen_attach:
   2876                 xen_mode = XEN_ATTACH;
   2877                 break;
   2878 #endif
   2879 
   2880 
   2881             case QEMU_OPTION_mic:
   2882                 audio_input_source = (char*)optarg;
   2883                 break;
   2884 #ifdef CONFIG_NAND
   2885             case QEMU_OPTION_nand:
   2886                 nand_add_dev(optarg);
   2887                 break;
   2888 
   2889 #endif
   2890 #ifdef CONFIG_HAX
   2891             case QEMU_OPTION_enable_hax:
   2892                 hax_disabled = 0;
   2893                 break;
   2894             case QEMU_OPTION_disable_hax:
   2895                 hax_disabled = 1;
   2896                 break;
   2897 #endif
   2898             case QEMU_OPTION_android_ports:
   2899                 android_op_ports = (char*)optarg;
   2900                 break;
   2901 
   2902             case QEMU_OPTION_android_port:
   2903                 android_op_port = (char*)optarg;
   2904                 break;
   2905 
   2906             case QEMU_OPTION_android_report_console:
   2907                 android_op_report_console = (char*)optarg;
   2908                 break;
   2909 
   2910             case QEMU_OPTION_http_proxy:
   2911                 op_http_proxy = (char*)optarg;
   2912                 break;
   2913 
   2914             case QEMU_OPTION_charmap:
   2915                 op_charmap_file = (char*)optarg;
   2916                 break;
   2917 
   2918             case QEMU_OPTION_android_hw:
   2919                 android_op_hwini = (char*)optarg;
   2920                 break;
   2921 
   2922             case QEMU_OPTION_dns_server:
   2923                 android_op_dns_server = (char*)optarg;
   2924                 break;
   2925 
   2926             case QEMU_OPTION_radio:
   2927                 android_op_radio = (char*)optarg;
   2928                 break;
   2929 
   2930             case QEMU_OPTION_gps:
   2931                 android_op_gps = (char*)optarg;
   2932                 break;
   2933 
   2934             case QEMU_OPTION_audio:
   2935                 android_op_audio = (char*)optarg;
   2936                 break;
   2937 
   2938             case QEMU_OPTION_cpu_delay:
   2939                 android_op_cpu_delay = (char*)optarg;
   2940                 break;
   2941 
   2942             case QEMU_OPTION_show_kernel:
   2943                 android_kmsg_init(ANDROID_KMSG_PRINT_MESSAGES);
   2944                 break;
   2945 
   2946 #ifdef CONFIG_NAND_LIMITS
   2947             case QEMU_OPTION_nand_limits:
   2948                 android_op_nand_limits = (char*)optarg;
   2949                 break;
   2950 #endif  // CONFIG_NAND_LIMITS
   2951 
   2952             case QEMU_OPTION_netspeed:
   2953                 android_op_netspeed = (char*)optarg;
   2954                 break;
   2955 
   2956             case QEMU_OPTION_netdelay:
   2957                 android_op_netdelay = (char*)optarg;
   2958                 break;
   2959 
   2960             case QEMU_OPTION_netfast:
   2961                 android_op_netfast = 1;
   2962                 break;
   2963 
   2964             case QEMU_OPTION_tcpdump:
   2965                 android_op_tcpdump = (char*)optarg;
   2966                 break;
   2967 
   2968             case QEMU_OPTION_boot_property:
   2969                 boot_property_parse_option((char*)optarg);
   2970                 break;
   2971 
   2972             case QEMU_OPTION_lcd_density:
   2973                 android_op_lcd_density = (char*)optarg;
   2974                 break;
   2975 
   2976             case QEMU_OPTION_ui_port:
   2977                 android_op_ui_port = (char*)optarg;
   2978                 break;
   2979 
   2980             case QEMU_OPTION_ui_settings:
   2981                 android_op_ui_settings = (char*)optarg;
   2982                 break;
   2983 
   2984             case QEMU_OPTION_audio_test_out:
   2985                 android_audio_test_start_out();
   2986                 break;
   2987 
   2988             case QEMU_OPTION_android_avdname:
   2989                 android_op_avd_name = (char*)optarg;
   2990                 break;
   2991 
   2992             case QEMU_OPTION_timezone:
   2993                 if (timezone_set((char*)optarg)) {
   2994                     fprintf(stderr, "emulator: it seems the timezone '%s' is not in zoneinfo format\n",
   2995                             (char*)optarg);
   2996                 }
   2997                 break;
   2998 
   2999             case QEMU_OPTION_snapshot_no_time_update:
   3000                 android_snapshot_update_time = 0;
   3001                 break;
   3002 
   3003             case QEMU_OPTION_list_webcam:
   3004                 android_list_web_cameras();
   3005                 exit(0);
   3006 
   3007             default:
   3008                 os_parse_cmd_args(popt->index, optarg);
   3009             }
   3010         }
   3011     }
   3012 
   3013     /* Initialize character map. */
   3014     if (android_charmap_setup(op_charmap_file)) {
   3015         if (op_charmap_file) {
   3016             PANIC(
   3017                     "Unable to initialize character map from file %s.",
   3018                     op_charmap_file);
   3019         } else {
   3020             PANIC(
   3021                     "Unable to initialize default character map.");
   3022         }
   3023     }
   3024 
   3025     /* If no data_dir is specified then try to find it relative to the
   3026        executable path.  */
   3027     if (!data_dir) {
   3028         data_dir = find_datadir(argv[0]);
   3029     }
   3030     /* If all else fails use the install patch specified when building.  */
   3031     if (!data_dir) {
   3032         data_dir = CONFIG_QEMU_SHAREDIR;
   3033     }
   3034 
   3035     if (!android_op_hwini) {
   3036         PANIC("Missing -android-hw <file> option!");
   3037     }
   3038     hw_ini = iniFile_newFromFile(android_op_hwini);
   3039     if (hw_ini == NULL) {
   3040         PANIC("Could not find %s file.", android_op_hwini);
   3041     }
   3042 
   3043     androidHwConfig_init(android_hw, 0);
   3044     androidHwConfig_read(android_hw, hw_ini);
   3045 
   3046     /* If we're loading VM from a snapshot, make sure that the current HW config
   3047      * matches the one with which the VM has been saved. */
   3048     if (loadvm && *loadvm && !snaphost_match_configs(hw_ini, loadvm)) {
   3049         exit(0);
   3050     }
   3051 
   3052     iniFile_free(hw_ini);
   3053 
   3054     const char* kernelSerialDevicePrefix =
   3055             androidHwConfig_getKernelSerialPrefix(android_hw);
   3056     VERBOSE_PRINT(init, "Using kernel serial device prefix: %s",
   3057                   kernelSerialDevicePrefix);
   3058 
   3059     {
   3060         int width  = android_hw->hw_lcd_width;
   3061         int height = android_hw->hw_lcd_height;
   3062         int depth  = android_hw->hw_lcd_depth;
   3063 
   3064         /* A bit of sanity checking */
   3065         if (width <= 0 || height <= 0    ||
   3066             (depth != 16 && depth != 32) ||
   3067             (((width|height) & 3) != 0)  )
   3068         {
   3069             PANIC("Invalid display configuration (%d,%d,%d)",
   3070                   width, height, depth);
   3071         }
   3072         android_display_width  = width;
   3073         android_display_height = height;
   3074         android_display_bpp    = depth;
   3075     }
   3076 
   3077 #ifdef CONFIG_NAND_LIMITS
   3078     /* Init nand stuff. */
   3079     if (android_op_nand_limits) {
   3080         parse_nand_limits(android_op_nand_limits);
   3081     }
   3082 #endif  // CONFIG_NAND_LIMITS
   3083 
   3084     /* Initialize AVD name from hardware configuration if needed */
   3085     if (!android_op_avd_name) {
   3086         if (android_hw->avd_name && *android_hw->avd_name) {
   3087             android_op_avd_name = android_hw->avd_name;
   3088             VERBOSE_PRINT(init,"AVD Name: %s", android_op_avd_name);
   3089         }
   3090     }
   3091 
   3092     // Determine format of all partition images, if possible.
   3093     // Note that _UNKNOWN means the file, if it exists, will be probed.
   3094     AndroidPartitionType system_partition_type =
   3095             ANDROID_PARTITION_TYPE_UNKNOWN;
   3096     AndroidPartitionType userdata_partition_type =
   3097             ANDROID_PARTITION_TYPE_UNKNOWN;
   3098     AndroidPartitionType cache_partition_type =
   3099             ANDROID_PARTITION_TYPE_UNKNOWN;
   3100 
   3101     {
   3102         // Starting with Android 4.4.x, the ramdisk.img contains
   3103         // an fstab.goldfish file that lists the format of each partition.
   3104         // If the file exists, parse it to get the appropriate values.
   3105         char* fstab = NULL;
   3106         size_t fstabSize = 0;
   3107 
   3108         if (android_extractRamdiskFile(android_hw->disk_ramdisk_path,
   3109                                        "fstab.goldfish",
   3110                                        &fstab,
   3111                                        &fstabSize)) {
   3112             VERBOSE_PRINT(init, "Ramdisk image contains fstab.goldfish file");
   3113 
   3114             android_extractPartitionFormat(fstab,
   3115                                            fstabSize,
   3116                                            "system",
   3117                                            "/system",
   3118                                            &system_partition_type);
   3119 
   3120             android_extractPartitionFormat(fstab,
   3121                                            fstabSize,
   3122                                            "userdata",
   3123                                            "/data",
   3124                                            &userdata_partition_type);
   3125 
   3126             android_extractPartitionFormat(fstab,
   3127                                            fstabSize,
   3128                                            "cache",
   3129                                            "/cache",
   3130                                            &cache_partition_type);
   3131 
   3132             free(fstab);
   3133         } else {
   3134             VERBOSE_PRINT(init, "No fstab.goldfish file in ramdisk image");
   3135         }
   3136     }
   3137 
   3138     /* Initialize system partition image */
   3139     android_nand_add_image("system",
   3140                            system_partition_type,
   3141                            ANDROID_PARTITION_OPEN_MODE_MUST_EXIST,
   3142                            android_hw->disk_systemPartition_size,
   3143                            android_hw->disk_systemPartition_path,
   3144                            android_hw->disk_systemPartition_initPath);
   3145 
   3146     /* Initialize data partition image */
   3147     android_nand_add_image("userdata",
   3148                            userdata_partition_type,
   3149                            ANDROID_PARTITION_OPEN_MODE_CREATE_IF_NEEDED,
   3150                            android_hw->disk_dataPartition_size,
   3151                            android_hw->disk_dataPartition_path,
   3152                            android_hw->disk_dataPartition_initPath);
   3153 
   3154     /* Initialize cache partition image, if any. Its type depends on the
   3155      * kernel version. For anything >= 3.10, it must be EXT4, or
   3156      * YAFFS2 otherwise.
   3157      */
   3158     if (android_hw->disk_cachePartition != 0) {
   3159         if (cache_partition_type == ANDROID_PARTITION_TYPE_UNKNOWN) {
   3160             cache_partition_type =
   3161                 (androidHwConfig_getKernelYaffs2Support(android_hw) >= 1) ?
   3162                         ANDROID_PARTITION_TYPE_YAFFS2 :
   3163                         ANDROID_PARTITION_TYPE_EXT4;
   3164         }
   3165 
   3166         AndroidPartitionOpenMode cache_partition_mode =
   3167                 (android_op_wipe_data ?
   3168                         ANDROID_PARTITION_OPEN_MODE_MUST_WIPE :
   3169                         ANDROID_PARTITION_OPEN_MODE_CREATE_IF_NEEDED);
   3170 
   3171         android_nand_add_image("cache",
   3172                                cache_partition_type,
   3173                                cache_partition_mode,
   3174                                android_hw->disk_cachePartition_size,
   3175                                android_hw->disk_cachePartition_path,
   3176                                NULL);
   3177     }
   3178 
   3179     /* Init SD-Card stuff. For Android, it is always hda */
   3180     /* If the -hda option was used, ignore the Android-provided one */
   3181     if (hda_opts == NULL) {
   3182         const char* sdPath = android_hw->hw_sdCard_path;
   3183         if (sdPath && *sdPath) {
   3184             if (!path_exists(sdPath)) {
   3185                 fprintf(stderr, "WARNING: SD Card image is missing: %s\n", sdPath);
   3186             } else if (filelock_create(sdPath) == NULL) {
   3187                 fprintf(stderr, "WARNING: SD Card image already in use: %s\n", sdPath);
   3188             } else {
   3189                 /* Successful locking */
   3190                 hda_opts = drive_add(sdPath, HD_ALIAS, 0);
   3191                 /* Set this property of any operation involving the SD Card
   3192                  * will be x100 slower, due to the corresponding file being
   3193                  * mounted as O_DIRECT. Note that this is only 'unsafe' in
   3194                  * the context of an emulator crash. The data is already
   3195                  * synced properly when the emulator exits (either normally or through ^C).
   3196                  */
   3197                 qemu_opt_set(hda_opts, "cache", "unsafe");
   3198             }
   3199         }
   3200     }
   3201 
   3202     if (hdb_opts == NULL) {
   3203         const char* spath = android_hw->disk_snapStorage_path;
   3204         if (spath && *spath) {
   3205             if (!path_exists(spath)) {
   3206                 PANIC("Snapshot storage file does not exist: %s", spath);
   3207             }
   3208             if (filelock_create(spath) == NULL) {
   3209                 PANIC("Snapshot storage already in use: %s", spath);
   3210             }
   3211             hdb_opts = drive_add(spath, HD_ALIAS, 1);
   3212             /* See comment above to understand why this is needed. */
   3213             qemu_opt_set(hdb_opts, "cache", "unsafe");
   3214         }
   3215     }
   3216 
   3217     /* Set the VM's max heap size, passed as a boot property */
   3218     if (android_hw->vm_heapSize > 0) {
   3219         char  tmp[64];
   3220         snprintf(tmp, sizeof(tmp), "%dm", android_hw->vm_heapSize);
   3221         boot_property_add("dalvik.vm.heapsize",tmp);
   3222     }
   3223 
   3224     /* From API 19 and above, the platform provides an explicit property for low memory devices. */
   3225     if (android_hw->hw_ramSize <= 512) {
   3226         boot_property_add("ro.config.low_ram", "true");
   3227     }
   3228 
   3229     /* Initialize net speed and delays stuff. */
   3230     if (android_parse_network_speed(android_op_netspeed) < 0 ) {
   3231         PANIC("invalid -netspeed parameter '%s'",
   3232                 android_op_netspeed);
   3233     }
   3234 
   3235     if ( android_parse_network_latency(android_op_netdelay) < 0 ) {
   3236         PANIC("invalid -netdelay parameter '%s'",
   3237                 android_op_netdelay);
   3238     }
   3239 
   3240     if (android_op_netfast) {
   3241         qemu_net_download_speed = 0;
   3242         qemu_net_upload_speed = 0;
   3243         qemu_net_min_latency = 0;
   3244         qemu_net_max_latency = 0;
   3245     }
   3246 
   3247     /* Initialize LCD density */
   3248     if (android_hw->hw_lcd_density) {
   3249         long density = android_hw->hw_lcd_density;
   3250         if (density <= 0) {
   3251             PANIC("Invalid hw.lcd.density value: %ld", density);
   3252         }
   3253         hwLcd_setBootProperty(density);
   3254     }
   3255 
   3256     /* Initialize presence of hardware nav button */
   3257     boot_property_add("qemu.hw.mainkeys", android_hw->hw_mainKeys ? "1" : "0");
   3258 
   3259     /* Initialize TCP dump */
   3260     if (android_op_tcpdump) {
   3261         if (qemu_tcpdump_start(android_op_tcpdump) < 0) {
   3262             fprintf(stdout, "could not start packet capture: %s\n", strerror(errno));
   3263         }
   3264     }
   3265 
   3266     /* Initialize modem */
   3267     if (android_op_radio) {
   3268         CharDriverState*  cs = qemu_chr_open("radio", android_op_radio, NULL);
   3269         if (cs == NULL) {
   3270             PANIC("unsupported character device specification: %s\n"
   3271                         "used -help-char-devices for list of available formats",
   3272                     android_op_radio);
   3273         }
   3274         android_qemud_set_channel( ANDROID_QEMUD_GSM, cs);
   3275     } else if (android_hw->hw_gsmModem != 0 ) {
   3276         if ( android_qemud_get_channel( ANDROID_QEMUD_GSM, &android_modem_cs ) < 0 ) {
   3277             PANIC("could not initialize qemud 'gsm' channel");
   3278         }
   3279     }
   3280 
   3281     /* Initialize GPS */
   3282     if (android_op_gps) {
   3283         CharDriverState*  cs = qemu_chr_open("gps", android_op_gps, NULL);
   3284         if (cs == NULL) {
   3285             PANIC("unsupported character device specification: %s\n"
   3286                         "used -help-char-devices for list of available formats",
   3287                     android_op_gps);
   3288         }
   3289         android_qemud_set_channel( ANDROID_QEMUD_GPS, cs);
   3290     } else if (android_hw->hw_gps != 0) {
   3291         if ( android_qemud_get_channel( "gps", &android_gps_cs ) < 0 ) {
   3292             PANIC("could not initialize qemud 'gps' channel");
   3293         }
   3294     }
   3295 
   3296     /* Initialize audio. */
   3297     if (android_op_audio) {
   3298         if ( !audio_check_backend_name( 0, android_op_audio ) ) {
   3299             PANIC("'%s' is not a valid audio output backend. see -help-audio-out",
   3300                     android_op_audio);
   3301         }
   3302         setenv("QEMU_AUDIO_DRV", android_op_audio, 1);
   3303     }
   3304 
   3305     /* Initialize OpenGLES emulation */
   3306     //android_hw_opengles_init();
   3307 
   3308     /* Initialize fake camera */
   3309     if (strcmp(android_hw->hw_camera_back, "emulated") &&
   3310         strcmp(android_hw->hw_camera_front, "emulated")) {
   3311         /* Fake camera is not used for camera emulation. */
   3312         boot_property_add("qemu.sf.fake_camera", "none");
   3313     } else {
   3314         /* Fake camera is used for at least one camera emulation. */
   3315         if (!strcmp(android_hw->hw_camera_back, "emulated") &&
   3316             !strcmp(android_hw->hw_camera_front, "emulated")) {
   3317             /* Fake camera is used for both, front and back camera emulation. */
   3318             boot_property_add("qemu.sf.fake_camera", "both");
   3319         } else if (!strcmp(android_hw->hw_camera_back, "emulated")) {
   3320             boot_property_add("qemu.sf.fake_camera", "back");
   3321         } else {
   3322             boot_property_add("qemu.sf.fake_camera", "front");
   3323         }
   3324     }
   3325 
   3326     /* Set LCD density (if required by -qemu, and AVD is missing it. */
   3327     if (android_op_lcd_density && !android_hw->hw_lcd_density) {
   3328         int density;
   3329         if (parse_int(android_op_lcd_density, &density) || density <= 0) {
   3330             PANIC("-lcd-density : %d", density);
   3331         }
   3332         hwLcd_setBootProperty(density);
   3333     }
   3334 
   3335     /* Initialize camera emulation. */
   3336     android_camera_service_init();
   3337 
   3338     if (android_op_cpu_delay) {
   3339         char*   end;
   3340         long    delay = strtol(android_op_cpu_delay, &end, 0);
   3341         if (end == NULL || *end || delay < 0 || delay > 1000 ) {
   3342             PANIC("option -cpu-delay must be an integer between 0 and 1000" );
   3343         }
   3344         if (delay > 0)
   3345             delay = (1000-delay);
   3346 
   3347         qemu_cpu_delay = (int) delay;
   3348     }
   3349 
   3350     if (android_op_dns_server) {
   3351         char*  x = strchr(android_op_dns_server, ',');
   3352         dns_count = 0;
   3353         if (x == NULL)
   3354         {
   3355             if ( add_dns_server( android_op_dns_server ) == 0 )
   3356                 dns_count = 1;
   3357         }
   3358         else
   3359         {
   3360             x = android_op_dns_server;
   3361             while (*x) {
   3362                 char*  y = strchr(x, ',');
   3363 
   3364                 if (y != NULL) {
   3365                     *y = 0;
   3366                     y++;
   3367                 } else {
   3368                     y = x + strlen(x);
   3369                 }
   3370 
   3371                 if (y > x && add_dns_server( x ) == 0) {
   3372                     dns_count += 1;
   3373                 }
   3374                 x = y;
   3375             }
   3376         }
   3377         if (dns_count == 0)
   3378             fprintf( stdout, "### WARNING: will use system default DNS server\n" );
   3379     }
   3380 
   3381     if (dns_count == 0)
   3382         dns_count = slirp_get_system_dns_servers();
   3383     if (dns_count) {
   3384         stralloc_add_format(kernel_config, " ndns=%d", dns_count);
   3385     }
   3386 
   3387     /* qemu.gles will be read by the OpenGL ES emulation libraries.
   3388      * If set to 0, the software GL ES renderer will be used as a fallback.
   3389      * If the parameter is undefined, this means the system image runs
   3390      * inside an emulator that doesn't support GPU emulation at all.
   3391      *
   3392      * We always start the GL ES renderer so we can gather stats on the
   3393      * underlying GL implementation. If GL ES acceleration is disabled,
   3394      * we just shut it down again once we have the strings. */
   3395     {
   3396         int qemu_gles = 0;
   3397         if (android_initOpenglesEmulation() == 0 &&
   3398             android_startOpenglesRenderer(android_hw->hw_lcd_width, android_hw->hw_lcd_height) == 0)
   3399         {
   3400             android_getOpenglesHardwareStrings(
   3401                     android_gl_vendor, sizeof(android_gl_vendor),
   3402                     android_gl_renderer, sizeof(android_gl_renderer),
   3403                     android_gl_version, sizeof(android_gl_version));
   3404             if (android_hw->hw_gpu_enabled) {
   3405                 qemu_gles = 1;
   3406             } else {
   3407                 android_stopOpenglesRenderer();
   3408                 qemu_gles = 0;
   3409             }
   3410         } else {
   3411             dwarning("Could not initialize OpenglES emulation, using software renderer.");
   3412         }
   3413         if (qemu_gles) {
   3414             stralloc_add_str(kernel_params, " qemu.gles=1");
   3415         } else {
   3416             stralloc_add_str(kernel_params, " qemu.gles=0");
   3417         }
   3418     }
   3419 
   3420     /* We always force qemu=1 when running inside QEMU */
   3421     stralloc_add_str(kernel_params, " qemu=1");
   3422 
   3423     /* We always initialize the first serial port for the android-kmsg
   3424      * character device (used to send kernel messages) */
   3425     serial_hds_add_at(0, "android-kmsg");
   3426     stralloc_add_format(kernel_params,
   3427                         " console=%s0",
   3428                         kernelSerialDevicePrefix);
   3429 
   3430     /* We always initialize the second serial port for the android-qemud
   3431      * character device as well */
   3432     serial_hds_add_at(1, "android-qemud");
   3433     stralloc_add_format(kernel_params,
   3434                         " android.qemud=%s1",
   3435                         kernelSerialDevicePrefix);
   3436 
   3437     if (pid_file && qemu_create_pidfile(pid_file) != 0) {
   3438         os_pidfile_error();
   3439         exit(1);
   3440     }
   3441 
   3442     /* Open the logfile at this point, if necessary. We can't open the logfile
   3443      * when encountering either of the logging options (-d or -D) because the
   3444      * other one may be encountered later on the command line, changing the
   3445      * location or level of logging.
   3446      */
   3447     if (log_mask) {
   3448         int mask;
   3449         if (log_file) {
   3450             qemu_set_log_filename(log_file);
   3451         }
   3452 
   3453         mask = qemu_str_to_log_mask(log_mask);
   3454         if (!mask) {
   3455             qemu_print_log_usage(stdout);
   3456             exit(1);
   3457         }
   3458         qemu_set_log(mask);
   3459     }
   3460 
   3461 #if defined(CONFIG_KVM)
   3462     if (kvm_allowed < 0) {
   3463         kvm_allowed = kvm_check_allowed();
   3464     }
   3465 #endif
   3466 
   3467     machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
   3468     if (smp_cpus > machine->max_cpus) {
   3469         PANIC("Number of SMP cpus requested (%d), exceeds max cpus "
   3470                 "supported by machine `%s' (%d)", smp_cpus,  machine->name,
   3471                 machine->max_cpus);
   3472     }
   3473 
   3474     if (display_type == DT_NOGRAPHIC) {
   3475        if (serial_device_index == 0)
   3476            serial_devices[0] = "stdio";
   3477        if (parallel_device_index == 0)
   3478            parallel_devices[0] = "null";
   3479        if (strncmp(monitor_device, "vc", 2) == 0)
   3480            monitor_device = "stdio";
   3481     }
   3482 
   3483     if (qemu_init_main_loop()) {
   3484         PANIC("qemu_init_main_loop failed");
   3485     }
   3486 
   3487     if (kernel_filename == NULL) {
   3488         kernel_filename = android_hw->kernel_path;
   3489     }
   3490     if (initrd_filename == NULL) {
   3491         initrd_filename = android_hw->disk_ramdisk_path;
   3492     }
   3493 
   3494     linux_boot = (kernel_filename != NULL);
   3495     net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
   3496 
   3497     if (!linux_boot && *kernel_cmdline != '\0') {
   3498         PANIC("-append only allowed with -kernel option");
   3499     }
   3500 
   3501     if (!linux_boot && initrd_filename != NULL) {
   3502         PANIC("-initrd only allowed with -kernel option");
   3503     }
   3504 
   3505     /* boot to floppy or the default cd if no hard disk defined yet */
   3506     if (!boot_devices[0]) {
   3507         boot_devices = "cad";
   3508     }
   3509     os_set_line_buffering();
   3510 
   3511     if (init_timer_alarm() < 0) {
   3512         PANIC("could not initialize alarm timer");
   3513     }
   3514     configure_icount(icount_option);
   3515 
   3516     /* init network clients */
   3517     if (nb_net_clients == 0) {
   3518         /* if no clients, we use a default config */
   3519         net_clients[nb_net_clients++] = "nic";
   3520 #ifdef CONFIG_SLIRP
   3521         net_clients[nb_net_clients++] = "user";
   3522 #endif
   3523     }
   3524 
   3525     for(i = 0;i < nb_net_clients; i++) {
   3526         if (net_client_parse(net_clients[i]) < 0) {
   3527             PANIC("Unable to parse net clients");
   3528         }
   3529     }
   3530     net_client_check();
   3531 
   3532 #ifdef TARGET_I386
   3533     /* XXX: this should be moved in the PC machine instantiation code */
   3534     if (net_boot != 0) {
   3535         int netroms = 0;
   3536 	for (i = 0; i < nb_nics && i < 4; i++) {
   3537 	    const char *model = nd_table[i].model;
   3538 	    char buf[1024];
   3539             char *filename;
   3540             if (net_boot & (1 << i)) {
   3541                 if (model == NULL)
   3542                     model = "ne2k_pci";
   3543                 snprintf(buf, sizeof(buf), "pxe-%s.bin", model);
   3544                 filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, buf);
   3545                 if (filename && get_image_size(filename) > 0) {
   3546                     if (nb_option_roms >= MAX_OPTION_ROMS) {
   3547                         PANIC("Too many option ROMs");
   3548                     }
   3549                     option_rom[nb_option_roms] = g_strdup(buf);
   3550                     nb_option_roms++;
   3551                     netroms++;
   3552                 }
   3553                 if (filename) {
   3554                     g_free(filename);
   3555                 }
   3556             }
   3557 	}
   3558 	if (netroms == 0) {
   3559 	    PANIC("No valid PXE rom found for network device");
   3560 	}
   3561     }
   3562 #endif
   3563 
   3564     /* init the memory */
   3565     if (ram_size == 0) {
   3566         ram_size = android_hw->hw_ramSize * 1024LL * 1024;
   3567         if (ram_size == 0) {
   3568             ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
   3569         }
   3570     }
   3571 
   3572     /* Quite often (especially on older XP machines) attempts to allocate large
   3573      * VM RAM is going to fail, and crash the emulator. Since it's failing deep
   3574      * inside QEMU, it's not really possible to provide the user with a
   3575      * meaningful explanation for the crash. So, lets see if QEMU is going to be
   3576      * able to allocate requested amount of RAM, and if not, lets try to come up
   3577      * with a recomendation. */
   3578     {
   3579         ram_addr_t r_ram = ram_size;
   3580         void* alloc_check = malloc(r_ram);
   3581         while (alloc_check == NULL && r_ram > 1024 * 1024) {
   3582         /* Make it 25% less */
   3583             r_ram -= r_ram / 4;
   3584             alloc_check = malloc(r_ram);
   3585         }
   3586         if (alloc_check != NULL) {
   3587             free(alloc_check);
   3588         }
   3589         if (r_ram != ram_size) {
   3590             /* Requested RAM is too large. Report this, as well as calculated
   3591              * recomendation. */
   3592             dwarning("Requested RAM size of %dMB is too large for your environment, and is reduced to %dMB.",
   3593                      (int)(ram_size / 1024 / 1024), (int)(r_ram / 1024 / 1024));
   3594             ram_size = r_ram;
   3595         }
   3596     }
   3597 
   3598 #ifndef _WIN32
   3599     qemu_log_rotation_init();
   3600 #endif
   3601 
   3602     /* init the dynamic translator */
   3603     cpu_exec_init_all(tb_size * 1024 * 1024);
   3604 
   3605     bdrv_init();
   3606 
   3607     /* we always create the cdrom drive, even if no disk is there */
   3608 #if 0
   3609     if (nb_drives_opt < MAX_DRIVES)
   3610         drive_add(NULL, CDROM_ALIAS);
   3611 
   3612     /* we always create at least one floppy */
   3613 
   3614     if (nb_drives_opt < MAX_DRIVES)
   3615         drive_add(NULL, FD_ALIAS, 0);
   3616     /* we always create one sd slot, even if no card is in it */
   3617 
   3618     if (1) {
   3619         drive_add(NULL, SD_ALIAS);
   3620     }
   3621 #endif
   3622 
   3623     /* open the virtual block devices */
   3624     if (snapshot)
   3625         qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot, NULL, 0);
   3626     if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func, &machine->use_scsi, 1) != 0)
   3627         exit(1);
   3628 
   3629     //register_savevm(NULL, "timer", 0, 2, timer_save, timer_load, &timers_state);
   3630 
   3631     SaveVMHandlers* ops = g_malloc0(sizeof(*ops));
   3632     ops->save_live_state = ram_save_live;
   3633     ops->load_state = ram_load;
   3634 
   3635     register_savevm_live(NULL,
   3636                          "ram",
   3637                          0,
   3638                          3,
   3639                          ops,
   3640                          NULL);
   3641 
   3642     /* must be after terminal init, SDL library changes signal handlers */
   3643     os_setup_signal_handling();
   3644 
   3645     /* Maintain compatibility with multiple stdio monitors */
   3646     if (!strcmp(monitor_device,"stdio")) {
   3647         for (i = 0; i < MAX_SERIAL_PORTS; i++) {
   3648             const char *devname = serial_devices[i];
   3649             if (devname && !strcmp(devname,"mon:stdio")) {
   3650                 monitor_device = NULL;
   3651                 break;
   3652             } else if (devname && !strcmp(devname,"stdio")) {
   3653                 monitor_device = NULL;
   3654                 serial_devices[i] = "mon:stdio";
   3655                 break;
   3656             }
   3657         }
   3658     }
   3659 
   3660     if (nb_numa_nodes > 0) {
   3661         int i;
   3662 
   3663         if (nb_numa_nodes > smp_cpus) {
   3664             nb_numa_nodes = smp_cpus;
   3665         }
   3666 
   3667         /* If no memory size if given for any node, assume the default case
   3668          * and distribute the available memory equally across all nodes
   3669          */
   3670         for (i = 0; i < nb_numa_nodes; i++) {
   3671             if (node_mem[i] != 0)
   3672                 break;
   3673         }
   3674         if (i == nb_numa_nodes) {
   3675             uint64_t usedmem = 0;
   3676 
   3677             /* On Linux, the each node's border has to be 8MB aligned,
   3678              * the final node gets the rest.
   3679              */
   3680             for (i = 0; i < nb_numa_nodes - 1; i++) {
   3681                 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
   3682                 usedmem += node_mem[i];
   3683             }
   3684             node_mem[i] = ram_size - usedmem;
   3685         }
   3686 
   3687         for (i = 0; i < nb_numa_nodes; i++) {
   3688             if (node_cpumask[i] != 0)
   3689                 break;
   3690         }
   3691         /* assigning the VCPUs round-robin is easier to implement, guest OSes
   3692          * must cope with this anyway, because there are BIOSes out there in
   3693          * real machines which also use this scheme.
   3694          */
   3695         if (i == nb_numa_nodes) {
   3696             for (i = 0; i < smp_cpus; i++) {
   3697                 node_cpumask[i % nb_numa_nodes] |= 1 << i;
   3698             }
   3699         }
   3700     }
   3701 
   3702     if (kvm_enabled()) {
   3703         int ret;
   3704 
   3705         ret = kvm_init(smp_cpus);
   3706         if (ret < 0) {
   3707             PANIC("failed to initialize KVM");
   3708         }
   3709     }
   3710 
   3711 #ifdef CONFIG_HAX
   3712     if (!hax_disabled)
   3713     {
   3714         int ret;
   3715 
   3716         hax_set_ramsize(ram_size);
   3717         ret = hax_init(smp_cpus);
   3718         fprintf(stderr, "HAX is %s and emulator runs in %s mode\n",
   3719             !ret ? "working" :"not working", !ret ? "fast virt" : "emulation");
   3720     }
   3721 #endif
   3722 
   3723     if (monitor_device) {
   3724         monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
   3725         if (!monitor_hd) {
   3726             PANIC("qemu: could not open monitor device '%s'",
   3727                               monitor_device);
   3728         }
   3729     }
   3730 
   3731     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
   3732         serial_hds_add(serial_devices[i]);
   3733     }
   3734 
   3735     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
   3736         const char *devname = parallel_devices[i];
   3737         if (devname && strcmp(devname, "none")) {
   3738             char label[32];
   3739             snprintf(label, sizeof(label), "parallel%d", i);
   3740             parallel_hds[i] = qemu_chr_open(label, devname, NULL);
   3741             if (!parallel_hds[i]) {
   3742                 PANIC("qemu: could not open parallel device '%s'",
   3743                         devname);
   3744             }
   3745         }
   3746     }
   3747 
   3748     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
   3749         const char *devname = virtio_consoles[i];
   3750         if (devname && strcmp(devname, "none")) {
   3751             char label[32];
   3752             snprintf(label, sizeof(label), "virtcon%d", i);
   3753             virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
   3754             if (!virtcon_hds[i]) {
   3755                 PANIC("qemu: could not open virtio console '%s'",
   3756                         devname);
   3757             }
   3758         }
   3759     }
   3760 
   3761     module_call_init(MODULE_INIT_DEVICE);
   3762 
   3763 
   3764     /* Check the CPU Architecture value */
   3765     {
   3766         static const char* kSupportedArchs[] = {
   3767 #if defined(TARGET_ARM)
   3768             "arm",
   3769 #endif
   3770 #if defined(TARGET_I386)
   3771             "x86",
   3772 #endif
   3773 #if defined(TARGET_X86_64)
   3774             "x86_64",
   3775 #endif
   3776 #if defined(TARGET_MIPS)
   3777             "mips",
   3778 #endif
   3779         };
   3780         const size_t kNumSupportedArchs =
   3781                 sizeof(kSupportedArchs) / sizeof(kSupportedArchs[0]);
   3782         bool supported_arch = false;
   3783         size_t n;
   3784         for (n = 0; n < kNumSupportedArchs; ++n) {
   3785             if (!strcmp(android_hw->hw_cpu_arch, kSupportedArchs[n])) {
   3786                 supported_arch = true;
   3787                 break;
   3788             }
   3789         }
   3790         if (!supported_arch) {
   3791             fprintf(stderr, "-- Invalid CPU architecture: %s, valid values:",
   3792                     android_hw->hw_cpu_arch);
   3793             for (n = 0; n < kNumSupportedArchs; ++n) {
   3794                 fprintf(stderr, " %s", kSupportedArchs[n]);
   3795             }
   3796             fprintf(stderr, "\n");
   3797             exit(1);
   3798         }
   3799     }
   3800 
   3801     /* Grab CPU model if provided in hardware.ini */
   3802     if (    !cpu_model
   3803          && android_hw->hw_cpu_model
   3804          && android_hw->hw_cpu_model[0] != '\0')
   3805     {
   3806         cpu_model = android_hw->hw_cpu_model;
   3807     }
   3808 
   3809     /* Combine kernel command line passed from the UI with parameters
   3810      * collected during initialization.
   3811      *
   3812      * The order is the following:
   3813      * - parameters from the hw configuration (kernel.parameters)
   3814      * - additionnal parameters from options (e.g. -memcheck)
   3815      * - the -append parameters.
   3816      */
   3817     {
   3818         const char* kernel_parameters;
   3819 
   3820         if (android_hw->kernel_parameters) {
   3821             stralloc_add_c(kernel_params, ' ');
   3822             stralloc_add_str(kernel_params, android_hw->kernel_parameters);
   3823         }
   3824 
   3825         /* If not empty, kernel_config always contains a leading space */
   3826         stralloc_append(kernel_params, kernel_config);
   3827 
   3828         if (*kernel_cmdline) {
   3829             stralloc_add_c(kernel_params, ' ');
   3830             stralloc_add_str(kernel_params, kernel_cmdline);
   3831         }
   3832 
   3833         /* Remove any leading/trailing spaces */
   3834         stralloc_strip(kernel_params);
   3835 
   3836         kernel_parameters = stralloc_cstr(kernel_params);
   3837         VERBOSE_PRINT(init, "Kernel parameters: %s", kernel_parameters);
   3838 
   3839         machine->init(ram_size,
   3840                       boot_devices,
   3841                       kernel_filename,
   3842                       kernel_parameters,
   3843                       initrd_filename,
   3844                       cpu_model);
   3845 
   3846         /* Initialize multi-touch emulation. */
   3847         if (androidHwConfig_isScreenMultiTouch(android_hw)) {
   3848             mts_port_create(NULL);
   3849         }
   3850 
   3851         stralloc_reset(kernel_params);
   3852         stralloc_reset(kernel_config);
   3853     }
   3854 
   3855     CPU_FOREACH(cpu) {
   3856         for (i = 0; i < nb_numa_nodes; i++) {
   3857             if (node_cpumask[i] & (1 << cpu->cpu_index)) {
   3858                 cpu->numa_node = i;
   3859             }
   3860         }
   3861     }
   3862 
   3863     current_machine = machine;
   3864 
   3865     /* Set KVM's vcpu state to qemu's initial CPUOldState. */
   3866     if (kvm_enabled()) {
   3867         int ret;
   3868 
   3869         ret = kvm_sync_vcpus();
   3870         if (ret < 0) {
   3871             PANIC("failed to initialize vcpus");
   3872         }
   3873     }
   3874 
   3875 #ifdef CONFIG_HAX
   3876     if (hax_enabled())
   3877         hax_sync_vcpus();
   3878 #endif
   3879 
   3880     /* just use the first displaystate for the moment */
   3881     ds = get_displaystate();
   3882 
   3883     /* Initialize display from the command line parameters. */
   3884     android_display_reset(ds,
   3885                           android_display_width,
   3886                           android_display_height,
   3887                           android_display_bpp);
   3888 
   3889     if (display_type == DT_DEFAULT) {
   3890 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
   3891         display_type = DT_SDL;
   3892 #else
   3893         display_type = DT_VNC;
   3894         vnc_display = "localhost:0,to=99";
   3895         show_vnc_port = 1;
   3896 #endif
   3897     }
   3898 
   3899 
   3900     switch (display_type) {
   3901     case DT_NOGRAPHIC:
   3902         break;
   3903 #if defined(CONFIG_CURSES)
   3904     case DT_CURSES:
   3905         curses_display_init(ds, full_screen);
   3906         break;
   3907 #endif
   3908 #if defined(CONFIG_SDL) && !defined(CONFIG_STANDALONE_CORE)
   3909     case DT_SDL:
   3910         sdl_display_init(ds, full_screen, no_frame);
   3911         break;
   3912 #elif defined(CONFIG_COCOA)
   3913     case DT_SDL:
   3914         cocoa_display_init(ds, full_screen);
   3915         break;
   3916 #elif defined(CONFIG_STANDALONE_CORE)
   3917     case DT_SDL:
   3918         coredisplay_init(ds);
   3919         break;
   3920 #endif
   3921     case DT_VNC:
   3922         vnc_display_init(ds);
   3923         if (vnc_display_open(ds, vnc_display) < 0) {
   3924             PANIC("Unable to initialize VNC display");
   3925         }
   3926 
   3927         if (show_vnc_port) {
   3928             printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
   3929         }
   3930         break;
   3931     default:
   3932         break;
   3933     }
   3934     dpy_resize(ds);
   3935 
   3936     dcl = ds->listeners;
   3937     while (dcl != NULL) {
   3938         if (dcl->dpy_refresh != NULL) {
   3939             ds->gui_timer = timer_new(QEMU_CLOCK_REALTIME, SCALE_MS, gui_update, ds);
   3940             timer_mod(ds->gui_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
   3941         }
   3942         dcl = dcl->next;
   3943     }
   3944 
   3945     if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
   3946         nographic_timer = timer_new(QEMU_CLOCK_REALTIME, SCALE_MS, nographic_update, NULL);
   3947         timer_mod(nographic_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
   3948     }
   3949 
   3950     text_consoles_set_display(ds);
   3951     qemu_chr_initial_reset();
   3952 
   3953     if (monitor_device && monitor_hd)
   3954         monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
   3955 
   3956     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
   3957         const char *devname = serial_devices[i];
   3958         if (devname && strcmp(devname, "none")) {
   3959             if (strstart(devname, "vc", 0))
   3960                 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
   3961         }
   3962     }
   3963 
   3964     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
   3965         const char *devname = parallel_devices[i];
   3966         if (devname && strcmp(devname, "none")) {
   3967             if (strstart(devname, "vc", 0))
   3968                 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
   3969         }
   3970     }
   3971 
   3972     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
   3973         const char *devname = virtio_consoles[i];
   3974         if (virtcon_hds[i] && devname) {
   3975             if (strstart(devname, "vc", 0))
   3976                 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
   3977         }
   3978     }
   3979 
   3980     if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
   3981         PANIC("qemu: could not open gdbserver on device '%s'",
   3982                 gdbstub_dev);
   3983     }
   3984 
   3985     /* call android-specific setup function */
   3986     android_emulation_setup();
   3987 
   3988 #if !defined(CONFIG_STANDALONE_CORE)
   3989     // For the standalone emulator (UI+core in one executable) we need to
   3990     // set the window title here.
   3991     android_emulator_set_base_port(android_base_port);
   3992 #endif
   3993 
   3994     if (loadvm)
   3995         do_loadvm(cur_mon, loadvm);
   3996 
   3997     if (incoming) {
   3998         autostart = 0; /* fixme how to deal with -daemonize */
   3999         qemu_start_incoming_migration(incoming);
   4000     }
   4001 
   4002     if (autostart)
   4003         vm_start();
   4004 
   4005     os_setup_post();
   4006 
   4007 #ifdef CONFIG_ANDROID
   4008     // This will notify the UI that the core is successfuly initialized
   4009     android_core_init_completed();
   4010 #endif  // CONFIG_ANDROID
   4011 
   4012     main_loop();
   4013     quit_timers();
   4014     net_cleanup();
   4015     android_emulation_teardown();
   4016     return 0;
   4017 }
   4018 
   4019 void
   4020 android_emulation_teardown(void)
   4021 {
   4022     android_charmap_done();
   4023 }
   4024