1 //! Interfaces for managing memory-backed files.
2
3 use std::os::unix::io::RawFd;
4 use crate::Result;
5 use crate::errno::Errno;
6 use std::ffi::CStr;
7
8 libc_bitflags!(
9 /// Options that change the behavior of [`memfd_create`].
10 pub struct MemFdCreateFlag: libc::c_uint {
11 /// Set the close-on-exec ([`FD_CLOEXEC`]) flag on the new file descriptor.
12 ///
13 /// By default, the new file descriptor is set to remain open across an [`execve`]
14 /// (the `FD_CLOEXEC` flag is initially disabled). This flag can be used to change
15 /// this default. The file offset is set to the beginning of the file (see [`lseek`]).
16 ///
17 /// See also the description of the `O_CLOEXEC` flag in [`open(2)`].
18 ///
19 /// [`execve`]: crate::unistd::execve
20 /// [`lseek`]: crate::unistd::lseek
21 /// [`FD_CLOEXEC`]: crate::fcntl::FdFlag::FD_CLOEXEC
22 /// [`open(2)`]: https://man7.org/linux/man-pages/man2/open.2.html
23 MFD_CLOEXEC;
24 /// Allow sealing operations on this file.
25 ///
26 /// See also the file sealing notes given in [`memfd_create(2)`].
27 ///
28 /// [`memfd_create(2)`]: https://man7.org/linux/man-pages/man2/memfd_create.2.html
29 MFD_ALLOW_SEALING;
30 }
31 );
32
33 /// Creates an anonymous file that lives in memory, and return a file-descriptor to it.
34 ///
35 /// The file behaves like a regular file, and so can be modified, truncated, memory-mapped, and so on.
36 /// However, unlike a regular file, it lives in RAM and has a volatile backing storage.
37 ///
38 /// For more information, see [`memfd_create(2)`].
39 ///
40 /// [`memfd_create(2)`]: https://man7.org/linux/man-pages/man2/memfd_create.2.html
memfd_create(name: &CStr, flags: MemFdCreateFlag) -> Result<RawFd>41 pub fn memfd_create(name: &CStr, flags: MemFdCreateFlag) -> Result<RawFd> {
42 let res = unsafe {
43 libc::syscall(libc::SYS_memfd_create, name.as_ptr(), flags.bits())
44 };
45
46 Errno::result(res).map(|r| r as RawFd)
47 }
48