1MEMFD_CREATE(2)            Linux Programmer's Manual           MEMFD_CREATE(2)
2
3
4

NAME

6       memfd_create - create an anonymous file
7

SYNOPSIS

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

DESCRIPTION

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

RETURN VALUE

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

ERRORS

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

VERSIONS

104       The memfd_create() system call first appeared in Linux 3.17; glibc sup‐
105       port was added in version 2.27.
106
107       EPERM  The MFD_HUGETLB flag was specified, but the caller was not priv‐
108              ileged  (did  not have the CAP_IPC_LOCK capability) and is not a
109              member of the sysctl_hugetlb_shm_group group; see  the  descrip‐
110              tion of /proc/sys/vm/sysctl_hugetlb_shm_group in proc(5).
111

CONFORMING TO

113       The memfd_create() system call is Linux-specific.
114

NOTES

116       The  memfd_create()  system call provides a simple alternative to manu‐
117       ally mounting a tmpfs(5) filesystem and creating and opening a file  in
118       that  filesystem.   The  primary purpose of memfd_create() is to create
119       files and associated file descriptors that are used with the file-seal‐
120       ing APIs provided by fcntl(2).
121
122       The  memfd_create()  system  call  also  has  uses without file sealing
123       (which is why file-sealing is  disabled,  unless  explicitly  requested
124       with  the MFD_ALLOW_SEALING flag).  In particular, it can be used as an
125       alternative to creating files in tmp or as an alternative to using  the
126       open(2) O_TMPFILE in cases where there is no intention to actually link
127       the resulting file into the filesystem.
128
129   File sealing
130       In the absence of file sealing, processes that communicate  via  shared
131       memory  must either trust each other, or take measures to deal with the
132       possibility that an untrusted peer may manipulate the shared memory re‐
133       gion  in problematic ways.  For example, an untrusted peer might modify
134       the contents of the shared memory at any time,  or  shrink  the  shared
135       memory region.  The former possibility leaves the local process vulner‐
136       able to time-of-check-to-time-of-use race conditions  (typically  dealt
137       with  by copying data from the shared memory region before checking and
138       using it).  The latter possibility leaves the local process  vulnerable
139       to  SIGBUS  signals when an attempt is made to access a now-nonexistent
140       location in the shared memory region.  (Dealing with  this  possibility
141       necessitates the use of a handler for the SIGBUS signal.)
142
143       Dealing  with untrusted peers imposes extra complexity on code that em‐
144       ploys shared memory.  Memory sealing enables that extra  complexity  to
145       be eliminated, by allowing a process to operate secure in the knowledge
146       that its peer can't modify the shared memory in an undesired fashion.
147
148       An example of the usage of the sealing mechanism is as follows:
149
150       1. The first process creates a tmpfs(5) file using memfd_create().  The
151          call yields a file descriptor used in subsequent steps.
152
153       2. The  first process sizes the file created in the previous step using
154          ftruncate(2), maps it using mmap(2), and populates the shared memory
155          with the desired data.
156
157       3. The  first  process uses the fcntl(2) F_ADD_SEALS operation to place
158          one or more seals on the file, in order to restrict further  modifi‐
159          cations  on  the  file.   (If placing the seal F_SEAL_WRITE, then it
160          will be necessary to first unmap the shared writable mapping created
161          in  the  previous step.  Otherwise, behavior similar to F_SEAL_WRITE
162          can be achieved by using F_SEAL_FUTURE_WRITE, which will prevent fu‐
163          ture  writes  via mmap(2) and write(2) from succeeding while keeping
164          existing shared writable mappings).
165
166       4. A second process obtains a file descriptor for the tmpfs(5) file and
167          maps it.  Among the possible ways in which this could happen are the
168          following:
169
170          *  The process that called memfd_create() could transfer the result‐
171             ing  file  descriptor  to  the  second  process via a UNIX domain
172             socket (see unix(7) and cmsg(3)).  The second process  then  maps
173             the file using mmap(2).
174
175          *  The  second process is created via fork(2) and thus automatically
176             inherits the file descriptor and mapping.   (Note  that  in  this
177             case  and the next, there is a natural trust relationship between
178             the two processes, since they are running under the same user ID.
179             Therefore, file sealing would not normally be necessary.)
180
181          *  The  second  process  opens  the  file /proc/<pid>/fd/<fd>, where
182             <pid> is the PID of  the  first  process  (the  one  that  called
183             memfd_create()),  and  <fd>  is the number of the file descriptor
184             returned by the call to memfd_create() in that process.  The sec‐
185             ond process then maps the file using mmap(2).
186
187       5. The  second  process  uses the fcntl(2) F_GET_SEALS operation to re‐
188          trieve the bit mask of seals that has  been  applied  to  the  file.
189          This  bit  mask can be inspected in order to determine what kinds of
190          restrictions have been placed on file  modifications.   If  desired,
191          the  second process can apply further seals to impose additional re‐
192          strictions (so long as the F_SEAL_SEAL seal has  not  yet  been  ap‐
193          plied).
194

