Linux memfd_create
Linux memfd_create() creates an anonymous volatile file and returns a descriptor for file operations and memory mapping.
The name passed to memfd_create() is a debugging label, shown with a memfd: prefix as the link target under /proc/self/fd and limited to 249 bytes, and several files may share one name. The new file starts with size 0 and is sized with ftruncate or filled by writes. It is released automatically once all references are dropped, so a mapping can keep it alive after the original descriptor closes. [1]
Without MFD_ALLOW_SEALING the initial seal set is F_SEAL_SEAL, so no other seals can be added, while with it the set starts empty. Seals let a receiving process rely on a peer being unable to modify or shrink a shared region, which would otherwise expose it to time-of-check-to-time-of-use races or SIGBUS. [1] MFD_NOEXEC_SEAL creates a non-executable object, and the vm.memfd_noexec sysctl, with values 0, 1 and 2, sets the default or rejects creation without that flag. [3] Backing pages are anonymous memory, and tmpfs pages can still be swapped out. [1] [4]
Relations
- related
- Linux file sealing, Memory-mapped file, Open file description, Copy-on-write (storage), tmpfs
Advantages
- A descriptor can identify a shared buffer without a named temporary-file lifecycle. [1]
- It can replace a temporary file or O_TMPFILE when the file is never meant to be linked into a filesystem. [1]
Limitations
- Creation may be restricted by kernel configuration, system policy or sandbox rules. [3]
- Combining MFD_HUGETLB with MFD_ALLOW_SEALING requires Linux 4.16 or later. [1]
- A receiving process has to read the seal mask with F_GET_SEALS before trusting the region. [1]
Citations
- Linux man-pages 6.19: memfd_create(2)
- Linux kernel: non-executable memfd policy
- Linux kernel: tmpfs and swap
Further reading
Sources & caveats
- memfd-api is the Linux man-pages 6.19 memfd_create(2) page, re-read for the name limit, initial size, release rule, seal defaults and the sealing procedure.
- memfd-noexec is the kernel documentation on non-executable memfd objects, re-read for MFD_NOEXEC_SEAL and the three sysctl values.
- tmpfs-doc is the kernel tmpfs documentation, re-read for the use of swap.
- The file-truncation entry links here because a sealed memfd object can forbid shrinking the file.