xref: /qemu/linux-user/main.c (revision 2732c739)
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/help-texts.h"
22 #include "qemu/units.h"
23 #include "qemu/accel.h"
24 #include "qemu-version.h"
25 #include <sys/syscall.h>
26 #include <sys/resource.h>
27 #include <sys/shm.h>
28 #include <linux/binfmts.h>
29 
30 #include "qapi/error.h"
31 #include "qemu.h"
32 #include "user-internals.h"
33 #include "qemu/path.h"
34 #include "qemu/queue.h"
35 #include "qemu/config-file.h"
36 #include "qemu/cutils.h"
37 #include "qemu/error-report.h"
38 #include "qemu/help_option.h"
39 #include "qemu/module.h"
40 #include "qemu/plugin.h"
41 #include "exec/exec-all.h"
42 #include "exec/gdbstub.h"
43 #include "tcg/tcg.h"
44 #include "qemu/timer.h"
45 #include "qemu/envlist.h"
46 #include "qemu/guest-random.h"
47 #include "elf.h"
48 #include "trace/control.h"
49 #include "target_elf.h"
50 #include "cpu_loop-common.h"
51 #include "crypto/init.h"
52 #include "fd-trans.h"
53 #include "signal-common.h"
54 #include "loader.h"
55 #include "user-mmap.h"
56 #include "accel/tcg/perf.h"
57 
58 #ifdef CONFIG_SEMIHOSTING
59 #include "semihosting/semihost.h"
60 #endif
61 
62 #ifndef AT_FLAGS_PRESERVE_ARGV0
63 #define AT_FLAGS_PRESERVE_ARGV0_BIT 0
64 #define AT_FLAGS_PRESERVE_ARGV0 (1 << AT_FLAGS_PRESERVE_ARGV0_BIT)
65 #endif
66 
67 char *exec_path;
68 char real_exec_path[PATH_MAX];
69 
70 int singlestep;
71 static const char *argv0;
72 static const char *gdbstub;
73 static envlist_t *envlist;
74 static const char *cpu_model;
75 static const char *cpu_type;
76 static const char *seed_optarg;
77 unsigned long mmap_min_addr;
78 uintptr_t guest_base;
79 bool have_guest_base;
80 
81 /*
82  * Used to implement backwards-compatibility for the `-strace`, and
83  * QEMU_STRACE options. Without this, the QEMU_LOG can be overwritten by
84  * -strace, or vice versa.
85  */
86 static bool enable_strace;
87 
88 /*
89  * The last log mask given by the user in an environment variable or argument.
90  * Used to support command line arguments overriding environment variables.
91  */
92 static int last_log_mask;
93 static const char *last_log_filename;
94 
95 /*
96  * When running 32-on-64 we should make sure we can fit all of the possible
97  * guest address space into a contiguous chunk of virtual host memory.
98  *
99  * This way we will never overlap with our own libraries or binaries or stack
100  * or anything else that QEMU maps.
101  *
102  * Many cpus reserve the high bit (or more than one for some 64-bit cpus)
103  * of the address for the kernel.  Some cpus rely on this and user space
104  * uses the high bit(s) for pointer tagging and the like.  For them, we
105  * must preserve the expected address space.
106  */
107 #ifndef MAX_RESERVED_VA
108 # if HOST_LONG_BITS > TARGET_VIRT_ADDR_SPACE_BITS
109 #  if TARGET_VIRT_ADDR_SPACE_BITS == 32 && \
110       (TARGET_LONG_BITS == 32 || defined(TARGET_ABI32))
111 /* There are a number of places where we assign reserved_va to a variable
112    of type abi_ulong and expect it to fit.  Avoid the last page.  */
113 #   define MAX_RESERVED_VA(CPU)  (0xfffffffful & TARGET_PAGE_MASK)
114 #  else
115 #   define MAX_RESERVED_VA(CPU)  (1ul << TARGET_VIRT_ADDR_SPACE_BITS)
116 #  endif
117 # else
118 #  define MAX_RESERVED_VA(CPU)  0
119 # endif
120 #endif
121 
122 unsigned long reserved_va;
123 
124 static void usage(int exitcode);
125 
126 static const char *interp_prefix = CONFIG_QEMU_INTERP_PREFIX;
127 const char *qemu_uname_release;
128 
129 #if !defined(TARGET_DEFAULT_STACK_SIZE)
130 /* XXX: on x86 MAP_GROWSDOWN only works if ESP <= address + 32, so
131    we allocate a bigger stack. Need a better solution, for example
132    by remapping the process stack directly at the right place */
133 #define TARGET_DEFAULT_STACK_SIZE	8 * 1024 * 1024UL
134 #endif
135 
136 unsigned long guest_stack_size = TARGET_DEFAULT_STACK_SIZE;
137 
138 /***********************************************************/
139 /* Helper routines for implementing atomic operations.  */
140 
141 /* Make sure everything is in a consistent state for calling fork().  */
142 void fork_start(void)
143 {
144     start_exclusive();
145     mmap_fork_start();
146     cpu_list_lock();
147     qemu_plugin_user_prefork_lock();
148 }
149 
150 void fork_end(int child)
151 {
152     qemu_plugin_user_postfork(child);
153     mmap_fork_end(child);
154     if (child) {
155         CPUState *cpu, *next_cpu;
156         /* Child processes created by fork() only have a single thread.
157            Discard information about the parent threads.  */
158         CPU_FOREACH_SAFE(cpu, next_cpu) {
159             if (cpu != thread_cpu) {
160                 QTAILQ_REMOVE_RCU(&cpus, cpu, node);
161             }
162         }
163         qemu_init_cpu_list();
164         gdbserver_fork(thread_cpu);
165     } else {
166         cpu_list_unlock();
167     }
168     /*
169      * qemu_init_cpu_list() reinitialized the child exclusive state, but we
170      * also need to keep current_cpu consistent, so call end_exclusive() for
171      * both child and parent.
172      */
173     end_exclusive();
174 }
175 
176 __thread CPUState *thread_cpu;
177 
178 bool qemu_cpu_is_self(CPUState *cpu)
179 {
180     return thread_cpu == cpu;
181 }
182 
183 void qemu_cpu_kick(CPUState *cpu)
184 {
185     cpu_exit(cpu);
186 }
187 
188 void task_settid(TaskState *ts)
189 {
190     if (ts->ts_tid == 0) {
191         ts->ts_tid = (pid_t)syscall(SYS_gettid);
192     }
193 }
194 
195 void stop_all_tasks(void)
196 {
197     /*
198      * We trust that when using NPTL, start_exclusive()
199      * handles thread stopping correctly.
200      */
201     start_exclusive();
202 }
203 
204 /* Assumes contents are already zeroed.  */
205 void init_task_state(TaskState *ts)
206 {
207     long ticks_per_sec;
208     struct timespec bt;
209 
210     ts->used = 1;
211     ts->sigaltstack_used = (struct target_sigaltstack) {
212         .ss_sp = 0,
213         .ss_size = 0,
214         .ss_flags = TARGET_SS_DISABLE,
215     };
216 
217     /* Capture task start time relative to system boot */
218 
219     ticks_per_sec = sysconf(_SC_CLK_TCK);
220 
221     if ((ticks_per_sec > 0) && !clock_gettime(CLOCK_BOOTTIME, &bt)) {
222         /* start_boottime is expressed in clock ticks */
223         ts->start_boottime = bt.tv_sec * (uint64_t) ticks_per_sec;
224         ts->start_boottime += bt.tv_nsec * (uint64_t) ticks_per_sec /
225                               NANOSECONDS_PER_SECOND;
226     }
227 }
228 
229 CPUArchState *cpu_copy(CPUArchState *env)
230 {
231     CPUState *cpu = env_cpu(env);
232     CPUState *new_cpu = cpu_create(cpu_type);
233     CPUArchState *new_env = new_cpu->env_ptr;
234     CPUBreakpoint *bp;
235 
236     /* Reset non arch specific state */
237     cpu_reset(new_cpu);
238 
239     new_cpu->tcg_cflags = cpu->tcg_cflags;
240     memcpy(new_env, env, sizeof(CPUArchState));
241 #if defined(TARGET_I386) || defined(TARGET_X86_64)
242     new_env->gdt.base = target_mmap(0, sizeof(uint64_t) * TARGET_GDT_ENTRIES,
243                                     PROT_READ | PROT_WRITE,
244                                     MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
245     memcpy(g2h_untagged(new_env->gdt.base), g2h_untagged(env->gdt.base),
246            sizeof(uint64_t) * TARGET_GDT_ENTRIES);
247     OBJECT(new_cpu)->free = OBJECT(cpu)->free;
248 #endif
249 
250     /* Clone all break/watchpoints.
251        Note: Once we support ptrace with hw-debug register access, make sure
252        BP_CPU break/watchpoints are handled correctly on clone. */
253     QTAILQ_INIT(&new_cpu->breakpoints);
254     QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
255         cpu_breakpoint_insert(new_cpu, bp->pc, bp->flags, NULL);
256     }
257 
258     return new_env;
259 }
260 
261 static void handle_arg_help(const char *arg)
262 {
263     usage(EXIT_SUCCESS);
264 }
265 
266 static void handle_arg_log(const char *arg)
267 {
268     last_log_mask = qemu_str_to_log_mask(arg);
269     if (!last_log_mask) {
270         qemu_print_log_usage(stdout);
271         exit(EXIT_FAILURE);
272     }
273 }
274 
275 static void handle_arg_dfilter(const char *arg)
276 {
277     qemu_set_dfilter_ranges(arg, &error_fatal);
278 }
279 
280 static void handle_arg_log_filename(const char *arg)
281 {
282     last_log_filename = arg;
283 }
284 
285 static void handle_arg_set_env(const char *arg)
286 {
287     char *r, *p, *token;
288     r = p = strdup(arg);
289     while ((token = strsep(&p, ",")) != NULL) {
290         if (envlist_setenv(envlist, token) != 0) {
291             usage(EXIT_FAILURE);
292         }
293     }
294     free(r);
295 }
296 
297 static void handle_arg_unset_env(const char *arg)
298 {
299     char *r, *p, *token;
300     r = p = strdup(arg);
301     while ((token = strsep(&p, ",")) != NULL) {
302         if (envlist_unsetenv(envlist, token) != 0) {
303             usage(EXIT_FAILURE);
304         }
305     }
306     free(r);
307 }
308 
309 static void handle_arg_argv0(const char *arg)
310 {
311     argv0 = strdup(arg);
312 }
313 
314 static void handle_arg_stack_size(const char *arg)
315 {
316     char *p;
317     guest_stack_size = strtoul(arg, &p, 0);
318     if (guest_stack_size == 0) {
319         usage(EXIT_FAILURE);
320     }
321 
322     if (*p == 'M') {
323         guest_stack_size *= MiB;
324     } else if (*p == 'k' || *p == 'K') {
325         guest_stack_size *= KiB;
326     }
327 }
328 
329 static void handle_arg_ld_prefix(const char *arg)
330 {
331     interp_prefix = strdup(arg);
332 }
333 
334 static void handle_arg_pagesize(const char *arg)
335 {
336     qemu_host_page_size = atoi(arg);
337     if (qemu_host_page_size == 0 ||
338         (qemu_host_page_size & (qemu_host_page_size - 1)) != 0) {
339         fprintf(stderr, "page size must be a power of two\n");
340         exit(EXIT_FAILURE);
341     }
342 }
343 
344 static void handle_arg_seed(const char *arg)
345 {
346     seed_optarg = arg;
347 }
348 
349 static void handle_arg_gdb(const char *arg)
350 {
351     gdbstub = g_strdup(arg);
352 }
353 
354 static void handle_arg_uname(const char *arg)
355 {
356     qemu_uname_release = strdup(arg);
357 }
358 
359 static void handle_arg_cpu(const char *arg)
360 {
361     cpu_model = strdup(arg);
362     if (cpu_model == NULL || is_help_option(cpu_model)) {
363         /* XXX: implement xxx_cpu_list for targets that still miss it */
364 #if defined(cpu_list)
365         cpu_list();
366 #endif
367         exit(EXIT_FAILURE);
368     }
369 }
370 
371 static void handle_arg_guest_base(const char *arg)
372 {
373     guest_base = strtol(arg, NULL, 0);
374     have_guest_base = true;
375 }
376 
377 static void handle_arg_reserved_va(const char *arg)
378 {
379     char *p;
380     int shift = 0;
381     reserved_va = strtoul(arg, &p, 0);
382     switch (*p) {
383     case 'k':
384     case 'K':
385         shift = 10;
386         break;
387     case 'M':
388         shift = 20;
389         break;
390     case 'G':
391         shift = 30;
392         break;
393     }
394     if (shift) {
395         unsigned long unshifted = reserved_va;
396         p++;
397         reserved_va <<= shift;
398         if (reserved_va >> shift != unshifted) {
399             fprintf(stderr, "Reserved virtual address too big\n");
400             exit(EXIT_FAILURE);
401         }
402     }
403     if (*p) {
404         fprintf(stderr, "Unrecognised -R size suffix '%s'\n", p);
405         exit(EXIT_FAILURE);
406     }
407 }
408 
409 static void handle_arg_singlestep(const char *arg)
410 {
411     singlestep = 1;
412 }
413 
414 static void handle_arg_strace(const char *arg)
415 {
416     enable_strace = true;
417 }
418 
419 static void handle_arg_version(const char *arg)
420 {
421     printf("qemu-" TARGET_NAME " version " QEMU_FULL_VERSION
422            "\n" QEMU_COPYRIGHT "\n");
423     exit(EXIT_SUCCESS);
424 }
425 
426 static void handle_arg_trace(const char *arg)
427 {
428     trace_opt_parse(arg);
429 }
430 
431 #if defined(TARGET_XTENSA)
432 static void handle_arg_abi_call0(const char *arg)
433 {
434     xtensa_set_abi_call0();
435 }
436 #endif
437 
438 static void handle_arg_perfmap(const char *arg)
439 {
440     perf_enable_perfmap();
441 }
442 
443 static void handle_arg_jitdump(const char *arg)
444 {
445     perf_enable_jitdump();
446 }
447 
448 static QemuPluginList plugins = QTAILQ_HEAD_INITIALIZER(plugins);
449 
450 #ifdef CONFIG_PLUGIN
451 static void handle_arg_plugin(const char *arg)
452 {
453     qemu_plugin_opt_parse(arg, &plugins);
454 }
455 #endif
456 
457 struct qemu_argument {
458     const char *argv;
459     const char *env;
460     bool has_arg;
461     void (*handle_opt)(const char *arg);
462     const char *example;
463     const char *help;
464 };
465 
466 static const struct qemu_argument arg_table[] = {
467     {"h",          "",                 false, handle_arg_help,
468      "",           "print this help"},
469     {"help",       "",                 false, handle_arg_help,
470      "",           ""},
471     {"g",          "QEMU_GDB",         true,  handle_arg_gdb,
472      "port",       "wait gdb connection to 'port'"},
473     {"L",          "QEMU_LD_PREFIX",   true,  handle_arg_ld_prefix,
474      "path",       "set the elf interpreter prefix to 'path'"},
475     {"s",          "QEMU_STACK_SIZE",  true,  handle_arg_stack_size,
476      "size",       "set the stack size to 'size' bytes"},
477     {"cpu",        "QEMU_CPU",         true,  handle_arg_cpu,
478      "model",      "select CPU (-cpu help for list)"},
479     {"E",          "QEMU_SET_ENV",     true,  handle_arg_set_env,
480      "var=value",  "sets targets environment variable (see below)"},
481     {"U",          "QEMU_UNSET_ENV",   true,  handle_arg_unset_env,
482      "var",        "unsets targets environment variable (see below)"},
483     {"0",          "QEMU_ARGV0",       true,  handle_arg_argv0,
484      "argv0",      "forces target process argv[0] to be 'argv0'"},
485     {"r",          "QEMU_UNAME",       true,  handle_arg_uname,
486      "uname",      "set qemu uname release string to 'uname'"},
487     {"B",          "QEMU_GUEST_BASE",  true,  handle_arg_guest_base,
488      "address",    "set guest_base address to 'address'"},
489     {"R",          "QEMU_RESERVED_VA", true,  handle_arg_reserved_va,
490      "size",       "reserve 'size' bytes for guest virtual address space"},
491     {"d",          "QEMU_LOG",         true,  handle_arg_log,
492      "item[,...]", "enable logging of specified items "
493      "(use '-d help' for a list of items)"},
494     {"dfilter",    "QEMU_DFILTER",     true,  handle_arg_dfilter,
495      "range[,...]","filter logging based on address range"},
496     {"D",          "QEMU_LOG_FILENAME", true, handle_arg_log_filename,
497      "logfile",     "write logs to 'logfile' (default stderr)"},
498     {"p",          "QEMU_PAGESIZE",    true,  handle_arg_pagesize,
499      "pagesize",   "set the host page size to 'pagesize'"},
500     {"singlestep", "QEMU_SINGLESTEP",  false, handle_arg_singlestep,
501      "",           "run in singlestep mode"},
502     {"strace",     "QEMU_STRACE",      false, handle_arg_strace,
503      "",           "log system calls"},
504     {"seed",       "QEMU_RAND_SEED",   true,  handle_arg_seed,
505      "",           "Seed for pseudo-random number generator"},
506     {"trace",      "QEMU_TRACE",       true,  handle_arg_trace,
507      "",           "[[enable=]<pattern>][,events=<file>][,file=<file>]"},
508 #ifdef CONFIG_PLUGIN
509     {"plugin",     "QEMU_PLUGIN",      true,  handle_arg_plugin,
510      "",           "[file=]<file>[,<argname>=<argvalue>]"},
511 #endif
512     {"version",    "QEMU_VERSION",     false, handle_arg_version,
513      "",           "display version information and exit"},
514 #if defined(TARGET_XTENSA)
515     {"xtensa-abi-call0", "QEMU_XTENSA_ABI_CALL0", false, handle_arg_abi_call0,
516      "",           "assume CALL0 Xtensa ABI"},
517 #endif
518     {"perfmap",    "QEMU_PERFMAP",     false, handle_arg_perfmap,
519      "",           "Generate a /tmp/perf-${pid}.map file for perf"},
520     {"jitdump",    "QEMU_JITDUMP",     false, handle_arg_jitdump,
521      "",           "Generate a jit-${pid}.dump file for perf"},
522     {NULL, NULL, false, NULL, NULL, NULL}
523 };
524 
525 static void usage(int exitcode)
526 {
527     const struct qemu_argument *arginfo;
528     int maxarglen;
529     int maxenvlen;
530 
531     printf("usage: qemu-" TARGET_NAME " [options] program [arguments...]\n"
532            "Linux CPU emulator (compiled for " TARGET_NAME " emulation)\n"
533            "\n"
534            "Options and associated environment variables:\n"
535            "\n");
536 
537     /* Calculate column widths. We must always have at least enough space
538      * for the column header.
539      */
540     maxarglen = strlen("Argument");
541     maxenvlen = strlen("Env-variable");
542 
543     for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
544         int arglen = strlen(arginfo->argv);
545         if (arginfo->has_arg) {
546             arglen += strlen(arginfo->example) + 1;
547         }
548         if (strlen(arginfo->env) > maxenvlen) {
549             maxenvlen = strlen(arginfo->env);
550         }
551         if (arglen > maxarglen) {
552             maxarglen = arglen;
553         }
554     }
555 
556     printf("%-*s %-*s Description\n", maxarglen+1, "Argument",
557             maxenvlen, "Env-variable");
558 
559     for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
560         if (arginfo->has_arg) {
561             printf("-%s %-*s %-*s %s\n", arginfo->argv,
562                    (int)(maxarglen - strlen(arginfo->argv) - 1),
563                    arginfo->example, maxenvlen, arginfo->env, arginfo->help);
564         } else {
565             printf("-%-*s %-*s %s\n", maxarglen, arginfo->argv,
566                     maxenvlen, arginfo->env,
567                     arginfo->help);
568         }
569     }
570 
571     printf("\n"
572            "Defaults:\n"
573            "QEMU_LD_PREFIX  = %s\n"
574            "QEMU_STACK_SIZE = %ld byte\n",
575            interp_prefix,
576            guest_stack_size);
577 
578     printf("\n"
579            "You can use -E and -U options or the QEMU_SET_ENV and\n"
580            "QEMU_UNSET_ENV environment variables to set and unset\n"
581            "environment variables for the target process.\n"
582            "It is possible to provide several variables by separating them\n"
583            "by commas in getsubopt(3) style. Additionally it is possible to\n"
584            "provide the -E and -U options multiple times.\n"
585            "The following lines are equivalent:\n"
586            "    -E var1=val2 -E var2=val2 -U LD_PRELOAD -U LD_DEBUG\n"
587            "    -E var1=val2,var2=val2 -U LD_PRELOAD,LD_DEBUG\n"
588            "    QEMU_SET_ENV=var1=val2,var2=val2 QEMU_UNSET_ENV=LD_PRELOAD,LD_DEBUG\n"
589            "Note that if you provide several changes to a single variable\n"
590            "the last change will stay in effect.\n"
591            "\n"
592            QEMU_HELP_BOTTOM "\n");
593 
594     exit(exitcode);
595 }
596 
597 static int parse_args(int argc, char **argv)
598 {
599     const char *r;
600     int optind;
601     const struct qemu_argument *arginfo;
602 
603     for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
604         if (arginfo->env == NULL) {
605             continue;
606         }
607 
608         r = getenv(arginfo->env);
609         if (r != NULL) {
610             arginfo->handle_opt(r);
611         }
612     }
613 
614     optind = 1;
615     for (;;) {
616         if (optind >= argc) {
617             break;
618         }
619         r = argv[optind];
620         if (r[0] != '-') {
621             break;
622         }
623         optind++;
624         r++;
625         if (!strcmp(r, "-")) {
626             break;
627         }
628         /* Treat --foo the same as -foo.  */
629         if (r[0] == '-') {
630             r++;
631         }
632 
633         for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
634             if (!strcmp(r, arginfo->argv)) {
635                 if (arginfo->has_arg) {
636                     if (optind >= argc) {
637                         (void) fprintf(stderr,
638                             "qemu: missing argument for option '%s'\n", r);
639                         exit(EXIT_FAILURE);
640                     }
641                     arginfo->handle_opt(argv[optind]);
642                     optind++;
643                 } else {
644                     arginfo->handle_opt(NULL);
645                 }
646                 break;
647             }
648         }
649 
650         /* no option matched the current argv */
651         if (arginfo->handle_opt == NULL) {
652             (void) fprintf(stderr, "qemu: unknown option '%s'\n", r);
653             exit(EXIT_FAILURE);
654         }
655     }
656 
657     if (optind >= argc) {
658         (void) fprintf(stderr, "qemu: no user program specified\n");
659         exit(EXIT_FAILURE);
660     }
661 
662     exec_path = argv[optind];
663 
664     return optind;
665 }
666 
667 int main(int argc, char **argv, char **envp)
668 {
669     struct target_pt_regs regs1, *regs = &regs1;
670     struct image_info info1, *info = &info1;
671     struct linux_binprm bprm;
672     TaskState *ts;
673     CPUArchState *env;
674     CPUState *cpu;
675     int optind;
676     char **target_environ, **wrk;
677     char **target_argv;
678     int target_argc;
679     int i;
680     int ret;
681     int execfd;
682     unsigned long max_reserved_va;
683     bool preserve_argv0;
684 
685     error_init(argv[0]);
686     module_call_init(MODULE_INIT_TRACE);
687     qemu_init_cpu_list();
688     module_call_init(MODULE_INIT_QOM);
689 
690     envlist = envlist_create();
691 
692     /* add current environment into the list */
693     for (wrk = environ; *wrk != NULL; wrk++) {
694         (void) envlist_setenv(envlist, *wrk);
695     }
696 
697     /* Read the stack limit from the kernel.  If it's "unlimited",
698        then we can do little else besides use the default.  */
699     {
700         struct rlimit lim;
701         if (getrlimit(RLIMIT_STACK, &lim) == 0
702             && lim.rlim_cur != RLIM_INFINITY
703             && lim.rlim_cur == (target_long)lim.rlim_cur
704             && lim.rlim_cur > guest_stack_size) {
705             guest_stack_size = lim.rlim_cur;
706         }
707     }
708 
709     cpu_model = NULL;
710 
711     qemu_add_opts(&qemu_trace_opts);
712     qemu_plugin_add_opts();
713 
714     optind = parse_args(argc, argv);
715 
716     qemu_set_log_filename_flags(last_log_filename,
717                                 last_log_mask | (enable_strace * LOG_STRACE),
718                                 &error_fatal);
719 
720     if (!trace_init_backends()) {
721         exit(1);
722     }
723     trace_init_file();
724     qemu_plugin_load_list(&plugins, &error_fatal);
725 
726     /* Zero out regs */
727     memset(regs, 0, sizeof(struct target_pt_regs));
728 
729     /* Zero out image_info */
730     memset(info, 0, sizeof(struct image_info));
731 
732     memset(&bprm, 0, sizeof (bprm));
733 
734     /* Scan interp_prefix dir for replacement files. */
735     init_paths(interp_prefix);
736 
737     init_qemu_uname_release();
738 
739     /*
740      * Manage binfmt-misc open-binary flag
741      */
742     execfd = qemu_getauxval(AT_EXECFD);
743     if (execfd == 0) {
744         execfd = open(exec_path, O_RDONLY);
745         if (execfd < 0) {
746             printf("Error while loading %s: %s\n", exec_path, strerror(errno));
747             _exit(EXIT_FAILURE);
748         }
749     }
750 
751     /* Resolve executable file name to full path name */
752     if (realpath(exec_path, real_exec_path)) {
753         exec_path = real_exec_path;
754     }
755 
756     /*
757      * get binfmt_misc flags
758      */
759     preserve_argv0 = !!(qemu_getauxval(AT_FLAGS) & AT_FLAGS_PRESERVE_ARGV0);
760 
761     /*
762      * Manage binfmt-misc preserve-arg[0] flag
763      *    argv[optind]     full path to the binary
764      *    argv[optind + 1] original argv[0]
765      */
766     if (optind + 1 < argc && preserve_argv0) {
767         optind++;
768     }
769 
770     if (cpu_model == NULL) {
771         cpu_model = cpu_get_model(get_elf_eflags(execfd));
772     }
773     cpu_type = parse_cpu_option(cpu_model);
774 
775     /* init tcg before creating CPUs and to get qemu_host_page_size */
776     {
777         AccelClass *ac = ACCEL_GET_CLASS(current_accel());
778 
779         accel_init_interfaces(ac);
780         ac->init_machine(NULL);
781     }
782     cpu = cpu_create(cpu_type);
783     env = cpu->env_ptr;
784     cpu_reset(cpu);
785     thread_cpu = cpu;
786 
787     /*
788      * Reserving too much vm space via mmap can run into problems
789      * with rlimits, oom due to page table creation, etc.  We will
790      * still try it, if directed by the command-line option, but
791      * not by default.
792      */
793     max_reserved_va = MAX_RESERVED_VA(cpu);
794     if (reserved_va != 0) {
795         if (max_reserved_va && reserved_va > max_reserved_va) {
796             fprintf(stderr, "Reserved virtual address too big\n");
797             exit(EXIT_FAILURE);
798         }
799     } else if (HOST_LONG_BITS == 64 && TARGET_VIRT_ADDR_SPACE_BITS <= 32) {
800         /*
801          * reserved_va must be aligned with the host page size
802          * as it is used with mmap()
803          */
804         reserved_va = max_reserved_va & qemu_host_page_mask;
805     }
806 
807     {
808         Error *err = NULL;
809         if (seed_optarg != NULL) {
810             qemu_guest_random_seed_main(seed_optarg, &err);
811         } else {
812             qcrypto_init(&err);
813         }
814         if (err) {
815             error_reportf_err(err, "cannot initialize crypto: ");
816             exit(1);
817         }
818     }
819 
820     target_environ = envlist_to_environ(envlist, NULL);
821     envlist_free(envlist);
822 
823     /*
824      * Read in mmap_min_addr kernel parameter.  This value is used
825      * When loading the ELF image to determine whether guest_base
826      * is needed.  It is also used in mmap_find_vma.
827      */
828     {
829         FILE *fp;
830 
831         if ((fp = fopen("/proc/sys/vm/mmap_min_addr", "r")) != NULL) {
832             unsigned long tmp;
833             if (fscanf(fp, "%lu", &tmp) == 1 && tmp != 0) {
834                 mmap_min_addr = tmp;
835                 qemu_log_mask(CPU_LOG_PAGE, "host mmap_min_addr=0x%lx\n",
836                               mmap_min_addr);
837             }
838             fclose(fp);
839         }
840     }
841 
842     /*
843      * We prefer to not make NULL pointers accessible to QEMU.
844      * If we're in a chroot with no /proc, fall back to 1 page.
845      */
846     if (mmap_min_addr == 0) {
847         mmap_min_addr = qemu_host_page_size;
848         qemu_log_mask(CPU_LOG_PAGE,
849                       "host mmap_min_addr=0x%lx (fallback)\n",
850                       mmap_min_addr);
851     }
852 
853     /*
854      * Prepare copy of argv vector for target.
855      */
856     target_argc = argc - optind;
857     target_argv = calloc(target_argc + 1, sizeof (char *));
858     if (target_argv == NULL) {
859         (void) fprintf(stderr, "Unable to allocate memory for target_argv\n");
860         exit(EXIT_FAILURE);
861     }
862 
863     /*
864      * If argv0 is specified (using '-0' switch) we replace
865      * argv[0] pointer with the given one.
866      */
867     i = 0;
868     if (argv0 != NULL) {
869         target_argv[i++] = strdup(argv0);
870     }
871     for (; i < target_argc; i++) {
872         target_argv[i] = strdup(argv[optind + i]);
873     }
874     target_argv[target_argc] = NULL;
875 
876     ts = g_new0(TaskState, 1);
877     init_task_state(ts);
878     /* build Task State */
879     ts->info = info;
880     ts->bprm = &bprm;
881     cpu->opaque = ts;
882     task_settid(ts);
883 
884     fd_trans_init();
885 
886     ret = loader_exec(execfd, exec_path, target_argv, target_environ, regs,
887         info, &bprm);
888     if (ret != 0) {
889         printf("Error while loading %s: %s\n", exec_path, strerror(-ret));
890         _exit(EXIT_FAILURE);
891     }
892 
893     for (wrk = target_environ; *wrk; wrk++) {
894         g_free(*wrk);
895     }
896 
897     g_free(target_environ);
898 
899     if (qemu_loglevel_mask(CPU_LOG_PAGE)) {
900         FILE *f = qemu_log_trylock();
901         if (f) {
902             fprintf(f, "guest_base  %p\n", (void *)guest_base);
903             fprintf(f, "page layout changed following binary load\n");
904             page_dump(f);
905 
906             fprintf(f, "start_brk   0x" TARGET_ABI_FMT_lx "\n",
907                     info->start_brk);
908             fprintf(f, "end_code    0x" TARGET_ABI_FMT_lx "\n",
909                     info->end_code);
910             fprintf(f, "start_code  0x" TARGET_ABI_FMT_lx "\n",
911                     info->start_code);
912             fprintf(f, "start_data  0x" TARGET_ABI_FMT_lx "\n",
913                     info->start_data);
914             fprintf(f, "end_data    0x" TARGET_ABI_FMT_lx "\n",
915                     info->end_data);
916             fprintf(f, "start_stack 0x" TARGET_ABI_FMT_lx "\n",
917                     info->start_stack);
918             fprintf(f, "brk         0x" TARGET_ABI_FMT_lx "\n",
919                     info->brk);
920             fprintf(f, "entry       0x" TARGET_ABI_FMT_lx "\n",
921                     info->entry);
922             fprintf(f, "argv_start  0x" TARGET_ABI_FMT_lx "\n",
923                     info->argv);
924             fprintf(f, "env_start   0x" TARGET_ABI_FMT_lx "\n",
925                     info->envp);
926             fprintf(f, "auxv_start  0x" TARGET_ABI_FMT_lx "\n",
927                     info->saved_auxv);
928             qemu_log_unlock(f);
929         }
930     }
931 
932     target_set_brk(info->brk);
933     syscall_init();
934     signal_init();
935 
936     /* Now that we've loaded the binary, GUEST_BASE is fixed.  Delay
937        generating the prologue until now so that the prologue can take
938        the real value of GUEST_BASE into account.  */
939     tcg_prologue_init(tcg_ctx);
940 
941     target_cpu_copy_regs(env, regs);
942 
943     if (gdbstub) {
944         if (gdbserver_start(gdbstub) < 0) {
945             fprintf(stderr, "qemu: could not open gdbserver on %s\n",
946                     gdbstub);
947             exit(EXIT_FAILURE);
948         }
949         gdb_handlesig(cpu, 0);
950     }
951 
952 #ifdef CONFIG_SEMIHOSTING
953     qemu_semihosting_guestfd_init();
954 #endif
955 
956     cpu_loop(env);
957     /* never exits */
958     return 0;
959 }
960