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)
}
}
#[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(())
}
}
}
}
#[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> {
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)
}
#[cfg(test)]
pub(crate) fn copy_atomic(&self, offset: u64, len: u64) -> Option<Vec<u8>> {
let mut out = Vec::new();
let range = self.copy_atomic_into(offset, len, &mut out)?;
out.truncate(range.end);
out.drain(..range.start);
Some(out)
}
pub(crate) fn copy_atomic_into(
&self,
offset: u64,
len: u64,
out: &mut Vec<u8>,
) -> Option<std::ops::Range<usize>> {
let start = offset & !7;
let end = offset.checked_add(len)?;
let word_end = end.checked_add(7)? & !7;
checked_range(self.len, start, word_end - start)?;
out.clear();
out.resize((word_end - start) as usize, 0);
let base = self.ptr.as_ptr();
for (chunk, at) in out.chunks_exact_mut(8).zip((start..word_end).step_by(8)) {
let word = unsafe { &*base.add(at as usize).cast::<AtomicU64>() };
chunk.copy_from_slice(&word.load(Ordering::Relaxed).to_le_bytes());
}
let skip = (offset - start) as usize;
Some(skip..skip + len as usize)
}
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) }
}
}
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 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,
}
}
}
}
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 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 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)
}
}
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)]
mod tests {
use super::*;
use std::io::Write;
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();
let ro = MapRo::new(&file, 65536).unwrap();
assert_eq!(ro.commit_word(64), Some(40));
assert_eq!(ro.copy_atomic(68, 4).unwrap(), b"abcd");
assert_eq!(ro.copy_atomic(65, 7).unwrap()[3..], *b"abcd");
assert!(ro.copy_atomic(65530, 8).is_none());
assert_eq!(unsafe { ro.committed_bytes(68, 4) }.unwrap(), b"abcd");
assert_eq!(rw.commit_word(64), Some(40));
rw.sync_range(64, 8).unwrap();
sync_data(&file).unwrap();
}
#[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 ro = MapRo::new(&file, 65536).unwrap();
assert!(ro.commit_word(4).is_none());
assert!(unsafe { ro.committed_bytes(65535, 2) }.is_none());
}
#[test]
fn lock_is_exclusive_across_handles() {
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]
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();
let ro = MapRo::new(&file, 131072).unwrap();
assert_eq!(ro.commit_word(131064), Some(0));
sync_all(&file).unwrap();
full_barrier(&file).unwrap();
}
#[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)));
}
}