2
0

main.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. /*
  2. * qemu user main
  3. *
  4. * Copyright (c) 2003-2008 Fabrice Bellard
  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
  17. * along with this program; if not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "qemu/osdep.h"
  20. #include "qemu/help-texts.h"
  21. #include "qemu/units.h"
  22. #include "qemu/accel.h"
  23. #include "qemu-version.h"
  24. #include <sys/syscall.h>
  25. #include <sys/resource.h>
  26. #include <sys/shm.h>
  27. #include <linux/binfmts.h>
  28. #include "qapi/error.h"
  29. #include "qemu.h"
  30. #include "user-internals.h"
  31. #include "qemu/path.h"
  32. #include "qemu/queue.h"
  33. #include "qemu/config-file.h"
  34. #include "qemu/cutils.h"
  35. #include "qemu/error-report.h"
  36. #include "qemu/help_option.h"
  37. #include "qemu/module.h"
  38. #include "qemu/plugin.h"
  39. #include "exec/exec-all.h"
  40. #include "exec/gdbstub.h"
  41. #include "gdbstub/user.h"
  42. #include "tcg/tcg.h"
  43. #include "qemu/timer.h"
  44. #include "qemu/envlist.h"
  45. #include "qemu/guest-random.h"
  46. #include "elf.h"
  47. #include "trace/control.h"
  48. #include "target_elf.h"
  49. #include "cpu_loop-common.h"
  50. #include "crypto/init.h"
  51. #include "fd-trans.h"
  52. #include "signal-common.h"
  53. #include "loader.h"
  54. #include "user-mmap.h"
  55. #include "accel/tcg/perf.h"
  56. #ifdef CONFIG_SEMIHOSTING
  57. #include "semihosting/semihost.h"
  58. #endif
  59. #ifndef AT_FLAGS_PRESERVE_ARGV0
  60. #define AT_FLAGS_PRESERVE_ARGV0_BIT 0
  61. #define AT_FLAGS_PRESERVE_ARGV0 (1 << AT_FLAGS_PRESERVE_ARGV0_BIT)
  62. #endif
  63. char *exec_path;
  64. char real_exec_path[PATH_MAX];
  65. int singlestep;
  66. static const char *argv0;
  67. static const char *gdbstub;
  68. static envlist_t *envlist;
  69. static const char *cpu_model;
  70. static const char *cpu_type;
  71. static const char *seed_optarg;
  72. unsigned long mmap_min_addr;
  73. uintptr_t guest_base;
  74. bool have_guest_base;
  75. /*
  76. * Used to implement backwards-compatibility for the `-strace`, and
  77. * QEMU_STRACE options. Without this, the QEMU_LOG can be overwritten by
  78. * -strace, or vice versa.
  79. */
  80. static bool enable_strace;
  81. /*
  82. * The last log mask given by the user in an environment variable or argument.
  83. * Used to support command line arguments overriding environment variables.
  84. */
  85. static int last_log_mask;
  86. static const char *last_log_filename;
  87. /*
  88. * When running 32-on-64 we should make sure we can fit all of the possible
  89. * guest address space into a contiguous chunk of virtual host memory.
  90. *
  91. * This way we will never overlap with our own libraries or binaries or stack
  92. * or anything else that QEMU maps.
  93. *
  94. * Many cpus reserve the high bit (or more than one for some 64-bit cpus)
  95. * of the address for the kernel. Some cpus rely on this and user space
  96. * uses the high bit(s) for pointer tagging and the like. For them, we
  97. * must preserve the expected address space.
  98. */
  99. #ifndef MAX_RESERVED_VA
  100. # if HOST_LONG_BITS > TARGET_VIRT_ADDR_SPACE_BITS
  101. # if TARGET_VIRT_ADDR_SPACE_BITS == 32 && \
  102. (TARGET_LONG_BITS == 32 || defined(TARGET_ABI32))
  103. # define MAX_RESERVED_VA(CPU) 0xfffffffful
  104. # else
  105. # define MAX_RESERVED_VA(CPU) ((1ul << TARGET_VIRT_ADDR_SPACE_BITS) - 1)
  106. # endif
  107. # else
  108. # define MAX_RESERVED_VA(CPU) 0
  109. # endif
  110. #endif
  111. unsigned long reserved_va;
  112. static void usage(int exitcode);
  113. static const char *interp_prefix = CONFIG_QEMU_INTERP_PREFIX;
  114. const char *qemu_uname_release;
  115. #if !defined(TARGET_DEFAULT_STACK_SIZE)
  116. /* XXX: on x86 MAP_GROWSDOWN only works if ESP <= address + 32, so
  117. we allocate a bigger stack. Need a better solution, for example
  118. by remapping the process stack directly at the right place */
  119. #define TARGET_DEFAULT_STACK_SIZE 8 * 1024 * 1024UL
  120. #endif
  121. unsigned long guest_stack_size = TARGET_DEFAULT_STACK_SIZE;
  122. /***********************************************************/
  123. /* Helper routines for implementing atomic operations. */
  124. /* Make sure everything is in a consistent state for calling fork(). */
  125. void fork_start(void)
  126. {
  127. start_exclusive();
  128. mmap_fork_start();
  129. cpu_list_lock();
  130. qemu_plugin_user_prefork_lock();
  131. }
  132. void fork_end(int child)
  133. {
  134. qemu_plugin_user_postfork(child);
  135. mmap_fork_end(child);
  136. if (child) {
  137. CPUState *cpu, *next_cpu;
  138. /* Child processes created by fork() only have a single thread.
  139. Discard information about the parent threads. */
  140. CPU_FOREACH_SAFE(cpu, next_cpu) {
  141. if (cpu != thread_cpu) {
  142. QTAILQ_REMOVE_RCU(&cpus, cpu, node);
  143. }
  144. }
  145. qemu_init_cpu_list();
  146. gdbserver_fork(thread_cpu);
  147. } else {
  148. cpu_list_unlock();
  149. }
  150. /*
  151. * qemu_init_cpu_list() reinitialized the child exclusive state, but we
  152. * also need to keep current_cpu consistent, so call end_exclusive() for
  153. * both child and parent.
  154. */
  155. end_exclusive();
  156. }
  157. __thread CPUState *thread_cpu;
  158. bool qemu_cpu_is_self(CPUState *cpu)
  159. {
  160. return thread_cpu == cpu;
  161. }
  162. void qemu_cpu_kick(CPUState *cpu)
  163. {
  164. cpu_exit(cpu);
  165. }
  166. void task_settid(TaskState *ts)
  167. {
  168. if (ts->ts_tid == 0) {
  169. ts->ts_tid = (pid_t)syscall(SYS_gettid);
  170. }
  171. }
  172. void stop_all_tasks(void)
  173. {
  174. /*
  175. * We trust that when using NPTL, start_exclusive()
  176. * handles thread stopping correctly.
  177. */
  178. start_exclusive();
  179. }
  180. /* Assumes contents are already zeroed. */
  181. void init_task_state(TaskState *ts)
  182. {
  183. long ticks_per_sec;
  184. struct timespec bt;
  185. ts->used = 1;
  186. ts->sigaltstack_used = (struct target_sigaltstack) {
  187. .ss_sp = 0,
  188. .ss_size = 0,
  189. .ss_flags = TARGET_SS_DISABLE,
  190. };
  191. /* Capture task start time relative to system boot */
  192. ticks_per_sec = sysconf(_SC_CLK_TCK);
  193. if ((ticks_per_sec > 0) && !clock_gettime(CLOCK_BOOTTIME, &bt)) {
  194. /* start_boottime is expressed in clock ticks */
  195. ts->start_boottime = bt.tv_sec * (uint64_t) ticks_per_sec;
  196. ts->start_boottime += bt.tv_nsec * (uint64_t) ticks_per_sec /
  197. NANOSECONDS_PER_SECOND;
  198. }
  199. }
  200. CPUArchState *cpu_copy(CPUArchState *env)
  201. {
  202. CPUState *cpu = env_cpu(env);
  203. CPUState *new_cpu = cpu_create(cpu_type);
  204. CPUArchState *new_env = new_cpu->env_ptr;
  205. CPUBreakpoint *bp;
  206. /* Reset non arch specific state */
  207. cpu_reset(new_cpu);
  208. new_cpu->tcg_cflags = cpu->tcg_cflags;
  209. memcpy(new_env, env, sizeof(CPUArchState));
  210. #if defined(TARGET_I386) || defined(TARGET_X86_64)
  211. new_env->gdt.base = target_mmap(0, sizeof(uint64_t) * TARGET_GDT_ENTRIES,
  212. PROT_READ | PROT_WRITE,
  213. MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  214. memcpy(g2h_untagged(new_env->gdt.base), g2h_untagged(env->gdt.base),
  215. sizeof(uint64_t) * TARGET_GDT_ENTRIES);
  216. OBJECT(new_cpu)->free = OBJECT(cpu)->free;
  217. #endif
  218. /* Clone all break/watchpoints.
  219. Note: Once we support ptrace with hw-debug register access, make sure
  220. BP_CPU break/watchpoints are handled correctly on clone. */
  221. QTAILQ_INIT(&new_cpu->breakpoints);
  222. QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
  223. cpu_breakpoint_insert(new_cpu, bp->pc, bp->flags, NULL);
  224. }
  225. return new_env;
  226. }
  227. static void handle_arg_help(const char *arg)
  228. {
  229. usage(EXIT_SUCCESS);
  230. }
  231. static void handle_arg_log(const char *arg)
  232. {
  233. last_log_mask = qemu_str_to_log_mask(arg);
  234. if (!last_log_mask) {
  235. qemu_print_log_usage(stdout);
  236. exit(EXIT_FAILURE);
  237. }
  238. }
  239. static void handle_arg_dfilter(const char *arg)
  240. {
  241. qemu_set_dfilter_ranges(arg, &error_fatal);
  242. }
  243. static void handle_arg_log_filename(const char *arg)
  244. {
  245. last_log_filename = arg;
  246. }
  247. static void handle_arg_set_env(const char *arg)
  248. {
  249. char *r, *p, *token;
  250. r = p = strdup(arg);
  251. while ((token = strsep(&p, ",")) != NULL) {
  252. if (envlist_setenv(envlist, token) != 0) {
  253. usage(EXIT_FAILURE);
  254. }
  255. }
  256. free(r);
  257. }
  258. static void handle_arg_unset_env(const char *arg)
  259. {
  260. char *r, *p, *token;
  261. r = p = strdup(arg);
  262. while ((token = strsep(&p, ",")) != NULL) {
  263. if (envlist_unsetenv(envlist, token) != 0) {
  264. usage(EXIT_FAILURE);
  265. }
  266. }
  267. free(r);
  268. }
  269. static void handle_arg_argv0(const char *arg)
  270. {
  271. argv0 = strdup(arg);
  272. }
  273. static void handle_arg_stack_size(const char *arg)
  274. {
  275. char *p;
  276. guest_stack_size = strtoul(arg, &p, 0);
  277. if (guest_stack_size == 0) {
  278. usage(EXIT_FAILURE);
  279. }
  280. if (*p == 'M') {
  281. guest_stack_size *= MiB;
  282. } else if (*p == 'k' || *p == 'K') {
  283. guest_stack_size *= KiB;
  284. }
  285. }
  286. static void handle_arg_ld_prefix(const char *arg)
  287. {
  288. interp_prefix = strdup(arg);
  289. }
  290. static void handle_arg_pagesize(const char *arg)
  291. {
  292. qemu_host_page_size = atoi(arg);
  293. if (qemu_host_page_size == 0 ||
  294. (qemu_host_page_size & (qemu_host_page_size - 1)) != 0) {
  295. fprintf(stderr, "page size must be a power of two\n");
  296. exit(EXIT_FAILURE);
  297. }
  298. }
  299. static void handle_arg_seed(const char *arg)
  300. {
  301. seed_optarg = arg;
  302. }
  303. static void handle_arg_gdb(const char *arg)
  304. {
  305. gdbstub = g_strdup(arg);
  306. }
  307. static void handle_arg_uname(const char *arg)
  308. {
  309. qemu_uname_release = strdup(arg);
  310. }
  311. static void handle_arg_cpu(const char *arg)
  312. {
  313. cpu_model = strdup(arg);
  314. if (cpu_model == NULL || is_help_option(cpu_model)) {
  315. /* XXX: implement xxx_cpu_list for targets that still miss it */
  316. #if defined(cpu_list)
  317. cpu_list();
  318. #endif
  319. exit(EXIT_FAILURE);
  320. }
  321. }
  322. static void handle_arg_guest_base(const char *arg)
  323. {
  324. guest_base = strtol(arg, NULL, 0);
  325. have_guest_base = true;
  326. }
  327. static void handle_arg_reserved_va(const char *arg)
  328. {
  329. char *p;
  330. int shift = 0;
  331. unsigned long val;
  332. val = strtoul(arg, &p, 0);
  333. switch (*p) {
  334. case 'k':
  335. case 'K':
  336. shift = 10;
  337. break;
  338. case 'M':
  339. shift = 20;
  340. break;
  341. case 'G':
  342. shift = 30;
  343. break;
  344. }
  345. if (shift) {
  346. unsigned long unshifted = val;
  347. p++;
  348. val <<= shift;
  349. if (val >> shift != unshifted) {
  350. fprintf(stderr, "Reserved virtual address too big\n");
  351. exit(EXIT_FAILURE);
  352. }
  353. }
  354. if (*p) {
  355. fprintf(stderr, "Unrecognised -R size suffix '%s'\n", p);
  356. exit(EXIT_FAILURE);
  357. }
  358. /* The representation is size - 1, with 0 remaining "default". */
  359. reserved_va = val ? val - 1 : 0;
  360. }
  361. static void handle_arg_singlestep(const char *arg)
  362. {
  363. singlestep = 1;
  364. }
  365. static void handle_arg_strace(const char *arg)
  366. {
  367. enable_strace = true;
  368. }
  369. static void handle_arg_version(const char *arg)
  370. {
  371. printf("qemu-" TARGET_NAME " version " QEMU_FULL_VERSION
  372. "\n" QEMU_COPYRIGHT "\n");
  373. exit(EXIT_SUCCESS);
  374. }
  375. static void handle_arg_trace(const char *arg)
  376. {
  377. trace_opt_parse(arg);
  378. }
  379. #if defined(TARGET_XTENSA)
  380. static void handle_arg_abi_call0(const char *arg)
  381. {
  382. xtensa_set_abi_call0();
  383. }
  384. #endif
  385. static void handle_arg_perfmap(const char *arg)
  386. {
  387. perf_enable_perfmap();
  388. }
  389. static void handle_arg_jitdump(const char *arg)
  390. {
  391. perf_enable_jitdump();
  392. }
  393. static QemuPluginList plugins = QTAILQ_HEAD_INITIALIZER(plugins);
  394. #ifdef CONFIG_PLUGIN
  395. static void handle_arg_plugin(const char *arg)
  396. {
  397. qemu_plugin_opt_parse(arg, &plugins);
  398. }
  399. #endif
  400. struct qemu_argument {
  401. const char *argv;
  402. const char *env;
  403. bool has_arg;
  404. void (*handle_opt)(const char *arg);
  405. const char *example;
  406. const char *help;
  407. };
  408. static const struct qemu_argument arg_table[] = {
  409. {"h", "", false, handle_arg_help,
  410. "", "print this help"},
  411. {"help", "", false, handle_arg_help,
  412. "", ""},
  413. {"g", "QEMU_GDB", true, handle_arg_gdb,
  414. "port", "wait gdb connection to 'port'"},
  415. {"L", "QEMU_LD_PREFIX", true, handle_arg_ld_prefix,
  416. "path", "set the elf interpreter prefix to 'path'"},
  417. {"s", "QEMU_STACK_SIZE", true, handle_arg_stack_size,
  418. "size", "set the stack size to 'size' bytes"},
  419. {"cpu", "QEMU_CPU", true, handle_arg_cpu,
  420. "model", "select CPU (-cpu help for list)"},
  421. {"E", "QEMU_SET_ENV", true, handle_arg_set_env,
  422. "var=value", "sets targets environment variable (see below)"},
  423. {"U", "QEMU_UNSET_ENV", true, handle_arg_unset_env,
  424. "var", "unsets targets environment variable (see below)"},
  425. {"0", "QEMU_ARGV0", true, handle_arg_argv0,
  426. "argv0", "forces target process argv[0] to be 'argv0'"},
  427. {"r", "QEMU_UNAME", true, handle_arg_uname,
  428. "uname", "set qemu uname release string to 'uname'"},
  429. {"B", "QEMU_GUEST_BASE", true, handle_arg_guest_base,
  430. "address", "set guest_base address to 'address'"},
  431. {"R", "QEMU_RESERVED_VA", true, handle_arg_reserved_va,
  432. "size", "reserve 'size' bytes for guest virtual address space"},
  433. {"d", "QEMU_LOG", true, handle_arg_log,
  434. "item[,...]", "enable logging of specified items "
  435. "(use '-d help' for a list of items)"},
  436. {"dfilter", "QEMU_DFILTER", true, handle_arg_dfilter,
  437. "range[,...]","filter logging based on address range"},
  438. {"D", "QEMU_LOG_FILENAME", true, handle_arg_log_filename,
  439. "logfile", "write logs to 'logfile' (default stderr)"},
  440. {"p", "QEMU_PAGESIZE", true, handle_arg_pagesize,
  441. "pagesize", "set the host page size to 'pagesize'"},
  442. {"singlestep", "QEMU_SINGLESTEP", false, handle_arg_singlestep,
  443. "", "run in singlestep mode"},
  444. {"strace", "QEMU_STRACE", false, handle_arg_strace,
  445. "", "log system calls"},
  446. {"seed", "QEMU_RAND_SEED", true, handle_arg_seed,
  447. "", "Seed for pseudo-random number generator"},
  448. {"trace", "QEMU_TRACE", true, handle_arg_trace,
  449. "", "[[enable=]<pattern>][,events=<file>][,file=<file>]"},
  450. #ifdef CONFIG_PLUGIN
  451. {"plugin", "QEMU_PLUGIN", true, handle_arg_plugin,
  452. "", "[file=]<file>[,<argname>=<argvalue>]"},
  453. #endif
  454. {"version", "QEMU_VERSION", false, handle_arg_version,
  455. "", "display version information and exit"},
  456. #if defined(TARGET_XTENSA)
  457. {"xtensa-abi-call0", "QEMU_XTENSA_ABI_CALL0", false, handle_arg_abi_call0,
  458. "", "assume CALL0 Xtensa ABI"},
  459. #endif
  460. {"perfmap", "QEMU_PERFMAP", false, handle_arg_perfmap,
  461. "", "Generate a /tmp/perf-${pid}.map file for perf"},
  462. {"jitdump", "QEMU_JITDUMP", false, handle_arg_jitdump,
  463. "", "Generate a jit-${pid}.dump file for perf"},
  464. {NULL, NULL, false, NULL, NULL, NULL}
  465. };
  466. static void usage(int exitcode)
  467. {
  468. const struct qemu_argument *arginfo;
  469. int maxarglen;
  470. int maxenvlen;
  471. printf("usage: qemu-" TARGET_NAME " [options] program [arguments...]\n"
  472. "Linux CPU emulator (compiled for " TARGET_NAME " emulation)\n"
  473. "\n"
  474. "Options and associated environment variables:\n"
  475. "\n");
  476. /* Calculate column widths. We must always have at least enough space
  477. * for the column header.
  478. */
  479. maxarglen = strlen("Argument");
  480. maxenvlen = strlen("Env-variable");
  481. for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
  482. int arglen = strlen(arginfo->argv);
  483. if (arginfo->has_arg) {
  484. arglen += strlen(arginfo->example) + 1;
  485. }
  486. if (strlen(arginfo->env) > maxenvlen) {
  487. maxenvlen = strlen(arginfo->env);
  488. }
  489. if (arglen > maxarglen) {
  490. maxarglen = arglen;
  491. }
  492. }
  493. printf("%-*s %-*s Description\n", maxarglen+1, "Argument",
  494. maxenvlen, "Env-variable");
  495. for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
  496. if (arginfo->has_arg) {
  497. printf("-%s %-*s %-*s %s\n", arginfo->argv,
  498. (int)(maxarglen - strlen(arginfo->argv) - 1),
  499. arginfo->example, maxenvlen, arginfo->env, arginfo->help);
  500. } else {
  501. printf("-%-*s %-*s %s\n", maxarglen, arginfo->argv,
  502. maxenvlen, arginfo->env,
  503. arginfo->help);
  504. }
  505. }
  506. printf("\n"
  507. "Defaults:\n"
  508. "QEMU_LD_PREFIX = %s\n"
  509. "QEMU_STACK_SIZE = %ld byte\n",
  510. interp_prefix,
  511. guest_stack_size);
  512. printf("\n"
  513. "You can use -E and -U options or the QEMU_SET_ENV and\n"
  514. "QEMU_UNSET_ENV environment variables to set and unset\n"
  515. "environment variables for the target process.\n"
  516. "It is possible to provide several variables by separating them\n"
  517. "by commas in getsubopt(3) style. Additionally it is possible to\n"
  518. "provide the -E and -U options multiple times.\n"
  519. "The following lines are equivalent:\n"
  520. " -E var1=val2 -E var2=val2 -U LD_PRELOAD -U LD_DEBUG\n"
  521. " -E var1=val2,var2=val2 -U LD_PRELOAD,LD_DEBUG\n"
  522. " QEMU_SET_ENV=var1=val2,var2=val2 QEMU_UNSET_ENV=LD_PRELOAD,LD_DEBUG\n"
  523. "Note that if you provide several changes to a single variable\n"
  524. "the last change will stay in effect.\n"
  525. "\n"
  526. QEMU_HELP_BOTTOM "\n");
  527. exit(exitcode);
  528. }
  529. static int parse_args(int argc, char **argv)
  530. {
  531. const char *r;
  532. int optind;
  533. const struct qemu_argument *arginfo;
  534. for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
  535. if (arginfo->env == NULL) {
  536. continue;
  537. }
  538. r = getenv(arginfo->env);
  539. if (r != NULL) {
  540. arginfo->handle_opt(r);
  541. }
  542. }
  543. optind = 1;
  544. for (;;) {
  545. if (optind >= argc) {
  546. break;
  547. }
  548. r = argv[optind];
  549. if (r[0] != '-') {
  550. break;
  551. }
  552. optind++;
  553. r++;
  554. if (!strcmp(r, "-")) {
  555. break;
  556. }
  557. /* Treat --foo the same as -foo. */
  558. if (r[0] == '-') {
  559. r++;
  560. }
  561. for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {
  562. if (!strcmp(r, arginfo->argv)) {
  563. if (arginfo->has_arg) {
  564. if (optind >= argc) {
  565. (void) fprintf(stderr,
  566. "qemu: missing argument for option '%s'\n", r);
  567. exit(EXIT_FAILURE);
  568. }
  569. arginfo->handle_opt(argv[optind]);
  570. optind++;
  571. } else {
  572. arginfo->handle_opt(NULL);
  573. }
  574. break;
  575. }
  576. }
  577. /* no option matched the current argv */
  578. if (arginfo->handle_opt == NULL) {
  579. (void) fprintf(stderr, "qemu: unknown option '%s'\n", r);
  580. exit(EXIT_FAILURE);
  581. }
  582. }
  583. if (optind >= argc) {
  584. (void) fprintf(stderr, "qemu: no user program specified\n");
  585. exit(EXIT_FAILURE);
  586. }
  587. exec_path = argv[optind];
  588. return optind;
  589. }
  590. int main(int argc, char **argv, char **envp)
  591. {
  592. struct target_pt_regs regs1, *regs = &regs1;
  593. struct image_info info1, *info = &info1;
  594. struct linux_binprm bprm;
  595. TaskState *ts;
  596. CPUArchState *env;
  597. CPUState *cpu;
  598. int optind;
  599. char **target_environ, **wrk;
  600. char **target_argv;
  601. int target_argc;
  602. int i;
  603. int ret;
  604. int execfd;
  605. unsigned long max_reserved_va;
  606. bool preserve_argv0;
  607. error_init(argv[0]);
  608. module_call_init(MODULE_INIT_TRACE);
  609. qemu_init_cpu_list();
  610. module_call_init(MODULE_INIT_QOM);
  611. envlist = envlist_create();
  612. /* add current environment into the list */
  613. for (wrk = environ; *wrk != NULL; wrk++) {
  614. (void) envlist_setenv(envlist, *wrk);
  615. }
  616. /* Read the stack limit from the kernel. If it's "unlimited",
  617. then we can do little else besides use the default. */
  618. {
  619. struct rlimit lim;
  620. if (getrlimit(RLIMIT_STACK, &lim) == 0
  621. && lim.rlim_cur != RLIM_INFINITY
  622. && lim.rlim_cur == (target_long)lim.rlim_cur
  623. && lim.rlim_cur > guest_stack_size) {
  624. guest_stack_size = lim.rlim_cur;
  625. }
  626. }
  627. cpu_model = NULL;
  628. qemu_add_opts(&qemu_trace_opts);
  629. qemu_plugin_add_opts();
  630. optind = parse_args(argc, argv);
  631. qemu_set_log_filename_flags(last_log_filename,
  632. last_log_mask | (enable_strace * LOG_STRACE),
  633. &error_fatal);
  634. if (!trace_init_backends()) {
  635. exit(1);
  636. }
  637. trace_init_file();
  638. qemu_plugin_load_list(&plugins, &error_fatal);
  639. /* Zero out regs */
  640. memset(regs, 0, sizeof(struct target_pt_regs));
  641. /* Zero out image_info */
  642. memset(info, 0, sizeof(struct image_info));
  643. memset(&bprm, 0, sizeof (bprm));
  644. /* Scan interp_prefix dir for replacement files. */
  645. init_paths(interp_prefix);
  646. init_qemu_uname_release();
  647. /*
  648. * Manage binfmt-misc open-binary flag
  649. */
  650. execfd = qemu_getauxval(AT_EXECFD);
  651. if (execfd == 0) {
  652. execfd = open(exec_path, O_RDONLY);
  653. if (execfd < 0) {
  654. printf("Error while loading %s: %s\n", exec_path, strerror(errno));
  655. _exit(EXIT_FAILURE);
  656. }
  657. }
  658. /* Resolve executable file name to full path name */
  659. if (realpath(exec_path, real_exec_path)) {
  660. exec_path = real_exec_path;
  661. }
  662. /*
  663. * get binfmt_misc flags
  664. */
  665. preserve_argv0 = !!(qemu_getauxval(AT_FLAGS) & AT_FLAGS_PRESERVE_ARGV0);
  666. /*
  667. * Manage binfmt-misc preserve-arg[0] flag
  668. * argv[optind] full path to the binary
  669. * argv[optind + 1] original argv[0]
  670. */
  671. if (optind + 1 < argc && preserve_argv0) {
  672. optind++;
  673. }
  674. if (cpu_model == NULL) {
  675. cpu_model = cpu_get_model(get_elf_eflags(execfd));
  676. }
  677. cpu_type = parse_cpu_option(cpu_model);
  678. /* init tcg before creating CPUs and to get qemu_host_page_size */
  679. {
  680. AccelClass *ac = ACCEL_GET_CLASS(current_accel());
  681. accel_init_interfaces(ac);
  682. ac->init_machine(NULL);
  683. }
  684. cpu = cpu_create(cpu_type);
  685. env = cpu->env_ptr;
  686. cpu_reset(cpu);
  687. thread_cpu = cpu;
  688. /*
  689. * Reserving too much vm space via mmap can run into problems
  690. * with rlimits, oom due to page table creation, etc. We will
  691. * still try it, if directed by the command-line option, but
  692. * not by default.
  693. */
  694. max_reserved_va = MAX_RESERVED_VA(cpu);
  695. if (reserved_va != 0) {
  696. if ((reserved_va + 1) % qemu_host_page_size) {
  697. char *s = size_to_str(qemu_host_page_size);
  698. fprintf(stderr, "Reserved virtual address not aligned mod %s\n", s);
  699. g_free(s);
  700. exit(EXIT_FAILURE);
  701. }
  702. if (max_reserved_va && reserved_va > max_reserved_va) {
  703. fprintf(stderr, "Reserved virtual address too big\n");
  704. exit(EXIT_FAILURE);
  705. }
  706. } else if (HOST_LONG_BITS == 64 && TARGET_VIRT_ADDR_SPACE_BITS <= 32) {
  707. /* MAX_RESERVED_VA + 1 is a large power of 2, so is aligned. */
  708. reserved_va = max_reserved_va;
  709. }
  710. {
  711. Error *err = NULL;
  712. if (seed_optarg != NULL) {
  713. qemu_guest_random_seed_main(seed_optarg, &err);
  714. } else {
  715. qcrypto_init(&err);
  716. }
  717. if (err) {
  718. error_reportf_err(err, "cannot initialize crypto: ");
  719. exit(1);
  720. }
  721. }
  722. target_environ = envlist_to_environ(envlist, NULL);
  723. envlist_free(envlist);
  724. /*
  725. * Read in mmap_min_addr kernel parameter. This value is used
  726. * When loading the ELF image to determine whether guest_base
  727. * is needed. It is also used in mmap_find_vma.
  728. */
  729. {
  730. FILE *fp;
  731. if ((fp = fopen("/proc/sys/vm/mmap_min_addr", "r")) != NULL) {
  732. unsigned long tmp;
  733. if (fscanf(fp, "%lu", &tmp) == 1 && tmp != 0) {
  734. mmap_min_addr = tmp;
  735. qemu_log_mask(CPU_LOG_PAGE, "host mmap_min_addr=0x%lx\n",
  736. mmap_min_addr);
  737. }
  738. fclose(fp);
  739. }
  740. }
  741. /*
  742. * We prefer to not make NULL pointers accessible to QEMU.
  743. * If we're in a chroot with no /proc, fall back to 1 page.
  744. */
  745. if (mmap_min_addr == 0) {
  746. mmap_min_addr = qemu_host_page_size;
  747. qemu_log_mask(CPU_LOG_PAGE,
  748. "host mmap_min_addr=0x%lx (fallback)\n",
  749. mmap_min_addr);
  750. }
  751. /*
  752. * Prepare copy of argv vector for target.
  753. */
  754. target_argc = argc - optind;
  755. target_argv = calloc(target_argc + 1, sizeof (char *));
  756. if (target_argv == NULL) {
  757. (void) fprintf(stderr, "Unable to allocate memory for target_argv\n");
  758. exit(EXIT_FAILURE);
  759. }
  760. /*
  761. * If argv0 is specified (using '-0' switch) we replace
  762. * argv[0] pointer with the given one.
  763. */
  764. i = 0;
  765. if (argv0 != NULL) {
  766. target_argv[i++] = strdup(argv0);
  767. }
  768. for (; i < target_argc; i++) {
  769. target_argv[i] = strdup(argv[optind + i]);
  770. }
  771. target_argv[target_argc] = NULL;
  772. ts = g_new0(TaskState, 1);
  773. init_task_state(ts);
  774. /* build Task State */
  775. ts->info = info;
  776. ts->bprm = &bprm;
  777. cpu->opaque = ts;
  778. task_settid(ts);
  779. fd_trans_init();
  780. ret = loader_exec(execfd, exec_path, target_argv, target_environ, regs,
  781. info, &bprm);
  782. if (ret != 0) {
  783. printf("Error while loading %s: %s\n", exec_path, strerror(-ret));
  784. _exit(EXIT_FAILURE);
  785. }
  786. for (wrk = target_environ; *wrk; wrk++) {
  787. g_free(*wrk);
  788. }
  789. g_free(target_environ);
  790. if (qemu_loglevel_mask(CPU_LOG_PAGE)) {
  791. FILE *f = qemu_log_trylock();
  792. if (f) {
  793. fprintf(f, "guest_base %p\n", (void *)guest_base);
  794. fprintf(f, "page layout changed following binary load\n");
  795. page_dump(f);
  796. fprintf(f, "start_brk 0x" TARGET_ABI_FMT_lx "\n",
  797. info->start_brk);
  798. fprintf(f, "end_code 0x" TARGET_ABI_FMT_lx "\n",
  799. info->end_code);
  800. fprintf(f, "start_code 0x" TARGET_ABI_FMT_lx "\n",
  801. info->start_code);
  802. fprintf(f, "start_data 0x" TARGET_ABI_FMT_lx "\n",
  803. info->start_data);
  804. fprintf(f, "end_data 0x" TARGET_ABI_FMT_lx "\n",
  805. info->end_data);
  806. fprintf(f, "start_stack 0x" TARGET_ABI_FMT_lx "\n",
  807. info->start_stack);
  808. fprintf(f, "brk 0x" TARGET_ABI_FMT_lx "\n",
  809. info->brk);
  810. fprintf(f, "entry 0x" TARGET_ABI_FMT_lx "\n",
  811. info->entry);
  812. fprintf(f, "argv_start 0x" TARGET_ABI_FMT_lx "\n",
  813. info->argv);
  814. fprintf(f, "env_start 0x" TARGET_ABI_FMT_lx "\n",
  815. info->envp);
  816. fprintf(f, "auxv_start 0x" TARGET_ABI_FMT_lx "\n",
  817. info->saved_auxv);
  818. qemu_log_unlock(f);
  819. }
  820. }
  821. target_set_brk(info->brk);
  822. syscall_init();
  823. signal_init();
  824. /* Now that we've loaded the binary, GUEST_BASE is fixed. Delay
  825. generating the prologue until now so that the prologue can take
  826. the real value of GUEST_BASE into account. */
  827. tcg_prologue_init(tcg_ctx);
  828. target_cpu_copy_regs(env, regs);
  829. if (gdbstub) {
  830. if (gdbserver_start(gdbstub) < 0) {
  831. fprintf(stderr, "qemu: could not open gdbserver on %s\n",
  832. gdbstub);
  833. exit(EXIT_FAILURE);
  834. }
  835. gdb_handlesig(cpu, 0);
  836. }
  837. #ifdef CONFIG_SEMIHOSTING
  838. qemu_semihosting_guestfd_init();
  839. #endif
  840. cpu_loop(env);
  841. /* never exits */
  842. return 0;
  843. }