]> git.ipfire.org Git - thirdparty/qemu.git/blame - linux-user/main.c
Merge tag 'pull-target-arm-20250704' of https://gitlab.com/pm215/qemu into staging
[thirdparty/qemu.git] / linux-user / main.c
CommitLineData
31e31b8a 1/*
93ac68bc 2 * qemu user main
5fafdf24 3 *
68d0f70e 4 * Copyright (c) 2003-2008 Fabrice Bellard
31e31b8a
FB
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
8167ee88 17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
31e31b8a 18 */
14a48c1d 19
d39594e9 20#include "qemu/osdep.h"
49f95221 21#include "qemu/help-texts.h"
b52713c1 22#include "qemu/units.h"
940e43aa 23#include "qemu/accel.h"
67a1de0d 24#include "qemu-version.h"
edf8e2af 25#include <sys/syscall.h>
703e0e89 26#include <sys/resource.h>
ee947430 27#include <sys/shm.h>
6e1c0d7b 28#include <linux/binfmts.h>
31e31b8a 29
daa76aa4 30#include "qapi/error.h"
3ef693a0 31#include "qemu.h"
3b249d26 32#include "user-internals.h"
f348b6d1 33#include "qemu/path.h"
dc5e9ac7 34#include "qemu/queue.h"
6533dd6e 35#include "qemu/config-file.h"
f348b6d1 36#include "qemu/cutils.h"
f5852efa 37#include "qemu/error-report.h"
f348b6d1 38#include "qemu/help_option.h"
0b8fa32f 39#include "qemu/module.h"
f308f64e 40#include "qemu/plugin.h"
16aa8eaa 41#include "user/guest-base.h"
970ae60e 42#include "user/page-protection.h"
85b4fa0c 43#include "exec/gdbstub.h"
d96bf49b 44#include "gdbstub/user.h"
d7ec12f8 45#include "tcg/startup.h"
1de7afc9
PB
46#include "qemu/timer.h"
47#include "qemu/envlist.h"
5ebdd774 48#include "qemu/guest-random.h"
d8fd2954 49#include "elf.h"
6533dd6e 50#include "trace/control.h"
542ca434 51#include "target_elf.h"
b74c8981 52#include "user/cpu_loop.h"
a573e9ba 53#include "crypto/init.h"
c093364f 54#include "fd-trans.h"
2113aed6 55#include "signal-common.h"
3ad0a769 56#include "loader.h"
5423e6d3 57#include "user-mmap.h"
327b75a4 58#include "tcg/perf.h"
ff8a8bbc 59#include "exec/page-vary.h"
04a6dfeb 60
e4a4aaa5
RH
61#ifdef CONFIG_SEMIHOSTING
62#include "semihosting/semihost.h"
63#endif
64
6e1c0d7b
LV
65#ifndef AT_FLAGS_PRESERVE_ARGV0
66#define AT_FLAGS_PRESERVE_ARGV0_BIT 0
67#define AT_FLAGS_PRESERVE_ARGV0 (1 << AT_FLAGS_PRESERVE_ARGV0_BIT)
68#endif
69
d088d664 70char *exec_path;
258bec39 71char real_exec_path[PATH_MAX];
d088d664 72
3cfb0456 73static bool opt_one_insn_per_tb;
44ed2fd1 74static unsigned long opt_tb_size;
8cb76755 75static const char *argv0;
fcedd920 76static const char *gdbstub;
8cb76755 77static envlist_t *envlist;
51fb256a 78static const char *cpu_model;
2278b939 79static const char *cpu_type;
5ebdd774 80static const char *seed_optarg;
379f6698 81unsigned long mmap_min_addr;
5ca870b9 82uintptr_t guest_base;
e307c192 83bool have_guest_base;
120a9848 84
4b25a506
JK
85/*
86 * Used to implement backwards-compatibility for the `-strace`, and
87 * QEMU_STRACE options. Without this, the QEMU_LOG can be overwritten by
88 * -strace, or vice versa.
89 */
90static bool enable_strace;
91
92/*
93 * The last log mask given by the user in an environment variable or argument.
94 * Used to support command line arguments overriding environment variables.
95 */
96static int last_log_mask;
b410253f 97static const char *last_log_filename;
4b25a506 98
288e65b9
AG
99/*
100 * When running 32-on-64 we should make sure we can fit all of the possible
101 * guest address space into a contiguous chunk of virtual host memory.
102 *
103 * This way we will never overlap with our own libraries or binaries or stack
104 * or anything else that QEMU maps.
18e80c55
RH
105 *
106 * Many cpus reserve the high bit (or more than one for some 64-bit cpus)
107 * of the address for the kernel. Some cpus rely on this and user space
108 * uses the high bit(s) for pointer tagging and the like. For them, we
109 * must preserve the expected address space.
288e65b9 110 */
18e80c55
RH
111#ifndef MAX_RESERVED_VA
112# if HOST_LONG_BITS > TARGET_VIRT_ADDR_SPACE_BITS
113# if TARGET_VIRT_ADDR_SPACE_BITS == 32 && \
114 (TARGET_LONG_BITS == 32 || defined(TARGET_ABI32))
95059f9c 115# define MAX_RESERVED_VA(CPU) 0xfffffffful
18e80c55 116# else
95059f9c 117# define MAX_RESERVED_VA(CPU) ((1ul << TARGET_VIRT_ADDR_SPACE_BITS) - 1)
18e80c55 118# endif
314992b1 119# else
8f67b9c6 120# define MAX_RESERVED_VA(CPU) 0
314992b1 121# endif
18e80c55
RH
122#endif
123
68a1c816 124unsigned long reserved_va;
30da4760 125unsigned long guest_addr_max;
1b530a6d 126
d03f9c32 127static void usage(int exitcode);
fc9c5412 128
7ee2822c 129static const char *interp_prefix = CONFIG_QEMU_INTERP_PREFIX;
e586822a 130const char *qemu_uname_release;
586314f2 131
0a3346b5 132#if !defined(TARGET_DEFAULT_STACK_SIZE)
9de5e440
FB
133/* XXX: on x86 MAP_GROWSDOWN only works if ESP <= address + 32, so
134 we allocate a bigger stack. Need a better solution, for example
135 by remapping the process stack directly at the right place */
0a3346b5
HD
136#define TARGET_DEFAULT_STACK_SIZE 8 * 1024 * 1024UL
137#endif
138
139unsigned long guest_stack_size = TARGET_DEFAULT_STACK_SIZE;
31e31b8a 140
d5975363
PB
141/***********************************************************/
142/* Helper routines for implementing atomic operations. */
143
d5975363
PB
144/* Make sure everything is in a consistent state for calling fork(). */
145void fork_start(void)
146{
06065c45 147 start_exclusive();
d032d1b4 148 mmap_fork_start();
024949ca 149 cpu_list_lock();
f7e15aff 150 qemu_plugin_user_prefork_lock();
3d6ed98d 151 gdbserver_fork_start();
d5975363
PB
152}
153
4edc98fc 154void fork_end(pid_t pid)
d5975363 155{
4edc98fc
IL
156 bool child = pid == 0;
157
f7e15aff 158 qemu_plugin_user_postfork(child);
d032d1b4 159 mmap_fork_end(child);
d5975363 160 if (child) {
bdc44640 161 CPUState *cpu, *next_cpu;
d5975363
PB
162 /* Child processes created by fork() only have a single thread.
163 Discard information about the parent threads. */
bdc44640
AF
164 CPU_FOREACH_SAFE(cpu, next_cpu) {
165 if (cpu != thread_cpu) {
3c55dd58 166 QTAILQ_REMOVE_RCU(&cpus_queue, cpu, node);
bdc44640
AF
167 }
168 }
267f685b 169 qemu_init_cpu_list();
d4e1369a 170 get_task_state(thread_cpu)->ts_tid = qemu_get_thread_id();
d5975363 171 } else {
267f685b 172 cpu_list_unlock();
d5975363 173 }
6604b057 174 gdbserver_fork_end(thread_cpu, pid);
7de0816f
IL
175 /*
176 * qemu_init_cpu_list() reinitialized the child exclusive state, but we
177 * also need to keep current_cpu consistent, so call end_exclusive() for
178 * both child and parent.
179 */
180 end_exclusive();
d5975363
PB
181}
182
b44316fb 183__thread CPUState *thread_cpu;
59faf6d6 184
178f9429
SF
185bool qemu_cpu_is_self(CPUState *cpu)
186{
187 return thread_cpu == cpu;
188}
189
190void qemu_cpu_kick(CPUState *cpu)
191{
192 cpu_exit(cpu);
193}
194
edf8e2af
MW
195void task_settid(TaskState *ts)
196{
197 if (ts->ts_tid == 0) {
edf8e2af 198 ts->ts_tid = (pid_t)syscall(SYS_gettid);
edf8e2af
MW
199 }
200}
201
202void stop_all_tasks(void)
203{
204 /*
205 * We trust that when using NPTL, start_exclusive()
206 * handles thread stopping correctly.
207 */
208 start_exclusive();
209}
210
c3a92833 211/* Assumes contents are already zeroed. */
624f7979
PB
212void init_task_state(TaskState *ts)
213{
eb33cdae
CE
214 long ticks_per_sec;
215 struct timespec bt;
216
624f7979 217 ts->used = 1;
5bfce0b7
PM
218 ts->sigaltstack_used = (struct target_sigaltstack) {
219 .ss_sp = 0,
220 .ss_size = 0,
221 .ss_flags = TARGET_SS_DISABLE,
222 };
eb33cdae
CE
223
224 /* Capture task start time relative to system boot */
225
226 ticks_per_sec = sysconf(_SC_CLK_TCK);
227
228 if ((ticks_per_sec > 0) && !clock_gettime(CLOCK_BOOTTIME, &bt)) {
229 /* start_boottime is expressed in clock ticks */
230 ts->start_boottime = bt.tv_sec * (uint64_t) ticks_per_sec;
231 ts->start_boottime += bt.tv_nsec * (uint64_t) ticks_per_sec /
232 NANOSECONDS_PER_SECOND;
233 }
624f7979 234}
fc9c5412 235
30ba0ee5
AF
236CPUArchState *cpu_copy(CPUArchState *env)
237{
29a0af61 238 CPUState *cpu = env_cpu(env);
2278b939 239 CPUState *new_cpu = cpu_create(cpu_type);
b77af26e 240 CPUArchState *new_env = cpu_env(new_cpu);
30ba0ee5 241 CPUBreakpoint *bp;
30ba0ee5
AF
242
243 /* Reset non arch specific state */
75a34036 244 cpu_reset(new_cpu);
30ba0ee5 245
6cc9d67c 246 new_cpu->tcg_cflags = cpu->tcg_cflags;
30ba0ee5 247 memcpy(new_env, env, sizeof(CPUArchState));
2732c739 248#if defined(TARGET_I386) || defined(TARGET_X86_64)
249 new_env->gdt.base = target_mmap(0, sizeof(uint64_t) * TARGET_GDT_ENTRIES,
250 PROT_READ | PROT_WRITE,
251 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
252 memcpy(g2h_untagged(new_env->gdt.base), g2h_untagged(env->gdt.base),
253 sizeof(uint64_t) * TARGET_GDT_ENTRIES);
254 OBJECT(new_cpu)->free = OBJECT(cpu)->free;
255#endif
30ba0ee5
AF
256
257 /* Clone all break/watchpoints.
258 Note: Once we support ptrace with hw-debug register access, make sure
259 BP_CPU break/watchpoints are handled correctly on clone. */
1d085f6c 260 QTAILQ_INIT(&new_cpu->breakpoints);
f0c3c505 261 QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
b3310ab3 262 cpu_breakpoint_insert(new_cpu, bp->pc, bp->flags, NULL);
30ba0ee5 263 }
30ba0ee5
AF
264
265 return new_env;
266}
267
fc9c5412
JS
268static void handle_arg_help(const char *arg)
269{
4d1275c2 270 usage(EXIT_SUCCESS);
fc9c5412
JS
271}
272
273static void handle_arg_log(const char *arg)
274{
4b25a506
JK
275 last_log_mask = qemu_str_to_log_mask(arg);
276 if (!last_log_mask) {
59a6fa6e 277 qemu_print_log_usage(stdout);
4d1275c2 278 exit(EXIT_FAILURE);
fc9c5412 279 }
fc9c5412
JS
280}
281
8423fa90
AB
282static void handle_arg_dfilter(const char *arg)
283{
7f4341e8 284 qemu_set_dfilter_ranges(arg, &error_fatal);
8423fa90
AB
285}
286
50171d42
CWR
287static void handle_arg_log_filename(const char *arg)
288{
b410253f 289 last_log_filename = arg;
50171d42
CWR
290}
291
fc9c5412
JS
292static void handle_arg_set_env(const char *arg)
293{
294 char *r, *p, *token;
295 r = p = strdup(arg);
296 while ((token = strsep(&p, ",")) != NULL) {
297 if (envlist_setenv(envlist, token) != 0) {
4d1275c2 298 usage(EXIT_FAILURE);
fc9c5412
JS
299 }
300 }
301 free(r);
302}
303
304static void handle_arg_unset_env(const char *arg)
305{
306 char *r, *p, *token;
307 r = p = strdup(arg);
308 while ((token = strsep(&p, ",")) != NULL) {
309 if (envlist_unsetenv(envlist, token) != 0) {
4d1275c2 310 usage(EXIT_FAILURE);
fc9c5412
JS
311 }
312 }
313 free(r);
314}
315
316static void handle_arg_argv0(const char *arg)
317{
318 argv0 = strdup(arg);
319}
320
321static void handle_arg_stack_size(const char *arg)
322{
323 char *p;
324 guest_stack_size = strtoul(arg, &p, 0);
325 if (guest_stack_size == 0) {
4d1275c2 326 usage(EXIT_FAILURE);
fc9c5412
JS
327 }
328
329 if (*p == 'M') {
b52713c1 330 guest_stack_size *= MiB;
fc9c5412 331 } else if (*p == 'k' || *p == 'K') {
b52713c1 332 guest_stack_size *= KiB;
fc9c5412
JS
333 }
334}
335
336static void handle_arg_ld_prefix(const char *arg)
337{
338 interp_prefix = strdup(arg);
339}
340
341static void handle_arg_pagesize(const char *arg)
342{
01e44980
RH
343 unsigned size, want = qemu_real_host_page_size();
344
345 if (qemu_strtoui(arg, NULL, 10, &size) || size != want) {
346 warn_report("Deprecated page size option cannot "
347 "change host page size (%u)", want);
fc9c5412
JS
348 }
349}
350
5ebdd774 351static void handle_arg_seed(const char *arg)
c5e4a5a9 352{
5ebdd774 353 seed_optarg = arg;
c5e4a5a9
MR
354}
355
fc9c5412
JS
356static void handle_arg_gdb(const char *arg)
357{
fcedd920 358 gdbstub = g_strdup(arg);
fc9c5412
JS
359}
360
361static void handle_arg_uname(const char *arg)
362{
363 qemu_uname_release = strdup(arg);
364}
365
366static void handle_arg_cpu(const char *arg)
367{
368 cpu_model = strdup(arg);
c8057f95 369 if (cpu_model == NULL || is_help_option(cpu_model)) {
b67e5cb4 370 list_cpus();
4d1275c2 371 exit(EXIT_FAILURE);
fc9c5412
JS
372 }
373}
374
fc9c5412
JS
375static void handle_arg_guest_base(const char *arg)
376{
377 guest_base = strtol(arg, NULL, 0);
e307c192 378 have_guest_base = true;
fc9c5412
JS
379}
380
381static void handle_arg_reserved_va(const char *arg)
382{
383 char *p;
384 int shift = 0;
95059f9c
RH
385 unsigned long val;
386
387 val = strtoul(arg, &p, 0);
fc9c5412
JS
388 switch (*p) {
389 case 'k':
390 case 'K':
391 shift = 10;
392 break;
393 case 'M':
394 shift = 20;
395 break;
396 case 'G':
397 shift = 30;
398 break;
399 }
400 if (shift) {
95059f9c 401 unsigned long unshifted = val;
fc9c5412 402 p++;
95059f9c
RH
403 val <<= shift;
404 if (val >> shift != unshifted) {
fc9c5412 405 fprintf(stderr, "Reserved virtual address too big\n");
4d1275c2 406 exit(EXIT_FAILURE);
fc9c5412
JS
407 }
408 }
409 if (*p) {
410 fprintf(stderr, "Unrecognised -R size suffix '%s'\n", p);
4d1275c2 411 exit(EXIT_FAILURE);
fc9c5412 412 }
95059f9c
RH
413 /* The representation is size - 1, with 0 remaining "default". */
414 reserved_va = val ? val - 1 : 0;
fc9c5412 415}
fc9c5412 416
c107521e
IL
417static const char *rtsig_map = CONFIG_QEMU_RTSIG_MAP;
418
419static void handle_arg_rtsig_map(const char *arg)
420{
421 rtsig_map = arg;
422}
423
e99c1f89 424static void handle_arg_one_insn_per_tb(const char *arg)
fc9c5412 425{
3cfb0456 426 opt_one_insn_per_tb = true;
fc9c5412
JS
427}
428
44ed2fd1
IL
429static void handle_arg_tb_size(const char *arg)
430{
431 if (qemu_strtoul(arg, NULL, 0, &opt_tb_size)) {
432 usage(EXIT_FAILURE);
433 }
434}
435
fc9c5412
JS
436static void handle_arg_strace(const char *arg)
437{
4b25a506 438 enable_strace = true;
fc9c5412
JS
439}
440
441static void handle_arg_version(const char *arg)
442{
7e563bfb 443 printf("qemu-" TARGET_NAME " version " QEMU_FULL_VERSION
0781dd6e 444 "\n" QEMU_COPYRIGHT "\n");
4d1275c2 445 exit(EXIT_SUCCESS);
fc9c5412
JS
446}
447
6533dd6e
LV
448static void handle_arg_trace(const char *arg)
449{
92eecfff 450 trace_opt_parse(arg);
6533dd6e
LV
451}
452
130ea832
MF
453#if defined(TARGET_XTENSA)
454static void handle_arg_abi_call0(const char *arg)
455{
456 xtensa_set_abi_call0();
457}
458#endif
459
5584e2db
IL
460static void handle_arg_perfmap(const char *arg)
461{
462 perf_enable_perfmap();
463}
464
465static void handle_arg_jitdump(const char *arg)
466{
467 perf_enable_jitdump();
468}
469
f308f64e
LV
470static QemuPluginList plugins = QTAILQ_HEAD_INITIALIZER(plugins);
471
472#ifdef CONFIG_PLUGIN
473static void handle_arg_plugin(const char *arg)
474{
475 qemu_plugin_opt_parse(arg, &plugins);
476}
477#endif
478
fc9c5412
JS
479struct qemu_argument {
480 const char *argv;
481 const char *env;
482 bool has_arg;
483 void (*handle_opt)(const char *arg);
484 const char *example;
485 const char *help;
486};
487
42644cee 488static const struct qemu_argument arg_table[] = {
fc9c5412
JS
489 {"h", "", false, handle_arg_help,
490 "", "print this help"},
daaf8c8e
MI
491 {"help", "", false, handle_arg_help,
492 "", ""},
fc9c5412
JS
493 {"g", "QEMU_GDB", true, handle_arg_gdb,
494 "port", "wait gdb connection to 'port'"},
495 {"L", "QEMU_LD_PREFIX", true, handle_arg_ld_prefix,
496 "path", "set the elf interpreter prefix to 'path'"},
497 {"s", "QEMU_STACK_SIZE", true, handle_arg_stack_size,
498 "size", "set the stack size to 'size' bytes"},
499 {"cpu", "QEMU_CPU", true, handle_arg_cpu,
c8057f95 500 "model", "select CPU (-cpu help for list)"},
fc9c5412
JS
501 {"E", "QEMU_SET_ENV", true, handle_arg_set_env,
502 "var=value", "sets targets environment variable (see below)"},
503 {"U", "QEMU_UNSET_ENV", true, handle_arg_unset_env,
504 "var", "unsets targets environment variable (see below)"},
505 {"0", "QEMU_ARGV0", true, handle_arg_argv0,
506 "argv0", "forces target process argv[0] to be 'argv0'"},
507 {"r", "QEMU_UNAME", true, handle_arg_uname,
508 "uname", "set qemu uname release string to 'uname'"},
fc9c5412
JS
509 {"B", "QEMU_GUEST_BASE", true, handle_arg_guest_base,
510 "address", "set guest_base address to 'address'"},
511 {"R", "QEMU_RESERVED_VA", true, handle_arg_reserved_va,
512 "size", "reserve 'size' bytes for guest virtual address space"},
c107521e
IL
513 {"t", "QEMU_RTSIG_MAP", true, handle_arg_rtsig_map,
514 "tsig hsig n[,...]",
515 "map target rt signals [tsig,tsig+n) to [hsig,hsig+n]"},
fc9c5412 516 {"d", "QEMU_LOG", true, handle_arg_log,
989b697d
PM
517 "item[,...]", "enable logging of specified items "
518 "(use '-d help' for a list of items)"},
8423fa90
AB
519 {"dfilter", "QEMU_DFILTER", true, handle_arg_dfilter,
520 "range[,...]","filter logging based on address range"},
50171d42 521 {"D", "QEMU_LOG_FILENAME", true, handle_arg_log_filename,
989b697d 522 "logfile", "write logs to 'logfile' (default stderr)"},
fc9c5412 523 {"p", "QEMU_PAGESIZE", true, handle_arg_pagesize,
01e44980 524 "pagesize", "deprecated change to host page size"},
e99c1f89
PM
525 {"one-insn-per-tb",
526 "QEMU_ONE_INSN_PER_TB", false, handle_arg_one_insn_per_tb,
527 "", "run with one guest instruction per emulated TB"},
44ed2fd1
IL
528 {"tb-size", "QEMU_TB_SIZE", true, handle_arg_tb_size,
529 "size", "TCG translation block cache size"},
fc9c5412
JS
530 {"strace", "QEMU_STRACE", false, handle_arg_strace,
531 "", "log system calls"},
5ebdd774 532 {"seed", "QEMU_RAND_SEED", true, handle_arg_seed,
c5e4a5a9 533 "", "Seed for pseudo-random number generator"},
6533dd6e
LV
534 {"trace", "QEMU_TRACE", true, handle_arg_trace,
535 "", "[[enable=]<pattern>][,events=<file>][,file=<file>]"},
f308f64e
LV
536#ifdef CONFIG_PLUGIN
537 {"plugin", "QEMU_PLUGIN", true, handle_arg_plugin,
3a445acb 538 "", "[file=]<file>[,<argname>=<argvalue>]"},
f308f64e 539#endif
fc9c5412 540 {"version", "QEMU_VERSION", false, handle_arg_version,
1386d4c0 541 "", "display version information and exit"},
130ea832
MF
542#if defined(TARGET_XTENSA)
543 {"xtensa-abi-call0", "QEMU_XTENSA_ABI_CALL0", false, handle_arg_abi_call0,
544 "", "assume CALL0 Xtensa ABI"},
545#endif
5584e2db
IL
546 {"perfmap", "QEMU_PERFMAP", false, handle_arg_perfmap,
547 "", "Generate a /tmp/perf-${pid}.map file for perf"},
548 {"jitdump", "QEMU_JITDUMP", false, handle_arg_jitdump,
549 "", "Generate a jit-${pid}.dump file for perf"},
fc9c5412
JS
550 {NULL, NULL, false, NULL, NULL, NULL}
551};
552
d03f9c32 553static void usage(int exitcode)
fc9c5412 554{
42644cee 555 const struct qemu_argument *arginfo;
fc9c5412
JS
556 int maxarglen;
557 int maxenvlen;
558
2e59915d
PB
559 printf("usage: qemu-" TARGET_NAME " [options] program [arguments...]\n"
560 "Linux CPU emulator (compiled for " TARGET_NAME " emulation)\n"
fc9c5412
JS
561 "\n"
562 "Options and associated environment variables:\n"
563 "\n");
564
63ec54d7
PM
565 /* Calculate column widths. We must always have at least enough space
566 * for the column header.
567 */
568 maxarglen = strlen("Argument");
569 maxenvlen = strlen("Env-variable");
fc9c5412
JS
570
571 for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
63ec54d7
PM
572 int arglen = strlen(arginfo->argv);
573 if (arginfo->has_arg) {
574 arglen += strlen(arginfo->example) + 1;
575 }
fc9c5412
JS
576 if (strlen(arginfo->env) > maxenvlen) {
577 maxenvlen = strlen(arginfo->env);
578 }
63ec54d7
PM
579 if (arglen > maxarglen) {
580 maxarglen = arglen;
fc9c5412
JS
581 }
582 }
583
63ec54d7
PM
584 printf("%-*s %-*s Description\n", maxarglen+1, "Argument",
585 maxenvlen, "Env-variable");
fc9c5412
JS
586
587 for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
588 if (arginfo->has_arg) {
589 printf("-%s %-*s %-*s %s\n", arginfo->argv,
63ec54d7
PM
590 (int)(maxarglen - strlen(arginfo->argv) - 1),
591 arginfo->example, maxenvlen, arginfo->env, arginfo->help);
fc9c5412 592 } else {
63ec54d7 593 printf("-%-*s %-*s %s\n", maxarglen, arginfo->argv,
fc9c5412
JS
594 maxenvlen, arginfo->env,
595 arginfo->help);
596 }
597 }
598
599 printf("\n"
600 "Defaults:\n"
601 "QEMU_LD_PREFIX = %s\n"
989b697d 602 "QEMU_STACK_SIZE = %ld byte\n",
fc9c5412 603 interp_prefix,
989b697d 604 guest_stack_size);
fc9c5412
JS
605
606 printf("\n"
607 "You can use -E and -U options or the QEMU_SET_ENV and\n"
608 "QEMU_UNSET_ENV environment variables to set and unset\n"
609 "environment variables for the target process.\n"
610 "It is possible to provide several variables by separating them\n"
611 "by commas in getsubopt(3) style. Additionally it is possible to\n"
612 "provide the -E and -U options multiple times.\n"
613 "The following lines are equivalent:\n"
614 " -E var1=val2 -E var2=val2 -U LD_PRELOAD -U LD_DEBUG\n"
615 " -E var1=val2,var2=val2 -U LD_PRELOAD,LD_DEBUG\n"
616 " QEMU_SET_ENV=var1=val2,var2=val2 QEMU_UNSET_ENV=LD_PRELOAD,LD_DEBUG\n"
617 "Note that if you provide several changes to a single variable\n"
f5048cb7
EB
618 "the last change will stay in effect.\n"
619 "\n"
620 QEMU_HELP_BOTTOM "\n");
fc9c5412 621
d03f9c32 622 exit(exitcode);
fc9c5412
JS
623}
624
625static int parse_args(int argc, char **argv)
626{
627 const char *r;
628 int optind;
42644cee 629 const struct qemu_argument *arginfo;
fc9c5412
JS
630
631 for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
632 if (arginfo->env == NULL) {
633 continue;
634 }
635
636 r = getenv(arginfo->env);
637 if (r != NULL) {
638 arginfo->handle_opt(r);
639 }
640 }
641
642 optind = 1;
643 for (;;) {
644 if (optind >= argc) {
645 break;
646 }
647 r = argv[optind];
648 if (r[0] != '-') {
649 break;
650 }
651 optind++;
652 r++;
653 if (!strcmp(r, "-")) {
654 break;
655 }
ba02577c
MI
656 /* Treat --foo the same as -foo. */
657 if (r[0] == '-') {
658 r++;
659 }
fc9c5412
JS
660
661 for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
662 if (!strcmp(r, arginfo->argv)) {
fc9c5412 663 if (arginfo->has_arg) {
1386d4c0 664 if (optind >= argc) {
138940bf
MI
665 (void) fprintf(stderr,
666 "qemu: missing argument for option '%s'\n", r);
4d1275c2 667 exit(EXIT_FAILURE);
1386d4c0
PM
668 }
669 arginfo->handle_opt(argv[optind]);
fc9c5412 670 optind++;
1386d4c0
PM
671 } else {
672 arginfo->handle_opt(NULL);
fc9c5412 673 }
fc9c5412
JS
674 break;
675 }
676 }
677
678 /* no option matched the current argv */
679 if (arginfo->handle_opt == NULL) {
138940bf 680 (void) fprintf(stderr, "qemu: unknown option '%s'\n", r);
4d1275c2 681 exit(EXIT_FAILURE);
fc9c5412
JS
682 }
683 }
684
685 if (optind >= argc) {
138940bf 686 (void) fprintf(stderr, "qemu: no user program specified\n");
4d1275c2 687 exit(EXIT_FAILURE);
fc9c5412
JS
688 }
689
fc9c5412
JS
690 exec_path = argv[optind];
691
692 return optind;
693}
694
902b3d5c 695int main(int argc, char **argv, char **envp)
31e31b8a 696{
01ffc75b 697 struct target_pt_regs regs1, *regs = &regs1;
31e31b8a 698 struct image_info info1, *info = &info1;
edf8e2af 699 struct linux_binprm bprm;
48e15fc2 700 TaskState *ts;
9349b4f9 701 CPUArchState *env;
db6b81d4 702 CPUState *cpu;
586314f2 703 int optind;
04a6dfeb 704 char **target_environ, **wrk;
7d8cec95
AJ
705 char **target_argv;
706 int target_argc;
7d8cec95 707 int i;
fd4d81dd 708 int ret;
03cfd8fa 709 int execfd;
ff8a8bbc 710 int host_page_size;
8f67b9c6 711 unsigned long max_reserved_va;
6e1c0d7b 712 bool preserve_argv0;
b12b6a18 713
f5852efa 714 error_init(argv[0]);
fe4db84d 715 module_call_init(MODULE_INIT_TRACE);
267f685b 716 qemu_init_cpu_list();
ce008c1f
AF
717 module_call_init(MODULE_INIT_QOM);
718
ec45bbe5 719 envlist = envlist_create();
04a6dfeb 720
7f750efc
AS
721 /*
722 * add current environment into the list
723 * envlist_setenv adds to the front of the list; to preserve environ
724 * order add from back to front
725 */
04a6dfeb 726 for (wrk = environ; *wrk != NULL; wrk++) {
7f750efc
AS
727 continue;
728 }
729 while (wrk != environ) {
730 wrk--;
04a6dfeb
AJ
731 (void) envlist_setenv(envlist, *wrk);
732 }
733
703e0e89
RH
734 /* Read the stack limit from the kernel. If it's "unlimited",
735 then we can do little else besides use the default. */
736 {
737 struct rlimit lim;
738 if (getrlimit(RLIMIT_STACK, &lim) == 0
81bbe906 739 && lim.rlim_cur != RLIM_INFINITY
0a3346b5
HD
740 && lim.rlim_cur == (target_long)lim.rlim_cur
741 && lim.rlim_cur > guest_stack_size) {
703e0e89
RH
742 guest_stack_size = lim.rlim_cur;
743 }
744 }
745
b1f9be31 746 cpu_model = NULL;
b5ec5ce0 747
6533dd6e 748 qemu_add_opts(&qemu_trace_opts);
f308f64e 749 qemu_plugin_add_opts();
6533dd6e 750
fc9c5412 751 optind = parse_args(argc, argv);
586314f2 752
b410253f
RH
753 qemu_set_log_filename_flags(last_log_filename,
754 last_log_mask | (enable_strace * LOG_STRACE),
755 &error_fatal);
4b25a506 756
6533dd6e
LV
757 if (!trace_init_backends()) {
758 exit(1);
759 }
92eecfff 760 trace_init_file();
0572f558 761 qemu_plugin_load_list(&plugins, &error_fatal);
6533dd6e 762
31e31b8a 763 /* Zero out regs */
01ffc75b 764 memset(regs, 0, sizeof(struct target_pt_regs));
31e31b8a
FB
765
766 /* Zero out image_info */
767 memset(info, 0, sizeof(struct image_info));
768
edf8e2af
MW
769 memset(&bprm, 0, sizeof (bprm));
770
74cd30b8
FB
771 /* Scan interp_prefix dir for replacement files. */
772 init_paths(interp_prefix);
773
4a24a758
PM
774 init_qemu_uname_release();
775
6e1c0d7b
LV
776 /*
777 * Manage binfmt-misc open-binary flag
778 */
25268a18 779 errno = 0;
768fe76e 780 execfd = qemu_getauxval(AT_EXECFD);
25268a18 781 if (errno != 0) {
9d3019bc 782 execfd = open(exec_path, O_RDONLY);
768fe76e 783 if (execfd < 0) {
9d3019bc 784 printf("Error while loading %s: %s\n", exec_path, strerror(errno));
768fe76e
YS
785 _exit(EXIT_FAILURE);
786 }
787 }
788
258bec39
HD
789 /* Resolve executable file name to full path name */
790 if (realpath(exec_path, real_exec_path)) {
791 exec_path = real_exec_path;
792 }
793
6e1c0d7b
LV
794 /*
795 * get binfmt_misc flags
796 */
797 preserve_argv0 = !!(qemu_getauxval(AT_FLAGS) & AT_FLAGS_PRESERVE_ARGV0);
798
799 /*
800 * Manage binfmt-misc preserve-arg[0] flag
801 * argv[optind] full path to the binary
802 * argv[optind + 1] original argv[0]
803 */
804 if (optind + 1 < argc && preserve_argv0) {
805 optind++;
806 }
807
46027c07 808 if (cpu_model == NULL) {
768fe76e 809 cpu_model = cpu_get_model(get_elf_eflags(execfd));
aaed909a 810 }
c1c8cfe5 811 cpu_type = parse_cpu_option(cpu_model);
2278b939 812
13c13397 813 /* init tcg before creating CPUs */
940e43aa 814 {
3cfb0456
PM
815 AccelState *accel = current_accel();
816 AccelClass *ac = ACCEL_GET_CLASS(accel);
2278b939 817
b86f59c7 818 accel_init_interfaces(ac);
3cfb0456
PM
819 object_property_set_bool(OBJECT(accel), "one-insn-per-tb",
820 opt_one_insn_per_tb, &error_abort);
44ed2fd1
IL
821 object_property_set_int(OBJECT(accel), "tb-size",
822 opt_tb_size, &error_abort);
51e18961 823 ac->init_machine(accel, NULL);
940e43aa 824 }
ff8a8bbc
RH
825
826 /*
827 * Finalize page size before creating CPUs.
828 * This will do nothing if !TARGET_PAGE_BITS_VARY.
829 * The most efficient setting is to match the host.
830 */
831 host_page_size = qemu_real_host_page_size();
832 set_preferred_target_page_bits(ctz32(host_page_size));
833 finalize_target_page_bits();
834
2278b939 835 cpu = cpu_create(cpu_type);
b77af26e 836 env = cpu_env(cpu);
0ac46af3 837 cpu_reset(cpu);
db6b81d4 838 thread_cpu = cpu;
3b46e624 839
8f67b9c6 840 /*
1b6f1b2e
WL
841 * Reserving too much vm space via mmap can run into problems with rlimits,
842 * oom due to page table creation, etc. We will still try it, if directed
843 * by the command-line option, but not by default. Unless we're running a
844 * target address space of 32 or fewer bits on a host with 64 bits.
8f67b9c6
RH
845 */
846 max_reserved_va = MAX_RESERVED_VA(cpu);
847 if (reserved_va != 0) {
13c13397
RH
848 if ((reserved_va + 1) % host_page_size) {
849 char *s = size_to_str(host_page_size);
2f7828b5
RH
850 fprintf(stderr, "Reserved virtual address not aligned mod %s\n", s);
851 g_free(s);
852 exit(EXIT_FAILURE);
853 }
8f67b9c6
RH
854 if (max_reserved_va && reserved_va > max_reserved_va) {
855 fprintf(stderr, "Reserved virtual address too big\n");
856 exit(EXIT_FAILURE);
857 }
858 } else if (HOST_LONG_BITS == 64 && TARGET_VIRT_ADDR_SPACE_BITS <= 32) {
95059f9c
RH
859 /* MAX_RESERVED_VA + 1 is a large power of 2, so is aligned. */
860 reserved_va = max_reserved_va;
8f67b9c6 861 }
30da4760
RH
862 if (reserved_va != 0) {
863 guest_addr_max = reserved_va;
864 } else if (MIN(TARGET_VIRT_ADDR_SPACE_BITS, TARGET_ABI_BITS) <= 32) {
865 guest_addr_max = UINT32_MAX;
866 } else {
867 guest_addr_max = ~0ul;
868 }
8f67b9c6 869
c8fb5cf9
RH
870 /*
871 * Temporarily disable
872 * "comparison is always false due to limited range of data type"
873 * due to comparison between (possible) uint64_t and uintptr_t.
874 */
875#pragma GCC diagnostic push
876#pragma GCC diagnostic ignored "-Wtype-limits"
f324a03e 877#pragma GCC diagnostic ignored "-Wtautological-compare"
c8fb5cf9
RH
878
879 /*
880 * Select an initial value for task_unmapped_base that is in range.
881 */
882 if (reserved_va) {
883 if (TASK_UNMAPPED_BASE < reserved_va) {
884 task_unmapped_base = TASK_UNMAPPED_BASE;
885 } else {
886 /* The most common default formula is TASK_SIZE / 3. */
887 task_unmapped_base = TARGET_PAGE_ALIGN(reserved_va / 3);
888 }
889 } else if (TASK_UNMAPPED_BASE < UINTPTR_MAX) {
890 task_unmapped_base = TASK_UNMAPPED_BASE;
891 } else {
892 /* 32-bit host: pick something medium size. */
893 task_unmapped_base = 0x10000000;
894 }
895 mmap_next_start = task_unmapped_base;
896
da2b71fa
RH
897 /* Similarly for elf_et_dyn_base. */
898 if (reserved_va) {
899 if (ELF_ET_DYN_BASE < reserved_va) {
900 elf_et_dyn_base = ELF_ET_DYN_BASE;
901 } else {
902 /* The most common default formula is TASK_SIZE / 3 * 2. */
903 elf_et_dyn_base = TARGET_PAGE_ALIGN(reserved_va / 3) * 2;
904 }
905 } else if (ELF_ET_DYN_BASE < UINTPTR_MAX) {
906 elf_et_dyn_base = ELF_ET_DYN_BASE;
907 } else {
908 /* 32-bit host: pick something medium size. */
909 elf_et_dyn_base = 0x18000000;
910 }
911
c8fb5cf9
RH
912#pragma GCC diagnostic pop
913
a573e9ba
RH
914 {
915 Error *err = NULL;
916 if (seed_optarg != NULL) {
a573e9ba
RH
917 qemu_guest_random_seed_main(seed_optarg, &err);
918 } else {
919 qcrypto_init(&err);
920 }
921 if (err) {
922 error_reportf_err(err, "cannot initialize crypto: ");
923 exit(1);
5ebdd774 924 }
c5e4a5a9
MR
925 }
926
04a6dfeb
AJ
927 target_environ = envlist_to_environ(envlist, NULL);
928 envlist_free(envlist);
b12b6a18 929
379f6698
PB
930 /*
931 * Read in mmap_min_addr kernel parameter. This value is used
932 * When loading the ELF image to determine whether guest_base
14f24e14 933 * is needed. It is also used in mmap_find_vma.
379f6698 934 */
14f24e14 935 {
379f6698
PB
936 FILE *fp;
937
938 if ((fp = fopen("/proc/sys/vm/mmap_min_addr", "r")) != NULL) {
939 unsigned long tmp;
c9f80666 940 if (fscanf(fp, "%lu", &tmp) == 1 && tmp != 0) {
78b79b2c 941 mmap_min_addr = MAX(tmp, host_page_size);
c9f80666
RH
942 qemu_log_mask(CPU_LOG_PAGE, "host mmap_min_addr=0x%lx\n",
943 mmap_min_addr);
379f6698
PB
944 }
945 fclose(fp);
946 }
947 }
379f6698 948
c9f80666
RH
949 /*
950 * We prefer to not make NULL pointers accessible to QEMU.
951 * If we're in a chroot with no /proc, fall back to 1 page.
952 */
953 if (mmap_min_addr == 0) {
ff8a8bbc 954 mmap_min_addr = host_page_size;
c9f80666
RH
955 qemu_log_mask(CPU_LOG_PAGE,
956 "host mmap_min_addr=0x%lx (fallback)\n",
957 mmap_min_addr);
958 }
959
7d8cec95
AJ
960 /*
961 * Prepare copy of argv vector for target.
962 */
963 target_argc = argc - optind;
2ee80bce 964 target_argv = g_new0(char *, target_argc + 1);
7d8cec95
AJ
965
966 /*
967 * If argv0 is specified (using '-0' switch) we replace
968 * argv[0] pointer with the given one.
969 */
970 i = 0;
971 if (argv0 != NULL) {
972 target_argv[i++] = strdup(argv0);
973 }
974 for (; i < target_argc; i++) {
975 target_argv[i] = strdup(argv[optind + i]);
976 }
977 target_argv[target_argc] = NULL;
978
c78d65e8 979 ts = g_new0(TaskState, 1);
edf8e2af
MW
980 init_task_state(ts);
981 /* build Task State */
982 ts->info = info;
983 ts->bprm = &bprm;
0429a971 984 cpu->opaque = ts;
edf8e2af
MW
985 task_settid(ts);
986
c093364f
OA
987 fd_trans_init();
988
9d3019bc 989 ret = loader_exec(execfd, exec_path, target_argv, target_environ, regs,
fd4d81dd
AP
990 info, &bprm);
991 if (ret != 0) {
9d3019bc 992 printf("Error while loading %s: %s\n", exec_path, strerror(-ret));
4d1275c2 993 _exit(EXIT_FAILURE);
b12b6a18
TS
994 }
995
996 for (wrk = target_environ; *wrk; wrk++) {
ec45bbe5 997 g_free(*wrk);
31e31b8a 998 }
3b46e624 999
ec45bbe5 1000 g_free(target_environ);
b12b6a18 1001
13829020 1002 if (qemu_loglevel_mask(CPU_LOG_PAGE)) {
93756fdc
RH
1003 FILE *f = qemu_log_trylock();
1004 if (f) {
1005 fprintf(f, "guest_base %p\n", (void *)guest_base);
1006 fprintf(f, "page layout changed following binary load\n");
1007 page_dump(f);
1008
93756fdc
RH
1009 fprintf(f, "end_code 0x" TARGET_ABI_FMT_lx "\n",
1010 info->end_code);
1011 fprintf(f, "start_code 0x" TARGET_ABI_FMT_lx "\n",
1012 info->start_code);
1013 fprintf(f, "start_data 0x" TARGET_ABI_FMT_lx "\n",
1014 info->start_data);
1015 fprintf(f, "end_data 0x" TARGET_ABI_FMT_lx "\n",
1016 info->end_data);
1017 fprintf(f, "start_stack 0x" TARGET_ABI_FMT_lx "\n",
1018 info->start_stack);
1019 fprintf(f, "brk 0x" TARGET_ABI_FMT_lx "\n",
1020 info->brk);
1021 fprintf(f, "entry 0x" TARGET_ABI_FMT_lx "\n",
1022 info->entry);
1023 fprintf(f, "argv_start 0x" TARGET_ABI_FMT_lx "\n",
60f1c801 1024 info->argv);
93756fdc 1025 fprintf(f, "env_start 0x" TARGET_ABI_FMT_lx "\n",
60f1c801 1026 info->envp);
93756fdc
RH
1027 fprintf(f, "auxv_start 0x" TARGET_ABI_FMT_lx "\n",
1028 info->saved_auxv);
1029 qemu_log_unlock(f);
1030 }
2e77eac6 1031 }
31e31b8a 1032
53a5960a 1033 target_set_brk(info->brk);
31e31b8a 1034 syscall_init();
c107521e 1035 signal_init(rtsig_map);
31e31b8a 1036
9002ec79
RH
1037 /* Now that we've loaded the binary, GUEST_BASE is fixed. Delay
1038 generating the prologue until now so that the prologue can take
1039 the real value of GUEST_BASE into account. */
935f75ae 1040 tcg_prologue_init();
9002ec79 1041
cd71c089
LV
1042 target_cpu_copy_regs(env, regs);
1043
fcedd920 1044 if (gdbstub) {
c0e6b8b7 1045 gdbserver_start(gdbstub, &error_fatal);
1fddef4b 1046 }
e4a4aaa5
RH
1047
1048#ifdef CONFIG_SEMIHOSTING
1049 qemu_semihosting_guestfd_init();
1050#endif
1051
1b6b029e
FB
1052 cpu_loop(env);
1053 /* never exits */
31e31b8a
FB
1054 return 0;
1055}