EXAMPLES

196       Below  are  shown  two  example  programs  that  demonstrate the use of
197       memfd_create() and the file sealing API.
198
199       The first program, t_memfd_create.c,  creates  a  tmpfs(5)  file  using
200       memfd_create(),  sets a size for the file, maps it into memory, and op‐
201       tionally places some seals on the file.   The  program  accepts  up  to
202       three command-line arguments, of which the first two are required.  The
203       first argument is the name to associate with the file, the second argu‐
204       ment  is  the size to be set for the file, and the optional third argu‐
205       ment is a string of characters that specify seals to be set on file.
206
207       The second program, t_get_seals.c, can be used to open an existing file
208       that  was  created via memfd_create() and inspect the set of seals that
209       have been applied to that file.
210
211       The following shell session demonstrates the  use  of  these  programs.
212       First we create a tmpfs(5) file and set some seals on it:
213
214           $ ./t_memfd_create my_memfd_file 4096 sw &
215           [1] 11775
216           PID: 11775; fd: 3; /proc/11775/fd/3
217
218       At this point, the t_memfd_create program continues to run in the back‐
219       ground.  From another program, we can obtain a file descriptor for  the
220       file  created by memfd_create() by opening the /proc/[pid]/fd file that
221       corresponds to the file descriptor  opened  by  memfd_create().   Using
222       that  pathname,  we  inspect the content of the /proc/[pid]/fd symbolic
223       link, and use our t_get_seals program to view the seals that have  been
224       placed on the file:
225
226           $ readlink /proc/11775/fd/3
227           /memfd:my_memfd_file (deleted)
228           $ ./t_get_seals /proc/11775/fd/3
229           Existing seals: WRITE SHRINK
230
231   Program source: t_memfd_create.c
232
233       #define _GNU_SOURCE
234       #include <stdint.h>
235       #include <sys/mman.h>
236       #include <fcntl.h>
237       #include <stdlib.h>
238       #include <unistd.h>
239       #include <string.h>
240       #include <stdio.h>
241
242       #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
243                               } while (0)
244
245       int
246       main(int argc, char *argv[])
247       {
248           int fd;
249           unsigned int seals;
250           char *addr;
251           char *name, *seals_arg;
252           ssize_t len;
253
254           if (argc < 3) {
255               fprintf(stderr, "%s name size [seals]\n", argv[0]);
256               fprintf(stderr, "\t'seals' can contain any of the "
257                       "following characters:\n");
258               fprintf(stderr, "\t\tg - F_SEAL_GROW\n");
259               fprintf(stderr, "\t\ts - F_SEAL_SHRINK\n");
260               fprintf(stderr, "\t\tw - F_SEAL_WRITE\n");
261               fprintf(stderr, "\t\tW - F_SEAL_FUTURE_WRITE\n");
262               fprintf(stderr, "\t\tS - F_SEAL_SEAL\n");
263               exit(EXIT_FAILURE);
264           }
265
266           name = argv[1];
267           len = atoi(argv[2]);
268           seals_arg = argv[3];
269
270           /* Create an anonymous file in tmpfs; allow seals to be
271              placed on the file. */
272
273           fd = memfd_create(name, MFD_ALLOW_SEALING);
274           if (fd == -1)
275               errExit("memfd_create");
276
277           /* Size the file as specified on the command line. */
278
279           if (ftruncate(fd, len) == -1)
280               errExit("truncate");
281
282           printf("PID: %jd; fd: %d; /proc/%jd/fd/%d\n",
283                   (intmax_t) getpid(), fd, (intmax_t) getpid(), fd);
284
285           /* Code to map the file and populate the mapping with data
286              omitted. */
287
288           /* If a 'seals' command-line argument was supplied, set some
289              seals on the file. */
290
291           if (seals_arg != NULL) {
292               seals = 0;
293
294               if (strchr(seals_arg, 'g') != NULL)
295                   seals |= F_SEAL_GROW;
296               if (strchr(seals_arg, 's') != NULL)
297                   seals |= F_SEAL_SHRINK;
298               if (strchr(seals_arg, 'w') != NULL)
299                   seals |= F_SEAL_WRITE;
300               if (strchr(seals_arg, 'W') != NULL)
301                   seals |= F_SEAL_FUTURE_WRITE;
302               if (strchr(seals_arg, 'S') != NULL)
303                   seals |= F_SEAL_SEAL;
304
305               if (fcntl(fd, F_ADD_SEALS, seals) == -1)
306                   errExit("fcntl");
307           }
308
309           /* Keep running, so that the file created by memfd_create()
310              continues to exist. */
311
312           pause();
313
314           exit(EXIT_SUCCESS);
315       }
316
317   Program source: t_get_seals.c
318
319       #define _GNU_SOURCE
320       #include <sys/mman.h>
321       #include <fcntl.h>
322       #include <unistd.h>
323       #include <stdlib.h>
324       #include <string.h>
325       #include <stdio.h>
326
327       #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
328                               } while (0)
329
330       int
331       main(int argc, char *argv[])
332       {
333           int fd;
334           unsigned int seals;
335
336           if (argc != 2) {
337               fprintf(stderr, "%s /proc/PID/fd/FD\n", argv[0]);
338               exit(EXIT_FAILURE);
339           }
340
341           fd = open(argv[1], O_RDWR);
342           if (fd == -1)
343               errExit("open");
344
345           seals = fcntl(fd, F_GET_SEALS);
346           if (seals == -1)
347               errExit("fcntl");
348
349           printf("Existing seals:");
350           if (seals & F_SEAL_SEAL)
351               printf(" SEAL");
352           if (seals & F_SEAL_GROW)
353               printf(" GROW");
354           if (seals & F_SEAL_WRITE)
355               printf(" WRITE");
356           if (seals & F_SEAL_FUTURE_WRITE)
357               printf(" FUTURE_WRITE");
358           if (seals & F_SEAL_SHRINK)
359               printf(" SHRINK");
360           printf("\n");
361
362           /* Code to map the file and access the contents of the
363              resulting mapping omitted. */
364
365           exit(EXIT_SUCCESS);
366       }
367

SEE ALSO

369       fcntl(2), ftruncate(2), mmap(2), shmget(2), shm_open(3)
370

COLOPHON

372       This  page  is  part of release 5.13 of the Linux man-pages project.  A
373       description of the project, information about reporting bugs,  and  the
374       latest     version     of     this    page,    can    be    found    at
375       https://www.kernel.org/doc/man-pages/.
376
377
378
379Linux                             2021-03-22                   MEMFD_CREATE(2)
Impressum