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

NAME

6       memfd_create - create an anonymous file
7

SYNOPSIS

9       #include <sys/memfd.h>
10
11       int memfd_create(const char *name, unsigned int flags);
12

DESCRIPTION

14       memfd_create()  creates an anonymous file and returns a file descriptor
15       that refers to it.  The file behaves like a regular file, and so can be
16       modified, truncated, memory-mapped, and so on.  However, unlike a regu‐
17       lar file, it lives in RAM and has a volatile backing storage.  Once all
18       references  to  the  file  are  dropped,  it is automatically released.
19       Anonymous memory is used for all backing pages of the file.  Therefore,
20       files created by memfd_create() have the same semantics as other anony‐
21       mous memory allocations such as those allocated using mmap(2) with  the
22       MAP_ANONYMOUS flag.
23
24       The initial size of the file is set to 0.  Following the call, the file
25       size should be set using ftruncate(2).  (Alternatively, the file may be
26       populated by calls to write(2) or similar.)
27
28       The  name  supplied in name is used as a filename and will be displayed
29       as the target of the  corresponding  symbolic  link  in  the  directory
30       /proc/self/fd/.   The displayed name is always prefixed with memfd: and
31       serves only for debugging purposes.  Names do not affect  the  behavior
32       of  the  file  descriptor, and as such multiple files can have the same
33       name without any side effects.
34
35       The following values may be bitwise ORed in flags to change the  behav‐
36       ior of memfd_create():
37
38       MFD_CLOEXEC
39              Set the close-on-exec (FD_CLOEXEC) flag on the new file descrip‐
40              tor.  See the description of the O_CLOEXEC flag in  open(2)  for
41              reasons why this may be useful.
42
43       MFD_ALLOW_SEALING
44              Allow  sealing  operations  on this file.  See the discussion of
45              the F_ADD_SEALS and F_GET_SEALS operations in fcntl(2), and also
46              NOTES,  below.  The initial set of seals is empty.  If this flag
47              is not set, the initial set of seals will be F_SEAL_SEAL,  mean‐
48              ing that no other seals can be set on the file.
49
50       MFD_HUGETLB (since Linux 4.14)
51              The  anonymous  file will be created in the hugetlbfs filesystem
52              using huge pages.  See the Linux kernel source  file  Documenta‐
53              tion/vm/hugetlbpage.txt  for  more  information about hugetlbfs.
54              The hugetlbfs filesystem does not  support  file-sealing  opera‐
55              tions.     Therefore,    specifying    both    MFD_HUGETLB   and
56              MFD_ALLOW_SEALING in flags is disallowed.
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 <sys/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       #include <sys/memfd.h>
226       #include <fcntl.h>
227       #include <stdlib.h>
228       #include <unistd.h>
229       #include <string.h>
230       #include <stdio.h>
231
232       #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
233                               } while (0)
234
235       int
236       main(int argc, char *argv[])
237       {
238           int fd;
239           unsigned int seals;
240           char *addr;
241           char *name, *seals_arg;
242           ssize_t len;
243
244           if (argc < 3) {
245               fprintf(stderr, "%s name size [seals]\n", argv[0]);
246               fprintf(stderr, "\t'seals' can contain any of the "
247                       "following characters:\n");
248               fprintf(stderr, "\t\tg - F_SEAL_GROW\n");
249               fprintf(stderr, "\t\ts - F_SEAL_SHRINK\n");
250               fprintf(stderr, "\t\tw - F_SEAL_WRITE\n");
251               fprintf(stderr, "\t\tS - F_SEAL_SEAL\n");
252               exit(EXIT_FAILURE);
253           }
254
255           name = argv[1];
256           len = atoi(argv[2]);
257           seals_arg = argv[3];
258
259           /* Create an anonymous file in tmpfs; allow seals to be
260              placed on the file */
261
262           fd = memfd_create(name, MFD_ALLOW_SEALING);
263           if (fd == -1)
264               errExit("memfd_create");
265
266           /* Size the file as specified on the command line */
267
268           if (ftruncate(fd, len) == -1)
269               errExit("truncate");
270
271           printf("PID: %ld; fd: %d; /proc/%ld/fd/%d\n",
272                   (long) getpid(), fd, (long) getpid(), fd);
273
274           /* Code to map the file and populate the mapping with data
275              omitted */
276
277           /* If a 'seals' command-line argument was supplied, set some
278              seals on the file */
279
280           if (seals_arg != NULL) {
281               seals = 0;
282
283               if (strchr(seals_arg, 'g') != NULL)
284                   seals |= F_SEAL_GROW;
285               if (strchr(seals_arg, 's') != NULL)
286                   seals |= F_SEAL_SHRINK;
287               if (strchr(seals_arg, 'w') != NULL)
288                   seals |= F_SEAL_WRITE;
289               if (strchr(seals_arg, 'S') != NULL)
290                   seals |= F_SEAL_SEAL;
291
292               if (fcntl(fd, F_ADD_SEALS, seals) == -1)
293                   errExit("fcntl");
294           }
295
296           /* Keep running, so that the file created by memfd_create()
297              continues to exist */
298
299           pause();
300
301           exit(EXIT_SUCCESS);
302       }
303
304   Program source: t_get_seals.c
305
306       #include <sys/memfd.h>
307       #include <fcntl.h>
308       #include <unistd.h>
309       #include <stdlib.h>
310       #include <string.h>
311       #include <stdio.h>
312
313       #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
314                               } while (0)
315
316       int
317       main(int argc, char *argv[])
318       {
319           int fd;
320           unsigned int seals;
321
322           if (argc != 2) {
323               fprintf(stderr, "%s /proc/PID/fd/FD\n", argv[0]);
324               exit(EXIT_FAILURE);
325           }
326
327           fd = open(argv[1], O_RDWR);
328           if (fd == -1)
329               errExit("open");
330
331           seals = fcntl(fd, F_GET_SEALS);
332           if (seals == -1)
333               errExit("fcntl");
334
335           printf("Existing seals:");
336           if (seals & F_SEAL_SEAL)
337               printf(" SEAL");
338           if (seals & F_SEAL_GROW)
339               printf(" GROW");
340           if (seals & F_SEAL_WRITE)
341               printf(" WRITE");
342           if (seals & F_SEAL_SHRINK)
343               printf(" SHRINK");
344           printf("\n");
345
346           /* Code to map the file and access the contents of the
347              resulting mapping omitted */
348
349           exit(EXIT_SUCCESS);
350       }
351

SEE ALSO

353       fcntl(2), ftruncate(2), mmap(2), shmget(2), shm_open(3)
354

COLOPHON

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