//
// Syd: rock-solid application kernel
// src/lookup.rs: Path lookup and canonicalization utilities
//
// Copyright (c) 2023, 2024, 2025, 2026 Ali Polatel <alip@chesswob.org>
// Based in part upon uutils coreutils package's src/lib/features/fs.rs which is:
//   (c) Joseph Crail <jbcrail@gmail.com>
//   (c) Jian Zeng <anonymousknight96 AT gmail.com>
// Tests base based in part upon gnulib packages' tests/test-canonicalize.c which is:
//   (c) Free Software Foundation, Inc.
// {chdir,getdir}_long() functions are based in part upon zsh/Src/compat.c which is:
//   (c) 1992-1997 Paul Falstad
//   SPDX-License-Identifier: ZSH
//
// SPDX-License-Identifier: GPL-3.0

use std::{
    ffi::CStr,
    fmt,
    hash::Hash,
    ops::Deref,
    os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, RawFd},
    sync::LazyLock,
};

use bitflags::bitflags;
use itoa::Integer;
use libc::{c_char, c_uint, AT_EMPTY_PATH, AT_SYMLINK_NOFOLLOW, S_ISVTX, S_IWGRP, S_IWOTH};
use memchr::arch::all::memchr::One;
use nix::{
    errno::Errno,
    fcntl::{OFlag, AT_FDCWD},
    libc::{
        mode_t, DT_BLK, DT_CHR, DT_DIR, DT_FIFO, DT_LNK, DT_REG, DT_SOCK, S_IFBLK, S_IFCHR,
        S_IFDIR, S_IFIFO, S_IFLNK, S_IFMT, S_IFREG, S_IFSOCK,
    },
    sys::stat::{mkdirat, Mode},
    unistd::Pid,
    NixPath,
};
use serde::{ser::SerializeMap, Serialize, Serializer};

use crate::{
    compat::{
        fstatx, getdents64, openat2, statx, FileStatx, OpenHow, ResolveFlag, STATX_INO,
        STATX_MNT_ID, STATX_MNT_ID_UNIQUE, STATX_MODE, STATX_NLINK, STATX_SIZE, STATX_TYPE,
    },
    config::*,
    cookie::safe_openat2,
    error,
    fd::{is_huge_file, SafeOwnedFd, AT_BADFD, NULL_FD, PROC_FD, PROC_FILE, ROOT_FD, ROOT_FILE},
    filemap::FileMap,
    fs::{readlinkat, readlinkfd},
    io::WriteFd,
    magic::ProcMagic,
    path::{dotdot_with_nul, XPath, XPathBuf, PATH_MAX},
    proc::proc_tgid,
    req::UNotifyEventRequest,
    retry::retry_on_eintr,
    sandbox::Sandbox,
};

/// Information to uniquely identify a file.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct FileInfo {
    /// Inode number
    pub ino: u64,
    /// Mount id
    pub mnt: u64,
}

impl FileInfo {
    /// Get information for the current working directory.
    pub fn from_cwd() -> Result<Self, Errno> {
        statx(AT_FDCWD, XPath::empty(), AT_EMPTY_PATH, Self::mask()).map(Self::from_statx)
    }

    /// Get information for a given file descriptor.
    pub fn from_fd<Fd: AsFd>(fd: Fd) -> Result<Self, Errno> {
        fstatx(fd, Self::mask()).map(Self::from_statx)
    }

    /// Convert statx information to FileInfo.
    ///
    /// The statx(2) call must have been called with STATX_INO|STATX_MNT_ID.
    pub fn from_statx(stx: FileStatx) -> Self {
        Self {
            ino: stx.stx_ino,
            mnt: stx.stx_mnt_id,
        }
    }

    /// Return masks for statx(2) required to attain file information.
    pub fn mask() -> c_uint {
        let mut mask = STATX_INO;
        mask |= if *HAVE_STATX_MNT_ID_UNIQUE {
            STATX_MNT_ID_UNIQUE
        } else {
            STATX_MNT_ID
        };
        mask
    }
}

bitflags! {
    /// Path canonicalization options
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub struct FsFlags: u16 {
        /// All components of the path must exist.
        /// This is the default.
        /// Without this option, the behaviour is:
        /// Last component may exist, other components must exist.
        /// Conflicts with the option `MISS_LAST`.
        const MUST_PATH = 1 << 0;
        /// Last component must not exist, other components must exist.
        /// Without this option, the default is:
        /// Last component may exist, other components must exist.
        /// Conflicts with the option `MUST_PATH`.
        const MISS_LAST = 1 << 1;
        /// Do not follow symbolic links for the last path component.
        /// Symbolic links for parent components will be resolved.
        const NO_FOLLOW_LAST = 1 << 2;
        /// Do not permit the path resolution to succeed if any
        /// component of the resolution is not a descendant of the
        /// directory indicated by dirfd. This causes absolute symbolic
        /// links (and absolute values of pathname) to be rejected.
        /// Currently, this flag also disables magic-link resolution
        /// (see below). However, this may change in the future.
        /// Therefore, to ensure that magic links are not resolved, the
        /// caller should explicitly specify RESOLVE_NO_MAGICLINKS.
        const RESOLVE_BENEATH = 1 << 3;
        /// Treat the directory referred to by dirfd as the root
        /// directory while resolving path.  Absolute symbolic
        /// links are interpreted relative to dirfd.  If a
        /// prefix component of path equates to dirfd, then an
        /// immediately following .. component likewise equates
        /// to dirfd (just as /.. is traditionally equivalent to
        /// /).  If path is absolute, it is also interpreted
        /// relative to dirfd.
        ///
        /// The effect of this flag is as though the calling
        /// process had used chroot(2) to (temporarily) modify
        /// its root directory (to the directory referred to by
        /// dirfd).  However, unlike chroot(2) (which changes
        /// the filesystem root permanently for a process),
        /// RESOLVE_IN_ROOT allows a program to efficiently
        /// restrict path resolution on a per-open basis.
        ///
        /// Currently, this flag also disables magic-link
        /// resolution.  However, this may change in the future.
        /// Therefore, to ensure that magic links are not
        /// resolved, the caller should explicitly specify
        /// RESOLVE_NO_MAGICLINKS.
        const RESOLVE_IN_ROOT = 1 << 4;
        /// Do not resolve symbolic links for any of the path components.
        const NO_RESOLVE_PATH = 1 << 5;
        /// Do not resolve proc magic symbolic links.
        const NO_RESOLVE_PROC = 1 << 6;
        /// Do not traverse through mount points.
        const NO_RESOLVE_XDEV = 1 << 7;
        /// Do not traverse through `..` components.
        const NO_RESOLVE_DOTDOT = 1 << 8;
        /// The return file descriptor should be split to (parent, base),
        /// and a fd to the owning directory should be opened instead.
        ///
        /// Default is to use an `O_PATH` file descriptor directly to the file.
        const WANT_BASE = 1 << 9;
    }
}

impl Default for FsFlags {
    fn default() -> Self {
        // All components of the path must exist.
        // This is the default.
        Self::MUST_PATH
    }
}

// Controls how missing components should be handled when canonicalizing a path.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum MissingHandling {
    // Last component may exist, other components must exist.
    Normal,

    // All components must exist.
    // Maps to FsFlags::MUST_PATH.
    Existing,

    // Last component must not exist, other components must exist.
    // Maps to FsFlags::MISS_LAST.
    Missing,
}

impl From<FsFlags> for MissingHandling {
    fn from(flag: FsFlags) -> Self {
        if flag.contains(FsFlags::MUST_PATH) {
            Self::Existing
        } else if flag.contains(FsFlags::MISS_LAST) {
            Self::Missing
        } else {
            Self::Normal
        }
    }
}

impl FsFlags {
    /// Return `Errno` corresponding to magic link restrictions.
    pub fn magic_errno(self) -> Errno {
        if self.intersects(Self::NO_RESOLVE_PATH | Self::NO_RESOLVE_PROC) {
            Errno::ELOOP
        } else if self.intersects(Self::RESOLVE_BENEATH | Self::RESOLVE_IN_ROOT) {
            Errno::EXDEV
        } else {
            Errno::EACCES
        }
    }

    /// Return true if symbolic links in last path component should be followed.
    pub fn follow_last(self) -> bool {
        !self.contains(Self::NO_FOLLOW_LAST)
    }

    /// Return true if symbolic links in path should be resolved.
    pub fn resolve_path(self) -> bool {
        !self.contains(Self::NO_RESOLVE_PATH)
    }

    /// Return true if magic /proc symbolic links should be resolved.
    pub fn resolve_proc(self) -> bool {
        !self.intersects(
            Self::NO_RESOLVE_PATH
                | Self::NO_RESOLVE_PROC
                | Self::RESOLVE_BENEATH
                | Self::RESOLVE_IN_ROOT,
        )
    }

    /// Return true if the path must exist.
    pub fn must_exist(self) -> bool {
        self.contains(Self::MUST_PATH)
    }

    /// Return true if the file may be missing.
    pub fn missing(self) -> bool {
        self.contains(Self::MISS_LAST)
    }

    /// Return true if the base path is requested.
    pub fn want_base(self) -> bool {
        self.contains(Self::WANT_BASE)
    }
}

impl Serialize for FsFlags {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut flags: Vec<&str> = vec![];

        if self.is_empty() {
            return serializer.collect_seq(flags);
        }

        if self.contains(Self::RESOLVE_BENEATH) {
            flags.push("resolve-beneath");
        }
        if self.contains(Self::RESOLVE_IN_ROOT) {
            flags.push("resolve-in-root");
        }
        if self.contains(Self::NO_RESOLVE_PATH) {
            flags.push("resolve-no-symlinks");
        }
        if self.contains(Self::NO_RESOLVE_PROC) {
            flags.push("resolve-no-magiclinks");
        }
        if self.contains(Self::NO_RESOLVE_XDEV) {
            flags.push("resolve-no-xdev");
        }
        if self.contains(Self::NO_RESOLVE_DOTDOT) {
            flags.push("resolve-no-dotdot");
        }
        if self.contains(Self::MUST_PATH) {
            flags.push("must-path");
        }
        if self.contains(Self::MISS_LAST) {
            flags.push("miss-last");
        }
        if self.contains(Self::NO_FOLLOW_LAST) {
            flags.push("no-follow");
        }
        if self.contains(Self::WANT_BASE) {
            flags.push("want-base");
        }

        serializer.collect_seq(flags)
    }
}

/// Represents UNIX file types
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum FileType {
    /// Represents regular file
    Reg,
    /// Represents directory
    Dir,
    /// Represents symbolic link
    ///
    /// Optionally, carries with it the symlink path it originates.
    Lnk,
    /// Represents a procfs magic symbolic link
    MagicLnk(ProcMagic),
    /// Represents a memory file descriptor.
    Mfd,
    /// Represents a secret memory file descriptor.
    MfdSec,
    /// Represents FIFO
    Fifo,
    /// Represents socket
    Sock,
    /// Represents character device
    Chr,
    /// Represents block device
    Blk,
    /// Represents unknown file
    Unk,
}

impl fmt::Display for FileType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Both Lnk and MagicLnk have XPathBuf as saved data,
        // and their Display traits mask control characters.
        let repr = match self {
            Self::Reg => "reg".to_string(),
            Self::Dir => "dir".to_string(),
            Self::Lnk => "lnk".to_string(),
            Self::MagicLnk(magic) => {
                if let Ok(p) = magic.link_path() {
                    format!("mgc@{p}")
                } else {
                    "mgc@?".to_string()
                }
            }
            Self::Mfd => "memfd".to_string(),
            Self::MfdSec => "secretmem".to_string(),
            Self::Fifo => "fifo".to_string(),
            Self::Sock => "sock".to_string(),
            Self::Chr => "chr".to_string(),
            Self::Blk => "blk".to_string(),
            Self::Unk => "unk".to_string(),
        };

        write!(f, "{repr}")
    }
}

impl Serialize for FileType {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl FileType {
    /// Test whether file type represents a regular file.
    pub fn is_file(self) -> bool {
        self == Self::Reg
    }

    /// Test whether file type represents a directory.
    pub fn is_dir(self) -> bool {
        self == Self::Dir
    }

    /// Test whether file type represents a symlink or magic link.
    pub fn is_link(self) -> bool {
        self.is_symlink() || self.is_magic_link()
    }

    /// Test whether file type represents a symlink.
    pub fn is_symlink(self) -> bool {
        self == Self::Lnk
    }

    /// Test whether file type represents a magic link.
    pub fn is_magic_link(self) -> bool {
        matches!(self, Self::MagicLnk(_))
    }

    /// Test whether file type represents a magic directory.
    ///
    /// Used to harden magic link open calls with O_DIRECTORY.
    pub fn is_magic_dir(self) -> bool {
        matches!(self, Self::MagicLnk(magic) if magic.want_dir())
    }

    /// Test whether file type represents a memory fd.
    pub fn is_memory_fd(self) -> bool {
        self == Self::Mfd
    }

    /// Test whether file type represents a secret memory fd.
    pub fn is_secret_memory_fd(self) -> bool {
        self == Self::MfdSec
    }

    /// Test whether file type represents a block device.
    pub fn is_block_device(self) -> bool {
        self == Self::Blk
    }

    /// Test whether file type represents a character device.
    pub fn is_char_device(self) -> bool {
        self == Self::Chr
    }

    /// Test whether file type represents a FIFO.
    pub fn is_fifo(self) -> bool {
        self == Self::Fifo
    }

    /// Test whether file type represents a socket.
    pub fn is_socket(self) -> bool {
        self == Self::Sock
    }

    /// Test whether file type represents an unknown file.
    pub fn is_unknown(self) -> bool {
        self == Self::Unk
    }

    /// Returns the file type as `mode_t`.
    ///
    /// Returns `None` if file type can't be represented as `mode_t`.
    pub fn mode(self) -> Option<mode_t> {
        match self {
            Self::Blk => Some(S_IFBLK),
            Self::Chr => Some(S_IFCHR),
            Self::Dir => Some(S_IFDIR),
            Self::Fifo => Some(S_IFIFO),
            Self::Lnk => Some(S_IFLNK),
            Self::Reg => Some(S_IFREG),
            Self::Sock => Some(S_IFSOCK),
            _ => None,
        }
    }
}

impl From<u8> for FileType {
    fn from(dt_type: u8) -> Self {
        match dt_type {
            DT_DIR => Self::Dir,
            DT_REG => Self::Reg,
            DT_LNK => Self::Lnk,
            DT_CHR => Self::Chr,
            DT_BLK => Self::Blk,
            DT_FIFO => Self::Fifo,
            DT_SOCK => Self::Sock,
            _ => Self::Unk,
        }
    }
}

impl From<mode_t> for FileType {
    fn from(mode: mode_t) -> Self {
        match mode & S_IFMT {
            S_IFBLK => Self::Blk,
            S_IFCHR => Self::Chr,
            S_IFDIR => Self::Dir,
            S_IFIFO => Self::Fifo,
            S_IFLNK => Self::Lnk,
            S_IFREG => Self::Reg,
            S_IFSOCK => Self::Sock,
            _ => Self::Unk,
        }
    }
}

/// Return the file type of the given file descriptor, and optional path.
pub fn file_type<Fd: AsFd>(
    fd: Fd,
    p: Option<&XPath>,
    follow_symlinks: bool,
) -> Result<FileType, Errno> {
    retry_on_eintr(|| {
        if let Some(p) = p {
            statx(
                &fd,
                p,
                if p.is_empty() {
                    AT_EMPTY_PATH
                } else if follow_symlinks {
                    0
                } else {
                    AT_SYMLINK_NOFOLLOW
                },
                STATX_TYPE,
            )
        } else {
            fstatx(&fd, STATX_TYPE)
        }
    })
    .map(|statx| FileType::from(mode_t::from(statx.stx_mode)))
}

/// Create directories recursively using fd-based operations.
pub fn safe_mkdir_all(dirfd: &SafeOwnedFd, path: &XPath) -> Result<SafeOwnedFd, Errno> {
    // Start from the base directory.
    let mut current_fd: Option<SafeOwnedFd> = None;

    // Split path by '/' and process each component.
    for component in path.as_bytes().split(|&b| b == b'/') {
        // Construct a XPath from component bytes.
        let component = XPath::from_bytes(component);

        // Skip empty and "." components.
        if component.is_empty() || component.is_dot() {
            continue;
        }

        // Reject ".." to prevent escapes.
        if component.is_equal(b"..") {
            return Err(Errno::EINVAL);
        }

        let base_fd = current_fd
            .as_ref()
            .map_or_else(|| dirfd.as_fd(), |fd| fd.as_fd());

        // Try to create the directory. EEXIST is OK.
        match retry_on_eintr(|| mkdirat(base_fd, component, Mode::S_IRWXU)) {
            Ok(()) | Err(Errno::EEXIST) => {}
            Err(errno) => return Err(errno),
        }

        // Open the directory with O_DIRECTORY|O_NOFOLLOW to prevent symlink attacks.
        // safe_open_path adds RESOLVE_BENEATH|RESOLVE_NO_SYMLINKS|RESOLVE_NO_MAGICLINKS.
        // We additionally request RESOLVE_NO_XDEV to prevent mount-over attacks.
        current_fd = Some(safe_open_path(
            base_fd,
            component,
            OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW,
            ResolveFlag::RESOLVE_NO_XDEV,
        )?);
    }

    // Return the fd of the final directory. If no components were processed
    // (empty or dot-only path), return a dup of the base directory fd.
    match current_fd {
        Some(fd) => Ok(fd),
        None => dirfd.try_clone(),
    }
}

/// Ensure the file we open is a regular file.
/// Ensure we do not block on a fifo if the file is one.
/// Returns (SafeOwnedFd, FileStatx) on success, Errno on failure.
#[inline(always)]
pub fn safe_open_file<Fd: AsFd, P: NixPath + ?Sized>(
    fd: Fd,
    base: &P,
) -> Result<(SafeOwnedFd, FileStatx), Errno> {
    // Open the file with O_PATH.
    let fd = safe_open_path(fd, base, OFlag::O_NOFOLLOW, ResolveFlag::empty())?;

    // Check the file type and bail if it's not a regular file.
    let statx = retry_on_eintr(|| fstatx(&fd, STATX_INO | STATX_TYPE | STATX_SIZE))?;
    let ftype = FileType::from(mode_t::from(statx.stx_mode));
    if !ftype.is_file() {
        return Err(Errno::ENOEXEC);
    }

    // Reopen the file safely via /proc/thread-self/fd.
    // We cannot use RESOLVE_NO_{MAGIC,SYM}LINKS or O_NOFOLLOW here.
    let pfd = XPathBuf::from_self_fd(fd.as_raw_fd())?;

    let flags = OFlag::O_RDONLY | OFlag::O_NOCTTY | OFlag::O_CLOEXEC;
    let fd = safe_open_msym(PROC_FILE(), &pfd, flags, ResolveFlag::empty())?;

    // Return SafeOwnedFd and FileStatx.
    Ok((fd, statx))
}

/// Ensure the file we open is a regular file.
/// Ensure we do not block on a fifo if the file is one.
/// Returns (SafeOwnedFd, FileStatx) on success, Errno on failure.
/// This is identical to `safe_open_file` except it may be called before `proc_init`.
pub fn safe_open_file2<Fd: AsFd, P: NixPath + ?Sized>(
    fd: Fd,
    base: &P,
) -> Result<(SafeOwnedFd, FileStatx), Errno> {
    // Open the file with O_PATH.
    // Do not resolve symbolic links.
    let how = OpenHow::new()
        .flags(OFlag::O_PATH | OFlag::O_CLOEXEC | OFlag::O_NOFOLLOW)
        .resolve(ResolveFlag::RESOLVE_NO_MAGICLINKS | ResolveFlag::RESOLVE_NO_SYMLINKS);
    #[expect(clippy::disallowed_methods)]
    let fd = retry_on_eintr(|| openat2(&fd, base, how))?;

    // Check the file type and bail if it's not a regular file.
    let statx = retry_on_eintr(|| fstatx(&fd, STATX_INO | STATX_TYPE | STATX_SIZE))?;
    let ftype = FileType::from(mode_t::from(statx.stx_mode));
    if !ftype.is_file() {
        return Err(Errno::EBADFD);
    }

    // Reopen the file safely via /proc/thread-self/fd.
    // Note, we cannot use RESOLVE_NO_{MAGIC,SYM}LINKS or O_NOFOLLOW here.
    let how = OpenHow::new().flags(OFlag::O_RDONLY | OFlag::O_CLOEXEC | OFlag::O_NOCTTY);
    let mut pfd = XPathBuf::from("/proc/thread-self/fd");
    pfd.push_fd(fd.as_raw_fd());

    #[expect(clippy::disallowed_methods)]
    let fd = retry_on_eintr(|| openat2(AT_BADFD, &pfd, how))?;

    // Return SafeOwnedFd and FileStatx.
    Ok((fd, statx))
}

/// Safely open and copy the given pathname into the file,
/// if the pathname exists. Returns the number of bytes copied.
pub fn safe_copy_if_exists<F, P>(dst: &mut F, src: &P) -> Result<u64, Errno>
where
    F: WriteFd,
    P: NixPath + ?Sized,
{
    let how = safe_open_how(OFlag::O_PATH, ResolveFlag::empty());

    // This function is only called before sandboxing.
    #[expect(clippy::disallowed_methods)]
    let fd = if let Ok(fd) = retry_on_eintr(|| openat2(AT_FDCWD, src, how)) {
        fd
    } else {
        return Ok(0);
    };

    // Check the file type and bail if it's not a regular file.
    let statx = retry_on_eintr(|| fstatx(&fd, STATX_TYPE))?;
    let ftype = FileType::from(mode_t::from(statx.stx_mode));
    if !ftype.is_file() {
        return Err(Errno::ENOEXEC);
    }

    // Reopen the file safely via /proc/thread-self/fd.
    // Note, we cannot use RESOLVE_NO_{MAGIC,SYM}LINKS or O_NOFOLLOW here.
    let mut pfd = XPathBuf::from("/proc/thread-self");
    pfd.push(b"fd");
    pfd.push_fd(fd.as_raw_fd());

    let how = safe_open_how(OFlag::O_RDONLY | OFlag::O_NOCTTY, ResolveFlag::empty());

    // This function is only called before sandboxing.
    #[expect(clippy::disallowed_methods)]
    let mut src = if let Ok(src) = retry_on_eintr(|| openat2(AT_FDCWD, &pfd, how)) {
        src
    } else {
        return Ok(0);
    };

    crate::io::copy(&mut src, dst)
}

/// Return a safe OpenHow structure.
pub fn safe_open_how(flags: OFlag, rflags: ResolveFlag) -> OpenHow {
    // Note we leave the caller to handle O_NOCTTY,
    // because its use is invalid with O_PATH.
    let mode = if flags.contains(OFlag::O_CREAT) || flags.contains(OFlag::O_TMPFILE) {
        Mode::from_bits_truncate(0o600)
    } else {
        Mode::empty()
    };
    OpenHow::new()
        .flags(flags | OFlag::O_CLOEXEC | OFlag::O_NOFOLLOW)
        .mode(mode)
        .resolve(
            rflags
                | ResolveFlag::RESOLVE_NO_MAGICLINKS
                | ResolveFlag::RESOLVE_NO_SYMLINKS
                | ResolveFlag::RESOLVE_BENEATH,
        )
}

/// Return a safe OpenHow structure without RESOLVE_BENEATH,
/// which allows for absolute pathnames.
pub fn safe_open_how_abs(flags: OFlag, rflags: ResolveFlag) -> OpenHow {
    // Note we leave the caller to handle O_NOCTTY,
    // because its use is invalid with O_PATH.
    let mode = if flags.contains(OFlag::O_CREAT) || flags.contains(OFlag::O_TMPFILE) {
        Mode::from_bits_truncate(0o600)
    } else {
        Mode::empty()
    };
    OpenHow::new()
        .flags(flags | OFlag::O_CLOEXEC | OFlag::O_NOFOLLOW)
        .mode(mode)
        .resolve(rflags | ResolveFlag::RESOLVE_NO_MAGICLINKS | ResolveFlag::RESOLVE_NO_SYMLINKS)
}

/// Return a safe OpenHow structure without O_NOFOLLOW,
/// RESOLVE_NO_MAGICLINKS and RESOLVE_NO_SYMLINKS.
pub fn safe_open_how_msym(flags: OFlag, rflags: ResolveFlag) -> OpenHow {
    // Note we leave the caller to handle O_NOCTTY,
    // because its use is invalid with O_PATH.
    OpenHow::new()
        .flags(flags | OFlag::O_CLOEXEC)
        .resolve(rflags)
}

/// Open a path safely using O_PATH and return a SafeOwnedFd.
#[inline(always)]
pub fn safe_open_path<Fd: AsFd, P: NixPath + ?Sized>(
    fd: Fd,
    base: &P,
    flags: OFlag,
    rflags: ResolveFlag,
) -> Result<SafeOwnedFd, Errno> {
    safe_open(fd, base, OFlag::O_PATH | flags, rflags)
}

/// Open a path safely and return an SafeOwnedFd.
#[inline(always)]
pub fn safe_open<Fd: AsFd, P: NixPath + ?Sized>(
    fd: Fd,
    base: &P,
    flags: OFlag,
    rflags: ResolveFlag,
) -> Result<SafeOwnedFd, Errno> {
    let how = safe_open_how(flags, rflags);
    base.with_nix_path(|cstr| {
        let xp = XPath::from_bytes(cstr.to_bytes());
        let (fd, base) = if xp.is_relative() {
            (fd.as_fd(), cstr)
        } else if xp.is_root() {
            unreachable!("BUG: Attempt to reopen /");
        } else {
            // Skip initial slashes, and open wrt. the static root-fd.
            // This ensures this function cannot be misused to escape rootfs.
            let n = xp
                .as_bytes()
                .iter()
                .position(|&b| b != b'/')
                .ok_or(Errno::ENOENT)?;
            let xp = &cstr.to_bytes_with_nul()[n..];
            // SAFETY: `with_nix_path` ensures:
            // 1. `xp` is null terminated.
            // 2. `xp` does not contain any interior null bytes.
            let cstr = unsafe { CStr::from_bytes_with_nul_unchecked(xp) };
            (ROOT_FILE(), cstr)
        };
        retry_on_eintr(|| safe_openat2(fd, base, how))
    })?
}

/// Open an absolute path safely using O_PATH and return a SafeOwnedFd.
#[inline(always)]
pub fn safe_open_path_abs<P: NixPath + ?Sized>(
    path: &P,
    flags: OFlag,
    rflags: ResolveFlag,
) -> Result<SafeOwnedFd, Errno> {
    safe_open_abs(path, OFlag::O_PATH | flags, rflags)
}

/// Open an absolute path safely and return a SafeOwnedFd.
#[inline(always)]
pub fn safe_open_abs<P: NixPath + ?Sized>(
    path: &P,
    flags: OFlag,
    rflags: ResolveFlag,
) -> Result<SafeOwnedFd, Errno> {
    let how = safe_open_how_abs(flags, rflags);
    path.with_nix_path(|cstr| {
        // Ensure path is an absolute path.
        let xp = XPath::from_bytes(cstr.to_bytes());
        if xp.is_relative() {
            return Err(Errno::EINVAL);
        }

        #[expect(clippy::disallowed_methods)]
        retry_on_eintr(|| openat2(AT_FDCWD, cstr, how))
    })?
}

/// Open a magic symlink safely using O_PATH and return a SafeOwnedFd.
#[inline(always)]
pub fn safe_open_path_msym<Fd: AsFd, P: NixPath + ?Sized>(
    fd: Fd,
    base: &P,
    flags: OFlag,
    rflags: ResolveFlag,
) -> Result<SafeOwnedFd, Errno> {
    safe_open_msym(fd, base, OFlag::O_PATH | flags, rflags)
}

/// Open a magic symlink safely and return a SafeOwnedFd.
#[inline(always)]
pub fn safe_open_msym<Fd: AsFd, P: NixPath + ?Sized>(
    fd: Fd,
    base: &P,
    flags: OFlag,
    rflags: ResolveFlag,
) -> Result<SafeOwnedFd, Errno> {
    let how = safe_open_how_msym(flags, rflags);

    base.with_nix_path(|cstr| {
        let xp = XPath::from_bytes(cstr.to_bytes());
        let (fd, base) = if xp.is_relative() {
            (fd.as_fd(), cstr)
        } else if xp.is_root() {
            unreachable!("BUG: Attempt to reopen /");
        } else {
            // Skip initial slashes, and open wrt. the static root-fd.
            // This ensures this function cannot be misused to escape rootfs.
            let n = xp
                .as_bytes()
                .iter()
                .position(|&b| b != b'/')
                .ok_or(Errno::ENOENT)?;
            let xp = &cstr.to_bytes_with_nul()[n..];
            // SAFETY: `with_nix_path` ensures:
            // 1. `xp` is null terminated.
            // 2. `xp` does not contain any interior null bytes.
            let cstr = unsafe { CStr::from_bytes_with_nul_unchecked(xp) };
            (ROOT_FILE(), cstr)
        };
        retry_on_eintr(|| safe_openat2(fd, base, how))
    })?
}

// We handle {Root,Cur}Dir transparently for efficiency.
// `None` stands for `ParentDir` which allows us to avoid an oversized enum.
#[derive(Debug, Default, PartialEq)]
struct PathComponent(Option<XPathBuf>);

impl PathComponent {
    const PARENT_DIR: Self = Self(None);
}

impl Serialize for PathComponent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        // XPath masks control characters in log output.
        let comp = match self.0.as_ref() {
            Some(p) => p,
            None => XPath::dotdot(),
        };

