SDL static config fix (Roman Zippel)
[qemu] / vl.c
1 /*
2  * QEMU System Emulator
3  * 
4  * Copyright (c) 2003-2004 Fabrice Bellard
5  * 
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "vl.h"
25
26 #include <getopt.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <time.h>
31 #include <malloc.h>
32 #include <errno.h>
33 #include <sys/time.h>
34
35 #ifndef _WIN32
36 #include <sys/times.h>
37 #include <sys/wait.h>
38 #include <pty.h>
39 #include <termios.h>
40 #include <sys/poll.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/socket.h>
44 #include <linux/if.h>
45 #include <linux/if_tun.h>
46 #endif
47
48 #if defined(CONFIG_SLIRP)
49 #include "libslirp.h"
50 #endif
51
52 #ifdef _WIN32
53 #include <sys/timeb.h>
54 #include <windows.h>
55 #define getopt_long_only getopt_long
56 #define memalign(align, size) malloc(size)
57 #endif
58
59 #ifdef CONFIG_SDL
60 /* SDL use the pthreads and they modify sigaction. We don't
61    want that. */
62 #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)
63 extern void __libc_sigaction();
64 #define sigaction(sig, act, oact) __libc_sigaction(sig, act, oact)
65 #else
66 extern void __sigaction();
67 #define sigaction(sig, act, oact) __sigaction(sig, act, oact)
68 #endif
69 #endif /* CONFIG_SDL */
70
71 #include "disas.h"
72
73 #include "exec-all.h"
74
75 //#define DO_TB_FLUSH
76
77 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
78
79 //#define DEBUG_UNUSED_IOPORT
80
81 #if !defined(CONFIG_SOFTMMU)
82 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
83 #else
84 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
85 #endif
86
87 /* in ms */
88 #define GUI_REFRESH_INTERVAL 30
89
90 /* XXX: use a two level table to limit memory usage */
91 #define MAX_IOPORTS 65536
92
93 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
94 char phys_ram_file[1024];
95 CPUState *global_env;
96 CPUState *cpu_single_env;
97 void *ioport_opaque[MAX_IOPORTS];
98 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
99 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
100 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
101 int vga_ram_size;
102 static DisplayState display_state;
103 int nographic;
104 int64_t ticks_per_sec;
105 int boot_device = 'c';
106 static int ram_size;
107 static char network_script[1024];
108 int pit_min_timer_count = 0;
109 int nb_nics;
110 NetDriverState nd_table[MAX_NICS];
111 SerialState *serial_console;
112 QEMUTimer *gui_timer;
113 int vm_running;
114 int audio_enabled = 0;
115
116 /***********************************************************/
117 /* x86 ISA bus support */
118
119 target_phys_addr_t isa_mem_base = 0;
120
121 uint32_t default_ioport_readb(void *opaque, uint32_t address)
122 {
123 #ifdef DEBUG_UNUSED_IOPORT
124     fprintf(stderr, "inb: port=0x%04x\n", address);
125 #endif
126     return 0xff;
127 }
128
129 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
130 {
131 #ifdef DEBUG_UNUSED_IOPORT
132     fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
133 #endif
134 }
135
136 /* default is to make two byte accesses */
137 uint32_t default_ioport_readw(void *opaque, uint32_t address)
138 {
139     uint32_t data;
140     data = ioport_read_table[0][address & (MAX_IOPORTS - 1)](opaque, address);
141     data |= ioport_read_table[0][(address + 1) & (MAX_IOPORTS - 1)](opaque, address + 1) << 8;
142     return data;
143 }
144
145 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
146 {
147     ioport_write_table[0][address & (MAX_IOPORTS - 1)](opaque, address, data & 0xff);
148     ioport_write_table[0][(address + 1) & (MAX_IOPORTS - 1)](opaque, address + 1, (data >> 8) & 0xff);
149 }
150
151 uint32_t default_ioport_readl(void *opaque, uint32_t address)
152 {
153 #ifdef DEBUG_UNUSED_IOPORT
154     fprintf(stderr, "inl: port=0x%04x\n", address);
155 #endif
156     return 0xffffffff;
157 }
158
159 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
160 {
161 #ifdef DEBUG_UNUSED_IOPORT
162     fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
163 #endif
164 }
165
166 void init_ioports(void)
167 {
168     int i;
169
170     for(i = 0; i < MAX_IOPORTS; i++) {
171         ioport_read_table[0][i] = default_ioport_readb;
172         ioport_write_table[0][i] = default_ioport_writeb;
173         ioport_read_table[1][i] = default_ioport_readw;
174         ioport_write_table[1][i] = default_ioport_writew;
175         ioport_read_table[2][i] = default_ioport_readl;
176         ioport_write_table[2][i] = default_ioport_writel;
177     }
178 }
179
180 /* size is the word size in byte */
181 int register_ioport_read(int start, int length, int size, 
182                          IOPortReadFunc *func, void *opaque)
183 {
184     int i, bsize;
185
186     if (size == 1) {
187         bsize = 0;
188     } else if (size == 2) {
189         bsize = 1;
190     } else if (size == 4) {
191         bsize = 2;
192     } else {
193         hw_error("register_ioport_read: invalid size");
194         return -1;
195     }
196     for(i = start; i < start + length; i += size) {
197         ioport_read_table[bsize][i] = func;
198         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
199             hw_error("register_ioport_read: invalid opaque");
200         ioport_opaque[i] = opaque;
201     }
202     return 0;
203 }
204
205 /* size is the word size in byte */
206 int register_ioport_write(int start, int length, int size, 
207                           IOPortWriteFunc *func, void *opaque)
208 {
209     int i, bsize;
210
211     if (size == 1) {
212         bsize = 0;
213     } else if (size == 2) {
214         bsize = 1;
215     } else if (size == 4) {
216         bsize = 2;
217     } else {
218         hw_error("register_ioport_write: invalid size");
219         return -1;
220     }
221     for(i = start; i < start + length; i += size) {
222         ioport_write_table[bsize][i] = func;
223         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
224             hw_error("register_ioport_read: invalid opaque");
225         ioport_opaque[i] = opaque;
226     }
227     return 0;
228 }
229
230 void pstrcpy(char *buf, int buf_size, const char *str)
231 {
232     int c;
233     char *q = buf;
234
235     if (buf_size <= 0)
236         return;
237
238     for(;;) {
239         c = *str++;
240         if (c == 0 || q >= buf + buf_size - 1)
241             break;
242         *q++ = c;
243     }
244     *q = '\0';
245 }
246
247 /* strcat and truncate. */
248 char *pstrcat(char *buf, int buf_size, const char *s)
249 {
250     int len;
251     len = strlen(buf);
252     if (len < buf_size) 
253         pstrcpy(buf + len, buf_size - len, s);
254     return buf;
255 }
256
257 /* return the size or -1 if error */
258 int load_image(const char *filename, uint8_t *addr)
259 {
260     int fd, size;
261     fd = open(filename, O_RDONLY | O_BINARY);
262     if (fd < 0)
263         return -1;
264     size = lseek(fd, 0, SEEK_END);
265     lseek(fd, 0, SEEK_SET);
266     if (read(fd, addr, size) != size) {
267         close(fd);
268         return -1;
269     }
270     close(fd);
271     return size;
272 }
273
274 void cpu_outb(CPUState *env, int addr, int val)
275 {
276     addr &= (MAX_IOPORTS - 1);
277     ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
278 }
279
280 void cpu_outw(CPUState *env, int addr, int val)
281 {
282     addr &= (MAX_IOPORTS - 1);
283     ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
284 }
285
286 void cpu_outl(CPUState *env, int addr, int val)
287 {
288     addr &= (MAX_IOPORTS - 1);
289     ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
290 }
291
292 int cpu_inb(CPUState *env, int addr)
293 {
294     addr &= (MAX_IOPORTS - 1);
295     return ioport_read_table[0][addr](ioport_opaque[addr], addr);
296 }
297
298 int cpu_inw(CPUState *env, int addr)
299 {
300     addr &= (MAX_IOPORTS - 1);
301     return ioport_read_table[1][addr](ioport_opaque[addr], addr);
302 }
303
304 int cpu_inl(CPUState *env, int addr)
305 {
306     addr &= (MAX_IOPORTS - 1);
307     return ioport_read_table[2][addr](ioport_opaque[addr], addr);
308 }
309
310 /***********************************************************/
311 void hw_error(const char *fmt, ...)
312 {
313     va_list ap;
314
315     va_start(ap, fmt);
316     fprintf(stderr, "qemu: hardware error: ");
317     vfprintf(stderr, fmt, ap);
318     fprintf(stderr, "\n");
319 #ifdef TARGET_I386
320     cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
321 #else
322     cpu_dump_state(global_env, stderr, 0);
323 #endif
324     va_end(ap);
325     abort();
326 }
327
328 /***********************************************************/
329 /* timers */
330
331 #if defined(__powerpc__)
332
333 static inline uint32_t get_tbl(void) 
334 {
335     uint32_t tbl;
336     asm volatile("mftb %0" : "=r" (tbl));
337     return tbl;
338 }
339
340 static inline uint32_t get_tbu(void) 
341 {
342         uint32_t tbl;
343         asm volatile("mftbu %0" : "=r" (tbl));
344         return tbl;
345 }
346
347 int64_t cpu_get_real_ticks(void)
348 {
349     uint32_t l, h, h1;
350     /* NOTE: we test if wrapping has occurred */
351     do {
352         h = get_tbu();
353         l = get_tbl();
354         h1 = get_tbu();
355     } while (h != h1);
356     return ((int64_t)h << 32) | l;
357 }
358
359 #elif defined(__i386__)
360
361 int64_t cpu_get_real_ticks(void)
362 {
363     int64_t val;
364     asm volatile ("rdtsc" : "=A" (val));
365     return val;
366 }
367
368 #elif defined(__x86_64__)
369
370 int64_t cpu_get_real_ticks(void)
371 {
372     uint32_t low,high;
373     int64_t val;
374     asm volatile("rdtsc" : "=a" (low), "=d" (high));
375     val = high;
376     val <<= 32;
377     val |= low;
378     return val;
379 }
380
381 #else
382 #error unsupported CPU
383 #endif
384
385 static int64_t cpu_ticks_offset;
386 static int cpu_ticks_enabled;
387
388 static inline int64_t cpu_get_ticks(void)
389 {
390     if (!cpu_ticks_enabled) {
391         return cpu_ticks_offset;
392     } else {
393         return cpu_get_real_ticks() + cpu_ticks_offset;
394     }
395 }
396
397 /* enable cpu_get_ticks() */
398 void cpu_enable_ticks(void)
399 {
400     if (!cpu_ticks_enabled) {
401         cpu_ticks_offset -= cpu_get_real_ticks();
402         cpu_ticks_enabled = 1;
403     }
404 }
405
406 /* disable cpu_get_ticks() : the clock is stopped. You must not call
407    cpu_get_ticks() after that.  */
408 void cpu_disable_ticks(void)
409 {
410     if (cpu_ticks_enabled) {
411         cpu_ticks_offset = cpu_get_ticks();
412         cpu_ticks_enabled = 0;
413     }
414 }
415
416 static int64_t get_clock(void)
417 {
418 #ifdef _WIN32
419     struct _timeb tb;
420     _ftime(&tb);
421     return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
422 #else
423     struct timeval tv;
424     gettimeofday(&tv, NULL);
425     return tv.tv_sec * 1000000LL + tv.tv_usec;
426 #endif
427 }
428
429 void cpu_calibrate_ticks(void)
430 {
431     int64_t usec, ticks;
432
433     usec = get_clock();
434     ticks = cpu_get_real_ticks();
435 #ifdef _WIN32
436     Sleep(50);
437 #else
438     usleep(50 * 1000);
439 #endif
440     usec = get_clock() - usec;
441     ticks = cpu_get_real_ticks() - ticks;
442     ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
443 }
444
445 /* compute with 96 bit intermediate result: (a*b)/c */
446 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
447 {
448     union {
449         uint64_t ll;
450         struct {
451 #ifdef WORDS_BIGENDIAN
452             uint32_t high, low;
453 #else
454             uint32_t low, high;
455 #endif            
456         } l;
457     } u, res;
458     uint64_t rl, rh;
459
460     u.ll = a;
461     rl = (uint64_t)u.l.low * (uint64_t)b;
462     rh = (uint64_t)u.l.high * (uint64_t)b;
463     rh += (rl >> 32);
464     res.l.high = rh / c;
465     res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
466     return res.ll;
467 }
468
469 #define QEMU_TIMER_REALTIME 0
470 #define QEMU_TIMER_VIRTUAL  1
471
472 struct QEMUClock {
473     int type;
474     /* XXX: add frequency */
475 };
476
477 struct QEMUTimer {
478     QEMUClock *clock;
479     int64_t expire_time;
480     QEMUTimerCB *cb;
481     void *opaque;
482     struct QEMUTimer *next;
483 };
484
485 QEMUClock *rt_clock;
486 QEMUClock *vm_clock;
487
488 static QEMUTimer *active_timers[2];
489 #ifdef _WIN32
490 static MMRESULT timerID;
491 #else
492 /* frequency of the times() clock tick */
493 static int timer_freq;
494 #endif
495
496 QEMUClock *qemu_new_clock(int type)
497 {
498     QEMUClock *clock;
499     clock = qemu_mallocz(sizeof(QEMUClock));
500     if (!clock)
501         return NULL;
502     clock->type = type;
503     return clock;
504 }
505
506 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
507 {
508     QEMUTimer *ts;
509
510     ts = qemu_mallocz(sizeof(QEMUTimer));
511     ts->clock = clock;
512     ts->cb = cb;
513     ts->opaque = opaque;
514     return ts;
515 }
516
517 void qemu_free_timer(QEMUTimer *ts)
518 {
519     qemu_free(ts);
520 }
521
522 /* stop a timer, but do not dealloc it */
523 void qemu_del_timer(QEMUTimer *ts)
524 {
525     QEMUTimer **pt, *t;
526
527     /* NOTE: this code must be signal safe because
528        qemu_timer_expired() can be called from a signal. */
529     pt = &active_timers[ts->clock->type];
530     for(;;) {
531         t = *pt;
532         if (!t)
533             break;
534         if (t == ts) {
535             *pt = t->next;
536             break;
537         }
538         pt = &t->next;
539     }
540 }
541
542 /* modify the current timer so that it will be fired when current_time
543    >= expire_time. The corresponding callback will be called. */
544 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
545 {
546     QEMUTimer **pt, *t;
547
548     qemu_del_timer(ts);
549
550     /* add the timer in the sorted list */
551     /* NOTE: this code must be signal safe because
552        qemu_timer_expired() can be called from a signal. */
553     pt = &active_timers[ts->clock->type];
554     for(;;) {
555         t = *pt;
556         if (!t)
557             break;
558         if (t->expire_time > expire_time) 
559             break;
560         pt = &t->next;
561     }
562     ts->expire_time = expire_time;
563     ts->next = *pt;
564     *pt = ts;
565 }
566
567 int qemu_timer_pending(QEMUTimer *ts)
568 {
569     QEMUTimer *t;
570     for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
571         if (t == ts)
572             return 1;
573     }
574     return 0;
575 }
576
577 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
578 {
579     if (!timer_head)
580         return 0;
581     return (timer_head->expire_time <= current_time);
582 }
583
584 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
585 {
586     QEMUTimer *ts;
587     
588     for(;;) {
589         ts = *ptimer_head;
590         if (ts->expire_time > current_time)
591             break;
592         /* remove timer from the list before calling the callback */
593         *ptimer_head = ts->next;
594         ts->next = NULL;
595         
596         /* run the callback (the timer list can be modified) */
597         ts->cb(ts->opaque);
598     }
599 }
600
601 int64_t qemu_get_clock(QEMUClock *clock)
602 {
603     switch(clock->type) {
604     case QEMU_TIMER_REALTIME:
605 #ifdef _WIN32
606         return GetTickCount();
607 #else
608         /* XXX: portability among Linux hosts */
609         if (timer_freq == 100) {
610             return times(NULL) * 10;
611         } else {
612             return ((int64_t)times(NULL) * 1000) / timer_freq;
613         }
614 #endif
615     default:
616     case QEMU_TIMER_VIRTUAL:
617         return cpu_get_ticks();
618     }
619 }
620
621 /* save a timer */
622 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
623 {
624     uint64_t expire_time;
625
626     if (qemu_timer_pending(ts)) {
627         expire_time = ts->expire_time;
628     } else {
629         expire_time = -1;
630     }
631     qemu_put_be64(f, expire_time);
632 }
633
634 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
635 {
636     uint64_t expire_time;
637
638     expire_time = qemu_get_be64(f);
639     if (expire_time != -1) {
640         qemu_mod_timer(ts, expire_time);
641     } else {
642         qemu_del_timer(ts);
643     }
644 }
645
646 static void timer_save(QEMUFile *f, void *opaque)
647 {
648     if (cpu_ticks_enabled) {
649         hw_error("cannot save state if virtual timers are running");
650     }
651     qemu_put_be64s(f, &cpu_ticks_offset);
652     qemu_put_be64s(f, &ticks_per_sec);
653 }
654
655 static int timer_load(QEMUFile *f, void *opaque, int version_id)
656 {
657     if (version_id != 1)
658         return -EINVAL;
659     if (cpu_ticks_enabled) {
660         return -EINVAL;
661     }
662     qemu_get_be64s(f, &cpu_ticks_offset);
663     qemu_get_be64s(f, &ticks_per_sec);
664     return 0;
665 }
666
667 #ifdef _WIN32
668 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
669                                  DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
670 #else
671 static void host_alarm_handler(int host_signum)
672 #endif
673 {
674     if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
675                            qemu_get_clock(vm_clock)) ||
676         qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
677                            qemu_get_clock(rt_clock))) {
678         /* stop the cpu because a timer occured */
679         cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
680     }
681 }
682
683 static void init_timers(void)
684 {
685     rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
686     vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
687
688 #ifdef _WIN32
689     {
690         int count=0;
691         timerID = timeSetEvent(10,    // interval (ms)
692                                0,     // resolution
693                                host_alarm_handler, // function
694                                (DWORD)&count,  // user parameter
695                                TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
696         if( !timerID ) {
697             perror("failed timer alarm");
698             exit(1);
699         }
700     }
701     pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
702 #else
703     {
704         struct sigaction act;
705         struct itimerval itv;
706         
707         /* get times() syscall frequency */
708         timer_freq = sysconf(_SC_CLK_TCK);
709         
710         /* timer signal */
711         sigfillset(&act.sa_mask);
712         act.sa_flags = 0;
713 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
714         act.sa_flags |= SA_ONSTACK;
715 #endif
716         act.sa_handler = host_alarm_handler;
717         sigaction(SIGALRM, &act, NULL);
718         
719         itv.it_interval.tv_sec = 0;
720         itv.it_interval.tv_usec = 1000;
721         itv.it_value.tv_sec = 0;
722         itv.it_value.tv_usec = 10 * 1000;
723         setitimer(ITIMER_REAL, &itv, NULL);
724         /* we probe the tick duration of the kernel to inform the user if
725            the emulated kernel requested a too high timer frequency */
726         getitimer(ITIMER_REAL, &itv);
727         pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * PIT_FREQ) / 
728             1000000;
729     }
730 #endif
731 }
732
733 void quit_timers(void)
734 {
735 #ifdef _WIN32
736     timeKillEvent(timerID);
737 #endif
738 }
739
740 /***********************************************************/
741 /* serial device */
742
743 #ifdef _WIN32
744
745 int serial_open_device(void)
746 {
747     return -1;
748 }
749
750 #else
751
752 int serial_open_device(void)
753 {
754     char slave_name[1024];
755     int master_fd, slave_fd;
756
757     if (serial_console == NULL && nographic) {
758         /* use console for serial port */
759         return 0;
760     } else {
761         if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
762             fprintf(stderr, "warning: could not create pseudo terminal for serial port\n");
763             return -1;
764         }
765         fprintf(stderr, "Serial port redirected to %s\n", slave_name);
766         return master_fd;
767     }
768 }
769
770 #endif
771
772 /***********************************************************/
773 /* Linux network device redirectors */
774
775 void hex_dump(FILE *f, const uint8_t *buf, int size)
776 {
777     int len, i, j, c;
778
779     for(i=0;i<size;i+=16) {
780         len = size - i;
781         if (len > 16)
782             len = 16;
783         fprintf(f, "%08x ", i);
784         for(j=0;j<16;j++) {
785             if (j < len)
786                 fprintf(f, " %02x", buf[i+j]);
787             else
788                 fprintf(f, "   ");
789         }
790         fprintf(f, " ");
791         for(j=0;j<len;j++) {
792             c = buf[i+j];
793             if (c < ' ' || c > '~')
794                 c = '.';
795             fprintf(f, "%c", c);
796         }
797         fprintf(f, "\n");
798     }
799 }
800
801 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
802 {
803     nd->send_packet(nd, buf, size);
804 }
805
806 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read, 
807                           IOReadHandler *fd_read, void *opaque)
808 {
809     nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
810 }
811
812 /* dummy network adapter */
813
814 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
815 {
816 }
817
818 static void dummy_add_read_packet(NetDriverState *nd, 
819                                   IOCanRWHandler *fd_can_read, 
820                                   IOReadHandler *fd_read, void *opaque)
821 {
822 }
823
824 static int net_dummy_init(NetDriverState *nd)
825 {
826     nd->send_packet = dummy_send_packet;
827     nd->add_read_packet = dummy_add_read_packet;
828     pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
829     return 0;
830 }
831
832 #if defined(CONFIG_SLIRP)
833
834 /* slirp network adapter */
835
836 static void *slirp_fd_opaque;
837 static IOCanRWHandler *slirp_fd_can_read;
838 static IOReadHandler *slirp_fd_read;
839 static int slirp_inited;
840
841 int slirp_can_output(void)
842 {
843     return slirp_fd_can_read(slirp_fd_opaque);
844 }
845
846 void slirp_output(const uint8_t *pkt, int pkt_len)
847 {
848 #if 0
849     printf("output:\n");
850     hex_dump(stdout, pkt, pkt_len);
851 #endif
852     slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
853 }
854
855 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
856 {
857 #if 0
858     printf("input:\n");
859     hex_dump(stdout, buf, size);
860 #endif
861     slirp_input(buf, size);
862 }
863
864 static void slirp_add_read_packet(NetDriverState *nd, 
865                                   IOCanRWHandler *fd_can_read, 
866                                   IOReadHandler *fd_read, void *opaque)
867 {
868     slirp_fd_opaque = opaque;
869     slirp_fd_can_read = fd_can_read;
870     slirp_fd_read = fd_read;
871 }
872
873 static int net_slirp_init(NetDriverState *nd)
874 {
875     if (!slirp_inited) {
876         slirp_inited = 1;
877         slirp_init();
878     }
879     nd->send_packet = slirp_send_packet;
880     nd->add_read_packet = slirp_add_read_packet;
881     pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
882     return 0;
883 }
884
885 #endif /* CONFIG_SLIRP */
886
887 #if !defined(_WIN32)
888
889 static int tun_open(char *ifname, int ifname_size)
890 {
891     struct ifreq ifr;
892     int fd, ret;
893     
894     fd = open("/dev/net/tun", O_RDWR);
895     if (fd < 0) {
896         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
897         return -1;
898     }
899     memset(&ifr, 0, sizeof(ifr));
900     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
901     pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
902     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
903     if (ret != 0) {
904         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
905         close(fd);
906         return -1;
907     }
908     printf("Connected to host network interface: %s\n", ifr.ifr_name);
909     pstrcpy(ifname, ifname_size, ifr.ifr_name);
910     fcntl(fd, F_SETFL, O_NONBLOCK);
911     return fd;
912 }
913
914 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
915 {
916     write(nd->fd, buf, size);
917 }
918
919 static void tun_add_read_packet(NetDriverState *nd, 
920                                 IOCanRWHandler *fd_can_read, 
921                                 IOReadHandler *fd_read, void *opaque)
922 {
923     qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
924 }
925
926 static int net_tun_init(NetDriverState *nd)
927 {
928     int pid, status;
929     char *args[3];
930     char **parg;
931
932     nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
933     if (nd->fd < 0)
934         return -1;
935
936     /* try to launch network init script */
937     pid = fork();
938     if (pid >= 0) {
939         if (pid == 0) {
940             parg = args;
941             *parg++ = network_script;
942             *parg++ = nd->ifname;
943             *parg++ = NULL;
944             execv(network_script, args);
945             exit(1);
946         }
947         while (waitpid(pid, &status, 0) != pid);
948         if (!WIFEXITED(status) ||
949             WEXITSTATUS(status) != 0) {
950             fprintf(stderr, "%s: could not launch network script\n",
951                     network_script);
952         }
953     }
954     nd->send_packet = tun_send_packet;
955     nd->add_read_packet = tun_add_read_packet;
956     return 0;
957 }
958
959 static int net_fd_init(NetDriverState *nd, int fd)
960 {
961     nd->fd = fd;
962     nd->send_packet = tun_send_packet;
963     nd->add_read_packet = tun_add_read_packet;
964     pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
965     return 0;
966 }
967
968 #endif /* !_WIN32 */
969
970 /***********************************************************/
971 /* dumb display */
972
973 #ifdef _WIN32
974
975 static void term_exit(void)
976 {
977 }
978
979 static void term_init(void)
980 {
981 }
982
983 #else
984
985 /* init terminal so that we can grab keys */
986 static struct termios oldtty;
987
988 static void term_exit(void)
989 {
990     tcsetattr (0, TCSANOW, &oldtty);
991 }
992
993 static void term_init(void)
994 {
995     struct termios tty;
996
997     tcgetattr (0, &tty);
998     oldtty = tty;
999
1000     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1001                           |INLCR|IGNCR|ICRNL|IXON);
1002     tty.c_oflag |= OPOST;
1003     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1004     /* if graphical mode, we allow Ctrl-C handling */
1005     if (nographic)
1006         tty.c_lflag &= ~ISIG;
1007     tty.c_cflag &= ~(CSIZE|PARENB);
1008     tty.c_cflag |= CS8;
1009     tty.c_cc[VMIN] = 1;
1010     tty.c_cc[VTIME] = 0;
1011     
1012     tcsetattr (0, TCSANOW, &tty);
1013
1014     atexit(term_exit);
1015
1016     fcntl(0, F_SETFL, O_NONBLOCK);
1017 }
1018
1019 #endif
1020
1021 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1022 {
1023 }
1024
1025 static void dumb_resize(DisplayState *ds, int w, int h)
1026 {
1027 }
1028
1029 static void dumb_refresh(DisplayState *ds)
1030 {
1031     vga_update_display();
1032 }
1033
1034 void dumb_display_init(DisplayState *ds)
1035 {
1036     ds->data = NULL;
1037     ds->linesize = 0;
1038     ds->depth = 0;
1039     ds->dpy_update = dumb_update;
1040     ds->dpy_resize = dumb_resize;
1041     ds->dpy_refresh = dumb_refresh;
1042 }
1043
1044 #if !defined(CONFIG_SOFTMMU)
1045 /***********************************************************/
1046 /* cpu signal handler */
1047 static void host_segv_handler(int host_signum, siginfo_t *info, 
1048                               void *puc)
1049 {
1050     if (cpu_signal_handler(host_signum, info, puc))
1051         return;
1052     term_exit();
1053     abort();
1054 }
1055 #endif
1056
1057 /***********************************************************/
1058 /* I/O handling */
1059
1060 #define MAX_IO_HANDLERS 64
1061
1062 typedef struct IOHandlerRecord {
1063     int fd;
1064     IOCanRWHandler *fd_can_read;
1065     IOReadHandler *fd_read;
1066     void *opaque;
1067     /* temporary data */
1068     struct pollfd *ufd;
1069     int max_size;
1070     struct IOHandlerRecord *next;
1071 } IOHandlerRecord;
1072
1073 static IOHandlerRecord *first_io_handler;
1074
1075 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read, 
1076                              IOReadHandler *fd_read, void *opaque)
1077 {
1078     IOHandlerRecord *ioh;
1079
1080     ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1081     if (!ioh)
1082         return -1;
1083     ioh->fd = fd;
1084     ioh->fd_can_read = fd_can_read;
1085     ioh->fd_read = fd_read;
1086     ioh->opaque = opaque;
1087     ioh->next = first_io_handler;
1088     first_io_handler = ioh;
1089     return 0;
1090 }
1091
1092 void qemu_del_fd_read_handler(int fd)
1093 {
1094     IOHandlerRecord **pioh, *ioh;
1095
1096     pioh = &first_io_handler;
1097     for(;;) {
1098         ioh = *pioh;
1099         if (ioh == NULL)
1100             break;
1101         if (ioh->fd == fd) {
1102             *pioh = ioh->next;
1103             break;
1104         }
1105         pioh = &ioh->next;
1106     }
1107 }
1108
1109 /***********************************************************/
1110 /* savevm/loadvm support */
1111
1112 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1113 {
1114     fwrite(buf, 1, size, f);
1115 }
1116
1117 void qemu_put_byte(QEMUFile *f, int v)
1118 {
1119     fputc(v, f);
1120 }
1121
1122 void qemu_put_be16(QEMUFile *f, unsigned int v)
1123 {
1124     qemu_put_byte(f, v >> 8);
1125     qemu_put_byte(f, v);
1126 }
1127
1128 void qemu_put_be32(QEMUFile *f, unsigned int v)
1129 {
1130     qemu_put_byte(f, v >> 24);
1131     qemu_put_byte(f, v >> 16);
1132     qemu_put_byte(f, v >> 8);
1133     qemu_put_byte(f, v);
1134 }
1135
1136 void qemu_put_be64(QEMUFile *f, uint64_t v)
1137 {
1138     qemu_put_be32(f, v >> 32);
1139     qemu_put_be32(f, v);
1140 }
1141
1142 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1143 {
1144     return fread(buf, 1, size, f);
1145 }
1146
1147 int qemu_get_byte(QEMUFile *f)
1148 {
1149     int v;
1150     v = fgetc(f);
1151     if (v == EOF)
1152         return 0;
1153     else
1154         return v;
1155 }
1156
1157 unsigned int qemu_get_be16(QEMUFile *f)
1158 {
1159     unsigned int v;
1160     v = qemu_get_byte(f) << 8;
1161     v |= qemu_get_byte(f);
1162     return v;
1163 }
1164
1165 unsigned int qemu_get_be32(QEMUFile *f)
1166 {
1167     unsigned int v;
1168     v = qemu_get_byte(f) << 24;
1169     v |= qemu_get_byte(f) << 16;
1170     v |= qemu_get_byte(f) << 8;
1171     v |= qemu_get_byte(f);
1172     return v;
1173 }
1174
1175 uint64_t qemu_get_be64(QEMUFile *f)
1176 {
1177     uint64_t v;
1178     v = (uint64_t)qemu_get_be32(f) << 32;
1179     v |= qemu_get_be32(f);
1180     return v;
1181 }
1182
1183 int64_t qemu_ftell(QEMUFile *f)
1184 {
1185     return ftell(f);
1186 }
1187
1188 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1189 {
1190     if (fseek(f, pos, whence) < 0)
1191         return -1;
1192     return ftell(f);
1193 }
1194
1195 typedef struct SaveStateEntry {
1196     char idstr[256];
1197     int instance_id;
1198     int version_id;
1199     SaveStateHandler *save_state;
1200     LoadStateHandler *load_state;
1201     void *opaque;
1202     struct SaveStateEntry *next;
1203 } SaveStateEntry;
1204
1205 static SaveStateEntry *first_se;
1206
1207 int register_savevm(const char *idstr, 
1208                     int instance_id, 
1209                     int version_id,
1210                     SaveStateHandler *save_state,
1211                     LoadStateHandler *load_state,
1212                     void *opaque)
1213 {
1214     SaveStateEntry *se, **pse;
1215
1216     se = qemu_malloc(sizeof(SaveStateEntry));
1217     if (!se)
1218         return -1;
1219     pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1220     se->instance_id = instance_id;
1221     se->version_id = version_id;
1222     se->save_state = save_state;
1223     se->load_state = load_state;
1224     se->opaque = opaque;
1225     se->next = NULL;
1226
1227     /* add at the end of list */
1228     pse = &first_se;
1229     while (*pse != NULL)
1230         pse = &(*pse)->next;
1231     *pse = se;
1232     return 0;
1233 }
1234
1235 #define QEMU_VM_FILE_MAGIC   0x5145564d
1236 #define QEMU_VM_FILE_VERSION 0x00000001
1237
1238 int qemu_savevm(const char *filename)
1239 {
1240     SaveStateEntry *se;
1241     QEMUFile *f;
1242     int len, len_pos, cur_pos, saved_vm_running, ret;
1243
1244     saved_vm_running = vm_running;
1245     vm_stop(0);
1246
1247     f = fopen(filename, "wb");
1248     if (!f) {
1249         ret = -1;
1250         goto the_end;
1251     }
1252
1253     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1254     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1255
1256     for(se = first_se; se != NULL; se = se->next) {
1257         /* ID string */
1258         len = strlen(se->idstr);
1259         qemu_put_byte(f, len);
1260         qemu_put_buffer(f, se->idstr, len);
1261
1262         qemu_put_be32(f, se->instance_id);
1263         qemu_put_be32(f, se->version_id);
1264
1265         /* record size: filled later */
1266         len_pos = ftell(f);
1267         qemu_put_be32(f, 0);
1268         
1269         se->save_state(f, se->opaque);
1270
1271         /* fill record size */
1272         cur_pos = ftell(f);
1273         len = ftell(f) - len_pos - 4;
1274         fseek(f, len_pos, SEEK_SET);
1275         qemu_put_be32(f, len);
1276         fseek(f, cur_pos, SEEK_SET);
1277     }
1278
1279     fclose(f);
1280     ret = 0;
1281  the_end:
1282     if (saved_vm_running)
1283         vm_start();
1284     return ret;
1285 }
1286
1287 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1288 {
1289     SaveStateEntry *se;
1290
1291     for(se = first_se; se != NULL; se = se->next) {
1292         if (!strcmp(se->idstr, idstr) && 
1293             instance_id == se->instance_id)
1294             return se;
1295     }
1296     return NULL;
1297 }
1298
1299 int qemu_loadvm(const char *filename)
1300 {
1301     SaveStateEntry *se;
1302     QEMUFile *f;
1303     int len, cur_pos, ret, instance_id, record_len, version_id;
1304     int saved_vm_running;
1305     unsigned int v;
1306     char idstr[256];
1307     
1308     saved_vm_running = vm_running;
1309     vm_stop(0);
1310
1311     f = fopen(filename, "rb");
1312     if (!f) {
1313         ret = -1;
1314         goto the_end;
1315     }
1316
1317     v = qemu_get_be32(f);
1318     if (v != QEMU_VM_FILE_MAGIC)
1319         goto fail;
1320     v = qemu_get_be32(f);
1321     if (v != QEMU_VM_FILE_VERSION) {
1322     fail:
1323         fclose(f);
1324         ret = -1;
1325         goto the_end;
1326     }
1327     for(;;) {
1328 #if defined (DO_TB_FLUSH)
1329         tb_flush(global_env);
1330 #endif
1331         len = qemu_get_byte(f);
1332         if (feof(f))
1333             break;
1334         qemu_get_buffer(f, idstr, len);
1335         idstr[len] = '\0';
1336         instance_id = qemu_get_be32(f);
1337         version_id = qemu_get_be32(f);
1338         record_len = qemu_get_be32(f);
1339 #if 0
1340         printf("idstr=%s instance=0x%x version=%d len=%d\n", 
1341                idstr, instance_id, version_id, record_len);
1342 #endif
1343         cur_pos = ftell(f);
1344         se = find_se(idstr, instance_id);
1345         if (!se) {
1346             fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
1347                     instance_id, idstr);
1348         } else {
1349             ret = se->load_state(f, se->opaque, version_id);
1350             if (ret < 0) {
1351                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
1352                         instance_id, idstr);
1353             }
1354         }
1355         /* always seek to exact end of record */
1356         qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1357     }
1358     fclose(f);
1359     ret = 0;
1360  the_end:
1361     if (saved_vm_running)
1362         vm_start();
1363     return ret;
1364 }
1365
1366 /***********************************************************/
1367 /* cpu save/restore */
1368
1369 #if defined(TARGET_I386)
1370
1371 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
1372 {
1373     qemu_put_be32(f, (uint32_t)dt->base);
1374     qemu_put_be32(f, dt->limit);
1375     qemu_put_be32(f, dt->flags);
1376 }
1377
1378 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
1379 {
1380     dt->base = (uint8_t *)qemu_get_be32(f);
1381     dt->limit = qemu_get_be32(f);
1382     dt->flags = qemu_get_be32(f);
1383 }
1384
1385 void cpu_save(QEMUFile *f, void *opaque)
1386 {
1387     CPUState *env = opaque;
1388     uint16_t fptag, fpus, fpuc;
1389     uint32_t hflags;
1390     int i;
1391
1392     for(i = 0; i < 8; i++)
1393         qemu_put_be32s(f, &env->regs[i]);
1394     qemu_put_be32s(f, &env->eip);
1395     qemu_put_be32s(f, &env->eflags);
1396     qemu_put_be32s(f, &env->eflags);
1397     hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
1398     qemu_put_be32s(f, &hflags);
1399     
1400     /* FPU */
1401     fpuc = env->fpuc;
1402     fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
1403     fptag = 0;
1404     for (i=7; i>=0; i--) {
1405         fptag <<= 2;
1406         if (env->fptags[i]) {
1407             fptag |= 3;
1408         }
1409     }
1410     
1411     qemu_put_be16s(f, &fpuc);
1412     qemu_put_be16s(f, &fpus);
1413     qemu_put_be16s(f, &fptag);
1414
1415     for(i = 0; i < 8; i++) {
1416         uint64_t mant;
1417         uint16_t exp;
1418         cpu_get_fp80(&mant, &exp, env->fpregs[i]);
1419         qemu_put_be64(f, mant);
1420         qemu_put_be16(f, exp);
1421     }
1422
1423     for(i = 0; i < 6; i++)
1424         cpu_put_seg(f, &env->segs[i]);
1425     cpu_put_seg(f, &env->ldt);
1426     cpu_put_seg(f, &env->tr);
1427     cpu_put_seg(f, &env->gdt);
1428     cpu_put_seg(f, &env->idt);
1429     
1430     qemu_put_be32s(f, &env->sysenter_cs);
1431     qemu_put_be32s(f, &env->sysenter_esp);
1432     qemu_put_be32s(f, &env->sysenter_eip);
1433     
1434     qemu_put_be32s(f, &env->cr[0]);
1435     qemu_put_be32s(f, &env->cr[2]);
1436     qemu_put_be32s(f, &env->cr[3]);
1437     qemu_put_be32s(f, &env->cr[4]);
1438     
1439     for(i = 0; i < 8; i++)
1440         qemu_put_be32s(f, &env->dr[i]);
1441
1442     /* MMU */
1443     qemu_put_be32s(f, &env->a20_mask);
1444 }
1445
1446 int cpu_load(QEMUFile *f, void *opaque, int version_id)
1447 {
1448     CPUState *env = opaque;
1449     int i;
1450     uint32_t hflags;
1451     uint16_t fpus, fpuc, fptag;
1452
1453     if (version_id != 1)
1454         return -EINVAL;
1455     for(i = 0; i < 8; i++)
1456         qemu_get_be32s(f, &env->regs[i]);
1457     qemu_get_be32s(f, &env->eip);
1458     qemu_get_be32s(f, &env->eflags);
1459     qemu_get_be32s(f, &env->eflags);
1460     qemu_get_be32s(f, &hflags);
1461
1462     qemu_get_be16s(f, &fpuc);
1463     qemu_get_be16s(f, &fpus);
1464     qemu_get_be16s(f, &fptag);
1465
1466     for(i = 0; i < 8; i++) {
1467         uint64_t mant;
1468         uint16_t exp;
1469         mant = qemu_get_be64(f);
1470         exp = qemu_get_be16(f);
1471         env->fpregs[i] = cpu_set_fp80(mant, exp);
1472     }
1473
1474     env->fpuc = fpuc;
1475     env->fpstt = (fpus >> 11) & 7;
1476     env->fpus = fpus & ~0x3800;
1477     for(i = 0; i < 8; i++) {
1478         env->fptags[i] = ((fptag & 3) == 3);
1479         fptag >>= 2;
1480     }
1481     
1482     for(i = 0; i < 6; i++)
1483         cpu_get_seg(f, &env->segs[i]);
1484     cpu_get_seg(f, &env->ldt);
1485     cpu_get_seg(f, &env->tr);
1486     cpu_get_seg(f, &env->gdt);
1487     cpu_get_seg(f, &env->idt);
1488     
1489     qemu_get_be32s(f, &env->sysenter_cs);
1490     qemu_get_be32s(f, &env->sysenter_esp);
1491     qemu_get_be32s(f, &env->sysenter_eip);
1492     
1493     qemu_get_be32s(f, &env->cr[0]);
1494     qemu_get_be32s(f, &env->cr[2]);
1495     qemu_get_be32s(f, &env->cr[3]);
1496     qemu_get_be32s(f, &env->cr[4]);
1497     
1498     for(i = 0; i < 8; i++)
1499         qemu_get_be32s(f, &env->dr[i]);
1500
1501     /* MMU */
1502     qemu_get_be32s(f, &env->a20_mask);
1503
1504     /* XXX: compute hflags from scratch, except for CPL and IIF */
1505     env->hflags = hflags;
1506     tlb_flush(env, 1);
1507     return 0;
1508 }
1509
1510 #elif defined(TARGET_PPC)
1511 void cpu_save(QEMUFile *f, void *opaque)
1512 {
1513 }
1514
1515 int cpu_load(QEMUFile *f, void *opaque, int version_id)
1516 {
1517     return 0;
1518 }
1519 #else
1520
1521 #warning No CPU save/restore functions
1522
1523 #endif
1524
1525 /***********************************************************/
1526 /* ram save/restore */
1527
1528 /* we just avoid storing empty pages */
1529 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
1530 {
1531     int i, v;
1532
1533     v = buf[0];
1534     for(i = 1; i < len; i++) {
1535         if (buf[i] != v)
1536             goto normal_save;
1537     }
1538     qemu_put_byte(f, 1);
1539     qemu_put_byte(f, v);
1540     return;
1541  normal_save:
1542     qemu_put_byte(f, 0); 
1543     qemu_put_buffer(f, buf, len);
1544 }
1545
1546 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
1547 {
1548     int v;
1549
1550     v = qemu_get_byte(f);
1551     switch(v) {
1552     case 0:
1553         if (qemu_get_buffer(f, buf, len) != len)
1554             return -EIO;
1555         break;
1556     case 1:
1557         v = qemu_get_byte(f);
1558         memset(buf, v, len);
1559         break;
1560     default:
1561         return -EINVAL;
1562     }
1563     return 0;
1564 }
1565
1566 static void ram_save(QEMUFile *f, void *opaque)
1567 {
1568     int i;
1569     qemu_put_be32(f, phys_ram_size);
1570     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1571         ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1572     }
1573 }
1574
1575 static int ram_load(QEMUFile *f, void *opaque, int version_id)
1576 {
1577     int i, ret;
1578
1579     if (version_id != 1)
1580         return -EINVAL;
1581     if (qemu_get_be32(f) != phys_ram_size)
1582         return -EINVAL;
1583     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1584         ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1585         if (ret)
1586             return ret;
1587     }
1588     return 0;
1589 }
1590
1591 /***********************************************************/
1592 /* main execution loop */
1593
1594 void gui_update(void *opaque)
1595 {
1596     display_state.dpy_refresh(&display_state);
1597     qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
1598 }
1599
1600 /* XXX: support several handlers */
1601 VMStopHandler *vm_stop_cb;
1602 VMStopHandler *vm_stop_opaque;
1603
1604 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
1605 {
1606     vm_stop_cb = cb;
1607     vm_stop_opaque = opaque;
1608     return 0;
1609 }
1610
1611 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
1612 {
1613     vm_stop_cb = NULL;
1614 }
1615
1616 void vm_start(void)
1617 {
1618     if (!vm_running) {
1619         cpu_enable_ticks();
1620         vm_running = 1;
1621     }
1622 }
1623
1624 void vm_stop(int reason) 
1625 {
1626     if (vm_running) {
1627         cpu_disable_ticks();
1628         vm_running = 0;
1629         if (reason != 0) {
1630             if (vm_stop_cb) {
1631                 vm_stop_cb(vm_stop_opaque, reason);
1632             }
1633         }
1634     }
1635 }
1636
1637 int main_loop(void)
1638 {
1639 #ifndef _WIN32
1640     struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
1641     IOHandlerRecord *ioh, *ioh_next;
1642     uint8_t buf[4096];
1643     int n, max_size;
1644 #endif
1645     int ret, timeout;
1646     CPUState *env = global_env;
1647
1648     for(;;) {
1649         if (vm_running) {
1650             ret = cpu_exec(env);
1651             if (reset_requested) {
1652                 ret = EXCP_INTERRUPT; 
1653                 break;
1654             }
1655             if (ret == EXCP_DEBUG) {
1656                 vm_stop(EXCP_DEBUG);
1657             }
1658             /* if hlt instruction, we wait until the next IRQ */
1659             /* XXX: use timeout computed from timers */
1660             if (ret == EXCP_HLT) 
1661                 timeout = 10;
1662             else
1663                 timeout = 0;
1664         } else {
1665             timeout = 10;
1666         }
1667
1668 #ifdef _WIN32
1669         if (timeout > 0)
1670             Sleep(timeout);
1671 #else
1672
1673         /* poll any events */
1674         /* XXX: separate device handlers from system ones */
1675         pf = ufds;
1676         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
1677             if (!ioh->fd_can_read) {
1678                 max_size = 0;
1679                 pf->fd = ioh->fd;
1680                 pf->events = POLLIN;
1681                 ioh->ufd = pf;
1682                 pf++;
1683             } else {
1684                 max_size = ioh->fd_can_read(ioh->opaque);
1685                 if (max_size > 0) {
1686                     if (max_size > sizeof(buf))
1687                         max_size = sizeof(buf);
1688                     pf->fd = ioh->fd;
1689                     pf->events = POLLIN;
1690                     ioh->ufd = pf;
1691                     pf++;
1692                 } else {
1693                     ioh->ufd = NULL;
1694                 }
1695             }
1696             ioh->max_size = max_size;
1697         }
1698         
1699         ret = poll(ufds, pf - ufds, timeout);
1700         if (ret > 0) {
1701             /* XXX: better handling of removal */
1702             for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
1703                 ioh_next = ioh->next;
1704                 pf = ioh->ufd;
1705                 if (pf) {
1706                     if (pf->revents & POLLIN) {
1707                         if (ioh->max_size == 0) {
1708                             /* just a read event */
1709                             ioh->fd_read(ioh->opaque, NULL, 0);
1710                         } else {
1711                             n = read(ioh->fd, buf, ioh->max_size);
1712                             if (n >= 0) {
1713                                 ioh->fd_read(ioh->opaque, buf, n);
1714                             } else if (errno != -EAGAIN) {
1715                                 ioh->fd_read(ioh->opaque, NULL, -errno);
1716                             }
1717                         }
1718                     }
1719                 }
1720             }
1721         }
1722
1723 #if defined(CONFIG_SLIRP)
1724         /* XXX: merge with poll() */
1725         if (slirp_inited) {
1726             fd_set rfds, wfds, xfds;
1727             int nfds;
1728             struct timeval tv;
1729
1730             nfds = -1;
1731             FD_ZERO(&rfds);
1732             FD_ZERO(&wfds);
1733             FD_ZERO(&xfds);
1734             slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1735             tv.tv_sec = 0;
1736             tv.tv_usec = 0;
1737             ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1738             if (ret >= 0) {
1739                 slirp_select_poll(&rfds, &wfds, &xfds);
1740             }
1741         }
1742 #endif
1743
1744 #endif
1745
1746         if (vm_running) {
1747             qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
1748                             qemu_get_clock(vm_clock));
1749             
1750             if (audio_enabled) {
1751                 /* XXX: add explicit timer */
1752                 SB16_run();
1753             }
1754             
1755             /* run dma transfers, if any */
1756             DMA_run();
1757         }
1758
1759         /* real time timers */
1760         qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
1761                         qemu_get_clock(rt_clock));
1762     }
1763     cpu_disable_ticks();
1764     return ret;
1765 }
1766
1767 void help(void)
1768 {
1769     printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
1770            "usage: %s [options] [disk_image]\n"
1771            "\n"
1772            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
1773            "\n"
1774            "Standard options:\n"
1775            "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
1776            "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
1777            "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
1778            "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
1779            "-boot [a|b|c|d] boot on floppy (a, b), hard disk (c) or CD-ROM (d)\n"
1780            "-snapshot       write to temporary files instead of disk image files\n"
1781            "-m megs         set virtual RAM size to megs MB\n"
1782            "-nographic      disable graphical output and redirect serial I/Os to console\n"
1783            "-enable-audio   enable audio support\n"
1784            "\n"
1785            "Network options:\n"
1786            "-nics n         simulate 'n' network cards [default=1]\n"
1787            "-macaddr addr   set the mac address of the first interface\n"
1788            "-n script       set tap/tun network init script [default=%s]\n"
1789            "-tun-fd fd      use this fd as already opened tap/tun interface\n"
1790 #ifdef CONFIG_SLIRP
1791            "-user-net       use user mode network stack [default if no tap/tun script]\n"
1792 #endif
1793            "-dummy-net      use dummy network stack\n"
1794            "\n"
1795            "Linux boot specific:\n"
1796            "-kernel bzImage use 'bzImage' as kernel image\n"
1797            "-append cmdline use 'cmdline' as kernel command line\n"
1798            "-initrd file    use 'file' as initial ram disk\n"
1799            "\n"
1800            "Debug/Expert options:\n"
1801            "-s              wait gdb connection to port %d\n"
1802            "-p port         change gdb connection port\n"
1803            "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
1804            "-hdachs c,h,s   force hard disk 0 geometry (usually qemu can guess it)\n"
1805            "-L path         set the directory for the BIOS and VGA BIOS\n"
1806 #ifdef USE_CODE_COPY
1807            "-no-code-copy   disable code copy acceleration\n"
1808 #endif
1809
1810            "\n"
1811            "During emulation, use C-a h to get terminal commands:\n",
1812 #ifdef CONFIG_SOFTMMU
1813            "qemu",
1814 #else
1815            "qemu-fast",
1816 #endif
1817            DEFAULT_NETWORK_SCRIPT, 
1818            DEFAULT_GDBSTUB_PORT,
1819            "/tmp/qemu.log");
1820     term_print_help();
1821 #ifndef CONFIG_SOFTMMU
1822     printf("\n"
1823            "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
1824            "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
1825            "PC emulation.\n");
1826 #endif
1827     exit(1);
1828 }
1829
1830 struct option long_options[] = {
1831     { "initrd", 1, NULL, 0, },
1832     { "hda", 1, NULL, 0, },
1833     { "hdb", 1, NULL, 0, },
1834     { "snapshot", 0, NULL, 0, },
1835     { "hdachs", 1, NULL, 0, },
1836     { "nographic", 0, NULL, 0, },
1837     { "kernel", 1, NULL, 0, },
1838     { "append", 1, NULL, 0, },
1839     { "tun-fd", 1, NULL, 0, },
1840     { "hdc", 1, NULL, 0, },
1841     { "hdd", 1, NULL, 0, },
1842     { "cdrom", 1, NULL, 0, },
1843     { "boot", 1, NULL, 0, },
1844     { "fda", 1, NULL, 0, },
1845     { "fdb", 1, NULL, 0, },
1846     { "no-code-copy", 0, NULL, 0 },
1847     { "nics", 1, NULL, 0 },
1848     { "macaddr", 1, NULL, 0 },
1849     { "user-net", 0, NULL, 0 },
1850     { "dummy-net", 0, NULL, 0 },
1851     { "enable-audio", 0, NULL, 0 },
1852     { NULL, 0, NULL, 0 },
1853 };
1854
1855 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1856
1857 /* this stack is only used during signal handling */
1858 #define SIGNAL_STACK_SIZE 32768
1859
1860 static uint8_t *signal_stack;
1861
1862 #endif
1863
1864 #define NET_IF_TUN   0
1865 #define NET_IF_USER  1
1866 #define NET_IF_DUMMY 2
1867
1868 int main(int argc, char **argv)
1869 {
1870 #ifdef CONFIG_GDBSTUB
1871     int use_gdbstub, gdbstub_port;
1872 #endif
1873     int c, i, long_index, has_cdrom;
1874     int snapshot, linux_boot;
1875     CPUState *env;
1876     const char *initrd_filename;
1877     const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
1878     const char *kernel_filename, *kernel_cmdline;
1879     DisplayState *ds = &display_state;
1880     int cyls, heads, secs;
1881     int start_emulation = 1;
1882     uint8_t macaddr[6];
1883     int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
1884     
1885 #if !defined(CONFIG_SOFTMMU)
1886     /* we never want that malloc() uses mmap() */
1887     mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
1888 #endif
1889     initrd_filename = NULL;
1890     for(i = 0; i < MAX_FD; i++)
1891         fd_filename[i] = NULL;
1892     for(i = 0; i < MAX_DISKS; i++)
1893         hd_filename[i] = NULL;
1894     ram_size = 32 * 1024 * 1024;
1895     vga_ram_size = VGA_RAM_SIZE;
1896     pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
1897 #ifdef CONFIG_GDBSTUB
1898     use_gdbstub = 0;
1899     gdbstub_port = DEFAULT_GDBSTUB_PORT;
1900 #endif
1901     snapshot = 0;
1902     nographic = 0;
1903     kernel_filename = NULL;
1904     kernel_cmdline = "";
1905     has_cdrom = 1;
1906     cyls = heads = secs = 0;
1907
1908     nb_tun_fds = 0;
1909     net_if_type = -1;
1910     nb_nics = 1;
1911     /* default mac address of the first network interface */
1912     macaddr[0] = 0x52;
1913     macaddr[1] = 0x54;
1914     macaddr[2] = 0x00;
1915     macaddr[3] = 0x12;
1916     macaddr[4] = 0x34;
1917     macaddr[5] = 0x56;
1918
1919
1920     for(;;) {
1921         c = getopt_long_only(argc, argv, "hm:d:n:sp:L:S", long_options, &long_index);
1922         if (c == -1)
1923             break;
1924         switch(c) {
1925         case 0:
1926             switch(long_index) {
1927             case 0:
1928                 initrd_filename = optarg;
1929                 break;
1930             case 1:
1931                 hd_filename[0] = optarg;
1932                 break;
1933             case 2:
1934                 hd_filename[1] = optarg;
1935                 break;
1936             case 3:
1937                 snapshot = 1;
1938                 break;
1939             case 4:
1940                 {
1941                     const char *p;
1942                     p = optarg;
1943                     cyls = strtol(p, (char **)&p, 0);
1944                     if (*p != ',')
1945                         goto chs_fail;
1946                     p++;
1947                     heads = strtol(p, (char **)&p, 0);
1948                     if (*p != ',')
1949                         goto chs_fail;
1950                     p++;
1951                     secs = strtol(p, (char **)&p, 0);
1952                     if (*p != '\0') {
1953                     chs_fail:
1954                         cyls = 0;
1955                     }
1956                 }
1957                 break;
1958             case 5:
1959                 nographic = 1;
1960                 break;
1961             case 6:
1962                 kernel_filename = optarg;
1963                 break;
1964             case 7:
1965                 kernel_cmdline = optarg;
1966                 break;
1967             case 8:
1968                 {
1969                     const char *p;
1970                     int fd;
1971                     if (nb_tun_fds < MAX_NICS) {
1972                         fd = strtol(optarg, (char **)&p, 0);
1973                         if (*p != '\0') {
1974                             fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
1975                             exit(1);
1976                         }
1977                         tun_fds[nb_tun_fds++] = fd;
1978                     }
1979                 }
1980                 break;
1981             case 9:
1982                 hd_filename[2] = optarg;
1983                 has_cdrom = 0;
1984                 break;
1985             case 10:
1986                 hd_filename[3] = optarg;
1987                 break;
1988             case 11:
1989                 hd_filename[2] = optarg;
1990                 has_cdrom = 1;
1991                 break;
1992             case 12:
1993                 boot_device = optarg[0];
1994                 if (boot_device != 'a' && boot_device != 'b' &&
1995                     boot_device != 'c' && boot_device != 'd') {
1996                     fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
1997                     exit(1);
1998                 }
1999                 break;
2000             case 13:
2001                 fd_filename[0] = optarg;
2002                 break;
2003             case 14:
2004                 fd_filename[1] = optarg;
2005                 break;
2006             case 15:
2007                 code_copy_enabled = 0;
2008                 break;
2009             case 16:
2010                 nb_nics = atoi(optarg);
2011                 if (nb_nics < 1 || nb_nics > MAX_NICS) {
2012                     fprintf(stderr, "qemu: invalid number of network interfaces\n");
2013                     exit(1);
2014                 }
2015                 break;
2016             case 17:
2017                 {
2018                     const char *p;
2019                     int i;
2020                     p = optarg;
2021                     for(i = 0; i < 6; i++) {
2022                         macaddr[i] = strtol(p, (char **)&p, 16);
2023                         if (i == 5) {
2024                             if (*p != '\0') 
2025                                 goto macaddr_error;
2026                         } else {
2027                             if (*p != ':') {
2028                             macaddr_error:
2029                                 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
2030                                 exit(1);
2031                             }
2032                             p++;
2033                         }
2034                     }
2035                 }
2036                 break;
2037             case 18:
2038                 net_if_type = NET_IF_USER;
2039                 break;
2040             case 19:
2041                 net_if_type = NET_IF_DUMMY;
2042                 break;
2043             case 20:
2044                 audio_enabled = 1;
2045                 break;
2046             }
2047             break;
2048         case 'h':
2049             help();
2050             break;
2051         case 'm':
2052             ram_size = atoi(optarg) * 1024 * 1024;
2053             if (ram_size <= 0)
2054                 help();
2055             if (ram_size > PHYS_RAM_MAX_SIZE) {
2056                 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
2057                         PHYS_RAM_MAX_SIZE / (1024 * 1024));
2058                 exit(1);
2059             }
2060             break;
2061         case 'd':
2062             {
2063                 int mask;
2064                 CPULogItem *item;
2065
2066                 mask = cpu_str_to_log_mask(optarg);
2067                 if (!mask) {
2068                     printf("Log items (comma separated):\n");
2069                     for(item = cpu_log_items; item->mask != 0; item++) {
2070                         printf("%-10s %s\n", item->name, item->help);
2071                     }
2072                     exit(1);
2073                 }
2074                 cpu_set_log(mask);
2075             }
2076             break;
2077         case 'n':
2078             pstrcpy(network_script, sizeof(network_script), optarg);
2079             break;
2080 #ifdef CONFIG_GDBSTUB
2081         case 's':
2082             use_gdbstub = 1;
2083             break;
2084         case 'p':
2085             gdbstub_port = atoi(optarg);
2086             break;
2087 #endif
2088         case 'L':
2089             bios_dir = optarg;
2090             break;
2091         case 'S':
2092             start_emulation = 0;
2093             break;
2094         }
2095     }
2096
2097     if (optind < argc) {
2098         hd_filename[0] = argv[optind++];
2099     }
2100
2101     linux_boot = (kernel_filename != NULL);
2102         
2103     if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
2104         fd_filename[0] == '\0')
2105         help();
2106     
2107     /* boot to cd by default if no hard disk */
2108     if (hd_filename[0] == '\0' && boot_device == 'c') {
2109         if (fd_filename[0] != '\0')
2110             boot_device = 'a';
2111         else
2112             boot_device = 'd';
2113     }
2114
2115 #if !defined(CONFIG_SOFTMMU)
2116     /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2117     {
2118         static uint8_t stdout_buf[4096];
2119         setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2120     }
2121 #else
2122     setvbuf(stdout, NULL, _IOLBF, 0);
2123 #endif
2124
2125     /* init host network redirectors */
2126     if (net_if_type == -1) {
2127         net_if_type = NET_IF_TUN;
2128 #if defined(CONFIG_SLIRP)
2129         if (access(network_script, R_OK) < 0) {
2130             net_if_type = NET_IF_USER;
2131         }
2132 #endif
2133     }
2134
2135     for(i = 0; i < nb_nics; i++) {
2136         NetDriverState *nd = &nd_table[i];
2137         nd->index = i;
2138         /* init virtual mac address */
2139         nd->macaddr[0] = macaddr[0];
2140         nd->macaddr[1] = macaddr[1];
2141         nd->macaddr[2] = macaddr[2];
2142         nd->macaddr[3] = macaddr[3];
2143         nd->macaddr[4] = macaddr[4];
2144         nd->macaddr[5] = macaddr[5] + i;
2145         switch(net_if_type) {
2146 #if defined(CONFIG_SLIRP)
2147         case NET_IF_USER:
2148             net_slirp_init(nd);
2149             break;
2150 #endif
2151 #if !defined(_WIN32)
2152         case NET_IF_TUN:
2153             if (i < nb_tun_fds) {
2154                 net_fd_init(nd, tun_fds[i]);
2155             } else {
2156                 if (net_tun_init(nd) < 0)
2157                     net_dummy_init(nd);
2158             }
2159             break;
2160 #endif
2161         case NET_IF_DUMMY:
2162         default:
2163             net_dummy_init(nd);
2164             break;
2165         }
2166     }
2167
2168     /* init the memory */
2169     phys_ram_size = ram_size + vga_ram_size;
2170
2171 #ifdef CONFIG_SOFTMMU
2172     phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
2173     if (!phys_ram_base) {
2174         fprintf(stderr, "Could not allocate physical memory\n");
2175         exit(1);
2176     }
2177 #else
2178     /* as we must map the same page at several addresses, we must use
2179        a fd */
2180     {
2181         const char *tmpdir;
2182
2183         tmpdir = getenv("QEMU_TMPDIR");
2184         if (!tmpdir)
2185             tmpdir = "/tmp";
2186         snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
2187         if (mkstemp(phys_ram_file) < 0) {
2188             fprintf(stderr, "Could not create temporary memory file '%s'\n", 
2189                     phys_ram_file);
2190             exit(1);
2191         }
2192         phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
2193         if (phys_ram_fd < 0) {
2194             fprintf(stderr, "Could not open temporary memory file '%s'\n", 
2195                     phys_ram_file);
2196             exit(1);
2197         }
2198         ftruncate(phys_ram_fd, phys_ram_size);
2199         unlink(phys_ram_file);
2200         phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
2201                              phys_ram_size, 
2202                              PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
2203                              phys_ram_fd, 0);
2204         if (phys_ram_base == MAP_FAILED) {
2205             fprintf(stderr, "Could not map physical memory\n");
2206             exit(1);
2207         }
2208     }
2209 #endif
2210
2211     /* we always create the cdrom drive, even if no disk is there */
2212     if (has_cdrom) {
2213         bs_table[2] = bdrv_new("cdrom");
2214         bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
2215     }
2216
2217     /* open the virtual block devices */
2218     for(i = 0; i < MAX_DISKS; i++) {
2219         if (hd_filename[i]) {
2220             if (!bs_table[i]) {
2221                 char buf[64];
2222                 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
2223                 bs_table[i] = bdrv_new(buf);
2224             }
2225             if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
2226                 fprintf(stderr, "qemu: could not open hard disk image '%s\n",
2227                         hd_filename[i]);
2228                 exit(1);
2229             }
2230             if (i == 0 && cyls != 0) 
2231                 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
2232         }
2233     }
2234
2235     /* we always create at least one floppy disk */
2236     fd_table[0] = bdrv_new("fda");
2237     bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
2238
2239     for(i = 0; i < MAX_FD; i++) {
2240         if (fd_filename[i]) {
2241             if (!fd_table[i]) {
2242                 char buf[64];
2243                 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
2244                 fd_table[i] = bdrv_new(buf);
2245                 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
2246             }
2247             if (fd_filename[i] != '\0') {
2248                 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
2249                     fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
2250                             fd_filename[i]);
2251                     exit(1);
2252                 }
2253             }
2254         }
2255     }
2256
2257     /* init CPU state */
2258     env = cpu_init();
2259     global_env = env;
2260     cpu_single_env = env;
2261
2262     register_savevm("timer", 0, 1, timer_save, timer_load, env);
2263     register_savevm("cpu", 0, 1, cpu_save, cpu_load, env);
2264     register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
2265
2266     init_ioports();
2267     cpu_calibrate_ticks();
2268
2269     /* terminal init */
2270     if (nographic) {
2271         dumb_display_init(ds);
2272     } else {
2273 #ifdef CONFIG_SDL
2274         sdl_display_init(ds);
2275 #else
2276         dumb_display_init(ds);
2277 #endif
2278     }
2279
2280     /* setup cpu signal handlers for MMU / self modifying code handling */
2281 #if !defined(CONFIG_SOFTMMU)
2282     
2283 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2284     {
2285         stack_t stk;
2286         signal_stack = memalign(16, SIGNAL_STACK_SIZE);
2287         stk.ss_sp = signal_stack;
2288         stk.ss_size = SIGNAL_STACK_SIZE;
2289         stk.ss_flags = 0;
2290
2291         if (sigaltstack(&stk, NULL) < 0) {
2292             perror("sigaltstack");
2293             exit(1);
2294         }
2295     }
2296 #endif
2297     {
2298         struct sigaction act;
2299         
2300         sigfillset(&act.sa_mask);
2301         act.sa_flags = SA_SIGINFO;
2302 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2303         act.sa_flags |= SA_ONSTACK;
2304 #endif
2305         act.sa_sigaction = host_segv_handler;
2306         sigaction(SIGSEGV, &act, NULL);
2307         sigaction(SIGBUS, &act, NULL);
2308 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2309         sigaction(SIGFPE, &act, NULL);
2310 #endif
2311     }
2312 #endif
2313
2314 #ifndef _WIN32
2315     {
2316         struct sigaction act;
2317         sigfillset(&act.sa_mask);
2318         act.sa_flags = 0;
2319         act.sa_handler = SIG_IGN;
2320         sigaction(SIGPIPE, &act, NULL);
2321     }
2322 #endif
2323     init_timers();
2324
2325 #if defined(TARGET_I386)
2326     pc_init(ram_size, vga_ram_size, boot_device,
2327             ds, fd_filename, snapshot,
2328             kernel_filename, kernel_cmdline, initrd_filename);
2329 #elif defined(TARGET_PPC)
2330     ppc_init(ram_size, vga_ram_size, boot_device,
2331              ds, fd_filename, snapshot,
2332              kernel_filename, kernel_cmdline, initrd_filename);
2333 #endif
2334
2335     /* launched after the device init so that it can display or not a
2336        banner */
2337     monitor_init();
2338
2339     gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
2340     qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
2341
2342 #ifdef CONFIG_GDBSTUB
2343     if (use_gdbstub) {
2344         if (gdbserver_start(gdbstub_port) < 0) {
2345             fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
2346                     gdbstub_port);
2347             exit(1);
2348         } else {
2349             printf("Waiting gdb connection on port %d\n", gdbstub_port);
2350         }
2351     } else 
2352 #endif
2353     if (start_emulation)
2354     {
2355         vm_start();
2356     }
2357     term_init();
2358     main_loop();
2359     quit_timers();
2360     return 0;
2361 }