qemu

FORK: QEMU emulator
git clone https://git.neptards.moe/neptards/qemu.git
Log | Files | Refs | Submodules | LICENSE

main.c (27157B)


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