12 os_fd_set_cloexec(int fd)
19 flags = fcntl(fd, F_GETFD);
23 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1)
30 set_cloexec_or_close(int fd)
32 if (os_fd_set_cloexec(fd) != 0) {
40 create_tmpfile_cloexec(char *tmpname)
45 fd = mkostemp(tmpname, O_CLOEXEC);
49 fd = mkstemp(tmpname);
51 fd = set_cloexec_or_close(fd);
60 * Create a new, unique, anonymous file of the given size, and
61 * return the file descriptor for it. The file descriptor is set
62 * CLOEXEC. The file is immediately suitable for mmap()'ing
63 * the given size at offset zero.
65 * The file should not have a permanent backing store like a disk,
66 * but may have if XDG_RUNTIME_DIR is not properly implemented in OS.
68 * The file name is deleted from the file system.
70 * The file is suitable for buffer sharing between processes by
71 * transmitting the file descriptor over Unix sockets using the
74 * If the C library implements posix_fallocate(), it is used to
75 * guarantee that disk space is available for the file at the
76 * given size. If disk space is insufficient, errno is set to ENOSPC.
77 * If posix_fallocate() is not supported, program may receive
78 * SIGBUS on accessing mmap()'ed file contents instead.
80 * If the C library implements memfd_create(), it is used to create the
81 * file purely in memory, without any backing file name on the file
82 * system, and then sealing off the possibility of shrinking it. This
83 * can then be checked before accessing mmap()'ed file contents, to
84 * make sure SIGBUS can't happen. It also avoids requiring
88 os_create_anonymous_file(off_t size)
90 static const char weston_template[] = "/weston-shared-XXXXXX";
96 #ifdef HAVE_MEMFD_CREATE
97 fd = memfd_create("weston-shared", MFD_CLOEXEC | MFD_ALLOW_SEALING);
99 /* We can add this seal before calling posix_fallocate(), as
100 * the file is currently zero-sized anyway.
102 * There is also no need to check for the return value, we
103 * couldn't do anything with it anyway.
105 fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK);
109 path = getenv("XDG_RUNTIME_DIR");
115 name = static_cast<char *>(malloc(strlen(path) + sizeof(weston_template)));
120 strcat(name, weston_template);
122 fd = create_tmpfile_cloexec(name);
130 #ifdef HAVE_POSIX_FALLOCATE
132 ret = posix_fallocate(fd, 0, size);
133 } while (ret == EINTR);
141 ret = ftruncate(fd, size);
142 } while (ret < 0 && errno == EINTR);