oslib-posix.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. /*
  2. * os-posix-lib.c
  3. *
  4. * Copyright (c) 2003-2008 Fabrice Bellard
  5. * Copyright (c) 2010 Red Hat, Inc.
  6. *
  7. * QEMU library functions on POSIX which are shared between QEMU and
  8. * the QEMU tools.
  9. *
  10. * Permission is hereby granted, free of charge, to any person obtaining a copy
  11. * of this software and associated documentation files (the "Software"), to deal
  12. * in the Software without restriction, including without limitation the rights
  13. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. * copies of the Software, and to permit persons to whom the Software is
  15. * furnished to do so, subject to the following conditions:
  16. *
  17. * The above copyright notice and this permission notice shall be included in
  18. * all copies or substantial portions of the Software.
  19. *
  20. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  23. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26. * THE SOFTWARE.
  27. */
  28. #include "qemu/osdep.h"
  29. #include <termios.h>
  30. #include <glib/gprintf.h>
  31. #include "qemu-common.h"
  32. #include "sysemu/sysemu.h"
  33. #include "trace.h"
  34. #include "qapi/error.h"
  35. #include "qemu/error-report.h"
  36. #include "qemu/madvise.h"
  37. #include "qemu/sockets.h"
  38. #include "qemu/thread.h"
  39. #include <libgen.h>
  40. #include "qemu/cutils.h"
  41. #include "qemu/compiler.h"
  42. #include "qemu/units.h"
  43. #ifdef CONFIG_LINUX
  44. #include <sys/syscall.h>
  45. #endif
  46. #ifdef __FreeBSD__
  47. #include <sys/sysctl.h>
  48. #include <sys/user.h>
  49. #include <sys/thr.h>
  50. #include <libutil.h>
  51. #endif
  52. #ifdef __NetBSD__
  53. #include <sys/sysctl.h>
  54. #include <lwp.h>
  55. #endif
  56. #ifdef __APPLE__
  57. #include <mach-o/dyld.h>
  58. #endif
  59. #ifdef __HAIKU__
  60. #include <kernel/image.h>
  61. #endif
  62. #include "qemu/mmap-alloc.h"
  63. #ifdef CONFIG_DEBUG_STACK_USAGE
  64. #include "qemu/error-report.h"
  65. #endif
  66. #define MAX_MEM_PREALLOC_THREAD_COUNT 16
  67. struct MemsetThread;
  68. typedef struct MemsetContext {
  69. bool all_threads_created;
  70. bool any_thread_failed;
  71. struct MemsetThread *threads;
  72. int num_threads;
  73. } MemsetContext;
  74. struct MemsetThread {
  75. char *addr;
  76. size_t numpages;
  77. size_t hpagesize;
  78. QemuThread pgthread;
  79. sigjmp_buf env;
  80. MemsetContext *context;
  81. };
  82. typedef struct MemsetThread MemsetThread;
  83. /* used by sigbus_handler() */
  84. static MemsetContext *sigbus_memset_context;
  85. struct sigaction sigbus_oldact;
  86. static QemuMutex sigbus_mutex;
  87. static QemuMutex page_mutex;
  88. static QemuCond page_cond;
  89. int qemu_get_thread_id(void)
  90. {
  91. #if defined(__linux__)
  92. return syscall(SYS_gettid);
  93. #elif defined(__FreeBSD__)
  94. /* thread id is up to INT_MAX */
  95. long tid;
  96. thr_self(&tid);
  97. return (int)tid;
  98. #elif defined(__NetBSD__)
  99. return _lwp_self();
  100. #elif defined(__OpenBSD__)
  101. return getthrid();
  102. #else
  103. return getpid();
  104. #endif
  105. }
  106. int qemu_daemon(int nochdir, int noclose)
  107. {
  108. return daemon(nochdir, noclose);
  109. }
  110. bool qemu_write_pidfile(const char *path, Error **errp)
  111. {
  112. int fd;
  113. char pidstr[32];
  114. while (1) {
  115. struct stat a, b;
  116. struct flock lock = {
  117. .l_type = F_WRLCK,
  118. .l_whence = SEEK_SET,
  119. .l_len = 0,
  120. };
  121. fd = qemu_open_old(path, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
  122. if (fd == -1) {
  123. error_setg_errno(errp, errno, "Cannot open pid file");
  124. return false;
  125. }
  126. if (fstat(fd, &b) < 0) {
  127. error_setg_errno(errp, errno, "Cannot stat file");
  128. goto fail_close;
  129. }
  130. if (fcntl(fd, F_SETLK, &lock)) {
  131. error_setg_errno(errp, errno, "Cannot lock pid file");
  132. goto fail_close;
  133. }
  134. /*
  135. * Now make sure the path we locked is the same one that now
  136. * exists on the filesystem.
  137. */
  138. if (stat(path, &a) < 0) {
  139. /*
  140. * PID file disappeared, someone else must be racing with
  141. * us, so try again.
  142. */
  143. close(fd);
  144. continue;
  145. }
  146. if (a.st_ino == b.st_ino) {
  147. break;
  148. }
  149. /*
  150. * PID file was recreated, someone else must be racing with
  151. * us, so try again.
  152. */
  153. close(fd);
  154. }
  155. if (ftruncate(fd, 0) < 0) {
  156. error_setg_errno(errp, errno, "Failed to truncate pid file");
  157. goto fail_unlink;
  158. }
  159. snprintf(pidstr, sizeof(pidstr), FMT_pid "\n", getpid());
  160. if (write(fd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
  161. error_setg(errp, "Failed to write pid file");
  162. goto fail_unlink;
  163. }
  164. return true;
  165. fail_unlink:
  166. unlink(path);
  167. fail_close:
  168. close(fd);
  169. return false;
  170. }
  171. /* alloc shared memory pages */
  172. void *qemu_anon_ram_alloc(size_t size, uint64_t *alignment, bool shared,
  173. bool noreserve)
  174. {
  175. const uint32_t qemu_map_flags = (shared ? QEMU_MAP_SHARED : 0) |
  176. (noreserve ? QEMU_MAP_NORESERVE : 0);
  177. size_t align = QEMU_VMALLOC_ALIGN;
  178. void *ptr = qemu_ram_mmap(-1, size, align, qemu_map_flags, 0);
  179. if (ptr == MAP_FAILED) {
  180. return NULL;
  181. }
  182. if (alignment) {
  183. *alignment = align;
  184. }
  185. trace_qemu_anon_ram_alloc(size, ptr);
  186. return ptr;
  187. }
  188. void qemu_anon_ram_free(void *ptr, size_t size)
  189. {
  190. trace_qemu_anon_ram_free(ptr, size);
  191. qemu_ram_munmap(-1, ptr, size);
  192. }
  193. void qemu_set_block(int fd)
  194. {
  195. int f;
  196. f = fcntl(fd, F_GETFL);
  197. assert(f != -1);
  198. f = fcntl(fd, F_SETFL, f & ~O_NONBLOCK);
  199. assert(f != -1);
  200. }
  201. int qemu_try_set_nonblock(int fd)
  202. {
  203. int f;
  204. f = fcntl(fd, F_GETFL);
  205. if (f == -1) {
  206. return -errno;
  207. }
  208. if (fcntl(fd, F_SETFL, f | O_NONBLOCK) == -1) {
  209. return -errno;
  210. }
  211. return 0;
  212. }
  213. void qemu_set_nonblock(int fd)
  214. {
  215. int f;
  216. f = qemu_try_set_nonblock(fd);
  217. assert(f == 0);
  218. }
  219. int socket_set_fast_reuse(int fd)
  220. {
  221. int val = 1, ret;
  222. ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
  223. (const char *)&val, sizeof(val));
  224. assert(ret == 0);
  225. return ret;
  226. }
  227. void qemu_set_cloexec(int fd)
  228. {
  229. int f;
  230. f = fcntl(fd, F_GETFD);
  231. assert(f != -1);
  232. f = fcntl(fd, F_SETFD, f | FD_CLOEXEC);
  233. assert(f != -1);
  234. }
  235. /*
  236. * Creates a pipe with FD_CLOEXEC set on both file descriptors
  237. */
  238. int qemu_pipe(int pipefd[2])
  239. {
  240. int ret;
  241. #ifdef CONFIG_PIPE2
  242. ret = pipe2(pipefd, O_CLOEXEC);
  243. if (ret != -1 || errno != ENOSYS) {
  244. return ret;
  245. }
  246. #endif
  247. ret = pipe(pipefd);
  248. if (ret == 0) {
  249. qemu_set_cloexec(pipefd[0]);
  250. qemu_set_cloexec(pipefd[1]);
  251. }
  252. return ret;
  253. }
  254. char *
  255. qemu_get_local_state_pathname(const char *relative_pathname)
  256. {
  257. g_autofree char *dir = g_strdup_printf("%s/%s",
  258. CONFIG_QEMU_LOCALSTATEDIR,
  259. relative_pathname);
  260. return get_relocated_path(dir);
  261. }
  262. void qemu_set_tty_echo(int fd, bool echo)
  263. {
  264. struct termios tty;
  265. tcgetattr(fd, &tty);
  266. if (echo) {
  267. tty.c_lflag |= ECHO | ECHONL | ICANON | IEXTEN;
  268. } else {
  269. tty.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
  270. }
  271. tcsetattr(fd, TCSANOW, &tty);
  272. }
  273. static const char *exec_dir;
  274. void qemu_init_exec_dir(const char *argv0)
  275. {
  276. char *p = NULL;
  277. char buf[PATH_MAX];
  278. if (exec_dir) {
  279. return;
  280. }
  281. #if defined(__linux__)
  282. {
  283. int len;
  284. len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
  285. if (len > 0) {
  286. buf[len] = 0;
  287. p = buf;
  288. }
  289. }
  290. #elif defined(__FreeBSD__) \
  291. || (defined(__NetBSD__) && defined(KERN_PROC_PATHNAME))
  292. {
  293. #if defined(__FreeBSD__)
  294. static int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
  295. #else
  296. static int mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
  297. #endif
  298. size_t len = sizeof(buf) - 1;
  299. *buf = '\0';
  300. if (!sysctl(mib, ARRAY_SIZE(mib), buf, &len, NULL, 0) &&
  301. *buf) {
  302. buf[sizeof(buf) - 1] = '\0';
  303. p = buf;
  304. }
  305. }
  306. #elif defined(__APPLE__)
  307. {
  308. char fpath[PATH_MAX];
  309. uint32_t len = sizeof(fpath);
  310. if (_NSGetExecutablePath(fpath, &len) == 0) {
  311. p = realpath(fpath, buf);
  312. if (!p) {
  313. return;
  314. }
  315. }
  316. }
  317. #elif defined(__HAIKU__)
  318. {
  319. image_info ii;
  320. int32_t c = 0;
  321. *buf = '\0';
  322. while (get_next_image_info(0, &c, &ii) == B_OK) {
  323. if (ii.type == B_APP_IMAGE) {
  324. strncpy(buf, ii.name, sizeof(buf));
  325. buf[sizeof(buf) - 1] = 0;
  326. p = buf;
  327. break;
  328. }
  329. }
  330. }
  331. #endif
  332. /* If we don't have any way of figuring out the actual executable
  333. location then try argv[0]. */
  334. if (!p && argv0) {
  335. p = realpath(argv0, buf);
  336. }
  337. if (p) {
  338. exec_dir = g_path_get_dirname(p);
  339. } else {
  340. exec_dir = CONFIG_BINDIR;
  341. }
  342. }
  343. const char *qemu_get_exec_dir(void)
  344. {
  345. return exec_dir;
  346. }
  347. #ifdef CONFIG_LINUX
  348. static void sigbus_handler(int signal, siginfo_t *siginfo, void *ctx)
  349. #else /* CONFIG_LINUX */
  350. static void sigbus_handler(int signal)
  351. #endif /* CONFIG_LINUX */
  352. {
  353. int i;
  354. if (sigbus_memset_context) {
  355. for (i = 0; i < sigbus_memset_context->num_threads; i++) {
  356. MemsetThread *thread = &sigbus_memset_context->threads[i];
  357. if (qemu_thread_is_self(&thread->pgthread)) {
  358. siglongjmp(thread->env, 1);
  359. }
  360. }
  361. }
  362. #ifdef CONFIG_LINUX
  363. /*
  364. * We assume that the MCE SIGBUS handler could have been registered. We
  365. * should never receive BUS_MCEERR_AO on any of our threads, but only on
  366. * the main thread registered for PR_MCE_KILL_EARLY. Further, we should not
  367. * receive BUS_MCEERR_AR triggered by action of other threads on one of
  368. * our threads. So, no need to check for unrelated SIGBUS when seeing one
  369. * for our threads.
  370. *
  371. * We will forward to the MCE handler, which will either handle the SIGBUS
  372. * or reinstall the default SIGBUS handler and reraise the SIGBUS. The
  373. * default SIGBUS handler will crash the process, so we don't care.
  374. */
  375. if (sigbus_oldact.sa_flags & SA_SIGINFO) {
  376. sigbus_oldact.sa_sigaction(signal, siginfo, ctx);
  377. return;
  378. }
  379. #endif /* CONFIG_LINUX */
  380. warn_report("os_mem_prealloc: unrelated SIGBUS detected and ignored");
  381. }
  382. static void *do_touch_pages(void *arg)
  383. {
  384. MemsetThread *memset_args = (MemsetThread *)arg;
  385. sigset_t set, oldset;
  386. int ret = 0;
  387. /*
  388. * On Linux, the page faults from the loop below can cause mmap_sem
  389. * contention with allocation of the thread stacks. Do not start
  390. * clearing until all threads have been created.
  391. */
  392. qemu_mutex_lock(&page_mutex);
  393. while (!memset_args->context->all_threads_created) {
  394. qemu_cond_wait(&page_cond, &page_mutex);
  395. }
  396. qemu_mutex_unlock(&page_mutex);
  397. /* unblock SIGBUS */
  398. sigemptyset(&set);
  399. sigaddset(&set, SIGBUS);
  400. pthread_sigmask(SIG_UNBLOCK, &set, &oldset);
  401. if (sigsetjmp(memset_args->env, 1)) {
  402. ret = -EFAULT;
  403. } else {
  404. char *addr = memset_args->addr;
  405. size_t numpages = memset_args->numpages;
  406. size_t hpagesize = memset_args->hpagesize;
  407. size_t i;
  408. for (i = 0; i < numpages; i++) {
  409. /*
  410. * Read & write back the same value, so we don't
  411. * corrupt existing user/app data that might be
  412. * stored.
  413. *
  414. * 'volatile' to stop compiler optimizing this away
  415. * to a no-op
  416. */
  417. *(volatile char *)addr = *addr;
  418. addr += hpagesize;
  419. }
  420. }
  421. pthread_sigmask(SIG_SETMASK, &oldset, NULL);
  422. return (void *)(uintptr_t)ret;
  423. }
  424. static void *do_madv_populate_write_pages(void *arg)
  425. {
  426. MemsetThread *memset_args = (MemsetThread *)arg;
  427. const size_t size = memset_args->numpages * memset_args->hpagesize;
  428. char * const addr = memset_args->addr;
  429. int ret = 0;
  430. /* See do_touch_pages(). */
  431. qemu_mutex_lock(&page_mutex);
  432. while (!memset_args->context->all_threads_created) {
  433. qemu_cond_wait(&page_cond, &page_mutex);
  434. }
  435. qemu_mutex_unlock(&page_mutex);
  436. if (size && qemu_madvise(addr, size, QEMU_MADV_POPULATE_WRITE)) {
  437. ret = -errno;
  438. }
  439. return (void *)(uintptr_t)ret;
  440. }
  441. static inline int get_memset_num_threads(size_t hpagesize, size_t numpages,
  442. int smp_cpus)
  443. {
  444. long host_procs = sysconf(_SC_NPROCESSORS_ONLN);
  445. int ret = 1;
  446. if (host_procs > 0) {
  447. ret = MIN(MIN(host_procs, MAX_MEM_PREALLOC_THREAD_COUNT), smp_cpus);
  448. }
  449. /* Especially with gigantic pages, don't create more threads than pages. */
  450. ret = MIN(ret, numpages);
  451. /* Don't start threads to prealloc comparatively little memory. */
  452. ret = MIN(ret, MAX(1, hpagesize * numpages / (64 * MiB)));
  453. /* In case sysconf() fails, we fall back to single threaded */
  454. return ret;
  455. }
  456. static int touch_all_pages(char *area, size_t hpagesize, size_t numpages,
  457. int smp_cpus, bool use_madv_populate_write)
  458. {
  459. static gsize initialized = 0;
  460. MemsetContext context = {
  461. .num_threads = get_memset_num_threads(hpagesize, numpages, smp_cpus),
  462. };
  463. size_t numpages_per_thread, leftover;
  464. void *(*touch_fn)(void *);
  465. int ret = 0, i = 0;
  466. char *addr = area;
  467. if (g_once_init_enter(&initialized)) {
  468. qemu_mutex_init(&page_mutex);
  469. qemu_cond_init(&page_cond);
  470. g_once_init_leave(&initialized, 1);
  471. }
  472. if (use_madv_populate_write) {
  473. /* Avoid creating a single thread for MADV_POPULATE_WRITE */
  474. if (context.num_threads == 1) {
  475. if (qemu_madvise(area, hpagesize * numpages,
  476. QEMU_MADV_POPULATE_WRITE)) {
  477. return -errno;
  478. }
  479. return 0;
  480. }
  481. touch_fn = do_madv_populate_write_pages;
  482. } else {
  483. touch_fn = do_touch_pages;
  484. }
  485. context.threads = g_new0(MemsetThread, context.num_threads);
  486. numpages_per_thread = numpages / context.num_threads;
  487. leftover = numpages % context.num_threads;
  488. for (i = 0; i < context.num_threads; i++) {
  489. context.threads[i].addr = addr;
  490. context.threads[i].numpages = numpages_per_thread + (i < leftover);
  491. context.threads[i].hpagesize = hpagesize;
  492. context.threads[i].context = &context;
  493. qemu_thread_create(&context.threads[i].pgthread, "touch_pages",
  494. touch_fn, &context.threads[i],
  495. QEMU_THREAD_JOINABLE);
  496. addr += context.threads[i].numpages * hpagesize;
  497. }
  498. if (!use_madv_populate_write) {
  499. sigbus_memset_context = &context;
  500. }
  501. qemu_mutex_lock(&page_mutex);
  502. context.all_threads_created = true;
  503. qemu_cond_broadcast(&page_cond);
  504. qemu_mutex_unlock(&page_mutex);
  505. for (i = 0; i < context.num_threads; i++) {
  506. int tmp = (uintptr_t)qemu_thread_join(&context.threads[i].pgthread);
  507. if (tmp) {
  508. ret = tmp;
  509. }
  510. }
  511. if (!use_madv_populate_write) {
  512. sigbus_memset_context = NULL;
  513. }
  514. g_free(context.threads);
  515. return ret;
  516. }
  517. static bool madv_populate_write_possible(char *area, size_t pagesize)
  518. {
  519. return !qemu_madvise(area, pagesize, QEMU_MADV_POPULATE_WRITE) ||
  520. errno != EINVAL;
  521. }
  522. void os_mem_prealloc(int fd, char *area, size_t memory, int smp_cpus,
  523. Error **errp)
  524. {
  525. static gsize initialized;
  526. int ret;
  527. size_t hpagesize = qemu_fd_getpagesize(fd);
  528. size_t numpages = DIV_ROUND_UP(memory, hpagesize);
  529. bool use_madv_populate_write;
  530. struct sigaction act;
  531. /*
  532. * Sense on every invocation, as MADV_POPULATE_WRITE cannot be used for
  533. * some special mappings, such as mapping /dev/mem.
  534. */
  535. use_madv_populate_write = madv_populate_write_possible(area, hpagesize);
  536. if (!use_madv_populate_write) {
  537. if (g_once_init_enter(&initialized)) {
  538. qemu_mutex_init(&sigbus_mutex);
  539. g_once_init_leave(&initialized, 1);
  540. }
  541. qemu_mutex_lock(&sigbus_mutex);
  542. memset(&act, 0, sizeof(act));
  543. #ifdef CONFIG_LINUX
  544. act.sa_sigaction = &sigbus_handler;
  545. act.sa_flags = SA_SIGINFO;
  546. #else /* CONFIG_LINUX */
  547. act.sa_handler = &sigbus_handler;
  548. act.sa_flags = 0;
  549. #endif /* CONFIG_LINUX */
  550. ret = sigaction(SIGBUS, &act, &sigbus_oldact);
  551. if (ret) {
  552. qemu_mutex_unlock(&sigbus_mutex);
  553. error_setg_errno(errp, errno,
  554. "os_mem_prealloc: failed to install signal handler");
  555. return;
  556. }
  557. }
  558. /* touch pages simultaneously */
  559. ret = touch_all_pages(area, hpagesize, numpages, smp_cpus,
  560. use_madv_populate_write);
  561. if (ret) {
  562. error_setg_errno(errp, -ret,
  563. "os_mem_prealloc: preallocating memory failed");
  564. }
  565. if (!use_madv_populate_write) {
  566. ret = sigaction(SIGBUS, &sigbus_oldact, NULL);
  567. if (ret) {
  568. /* Terminate QEMU since it can't recover from error */
  569. perror("os_mem_prealloc: failed to reinstall signal handler");
  570. exit(1);
  571. }
  572. qemu_mutex_unlock(&sigbus_mutex);
  573. }
  574. }
  575. char *qemu_get_pid_name(pid_t pid)
  576. {
  577. char *name = NULL;
  578. #if defined(__FreeBSD__)
  579. /* BSDs don't have /proc, but they provide a nice substitute */
  580. struct kinfo_proc *proc = kinfo_getproc(pid);
  581. if (proc) {
  582. name = g_strdup(proc->ki_comm);
  583. free(proc);
  584. }
  585. #else
  586. /* Assume a system with reasonable procfs */
  587. char *pid_path;
  588. size_t len;
  589. pid_path = g_strdup_printf("/proc/%d/cmdline", pid);
  590. g_file_get_contents(pid_path, &name, &len, NULL);
  591. g_free(pid_path);
  592. #endif
  593. return name;
  594. }
  595. pid_t qemu_fork(Error **errp)
  596. {
  597. sigset_t oldmask, newmask;
  598. struct sigaction sig_action;
  599. int saved_errno;
  600. pid_t pid;
  601. /*
  602. * Need to block signals now, so that child process can safely
  603. * kill off caller's signal handlers without a race.
  604. */
  605. sigfillset(&newmask);
  606. if (pthread_sigmask(SIG_SETMASK, &newmask, &oldmask) != 0) {
  607. error_setg_errno(errp, errno,
  608. "cannot block signals");
  609. return -1;
  610. }
  611. pid = fork();
  612. saved_errno = errno;
  613. if (pid < 0) {
  614. /* attempt to restore signal mask, but ignore failure, to
  615. * avoid obscuring the fork failure */
  616. (void)pthread_sigmask(SIG_SETMASK, &oldmask, NULL);
  617. error_setg_errno(errp, saved_errno,
  618. "cannot fork child process");
  619. errno = saved_errno;
  620. return -1;
  621. } else if (pid) {
  622. /* parent process */
  623. /* Restore our original signal mask now that the child is
  624. * safely running. Only documented failures are EFAULT (not
  625. * possible, since we are using just-grabbed mask) or EINVAL
  626. * (not possible, since we are using correct arguments). */
  627. (void)pthread_sigmask(SIG_SETMASK, &oldmask, NULL);
  628. } else {
  629. /* child process */
  630. size_t i;
  631. /* Clear out all signal handlers from parent so nothing
  632. * unexpected can happen in our child once we unblock
  633. * signals */
  634. sig_action.sa_handler = SIG_DFL;
  635. sig_action.sa_flags = 0;
  636. sigemptyset(&sig_action.sa_mask);
  637. for (i = 1; i < NSIG; i++) {
  638. /* Only possible errors are EFAULT or EINVAL The former
  639. * won't happen, the latter we expect, so no need to check
  640. * return value */
  641. (void)sigaction(i, &sig_action, NULL);
  642. }
  643. /* Unmask all signals in child, since we've no idea what the
  644. * caller's done with their signal mask and don't want to
  645. * propagate that to children */
  646. sigemptyset(&newmask);
  647. if (pthread_sigmask(SIG_SETMASK, &newmask, NULL) != 0) {
  648. Error *local_err = NULL;
  649. error_setg_errno(&local_err, errno,
  650. "cannot unblock signals");
  651. error_report_err(local_err);
  652. _exit(1);
  653. }
  654. }
  655. return pid;
  656. }
  657. void *qemu_alloc_stack(size_t *sz)
  658. {
  659. void *ptr, *guardpage;
  660. int flags;
  661. #ifdef CONFIG_DEBUG_STACK_USAGE
  662. void *ptr2;
  663. #endif
  664. size_t pagesz = qemu_real_host_page_size();
  665. #ifdef _SC_THREAD_STACK_MIN
  666. /* avoid stacks smaller than _SC_THREAD_STACK_MIN */
  667. long min_stack_sz = sysconf(_SC_THREAD_STACK_MIN);
  668. *sz = MAX(MAX(min_stack_sz, 0), *sz);
  669. #endif
  670. /* adjust stack size to a multiple of the page size */
  671. *sz = ROUND_UP(*sz, pagesz);
  672. /* allocate one extra page for the guard page */
  673. *sz += pagesz;
  674. flags = MAP_PRIVATE | MAP_ANONYMOUS;
  675. #if defined(MAP_STACK) && defined(__OpenBSD__)
  676. /* Only enable MAP_STACK on OpenBSD. Other OS's such as
  677. * Linux/FreeBSD/NetBSD have a flag with the same name
  678. * but have differing functionality. OpenBSD will SEGV
  679. * if it spots execution with a stack pointer pointing
  680. * at memory that was not allocated with MAP_STACK.
  681. */
  682. flags |= MAP_STACK;
  683. #endif
  684. ptr = mmap(NULL, *sz, PROT_READ | PROT_WRITE, flags, -1, 0);
  685. if (ptr == MAP_FAILED) {
  686. perror("failed to allocate memory for stack");
  687. abort();
  688. }
  689. #if defined(HOST_IA64)
  690. /* separate register stack */
  691. guardpage = ptr + (((*sz - pagesz) / 2) & ~pagesz);
  692. #elif defined(HOST_HPPA)
  693. /* stack grows up */
  694. guardpage = ptr + *sz - pagesz;
  695. #else
  696. /* stack grows down */
  697. guardpage = ptr;
  698. #endif
  699. if (mprotect(guardpage, pagesz, PROT_NONE) != 0) {
  700. perror("failed to set up stack guard page");
  701. abort();
  702. }
  703. #ifdef CONFIG_DEBUG_STACK_USAGE
  704. for (ptr2 = ptr + pagesz; ptr2 < ptr + *sz; ptr2 += sizeof(uint32_t)) {
  705. *(uint32_t *)ptr2 = 0xdeadbeaf;
  706. }
  707. #endif
  708. return ptr;
  709. }
  710. #ifdef CONFIG_DEBUG_STACK_USAGE
  711. static __thread unsigned int max_stack_usage;
  712. #endif
  713. void qemu_free_stack(void *stack, size_t sz)
  714. {
  715. #ifdef CONFIG_DEBUG_STACK_USAGE
  716. unsigned int usage;
  717. void *ptr;
  718. for (ptr = stack + qemu_real_host_page_size(); ptr < stack + sz;
  719. ptr += sizeof(uint32_t)) {
  720. if (*(uint32_t *)ptr != 0xdeadbeaf) {
  721. break;
  722. }
  723. }
  724. usage = sz - (uintptr_t) (ptr - stack);
  725. if (usage > max_stack_usage) {
  726. error_report("thread %d max stack usage increased from %u to %u",
  727. qemu_get_thread_id(), max_stack_usage, usage);
  728. max_stack_usage = usage;
  729. }
  730. #endif
  731. munmap(stack, sz);
  732. }
  733. /*
  734. * Disable CFI checks.
  735. * We are going to call a signal hander directly. Such handler may or may not
  736. * have been defined in our binary, so there's no guarantee that the pointer
  737. * used to set the handler is a cfi-valid pointer. Since the handlers are
  738. * stored in kernel memory, changing the handler to an attacker-defined
  739. * function requires being able to call a sigaction() syscall,
  740. * which is not as easy as overwriting a pointer in memory.
  741. */
  742. QEMU_DISABLE_CFI
  743. void sigaction_invoke(struct sigaction *action,
  744. struct qemu_signalfd_siginfo *info)
  745. {
  746. siginfo_t si = {};
  747. si.si_signo = info->ssi_signo;
  748. si.si_errno = info->ssi_errno;
  749. si.si_code = info->ssi_code;
  750. /* Convert the minimal set of fields defined by POSIX.
  751. * Positive si_code values are reserved for kernel-generated
  752. * signals, where the valid siginfo fields are determined by
  753. * the signal number. But according to POSIX, it is unspecified
  754. * whether SI_USER and SI_QUEUE have values less than or equal to
  755. * zero.
  756. */
  757. if (info->ssi_code == SI_USER || info->ssi_code == SI_QUEUE ||
  758. info->ssi_code <= 0) {
  759. /* SIGTERM, etc. */
  760. si.si_pid = info->ssi_pid;
  761. si.si_uid = info->ssi_uid;
  762. } else if (info->ssi_signo == SIGILL || info->ssi_signo == SIGFPE ||
  763. info->ssi_signo == SIGSEGV || info->ssi_signo == SIGBUS) {
  764. si.si_addr = (void *)(uintptr_t)info->ssi_addr;
  765. } else if (info->ssi_signo == SIGCHLD) {
  766. si.si_pid = info->ssi_pid;
  767. si.si_status = info->ssi_status;
  768. si.si_uid = info->ssi_uid;
  769. }
  770. action->sa_sigaction(info->ssi_signo, &si, NULL);
  771. }
  772. #ifndef HOST_NAME_MAX
  773. # ifdef _POSIX_HOST_NAME_MAX
  774. # define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
  775. # else
  776. # define HOST_NAME_MAX 255
  777. # endif
  778. #endif
  779. char *qemu_get_host_name(Error **errp)
  780. {
  781. long len = -1;
  782. g_autofree char *hostname = NULL;
  783. #ifdef _SC_HOST_NAME_MAX
  784. len = sysconf(_SC_HOST_NAME_MAX);
  785. #endif /* _SC_HOST_NAME_MAX */
  786. if (len < 0) {
  787. len = HOST_NAME_MAX;
  788. }
  789. /* Unfortunately, gethostname() below does not guarantee a
  790. * NULL terminated string. Therefore, allocate one byte more
  791. * to be sure. */
  792. hostname = g_new0(char, len + 1);
  793. if (gethostname(hostname, len) < 0) {
  794. error_setg_errno(errp, errno,
  795. "cannot get hostname");
  796. return NULL;
  797. }
  798. return g_steal_pointer(&hostname);
  799. }
  800. size_t qemu_get_host_physmem(void)
  801. {
  802. #ifdef _SC_PHYS_PAGES
  803. long pages = sysconf(_SC_PHYS_PAGES);
  804. if (pages > 0) {
  805. if (pages > SIZE_MAX / qemu_real_host_page_size()) {
  806. return SIZE_MAX;
  807. } else {
  808. return pages * qemu_real_host_page_size();
  809. }
  810. }
  811. #endif
  812. return 0;
  813. }
  814. /* Sets a specific flag */
  815. int fcntl_setfl(int fd, int flag)
  816. {
  817. int flags;
  818. flags = fcntl(fd, F_GETFL);
  819. if (flags == -1) {
  820. return -errno;
  821. }
  822. if (fcntl(fd, F_SETFL, flags | flag) == -1) {
  823. return -errno;
  824. }
  825. return 0;
  826. }