use std::collections::HashMap;
use std::ffi::CStr;
use std::ffi::CString;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::io;
use std::os::fd::RawFd;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::ffi::OsStringExt;
use std::os::unix::fs::MetadataExt;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use detcore_model::fd::RawInode;
use reverie::BackendCapabilities;
use reverie::syscalls::Errno;
use serde::Deserialize;
use serde::Serialize;
use crate::util::describe_io_error;
pub(crate) const PROC_ROOT_INO: u64 = 1;
pub(crate) const PROC_BLOCK_SIZE: i64 = 1024;
pub(crate) const VIRTUAL_PROC_DEVICE: u64 = 0x00f0_00ff;
pub(crate) fn rendered_inode(path: &Path) -> u64 {
const RENDERED_INODE_BASE: u64 = 0xf000_0000;
if let Some(name) = crate::procfs::per_process_name(path) {
return per_process_inode(name);
}
RENDERED_INODE_BASE | (fnv1a(FNV_OFFSET_BASIS, path.as_os_str().as_bytes()) & 0x0fff_ffff)
}
pub(crate) const MAX_INCARNATION: u32 = (1 << INCARNATION_BITS) - 1;
const INCARNATION_BITS: u32 = 8;
const PID_BITS: u32 = 22;
const INDEX_BITS: u32 = 3;
const _: () = assert!(
crate::procfs::ProcfsFile::PER_PROCESS_NAMES.len() < 1 << INDEX_BITS,
"every per-process file needs an index in its inode number"
);
const _: () = assert!(1 + INDEX_BITS + 2 * PID_BITS + 2 * INCARNATION_BITS == 64);
pub(crate) fn incarnation_fits(incarnation: crate::procfs::TaskIncarnation) -> bool {
incarnation.process <= MAX_INCARNATION
&& incarnation
.thread
.is_none_or(|thread| thread <= MAX_INCARNATION)
}
pub(crate) fn per_process_inode(name: crate::procfs::PerProcessName) -> u64 {
let index = crate::procfs::ProcfsFile::PER_PROCESS_NAMES
.iter()
.position(|candidate| *candidate == name.filename)
.expect("a per-process file Detcore renders has an index")
+ 1;
let field = |value: i64, bits: u32, what: &str| -> u64 {
assert!(
(0..1_i64 << bits).contains(&value),
"{what} {value} of {} does not fit the {bits}-bit field of its inode number",
name.task.process
);
value as u64
};
let index = field(index as i64, INDEX_BITS, "file index");
let process = field(name.task.process.into(), PID_BITS, "pid");
let thread = field(name.task.thread.unwrap_or(0).into(), PID_BITS, "tid");
let incarnation = name.incarnation.unwrap_or(crate::procfs::TaskIncarnation {
process: 0,
thread: None,
});
let process_incarnation = field(
incarnation.process.into(),
INCARNATION_BITS,
"pid incarnation",
);
let thread_incarnation = field(
incarnation.thread.unwrap_or(0).into(),
INCARNATION_BITS,
"tid incarnation",
);
1 << 63
| index << (PID_BITS * 2 + INCARNATION_BITS * 2)
| process << (PID_BITS + INCARNATION_BITS * 2)
| thread << (INCARNATION_BITS * 2)
| process_incarnation << INCARNATION_BITS
| thread_incarnation
}
const PATH_KEY_BIT: u64 = 1 << 63;
const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
fn fnv1a(hash: u64, bytes: &[u8]) -> u64 {
const PRIME: u64 = 0x0000_0100_0000_01b3;
bytes.iter().fold(hash, |hash, &byte| {
(hash ^ u64::from(byte)).wrapping_mul(PRIME)
})
}
pub(crate) fn may_be_procfs(device: u64, block_size: i64) -> bool {
libc::major(device) == 0 && block_size == PROC_BLOCK_SIZE
}
pub(crate) const KVM_SYNTHETIC_PROC_DEVICE: u64 = libc::makedev(0, 0xff01);
pub(crate) fn is_backend_procfs_device(
backend: &BackendCapabilities,
device: u64,
block_size: i64,
) -> bool {
!tool_can_name_guest_descriptors(backend)
&& device == KVM_SYNTHETIC_PROC_DEVICE
&& block_size == 4096
}
pub(crate) fn unprovable_procfs_signature(
backend: &BackendCapabilities,
physical_tid: Option<i32>,
device: u64,
block_size: i64,
) -> bool {
tool_can_name_guest_descriptors(backend)
&& !guest_tids_name_host_tasks(backend, physical_tid)
&& may_be_procfs(device, block_size)
}
pub(crate) fn guest_tids_name_host_tasks(
backend: &BackendCapabilities,
physical_tid: Option<i32>,
) -> bool {
!backend.provides_process_signal_control && physical_tid.is_none()
}
pub(crate) fn tool_can_name_guest_descriptors(backend: &BackendCapabilities) -> bool {
!backend.provides_process_signal_control
}
pub(crate) fn path_inode(device: u64, path: &Path) -> RawInode {
RawInode::new(
device,
PATH_KEY_BIT | fnv1a(FNV_OFFSET_BASIS, path.as_os_str().as_bytes()),
)
}
pub(crate) fn with_incarnation(key: RawInode, task: i32, incarnation: u32) -> RawInode {
let hash = fnv1a(
fnv1a(key.ino, &task.to_le_bytes()),
&incarnation.to_le_bytes(),
);
RawInode::new(key.dev, PATH_KEY_BIT | hash)
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProcfsName {
pub path: RawInode,
pub tasks: Vec<i32>,
pub threads_counted: Option<u64>,
}
impl ProcfsName {
pub(crate) fn new(device: u64, within: &Path) -> Self {
Self {
path: path_inode(device, within),
tasks: tasks_named(within),
threads_counted: None,
}
}
pub(crate) fn in_snapshot(self, threads_counted: u64) -> Self {
Self {
threads_counted: Some(threads_counted),
..self
}
}
}
fn task_id(component: Option<Component<'_>>) -> Option<i32> {
match component {
Some(Component::Normal(name)) => name
.to_str()?
.parse::<i32>()
.ok()
.filter(|id| *id > 0 && name.as_bytes()[0] != b'+'),
_ => None,
}
}
fn tasks_named(within: &Path) -> Vec<i32> {
let mut components = within
.components()
.skip_while(|component| *component == Component::RootDir);
let Some(pid) = task_id(components.next()) else {
return Vec::new();
};
let mut tasks = vec![pid];
if components.next() == Some(Component::Normal(OsStr::new("task")))
&& let Some(tid) = task_id(components.next())
{
tasks.push(tid);
}
tasks
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ProcfsMount {
id: u64,
root: PathBuf,
mount_point: PathBuf,
}
pub(crate) fn procfs_mounts(
tid: i32,
device: u64,
reread: bool,
) -> io::Result<Option<Arc<[ProcfsMount]>>> {
procfs_mounts_at(Path::new(&format!("/proc/{tid}")), device, reread)
}
fn procfs_mounts_at(
task: &Path,
device: u64,
reread: bool,
) -> io::Result<Option<Arc<[ProcfsMount]>>> {
type Key = (u64, Option<u64>, u64, u64, PathBuf, u64);
static PROCFS_DEVICES: OnceLock<Mutex<HashMap<Key, Arc<[ProcfsMount]>>>> = OnceLock::new();
let namespace = std::fs::metadata(task.join("ns/mnt"))?;
let root_link = task.join("root");
let root = identify(&root_link, true)?;
let root_path = std::fs::read_link(&root_link)?;
let key = (
namespace.ino(),
root.mount_id,
root.device,
root.inode,
root_path.clone(),
device,
);
let known = PROCFS_DEVICES.get_or_init(Default::default);
if !reread && let Some(mounts) = known.lock().unwrap().get(&key) {
return Ok(Some(mounts.clone()));
}
let mountinfo_path = task.join("mountinfo");
let mountinfo = read_checking_close(mountinfo_path.to_str().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"non-UTF8 task procfs directory",
)
})?)?;
let mounts = procfs_mounts_in(&mountinfo, device, &root_path);
if mounts.is_empty() {
known.lock().unwrap().remove(&key);
return Ok(None);
}
let mounts: Arc<[ProcfsMount]> = mounts.into();
known.lock().unwrap().insert(key, mounts.clone());
Ok(Some(mounts))
}
pub(crate) fn descriptor_procfs_path(
task: &Path,
fd: i32,
device: u64,
inode: u64,
) -> Result<Option<PathBuf>, String> {
let link = task.join("fd").join(fd.to_string());
if !is_on_procfs(&link, device, inode)? {
return Ok(None);
}
let mounts = procfs_mounts_at(task, device, false)
.map_err(|error| {
format!(
"cannot read task mount table: {}",
describe_io_error(&error)
)
})?
.ok_or_else(|| "procfs descriptor is outside the task's procfs mounts".to_owned())?;
let (canonical, mount_id) = inspect_link(&link, device, inode)?;
path_within(
&mounts,
mount_id,
&canonical,
|| procfs_mounts_at(task, device, true),
mount_root,
)
.map(Some)
}
const INTERRUPTED_ATTEMPTS: usize = 8;
fn read_checking_close(path: &str) -> io::Result<Vec<u8>> {
let c_path = c_path(Path::new(path))?;
let fd = retrying_interrupted("open", path, || {
let fd = unsafe { libc::open(c_path.as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC) };
if fd < 0 {
Err(io::Error::last_os_error())
} else {
Ok(fd)
}
})?;
let read = read_to_end(fd, path);
if unsafe { libc::close(fd) } != 0 {
return Err(io::Error::other(format!(
"cannot close descriptor {fd} of {path}: {}",
describe_io_error(&io::Error::last_os_error())
)));
}
read
}
fn read_to_end(fd: RawFd, path: &str) -> io::Result<Vec<u8>> {
let mut contents = Vec::new();
let mut chunk = [0u8; 4096];
loop {
let count = retrying_interrupted("read", path, || {
let count = unsafe { libc::read(fd, chunk.as_mut_ptr().cast(), chunk.len()) };
usize::try_from(count).map_err(|_| io::Error::last_os_error())
})?;
if count == 0 {
return Ok(contents);
}
contents.extend_from_slice(&chunk[..count]);
}
}
fn retrying_interrupted<T>(
name: &str,
path: &str,
mut call: impl FnMut() -> io::Result<T>,
) -> io::Result<T> {
for _ in 0..INTERRUPTED_ATTEMPTS {
match call() {
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
done => return done,
}
}
Err(io::Error::other(format!(
"the {name} of {path} was interrupted in each of {INTERRUPTED_ATTEMPTS} attempts"
)))
}
fn procfs_mounts_in(mountinfo: &[u8], device: u64, guest_root: &Path) -> Vec<ProcfsMount> {
let wanted = format!("{}:{}", libc::major(device), libc::minor(device));
mountinfo
.split(|byte| *byte == b'\n')
.filter_map(|line| {
let fields: Vec<&[u8]> = line.split(|byte| *byte == b' ').collect();
if fields.get(2).copied() != Some(wanted.as_bytes()) {
return None;
}
let separator = 6 + fields.get(6..)?.iter().position(|field| *field == b"-")?;
if fields.get(separator + 1).copied() != Some(b"proc".as_slice()) {
return None;
}
let mount_point = unescape(fields[4]);
Some(ProcfsMount {
id: std::str::from_utf8(fields[0]).ok()?.parse().ok()?,
root: unescape(fields[3]),
mount_point: guest_root.join(mount_point.strip_prefix("/").unwrap_or(&mount_point)),
})
})
.collect()
}
fn unescape(field: &[u8]) -> PathBuf {
let mut path = Vec::with_capacity(field.len());
let mut index = 0;
while index < field.len() {
let octal = field
.get(index + 1..index + 4)
.filter(|digits| field[index] == b'\\' && digits.iter().all(u8::is_ascii_digit))
.filter(|digits| digits.iter().all(|digit| *digit < b'8'));
match octal {
Some(digits) => {
path.push(digits.iter().fold(0u8, |value, digit| {
value.wrapping_mul(8).wrapping_add(digit - b'0')
}));
index += 4;
}
None => {
path.push(field[index]);
index += 1;
}
}
}
PathBuf::from(OsString::from_vec(path))
}
pub(crate) fn path_within(
mounts: &[ProcfsMount],
mount_id: u64,
canonical: &Path,
reread: impl FnOnce() -> io::Result<Option<Arc<[ProcfsMount]>>>,
mount_root: impl Fn(&Path) -> io::Result<Option<u64>>,
) -> Result<PathBuf, String> {
if let Ok(within) = within_table(mounts, mount_id, canonical, &mount_root) {
return Ok(within);
}
match reread() {
Ok(Some(mounts)) => within_table(&mounts, mount_id, canonical, &mount_root),
Ok(None) => Err(format!(
"{} was reached through mount {mount_id}, and the guest's mount table, read again, lists no procfs mount of its device",
canonical.display()
)),
Err(error) => Err(format!(
"{} was reached through mount {mount_id}, and the guest's mount table cannot be read again: {}",
canonical.display(),
describe_io_error(&error)
)),
}
}
fn within_table(
mounts: &[ProcfsMount],
mount_id: u64,
canonical: &Path,
mount_root: &impl Fn(&Path) -> io::Result<Option<u64>>,
) -> Result<PathBuf, String> {
let reached = format!(
"{} was reached through mount {mount_id}",
canonical.display()
);
let mount = mounts
.iter()
.find(|mount| mount.id == mount_id)
.ok_or_else(|| {
format!("{reached}, which the guest's mount table does not list as a procfs mount")
})?;
let point = mount.mount_point.display();
let rest = canonical.strip_prefix(&mount.mount_point).map_err(|_| {
format!("{reached}, which the guest's mount table lists at {point}, not above it")
})?;
match mount_root(&mount.mount_point) {
Ok(Some(found)) if found == mount_id => {}
Ok(Some(found)) => {
return Err(format!(
"{reached}, and {point}, where the guest's mount table lists it, is the root of mount {found}"
));
}
Ok(None) => {
return Err(format!(
"{reached}, and {point}, where the guest's mount table lists it, is the root of no mount"
));
}
Err(error) => {
return Err(format!(
"{reached}, and cannot tell whether {point}, where the guest's mount table lists it, holds it: {}",
describe_io_error(&error)
));
}
}
if rest.as_os_str().is_empty() {
Ok(mount.root.clone())
} else {
Ok(mount.root.join(rest))
}
}
pub(crate) fn inspect_link(link: &Path, device: u64, inode: u64) -> Result<(PathBuf, u64), String> {
let mount_id = check_link_object(link, device, inode)?
.ok_or_else(|| format!("the kernel does not report the mount of {}", link.display()))?;
let canonical = std::fs::read_link(link).map_err(|error| {
format!(
"cannot read the link {}: {}",
link.display(),
describe_io_error(&error)
)
})?;
Ok((refuse_deleted(link, canonical)?, mount_id))
}
fn refuse_deleted(link: &Path, canonical: PathBuf) -> Result<PathBuf, String> {
if canonical.as_os_str().as_bytes().ends_with(b" (deleted)") {
return Err(format!(
"{} leads to {}, an entry of a task that has exited",
link.display(),
canonical.display()
));
}
Ok(canonical)
}
pub(crate) fn is_on_procfs(link: &Path, device: u64, inode: u64) -> Result<bool, String> {
check_link_object(link, device, inode)?;
let path = CString::new(link.as_os_str().as_bytes())
.map_err(|_| format!("{} contains a NUL byte", link.display()))?;
let mut buf = std::mem::MaybeUninit::<libc::statfs>::uninit();
if unsafe { libc::statfs(path.as_ptr(), buf.as_mut_ptr()) } != 0 {
return Err(format!(
"cannot statfs {}: {}",
link.display(),
describe_io_error(&io::Error::last_os_error())
));
}
Ok(unsafe { buf.assume_init() }.f_type == libc::PROC_SUPER_MAGIC)
}
fn check_link_object(link: &Path, device: u64, inode: u64) -> Result<Option<u64>, String> {
let found = identify(link, true).map_err(|error| {
format!(
"cannot stat {}: {}",
link.display(),
describe_io_error(&error)
)
})?;
if found.device != device || found.inode != inode {
return Err(format!(
"{} is not the object the guest saw",
link.display()
));
}
Ok(found.mount_id)
}
struct FileIdentity {
device: u64,
inode: u64,
mount_id: Option<u64>,
mount_root: Option<bool>,
}
fn identify(path: &Path, follow: bool) -> io::Result<FileIdentity> {
let mut flags = libc::AT_NO_AUTOMOUNT;
if !follow {
flags |= libc::AT_SYMLINK_NOFOLLOW;
}
identify_at(libc::AT_FDCWD, &c_path(path)?, flags)
}
fn c_path(path: &Path) -> io::Result<CString> {
CString::new(path.as_os_str().as_bytes())
.map_err(|_| io::Error::other(format!("{} contains a NUL byte", path.display())))
}
fn identify_at(dirfd: RawFd, path: &CStr, flags: i32) -> io::Result<FileIdentity> {
let mut buf = std::mem::MaybeUninit::<libc::statx>::zeroed();
let mask = libc::STATX_INO | libc::STATX_MNT_ID;
if unsafe { libc::statx(dirfd, path.as_ptr(), flags, mask, buf.as_mut_ptr()) } != 0 {
return Err(io::Error::last_os_error());
}
let found = unsafe { buf.assume_init() };
if found.stx_mask & libc::STATX_INO == 0 {
return Err(io::Error::other("statx reported no inode number"));
}
let mount_root = libc::STATX_ATTR_MOUNT_ROOT as u64;
Ok(FileIdentity {
device: libc::makedev(found.stx_dev_major, found.stx_dev_minor),
inode: found.stx_ino,
mount_id: (found.stx_mask & libc::STATX_MNT_ID != 0).then_some(found.stx_mnt_id),
mount_root: (found.stx_attributes_mask & mount_root != 0)
.then_some(found.stx_attributes & mount_root != 0),
})
}
pub(crate) fn mount_root(path: &Path) -> io::Result<Option<u64>> {
let path = c_path(path)?;
let mut how: libc::open_how = unsafe { std::mem::zeroed() };
how.flags = (libc::O_PATH | libc::O_CLOEXEC) as u64;
how.resolve = libc::RESOLVE_NO_SYMLINKS;
let fd = unsafe {
libc::syscall(
libc::SYS_openat2,
libc::AT_FDCWD,
path.as_ptr(),
&how as *const libc::open_how,
std::mem::size_of::<libc::open_how>(),
)
};
if fd < 0 {
return Err(io::Error::last_os_error());
}
let fd = RawFd::try_from(fd)
.map_err(|_| io::Error::other(format!("openat2 returned {fd}, which is no descriptor")))?;
let found = identify_at(fd, c"", libc::AT_EMPTY_PATH | libc::AT_NO_AUTOMOUNT);
if unsafe { libc::close(fd) } != 0 {
return Err(io::Error::other(format!(
"cannot close descriptor {fd}: {}",
describe_io_error(&io::Error::last_os_error())
)));
}
let found = found?;
match (found.mount_root, found.mount_id) {
(Some(false), _) => Ok(None),
(Some(true), Some(id)) => Ok(Some(id)),
_ => Err(io::Error::other(
"the kernel does not report the root of a mount",
)),
}
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Injected<T> {
Ran(T),
NotRun(String),
Failed(String),
}
pub(crate) fn read_open(result: Result<i64, Errno>) -> Injected<RawFd> {
match result {
Ok(fd) => RawFd::try_from(fd).map_or_else(
|_| Injected::Failed(format!("openat returned {fd}, which is no descriptor")),
Injected::Ran,
),
Err(
errno @ (Errno::EINTR
| Errno::ERESTARTSYS
| Errno::ERESTARTNOINTR
| Errno::ERESTARTNOHAND
| Errno::ERESTART_RESTARTBLOCK),
) => Injected::NotRun(errno.to_string()),
Err(errno) => Injected::Failed(format!("cannot open the guest's path again: {errno}")),
}
}
pub(crate) fn read_close(result: Result<i64, Errno>) -> Injected<()> {
match result {
Ok(0) => Injected::Ran(()),
Ok(other) => Injected::Failed(format!(
"close of the guest's O_PATH descriptor returned {other}, which close never returns"
)),
Err(
errno @ (Errno::ERESTARTSYS
| Errno::ERESTARTNOINTR
| Errno::ERESTARTNOHAND
| Errno::ERESTART_RESTARTBLOCK),
) => Injected::NotRun(errno.to_string()),
Err(errno) => Injected::Failed(format!(
"close of the guest's O_PATH descriptor returned {errno:?}"
)),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct ProcfsDirectory {
path: PathBuf,
}
impl ProcfsDirectory {
pub(crate) fn new(path: PathBuf) -> Self {
Self { path }
}
fn entry_path(&self, name: &[u8]) -> PathBuf {
match name {
b"." => self.path.clone(),
b".." => self.path.parent().unwrap_or(&self.path).to_path_buf(),
name => self.path.join(OsStr::from_bytes(name)),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct DirectoryInodes {
device: u64,
procfs: Option<ProcfsDirectory>,
}
impl DirectoryInodes {
pub(crate) fn new(device: u64, procfs: Option<ProcfsDirectory>) -> Self {
Self { device, procfs }
}
pub(crate) fn device(&self) -> u64 {
self.device
}
pub(crate) fn rendered_entry_inode(
&self,
name: &[u8],
files: crate::procfs::RenderedFiles,
) -> Option<u64> {
let path = self.entry_procfs_path(name)?;
crate::procfs::ProcfsFile::from_path(&path)
.filter(|file| file.per_process_name().is_none())?
.rendered_path(files)
.map(rendered_inode)
}
pub(crate) fn entry_procfs_path(&self, name: &[u8]) -> Option<PathBuf> {
let within = self.procfs.as_ref()?.entry_path(name);
let relative = within.strip_prefix("/").unwrap_or(&within);
Some(Path::new("/proc").join(relative))
}
pub(crate) fn entry_inode(&self, name: &[u8], host_ino: u64) -> (RawInode, Option<ProcfsName>) {
let procfs = self
.procfs
.as_ref()
.map(|directory| ProcfsName::new(self.device, &directory.entry_path(name)));
(RawInode::new(self.device, host_ino), procfs)
}
}
pub(crate) async fn preserving_errno<F: std::future::Future>(work: F) -> F::Output {
let saved = nix::errno::Errno::last_raw();
let output = work.await;
nix::errno::Errno::set_raw(saved);
output
}
#[cfg(test)]
mod tests {
use std::fs::File;
use std::os::fd::AsRawFd;
use super::*;
#[test]
fn a_task_generation_fits_its_inode_field_up_to_its_bound() {
use crate::procfs::TaskIncarnation;
let identity = |process, thread| TaskIncarnation { process, thread };
assert_eq!(MAX_INCARNATION, 255);
assert!(incarnation_fits(identity(1, None)));
assert!(incarnation_fits(identity(255, None)));
assert!(incarnation_fits(identity(255, Some(255))));
assert!(!incarnation_fits(identity(256, None)));
assert!(!incarnation_fits(identity(1, Some(256))));
assert!(!incarnation_fits(identity(u32::MAX, Some(1))));
}
#[test]
fn a_failed_host_call_leaves_the_callers_errno() {
const SENTINEL: i32 = 4242;
nix::errno::Errno::set_raw(SENTINEL);
let inside = futures::executor::block_on(preserving_errno(async {
assert!(std::fs::symlink_metadata("/proc/self/fd/-1").is_err());
nix::errno::Errno::last_raw()
}));
assert_eq!(inside, libc::ENOENT, "the failed call set errno");
assert_eq!(nix::errno::Errno::last_raw(), SENTINEL);
}
#[cfg(target_arch = "x86_64")]
fn deny_in_this_thread(syscalls: &[i64], errno: i32) {
const AUDIT_ARCH_X86_64: u32 = 0xc000_003e;
let load = |offset: u32| libc::sock_filter {
code: (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16,
jt: 0,
jf: 0,
k: offset,
};
let jump_if = |value: u32, jt: u8, jf: u8| libc::sock_filter {
code: (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16,
jt,
jf,
k: value,
};
let ret = |action: u32| libc::sock_filter {
code: (libc::BPF_RET | libc::BPF_K) as u16,
jt: 0,
jf: 0,
k: action,
};
let mut program = vec![
load(4),
jump_if(AUDIT_ARCH_X86_64, 1, 0),
ret(libc::SECCOMP_RET_ALLOW),
load(0),
];
for (index, syscall) in syscalls.iter().enumerate() {
let over = u8::try_from(syscalls.len() - index).unwrap();
program.push(jump_if(u32::try_from(*syscall).unwrap(), over, 0));
}
program.push(ret(libc::SECCOMP_RET_ALLOW));
program.push(ret(libc::SECCOMP_RET_ERRNO | errno as u32));
let fprog = libc::sock_fprog {
len: program.len() as u16,
filter: program.as_mut_ptr(),
};
assert_eq!(
unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) },
0
);
let installed = unsafe {
libc::syscall(
libc::SYS_seccomp,
libc::SECCOMP_SET_MODE_FILTER,
0,
&fprog as *const libc::sock_fprog,
)
};
assert_eq!(installed, 0, "seccomp: {}", io::Error::last_os_error());
}
#[cfg(target_arch = "x86_64")]
fn mount_table_error_with_denied(syscalls: &'static [i64], errno: i32) -> String {
let root = std::fs::metadata("/").unwrap().dev();
std::thread::spawn(move || {
deny_in_this_thread(syscalls, errno);
let tid = unsafe { libc::gettid() };
let error = procfs_mounts(tid, root, false).unwrap_err();
format!("{tid} {}", describe_io_error(&error))
})
.join()
.unwrap()
}
#[cfg(target_arch = "x86_64")]
#[test]
fn a_mount_table_read_whose_close_is_refused_is_an_error() {
let error = mount_table_error_with_denied(&[libc::SYS_close], libc::EPERM);
let (_, error) = error.split_once(' ').unwrap();
let fd: i32 = error
.strip_prefix("cannot close descriptor ")
.and_then(|rest| rest.split_once(' '))
.and_then(|(fd, _)| fd.parse().ok())
.unwrap_or_else(|| panic!("not a refused close: {error}"));
assert!(error.ends_with(": PermissionDenied (errno 1)"), "{error}");
assert!(unsafe { libc::fcntl(fd, libc::F_GETFD) } >= 0, "{error}");
assert_eq!(unsafe { libc::close(fd) }, 0);
}
#[cfg(target_arch = "x86_64")]
#[test]
fn a_mount_table_read_that_is_always_interrupted_is_an_error() {
let error = mount_table_error_with_denied(&[libc::SYS_read], libc::EINTR);
let (tid, error) = error.split_once(' ').unwrap();
assert_eq!(
error,
format!(
"the read of /proc/{tid}/mountinfo was interrupted in each of {INTERRUPTED_ATTEMPTS} attempts"
)
);
}
#[cfg(target_arch = "x86_64")]
#[test]
fn a_mount_table_open_that_is_always_interrupted_is_an_error() {
let error = mount_table_error_with_denied(&[libc::SYS_open, libc::SYS_openat], libc::EINTR);
let (tid, error) = error.split_once(' ').unwrap();
assert_eq!(
error,
format!(
"the open of /proc/{tid}/mountinfo was interrupted in each of {INTERRUPTED_ATTEMPTS} attempts"
)
);
}
#[test]
fn an_interrupted_call_is_made_again_a_bounded_number_of_times() {
let interrupted = || io::Error::from_raw_os_error(libc::EINTR);
let mut calls = 0;
let error = retrying_interrupted("read", "/x", || -> io::Result<()> {
calls += 1;
Err(interrupted())
})
.unwrap_err();
assert_eq!(calls, INTERRUPTED_ATTEMPTS);
assert_ne!(error.kind(), io::ErrorKind::Interrupted);
let mut calls = 0;
let read = retrying_interrupted("read", "/x", || {
calls += 1;
if calls < 3 { Err(interrupted()) } else { Ok(7) }
});
assert_eq!((read.unwrap(), calls), (7, 3));
let mut calls = 0;
let error = retrying_interrupted("open", "/x", || -> io::Result<()> {
calls += 1;
Err(io::Error::from_raw_os_error(libc::EACCES))
})
.unwrap_err();
assert_eq!((error.raw_os_error(), calls), (Some(libc::EACCES), 1));
}
#[test]
fn a_file_longer_than_one_read_is_read_whole() {
let path = std::env::current_exe().unwrap();
let path = path.to_str().unwrap();
let expected = std::fs::read(path).unwrap();
assert!(expected.len() > 2 * 4096, "too short to need several reads");
assert!(read_checking_close(path).unwrap() == expected);
}
const PROC_DEVICE: u64 = libc::makedev(0, 23);
fn proc_fd_listing() -> DirectoryInodes {
DirectoryInodes::new(
PROC_DEVICE,
Some(ProcfsDirectory::new(PathBuf::from("/3/fd"))),
)
}
fn name(path: &str) -> Option<ProcfsName> {
Some(ProcfsName::new(PROC_DEVICE, Path::new(path)))
}
#[test]
fn a_procfs_entry_names_its_path_whatever_its_host_inode() {
let listing = proc_fd_listing();
let (host, before) = listing.entry_inode(b"0", 4_123_456);
let (rebuilt_host, rebuilt) = listing.entry_inode(b"0", 4_987_654);
assert_eq!(host, RawInode::new(PROC_DEVICE, 4_123_456));
assert_eq!(rebuilt_host, RawInode::new(PROC_DEVICE, 4_987_654));
assert_eq!(before, rebuilt);
assert_eq!(before, name("/3/fd/0"));
assert_eq!(before.unwrap().tasks, vec![3]);
assert_ne!(listing.entry_inode(b"1", 4_123_456).1, name("/3/fd/0"));
}
#[test]
fn other_directories_keep_host_keys() {
let device = libc::makedev(8, 1);
let listing = DirectoryInodes::new(device, None);
assert_eq!(
listing.entry_inode(b"a", 77),
(RawInode::new(device, 77), None)
);
assert_ne!(listing.entry_inode(b"a", 77), listing.entry_inode(b"a", 78));
}
#[test]
fn dot_entries_name_the_directory_and_its_parent() {
let listing = proc_fd_listing();
assert_eq!(listing.entry_inode(b".", 9).1, name("/3/fd"));
assert_eq!(listing.entry_inode(b"..", 9).1, name("/3"));
let root =
DirectoryInodes::new(PROC_DEVICE, Some(ProcfsDirectory::new(PathBuf::from("/"))));
assert_eq!(root.entry_inode(b".", PROC_ROOT_INO).1, name("/"));
assert_eq!(root.entry_inode(b"..", PROC_ROOT_INO).1, name("/"));
assert_eq!(root.entry_inode(b"self", 4_026_531_841).1, name("/self"));
assert_eq!(
root.entry_inode(b"self", 4_026_531_841).1.unwrap().tasks,
Vec::<i32>::new()
);
}
#[test]
fn path_keys_cannot_equal_procfs_inodes() {
let paths = ["/", "/1", "/3/fd/0", "/sys/kernel/pid_max"];
let mut keys: Vec<RawInode> = paths
.iter()
.map(|path| path_inode(PROC_DEVICE, Path::new(path)))
.collect();
keys.push(with_incarnation(keys[1], 1, 2));
keys.push(with_incarnation(keys[1], 1, 3));
for key in &keys {
assert_eq!(key.dev, PROC_DEVICE);
assert!(key.ino > u64::from(u32::MAX), "{key:?}");
}
for (index, key) in keys.iter().enumerate() {
assert!(!keys[index + 1..].contains(key), "{key:?}");
}
let other_mount = libc::makedev(0, 24);
assert_ne!(
path_inode(PROC_DEVICE, Path::new("/1")),
path_inode(other_mount, Path::new("/1"))
);
}
#[test]
fn a_path_names_its_process_and_thread() {
let tasks = |path: &str| tasks_named(Path::new(path));
assert_eq!(tasks("/3"), vec![3]);
assert_eq!(tasks("/3/fd/0"), vec![3]);
assert_eq!(tasks("/3/task/7/fd/0"), vec![3, 7]);
assert_eq!(tasks("/3/task"), vec![3]);
assert_eq!(tasks("/3/task/self"), vec![3]);
for path in [
"/",
"/self",
"/sys/kernel/pid_max",
"/0",
"/-3",
"/+3",
"/3 (deleted)",
] {
assert_eq!(tasks(path), Vec::<i32>::new(), "{path}");
}
}
#[test]
fn only_kvms_synthetic_procfs_device_is_proved_by_its_stat_fields() {
let synthetic = libc::makedev(0, 0xff01);
assert!(is_backend_procfs_device(
&BackendCapabilities::KVM,
synthetic,
4096
));
assert!(!is_backend_procfs_device(
&BackendCapabilities::KVM,
synthetic,
1024
));
assert!(!is_backend_procfs_device(
&BackendCapabilities::KVM,
PROC_DEVICE,
1024
));
assert!(!is_backend_procfs_device(
&BackendCapabilities::PTRACE,
synthetic,
4096
));
assert!(!is_backend_procfs_device(
&BackendCapabilities::PTRACE,
PROC_DEVICE,
1024
));
assert!(!is_backend_procfs_device(
&BackendCapabilities::DBT,
PROC_DEVICE,
1024
));
}
#[test]
fn only_a_backend_that_names_no_entries_but_shares_procfs_keeps_its_signature() {
assert!(unprovable_procfs_signature(
&BackendCapabilities::DBT,
Some(4242),
PROC_DEVICE,
1024
));
assert!(!unprovable_procfs_signature(
&BackendCapabilities::DBT,
Some(4242),
PROC_DEVICE,
4096
));
assert!(!unprovable_procfs_signature(
&BackendCapabilities::DBT,
Some(4242),
libc::makedev(8, 1),
1024
));
assert!(!unprovable_procfs_signature(
&BackendCapabilities::PTRACE,
None,
PROC_DEVICE,
1024
));
assert!(!unprovable_procfs_signature(
&BackendCapabilities::KVM,
None,
PROC_DEVICE,
1024
));
}
#[test]
fn only_anonymous_devices_with_1024_byte_blocks_may_be_procfs() {
assert!(may_be_procfs(PROC_DEVICE, 1024));
assert!(!may_be_procfs(libc::makedev(8, 1), 1024));
assert!(!may_be_procfs(PROC_DEVICE, 4096));
}
const MOUNTINFO: &[u8] = b"\
22 1 0:21 / /proc rw,nosuid,nodev,noexec,relatime shared:12 - proc proc rw
23 1 0:22 / /dev/pts rw,nosuid,noexec,relatime shared:2 - devpts devpts rw,mode=620
24 1 0:23 / /mnt/a\\040b rw,relatime - fuse.squashfuse_ll squashfuse_ll rw,user_id=0
25 22 0:24 / /proc/sys/fs/binfmt_misc rw,relatime shared:7 - autofs systemd-1 rw
26 1 0:25 / /srv/proc rw - proc proc rw
27 1 0:21 /sys /srv/my\\040sys rw master:3 - proc proc rw
";
#[test]
fn procfs_entries_are_named_only_where_thread_ids_are_host_ids() {
assert!(guest_tids_name_host_tasks(
&BackendCapabilities::PTRACE,
None
));
assert!(guest_tids_name_host_tasks(
&BackendCapabilities::SABRE,
None
));
assert!(guest_tids_name_host_tasks(
&BackendCapabilities::LITEINST_IN_GUEST,
None
));
assert!(!guest_tids_name_host_tasks(&BackendCapabilities::KVM, None));
assert!(!guest_tids_name_host_tasks(
&BackendCapabilities::DBT,
Some(4_321)
));
assert!(!guest_tids_name_host_tasks(
&BackendCapabilities::PTRACE,
Some(4_321)
));
for backend in [
BackendCapabilities::PTRACE,
BackendCapabilities::LITEINST_IN_GUEST,
BackendCapabilities::SABRE,
BackendCapabilities::DBT,
] {
assert!(tool_can_name_guest_descriptors(&backend));
}
assert!(!tool_can_name_guest_descriptors(&BackendCapabilities::KVM));
}
#[test]
fn an_entry_of_a_task_that_has_exited_is_not_named() {
let (sender, receiver) = std::sync::mpsc::channel();
let (finish, finished) = std::sync::mpsc::channel::<()>();
let thread = std::thread::spawn(move || {
sender.send(unsafe { libc::gettid() }).unwrap();
finished.recv().unwrap();
});
let tid = receiver.recv().unwrap();
let fds = File::open(format!("/proc/self/task/{tid}/fd")).unwrap();
let metadata = fds.metadata().unwrap();
let link = PathBuf::from(format!("/proc/self/fd/{}", fds.as_raw_fd()));
let inspect = || inspect_link(&link, metadata.dev(), metadata.ino()).map(|(path, _)| path);
let expected = format!("/proc/{}/task/{tid}/fd", std::process::id());
assert_eq!(inspect(), Ok(PathBuf::from(expected)));
finish.send(()).unwrap();
thread.join().unwrap();
let start = std::time::Instant::now();
let refused = loop {
match inspect() {
Err(reason) => break reason,
Ok(path) => assert!(
start.elapsed() < std::time::Duration::from_secs(10),
"{} still names {} after its task exited",
link.display(),
path.display()
),
}
std::thread::sleep(std::time::Duration::from_millis(1));
};
assert!(
refused.starts_with("cannot stat ")
|| refused.ends_with("an entry of a task that has exited"),
"{refused}"
);
}
#[test]
fn a_path_linux_marks_deleted_names_nothing() {
let link = Path::new("/proc/self/fd/3");
let live = PathBuf::from("/proc/12/task/13/fd");
assert_eq!(refuse_deleted(link, live.clone()), Ok(live));
let deleted = PathBuf::from("/proc/12/task/13/fd (deleted)");
assert_eq!(
refuse_deleted(link, deleted),
Err(
"/proc/self/fd/3 leads to /proc/12/task/13/fd (deleted), an entry of a task \
that has exited"
.to_string()
)
);
}
#[test]
fn a_procfs_object_is_told_by_its_filesystem_type() {
let stat = File::open("/proc/self/stat").unwrap();
let null = File::open("/dev/null").unwrap();
let link = |file: &File| PathBuf::from(format!("/proc/self/fd/{}", file.as_raw_fd()));
let (stat_metadata, null_metadata) = (stat.metadata().unwrap(), null.metadata().unwrap());
assert_eq!(
is_on_procfs(&link(&stat), stat_metadata.dev(), stat_metadata.ino()),
Ok(true)
);
assert_eq!(
is_on_procfs(&link(&null), null_metadata.dev(), null_metadata.ino()),
Ok(false)
);
let other = is_on_procfs(&link(&null), stat_metadata.dev(), stat_metadata.ino());
assert!(
other
.as_ref()
.is_err_and(|reason| reason.ends_with("is not the object the guest saw")),
"{other:?}"
);
}
#[test]
fn mountinfo_names_procfs_mounts_by_type() {
let mounts = |minor| procfs_mounts_in(MOUNTINFO, libc::makedev(0, minor), Path::new("/"));
let mount = |id: u64, root: &str, mount_point: &str| ProcfsMount {
id,
root: PathBuf::from(root),
mount_point: PathBuf::from(mount_point),
};
assert_eq!(
mounts(21),
vec![mount(22, "/", "/proc"), mount(27, "/sys", "/srv/my sys")]
);
assert_eq!(
mounts(25),
vec![mount(26, "/", "/srv/proc")],
"a mount with no optional fields"
);
for minor in [22, 23, 24, 26] {
assert!(mounts(minor).is_empty(), "0:{minor}");
}
assert!(procfs_mounts_in(MOUNTINFO, libc::makedev(8, 21), Path::new("/")).is_empty());
}
#[test]
fn mount_points_are_read_in_the_frame_of_the_guests_root() {
let mounts = procfs_mounts_in(MOUNTINFO, libc::makedev(0, 21), Path::new("/box"));
let points: Vec<&Path> = mounts
.iter()
.map(|mount| mount.mount_point.as_path())
.collect();
assert_eq!(
points,
[Path::new("/box/proc"), Path::new("/box/srv/my sys")]
);
}
fn only_root(point: &'static str, id: u64) -> impl Fn(&Path) -> io::Result<Option<u64>> + Copy {
move |path| Ok((path == Path::new(point)).then_some(id))
}
fn named_in(mounts: &Arc<[ProcfsMount]>, mount_id: u64, canonical: &str) -> Option<PathBuf> {
path_within(
mounts,
mount_id,
Path::new(canonical),
|| Ok(Some(mounts.clone())),
|path| {
let mount = mounts.iter().find(|mount| mount.mount_point == path);
Ok(mount.map(|mount| mount.id))
},
)
.ok()
}
#[test]
fn a_path_within_procfs_does_not_depend_on_the_mount() {
let mounts: Arc<[ProcfsMount]> =
procfs_mounts_in(MOUNTINFO, libc::makedev(0, 21), Path::new("/")).into();
let within = |id: u64, path: &str| named_in(&mounts, id, path);
let named = |path: &str| Some(PathBuf::from(path));
assert_eq!(within(22, "/proc"), named("/"));
assert_eq!(within(22, "/proc/3/fd/0"), named("/3/fd/0"));
assert_eq!(within(27, "/srv/my sys/kernel"), named("/sys/kernel"));
assert_eq!(within(22, "/proc/sys/kernel"), named("/sys/kernel"));
assert_eq!(within(22, "/procfs/3"), None);
assert_eq!(within(22, "/elsewhere/3"), None);
assert_eq!(within(27, "/proc/3"), None);
assert_eq!(within(26, "/srv/proc/3"), None);
}
#[test]
fn a_stale_table_names_nothing_rather_than_another_entry() {
let device = libc::makedev(0, 21);
let before: Arc<[ProcfsMount]> = procfs_mounts_in(
b"\
22 1 0:21 / /proc rw - proc proc rw
30 1 0:21 /sys /box/proc rw - proc proc rw
",
device,
Path::new("/"),
)
.into();
let sysctl = Some(PathBuf::from("/sys/kernel"));
assert_eq!(named_in(&before, 30, "/box/proc/kernel"), sysctl);
let after = b"\
30 1 0:21 /sys /proc rw - proc proc rw
";
let own: Arc<[ProcfsMount]> = procfs_mounts_in(after, device, Path::new("/")).into();
let in_box = only_root("/proc", 30);
let kernel = Path::new("/proc/kernel");
assert_eq!(
path_within(&before, 30, kernel, || Ok(Some(before.clone())), in_box),
Err("/proc/kernel was reached through mount 30, which the guest's mount table lists at /box/proc, not above it".into())
);
assert_eq!(
path_within(&before, 30, kernel, || Ok(Some(own.clone())), in_box).ok(),
sysctl
);
let traced: Arc<[ProcfsMount]> = procfs_mounts_in(after, device, Path::new("/box")).into();
assert_eq!(named_in(&traced, 30, "/box/proc/kernel"), sysctl);
}
#[test]
fn a_mount_moved_by_a_rename_is_found_where_it_moved() {
let device = libc::makedev(0, 21);
let table = |mount_point: &str| -> Arc<[ProcfsMount]> {
let line = format!("30 1 0:21 / {mount_point} rw - proc proc rw\n");
procfs_mounts_in(line.as_bytes(), device, Path::new("/")).into()
};
let remembered = table("/a/proc");
let moved = table("/a/proc/moved/proc");
let found = only_root("/a/proc/moved/proc", 30);
let stat = Path::new("/a/proc/moved/proc/1/stat");
let named = Ok(PathBuf::from("/1/stat"));
assert_eq!(
path_within(&remembered, 30, stat, || Ok(Some(moved.clone())), found),
named
);
assert_eq!(
path_within(&moved, 30, stat, || panic!("read again"), found),
named
);
let reached = "/a/proc/moved/proc/1/stat was reached through mount 30, and /a/proc";
assert_eq!(
path_within(
&remembered,
30,
stat,
|| Ok(Some(remembered.clone())),
found
),
Err(format!(
"{reached}, where the guest's mount table lists it, is the root of no mount"
))
);
let covered = only_root("/a/proc", 31);
assert_eq!(
path_within(
&remembered,
30,
stat,
|| Ok(Some(remembered.clone())),
covered
),
Err(format!(
"{reached}, where the guest's mount table lists it, is the root of mount 31"
))
);
let unknown = |_: &Path| Err(io::Error::other("no statx"));
assert_eq!(
path_within(
&remembered,
30,
stat,
|| Ok(Some(remembered.clone())),
unknown
),
Err(
"/a/proc/moved/proc/1/stat was reached through mount 30, and cannot tell whether /a/proc, where the guest's mount table lists it, holds it: no statx"
.to_string()
)
);
assert_eq!(
path_within(&remembered, 30, stat, || Ok(None), found),
Err("/a/proc/moved/proc/1/stat was reached through mount 30, and the guest's mount table, read again, lists no procfs mount of its device".into())
);
assert_eq!(
path_within(&remembered, 30, stat, || Err(io::Error::other("gone")), found),
Err("/a/proc/moved/proc/1/stat was reached through mount 30, and the guest's mount table cannot be read again: gone".into())
);
}
#[test]
fn a_mount_point_read_in_another_frame_names_nothing() {
let table: Arc<[ProcfsMount]> = procfs_mounts_in(
b"22 1 0:21 / /sys/sys rw - proc proc rw\n",
libc::makedev(0, 21),
Path::new("/"),
)
.into();
let tracer = only_root("/sys", 22);
assert_eq!(
path_within(
&table,
22,
Path::new("/sys/sys/kernel/hostname"),
|| Ok(Some(table.clone())),
tracer
),
Err("/sys/sys/kernel/hostname was reached through mount 22, and /sys/sys, where the guest's mount table lists it, is the root of no mount".into())
);
}
#[test]
fn an_open_ran_unless_it_reports_a_restart() {
let own = libc::SYS_openat;
for fd in [0, 3, own - 1, own, own + 1] {
assert_eq!(read_open(Ok(fd)), Injected::Ran(fd as RawFd));
}
assert_eq!(
read_open(Ok(1 << 40)),
Injected::Failed(format!(
"openat returned {}, which is no descriptor",
1i64 << 40
))
);
for errno in [
Errno::EINTR,
Errno::ERESTARTSYS,
Errno::ERESTARTNOINTR,
Errno::ERESTARTNOHAND,
Errno::ERESTART_RESTARTBLOCK,
] {
assert_eq!(read_open(Err(errno)), Injected::NotRun(errno.to_string()));
}
assert_eq!(
read_open(Err(Errno::EPERM)),
Injected::Failed(format!(
"cannot open the guest's path again: {}",
Errno::EPERM
))
);
}
#[test]
fn only_a_close_returning_0_ran() {
assert_eq!(read_close(Ok(0)), Injected::Ran(()));
assert_eq!(
read_close(Ok(libc::SYS_close)),
Injected::Failed(format!(
"close of the guest's O_PATH descriptor returned {}, which close never returns",
libc::SYS_close
))
);
assert_eq!(
read_close(Ok(5)),
Injected::Failed(
"close of the guest's O_PATH descriptor returned 5, which close never returns"
.into()
)
);
assert_eq!(
read_close(Err(Errno::ERESTARTSYS)),
Injected::NotRun(Errno::ERESTARTSYS.to_string())
);
for (errno, name) in [(Errno::EPERM, "EPERM"), (Errno::EINTR, "EINTR")] {
assert_eq!(
read_close(Err(errno)),
Injected::Failed(format!(
"close of the guest's O_PATH descriptor returned {name}"
))
);
}
}
#[test]
fn this_process_reads_its_own_procfs_entries() {
let pid = std::process::id() as i32;
let proc = std::fs::metadata("/proc").unwrap();
let mounts = procfs_mounts(pid, proc.dev(), false).unwrap().unwrap();
assert!(
procfs_mounts(pid, proc.dev(), false).unwrap().is_some(),
"once remembered"
);
assert!(
procfs_mounts(pid, proc.dev(), true).unwrap().is_some(),
"read again"
);
assert!(
procfs_mounts(pid, std::fs::metadata("/").unwrap().dev(), false)
.unwrap()
.is_none()
);
assert!(
procfs_mounts(-1, proc.dev(), false).is_err(),
"no such thread"
);
let stat = std::fs::metadata(format!("/proc/{pid}/stat")).unwrap();
let file = File::open("/proc/self/stat").unwrap();
let link = PathBuf::from(format!("/proc/{pid}/fd/{}", file.as_raw_fd()));
let (canonical, mount_id) = inspect_link(&link, stat.dev(), stat.ino()).unwrap();
assert_eq!(
path_within(
&mounts,
mount_id,
&canonical,
|| panic!("read again"),
mount_root
),
Ok(PathBuf::from(format!("/{pid}/stat")))
);
let mount = mounts.iter().find(|mount| mount.id == mount_id).unwrap();
assert_eq!(mount_root(&mount.mount_point).unwrap(), Some(mount_id));
let directory = mount.mount_point.join(pid.to_string());
assert_eq!(mount_root(&directory).unwrap(), None);
let refused = |path: &Path| mount_root(path).map_err(|error| error.raw_os_error());
assert_eq!(
refused(&mount.mount_point.join("self")),
Err(Some(libc::ELOOP))
);
let through_root = mount
.mount_point
.join(format!("{pid}/root"))
.join(mount.mount_point.strip_prefix("/").unwrap());
let followed = identify(&through_root, false).unwrap();
assert_eq!(
(followed.mount_root, followed.mount_id),
(Some(true), Some(mount_id))
);
assert_eq!(refused(&through_root), Err(Some(libc::ELOOP)));
assert!(inspect_link(&link, stat.dev(), stat.ino() + 1).is_err());
assert!(inspect_link(&link, stat.dev() + 1, stat.ino()).is_err());
let cwd = PathBuf::from(format!("/proc/{pid}/cwd"));
let here = std::fs::metadata(".").unwrap();
assert_eq!(
inspect_link(&cwd, here.dev(), here.ino()).unwrap().0,
std::env::current_dir().unwrap()
);
}
}