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