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