        serializer.serialize_str(&comp.to_string())
    }
}

// Generates a vector of path components in reverse order:
// - Assumes handling of the initial RootDir is done by the caller.
// - Returns an additional bool to check for trailing slash.
#[expect(clippy::arithmetic_side_effects)]
fn path_components(path: &XPath) -> Result<(Vec<PathComponent>, bool), Errno> {
    let path = path.as_bytes();
    let mut off = 0;
    let mut components = Vec::new();

    for pos in One::new(b'/').iter(path) {
        let len = pos - off;
        match len {
            0 => {}                      // Skip empty component.
            1 if path[off] == b'.' => {} // Skip current directory component.
            2 if path[off] == b'.' && path[off + 1] == b'.' => {
                components.try_reserve(1).or(Err(Errno::ENOMEM))?;
                components.push(PathComponent::PARENT_DIR);
            }
            1..PATH_MAX => {
                let mut component = XPathBuf::new();
                component.try_reserve(pos - off).or(Err(Errno::ENOMEM))?;
                component.extend(&path[off..pos]);
                components.try_reserve(1).or(Err(Errno::ENOMEM))?;
                components.push(PathComponent(Some(component)));
            }
            _ => return Err(Errno::ENAMETOOLONG),
        }
        off = pos + 1; // Move past the '/'.
    }

    // Handle the last component if it's not ended by a slash.
    let slash = if off < path.len() {
        let len = path.len() - off;
        match len {
            // 0 => unreachable!(),
            1 if path[off] == b'.' => {
                // Skip current directory component.
                off >= 1 && path[off - 1] == b'/'
            }
            2 if path[off] == b'.' && path[off + 1] == b'.' => {
                components.try_reserve(1).or(Err(Errno::ENOMEM))?;
                components.push(PathComponent::PARENT_DIR);
                true
            }
            1..PATH_MAX => {
                let mut component = XPathBuf::new();
                component
                    .try_reserve(path.len() - off)
                    .or(Err(Errno::ENOMEM))?;
                component.extend(&path[off..]);
                components.try_reserve(1).or(Err(Errno::ENOMEM))?;
                components.push(PathComponent(Some(component)));
                false
            }
            _ => return Err(Errno::ENAMETOOLONG),
        }
    } else {
        true
    };

    // Reverse so pop() returns components in forward order.
    components.reverse();

    Ok((components, slash))
}

// Adds path components from a symlink target to the component stack in reverse order.
#[expect(clippy::arithmetic_side_effects)]
fn path_components2(path: &XPath, components: &mut Vec<PathComponent>) -> Result<(), Errno> {
    let path = path.as_bytes();
    let mut off = 0;
    let mut new_components = Vec::new();

    for pos in One::new(b'/').iter(path) {
        let len = pos - off;
        match len {
            0 => {}                      // Skip empty components.
            1 if path[off] == b'.' => {} // Skip current directory component.
            2 if path[off] == b'.' && path[off + 1] == b'.' => {
                new_components.try_reserve(1).or(Err(Errno::ENOMEM))?;
                new_components.push(PathComponent::PARENT_DIR);
            }
            1..PATH_MAX => {
                let mut component = XPathBuf::new();
                component.try_reserve(pos - off).or(Err(Errno::ENOMEM))?;
                component.extend(&path[off..pos]);
                new_components.try_reserve(1).or(Err(Errno::ENOMEM))?;
                new_components.push(PathComponent(Some(component)));
            }
            _ => return Err(Errno::ENAMETOOLONG),
        }
        off = pos + 1; // Move past the '/'.
    }

    // Handle the last component if it's not ended by a slash.
    if off < path.len() {
        let len = path.len() - off;
        match len {
            1 if path[off] == b'.' => {} // Skip current directory component.
            2 if path[off] == b'.' && path[off + 1] == b'.' => {
                new_components.try_reserve(1).or(Err(Errno::ENOMEM))?;
                new_components.push(PathComponent::PARENT_DIR);
            }
            1..PATH_MAX => {
                let mut component = XPathBuf::new();
                component
                    .try_reserve(1 + path.len() - off)
                    .or(Err(Errno::ENOMEM))?;
                component.extend(&path[off..]);

                // Preserve trailing slash for directory assertion.
                if path.ends_with(b"/") {
                    component.append_byte(b'/');
                }

                new_components.try_reserve(1).or(Err(Errno::ENOMEM))?;
                new_components.push(PathComponent(Some(component)));
            }
            _ => return Err(Errno::ENAMETOOLONG),
        }
    }

    // Reverse so pop() returns components in forward order.
    new_components.reverse();

    components
        .try_reserve(new_components.len())
        .or(Err(Errno::ENOMEM))?;
    components.extend(new_components);

    Ok(())
}

/// Gets current working directory handling arbitrarily long pathnames.
///
/// Safety: This function does not change the current working directory.
#[expect(clippy::arithmetic_side_effects)]
pub fn getdir_long<Fd: AsFd>(fd: Fd, max_components: usize) -> Result<XPathBuf, Errno> {
    // Record information on current directory.
    let mut pinfo = FileInfo::from_fd(&fd)?;

    let mut dir: Box<dyn AsFd> = Box::new(fd);
    let mut cwd = Vec::new();
    cwd.try_reserve(PATH_MAX).or(Err(Errno::ENOMEM))?;

    let flags = (OFlag::O_RDONLY
        | OFlag::O_CLOEXEC
        | OFlag::O_DIRECTORY
        | OFlag::O_LARGEFILE
        | OFlag::O_NOCTTY
        | OFlag::O_NOFOLLOW)
        .bits();

    let mut i = 0;
    while i < max_components {
        // Move one directory level up.
        let fd = retry_on_eintr(|| {
            // SAFETY: We do confine the string pointer here, so we cannot use nix.
            Errno::result(unsafe {
                libc::openat(
                    dir.as_fd().as_raw_fd(),
                    dotdot_with_nul() as *const c_char,
                    flags,
                    0,
                )
            })
        })
        .map(|fd| {
            // SAFETY: openat(2) returns a valid FD on success.
            unsafe { SafeOwnedFd::from_raw_fd(fd) }
        })?;
        dir = Box::new(fd);

        let info = FileInfo::from_fd(&dir)?;
        if info == pinfo {
            // Current file information and parent are the same:
            // We have reached the root directory.
            let cwd = if !cwd.is_empty() {
                // Re-reverse the path and return.
                cwd.reverse();
                cwd.into()
            } else {
                // LOL: This was rootfs to begin with!
                XPathBuf::from("/")
            };
            return Ok(cwd);
        }

        // There's no guarantee on the order of items returned by getdents64(2).
        // Therefore we must potentially check each element for dot or dotdot,
        // until we actually see one.
        let mut found = false;
        let mut seen_dot = false;
        let mut seen_dotdot = false;
        let new_device = info.mnt != pinfo.mnt;
        'main: loop {
            let mut entries = match getdents64(&dir, DIRENT_BUF_SIZE) {
                Ok(entries) => entries,
                Err(Errno::ECANCELED) => break, // EOF or empty directory
                Err(errno) => return Err(errno),
            };

            for entry in &mut entries {
                if !seen_dot && entry.is_dot() {
                    seen_dot = true;
                    continue;
                }
                if !seen_dotdot && entry.is_dotdot() {
                    seen_dotdot = true;
                    continue;
                }

                if !new_device && entry.ino() != pinfo.ino {
                    // This is not our directory entry, continue.
                    continue;
                }
                if pinfo
                    != statx(
                        &dir,
                        entry.as_xpath(),
                        AT_SYMLINK_NOFOLLOW,
                        FileInfo::mask(),
                    )
                    .map(FileInfo::from_statx)?
                {
                    // This is not our directory entry as verified
                    // by device & inode check.
                    continue;
                }

                // Found our entry!
                found = true;

                // Record parent information.
                pinfo = info;

                // Push the name reversed,
                // we'll re-reverse at the end.
                cwd.try_reserve(entry.name_bytes().len().saturating_add(1))
                    .or(Err(Errno::ENOMEM))?;
                cwd.extend(entry.name_bytes().iter().rev());
                cwd.push(b'/');

                break 'main;
            }
        }

        if found {
            i += 1;
        } else {
            return Err(Errno::ENOENT);
        }
    }

    Err(Errno::ERANGE)
}

/// An enum that may either be a SafeOwnedFd or BorrowedFd.
pub enum MaybeFd {
    /// An `SafeOwnedFd` which will be closed when `MaybeFd` is closed.
    Owned(SafeOwnedFd),
    /// A `RawFd` that will remain open at least as long as `MaybeFd`.
    RawFd(RawFd),
}

impl Clone for MaybeFd {
    fn clone(&self) -> Self {
        match self {
            MaybeFd::Owned(fd) => MaybeFd::RawFd(fd.as_raw_fd()),
            MaybeFd::RawFd(fd) => MaybeFd::RawFd(*fd),
        }
    }
}

impl AsFd for MaybeFd {
    fn as_fd(&self) -> BorrowedFd<'_> {
        match self {
            MaybeFd::Owned(owned) => owned.as_fd(),
            // SAFETY: RawFd is alive as long as MaybeFd.
            MaybeFd::RawFd(fd) => unsafe { BorrowedFd::borrow_raw(*fd) },
        }
    }
}

impl AsRawFd for MaybeFd {
    fn as_raw_fd(&self) -> RawFd {
        match self {
            MaybeFd::Owned(owned) => owned.as_raw_fd(),
            MaybeFd::RawFd(fd) => *fd,
        }
    }
}

impl From<SafeOwnedFd> for MaybeFd {
    fn from(fd: SafeOwnedFd) -> Self {
        MaybeFd::Owned(fd)
    }
}

#[expect(clippy::disallowed_types)]
impl From<std::os::fd::OwnedFd> for MaybeFd {
    fn from(fd: std::os::fd::OwnedFd) -> Self {
        MaybeFd::Owned(fd.into())
    }
}

impl From<RawFd> for MaybeFd {
    fn from(fd: RawFd) -> Self {
        MaybeFd::RawFd(fd)
    }
}

impl Default for MaybeFd {
    fn default() -> Self {
        Self::RawFd(AT_BADFD.as_raw_fd())
    }
}

impl fmt::Debug for MaybeFd {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MaybeFd::Owned(_) => f
                .debug_tuple("SafeOwnedFd")
                .field(&self.as_raw_fd())
                .finish(),
            MaybeFd::RawFd(_) => f.debug_tuple("RawFd").field(&self.as_raw_fd()).finish(),
        }
    }
}

#[derive(Debug, Clone, Default)]
pub(crate) struct FileMapEntry {
    pub(crate) fd: MaybeFd,
    f_type: Option<FileType>,
    f_mode: Option<u16>,
    mnt_id: Option<u64>,
    pub(crate) target: Option<Result<XPathBuf, Errno>>,
    nvisit: u8, // symlink visit count, used for loop detection.
}

impl FileMapEntry {
    pub(crate) fn new(
        fd: MaybeFd,
        f_type: Option<FileType>,
        f_mode: Option<u16>,
        mnt_id: Option<u64>,
        target: Option<Result<XPathBuf, Errno>>,
    ) -> Self {
        Self {
            fd,
            f_type,
            f_mode,
            mnt_id,
            target,
            nvisit: 1,
        }
    }

    pub(crate) fn from_magic_link(
        magic: ProcMagic,
        want_dir: bool,
        request: Option<&UNotifyEventRequest>,
        sandbox: Option<&Sandbox>,
    ) -> Result<(Self, XPathBuf), Errno> {
        // Create path to symlink.
        let remote_sym = magic.rlink_path()?;

        // Open directory using the magic symlink.
        let flags = if want_dir || magic.want_dir() {
            OFlag::O_PATH | OFlag::O_DIRECTORY
        } else {
            OFlag::O_PATH
        };

        let fd = safe_open_msym(ROOT_FILE(), &remote_sym, flags, ResolveFlag::empty())?;
        let sym = XPathBuf::from_self_fd(fd.as_raw_fd())?;

        // Try to readlink(2).
        let (target, is_deleted, is_mfd, is_mfdsec) = match readlinkat(PROC_FILE(), &sym) {
            Ok(mut p) => {
                if p.is_relative() {
                    // /proc/1/fd/42 -> pipe:[4242], socket:[4242]
                    if magic.want_dir() {
                        return Err(Errno::EBADF);
                    }

                    // Magic link points to magic path.
                    // Paths such as [pipe:64], [socket:42] etc.
                    // 1. /proc/$pid/exe
                    // 2. /proc/$pid/fd/$fd
                    (Some(p), false, false, false)
                } else if p.ends_with(b" (deleted)") {
                    if p.starts_with(b"/memfd:") {
                        // Memory file descriptor:
                        // 1. Truncate deleted suffix
                        // 2. Change root slash to !
                        // This is used in access check as !memfd:* or !memfd-hugetlb:*.
                        p.truncate(
                            p.len()
                                .checked_sub(b" (deleted)".len())
                                .ok_or(Errno::EOVERFLOW)?,
                        );
                        p.set(0, b'!');
                        (Some(p), false, true, false)
                    } else if p.is_equal(b"/secretmem (deleted)") {
                        // Secret memory file descriptor:
                        // 1. Truncate deleted suffix
                        // 2. Change root slash to !
                        // This is used in access check as !secretmem.
                        p.truncate(
                            p.len()
                                .checked_sub(b" (deleted)".len())
                                .ok_or(Errno::EOVERFLOW)?,
                        );
                        p.set(0, b'!');
                        (Some(p), false, false, true)
                    } else {
                        // /proc/1/cwd -> /path/to/foo (deleted)
                        //
                        // This may be a deleted file,
                        // or a file whose name funnily
                        // ends with a genuine " (deleted)" string.
                        //
                        // We will statx(2) and check nlink to tell.
                        (Some(p), true, false, false)
                    }
                } else {
                    // Genuine file descriptor that points to a valid directory.
                    (Some(p), false, false, false)
                }
            }
            Err(Errno::ENAMETOOLONG) => (None, false, false, false),
            Err(errno) => return Err(errno),
        };

        // Ensure magic symlink is /proc prefixed.
        let mut sym = XPathBuf::from("/proc");

        // We do not use XPathBuf::push here to append to the path.
        // `remote_sym` is returned by the host Linux kernel, therefore
        // this is safe against path traversals.
        sym.append_byte(b'/');
        sym.append_bytes(remote_sym.as_bytes());

        if let Some(mut target) = target {
            // Prevent hidden path pass-through via magic symlinks.
            // Passing through root is OK.
            if !target.is_root() && target.is_absolute() {
                if let Some(sandbox) = sandbox {
                    sandbox.check_walk(request, magic.pid(), target.deref())?;
                }
            }

            // We managed to successfully readlink.
            //
            // Check for deleted entries.
            if is_deleted {
                let stx = retry_on_eintr(|| fstatx(&fd, STATX_TYPE | STATX_NLINK))?;
                let f_type = FileType::from(mode_t::from(stx.stx_mode));

                if stx.stx_nlink == 0 {
                    // File is deleted, strip the deleted suffix.
                    target.truncate(
                        target
                            .len()
                            .checked_sub(b" (deleted)".len())
                            .ok_or(Errno::EOVERFLOW)?,
                    );
                }

                let entry = Self {
                    fd: fd.into(),
                    f_type: Some(f_type),
                    f_mode: None,
                    mnt_id: None,
                    target: Some(Ok(target)),
                    nvisit: 0,
                };

                return Ok((entry, sym));
            }

            let f_type = if is_mfd {
                // Check for MFD_HUGETLB.
                if is_huge_file(&fd).unwrap_or(false) {
                    target.replace_prefix(MFD_NAME_PREFIX, MFD_HUGETLB_NAME_PREFIX)?;
                }
                Some(FileType::Mfd)
            } else if is_mfdsec {
                Some(FileType::MfdSec)
            } else if magic.want_dir() {
                Some(FileType::Dir)
            } else {
                file_type(&fd, None, false).ok()
            };

            let entry = Self {
                fd: fd.into(),
                f_type,
                f_mode: None,
                mnt_id: None,
                target: Some(Ok(target)),
                nvisit: 0,
            };

            return Ok((entry, sym));
        }

        // Use getdir_long().
        //
        // getdir_long() does not change CWD!
        // We limit maximum dir components to PATH_MAX_COMP so the
        // sandbox process cannot create arbitrarily long directories
        // and crash Syd.
        let target = getdir_long(&fd, PATH_MAX_COMP)?;

        // Prevent hidden path pass-through via magic symlinks.
        // Part 2: Prevent bypass via too-long paths.
        // Passing through root is OK.
        if !target.is_root() && target.is_absolute() {
            if let Some(sandbox) = sandbox {
                sandbox.check_walk(request, magic.pid(), target.deref())?;
            }
        }

        let entry = Self {
            fd: fd.into(),
            f_type: Some(FileType::Dir),
            f_mode: None,
            mnt_id: None,
            target: Some(Ok(target)),
            nvisit: 0,
        };

        Ok((entry, sym))
    }

    // Return the file information of an entry safely.
    // This is currently only used for symlinks post-readlink
    // for symbolic link detection.
    #[expect(clippy::cast_possible_truncation)]
    fn get_mode(&mut self) -> Result<u16, Errno> {
        // Return mode if we've saved it before.
        if let Some(mode) = self.f_mode {
            return Ok(mode);
        }

        // All done, fstat the fd of the entry.
        let stx = retry_on_eintr(|| fstatx(&self.fd, STATX_TYPE | STATX_MODE))?;

        // Keep magic link information for readlink to consume later.
        if !self.is_magic_link() {
            let f_type = FileType::from(mode_t::from(stx.stx_mode));
            self.f_type = Some(f_type);
        }

        // Save and return file mode.
        let mode = stx.stx_mode & !(S_IFMT as u16);
        self.f_mode = Some(mode);

        Ok(mode)
    }

    fn is_magic_link(&self) -> bool {
        matches!(self.f_type, Some(FileType::MagicLnk(_)))
    }
}

