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
77       descriptor  is inherited by the child produced by fork(2) and refers to
78       the same file.  The file  descriptor  is  preserved  across  execve(2),
79       unless 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

CONFORMING TO

108       The memfd_create() system call is Linux-specific.
109

NOTES

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
128       region in problematic ways.  For example, an untrusted peer might  mod‐
129       ify 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
139       employs 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
158          future 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
183          retrieve  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
187          restrictions  (so  long  as  the  F_SEAL_SEAL  seal has not yet been
188          applied).
189

EXAMPLES

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
196       optionally  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 <sys/mman.h>
230       #include <fcntl.h>
231       #include <stdlib.h>
232       #include <unistd.h>
233       #include <string.h>
234       #include <stdio.h>
235
236       #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
237                               } while (0)
238
239       int
240       main(int argc, char *argv[])
241       {
242           int fd;
243           unsigned int seals;
244           char *addr;
245           char *name, *seals_arg;
246           ssize_t len;
247
248           if (argc < 3) {
249               fprintf(stderr, "%s name size [seals]\n", argv[0]);
250               fprintf(stderr, "\t'seals' can contain any of the "
251                       "following characters:\n");
252               fprintf(stderr, "\t\tg - F_SEAL_GROW\n");
253               fprintf(stderr, "\t\ts - F_SEAL_SHRINK\n");
254               fprintf(stderr, "\t\tw - F_SEAL_WRITE\n");
255               fprintf(stderr, "\t\tW - F_SEAL_FUTURE_WRITE\n");
256               fprintf(stderr, "\t\tS - F_SEAL_SEAL\n");
257               exit(EXIT_FAILURE);
258           }
259
260           name = argv[1];
261           len = atoi(argv[2]);
262           seals_arg = argv[3];
263
264           /* Create an anonymous file in tmpfs; allow seals to be
265              placed on the file */
266
267           fd = memfd_create(name, MFD_ALLOW_SEALING);
268           if (fd == -1)
269               errExit("memfd_create");
270
271           /* Size the file as specified on the command line */
272
273           if (ftruncate(fd, len) == -1)
274               errExit("truncate");
275
276           printf("PID: %ld; fd: %d; /proc/%ld/fd/%d\n",
277                   (long) getpid(), fd, (long) getpid(), fd);
278
279           /* Code to map the file and populate the mapping with data
280              omitted */
281
282           /* If a 'seals' command-line argument was supplied, set some
283              seals on the file */
284
285           if (seals_arg != NULL) {
286               seals = 0;
287
288               if (strchr(seals_arg, 'g') != NULL)
289                   seals |= F_SEAL_GROW;
290               if (strchr(seals_arg, 's') != NULL)
291                   seals |= F_SEAL_SHRINK;
292               if (strchr(seals_arg, 'w') != NULL)
293                   seals |= F_SEAL_WRITE;
294               if (strchr(seals_arg, 'W') != NULL)
295                   seals |= F_SEAL_FUTURE_WRITE;
296               if (strchr(seals_arg, 'S') != NULL)
297                   seals |= F_SEAL_SEAL;
298
299               if (fcntl(fd, F_ADD_SEALS, seals) == -1)
300                   errExit("fcntl");
301           }
302
303           /* Keep running, so that the file created by memfd_create()
304              continues to exist */
305
306           pause();
307
308           exit(EXIT_SUCCESS);
309       }
310
311   Program source: t_get_seals.c
312
313       #define _GNU_SOURCE
314       #include <sys/mman.h>
315       #include <fcntl.h>
316       #include <unistd.h>
317       #include <stdlib.h>
318       #include <string.h>
319       #include <stdio.h>
320
321       #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
322                               } while (0)
323
324       int
325       main(int argc, char *argv[])
326       {
327           int fd;
328           unsigned int seals;
329
330           if (argc != 2) {
331               fprintf(stderr, "%s /proc/PID/fd/FD\n", argv[0]);
332               exit(EXIT_FAILURE);
333           }
334
335           fd = open(argv[1], O_RDWR);
336           if (fd == -1)
337               errExit("open");
338
339           seals = fcntl(fd, F_GET_SEALS);
340           if (seals == -1)
341               errExit("fcntl");
342
343           printf("Existing seals:");
344           if (seals & F_SEAL_SEAL)
345               printf(" SEAL");
346           if (seals & F_SEAL_GROW)
347               printf(" GROW");
348           if (seals & F_SEAL_WRITE)
349               printf(" WRITE");
350           if (seals & F_SEAL_FUTURE_WRITE)
351               printf(" FUTURE_WRITE");
352           if (seals & F_SEAL_SHRINK)
353               printf(" SHRINK");
354           printf("\n");
355
356           /* Code to map the file and access the contents of the
357              resulting mapping omitted */
358
359           exit(EXIT_SUCCESS);
360       }
361

SEE ALSO

363       fcntl(2), ftruncate(2), mmap(2), shmget(2), shm_open(3)
364

COLOPHON

366       This page is part of release 5.07 of the Linux  man-pages  project.   A
367       description  of  the project, information about reporting bugs, and the
368       latest    version    of    this    page,    can     be     found     at
369       https://www.kernel.org/doc/man-pages/.
370
371
372
373Linux                             2020-06-09                   MEMFD_CREATE(2)
Impressum