main.c 19 KB

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