// Extension methods for FileMap that require lookup-specific types
impl FileMap {
    fn open(
        &mut self,
        pid: Pid,
        path: &XPath,
        fsflags: FsFlags,
        filetyp: Option<FileType>,
        request: Option<&UNotifyEventRequest>,
        sandbox: Option<&Sandbox>,
    ) -> Result<&mut FileMapEntry, Errno> {
        // Opening a component which is hidden would let us obtain
        // metadata and then resolve through it. Reject early. Passing
        // through root is OK.
        if !path.is_root() {
            if let Some(sandbox) = sandbox {
                sandbox.check_walk(request, pid, path)?;
            }
        }

        let (parent, base) = path.split();
        let (parent_fd, base) = if let Some(parent_entry) = self.get(parent) {
            (parent_entry.fd.as_fd(), base)
        } else {
            let base = XPath::from_bytes(&path.as_bytes()[1..]);
            if !base.is_relative() {
                return Err(Errno::EINVAL);
            }
            // rootfs view must be identical.
            (ROOT_FILE(), base)
        };

        // Force RESOLVE_NO_XDEV as necessary.
        let mut rflags = ResolveFlag::empty();
        if fsflags.contains(FsFlags::NO_RESOLVE_XDEV) {
            rflags.insert(ResolveFlag::RESOLVE_NO_XDEV);
        }
        let fd = safe_open_path(parent_fd, base, OFlag::O_NOFOLLOW, rflags)?;

        // Insert entry and return FD.
        let entry = FileMapEntry::new(fd.into(), filetyp, None, None, None);
        let mut p = XPathBuf::new();
        p.try_reserve(path.len()).or(Err(Errno::ENOMEM))?;
        p.extend(path.as_bytes());

        self.try_insert(p, entry)?;

        self.get_mut(path).ok_or(Errno::ENOENT)
    }

    // Resolve a symbolic link honouring magic proc links.
    fn readlink(
        &mut self,
        path: &XPath,
        pid: Pid,
        fsflags: FsFlags,
        filetyp: Option<FileType>,
        request: Option<&UNotifyEventRequest>,
        sandbox: Option<&Sandbox>,
    ) -> Result<XPathBuf, Errno> {
        if path.is_root() {
            // Root directory isn't a symlink.
            return Err(Errno::EINVAL);
        }

        // Check if we have queried this file before.
        let entry = if let Some(entry) = self.get_mut(path) {
            match entry.target.as_ref() {
                Some(Ok(target)) => {
                    #[expect(clippy::arithmetic_side_effects)]
                    return if entry.nvisit >= MAXSYMLINKS {
                        // Symbolic link loop detected.
                        Err(Errno::ELOOP)
                    } else {
                        entry.nvisit += 1;
                        Ok(target.try_clone()?)
                    };
                }
                Some(Err(errno)) => {
                    // File isn't a symbolic link.
                    return Err(*errno);
                }
                None => entry,
            }
        } else {
            self.open(pid, path, fsflags, filetyp, request, sandbox)?
        };

        // All done, resolve symbolic link.
        let target = match readlinkfd(&entry.fd) {
            Ok(target) => target,
            Err(errno) => {
                // Mark resolve fail in target.
                entry.target = Some(Err(errno));
                return Err(errno);
            }
        };

        let force_no_symlinks = sandbox
            .map(|sb| sb.flags.force_no_symlinks())
            .unwrap_or(false);
        if force_no_symlinks || !fsflags.resolve_path() {
            // RESOLVE_NO_SYMLINKS -> ELOOP
            return Err(Errno::ELOOP);
        }

        if target.is_absolute() && fsflags.contains(FsFlags::RESOLVE_BENEATH) {
            // RESOLVE_BENEATH -> EXDEV
            return Err(Errno::EXDEV);
        }

        // File is known to be a symlink, save target.
        entry.target = Some(Ok(target.try_clone()?));

        // Restrictions a la CONFIG_GRKERNSEC_LINK:
        // Do not follow symbolic links if the parent directory
        // has either one of the following:
        // 1. sticky-bit set.
        // 2. world-writable.
        // 3. group-writable.
        let restrict_symlinks = sandbox
            .map(|sb| !sb.flags.allow_unsafe_symlinks())
            .unwrap_or(false);
        if restrict_symlinks {
            // Open the parent if it is not in the FileMap yet,
            // e.g. after dotdot traversal.
            if self.get(path.parent()).is_none() {
                self.open(pid, path.parent(), fsflags, None, request, sandbox)?;
            }
            let entry = self.get_mut(path.parent()).ok_or(Errno::ELOOP)?;

            let mut err = None;
            let mode: u32 = entry.get_mode()?.into();
            if mode & S_ISVTX != 0 {
                err = Some("parent directory has sticky bit set");
            } else if mode & S_IWOTH != 0 {
                err = Some("parent directory is world writable");
            } else if mode & S_IWGRP != 0 {
                err = Some("parent directory is group writable");
            }

            if let Some(msg) = err {
                error!("ctx": "trusted_symlinks", "path": path,
                    "pid": pid.as_raw(), "fsflags": fsflags,
                    "msg": format!("follow for untrusted symlink blocked: {msg}"),
                    "tip": "fix parent directory permissions or use `trace/allow_unsafe_symlinks:1'");
                return Err(Errno::ELOOP);
            }
        }

        // RESOLVE_NO_MAGICLINKS is handled by ProcMagic::check_link() in canonicalize().
        Ok(target)
    }

    // Return the mount id and file type of a path safely.
    fn get_mnt_id(
        &mut self,
        path: &XPath,
        pid: Pid,
        fsflags: FsFlags,
        filetyp: Option<FileType>,
        request: Option<&UNotifyEventRequest>,
        sandbox: Option<&Sandbox>,
    ) -> Result<u64, Errno> {
        let mut mask = STATX_TYPE;
        mask |= if *HAVE_STATX_MNT_ID_UNIQUE {
            STATX_MNT_ID_UNIQUE
        } else {
            STATX_MNT_ID
        };

        // If we have queried this file before, reuse information.
        let entry = if let Some(entry) = self.get_mut(path) {
            entry
        } else {
            self.open(pid, path, fsflags, filetyp, request, sandbox)?
        };

        // Return mount id if we've saved it before.
        if let Some(mnt_id) = entry.mnt_id {
            return Ok(mnt_id);
        }

        // All done, fstat the fd of the entry.
        let stx = retry_on_eintr(|| fstatx(&entry.fd, mask))?;

        // Keep magic link information for readlink to consume later.
        if !entry.is_magic_link() {
            let f_type = FileType::from(mode_t::from(stx.stx_mode));
            entry.f_type = Some(f_type);
        }

        // Save and return mount id.
        let mnt_id = stx.stx_mnt_id;
        entry.mnt_id = Some(mnt_id);

        Ok(mnt_id)
    }
}

/// A static [`MaybeFd`] wrapping the root file descriptor.
///
/// This is used by [`CanonicalPath::dir`] to return a reference
/// to a [`MaybeFd`] for the root path (`/`) which has no owning
/// directory.
static ROOT_MAYBE_FD: LazyLock<MaybeFd> = LazyLock::new(|| ROOT_FD().into());

/// Return value of `safe_canonicalize`.
#[derive(Debug)]
pub struct CanonicalPath {
    /// Canonical, absolute form of path.
    ///
    /// # Safety
    ///
    /// This must solely used in access check, and must never be passed
    /// as an argument to system calls. Failing to do so will very
    /// likely result in a TOCTTOU vulnerability.
    pub abs: XPathBuf,

    /// The index of the final, base component of the path.
    ///
    /// This is an index into the `abs` element.
    /// This may be 0 in which case `dir` must be used.
    pub base_offset: usize,

    /// An `O_PATH` file descriptor to the owning directory.
    ///
    /// This is `Some` for all paths except the root path, ie `/`,
    /// which has no owning directory.
    pub dir: Option<MaybeFd>,

    /// File type information, if available.
    pub typ: Option<FileType>,
}

impl fmt::Display for CanonicalPath {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // XPathBuf's Display masks control characters in path.
        write!(f, "{}", self.abs())
    }
}

impl Serialize for CanonicalPath {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(Some(4))?;

        map.serialize_entry("abs", &self.abs())?;
        if self.base().is_empty() {
            map.serialize_entry("fd", &self.dir.as_ref().map(|fd| fd.as_raw_fd()))?;
        } else {
            map.serialize_entry("dir", &self.dir.as_ref().map(|fd| fd.as_raw_fd()))?;
            map.serialize_entry("base", self.base())?;
        }
        map.serialize_entry("type", &self.typ)?;

        let owned = matches!(self.dir, Some(MaybeFd::Owned(_)));
        map.serialize_entry("owned", &owned)?;

        map.end()
    }
}

impl CanonicalPath {
    /// Test whether file type represents a regular file.
    pub fn is_file(&self) -> bool {
        self.typ.as_ref().map(|typ| typ.is_file()).unwrap_or(false)
    }

    /// Test whether file type represents a directory.
    pub fn is_dir(&self) -> bool {
        self.typ.as_ref().map(|typ| typ.is_dir()).unwrap_or(false)
    }

    /// Test whether file type represents a symlink.
    pub fn is_symlink(&self) -> bool {
        self.typ
            .as_ref()
            .map(|typ| typ.is_symlink())
            .unwrap_or(false)
    }

    /// Test whether file type represents a magic link.
    pub fn is_magic_link(&self) -> bool {
        self.typ
            .as_ref()
            .map(|typ| typ.is_magic_link())
            .unwrap_or(false)
    }

    /// Test whether file type represents a magic directory.
    ///
    /// TODO: Use to harden magic link calls with O_DIRECTORY.
    pub fn is_magic_dir(&self) -> bool {
        self.typ
            .as_ref()
            .map(|typ| typ.is_magic_dir())
            .unwrap_or(false)
    }

    /// Test whether file type represents a memory fd.
    pub fn is_memory_fd(&self) -> bool {
        self.typ
            .as_ref()
            .map(|typ| typ.is_memory_fd())
            .unwrap_or(false)
    }

    /// Test whether file type represents a block device.
    pub fn is_block_device(&self) -> bool {
        self.typ
            .as_ref()
            .map(|typ| typ.is_block_device())
            .unwrap_or(false)
    }

    /// Test whether file type represents a character device.
    pub fn is_char_device(&self) -> bool {
        self.typ
            .as_ref()
            .map(|typ| typ.is_char_device())
            .unwrap_or(false)
    }

    /// Test whether file type represents a FIFO.
    pub fn is_fifo(&self) -> bool {
        self.typ.as_ref().map(|typ| typ.is_fifo()).unwrap_or(false)
    }

    /// Test whether file type represents a socket.
    pub fn is_socket(&self) -> bool {
        self.typ
            .as_ref()
            .map(|typ| typ.is_socket())
            .unwrap_or(false)
    }

    /// Test whether file type represents an unknown file.
    pub fn is_unknown(&self) -> bool {
        self.typ
            .as_ref()
            .map(|typ| typ.is_unknown())
            .unwrap_or(false)
    }

    /// Returns a reference to the directory fd of path.
    ///
    /// For the root path (`/`) which has no owning directory,
    /// this returns the saved static root fd.
    pub fn dir(&self) -> &MaybeFd {
        match &self.dir {
            Some(ref fd) => fd,
            None => &ROOT_MAYBE_FD,
        }
    }

    /// Returns a reference to the absolute form of path.
    ///
    /// # Safety
    ///
    /// This must solely used in access check, and must never be passed
    /// as an argument to system calls. Failing to do so will very
    /// likely result in a TOCTTOU vulnerability.
    pub fn abs(&self) -> &XPath {
        self.abs.as_ref()
    }

    /// Returns a reference to the final, base, component of path.
    ///
    /// This may be empty in which case `dir` must be used.
    pub fn base(&self) -> &XPath {
        // Construct slice to base using base offset.
        let base = if self.base_offset > 0 {
            XPath::from_bytes(&self.abs.0.as_slice()[self.base_offset..])
        } else {
            XPath::empty()
        };

        // Ensure base doesn't have any slashes except trailing slash.
        match base.find_char(b'/') {
            None => {}
            Some(0) => unreachable!("BUG: `{base}' contains slash, report a bug!"),
            Some(n) if n == base.len().saturating_sub(1) => {}
            Some(_) => unreachable!("BUG: `{base}' contains slash, report a bug!"),
        }

        base
    }

    /// Returns a reference to the parent of path.
    ///
    /// # Safety
    ///
    /// This must solely used in access check, and must never be passed
    /// as an argument to system calls. Failing to do so will very
    /// likely result in a TOCTTOU vulnerability.
    pub fn parent(&self) -> &XPath {
        self.abs().split().0
    }

    /// Consume the `CanonicalPath` and return the absolute path.
    pub fn take(self) -> XPathBuf {
        self.abs
    }

    /// Set the absolute path of the given `CanonicalPath`.
    ///
    /// Panics if `base` is not empty to prevent dangling references.
    pub fn set_abs(&mut self, path: XPathBuf) {
        assert_eq!(
            self.base_offset, 0,
            "BUG: set_abs called with base index {}!",
            self.base_offset
        );
        self.abs = path;
    }

    /// Create a new `CanonicalPath` for (saved) `/`.
    ///
    /// This fd is opened at startup.
    pub fn new_root() -> CanonicalPath {
        Self {
            abs: XPathBuf::from("/"),
            base_offset: 0,
            dir: None,
            typ: Some(FileType::Dir),
        }
    }

    /// Create a new `CanonicalPath` for a magic file.
    ///
    /// Magic files are virtual files that do not have a filesystem part,
    /// and therefore are not subject to TOCTTOU.
    pub fn new_magic(virtual_path: XPathBuf) -> CanonicalPath {
        Self {
            abs: virtual_path,
            base_offset: 0,
            dir: Some(NULL_FD().into()),
            typ: Some(FileType::Chr),
        }
    }

    /// Create a new `CanonicalPath` from a KCOV memfd.
    #[cfg(not(feature = "kcov"))]
    pub fn new_kcov(_tid: Pid) -> Result<CanonicalPath, Errno> {
        Err(Errno::ENOSYS)
    }

    /// Create a new `CanonicalPath` from a KCOV memfd.
    #[cfg(feature = "kcov")]
    pub fn new_kcov(tid: Pid) -> Result<CanonicalPath, Errno> {
        Ok(Self {
            abs: XPathBuf::from("/dev/kcov"),
            base_offset: 0,
            dir: Some(crate::kcov::abi::kcov_open(tid)?),
            typ: Some(FileType::Mfd),
        })
    }

    /// Create a new `CanonicalPath` for a `/dev/null'.
    pub fn new_null() -> CanonicalPath {
        Self {
            abs: XPathBuf::from("/dev/null"),
            base_offset: 0,
            dir: Some(NULL_FD().into()),
            typ: Some(FileType::Chr),
        }
    }

    /// Create a new `CanonicalPath` for the given mask path.
    pub fn new_mask(mask: &XPath, abs: &XPath) -> Result<CanonicalPath, Errno> {
        let base = XPath::from_bytes(&mask.as_bytes()[b"/".len()..]);
        let fd = safe_open_path(ROOT_FILE(), base, OFlag::empty(), ResolveFlag::empty())?;
        let typ = file_type(&fd, None, false)?;

        Ok(Self {
            abs: abs.to_owned(), // Points to the original path.
            base_offset: 0,
            dir: Some(fd.into()), // Points to the mask path.
            typ: Some(typ),
        })
    }

    /// Create a new `CanonicalPath` from an absolute tty name.
    pub fn new_tty(abs: XPathBuf) -> Result<CanonicalPath, Errno> {
        assert!(
            abs.is_dev(),
            "BUG: non /dev path passed to CanonicalPath::new_tty!"
        );

        let base = XPath::from_bytes(&abs.as_bytes()[b"/".len()..]);
        let fd = safe_open_path(ROOT_FILE(), base, OFlag::empty(), ResolveFlag::empty())?;

        Ok(Self {
            abs,
            base_offset: 0,
            dir: Some(fd.into()),
            typ: Some(FileType::Chr),
        })
    }

    /// Create a new `CanonicalPath` from a crypt file descriptor.
    pub fn new_crypt(fd: MaybeFd, abs: XPathBuf) -> CanonicalPath {
        Self {
            abs,
            base_offset: 0,
            dir: Some(fd),
            typ: Some(FileType::Reg),
        }
    }

    /// Create a new `CanonicalPath` from a file descriptor.
    ///
    /// The return value has `abs` field populated and
    /// may be used in access checks.
    pub fn new_fd(mut fd: MaybeFd, pid: Pid) -> Result<CanonicalPath, Errno> {
        // Open CWD using the magic symlink.
        let cwd = fd.as_raw_fd() == libc::AT_FDCWD;
        if cwd {
            let cwd = XPathBuf::from_cwd(pid)?;
            fd = safe_open_path_msym(PROC_FILE(), &cwd, OFlag::O_DIRECTORY, ResolveFlag::empty())?
                .into();
        }
        let sym = XPathBuf::from_self_fd(fd.as_raw_fd())?;

        // Try to readlink(2).
        let (target, is_deleted, is_mfd, is_mfdsec) = match readlinkat(PROC_FILE(), &sym) {
            Ok(mut p) => {
                if p.is_relative() {
                    // /proc/1/fd/42 -> pipe:[4242], socket:[4242]
                    if cwd {
                        // /proc/$pid/cwd: This can never happen.
                        return Err(Errno::ENOTDIR);
                    }

                    // /proc fd symlink doesn't refer to a filesystem path.
                    let mut sym = XPathBuf::from("/proc");
                    sym.push_pid(pid);

                    sym.push(b"fd");
                    sym.push(p.as_bytes());

                    (Some(sym), false, false, false)
                } else if p.ends_with(b" (deleted)") {
                    if p.starts_with(b"/memfd:") {
                        // Memory file descriptor:
                        // 1. Truncate deleted suffix
                        // 2. Change root slash to !
                        // This is used in access check as
                        // !memfd:* or !memfd-hugetlb:*
                        p.truncate(
                            p.len()
                                .checked_sub(b" (deleted)".len())
                                .ok_or(Errno::EOVERFLOW)?,
                        );
                        p.set(0, b'!');
                        (Some(p), false, true, false)
                    } else if p.is_equal(b"/secretmem (deleted)") {
                        // Secret memory file descriptor:
                        // 1. Truncate deleted suffix
                        // 2. Change root slash to !
                        // This is used in access check as !secretmem.
                        p.truncate(
                            p.len()
                                .checked_sub(b" (deleted)".len())
                                .ok_or(Errno::EOVERFLOW)?,
                        );
                        p.set(0, b'!');
                        (Some(p), false, false, true)
                    } else {
                        // /proc/1/cwd -> /path/to/foo (deleted)
                        //
                        // This may be a deleted file,
                        // or a file whose name funnily
                        // ends with a genuine " (deleted)" string.
                        //
                        // We will statx(2) and check nlink to tell.
                        (Some(p), true, false, false)
                    }
                } else {
                    // Genuine file descriptor that points to a valid directory.
                    (Some(p), false, false, false)
                }
            }
            Err(Errno::ENOENT) => return Err(Errno::EBADF),
            Err(Errno::ENAMETOOLONG) => (None, false, false, false),
            Err(errno) => return Err(errno),
        };

        if let Some(mut path) = target {
            // We managed to successfully readlink.
            //
            // Check for deleted entries.
            if is_deleted {
                // Check if path is really deleted.
                let stx = retry_on_eintr(|| fstatx(&fd, STATX_TYPE | STATX_NLINK))?;
                let f_type = FileType::from(mode_t::from(stx.stx_mode));

                if stx.stx_nlink == 0 {
                    // File is deleted, strip the deleted suffix.
                    #[expect(clippy::arithmetic_side_effects)]
                    path.truncate(path.len() - b" (deleted)".len());
                }

                return Ok(Self {
                    abs: path,
                    base_offset: 0,
                    dir: Some(fd),
                    typ: Some(f_type),
                });
            }

            let file_type = if is_mfd {
                // Check for MFD_HUGETLB.
                if is_huge_file(&fd).unwrap_or(false) {
                    path.replace_prefix(MFD_NAME_PREFIX, MFD_HUGETLB_NAME_PREFIX)?;
                }
                Some(FileType::Mfd)
            } else if is_mfdsec {
                Some(FileType::MfdSec)
            } else if cwd {
                Some(FileType::Dir)
            } else {
                file_type(&fd, None, false).ok()
            };

            return Ok(Self {
                abs: path,
                base_offset: 0,
                dir: Some(fd),
                typ: file_type,
            });
        }

        // Use getdir_long().
        //
        // getdir_long() does not change CWD!
        // We limit maximum dir components to PATH_MAX_COMP so the sandbox
        // process cannot create arbitrarily long directories and
        // crash Syd.
        let path = getdir_long(&fd, PATH_MAX_COMP)?;

        Ok(Self {
            abs: path,
            base_offset: 0,
            dir: Some(fd),
            typ: Some(FileType::Dir),
        })
    }

