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