#![cfg(target_os = "macos")]
mod common;
macro_rules! note {
($($arg:tt)*) => {
crate::common::note(&format!($($arg)*))
};
}
use std::sync::{Mutex, MutexGuard};
use oscall::io::macos;
static SERIAL: Mutex<()> = Mutex::new(());
fn serial() -> MutexGuard<'static, ()> {
SERIAL
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
#[test]
fn limits() {
let _serial = serial();
let limits = macos::limits().unwrap();
note!("io::macos: {limits:?}");
assert!(limits.process >= 1, "{limits:?}");
assert!(limits.system >= limits.process, "{limits:?}");
assert!(limits.threads >= 1, "{limits:?}");
assert_eq!(limits, macos::limits().unwrap());
let said = std::process::Command::new("sysctl")
.args(["-n", "kern.aiomax", "kern.aioprocmax", "kern.aiothreads"])
.output()
.unwrap();
let said: Vec<u32> = String::from_utf8(said.stdout)
.unwrap()
.lines()
.map(|line| line.trim().parse().unwrap())
.collect();
assert_eq!(said, [limits.system, limits.process, limits.threads]);
}
#[cfg(feature = "alloc")]
mod operation {
use std::time::{Duration, Instant};
use oscall::event::{Event, Poller};
use oscall::io::macos::{self, Batch, Operation};
use oscall::process::unix::SignalExt;
use oscall::process::{Signal, Signals};
use oscall::{ErrorKind, fs, io};
use super::{common, serial};
const LONG: Duration = Duration::from_secs(60);
fn finish(operation: &Operation) -> oscall::Result<usize> {
assert_eq!(macos::wait(&[operation], Some(LONG)).unwrap(), Some(0));
assert!(!operation.is_pending());
operation.result().expect("the operation is over")
}
fn open(path: &std::path::Path, options: &fs::OpenOptions) -> oscall::OwnedHandle {
fs::open(path, options).unwrap()
}
struct Fifo(oscall::OwnedHandle);
impl Fifo {
fn new(name: &str) -> Self {
let path = common::tmp_dir(name).join("fifo");
fs::unix::mkfifo(&path, 0o600).unwrap();
Self::open(&path)
}
fn open(path: &std::path::Path) -> Self {
Self(open(path, &fs::OpenOptions::new().read(true).write(true)))
}
}
impl Drop for Fifo {
fn drop(&mut self) {
let _ = io::set_nonblocking(&self.0, true);
let _ = io::write(&self.0, &[b'!'; 256]);
}
}
#[track_caller]
fn assert_refused(error: oscall::Error, kind: ErrorKind) {
if error.kind() != ErrorKind::WouldBlock {
assert_eq!(error.kind(), kind, "{error:?}");
}
}
fn read_write() -> fs::OpenOptions {
fs::OpenOptions::new().read(true).write(true).create(true)
}
#[test]
fn nothing_started() {
let _serial = serial();
let mut operation = Operation::new();
assert!(format!("{operation:?}").starts_with("Operation"));
assert!(!operation.is_pending());
assert_eq!(operation.result(), None);
assert_eq!(operation.cancel(), Ok(false));
assert_eq!(operation.take_buffer(), None);
let err = macos::wait(&[&operation], Some(Duration::ZERO)).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidInput);
let err = macos::wait(&[], Some(Duration::ZERO)).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidInput);
drop(Operation::default());
}
#[test]
fn file_read_and_write() {
let _serial = serial();
let dir = common::tmp_dir("io_macos_file");
let path = dir.join("data");
let file = open(&path, &read_write());
let mut operation = Operation::new();
operation.write(&file, b"0123456789".to_vec(), 0).unwrap();
assert_eq!(finish(&operation), Ok(10));
assert_eq!(operation.result(), Some(Ok(10)));
assert_eq!(operation.cancel(), Ok(false));
assert_eq!(operation.take_buffer().as_deref(), Some(&b"0123456789"[..]));
assert_eq!(operation.take_buffer(), None);
assert_eq!(operation.result(), Some(Ok(10)));
assert_eq!(std::fs::read(&path).unwrap(), b"0123456789");
operation.write(&file, b"abc".to_vec(), 4).unwrap();
assert_eq!(finish(&operation), Ok(3));
operation.write(&file, b"xy".to_vec(), 12).unwrap();
assert_eq!(finish(&operation), Ok(2));
assert_eq!(std::fs::read(&path).unwrap(), b"0123abc789\0\0xy");
assert_eq!(io::seek(&file, io::SeekFrom::Current(0)), Ok(0));
let mut buf = Vec::with_capacity(5);
buf.extend_from_slice(b"??");
let capacity = buf.capacity();
operation.read(&file, buf, 2).unwrap();
assert_eq!(finish(&operation), Ok(capacity.min(12)));
let buf = operation.take_buffer().unwrap();
assert_eq!(buf, &b"23abc789\0\0xy"[..capacity.min(12)]);
assert_eq!(buf.capacity(), capacity);
operation.read(&file, Vec::with_capacity(64), 10).unwrap();
assert_eq!(finish(&operation), Ok(4));
assert_eq!(operation.take_buffer().unwrap(), b"\0\0xy");
for offset in [14, 15, 1 << 40] {
operation
.read(&file, Vec::with_capacity(64), offset)
.unwrap();
assert_eq!(finish(&operation), Ok(0), "at {offset}");
assert_eq!(operation.take_buffer().unwrap(), b"");
}
operation.read(&file, Vec::new(), 0).unwrap();
assert_eq!(finish(&operation), Ok(0));
assert_eq!(operation.take_buffer().unwrap(), b"");
operation.write(&file, Vec::new(), 0).unwrap();
assert_eq!(finish(&operation), Ok(0));
let mut expected = [0u8; 14];
assert_eq!(io::read_at(&file, &mut expected, 0), Ok(14));
operation.read(&file, Vec::with_capacity(14), 0).unwrap();
assert_eq!(finish(&operation), Ok(14));
assert_eq!(operation.take_buffer().unwrap(), expected);
}
#[test]
fn large_transfers() {
let _serial = serial();
let dir = common::tmp_dir("io_macos_large");
let path = dir.join("data");
let file = open(&path, &read_write());
let data: Vec<u8> = (0..(8usize << 20)).map(|i| ((i * 31) >> 3) as u8).collect();
let part = data.len() / 4;
let mut writes: Vec<Operation> = (0..4).map(|_| Operation::new()).collect();
for (i, write) in writes.iter_mut().enumerate() {
let chunk = data[i * part..(i + 1) * part].to_vec();
write.write(&file, chunk, (i * part) as u64).unwrap();
}
let mut left: Vec<&Operation> = writes.iter().collect();
while !left.is_empty() {
let index = macos::wait(&left, Some(LONG)).unwrap().expect("a write");
assert_eq!(left[index].result(), Some(Ok(part)));
left.remove(index);
}
let mut sync = Operation::new();
sync.sync(&file, false).unwrap();
assert_eq!(finish(&sync), Ok(0));
assert_eq!(sync.take_buffer(), None);
sync.sync(&file, true).unwrap();
assert_eq!(finish(&sync), Ok(0));
assert!(std::fs::read(&path).unwrap() == data);
let mut reads: Vec<Operation> = (0..4).map(|_| Operation::new()).collect();
for (i, read) in reads.iter_mut().enumerate() {
read.read(&file, Vec::with_capacity(part), (i * part) as u64)
.unwrap();
}
for (i, read) in reads.iter_mut().enumerate() {
assert_eq!(finish(read), Ok(part));
assert!(read.take_buffer().unwrap() == data[i * part..(i + 1) * part]);
}
}
#[test]
fn what_fails() {
let _serial = serial();
let dir = common::tmp_dir("io_macos_fails");
let path = dir.join("data");
std::fs::write(&path, b"0123456789").unwrap();
let mut operation = Operation::new();
let file = open(&path, &read_write());
let err = operation
.read(&file, Vec::with_capacity(4), u64::MAX)
.unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidInput);
assert!(!operation.is_pending());
assert_eq!(operation.result(), None);
let read_only = open(&path, &fs::OpenOptions::new().read(true));
let err = operation
.write(&read_only, b"nothing".to_vec(), 0)
.unwrap_err();
assert_refused(err, ErrorKind::BadHandle);
assert_eq!(operation.result(), None);
assert_eq!(operation.take_buffer().as_deref(), Some(&b"nothing"[..]));
let write_only = open(&path, &fs::OpenOptions::new().write(true));
let err = operation
.read(&write_only, Vec::with_capacity(4), 0)
.unwrap_err();
assert_refused(err, ErrorKind::BadHandle);
assert_eq!(std::fs::read(&path).unwrap(), b"0123456789");
let (reader, writer) = io::pipe().unwrap();
let err = operation
.read(&reader, Vec::with_capacity(4), 0)
.unwrap_err();
assert_refused(err, ErrorKind::NotSeekable);
let err = operation.write(&writer, b"x".to_vec(), 0).unwrap_err();
assert_refused(err, ErrorKind::NotSeekable);
note!("io::macos: a pipe is refused with {err:?}");
let directory = open(&dir, &fs::OpenOptions::new().read(true));
operation
.read(&directory, Vec::with_capacity(4), 0)
.unwrap();
let err = finish(&operation).unwrap_err();
assert_eq!(err.kind(), ErrorKind::IsADirectory);
assert_eq!(operation.take_buffer().unwrap(), b"");
}
#[test]
fn in_flight() {
let _serial = serial();
let fifo = Fifo::new("io_macos_in_flight");
let fifo = &fifo.0;
let mut read = Operation::new();
read.read(fifo, Vec::with_capacity(16), 0).unwrap();
assert!(read.is_pending());
assert_eq!(read.result(), None);
assert_eq!(read.take_buffer(), None);
let err = read.read(fifo, Vec::new(), 0).unwrap_err();
assert_eq!(err.kind(), ErrorKind::ResourceBusy);
let err = read.sync(fifo, false).unwrap_err();
assert_eq!(err.kind(), ErrorKind::ResourceBusy);
assert_eq!(macos::wait(&[&read], Some(Duration::ZERO)), Ok(None));
let start = Instant::now();
assert_eq!(
macos::wait(&[&read], Some(Duration::from_millis(60))),
Ok(None)
);
assert!(start.elapsed() >= Duration::from_millis(60));
assert!(read.is_pending());
let start = Instant::now();
std::thread::scope(|scope| {
scope.spawn(|| {
std::thread::sleep(Duration::from_millis(100));
io::write(fifo, b"hello").unwrap();
});
assert_eq!(macos::wait(&[&read], Some(LONG)), Ok(Some(0)));
assert!(start.elapsed() >= Duration::from_millis(100));
assert!(start.elapsed() < LONG);
});
assert_eq!(read.result(), Some(Ok(5)));
assert_eq!(macos::wait(&[&read], None), Ok(Some(0)));
assert_eq!(read.take_buffer().unwrap(), b"hello");
}
#[test]
fn wait_for_one_of_several() {
let _serial = serial();
let fifos: Vec<_> = (0..3)
.map(|i| Fifo::new(&format!("io_macos_several_{i}")))
.collect();
let fifos: Vec<_> = fifos.iter().map(|fifo| &fifo.0).collect();
let mut reads: Vec<Operation> = (0..3).map(|_| Operation::new()).collect();
for (read, fifo) in reads.iter_mut().zip(&fifos) {
read.read(*fifo, Vec::with_capacity(8), 0).unwrap();
}
let idle = Operation::new();
let list = [&idle, &reads[0], &reads[1], &reads[2]];
assert_eq!(
macos::wait(&list, Some(Duration::from_millis(20))),
Ok(None)
);
io::write(fifos[1], b"one").unwrap();
assert_eq!(macos::wait(&list, Some(LONG)), Ok(Some(2)));
assert_eq!(reads[1].result(), Some(Ok(3)));
let list = [&reads[0], &idle, &reads[2]];
assert_eq!(
macos::wait(&list, Some(Duration::from_millis(20))),
Ok(None)
);
io::write(fifos[2], b"two!").unwrap();
assert_eq!(macos::wait(&list, Some(LONG)), Ok(Some(2)));
assert_eq!(reads[2].result(), Some(Ok(4)));
io::write(fifos[0], b"three").unwrap();
assert_eq!(macos::wait(&[&reads[0]], None), Ok(Some(0)));
assert_eq!(reads[0].take_buffer().unwrap(), b"three");
assert_eq!(reads[1].take_buffer().unwrap(), b"one");
assert_eq!(reads[2].take_buffer().unwrap(), b"two!");
}
#[test]
fn moved_to_another_thread() {
let _serial = serial();
let fifo = Fifo::new("io_macos_moved");
let fifo = &fifo.0;
let mut read = std::thread::scope(|scope| {
scope
.spawn(|| {
let mut read = Operation::new();
read.read(fifo, Vec::with_capacity(8), 0).unwrap();
read
})
.join()
.unwrap()
});
assert!(read.is_pending());
io::write(fifo, b"late").unwrap();
assert_eq!(finish(&read), Ok(4));
assert_eq!(read.take_buffer().unwrap(), b"late");
}
fn running_read(fifo: &oscall::OwnedHandle) -> Operation {
for _ in 0..200 {
let mut read = Operation::new();
read.read(fifo, Vec::with_capacity(1), 0).unwrap();
std::thread::sleep(Duration::from_millis(20));
if !read.cancel().unwrap() {
assert!(read.is_pending());
return read;
}
}
panic!("the kernel started on none of 200 reads in 20 ms each");
}
fn fill(fifo: &oscall::OwnedHandle, limit: usize) -> (Vec<Operation>, oscall::Error) {
let mut reads = Vec::new();
loop {
let mut read = Operation::new();
match read.read(fifo, Vec::with_capacity(1), 0) {
Ok(()) => reads.push(read),
Err(error) => return (reads, error),
}
assert!(reads.len() <= limit, "more operations than the limit");
}
}
fn release(fifo: &oscall::OwnedHandle, reads: &[Operation]) {
let mut running = 0;
for read in reads {
if read.is_pending() && !read.cancel().unwrap() {
running += 1;
}
}
assert_eq!(io::write(fifo, &vec![b'r'; running]), Ok(running));
for read in reads {
if read.result().is_none() {
finish(read).unwrap();
}
}
}
#[test]
fn limit_of_the_process() {
let _serial = serial();
let limit = macos::limits().unwrap().process as usize;
let fifo = Fifo::new("io_macos_limit");
let fifo = &fifo.0;
let dir = common::tmp_dir("io_macos_limit_file");
let file = open(&dir.join("data"), &read_write());
let (mut reads, refused) = fill(fifo, limit);
assert_eq!(refused.kind(), ErrorKind::WouldBlock, "{refused:?}");
assert_eq!(reads.len(), limit);
let mut other = Operation::new();
let err = other.write(&file, b"refused".to_vec(), 0).unwrap_err();
assert_eq!(err.kind(), ErrorKind::WouldBlock);
assert_eq!(other.result(), None);
assert_eq!(other.take_buffer().as_deref(), Some(&b"refused"[..]));
let err = other.sync(&file, false).unwrap_err();
assert_eq!(err.kind(), ErrorKind::WouldBlock);
io::write(fifo, b"1").unwrap();
std::thread::sleep(Duration::from_millis(200));
let mut another = Operation::new();
let err = another.read(fifo, Vec::with_capacity(1), 0).unwrap_err();
assert_eq!(err.kind(), ErrorKind::WouldBlock);
let list: Vec<&Operation> = reads.iter().collect();
let over = macos::wait(&list, Some(LONG)).unwrap().expect("a read");
assert_eq!(reads[over].result(), Some(Ok(1)));
assert_eq!(reads[over].take_buffer().unwrap(), b"1");
another.read(fifo, Vec::with_capacity(1), 0).unwrap();
let err = other.sync(&file, true).unwrap_err();
assert_eq!(err.kind(), ErrorKind::WouldBlock);
reads[over] = another;
release(fifo, &reads);
drop(reads);
let (reads, refused) = fill(fifo, limit);
assert_eq!(refused.kind(), ErrorKind::WouldBlock);
assert_eq!(reads.len(), limit);
release(fifo, &reads);
}
#[test]
fn cancel() {
let _serial = serial();
let limit = macos::limits().unwrap().process as usize;
let fifo = Fifo::new("io_macos_cancel");
let fifo = &fifo.0;
let mut reads = vec![running_read(fifo)];
reads.extend(fill(fifo, limit).0);
assert_eq!(reads.len(), limit);
std::thread::sleep(Duration::from_millis(200));
let cancelled: Vec<bool> = reads.iter().map(|read| read.cancel().unwrap()).collect();
let given_up = cancelled.iter().filter(|&&cancelled| cancelled).count();
note!(
"io::macos: of {limit} reads that wait, {given_up} were cancelled and {} run",
limit - given_up
);
let mut running = Vec::new();
for (mut read, cancelled) in reads.into_iter().zip(cancelled) {
if cancelled {
assert!(!read.is_pending());
let err = read.result().expect("it is over").unwrap_err();
assert_eq!(err.kind(), ErrorKind::Canceled);
assert_eq!(read.cancel(), Ok(false));
assert_eq!(macos::wait(&[&read], Some(Duration::ZERO)), Ok(Some(0)));
assert_eq!(read.take_buffer().unwrap(), b"");
} else {
assert!(read.is_pending());
assert_eq!(read.cancel(), Ok(false));
running.push(read);
}
}
assert!(!running.is_empty());
assert_eq!(
io::write(fifo, &vec![b'c'; running.len()]),
Ok(running.len())
);
for mut read in running {
assert_eq!(finish(&read), Ok(1));
assert_eq!(read.take_buffer().unwrap(), b"c");
}
}
#[test]
fn cancel_at_once() {
let _serial = serial();
let dir = common::tmp_dir("io_macos_cancel_at_once");
let path = dir.join("data");
let file = open(&path, &read_write());
const LEN: usize = 1 << 20;
let mut write = Operation::new();
let mut given_up = 0;
for round in 0..32u8 {
let offset = round as u64 * LEN as u64;
write.write(&file, vec![round + 1; LEN], offset).unwrap();
let cancelled = write.cancel().unwrap();
let outcome = finish(&write);
let mut written = vec![0u8; LEN];
let read = io::read_at(&file, &mut written, offset).unwrap();
if cancelled {
given_up += 1;
assert_eq!(outcome.unwrap_err().kind(), ErrorKind::Canceled);
assert!(written[..read].iter().all(|&byte| byte == 0));
} else {
assert_eq!(outcome, Ok(LEN));
assert_eq!(read, LEN);
assert!(written.iter().all(|&byte| byte == round + 1));
}
assert_eq!(write.take_buffer().unwrap().len(), LEN);
}
note!("io::macos: of 32 writes cancelled at once, {given_up} were not made");
assert!(given_up > 0, "none of 32 writes was cancelled");
}
#[test]
fn dropped_in_flight() {
let _serial = serial();
let limit = macos::limits().unwrap().process as usize;
let fifo = Fifo::new("io_macos_dropped");
let fifo = &fifo.0;
let read = running_read(fifo);
let start = Instant::now();
std::thread::scope(|scope| {
scope.spawn(|| {
std::thread::sleep(Duration::from_millis(150));
io::write(fifo, b"d").unwrap();
});
drop(read);
});
let waited = start.elapsed();
assert!(waited >= Duration::from_millis(150), "{waited:?}");
assert!(waited < Duration::from_secs(4), "{waited:?}");
let again = running_read(fifo);
assert!(again.is_pending(), "the byte was not read");
io::write(fifo, b"e").unwrap();
assert_eq!(finish(&again), Ok(1));
let dir = common::tmp_dir("io_macos_dropped_file");
let path = dir.join("data");
std::fs::write(&path, vec![5u8; 1 << 20]).unwrap();
let file = open(&path, &read_write());
for round in 0..100 {
let mut operation = Operation::new();
match round % 3 {
0 => operation.read(&file, Vec::with_capacity(1 << 20), 0),
1 => operation.write(&file, vec![5u8; 1 << 20], 0),
_ => operation.sync(&file, round % 2 == 0),
}
.unwrap();
}
assert!(std::fs::read(&path).unwrap() == vec![5u8; 1 << 20]);
let (reads, refused) = fill(fifo, limit);
assert_eq!(refused.kind(), ErrorKind::WouldBlock);
assert_eq!(reads.len(), limit);
release(fifo, &reads);
}
#[test]
fn kept_memory() {
let _serial = serial();
let dir = common::tmp_dir("io_macos_kept");
let path = dir.join("data");
let file = open(&path, &read_write());
let mut operation = Operation::new();
static DATA: [u8; 12] = *b"kept memory!";
unsafe { operation.write_kept(&file, DATA.as_ptr(), DATA.len(), 3) }.unwrap();
assert_eq!(finish(&operation), Ok(12));
assert_eq!(operation.take_buffer(), None);
assert_eq!(std::fs::read(&path).unwrap(), b"\0\0\0kept memory!");
let mut array = [b'.'; 16];
unsafe { operation.read_kept(&file, array[2..].as_mut_ptr(), 8, 3) }.unwrap();
assert_eq!(finish(&operation), Ok(8));
assert_eq!(operation.take_buffer(), None);
assert_eq!(&array, b"..kept mem......");
unsafe { operation.read_kept(&file, array.as_mut_ptr(), 16, 11) }.unwrap();
assert_eq!(finish(&operation), Ok(4));
assert_eq!(&array, b"ory!pt mem......");
unsafe { operation.read_kept(&file, array.as_mut_ptr(), 0, 0) }.unwrap();
assert_eq!(finish(&operation), Ok(0));
assert_eq!(&array, b"ory!pt mem......");
let err = unsafe { operation.read_kept(&file, std::ptr::null_mut(), 0, 0) }.unwrap_err();
note!("io::macos: a read into no memory at all: {err:?}");
assert_refused(err, ErrorKind::InvalidInput);
assert_eq!(operation.result(), None);
let read_only = open(&path, &fs::OpenOptions::new().read(true));
let err = unsafe { operation.write_kept(&read_only, DATA.as_ptr(), 12, 0) }.unwrap_err();
assert_refused(err, ErrorKind::BadHandle);
assert_eq!(operation.result(), None);
let fifo = Fifo::new("io_macos_kept_fifo");
let fifo = &fifo.0;
let mut late = Box::new([0u8; 4]);
unsafe { operation.read_kept(fifo, late.as_mut_ptr(), 4, 0) }.unwrap();
assert!(operation.is_pending());
let err = unsafe { operation.write_kept(&file, DATA.as_ptr(), 12, 0) }.unwrap_err();
assert_eq!(err.kind(), ErrorKind::ResourceBusy);
io::write(fifo, b"late").unwrap();
assert_eq!(finish(&operation), Ok(4));
assert_eq!(&*late, b"late");
}
#[test]
fn batch() {
let _serial = serial();
let dir = common::tmp_dir("io_macos_batch");
let path = dir.join("data");
let file = open(&path, &read_write());
assert_eq!(macos::BATCH_MAX, 16);
let batch = Batch::new();
assert!(batch.is_empty());
assert!(format!("{batch:?}").starts_with("Batch"));
let err = batch.submit(None).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidInput);
let err = Batch::default().submit_and_wait().unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidInput);
const PART: usize = 100_000;
let data: Vec<u8> = (0..4 * PART).map(|i| (i / 7) as u8).collect();
let mut writes: Vec<Operation> = (0..4).map(|_| Operation::new()).collect();
let mut batch = Batch::new();
for (i, write) in writes.iter_mut().enumerate() {
let chunk = data[i * PART..(i + 1) * PART].to_vec();
batch.write(write, &file, chunk, (i * PART) as u64).unwrap();
}
assert_eq!(batch.len(), 4);
batch.submit_and_wait().unwrap();
for write in &mut writes {
assert_eq!(write.result(), Some(Ok(PART)));
assert_eq!(write.take_buffer().unwrap().len(), PART);
}
assert!(std::fs::read(&path).unwrap() == data);
let mut reads: Vec<Operation> = (0..4).map(|_| Operation::new()).collect();
let mut kept = vec![0u8; 2 * PART];
let mut batch = Batch::new();
for (i, read) in reads.iter_mut().enumerate() {
let offset = (i * PART) as u64;
if i < 2 {
batch
.read(read, &file, Vec::with_capacity(PART), offset)
.unwrap();
} else {
unsafe {
let ptr = kept.as_mut_ptr().add((i - 2) * PART);
batch.read_kept(read, &file, ptr, PART, offset).unwrap();
}
}
}
batch.submit(None).unwrap();
for (i, read) in reads.iter_mut().enumerate() {
assert_eq!(finish(read), Ok(PART));
if i < 2 {
assert!(read.take_buffer().unwrap() == data[i * PART..(i + 1) * PART]);
} else {
assert_eq!(read.take_buffer(), None);
}
}
assert!(kept == data[2 * PART..]);
let mut batch = Batch::new();
unsafe { batch.write_kept(&mut reads[0], &file, kept.as_ptr(), 10, 0) }.unwrap();
batch.submit_and_wait().unwrap();
assert_eq!(reads[0].result(), Some(Ok(10)));
assert_eq!(&std::fs::read(&path).unwrap()[..10], &kept[..10]);
let mut batch = Batch::new();
let [first, second, ..] = &mut writes[..] else {
unreachable!()
};
batch
.write(first, &file, b"never written".to_vec(), 0)
.unwrap();
let err = batch.read(second, &file, Vec::new(), u64::MAX).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidInput);
assert_eq!(batch.len(), 1);
assert_eq!(writes[0].result(), None);
assert!(!writes[0].is_pending());
assert_eq!(
writes[0].take_buffer().as_deref(),
Some(&b"never written"[..])
);
assert_eq!(&std::fs::read(&path).unwrap()[..10], &kept[..10]);
let mut many: Vec<Operation> = (0..17).map(|_| Operation::new()).collect();
let (last, many) = many.split_last_mut().unwrap();
let mut batch = Batch::new();
for operation in many.iter_mut() {
batch
.read(operation, &file, Vec::with_capacity(8), 0)
.unwrap();
}
let err = batch
.read(last, &file, Vec::with_capacity(8), 0)
.unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidInput);
assert_eq!(batch.len(), 16);
batch.submit_and_wait().unwrap();
for operation in many.iter_mut() {
assert_eq!(operation.result(), Some(Ok(8)));
}
let fifo = Fifo::new("io_macos_batch_fifo");
let fifo = &fifo.0;
let mut busy = Operation::new();
busy.read(fifo, Vec::with_capacity(1), 0).unwrap();
let mut batch = Batch::new();
let err = batch.read(&mut busy, &file, Vec::new(), 0).unwrap_err();
assert_eq!(err.kind(), ErrorKind::ResourceBusy);
io::write(fifo, b"b").unwrap();
assert_eq!(finish(&busy), Ok(1));
}
fn started(operations: &[Operation]) -> Vec<usize> {
(0..operations.len())
.filter(|&i| operations[i].is_pending() || operations[i].result().is_some())
.collect()
}
#[test]
fn batch_refused_in_part() {
let _serial = serial();
let limit = macos::limits().unwrap().process as usize;
let dir = common::tmp_dir("io_macos_batch_refused");
let path = dir.join("data");
std::fs::write(&path, b"0123456789").unwrap();
let file = open(&path, &read_write());
let read_only = open(&path, &fs::OpenOptions::new().read(true));
for wait in [false, true] {
let mut operations: Vec<Operation> = (0..3).map(|_| Operation::new()).collect();
let [first, second, third] = &mut operations[..] else {
unreachable!()
};
let mut batch = Batch::new();
batch.read(first, &file, Vec::with_capacity(4), 0).unwrap();
batch
.write(second, &read_only, b"refused".to_vec(), 0)
.unwrap();
batch.read(third, &file, Vec::with_capacity(4), 6).unwrap();
let refusal = if wait {
batch.submit_and_wait()
} else {
batch.submit(None)
};
let started = started(&operations);
note!(
"io::macos: a batch with a write to a handle open for reading, waited for: \
{wait}: {refusal:?}, and started: {started:?}"
);
assert_refused(refusal.unwrap_err(), ErrorKind::BadHandle);
assert!(!started.contains(&1));
assert_eq!(
operations[1].take_buffer().as_deref(),
Some(&b"refused"[..])
);
assert_eq!(started, []);
for i in [0, 2] {
assert!(operations[i].take_buffer().unwrap().is_empty());
}
assert_eq!(std::fs::read(&path).unwrap(), b"0123456789");
}
let mut operations: Vec<Operation> = (0..2).map(|_| Operation::new()).collect();
let directory = open(&dir, &fs::OpenOptions::new().read(true));
let [first, second] = &mut operations[..] else {
unreachable!()
};
let mut batch = Batch::new();
batch.read(first, &file, Vec::with_capacity(4), 2).unwrap();
batch
.read(second, &directory, Vec::with_capacity(4), 0)
.unwrap();
let waited = batch.submit_and_wait();
note!(
"io::macos: a batch one read of which fails, waited for: {waited:?}, \
and started: {:?}",
started(&operations)
);
waited.unwrap();
assert_eq!(operations[0].result(), Some(Ok(4)));
let err = operations[1].result().expect("it is over").unwrap_err();
assert_eq!(err.kind(), ErrorKind::IsADirectory);
let fifo = Fifo::new("io_macos_batch_limit");
let fifo = &fifo.0;
let mut held = Vec::new();
for _ in 0..limit - 2 {
let mut read = Operation::new();
read.read(fifo, Vec::with_capacity(1), 0).unwrap();
held.push(read);
}
let mut four: Vec<Operation> = (0..4).map(|_| Operation::new()).collect();
let mut batch = Batch::new();
for (i, operation) in four.iter_mut().enumerate() {
batch
.read(operation, &file, Vec::with_capacity(2), 2 * i as u64)
.unwrap();
}
let refusal = batch.submit(None);
let over_limit = started(&four);
note!(
"io::macos: a batch of 4 with 2 places left: {refusal:?}, and started: {over_limit:?}"
);
release(fifo, &held);
drop(held);
for &i in &over_limit {
assert_eq!(finish(&four[i]), Ok(2));
}
assert_eq!(refusal.unwrap_err().kind(), ErrorKind::WouldBlock);
assert_eq!(over_limit, [0, 1]);
for (i, operation) in four.iter_mut().enumerate() {
if !over_limit.contains(&i) {
assert!(operation.take_buffer().unwrap().is_empty());
}
}
let mut batch = Batch::new();
for (i, operation) in four.iter_mut().enumerate() {
batch
.read(operation, &file, Vec::with_capacity(2), 2 * i as u64)
.unwrap();
}
batch.submit(None).unwrap();
assert_eq!(started(&four), [0, 1, 2, 3]);
for operation in &four {
assert_eq!(finish(operation), Ok(2));
}
}
fn sigio() -> Signal {
Signal::from_raw(macos::SIGIO)
}
fn poll(poller: &Poller, timeout: Duration) -> Vec<usize> {
let mut events = [Event::EMPTY; 8];
loop {
match poller.wait(&mut events, Some(timeout)) {
Ok(count) => return events[..count].iter().map(Event::token).collect(),
Err(error) if error.kind() == ErrorKind::Interrupted => {}
Err(error) => panic!("{error:?}"),
}
}
}
fn finish_through_signals(operation: &Operation) -> oscall::Result<usize> {
loop {
match macos::wait(&[operation], Some(LONG)) {
Ok(over) => {
assert_eq!(over, Some(0));
return operation.result().expect("the operation is over");
}
Err(error) if error.kind() == ErrorKind::Interrupted => {}
Err(error) => panic!("{error:?}"),
}
}
}
fn drain(signals: &Signals) -> usize {
let mut count = 0;
while let Some(signal) = signals.try_next() {
assert_eq!(signal, sigio());
count += 1;
}
count
}
#[test]
fn notice_by_signal() {
let _serial = serial();
let dir = common::tmp_dir("io_macos_notice");
let path = dir.join("data");
let file = open(&path, &read_write());
let fifo = Fifo::new("io_macos_notice_fifo");
let fifo = &fifo.0;
let signals = Signals::new(&[sigio()]).unwrap();
let poller = Poller::new().unwrap();
poller.register_signals(&signals, 7).unwrap();
const QUIET: Duration = Duration::from_millis(150);
let mut read = Operation::new();
read.set_notice(Some(sigio()));
read.read(fifo, Vec::with_capacity(4), 0).unwrap();
assert_eq!(poll(&poller, QUIET), []);
assert_eq!(signals.try_next(), None);
io::write(fifo, b"told").unwrap();
assert_eq!(poll(&poller, LONG), [7]);
let over = read.result();
note!("io::macos: when the signal of a notice is told, the outcome is {over:?}");
assert_eq!(over, Some(Ok(4)));
assert_eq!(drain(&signals), 1);
assert_eq!(read.take_buffer().unwrap(), b"told");
assert_eq!(poll(&poller, QUIET), []);
read.read(&file, Vec::with_capacity(4), 0).unwrap();
assert_eq!(poll(&poller, LONG), [7]);
assert_eq!(drain(&signals), 1);
assert_eq!(finish_through_signals(&read), Ok(0));
read.set_notice(None);
read.write(&file, b"quiet".to_vec(), 0).unwrap();
assert_eq!(finish_through_signals(&read), Ok(5));
assert_eq!(poll(&poller, QUIET), []);
assert_eq!(signals.try_next(), None);
let mut writes: Vec<Operation> = (0..8).map(|_| Operation::new()).collect();
for (i, write) in writes.iter_mut().enumerate() {
write.set_notice(Some(sigio()));
write
.write(&file, vec![i as u8; 1000], i as u64 * 1000)
.unwrap();
}
let (mut events, mut told) = (0, 0);
let deadline = Instant::now() + LONG;
while writes.iter().any(|write| write.result().is_none()) {
events += poll(&poller, Duration::from_millis(100)).len();
told += drain(&signals);
assert!(Instant::now() < deadline);
}
std::thread::sleep(QUIET);
events += poll(&poller, Duration::ZERO).len();
told += drain(&signals);
note!(
"io::macos: 8 writes with a notice: {events} events of the poller, \
{told} signals taken"
);
assert!((1..=8).contains(&told), "{told} signals for 8 operations");
for write in &writes {
assert_eq!(write.result(), Some(Ok(1000)));
}
let mut reads: Vec<Operation> = (0..3).map(|_| Operation::new()).collect();
let mut batch = Batch::new();
for read in reads.iter_mut() {
read.set_notice(Some(sigio()));
batch.read(read, fifo, Vec::with_capacity(1), 0).unwrap();
}
batch.submit(Some(sigio())).unwrap();
assert_eq!(poll(&poller, QUIET), []);
io::write(fifo, b"12").unwrap();
let deadline = Instant::now() + LONG;
while reads.iter().filter(|read| read.result().is_some()).count() < 2 {
std::thread::sleep(Duration::from_millis(5));
assert!(Instant::now() < deadline);
}
let early = poll(&poller, QUIET);
note!("io::macos: with 2 of the 3 reads of a batch over, the poller has {early:?}");
assert_eq!(early, []);
assert_eq!(signals.try_next(), None);
io::write(fifo, b"3").unwrap();
assert_eq!(poll(&poller, LONG), [7]);
assert_eq!(drain(&signals), 1);
for read in &reads {
assert_eq!(read.result(), Some(Ok(1)));
}
let mut batch = Batch::new();
for read in reads.iter_mut() {
batch.read(read, &file, Vec::with_capacity(1), 0).unwrap();
}
batch.submit(None).unwrap();
for read in &reads {
assert_eq!(finish_through_signals(read), Ok(1));
}
assert_eq!(poll(&poller, QUIET), []);
assert_eq!(signals.try_next(), None);
for number in [0, -1, 1000, oscall::process::unix::SIGKILL] {
let mut refused = Operation::new();
refused.set_notice(Some(Signal::from_raw(number)));
match refused.read(&file, Vec::with_capacity(1), 0) {
Err(error) => {
note!("io::macos: a notice by the signal {number} is refused: {error:?}");
assert_refused(error, ErrorKind::InvalidInput);
}
Ok(()) => panic!("a notice by the signal {number} was taken"),
}
assert_eq!(refused.result(), None);
}
poller.deregister_signals(&signals).unwrap();
drop(signals);
let mut last = Operation::new();
last.set_notice(Some(sigio()));
last.write(&file, b"nobody listens".to_vec(), 0).unwrap();
assert_eq!(finish_through_signals(&last), Ok(14));
std::thread::sleep(QUIET);
}
const HELPER: &str = "OSCALL_IO_MACOS_HELPER";
#[test]
fn dropped_and_never_over() {
let _serial = serial();
let path = common::tmp_dir("io_macos_never_over").join("fifo");
fs::unix::mkfifo(&path, 0o600).unwrap();
let status = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "operation::helper", "--nocapture"])
.env(HELPER, &path)
.status()
.unwrap();
assert!(status.success(), "{status:?}");
}
#[test]
fn helper() {
let Some(path) = std::env::var_os(HELPER) else {
return;
};
let limit = macos::limits().unwrap().process as usize;
let fifo = Fifo::open(std::path::Path::new(&path));
let fifo = &fifo.0;
let read = running_read(fifo);
let start = Instant::now();
drop(read);
let waited = start.elapsed();
assert!(waited >= Duration::from_secs(4), "{waited:?}");
assert!(waited < Duration::from_secs(30), "{waited:?}");
let (reads, refused) = fill(fifo, limit);
assert_eq!(refused.kind(), ErrorKind::WouldBlock);
assert_eq!(reads.len(), limit - 1);
let mut running = 1;
for read in &reads {
if !read.cancel().unwrap() {
running += 1;
}
}
assert_eq!(io::write(fifo, &vec![b'h'; running]), Ok(running));
for read in &reads {
if read.result().is_none() {
assert_eq!(finish(read), Ok(1));
}
}
std::thread::sleep(Duration::from_millis(200));
drop(reads);
let (reads, _) = fill(fifo, limit);
assert_eq!(reads.len(), limit - 1);
release(fifo, &reads);
}
}