use std::fs::File;
use std::io;
use std::os::fd::AsRawFd;
use std::ptr::NonNull;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering, fence};
use std::time::Duration;
fn checked_range(map_len: usize, offset: u64, len: u64) -> Option<usize> {
let end = offset.checked_add(len)?;
if end > map_len as u64 {
return None;
}
usize::try_from(end).ok()
}
fn checked_word(map_len: usize, offset: u64) -> Option<usize> {
if offset % 8 != 0 {
return None;
}
checked_range(map_len, offset, 4)?;
usize::try_from(offset).ok()
}
fn last_os_error() -> io::Error {
io::Error::last_os_error()
}
fn map(file: &File, len: usize, prot: libc::c_int) -> io::Result<NonNull<u8>> {
if len == 0 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"cannot map zero bytes",
));
}
let ptr = unsafe {
libc::mmap(
std::ptr::null_mut(),
len,
prot,
libc::MAP_SHARED,
file.as_raw_fd(),
0,
)
};
if ptr == libc::MAP_FAILED {
return Err(last_os_error());
}
NonNull::new(ptr.cast::<u8>()).ok_or_else(|| io::Error::other("mmap returned null"))
}
unsafe fn unmap(ptr: NonNull<u8>, len: usize) {
unsafe {
libc::munmap(ptr.as_ptr().cast(), len);
}
}
pub(crate) fn page_size() -> usize {
let n = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
if n <= 0 { 4096 } else { n as usize }
}
fn msync(ptr: NonNull<u8>, map_len: usize, offset: u64, len: u64) -> io::Result<()> {
if len == 0 {
return Ok(());
}
let end = checked_range(map_len, offset, len)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "msync range out of bounds"))?;
let page = page_size();
let start = (offset as usize) / page * page;
let rc = unsafe { libc::msync(ptr.as_ptr().add(start).cast(), end - start, libc::MS_SYNC) };
if rc != 0 {
Err(last_os_error())
} else {
Ok(())
}
}
#[derive(Debug)]
struct Region {
ptr: NonNull<u8>,
len: usize,
}
unsafe impl Send for Region {}
unsafe impl Sync for Region {}
impl Drop for Region {
fn drop(&mut self) {
unsafe { unmap(self.ptr, self.len) }
}
}
#[derive(Debug)]
pub(crate) struct MapRw {
ptr: NonNull<u8>,
len: usize,
region: Arc<Region>,
}
unsafe impl Send for MapRw {}
impl MapRw {
pub(crate) fn new(file: &File, len: usize) -> io::Result<MapRw> {
let ptr = map(file, len, libc::PROT_READ | libc::PROT_WRITE)?;
Ok(MapRw {
ptr,
len,
region: Arc::new(Region { ptr, len }),
})
}
pub(crate) fn advice(&self) -> Advice {
Advice {
region: Arc::clone(&self.region),
}
}
pub(crate) fn len(&self) -> usize {
self.len
}
fn word(&self, offset: u64) -> Option<&AtomicU32> {
let off = checked_word(self.len, offset)?;
Some(unsafe { AtomicU32::from_ptr(self.ptr.as_ptr().add(off).cast::<u32>()) })
}
pub(crate) fn commit_word(&self, offset: u64) -> Option<u32> {
Some(self.word(offset)?.load(Ordering::Acquire))
}
pub(crate) fn store_commit_word(&self, offset: u64, value: u32) -> Option<()> {
self.word(offset)?.store(value, Ordering::Release);
Some(())
}
pub(crate) fn bytes_mut(&mut self, offset: u64, len: u64) -> Option<&mut [u8]> {
let end = checked_range(self.len, offset, len)?;
let start = offset as usize;
Some(unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr().add(start), end - start) })
}
pub(crate) fn bytes(&self, offset: u64, len: u64) -> Option<&[u8]> {
let end = checked_range(self.len, offset, len)?;
let start = offset as usize;
Some(unsafe { std::slice::from_raw_parts(self.ptr.as_ptr().add(start), end - start) })
}
pub(crate) fn sync_range(&self, offset: u64, len: u64) -> io::Result<()> {
msync(self.ptr, self.len, offset, len)
}
pub(crate) fn flush_handle(&self) -> Flush {
Flush {
region: Arc::clone(&self.region),
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct Flush {
region: Arc<Region>,
}
impl Flush {
pub(crate) fn sync_range(&self, offset: u64, len: u64) -> io::Result<()> {
msync(self.region.ptr, self.region.len, offset, len)
}
}
#[derive(Debug, Clone)]
pub(crate) struct Advice {
region: Arc<Region>,
}
impl Advice {
pub(crate) fn len(&self) -> u64 {
self.region.len as u64
}
pub(crate) fn prefault(&self, offset: u64, len: u64) -> io::Result<()> {
let map_len = self.region.len;
let page = page_size();
let start = usize::try_from(offset).unwrap_or(usize::MAX).min(map_len) / page * page;
let end = usize::try_from(offset.saturating_add(len))
.unwrap_or(usize::MAX)
.min(map_len);
if start >= end {
return Ok(());
}
#[cfg(not(any(target_vendor = "apple", target_os = "linux")))]
return Ok(());
#[cfg(any(target_vendor = "apple", target_os = "linux"))]
{
#[cfg(target_vendor = "apple")]
let advice = libc::MADV_WILLNEED;
#[cfg(target_os = "linux")]
let advice = libc::MADV_POPULATE_WRITE;
let ptr = self.region.ptr.as_ptr();
let rc = unsafe { libc::madvise(ptr.add(start).cast(), end - start, advice) };
if rc != 0 {
Err(last_os_error())
} else {
Ok(())
}
}
}
}
pub(crate) const MAPPED_READS: bool = cfg!(any(target_arch = "x86_64", target_arch = "aarch64"));
#[derive(Debug)]
pub(crate) struct MapRo {
ptr: NonNull<u8>,
len: usize,
}
unsafe impl Send for MapRo {}
impl MapRo {
pub(crate) fn new(file: &File, len: usize) -> io::Result<MapRo> {
if !MAPPED_READS {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"read-only mappings are not used on this target",
));
}
let ptr = map(file, len, libc::PROT_READ)?;
Ok(MapRo { ptr, len })
}
pub(crate) fn commit_word(&self, offset: u64) -> Option<u32> {
let off = checked_word(self.len, offset)?;
let word = unsafe { &*self.ptr.as_ptr().add(off).cast::<AtomicU32>() };
let value = word.load(Ordering::Relaxed);
if value != 0 {
fence(Ordering::Acquire);
}
Some(value)
}
pub(crate) fn load_u32(&self, offset: u64) -> Option<u32> {
if offset % 4 != 0 {
return None;
}
checked_range(self.len, offset, 4)?;
let word = unsafe { &*self.ptr.as_ptr().add(offset as usize).cast::<AtomicU32>() };
Some(word.load(Ordering::Relaxed))
}
pub(crate) fn words(&self, offset: u64, count: u64) -> Option<SharedWords<'_>> {
if offset % 8 != 0 {
return None;
}
let end = checked_range(self.len, offset, count.checked_mul(8)?)?;
let start = offset as usize;
let words = unsafe {
std::slice::from_raw_parts(
self.ptr.as_ptr().add(start).cast::<AtomicU64>(),
(end - start) / 8,
)
};
Some(SharedWords { words })
}
pub(crate) unsafe fn committed_bytes(&self, offset: u64, len: u64) -> Option<&[u8]> {
let end = checked_range(self.len, offset, len)?;
let start = offset as usize;
Some(unsafe { std::slice::from_raw_parts(self.ptr.as_ptr().add(start), end - start) })
}
}
impl Drop for MapRo {
fn drop(&mut self) {
unsafe { unmap(self.ptr, self.len) }
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct SharedWords<'a> {
words: &'a [AtomicU64],
}
impl<'a> SharedWords<'a> {
#[cfg_attr(not(any(test, fuzzing)), allow(dead_code))]
pub(crate) fn new(words: &'a [AtomicU64]) -> SharedWords<'a> {
SharedWords { words }
}
#[inline]
pub(crate) fn len(self) -> usize {
self.words.len()
}
#[inline]
pub(crate) fn get(self, i: usize) -> Option<u64> {
Some(self.words.get(i)?.load(Ordering::Relaxed))
}
#[inline]
pub(crate) fn split_at_checked(self, mid: usize) -> Option<(SharedWords<'a>, SharedWords<'a>)> {
let (a, b) = self.words.split_at_checked(mid)?;
Some((SharedWords { words: a }, SharedWords { words: b }))
}
#[inline]
pub(crate) fn iter(self) -> impl Iterator<Item = u64> + 'a {
self.words.iter().map(|w| w.load(Ordering::Relaxed))
}
#[inline]
pub(crate) fn chunks_exact(
self,
n: usize,
) -> (impl Iterator<Item = SharedWords<'a>>, SharedWords<'a>) {
let chunks = self.words.chunks_exact(n);
let rest = SharedWords {
words: chunks.remainder(),
};
(chunks.map(|words| SharedWords { words }), rest)
}
}
const NOTIFY_REGION_LEN: usize = 4096;
const NOTIFY_EVENT: u64 = 0;
const NOTIFY_WAITERS: u64 = 64;
const NOTIFY_WRITER_FLAG: u64 = 128;
const NOTIFY_NONCE_LO: u64 = 192;
const NOTIFY_NONCE_HI: u64 = 200;
pub(crate) const NOTIFY_NAME_LEN: usize = 28;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NotifyLocation {
Memfd { pid: u32, fd: i32 },
Shm { name: [u8; NOTIFY_NAME_LEN] },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WaitOutcome {
Returned,
Unsupported,
}
#[derive(Debug)]
pub(crate) struct Notify {
map: MapRw,
owner: Option<Owner>,
}
#[derive(Debug)]
struct Owner {
#[allow(dead_code)]
file: File,
#[cfg_attr(not(target_vendor = "apple"), allow(dead_code))]
name: Option<[u8; NOTIFY_NAME_LEN]>,
}
impl Notify {
pub(crate) fn create(nonce: u64) -> io::Result<(Notify, NotifyLocation)> {
let (file, location, name) = create_region(nonce)?;
let mapped = (|| {
file.set_len(NOTIFY_REGION_LEN as u64)?;
#[cfg(target_os = "linux")]
seal(&file)?;
MapRw::new(&file, NOTIFY_REGION_LEN)
})();
let map = match mapped {
Ok(map) => map,
Err(e) => {
if let Some(name) = &name {
unlink_region(name);
}
return Err(e);
}
};
let notify = Notify {
map,
owner: Some(Owner { file, name }),
};
notify
.word(NOTIFY_NONCE_LO)
.store(nonce as u32, Ordering::SeqCst);
notify
.word(NOTIFY_NONCE_HI)
.store((nonce >> 32) as u32, Ordering::SeqCst);
notify.word(NOTIFY_WRITER_FLAG).store(1, Ordering::SeqCst);
Ok((notify, location))
}
pub(crate) fn attach(location: &NotifyLocation, nonce: u64) -> io::Result<Notify> {
let file = open_region(location)?;
if file.metadata()?.len() < NOTIFY_REGION_LEN as u64 {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"notify region too short",
));
}
let notify = Notify {
map: MapRw::new(&file, NOTIFY_REGION_LEN)?,
owner: None,
};
if notify.nonce() != nonce {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"notify region belongs to another writer",
));
}
Ok(notify)
}
fn word(&self, offset: u64) -> &AtomicU32 {
self.map
.word(offset)
.unwrap_or_else(|| unreachable!("notify offsets are in bounds"))
}
fn nonce(&self) -> u64 {
u64::from(self.word(NOTIFY_NONCE_LO).load(Ordering::SeqCst))
| u64::from(self.word(NOTIFY_NONCE_HI).load(Ordering::SeqCst)) << 32
}
pub(crate) fn publisher(&self) -> NotifyPublisher {
NotifyPublisher {
region: Arc::clone(&self.map.region),
}
}
pub(crate) fn writer_notifies(&self) -> bool {
self.word(NOTIFY_WRITER_FLAG).load(Ordering::SeqCst) != 0
}
pub(crate) fn publish(&self) {
let event = self.word(NOTIFY_EVENT);
event.fetch_add(1, Ordering::SeqCst);
if self.word(NOTIFY_WAITERS).load(Ordering::SeqCst) != 0 {
wake_all(event);
}
}
pub(crate) fn begin_wait(&self) -> u32 {
self.word(NOTIFY_WAITERS).fetch_add(1, Ordering::SeqCst);
self.word(NOTIFY_EVENT).load(Ordering::SeqCst)
}
pub(crate) fn wait(&self, seen: u32, timeout: Duration) -> WaitOutcome {
#[cfg(test)]
{
test_hooks::WAITS.fetch_add(1, Ordering::SeqCst);
if test_hooks::FORCE_UNSUPPORTED.load(Ordering::SeqCst) {
return WaitOutcome::Unsupported;
}
}
wait_on(self.word(NOTIFY_EVENT), seen, timeout)
}
pub(crate) fn end_wait(&self) {
let waiters = self.word(NOTIFY_WAITERS);
let mut current = waiters.load(Ordering::SeqCst);
while current != 0 {
match waiters.compare_exchange_weak(
current,
current - 1,
Ordering::SeqCst,
Ordering::SeqCst,
) {
Ok(_) => break,
Err(actual) => current = actual,
}
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct NotifyPublisher {
region: Arc<Region>,
}
impl NotifyPublisher {
fn word(&self, offset: u64) -> &AtomicU32 {
let off = checked_word(self.region.len, offset)
.unwrap_or_else(|| unreachable!("notify offsets are in bounds"));
unsafe { AtomicU32::from_ptr(self.region.ptr.as_ptr().add(off).cast::<u32>()) }
}
pub(crate) fn publish(&self) {
let event = self.word(NOTIFY_EVENT);
event.fetch_add(1, Ordering::SeqCst);
if self.word(NOTIFY_WAITERS).load(Ordering::SeqCst) != 0 {
wake_all(event);
}
}
#[cfg(test)]
pub(crate) fn event(&self) -> u32 {
self.word(NOTIFY_EVENT).load(Ordering::SeqCst)
}
}
impl Notify {
pub(crate) fn release_after_fork(mut self) {
self.owner = None;
}
}
impl Drop for Notify {
fn drop(&mut self) {
let Some(owner) = &self.owner else { return };
self.word(NOTIFY_WRITER_FLAG).store(0, Ordering::SeqCst);
self.publish();
if let Some(name) = &owner.name {
unlink_region(name);
}
}
}
#[cfg(test)]
pub(crate) mod test_hooks {
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicU64};
pub(crate) static WAITS: AtomicU64 = AtomicU64::new(0);
pub(crate) static FORCE_UNSUPPORTED: AtomicBool = AtomicBool::new(false);
pub(crate) static LOCK: Mutex<()> = Mutex::new(());
}
pub(crate) fn unlink_stale_region(location: &NotifyLocation) {
if let NotifyLocation::Shm { name } = location {
unlink_region(name);
}
}
#[cfg(target_os = "linux")]
fn create_region(_nonce: u64) -> io::Result<(File, NotifyLocation, Option<[u8; NOTIFY_NAME_LEN]>)> {
use std::os::fd::FromRawFd;
let fd = unsafe {
libc::memfd_create(
c"tickertape-notify".as_ptr(),
libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING,
)
};
if fd < 0 {
return Err(last_os_error());
}
let file = unsafe { File::from_raw_fd(fd) };
Ok((
file,
NotifyLocation::Memfd {
pid: std::process::id(),
fd,
},
None,
))
}
#[cfg(target_os = "linux")]
fn seal(file: &File) -> io::Result<()> {
let seals = libc::F_SEAL_SHRINK | libc::F_SEAL_GROW | libc::F_SEAL_SEAL;
if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_ADD_SEALS, seals) } != 0 {
return Err(last_os_error());
}
Ok(())
}
#[cfg(target_os = "linux")]
fn open_region(location: &NotifyLocation) -> io::Result<File> {
let NotifyLocation::Memfd { pid, fd } = location else {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"notify region of another platform",
));
};
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(format!("/proc/{pid}/fd/{fd}"))?;
let seals = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GET_SEALS) };
if seals < 0 || seals & libc::F_SEAL_SHRINK == 0 {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"notify region can shrink",
));
}
Ok(file)
}
#[cfg(target_os = "linux")]
fn unlink_region(_name: &[u8; NOTIFY_NAME_LEN]) {}
#[cfg(target_vendor = "apple")]
fn c_name(name: &[u8; NOTIFY_NAME_LEN]) -> io::Result<std::ffi::CString> {
std::ffi::CString::new(
name.iter()
.copied()
.take_while(|&b| b != 0)
.collect::<Vec<u8>>(),
)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad notify region name"))
}
#[cfg(target_vendor = "apple")]
fn create_region(nonce: u64) -> io::Result<(File, NotifyLocation, Option<[u8; NOTIFY_NAME_LEN]>)> {
use std::os::fd::FromRawFd;
let mut name = [0u8; NOTIFY_NAME_LEN];
name.copy_from_slice(format!("/tickertape.{nonce:016x}").as_bytes());
let c = c_name(&name)?;
let fd = unsafe {
libc::shm_open(
c.as_ptr(),
libc::O_RDWR | libc::O_CREAT | libc::O_EXCL,
0o600 as libc::c_uint,
)
};
if fd < 0 {
return Err(last_os_error());
}
let file = unsafe { File::from_raw_fd(fd) };
if let Err(e) = set_cloexec(&file) {
unlink_region(&name);
return Err(e);
}
Ok((file, NotifyLocation::Shm { name }, Some(name)))
}
#[cfg(target_vendor = "apple")]
fn open_region(location: &NotifyLocation) -> io::Result<File> {
use std::os::fd::FromRawFd;
let NotifyLocation::Shm { name } = location else {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"notify region of another platform",
));
};
if !name.starts_with(b"/tickertape.") {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"bad notify region name",
));
}
let c = c_name(name)?;
let fd = unsafe { libc::shm_open(c.as_ptr(), libc::O_RDWR, 0 as libc::c_uint) };
if fd < 0 {
return Err(last_os_error());
}
let file = unsafe { File::from_raw_fd(fd) };
set_cloexec(&file)?;
Ok(file)
}
#[cfg(target_vendor = "apple")]
fn set_cloexec(file: &File) -> io::Result<()> {
if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) } != 0 {
return Err(last_os_error());
}
Ok(())
}
#[cfg(target_vendor = "apple")]
fn unlink_region(name: &[u8; NOTIFY_NAME_LEN]) {
if !name.starts_with(b"/tickertape.") {
return;
}
if let Ok(c) = c_name(name) {
unsafe { libc::shm_unlink(c.as_ptr()) };
}
}
#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
fn create_region(_nonce: u64) -> io::Result<(File, NotifyLocation, Option<[u8; NOTIFY_NAME_LEN]>)> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"no notify region on this platform",
))
}
#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
fn open_region(_location: &NotifyLocation) -> io::Result<File> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"no notify region on this platform",
))
}
#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
fn unlink_region(_name: &[u8; NOTIFY_NAME_LEN]) {}
#[cfg(target_os = "linux")]
fn wait_on(word: &AtomicU32, expected: u32, timeout: Duration) -> WaitOutcome {
let ts = libc::timespec {
tv_sec: libc::time_t::try_from(timeout.as_secs()).unwrap_or(libc::time_t::MAX),
tv_nsec: timeout.subsec_nanos() as libc::c_long,
};
let rc = unsafe {
libc::syscall(
libc::SYS_futex,
word.as_ptr(),
libc::FUTEX_WAIT,
expected,
&ts as *const libc::timespec,
std::ptr::null::<u32>(),
0u32,
)
};
if rc == 0 {
return WaitOutcome::Returned;
}
match io::Error::last_os_error().raw_os_error() {
Some(libc::EAGAIN | libc::EINTR | libc::ETIMEDOUT) => WaitOutcome::Returned,
_ => WaitOutcome::Unsupported,
}
}
#[cfg(target_os = "linux")]
fn wake_all(word: &AtomicU32) {
unsafe {
libc::syscall(
libc::SYS_futex,
word.as_ptr(),
libc::FUTEX_WAKE,
i32::MAX,
std::ptr::null::<libc::timespec>(),
std::ptr::null::<u32>(),
0u32,
);
}
}
#[cfg(target_vendor = "apple")]
mod os_sync {
use std::sync::OnceLock;
pub(super) type WaitFn =
unsafe extern "C" fn(*mut libc::c_void, u64, libc::size_t, u32, u32, u64) -> libc::c_int;
pub(super) type WakeFn =
unsafe extern "C" fn(*mut libc::c_void, libc::size_t, u32) -> libc::c_int;
pub(super) const SHARED: u32 = 0x1;
pub(super) const CLOCK_MACH_ABSOLUTE_TIME: u32 = 32;
pub(super) fn functions() -> Option<(WaitFn, WakeFn)> {
static FUNCTIONS: OnceLock<Option<(WaitFn, WakeFn)>> = OnceLock::new();
*FUNCTIONS.get_or_init(|| {
let wait = unsafe {
libc::dlsym(
libc::RTLD_DEFAULT,
c"os_sync_wait_on_address_with_timeout".as_ptr(),
)
};
let wake =
unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"os_sync_wake_by_address_all".as_ptr()) };
if wait.is_null() || wake.is_null() {
return None;
}
Some(unsafe {
(
std::mem::transmute::<*mut libc::c_void, WaitFn>(wait),
std::mem::transmute::<*mut libc::c_void, WakeFn>(wake),
)
})
})
}
}
#[cfg(target_vendor = "apple")]
fn wait_on(word: &AtomicU32, expected: u32, timeout: Duration) -> WaitOutcome {
let Some((wait, _)) = os_sync::functions() else {
return WaitOutcome::Unsupported;
};
let ns = u64::try_from(timeout.as_nanos()).unwrap_or(u64::MAX).max(1);
let rc = unsafe {
wait(
word.as_ptr().cast(),
u64::from(expected),
4,
os_sync::SHARED,
os_sync::CLOCK_MACH_ABSOLUTE_TIME,
ns,
)
};
if rc >= 0 {
return WaitOutcome::Returned;
}
match io::Error::last_os_error().raw_os_error() {
Some(libc::ETIMEDOUT | libc::EINTR) => WaitOutcome::Returned,
_ => WaitOutcome::Unsupported,
}
}
#[cfg(target_vendor = "apple")]
fn wake_all(word: &AtomicU32) {
if let Some((_, wake)) = os_sync::functions() {
unsafe {
wake(word.as_ptr().cast(), 4, os_sync::SHARED);
}
}
}
#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
fn wait_on(_word: &AtomicU32, _expected: u32, _timeout: Duration) -> WaitOutcome {
WaitOutcome::Unsupported
}
#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
fn wake_all(_word: &AtomicU32) {}
pub(crate) fn try_lock_exclusive(file: &File) -> io::Result<bool> {
let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
if rc == 0 {
return Ok(true);
}
let err = last_os_error();
if err.raw_os_error() == Some(libc::EWOULDBLOCK) {
Ok(false)
} else {
Err(err)
}
}
pub(crate) fn unlock(file: &File) -> io::Result<()> {
let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_UN) };
if rc == 0 {
Ok(())
} else {
Err(last_os_error())
}
}
#[cfg(test)]
pub(crate) mod forked {
use std::fs::File;
use std::io::{self, Write};
use std::os::unix::io::{FromRawFd, RawFd};
use std::sync::Mutex;
use std::time::{Duration, Instant};
pub(crate) static LOCK: Mutex<()> = Mutex::new(());
pub(crate) const PANICKED: i32 = 101;
pub(crate) const WAIT_FAILED: i32 = 102;
const TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Debug)]
pub(crate) struct Child {
pid: libc::pid_t,
release: Option<File>,
}
pub(crate) fn fork(in_child: impl FnOnce()) -> io::Result<Child> {
let mut fds = [0 as libc::c_int; 2];
if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
return Err(super::last_os_error());
}
let [read_fd, write_fd] = fds;
for fd in fds {
unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) };
}
let pid = unsafe { libc::fork() };
if pid < 0 {
let err = super::last_os_error();
unsafe {
libc::close(read_fd);
libc::close(write_fd);
}
return Err(err);
}
if pid == 0 {
let mut status = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(in_child))
{
Ok(()) => 0,
Err(_) => PANICKED,
};
let mut byte = 0_u8;
unsafe {
libc::close(write_fd);
while libc::read(read_fd, (&raw mut byte).cast(), 1) < 0 {
if io::Error::last_os_error().raw_os_error() != Some(libc::EINTR) {
if status == 0 {
status = WAIT_FAILED;
}
break;
}
}
}
exit(status);
}
unsafe { libc::close(read_fd) };
Ok(Child {
pid,
release: Some(unsafe { File::from_raw_fd(write_fd) }),
})
}
pub(crate) fn exit(status: i32) -> ! {
unsafe { libc::_exit(status) }
}
pub(crate) fn interrupt_on(signal: libc::c_int) {
extern "C" fn ignore(_: libc::c_int) {}
unsafe {
let mut action: libc::sigaction = std::mem::zeroed();
action.sa_sigaction = ignore as extern "C" fn(libc::c_int) as libc::sighandler_t;
libc::sigaction(signal, &action, std::ptr::null_mut());
}
}
pub(crate) fn is_open(fd: RawFd) -> bool {
unsafe { libc::fcntl(fd, libc::F_GETFD) != -1 }
}
enum ReapError {
TimedOut,
Wait(io::Error),
}
impl Child {
pub(crate) fn wait(self) -> Option<i32> {
self.wait_within(TIMEOUT)
}
pub(crate) fn wait_within(mut self, timeout: Duration) -> Option<i32> {
let pid = self.pid;
match self.reap(timeout) {
Ok(status) => status,
Err(e) => panic!("{}", e.message(pid, timeout)),
}
}
pub(crate) fn signal(&self, signal: libc::c_int) {
unsafe { libc::kill(self.pid, signal) };
}
fn reap(&mut self, timeout: Duration) -> Result<Option<i32>, ReapError> {
let Some(mut release) = self.release.take() else {
return Ok(None);
};
let _ = release.write_all(&[1]);
drop(release);
let deadline = Instant::now() + timeout;
let mut status = 0;
loop {
let rc = unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) };
if rc == self.pid {
break;
}
if rc < 0 {
let err = io::Error::last_os_error();
if err.kind() != io::ErrorKind::Interrupted {
return Err(ReapError::Wait(err));
}
} else if Instant::now() >= deadline {
unsafe {
libc::kill(self.pid, libc::SIGKILL);
while libc::waitpid(self.pid, &mut status, 0) < 0
&& io::Error::last_os_error().kind() == io::ErrorKind::Interrupted
{
}
}
return Err(ReapError::TimedOut);
} else {
std::thread::sleep(Duration::from_millis(1));
}
}
Ok(libc::WIFEXITED(status).then(|| libc::WEXITSTATUS(status)))
}
}
impl ReapError {
fn message(&self, pid: libc::pid_t, timeout: Duration) -> String {
match self {
ReapError::TimedOut => format!(
"forked child {pid} did not exit within {timeout:?} of its release (deadlocked?); killed it"
),
ReapError::Wait(e) => format!("waiting for forked child {pid} failed: {e}"),
}
}
}
impl Drop for Child {
fn drop(&mut self) {
if let Err(e) = self.reap(TIMEOUT) {
if !std::thread::panicking() {
panic!("{}", e.message(self.pid, TIMEOUT));
}
}
}
}
}
pub(crate) fn preallocate(file: &File, len: u64) -> io::Result<()> {
let len_off = libc::off_t::try_from(len)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "segment too large"))?;
#[cfg(any(target_os = "linux", target_os = "android"))]
{
let rc = unsafe { libc::fallocate(file.as_raw_fd(), 0, 0, len_off) };
if rc != 0 {
return Err(last_os_error());
}
Ok(())
}
#[cfg(target_vendor = "apple")]
{
let mut store = libc::fstore_t {
fst_flags: libc::F_ALLOCATECONTIG,
fst_posmode: libc::F_PEOFPOSMODE,
fst_offset: 0,
fst_length: len_off,
fst_bytesalloc: 0,
};
let mut rc = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_PREALLOCATE, &mut store) };
if rc == -1 {
store.fst_flags = libc::F_ALLOCATEALL;
rc = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_PREALLOCATE, &mut store) };
}
if rc == -1 {
return Err(last_os_error());
}
file.set_len(len)
}
#[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
{
let _ = len_off;
file.set_len(len)
}
}
pub(crate) fn msync_file(file: &File, offset: u64, len: u64) -> io::Result<()> {
let size = usize::try_from(file.metadata()?.len())
.map_err(|_| io::Error::other("file too large to map"))?;
MapRw::new(file, size)?.sync_range(offset, len)
}
pub(crate) fn sync_data(file: &File) -> io::Result<()> {
#[cfg(any(target_os = "linux", target_os = "android"))]
let rc = unsafe { libc::fdatasync(file.as_raw_fd()) };
#[cfg(not(any(target_os = "linux", target_os = "android")))]
let rc = unsafe { libc::fsync(file.as_raw_fd()) };
if rc != 0 {
Err(last_os_error())
} else {
Ok(())
}
}
pub(crate) fn sync_all(file: &File) -> io::Result<()> {
let rc = unsafe { libc::fsync(file.as_raw_fd()) };
if rc != 0 {
Err(last_os_error())
} else {
Ok(())
}
}
pub(crate) fn full_barrier(file: &File) -> io::Result<()> {
#[cfg(target_vendor = "apple")]
{
let rc = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_FULLFSYNC) };
if rc == -1 {
Err(last_os_error())
} else {
Ok(())
}
}
#[cfg(not(target_vendor = "apple"))]
{
sync_data(file)
}
}
#[cfg(target_os = "linux")]
pub(crate) fn start_writeback(file: &File, offset: u64, len: u64) -> io::Result<()> {
let (Ok(offset), Ok(len)) = (
libc::off64_t::try_from(offset),
libc::off64_t::try_from(len),
) else {
return Err(io::Error::from(io::ErrorKind::InvalidInput));
};
let rc = unsafe {
libc::sync_file_range(file.as_raw_fd(), offset, len, libc::SYNC_FILE_RANGE_WRITE)
};
if rc != 0 {
Err(last_os_error())
} else {
Ok(())
}
}
#[cfg(target_os = "linux")]
pub(crate) const AFFINITY_CPUS: usize = 8192;
#[cfg(target_os = "linux")]
pub(crate) fn set_thread_affinity(cpus: impl IntoIterator<Item = usize>) -> io::Result<()> {
let mut mask = vec![0u64; AFFINITY_CPUS / 64];
for cpu in cpus {
let word = mask
.get_mut(cpu / 64)
.ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?;
*word |= 1 << (cpu % 64);
}
let rc = unsafe {
libc::syscall(
libc::SYS_sched_setaffinity,
0 as libc::pid_t,
std::mem::size_of_val(mask.as_slice()),
mask.as_ptr(),
)
};
if rc != 0 {
Err(last_os_error())
} else {
Ok(())
}
}
#[cfg(all(target_os = "linux", test))]
pub(crate) fn thread_affinity() -> io::Result<Vec<usize>> {
let mut mask = vec![0u64; AFFINITY_CPUS / 64];
let rc = unsafe {
libc::syscall(
libc::SYS_sched_getaffinity,
0 as libc::pid_t,
std::mem::size_of_val(mask.as_slice()),
mask.as_mut_ptr(),
)
};
if rc < 0 {
return Err(last_os_error());
}
Ok((0..AFFINITY_CPUS)
.filter(|cpu| mask[cpu / 64] & (1 << (cpu % 64)) != 0)
.collect())
}
pub(crate) fn is_storage_full(err: &io::Error) -> bool {
matches!(err.raw_os_error(), Some(code) if code == libc::ENOSPC || code == libc::EDQUOT)
}
#[cfg(test)]
impl MapRo {
fn anonymous(bytes: &[u8]) -> MapRo {
let page = page_size();
let len = bytes.len().max(1).div_ceil(page) * page;
let ptr = unsafe {
libc::mmap(
std::ptr::null_mut(),
len,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_PRIVATE | libc::MAP_ANON,
-1,
0,
)
};
assert_ne!(ptr, libc::MAP_FAILED, "{}", last_os_error());
let ptr = NonNull::new(ptr.cast::<u8>()).expect("mmap returned null");
unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr.as_ptr(), bytes.len()) };
if MAPPED_READS && !cfg!(miri) {
let rc = unsafe { libc::mprotect(ptr.as_ptr().cast(), len, libc::PROT_READ) };
assert_eq!(rc, 0, "{}", last_os_error());
}
MapRo { ptr, len }
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
#[test]
fn map_ro_loads_validate_a_record_on_anonymous_memory() {
use crate::format::{self, RecordHeader};
let payload: Vec<u8> = (0..203_u32).map(|i| (i * 13 + 5) as u8).collect();
let header = RecordHeader {
seq: 9,
schema_id: 3,
venue_ts_ns: 11,
local_ts_ns: 12,
};
let len = format::frame_len(payload.len()).unwrap();
let mut image = vec![0u8; 64 + format::align8(u64::from(len)) as usize + 16];
let body = &mut image[68..64 + len as usize];
format::write_record_fields(&header, body);
body[36..].copy_from_slice(&payload);
format::finish_record_body(len, body);
image[64..68].copy_from_slice(&len.to_le_bytes());
let end = image.len();
image[end - 8..].copy_from_slice(&[0xa5; 8]);
let map = MapRo::anonymous(&image);
let size = map.len;
assert_eq!(map.commit_word(64), Some(len));
let crc = map.load_u32(68).unwrap();
assert_eq!(crc.to_le_bytes(), image[68..72]);
let words = map
.words(72, (format::align8(u64::from(len)) - 8) / 8)
.unwrap();
assert_eq!(format::decode_record_words(len, crc, words, 9), Ok(header));
let bytes = unsafe { map.committed_bytes(104, payload.len() as u64) }.unwrap();
assert_eq!(bytes, &payload[..]);
let next = 64 + format::align8(u64::from(len));
assert_eq!(map.commit_word(next), Some(0));
assert_eq!(
map.words(next + 8, 1).unwrap().get(0),
Some(0xa5a5_a5a5_a5a5_a5a5)
);
let last = size as u64;
assert!(map.load_u32(last - 4).is_some());
assert!(map.load_u32(last).is_none());
assert!(map.load_u32(last - 2).is_none(), "misaligned");
assert!(map.load_u32(u64::MAX - 3).is_none());
assert_eq!(map.words(last - 8, 1).map(|w| w.len()), Some(1));
assert!(map.words(last - 8, 2).is_none());
assert!(map.words(last, 0).is_some_and(|w| w.len() == 0));
assert!(map.words(last + 8, 0).is_none());
assert!(map.words(4, 1).is_none(), "misaligned");
assert!(map.words(8, u64::MAX / 4).is_none(), "overflowing length");
assert!(map.words(u64::MAX - 7, 1).is_none(), "overflowing end");
let all = map.words(0, last / 8).unwrap();
assert_eq!(all.len() as u64, last / 8);
assert_eq!(all.get(8), Some(u64::from(len) | u64::from(crc) << 32));
assert_eq!(all.iter().count() as u64, last / 8);
assert!(map.commit_word(last - 4).is_none());
assert!(unsafe { map.committed_bytes(last - 1, 2) }.is_none());
}
fn temp_file(len: u64) -> (tempfile::TempDir, File) {
let dir = tempfile::tempdir().unwrap();
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.open(dir.path().join("f"))
.unwrap();
preallocate(&file, len).unwrap();
(dir, file)
}
#[test]
fn rw_and_ro_mappings_share_bytes() {
let (_dir, file) = temp_file(65536);
let mut rw = MapRw::new(&file, 65536).unwrap();
rw.bytes_mut(68, 4).unwrap().copy_from_slice(b"abcd");
rw.store_commit_word(64, 40).unwrap();
assert_eq!(rw.commit_word(64), Some(40));
rw.sync_range(64, 8).unwrap();
sync_data(&file).unwrap();
let Some(ro) = map_ro_where_supported(&file, 65536) else {
return;
};
assert_eq!(ro.commit_word(64), Some(40));
assert_eq!(ro.load_u32(68), Some(u32::from_le_bytes(*b"abcd")));
assert_eq!(ro.load_u32(66), None, "misaligned");
assert_eq!(ro.load_u32(65532).map(|_| ()), Some(()));
assert_eq!(ro.load_u32(65536), None);
let words = ro.words(64, 2).unwrap();
assert_eq!(words.len(), 2);
assert_eq!(
words.get(0),
Some(40 | u64::from(u32::from_le_bytes(*b"abcd")) << 32)
);
assert_eq!(words.get(1), Some(0));
assert_eq!(words.get(2), None);
assert!(ro.words(68, 1).is_none(), "misaligned");
assert!(ro.words(65528, 1).is_some());
assert!(ro.words(65528, 2).is_none());
assert!(ro.words(8, u64::MAX).is_none(), "overflowing length");
assert_eq!(unsafe { ro.committed_bytes(68, 4) }.unwrap(), b"abcd");
}
#[test]
fn bounds_and_alignment_are_checked() {
let (_dir, file) = temp_file(65536);
let mut rw = MapRw::new(&file, 65536).unwrap();
assert!(
rw.commit_word(65532).is_none(),
"4-aligned but not 8-aligned"
);
assert!(rw.commit_word(65536).is_none());
assert!(rw.commit_word(65528).is_some());
assert!(rw.bytes_mut(65530, 7).is_none());
assert!(rw.bytes(u64::MAX, 2).is_none());
let Some(ro) = map_ro_where_supported(&file, 65536) else {
return;
};
assert!(ro.commit_word(4).is_none());
assert!(unsafe { ro.committed_bytes(65535, 2) }.is_none());
}
#[test]
fn lock_is_exclusive_across_handles() {
let _forked = forked::LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lock");
let a = File::create(&path).unwrap();
let b = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
assert!(try_lock_exclusive(&a).unwrap());
assert!(
!try_lock_exclusive(&b).unwrap(),
"flock locks are per open file description"
);
drop(a);
assert!(try_lock_exclusive(&b).unwrap());
}
#[test]
#[should_panic(expected = "did not exit within 100ms of its release (deadlocked?); killed it")]
fn forked_child_that_never_exits_is_killed() {
let _forked = forked::LOCK.lock().unwrap_or_else(|e| e.into_inner());
let child = forked::fork(|| {
loop {
std::thread::sleep(std::time::Duration::from_secs(1));
}
})
.unwrap();
child.wait_within(std::time::Duration::from_millis(100));
}
#[test]
fn forked_child_keeps_waiting_when_its_wait_is_interrupted() {
let _forked = forked::LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lock");
let locked = File::create(&path).unwrap();
assert!(try_lock_exclusive(&locked).unwrap());
forked::interrupt_on(libc::SIGUSR1);
let child = forked::fork(|| {}).unwrap();
drop(locked);
let other = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
std::thread::sleep(std::time::Duration::from_millis(50));
child.signal(libc::SIGUSR1);
std::thread::sleep(std::time::Duration::from_millis(50));
assert!(
!try_lock_exclusive(&other).unwrap(),
"the interrupted child must still hold its copy of the lock"
);
assert_eq!(child.wait(), Some(0));
assert!(try_lock_exclusive(&other).unwrap());
}
#[test]
fn unlock_releases_a_lock_that_a_copied_descriptor_still_holds() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lock");
let a = File::create(&path).unwrap();
let copy = a.try_clone().unwrap();
let other = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
assert!(try_lock_exclusive(&a).unwrap());
drop(a);
assert!(
!try_lock_exclusive(&other).unwrap(),
"the copy still holds the lock"
);
unlock(©).unwrap();
assert!(try_lock_exclusive(&other).unwrap());
}
#[test]
fn preallocate_sets_size_and_zeroes() {
let (_dir, mut file) = temp_file(131072);
assert_eq!(file.metadata().unwrap().len(), 131072);
file.write_all(b"x").unwrap();
sync_all(&file).unwrap();
full_barrier(&file).unwrap();
if let Some(ro) = map_ro_where_supported(&file, 131072) {
assert_eq!(ro.commit_word(131064), Some(0));
}
}
fn map_ro_where_supported(file: &File, len: usize) -> Option<MapRo> {
let mapped = MapRo::new(file, len);
assert_eq!(
mapped.is_ok(),
MAPPED_READS,
"MapRo::new: {:?}",
mapped.as_ref().err()
);
match mapped {
Ok(ro) => Some(ro),
Err(e) => {
assert_eq!(e.kind(), io::ErrorKind::Unsupported);
None
}
}
}
#[test]
fn mapped_reads_exactly_on_x86_64_and_aarch64() {
assert_eq!(
MAPPED_READS,
cfg!(any(target_arch = "x86_64", target_arch = "aarch64"))
);
let (_dir, file) = temp_file(65536);
let ro = map_ro_where_supported(&file, 65536);
assert_eq!(ro.is_some(), MAPPED_READS);
if !MAPPED_READS {
let err = MapRo::new(&file, 65536).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::Unsupported);
}
}
#[test]
fn notify_region_attach_checks_the_nonce_and_sees_publications() {
let (owner, location) = Notify::create(0x1234_5678_9abc_def0).unwrap();
assert!(Notify::attach(&location, 1).is_err(), "wrong nonce");
let reader = Notify::attach(&location, 0x1234_5678_9abc_def0).unwrap();
assert!(reader.writer_notifies());
let seen = reader.begin_wait();
owner.publish();
let started = std::time::Instant::now();
assert_eq!(
reader.wait(seen, Duration::from_secs(10)),
WaitOutcome::Returned
);
assert!(started.elapsed() < Duration::from_secs(5));
reader.end_wait();
reader.end_wait(); drop(owner);
assert!(
!reader.writer_notifies(),
"a dropped writer clears its flag"
);
}
#[cfg(target_os = "linux")]
#[test]
fn notify_attach_rejects_an_unsealed_region() {
use std::os::fd::FromRawFd;
let fd = unsafe { libc::memfd_create(c"unsealed".as_ptr(), libc::MFD_CLOEXEC) };
assert!(fd >= 0);
let file = unsafe { File::from_raw_fd(fd) };
file.set_len(NOTIFY_REGION_LEN as u64).unwrap();
let location = NotifyLocation::Memfd {
pid: std::process::id(),
fd,
};
let err = Notify::attach(&location, 0).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{err}");
}
#[test]
fn notify_region_cannot_shrink() {
let (owner, location) = Notify::create(7).unwrap();
let file = &owner.owner.as_ref().unwrap().file;
assert!(file.set_len(0).is_err(), "owner's descriptor");
assert!(file.set_len(1).is_err());
let other = open_region(&location).unwrap();
assert!(
other.set_len(0).is_err(),
"another descriptor for the same region"
);
assert!(other.metadata().unwrap().len() >= NOTIFY_REGION_LEN as u64);
}
#[test]
fn storage_full_detection() {
assert!(is_storage_full(&io::Error::from_raw_os_error(libc::ENOSPC)));
assert!(!is_storage_full(&io::Error::from_raw_os_error(libc::EIO)));
}
}