1MEMFD_CREATE(2) Linux Programmer's Manual MEMFD_CREATE(2)
2
3
4
6 memfd_create - create an anonymous file
7
9 #define _GNU_SOURCE /* See feature_test_macros(7) */
10 #include <sys/mman.h>
11
12 int memfd_create(const char *name, unsigned int flags);
13
15 memfd_create() creates an anonymous file and returns a file descriptor
16 that refers to it. The file behaves like a regular file, and so can be
17 modified, truncated, memory-mapped, and so on. However, unlike a regu‐
18 lar file, it lives in RAM and has a volatile backing storage. Once all
19 references to the file are dropped, it is automatically released.
20 Anonymous memory is used for all backing pages of the file. Therefore,
21 files created by memfd_create() have the same semantics as other anony‐
22 mous memory allocations such as those allocated using mmap(2) with the
23 MAP_ANONYMOUS flag.
24
25 The initial size of the file is set to 0. Following the call, the file
26 size should be set using ftruncate(2). (Alternatively, the file may be
27 populated by calls to write(2) or similar.)
28
29 The name supplied in name is used as a filename and will be displayed
30 as the target of the corresponding symbolic link in the directory
31 /proc/self/fd/. The displayed name is always prefixed with memfd: and
32 serves only for debugging purposes. Names do not affect the behavior
33 of the file descriptor, and as such multiple files can have the same
34 name without any side effects.
35
36 The following values may be bitwise ORed in flags to change the behav‐
37 ior of memfd_create():
38
39 MFD_CLOEXEC
40 Set the close-on-exec (FD_CLOEXEC) flag on the new file descrip‐
41 tor. See the description of the O_CLOEXEC flag in open(2) for
42 reasons why this may be useful.
43
44 MFD_ALLOW_SEALING
45 Allow sealing operations on this file. See the discussion of
46 the F_ADD_SEALS and F_GET_SEALS operations in fcntl(2), and also
47 NOTES, below. The initial set of seals is empty. If this flag
48 is not set, the initial set of seals will be F_SEAL_SEAL, mean‐
49 ing that no other seals can be set on the file.
50
51 MFD_HUGETLB (since Linux 4.14)
52 The anonymous file will be created in the hugetlbfs filesystem
53 using huge pages. See the Linux kernel source file Documenta‐
54 tion/admin-guide/mm/hugetlbpage.rst for more information about
55 hugetlbfs. Specifying both MFD_HUGETLB and MFD_ALLOW_SEALING in
56 flags is supported since Linux 4.16.
57
58 MFD_HUGE_2MB, MFD_HUGE_1GB, ...
59 Used in conjunction with MFD_HUGETLB to select alternative
60 hugetlb page sizes (respectively, 2 MB, 1 GB, ...) on systems
61 that support multiple hugetlb page sizes. Definitions for known
62 huge page sizes are included in the header file <linux/memfd.h>.
63
64 For details on encoding huge page sizes not included in the
65 header file, see the discussion of the similarly named constants
66 in mmap(2).
67
68 Unused bits in flags must be 0.
69
70 As its return value, memfd_create() returns a new file descriptor that
71 can be used to refer to the file. This file descriptor is opened for
72 both reading and writing (O_RDWR) and O_LARGEFILE is set for the file
73 descriptor.
74
75 With respect to fork(2) and execve(2), the usual semantics apply for
76 the file descriptor created by memfd_create(). A copy of the file de‐
77 scriptor is inherited by the child produced by fork(2) and refers to
78 the same file. The file descriptor is preserved across execve(2), un‐
79 less the close-on-exec flag has been set.
80
82 On success, memfd_create() returns a new file descriptor. On error, -1
83 is returned and errno is set to indicate the error.
84
86 EFAULT The address in name points to invalid memory.
87
88 EINVAL flags included unknown bits.
89
90 EINVAL name was too long. (The limit is 249 bytes, excluding the ter‐
91 minating null byte.)
92
93 EINVAL Both MFD_HUGETLB and MFD_ALLOW_SEALING were specified in flags.
94
95 EMFILE The per-process limit on the number of open file descriptors has
96 been reached.
97
98 ENFILE The system-wide limit on the total number of open files has been
99 reached.
100
101 ENOMEM There was insufficient memory to create a new anonymous file.
102
104 The memfd_create() system call first appeared in Linux 3.17; glibc sup‐
105 port was added in version 2.27.
106
108 The memfd_create() system call is Linux-specific.
109
111 The memfd_create() system call provides a simple alternative to manu‐
112 ally mounting a tmpfs(5) filesystem and creating and opening a file in
113 that filesystem. The primary purpose of memfd_create() is to create
114 files and associated file descriptors that are used with the file-seal‐
115 ing APIs provided by fcntl(2).
116
117 The memfd_create() system call also has uses without file sealing
118 (which is why file-sealing is disabled, unless explicitly requested
119 with the MFD_ALLOW_SEALING flag). In particular, it can be used as an
120 alternative to creating files in tmp or as an alternative to using the
121 open(2) O_TMPFILE in cases where there is no intention to actually link
122 the resulting file into the filesystem.
123
124 File sealing
125 In the absence of file sealing, processes that communicate via shared
126 memory must either trust each other, or take measures to deal with the
127 possibility that an untrusted peer may manipulate the shared memory re‐
128 gion in problematic ways. For example, an untrusted peer might modify
129 the contents of the shared memory at any time, or shrink the shared
130 memory region. The former possibility leaves the local process vulner‐
131 able to time-of-check-to-time-of-use race conditions (typically dealt
132 with by copying data from the shared memory region before checking and
133 using it). The latter possibility leaves the local process vulnerable
134 to SIGBUS signals when an attempt is made to access a now-nonexistent
135 location in the shared memory region. (Dealing with this possibility
136 necessitates the use of a handler for the SIGBUS signal.)
137
138 Dealing with untrusted peers imposes extra complexity on code that em‐
139 ploys shared memory. Memory sealing enables that extra complexity to
140 be eliminated, by allowing a process to operate secure in the knowledge
141 that its peer can't modify the shared memory in an undesired fashion.
142
143 An example of the usage of the sealing mechanism is as follows:
144
145 1. The first process creates a tmpfs(5) file using memfd_create(). The
146 call yields a file descriptor used in subsequent steps.
147
148 2. The first process sizes the file created in the previous step using
149 ftruncate(2), maps it using mmap(2), and populates the shared memory
150 with the desired data.
151
152 3. The first process uses the fcntl(2) F_ADD_SEALS operation to place
153 one or more seals on the file, in order to restrict further modifi‐
154 cations on the file. (If placing the seal F_SEAL_WRITE, then it
155 will be necessary to first unmap the shared writable mapping created
156 in the previous step. Otherwise, behavior similar to F_SEAL_WRITE
157 can be achieved by using F_SEAL_FUTURE_WRITE, which will prevent fu‐
158 ture writes via mmap(2) and write(2) from succeeding while keeping
159 existing shared writable mappings).
160
161 4. A second process obtains a file descriptor for the tmpfs(5) file and
162 maps it. Among the possible ways in which this could happen are the
163 following:
164
165 * The process that called memfd_create() could transfer the result‐
166 ing file descriptor to the second process via a UNIX domain
167 socket (see unix(7) and cmsg(3)). The second process then maps
168 the file using mmap(2).
169
170 * The second process is created via fork(2) and thus automatically
171 inherits the file descriptor and mapping. (Note that in this
172 case and the next, there is a natural trust relationship between
173 the two processes, since they are running under the same user ID.
174 Therefore, file sealing would not normally be necessary.)
175
176 * The second process opens the file /proc/<pid>/fd/<fd>, where
177 <pid> is the PID of the first process (the one that called
178 memfd_create()), and <fd> is the number of the file descriptor
179 returned by the call to memfd_create() in that process. The sec‐
180 ond process then maps the file using mmap(2).
181
182 5. The second process uses the fcntl(2) F_GET_SEALS operation to re‐
183 trieve the bit mask of seals that has been applied to the file.
184 This bit mask can be inspected in order to determine what kinds of
185 restrictions have been placed on file modifications. If desired,
186 the second process can apply further seals to impose additional re‐
187 strictions (so long as the F_SEAL_SEAL seal has not yet been ap‐
188 plied).
189
191 Below are shown two example programs that demonstrate the use of
192 memfd_create() and the file sealing API.
193
194 The first program, t_memfd_create.c, creates a tmpfs(5) file using
195 memfd_create(), sets a size for the file, maps it into memory, and op‐
196 tionally places some seals on the file. The program accepts up to
197 three command-line arguments, of which the first two are required. The
198 first argument is the name to associate with the file, the second argu‐
199 ment is the size to be set for the file, and the optional third argu‐
200 ment is a string of characters that specify seals to be set on file.
201
202 The second program, t_get_seals.c, can be used to open an existing file
203 that was created via memfd_create() and inspect the set of seals that
204 have been applied to that file.
205
206 The following shell session demonstrates the use of these programs.
207 First we create a tmpfs(5) file and set some seals on it:
208
209 $ ./t_memfd_create my_memfd_file 4096 sw &
210 [1] 11775
211 PID: 11775; fd: 3; /proc/11775/fd/3
212
213 At this point, the t_memfd_create program continues to run in the back‐
214 ground. From another program, we can obtain a file descriptor for the
215 file created by memfd_create() by opening the /proc/[pid]/fd file that
216 corresponds to the file descriptor opened by memfd_create(). Using
217 that pathname, we inspect the content of the /proc/[pid]/fd symbolic
218 link, and use our t_get_seals program to view the seals that have been
219 placed on the file:
220
221 $ readlink /proc/11775/fd/3
222 /memfd:my_memfd_file (deleted)
223 $ ./t_get_seals /proc/11775/fd/3
224 Existing seals: WRITE SHRINK
225
226 Program source: t_memfd_create.c
227
228 #define _GNU_SOURCE
229 #include <stdint.h>
230 #include <sys/mman.h>
231 #include <fcntl.h>
232 #include <stdlib.h>
233 #include <unistd.h>
234 #include <string.h>
235 #include <stdio.h>
236
237 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \
238 } while (0)
239
240 int
241 main(int argc, char *argv[])
242 {
243 int fd;
244 unsigned int seals;
245 char *addr;
246 char *name, *seals_arg;
247 ssize_t len;
248
249 if (argc < 3) {
250 fprintf(stderr, "%s name size [seals]\n", argv[0]);
251 fprintf(stderr, "\t'seals' can contain any of the "
252 "following characters:\n");
253 fprintf(stderr, "\t\tg - F_SEAL_GROW\n");
254 fprintf(stderr, "\t\ts - F_SEAL_SHRINK\n");
255 fprintf(stderr, "\t\tw - F_SEAL_WRITE\n");
256 fprintf(stderr, "\t\tW - F_SEAL_FUTURE_WRITE\n");
257 fprintf(stderr, "\t\tS - F_SEAL_SEAL\n");
258 exit(EXIT_FAILURE);
259 }
260
261 name = argv[1];
262 len = atoi(argv[2]);
263 seals_arg = argv[3];
264
265 /* Create an anonymous file in tmpfs; allow seals to be
266 placed on the file */
267
268 fd = memfd_create(name, MFD_ALLOW_SEALING);
269 if (fd == -1)
270 errExit("memfd_create");
271
272 /* Size the file as specified on the command line */
273
274 if (ftruncate(fd, len) == -1)
275 errExit("truncate");
276
277 printf("PID: %jd; fd: %d; /proc/%jd/fd/%d\n",
278 (intmax_t) getpid(), fd, (intmax_t) getpid(), fd);
279
280 /* Code to map the file and populate the mapping with data
281 omitted */
282
283 /* If a 'seals' command-line argument was supplied, set some
284 seals on the file */
285
286 if (seals_arg != NULL) {
287 seals = 0;
288
289 if (strchr(seals_arg, 'g') != NULL)
290 seals |= F_SEAL_GROW;
291 if (strchr(seals_arg, 's') != NULL)
292 seals |= F_SEAL_SHRINK;
293 if (strchr(seals_arg, 'w') != NULL)
294 seals |= F_SEAL_WRITE;
295 if (strchr(seals_arg, 'W') != NULL)
296 seals |= F_SEAL_FUTURE_WRITE;
297 if (strchr(seals_arg, 'S') != NULL)
298 seals |= F_SEAL_SEAL;
299
300 if (fcntl(fd, F_ADD_SEALS, seals) == -1)
301 errExit("fcntl");
302 }
303
304 /* Keep running, so that the file created by memfd_create()
305 continues to exist */
306
307 pause();
308
309 exit(EXIT_SUCCESS);
310 }
311
312 Program source: t_get_seals.c
313
314 #define _GNU_SOURCE
315 #include <sys/mman.h>
316 #include <fcntl.h>
317 #include <unistd.h>
318 #include <stdlib.h>
319 #include <string.h>
320 #include <stdio.h>
321
322 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \
323 } while (0)
324
325 int
326 main(int argc, char *argv[])
327 {
328 int fd;
329 unsigned int seals;
330
331 if (argc != 2) {
332 fprintf(stderr, "%s /proc/PID/fd/FD\n", argv[0]);
333 exit(EXIT_FAILURE);
334 }
335
336 fd = open(argv[1], O_RDWR);
337 if (fd == -1)
338 errExit("open");
339
340 seals = fcntl(fd, F_GET_SEALS);
341 if (seals == -1)
342 errExit("fcntl");
343
344 printf("Existing seals:");
345 if (seals & F_SEAL_SEAL)
346 printf(" SEAL");
347 if (seals & F_SEAL_GROW)
348 printf(" GROW");
349 if (seals & F_SEAL_WRITE)
350 printf(" WRITE");
351 if (seals & F_SEAL_FUTURE_WRITE)
352 printf(" FUTURE_WRITE");
353 if (seals & F_SEAL_SHRINK)
354 printf(" SHRINK");
355 printf("\n");
356
357 /* Code to map the file and access the contents of the
358 resulting mapping omitted */
359
360 exit(EXIT_SUCCESS);
361 }
362
364 fcntl(2), ftruncate(2), mmap(2), shmget(2), shm_open(3)
365
367 This page is part of release 5.10 of the Linux man-pages project. A
368 description of the project, information about reporting bugs, and the
369 latest version of this page, can be found at
370 https://www.kernel.org/doc/man-pages/.
371
372
373
374Linux 2020-11-01 MEMFD_CREATE(2)