/js/src/ctypes/libffi/src/closures.c

http://github.com/zpao/v8monkey · C · 610 lines · 397 code · 108 blank · 105 comment · 104 complexity · 141ecb0f7d4c7abf4f3ed2b6374bd632 MD5 · raw file

  1. /* -----------------------------------------------------------------------
  2. closures.c - Copyright (c) 2007 Red Hat, Inc.
  3. Copyright (C) 2007, 2009 Free Software Foundation, Inc
  4. Code to allocate and deallocate memory for closures.
  5. Permission is hereby granted, free of charge, to any person obtaining
  6. a copy of this software and associated documentation files (the
  7. ``Software''), to deal in the Software without restriction, including
  8. without limitation the rights to use, copy, modify, merge, publish,
  9. distribute, sublicense, and/or sell copies of the Software, and to
  10. permit persons to whom the Software is furnished to do so, subject to
  11. the following conditions:
  12. The above copyright notice and this permission notice shall be included
  13. in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  21. DEALINGS IN THE SOFTWARE.
  22. ----------------------------------------------------------------------- */
  23. #if defined __linux__ && !defined _GNU_SOURCE
  24. #define _GNU_SOURCE 1
  25. #endif
  26. #include <ffi.h>
  27. #include <ffi_common.h>
  28. #ifndef FFI_MMAP_EXEC_WRIT
  29. # if __gnu_linux__
  30. /* This macro indicates it may be forbidden to map anonymous memory
  31. with both write and execute permission. Code compiled when this
  32. option is defined will attempt to map such pages once, but if it
  33. fails, it falls back to creating a temporary file in a writable and
  34. executable filesystem and mapping pages from it into separate
  35. locations in the virtual memory space, one location writable and
  36. another executable. */
  37. # define FFI_MMAP_EXEC_WRIT 1
  38. # define HAVE_MNTENT 1
  39. # endif
  40. # if defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__)
  41. /* Windows systems may have Data Execution Protection (DEP) enabled,
  42. which requires the use of VirtualMalloc/VirtualFree to alloc/free
  43. executable memory. */
  44. # define FFI_MMAP_EXEC_WRIT 1
  45. # endif
  46. #endif
  47. #if FFI_MMAP_EXEC_WRIT && !defined FFI_MMAP_EXEC_SELINUX
  48. # ifdef __linux__
  49. /* When defined to 1 check for SELinux and if SELinux is active,
  50. don't attempt PROT_EXEC|PROT_WRITE mapping at all, as that
  51. might cause audit messages. */
  52. # define FFI_MMAP_EXEC_SELINUX 1
  53. # endif
  54. #endif
  55. #if FFI_CLOSURES
  56. # if FFI_MMAP_EXEC_WRIT
  57. #define USE_LOCKS 1
  58. #define USE_DL_PREFIX 1
  59. #ifdef __GNUC__
  60. #ifndef USE_BUILTIN_FFS
  61. #define USE_BUILTIN_FFS 1
  62. #endif
  63. #endif
  64. /* We need to use mmap, not sbrk. */
  65. #define HAVE_MORECORE 0
  66. /* We could, in theory, support mremap, but it wouldn't buy us anything. */
  67. #define HAVE_MREMAP 0
  68. /* We have no use for this, so save some code and data. */
  69. #define NO_MALLINFO 1
  70. /* We need all allocations to be in regular segments, otherwise we
  71. lose track of the corresponding code address. */
  72. #define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
  73. /* Don't allocate more than a page unless needed. */
  74. #define DEFAULT_GRANULARITY ((size_t)malloc_getpagesize)
  75. #if FFI_CLOSURE_TEST
  76. /* Don't release single pages, to avoid a worst-case scenario of
  77. continuously allocating and releasing single pages, but release
  78. pairs of pages, which should do just as well given that allocations
  79. are likely to be small. */
  80. #define DEFAULT_TRIM_THRESHOLD ((size_t)malloc_getpagesize)
  81. #endif
  82. #include <sys/types.h>
  83. #include <sys/stat.h>
  84. #include <fcntl.h>
  85. #include <errno.h>
  86. #ifndef _MSC_VER
  87. #include <unistd.h>
  88. #endif
  89. #include <string.h>
  90. #include <stdio.h>
  91. #if !defined(X86_WIN32) && !defined(X86_WIN64)
  92. #ifdef HAVE_MNTENT
  93. #include <mntent.h>
  94. #endif /* HAVE_MNTENT */
  95. #include <sys/param.h>
  96. #include <pthread.h>
  97. /* We don't want sys/mman.h to be included after we redefine mmap and
  98. dlmunmap. */
  99. #include <sys/mman.h>
  100. #define LACKS_SYS_MMAN_H 1
  101. #if FFI_MMAP_EXEC_SELINUX
  102. #include <sys/statfs.h>
  103. #include <stdlib.h>
  104. static int selinux_enabled = -1;
  105. static int
  106. selinux_enabled_check (void)
  107. {
  108. struct statfs sfs;
  109. FILE *f;
  110. char *buf = NULL;
  111. size_t len = 0;
  112. if (statfs ("/selinux", &sfs) >= 0
  113. && (unsigned int) sfs.f_type == 0xf97cff8cU)
  114. return 1;
  115. f = fopen ("/proc/mounts", "r");
  116. if (f == NULL)
  117. return 0;
  118. while (getline (&buf, &len, f) >= 0)
  119. {
  120. char *p = strchr (buf, ' ');
  121. if (p == NULL)
  122. break;
  123. p = strchr (p + 1, ' ');
  124. if (p == NULL)
  125. break;
  126. if (strncmp (p + 1, "selinuxfs ", 10) == 0)
  127. {
  128. free (buf);
  129. fclose (f);
  130. return 1;
  131. }
  132. }
  133. free (buf);
  134. fclose (f);
  135. return 0;
  136. }
  137. #define is_selinux_enabled() (selinux_enabled >= 0 ? selinux_enabled \
  138. : (selinux_enabled = selinux_enabled_check ()))
  139. #else
  140. #define is_selinux_enabled() 0
  141. #endif /* !FFI_MMAP_EXEC_SELINUX */
  142. #elif defined (__CYGWIN__)
  143. #include <sys/mman.h>
  144. /* Cygwin is Linux-like, but not quite that Linux-like. */
  145. #define is_selinux_enabled() 0
  146. #endif /* !defined(X86_WIN32) && !defined(X86_WIN64) */
  147. /* Declare all functions defined in dlmalloc.c as static. */
  148. static void *dlmalloc(size_t);
  149. static void dlfree(void*);
  150. static void *dlcalloc(size_t, size_t) MAYBE_UNUSED;
  151. static void *dlrealloc(void *, size_t) MAYBE_UNUSED;
  152. static void *dlmemalign(size_t, size_t) MAYBE_UNUSED;
  153. static void *dlvalloc(size_t) MAYBE_UNUSED;
  154. static int dlmallopt(int, int) MAYBE_UNUSED;
  155. static size_t dlmalloc_footprint(void) MAYBE_UNUSED;
  156. static size_t dlmalloc_max_footprint(void) MAYBE_UNUSED;
  157. static void** dlindependent_calloc(size_t, size_t, void**) MAYBE_UNUSED;
  158. static void** dlindependent_comalloc(size_t, size_t*, void**) MAYBE_UNUSED;
  159. static void *dlpvalloc(size_t) MAYBE_UNUSED;
  160. static int dlmalloc_trim(size_t) MAYBE_UNUSED;
  161. static size_t dlmalloc_usable_size(void*) MAYBE_UNUSED;
  162. static void dlmalloc_stats(void) MAYBE_UNUSED;
  163. #if !(defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__)) || defined (__CYGWIN__)
  164. /* Use these for mmap and munmap within dlmalloc.c. */
  165. static void *dlmmap(void *, size_t, int, int, int, off_t);
  166. static int dlmunmap(void *, size_t);
  167. #endif /* !(defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__)) || defined (__CYGWIN__) */
  168. #define mmap dlmmap
  169. #define munmap dlmunmap
  170. #include "dlmalloc.c"
  171. #undef mmap
  172. #undef munmap
  173. #if !(defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__)) || defined (__CYGWIN__)
  174. /* A mutex used to synchronize access to *exec* variables in this file. */
  175. static pthread_mutex_t open_temp_exec_file_mutex = PTHREAD_MUTEX_INITIALIZER;
  176. /* A file descriptor of a temporary file from which we'll map
  177. executable pages. */
  178. static int execfd = -1;
  179. /* The amount of space already allocated from the temporary file. */
  180. static size_t execsize = 0;
  181. /* Open a temporary file name, and immediately unlink it. */
  182. static int
  183. open_temp_exec_file_name (char *name)
  184. {
  185. int fd = mkstemp (name);
  186. if (fd != -1)
  187. unlink (name);
  188. return fd;
  189. }
  190. /* Open a temporary file in the named directory. */
  191. static int
  192. open_temp_exec_file_dir (const char *dir)
  193. {
  194. static const char suffix[] = "/ffiXXXXXX";
  195. int lendir = strlen (dir);
  196. char *tempname = __builtin_alloca (lendir + sizeof (suffix));
  197. if (!tempname)
  198. return -1;
  199. memcpy (tempname, dir, lendir);
  200. memcpy (tempname + lendir, suffix, sizeof (suffix));
  201. return open_temp_exec_file_name (tempname);
  202. }
  203. /* Open a temporary file in the directory in the named environment
  204. variable. */
  205. static int
  206. open_temp_exec_file_env (const char *envvar)
  207. {
  208. const char *value = getenv (envvar);
  209. if (!value)
  210. return -1;
  211. return open_temp_exec_file_dir (value);
  212. }
  213. #ifdef HAVE_MNTENT
  214. /* Open a temporary file in an executable and writable mount point
  215. listed in the mounts file. Subsequent calls with the same mounts
  216. keep searching for mount points in the same file. Providing NULL
  217. as the mounts file closes the file. */
  218. static int
  219. open_temp_exec_file_mnt (const char *mounts)
  220. {
  221. static const char *last_mounts;
  222. static FILE *last_mntent;
  223. if (mounts != last_mounts)
  224. {
  225. if (last_mntent)
  226. endmntent (last_mntent);
  227. last_mounts = mounts;
  228. if (mounts)
  229. last_mntent = setmntent (mounts, "r");
  230. else
  231. last_mntent = NULL;
  232. }
  233. if (!last_mntent)
  234. return -1;
  235. for (;;)
  236. {
  237. int fd;
  238. struct mntent mnt;
  239. char buf[MAXPATHLEN * 3];
  240. if (getmntent_r (last_mntent, &mnt, buf, sizeof (buf)))
  241. return -1;
  242. if (hasmntopt (&mnt, "ro")
  243. || hasmntopt (&mnt, "noexec")
  244. || access (mnt.mnt_dir, W_OK))
  245. continue;
  246. fd = open_temp_exec_file_dir (mnt.mnt_dir);
  247. if (fd != -1)
  248. return fd;
  249. }
  250. }
  251. #endif /* HAVE_MNTENT */
  252. /* Instructions to look for a location to hold a temporary file that
  253. can be mapped in for execution. */
  254. static struct
  255. {
  256. int (*func)(const char *);
  257. const char *arg;
  258. int repeat;
  259. } open_temp_exec_file_opts[] = {
  260. { open_temp_exec_file_env, "TMPDIR", 0 },
  261. { open_temp_exec_file_dir, "/tmp", 0 },
  262. { open_temp_exec_file_dir, "/var/tmp", 0 },
  263. { open_temp_exec_file_dir, "/dev/shm", 0 },
  264. { open_temp_exec_file_env, "HOME", 0 },
  265. #ifdef HAVE_MNTENT
  266. { open_temp_exec_file_mnt, "/etc/mtab", 1 },
  267. { open_temp_exec_file_mnt, "/proc/mounts", 1 },
  268. #endif /* HAVE_MNTENT */
  269. };
  270. /* Current index into open_temp_exec_file_opts. */
  271. static int open_temp_exec_file_opts_idx = 0;
  272. /* Reset a current multi-call func, then advances to the next entry.
  273. If we're at the last, go back to the first and return nonzero,
  274. otherwise return zero. */
  275. static int
  276. open_temp_exec_file_opts_next (void)
  277. {
  278. if (open_temp_exec_file_opts[open_temp_exec_file_opts_idx].repeat)
  279. open_temp_exec_file_opts[open_temp_exec_file_opts_idx].func (NULL);
  280. open_temp_exec_file_opts_idx++;
  281. if (open_temp_exec_file_opts_idx
  282. == (sizeof (open_temp_exec_file_opts)
  283. / sizeof (*open_temp_exec_file_opts)))
  284. {
  285. open_temp_exec_file_opts_idx = 0;
  286. return 1;
  287. }
  288. return 0;
  289. }
  290. /* Return a file descriptor of a temporary zero-sized file in a
  291. writable and exexutable filesystem. */
  292. static int
  293. open_temp_exec_file (void)
  294. {
  295. int fd;
  296. do
  297. {
  298. fd = open_temp_exec_file_opts[open_temp_exec_file_opts_idx].func
  299. (open_temp_exec_file_opts[open_temp_exec_file_opts_idx].arg);
  300. if (!open_temp_exec_file_opts[open_temp_exec_file_opts_idx].repeat
  301. || fd == -1)
  302. {
  303. if (open_temp_exec_file_opts_next ())
  304. break;
  305. }
  306. }
  307. while (fd == -1);
  308. return fd;
  309. }
  310. /* Map in a chunk of memory from the temporary exec file into separate
  311. locations in the virtual memory address space, one writable and one
  312. executable. Returns the address of the writable portion, after
  313. storing an offset to the corresponding executable portion at the
  314. last word of the requested chunk. */
  315. static void *
  316. dlmmap_locked (void *start, size_t length, int prot, int flags, off_t offset)
  317. {
  318. void *ptr;
  319. if (execfd == -1)
  320. {
  321. open_temp_exec_file_opts_idx = 0;
  322. retry_open:
  323. execfd = open_temp_exec_file ();
  324. if (execfd == -1)
  325. return MFAIL;
  326. }
  327. offset = execsize;
  328. if (ftruncate (execfd, offset + length))
  329. return MFAIL;
  330. flags &= ~(MAP_PRIVATE | MAP_ANONYMOUS);
  331. flags |= MAP_SHARED;
  332. ptr = mmap (NULL, length, (prot & ~PROT_WRITE) | PROT_EXEC,
  333. flags, execfd, offset);
  334. if (ptr == MFAIL)
  335. {
  336. if (!offset)
  337. {
  338. close (execfd);
  339. goto retry_open;
  340. }
  341. ftruncate (execfd, offset);
  342. return MFAIL;
  343. }
  344. else if (!offset
  345. && open_temp_exec_file_opts[open_temp_exec_file_opts_idx].repeat)
  346. open_temp_exec_file_opts_next ();
  347. start = mmap (start, length, prot, flags, execfd, offset);
  348. if (start == MFAIL)
  349. {
  350. munmap (ptr, length);
  351. ftruncate (execfd, offset);
  352. return start;
  353. }
  354. mmap_exec_offset ((char *)start, length) = (char*)ptr - (char*)start;
  355. execsize += length;
  356. return start;
  357. }
  358. /* Map in a writable and executable chunk of memory if possible.
  359. Failing that, fall back to dlmmap_locked. */
  360. static void *
  361. dlmmap (void *start, size_t length, int prot,
  362. int flags, int fd, off_t offset)
  363. {
  364. void *ptr;
  365. assert (start == NULL && length % malloc_getpagesize == 0
  366. && prot == (PROT_READ | PROT_WRITE)
  367. && flags == (MAP_PRIVATE | MAP_ANONYMOUS)
  368. && fd == -1 && offset == 0);
  369. #if FFI_CLOSURE_TEST
  370. printf ("mapping in %zi\n", length);
  371. #endif
  372. if (execfd == -1 && !is_selinux_enabled ())
  373. {
  374. ptr = mmap (start, length, prot | PROT_EXEC, flags, fd, offset);
  375. if (ptr != MFAIL || (errno != EPERM && errno != EACCES))
  376. /* Cool, no need to mess with separate segments. */
  377. return ptr;
  378. /* If MREMAP_DUP is ever introduced and implemented, try mmap
  379. with ((prot & ~PROT_WRITE) | PROT_EXEC) and mremap with
  380. MREMAP_DUP and prot at this point. */
  381. }
  382. if (execsize == 0 || execfd == -1)
  383. {
  384. pthread_mutex_lock (&open_temp_exec_file_mutex);
  385. ptr = dlmmap_locked (start, length, prot, flags, offset);
  386. pthread_mutex_unlock (&open_temp_exec_file_mutex);
  387. return ptr;
  388. }
  389. return dlmmap_locked (start, length, prot, flags, offset);
  390. }
  391. /* Release memory at the given address, as well as the corresponding
  392. executable page if it's separate. */
  393. static int
  394. dlmunmap (void *start, size_t length)
  395. {
  396. /* We don't bother decreasing execsize or truncating the file, since
  397. we can't quite tell whether we're unmapping the end of the file.
  398. We don't expect frequent deallocation anyway. If we did, we
  399. could locate pages in the file by writing to the pages being
  400. deallocated and checking that the file contents change.
  401. Yuck. */
  402. msegmentptr seg = segment_holding (gm, start);
  403. void *code;
  404. #if FFI_CLOSURE_TEST
  405. printf ("unmapping %zi\n", length);
  406. #endif
  407. if (seg && (code = add_segment_exec_offset (start, seg)) != start)
  408. {
  409. int ret = munmap (code, length);
  410. if (ret)
  411. return ret;
  412. }
  413. return munmap (start, length);
  414. }
  415. #if FFI_CLOSURE_FREE_CODE
  416. /* Return segment holding given code address. */
  417. static msegmentptr
  418. segment_holding_code (mstate m, char* addr)
  419. {
  420. msegmentptr sp = &m->seg;
  421. for (;;) {
  422. if (addr >= add_segment_exec_offset (sp->base, sp)
  423. && addr < add_segment_exec_offset (sp->base, sp) + sp->size)
  424. return sp;
  425. if ((sp = sp->next) == 0)
  426. return 0;
  427. }
  428. }
  429. #endif
  430. #endif /* !(defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__)) || defined (__CYGWIN__) */
  431. /* Allocate a chunk of memory with the given size. Returns a pointer
  432. to the writable address, and sets *CODE to the executable
  433. corresponding virtual address. */
  434. void *
  435. ffi_closure_alloc (size_t size, void **code)
  436. {
  437. void *ptr;
  438. if (!code)
  439. return NULL;
  440. ptr = dlmalloc (size);
  441. if (ptr)
  442. {
  443. msegmentptr seg = segment_holding (gm, ptr);
  444. *code = add_segment_exec_offset (ptr, seg);
  445. }
  446. return ptr;
  447. }
  448. /* Release a chunk of memory allocated with ffi_closure_alloc. If
  449. FFI_CLOSURE_FREE_CODE is nonzero, the given address can be the
  450. writable or the executable address given. Otherwise, only the
  451. writable address can be provided here. */
  452. void
  453. ffi_closure_free (void *ptr)
  454. {
  455. #if FFI_CLOSURE_FREE_CODE
  456. msegmentptr seg = segment_holding_code (gm, ptr);
  457. if (seg)
  458. ptr = sub_segment_exec_offset (ptr, seg);
  459. #endif
  460. dlfree (ptr);
  461. }
  462. #if FFI_CLOSURE_TEST
  463. /* Do some internal sanity testing to make sure allocation and
  464. deallocation of pages are working as intended. */
  465. int main ()
  466. {
  467. void *p[3];
  468. #define GET(idx, len) do { p[idx] = dlmalloc (len); printf ("allocated %zi for p[%i]\n", (len), (idx)); } while (0)
  469. #define PUT(idx) do { printf ("freeing p[%i]\n", (idx)); dlfree (p[idx]); } while (0)
  470. GET (0, malloc_getpagesize / 2);
  471. GET (1, 2 * malloc_getpagesize - 64 * sizeof (void*));
  472. PUT (1);
  473. GET (1, 2 * malloc_getpagesize);
  474. GET (2, malloc_getpagesize / 2);
  475. PUT (1);
  476. PUT (0);
  477. PUT (2);
  478. return 0;
  479. }
  480. #endif /* FFI_CLOSURE_TEST */
  481. # else /* ! FFI_MMAP_EXEC_WRIT */
  482. /* On many systems, memory returned by malloc is writable and
  483. executable, so just use it. */
  484. #include <stdlib.h>
  485. void *
  486. ffi_closure_alloc (size_t size, void **code)
  487. {
  488. if (!code)
  489. return NULL;
  490. return *code = malloc (size);
  491. }
  492. void
  493. ffi_closure_free (void *ptr)
  494. {
  495. free (ptr);
  496. }
  497. # endif /* ! FFI_MMAP_EXEC_WRIT */
  498. #endif /* FFI_CLOSURES */