diff --git a/changelog/2431.changed.md b/changelog/2431.changed.md new file mode 100644 index 0000000000..a1ddf7b702 --- /dev/null +++ b/changelog/2431.changed.md @@ -0,0 +1 @@ +Change the type of the `name` argument of `memfd_create()` from `&CStr` to `(name: &P)` diff --git a/src/sys/memfd.rs b/src/sys/memfd.rs index 22ee5fc5b7..02afdfb7c8 100644 --- a/src/sys/memfd.rs +++ b/src/sys/memfd.rs @@ -4,8 +4,7 @@ use cfg_if::cfg_if; use std::os::unix::io::{FromRawFd, OwnedFd, RawFd}; use crate::errno::Errno; -use crate::Result; -use std::ffi::CStr; +use crate::{NixPath, Result}; libc_bitflags!( /// Options that change the behavior of [`memfd_create`]. @@ -84,9 +83,13 @@ libc_bitflags!( /// /// [`memfd_create(2)`]: https://man7.org/linux/man-pages/man2/memfd_create.2.html #[inline] // Delays codegen, preventing linker errors with dylibs and --no-allow-shlib-undefined -pub fn memfd_create(name: &CStr, flags: MemFdCreateFlag) -> Result { - let res = unsafe { - cfg_if! { +pub fn memfd_create( + name: &P, + flags: MemFdCreateFlag, +) -> Result { + let res = name.with_nix_path(|cstr| { + unsafe { + cfg_if! { if #[cfg(all( // Android does not have a memfd_create symbol not(target_os = "android"), @@ -97,12 +100,13 @@ pub fn memfd_create(name: &CStr, flags: MemFdCreateFlag) -> Result { target_env = "musl", )))] { - libc::memfd_create(name.as_ptr(), flags.bits()) + libc::memfd_create(cstr.as_ptr(), flags.bits()) } else { - libc::syscall(libc::SYS_memfd_create, name.as_ptr(), flags.bits()) + libc::syscall(libc::SYS_memfd_create, cstr.as_ptr(), flags.bits()) } } - }; + } + })?; Errno::result(res).map(|r| unsafe { OwnedFd::from_raw_fd(r as RawFd) }) } diff --git a/test/sys/mod.rs b/test/sys/mod.rs index fb3f6be0e5..26805c239f 100644 --- a/test/sys/mod.rs +++ b/test/sys/mod.rs @@ -82,3 +82,6 @@ mod test_statfs; target_os = "haiku" )))] mod test_resource; + +#[cfg(any(linux_android, target_os = "freebsd"))] +mod test_memfd; \ No newline at end of file diff --git a/test/sys/test_memfd.rs b/test/sys/test_memfd.rs new file mode 100644 index 0000000000..09ea344992 --- /dev/null +++ b/test/sys/test_memfd.rs @@ -0,0 +1,22 @@ +use nix::sys::memfd::memfd_create; +use nix::sys::memfd::MemFdCreateFlag; +use nix::unistd::lseek; +use nix::unistd::read; +use nix::unistd::{write, Whence}; +use std::os::fd::{AsFd, AsRawFd}; + +#[test] +fn test_memfd_create() { + let fd = + memfd_create("test_memfd_create_name", MemFdCreateFlag::MFD_CLOEXEC) + .unwrap(); + let contents = b"hello"; + assert_eq!(write(fd.as_fd(), contents).unwrap(), 5); + + lseek(fd.as_raw_fd(), 0, Whence::SeekSet).unwrap(); + + let mut buf = vec![0_u8; contents.len()]; + assert_eq!(read(fd.as_raw_fd(), &mut buf).unwrap(), 5); + + assert_eq!(contents, buf.as_slice()); +}