xref: /openbmc/qemu/bsd-user/main.c (revision e6e102b9)
1 /*
2  *  qemu bsd user main
3  *
4  *  Copyright (c) 2003-2008 Fabrice Bellard
5  *  Copyright (c) 2013-14 Stacey Son
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
19  */
20 
21 #include "qemu/osdep.h"
22 #include <sys/resource.h>
23 #include <sys/sysctl.h>
24 
25 #include "qemu/help-texts.h"
26 #include "qemu/units.h"
27 #include "qemu/accel.h"
28 #include "qemu-version.h"
29 #include <machine/trap.h>
30 
31 #include "qapi/error.h"
32 #include "qemu.h"
33 #include "qemu/config-file.h"
34 #include "qemu/error-report.h"
35 #include "qemu/path.h"
36 #include "qemu/help_option.h"
37 #include "qemu/module.h"
38 #include "exec/exec-all.h"
39 #include "user/guest-base.h"
40 #include "tcg/startup.h"
41 #include "qemu/timer.h"
42 #include "qemu/envlist.h"
43 #include "qemu/cutils.h"
44 #include "exec/log.h"
45 #include "trace/control.h"
46 #include "crypto/init.h"
47 #include "qemu/guest-random.h"
48 #include "gdbstub/user.h"
49 #include "exec/page-vary.h"
50 
51 #include "host-os.h"
52 #include "target_arch_cpu.h"
53 
54 
55 /*
56  * TODO: Remove these and rely only on qemu_real_host_page_size().
57  */
58 uintptr_t qemu_host_page_size;
59 intptr_t qemu_host_page_mask;
60 
61 static bool opt_one_insn_per_tb;
62 uintptr_t guest_base;
63 bool have_guest_base;
64 /*
65  * When running 32-on-64 we should make sure we can fit all of the possible
66  * guest address space into a contiguous chunk of virtual host memory.
67  *
68  * This way we will never overlap with our own libraries or binaries or stack
69  * or anything else that QEMU maps.
70  *
71  * Many cpus reserve the high bit (or more than one for some 64-bit cpus)
72  * of the address for the kernel.  Some cpus rely on this and user space
73  * uses the high bit(s) for pointer tagging and the like.  For them, we
74  * must preserve the expected address space.
75  */
76 #ifndef MAX_RESERVED_VA
77 # if HOST_LONG_BITS > TARGET_VIRT_ADDR_SPACE_BITS
78 #  if TARGET_VIRT_ADDR_SPACE_BITS == 32 && \
79       (TARGET_LONG_BITS == 32 || defined(TARGET_ABI32))
80 #   define MAX_RESERVED_VA(CPU)  0xfffffffful
81 #  else
82 #   define MAX_RESERVED_VA(CPU)  ((1ul << TARGET_VIRT_ADDR_SPACE_BITS) - 1)
83 #  endif
84 # else
85 #  define MAX_RESERVED_VA(CPU)  0
86 # endif
87 #endif
88 
89 unsigned long reserved_va;
90 
91 const char *interp_prefix = CONFIG_QEMU_INTERP_PREFIX;
92 const char *qemu_uname_release;
93 
94 unsigned long target_maxtsiz = TARGET_MAXTSIZ;   /* max text size */
95 unsigned long target_dfldsiz = TARGET_DFLDSIZ;   /* initial data size limit */
96 unsigned long target_maxdsiz = TARGET_MAXDSIZ;   /* max data size */
97 unsigned long target_dflssiz = TARGET_DFLSSIZ;   /* initial data size limit */
98 unsigned long target_maxssiz = TARGET_MAXSSIZ;   /* max stack size */
99 unsigned long target_sgrowsiz = TARGET_SGROWSIZ; /* amount to grow stack */
100 
101 /* Helper routines for implementing atomic operations. */
102 
103 void fork_start(void)
104 {
105     start_exclusive();
106     cpu_list_lock();
107     mmap_fork_start();
108     gdbserver_fork_start();
109 }
110 
111 void fork_end(pid_t pid)
112 {
113     bool child = pid == 0;
114 
115     if (child) {
116         CPUState *cpu, *next_cpu;
117         /*
118          * Child processes created by fork() only have a single thread.  Discard
119          * information about the parent threads.
120          */
121         CPU_FOREACH_SAFE(cpu, next_cpu) {
122             if (cpu != thread_cpu) {
123                 QTAILQ_REMOVE_RCU(&cpus_queue, cpu, node);
124             }
125         }
126         mmap_fork_end(child);
127         /*
128          * qemu_init_cpu_list() takes care of reinitializing the exclusive
129          * state, so we don't need to end_exclusive() here.
130          */
131         qemu_init_cpu_list();
132         get_task_state(thread_cpu)->ts_tid = qemu_get_thread_id();
133         gdbserver_fork_end(thread_cpu, pid);
134     } else {
135         mmap_fork_end(child);
136         cpu_list_unlock();
137         gdbserver_fork_end(thread_cpu, pid);
138         end_exclusive();
139     }
140 }
141 
142 void cpu_loop(CPUArchState *env)
143 {
144     target_cpu_loop(env);
145 }
146 
147 static void usage(void)
148 {
149     printf("qemu-" TARGET_NAME " version " QEMU_FULL_VERSION
150            "\n" QEMU_COPYRIGHT "\n"
151            "usage: qemu-" TARGET_NAME " [options] program [arguments...]\n"
152            "BSD CPU emulator (compiled for %s emulation)\n"
153            "\n"
154            "Standard options:\n"
155            "-h                print this help\n"
156            "-g port           wait gdb connection to port\n"
157            "-L path           set the elf interpreter prefix (default=%s)\n"
158            "-s size           set the stack size in bytes (default=%ld)\n"
159            "-cpu model        select CPU (-cpu help for list)\n"
160            "-drop-ld-preload  drop LD_PRELOAD for target process\n"
161            "-E var=value      sets/modifies targets environment variable(s)\n"
162            "-U var            unsets targets environment variable(s)\n"
163            "-B address        set guest_base address to address\n"
164            "\n"
165            "Debug options:\n"
166            "-d item1[,...]    enable logging of specified items\n"
167            "                  (use '-d help' for a list of log items)\n"
168            "-D logfile        write logs to 'logfile' (default stderr)\n"
169            "-one-insn-per-tb  run with one guest instruction per emulated TB\n"
170            "-strace           log system calls\n"
171            "-trace            [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
172            "                  specify tracing options\n"
173            "\n"
174            "Environment variables:\n"
175            "QEMU_STRACE       Print system calls and arguments similar to the\n"
176            "                  'strace' program.  Enable by setting to any value.\n"
177            "You can use -E and -U options to set/unset environment variables\n"
178            "for target process.  It is possible to provide several variables\n"
179            "by repeating the option.  For example:\n"
180            "    -E var1=val2 -E var2=val2 -U LD_PRELOAD -U LD_DEBUG\n"
181            "Note that if you provide several changes to single variable\n"
182            "last change will stay in effect.\n"
183            "\n"
184            QEMU_HELP_BOTTOM "\n"
185            ,
186            TARGET_NAME,
187            interp_prefix,
188            target_dflssiz);
189     exit(1);
190 }
191 
192 __thread CPUState *thread_cpu;
193 
194 void stop_all_tasks(void)
195 {
196     /*
197      * We trust when using NPTL (pthreads) start_exclusive() handles thread
198      * stopping correctly.
199      */
200     start_exclusive();
201 }
202 
203 bool qemu_cpu_is_self(CPUState *cpu)
204 {
205     return thread_cpu == cpu;
206 }
207 
208 void qemu_cpu_kick(CPUState *cpu)
209 {
210     cpu_exit(cpu);
211 }
212 
213 /* Assumes contents are already zeroed.  */
214 static void init_task_state(TaskState *ts)
215 {
216     ts->sigaltstack_used = (struct target_sigaltstack) {
217         .ss_sp = 0,
218         .ss_size = 0,
219         .ss_flags = TARGET_SS_DISABLE,
220     };
221 }
222 
223 void gemu_log(const char *fmt, ...)
224 {
225     va_list ap;
226 
227     va_start(ap, fmt);
228     vfprintf(stderr, fmt, ap);
229     va_end(ap);
230 }
231 
232 static void
233 adjust_ssize(void)
234 {
235     struct rlimit rl;
236 
237     if (getrlimit(RLIMIT_STACK, &rl) != 0) {
238         return;
239     }
240 
241     target_maxssiz = MIN(target_maxssiz, rl.rlim_max);
242     target_dflssiz = MIN(MAX(target_dflssiz, rl.rlim_cur), target_maxssiz);
243 
244     rl.rlim_max = target_maxssiz;
245     rl.rlim_cur = target_dflssiz;
246     setrlimit(RLIMIT_STACK, &rl);
247 }
248 
249 int main(int argc, char **argv)
250 {
251     const char *filename;
252     const char *cpu_model;
253     const char *cpu_type;
254     const char *log_file = NULL;
255     const char *log_mask = NULL;
256     const char *seed_optarg = NULL;
257     struct target_pt_regs regs1, *regs = &regs1;
258     struct image_info info1, *info = &info1;
259     struct bsd_binprm bprm;
260     TaskState *ts;
261     CPUArchState *env;
262     CPUState *cpu;
263     int optind, rv;
264     const char *r;
265     const char *gdbstub = NULL;
266     char **target_environ, **wrk;
267     envlist_t *envlist = NULL;
268     char *argv0 = NULL;
269     int host_page_size;
270     unsigned long max_reserved_va;
271 
272     adjust_ssize();
273 
274     if (argc <= 1) {
275         usage();
276     }
277 
278 
279     error_init(argv[0]);
280     module_call_init(MODULE_INIT_TRACE);
281     qemu_init_cpu_list();
282     module_call_init(MODULE_INIT_QOM);
283 
284     envlist = envlist_create();
285 
286     /*
287      * add current environment into the list
288      * envlist_setenv adds to the front of the list; to preserve environ
289      * order add from back to front
290      */
291     for (wrk = environ; *wrk != NULL; wrk++) {
292         continue;
293     }
294     while (wrk != environ) {
295         wrk--;
296         (void) envlist_setenv(envlist, *wrk);
297     }
298 
299     qemu_host_page_size = getpagesize();
300     qemu_host_page_size = MAX(qemu_host_page_size, TARGET_PAGE_SIZE);
301 
302     cpu_model = NULL;
303 
304     qemu_add_opts(&qemu_trace_opts);
305 
306     optind = 1;
307     for (;;) {
308         if (optind >= argc) {
309             break;
310         }
311         r = argv[optind];
312         if (r[0] != '-') {
313             break;
314         }
315         optind++;
316         r++;
317         if (!strcmp(r, "-")) {
318             break;
319         } else if (!strcmp(r, "d")) {
320             if (optind >= argc) {
321                 break;
322             }
323             log_mask = argv[optind++];
324         } else if (!strcmp(r, "D")) {
325             if (optind >= argc) {
326                 break;
327             }
328             log_file = argv[optind++];
329         } else if (!strcmp(r, "E")) {
330             r = argv[optind++];
331             if (envlist_setenv(envlist, r) != 0) {
332                 usage();
333             }
334         } else if (!strcmp(r, "ignore-environment")) {
335             envlist_free(envlist);
336             envlist = envlist_create();
337         } else if (!strcmp(r, "U")) {
338             r = argv[optind++];
339             if (envlist_unsetenv(envlist, r) != 0) {
340                 usage();
341             }
342         } else if (!strcmp(r, "s")) {
343             r = argv[optind++];
344             rv = qemu_strtoul(r, &r, 0, &target_dflssiz);
345             if (rv < 0 || target_dflssiz <= 0) {
346                 usage();
347             }
348             if (*r == 'M') {
349                 target_dflssiz *= 1024 * 1024;
350             } else if (*r == 'k' || *r == 'K') {
351                 target_dflssiz *= 1024;
352             }
353             if (target_dflssiz > target_maxssiz) {
354                 usage();
355             }
356         } else if (!strcmp(r, "L")) {
357             interp_prefix = argv[optind++];
358         } else if (!strcmp(r, "p")) {
359             unsigned size, want = qemu_real_host_page_size();
360 
361             r = argv[optind++];
362             if (qemu_strtoui(r, NULL, 10, &size) || size != want) {
363                 warn_report("Deprecated page size option cannot "
364                             "change host page size (%u)", want);
365             }
366         } else if (!strcmp(r, "g")) {
367             gdbstub = g_strdup(argv[optind++]);
368         } else if (!strcmp(r, "r")) {
369             qemu_uname_release = argv[optind++];
370         } else if (!strcmp(r, "cpu")) {
371             cpu_model = argv[optind++];
372             if (is_help_option(cpu_model)) {
373                 list_cpus();
374                 exit(1);
375             }
376         } else if (!strcmp(r, "B")) {
377             rv = qemu_strtoul(argv[optind++], NULL, 0, &guest_base);
378             if (rv < 0) {
379                 usage();
380             }
381             have_guest_base = true;
382         } else if (!strcmp(r, "drop-ld-preload")) {
383             (void) envlist_unsetenv(envlist, "LD_PRELOAD");
384         } else if (!strcmp(r, "seed")) {
385             seed_optarg = optarg;
386         } else if (!strcmp(r, "one-insn-per-tb")) {
387             opt_one_insn_per_tb = true;
388         } else if (!strcmp(r, "strace")) {
389             do_strace = 1;
390         } else if (!strcmp(r, "trace")) {
391             trace_opt_parse(optarg);
392         } else if (!strcmp(r, "0")) {
393             argv0 = argv[optind++];
394         } else {
395             usage();
396         }
397     }
398 
399     qemu_host_page_mask = -qemu_host_page_size;
400 
401     /* init debug */
402     {
403         int mask = 0;
404         if (log_mask) {
405             mask = qemu_str_to_log_mask(log_mask);
406             if (!mask) {
407                 qemu_print_log_usage(stdout);
408                 exit(1);
409             }
410         }
411         qemu_set_log_filename_flags(log_file, mask, &error_fatal);
412     }
413 
414     if (optind >= argc) {
415         usage();
416     }
417     filename = argv[optind];
418     if (argv0) {
419         argv[optind] = argv0;
420     }
421 
422     if (!trace_init_backends()) {
423         exit(1);
424     }
425     trace_init_file();
426 
427     /* Zero out regs */
428     memset(regs, 0, sizeof(struct target_pt_regs));
429 
430     /* Zero bsd params */
431     memset(&bprm, 0, sizeof(bprm));
432 
433     /* Zero out image_info */
434     memset(info, 0, sizeof(struct image_info));
435 
436     /* Scan interp_prefix dir for replacement files. */
437     init_paths(interp_prefix);
438 
439     if (cpu_model == NULL) {
440         cpu_model = TARGET_DEFAULT_CPU_MODEL;
441     }
442 
443     cpu_type = parse_cpu_option(cpu_model);
444 
445     /* init tcg before creating CPUs and to get qemu_host_page_size */
446     {
447         AccelState *accel = current_accel();
448         AccelClass *ac = ACCEL_GET_CLASS(accel);
449 
450         accel_init_interfaces(ac);
451         object_property_set_bool(OBJECT(accel), "one-insn-per-tb",
452                                  opt_one_insn_per_tb, &error_abort);
453         ac->init_machine(NULL);
454     }
455 
456     /*
457      * Finalize page size before creating CPUs.
458      * This will do nothing if !TARGET_PAGE_BITS_VARY.
459      * The most efficient setting is to match the host.
460      */
461     host_page_size = qemu_real_host_page_size();
462     set_preferred_target_page_bits(ctz32(host_page_size));
463     finalize_target_page_bits();
464 
465     cpu = cpu_create(cpu_type);
466     env = cpu_env(cpu);
467     cpu_reset(cpu);
468     thread_cpu = cpu;
469 
470     /*
471      * Reserving too much vm space via mmap can run into problems with rlimits,
472      * oom due to page table creation, etc.  We will still try it, if directed
473      * by the command-line option, but not by default. Unless we're running a
474      * target address space of 32 or fewer bits on a host with 64 bits.
475      */
476     max_reserved_va = MAX_RESERVED_VA(cpu);
477     if (reserved_va != 0) {
478         if ((reserved_va + 1) % host_page_size) {
479             char *s = size_to_str(host_page_size);
480             fprintf(stderr, "Reserved virtual address not aligned mod %s\n", s);
481             g_free(s);
482             exit(EXIT_FAILURE);
483         }
484         if (max_reserved_va && reserved_va > max_reserved_va) {
485             fprintf(stderr, "Reserved virtual address too big\n");
486             exit(EXIT_FAILURE);
487         }
488     } else if (HOST_LONG_BITS == 64 && TARGET_VIRT_ADDR_SPACE_BITS <= 32) {
489         /* MAX_RESERVED_VA + 1 is a large power of 2, so is aligned. */
490         reserved_va = max_reserved_va;
491     }
492 
493     if (getenv("QEMU_STRACE")) {
494         do_strace = 1;
495     }
496 
497     target_environ = envlist_to_environ(envlist, NULL);
498     envlist_free(envlist);
499 
500     {
501         Error *err = NULL;
502         if (seed_optarg != NULL) {
503             qemu_guest_random_seed_main(seed_optarg, &err);
504         } else {
505             qcrypto_init(&err);
506         }
507         if (err) {
508             error_reportf_err(err, "cannot initialize crypto: ");
509             exit(1);
510         }
511     }
512 
513     /*
514      * Now that page sizes are configured we can do
515      * proper page alignment for guest_base.
516      */
517     if (have_guest_base) {
518         if (guest_base & ~qemu_host_page_mask) {
519             error_report("Selected guest base not host page aligned");
520             exit(1);
521         }
522     }
523 
524     /*
525      * If reserving host virtual address space, do so now.
526      * Combined with '-B', ensure that the chosen range is free.
527      */
528     if (reserved_va) {
529         void *p;
530 
531         if (have_guest_base) {
532             p = mmap((void *)guest_base, reserved_va + 1, PROT_NONE,
533                      MAP_ANON | MAP_PRIVATE | MAP_FIXED | MAP_EXCL, -1, 0);
534         } else {
535             p = mmap(NULL, reserved_va + 1, PROT_NONE,
536                      MAP_ANON | MAP_PRIVATE, -1, 0);
537         }
538         if (p == MAP_FAILED) {
539             const char *err = strerror(errno);
540             char *sz = size_to_str(reserved_va + 1);
541 
542             if (have_guest_base) {
543                 error_report("Cannot allocate %s bytes at -B %p for guest "
544                              "address space: %s", sz, (void *)guest_base, err);
545             } else {
546                 error_report("Cannot allocate %s bytes for guest "
547                              "address space: %s", sz, err);
548             }
549             exit(1);
550         }
551         guest_base = (uintptr_t)p;
552         have_guest_base = true;
553 
554         /* Ensure that mmap_next_start is within range. */
555         if (reserved_va <= mmap_next_start) {
556             mmap_next_start = (reserved_va / 4 * 3)
557                               & TARGET_PAGE_MASK & qemu_host_page_mask;
558         }
559     }
560 
561     if (loader_exec(filename, argv + optind, target_environ, regs, info,
562                     &bprm) != 0) {
563         printf("Error loading %s\n", filename);
564         _exit(1);
565     }
566 
567     for (wrk = target_environ; *wrk; wrk++) {
568         g_free(*wrk);
569     }
570 
571     g_free(target_environ);
572 
573     if (qemu_loglevel_mask(CPU_LOG_PAGE)) {
574         FILE *f = qemu_log_trylock();
575         if (f) {
576             fprintf(f, "guest_base  %p\n", (void *)guest_base);
577             fprintf(f, "page layout changed following binary load\n");
578             page_dump(f);
579 
580             fprintf(f, "end_code    0x" TARGET_ABI_FMT_lx "\n",
581                     info->end_code);
582             fprintf(f, "start_code  0x" TARGET_ABI_FMT_lx "\n",
583                     info->start_code);
584             fprintf(f, "start_data  0x" TARGET_ABI_FMT_lx "\n",
585                     info->start_data);
586             fprintf(f, "end_data    0x" TARGET_ABI_FMT_lx "\n",
587                     info->end_data);
588             fprintf(f, "start_stack 0x" TARGET_ABI_FMT_lx "\n",
589                     info->start_stack);
590             fprintf(f, "brk         0x" TARGET_ABI_FMT_lx "\n", info->brk);
591             fprintf(f, "entry       0x" TARGET_ABI_FMT_lx "\n", info->entry);
592 
593             qemu_log_unlock(f);
594         }
595     }
596 
597     /* build Task State */
598     ts = g_new0(TaskState, 1);
599     init_task_state(ts);
600     ts->info = info;
601     ts->bprm = &bprm;
602     cpu->opaque = ts;
603 
604     target_set_brk(info->brk);
605     syscall_init();
606     signal_init();
607 
608     /*
609      * Now that we've loaded the binary, GUEST_BASE is fixed.  Delay
610      * generating the prologue until now so that the prologue can take
611      * the real value of GUEST_BASE into account.
612      */
613     tcg_prologue_init();
614 
615     target_cpu_init(env, regs);
616 
617     if (gdbstub) {
618         gdbserver_start(gdbstub);
619         gdb_handlesig(cpu, 0, NULL, NULL, 0);
620     }
621     cpu_loop(env);
622     /* never exits */
623     return 0;
624 }
625