Start of man-pages-5.14: updating Changes and Changes.old
[man-pages.git] / man2 / memfd_create.2
blobee9fa8aa6df069e3b3fce68a11826dac639f18a0
1 .\" Copyright (C) 2014 Michael Kerrisk <mtk.manpages@gmail.com>
2 .\" and Copyright (C) 2014 David Herrmann <dh.herrmann@gmail.com>
3 .\"
4 .\" %%%LICENSE_START(GPLv2+)
5 .\"
6 .\" This program is free software; you can redistribute it and/or modify
7 .\" it under the terms of the GNU General Public License as published by
8 .\" the Free Software Foundation; either version 2 of the License, or
9 .\" (at your option) any later version.
10 .\"
11 .\" This program is distributed in the hope that it will be useful,
12 .\" but WITHOUT ANY WARRANTY; without even the implied warranty of
13 .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 .\" GNU General Public License for more details.
15 .\"
16 .\" You should have received a copy of the GNU General Public
17 .\" License along with this manual; if not, see
18 .\" <http://www.gnu.org/licenses/>.
19 .\" %%%LICENSE_END
20 .\"
21 .TH MEMFD_CREATE 2 2021-03-22 Linux "Linux Programmer's Manual"
22 .SH NAME
23 memfd_create \- create an anonymous file
24 .SH SYNOPSIS
25 .nf
26 .BR "#define _GNU_SOURCE" "         /* See feature_test_macros(7) */"
27 .B #include <sys/mman.h>
28 .PP
29 .BI "int memfd_create(const char *" name ", unsigned int " flags ");"
30 .fi
31 .SH DESCRIPTION
32 .BR memfd_create ()
33 creates an anonymous file and returns a file descriptor that refers to it.
34 The file behaves like a regular file, and so can be modified,
35 truncated, memory-mapped, and so on.
36 However, unlike a regular file,
37 it lives in RAM and has a volatile backing storage.
38 Once all references to the file are dropped, it is automatically released.
39 Anonymous memory is used for all backing pages of the file.
40 Therefore, files created by
41 .BR memfd_create ()
42 have the same semantics as other anonymous
43 .\" David Herrmann:
44 .\"     memfd uses VM_NORESERVE so each page is accounted on first access.
45 .\"     This means, the overcommit-limits (see __vm_enough_memory()) and the
46 .\"     memory-cgroup limits (mem_cgroup_try_charge()) are applied. Note that
47 .\"     those are accounted on "current" and "current->mm", that is, the
48 .\"     process doing the first page access.
49 memory allocations such as those allocated using
50 .BR mmap (2)
51 with the
52 .BR MAP_ANONYMOUS
53 flag.
54 .PP
55 The initial size of the file is set to 0.
56 Following the call, the file size should be set using
57 .BR ftruncate (2).
58 (Alternatively, the file may be populated by calls to
59 .BR write (2)
60 or similar.)
61 .PP
62 The name supplied in
63 .I name
64 is used as a filename and will be displayed
65 as the target of the corresponding symbolic link in the directory
66 .IR /proc/self/fd/ .
67 The displayed name is always prefixed with
68 .IR memfd:
69 and serves only for debugging purposes.
70 Names do not affect the behavior of the file descriptor,
71 and as such multiple files can have the same name without any side effects.
72 .PP
73 The following values may be bitwise ORed in
74 .IR flags
75 to change the behavior of
76 .BR memfd_create ():
77 .TP
78 .BR MFD_CLOEXEC
79 Set the close-on-exec
80 .RB ( FD_CLOEXEC )
81 flag on the new file descriptor.
82 See the description of the
83 .B O_CLOEXEC
84 flag in
85 .BR open (2)
86 for reasons why this may be useful.
87 .TP
88 .BR MFD_ALLOW_SEALING
89 Allow sealing operations on this file.
90 See the discussion of the
91 .B F_ADD_SEALS
92 and
93 .BR F_GET_SEALS
94 operations in
95 .BR fcntl (2),
96 and also NOTES, below.
97 The initial set of seals is empty.
98 If this flag is not set, the initial set of seals will be
99 .BR F_SEAL_SEAL ,
100 meaning that no other seals can be set on the file.
101 .\" FIXME Why is the MFD_ALLOW_SEALING behavior not simply the default?
102 .\" Is it worth adding some text explaining this?
104 .BR MFD_HUGETLB " (since Linux 4.14)"
105 .\" commit 749df87bd7bee5a79cef073f5d032ddb2b211de8
106 The anonymous file will be created in the hugetlbfs filesystem using
107 huge pages.
108 See the Linux kernel source file
109 .I Documentation/admin\-guide/mm/hugetlbpage.rst
110 for more information about hugetlbfs.
111 .\" commit 47b9012ecdc747f6936395265e677d41e11a31ff
112 Specifying both
113 .B MFD_HUGETLB
115 .B MFD_ALLOW_SEALING
117 .I flags
118 is supported since Linux 4.16.
120 .BR MFD_HUGE_2MB ", " MFD_HUGE_1GB ", " "..."
121 Used in conjunction with
122 .B MFD_HUGETLB
123 to select alternative hugetlb page sizes (respectively, 2\ MB, 1\ GB, ...)
124 on systems that support multiple hugetlb page sizes.
125 Definitions for known
126 huge page sizes are included in the header file
127 .I <linux/memfd.h>.
129 For details on encoding huge page sizes not included in the header file,
130 see the discussion of the similarly named constants in
131 .BR mmap (2).
133 Unused bits in
134 .I flags
135 must be 0.
137 As its return value,
138 .BR memfd_create ()
139 returns a new file descriptor that can be used to refer to the file.
140 This file descriptor is opened for both reading and writing
141 .RB ( O_RDWR )
143 .B O_LARGEFILE
144 is set for the file descriptor.
146 With respect to
147 .BR fork (2)
149 .BR execve (2),
150 the usual semantics apply for the file descriptor created by
151 .BR memfd_create ().
152 A copy of the file descriptor is inherited by the child produced by
153 .BR fork (2)
154 and refers to the same file.
155 The file descriptor is preserved across
156 .BR execve (2),
157 unless the close-on-exec flag has been set.
158 .SH RETURN VALUE
159 On success,
160 .BR memfd_create ()
161 returns a new file descriptor.
162 On error, \-1 is returned and
163 .I errno
164 is set to indicate the error.
165 .SH ERRORS
167 .B EFAULT
168 The address in
169 .IR name
170 points to invalid memory.
172 .B EINVAL
173 .I flags
174 included unknown bits.
176 .B EINVAL
177 .I name
178 was too long.
179 (The limit is
180 .\" NAME_MAX - strlen("memfd:")
181 249 bytes, excluding the terminating null byte.)
183 .B EINVAL
184 Both
185 .B MFD_HUGETLB
187 .B MFD_ALLOW_SEALING
188 were specified in
189 .IR flags .
191 .B EMFILE
192 The per-process limit on the number of open file descriptors has been reached.
194 .B ENFILE
195 The system-wide limit on the total number of open files has been reached.
197 .B ENOMEM
198 There was insufficient memory to create a new anonymous file.
199 .SH VERSIONS
201 .BR memfd_create ()
202 system call first appeared in Linux 3.17;
203 glibc support was added in version 2.27.
205 .B EPERM
207 .B MFD_HUGETLB
208 flag was specified, but the caller was not privileged (did not have the
209 .B CAP_IPC_LOCK
210 capability)
211 and is not a member of the
212 .I sysctl_hugetlb_shm_group
213 group; see the description of
214 .I /proc/sys/vm/sysctl_hugetlb_shm_group
216 .BR proc (5).
217 .SH CONFORMING TO
219 .BR memfd_create ()
220 system call is Linux-specific.
221 .SH NOTES
222 .\" See also http://lwn.net/Articles/593918/
223 .\" and http://lwn.net/Articles/594919/ and http://lwn.net/Articles/591108/
225 .BR memfd_create ()
226 system call provides a simple alternative to manually mounting a
227 .BR tmpfs (5)
228 filesystem and creating and opening a file in that filesystem.
229 The primary purpose of
230 .BR memfd_create ()
231 is to create files and associated file descriptors that are
232 used with the file-sealing APIs provided by
233 .BR fcntl (2).
236 .BR memfd_create ()
237 system call also has uses without file sealing
238 (which is why file-sealing is disabled, unless explicitly requested with the
239 .BR MFD_ALLOW_SEALING
240 flag).
241 In particular, it can be used as an alternative to creating files in
242 .IR tmp
243 or as an alternative to using the
244 .BR  open (2)
245 .B O_TMPFILE
246 in cases where there is no intention to actually link the
247 resulting file into the filesystem.
248 .SS File sealing
249 In the absence of file sealing,
250 processes that communicate via shared memory must either trust each other,
251 or take measures to deal with the possibility that an untrusted peer
252 may manipulate the shared memory region in problematic ways.
253 For example, an untrusted peer might modify the contents of the
254 shared memory at any time, or shrink the shared memory region.
255 The former possibility leaves the local process vulnerable to
256 time-of-check-to-time-of-use race conditions
257 (typically dealt with by copying data from
258 the shared memory region before checking and using it).
259 The latter possibility leaves the local process vulnerable to
260 .BR SIGBUS
261 signals when an attempt is made to access a now-nonexistent
262 location in the shared memory region.
263 (Dealing with this possibility necessitates the use of a handler for the
264 .BR SIGBUS
265 signal.)
267 Dealing with untrusted peers imposes extra complexity on
268 code that employs shared memory.
269 Memory sealing enables that extra complexity to be eliminated,
270 by allowing a process to operate secure in the knowledge that
271 its peer can't modify the shared memory in an undesired fashion.
273 An example of the usage of the sealing mechanism is as follows:
274 .IP 1. 3
275 The first process creates a
276 .BR tmpfs (5)
277 file using
278 .BR memfd_create ().
279 The call yields a file descriptor used in subsequent steps.
280 .IP 2.
281 The first process
282 sizes the file created in the previous step using
283 .BR ftruncate (2),
284 maps it using
285 .BR mmap (2),
286 and populates the shared memory with the desired data.
287 .IP 3.
288 The first process uses the
289 .BR fcntl (2)
290 .B F_ADD_SEALS
291 operation to place one or more seals on the file,
292 in order to restrict further modifications on the file.
293 (If placing the seal
294 .BR F_SEAL_WRITE ,
295 then it will be necessary to first unmap the shared writable mapping
296 created in the previous step.
297 Otherwise, behavior similar to
298 .BR F_SEAL_WRITE
299 can be achieved by using
300 .BR F_SEAL_FUTURE_WRITE ,
301 which will prevent future writes via
302 .BR mmap (2)
304 .BR write (2)
305 from succeeding while keeping existing shared writable mappings).
306 .IP 4.
307 A second process obtains a file descriptor for the
308 .BR tmpfs (5)
309 file and maps it.
310 Among the possible ways in which this could happen are the following:
312 .IP * 3
313 The process that called
314 .BR memfd_create ()
315 could transfer the resulting file descriptor to the second process
316 via a UNIX domain socket (see
317 .BR unix (7)
319 .BR cmsg (3)).
320 The second process then maps the file using
321 .BR mmap (2).
322 .IP *
323 The second process is created via
324 .BR fork (2)
325 and thus automatically inherits the file descriptor and mapping.
326 (Note that in this case and the next,
327 there is a natural trust relationship between the two processes,
328 since they are running under the same user ID.
329 Therefore, file sealing would not normally be necessary.)
330 .IP *
331 The second process opens the file
332 .IR /proc/<pid>/fd/<fd> ,
333 where
334 .I <pid>
335 is the PID of the first process (the one that called
336 .BR memfd_create ()),
338 .I <fd>
339 is the number of the file descriptor returned by the call to
340 .BR memfd_create ()
341 in that process.
342 The second process then maps the file using
343 .BR mmap (2).
345 .IP 5.
346 The second process uses the
347 .BR fcntl (2)
348 .B F_GET_SEALS
349 operation to retrieve the bit mask of seals
350 that has been applied to the file.
351 This bit mask can be inspected in order to determine
352 what kinds of restrictions have been placed on file modifications.
353 If desired, the second process can apply further seals
354 to impose additional restrictions (so long as the
355 .BR F_SEAL_SEAL
356 seal has not yet been applied).
357 .SH EXAMPLES
358 Below are shown two example programs that demonstrate the use of
359 .BR memfd_create ()
360 and the file sealing API.
362 The first program,
363 .IR t_memfd_create.c ,
364 creates a
365 .BR tmpfs (5)
366 file using
367 .BR memfd_create (),
368 sets a size for the file, maps it into memory,
369 and optionally places some seals on the file.
370 The program accepts up to three command-line arguments,
371 of which the first two are required.
372 The first argument is the name to associate with the file,
373 the second argument is the size to be set for the file,
374 and the optional third argument is a string of characters that specify
375 seals to be set on file.
377 The second program,
378 .IR t_get_seals.c ,
379 can be used to open an existing file that was created via
380 .BR memfd_create ()
381 and inspect the set of seals that have been applied to that file.
383 The following shell session demonstrates the use of these programs.
384 First we create a
385 .BR tmpfs (5)
386 file and set some seals on it:
388 .in +4n
390 $ \fB./t_memfd_create my_memfd_file 4096 sw &\fP
391 [1] 11775
392 PID: 11775; fd: 3; /proc/11775/fd/3
396 At this point, the
397 .I t_memfd_create
398 program continues to run in the background.
399 From another program, we can obtain a file descriptor for the
400 file created by
401 .BR memfd_create ()
402 by opening the
403 .IR /proc/[pid]/fd
404 file that corresponds to the file descriptor opened by
405 .BR memfd_create ().
406 Using that pathname, we inspect the content of the
407 .IR /proc/[pid]/fd
408 symbolic link, and use our
409 .I t_get_seals
410 program to view the seals that have been placed on the file:
412 .in +4n
414 $ \fBreadlink /proc/11775/fd/3\fP
415 /memfd:my_memfd_file (deleted)
416 $ \fB./t_get_seals /proc/11775/fd/3\fP
417 Existing seals: WRITE SHRINK
420 .SS Program source: t_memfd_create.c
423 #define _GNU_SOURCE
424 #include <stdint.h>
425 #include <sys/mman.h>
426 #include <fcntl.h>
427 #include <stdlib.h>
428 #include <unistd.h>
429 #include <string.h>
430 #include <stdio.h>
432 #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \e
433                         } while (0)
436 main(int argc, char *argv[])
438     int fd;
439     unsigned int seals;
440     char *addr;
441     char *name, *seals_arg;
442     ssize_t len;
444     if (argc < 3) {
445         fprintf(stderr, "%s name size [seals]\en", argv[0]);
446         fprintf(stderr, "\et\(aqseals\(aq can contain any of the "
447                 "following characters:\en");
448         fprintf(stderr, "\et\etg \- F_SEAL_GROW\en");
449         fprintf(stderr, "\et\ets \- F_SEAL_SHRINK\en");
450         fprintf(stderr, "\et\etw \- F_SEAL_WRITE\en");
451         fprintf(stderr, "\et\etW \- F_SEAL_FUTURE_WRITE\en");
452         fprintf(stderr, "\et\etS \- F_SEAL_SEAL\en");
453         exit(EXIT_FAILURE);
454     }
456     name = argv[1];
457     len = atoi(argv[2]);
458     seals_arg = argv[3];
460     /* Create an anonymous file in tmpfs; allow seals to be
461        placed on the file. */
463     fd = memfd_create(name, MFD_ALLOW_SEALING);
464     if (fd == \-1)
465         errExit("memfd_create");
467     /* Size the file as specified on the command line. */
469     if (ftruncate(fd, len) == \-1)
470         errExit("truncate");
472     printf("PID: %jd; fd: %d; /proc/%jd/fd/%d\en",
473             (intmax_t) getpid(), fd, (intmax_t) getpid(), fd);
475     /* Code to map the file and populate the mapping with data
476        omitted. */
478     /* If a \(aqseals\(aq command\-line argument was supplied, set some
479        seals on the file. */
481     if (seals_arg != NULL) {
482         seals = 0;
484         if (strchr(seals_arg, \(aqg\(aq) != NULL)
485             seals |= F_SEAL_GROW;
486         if (strchr(seals_arg, \(aqs\(aq) != NULL)
487             seals |= F_SEAL_SHRINK;
488         if (strchr(seals_arg, \(aqw\(aq) != NULL)
489             seals |= F_SEAL_WRITE;
490         if (strchr(seals_arg, \(aqW\(aq) != NULL)
491             seals |= F_SEAL_FUTURE_WRITE;
492         if (strchr(seals_arg, \(aqS\(aq) != NULL)
493             seals |= F_SEAL_SEAL;
495         if (fcntl(fd, F_ADD_SEALS, seals) == \-1)
496             errExit("fcntl");
497     }
499     /* Keep running, so that the file created by memfd_create()
500        continues to exist. */
502     pause();
504     exit(EXIT_SUCCESS);
507 .SS Program source: t_get_seals.c
510 #define _GNU_SOURCE
511 #include <sys/mman.h>
512 #include <fcntl.h>
513 #include <unistd.h>
514 #include <stdlib.h>
515 #include <string.h>
516 #include <stdio.h>
518 #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \e
519                         } while (0)
522 main(int argc, char *argv[])
524     int fd;
525     unsigned int seals;
527     if (argc != 2) {
528         fprintf(stderr, "%s /proc/PID/fd/FD\en", argv[0]);
529         exit(EXIT_FAILURE);
530     }
532     fd = open(argv[1], O_RDWR);
533     if (fd == \-1)
534         errExit("open");
536     seals = fcntl(fd, F_GET_SEALS);
537     if (seals == \-1)
538         errExit("fcntl");
540     printf("Existing seals:");
541     if (seals & F_SEAL_SEAL)
542         printf(" SEAL");
543     if (seals & F_SEAL_GROW)
544         printf(" GROW");
545     if (seals & F_SEAL_WRITE)
546         printf(" WRITE");
547     if (seals & F_SEAL_FUTURE_WRITE)
548         printf(" FUTURE_WRITE");
549     if (seals & F_SEAL_SHRINK)
550         printf(" SHRINK");
551     printf("\en");
553     /* Code to map the file and access the contents of the
554        resulting mapping omitted. */
556     exit(EXIT_SUCCESS);
559 .SH SEE ALSO
560 .BR fcntl (2),
561 .BR ftruncate (2),
562 .BR mmap (2),
563 .BR shmget (2),
564 .BR shm_open (3)