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.)
157
158       4. A second process obtains a file descriptor for the tmpfs(5) file and
159          maps it.  Among the possible ways in which this could happen are the
160          following:
161
162          *  The process that called memfd_create() could transfer the result‐
163             ing  file  descriptor  to  the  second  process via a UNIX domain
164             socket (see unix(7) and cmsg(3)).  The second process  then  maps
165             the file using mmap(2).
166
167          *  The  second process is created via fork(2) and thus automatically
168             inherits the file descriptor and mapping.   (Note  that  in  this
169             case  and the next, there is a natural trust relationship between
170             the two processes, since they are running under the same user ID.
171             Therefore, file sealing would not normally be necessary.)
172
173          *  The  second  process  opens  the  file /proc/<pid>/fd/<fd>, where
174             <pid> is the PID of  the  first  process  (the  one  that  called
175             memfd_create()),  and  <fd>  is the number of the file descriptor
176             returned by the call to memfd_create() in that process.  The sec‐
177             ond process then maps the file using mmap(2).
178
179       5. The  second  process  uses  the  fcntl(2)  F_GET_SEALS  operation to
180          retrieve the bit mask of seals that has been applied  to  the  file.
181          This  bit  mask can be inspected in order to determine what kinds of
182          restrictions have been placed on file  modifications.   If  desired,
183          the  second  process  can  apply  further seals to impose additional
184          restrictions (so long as the  F_SEAL_SEAL  seal  has  not  yet  been
185          applied).
186

EXAMPLE

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

SEE ALSO

355       fcntl(2), ftruncate(2), mmap(2), shmget(2), shm_open(3)
356

COLOPHON

358       This  page  is  part of release 5.02 of the Linux man-pages project.  A
359       description of the project, information about reporting bugs,  and  the
360       latest     version     of     this    page,    can    be    found    at
361       https://www.kernel.org/doc/man-pages/.
362
363
364
365Linux                             2019-03-06                   MEMFD_CREATE(2)
Impressum