main.c 19 KB

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