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