Skip to content

Commit 174d428

Browse files
committed
Use anonymous shared memory for tempfiles
SHM_ANON on FreeBSD, memfd on recent Linux. - avoids usage of posix_fallocate on Copy-on-Write filesystems like ZFS when XDG_RUNTIME_DIR is something like ~/.tmp instead of a tmpfs (FreeBSD 12 does not even allow it on ZFS anymore) - avoids touching the filesystem, which increases sandboxing potential
1 parent 5df4a68 commit 174d428

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

configure.ac

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ AC_CHECK_DECL(TFD_CLOEXEC,[],
102102
AC_CHECK_DECL(CLOCK_MONOTONIC,[],
103103
[AC_MSG_ERROR("CLOCK_MONOTONIC is needed to compile weston")],
104104
[[#include <time.h>]])
105-
AC_CHECK_HEADERS([execinfo.h])
105+
AC_CHECK_HEADERS([execinfo.h linux/memfd.h])
106106

107107
AC_CHECK_FUNCS([mkostemp strchrnul initgroups posix_fallocate])
108108

shared/os-compatibility.c

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,13 @@
2525

2626
#include "config.h"
2727

28+
#ifdef __FreeBSD__
29+
#include <sys/mman.h>
30+
#elif HAVE_LINUX_MEMFD_H
31+
#define _GNU_SOURCE
32+
#include <sys/syscall.h>
33+
#include <linux/memfd.h>
34+
#endif
2835
#include <sys/types.h>
2936
#include <sys/socket.h>
3037
#include <unistd.h>
@@ -107,12 +114,15 @@ os_epoll_create_cloexec(void)
107114
return set_cloexec_or_close(fd);
108115
}
109116

117+
#ifndef __FreeBSD__
110118
static int
111119
create_tmpfile_cloexec(char *tmpname)
112120
{
113121
int fd;
114122

115-
#ifdef HAVE_MKOSTEMP
123+
#ifdef HAVE_LINUX_MEMFD_H
124+
fd = syscall(SYS_memfd_create, tmpname, MFD_CLOEXEC);
125+
#elif HAVE_MKOSTEMP
116126
fd = mkostemp(tmpname, O_CLOEXEC);
117127
if (fd >= 0)
118128
unlink(tmpname);
@@ -126,6 +136,7 @@ create_tmpfile_cloexec(char *tmpname)
126136

127137
return fd;
128138
}
139+
#endif
129140

130141
/*
131142
* Create a new, unique, anonymous file of the given size, and
@@ -151,11 +162,13 @@ create_tmpfile_cloexec(char *tmpname)
151162
int
152163
os_create_anonymous_file(off_t size)
153164
{
165+
int fd, ret;
166+
#ifdef __FreeBSD__
167+
fd = shm_open(SHM_ANON, O_CREAT | O_RDWR, 0600); // shm_open is always CLOEXEC
168+
#else
154169
static const char template[] = "/weston-shared-XXXXXX";
155170
const char *path;
156171
char *name;
157-
int fd;
158-
int ret;
159172

160173
path = getenv("XDG_RUNTIME_DIR");
161174
if (!path) {
@@ -173,11 +186,12 @@ os_create_anonymous_file(off_t size)
173186
fd = create_tmpfile_cloexec(name);
174187

175188
free(name);
189+
#endif
176190

177191
if (fd < 0)
178192
return -1;
179193

180-
#ifdef HAVE_POSIX_FALLOCATE
194+
#if defined(HAVE_POSIX_FALLOCATE) && !defined(__FreeBSD__)
181195
do {
182196
ret = posix_fallocate(fd, 0, size);
183197
} while (ret == EINTR);

0 commit comments

Comments
 (0)