xref: /openbmc/qemu/bsd-user/main.c (revision 41b8280a)
1 /*
2  *  qemu user main
3  *
4  *  Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <stdarg.h>
22 #include <string.h>
23 #include <errno.h>
24 #include <unistd.h>
25 #include <machine/trap.h>
26 #include <sys/types.h>
27 #include <sys/mman.h>
28 
29 #include "qemu.h"
30 #include "qemu-common.h"
31 /* For tb_lock */
32 #include "cpu.h"
33 #include "tcg.h"
34 #include "qemu/timer.h"
35 #include "qemu/envlist.h"
36 
37 int singlestep;
38 #if defined(CONFIG_USE_GUEST_BASE)
39 unsigned long mmap_min_addr;
40 unsigned long guest_base;
41 int have_guest_base;
42 unsigned long reserved_va;
43 #endif
44 
45 static const char *interp_prefix = CONFIG_QEMU_INTERP_PREFIX;
46 const char *qemu_uname_release = CONFIG_UNAME_RELEASE;
47 extern char **environ;
48 enum BSDType bsd_type;
49 
50 /* XXX: on x86 MAP_GROWSDOWN only works if ESP <= address + 32, so
51    we allocate a bigger stack. Need a better solution, for example
52    by remapping the process stack directly at the right place */
53 unsigned long x86_stack_size = 512 * 1024;
54 
55 void gemu_log(const char *fmt, ...)
56 {
57     va_list ap;
58 
59     va_start(ap, fmt);
60     vfprintf(stderr, fmt, ap);
61     va_end(ap);
62 }
63 
64 #if defined(TARGET_I386)
65 int cpu_get_pic_interrupt(CPUX86State *env)
66 {
67     return -1;
68 }
69 #endif
70 
71 /* These are no-ops because we are not threadsafe.  */
72 static inline void cpu_exec_start(CPUArchState *env)
73 {
74 }
75 
76 static inline void cpu_exec_end(CPUArchState *env)
77 {
78 }
79 
80 static inline void start_exclusive(void)
81 {
82 }
83 
84 static inline void end_exclusive(void)
85 {
86 }
87 
88 void fork_start(void)
89 {
90 }
91 
92 void fork_end(int child)
93 {
94     if (child) {
95         gdbserver_fork((CPUArchState *)thread_cpu->env_ptr);
96     }
97 }
98 
99 void cpu_list_lock(void)
100 {
101 }
102 
103 void cpu_list_unlock(void)
104 {
105 }
106 
107 #ifdef TARGET_I386
108 /***********************************************************/
109 /* CPUX86 core interface */
110 
111 void cpu_smm_update(CPUX86State *env)
112 {
113 }
114 
115 uint64_t cpu_get_tsc(CPUX86State *env)
116 {
117     return cpu_get_real_ticks();
118 }
119 
120 static void write_dt(void *ptr, unsigned long addr, unsigned long limit,
121                      int flags)
122 {
123     unsigned int e1, e2;
124     uint32_t *p;
125     e1 = (addr << 16) | (limit & 0xffff);
126     e2 = ((addr >> 16) & 0xff) | (addr & 0xff000000) | (limit & 0x000f0000);
127     e2 |= flags;
128     p = ptr;
129     p[0] = tswap32(e1);
130     p[1] = tswap32(e2);
131 }
132 
133 static uint64_t *idt_table;
134 #ifdef TARGET_X86_64
135 static void set_gate64(void *ptr, unsigned int type, unsigned int dpl,
136                        uint64_t addr, unsigned int sel)
137 {
138     uint32_t *p, e1, e2;
139     e1 = (addr & 0xffff) | (sel << 16);
140     e2 = (addr & 0xffff0000) | 0x8000 | (dpl << 13) | (type << 8);
141     p = ptr;
142     p[0] = tswap32(e1);
143     p[1] = tswap32(e2);
144     p[2] = tswap32(addr >> 32);
145     p[3] = 0;
146 }
147 /* only dpl matters as we do only user space emulation */
148 static void set_idt(int n, unsigned int dpl)
149 {
150     set_gate64(idt_table + n * 2, 0, dpl, 0, 0);
151 }
152 #else
153 static void set_gate(void *ptr, unsigned int type, unsigned int dpl,
154                      uint32_t addr, unsigned int sel)
155 {
156     uint32_t *p, e1, e2;
157     e1 = (addr & 0xffff) | (sel << 16);
158     e2 = (addr & 0xffff0000) | 0x8000 | (dpl << 13) | (type << 8);
159     p = ptr;
160     p[0] = tswap32(e1);
161     p[1] = tswap32(e2);
162 }
163 
164 /* only dpl matters as we do only user space emulation */
165 static void set_idt(int n, unsigned int dpl)
166 {
167     set_gate(idt_table + n, 0, dpl, 0, 0);
168 }
169 #endif
170 
171 void cpu_loop(CPUX86State *env)
172 {
173     int trapnr;
174     abi_ulong pc;
175     //target_siginfo_t info;
176 
177     for(;;) {
178         trapnr = cpu_x86_exec(env);
179         switch(trapnr) {
180         case 0x80:
181             /* syscall from int $0x80 */
182             if (bsd_type == target_freebsd) {
183                 abi_ulong params = (abi_ulong) env->regs[R_ESP] +
184                     sizeof(int32_t);
185                 int32_t syscall_nr = env->regs[R_EAX];
186                 int32_t arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8;
187 
188                 if (syscall_nr == TARGET_FREEBSD_NR_syscall) {
189                     get_user_s32(syscall_nr, params);
190                     params += sizeof(int32_t);
191                 } else if (syscall_nr == TARGET_FREEBSD_NR___syscall) {
192                     get_user_s32(syscall_nr, params);
193                     params += sizeof(int64_t);
194                 }
195                 get_user_s32(arg1, params);
196                 params += sizeof(int32_t);
197                 get_user_s32(arg2, params);
198                 params += sizeof(int32_t);
199                 get_user_s32(arg3, params);
200                 params += sizeof(int32_t);
201                 get_user_s32(arg4, params);
202                 params += sizeof(int32_t);
203                 get_user_s32(arg5, params);
204                 params += sizeof(int32_t);
205                 get_user_s32(arg6, params);
206                 params += sizeof(int32_t);
207                 get_user_s32(arg7, params);
208                 params += sizeof(int32_t);
209                 get_user_s32(arg8, params);
210                 env->regs[R_EAX] = do_freebsd_syscall(env,
211                                                       syscall_nr,
212                                                       arg1,
213                                                       arg2,
214                                                       arg3,
215                                                       arg4,
216                                                       arg5,
217                                                       arg6,
218                                                       arg7,
219                                                       arg8);
220             } else { //if (bsd_type == target_openbsd)
221                 env->regs[R_EAX] = do_openbsd_syscall(env,
222                                                       env->regs[R_EAX],
223                                                       env->regs[R_EBX],
224                                                       env->regs[R_ECX],
225                                                       env->regs[R_EDX],
226                                                       env->regs[R_ESI],
227                                                       env->regs[R_EDI],
228                                                       env->regs[R_EBP]);
229             }
230             if (((abi_ulong)env->regs[R_EAX]) >= (abi_ulong)(-515)) {
231                 env->regs[R_EAX] = -env->regs[R_EAX];
232                 env->eflags |= CC_C;
233             } else {
234                 env->eflags &= ~CC_C;
235             }
236             break;
237 #ifndef TARGET_ABI32
238         case EXCP_SYSCALL:
239             /* syscall from syscall instruction */
240             if (bsd_type == target_freebsd)
241                 env->regs[R_EAX] = do_freebsd_syscall(env,
242                                                       env->regs[R_EAX],
243                                                       env->regs[R_EDI],
244                                                       env->regs[R_ESI],
245                                                       env->regs[R_EDX],
246                                                       env->regs[R_ECX],
247                                                       env->regs[8],
248                                                       env->regs[9], 0, 0);
249             else { //if (bsd_type == target_openbsd)
250                 env->regs[R_EAX] = do_openbsd_syscall(env,
251                                                       env->regs[R_EAX],
252                                                       env->regs[R_EDI],
253                                                       env->regs[R_ESI],
254                                                       env->regs[R_EDX],
255                                                       env->regs[10],
256                                                       env->regs[8],
257                                                       env->regs[9]);
258             }
259             env->eip = env->exception_next_eip;
260             if (((abi_ulong)env->regs[R_EAX]) >= (abi_ulong)(-515)) {
261                 env->regs[R_EAX] = -env->regs[R_EAX];
262                 env->eflags |= CC_C;
263             } else {
264                 env->eflags &= ~CC_C;
265             }
266             break;
267 #endif
268 #if 0
269         case EXCP0B_NOSEG:
270         case EXCP0C_STACK:
271             info.si_signo = SIGBUS;
272             info.si_errno = 0;
273             info.si_code = TARGET_SI_KERNEL;
274             info._sifields._sigfault._addr = 0;
275             queue_signal(env, info.si_signo, &info);
276             break;
277         case EXCP0D_GPF:
278             /* XXX: potential problem if ABI32 */
279 #ifndef TARGET_X86_64
280             if (env->eflags & VM_MASK) {
281                 handle_vm86_fault(env);
282             } else
283 #endif
284             {
285                 info.si_signo = SIGSEGV;
286                 info.si_errno = 0;
287                 info.si_code = TARGET_SI_KERNEL;
288                 info._sifields._sigfault._addr = 0;
289                 queue_signal(env, info.si_signo, &info);
290             }
291             break;
292         case EXCP0E_PAGE:
293             info.si_signo = SIGSEGV;
294             info.si_errno = 0;
295             if (!(env->error_code & 1))
296                 info.si_code = TARGET_SEGV_MAPERR;
297             else
298                 info.si_code = TARGET_SEGV_ACCERR;
299             info._sifields._sigfault._addr = env->cr[2];
300             queue_signal(env, info.si_signo, &info);
301             break;
302         case EXCP00_DIVZ:
303 #ifndef TARGET_X86_64
304             if (env->eflags & VM_MASK) {
305                 handle_vm86_trap(env, trapnr);
306             } else
307 #endif
308             {
309                 /* division by zero */
310                 info.si_signo = SIGFPE;
311                 info.si_errno = 0;
312                 info.si_code = TARGET_FPE_INTDIV;
313                 info._sifields._sigfault._addr = env->eip;
314                 queue_signal(env, info.si_signo, &info);
315             }
316             break;
317         case EXCP01_DB:
318         case EXCP03_INT3:
319 #ifndef TARGET_X86_64
320             if (env->eflags & VM_MASK) {
321                 handle_vm86_trap(env, trapnr);
322             } else
323 #endif
324             {
325                 info.si_signo = SIGTRAP;
326                 info.si_errno = 0;
327                 if (trapnr == EXCP01_DB) {
328                     info.si_code = TARGET_TRAP_BRKPT;
329                     info._sifields._sigfault._addr = env->eip;
330                 } else {
331                     info.si_code = TARGET_SI_KERNEL;
332                     info._sifields._sigfault._addr = 0;
333                 }
334                 queue_signal(env, info.si_signo, &info);
335             }
336             break;
337         case EXCP04_INTO:
338         case EXCP05_BOUND:
339 #ifndef TARGET_X86_64
340             if (env->eflags & VM_MASK) {
341                 handle_vm86_trap(env, trapnr);
342             } else
343 #endif
344             {
345                 info.si_signo = SIGSEGV;
346                 info.si_errno = 0;
347                 info.si_code = TARGET_SI_KERNEL;
348                 info._sifields._sigfault._addr = 0;
349                 queue_signal(env, info.si_signo, &info);
350             }
351             break;
352         case EXCP06_ILLOP:
353             info.si_signo = SIGILL;
354             info.si_errno = 0;
355             info.si_code = TARGET_ILL_ILLOPN;
356             info._sifields._sigfault._addr = env->eip;
357             queue_signal(env, info.si_signo, &info);
358             break;
359 #endif
360         case EXCP_INTERRUPT:
361             /* just indicate that signals should be handled asap */
362             break;
363 #if 0
364         case EXCP_DEBUG:
365             {
366                 int sig;
367 
368                 sig = gdb_handlesig (env, TARGET_SIGTRAP);
369                 if (sig)
370                   {
371                     info.si_signo = sig;
372                     info.si_errno = 0;
373                     info.si_code = TARGET_TRAP_BRKPT;
374                     queue_signal(env, info.si_signo, &info);
375                   }
376             }
377             break;
378 #endif
379         default:
380             pc = env->segs[R_CS].base + env->eip;
381             fprintf(stderr, "qemu: 0x%08lx: unhandled CPU exception 0x%x - aborting\n",
382                     (long)pc, trapnr);
383             abort();
384         }
385         process_pending_signals(env);
386     }
387 }
388 #endif
389 
390 #ifdef TARGET_SPARC
391 #define SPARC64_STACK_BIAS 2047
392 
393 //#define DEBUG_WIN
394 /* WARNING: dealing with register windows _is_ complicated. More info
395    can be found at http://www.sics.se/~psm/sparcstack.html */
396 static inline int get_reg_index(CPUSPARCState *env, int cwp, int index)
397 {
398     index = (index + cwp * 16) % (16 * env->nwindows);
399     /* wrap handling : if cwp is on the last window, then we use the
400        registers 'after' the end */
401     if (index < 8 && env->cwp == env->nwindows - 1)
402         index += 16 * env->nwindows;
403     return index;
404 }
405 
406 /* save the register window 'cwp1' */
407 static inline void save_window_offset(CPUSPARCState *env, int cwp1)
408 {
409     unsigned int i;
410     abi_ulong sp_ptr;
411 
412     sp_ptr = env->regbase[get_reg_index(env, cwp1, 6)];
413 #ifdef TARGET_SPARC64
414     if (sp_ptr & 3)
415         sp_ptr += SPARC64_STACK_BIAS;
416 #endif
417 #if defined(DEBUG_WIN)
418     printf("win_overflow: sp_ptr=0x" TARGET_ABI_FMT_lx " save_cwp=%d\n",
419            sp_ptr, cwp1);
420 #endif
421     for(i = 0; i < 16; i++) {
422         /* FIXME - what to do if put_user() fails? */
423         put_user_ual(env->regbase[get_reg_index(env, cwp1, 8 + i)], sp_ptr);
424         sp_ptr += sizeof(abi_ulong);
425     }
426 }
427 
428 static void save_window(CPUSPARCState *env)
429 {
430 #ifndef TARGET_SPARC64
431     unsigned int new_wim;
432     new_wim = ((env->wim >> 1) | (env->wim << (env->nwindows - 1))) &
433         ((1LL << env->nwindows) - 1);
434     save_window_offset(env, cpu_cwp_dec(env, env->cwp - 2));
435     env->wim = new_wim;
436 #else
437     save_window_offset(env, cpu_cwp_dec(env, env->cwp - 2));
438     env->cansave++;
439     env->canrestore--;
440 #endif
441 }
442 
443 static void restore_window(CPUSPARCState *env)
444 {
445 #ifndef TARGET_SPARC64
446     unsigned int new_wim;
447 #endif
448     unsigned int i, cwp1;
449     abi_ulong sp_ptr;
450 
451 #ifndef TARGET_SPARC64
452     new_wim = ((env->wim << 1) | (env->wim >> (env->nwindows - 1))) &
453         ((1LL << env->nwindows) - 1);
454 #endif
455 
456     /* restore the invalid window */
457     cwp1 = cpu_cwp_inc(env, env->cwp + 1);
458     sp_ptr = env->regbase[get_reg_index(env, cwp1, 6)];
459 #ifdef TARGET_SPARC64
460     if (sp_ptr & 3)
461         sp_ptr += SPARC64_STACK_BIAS;
462 #endif
463 #if defined(DEBUG_WIN)
464     printf("win_underflow: sp_ptr=0x" TARGET_ABI_FMT_lx " load_cwp=%d\n",
465            sp_ptr, cwp1);
466 #endif
467     for(i = 0; i < 16; i++) {
468         /* FIXME - what to do if get_user() fails? */
469         get_user_ual(env->regbase[get_reg_index(env, cwp1, 8 + i)], sp_ptr);
470         sp_ptr += sizeof(abi_ulong);
471     }
472 #ifdef TARGET_SPARC64
473     env->canrestore++;
474     if (env->cleanwin < env->nwindows - 1)
475         env->cleanwin++;
476     env->cansave--;
477 #else
478     env->wim = new_wim;
479 #endif
480 }
481 
482 static void flush_windows(CPUSPARCState *env)
483 {
484     int offset, cwp1;
485 
486     offset = 1;
487     for(;;) {
488         /* if restore would invoke restore_window(), then we can stop */
489         cwp1 = cpu_cwp_inc(env, env->cwp + offset);
490 #ifndef TARGET_SPARC64
491         if (env->wim & (1 << cwp1))
492             break;
493 #else
494         if (env->canrestore == 0)
495             break;
496         env->cansave++;
497         env->canrestore--;
498 #endif
499         save_window_offset(env, cwp1);
500         offset++;
501     }
502     cwp1 = cpu_cwp_inc(env, env->cwp + 1);
503 #ifndef TARGET_SPARC64
504     /* set wim so that restore will reload the registers */
505     env->wim = 1 << cwp1;
506 #endif
507 #if defined(DEBUG_WIN)
508     printf("flush_windows: nb=%d\n", offset - 1);
509 #endif
510 }
511 
512 void cpu_loop(CPUSPARCState *env)
513 {
514     CPUState *cs = CPU(sparc_env_get_cpu(env));
515     int trapnr, ret, syscall_nr;
516     //target_siginfo_t info;
517 
518     while (1) {
519         trapnr = cpu_sparc_exec (env);
520 
521         switch (trapnr) {
522 #ifndef TARGET_SPARC64
523         case 0x80:
524 #else
525         /* FreeBSD uses 0x141 for syscalls too */
526         case 0x141:
527             if (bsd_type != target_freebsd)
528                 goto badtrap;
529         case 0x100:
530 #endif
531             syscall_nr = env->gregs[1];
532             if (bsd_type == target_freebsd)
533                 ret = do_freebsd_syscall(env, syscall_nr,
534                                          env->regwptr[0], env->regwptr[1],
535                                          env->regwptr[2], env->regwptr[3],
536                                          env->regwptr[4], env->regwptr[5], 0, 0);
537             else if (bsd_type == target_netbsd)
538                 ret = do_netbsd_syscall(env, syscall_nr,
539                                         env->regwptr[0], env->regwptr[1],
540                                         env->regwptr[2], env->regwptr[3],
541                                         env->regwptr[4], env->regwptr[5]);
542             else { //if (bsd_type == target_openbsd)
543 #if defined(TARGET_SPARC64)
544                 syscall_nr &= ~(TARGET_OPENBSD_SYSCALL_G7RFLAG |
545                                 TARGET_OPENBSD_SYSCALL_G2RFLAG);
546 #endif
547                 ret = do_openbsd_syscall(env, syscall_nr,
548                                          env->regwptr[0], env->regwptr[1],
549                                          env->regwptr[2], env->regwptr[3],
550                                          env->regwptr[4], env->regwptr[5]);
551             }
552             if ((unsigned int)ret >= (unsigned int)(-515)) {
553                 ret = -ret;
554 #if defined(TARGET_SPARC64) && !defined(TARGET_ABI32)
555                 env->xcc |= PSR_CARRY;
556 #else
557                 env->psr |= PSR_CARRY;
558 #endif
559             } else {
560 #if defined(TARGET_SPARC64) && !defined(TARGET_ABI32)
561                 env->xcc &= ~PSR_CARRY;
562 #else
563                 env->psr &= ~PSR_CARRY;
564 #endif
565             }
566             env->regwptr[0] = ret;
567             /* next instruction */
568 #if defined(TARGET_SPARC64)
569             if (bsd_type == target_openbsd &&
570                 env->gregs[1] & TARGET_OPENBSD_SYSCALL_G2RFLAG) {
571                 env->pc = env->gregs[2];
572                 env->npc = env->pc + 4;
573             } else if (bsd_type == target_openbsd &&
574                        env->gregs[1] & TARGET_OPENBSD_SYSCALL_G7RFLAG) {
575                 env->pc = env->gregs[7];
576                 env->npc = env->pc + 4;
577             } else {
578                 env->pc = env->npc;
579                 env->npc = env->npc + 4;
580             }
581 #else
582             env->pc = env->npc;
583             env->npc = env->npc + 4;
584 #endif
585             break;
586         case 0x83: /* flush windows */
587 #ifdef TARGET_ABI32
588         case 0x103:
589 #endif
590             flush_windows(env);
591             /* next instruction */
592             env->pc = env->npc;
593             env->npc = env->npc + 4;
594             break;
595 #ifndef TARGET_SPARC64
596         case TT_WIN_OVF: /* window overflow */
597             save_window(env);
598             break;
599         case TT_WIN_UNF: /* window underflow */
600             restore_window(env);
601             break;
602         case TT_TFAULT:
603         case TT_DFAULT:
604 #if 0
605             {
606                 info.si_signo = SIGSEGV;
607                 info.si_errno = 0;
608                 /* XXX: check env->error_code */
609                 info.si_code = TARGET_SEGV_MAPERR;
610                 info._sifields._sigfault._addr = env->mmuregs[4];
611                 queue_signal(env, info.si_signo, &info);
612             }
613 #endif
614             break;
615 #else
616         case TT_SPILL: /* window overflow */
617             save_window(env);
618             break;
619         case TT_FILL: /* window underflow */
620             restore_window(env);
621             break;
622         case TT_TFAULT:
623         case TT_DFAULT:
624 #if 0
625             {
626                 info.si_signo = SIGSEGV;
627                 info.si_errno = 0;
628                 /* XXX: check env->error_code */
629                 info.si_code = TARGET_SEGV_MAPERR;
630                 if (trapnr == TT_DFAULT)
631                     info._sifields._sigfault._addr = env->dmmuregs[4];
632                 else
633                     info._sifields._sigfault._addr = env->tsptr->tpc;
634                 //queue_signal(env, info.si_signo, &info);
635             }
636 #endif
637             break;
638 #endif
639         case EXCP_INTERRUPT:
640             /* just indicate that signals should be handled asap */
641             break;
642         case EXCP_DEBUG:
643             {
644                 int sig;
645 
646                 sig = gdb_handlesig(cs, TARGET_SIGTRAP);
647 #if 0
648                 if (sig)
649                   {
650                     info.si_signo = sig;
651                     info.si_errno = 0;
652                     info.si_code = TARGET_TRAP_BRKPT;
653                     //queue_signal(env, info.si_signo, &info);
654                   }
655 #endif
656             }
657             break;
658         default:
659 #ifdef TARGET_SPARC64
660         badtrap:
661 #endif
662             printf ("Unhandled trap: 0x%x\n", trapnr);
663             cpu_dump_state(cs, stderr, fprintf, 0);
664             exit (1);
665         }
666         process_pending_signals (env);
667     }
668 }
669 
670 #endif
671 
672 static void usage(void)
673 {
674     printf("qemu-" TARGET_NAME " version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
675            "usage: qemu-" TARGET_NAME " [options] program [arguments...]\n"
676            "BSD CPU emulator (compiled for %s emulation)\n"
677            "\n"
678            "Standard options:\n"
679            "-h                print this help\n"
680            "-g port           wait gdb connection to port\n"
681            "-L path           set the elf interpreter prefix (default=%s)\n"
682            "-s size           set the stack size in bytes (default=%ld)\n"
683            "-cpu model        select CPU (-cpu help for list)\n"
684            "-drop-ld-preload  drop LD_PRELOAD for target process\n"
685            "-E var=value      sets/modifies targets environment variable(s)\n"
686            "-U var            unsets targets environment variable(s)\n"
687 #if defined(CONFIG_USE_GUEST_BASE)
688            "-B address        set guest_base address to address\n"
689 #endif
690            "-bsd type         select emulated BSD type FreeBSD/NetBSD/OpenBSD (default)\n"
691            "\n"
692            "Debug options:\n"
693            "-d item1[,...]    enable logging of specified items\n"
694            "                  (use '-d help' for a list of log items)\n"
695            "-D logfile        write logs to 'logfile' (default stderr)\n"
696            "-p pagesize       set the host page size to 'pagesize'\n"
697            "-singlestep       always run in singlestep mode\n"
698            "-strace           log system calls\n"
699            "\n"
700            "Environment variables:\n"
701            "QEMU_STRACE       Print system calls and arguments similar to the\n"
702            "                  'strace' program.  Enable by setting to any value.\n"
703            "You can use -E and -U options to set/unset environment variables\n"
704            "for target process.  It is possible to provide several variables\n"
705            "by repeating the option.  For example:\n"
706            "    -E var1=val2 -E var2=val2 -U LD_PRELOAD -U LD_DEBUG\n"
707            "Note that if you provide several changes to single variable\n"
708            "last change will stay in effect.\n"
709            ,
710            TARGET_NAME,
711            interp_prefix,
712            x86_stack_size);
713     exit(1);
714 }
715 
716 THREAD CPUState *thread_cpu;
717 
718 /* Assumes contents are already zeroed.  */
719 void init_task_state(TaskState *ts)
720 {
721     int i;
722 
723     ts->used = 1;
724     ts->first_free = ts->sigqueue_table;
725     for (i = 0; i < MAX_SIGQUEUE_SIZE - 1; i++) {
726         ts->sigqueue_table[i].next = &ts->sigqueue_table[i + 1];
727     }
728     ts->sigqueue_table[i].next = NULL;
729 }
730 
731 int main(int argc, char **argv)
732 {
733     const char *filename;
734     const char *cpu_model;
735     const char *log_file = NULL;
736     const char *log_mask = NULL;
737     struct target_pt_regs regs1, *regs = &regs1;
738     struct image_info info1, *info = &info1;
739     TaskState ts1, *ts = &ts1;
740     CPUArchState *env;
741     CPUState *cpu;
742     int optind;
743     const char *r;
744     int gdbstub_port = 0;
745     char **target_environ, **wrk;
746     envlist_t *envlist = NULL;
747     bsd_type = target_openbsd;
748 
749     if (argc <= 1)
750         usage();
751 
752     module_call_init(MODULE_INIT_QOM);
753 
754     if ((envlist = envlist_create()) == NULL) {
755         (void) fprintf(stderr, "Unable to allocate envlist\n");
756         exit(1);
757     }
758 
759     /* add current environment into the list */
760     for (wrk = environ; *wrk != NULL; wrk++) {
761         (void) envlist_setenv(envlist, *wrk);
762     }
763 
764     cpu_model = NULL;
765 #if defined(cpudef_setup)
766     cpudef_setup(); /* parse cpu definitions in target config file (TBD) */
767 #endif
768 
769     optind = 1;
770     for(;;) {
771         if (optind >= argc)
772             break;
773         r = argv[optind];
774         if (r[0] != '-')
775             break;
776         optind++;
777         r++;
778         if (!strcmp(r, "-")) {
779             break;
780         } else if (!strcmp(r, "d")) {
781             if (optind >= argc) {
782                 break;
783             }
784             log_mask = argv[optind++];
785         } else if (!strcmp(r, "D")) {
786             if (optind >= argc) {
787                 break;
788             }
789             log_file = argv[optind++];
790         } else if (!strcmp(r, "E")) {
791             r = argv[optind++];
792             if (envlist_setenv(envlist, r) != 0)
793                 usage();
794         } else if (!strcmp(r, "ignore-environment")) {
795             envlist_free(envlist);
796             if ((envlist = envlist_create()) == NULL) {
797                 (void) fprintf(stderr, "Unable to allocate envlist\n");
798                 exit(1);
799             }
800         } else if (!strcmp(r, "U")) {
801             r = argv[optind++];
802             if (envlist_unsetenv(envlist, r) != 0)
803                 usage();
804         } else if (!strcmp(r, "s")) {
805             r = argv[optind++];
806             x86_stack_size = strtol(r, (char **)&r, 0);
807             if (x86_stack_size <= 0)
808                 usage();
809             if (*r == 'M')
810                 x86_stack_size *= 1024 * 1024;
811             else if (*r == 'k' || *r == 'K')
812                 x86_stack_size *= 1024;
813         } else if (!strcmp(r, "L")) {
814             interp_prefix = argv[optind++];
815         } else if (!strcmp(r, "p")) {
816             qemu_host_page_size = atoi(argv[optind++]);
817             if (qemu_host_page_size == 0 ||
818                 (qemu_host_page_size & (qemu_host_page_size - 1)) != 0) {
819                 fprintf(stderr, "page size must be a power of two\n");
820                 exit(1);
821             }
822         } else if (!strcmp(r, "g")) {
823             gdbstub_port = atoi(argv[optind++]);
824         } else if (!strcmp(r, "r")) {
825             qemu_uname_release = argv[optind++];
826         } else if (!strcmp(r, "cpu")) {
827             cpu_model = argv[optind++];
828             if (is_help_option(cpu_model)) {
829 /* XXX: implement xxx_cpu_list for targets that still miss it */
830 #if defined(cpu_list)
831                     cpu_list(stdout, &fprintf);
832 #endif
833                 exit(1);
834             }
835 #if defined(CONFIG_USE_GUEST_BASE)
836         } else if (!strcmp(r, "B")) {
837            guest_base = strtol(argv[optind++], NULL, 0);
838            have_guest_base = 1;
839 #endif
840         } else if (!strcmp(r, "drop-ld-preload")) {
841             (void) envlist_unsetenv(envlist, "LD_PRELOAD");
842         } else if (!strcmp(r, "bsd")) {
843             if (!strcasecmp(argv[optind], "freebsd")) {
844                 bsd_type = target_freebsd;
845             } else if (!strcasecmp(argv[optind], "netbsd")) {
846                 bsd_type = target_netbsd;
847             } else if (!strcasecmp(argv[optind], "openbsd")) {
848                 bsd_type = target_openbsd;
849             } else {
850                 usage();
851             }
852             optind++;
853         } else if (!strcmp(r, "singlestep")) {
854             singlestep = 1;
855         } else if (!strcmp(r, "strace")) {
856             do_strace = 1;
857         } else
858         {
859             usage();
860         }
861     }
862 
863     /* init debug */
864     qemu_set_log_filename(log_file);
865     if (log_mask) {
866         int mask;
867 
868         mask = qemu_str_to_log_mask(log_mask);
869         if (!mask) {
870             qemu_print_log_usage(stdout);
871             exit(1);
872         }
873         qemu_set_log(mask);
874     }
875 
876     if (optind >= argc) {
877         usage();
878     }
879     filename = argv[optind];
880 
881     /* Zero out regs */
882     memset(regs, 0, sizeof(struct target_pt_regs));
883 
884     /* Zero out image_info */
885     memset(info, 0, sizeof(struct image_info));
886 
887     /* Scan interp_prefix dir for replacement files. */
888     init_paths(interp_prefix);
889 
890     if (cpu_model == NULL) {
891 #if defined(TARGET_I386)
892 #ifdef TARGET_X86_64
893         cpu_model = "qemu64";
894 #else
895         cpu_model = "qemu32";
896 #endif
897 #elif defined(TARGET_SPARC)
898 #ifdef TARGET_SPARC64
899         cpu_model = "TI UltraSparc II";
900 #else
901         cpu_model = "Fujitsu MB86904";
902 #endif
903 #else
904         cpu_model = "any";
905 #endif
906     }
907     tcg_exec_init(0);
908     cpu_exec_init_all();
909     /* NOTE: we need to init the CPU at this stage to get
910        qemu_host_page_size */
911     env = cpu_init(cpu_model);
912     if (!env) {
913         fprintf(stderr, "Unable to find CPU definition\n");
914         exit(1);
915     }
916     cpu = ENV_GET_CPU(env);
917 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
918     cpu_reset(cpu);
919 #endif
920     thread_cpu = cpu;
921 
922     if (getenv("QEMU_STRACE")) {
923         do_strace = 1;
924     }
925 
926     target_environ = envlist_to_environ(envlist, NULL);
927     envlist_free(envlist);
928 
929 #if defined(CONFIG_USE_GUEST_BASE)
930     /*
931      * Now that page sizes are configured in cpu_init() we can do
932      * proper page alignment for guest_base.
933      */
934     guest_base = HOST_PAGE_ALIGN(guest_base);
935 
936     /*
937      * Read in mmap_min_addr kernel parameter.  This value is used
938      * When loading the ELF image to determine whether guest_base
939      * is needed.
940      *
941      * When user has explicitly set the quest base, we skip this
942      * test.
943      */
944     if (!have_guest_base) {
945         FILE *fp;
946 
947         if ((fp = fopen("/proc/sys/vm/mmap_min_addr", "r")) != NULL) {
948             unsigned long tmp;
949             if (fscanf(fp, "%lu", &tmp) == 1) {
950                 mmap_min_addr = tmp;
951                 qemu_log("host mmap_min_addr=0x%lx\n", mmap_min_addr);
952             }
953             fclose(fp);
954         }
955     }
956 #endif /* CONFIG_USE_GUEST_BASE */
957 
958     if (loader_exec(filename, argv+optind, target_environ, regs, info) != 0) {
959         printf("Error loading %s\n", filename);
960         _exit(1);
961     }
962 
963     for (wrk = target_environ; *wrk; wrk++) {
964         free(*wrk);
965     }
966 
967     free(target_environ);
968 
969     if (qemu_log_enabled()) {
970 #if defined(CONFIG_USE_GUEST_BASE)
971         qemu_log("guest_base  0x%lx\n", guest_base);
972 #endif
973         log_page_dump();
974 
975         qemu_log("start_brk   0x" TARGET_ABI_FMT_lx "\n", info->start_brk);
976         qemu_log("end_code    0x" TARGET_ABI_FMT_lx "\n", info->end_code);
977         qemu_log("start_code  0x" TARGET_ABI_FMT_lx "\n",
978                  info->start_code);
979         qemu_log("start_data  0x" TARGET_ABI_FMT_lx "\n",
980                  info->start_data);
981         qemu_log("end_data    0x" TARGET_ABI_FMT_lx "\n", info->end_data);
982         qemu_log("start_stack 0x" TARGET_ABI_FMT_lx "\n",
983                  info->start_stack);
984         qemu_log("brk         0x" TARGET_ABI_FMT_lx "\n", info->brk);
985         qemu_log("entry       0x" TARGET_ABI_FMT_lx "\n", info->entry);
986     }
987 
988     target_set_brk(info->brk);
989     syscall_init();
990     signal_init();
991 
992 #if defined(CONFIG_USE_GUEST_BASE)
993     /* Now that we've loaded the binary, GUEST_BASE is fixed.  Delay
994        generating the prologue until now so that the prologue can take
995        the real value of GUEST_BASE into account.  */
996     tcg_prologue_init(&tcg_ctx);
997 #endif
998 
999     /* build Task State */
1000     memset(ts, 0, sizeof(TaskState));
1001     init_task_state(ts);
1002     ts->info = info;
1003     env->opaque = ts;
1004 
1005 #if defined(TARGET_I386)
1006     cpu_x86_set_cpl(env, 3);
1007 
1008     env->cr[0] = CR0_PG_MASK | CR0_WP_MASK | CR0_PE_MASK;
1009     env->hflags |= HF_PE_MASK;
1010     if (env->features[FEAT_1_EDX] & CPUID_SSE) {
1011         env->cr[4] |= CR4_OSFXSR_MASK;
1012         env->hflags |= HF_OSFXSR_MASK;
1013     }
1014 #ifndef TARGET_ABI32
1015     /* enable 64 bit mode if possible */
1016     if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_LM)) {
1017         fprintf(stderr, "The selected x86 CPU does not support 64 bit mode\n");
1018         exit(1);
1019     }
1020     env->cr[4] |= CR4_PAE_MASK;
1021     env->efer |= MSR_EFER_LMA | MSR_EFER_LME;
1022     env->hflags |= HF_LMA_MASK;
1023 #endif
1024 
1025     /* flags setup : we activate the IRQs by default as in user mode */
1026     env->eflags |= IF_MASK;
1027 
1028     /* linux register setup */
1029 #ifndef TARGET_ABI32
1030     env->regs[R_EAX] = regs->rax;
1031     env->regs[R_EBX] = regs->rbx;
1032     env->regs[R_ECX] = regs->rcx;
1033     env->regs[R_EDX] = regs->rdx;
1034     env->regs[R_ESI] = regs->rsi;
1035     env->regs[R_EDI] = regs->rdi;
1036     env->regs[R_EBP] = regs->rbp;
1037     env->regs[R_ESP] = regs->rsp;
1038     env->eip = regs->rip;
1039 #else
1040     env->regs[R_EAX] = regs->eax;
1041     env->regs[R_EBX] = regs->ebx;
1042     env->regs[R_ECX] = regs->ecx;
1043     env->regs[R_EDX] = regs->edx;
1044     env->regs[R_ESI] = regs->esi;
1045     env->regs[R_EDI] = regs->edi;
1046     env->regs[R_EBP] = regs->ebp;
1047     env->regs[R_ESP] = regs->esp;
1048     env->eip = regs->eip;
1049 #endif
1050 
1051     /* linux interrupt setup */
1052 #ifndef TARGET_ABI32
1053     env->idt.limit = 511;
1054 #else
1055     env->idt.limit = 255;
1056 #endif
1057     env->idt.base = target_mmap(0, sizeof(uint64_t) * (env->idt.limit + 1),
1058                                 PROT_READ|PROT_WRITE,
1059                                 MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
1060     idt_table = g2h(env->idt.base);
1061     set_idt(0, 0);
1062     set_idt(1, 0);
1063     set_idt(2, 0);
1064     set_idt(3, 3);
1065     set_idt(4, 3);
1066     set_idt(5, 0);
1067     set_idt(6, 0);
1068     set_idt(7, 0);
1069     set_idt(8, 0);
1070     set_idt(9, 0);
1071     set_idt(10, 0);
1072     set_idt(11, 0);
1073     set_idt(12, 0);
1074     set_idt(13, 0);
1075     set_idt(14, 0);
1076     set_idt(15, 0);
1077     set_idt(16, 0);
1078     set_idt(17, 0);
1079     set_idt(18, 0);
1080     set_idt(19, 0);
1081     set_idt(0x80, 3);
1082 
1083     /* linux segment setup */
1084     {
1085         uint64_t *gdt_table;
1086         env->gdt.base = target_mmap(0, sizeof(uint64_t) * TARGET_GDT_ENTRIES,
1087                                     PROT_READ|PROT_WRITE,
1088                                     MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
1089         env->gdt.limit = sizeof(uint64_t) * TARGET_GDT_ENTRIES - 1;
1090         gdt_table = g2h(env->gdt.base);
1091 #ifdef TARGET_ABI32
1092         write_dt(&gdt_table[__USER_CS >> 3], 0, 0xfffff,
1093                  DESC_G_MASK | DESC_B_MASK | DESC_P_MASK | DESC_S_MASK |
1094                  (3 << DESC_DPL_SHIFT) | (0xa << DESC_TYPE_SHIFT));
1095 #else
1096         /* 64 bit code segment */
1097         write_dt(&gdt_table[__USER_CS >> 3], 0, 0xfffff,
1098                  DESC_G_MASK | DESC_B_MASK | DESC_P_MASK | DESC_S_MASK |
1099                  DESC_L_MASK |
1100                  (3 << DESC_DPL_SHIFT) | (0xa << DESC_TYPE_SHIFT));
1101 #endif
1102         write_dt(&gdt_table[__USER_DS >> 3], 0, 0xfffff,
1103                  DESC_G_MASK | DESC_B_MASK | DESC_P_MASK | DESC_S_MASK |
1104                  (3 << DESC_DPL_SHIFT) | (0x2 << DESC_TYPE_SHIFT));
1105     }
1106 
1107     cpu_x86_load_seg(env, R_CS, __USER_CS);
1108     cpu_x86_load_seg(env, R_SS, __USER_DS);
1109 #ifdef TARGET_ABI32
1110     cpu_x86_load_seg(env, R_DS, __USER_DS);
1111     cpu_x86_load_seg(env, R_ES, __USER_DS);
1112     cpu_x86_load_seg(env, R_FS, __USER_DS);
1113     cpu_x86_load_seg(env, R_GS, __USER_DS);
1114     /* This hack makes Wine work... */
1115     env->segs[R_FS].selector = 0;
1116 #else
1117     cpu_x86_load_seg(env, R_DS, 0);
1118     cpu_x86_load_seg(env, R_ES, 0);
1119     cpu_x86_load_seg(env, R_FS, 0);
1120     cpu_x86_load_seg(env, R_GS, 0);
1121 #endif
1122 #elif defined(TARGET_SPARC)
1123     {
1124         int i;
1125         env->pc = regs->pc;
1126         env->npc = regs->npc;
1127         env->y = regs->y;
1128         for(i = 0; i < 8; i++)
1129             env->gregs[i] = regs->u_regs[i];
1130         for(i = 0; i < 8; i++)
1131             env->regwptr[i] = regs->u_regs[i + 8];
1132     }
1133 #else
1134 #error unsupported target CPU
1135 #endif
1136 
1137     if (gdbstub_port) {
1138         gdbserver_start (gdbstub_port);
1139         gdb_handlesig(cpu, 0);
1140     }
1141     cpu_loop(env);
1142     /* never exits */
1143     return 0;
1144 }
1145