    // Create a `CanonicalPath` using a `FileMap`.
    #[expect(clippy::cognitive_complexity)]
    fn new(
        mut abs: XPathBuf,
        mut typ: Option<FileType>,
        fsflags: FsFlags,
        mut filemap: FileMap,
        resolve_xdev: bool,
    ) -> Result<CanonicalPath, Errno> {
        if abs.is_root() {
            // rootfs view must be identical!
            return Ok(Self::new_root());
        }

        let follow_last = fsflags.follow_last();
        let (mut is_magic_link, magic_base) = match typ {
            Some(FileType::MagicLnk(magic @ (ProcMagic::Pid { .. } | ProcMagic::Tid { .. }))) => {
                if follow_last {
                    (false, magic.base()?)
                } else {
                    (true, None)
                }
            }
            Some(FileType::MagicLnk(ref magic)) => (true, magic.base()?),
            _ => (false, None),
        };

        // During statx(2) and openat2(2) we don't want trailing slash,
        // or we'll get unexpected ELOOP on symbolic links.
        let has_trailing_slash = abs.ends_with_slash();
        if has_trailing_slash {
            #[expect(clippy::arithmetic_side_effects)]
            abs.truncate(abs.len() - 1);
        }

        // Determine file type.
        let entry = filemap.remove(&abs);
        let mut magic_parent: XPathBuf;
        let mut is_magic_dot = false;
        let (parent, mut base) = abs.split();

        let (parent_fd, has_parent) = if let Some(ref entry) = entry {
            typ = if let Some(f_type) = entry.f_type {
                Some(f_type)
            } else {
                file_type(&entry.fd, None, false).ok()
            };

            magic_parent = XPathBuf::from_self_fd(entry.fd.as_raw_fd())?;
            base = &magic_parent;
            is_magic_link = true; // Avoids ELOOP.

            (PROC_FD().into(), false)
        } else if let Some(entry_parent) = filemap.remove(parent) {
            if let Some(ref magic_base) = magic_base {
                base = magic_base;
            } else {
                typ = if let Some(Some(f_type)) = entry.as_ref().map(|e| e.f_type) {
                    Some(f_type)
                } else {
                    file_type(&entry_parent.fd, Some(base), false).ok()
                };
            }

            (entry_parent.fd, true)
        } else if abs.len() >= PATH_MAX {
            // Open using dotdot reference.
            let (child_fd, n_dotdot) =
                if let Some((child_fd, n_dotdot)) = filemap.find_descendant(&abs) {
                    (child_fd, n_dotdot)
                } else {
                    return Err(Errno::ENAMETOOLONG);
                };

            let mut dotdot = XPathBuf::new();
            dotdot.try_reserve(2).or(Err(Errno::ENOMEM))?;
            dotdot.extend(b"..");
            magic_parent = dotdot;

            for _ in 1..n_dotdot {
                magic_parent
                    .try_reserve(b"/..".len())
                    .or(Err(Errno::ENOMEM))?;
                magic_parent.append_bytes(b"/..");
            }
            base = &magic_parent;
            typ = Some(FileType::Dir);
            is_magic_dot = true; // Avoids dotdot desync TOCTOU.
            is_magic_link = true; // Avoids EXDEV.
            (child_fd, false)
        } else {
            base = XPath::from_bytes(&abs.as_bytes()[1..]);

            if !is_magic_link {
                typ = if let Some(Some(f_type)) = entry.as_ref().map(|e| e.f_type) {
                    Some(f_type)
                } else {
                    file_type(ROOT_FILE(), Some(base), false).ok()
                };
            }

            // rootfs view must be identical!
            (ROOT_FD().into(), false)
        };

        // Do we want to resolve symbolic links for the last component?
        if follow_last {
            match typ {
                None if fsflags.must_exist() => {
                    // Last component must exist but it doesn't.
                    return Err(Errno::ENOENT);
                }
                Some(FileType::Lnk) => {
                    // Symlink appeared out-of-nowhere, deny.
                    return Err(Errno::ELOOP);
                }
                _ => {}
            }
        } else if has_trailing_slash && typ.is_none() && fsflags.must_exist() {
            // Attempt to follow dangling symbolic link.
            return Err(Errno::ENOENT);
        }

        if has_trailing_slash && !fsflags.missing() && !matches!(typ, None | Some(FileType::Dir)) {
            // Trailing slash on non-directory.
            return Err(Errno::ENOTDIR);
        }

        // MISS_LAST requires the last component to be absent.
        // Dangling symbolic links require special handling downstream.
        if fsflags.missing() && typ.as_ref().map(|t| !t.is_symlink()).unwrap_or(false) {
            return Err(Errno::EEXIST);
        }

        // Do we want to open the file or the owning directory?
        let open_parent = fsflags.intersects(FsFlags::MISS_LAST | FsFlags::WANT_BASE)
            || (typ.is_none() && !fsflags.must_exist());

        if open_parent {
            // Open an `O_PATH` file descriptor to the owning directory.
            // Use parent fd as a reference if available.
            let parent_fd = if has_parent {
                parent_fd
            } else if parent.is_root() {
                // rootfs view must be identical!
                ROOT_FD().into()
            } else {
                let base = XPath::from_bytes(&parent.as_bytes()[1..]);
                if !base.is_relative() {
                    return Err(Errno::EINVAL);
                }

                let mut rflags = ResolveFlag::empty();
                if !resolve_xdev {
                    rflags.insert(ResolveFlag::RESOLVE_NO_XDEV);
                }

                safe_open_path(ROOT_FILE(), base, OFlag::O_DIRECTORY, rflags)?.into()
            };

            // Calculate parent length early here, as `parent' which is
            // a reference into `abs' can potentially get invalidated in
            // the next trailing slash check.
            let parent_len = parent.len();

            // Preserve trailing slash to assert directory
            // after sandbox path hide check.
            if has_trailing_slash && !abs.is_root() {
                abs.try_reserve(1).or(Err(Errno::ENOMEM))?;
                abs.append_byte(b'/');
            };

            // Ensure we have the correct base path, because e.g. for
            // /proc/self/fd, `base' atm points not the actual base but
            // $pid/fd.  This happens due to the special parent handling
            // above and here we correct base.
            //
            // When parent is "/", parent_len == 1 and we must NOT skip another byte.
            // For all other parents we skip the separating '/'.
            #[expect(clippy::arithmetic_side_effects)]
            let base_offset = parent_len + usize::from(parent_len > 1);

            return Ok(Self {
                abs,
                base_offset,
                dir: Some(parent_fd),
                typ,
            });
        }

        // If the original path had a trailing slash,
        // require a directory on the final open including magic symlinks.
        let mut flags = OFlag::O_PATH | OFlag::O_CLOEXEC;
        if has_trailing_slash || matches!(typ, Some(FileType::Dir)) {
            flags.insert(OFlag::O_DIRECTORY);
        }

        // Attempt to return the O_PATH fd we opened.
        if let Some(entry) = entry {
            if has_trailing_slash && !abs.is_root() {
                // Preserve trailing slash to assert directory after
                // sandbox path hide check.
                abs.try_reserve(1).or(Err(Errno::ENOMEM))?;
                abs.append_byte(b'/');
            }

            // Handle O_NOFOLLOW for magic symbolic links.
            let mut magic_fd = None;
            let mut magic_ln = None;
            if !follow_last {
                if let Some(FileType::MagicLnk(magic)) = entry.f_type {
                    // Create path to symlink.
                    let remote_sym = magic.rlink_path()?;

                    // Open a O_PATH|O_NOFOLLOW fd to the magiclink.
                    magic_fd = Some(
                        safe_open_path_msym(
                            ROOT_FILE(),
                            &remote_sym,
                            OFlag::empty(),
                            ResolveFlag::empty(),
                        )?
                        .into(),
                    );

                    // Prepare absolute path to the magiclink.
                    let mut remote_abs = XPathBuf::new();
                    remote_abs
                        .try_reserve(b"/proc/".len())
                        .or(Err(Errno::ENOMEM))?;
                    remote_abs.extend(b"/proc/");

                    // `remote_sym` is returned by the host Linux kernel:
                    // 1. Link contents are trusted.
                    // 2. Link contents may contain slashes.
                    remote_abs
                        .try_reserve(remote_sym.len())
                        .or(Err(Errno::ENOMEM))?;
                    remote_abs.append_bytes(remote_sym.as_bytes());

                    if has_trailing_slash && !remote_abs.is_root() {
                        // Preserve trailing slash to assert directory
                        // after sandbox path hide check.
                        remote_abs.try_reserve(1).or(Err(Errno::ENOMEM))?;
                        remote_abs.append_byte(b'/');
                    }

                    // NO_FOLLOW_LAST is set, path points to magiclink.
                    typ = Some(FileType::MagicLnk(magic));
                    magic_ln = Some(remote_abs);
                }
            }

            return Ok(Self {
                abs: magic_ln.unwrap_or(abs),
                base_offset: 0,
                dir: Some(magic_fd.unwrap_or(entry.fd)),
                typ,
            });
        }

        // safe_open does not follow symlinks.
        // Exception: Final component is a (magic) symlink, and NO_FOLLOW_LAST isn't set.
        let fd = if is_magic_link {
            if !follow_last {
                // NO_FOLLOW_LAST set, insert O_NOFOLLOW.
                flags.insert(OFlag::O_NOFOLLOW);
            }
            safe_open_msym(parent_fd, base, flags, ResolveFlag::empty())
        } else {
            // O_NOFOLLOW already set here.
            let mut rflags = ResolveFlag::empty();
            if !resolve_xdev {
                rflags.insert(ResolveFlag::RESOLVE_NO_XDEV);
            }

            safe_open(parent_fd, base, flags, rflags)
        }?;

        // Resync after dotdot open to avoid TOCTOU.
        if is_magic_dot {
            abs = getdir_long(&fd, PATH_MAX_COMP)?;
        }

        // Preserve trailing slash to assert directory
        // after sandbox path hide check.
        if has_trailing_slash && !abs.is_root() {
            abs.try_reserve(1).or(Err(Errno::ENOMEM))?;
            abs.append_byte(b'/');
        }

        Ok(Self {
            abs,
            base_offset: 0,
            dir: Some(fd.into()),
            typ,
        })
    }
}

/// Return the canonical, absolute form of a path safely as a file
/// descriptor to the owning file descriptor together with the base
/// component and optional file type.
#[expect(clippy::cognitive_complexity)]
pub fn safe_canonicalize(
    pid: Pid,
    fd: Option<RawFd>,
    path: &XPath,
    mut fsflags: FsFlags,
    request: Option<&UNotifyEventRequest>,
    sandbox: Option<&Sandbox>,
) -> Result<CanonicalPath, Errno> {
    // Safely initialize flags.
    let flags = sandbox.map(|sb| *sb.flags).unwrap_or_default();

    // Validate options.
    let resolve_beneath = fsflags.contains(FsFlags::RESOLVE_BENEATH);
    let resolve_in_root = fsflags.contains(FsFlags::RESOLVE_IN_ROOT);
    if resolve_beneath && resolve_in_root {
        return Err(Errno::EINVAL);
    }

    // Validate path.
    if path.is_empty() {
        return Err(Errno::ENOENT);
    }

    // File map is a hash table with paths as keys. The values are the
    // file descriptor, the file type, and optional symbolic link
    // target. This map is used throughout canonicalization to ensure:
    // 1. We never reopen the same file.
    // 2. We never follow the same link.
    // 3. We never recheck the file type or mount id.
    let mut filemap: FileMap = FileMap::try_new()?;
    let mut file_type = None;

    let (mut result, cwd) = if resolve_in_root || path.is_relative() {
        if let Some(fd) = fd {
            let magic = if fd == libc::AT_FDCWD {
                ProcMagic::Cwd { pid }
            } else if fd < 0 {
                return Err(Errno::EBADF);
            } else {
                ProcMagic::Fd { pid, fd }
            };
            let (mut entry, sym) = FileMapEntry::from_magic_link(magic, true, request, sandbox)
                .map_err(|e| {
                    // Return bad-fd rather than no-such-file for genuine fds.
                    if e == Errno::ENOENT {
                        Errno::EBADF
                    } else {
                        e
                    }
                })?;

            // fd_entry's target member is always Some, when
            // FileMapEntry::from_magic_link returns success with
            // want_dir parameter set to true.
            #[expect(clippy::disallowed_methods)]
            let dir = entry
                .target
                .as_ref()
                .unwrap()
                .as_ref()
                .unwrap()
                .try_clone()?;

            let entry_sym = FileMapEntry::new(
                MaybeFd::RawFd(entry.fd.as_raw_fd()),
                Some(FileType::MagicLnk(magic)),
                entry.f_mode,
                entry.mnt_id,
                entry.target.take(),
            );

            entry.f_type = Some(FileType::Dir);
            filemap.try_insert(dir.try_clone()?, entry)?;
            filemap.try_insert(sym, entry_sym)?;

            (dir.try_clone()?, dir)
        } else {
            let magic = ProcMagic::Cwd { pid };
            let (mut entry, sym) = FileMapEntry::from_magic_link(magic, true, request, sandbox)?;

            // cwd_entry's target member is always Some, when
            // FileMapEntry::from_magic_link returns success with
            // want_dir parameter set to true.
            #[expect(clippy::disallowed_methods)]
            let dir = entry
                .target
                .as_ref()
                .unwrap()
                .as_ref()
                .unwrap()
                .try_clone()?;

            let entry_sym = FileMapEntry::new(
                MaybeFd::RawFd(entry.fd.as_raw_fd()),
                Some(FileType::MagicLnk(magic)),
                entry.f_mode,
                entry.mnt_id,
                entry.target.take(),
            );

            entry.f_type = Some(FileType::Dir);
            filemap.try_insert(dir.try_clone()?, entry)?;
            filemap.try_insert(sym, entry_sym)?;

            (dir.try_clone()?, dir)
        }
    } else if resolve_beneath {
        // RESOLVE_BENEATH rejects absolute values of pathname.
        return Err(Errno::EXDEV);
    } else if path.is_root() {
        // Special case, `/` is never a symlink.
        // This must be done after the RESOLVE_BENEATH check!
        return Ok(CanonicalPath::new_root());
    } else {
        // Absolute path, CWD is ignored.
        (XPathBuf::from("/"), XPathBuf::from("/"))
    };

    // What do we do when a component is missing?
    let miss_mode = MissingHandling::from(fsflags);
    // Do we want to resolve magic /proc symbolic links?
    let resolve_proc = if flags.force_no_magiclinks() {
        fsflags.insert(FsFlags::NO_RESOLVE_PROC);
        false
    } else {
        fsflags.resolve_proc()
    };
    // Do we want to traverse through mount points?
    //
    // As of version 3.39.0 this may be enforced
    // using the trace/force_no_xdev option.
    let resolve_xdev = if flags.force_no_xdev() {
        fsflags.insert(FsFlags::NO_RESOLVE_XDEV);
        false
    } else {
        !fsflags.contains(FsFlags::NO_RESOLVE_XDEV)
    };

    // `..` restriction for path traversal for chdir and open* family calls.
    let deny_dotdot = fsflags.contains(FsFlags::NO_RESOLVE_DOTDOT);

    // Restriction for /proc magic links.
    let restrict_magiclinks = !flags.allow_unsafe_magiclinks();

    // Do we want to resolve symbolic links for the last component?
    let no_follow_last = !fsflags.follow_last();

    // Do we want the base component of the path?
    let want_base = fsflags.want_base();

    // Options to open flags. O_NOFOLLOW is omitted here on purpose.
    let mut open_flags = OFlag::O_PATH | OFlag::O_CLOEXEC;

    // Split path into components, record trailing slash.
    let (mut parts, mut has_to_be_directory) = path_components(path)?;

    // Assert directory requirement with O_DIRECTORY.
    if has_to_be_directory {
        open_flags.insert(OFlag::O_DIRECTORY);
    }

    // Determine reference mount id for RESOLVE_NO_XDEV.
    let mnt_id = if resolve_xdev {
        // Do nothing if RESOLVE_NO_XDEV is not set.
        None
    } else {
        Some(filemap.get_mnt_id(&cwd, pid, fsflags, file_type, request, sandbox)?)
    };

    let mut last;
    let mut loop_first = true;
    let mut no_resolve_symlinks;
    while let Some(part) = parts.pop() {
        // Limit maximum dir components to PATH_MAX_COMP so the sandbox
        // process cannot create arbitrarily long directories and crash
        // Syd.
        if result.len() >= PATH_MAX && parts.len() >= PATH_MAX_COMP {
            return Err(Errno::ENAMETOOLONG);
        }

        // Check if this is the last component.
        //
        // It may not necessarily be the last iteration,
        // in case the last component points to a symlink.
        last = parts.is_empty();

        // Do we want to resolve symbolic links in this path component?
        //
        // The answer is YES for all path components but the final
        // component. The resolution of the final component depends
        // on the following conditions:
        //
        // The answer is NO _if_ NO_FOLLOW_LAST flag is set, YES otherwise.
        //
        // _Unless_ the final component has a trailing slash which asserts a directory,
        // in which case we _DO_ resolve symbolic links in the final component regardless
        // of the NO_FOLLOW_LAST flag.
        //
        // _However_, if one of MISS_LAST or WANT_BASE flags is also set, the trailing slash
        // is irrelevant, and we do _NOT_ resolve symlinks in the final
        // component.
        no_resolve_symlinks = last
            && no_follow_last
            && (!has_to_be_directory || miss_mode == MissingHandling::Missing || want_base);

        if deny_dotdot && part == PathComponent::PARENT_DIR {
            // Traversing through `..` is forbidden with trace/deny_dotdot:1.
            return Err(Errno::EACCES);
        }

        // The first iteration of checks for RESOLVE_BENEATH,
        // and RESOLVE_NO_XDEV was done before the loop so
        // we skip them here for one turn.
        if !loop_first {
            // Check for RESOLVE_BENEATH and RESOLVE_NO_XDEV.
            // Temporary jumps are not allowed!
            if resolve_beneath && !result.deref().descendant_of(cwd.as_bytes()) {
                return Err(Errno::EXDEV);
            }

            if let Some(mnt_id) = mnt_id {
                // Jumping to "/" is ok, but later components cannot cross.
                if !result.is_root() {
                    let my_mnt_id =
                        filemap.get_mnt_id(&result, pid, fsflags, file_type, request, sandbox)?;
                    if my_mnt_id != mnt_id {
                        return Err(Errno::EXDEV);
                    }
                }
            }
        } else {
            loop_first = false;
        }

        match part {
            PathComponent(Some(ref p)) => {
                let len = p.len()
                    .checked_add(1) // path-sep
                    .ok_or(Errno::ENAMETOOLONG)?;
                result.try_reserve(len).or(Err(Errno::ENOMEM))?;
                result.push(p.as_bytes());

                // Invalidate file type.
                file_type = None;
            }
            PathComponent::PARENT_DIR => {
                // Check for RESOLVE_IN_ROOT:
                //
                // If a prefix component of path equates to dirfd,
                // then an immediately following .. component likewise
                // equates to dirfd (just as /.. is traditionally
                // equivalent to /).
                if !(result.is_equal(b"/") || resolve_in_root && result.is_equal(cwd.as_bytes())) {
                    // SAFETY:
                    // 1. `result` is a normalized absolute path.
                    // 2. `result` does not have a trailing slash.
                    unsafe { result.pop_unchecked() };
                }

                continue;
            }
        }

        // - NO_MAGICLINKS unless trace/allow_unsafe_magiclinks:1.
        //   Continue in case:
        //   (a) pipe:42 socket:42 etc, special paths.
        //   (b) file descriptors that point to deleted paths.
        // - Handle /proc/self and /proc/thread-self indirections.
        let result_magic = match ProcMagic::check_link(pid, result.deref(), restrict_magiclinks)? {
            Some(_) if !resolve_proc && (!last || !no_follow_last) => {
                // NO_SYMLINKS|NO_MAGICLINKS|BENEATH|IN_ROOT.
                return Err(fsflags.magic_errno());
            }
            Some(
                magic @ (ProcMagic::Fd { .. }
                | ProcMagic::Cwd { .. }
                | ProcMagic::Root { .. }
                | ProcMagic::Exe { .. }),
            ) => {
                // Handle /proc/$pid/{fd/<n>,cwd,root,exe} indirection unless
                // this is the final component and NO_FOLLOW_LAST is set.
                let sym = magic.link_path()?;
                file_type = Some(FileType::MagicLnk(magic));

                let target = if let Some(entry) = filemap.get(&sym) {
                    // Magic link target member is always Some.
                    #[expect(clippy::disallowed_methods)]
                    entry
                        .target
                        .as_ref()
                        .unwrap()
                        .as_ref()
                        .unwrap()
                        .try_clone()?
                } else {
                    let (mut entry, _) =
                        FileMapEntry::from_magic_link(magic, !last, request, sandbox)?;

                    // Magic link target member is always Some.
                    #[expect(clippy::disallowed_methods)]
                    let target = entry.target.take().unwrap().unwrap();

                    let entry_sym = FileMapEntry::new(
                        MaybeFd::RawFd(entry.fd.as_raw_fd()),
                        Some(FileType::MagicLnk(magic)),
                        entry.f_mode,
                        entry.mnt_id,
                        Some(Ok(target.try_clone()?)),
                    );
                    filemap.try_insert(sym, entry_sym)?;

                    if target.is_absolute() {
                        // entry.target is intentionally None here.
                        filemap.try_insert(target.try_clone()?, entry)?;
                    }

                    target
                };

                if last && !no_resolve_symlinks {
                    if target.is_relative() {
                        // Magic link points to magic path.
                        // Paths such as [pipe:64], [socket:42] etc.
                        // Append to result so the user can filter.

                        // SAFETY:
                        // 1. `result` is a normalized absolute path.
                        // 2. `result` does not have a trailing slash.
                        unsafe { result.pop_unchecked() };
                        result.try_reserve(target.len()).or(Err(Errno::ENOMEM))?;
                        result.push(target.as_bytes());
                    } else {
                        // Magic link points to genuine path.
                        // Set the result to target, reset file type.
                        result.clear();
                        result.try_reserve(target.len()).or(Err(Errno::ENOMEM))?;
                        result.append_bytes(target.as_bytes());
                        file_type = None;
                    }

                    if has_to_be_directory {
                        result.try_reserve(1).or(Err(Errno::ENOMEM))?;
                        result.push(b"");
                    }

                    break;
                }

                Some(Ok(target))
            }
            Some(magic @ ProcMagic::Ns { .. }) => {
                // Keep magic type so CanonicalPath::new opens with safe_open_msym.
                file_type = Some(FileType::MagicLnk(magic));
                Some(Err(Errno::EINVAL))
            }
            Some(magic @ (ProcMagic::Pid { .. } | ProcMagic::Tid { .. })) => {
                // ProcMagic::check_link does not check for these.
                unreachable!("BUG: ProcMagic::check_link returned invalid magic `{magic:?}'!");
            }
            None if result.is_proc_self(false) => {
                // Handle /proc/self indirection unless
                // this is the final component and NO_FOLLOW_LAST
                // is set. NO_MAGICLINKS allows /proc/self.
                if !no_resolve_symlinks {
                    file_type = Some(FileType::Dir);

                    // SAFETY:
                    // 1. `result` is a normalized absolute path.
                    // 2. `result` does not have a trailing slash.
                    unsafe { result.pop_unchecked() };

                    result
                        .try_reserve(1 + libc::pid_t::MAX_STR_LEN)
                        .or(Err(Errno::ENOMEM))?;
                    result.push_pid(pid);
                } else if last {
                    // Set file type to magic symlink.
                    file_type = Some(FileType::MagicLnk(ProcMagic::Pid { pid }));
                }

                Some(Err(Errno::EINVAL))
            }
            None if result.is_proc_self(true) => {
                // Handle /proc/thread-self indirection unless
                // this is the final component and NO_FOLLOW_LAST
                // is set. NO_MAGICLINKS allows /proc/thread-self.
                let tgid = proc_tgid(pid)?;
                if !no_resolve_symlinks {
                    file_type = Some(FileType::Dir);

                    // SAFETY:
                    // 1. `result` is a normalized absolute path.
                    // 2. `result` does not have a trailing slash.
                    unsafe { result.pop_unchecked() };

                    result
                        .try_reserve(6 + libc::pid_t::MAX_STR_LEN * 2)
                        .or(Err(Errno::ENOMEM))?;
                    result.push_pid(tgid);
                    result.push(b"task");
                    result.push_pid(pid);
                } else if last {
                    // Set file type to magic symlink.
                    file_type = Some(FileType::MagicLnk(ProcMagic::Tid { tgid, pid }));
                }

                Some(Err(Errno::EINVAL))
            }
            None => None,
        };

        // We're resolving symbolic links for all path components but last.
        // The resolution of the last component depends on the NO_FOLLOW_LAST option.
        if no_resolve_symlinks {
            // Handle trailing slash as part of a symlink target.
            if result.ends_with(b"/") {
                has_to_be_directory = true;
                open_flags.insert(OFlag::O_DIRECTORY);
            }

            // Invalidate file type since we are not going to resolve
            // the final component. One exception is (magic) symbolic
            // links whose information we keep for later hardening.
            if !file_type
                .as_ref()
                .map(|typ| typ.is_symlink() || typ.is_magic_link())
                .unwrap_or(false)
            {
                file_type = None;
            }

            // Nothing left to do, break out.
            break;
        }

        let resolve_result = if let Some(result_magic) = result_magic {
            result_magic
        } else {
            filemap.readlink(&result, pid, fsflags, file_type, request, sandbox)
        };

        match resolve_result {
            Ok(target) => {
                // Invalidate file type before the next round.
                file_type = None;

                if target.is_relative() {
                    // SAFETY:
                    // 1. `result` is a normalized absolute path.
                    // 2. `result` does not have a trailing slash.
                    unsafe { result.pop_unchecked() };
                } else if resolve_in_root {
                    // RESOLVE_IN_ROOT: Absolute symlinks are treated relative to dirfd.
                    // `result` is an absolute path so truncating to CWD length is ok.
                    result.truncate(cwd.len());
                } else {
                    // RootDir as part of resolving a symlink to an absolute path:
                    // `result` is an absolute path so truncating to 1 effectively
                    // leaves behind / only.
                    result.truncate(1);
                }
                path_components2(target.deref(), &mut parts)?;
            }
            Err(Errno::EINVAL) => {
                // Handle trailing slash as part of a symlink target.
                if last && !has_to_be_directory && result.ends_with(b"/") {
                    has_to_be_directory = true;
                    open_flags.insert(OFlag::O_DIRECTORY);
                } else if !file_type.map(|t| t.is_magic_link()).unwrap_or(false) {
                    // Invalidate only non-magic types;
                    // keep MagicLnk so we open via magicsym.
                    file_type = None;
                }
            }
            Err(Errno::ELOOP) => return Err(Errno::ELOOP),
            Err(errno) => match miss_mode {
                MissingHandling::Existing => return Err(errno),
                _ if !parts.is_empty() => return Err(errno),
                _ => {
                    // Invalidate file type.
                    file_type = None;
                }
            },
        }
    }

    // Check final component for Stat sandboxing.
    if let Some(sandbox) = sandbox {
        sandbox.check_stat(request, pid, &result)?;
    }

    // Deny symbolic links at final component,
    // unless NO_FOLLOW_LAST is set explicitly.
    if fsflags.follow_last()
        && file_type
            .as_ref()
            .map(|typ| typ.is_symlink())
            .unwrap_or(false)
    {
        return Err(Errno::ELOOP);
    }

    // Check for RESOLVE_BENEATH and RESOLVE_NO_XDEV.
    if resolve_beneath && !result.deref().descendant_of(cwd.as_bytes()) {
        return Err(Errno::EXDEV);
    }

    // Handle trailing slash:
    // 1. Keep trailing slash as necessary.
    // 2. Add trailing slash for directories to assert file type.
    if has_to_be_directory {
        let dir_ok = match file_type {
            Some(FileType::Dir) => true,
            Some(FileType::MagicLnk(ProcMagic::Cwd { .. } | ProcMagic::Root { .. })) => true,
            Some(FileType::MagicLnk(ProcMagic::Pid { .. } | ProcMagic::Tid { .. })) => true,
            // Everything else (Exe/Fd/Ns/other magics) is not directory-typed.
            Some(FileType::MagicLnk(_)) => false,
            // Unknown type: defer to the open() with O_DIRECTORY to decide.
            None => true,
            _ => false,
        };

        if matches!(
            miss_mode,
            MissingHandling::Existing | MissingHandling::Normal
        ) && !dir_ok
        {
            return Err(Errno::ENOTDIR);
        }

        if !result.is_root() {
            result.try_reserve(1).or(Err(Errno::ENOMEM))?;
            result.append_byte(b'/');
        }
    }

    if let Some(mnt_id) = mnt_id {
        // Open last component.
        let my_mnt_id = match (
            filemap.get_mnt_id(&result, pid, fsflags, file_type, request, sandbox),
            miss_mode,
        ) {
            (Ok(mnt_id), _) => mnt_id,
            (Err(Errno::ELOOP), _) => {
                // Symlink appeared out-of-nowhere, deny.
                return Err(Errno::ELOOP);
            }
            (Err(Errno::ENOENT), MissingHandling::Existing) => {
                return Err(Errno::ENOENT);
            }
            (Err(Errno::ENOTDIR), MissingHandling::Existing | MissingHandling::Normal)
                if has_to_be_directory =>
            {
                return Err(Errno::ENOTDIR);
            }
            _ => return Err(Errno::EXDEV),
        };

        if my_mnt_id != mnt_id {
            return Err(Errno::EXDEV);
        }
    }

    // Symbolic link resolution is no-longer needed/wanted.
    open_flags |= OFlag::O_NOFOLLOW;

    // Open a file descriptor to the canonical path, without resolving
    // symbolic links anymore. This brings safety against TOCTTOU
    // attacks.
    let path = CanonicalPath::new(result, file_type, fsflags, filemap, resolve_xdev)?;

    Ok(path)
}

