use std::sync::OnceLock;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use crate::types::NANOS_PER_RCB;
pub unsafe fn raw_syscall(number: libc::c_long, args: [u64; 6]) -> i64 {
#[cfg(target_arch = "x86_64")]
{
let result: i64;
unsafe {
core::arch::asm!(
"syscall",
inlateout("rax") number => result,
in("rdi") args[0],
in("rsi") args[1],
in("rdx") args[2],
in("r10") args[3],
in("r8") args[4],
in("r9") args[5],
lateout("rcx") _,
lateout("r11") _,
options(nostack),
);
}
result
}
#[cfg(not(target_arch = "x86_64"))]
{
let result =
unsafe { libc::syscall(number, args[0], args[1], args[2], args[3], args[4], args[5]) };
if result < 0 {
-i64::from(
std::io::Error::last_os_error()
.raw_os_error()
.unwrap_or(libc::EIO),
)
} else {
result
}
}
}
pub fn raw_result(result: i64) -> std::io::Result<u64> {
if (-4095..0).contains(&result) {
Err(std::io::Error::from_raw_os_error(-result as i32))
} else {
Ok(result as u64)
}
}
pub fn raw_zero_result(result: i64) -> std::io::Result<()> {
match raw_result(result)? {
0 => Ok(()),
other => Err(std::io::Error::other(format!(
"a syscall that returns 0 on success returned {other}"
))),
}
}
pub fn describe_io_error(error: &std::io::Error) -> String {
if let Some(code) = error.raw_os_error() {
return format!("{:?} (errno {code})", error.kind());
}
match error
.get_ref()
.and_then(|inner| inner.downcast_ref::<std::io::Error>())
{
Some(inner) => describe_io_error(inner),
None => error.to_string(),
}
}
#[allow(dead_code)]
pub fn punch_out_print(msg: &str) {
use std::io::Write;
if let Ok(mut tty) = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open("/dev/tty")
{
writeln!(tty, "{}", msg).unwrap();
} else {
eprintln!("{}", msg);
}
}
pub fn rcbs_to_duration(rcbs: u64) -> Duration {
Duration::from_nanos((rcbs as f64 * NANOS_PER_RCB) as u64)
}
pub fn truncated(width: usize, mut s: String) -> String {
if s.len() > width {
if width >= 3 {
s.truncate(width - 3);
s.push_str("...");
s
} else {
s.truncate(width);
s
}
} else {
s
}
}
pub struct RetryingStderr;
pub const STDERR_DIAGNOSTIC_DEADLINE: std::time::Duration = std::time::Duration::from_millis(2500);
static STDERR_BLOCKED_SINCE: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
static STDERR_ORIGIN_ADDR: OnceLock<usize> = OnceLock::new();
pub fn init_shared_stderr_deadline_origin() {
STDERR_ORIGIN_ADDR.get_or_init(|| {
let addr = unsafe {
libc::mmap(
std::ptr::null_mut(),
std::mem::size_of::<AtomicU64>(),
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_SHARED | libc::MAP_ANONYMOUS,
-1,
0,
)
};
if addr == libc::MAP_FAILED {
return 0;
}
unsafe { (addr as *mut AtomicU64).write(AtomicU64::new(0)) };
addr as usize
});
}
fn shared_origin_cell() -> Option<&'static AtomicU64> {
match STDERR_ORIGIN_ADDR.get() {
None | Some(0) => None,
Some(&addr) => Some(unsafe { &*(addr as *const AtomicU64) }),
}
}
fn monotonic_nanos() -> u64 {
let mut ts = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) };
(ts.tv_sec as u64) * 1_000_000_000 + (ts.tv_nsec as u64)
}
#[doc(hidden)]
pub fn stderr_deadline_is_shared() -> bool {
shared_origin_cell().is_some()
}
fn stderr_blocked_for() -> std::time::Duration {
match shared_origin_cell() {
Some(cell) => {
let now = monotonic_nanos();
let origin = match cell.compare_exchange(0, now, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => now,
Err(existing) => existing,
};
std::time::Duration::from_nanos(now.saturating_sub(origin))
}
None => STDERR_BLOCKED_SINCE
.get_or_init(std::time::Instant::now)
.elapsed(),
}
}
#[doc(hidden)]
pub fn reset_stderr_deadline_origin_for_test() {
if let Some(cell) = shared_origin_cell() {
cell.store(0, Ordering::Release);
}
}
impl std::io::Write for RetryingStderr {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
loop {
let must_not_wait = crate::nonwaiting_write::diagnostics_must_not_wait();
let attempt = if must_not_wait {
crate::nonwaiting_write::write_without_waiting_for_a_reader(
libc::STDERR_FILENO,
buf,
)
} else {
let n = unsafe { libc::write(libc::STDERR_FILENO, buf.as_ptr().cast(), buf.len()) };
if n >= 0 {
Ok(n as usize)
} else {
Err(std::io::Error::last_os_error())
}
};
let err = match attempt {
Ok(n) => return Ok(n),
Err(err) => err,
};
match err.kind() {
std::io::ErrorKind::Interrupted if must_not_wait => {
if STDERR_DIAGNOSTIC_DEADLINE
.checked_sub(stderr_blocked_for())
.is_none()
{
return Err(std::io::ErrorKind::TimedOut.into());
}
continue;
}
std::io::ErrorKind::Interrupted => continue,
std::io::ErrorKind::WouldBlock => {
let spent = stderr_blocked_for();
let Some(remaining) = STDERR_DIAGNOSTIC_DEADLINE.checked_sub(spent) else {
return Err(err);
};
let mut pfd = libc::pollfd {
fd: libc::STDERR_FILENO,
events: libc::POLLOUT,
revents: 0,
};
let timeout_ms = i32::try_from(remaining.as_millis())
.unwrap_or(i32::MAX)
.min(1000);
unsafe {
libc::poll(&mut pfd, 1, timeout_ms);
}
continue;
}
_ => return Err(err),
}
}
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
pub struct DroppingStderr;
impl std::io::Write for DroppingStderr {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
match RetryingStderr.write(buf) {
Err(_) if crate::nonwaiting_write::diagnostics_must_not_wait() => Ok(buf.len()),
result => result,
}
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
macro_rules! capped_eprintln {
($($arg:tt)*) => {
if crate::nonwaiting_write::diagnostics_must_not_wait() {
let mut line = format!($($arg)*);
line.push('\n');
let _ = std::io::Write::write_all(&mut crate::util::DroppingStderr, line.as_bytes());
} else {
eprintln!($($arg)*);
}
};
}
pub(crate) use capped_eprintln;
#[cfg(test)]
mod shared_stderr_origin_tests {
use super::*;
static SERIALISE: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn exclusive() -> std::sync::MutexGuard<'static, ()> {
SERIALISE.lock().unwrap_or_else(|e| e.into_inner())
}
#[test]
fn the_origin_is_shared_across_a_fork() {
let _exclusive = exclusive();
init_shared_stderr_deadline_origin();
let cell = shared_origin_cell().expect("mapping must exist after init");
cell.store(0, Ordering::Release);
let pid = unsafe { libc::fork() };
assert!(pid >= 0, "fork failed");
if pid == 0 {
shared_origin_cell()
.expect("child inherited no mapping")
.store(4242, Ordering::Release);
unsafe { libc::_exit(0) };
}
let mut status = 0;
assert_eq!(
unsafe { libc::waitpid(pid, &mut status, 0) },
pid,
"waitpid"
);
assert_eq!(status, 0, "child exited nonzero");
assert_eq!(
cell.load(Ordering::Acquire),
4242,
"the parent cannot see the child's write, so each container init would \
start its OWN deadline and the invocation would spend one per process -- \
check MAP_SHARED in init_shared_stderr_deadline_origin"
);
cell.store(0, Ordering::Release);
}
#[test]
fn the_first_writer_installs_the_origin_and_others_inherit_it() {
let _exclusive = exclusive();
init_shared_stderr_deadline_origin();
reset_stderr_deadline_origin_for_test();
let cell = shared_origin_cell().expect("mapping must exist after init");
let first = stderr_blocked_for();
let installed = cell.load(Ordering::Acquire);
assert_ne!(installed, 0, "the first call must install a nonzero origin");
assert!(
first < Duration::from_millis(50),
"first call saw {first:?}"
);
std::thread::sleep(Duration::from_millis(20));
let second = stderr_blocked_for();
assert_eq!(
cell.load(Ordering::Acquire),
installed,
"a later call moved the origin, so each caller would get a fresh \
allowance and the deadline would stop being a total"
);
assert!(
second >= Duration::from_millis(15),
"the second call reported {second:?}, so it is not measuring from the \
origin the first call installed"
);
reset_stderr_deadline_origin_for_test();
}
#[test]
fn whether_the_deadline_is_invocation_wide_is_observable() {
let _exclusive = exclusive();
init_shared_stderr_deadline_origin();
assert!(
stderr_deadline_is_shared(),
"the origin is not shared after init, so the deadline is per-process and \
is multiplied by the number of writing processes"
);
}
}
pub struct RawFd(u64);
impl RawFd {
pub fn open(path: &std::path::Path, flags: libc::c_int) -> std::io::Result<Self> {
let path = raw_path(path)?;
let fd = raw_result(unsafe {
raw_syscall(
libc::SYS_openat,
[
libc::AT_FDCWD as u64,
path.as_ptr() as u64,
(flags | libc::O_CLOEXEC) as u64,
0,
0,
0,
],
)
})?;
Ok(Self(fd))
}
pub fn open_at(&self, name: &std::ffi::OsStr, flags: libc::c_int) -> std::io::Result<Self> {
let name = raw_path(std::path::Path::new(name))?;
let fd = raw_result(unsafe {
raw_syscall(
libc::SYS_openat,
[
self.0,
name.as_ptr() as u64,
(flags | libc::O_CLOEXEC) as u64,
0,
0,
0,
],
)
})?;
Ok(Self(fd))
}
pub fn stat_at(&self, name: &std::ffi::OsStr) -> std::io::Result<libc::stat> {
let name = raw_path(std::path::Path::new(name))?;
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
raw_zero_result(unsafe {
raw_syscall(
libc::SYS_newfstatat,
[
self.0,
name.as_ptr() as u64,
&mut stat as *mut libc::stat as u64,
libc::AT_SYMLINK_NOFOLLOW as u64,
0,
0,
],
)
})?;
Ok(stat)
}
pub fn raw(&self) -> u64 {
self.0
}
pub fn stat(&self) -> std::io::Result<libc::stat> {
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
raw_zero_result(unsafe {
raw_syscall(
libc::SYS_fstat,
[self.0, &mut stat as *mut libc::stat as u64, 0, 0, 0, 0],
)
})?;
Ok(stat)
}
pub fn read_at(&self, buffer: &mut [u8], offset: u64) -> std::io::Result<usize> {
raw_result(unsafe {
raw_syscall(
libc::SYS_pread64,
[
self.0,
buffer.as_mut_ptr() as u64,
buffer.len() as u64,
offset,
0,
0,
],
)
})
.map(|read| read as usize)
}
}
impl Drop for RawFd {
fn drop(&mut self) {
unsafe { raw_syscall(libc::SYS_close, [self.0, 0, 0, 0, 0, 0]) };
}
}
fn raw_path(path: &std::path::Path) -> std::io::Result<std::ffi::CString> {
use std::os::unix::ffi::OsStrExt;
std::ffi::CString::new(path.as_os_str().as_bytes())
.map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput))
}
pub fn raw_stat(path: &std::path::Path) -> std::io::Result<libc::stat> {
let path = raw_path(path)?;
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
raw_zero_result(unsafe {
raw_syscall(
libc::SYS_newfstatat,
[
libc::AT_FDCWD as u64,
path.as_ptr() as u64,
&mut stat as *mut libc::stat as u64,
0,
0,
0,
],
)
})?;
Ok(stat)
}
pub fn raw_read_link(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
use std::os::unix::ffi::OsStrExt;
let path = raw_path(path)?;
let mut target = vec![0_u8; libc::PATH_MAX as usize];
let read = raw_result(unsafe {
raw_syscall(
libc::SYS_readlinkat,
[
libc::AT_FDCWD as u64,
path.as_ptr() as u64,
target.as_mut_ptr() as u64,
target.len() as u64,
0,
0,
],
)
})? as usize;
target.truncate(read);
Ok(std::path::PathBuf::from(std::ffi::OsStr::from_bytes(
&target,
)))
}
pub fn raw_read_file(path: &std::path::Path) -> std::io::Result<Vec<u8>> {
let file = RawFd::open(path, libc::O_RDONLY)?;
let mut contents = Vec::new();
let mut chunk = vec![0_u8; 4096];
loop {
let read = raw_result(unsafe {
raw_syscall(
libc::SYS_read,
[
file.raw(),
chunk.as_mut_ptr() as u64,
chunk.len() as u64,
0,
0,
0,
],
)
})? as usize;
if read == 0 {
return Ok(contents);
}
contents.extend_from_slice(&chunk[..read]);
}
}
pub fn raw_read_listing(path: &std::path::Path) -> std::io::Result<Vec<u8>> {
let mut capacity = 64 * 1024;
loop {
let file = RawFd::open(path, libc::O_RDONLY)?;
let mut contents = vec![0_u8; capacity];
let mut filled = 0;
while filled < capacity {
let read = raw_result(unsafe {
raw_syscall(
libc::SYS_read,
[
file.raw(),
contents[filled..].as_mut_ptr() as u64,
(capacity - filled) as u64,
0,
0,
0,
],
)
})? as usize;
if read == 0 {
contents.truncate(filled);
return Ok(contents);
}
filled += read;
}
capacity *= 2;
}
}
pub fn canonicalize(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
use std::os::unix::ffi::OsStrExt;
use std::path::PathBuf;
let error = std::io::Error::from_raw_os_error;
let bytes = path.as_os_str().as_bytes();
if bytes.is_empty() {
return Err(error(libc::ENOENT));
}
let mut pending: Vec<Vec<u8>> = Vec::new();
let push = |pending: &mut Vec<Vec<u8>>, bytes: &[u8]| {
let mut pieces: Vec<Vec<u8>> = bytes
.split(|&byte| byte == b'/')
.filter(|piece| !piece.is_empty())
.map(<[u8]>::to_vec)
.collect();
if bytes.len() > 1 && bytes.ends_with(b"/") {
pieces.push(b".".to_vec());
}
pieces.reverse();
pending.extend(pieces);
};
let mut resolved = if bytes.starts_with(b"/") {
PathBuf::from("/")
} else {
let mut cwd = vec![0_u8; libc::PATH_MAX as usize];
let length = unsafe {
raw_syscall(
libc::SYS_getcwd,
[cwd.as_mut_ptr() as u64, cwd.len() as u64, 0, 0, 0, 0],
)
};
let length = if length == -(libc::ENAMETOOLONG as i64) {
let here = RawFd::open(
std::path::Path::new("."),
libc::O_RDONLY | libc::O_DIRECTORY,
)?;
cwd = path_of_directory(here)?;
cwd.push(0);
cwd.len()
} else {
raw_result(length)? as usize
};
cwd.truncate(length.saturating_sub(1));
if !cwd.starts_with(b"/") {
return Err(error(libc::ENOENT));
}
PathBuf::from(std::ffi::OsStr::from_bytes(&cwd))
};
push(&mut pending, bytes);
let is_directory = |path: &std::path::Path| {
raw_stat(path).map(|stat| stat.st_mode & libc::S_IFMT == libc::S_IFDIR)
};
let mut links = 0;
while let Some(piece) = pending.pop() {
if piece == b"." || piece == b".." {
if !is_directory(&resolved)? {
return Err(error(libc::ENOTDIR));
}
if piece == b".." {
resolved.pop();
}
continue;
}
let candidate = resolved.join(std::ffi::OsStr::from_bytes(&piece));
let spelled = std::ffi::CString::new(candidate.as_os_str().as_bytes())
.map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput))?;
let mut target = vec![0_u8; libc::PATH_MAX as usize];
let read = loop {
let read = unsafe {
raw_syscall(
libc::SYS_readlinkat,
[
libc::AT_FDCWD as u64,
spelled.as_ptr() as u64,
target.as_mut_ptr() as u64,
target.len() as u64,
0,
0,
],
)
};
if read != target.len() as i64 {
break read;
}
target.resize(target.len() * 2, 0);
};
if read == -(libc::EINVAL as i64) {
resolved = candidate;
continue;
}
let read = raw_result(read)? as usize;
links += 1;
if links > 40 {
return Err(error(libc::ELOOP));
}
if target[..read].starts_with(b"/") {
resolved = PathBuf::from("/");
}
push(&mut pending, &target[..read]);
}
Ok(resolved)
}
fn path_of_directory(start: RawFd) -> std::io::Result<Vec<u8>> {
use std::os::unix::ffi::OsStrExt;
let mut names: Vec<Vec<u8>> = Vec::new();
let mut current = start;
loop {
let here = current.stat()?;
let parent = current.open_at(
std::ffi::OsStr::new(".."),
libc::O_RDONLY | libc::O_DIRECTORY,
)?;
let above = parent.stat()?;
if (above.st_dev, above.st_ino) == (here.st_dev, here.st_ino) {
break;
}
let name = find_in_open_directory(&parent, |name| {
parent
.stat_at(name)
.is_ok_and(|stat| (stat.st_dev, stat.st_ino) == (here.st_dev, here.st_ino))
.then(|| name.as_bytes().to_vec())
})?
.ok_or_else(|| std::io::Error::from_raw_os_error(libc::ENOENT))?;
names.push(name);
current = parent;
}
let mut path = Vec::new();
for name in names.iter().rev() {
path.push(b'/');
path.extend_from_slice(name);
}
if path.is_empty() {
path.push(b'/');
}
Ok(path)
}
pub fn find_in_directory<T>(
path: &std::path::Path,
visit: impl FnMut(&std::ffi::OsStr) -> Option<T>,
) -> std::io::Result<Option<T>> {
let directory = RawFd::open(path, libc::O_RDONLY | libc::O_DIRECTORY)?;
find_in_open_directory(&directory, visit)
}
pub fn find_in_open_directory<T>(
directory: &RawFd,
mut visit: impl FnMut(&std::ffi::OsStr) -> Option<T>,
) -> std::io::Result<Option<T>> {
use std::os::unix::ffi::OsStrExt;
let fd = directory.raw();
let mut buffer = vec![0_u8; 32 * 1024];
'listing: loop {
let read = unsafe {
raw_syscall(
libc::SYS_getdents64,
[fd, buffer.as_mut_ptr() as u64, buffer.len() as u64, 0, 0, 0],
)
};
if read < 0 {
break Err(std::io::Error::from_raw_os_error(-read as i32));
}
if read == 0 {
break Ok(None);
}
let mut offset = 0_usize;
let read = read as usize;
while offset + 19 <= read {
let reclen = u16::from_ne_bytes([buffer[offset + 16], buffer[offset + 17]]) as usize;
if reclen < 19 || offset + reclen > read {
break;
}
let name = &buffer[offset + 19..offset + reclen];
let name = &name[..name
.iter()
.position(|byte| *byte == 0)
.unwrap_or(name.len())];
if name != b"."
&& name != b".."
&& let Some(found) = visit(std::ffi::OsStr::from_bytes(name))
{
break 'listing Ok(Some(found));
}
offset += reclen;
}
}
}
#[cfg(test)]
mod find_in_directory_tests {
use super::*;
#[test]
#[allow(clippy::disallowed_methods)] fn find_in_directory_visits_every_name_and_stops_at_the_first_find() {
let directory = tempfile::tempdir().unwrap();
for index in 0..300 {
std::fs::write(
directory
.path()
.join(format!("entry-with-a-long-name-{index}")),
b"",
)
.unwrap();
}
let mut visited = Vec::new();
let none: Option<()> = find_in_directory(directory.path(), |name| {
visited.push(name.to_owned());
None
})
.unwrap();
assert!(none.is_none());
visited.sort();
let mut expected: Vec<_> = std::fs::read_dir(directory.path())
.unwrap()
.map(|entry| entry.unwrap().file_name())
.collect();
expected.sort();
assert_eq!(visited.len(), 300);
assert_eq!(visited, expected);
let mut calls = 0;
let found = find_in_directory(directory.path(), |name| {
calls += 1;
(calls == 7).then(|| name.to_owned())
})
.unwrap();
assert!(found.is_some());
assert_eq!(calls, 7);
let file = directory.path().join("entry-with-a-long-name-0");
assert!(find_in_directory(&file, |_| Some(())).is_err());
}
}
#[cfg(test)]
mod canonicalize_tests {
use std::os::unix::fs::symlink;
use std::path::Path;
use super::*;
#[test]
fn a_long_directory_path_is_found_by_walking_up() {
use std::os::unix::ffi::OsStrExt;
let directory = tempfile::tempdir().unwrap();
#[allow(clippy::disallowed_methods)] let root = std::fs::canonicalize(directory.path()).unwrap();
let name = "d".repeat(200);
let spelled = std::ffi::CString::new(name.as_str()).unwrap();
let mut levels = vec![RawFd::open(&root, libc::O_RDONLY | libc::O_DIRECTORY).unwrap()];
let mut expected = root.clone();
for _ in 0..25 {
let parent = levels.last().unwrap();
assert_eq!(
unsafe { libc::mkdirat(parent.raw() as i32, spelled.as_ptr(), 0o700) },
0
);
let child = parent
.open_at(
std::ffi::OsStr::new(&name),
libc::O_RDONLY | libc::O_DIRECTORY,
)
.unwrap();
levels.push(child);
expected.push(&name);
}
assert!(expected.as_os_str().len() > 4096);
let deepest = levels
.last()
.unwrap()
.open_at(
std::ffi::OsStr::new("."),
libc::O_RDONLY | libc::O_DIRECTORY,
)
.unwrap();
let found = path_of_directory(deepest).unwrap();
let short = RawFd::open(&root, libc::O_RDONLY | libc::O_DIRECTORY).unwrap();
let short = path_of_directory(short).unwrap();
for parent in levels[..25].iter().rev() {
unsafe { libc::unlinkat(parent.raw() as i32, spelled.as_ptr(), libc::AT_REMOVEDIR) };
}
assert_eq!(std::ffi::OsStr::from_bytes(&found), expected.as_os_str());
assert_eq!(std::ffi::OsStr::from_bytes(&short), root.as_os_str());
}
#[test]
#[allow(clippy::disallowed_methods)] fn canonicalize_matches_realpath() {
let directory = tempfile::tempdir().unwrap();
let root = directory.path();
std::fs::create_dir_all(root.join("a/b/c")).unwrap();
std::fs::write(root.join("a/b/c/file"), b"").unwrap();
symlink(root.join("a/b"), root.join("absolute")).unwrap();
symlink("a/b/c", root.join("relative")).unwrap();
symlink("relative", root.join("chained")).unwrap();
symlink("../../b", root.join("a/b/c/up")).unwrap();
symlink("loop2", root.join("loop1")).unwrap();
symlink("loop1", root.join("loop2")).unwrap();
for spelled in [
root.join("a/b/c/file"),
root.join("absolute/c/file"),
root.join("relative/file"),
root.join("chained/./file"),
root.join("chained/../c/file"),
root.join("a/b/c/up/c/file"),
root.join("absolute/c/up/../.."),
Path::new("/proc/self").to_path_buf(),
Path::new("/proc/self/exe").to_path_buf(),
Path::new("/").to_path_buf(),
] {
assert_eq!(
canonicalize(&spelled).unwrap(),
std::fs::canonicalize(&spelled).unwrap(),
"{spelled:?}"
);
}
for spelled in [
root.join("a/b/"),
root.join("a/b/."),
root.join("absolute/"),
root.join("relative/."),
] {
assert_eq!(
canonicalize(&spelled).unwrap(),
std::fs::canonicalize(&spelled).unwrap(),
"{spelled:?}"
);
}
let error = |spelled: &Path| canonicalize(spelled).unwrap_err().raw_os_error();
let reference = |spelled: &Path| std::fs::canonicalize(spelled).unwrap_err().raw_os_error();
let file = root.join("a/b/c/file");
let violating = [
Path::new("").to_path_buf(),
root.join("missing/file"),
root.join("a/b/c/file/x"),
root.join("loop1"),
file.join(""),
Path::new(&format!("{}/.", file.display())).to_path_buf(),
Path::new(&format!("{}/..", file.display())).to_path_buf(),
Path::new(&format!("{}/../file", file.display())).to_path_buf(),
];
for spelled in &violating {
assert_eq!(error(spelled), reference(spelled), "{spelled:?}");
}
assert_eq!(error(&violating[0]), Some(libc::ENOENT));
assert_eq!(error(&violating[3]), Some(libc::ELOOP));
assert_eq!(error(&violating[5]), Some(libc::ENOTDIR));
let here = std::env::current_dir().unwrap();
assert_eq!(
canonicalize(Path::new(".")).unwrap(),
std::fs::canonicalize(&here).unwrap()
);
}
}