main.c 19 KB

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