#[cfg(test)]
mod tests {
    use std::{
        ffi::OsStr,
        fs::{self, OpenOptions, Permissions},
        os::{
            fd::{AsRawFd, IntoRawFd},
            unix::{
                ffi::OsStrExt,
                fs::{symlink, OpenOptionsExt, PermissionsExt},
                net::UnixStream,
            },
        },
        path::Path,
        process::{exit, Command},
        thread::sleep,
        time::{Duration, SystemTime},
    };

    use bitflags::Flags;
    use nix::{
        fcntl::{open, openat},
        sched::{unshare, CloneFlags},
        sys::{
            resource::{getrlimit, Resource},
            signal::{kill, Signal},
            stat::{umask, Mode},
            wait::waitpid,
        },
        unistd::{chdir, close, fchdir, fork, getcwd, pause, ForkResult},
    };

    use super::*;
    use crate::{
        confine::confine_rlimit,
        fd::{close_static_files, open_static_files},
        xpath,
    };

    // Directory depth enough to trigger capacity checks.
    const MAX_DEPTH: usize = PATH_MAX_COMP * 2;

    struct TestGuard;

    impl Drop for TestGuard {
        fn drop(&mut self) {
            let _ = close_static_files;
        }
    }

    fn setup() -> Option<TestGuard> {
        umask(Mode::from_bits_truncate(0o7077));
        let _ = increase_fd_limits();

        let _ = crate::log::log_init_simple(crate::syslog::LogLevel::Warn);

        if let Err(errno) = open_static_files() {
            eprintln!("Failed to initialize static files: {errno}!");
            return None;
        }

        Some(TestGuard)
    }

    fn increase_fd_limits() -> Result<(), Errno> {
        let (_, hard_limit) = getrlimit(Resource::RLIMIT_NOFILE)?;
        confine_rlimit(Resource::RLIMIT_NOFILE, Some(hard_limit))
    }

    // Join a multi-component relative path to a base path.
    fn join_path(base: &XPath, rel: &[u8]) -> XPathBuf {
        let mut p = base.to_owned();
        if p.last().map(|c| c != b'/').unwrap_or(true) {
            p.append_byte(b'/');
        }
        p.append_bytes(rel);
        p
    }

    // A helper function to create a deep directory structure.
    fn setup_deep_directory_structure(name: &XPath, depth: usize) -> Result<(), Errno> {
        let mut path = Vec::new();
        for _ in 0..depth {
            path.extend(name.as_bytes());
            path.push(b'/');
        }
        let cwd = open(c".", OFlag::O_PATH, Mode::empty())?.into();
        safe_mkdir_all(&cwd, XPath::from_bytes(&path[..])).map(drop)
    }

    // A helper function to get the current atime of a file
    fn get_atime<P: AsRef<Path>>(path: P) -> SystemTime {
        let metadata = fs::metadata(path).expect("Failed to get metadata");
        metadata.accessed().expect("Failed to get accessed time")
    }

    // Helper function to assert that the atime of a file or directory has not changed
    fn assert_atime_unchanged<'a, P: AsRef<Path>, F>(path: P, func: F)
    where
        F: FnOnce() -> Result<CanonicalPath, Errno>,
    {
        let original_atime_f = get_atime(&path);
        let original_atime_p = get_atime(path.as_ref().parent().unwrap());
        sleep(Duration::from_secs(7));
        assert!(
            func().is_ok(),
            "canonicalize {} failed",
            path.as_ref().display()
        );
        // We allow a 1-second tolerance since some filesystems do not have nanosecond precision.
        let new_atime_f = get_atime(&path);
        let new_atime_p = get_atime(path.as_ref().parent().unwrap());
        assert!(
            new_atime_f <= original_atime_f + Duration::new(1, 0),
            "The atime of the file should not have significantly changed."
        );
        assert!(
            new_atime_p <= original_atime_p + Duration::new(1, 0),
            "The atime of the parent dir should not have significantly changed."
        );
    }

