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