use std::io;
use std::process::Command;
pub struct SharedMemory(imp::Memory);
impl SharedMemory {
pub fn create(name: &str, len: usize) -> io::Result<Self> {
imp::Memory::create(name, len).map(Self)
}
#[must_use]
pub fn as_ptr(&self) -> *mut u8 {
self.0.as_ptr()
}
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn hand_to(&self, command: &mut Command, flag: &str) {
self.0.hand_to(command, flag);
}
pub fn handed_over(&mut self) {
self.0.handed_over();
}
}
#[cfg(all(
unix,
any(
target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "watchos",
target_os = "visionos"
)
))]
mod imp {
use std::io;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::process::Command;
use std::ptr::NonNull;
pub struct Memory {
base: NonNull<u8>,
len: usize,
descriptor: Option<OwnedFd>,
}
unsafe impl Send for Memory {}
unsafe impl Sync for Memory {}
impl Memory {
pub fn create(name: &str, len: usize) -> io::Result<Self> {
if len == 0 {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "empty memory"));
}
let descriptor = create_descriptor(name)?;
let size = libc::off_t::try_from(len).map_err(io::Error::other)?;
if unsafe { libc::ftruncate(descriptor.as_raw_fd(), size) } != 0 {
return Err(io::Error::last_os_error());
}
seal(&descriptor)?;
let base = unsafe {
libc::mmap(
std::ptr::null_mut(),
len,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_SHARED,
descriptor.as_raw_fd(),
0,
)
};
if base == libc::MAP_FAILED {
return Err(io::Error::last_os_error());
}
let base = NonNull::new(base.cast()).ok_or_else(|| io::Error::other("null mapping"))?;
Ok(Self {
base,
len,
descriptor: Some(descriptor),
})
}
pub const fn as_ptr(&self) -> *mut u8 {
self.base.as_ptr()
}
pub const fn len(&self) -> usize {
self.len
}
pub fn hand_to(&self, command: &mut Command, flag: &str) {
use std::os::unix::process::CommandExt;
let Some(fd) = self.descriptor.as_ref().map(AsRawFd::as_raw_fd) else {
return;
};
command.arg(format!("{flag}{fd}"));
unsafe {
command.pre_exec(move || {
if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {
return Err(io::Error::last_os_error());
}
Ok(())
});
}
}
pub fn handed_over(&mut self) {
self.descriptor = None;
}
}
impl Drop for Memory {
fn drop(&mut self) {
unsafe { libc::munmap(self.base.as_ptr().cast(), self.len) };
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn create_descriptor(name: &str) -> io::Result<OwnedFd> {
let name = std::ffi::CString::new(name).map_err(io::Error::other)?;
let fd = unsafe {
libc::syscall(
libc::SYS_memfd_create,
name.as_ptr(),
libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING,
)
};
if fd < 0 {
return Err(io::Error::last_os_error());
}
let fd = libc::c_int::try_from(fd).map_err(io::Error::other)?;
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn seal(descriptor: &OwnedFd) -> io::Result<()> {
let sealed = unsafe {
libc::fcntl(
descriptor.as_raw_fd(),
libc::F_ADD_SEALS,
libc::F_SEAL_SHRINK | libc::F_SEAL_GROW | libc::F_SEAL_SEAL,
)
};
if sealed != 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "watchos",
target_os = "visionos"
))]
fn create_descriptor(_name: &str) -> io::Result<OwnedFd> {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
for _ in 0..8 {
let name = format!(
"/tilo-m{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
);
let name = std::ffi::CString::new(name).map_err(io::Error::other)?;
let fd = unsafe {
libc::shm_open(
name.as_ptr(),
libc::O_RDWR | libc::O_CREAT | libc::O_EXCL,
libc::c_uint::from(0o600u16),
)
};
if fd < 0 {
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(libc::EEXIST) {
continue;
}
return Err(error);
}
let descriptor = unsafe { OwnedFd::from_raw_fd(fd) };
unsafe { libc::shm_unlink(name.as_ptr()) };
if unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) } != 0 {
return Err(io::Error::last_os_error());
}
return Ok(descriptor);
}
Err(io::Error::from(io::ErrorKind::AlreadyExists))
}
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "watchos",
target_os = "visionos"
))]
#[allow(
clippy::unnecessary_wraps,
clippy::missing_const_for_fn,
reason = "the signature is shared with the Linux seal, which can fail"
)]
fn seal(_descriptor: &OwnedFd) -> io::Result<()> {
Ok(())
}
}
#[cfg(all(
unix,
not(any(
target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "watchos",
target_os = "visionos"
))
))]
mod imp {
use std::io;
use std::process::Command;
pub struct Memory(std::convert::Infallible);
impl Memory {
pub fn create(_name: &str, _len: usize) -> io::Result<Self> {
Err(io::ErrorKind::Unsupported.into())
}
pub const fn as_ptr(&self) -> *mut u8 {
match self.0 {}
}
pub const fn len(&self) -> usize {
match self.0 {}
}
pub const fn hand_to(&self, _command: &mut Command, _flag: &str) {
match self.0 {}
}
pub const fn handed_over(&self) {
match self.0 {}
}
}
}
#[cfg(not(unix))]
mod imp {
use std::io;
use std::process::Command;
pub struct Memory(std::convert::Infallible);
impl Memory {
pub fn create(_name: &str, _len: usize) -> io::Result<Self> {
Err(io::ErrorKind::Unsupported.into())
}
pub const fn as_ptr(&self) -> *mut u8 {
match self.0 {}
}
pub const fn len(&self) -> usize {
match self.0 {}
}
pub const fn hand_to(&self, _command: &mut Command, _flag: &str) {
match self.0 {}
}
pub const fn handed_over(&self) {
match self.0 {}
}
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use tilo_test_env::SpawnUnderEnvLock as _;
fn run_child(memory: &mut SharedMemory, script: &str) -> io::Result<std::process::ExitStatus> {
let mut command = Command::new("/bin/sh");
command.args([
"-c",
&format!("for argument; do fd=${{argument#--memory=}}; done\n{script}"),
"child",
]);
memory.hand_to(&mut command, "--memory=");
let mut child = command.spawn_locked()?;
memory.handed_over();
child.wait()
}
#[test]
#[cfg(target_os = "linux")]
fn a_child_writes_into_the_memory_it_inherits() {
let mut memory = SharedMemory::create("tilo-process-test", 4096).unwrap();
let status = run_child(
&mut memory,
"printf '\\001\\002\\003\\004' | dd of=/dev/fd/$fd bs=1 seek=8 conv=notrunc status=none",
)
.unwrap();
assert!(status.success(), "{status}");
let written = unsafe { std::slice::from_raw_parts(memory.as_ptr(), 12) };
assert_eq!(written, [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4]);
}
tilo_test_env::scenario! {
fn shared_memory_is_inherited_once_and_never_empty;
phase a_child_inherits_the_memory_once;
{
let mut memory = SharedMemory::create("tilo-process-test", 4096).unwrap();
assert_eq!(memory.len(), 4096);
assert!(
run_child(&mut memory, "[ -e /dev/fd/$fd ]")
.unwrap()
.success()
);
let mut again = Command::new("/bin/true");
memory.hand_to(&mut again, "--memory=");
assert_eq!(again.get_args().count(), 0);
}
phase empty_memory_is_refused;
{
assert!(SharedMemory::create("tilo-process-test", 0).is_err());
}
}
}