    // std::fs::remove_dir_all stops on the first error.
    // we need something more forceful.
    fn remove_dir_all<P: AsRef<Path>>(path: P) -> std::io::Result<()> {
        let status = Command::new("rm")
            .arg("-rf")
            .arg(path.as_ref().to_string_lossy().to_string())
            .status()?;
        if status.success() {
            Ok(())
        } else {
            Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to remove directory: {}", path.as_ref().display()),
            ))
        }
    }

    // Helper function to create a symlink chain that eventually loops back to an earlier link
    fn setup_symlink_loop(tmp_dir: &XPath, links: &[(&str, &str)]) {
        for &(src, dst) in links {
            let src_path = join_path(&tmp_dir.to_owned(), src.as_bytes());

            // Check and create parent directory for the source if necessary
            let src_parent = src_path.parent();
            if !src_parent.exists(false) {
                fs::create_dir_all(src_parent.as_path()).unwrap();
            }

            // The destination is given relative to the source
            let dst_path = XPath::from_bytes(&dst.as_bytes());

            // Avoid creating a symlink if the source already exists
            if src_path.exists(false) {
                fs::remove_file(src_path.as_path()).unwrap();
            }

            // If the destination is an absolute path or starts with '/', we strip the '/' and prefix with tmp_dir
            let full_dst_path = if dst_path.is_absolute() {
                join_path(
                    &tmp_dir.to_owned(),
                    dst_path.strip_prefix(b"/").unwrap().as_bytes(),
                )
            } else {
                join_path(&src_parent.to_owned(), dst_path.as_bytes())
            };

            // Create parent directories for the destination if they don't exist
            let dst_parent = full_dst_path.parent();
            if !dst_parent.exists(false) {
                fs::create_dir_all(dst_parent.as_path()).unwrap();
            }

            // Create the symlink
            symlink(full_dst_path.as_path(), src_path.as_path())
                .expect(&format!("Unable to symlink {src_path} -> {full_dst_path}",));
        }
    }

    fn tempdir() -> Result<(XPathBuf, tempfile::TempDir), Box<dyn std::error::Error>> {
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir_in(".")?;
        let _ = OpenOptions::new()
            .write(true)
            .create(true)
            .mode(0o600)
            .open(tmp.path().join("test"))?;
        let name = tmp
            .path()
            .to_path_buf()
            .file_name()
            .unwrap()
            .as_bytes()
            .into();
        Ok((name, tmp))
    }

    // Changes the current directory to `dir` handling arbitrarily long pathnames.
    fn chdir_long(dir: &XPath) -> Result<(), Errno> {
        let mut path_buf = dir.as_bytes();
        let mut current_dir_fd = -2;

        loop {
            // Attempt to change directory.
            let dir = XPath::from_bytes(path_buf);
            if path_buf.is_empty() || chdir(dir).is_ok() {
                if current_dir_fd >= 0 {
                    let _ = close(current_dir_fd);
                }
                return Ok(());
            }

            if !matches!(Errno::last(), Errno::ENAMETOOLONG | Errno::ENOMEM)
                || dir.len() < PATH_MAX - 1
            {
                break;
            }

            // Handle long path by trying to split at a directory boundary
            let mut boundary = path_buf.len().min(PATH_MAX - 1);
            while boundary > 0 && path_buf[boundary] != b'/' {
                boundary -= 1;
            }

            if boundary == 0 {
                break;
            }

            // Attempt to temporarily change to the subdirectory.
            if current_dir_fd == -2 {
                // Open current directory.
                current_dir_fd = open(".", OFlag::O_PATH | OFlag::O_DIRECTORY, Mode::empty())
                    .map(|fd| fd.into_raw_fd())?;
            }

            let dir = XPath::from_bytes(&path_buf[..boundary]);
            if chdir(dir).is_err() {
                break;
            }

            // Move to the next component.
            path_buf = &path_buf[boundary + 1..];
        }

        // Save last errno to return from the function.
        let errno = match Errno::last() {
            Errno::UnknownErrno => Errno::ENAMETOOLONG,
            errno => errno,
        };

        // Attempt to restore the original directory if there was a failure.
        if current_dir_fd >= 0 {
            let result = fchdir(unsafe { BorrowedFd::borrow_raw(current_dir_fd) });
            let _ = close(current_dir_fd);

            return if result.is_ok() {
                Err(errno)
            } else {
                Err(Errno::ENOTRECOVERABLE)
            };
        }

        Err(if current_dir_fd == -2 {
            errno
        } else {
            Errno::ENOTRECOVERABLE
        })
    }

    #[test]
    fn test_path_components_empty_path() {
        let path = XPath::from_bytes(b"");
        let (components, has_trailing_slash) = path_components(&path).unwrap();
        assert!(components.is_empty());
        assert!(has_trailing_slash);
    }

    #[test]
    fn test_path_components_only_parent_dir() {
        let path = XPath::from_bytes(b"..");
        let (components, has_trailing_slash) = path_components(&path).unwrap();
        assert_eq!(components.len(), 1);
        assert_eq!(components[0], PathComponent::PARENT_DIR);
        assert!(has_trailing_slash);
    }

    #[test]
    fn test_path_components_multiple_parent_dir() {
        let path = XPath::from_bytes(b"../..");
        let (components, has_trailing_slash) = path_components(&path).unwrap();
        assert_eq!(components.len(), 2);
        assert_eq!(components[0], PathComponent::PARENT_DIR);
        assert_eq!(components[1], PathComponent::PARENT_DIR);
        assert!(has_trailing_slash);
    }

    #[test]
    fn test_path_components_parent_dir_with_normal_components() {
        // Path: "../foo/../bar" -> reversed: [bar, .., foo, ..]
        let path = XPath::from_bytes(b"../foo/../bar");
        let (components, has_trailing_slash) = path_components(&path).unwrap();
        assert_eq!(components.len(), 4);
        assert_eq!(components[0], PathComponent(Some(XPathBuf::from("bar"))));
        assert_eq!(components[1], PathComponent::PARENT_DIR);
        assert_eq!(components[2], PathComponent(Some(XPathBuf::from("foo"))));
        assert_eq!(components[3], PathComponent::PARENT_DIR);
        assert!(!has_trailing_slash);
    }

    #[test]
    fn test_path_components_trailing_slash_with_parent_dir() {
        // Path: "../foo/.." -> reversed: [.., foo, ..]
        let path = XPath::from_bytes(b"../foo/..");
        let (components, has_trailing_slash) = path_components(&path).unwrap();
        assert_eq!(components.len(), 3);
        assert_eq!(components[0], PathComponent::PARENT_DIR);
        assert_eq!(components[1], PathComponent(Some(XPathBuf::from("foo"))));
        assert_eq!(components[2], PathComponent::PARENT_DIR);
        assert!(has_trailing_slash);
    }

    #[test]
    fn test_path_components_leading_slashes_are_skipped() {
        // Path: "////..////bar" -> reversed: [bar, ..]
        let path = XPath::from_bytes(b"////..////bar");
        let (components, has_trailing_slash) = path_components(&path).unwrap();
        assert_eq!(components.len(), 2);
        assert_eq!(components[0], PathComponent(Some(XPathBuf::from("bar"))));
        assert_eq!(components[1], PathComponent::PARENT_DIR);
        assert!(!has_trailing_slash);
    }

    #[test]
    fn test_path_components_path_with_mixed_components_and_trailing_slash() {
        // Path: "../foo/../bar/" -> reversed: [bar, .., foo, ..]
        let path = XPath::from_bytes(b"../foo/../bar/");
        let (components, has_trailing_slash) = path_components(&path).unwrap();
        assert_eq!(components.len(), 4);
        assert_eq!(components[0], PathComponent(Some(XPathBuf::from("bar"))));
        assert_eq!(components[1], PathComponent::PARENT_DIR);
        assert_eq!(components[2], PathComponent(Some(XPathBuf::from("foo"))));
        assert_eq!(components[3], PathComponent::PARENT_DIR);
        assert!(has_trailing_slash);
    }

    #[test]
    fn test_path_components_complex_path_with_leading_parent_dir() {
        // Path: "../foo/bar/../../baz/.." -> forward: [.., foo, bar, .., .., baz, ..]
        // Reversed: [.., baz, .., .., bar, foo, ..]
        let path = XPath::from_bytes(b"../foo/bar/../../baz/..");
        let (components, has_trailing_slash) = path_components(&path).unwrap();
        assert_eq!(components.len(), 7);
        assert_eq!(components[0], PathComponent::PARENT_DIR);
        assert_eq!(components[1], PathComponent(Some(XPathBuf::from("baz"))));
        assert_eq!(components[2], PathComponent::PARENT_DIR);
        assert_eq!(components[3], PathComponent::PARENT_DIR);
        assert_eq!(components[4], PathComponent(Some(XPathBuf::from("bar"))));
        assert_eq!(components[5], PathComponent(Some(XPathBuf::from("foo"))));
        assert_eq!(components[6], PathComponent::PARENT_DIR);
        assert!(has_trailing_slash);
    }

    #[test]
    fn test_path_components_root_path_is_handled_externally() {
        let path = XPath::from_bytes(b"/..");
        let (components, has_trailing_slash) = path_components(&path).unwrap();
        assert_eq!(components.len(), 1);
        assert_eq!(components[0], PathComponent::PARENT_DIR);
        assert!(has_trailing_slash);
    }

    #[test]
    fn test_chdir_long() {
        // Unshare current working directory.
        unshare(CloneFlags::CLONE_FS).unwrap();

        // Create a deep directory structure.
        let name = XPathBuf::from(&[b'o'; 200][..]);
        setup_deep_directory_structure(&name, MAX_DEPTH).unwrap();

        // Save current working directory.
        let fd = open(".", OFlag::O_PATH | OFlag::O_DIRECTORY, Mode::empty()).unwrap();

        // Attempt to change dir into it.
        let mut lname = name.clone();
        for _ in 0..MAX_DEPTH - 1 {
            lname.push(name.as_bytes());
        }
        let result = chdir_long(&lname);

        // Restore current working directory.
        fchdir(fd).unwrap();

        // Clean up after the test.
        Command::new("rm").arg("-rf").arg(name).status().unwrap();

        assert!(result.is_ok(), "chdir_long failed: {result:?}");
    }

    #[test]
    fn test_getdir_long_with_deep_structure() {
        // Unshare current working directory.
        unshare(CloneFlags::CLONE_FS).unwrap();

        // Create a deep directory structure.
        let name = XPathBuf::from(&[b'o'; 200][..]);
        setup_deep_directory_structure(&name, MAX_DEPTH).unwrap();

        // Save current working directory.
        let fd = open(".", OFlag::O_PATH | OFlag::O_DIRECTORY, Mode::empty()).unwrap();
        let mut cwd = getcwd().map(XPathBuf::from).unwrap();

        // Attempt to change dir into it.
        let max = cwd.depth() + MAX_DEPTH + 1;
        for _ in 0..MAX_DEPTH {
            cwd.push(name.as_bytes());
        }
        let result = chdir_long(&cwd);

        // Get current working directory.
        let result_cwd = if result.is_ok() {
            let cwd_fd = open(".", OFlag::O_PATH | OFlag::O_DIRECTORY, Mode::empty()).unwrap();
            Some(getdir_long(cwd_fd, max))
        } else {
            None
        };

        // Restore current working directory.
        fchdir(fd).unwrap();

        // Clean up after the test.
        Command::new("rm").arg("-rf").arg(name).status().unwrap();

        // Check results.
        assert!(result.is_ok(), "chdir_long failed: {result:?}");

        let result_cwd = result_cwd.unwrap();
        assert!(result_cwd.is_ok(), "getdir_long failed: {result_cwd:?}");

        let result_cwd = result_cwd.unwrap();
        assert_eq!(cwd, result_cwd, "getdir_long returned incorrect directory");
    }

    #[test]
    fn test_getdir_long_limit_max_components() {
        // Unshare current working directory.
        unshare(CloneFlags::CLONE_FS).unwrap();

        // Create a deep directory structure.
        let name = XPathBuf::from(&[b'o'; 200][..]);
        setup_deep_directory_structure(&name, MAX_DEPTH).unwrap();

        // Save current working directory.
        let fd = open(".", OFlag::O_PATH | OFlag::O_DIRECTORY, Mode::empty()).unwrap();
        let mut cwd = getcwd().map(XPathBuf::from).unwrap();

        // Attempt to change dir into it.
        let max = cwd.depth() + MAX_DEPTH;
        for _ in 0..MAX_DEPTH {
            cwd.push(name.as_bytes());
        }
        let result = chdir_long(&cwd);

        // Get current working directory.
        let result_cwd = if result.is_ok() {
            let cwd_fd = open(".", OFlag::O_PATH | OFlag::O_DIRECTORY, Mode::empty()).unwrap();
            Some(getdir_long(cwd_fd, max))
        } else {
            None
        };

        // Restore current working directory.
        fchdir(fd).unwrap();

        // Clean up after the test.
        Command::new("rm").arg("-rf").arg(name).status().unwrap();

        // Check results.
        assert!(result.is_ok(), "chdir_long failed: {result:?}");

        let result_cwd = result_cwd.unwrap();
        assert_eq!(
            result_cwd,
            Err(Errno::ERANGE),
            "getdir_long did not fail as expected: {result_cwd:?}"
        );
    }

    #[test]
    fn test_filemap_capacity_check() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        // Create a deep directory structure to verify FileMap capacity check.
        let name = XPathBuf::from(&[b'o'; 200][..]);
        setup_deep_directory_structure(&name, MAX_DEPTH).unwrap();

        // Save current working directory.
        let mut cwd = getcwd().map(XPathBuf::from).unwrap();

        // Construct the deep path string.
        for _ in 0..MAX_DEPTH {
            cwd.push(name.as_bytes());
        }

        let result = safe_canonicalize(Pid::this(), None, &cwd, FsFlags::empty(), None, None);

        // Clean up after the test.
        Command::new("rm").arg("-rf").arg("a").status().unwrap();

        // Assert the expected error.
        match result {
            Err(Errno::ENAMETOOLONG) => {} // Success
            Err(errno) => panic!("Expected ENAMETOOLONG, got {errno}"),
            Ok(_) => panic!("Expected ENAMETOOLONG, but succeeded"),
        }
    }

    #[test]
    fn test_safe_mkdir_all_single_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let base_fd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();

        let path = XPath::from_bytes(b"testdir");
        let result = safe_mkdir_all(&base_fd, path);
        assert!(result.is_ok(), "safe_mkdir_all failed: {result:?}");

        // Verify directory exists.
        assert!(tmp.path().join("testdir").is_dir());
    }

    #[test]
    fn test_safe_mkdir_all_nested_directories() {
        let tmp = tempfile::tempdir().unwrap();
        let base_fd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();

        let path = XPath::from_bytes(b"a/b/c/d");
        let result = safe_mkdir_all(&base_fd, path);
        assert!(result.is_ok(), "safe_mkdir_all failed: {result:?}");

        // Verify all directories exist.
        assert!(tmp.path().join("a").is_dir());
        assert!(tmp.path().join("a/b").is_dir());
        assert!(tmp.path().join("a/b/c").is_dir());
        assert!(tmp.path().join("a/b/c/d").is_dir());
    }

    #[test]
    fn test_safe_mkdir_all_rejects_dotdot() {
        let tmp = tempfile::tempdir().unwrap();
        let base_fd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();

        // Create a subdirectory first
        fs::create_dir(tmp.path().join("sub")).unwrap();

        // Try to escape using ".."
        let path = XPath::from_bytes(b"sub/../escape");
        let result = safe_mkdir_all(&base_fd, path);
        assert_eq!(
            result.unwrap_err(),
            Errno::EINVAL,
            "should reject '..' components"
        );
    }

    #[test]
    fn test_safe_mkdir_all_rejects_leading_dotdot() {
        let tmp = tempfile::tempdir().unwrap();
        let base_fd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();

        let path = XPath::from_bytes(b"../escape");
        let result = safe_mkdir_all(&base_fd, path);
        assert_eq!(
            result.unwrap_err(),
            Errno::EINVAL,
            "should reject leading '..'"
        );
    }

    #[test]
    fn test_safe_mkdir_all_existing_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let base_fd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();

        // Create directory manually.
        fs::create_dir(tmp.path().join("existing")).unwrap();

        // safe_mkdir_all should succeed even if directory exists.
        let path = XPath::from_bytes(b"existing");
        let result = safe_mkdir_all(&base_fd, path);
        assert!(result.is_ok(), "should succeed for existing directory");
    }

    #[test]
    fn test_safe_mkdir_all_partial_existing() {
        let tmp = tempfile::tempdir().unwrap();
        let base_fd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();

        // Create partial path.
        fs::create_dir_all(tmp.path().join("a/b")).unwrap();

        // Extend the path.
        let path = XPath::from_bytes(b"a/b/c/d");
        let result = safe_mkdir_all(&base_fd, path);
        assert!(result.is_ok(), "should succeed for partial existing path");
        assert!(tmp.path().join("a/b/c/d").is_dir());
    }

    #[test]
    fn test_safe_mkdir_all_symlink_attack_prevention() {
        let tmp = tempfile::tempdir().unwrap();
        let base_fd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();

        // Create a target directory outside the base.
        let outside = tempfile::tempdir().unwrap();

        // Create a symlink pointing outside.
        std::os::unix::fs::symlink(outside.path(), tmp.path().join("escape_link")).unwrap();

        // Try to create directories through the symlink.
        let path = XPath::from_bytes(b"escape_link/target");
        let result = safe_mkdir_all(&base_fd, path);

        // Should fail because O_NOFOLLOW + RESOLVE_NO_SYMLINKS prevents symlink traversal.
        assert_eq!(
            result.unwrap_err(),
            Errno::ENOTDIR,
            "should reject symlink traversal"
        );

        // Verify the target directory was NOT created outside.
        assert!(!outside.path().join("target").exists());
    }

    #[test]
    fn test_safe_mkdir_all_empty_path() {
        let tmp = tempfile::tempdir().unwrap();
        let base_fd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();

        // Empty path should succeed (no-op).
        let path = XPath::from_bytes(b"");
        let result = safe_mkdir_all(&base_fd, path);
        assert!(result.is_ok(), "empty path should be a no-op");
    }

    #[test]
    fn test_safe_mkdir_all_dot_only() {
        let tmp = tempfile::tempdir().unwrap();
        let base_fd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();

        // Path with only "." components should succeed (no-op).
        let path = XPath::from_bytes(b"./././.");
        let result = safe_mkdir_all(&base_fd, path);
        assert!(result.is_ok(), "'.' components should be skipped");
    }

    #[test]
    fn test_safe_mkdir_all_mixed_dot_components() {
        let tmp = tempfile::tempdir().unwrap();
        let base_fd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();

        // Path with mixed "." and real components.
        let path = XPath::from_bytes(b"./a/./b/./c");
        let result = safe_mkdir_all(&base_fd, path);
        assert!(result.is_ok(), "should handle mixed '.' components");
        assert!(tmp.path().join("a/b/c").is_dir());
    }

    #[test]
    fn test_safe_mkdir_all_trailing_slashes() {
        let tmp = tempfile::tempdir().unwrap();
        let base_fd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();

        let path = XPath::from_bytes(b"a/b/c/");
        let result = safe_mkdir_all(&base_fd, path);
        assert!(result.is_ok(), "trailing slash should be handled");
        assert!(tmp.path().join("a/b/c").is_dir());
    }

    #[test]
    fn test_safe_mkdir_all_multiple_slashes() {
        let tmp = tempfile::tempdir().unwrap();
        let base_fd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();

        let path = XPath::from_bytes(b"a//b///c");
        let result = safe_mkdir_all(&base_fd, path);
        assert!(result.is_ok(), "multiple slashes should be handled");
        assert!(tmp.path().join("a/b/c").is_dir());
    }

    #[test]
    fn test_safe_mkdir_all_file_exists_error() {
        let tmp = tempfile::tempdir().unwrap();
        let base_fd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();

        // Create a regular file.
        fs::write(tmp.path().join("file"), b"content").unwrap();

        // Try to create directory at path with file component.
        let path = XPath::from_bytes(b"file/subdir");
        let result = safe_mkdir_all(&base_fd, path);

        // Should fail because "file" is not a directory.
        assert_eq!(
            result.unwrap_err(),
            Errno::ENOTDIR,
            "should fail when path component is a file"
        );
    }

    fn test_sandbox() -> Sandbox {
        let mut sb = Sandbox::default();
        sb.config("allow/lpath+/***").unwrap();
        sb.flags.clear();
        sb
    }

    // Empty path always yields ENOENT regardless of flags.
    #[test]
    fn test_canonicalize_1() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b""),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b""),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b""),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b""),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b""),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b""),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");
    }

    // Repeated root slashes collapse to `/`.
    #[test]
    fn test_canonicalize_2() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let root = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"//"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(root.abs.as_bytes(), b"/");
        assert_eq!(root.typ, Some(FileType::Dir));
    }

    // Redundant interior slashes are normalized away.
    #[test]
    fn test_canonicalize_3() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let result_test = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap()
        .abs;
        let paths = vec![
            "/etc/passwd",
            "/etc//passwd",
            "/etc///passwd",
            "//etc/passwd",
            "//etc//passwd",
            "//etc///passwd",
            "///etc/passwd",
            "///etc//passwd",
            "///etc///passwd",
        ];
        for path in &paths {
            let path = XPathBuf::from(path.to_string());
            let result = safe_canonicalize(
                Pid::this(),
                None,
                &path.deref(),
                FsFlags::empty(),
                None,
                Some(&sandbox),
            )
            .unwrap()
            .abs;
            assert_eq!(result, result_test);
        }
    }

    // Relative and absolute paths with `.` and `..` produce identical canonical forms.
    #[test]
    fn test_canonicalize_4() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let cwd = XPathBuf::from(std::env::current_dir().unwrap());
        let (tmp, _tmp_guard) = tempdir().unwrap();

        let path = xpath!("{tmp}//./..//{tmp}/test");
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{path}->{result:?}");
        let result1 = result.unwrap().abs;
        let path = xpath!("{cwd}/{tmp}//./..//{tmp}/test");
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{path}->{result:?}");
        let result2 = result.unwrap().abs;

        assert!(!result1.is_empty(), "result:{result1}");
        assert!(!result2.is_empty(), "result:{result2}");
        assert_eq!(result1, result2);
    }

    // Trailing slash on a regular file is tolerated by the canonicalizer.
    #[test]
    fn test_canonicalize_5() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let (path, _tmp_guard) = tempdir().unwrap();
        let test = xpath!("{path}/test/");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &test.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOTDIR)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &test.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOTDIR)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &test.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &test.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOTDIR)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &test.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOTDIR)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &test.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // Traversal through a missing directory yields ENOENT.
    #[test]
    fn test_canonicalize_6() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/zzz/.."),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/zzz/.."),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/zzz/.."),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/zzz/.."),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");
    }

    // Relative symlink target resolution follows standard POSIX semantics.
    #[test]
    fn test_canonicalize_7() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        // Setup
        let sandbox = test_sandbox();
        let root_test_dir = &XPath::from_bytes(b"test_root_relative_symlink_resolution");
        let deep_dir = join_path(&root_test_dir.to_owned(), b"a/b/c");
        let _ = remove_dir_all(&root_test_dir);
        fs::create_dir_all(&root_test_dir.join(b"d")).unwrap();
        fs::create_dir_all(&deep_dir).unwrap();

        // Create a symlink in "b" that points upwards to "a"
        let rel_link = join_path(&root_test_dir.to_owned(), b"a/b/rel_link");
        symlink("../..", &rel_link).unwrap();

        // Append /proc/self/cwd to get an absolute path to our symlinked path
        let abs_link_path = &join_path(
            &XPathBuf::from("/proc/self/cwd"),
            join_path(&root_test_dir.to_owned(), b"a/b/rel_link/d").as_bytes(),
        );

        // Call canonicalize
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &abs_link_path.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(
            result.is_ok(),
            "canonicalize:{abs_link_path} result:{result:?}",
        );
        let resolved_path = result.unwrap().abs;

        // We expect the path to be resolved to "test_root/a/d", but we need to canonicalize it
        let expected_path = fs::canonicalize(&join_path(
            &XPath::from_bytes(b"/proc/self/cwd"),
            root_test_dir.join(b"d").as_bytes(),
        ))
        .unwrap();

        // Cleanup:
        // remove_dir_all cannot remove a directory tree
        // if it spots a symbolic link loop unlike `rm -rf`.
        // let _ = remove_dir_all(&root_test_dir);
        Command::new("/bin/rm")
            .arg("-rf")
            .arg(&root_test_dir)
            .status()
            .expect("rm -rf tmpdir");

        assert_eq!(resolved_path, XPathBuf::from(expected_path));
    }

    // Trailing slash on a directory preserves the slash in output.
    #[test]
    fn test_canonicalize_8() {
        let sandbox = test_sandbox();

        // Spawn a new process which will inherit the fds.
        // Note we cannot use the current process here,
        // as XPath::check will think it's Syd and deny
        // access.
        let child = match unsafe { fork() } {
            Ok(ForkResult::Parent { child }) => child,
            Ok(ForkResult::Child) => {
                pause();
                exit(127);
            }
            Err(errno) => exit(errno as i32),
        };

        let test_guard = setup();
        if test_guard.is_none() {
            kill(child, Signal::SIGKILL).unwrap();
            waitpid(child, None).unwrap();
            return;
        }

        let path = XPath::from_bytes(b"/usr/");
        let pexp = path;
        let path =
            safe_canonicalize(child, None, &path, FsFlags::empty(), None, Some(&sandbox)).unwrap();
        assert_eq!(pexp, path.abs.deref(), "{pexp} != {path:?}");

        let parg = XPath::from_bytes(b"/proc/self/");
        let pexp = xpath!("/proc/{child}/");

        let path =
            safe_canonicalize(child, None, &parg, FsFlags::empty(), None, Some(&sandbox)).unwrap();
        assert_eq!(path.abs, pexp, "{pexp} != {path:?}");

        let path = safe_canonicalize(
            child,
            None,
            &parg,
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, pexp, "{pexp} != {path:?}");

        kill(child, Signal::SIGKILL).unwrap();
        waitpid(child, None).unwrap();
    }

    // Canonicalization does not update atime of the target file.
    #[test]
    fn test_canonicalize_9() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let cdir = XPathBuf::from(std::env::current_dir().unwrap());
        let (tmp_name, _tmp_guard) = tempdir().unwrap();
        let base = cdir.join(tmp_name.as_bytes());
        let path = base.join(b"file");
        fs::File::create(&path).unwrap();

        assert_atime_unchanged(&path, || {
            safe_canonicalize(
                Pid::this(),
                None,
                &path.deref(),
                FsFlags::empty(),
                None,
                Some(&sandbox),
            )
        });

        let _ = remove_dir_all(&base);
    }

    // Canonicalization does not update atime under MUST_PATH.
    #[test]
    fn test_canonicalize_10() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let cdir = XPathBuf::from(std::env::current_dir().unwrap());
        let (tmp_name, _tmp_guard) = tempdir().unwrap();
        let base = cdir.join(&tmp_name.as_bytes());
        let path = base.join(b"file");
        fs::File::create(&path).unwrap();

        assert_atime_unchanged(&path, || {
            safe_canonicalize(
                Pid::this(),
                None,
                &path.deref(),
                FsFlags::MUST_PATH,
                None,
                Some(&sandbox),
            )
        });

        let _ = remove_dir_all(&base);
    }

    // Two-element symlink loop yields ELOOP when followed.
    #[test]
    fn test_canonicalize_11() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let tmp_dir = tempfile::Builder::new()
            .disable_cleanup(true)
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .expect("Failed to create temp dir");
        let dir_path = XPathBuf::from(tmp_dir.path().to_path_buf());

        // Create a symlink loop: link_a -> link_b -> link_a
        let mut link_a = dir_path.join(b"link_a");
        let mut link_b = dir_path.join(b"link_b");
        symlink(&link_b, &link_a).expect("Failed to create symlink a");
        symlink(&link_a, &link_b).expect("Failed to create symlink b");

        // Now check that canonicalize detects the loop correctly
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link_a.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link_a.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link_a.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link_a.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link_a.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link_a.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        // Add a trailing slash and retest.
        link_a.push(b"");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link_a.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link_a.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        // Add a trailing slash and retest.
        link_b.push(b"");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link_b.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link_b.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // Symlink to nonexistent target yields ENOENT under MUST_PATH.
    #[test]
    fn test_canonicalize_12() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let tmp_dir = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .expect("Failed to create temp dir");
        let dir_path = XPathBuf::from(tmp_dir.path().to_path_buf());

        // Create a valid symlink to a non-existent final component
        let mut valid_link = dir_path.join(b"valid_link");
        let nonexistent_target = dir_path.join(b"nonexistent");
        symlink(&nonexistent_target, &valid_link)
            .expect("Failed to create symlink to non-existent target");

        // Now check that canonicalize handles the non-existent final component correctly.
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &valid_link.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &valid_link.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &valid_link.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &valid_link.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &valid_link.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &valid_link.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");

        // Add a trailing slash and retest.
        valid_link.push(b"");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &valid_link.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &valid_link.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
    }

    // Self-referential symlink yields ELOOP when followed.
    #[test]
    fn test_canonicalize_13() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let tmp_dir = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .expect("Failed to create temp dir");
        let dir_path = XPathBuf::from(tmp_dir.path().to_path_buf());
        let mut symlink_path = dir_path.join(b"self_link");
        symlink(symlink_path.as_path(), symlink_path.as_path())
            .expect("Failed to create self-referential symlink");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &symlink_path.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &symlink_path.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &symlink_path.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &symlink_path.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &symlink_path.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &symlink_path.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        // Add a trailing slash and retest.
        symlink_path.push(b"");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &symlink_path.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &symlink_path.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // Broken symlink is tolerated without MUST_PATH.
    #[test]
    fn test_canonicalize_14() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let tmp_dir = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .expect("Failed to create temp dir");
        let dir_path = XPathBuf::from(tmp_dir.path().to_path_buf());
        let mut broken_link = dir_path.join(b"broken_link");
        let nonexistent_target = dir_path.join(b"nonexistent_target");
        symlink(nonexistent_target.as_path(), broken_link.as_path())
            .expect("Failed to create broken symlink");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &broken_link.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &broken_link.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &broken_link.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &broken_link.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &broken_link.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &broken_link.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");

        // Add a trailing slash and retest.
        broken_link.push(b"");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &broken_link.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &broken_link.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
    }

    // Symlink to directory resolves to Dir type when followed.
    #[test]
    fn test_canonicalize_15() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let tmp_dir = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .expect("Failed to create temp dir");
        let tmp_path = XPathBuf::from(tmp_dir.path().to_path_buf());
        let dir = tmp_path.join(b"dir");
        fs::create_dir(&dir).expect("Failed to create directory");

        let symlink_path = tmp_path.join(b"dir_link");
        symlink(dir.as_path(), symlink_path.as_path())
            .expect("Failed to create symlink to directory");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &symlink_path.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &symlink_path.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(result.as_ref().unwrap().typ.unwrap().is_dir(), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &symlink_path.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &symlink_path.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(result.as_ref().unwrap().typ.unwrap().is_dir(), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &symlink_path.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &symlink_path.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // Three-element chain resolves to final target when followed.
    #[test]
    fn test_canonicalize_16() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let tmp_dir = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .expect("Failed to create temp dir");
        let dir_path = XPathBuf::from(tmp_dir.path().to_path_buf());
        let link1 = dir_path.join(b"link1");
        let link2 = dir_path.join(b"link2");
        let link3 = dir_path.join(b"link3");
        let file = dir_path.join(b"file");
        fs::write(file.as_path(), "content").expect("Failed to write file");

        // Create a chain of symlinks: link1 -> link2 -> link3 -> file
        symlink(link2.as_path(), link1.as_path()).expect("Failed to create link1");
        symlink(link3.as_path(), link2.as_path()).expect("Failed to create link2");
        symlink(file.as_path(), link3.as_path()).expect("Failed to create link3");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link1.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link1.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_file(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link1.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link1.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_file(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link1.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link1.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // Complex symlink loop with intermediate components yields ELOOP.
    #[test]
    fn test_canonicalize_17() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let tmp_dir = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .expect("Failed to create temp dir");
        let dir_path = XPathBuf::from(tmp_dir.path().to_path_buf());

        // Setting up a complex symlink scenario.
        setup_symlink_loop(
            &dir_path.deref(),
            &[("a", "b/c"), ("b/c", "d"), ("b/d", "../e"), ("e", "f/../a")],
        );

        let mut path = dir_path.join(b"a");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        // Add a trailing slash and retest.
        path.push(b"");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        // Add a final component and retest.
        path.push(b"foo");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // Symlinks containing `.` and `..` in targets resolve correctly.
    #[test]
    fn test_canonicalize_18() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let tmp_dir = tempfile::Builder::new()
            .disable_cleanup(true)
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .expect("Failed to create temp dir");

        // Create a complex directory structure with dots and symlinks.
        fs::create_dir_all(tmp_dir.path().join("b")).expect("Failed to create directory b");
        symlink("b", tmp_dir.path().join("a")).expect("Failed to create symlink a -> b");
        symlink("..///e", tmp_dir.path().join("b").join("d"))
            .expect("Failed to create symlink b/d -> ../e");
        symlink("b/.///./d", tmp_dir.path().join("e")).expect("Failed to create symlink e -> b/d");

        let mut path = XPathBuf::from(tmp_dir.path().join("a").join(".").join("d"));

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{path}->{result:?}");
        let result = result.unwrap();
        assert!(result.abs.exists(false), "{path}->{result:?}");
        assert!(!result.abs.exists(true), "{path}->{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{path}->{result:?}");
        let result = result.unwrap();
        assert!(result.abs.exists(false), "{path}->{result:?}");
        assert!(!result.abs.exists(true), "{path}->{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        // Add a trailing slash and retest.
        path.push(b"");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        // Add a final component and retest.
        path.push(b"foo");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // `/proc/self` resolves as a magic symlink to the process PID.
    #[test]
    fn test_canonicalize_19() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let pid = Pid::this();
        let path = safe_canonicalize(
            pid,
            None,
            &XPath::from_bytes(b"/proc/self"),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .expect("canonicalize /proc/self");
        assert!(
            path.typ
                .as_ref()
                .map(|typ| typ.is_symlink())
                .unwrap_or(false),
            "path:{path:?}"
        );
        assert_eq!(
            path.abs.deref(),
            XPath::from_bytes(b"/proc/self"),
            "path:{path:?}"
        );
        match path.typ {
            Some(FileType::Lnk) => {}
            _ => panic!("path:{path:?}"),
        }
    }

    // `/proc/self/fd/N` resolves existing file descriptors.
    #[test]
    fn test_canonicalize_20() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        // We cannot assume the FDs {0,1,2} are open here.
        let sandbox = test_sandbox();
        let fd = open("/dev/null", OFlag::O_RDONLY, Mode::empty()).unwrap();
        let fd = xpath!("/proc/self/fd/{}", fd.as_raw_fd());
        let pid = Pid::this();

        let result = safe_canonicalize(
            pid,
            None,
            &fd.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");

        let result = safe_canonicalize(
            pid,
            None,
            &fd.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");

        let result = safe_canonicalize(
            pid,
            None,
            &fd.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // Pipe file descriptors resolve through child process `/proc`.
    #[test]
    fn test_canonicalize_21() {
        let sandbox = test_sandbox();

        // Create a socket pair.
        let (read_end, write_end) = UnixStream::pair().unwrap();

        // Spawn a new process which will inherit the fds.
        // Note we cannot use the current process here,
        // as XPath::check will think it's Syd and deny
        // access.
        let child = match unsafe { fork() } {
            Ok(ForkResult::Parent { child }) => child,
            Ok(ForkResult::Child) => {
                pause();
                exit(127);
            }
            Err(errno) => exit(errno as i32),
        };

        let test_guard = setup();
        if test_guard.is_none() {
            kill(child, Signal::SIGKILL).unwrap();
            waitpid(child, None).unwrap();
            return;
        }

        // Wait for the child's /proc entry to become accessible.
        let child_proc = xpath!("/proc/{child}/fd");
        for _ in 0..100 {
            if child_proc.deref().exists(true) {
                break;
            }
            sleep(Duration::from_millis(10));
        }

        let fd = read_end.as_raw_fd();
        let path = xpath!("/proc/{child}/fd/{fd}");
        let result = safe_canonicalize(
            child,
            None,
            &path.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{path}->{result:?}");

        let fd = write_end.as_raw_fd();
        let path = xpath!("/proc/{child}/fd/{fd}");
        let result = safe_canonicalize(
            child,
            None,
            &path.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{path}->{result:?}");

        kill(child, Signal::SIGKILL).unwrap();
        waitpid(child, None).unwrap();
    }

    // CanonicalPath fields are correctly set for various path types and flags.
    #[test]
    fn test_canonicalize_22() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();

        // Case 1: Regular file
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.dir.is_some());
        assert!(path.base().is_empty());
        assert_eq!(path.base_offset, 0);

        // Case 2: Root path
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.dir.is_none(), "{path:?}");
        assert!(path.base().is_empty(), "{path:?}");
        assert_eq!(path.base_offset, 0, "{path:?}");

        // Case 3: Directory with trailing slash
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.dir.is_some());
        assert!(path.base().is_empty());
        assert_eq!(path.base_offset, 0);

        // Case 4: MISS_LAST with non-existent final component.
        let cwd = XPathBuf::from(std::env::current_dir().unwrap());
        let (tmp, _tmp_guard) = tempdir().unwrap();
        let missing = xpath!("{cwd}/{tmp}/nonexistent");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &missing.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.base_offset > 0, "{}", path.base_offset);
        assert_eq!(path.base_offset, path.abs().len() - b"nonexistent".len());
        assert_eq!(path.base().as_bytes(), b"nonexistent");

        // Case 5: MISS_LAST with trailing slash.
        let missing_dir = xpath!("{cwd}/{tmp}/newdir/");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &missing_dir.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.base_offset > 0, "{}", path.base_offset);
        assert_eq!(path.base_offset, path.abs().len() - b"newdir/".len());
        assert_eq!(path.base().as_bytes(), b"newdir/");

        // Case 6: Path with dotdot resolution.
        let dotdot_path = xpath!("{cwd}/{tmp}/../{tmp}/test");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &dotdot_path.deref(),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.base_offset > 0, "{}", path.base_offset);
        assert_eq!(path.base_offset, path.abs().len() - b"test".len());
        assert_eq!(path.base().as_bytes(), b"test");

        // Case 7: NO_FOLLOW_LAST | MISS_LAST with symlink.
        let link_src = xpath!("{cwd}/{tmp}/link_src");
        let link_dst = xpath!("{cwd}/{tmp}/link_dst");
        symlink(&link_dst, &link_src).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link_src.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );
    }

    // RESOLVE_BENEATH rejects absolute paths with EXDEV.
    #[test]
    fn test_canonicalize_23() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // Parent traversal at root is clamped to root itself.
    #[test]
    fn test_canonicalize_24() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/.."),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        let path = result.unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // Dot-only path `.` resolves to the current working directory.
    #[test]
    fn test_canonicalize_25() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let cwd = XPathBuf::from(std::env::current_dir().unwrap());
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"."),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        let path = result.unwrap();
        assert_eq!(path.abs, cwd, "{path:?}");
    }

    // `/dev/null` returns the static null device path.
    #[test]
    fn test_canonicalize_26() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/dev/null"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        let path = result.unwrap();
        assert_eq!(path.abs.as_bytes(), b"/dev/null");
    }

    // `/proc` returns the static procfs path.
    #[test]
    fn test_canonicalize_27() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        let path = result.unwrap();
        assert_eq!(path.abs.as_bytes(), b"/proc");
    }

    // NO_RESOLVE_DOTDOT forbids `..` traversal with EACCES.
    #[test]
    fn test_canonicalize_28() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/.."),
            FsFlags::NO_RESOLVE_DOTDOT,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EACCES)), "{result:?}");
    }

    // NO_RESOLVE_PATH rejects symlink resolution with ELOOP.
    #[test]
    fn test_canonicalize_29() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let tmp_dir = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .expect("Failed to create temp dir");
        let dir_path = XPathBuf::from(tmp_dir.path().to_path_buf());
        let link = dir_path.join(b"link");
        let target = dir_path.join(b"target");
        fs::write(target.as_path(), "content").unwrap();
        symlink(target.as_path(), link.as_path()).unwrap();

        let result = safe_canonicalize(
            Pid::this(),
            None,
            &link.deref(),
            FsFlags::NO_RESOLVE_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // WANT_BASE on a regular file correctly splits parent and base.
    #[test]
    fn test_canonicalize_30() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }

        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        let path = result.unwrap();
        assert!(path.dir.is_some(), "{path:?}");
        assert!(path.base_offset > 0, "{path:?}");
        assert_eq!(path.base().as_bytes(), b"passwd", "{path:?}");
    }

    // Root path with MUST_PATH returns `/` with Dir type.
    #[test]
    fn test_canonicalize_31() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
        assert_eq!(path.typ, Some(FileType::Dir));
        assert!(path.dir.is_none());
    }

    // Root with MISS_LAST still returns `/` since rootfs is handled before flag dispatch.
    #[test]
    fn test_canonicalize_32() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/"),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // Root with NO_FOLLOW_LAST returns `/`; root has no symlink to skip.
    #[test]
    fn test_canonicalize_33() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/"),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // Root with WANT_BASE has base_offset 0 and empty base.
    #[test]
    fn test_canonicalize_34() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/"),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base_offset, 0);
        assert!(path.base().is_empty());
    }

    // Root with NO_FOLLOW_LAST|MUST_PATH returns `/`.
    #[test]
    fn test_canonicalize_35() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/"),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // Root with NO_FOLLOW_LAST|MISS_LAST returns `/`.
    #[test]
    fn test_canonicalize_36() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/"),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // Root with NO_RESOLVE_PATH passes since `/` has no symlink components.
    #[test]
    fn test_canonicalize_37() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/"),
            FsFlags::NO_RESOLVE_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // Root with NO_RESOLVE_DOTDOT passes since `/` has no dotdot.
    #[test]
    fn test_canonicalize_38() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/"),
            FsFlags::NO_RESOLVE_DOTDOT,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // Root with RESOLVE_BENEATH yields EXDEV because absolute paths are rejected.
    #[test]
    fn test_canonicalize_39() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // Double-slash `//` normalizes to `/`.
    #[test]
    fn test_canonicalize_40() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"//"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // Triple-slash `///` normalizes to `/`.
    #[test]
    fn test_canonicalize_41() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"///"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `/.` normalizes to `/` since dot is stripped.
    #[test]
    fn test_canonicalize_42() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/."),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `/.` with MUST_PATH normalizes to `/`.
    #[test]
    fn test_canonicalize_43() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/."),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `/..` is clamped to `/` since parent of root is root.
    #[test]
    fn test_canonicalize_44() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/.."),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `/../..` double-dotdot at root stays clamped to `/`.
    #[test]
    fn test_canonicalize_45() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/../.."),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `/..` with NO_RESOLVE_DOTDOT yields EACCES.
    #[test]
    fn test_canonicalize_46() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/.."),
            FsFlags::NO_RESOLVE_DOTDOT,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EACCES)), "{result:?}");
    }

    // `/../..` with NO_RESOLVE_DOTDOT rejects on the first dotdot.
    #[test]
    fn test_canonicalize_47() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/../.."),
            FsFlags::NO_RESOLVE_DOTDOT,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EACCES)), "{result:?}");
    }

    // `/etc/..` resolves back to `/`.
    #[test]
    fn test_canonicalize_48() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/.."),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `/etc/..` with MUST_PATH resolves to `/`.
    #[test]
    fn test_canonicalize_49() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/.."),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `/etc/..` with NO_RESOLVE_DOTDOT yields EACCES.
    #[test]
    fn test_canonicalize_50() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/.."),
            FsFlags::NO_RESOLVE_DOTDOT,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EACCES)), "{result:?}");
    }

    // `/etc/../etc/passwd` dotdot-then-descend resolves to `/etc/passwd`.
    #[test]
    fn test_canonicalize_51() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/../etc/passwd"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // `/etc/../etc/passwd` with MUST_PATH.
    #[test]
    fn test_canonicalize_52() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/../etc/passwd"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // `/etc/../etc/passwd` with NO_RESOLVE_DOTDOT fails on the dotdot.
    #[test]
    fn test_canonicalize_53() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/../etc/passwd"),
            FsFlags::NO_RESOLVE_DOTDOT,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EACCES)), "{result:?}");
    }

    // `/etc/./passwd` dot-component in middle resolves to `/etc/passwd`.
    #[test]
    fn test_canonicalize_54() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/./passwd"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // `/etc/./passwd` with MUST_PATH.
    #[test]
    fn test_canonicalize_55() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/./passwd"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // `/etc//passwd` duplicate slash normalizes to `/etc/passwd`.
    #[test]
    fn test_canonicalize_56() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc//passwd"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // `///etc///passwd` multiple slashes normalize to `/etc/passwd`.
    #[test]
    fn test_canonicalize_57() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"///etc///passwd"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // `/etc/passwd` with empty flags returns a regular file.
    #[test]
    fn test_canonicalize_58() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
        assert!(path.dir.is_some());
    }

    // `/etc/passwd` with MUST_PATH succeeds because the file exists.
    #[test]
    fn test_canonicalize_59() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // `/etc/passwd` with MISS_LAST tolerates existing last component.
    #[test]
    fn test_canonicalize_60() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // `/etc/passwd` with NO_FOLLOW_LAST succeeds; passwd is not a symlink.
    #[test]
    fn test_canonicalize_61() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // `/etc/passwd` with NO_FOLLOW_LAST|MUST_PATH.
    #[test]
    fn test_canonicalize_62() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
    }

    // `/etc/passwd` with NO_FOLLOW_LAST|MISS_LAST.
    #[test]
    fn test_canonicalize_63() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // `/etc/passwd` with WANT_BASE splits base="passwd".
    #[test]
    fn test_canonicalize_64() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.base_offset > 0);
        assert_eq!(path.base().as_bytes(), b"passwd");
    }

    // `/etc/passwd` with WANT_BASE|MUST_PATH splits base="passwd".
    #[test]
    fn test_canonicalize_65() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::WANT_BASE | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"passwd");
    }

    // `/etc/passwd` with NO_RESOLVE_DOTDOT passes since no dotdot in path.
    #[test]
    fn test_canonicalize_66() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::NO_RESOLVE_DOTDOT,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
    }

    // `/etc/passwd` with NO_RESOLVE_PATH passes since no symlinks in path.
    #[test]
    fn test_canonicalize_67() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::NO_RESOLVE_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
    }

    // `/etc/passwd` with RESOLVE_BENEATH rejects absolute path.
    #[test]
    fn test_canonicalize_68() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/etc` directory with empty flags.
    #[test]
    fn test_canonicalize_69() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc");
    }

    // `/etc` with MUST_PATH.
    #[test]
    fn test_canonicalize_70() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc");
    }

    // `/etc` with WANT_BASE splits dir and base="etc".
    #[test]
    fn test_canonicalize_71() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc"),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"etc");
        assert!(path.dir.is_some());
    }

    // `/etc/` trailing slash on directory is preserved.
    #[test]
    fn test_canonicalize_72() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/");
    }

    // `/etc/` with MUST_PATH preserves trailing slash.
    #[test]
    fn test_canonicalize_73() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/");
    }

    // `/etc/` with RESOLVE_BENEATH rejects.
    #[test]
    fn test_canonicalize_74() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/usr/bin` nested directory resolves correctly.
    #[test]
    fn test_canonicalize_75() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/usr/bin"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.abs.as_bytes().starts_with(b"/usr"));
    }

    // `/usr/bin` with MUST_PATH.
    #[test]
    fn test_canonicalize_76() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/usr/bin"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
    }

    // `/usr/bin` with WANT_BASE gives base="bin".
    #[test]
    fn test_canonicalize_77() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/usr/bin"),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"bin");
    }

    // `/dev/null` resolves to static `/dev/null` path.
    #[test]
    fn test_canonicalize_78() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/dev/null"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/dev/null");
    }

    // `/dev/null` with NO_FOLLOW_LAST.
    #[test]
    fn test_canonicalize_79() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/dev/null"),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/dev/null");
    }

    // `/dev/null` with MISS_LAST.
    #[test]
    fn test_canonicalize_80() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/dev/null"),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // `/dev/null` with RESOLVE_BENEATH fails.
    #[test]
    fn test_canonicalize_81() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/dev/null"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/proc` resolves to static `/proc` path.
    #[test]
    fn test_canonicalize_82() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/proc");
    }

    // `/proc` with NO_FOLLOW_LAST.
    #[test]
    fn test_canonicalize_83() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc"),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/proc");
    }

    // `/proc` with MISS_LAST.
    #[test]
    fn test_canonicalize_84() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc"),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // `/proc` with RESOLVE_BENEATH fails.
    #[test]
    fn test_canonicalize_85() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `.` resolves to CWD.
    #[test]
    fn test_canonicalize_86() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let cwd = XPathBuf::from(std::env::current_dir().unwrap());
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"."),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, cwd);
    }

    // `.` with WANT_BASE splits CWD correctly.
    #[test]
    fn test_canonicalize_87() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"."),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
    }

    // `..` resolves to parent of CWD.
    #[test]
    fn test_canonicalize_88() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b".."),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
    }

    // `..` with MUST_PATH.
    #[test]
    fn test_canonicalize_89() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b".."),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
    }

    // `/nonexistent` with MUST_PATH yields ENOENT.
    #[test]
    fn test_canonicalize_90() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/nonexistent"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");
    }

    // `/nonexistent` with empty flags tolerates missing last component.
    #[test]
    fn test_canonicalize_91() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/nonexistent"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/nonexistent");
        assert_eq!(path.typ, None);
    }

    // `/nonexistent` with MISS_LAST.
    #[test]
    fn test_canonicalize_92() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/nonexistent"),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/nonexistent");
    }

    // `/nonexistent` with MISS_LAST has base="nonexistent".
    #[test]
    fn test_canonicalize_93() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/nonexistent"),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.base_offset > 0);
        assert_eq!(path.base().as_bytes(), b"nonexistent");
    }

    // `/nonexistent` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_94() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/nonexistent"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/nonexistent/foo` with MUST_PATH fails because intermediate is missing.
    #[test]
    fn test_canonicalize_95() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/nonexistent/foo"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");
    }

    // `/nonexistent/foo` with MISS_LAST fails because intermediate is also missing.
    #[test]
    fn test_canonicalize_96() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/nonexistent/foo"),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");
    }

    // `/nonexistent/foo` with empty flags fails on missing intermediate.
    #[test]
    fn test_canonicalize_97() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/nonexistent/foo"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");
    }

    // Empty path with MISS_LAST still yields ENOENT.
    #[test]
    fn test_canonicalize_98() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b""),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");
    }

    // Empty path with WANT_BASE still yields ENOENT.
    #[test]
    fn test_canonicalize_99() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b""),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");
    }

    // MISS_LAST on tempdir's nonexistent child correctly splits base.
    #[test]
    fn test_canonicalize_100() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let missing = dir.join(b"missing_child");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &missing.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"missing_child");
    }

    // MISS_LAST with trailing slash on nonexistent child preserves slash.
    #[test]
    fn test_canonicalize_101() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let missing = dir.join(b"newdir/");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &missing.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"newdir/");
    }

    // WANT_BASE on existing tempdir file splits correctly.
    #[test]
    fn test_canonicalize_102() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let file = dir.join(b"myfile");
        fs::write(file.as_path(), "data").unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &file.deref(),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"myfile");
        assert!(path.dir.is_some());
    }

    // Symlink to file: following resolves to target with File type.
    #[test]
    fn test_canonicalize_103() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"target");
        fs::write(tgt.as_path(), "x").unwrap();
        let lnk = dir.join(b"link");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, tgt);
        assert!(path.typ.unwrap().is_file());
    }

    // Symlink to file with MUST_PATH: resolves to target.
    #[test]
    fn test_canonicalize_104() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"target");
        fs::write(tgt.as_path(), "x").unwrap();
        let lnk = dir.join(b"link");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, tgt);
    }

    // Symlink to file with NO_FOLLOW_LAST: returns symlink itself with Lnk type.
    #[test]
    fn test_canonicalize_105() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"target");
        fs::write(tgt.as_path(), "x").unwrap();
        let lnk = dir.join(b"link");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, lnk);
        assert!(path.typ.unwrap().is_symlink());
    }

    // Symlink to file with NO_FOLLOW_LAST|MUST_PATH.
    #[test]
    fn test_canonicalize_106() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"target");
        fs::write(tgt.as_path(), "x").unwrap();
        let lnk = dir.join(b"link");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.typ.unwrap().is_symlink());
    }

    // Symlink to file with MISS_LAST.
    #[test]
    fn test_canonicalize_107() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"target");
        fs::write(tgt.as_path(), "x").unwrap();
        let lnk = dir.join(b"link");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // Symlink to file with NO_FOLLOW_LAST|MISS_LAST.
    #[test]
    fn test_canonicalize_108() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"target");
        fs::write(tgt.as_path(), "x").unwrap();
        let lnk = dir.join(b"link");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );
    }

    // Symlink to file with WANT_BASE: base is the link name when not following.
    #[test]
    fn test_canonicalize_109() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"target");
        fs::write(tgt.as_path(), "x").unwrap();
        let lnk = dir.join(b"link");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.base_offset > 0);
    }

    // Symlink to file with NO_RESOLVE_PATH is rejected with ELOOP.
    #[test]
    fn test_canonicalize_110() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"target");
        fs::write(tgt.as_path(), "x").unwrap();
        let lnk = dir.join(b"link");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_RESOLVE_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // Symlink to directory: following resolves to dir with Dir type.
    #[test]
    fn test_canonicalize_111() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"mydir");
        fs::create_dir(&tgt).unwrap();
        let lnk = dir.join(b"dirlink");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, tgt);
        assert!(path.typ.unwrap().is_dir());
    }

    // Symlink to directory with NO_FOLLOW_LAST returns Lnk type.
    #[test]
    fn test_canonicalize_112() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"mydir");
        fs::create_dir(&tgt).unwrap();
        let lnk = dir.join(b"dirlink");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.typ.unwrap().is_symlink());
    }

    // Symlink to directory with MUST_PATH resolves to Dir.
    #[test]
    fn test_canonicalize_113() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"mydir");
        fs::create_dir(&tgt).unwrap();
        let lnk = dir.join(b"dirlink");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.typ.unwrap().is_dir());
    }

    // Broken symlink with empty flags is tolerated.
    #[test]
    fn test_canonicalize_114() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"broken");
        let noexist = dir.join(b"noexist");
        symlink(noexist.as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, noexist);
        assert_eq!(path.typ, None);
    }

    // Broken symlink with MUST_PATH yields ENOENT.
    #[test]
    fn test_canonicalize_115() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"broken");
        symlink(dir.join(b"noexist").as_path(), lnk.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");
    }

    // Broken symlink with NO_FOLLOW_LAST returns the link itself.
    #[test]
    fn test_canonicalize_116() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"broken");
        symlink(dir.join(b"noexist").as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.typ.unwrap().is_symlink());
    }

    // Broken symlink with NO_FOLLOW_LAST|MUST_PATH.
    #[test]
    fn test_canonicalize_117() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"broken");
        symlink(dir.join(b"noexist").as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, lnk);
        assert!(path.typ.unwrap().is_symlink());
    }

    // Broken symlink with MISS_LAST.
    #[test]
    fn test_canonicalize_118() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"broken");
        symlink(dir.join(b"noexist").as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        let noexist = dir.join(b"noexist");
        assert_eq!(path.abs, noexist);
    }

    // Broken symlink with NO_FOLLOW_LAST|MISS_LAST.
    #[test]
    fn test_canonicalize_119() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"broken");
        symlink(dir.join(b"noexist").as_path(), lnk.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );
    }

    // Self-referential symlink with empty flags yields ELOOP.
    #[test]
    fn test_canonicalize_120() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"self");
        symlink(lnk.as_path(), lnk.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // Self-referential symlink with MUST_PATH yields ELOOP.
    #[test]
    fn test_canonicalize_121() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"self");
        symlink(lnk.as_path(), lnk.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // Self-referential symlink with NO_FOLLOW_LAST succeeds.
    #[test]
    fn test_canonicalize_122() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"self");
        symlink(lnk.as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.typ.unwrap().is_symlink());
    }

    // Two-link loop: a -> b -> a with empty flags yields ELOOP.
    #[test]
    fn test_canonicalize_123() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let a = dir.join(b"a");
        let b = dir.join(b"b");
        symlink(b.as_path(), a.as_path()).unwrap();
        symlink(a.as_path(), b.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &a.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // Two-link loop with NO_FOLLOW_LAST succeeds returning the link.
    #[test]
    fn test_canonicalize_124() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let a = dir.join(b"a");
        let b = dir.join(b"b");
        symlink(b.as_path(), a.as_path()).unwrap();
        symlink(a.as_path(), b.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &a.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.typ.unwrap().is_symlink());
    }

    // Two-link loop with MUST_PATH yields ELOOP.
    #[test]
    fn test_canonicalize_125() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let a = dir.join(b"a");
        let b = dir.join(b"b");
        symlink(b.as_path(), a.as_path()).unwrap();
        symlink(a.as_path(), b.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &a.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // Three-link chain a -> b -> c -> file: following resolves to file.
    #[test]
    fn test_canonicalize_126() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let file = dir.join(b"file");
        fs::write(file.as_path(), "x").unwrap();
        let c = dir.join(b"c");
        symlink(file.as_path(), c.as_path()).unwrap();
        let b = dir.join(b"b");
        symlink(c.as_path(), b.as_path()).unwrap();
        let a = dir.join(b"a");
        symlink(b.as_path(), a.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &a.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, file);
        assert!(path.typ.unwrap().is_file());
    }

    // Three-link chain with NO_FOLLOW_LAST stops at first link.
    #[test]
    fn test_canonicalize_127() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let file = dir.join(b"file");
        fs::write(file.as_path(), "x").unwrap();
        let c = dir.join(b"c");
        symlink(file.as_path(), c.as_path()).unwrap();
        let b = dir.join(b"b");
        symlink(c.as_path(), b.as_path()).unwrap();
        let a = dir.join(b"a");
        symlink(b.as_path(), a.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &a.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.typ.unwrap().is_symlink());
        assert_eq!(path.abs, a);
    }

    // Symlink with relative target: link -> "target" (relative, same dir).
    #[test]
    fn test_canonicalize_128() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"target");
        fs::write(tgt.as_path(), "x").unwrap();
        symlink("target", dir.join(b"rellink").as_path()).unwrap();
        let lnk = dir.join(b"rellink");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, tgt);
    }

    // Symlink with relative target containing dotdot: "../sibling".
    #[test]
    fn test_canonicalize_129() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let subdir = dir.join(b"sub");
        fs::create_dir(&subdir).unwrap();
        let tgt = dir.join(b"sibling");
        fs::write(tgt.as_path(), "x").unwrap();
        // link in sub/ pointing to ../sibling
        symlink("../sibling", subdir.join(b"link").as_path()).unwrap();
        let lnk = subdir.join(b"link");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, tgt);
    }

    // Symlink in intermediate directory: dir_link -> real_dir, then access dir_link/file.
    #[test]
    fn test_canonicalize_130() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let real = dir.join(b"real");
        fs::create_dir(&real).unwrap();
        let file = real.join(b"file");
        fs::write(file.as_path(), "x").unwrap();
        let lnk = dir.join(b"dir_link");
        symlink(real.as_path(), lnk.as_path()).unwrap();
        let through = lnk.join(b"file");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &through.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, file);
    }

    // Symlink in intermediate dir with MUST_PATH.
    #[test]
    fn test_canonicalize_131() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let real = dir.join(b"real");
        fs::create_dir(&real).unwrap();
        let file = real.join(b"file");
        fs::write(file.as_path(), "x").unwrap();
        let lnk = dir.join(b"dir_link");
        symlink(real.as_path(), lnk.as_path()).unwrap();
        let through = lnk.join(b"file");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &through.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, file);
    }

    // Symlink in intermediate dir with NO_FOLLOW_LAST: intermediate is still resolved.
    #[test]
    fn test_canonicalize_132() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let real = dir.join(b"real");
        fs::create_dir(&real).unwrap();
        let file = real.join(b"file");
        fs::write(file.as_path(), "x").unwrap();
        let lnk = dir.join(b"dir_link");
        symlink(real.as_path(), lnk.as_path()).unwrap();
        let through = lnk.join(b"file");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &through.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, file);
    }

    // Symlink to /dev/null resolves to /dev/null.
    #[test]
    fn test_canonicalize_133() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"null_link");
        symlink("/dev/null", lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/dev/null");
    }

    // Symlink to / resolves to /.
    #[test]
    fn test_canonicalize_134() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"root_link");
        symlink("/", lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // Deep directory traversal.
    #[test]
    fn test_canonicalize_135() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let tfd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();
        let mut deep = Vec::new();
        while deep.len() < PATH_MAX {
            if !deep.is_empty() {
                deep.push(b'/');
            }
            deep.push(b'x');
        }
        let tfd = safe_mkdir_all(&tfd, XPath::from_bytes(&deep[..])).unwrap();
        openat(
            tfd,
            "file",
            OFlag::O_RDWR | OFlag::O_CREAT | OFlag::O_EXCL,
            Mode::from_bits_retain(0o600),
        )
        .map(drop)
        .unwrap();
        let mut tmp = tmp.path().to_path_buf();
        tmp.push(OsStr::from_bytes(&deep));
        tmp.push("file");
        let tmp = XPath::from_bytes(tmp.as_os_str().as_bytes());
        let path = safe_canonicalize(
            Pid::this(),
            None,
            tmp,
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), tmp.as_bytes());
    }

    // Deep directory with WANT_BASE: base is "file".
    #[test]
    fn test_canonicalize_136() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let tfd = open(
            tmp.path(),
            OFlag::O_PATH | OFlag::O_DIRECTORY,
            Mode::empty(),
        )
        .unwrap()
        .into();
        let mut deep = Vec::new();
        while deep.len() < PATH_MAX - 256 {
            if !deep.is_empty() {
                deep.push(b'/');
            }
            deep.push(b'x');
        }
        let tfd = safe_mkdir_all(&tfd, XPath::from_bytes(&deep[..])).unwrap();
        openat(
            tfd,
            "target",
            OFlag::O_RDWR | OFlag::O_CREAT | OFlag::O_EXCL,
            Mode::from_bits_retain(0o600),
        )
        .map(drop)
        .unwrap();
        let mut tmp = tmp.path().to_path_buf();
        tmp.push(OsStr::from_bytes(&deep));
        tmp.push("target");
        let tmp = XPath::from_bytes(tmp.as_os_str().as_bytes());
        let path = safe_canonicalize(
            Pid::this(),
            None,
            tmp,
            FsFlags::WANT_BASE | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"target");
    }

    // `/etc/./../../etc/passwd` complex normalization resolves to `/etc/passwd`.
    #[test]
    fn test_canonicalize_137() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/./../../etc/passwd"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // `//etc//.//..//etc//passwd` excessive syntax resolves to `/etc/passwd`.
    #[test]
    fn test_canonicalize_138() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"//etc//.//..//etc//passwd"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // `/etc/passwd` with WANT_BASE has dir.is_some().
    #[test]
    fn test_canonicalize_139() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/passwd"),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.dir.is_some());
        assert_eq!(path.base_offset, path.abs().len() - b"passwd".len());
    }

    // `/etc/` with WANT_BASE: trailing slash means base is empty.
    #[test]
    fn test_canonicalize_140() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/"),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.dir.is_some());
    }

    // `/etc` with MISS_LAST.
    #[test]
    fn test_canonicalize_141() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc"),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // `/etc` with NO_FOLLOW_LAST.
    #[test]
    fn test_canonicalize_142() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc"),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc");
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `/etc` with NO_FOLLOW_LAST|MUST_PATH.
    #[test]
    fn test_canonicalize_143() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc"),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc");
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `/etc` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_144() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/etc` with NO_RESOLVE_DOTDOT passes.
    #[test]
    fn test_canonicalize_145() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc"),
            FsFlags::NO_RESOLVE_DOTDOT,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc");
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `/etc` with NO_RESOLVE_PATH passes (no symlinks).
    #[test]
    fn test_canonicalize_146() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc"),
            FsFlags::NO_RESOLVE_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc");
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `/zzz/..` nonexistent then dotdot yields ENOENT.
    #[test]
    fn test_canonicalize_147() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/zzz/.."),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");
    }

    // `/zzz/..` with MUST_PATH yields ENOENT.
    #[test]
    fn test_canonicalize_148() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/zzz/.."),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");
    }

    // `/zzz/..` with NO_FOLLOW_LAST yields ENOENT.
    #[test]
    fn test_canonicalize_149() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/zzz/.."),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");
    }

    // `/zzz/..` with NO_FOLLOW_LAST|MUST_PATH yields ENOENT.
    #[test]
    fn test_canonicalize_150() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/zzz/.."),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");
    }

    // `/usr/` with empty flags preserves trailing slash.
    #[test]
    fn test_canonicalize_151() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/usr/"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/usr/");
    }

    // `/usr/` with MUST_PATH.
    #[test]
    fn test_canonicalize_152() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/usr/"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/usr/");
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `/tmp` with empty flags.
    #[test]
    fn test_canonicalize_153() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/tmp"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        // /tmp may be a symlink on some systems; just verify it resolves
        // to a directory.
        assert!(path.typ.unwrap().is_dir());
    }

    // `/tmp` with MUST_PATH.
    #[test]
    fn test_canonicalize_154() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/tmp"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.typ.unwrap().is_dir());
    }

    // `/proc/self` with NO_FOLLOW_LAST returns the magic symlink itself.
    #[test]
    fn test_canonicalize_155() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc/self"),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/proc/self");
        assert!(path.typ.unwrap().is_symlink());
    }

    // `/proc/self` with empty flags resolves to /proc/<pid>.
    #[test]
    fn test_canonicalize_156() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let pid = Pid::this();
        let path = safe_canonicalize(
            pid,
            None,
            &XPath::from_bytes(b"/proc/self"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        let expected = xpath!("/proc/{pid}");
        assert_eq!(path.abs, expected);
    }

    // `/proc/self` with MUST_PATH resolves to /proc/<pid>.
    #[test]
    fn test_canonicalize_157() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let pid = Pid::this();
        let path = safe_canonicalize(
            pid,
            None,
            &XPath::from_bytes(b"/proc/self"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        let expected = xpath!("/proc/{pid}");
        assert_eq!(path.abs, expected);
    }

    // `/proc/self` with NO_FOLLOW_LAST|MUST_PATH returns symlink.
    #[test]
    fn test_canonicalize_158() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc/self"),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/proc/self");
    }

    // `..` with NO_RESOLVE_DOTDOT yields EACCES.
    #[test]
    fn test_canonicalize_159() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b".."),
            FsFlags::NO_RESOLVE_DOTDOT,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EACCES)), "{result:?}");
    }

    // `.` with NO_RESOLVE_DOTDOT passes (no dotdot component).
    #[test]
    fn test_canonicalize_160() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"."),
            FsFlags::NO_RESOLVE_DOTDOT,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.abs.as_bytes().starts_with(b"/"));
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // Symlink to file with WANT_BASE|MUST_PATH.
    #[test]
    fn test_canonicalize_161() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"target");
        fs::write(tgt.as_path(), "x").unwrap();
        let lnk = dir.join(b"link");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::WANT_BASE | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.base_offset > 0);
    }

    // Symlink chain with WANT_BASE: base is final target name.
    #[test]
    fn test_canonicalize_162() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let file = dir.join(b"final");
        fs::write(file.as_path(), "x").unwrap();
        let b = dir.join(b"b");
        symlink(file.as_path(), b.as_path()).unwrap();
        let a = dir.join(b"a");
        symlink(b.as_path(), a.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &a.deref(),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"final");
    }

    // Symlink to dir with WANT_BASE.
    #[test]
    fn test_canonicalize_163() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"tdir");
        fs::create_dir(&tgt).unwrap();
        let lnk = dir.join(b"dlink");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.base_offset > 0);
    }

    // Broken symlink with WANT_BASE.
    #[test]
    fn test_canonicalize_164() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"broken");
        symlink(dir.join(b"noexist").as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"noexist");
        assert!(path.base_offset > 0);
    }

    // Symlink loop with MISS_LAST yields ELOOP.
    #[test]
    fn test_canonicalize_165() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let a = dir.join(b"a");
        let b = dir.join(b"b");
        symlink(b.as_path(), a.as_path()).unwrap();
        symlink(a.as_path(), b.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &a.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // Symlink loop with NO_FOLLOW_LAST|MISS_LAST succeeds.
    #[test]
    fn test_canonicalize_166() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let a = dir.join(b"a");
        let b = dir.join(b"b");
        symlink(b.as_path(), a.as_path()).unwrap();
        symlink(a.as_path(), b.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &a.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );
    }

    // Self-ref symlink with MISS_LAST yields ELOOP.
    #[test]
    fn test_canonicalize_167() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"self");
        symlink(lnk.as_path(), lnk.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // Self-ref symlink with NO_FOLLOW_LAST|MISS_LAST succeeds.
    #[test]
    fn test_canonicalize_168() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"self");
        symlink(lnk.as_path(), lnk.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );
    }

    // Self-ref symlink with NO_FOLLOW_LAST|MUST_PATH.
    #[test]
    fn test_canonicalize_169() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"self");
        symlink(lnk.as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, lnk);
        assert!(path.typ.unwrap().is_symlink());
    }

    // Dotdot-symlink: sub/up -> "..", access sub/up/file -> d/file.
    #[test]
    fn test_canonicalize_170() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let sub = dir.join(b"sub");
        fs::create_dir(&sub).unwrap();
        let file = dir.join(b"file");
        fs::write(file.as_path(), "x").unwrap();
        symlink("..", sub.join(b"up").as_path()).unwrap();
        let path = join_path(&sub, b"up/file");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, file);
    }

    // Multiple symlinks in path: a -> real_a, c -> real_c, access a/c/file.
    #[test]
    fn test_canonicalize_171() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let real_a = dir.join(b"real_a");
        fs::create_dir(&real_a).unwrap();
        let real_c = real_a.join(b"real_c");
        fs::create_dir(&real_c).unwrap();
        let file = real_c.join(b"file");
        fs::write(file.as_path(), "x").unwrap();
        let a_link = dir.join(b"a");
        symlink(real_a.as_path(), a_link.as_path()).unwrap();
        let c_link = real_a.join(b"c");
        symlink(real_c.as_path(), c_link.as_path()).unwrap();
        let path = join_path(&a_link, b"c/file");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, file);
    }

    // `/dev/null` with WANT_BASE.
    #[test]
    fn test_canonicalize_172() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/dev/null"),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/dev/null");
    }

    // `/proc` with WANT_BASE.
    #[test]
    fn test_canonicalize_173() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc"),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/proc");
    }

    // `/dev/null` with NO_RESOLVE_DOTDOT passes.
    #[test]
    fn test_canonicalize_174() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/dev/null"),
            FsFlags::NO_RESOLVE_DOTDOT,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/dev/null");
        assert!(path.typ.unwrap().is_char_device());
    }

    // `/dev/null` with NO_RESOLVE_PATH passes.
    #[test]
    fn test_canonicalize_175() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/dev/null"),
            FsFlags::NO_RESOLVE_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/dev/null");
        assert!(path.typ.unwrap().is_char_device());
    }

    // `/proc` with NO_RESOLVE_DOTDOT passes.
    #[test]
    fn test_canonicalize_176() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc"),
            FsFlags::NO_RESOLVE_DOTDOT,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/proc");
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `/proc` with NO_RESOLVE_PATH passes.
    #[test]
    fn test_canonicalize_177() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc"),
            FsFlags::NO_RESOLVE_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/proc");
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `/proc/self/cwd` resolves to CWD.
    #[test]
    fn test_canonicalize_178() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc/self/cwd"),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.abs.as_bytes().starts_with(b"/"));
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `/proc/self/cwd` with MUST_PATH.
    #[test]
    fn test_canonicalize_179() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc/self/cwd"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.abs.as_bytes().starts_with(b"/"));
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `/proc/self/cwd` with NO_FOLLOW_LAST returns magic symlink.
    #[test]
    fn test_canonicalize_180() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc/self/cwd"),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.typ.unwrap().is_magic_link());
    }

    // `/nonexistent` with NO_FOLLOW_LAST.
    #[test]
    fn test_canonicalize_181() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/nonexistent"),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/nonexistent");
        assert_eq!(path.typ, None);
    }

    // `/nonexistent` with NO_FOLLOW_LAST|MUST_PATH yields ENOENT.
    #[test]
    fn test_canonicalize_182() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/nonexistent"),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ENOENT)), "{result:?}");
    }

    // `/nonexistent` with WANT_BASE.
    #[test]
    fn test_canonicalize_183() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/nonexistent"),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"nonexistent");
        assert!(path.base_offset > 0);
    }

    // `/nonexistent` with NO_FOLLOW_LAST|MISS_LAST.
    #[test]
    fn test_canonicalize_184() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/nonexistent"),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/nonexistent");
        assert_eq!(path.typ, None);
    }

    // `//` with MUST_PATH normalizes to `/`.
    #[test]
    fn test_canonicalize_185() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"//"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `//` with WANT_BASE.
    #[test]
    fn test_canonicalize_186() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"//"),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `///` with MUST_PATH.
    #[test]
    fn test_canonicalize_187() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"///"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `/.` with WANT_BASE.
    #[test]
    fn test_canonicalize_188() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/."),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `/..` with WANT_BASE.
    #[test]
    fn test_canonicalize_189() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/.."),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `/..` with MISS_LAST.
    #[test]
    fn test_canonicalize_190() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/.."),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `/..` with NO_FOLLOW_LAST.
    #[test]
    fn test_canonicalize_191() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/.."),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `/etc/..` with WANT_BASE.
    #[test]
    fn test_canonicalize_192() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/.."),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `/etc/..` with MISS_LAST.
    #[test]
    fn test_canonicalize_193() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/.."),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `/etc/..` with NO_FOLLOW_LAST.
    #[test]
    fn test_canonicalize_194() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/.."),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/");
    }

    // `/etc/../etc/passwd` with WANT_BASE: base="passwd".
    #[test]
    fn test_canonicalize_195() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/../etc/passwd"),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"passwd");
    }

    // `/etc/../etc/passwd` with MISS_LAST.
    #[test]
    fn test_canonicalize_196() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/../etc/passwd"),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // `/etc/../etc/passwd` with NO_FOLLOW_LAST.
    #[test]
    fn test_canonicalize_197() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/../etc/passwd"),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // `/etc/./passwd` with WANT_BASE: base="passwd".
    #[test]
    fn test_canonicalize_198() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/./passwd"),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"passwd");
    }

    // `/etc/./passwd` with MISS_LAST.
    #[test]
    fn test_canonicalize_199() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/./passwd"),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // `/etc//passwd` with MUST_PATH.
    #[test]
    fn test_canonicalize_200() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc//passwd"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // `/etc//passwd` with WANT_BASE.
    #[test]
    fn test_canonicalize_201() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc//passwd"),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"passwd");
    }

    // `///etc///passwd` with MUST_PATH.
    #[test]
    fn test_canonicalize_202() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"///etc///passwd"),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // Symlink to dir with MISS_LAST.
    #[test]
    fn test_canonicalize_203() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"mydir");
        fs::create_dir(&tgt).unwrap();
        let lnk = dir.join(b"dirlink");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // Symlink to dir with NO_FOLLOW_LAST|MISS_LAST.
    #[test]
    fn test_canonicalize_204() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"mydir");
        fs::create_dir(&tgt).unwrap();
        let lnk = dir.join(b"dirlink");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(result.is_ok(), "{result:?}");
        assert!(
            result.as_ref().unwrap().typ.unwrap().is_symlink(),
            "{result:?}"
        );
    }

    // Symlink to dir with NO_FOLLOW_LAST|MUST_PATH.
    #[test]
    fn test_canonicalize_205() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"mydir");
        fs::create_dir(&tgt).unwrap();
        let lnk = dir.join(b"dirlink");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.typ.unwrap().is_symlink());
    }

    // Symlink to dir with NO_RESOLVE_PATH yields ELOOP.
    #[test]
    fn test_canonicalize_206() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"mydir");
        fs::create_dir(&tgt).unwrap();
        let lnk = dir.join(b"dirlink");
        symlink(tgt.as_path(), lnk.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_RESOLVE_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // Three-link chain with MUST_PATH resolves to file.
    #[test]
    fn test_canonicalize_207() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let file = dir.join(b"file");
        fs::write(file.as_path(), "x").unwrap();
        let c = dir.join(b"c");
        symlink(file.as_path(), c.as_path()).unwrap();
        let b = dir.join(b"b");
        symlink(c.as_path(), b.as_path()).unwrap();
        let a = dir.join(b"a");
        symlink(b.as_path(), a.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &a.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, file);
    }

    // Three-link chain with NO_RESOLVE_PATH yields ELOOP.
    #[test]
    fn test_canonicalize_208() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let file = dir.join(b"file");
        fs::write(file.as_path(), "x").unwrap();
        let c = dir.join(b"c");
        symlink(file.as_path(), c.as_path()).unwrap();
        let b = dir.join(b"b");
        symlink(c.as_path(), b.as_path()).unwrap();
        let a = dir.join(b"a");
        symlink(b.as_path(), a.as_path()).unwrap();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &a.deref(),
            FsFlags::NO_RESOLVE_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // Symlink with relative target and MUST_PATH.
    #[test]
    fn test_canonicalize_209() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"target");
        fs::write(tgt.as_path(), "x").unwrap();
        symlink("target", dir.join(b"rellink").as_path()).unwrap();
        let lnk = dir.join(b"rellink");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, tgt);
    }

    // Symlink with relative target and NO_FOLLOW_LAST.
    #[test]
    fn test_canonicalize_210() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let tgt = dir.join(b"target");
        fs::write(tgt.as_path(), "x").unwrap();
        symlink("target", dir.join(b"rellink").as_path()).unwrap();
        let lnk = dir.join(b"rellink");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.typ.unwrap().is_symlink());
    }

    // Symlink through intermediate dir with NO_RESOLVE_PATH rejects.
    #[test]
    fn test_canonicalize_211() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let real = dir.join(b"real");
        fs::create_dir(&real).unwrap();
        fs::write(real.join(b"file").as_path(), "x").unwrap();
        let lnk = dir.join(b"dir_link");
        symlink(real.as_path(), lnk.as_path()).unwrap();
        let through = lnk.join(b"file");
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &through.deref(),
            FsFlags::NO_RESOLVE_PATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::ELOOP)), "{result:?}");
    }

    // `/etc/./passwd` with NO_FOLLOW_LAST.
    #[test]
    fn test_canonicalize_212() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/./passwd"),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // `/etc//passwd` with NO_FOLLOW_LAST.
    #[test]
    fn test_canonicalize_213() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc//passwd"),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
    }

    // `/etc/./passwd` with NO_RESOLVE_DOTDOT passes (no dotdot).
    #[test]
    fn test_canonicalize_214() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/./passwd"),
            FsFlags::NO_RESOLVE_DOTDOT,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
        assert_eq!(path.typ, Some(FileType::Reg));
    }

    // `/etc/./passwd` with NO_RESOLVE_PATH passes (no symlinks).
    #[test]
    fn test_canonicalize_215() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/./passwd"),
            FsFlags::NO_RESOLVE_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/passwd");
        assert_eq!(path.typ, Some(FileType::Reg));
    }

    // `/etc/./passwd` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_216() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/./passwd"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/etc//passwd` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_217() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc//passwd"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `///etc///passwd` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_218() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"///etc///passwd"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/etc/../etc/passwd` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_219() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/../etc/passwd"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/..` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_220() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/.."),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/.` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_221() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/."),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `//` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_222() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"//"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/usr/` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_223() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/usr/"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/usr/bin` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_224() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/usr/bin"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/tmp` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_225() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/tmp"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/proc/self` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_226() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc/self"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/proc/self/cwd` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_227() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/proc/self/cwd"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `/nonexistent/foo` with RESOLVE_BENEATH yields EXDEV.
    #[test]
    fn test_canonicalize_228() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/nonexistent/foo"),
            FsFlags::RESOLVE_BENEATH,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EXDEV)), "{result:?}");
    }

    // `.` with MISS_LAST.
    #[test]
    fn test_canonicalize_229() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"."),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // `.` with NO_FOLLOW_LAST.
    #[test]
    fn test_canonicalize_230() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"."),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.abs.as_bytes().starts_with(b"/"));
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `..` with MISS_LAST.
    #[test]
    fn test_canonicalize_231() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b".."),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // `..` with NO_FOLLOW_LAST.
    #[test]
    fn test_canonicalize_232() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b".."),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.abs.as_bytes().starts_with(b"/"));
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `..` with WANT_BASE.
    #[test]
    fn test_canonicalize_233() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b".."),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.abs.as_bytes().starts_with(b"/"));
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `.` with NO_FOLLOW_LAST|MUST_PATH.
    #[test]
    fn test_canonicalize_234() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"."),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.abs.as_bytes().starts_with(b"/"));
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `..` with NO_FOLLOW_LAST|MUST_PATH.
    #[test]
    fn test_canonicalize_235() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b".."),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.abs.as_bytes().starts_with(b"/"));
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // Symlink chain of 5 links resolves to file.
    #[test]
    fn test_canonicalize_236() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let file = dir.join(b"file");
        fs::write(file.as_path(), "x").unwrap();
        let e = dir.join(b"e");
        symlink(file.as_path(), e.as_path()).unwrap();
        let dd = dir.join(b"d");
        symlink(e.as_path(), dd.as_path()).unwrap();
        let c = dir.join(b"c");
        symlink(dd.as_path(), c.as_path()).unwrap();
        let b = dir.join(b"b");
        symlink(c.as_path(), b.as_path()).unwrap();
        let a = dir.join(b"a");
        symlink(b.as_path(), a.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &a.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, file);
    }

    // Symlink chain of 5 with NO_FOLLOW_LAST stops at first link.
    #[test]
    fn test_canonicalize_237() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let file = dir.join(b"file");
        fs::write(file.as_path(), "x").unwrap();
        let e = dir.join(b"e");
        symlink(file.as_path(), e.as_path()).unwrap();
        let dd = dir.join(b"d");
        symlink(e.as_path(), dd.as_path()).unwrap();
        let c = dir.join(b"c");
        symlink(dd.as_path(), c.as_path()).unwrap();
        let b = dir.join(b"b");
        symlink(c.as_path(), b.as_path()).unwrap();
        let a = dir.join(b"a");
        symlink(b.as_path(), a.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &a.deref(),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, a);
    }

    // Relative "../target" with WANT_BASE.
    #[test]
    fn test_canonicalize_238() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let sub = dir.join(b"sub");
        fs::create_dir(&sub).unwrap();
        let tgt = dir.join(b"target");
        fs::write(tgt.as_path(), "x").unwrap();
        symlink("../target", sub.join(b"link").as_path()).unwrap();
        let lnk = sub.join(b"link");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::WANT_BASE,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"target");
    }

    // Dotdot-symlink with MUST_PATH.
    #[test]
    fn test_canonicalize_239() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let sub = dir.join(b"sub");
        fs::create_dir(&sub).unwrap();
        let file = dir.join(b"file");
        fs::write(file.as_path(), "x").unwrap();
        symlink("..", sub.join(b"up").as_path()).unwrap();
        let path = join_path(&sub, b"up/file");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, file);
    }

    // Nested symlink dirs: a -> b, b/c, access a/c/file.
    #[test]
    fn test_canonicalize_240() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let b_dir = dir.join(b"b");
        fs::create_dir(&b_dir).unwrap();
        let c_dir = b_dir.join(b"c");
        fs::create_dir(&c_dir).unwrap();
        let file = c_dir.join(b"file");
        fs::write(file.as_path(), "x").unwrap();
        let a = dir.join(b"a");
        symlink(b_dir.as_path(), a.as_path()).unwrap();
        let path = join_path(&a, b"c/file");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs, file);
    }

    // MISS_LAST on tempdir's existing subdir missing child.
    #[test]
    fn test_canonicalize_241() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let sub = dir.join(b"existing");
        fs::create_dir(&sub).unwrap();
        let path = sub.join(b"newfile");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"newfile");
    }

    // WANT_BASE|MISS_LAST on missing component.
    #[test]
    fn test_canonicalize_242() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let path = dir.join(b"missing");
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &path.deref(),
            FsFlags::WANT_BASE | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.base().as_bytes(), b"missing");
        assert!(path.base_offset > 0);
    }

    // Symlink to /proc/self resolves correctly.
    #[test]
    fn test_canonicalize_243() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let lnk = dir.join(b"proc_link");
        symlink("/proc/self", lnk.as_path()).unwrap();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &lnk.deref(),
            FsFlags::empty(),
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert!(path.abs.as_bytes().starts_with(b"/proc/"));
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // Nested tempdir with all major flags succeed.
    #[test]
    fn test_canonicalize_244() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let tmp = tempfile::Builder::new()
            .permissions(Permissions::from_mode(0o700))
            .tempdir()
            .unwrap();
        let dir = XPathBuf::from(tmp.path().to_path_buf());
        let sub = join_path(&dir, b"a/b/c");
        fs::create_dir_all(&sub).unwrap();
        let file = sub.join(b"f");
        fs::write(file.as_path(), "x").unwrap();
        for flags in [
            FsFlags::empty(),
            FsFlags::MUST_PATH,
            FsFlags::MISS_LAST,
            FsFlags::NO_FOLLOW_LAST,
            FsFlags::WANT_BASE,
        ] {
            let result = safe_canonicalize(
                Pid::this(),
                None,
                &file.deref(),
                flags,
                None,
                Some(&sandbox),
            );
            if flags == FsFlags::MISS_LAST {
                assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
            } else {
                let path = result.unwrap_or_else(|e| panic!("flags={flags:?}: {e:?}"));
                assert_eq!(path.abs, file, "flags={flags:?}");
                assert_eq!(path.typ, Some(FileType::Reg), "flags={flags:?}");
            }
        }
    }

    // `/etc/` with NO_FOLLOW_LAST.
    #[test]
    fn test_canonicalize_245() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/"),
            FsFlags::NO_FOLLOW_LAST,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/");
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `/etc/` with MISS_LAST.
    #[test]
    fn test_canonicalize_246() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/"),
            FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }

    // `/etc/` with NO_RESOLVE_DOTDOT passes.
    #[test]
    fn test_canonicalize_247() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/"),
            FsFlags::NO_RESOLVE_DOTDOT,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/");
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `/etc/` with NO_RESOLVE_PATH passes.
    #[test]
    fn test_canonicalize_248() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/"),
            FsFlags::NO_RESOLVE_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/");
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `/etc/` with NO_FOLLOW_LAST|MUST_PATH.
    #[test]
    fn test_canonicalize_249() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let path = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/"),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MUST_PATH,
            None,
            Some(&sandbox),
        )
        .unwrap();
        assert_eq!(path.abs.as_bytes(), b"/etc/");
        assert_eq!(path.typ, Some(FileType::Dir));
    }

    // `/etc/` with NO_FOLLOW_LAST|MISS_LAST.
    #[test]
    fn test_canonicalize_250() {
        let test_guard = setup();
        if test_guard.is_none() {
            return;
        }
        let sandbox = test_sandbox();
        let result = safe_canonicalize(
            Pid::this(),
            None,
            &XPath::from_bytes(b"/etc/"),
            FsFlags::NO_FOLLOW_LAST | FsFlags::MISS_LAST,
            None,
            Some(&sandbox),
        );
        assert!(matches!(result, Err(Errno::EEXIST)), "{result:?}");
    }
}
