//
// Syd: rock-solid unikernel
// src/test-do.rs: Integration test cases
//
// Copyright (c) 2023, 2024 Ali Polatel <alip@chesswob.org>
// Based in part upon coreutils' autoconf tests which are
//   Copyright (C) 2003-2007, 2009-2023 Free Software Foundation, Inc.
// Based in part upon gnulib's tests which are
//   Copyright (C) 2017-2024 Free Software Foundation, Inc.
//
// SPDX-License-Identifier: GPL-3.0-or-later

#![allow(clippy::disallowed_methods)]
#![allow(clippy::disallowed_types)]
#![allow(clippy::useless_conversion)]

use std::{
    env,
    ffi::{CStr, CString, OsStr, OsString},
    fs,
    fs::{File, OpenOptions},
    io::{ErrorKind, IoSlice, IoSliceMut, Read, Write},
    net::{Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6, TcpListener, TcpStream},
    num::NonZeroUsize,
    os::{
        fd::{AsRawFd, BorrowedFd, IntoRawFd, OwnedFd, RawFd},
        unix::{
            ffi::{OsStrExt, OsStringExt},
            fs::{symlink, OpenOptionsExt, PermissionsExt},
            net::{UnixDatagram, UnixListener, UnixStream},
            prelude::FromRawFd,
            process::CommandExt,
        },
    },
    path::{Path, PathBuf},
    process::{exit, Command, Stdio},
    str::FromStr,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc, Barrier,
    },
    thread,
    thread::sleep,
    time::{Duration, Instant},
};

use hex::DisplayHex;
use nix::{
    errno::Errno,
    fcntl::{self, fcntl, open, openat, readlink, AtFlags, FcntlArg, FdFlag, OFlag},
    libc::{_exit, pthread_create, pthread_join, pthread_t},
    pty::{grantpt, posix_openpt, ptsname, unlockpt},
    sched::{unshare, CloneFlags},
    sys::{
        inotify::{AddWatchFlags, InitFlags, Inotify},
        mman::{mmap, mprotect, MapFlags, ProtFlags},
        personality,
        personality::Persona,
        ptrace::{attach, seize, traceme, Options},
        signal::{
            kill, killpg, sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal, SIGALRM,
            SIGKILL,
        },
        socket::{
            accept, bind, connect, recv, recvfrom, recvmsg, send, sendmmsg, sendmsg, sendto,
            setsockopt, socket, socketpair, sockopt::AlgSetKey, AddressFamily, AlgAddr,
            ControlMessage, MsgFlags, MultiHeaders, SockFlag, SockType, SockaddrIn, SockaddrIn6,
            UnixAddr,
        },
        stat::{
            fchmod, fchmodat, fstat, fstatat, lstat, mkdirat, mknod, mknodat, stat, umask,
            FchmodatFlags, Mode, SFlag,
        },
        wait::{waitpid, WaitStatus},
    },
    unistd::{
        access, chdir, close, dup2, execv, fork, ftruncate, getgid, getpgrp, getresgid, getresuid,
        getuid, lseek64, mkdir, pipe, read, setgid, setsid, setuid, symlinkat, tcsetpgrp, truncate,
        unlink, unlinkat, write, AccessFlags, ForkResult, Gid, Pid, Uid, UnlinkatFlags, Whence,
    },
    NixPath,
};
use sendfd::{RecvWithFd, SendWithFd};
use syd::{
    compat::ftruncate64,
    fs::{fanotify_init, fanotify_mark, SmallPathBuf},
};

// Set global allocator to mimalloc.
#[global_allocator]
static GLOBAL: mimalloc2_rust::GlobalMiMalloc = mimalloc2_rust::GlobalMiMalloc;

type TestCase<'a> = (&'a str, &'a str, fn() -> !);
const TESTS: &[TestCase] = &[
    ("alloc",
     "Keep allocating more and more memory until allocation fails with ENOMEM",
     do_alloc),
    ("exit",
     "Given an exit code, exit with this code",
     do_exit),
    ("kill",
     "Given a pid and signal, send the signal to pid and exit with errno",
     do_kill),
    ("tkill",
     "Given a tid and signal, send the signal to pid and exit with errno",
     do_tkill),
    ("killpg_self",
     "Given a signal, send the current process group the signal and exit with errno",
     do_killpg_self),
    ("exec",
     "Try to execute the given path and return errno on failure",
     do_exec),
    ("getuid",
     "Given a user id, compare against the current UID and exit with success if they match",
     do_getuid),
    ("setuid",
     "Given a user id, set user id then get current UID and check if they match",
     do_setuid),
    ("setreuid",
     "Given real and effective user ids, set user ids then get current UIDs and check if they match",
     do_setreuid),
    ("setresuid",
     "Given real, effective, and saved user ids, set user ids then get current UIDs and check if they match",
     do_setresuid),
    ("setgid",
     "Given a group id, set group id then get current GID and check if they match",
     do_setgid),
    ("setregid",
     "Given real and effective group ids, set group ids then get current GIDs and check if they match",
     do_setregid),
    ("setresgid",
     "Given real, effective, and saved group ids, set group ids then get current GIDs and check if they match",
     do_setresgid),
    ("hascap",
     "Check if the process has the given capability and exit with success if that's true",
     do_hascap),
    ("readlink",
     "Check if readlink with the given argument succeeds",
     do_readlink),
    ("truncate",
     "Check if truncate works sanely",
     do_truncate),
    ("ftruncate",
     "Check if ftruncate works sanely",
     do_ftruncate),
    ("truncate64",
     "Check if truncate64 works sanely",
     do_truncate64),
    ("ftruncate64",
     "Check if truncate64 works sanely",
     do_ftruncate64),
    ("lgetxattr",
     "Given a path, run lgetxattr on it and return errno",
     do_lgetxattr),
    ("socket",
     "Attempt to create a socket with the given domain, type and protocol and exit with errno",
     do_socket),
    ("detect_ptrace",
     "Try to detect existence of a ptracer using the traceme operation",
     do_detect_ptrace),
    ("segv",
     "Cause a segmantation fault (used to test SegvGuard)",
     do_segv),
    ("personality",
     "If on 64bit, try to switch personality to 32bit and exit depending on expect success boolean given as first argument",
     do_personality),
    ("mmap_prot_read_exec_with_map_anonymous",
     "Check mmap: PROT_READ|PROT_EXEC with MAP_ANONYMOUS is killed.",
    do_mmap_prot_read_exec_with_map_anonymous),
    ("mmap_prot_write_exec_with_map_anonymous",
     "Check mmap: PROT_WRITE|PROT_EXEC with MAP_ANONYMOUS is killed.",
    do_mmap_prot_write_exec_with_map_anonymous),
    ("mmap_prot_read_exec_with_backing_file",
     "Check mmap: PROT_READ|PROT_EXEC with backing file.",
     do_mmap_prot_read_exec_with_backing_file),
    ("mmap_prot_write_exec_with_backing_file",
     "Check mmap: PROT_WRITE|PROT_EXEC with backing file.",
     do_mmap_prot_write_exec_with_backing_file),
    ("mmap_prot_exec_rdwr_fd",
     "Check mmap: PROT_READ|PROT_EXEC with a writable FD, then try modifying the contents.",
     do_mmap_prot_exec_rdwr_fd),
    ("mmap_fixed_null",
     "Use mmap with MAP_FIXED on the NULL address and expects it to be denied by EACCES",
     do_mmap_fixed_null),
    ("mprotect_read_to_exec",
     "mprotect PROT_EXEC a previously PROT_READ region.",
     do_mprotect_read_to_exec),
    ("mprotect_read_to_write_exec",
     "mprotect PROT_WRITE|PROT_EXEC a previously PROT_READ region.",
     do_mprotect_read_to_write_exec),
    ("mprotect_write_to_exec",
     "mprotect PROT_EXEC a previously PROT_WRITE region.",
     do_mprotect_write_to_exec),
    ("mprotect_write_to_read_exec",
     "mprotect PROT_READ|PROT_EXEC a previously PROT_WRITE region.",
     do_mprotect_write_to_read_exec),
    ("thread",
     "Given an exit code and number of threads, spawns threads exiting with random codes and parent exits with the given value",
     do_thread),
    ("fork",
     "Given an exit code and number of processes, spawns processes exiting with random codes and parent exits with the given value",
     do_fork),
    ("dlopen_now",
     "Given a library as argument, try to dlopen it with RTLD_NOW",
     do_dlopen_now),
    ("dlopen_lazy",
     "Given a library as argument, try to dlopen it with RTLD_LAZY",
     do_dlopen_lazy),
    ("connect4",
     "Connect to the given Ipv4 address and port",
     do_connect4),
    ("connect6",
     "Connect to the given Ipv6 address and port",
     do_connect6),
    ("connect4_0",
     "Check if bind to port zero is allowlisted with allowlist_safe_bind for Ipv4 addresses (requires an Ipv4 address as argument)",
     do_connect4_0),
    ("connect6_0",
     "Check if bind to port zero is allowlisted with allowlist_safe_bind for Ipv6 addresses (requires an Ipv6 address as argument)",
     do_connect6_0),
    ("sendmsg_scm_rights_one",
     "Check if sendmsg is correctly emulated when passing a single file descriptor with SCM_RIGHTS",
     do_sendmsg_scm_rights_one),
    ("sendmsg_scm_rights_many",
     "Check if sendmsg is correctly emulated when passing many file descriptors with SCM_RIGHTS",
     do_sendmsg_scm_rights_many),
    ("sendmmsg",
     "Check if sendmmsg is correctly emulated",
     do_sendmmsg),
    ("kcapi_hash_block",
     "Check if hashing with kernel crypto API is correctly emulated (block mode)",
     do_kcapi_hash_block),
    ("kcapi_hash_stream",
     "Check if hashing with kernel crypto API is correctly emulated (stream mode)",
     do_kcapi_hash_stream),
    ("kcapi_cipher_block",
     "Check if encrypting with kernel crypto API is correctly emulated (block mode)",
     do_kcapi_cipher_block),
    ("toolong_unix_connect",
     "Check if bind and connect works with UNIX domain sockets with canonicalized names longer than UNIX_PATH_MAX",
     do_toolong_unix_connect),
    ("toolong_unix_sendto",
     "Check if bind and sendto works with UNIX domain sockets with canonicalized names longer than UNIX_PATH_MAX",
     do_toolong_unix_sendto),
    ("toolong_unix_sendmsg",
     "Check if bind and sendmsg works with UNIX domain sockets with canonicalized names longer than UNIX_PATH_MAX",
     do_toolong_unix_sendmsg),
    ("ifconfig_lo",
     "Check socket configuration control ioctls work for loopback",
     do_ifconfig_lo),
    ("stat_bypass_with_read",
     "Check if stat sandboxing can be bypassed by attempting to read from denylisted path",
     do_stat_bypass_with_read),
    ("stat_bypass_with_write",
     "Check if stat sandboxing can be bypassed by attempting to write to denylisted path",
     do_stat_bypass_with_write),
    ("stat_bypass_with_exec",
     "Check if stat sandboxing can be bypassed by attempting to execute denylisted path",
     do_stat_bypass_with_exec),
    ("symlink_toctou",
     "Escape the sandbox with a symlink attack (assumes /etc/passwd is denylisted)",
     do_symlink_toctou),
    ("symlinkat_toctou",
     "Escape the sandbox with a symlink attack utilizing symlinkat (assumes /etc/passwd is denylisted)",
     do_symlinkat_toctou),
    ("ptrmod_toctou_exec_fail",
     "Escape the sandbox with a pointer modification attack utilizing the continue in exec hook with a failing execve",
     do_ptrmod_toctou_exec_fail),
    ("ptrmod_toctou_exec_success_quick",
     "Escape the sandbox with a pointer modification attack utilizing the continue in exec hook with a succeeding execve",
     do_ptrmod_toctou_exec_success_quick),
    ("ptrmod_toctou_exec_success_double_fork",
     "Escape the sandbox with a pointer modification attack utilizing the continue in exec hook with a succeeding execve",
     do_ptrmod_toctou_exec_success_double_fork),
    ("ptrmod_toctou_open",
     "Escape the sandbox with a pointer modification attack (assumes /etc/passwd is denylisted)",
     do_ptrmod_toctou_open),
    ("ptrmod_toctou_creat",
     "Escape the sandbox with a pointer modification attack to create a denylisted file (assumes the file `deny.syd-tmp' is denylisted)",
     do_ptrmod_toctou_creat),
    ("ptrmod_toctou_opath",
     "Leak hidden path in the sandbox with a pointer modification attack (assumes /etc/passwd is hidden)",
     do_ptrmod_toctou_opath),
    ("vfsmod_toctou_mmap",
     "Map a denylisted library into memory with file descriptor modification attack (assumes ./lib-bad exists and is denylisted)",
     do_vfsmod_toctou_mmap),
    ("vfsmod_toctou_open_file",
     "Escape the sandbox with a symlink modification attack to read a denylisted file (assumes /etc/passwd is denylisted)",
     do_vfsmod_toctou_open_file),
    ("vfsmod_toctou_open_path",
     "Escape the sandbox with a symlink modification attack to read a denylisted path (assumes /etc/passwd is denylisted)",
     do_vfsmod_toctou_open_path),
    ("io_uring_escape",
     "Escape the sandbox by opening and reading a file through io-uring interface (assumes /etc/passwd is denylisted)",
     do_io_uring_escape),
    ("opath_escape",
     "Escape the sandbox by reopening a fd opened initially with O_PATH",
     do_opath_escape),
    ("devfd_escape_open",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, fd/{fd})",
     do_devfd_escape_open),
    ("devfd_escape_open_relpath_1",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, fd/./{fd})",
     do_devfd_escape_open_relpath_1),
    ("devfd_escape_open_relpath_2",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, ./fd/{fd})",
     do_devfd_escape_open_relpath_2),
    ("devfd_escape_open_relpath_3",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, ./fd/././{fd})",
     do_devfd_escape_open_relpath_3),
    ("devfd_escape_open_relpath_4",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, fd/../fd/{fd})",
     do_devfd_escape_open_relpath_4),
    ("devfd_escape_open_relpath_5",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, ./././fd/{fd})",
     do_devfd_escape_open_relpath_5),
    ("devfd_escape_open_relpath_6",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, foo/../fd/{fd})",
     do_devfd_escape_open_relpath_6),
    ("devfd_escape_open_relpath_7",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, fd/foo/..//{fd})",
     do_devfd_escape_open_relpath_7),
    ("devfd_escape_open_relpath_8",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, fd/foo/.././{fd})",
     do_devfd_escape_open_relpath_8),
    ("devfd_escape_open_relpath_9",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, fd/foo/bar/../../{fd})",
     do_devfd_escape_open_relpath_9),
    ("devfd_escape_open_relpath_10",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, ././fd/foo/../././{fd})",
     do_devfd_escape_open_relpath_10),
    ("devfd_escape_open_relpath_11",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, fd/./././foo/../{fd})",
     do_devfd_escape_open_relpath_11),
    ("devfd_escape_open_relpath_12",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, fd/bar/./../{fd})",
     do_devfd_escape_open_relpath_12),
    ("devfd_escape_open_relpath_13",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, foo/bar/../../fd/{fd})",
     do_devfd_escape_open_relpath_13),
    ("devfd_escape_open_relpath_14",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, foo/./bar/../../fd/{fd})",
     do_devfd_escape_open_relpath_14),
    ("devfd_escape_open_relpath_15",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, ././foo/../fd/././{fd})",
     do_devfd_escape_open_relpath_15),
    ("devfd_escape_open_relpath_16",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, fd/././foo/bar/../.././{fd})",
     do_devfd_escape_open_relpath_16),
    ("devfd_escape_open_relpath_17",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, fd/foo/./bar/../../{fd})",
     do_devfd_escape_open_relpath_17),
    ("devfd_escape_open_relpath_18",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, ./fd/./bar/.././{fd})",
     do_devfd_escape_open_relpath_18),
    ("devfd_escape_open_relpath_19",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, fd/../.././fd/./{fd})",
     do_devfd_escape_open_relpath_19),
    ("devfd_escape_open_relpath_20",
     "Read /dev/fd where self belongs to syd rather than the process utilizing open(/dev) and openat(dirfd, fd/./././././././{fd})",
     do_devfd_escape_open_relpath_20),
    ("procself_escape_open",
     "Read /proc/self where self belongs to syd rather than the process utilizing open(/proc) and openat(dirfd, self/status)",
     do_procself_escape_open),
    ("procself_escape_open_relpath_1",
     "Read /proc/self where self belongs to syd rather than the process utilizing open(/proc) and openat(dirfd, self/./status)",
     do_procself_escape_open_relpath_1),
    ("procself_escape_open_relpath_2",
     "Read /proc/self where self belongs to syd rather than the process utilizing open(/proc) and openat(dirfd, ./self/status)",
     do_procself_escape_open_relpath_2),
    ("procself_escape_open_relpath_3",
     "Read /proc/self where self belongs to syd rather than the process utilizing open(/proc) and openat(dirfd, ./self/././status)",
     do_procself_escape_open_relpath_3),
    ("procself_escape_open_relpath_4",
     "Read /proc/self where self belongs to syd rather than the process utilizing open(/proc) and openat(dirfd, self/../self/status)",
     do_procself_escape_open_relpath_4),
    ("procself_escape_open_relpath_5",
     "Read /proc/self where self belongs to syd rather than the process utilizing open(/proc) and openat(dirfd, ./././self/status)",
     do_procself_escape_open_relpath_5),
    ("procself_escape_open_relpath_6",
     "Read /proc/self where self belongs to syd rather than the process utilizing open(/proc) and openat(dirfd, self/../.././self/./status)",
     do_procself_escape_open_relpath_6),
    ("procself_escape_open_relpath_7",
     "Read /proc/self where self belongs to syd rather than the process utilizing open(/proc) and openat(dirfd, self/./././././././status)",
     do_procself_escape_open_relpath_7),
    ("procself_escape_symlink",
     "Read /proc/self where self belongs to syd rather than the process utilizing symlink(self, /proc/./self/) and open(self/status)",
     do_procself_escape_symlink),
    ("umask_bypass_277", "Set umask to 277 and check if it's bypassed",
     do_umask_bypass_277),
    ("umask_bypass_077", "Set umask to 077 and check if it's bypassed",
     do_umask_bypass_077),
    ("emulate_opath", "Open a file relative to a fd opened with O_PATH",
     do_emulate_opath),
    ("emulate_otmpfile", "Open a file with O_TMPFILE flag",
     do_emulate_otmpfile),
    ("honor_umask", "Check if umask is honored (requires expected file mode as argument)",
     do_honor_umask),
    ("force_umask_bypass_with_open",
     "Check if trace/force_umask may be bypassed with an open(O_CREAT)",
     do_force_umask_bypass_with_open),
    ("force_umask_bypass_with_mknod",
     "Check if trace/force_umask may be bypassed with an mknod",
     do_force_umask_bypass_with_mknod),
    ("force_umask_bypass_with_mkdir",
     "Check if trace/force_umask may be bypassed with an mkdir",
     do_force_umask_bypass_with_mkdir),
    ("force_umask_bypass_with_fchmod",
     "Check if trace/force_umask may be bypassed with a fchmod",
     do_force_umask_bypass_with_fchmod),
    ("open_utf8_invalid",
     "Check if a file with invalid UTF-8 in its pathname can be opened",
     do_open_utf8_invalid),
    ("exec_in_inaccessible_directory",
     "Check if exec calls work from within an inaccessible directory",
     do_exec_in_inaccessible_directory),
    ("fstat_on_pipe",
     "Check if fstat on a pipe fd succeeds",
     do_fstat_on_pipe),
    ("fstat_on_socket",
     "Check if fstat on a socket fd succeeds",
     do_fstat_on_socket),
    ("fstat_on_deleted_file",
     "Check if fstat on a deleted file with an open fd succeeds",
     do_fstat_on_deleted_file),
    ("fstat_on_temp_file",
     "Check if fstat on a fd opened with O_TMPFILE succeeds",
     do_fstat_on_temp_file),
    ("fchmodat_on_proc_fd",
     "Check if fchmodat on a /proc/self/fd link works",
     do_fchmodat_on_proc_fd),
    ("linkat_on_fd",
     "Check if linkat using a fd and AT_EMPTY_PATH works",
     do_linkat_on_fd),
    ("block_ioctl_tiocsti",
     "Check if TIOCSTI ioctl is properly blocked by the sandbox",
     do_block_ioctl_tiocsti),
    ("block_prctl_ptrace",
     "Check if prctl option PR_SET_PTRACER is blocked by the sandbox",
     do_block_prctl_ptrace),
    ("block_dev_random",
     "Check if getrandom with the flag GRND_RANDOM is blocked by the sandbox",
     do_block_dev_random),
    ("block_dev_urandom",
     "Check if getrandom without the flag GRND_RANDOM is blocked by the sandbox",
     do_block_dev_urandom),
    ("kill_during_syscall",
     "Kill child during a busy system call loop which may hand the sandbox",
     do_kill_during_syscall),
    ("open_toolong_path",
     "Try to open a file with a path name longer than PATH_MAX",
     do_open_toolong_path),
    ("open_null_path",
     "Try to open a file with NULL pointer as path",
     do_open_null_path),
    ("utimensat_null",
     "Try to call utimensat with a NULL pointer as path",
     do_utimensat_null),
    ("path_resolution",
     "Try to open a path with various functionally identical absolute and relative paths",
     do_path_resolution),
    ("emulate_open_fifo",
     "Try to open a FIFO and see if the emulated open call deadlocks Syd",
     do_emulate_open_fifo),
    ("deny_magiclinks",
     "Try to access /proc/1/fd, /proc/1/cwd, and /proc/1/exe and expect ELOOP",
     do_deny_magiclinks),
    ("open_magiclinks",
     "Try to open /proc/{self,1}/{cwd,exe,root} and expect success or ELOOP",
     do_open_magiclinks),
    ("lstat_magiclinks",
     "Check if lstat()'ing magic proc symbolic links works as expected",
     do_lstat_magiclinks),
    ("access_unsafe_paths",
     "Check if accessing unsafe paths are denied as expected",
     do_access_unsafe_paths),
    ("open_trailing_slash",
     "Check if open with trailing slash is handled correctly",
     do_open_trailing_slash),
    ("openat_trailing_slash",
     "Check if openat with trailing slash is handled correctly",
     do_openat_trailing_slash),
    ("lstat_trailing_slash",
     "Check if lstat with trailing slash is handled correctly",
     do_lstat_trailing_slash),
    ("fstatat_trailing_slash",
     "Check if fstatat with trailing slash is handled correctly",
     do_fstatat_trailing_slash),
    ("mkdir_symlinks",
     "Check mkdir works correctly with symbolic links",
     do_mkdir_symlinks),
    ("mkdir_trailing_dot",
     "Check if mkdir with trailing dot is handled correctly",
     do_mkdir_trailing_dot),
    ("mkdirat_trailing_dot",
     "Check if mkdirat with trailing dot is handled correctly",
     do_mkdirat_trailing_dot),
    ("rmdir_trailing_slashdot",
     "Check if rmdir with trailing slash and dot are handled correctly",
     do_rmdir_trailing_slashdot),
    ("rmdir_cwd_and_create_file",
     "Check if rmdir cwd and creating a file in cwd fails with ENOENT",
     do_rmdir_cwd_and_create_file),
    ("rmdir_cwd_and_create_dir",
     "Check if rmdir cwd and creating a dir in cwd fails with ENOENT",
     do_rmdir_cwd_and_create_dir),
    ("rmdir_cwd_and_create_fifo",
     "Check if rmdir cwd and creating a fifo in cwd fails with ENOENT",
     do_rmdir_cwd_and_create_fifo),
    ("rmdir_cwd_and_create_unix",
     "Check if rmdir cwd and creating a unix socket in cwd fails with ENOENT",
     do_rmdir_cwd_and_create_unix),
    ("mkdir_eexist_escape",
     "Check if mkdir's EEXIST return value can be misused to locate hidden paths",
     do_mkdir_eexist_escape),
    ("mkdirat_eexist_escape",
     "Check if mkdirat's EEXIST return value can be misused to locate hidden paths",
     do_mkdirat_eexist_escape),
    ("mknod_eexist_escape",
     "Check if mknod's EEXIST return value can be misused to locate hidden paths",
     do_mknod_eexist_escape),
    ("mknodat_eexist_escape",
     "Check if mknodat's EEXIST return value can be misused to locate hidden paths",
     do_mknodat_eexist_escape),
    ("fopen_supports_mode_e",
     "Check if fopen supports mode 'e' in case the libc is GNU Libc",
     do_fopen_supports_mode_e),
    ("fopen_supports_mode_x",
     "Check if fopen supports mode 'x' in case the libc is GNU Libc",
     do_fopen_supports_mode_x),
    ("link_no_symlink_deref",
     "Check if link(2) dereferences symlinks",
     do_link_no_symlink_deref),
    ("link_posix",
     "Check if link(2) obeys POSIX",
     do_link_posix),
    ("linkat_posix",
     "Check if linkat(2) obeys POSIX",
     do_linkat_posix),
    ("getcwd_long",
     "Check if getcwd handles long file names properly by dynamically creating a deep structure and checking for errors at each step",
     do_getcwd_long),
    ("creat_thru_dangling",
     "Check if creating a file throug a dangling symbolic link behaves as expected",
     do_creat_thru_dangling),
    ("mkdirat_non_dir_fd",
     "Check if invalid file descriptors fail with ENOTDIR",
     do_mkdirat_non_dir_fd),
    ("fanotify_mark",
     "Check if marking the given directory and path with fanotify API succeeds",
     do_fanotify_mark),
    ("inotify_add_watch",
     "Check if adding an inotify watch to the given path succeeds",
    do_inotify_add_watch),
    ("blocking_udp4",
     "Check if blocking UDP with Ipv4 deadlocks the sandbox",
     do_blocking_udp4),
    ("blocking_udp6",
     "Check if blocking UDP with Ipv6 deadlocks the sandbox",
     do_blocking_udp6),
    ("close_on_exec",
     "Check if open with O_CLOEXEC is handled correctly by the sandbox",
     do_close_on_exec),
    ("open_exclusive_restart",
     "Check if open with O_CREAT|O_EXCL works even if restarted after a signal handler",
     do_open_exclusive_restart),
    ("open_exclusive_repeat",
     "Check if open with O_CREAT|O_EXCL works when repeated quickly",
     do_open_exclusive_repeat),
    ("unshare_user_bypass_limit",
     "Check if user namespace limitations can be bypassed by changing the sysctl",
     do_unshare_user_bypass_limit),
    ("setsid_detach_tty",
     "Check if setsid successfully detaches from controlling terminal.",
     do_setsid_detach_tty),
    ("pty_io_rust",
     "Check if input/output with PTYs work (using nix crate, purely in Rust)",
     do_pty_io_rust),
    ("pty_io_gawk",
     "Check if input/output with PTYs work (using GNU Awk)",
     do_pty_io_gawk),
    ("diff_dev_fd",
     "Check if bash -c \"diff -u <(cat /etc/passwd) <(cat /etc/passwd)\"",
     do_diff_dev_fd),
    ("bind_unix_socket",
     "Check if binding to a relative UNIX domain socket works and the umask is preserved",
     do_bind_unix_socket),
    ("interrupt_mkdir",
     "Check if interrupted mkdir system calls deadlocks syd",
     do_interrupt_mkdir),
    ("interrupt_bind_ipv4",
     "Check if interrupted bind system calls using an Ipv4 address deadlocks syd",
     do_interrupt_bind_ipv4),
    ("interrupt_bind_unix",
     "Check if interrupted bind system calls using a UNIX socket address deadlocks syd",
     do_interrupt_bind_unix),
    ("interrupt_connect_ipv4",
     "Check if interrupted connect system calls using an Ipv4 address deadlocks syd",
     do_interrupt_connect_ipv4),
    ("repetitive_clone",
     "Check if repetitive clone calls cause fork failure under syd",
     do_repetitive_clone),
    ("syscall_fuzz",
     "Fuzz system calls under syd for stress testing (requires: trinity)",
     do_syscall_fuzz),
    ("fork_bomb",
     "Check if a fork bomb in a container crashes syd",
     do_fork_bomb),
    ("fork_bomb_asm",
     "Check if a fork bomb using inline assembly in a container crashes syd",
     do_fork_bomb_asm),
    ("thread_bomb",
     "Check if a thread bomb in a container crashes syd",
     do_thread_bomb),
];

extern "C" fn modify_fd(ptr: *mut nix::libc::c_void) -> *mut nix::libc::c_void {
    let denylisted_fd = ptr as *mut RawFd;
    let denylisted_fd = unsafe { *denylisted_fd };

    // Swap standard input (fd 0) with denylisted_fd.
    let _ = dup2(denylisted_fd, nix::libc::STDIN_FILENO);

    std::ptr::null_mut()
}

extern "C" fn modify_ptr(ptr: *mut nix::libc::c_void) -> *mut nix::libc::c_void {
    let ptr = ptr as *mut i8;
    for _ in 0..10_000 {
        unsafe {
            ptr.copy_from_nonoverlapping(b"/etc/passwd".as_ptr() as *const _, b"/etc/passwd".len())
        };
    }
    std::ptr::null_mut()
}

extern "C" fn modify_ptr_creat(ptr: *mut nix::libc::c_void) -> *mut nix::libc::c_void {
    let ptr = ptr as *mut i8;
    for _ in 0..10_000 {
        unsafe {
            ptr.copy_from_nonoverlapping(
                b"./deny.syd-tmp".as_ptr() as *const _,
                b"./deny.syd-tmp".len(),
            )
        };
    }
    std::ptr::null_mut()
}

extern "C" fn modify_ptr_exec(ptr: *mut nix::libc::c_void) -> *mut nix::libc::c_void {
    let ptr = ptr as *mut i8;
    for _ in 0..10_000 {
        unsafe {
            ptr.copy_from_nonoverlapping(
                b"./toctou_exec".as_ptr() as *const _,
                b"./toctou_exec".len(),
            )
        };
    }
    std::ptr::null_mut()
}

extern "C" fn sigalarm_handler(_: nix::libc::c_int) {
    // SIGALRM handler does nothing; it's just here to interrupt syscalls
}

fn setup_sigalarm_handler(interval: Option<nix::libc::suseconds_t>, flags: SaFlags) {
    let action = SigAction::new(
        SigHandler::Handler(sigalarm_handler),
        flags,
        SigSet::empty(),
    );

    unsafe { sigaction(SIGALRM, &action).expect("Failed to set SIGALRM handler") };

    // Raise an alarm every 25 µs by default.
    let it_interval = nix::libc::timeval {
        tv_sec: 0,
        tv_usec: interval.unwrap_or(25),
    };
    let it_value = it_interval;
    let timer = nix::libc::itimerval {
        it_interval,
        it_value,
    };

    unsafe {
        nix::libc::syscall(nix::libc::SYS_setitimer, nix::libc::ITIMER_REAL, &timer, 0);
    }
}

fn setup_ipv4_server() {
    let listener = TcpListener::bind("127.0.0.1:65432").expect("Failed to bind to address");

    loop {
        // Start listening for connections
        match listener.accept() {
            Ok((mut stream, _addr)) => {
                // Send "HELO" message and then close the connection
                let message = "HELO";
                let _ = stream.write_all(message.as_bytes());
            }
            Err(error) => {
                eprintln!("Connection failed: {error}");
                // Continue the loop to listen for the next connection
            }
        }
    }
}

fn help() {
    println!("Usage: env SYD_TEST_DO=<command> syd-test-do <args>");
    println!("Commands:");

    // Sort by command name.
    let mut tests: Vec<_> = TESTS.to_vec();
    tests.sort_by(|a, b| a.0.cmp(b.0));

    for (idx, (name, description, _)) in tests.iter().enumerate() {
        let idx = idx + 1;
        println!("{idx:>3}: {name:<32} {description}.");
    }
}

fn main() {
    // Configure mimalloc.
    syd::configure_mimalloc();

    #[allow(clippy::disallowed_methods)]
    syd::set_sigpipe_dfl().expect("SIGPIPE");

    let args = std::env::args().skip(1).collect::<Vec<_>>();
    let args_is_empty = args.is_empty();
    if !args_is_empty
        && matches!(
            args[0].as_str(),
            "-h" | "--help" | "-l" | "--list" | "help" | "list"
        )
    {
        help();
        exit(0);
    }

    if let Ok(command) = env::var("SYD_TEST_DO") {
        if let Some((_, _, test)) = TESTS.iter().find(|&&(name, _, _)| name == command) {
            test();
        }
    }

    help();
    exit(1);
}

fn trinity_available() -> bool {
    Command::new("which")
        .arg("trinity")
        .status()
        .expect("Failed to execute command")
        .success()
}

fn do_fork_bomb() -> ! {
    // Ensure the caller knows what they're doing.
    match env::var("SYD_TEST_FORCE") {
        Ok(ref s) if s == "IKnowWhatIAmDoing" => {}
        _ => {
            eprintln!("Set SYD_TEST_FORCE environment variable to IKnowWhatIAmDoing to continue.");
            exit(1);
        }
    }
    loop {
        unsafe {
            let _ = fork();
        }
    }
}

fn do_fork_bomb_asm() -> ! {
    // Ensure the caller knows what they're doing.
    match env::var("SYD_TEST_FORCE") {
        Ok(ref s) if s == "IKnowWhatIAmDoing" => {}
        _ => {
            eprintln!("Set SYD_TEST_FORCE environment variable to IKnowWhatIAmDoing to continue.");
            exit(1);
        }
    }
    loop {
        unsafe {
            syd::fork_fast();
        }
    }
}

fn do_thread_bomb() -> ! {
    // Ensure the caller knows what they're doing.
    match env::var("SYD_TEST_FORCE") {
        Ok(ref s) if s == "IKnowWhatIAmDoing" => {}
        _ => {
            eprintln!("Set SYD_TEST_FORCE environment variable to IKnowWhatIAmDoing to continue.");
            exit(1);
        }
    }
    loop {
        thread::spawn(|| loop {
            thread::spawn(|| {});
        });
    }
}

fn do_syscall_fuzz() -> ! {
    if !trinity_available() {
        eprintln!("trinity not found in PATH. Skipping the test.");
        exit(0);
    }

    let mut syscalls = Vec::new();
    for syscall in syd::config::HOOK_SYSCALLS {
        match *syscall {
            "faccessat2" | "fchmodat2" | "openat2" | "umount2" => {}
            "stat" => {
                syscalls.push("newstat".to_string());
            }
            "fstat" => {
                syscalls.push("newfstat".to_string());
            }
            "newfstatat" => {
                syscalls.push("fstatat64".to_string());
            }
            name if name.ends_with("32") => {}
            _ => {
                syscalls.push(syscall.to_string());
            }
        }
    }
    syscalls.sort();
    println!(
        "# fuzzing {} system calls with trinity: {}",
        syscalls.len(),
        syscalls.join(", ")
    );

    let nsyscall: usize = match env::var("SYD_TEST_FUZZ")
        .unwrap_or("1000000".to_string())
        .parse()
    {
        Ok(n) => n,
        Err(error) => {
            eprintln!("Invalid value for SYD_TEST_FUZZ: {error}");
            exit(127);
        }
    };
    let syscalls: Vec<String> = syscalls
        .into_iter()
        .map(|name| format!("-c{name}"))
        .collect();

    // Let the game begin!
    Command::new("trinity")
        .args(["-q", "--stats"])
        .arg(format!("-C{}", num_cpus::get().saturating_mul(7)))
        .arg(format!("-N{nsyscall}"))
        .args(syscalls)
        .stderr(Stdio::inherit())
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .exec();
    eprintln!("Failed to execute trinity: {}", Errno::last());
    exit(1);
}

fn do_interrupt_connect_ipv4() -> ! {
    // Fork the process
    match unsafe { fork() } {
        Ok(ForkResult::Child) => {
            // In child: Set up a simple IPv4 server
            setup_ipv4_server();
            exit(0);
        }
        Ok(ForkResult::Parent { child, .. }) => {
            // In parent: Start connecting in a loop

            // Set up SIGALRM handler.
            setup_sigalarm_handler(None, SaFlags::SA_RESTART);

            // Run the test multiple times
            const TEST_DURATION: Duration = Duration::from_secs(60);
            let epoch = Instant::now();
            let mut i = 0;
            let mut last_report = epoch;
            eprintln!("Starting test, duration: 60 seconds...");

            loop {
                // Create a socket to connect to the server
                let sock = match socket(
                    AddressFamily::Inet,
                    SockType::Stream,
                    SockFlag::empty(),
                    None,
                ) {
                    Ok(sock) => sock,
                    Err(error) => {
                        eprintln!("socket creation failed: {error}");
                        let _ = kill(child, SIGKILL);
                        exit(1);
                    }
                };

                let now = Instant::now();
                let addr = SockaddrIn::new(127, 0, 0, 1, 65432);
                let res = connect(sock.as_raw_fd(), &addr);
                i += 1;
                match res {
                    Ok(()) => {}
                    Err(Errno::ECONNREFUSED) => {
                        // Wait for the Ipv4 server to set itself up.
                    }
                    Err(error) => {
                        let sec = now.elapsed().as_secs_f64();
                        eprintln!("Failed to connect to server on attempt {i}: {error}. Time taken {sec} seconds.");
                        let _ = kill(child, SIGKILL);
                        exit(1);
                    }
                };

                let elapsed = epoch.elapsed();
                let since_last_report = last_report.elapsed();
                if elapsed >= TEST_DURATION {
                    eprintln!("Timeout reached. Finalizing test.");
                    break;
                } else if since_last_report.as_secs() >= 10 {
                    last_report = Instant::now();
                    eprintln!(
                        "{} attempts in {} seconds, {} seconds left...",
                        i,
                        elapsed.as_secs(),
                        TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
                    );
                }
            }

            eprintln!("Interrupt connect test completed.");
            let _ = kill(child, SIGKILL);
            exit(0);
        }
        Err(error) => {
            eprintln!("Fork failed: {error}");
            exit(1);
        }
    }
}

fn do_interrupt_bind_ipv4() -> ! {
    // Bind to localhost port 65432.
    let addr = SockaddrIn::new(127, 0, 0, 1, 65432);

    // Set up SIGALRM handler.
    setup_sigalarm_handler(None, SaFlags::SA_RESTART);

    // Run the test multiple times
    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        let sock = match socket(
            AddressFamily::Inet,
            SockType::Stream,
            SockFlag::empty(),
            None,
        ) {
            Ok(sock) => sock,
            Err(error) => {
                eprintln!("socket creation failed: {error}");
                exit(1);
            }
        };

        let now = Instant::now();
        let res = bind(sock.as_raw_fd(), &addr);
        i += 1;
        if let Err(error) = res {
            let sec = now.elapsed().as_secs_f64();
            eprintln!("Failed to bind to 127.0.0.1 port 65432 attempt {i}: {error}. Time taken {sec} seconds.");
            exit(1);
        }

        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Interrupt bind test completed.");
    exit(0);
}

fn do_interrupt_bind_unix() -> ! {
    // Path to the Unix domain socket.
    let path = "test.socket";
    let addr = UnixAddr::new(path).unwrap();

    // Set up SIGALRM handler.
    setup_sigalarm_handler(None, SaFlags::SA_RESTART);

    // Run the test multiple times
    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        // Remove the socket file before each iteration.
        let _ = fs::remove_file(path);

        let sock = match socket(
            AddressFamily::Unix,
            SockType::Stream,
            SockFlag::empty(),
            None,
        ) {
            Ok(sock) => sock,
            Err(error) => {
                eprintln!("Socket creation failed: {error}");
                exit(1);
            }
        };

        let now = Instant::now();
        let res = bind(sock.as_raw_fd(), &addr);
        i += 1;
        if let Err(error) = res {
            let sec = now.elapsed().as_secs_f64();
            eprintln!("Failed to bind to Unix domain socket 'test.socket' attempt {i}: {error}. Time taken {sec} seconds.");
            exit(1);
        }

        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Interrupt bind test completed.");
    exit(0);
}

fn do_interrupt_mkdir() -> ! {
    // Set up SIGALRM handler.
    setup_sigalarm_handler(None, SaFlags::SA_RESTART);

    // Run the test multiple times
    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        // Clean up
        let _ = unlinkat(None, "test.dir", UnlinkatFlags::RemoveDir);

        let now = Instant::now();
        let res = mkdir("test.dir", Mode::from_bits_truncate(0o700));
        i += 1;
        if let Err(error) = res {
            let sec = now.elapsed().as_secs_f64();
            eprintln!(
                "Failed to mkdir test.dir at attempt {i}: {error}. Time taken {sec} seconds."
            );
            exit(1);
        }

        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Interrupt mkdir test completed.");
    exit(0);
}

fn do_bind_unix_socket() -> ! {
    const UMASK: nix::libc::mode_t = 0o077;

    // Set an uncommon umask
    let _ = umask(Mode::from_bits_truncate(UMASK));

    // Try to bind to the socket
    let _ = match UnixListener::bind("test.socket") {
        Ok(listener) => listener,
        Err(error) => {
            eprintln!("Failed to bind to socket: {error}");
            exit(1);
        }
    };

    // Calculate expected permissions based on the umask
    let expected_mode = 0o777 & !UMASK;

    // Check if the socket was created with correct permissions
    let metadata = fs::metadata("test.socket").expect("Failed to retrieve metadata");
    let permissions = metadata.permissions();
    let mode = permissions.mode() & 0o777; // Mask out file type bits
    if mode != expected_mode {
        eprintln!("Socket does not have correct permissions. Expected: {expected_mode:o}, Found: {mode:o}");
        exit(1);
    }

    eprintln!("Test succeeded!");
    exit(0);
}

fn do_diff_dev_fd() -> ! {
    // Spawn a child process running the gawk script
    let mut child = Command::new("bash")
        .arg("-c")
        .arg("diff -u <(cat /etc/passwd) <(cat /etc/passwd)")
        .stdin(Stdio::inherit())
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .spawn()
        .unwrap_or_else(|error| {
            eprintln!("Failed to execute gawk: {error}");
            exit(1);
        });

    // Get stdout handle
    let child_stdout = child.stdout.as_mut().unwrap_or_else(|| {
        eprintln!("Failed to get child stdout.");
        exit(1);
    });

    // Read the output from the child process
    let mut output = String::new();
    let raw_fd = child_stdout.as_raw_fd();
    let mut file = unsafe { File::from_raw_fd(raw_fd) };

    if let Err(error) = file.read_to_string(&mut output) {
        eprintln!("Failed to read output of child process: {error}");
        exit(1);
    }
    println!("Child output: {output}");
    if !output.is_empty() {
        eprintln!("Unexpected output!");
        exit(1);
    }

    // Ensure the child process finishes
    let status = match child.wait() {
        Ok(status) => status,
        Err(error) => {
            eprintln!("Failed to wait for child: {error}");
            exit(1);
        }
    };
    if !status.success() {
        eprintln!("Child process failed.");
        exit(1);
    }

    exit(0);
}

fn do_repetitive_clone() -> ! {
    // Spawn a child process running the shell script
    let mut child = Command::new("bash")
        .args(["-e", "-c"])
        .arg(
            r#"
yes syd |
while read i
do
    name=$(echo "$i" | sed -e 's|syd|box|')
    echo "${name}" >> /dev/null
done
"#,
        )
        .spawn()
        .unwrap_or_else(|error| {
            eprintln!("Failed to execute bash: {error}");
            exit(1);
        });

    // Ensure the child process finishes
    let status = match child.wait() {
        Ok(status) => status,
        Err(error) => {
            eprintln!("Failed to wait for child: {error}");
            exit(1);
        }
    };
    if !status.success() {
        eprintln!("Child process failed.");
        exit(1);
    }

    exit(0);
}

fn do_pty_io_gawk() -> ! {
    // Spawn a child process running the gawk script
    let mut child = Command::new("gawk")
        .arg(
            r#"BEGIN {
            c = "echo 123 > /dev/tty; read x < /dev/tty; echo \"x is $x\"";
            PROCINFO[c, "pty"] = 1;
            c |& getline; print;
            print "abc" |& c;
            c |& getline; print;
        }"#,
        )
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .spawn()
        .unwrap_or_else(|error| {
            eprintln!("Failed to execute gawk: {error}");
            exit(1);
        });

    // Get stdin and stdout handles
    let child_stdin = child.stdin.as_mut().unwrap_or_else(|| {
        eprintln!("Failed to get child stdin.");
        exit(1);
    });
    let child_stdout = child.stdout.as_mut().unwrap_or_else(|| {
        eprintln!("Failed to get child stdout.");
        exit(1);
    });

    // Write input "abc" to the child process
    if let Err(error) = child_stdin.write_all(b"abc\n") {
        eprintln!("Failed to write input to child process: {error}");
        exit(1);
    }

    // Read the output from the child process
    let mut output = String::new();
    let raw_fd = child_stdout.as_raw_fd();
    let mut file = unsafe { File::from_raw_fd(raw_fd) };

    if let Err(error) = file.read_to_string(&mut output) {
        eprintln!("Failed to read output of child process: {error}");
        exit(1);
    }
    print!("Child output:\n{output}");
    if output != "123\nx is abc\n" {
        eprintln!("Unexpected output!");
        exit(1);
    }

    // Ensure the child process finishes
    let status = match child.wait() {
        Ok(status) => status,
        Err(error) => {
            eprintln!("Failed to wait for child: {error}");
            exit(1);
        }
    };
    if !status.success() {
        eprintln!("Child process failed.");
        exit(1);
    }

    exit(0);
}

fn do_pty_io_rust() -> ! {
    let mut master_fd = match posix_openpt(OFlag::O_RDWR) {
        Ok(fd) => fd,
        Err(error) => {
            eprintln!("Failed to open PTY: {error}");
            exit(1);
        }
    };

    if let Err(error) = grantpt(&master_fd) {
        eprintln!("Failed to grant PTY: {error}");
        exit(1);
    }

    if let Err(error) = unlockpt(&master_fd) {
        eprintln!("Failed to unlock PTY: {error}");
        exit(1);
    }

    let slave_name = match unsafe { ptsname(&master_fd) } {
        Ok(name) => name,
        Err(error) => {
            eprintln!("Failed to get slave PTY name: {error}");
            exit(1);
        }
    };

    let (pipe_read, pipe_write) = match pipe() {
        Ok((r, w)) => (r, w),
        Err(e) => {
            eprintln!("Failed to create pipe: {}", e);
            exit(1);
        }
    };

    match unsafe { fork() } {
        Ok(ForkResult::Parent { .. }) => {
            // Parent process
            drop(pipe_write);

            // Wait for child to be ready after "123\n"
            let mut buffer = [0];
            read(pipe_read.as_raw_fd(), &mut buffer).unwrap();
            if buffer[0] != 1 {
                eprintln!("Sync error: Child not ready after 123");
                exit(1);
            }

            // Read "123\n" from child
            let mut output_1 = [0; 64];
            let bytes_read = match master_fd.read(&mut output_1) {
                Ok(n) => n,
                Err(error) => {
                    eprintln!("Failed to read 123 from child: {error}");
                    exit(1);
                }
            };
            let output_1 = std::str::from_utf8(&output_1[..bytes_read]).unwrap();

            // Write "abc\n" to child
            if let Err(error) = master_fd.write_all(b"abc\n") {
                eprintln!("Failed to write abc to child: {error}");
                exit(1);
            }

            // Wait for child to be ready after "x is abc\n"
            read(pipe_read.as_raw_fd(), &mut buffer).unwrap();
            if buffer[0] != 2 {
                eprintln!("Sync error: Child not ready after x is abc");
                exit(1);
            } else {
                // Wait a bit for the message to appear in the PTY.
                sleep(Duration::from_millis(100));
            }

            // Read "x is abc\n" from child
            let mut output_2 = [0; 64];
            let bytes_read = match master_fd.read(&mut output_2) {
                Ok(n) => n,
                Err(error) => {
                    eprintln!("Failed to read x is abc from child: {error}");
                    exit(1);
                }
            };
            let output_2 = std::str::from_utf8(&output_2[..bytes_read]).unwrap();

            // Check and finalize the test.
            let output_1 = output_1.trim_end();
            let output_2 = output_2.trim_end();
            eprintln!("Child output: {output_1:?}+{output_2:?}");
            if output_1 != "123" || !output_2.ends_with("x is abc") {
                eprintln!("Unexpected output!");
                exit(1);
            } else {
                eprintln!("Test succeeded!");
                exit(0);
            }
        }
        Ok(ForkResult::Child) => {
            // Child process
            drop(pipe_read);
            drop(master_fd);

            // Start a new session to set the PTY as the controlling terminal
            setsid().expect("setsid failed");

            eprintln!("Child: opening PTY {slave_name}");
            let slave_fd = match open(slave_name.as_str(), OFlag::O_RDWR, Mode::empty()) {
                Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
                Err(error) => {
                    eprintln!("Failed to open {slave_name}: {error}");
                    exit(1);
                }
            };

            // Make the PTY the controlling terminal
            if unsafe { nix::libc::ioctl(slave_fd.as_raw_fd(), nix::libc::TIOCSCTTY, 0) } == -1 {
                eprintln!(
                    "Failed to set PTY {slave_name} as controlling terminal: {}",
                    Errno::last()
                );
                exit(1);
            }

            eprintln!("Child: opening /dev/tty");
            // Open /dev/tty, which now refers to the slave end of the PTY
            let tty_fd = match open("/dev/tty", OFlag::O_RDWR, Mode::empty()) {
                Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
                Err(error) => {
                    eprintln!("Failed to open /dev/tty: {error}");
                    exit(1);
                }
            };

            // Write "123\n" directly to slave_fd
            if let Err(error) = write(&tty_fd, b"123\n") {
                eprintln!("Failed to write 123 to slave FD: {error}");
                exit(1);
            }

            // Notify parent that child is ready
            write(&pipe_write, &[1]).unwrap();

            // Read input directly from slave_fd
            let mut input = [0; 64];
            let nbytes = match read(slave_fd.as_raw_fd(), &mut input) {
                Ok(n) => n,
                Err(error) => {
                    eprintln!("Failed to read abc from slave FD: {error}");
                    exit(1);
                }
            };
            let input_str = std::str::from_utf8(&input[..nbytes]).unwrap().trim();

            // Write response directly to slave_fd
            let response = format!("x is {}\n", input_str);
            if let Err(error) = write(&tty_fd, response.as_bytes()) {
                eprintln!("Failed to write x is abc to slave FD: {error}");
                exit(1);
            }

            // Notify parent that child is ready
            write(&pipe_write, &[2]).unwrap();

            drop(slave_fd);
            exit(0);
        }
        Err(error) => {
            eprintln!("Failed to fork: {error}");
            exit(1);
        }
    }
}

fn do_setsid_detach_tty() -> ! {
    let tty = match open("/dev/tty", OFlag::O_RDWR, Mode::empty()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Opening /dev/tty failed: {errno}!");
            eprintln!("Skipping test!");
            exit(0);
        }
    };

    match unsafe { fork() }.expect("Failed to fork!") {
        ForkResult::Child => {
            let pgrp = match setsid() {
                Ok(pgrp) => {
                    eprintln!("setsid succeeded as expected!");
                    pgrp
                }
                Err(errno) => {
                    eprintln!("setsid failed: {errno}");
                    unsafe { nix::libc::_exit(1) };
                }
            };

            match tcsetpgrp(std::io::stdout(), pgrp) {
                Ok(_) => {
                    eprintln!("tcsetpgrp succeeded unexpectedly!");
                    unsafe { nix::libc::_exit(1) };
                }
                Err(Errno::ENOTTY) => {
                    eprintln!("tcsetpgrp failed with ENOTTY as expected!");
                }
                Err(errno) => {
                    eprintln!("tcsetpgrp failed with unexpected errno: {errno}");
                    unsafe { nix::libc::_exit(1) };
                }
            }

            match open("/dev/tty", OFlag::O_RDONLY, Mode::empty()) {
                Ok(fd) => {
                    let _ = close(fd);
                    eprintln!("Opening /dev/tty succeeded unexpectedly!");
                    unsafe { nix::libc::_exit(1) };
                }
                Err(Errno::ENXIO) => {
                    eprintln!("Opening /dev/tty failed with ENXIO as expected!");
                }
                Err(errno) => {
                    eprintln!("Opening /dev/tty failed with unexpected errno: {errno}");
                    unsafe { nix::libc::_exit(1) };
                }
            }

            match Errno::result(unsafe {
                nix::libc::ioctl(tty.as_raw_fd(), nix::libc::TIOCSCTTY, 0)
            }) {
                Ok(_) => {
                    eprintln!("ioctl(TIOCSCTTY) succeeded unexpectedly!");
                    unsafe { nix::libc::_exit(1) };
                }
                Err(Errno::EPERM) => {
                    eprintln!("ioctl(TIOCSCTTY) failed with EPERM as expected!");
                }
                Err(errno) => {
                    eprintln!("ioctl(TIOCSCTTY) failed with unexpected errno: {errno}");
                    unsafe { nix::libc::_exit(1) };
                }
            }

            eprintln!("Test succeeded!");
            unsafe { nix::libc::_exit(0) };
        }
        ForkResult::Parent { child, .. } => {
            let status = waitpid(child, None).expect("Failed to wait!");
            if let WaitStatus::Exited(_, exit_code) = status {
                exit(exit_code);
            } else {
                eprintln!("Child exited with unexpected status: {status:?}");
                exit(1);
            }
        }
    }
}

fn do_open_exclusive_repeat() -> ! {
    // Try to unlink the file; it's okay if it doesn't exist.
    let _ = unlink("test-file");

    // Try to open the file with O_CREAT | O_EXCL
    let fd = match open(
        "test-file",
        OFlag::O_CREAT | OFlag::O_EXCL,
        Mode::from_bits_truncate(0o644),
    ) {
        Ok(fd) => fd,
        Err(error) => {
            eprintln!("Failed to create file exclusively: {error}");
            exit(1);
        }
    };
    let _ = close(fd);

    // Try the same again right after.
    match open(
        "test-file",
        OFlag::O_CREAT | OFlag::O_EXCL,
        Mode::from_bits_truncate(0o644),
    ) {
        Ok(fd) => {
            let _ = close(fd);
            eprintln!("Second exclusive open succeded!");
            exit(1);
        }
        Err(error) => {
            eprintln!("Failed to create file exclusively: {error}");
        }
    }

    eprintln!("Test succeeded!");
    exit(0);
}

fn do_open_exclusive_restart() -> ! {
    // Try to unlink the file; it's okay if it doesn't exist.
    let _ = unlink("test-file");

    // Set up SIGALRM handler.
    setup_sigalarm_handler(None, SaFlags::SA_RESTART);

    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        // Try to open the file with O_CREAT | O_EXCL
        let fd = match open(
            "test-file",
            OFlag::O_CREAT | OFlag::O_EXCL,
            Mode::from_bits_truncate(0o644),
        ) {
            Ok(fd) => fd,
            Err(Errno::EINTR) => continue,
            Err(error) => {
                eprintln!("Failed to create file exclusively: {error}");
                exit(1);
            }
        };

        // If we're here, it means open succeeded;
        // close the file descriptor and remove the file.
        let _ = close(fd);
        let _ = unlink("test-file");

        i += 1;
        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Test succeeded!");
    exit(0);
}

fn do_unshare_user_bypass_limit() -> ! {
    // Step 1: Write a large number to the file
    if let Err(error) = File::create("/proc/sys/user/max_user_namespaces")
        .and_then(|mut file| file.write_all(b"10000"))
    {
        eprintln!("Failed to write to /proc/sys/user/max_user_namespaces: {error:?}");
        //Let's fallthrough and check for sure.
        //exit(1);
    }

    // Step 2: Attempt to unshare with CLONE_NEWUSER
    match unshare(CloneFlags::CLONE_NEWUSER) {
        Ok(_) => {
            eprintln!("Test failed: user namespace limitation bypassed!");
            exit(1);
        }
        Err(Errno::EACCES) => {
            eprintln!("Expected error occurred: {:?}", Errno::EACCES);
            exit(0);
        }
        Err(error) => {
            eprintln!("Unexpected error occurred: {error:?}");
            exit(1);
        }
    }
}

fn do_close_on_exec() -> ! {
    // 1. Open /dev/null with O_CLOEXEC using open
    let fd = match open(
        "/dev/null",
        OFlag::O_RDONLY | OFlag::O_CLOEXEC,
        Mode::empty(),
    ) {
        Ok(fd) => fd,
        Err(error) => {
            eprintln!("Error opening /dev/null with open: {error}");
            exit(1);
        }
    };

    // Check if O_CLOEXEC is set
    let flags = match fcntl(fd, FcntlArg::F_GETFD) {
        Ok(flags) => flags,
        Err(error) => {
            eprintln!("Error getting flags with fcntl: {error}");
            exit(1);
        }
    };
    let _ = close(fd);

    if flags & nix::libc::FD_CLOEXEC == 0 {
        eprintln!("O_CLOEXEC is not set for open: {flags:?}");
        exit(1);
    }

    // 2. Open /dev/null with O_CLOEXEC using openat
    let fd = match openat(
        None,
        "/dev/null",
        OFlag::O_RDONLY | OFlag::O_CLOEXEC,
        Mode::empty(),
    ) {
        Ok(fd) => fd,
        Err(error) => {
            eprintln!("Error opening /dev/null with openat: {error}");
            exit(1);
        }
    };

    // Check if O_CLOEXEC is set
    let flags = match fcntl(fd, FcntlArg::F_GETFD) {
        Ok(flags) => flags,
        Err(error) => {
            eprintln!("Error getting flags with fcntl: {error}");
            exit(1);
        }
    };
    let _ = close(fd);

    if flags & nix::libc::FD_CLOEXEC == 0 {
        eprintln!("O_CLOEXEC is not set for openat: {flags:?}");
        exit(1);
    }

    // If both checks pass, print success message and exit with 0
    eprintln!("Success: O_CLOEXEC is set for both open and openat");
    exit(0);
}

fn do_blocking_udp6() -> ! {
    const NUM_THREADS: usize = 64;
    const SERVER_PORT: u16 = 65432;

    // Spawn a blocking UDP server
    thread::spawn(move || {
        let server_fd = socket(
            AddressFamily::Inet6,
            SockType::Datagram,
            SockFlag::empty(),
            None,
        )
        .unwrap_or_else(|error| {
            eprintln!("Failed to create server socket: {error}");
            exit(1);
        });

        let sockaddr_v6 = SocketAddrV6::new("::1".parse().unwrap(), SERVER_PORT, 0, 0);
        let sockaddr = SockaddrIn6::from(sockaddr_v6);
        bind(server_fd.as_raw_fd(), &sockaddr).unwrap_or_else(|error| {
            eprintln!("Failed to bind server socket: {error}");
            exit(1);
        });

        let mut buf = [0; 1024];
        loop {
            // Blocking call to receive data
            let (len, _) =
                recvfrom::<SockaddrIn6>(server_fd.as_raw_fd(), &mut buf).unwrap_or_else(|error| {
                    eprintln!("Server failed to receive data: {error}");
                    exit(1);
                });
            eprintln!("Server received: {:?}", &buf[..len]);
        }
    });

    let barrier = Arc::new(Barrier::new(NUM_THREADS + 1));

    // Spawn many threads connecting to the UDP server
    for _ in 0..NUM_THREADS {
        let barrier = Arc::clone(&barrier);
        thread::spawn(move || {
            let client_fd = socket(
                AddressFamily::Inet6,
                SockType::Datagram,
                SockFlag::empty(),
                None,
            )
            .unwrap_or_else(|error| {
                eprintln!("Failed to create client socket: {error}");
                exit(1);
            });

            let sockaddr_v6 = SocketAddrV6::new("::1".parse().unwrap(), SERVER_PORT, 0, 0);
            let sockaddr = SockaddrIn6::from(sockaddr_v6);
            connect(client_fd.as_raw_fd(), &sockaddr).unwrap_or_else(|error| {
                eprintln!("Client failed to connect: {error}");
                exit(1);
            });

            barrier.wait();

            // Now all threads will send data simultaneously
            sendto(
                client_fd.as_raw_fd(),
                b"Heavy is the root of light. Still is the master of moving.",
                &sockaddr,
                MsgFlags::empty(),
            )
            .unwrap_or_else(|error| {
                eprintln!("Client failed to send data: {error}");
                exit(1);
            });

            let mut buf = [0; 1024];
            recvfrom::<SockaddrIn6>(client_fd.as_raw_fd(), &mut buf).unwrap_or_else(|error| {
                eprintln!("Client failed to receive data: {error}");
                exit(1);
            });
        });
    }

    // Ensure main thread waits for all child threads
    barrier.wait();
    eprintln!("Test completed successfully!");
    exit(0);
}

fn do_blocking_udp4() -> ! {
    const NUM_THREADS: usize = 64;
    const SERVER_PORT: u16 = 65432;

    // Spawn a blocking UDP server
    thread::spawn(move || {
        let server_fd = socket(
            AddressFamily::Inet,
            SockType::Datagram,
            SockFlag::empty(),
            None,
        )
        .unwrap_or_else(|error| {
            eprintln!("Failed to create server socket: {error}");
            exit(1);
        });

        let sockaddr = SockaddrIn::new(127, 0, 0, 1, SERVER_PORT);
        bind(server_fd.as_raw_fd(), &sockaddr).unwrap_or_else(|error| {
            eprintln!("Failed to bind server socket: {error}");
            exit(1);
        });

        let mut buf = [0; 1024];
        loop {
            // Blocking call to receive data
            let (len, _) =
                recvfrom::<SockaddrIn>(server_fd.as_raw_fd(), &mut buf).unwrap_or_else(|error| {
                    eprintln!("Server failed to receive data: {error}");
                    exit(1);
                });
            eprintln!("Server received: {:?}", &buf[..len]);
        }
    });

    let barrier = Arc::new(Barrier::new(NUM_THREADS + 1));

    // Spawn many threads connecting to the UDP server
    for _ in 0..NUM_THREADS {
        let barrier = Arc::clone(&barrier);
        thread::spawn(move || {
            let client_fd = socket(
                AddressFamily::Inet,
                SockType::Datagram,
                SockFlag::empty(),
                None,
            )
            .unwrap_or_else(|error| {
                eprintln!("Failed to create client socket: {error}");
                exit(1);
            });

            let sockaddr = SockaddrIn::new(127, 0, 0, 1, SERVER_PORT);
            connect(client_fd.as_raw_fd(), &sockaddr).unwrap_or_else(|error| {
                eprintln!("Client failed to connect: {error}");
                exit(1);
            });

            barrier.wait();

            // Now all threads will send data simultaneously
            sendto(
                client_fd.as_raw_fd(),
                b"Heavy is the root of light. Still is the master of moving.",
                &sockaddr,
                MsgFlags::empty(),
            )
            .unwrap_or_else(|error| {
                eprintln!("Client failed to send data: {error}");
                exit(1);
            });

            let mut buf = [0; 1024];
            recvfrom::<SockaddrIn>(client_fd.as_raw_fd(), &mut buf).unwrap_or_else(|error| {
                eprintln!("Client failed to receive data: {error}");
                exit(1);
            });
        });
    }

    // Ensure main thread waits for all child threads
    barrier.wait();
    eprintln!("Test completed successfully!");
    exit(0);
}

fn do_inotify_add_watch() -> ! {
    let args: Vec<String> = std::env::args().collect();
    if args.len() != 2 {
        eprintln!("Usage: {} <path>", args[0]);
        exit(nix::libc::EINVAL);
    }

    let instance = match Inotify::init(InitFlags::IN_CLOEXEC) {
        Ok(instance) => instance,
        Err(errno) => {
            eprintln!("inotify_init failed: {errno}");
            exit(errno as i32);
        }
    };

    match instance.add_watch(
        Path::new(&args[1]),
        AddWatchFlags::IN_ALL_EVENTS | AddWatchFlags::IN_DONT_FOLLOW,
    ) {
        Ok(_) => {
            eprintln!("inotify_add_watch succeeded!");
            exit(0);
        }
        Err(errno) => {
            eprintln!("inotify_add_watch failed: {errno}");
            exit(errno as i32);
        }
    };
}

fn do_fanotify_mark() -> ! {
    let args: Vec<String> = std::env::args().collect();
    if args.len() != 3 {
        eprintln!("Usage: {} <dirpath> <path>", args[0]);
        exit(nix::libc::EINVAL);
    }

    let dirpath = &args[1];
    let path = &args[2];

    // Initialize a new fanotify instance.
    let notify_fd = match fanotify_init(
        nix::libc::FAN_CLOEXEC | nix::libc::FAN_CLASS_NOTIF | nix::libc::FAN_REPORT_FID,
        0,
    ) {
        Ok(fd) => fd,
        Err(errno) => {
            eprintln!("Failed to initialize fanotify: {errno}");
            exit(errno as i32);
        }
    };

    // Determine dirfd based on the dirpath argument.
    let dirfd: Option<RawFd> = if dirpath == "0" {
        None
    } else {
        match open(
            Path::new(dirpath),
            OFlag::O_RDONLY | OFlag::O_DIRECTORY,
            Mode::empty(),
        ) {
            Ok(fd) => Some(fd),
            Err(errno) => {
                eprintln!("Failed to open directory {dirpath}: {errno}");
                exit(errno as i32);
            }
        }
    };

    // Determine the path argument.
    let path = if path == "0" {
        None
    } else {
        Some(Path::new(path))
    };

    // Attempt to mark the directory with the fanotify instance.
    match fanotify_mark(
        &notify_fd,
        nix::libc::FAN_MARK_ADD | nix::libc::FAN_MARK_DONT_FOLLOW,
        nix::libc::FAN_ACCESS,
        dirfd,
        path,
    ) {
        Ok(_) => {
            // Exit with success
            eprintln!("Mark with fanotify returned success!");
            exit(0);
        }
        Err(errno) => {
            eprintln!("Failed to mark with fanotify: {errno}");
            exit(errno as i32);
        }
    }
}

fn do_mkdirat_non_dir_fd() -> ! {
    // Open a file descriptor to /dev/null
    let fd = open("/dev/null", OFlag::O_RDONLY, Mode::empty()).expect("Failed to open /dev/null");

    // Try to use this file descriptor as a directory file descriptor
    let result = mkdirat(Some(fd), "dir", Mode::from_bits_truncate(0o700));

    // Close the file descriptor
    let _ = close(fd);

    match result {
        Err(Errno::ENOTDIR) => {
            // Expected error case: parent is not a directory
            eprintln!("Attempted to create directory under /dev/null, got ENOTDIR as expected.");
            exit(0);
        }
        Err(error) => {
            // Any other error case
            eprintln!("Unexpected error while trying to create directory under /dev/null: {error}");
            exit(1);
        }
        Ok(_) => {
            // Unexpected success case
            eprintln!("Unexpectedly succeeded in creating directory under /dev/null.");
            exit(1);
        }
    }
}

fn do_creat_thru_dangling() -> ! {
    let mut result = 0;

    // Create a dangling symlink
    if let Err(error) = symlink("no-such", "dangle") {
        eprintln!("symlink(no-such, dangle) failed: {error}");
        result |= 1;
    }

    // Test open with O_CREAT | O_EXCL flags
    match open(
        "dangle",
        OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_EXCL,
        Mode::empty(),
    ) {
        Ok(fd) => {
            let _ = close(fd);
            let _ = unlink("no-such");
            eprintln!("Opening dangling symlink with O_CREAT|O_EXCL created the target file unexpectedly.");
            result |= 2;
        }
        Err(Errno::EEXIST) => {
            eprintln!("Opening dangling symlink with O_CREAT|O_EXCL failed with EEXIST.");
        }
        Err(error) => {
            eprintln!("Opening dangling symlink with O_CREAT|O_EXCL failed with unexpected error: {error}");
            result |= 4;
        }
    }

    // Test openat with O_CREAT | O_EXCL flags
    match openat(
        None,
        "dangle",
        OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_EXCL,
        Mode::empty(),
    ) {
        Ok(fd) => {
            let _ = close(fd);
            let _ = unlink("no-such");
            eprintln!("openat'ing dangling symlink with O_CREAT|O_EXCL created the target file unexpectedly.");
            result |= 8;
        }
        Err(Errno::EEXIST) => {
            eprintln!("openat'ing dangling symlink with O_CREAT|O_EXCL failed with EEXIST.");
        }
        Err(error) => {
            eprintln!("openat'ing dangling symlink with O_CREAT|O_EXCL failed with unexpected error: {error}");
            result |= 16;
        }
    }

    // Test open with O_CREAT flag
    match open("dangle", OFlag::O_WRONLY | OFlag::O_CREAT, Mode::empty()) {
        Ok(fd) => {
            let _ = close(fd);
            let _ = unlink("no-such");
            eprintln!("Opening dangling symlink with O_CREAT created the target file as expected.");
        }
        Err(error) => {
            eprintln!("Opening dangling symlink with O_CREAT failed: {error}");
            result |= 32;
        }
    }

    // Test openat with O_CREAT flag
    match openat(
        None,
        "dangle",
        OFlag::O_WRONLY | OFlag::O_CREAT,
        Mode::empty(),
    ) {
        Ok(fd) => {
            let _ = close(fd);
            let _ = unlink("no-such");
            eprintln!(
                "openat'ing dangling symlink with O_CREAT created the target file as expected."
            );
        }
        Err(error) => {
            eprintln!("openat'ing dangling symlink with O_CREAT failed: {error}");
            result |= 64;
        }
    }

    // Cleanup
    let _ = unlink("dangle");

    if result == 0 {
        eprintln!("Test succeded!");
        exit(0);
    } else {
        eprintln!("Test failed: {result}");
        exit(1);
    }
}

fn do_getcwd_long() -> ! {
    const PATH_MAX: usize = nix::libc::PATH_MAX as usize;
    const DIR_NAME: &str = "confdir3";
    const DIR_NAME_SIZE: usize = DIR_NAME.len() + 1;
    const DOTDOTSLASH_LEN: usize = 3;
    const BUF_SLOP: usize = 20;

    let max = nix::libc::PATH_MAX as usize;
    let mut buf = vec![0; max * (DIR_NAME_SIZE / DOTDOTSLASH_LEN + 1) + DIR_NAME_SIZE + BUF_SLOP];
    let cwd = unsafe { nix::libc::getcwd(buf.as_mut_ptr(), max) };
    if cwd.is_null() {
        eprintln!("Failed to get current working directory: {}", Errno::last());
        exit(1);
    }
    let cwd = unsafe { CStr::from_ptr(cwd) };
    let cwd = OsString::from_vec(cwd.to_bytes().to_vec());
    let cwd = Path::new(&cwd);

    let mut cwd_len = cwd.as_os_str().len();
    let initial_cwd_len = cwd_len;
    let mut n_chdirs = 0;
    let mut fail = 0;

    loop {
        let dotdot_max = PATH_MAX * (DIR_NAME_SIZE / DOTDOTSLASH_LEN);
        let mut c: Option<usize> = None;

        cwd_len += DIR_NAME_SIZE;
        let dir_path = Path::new(DIR_NAME);
        if mkdir(dir_path, Mode::from_bits_truncate(0o700)).is_err() || chdir(dir_path).is_err() {
            if Errno::last() != Errno::ERANGE && Errno::last() != Errno::ENOENT {
                #[cfg(target_os = "linux")]
                if Errno::last() != Errno::EINVAL {
                    fail = 20;
                }
            }
            break;
        }

        if (PATH_MAX..PATH_MAX + DIR_NAME_SIZE).contains(&cwd_len) {
            let cwd = unsafe { nix::libc::getcwd(buf.as_mut_ptr(), max) };
            if cwd.is_null() && Errno::last() == Errno::ENOENT {
                fail = 11;
                eprintln!("getcwd is partly working: {fail}");
                break;
            }
            if !cwd.is_null() {
                fail = 31;
                eprintln!("getcwd has the AIX bug!");
                break;
            }
            if Errno::last() != Errno::ERANGE {
                fail = 21;
                eprintln!("getcwd isn't working ({fail}): {}", Errno::last());
                break;
            }

            let cwd = unsafe { nix::libc::getcwd(buf.as_mut_ptr(), cwd_len + 1) };
            if !cwd.is_null() {
                let cwd = unsafe { CStr::from_ptr(cwd) };
                let cwd = OsString::from_vec(cwd.to_bytes().to_vec());
                let cwd = Path::new(&cwd);
                if stat(cwd).is_err() && Errno::last() == Errno::ERANGE {
                    eprintln!("getcwd works but with shorter paths.");
                    fail = 32;
                    break;
                }
            }
            c = Some(unsafe { CStr::from_ptr(cwd) }.len());
        }

        if dotdot_max <= cwd_len - initial_cwd_len {
            if dotdot_max + DIR_NAME_SIZE + BUF_SLOP < cwd_len - initial_cwd_len {
                break;
            }
            let cwd = unsafe { nix::libc::getcwd(buf.as_mut_ptr(), cwd_len + 1) };
            if cwd.is_null() {
                match Errno::last() {
                    Errno::ERANGE | Errno::ENOENT | Errno::ENAMETOOLONG => {
                        fail = 12;
                        eprintln!("getcwd is partly working: {fail}: {}", Errno::last());
                        break;
                    }
                    errno => {
                        eprintln!("getcwd isn't working ({fail}): {errno}");
                        fail = 22;
                        break;
                    }
                }
            } else {
                c = Some(unsafe { CStr::from_ptr(cwd) }.len());
            }
        }

        if let Some(len) = c {
            if len != cwd_len {
                fail = 23;
                eprintln!("getcwd isn't working ({fail}).");
                break;
            }
        }
        n_chdirs += 1;
    }

    let path = Path::new(DIR_NAME);
    let path = CString::new(path.as_os_str().as_bytes()).unwrap();
    unsafe { nix::libc::rmdir(path.as_ptr()) };
    for _ in 0..=n_chdirs {
        if chdir(Path::new("..")).is_ok() && unsafe { nix::libc::rmdir(path.as_ptr()) } == 0 {
            break;
        }
    }

    if fail == 0 {
        eprintln!("Test succeded!");
        exit(0);
    } else if fail < 20 {
        eprintln!("Test succeded partially!");
        exit(0);
    } else {
        eprintln!("Test failed: {fail}");
        exit(fail);
    }
}

fn do_linkat_posix() -> ! {
    // Cleanup any existing files
    let _ = unlink("conftest.a");
    let _ = unlink("conftest.b");
    let _ = unlink("conftest.lnk");
    let file_a = CString::new("conftest.a").unwrap();
    let file_b = CString::new("conftest.b").unwrap();
    let s_link = CString::new("conftest.lnk").unwrap();
    let file_b_slash = CString::new("conftest.b/").unwrap();
    let s_link_slash = CString::new("conftest.lnk/").unwrap();

    // Create a regular file
    let fd = unsafe { nix::libc::creat(file_a.as_ptr(), 0o644) };
    if fd < 0 {
        eprintln!("Failed to create conftest.a: {}", Errno::last());
        exit(1);
    }
    let _ = unsafe { nix::libc::close(fd) };

    // Create a symlink
    if unsafe { nix::libc::symlink(file_a.as_ptr(), s_link.as_ptr()) } != 0 {
        eprintln!("Failed to create symlink: {}", Errno::last());
        exit(1);
    }

    // Check whether link obeys POSIX
    let mut result = 0;

    if unsafe {
        nix::libc::linkat(
            nix::libc::AT_FDCWD,
            file_a.as_ptr(),
            nix::libc::AT_FDCWD,
            file_b_slash.as_ptr(),
            0,
        )
    } == 0
    {
        result |= 1;
    }

    let mut sb: nix::libc::stat = unsafe { std::mem::zeroed() };
    if unsafe { nix::libc::lstat(s_link_slash.as_ptr(), &mut sb) } == 0
        && unsafe {
            nix::libc::linkat(
                nix::libc::AT_FDCWD,
                s_link_slash.as_ptr(),
                nix::libc::AT_FDCWD,
                file_b.as_ptr(),
                0,
            )
        } == 0
    {
        result |= 2;
    }

    if unsafe { nix::libc::rename(file_a.as_ptr(), file_b.as_ptr()) } != 0 {
        result |= 4;
    }

    if unsafe {
        nix::libc::linkat(
            nix::libc::AT_FDCWD,
            file_b.as_ptr(),
            nix::libc::AT_FDCWD,
            s_link.as_ptr(),
            0,
        )
    } == 0
    {
        result |= 8;
    }

    // Cleanup
    let _ = unlink("conftest.a");
    let _ = unlink("conftest.b");
    let _ = unlink("conftest.lnk");

    if result != 0 {
        eprintln!("Test failed: linkat does not obey POSIX: {result}");
        exit(1);
    }

    eprintln!("Test succeeded: linkat obeys POSIX");
    exit(0);
}

fn do_link_posix() -> ! {
    // Cleanup any existing files
    let _ = unlink("conftest.a");
    let _ = unlink("conftest.b");
    let _ = unlink("conftest.lnk");
    let file_a = CString::new("conftest.a").unwrap();
    let file_b = CString::new("conftest.b").unwrap();
    let s_link = CString::new("conftest.lnk").unwrap();
    let file_b_slash = CString::new("conftest.b/").unwrap();
    let s_link_slash = CString::new("conftest.lnk/").unwrap();

    // Create a regular file
    let fd = unsafe { nix::libc::creat(file_a.as_ptr(), 0o644) };
    if fd < 0 {
        eprintln!("Failed to create conftest.a: {}", Errno::last());
        exit(1);
    }
    let _ = unsafe { nix::libc::close(fd) };

    // Create a symlink
    if unsafe { nix::libc::symlink(file_a.as_ptr(), s_link.as_ptr()) } != 0 {
        eprintln!("Failed to create symlink: {}", Errno::last());
        exit(1);
    }

    // Check whether link obeys POSIX
    let mut result = 0;

    if unsafe { nix::libc::link(file_a.as_ptr(), file_b_slash.as_ptr()) } == 0 {
        result |= 1;
    }

    let mut sb: nix::libc::stat = unsafe { std::mem::zeroed() };
    if unsafe { nix::libc::lstat(s_link_slash.as_ptr(), &mut sb) } == 0
        && unsafe { nix::libc::link(s_link_slash.as_ptr(), file_b.as_ptr()) } == 0
    {
        result |= 2;
    }

    if unsafe { nix::libc::rename(file_a.as_ptr(), file_b.as_ptr()) } != 0 {
        result |= 4;
    }

    if unsafe { nix::libc::link(file_b.as_ptr(), s_link.as_ptr()) } == 0 {
        result |= 8;
    }

    // Cleanup
    let _ = unlink("conftest.a");
    let _ = unlink("conftest.b");
    let _ = unlink("conftest.lnk");

    if result != 0 {
        eprintln!("Test failed: link does not obey POSIX: {result}");
        exit(1);
    }

    eprintln!("Test succeeded: link obeys POSIX");
    exit(0);
}

fn do_link_no_symlink_deref() -> ! {
    // Cleanup any existing files
    let _ = unlink("conftest.file");
    let _ = unlink("conftest.sym");
    let _ = unlink("conftest.hard");
    let file = CString::new("conftest.file").unwrap();
    let slink = CString::new("conftest.sym").unwrap();
    let hlink = CString::new("conftest.hard").unwrap();

    // Create a regular file.
    let fd = unsafe { nix::libc::creat(file.as_ptr(), 0o644) };
    if fd < 0 {
        eprintln!("Failed to create conftest.file: {}", Errno::last());
        exit(1);
    }
    let _ = unsafe { nix::libc::close(fd) };

    // Create a symlink to the regular file.
    if unsafe { nix::libc::symlink(file.as_ptr(), slink.as_ptr()) } != 0 {
        eprintln!("Failed to create symlink");
        exit(1);
    }

    // Attempt to create a hard link to the symlink.
    if unsafe { nix::libc::link(slink.as_ptr(), hlink.as_ptr()) } != 0 {
        eprintln!("Failed to create hard link: {}", Errno::last());
        exit(1);
    }

    // Check the metadata of the hard link and the file
    // If the dev/inode of hard and file are the same, then
    // the link call followed the symlink.
    let mut sb_hard: nix::libc::stat = unsafe { std::mem::zeroed() };
    let mut sb_file: nix::libc::stat = unsafe { std::mem::zeroed() };
    let mut sb_link: nix::libc::stat = unsafe { std::mem::zeroed() };

    if unsafe { nix::libc::lstat(hlink.as_ptr(), &mut sb_hard) } != 0
        || unsafe { nix::libc::lstat(slink.as_ptr(), &mut sb_link) } != 0
        || unsafe { nix::libc::stat(file.as_ptr(), &mut sb_file) } != 0
    {
        eprintln!("Failed to get file metadata: {}", Errno::last());
        exit(1);
    }

    // If the dev/inode of hard and file are the same, then the link call followed the symlink.
    if sb_hard.st_dev == sb_file.st_dev && sb_hard.st_ino == sb_file.st_ino {
        eprintln!("Test failed: link(2) dereferences symbolic links:");
        eprintln!("file: {sb_file:?}");
        eprintln!("link: {sb_link:?}");
        eprintln!("hard: {sb_hard:?}");
        exit(1);
    }

    // Cleanup
    let _ = unlink("conftest.file");
    let _ = unlink("conftest.sym");
    let _ = unlink("conftest.hard");

    eprintln!("Test succeeded: link(2) does not dereference symbolic links");
    exit(0);
}

fn do_fopen_supports_mode_e() -> ! {
    let mut result = 0;
    let filename = CString::new("conftest.e").unwrap();
    let mode_re = CString::new("re").unwrap();

    let _ = unlink("conftest.e");
    let mut file = File::create("conftest.e").expect("Failed to create conftest.e");
    file.write_all(b"Heavy is the root of light. Still is the master of moving.")
        .expect("Failed to write to conftest.x");

    let fp = unsafe { nix::libc::fopen(filename.as_ptr(), mode_re.as_ptr()) };
    if !fp.is_null() {
        let fd = unsafe { nix::libc::fileno(fp) };
        let flags = FdFlag::from_bits_truncate(
            fcntl::fcntl(fd, fcntl::F_GETFD).expect("Failed to get file descriptor flags"),
        );
        if !flags.contains(FdFlag::FD_CLOEXEC) {
            eprintln!("File descriptor does not have close-on-exec flag: {flags:?}");
            result |= 2;
        }
        unsafe {
            nix::libc::fclose(fp);
        }
    } else {
        eprintln!("The 'e' flag is rejected!");
        result |= 4;
    }

    let _ = unlink("conftest.e");

    if result == 0 {
        eprintln!("Test succeded!");
        exit(0);
    } else {
        eprintln!("Test failed: {result}");
        exit(1);
    }
}

fn do_fopen_supports_mode_x() -> ! {
    let mut result = 0;
    let filename = CString::new("conftest.x").unwrap();
    let mode_w = CString::new("w").unwrap();
    let mode_wx = CString::new("wx").unwrap();

    let _ = unlink("conftest.x");

    let fp_w = unsafe { nix::libc::fopen(filename.as_ptr(), mode_w.as_ptr()) };
    if fp_w.is_null() {
        eprintln!("Failed to create conftest.x: {}", Errno::last());
        result |= 1;
    } else {
        unsafe {
            nix::libc::fclose(fp_w);
        }

        let fp_wx = unsafe { nix::libc::fopen(filename.as_ptr(), mode_wx.as_ptr()) };
        if !fp_wx.is_null() {
            eprintln!("The 'x' flag is ignored");
            result |= 2;
            unsafe {
                nix::libc::fclose(fp_wx);
            }
        } else {
            let error = Errno::last();
            if error != Errno::EEXIST {
                eprintln!("The 'x' flag is rejected");
                result |= 4;
            }
        }
    }

    let _ = unlink("conftest.x");

    if result == 0 {
        eprintln!("Test succeded!");
        exit(0);
    } else {
        eprintln!("Test failed: {result}");
        exit(1);
    }
}

fn do_mknodat_eexist_escape() -> ! {
    match mknodat(None, "/boot", SFlag::S_IFREG, Mode::S_IRWXU, 0) {
        Ok(_) => {
            eprintln!("mknodat /boot succeded unexpectedly!");
            exit(1);
        }
        Err(Errno::ENOENT) => {
            eprintln!("/boot successfully hidden on mknodat!");
            exit(0);
        }
        Err(errno) => {
            eprintln!("mknodat /boot returned unexpected errno: {errno}!");
            exit(1);
        }
    }
}

fn do_mknod_eexist_escape() -> ! {
    match mknod("/boot", SFlag::S_IFREG, Mode::S_IRWXU, 0) {
        Ok(_) => {
            eprintln!("mknod /boot succeded unexpectedly!");
            exit(1);
        }
        Err(Errno::ENOENT) => {
            eprintln!("/boot successfully hidden on mknod!");
            exit(0);
        }
        Err(errno) => {
            eprintln!("mknod /boot returned unexpected errno: {errno}!");
            exit(1);
        }
    }
}

fn do_mkdirat_eexist_escape() -> ! {
    match mkdirat(None, "/boot", Mode::S_IRWXU) {
        Ok(_) => {
            eprintln!("mkdirat /boot succeded unexpectedly!");
            exit(1);
        }
        Err(Errno::ENOENT) => {
            eprintln!("/boot successfully hidden on mkdirat!");
            exit(0);
        }
        Err(errno) => {
            eprintln!("mkdir /boot returned unexpected errno: {errno}!");
            exit(1);
        }
    }
}

fn do_mkdir_eexist_escape() -> ! {
    match mkdir("/boot", Mode::S_IRWXU) {
        Ok(_) => {
            eprintln!("mkdir /boot succeded unexpectedly!");
            exit(1);
        }
        Err(Errno::ENOENT) => {
            eprintln!("/boot successfully hidden on mkdir!");
            exit(0);
        }
        Err(errno) => {
            eprintln!("mkdir /boot returned unexpected errno: {errno}!");
            exit(1);
        }
    }
}

fn do_rmdir_cwd_and_create_file() -> ! {
    // Parsing the first argument as the test directory.
    let args: Vec<String> = std::env::args().collect();
    if args.len() < 2 {
        panic!("Expected exactly one argument for test directory");
    }
    let dir = &args[1];

    // Enter the test directory.
    if let Err(errno) = chdir(Path::new(dir)) {
        eprintln!("Failed to enter test directory {dir}: {errno}!");
        exit(errno as i32);
    }

    // Remove the test directory.
    if let Err(errno) = unlinkat(
        None,
        Path::new(&format!("../{dir}")),
        UnlinkatFlags::RemoveDir,
    ) {
        eprintln!("Failed to remove test directory {dir}: {errno}!");
        exit(errno as i32);
    }

    // Try to create a file in the removed directory.
    match open("escape", OFlag::O_CREAT, Mode::from_bits_truncate(0o700)) {
        Ok(fd) => {
            let _ = close(fd);
            eprintln!("Unexpected file creation in removed directory!");
            exit(127);
        }
        Err(Errno::EACCES) => {
            eprintln!("Unexpected access violation during file creation in removed directory!");
            exit(Errno::EACCES as i32);
        }
        Err(Errno::ENOENT) => {
            eprintln!("File creation in removed directory returned ENOENT as expected.");
            exit(0);
        }
        Err(errno) => {
            eprintln!("Unexpected error {errno} during file creation in removed directory!");
            exit(errno as i32);
        }
    }
}

fn do_rmdir_cwd_and_create_dir() -> ! {
    // Parsing the first argument as the test directory.
    let args: Vec<String> = std::env::args().collect();
    if args.len() < 2 {
        panic!("Expected exactly one argument for test directory");
    }
    let dir = &args[1];

    // Enter the test directory.
    if let Err(errno) = chdir(Path::new(dir)) {
        eprintln!("Failed to enter test directory {dir}: {errno}!");
        exit(errno as i32);
    }

    // Remove the test directory.
    if let Err(errno) = unlinkat(
        None,
        Path::new(&format!("../{dir}")),
        UnlinkatFlags::RemoveDir,
    ) {
        eprintln!("Failed to remove test directory {dir}: {errno}!");
        exit(errno as i32);
    }

    // Try to create a directory in the removed directory.
    match mkdir("escape", Mode::from_bits_truncate(0o700)) {
        Ok(_) => {
            eprintln!("Unexpected dir creation in removed directory!");
            exit(127);
        }
        Err(Errno::EACCES) => {
            eprintln!("Unexpected access violation during dir creation in removed directory!");
            exit(Errno::EACCES as i32);
        }
        Err(Errno::ENOENT) => {
            eprintln!("Dir creation in removed directory returned ENOENT as expected.");
            exit(0);
        }
        Err(errno) => {
            eprintln!("Unexpected error {errno} during dir creation in removed directory!");
            exit(errno as i32);
        }
    }
}

fn do_rmdir_cwd_and_create_fifo() -> ! {
    // Parsing the first argument as the test directory.
    let args: Vec<String> = std::env::args().collect();
    if args.len() < 2 {
        panic!("Expected exactly one argument for test directory");
    }
    let dir = &args[1];

    // Enter the test directory.
    if let Err(errno) = chdir(Path::new(dir)) {
        eprintln!("Failed to enter test directory {dir}: {errno}!");
        exit(errno as i32);
    }

    // Remove the test directory.
    if let Err(errno) = unlinkat(
        None,
        Path::new(&format!("../{dir}")),
        UnlinkatFlags::RemoveDir,
    ) {
        eprintln!("Failed to remove test directory {dir}: {errno}!");
        exit(errno as i32);
    }

    // Try to create a FIFO in the removed directory.
    match mknod("escape", SFlag::S_IFIFO, Mode::from_bits_truncate(0o700), 0) {
        Ok(_) => {
            eprintln!("Unexpected fifo creation in removed directory!");
            exit(127);
        }
        Err(Errno::EACCES) => {
            eprintln!("Unexpected access violation during fifo creation in removed directory!");
            exit(Errno::EACCES as i32);
        }
        Err(Errno::ENOENT) => {
            eprintln!("Fifo creation in removed directory returned ENOENT as expected.");
            exit(0);
        }
        Err(errno) => {
            eprintln!("Unexpected error {errno} during fifo creation in removed directory!");
            exit(errno as i32);
        }
    }
}

fn do_rmdir_cwd_and_create_unix() -> ! {
    // Parsing the first argument as the test directory.
    let args: Vec<String> = std::env::args().collect();
    if args.len() < 2 {
        panic!("Expected exactly one argument for test directory");
    }
    let dir = &args[1];

    // Enter the test directory.
    if let Err(errno) = chdir(Path::new(dir)) {
        eprintln!("Failed to enter test directory {dir}: {errno}!");
        exit(errno as i32);
    }

    // Remove the test directory.
    if let Err(errno) = unlinkat(
        None,
        Path::new(&format!("../{dir}")),
        UnlinkatFlags::RemoveDir,
    ) {
        eprintln!("Failed to remove test directory {dir}: {errno}!");
        exit(errno as i32);
    }

    // Try to bind a UNIX socket in the removed directory.
    let sock = match socket(
        AddressFamily::Unix,
        SockType::Stream,
        SockFlag::SOCK_CLOEXEC,
        None,
    ) {
        Ok(sock) => sock,
        Err(errno) => {
            eprintln!("Unexpected error during UNIX socket creation: {errno}!");
            exit(errno as i32);
        }
    };
    let addr = match UnixAddr::new("escape") {
        Ok(a) => a,
        Err(errno) => {
            eprintln!("Failed to create socket address: {errno}!");
            exit(errno as i32);
        }
    };
    match bind(sock.as_raw_fd(), &addr) {
        Ok(_) => {
            eprintln!("Unexpected socket creation in removed directory!");
            exit(127);
        }
        Err(Errno::EADDRNOTAVAIL) => {
            eprintln!("Unexpected access violation during socket creation in removed directory!");
            exit(Errno::EADDRNOTAVAIL as i32);
        }
        Err(Errno::ENOENT) => {
            eprintln!("Socket creation in removed directory returned ENOENT as expected.");
            exit(0);
        }
        Err(errno) => {
            eprintln!("Unexpected error {errno} during socket creation in removed directory!");
            exit(errno as i32);
        }
    }
}

fn do_rmdir_trailing_slashdot() -> ! {
    // 1. Create test.file as a file, panic on errors
    fs::write("test.file", "").expect("Failed to create test.file");

    // 2. Create test directories, panic on errors
    fs::create_dir("test.dir").expect("Failed to create test.dir");
    fs::create_dir("test.").expect("Failed to create test.");

    // 3. Convert the rmdirs in the C test, fails should cause eprintln!() and context
    let mut result = 0;

    // Try to remove test.file/ (this should fail)
    let path = CString::new("test.file/").unwrap();
    if unsafe { nix::libc::rmdir(path.as_ptr()) } == 0 {
        eprintln!("Unexpected success removing non-directory test.file/");
        result |= 1;
    } else if Errno::last() != nix::errno::Errno::ENOTDIR {
        result |= 2;
        eprintln!("Failed to remove test.file/: {}", Errno::last());
    } else {
        eprintln!("Removing non-directory test.file/ failed with ENOTDIR.");
    }

    // Try to remove test.dir/./ (this should fail with EINVAL)
    let path = CString::new("test.dir/./").unwrap();
    if unsafe { nix::libc::rmdir(path.as_ptr()) } == 0 {
        eprintln!("Unexpected success rmdir'ing path with dot as final component");
        result |= 4;
    } else if Errno::last() != nix::errno::Errno::EINVAL {
        result |= 8;
        eprintln!("Failed to remove test.dir/./: {}", Errno::last());
    } else {
        eprintln!("rmdir'ing path with dot as final component failed with EINVAL.");
    }

    // Try to remove test., this should succeed
    let path = CString::new("test.").unwrap();
    if unsafe { nix::libc::rmdir(path.as_ptr()) } != 0 {
        result |= 16;
        eprintln!("Failed to remove test.: {}", Errno::last());
    } else {
        eprintln!("Removing directory test. succeded.");
    }

    // 5. Exit 0 on success, exit 1 if any fails
    if result == 0 {
        eprintln!("Test succeeded!");
        exit(0);
    } else {
        println!("Test failed with result: {}", result);
        exit(1);
    }
}

fn do_mkdirat_trailing_dot() -> ! {
    // 1. Convert the mkdirats in the C test, fails should cause eprintln!() and context
    let mut result = 0;

    // 2. Try to mkdirat "." (this should fail with EEXIST)
    let path = CString::new(".").unwrap();
    if unsafe { nix::libc::mkdirat(nix::libc::AT_FDCWD, path.as_ptr(), 0o700) } == 0 {
        eprintln!("Unexpected success mkdirat'ing dot");
        result |= 1;
    } else if Errno::last() != Errno::EEXIST {
        result |= 2;
        eprintln!("Failed to mkdirat .: {}", Errno::last());
    } else {
        eprintln!("mkdirat'ing . failed with EEXIST.");
    }

    // 4. Try to mkdirat ".." (this should fail with EEXIST)
    let path = CString::new("..").unwrap();
    if unsafe { nix::libc::mkdirat(nix::libc::AT_FDCWD, path.as_ptr(), 0o700) } == 0 {
        eprintln!("Unexpected success mkdirat'ing ..");
        result |= 4;
    } else if Errno::last() != Errno::EEXIST {
        result |= 8;
        eprintln!("Failed to mkdirat ..: {}", Errno::last());
    } else {
        eprintln!("mkdirat'ing .. failed with EEXIST.");
    }

    // 5. Try to mkdirat conftest.dir/./ (this should fail with ENOENT)
    let path = CString::new("conftest.dir/././././////").unwrap();
    if unsafe { nix::libc::mkdirat(nix::libc::AT_FDCWD, path.as_ptr(), 0o700) } == 0 {
        eprintln!("Unexpected success mkdirat'ing path with dot as final component");
        result |= 16;
    } else if Errno::last() != Errno::ENOENT {
        result |= 32;
        eprintln!(
            "Failed to mkdirat conftest.dir/././././////: {}",
            Errno::last()
        );
    } else {
        eprintln!("mkdirat'ing path with dot as final component failed with ENOENT.");
    }

    // 6. Exit 0 on success, exit 1 if any fails
    if result == 0 {
        eprintln!("Test succeeded!");
        exit(0);
    } else {
        println!("Test failed with result: {}", result);
        exit(1);
    }
}

fn do_mkdir_trailing_dot() -> ! {
    // 1. Convert the mkdirs in the C test, fails should cause eprintln!() and context
    let mut result = 0;

    // 2. Try to mkdir "." (this should fail with EEXIST)
    let path = CString::new(".").unwrap();
    if unsafe { nix::libc::mkdir(path.as_ptr(), 0o700) } == 0 {
        eprintln!("Unexpected success mkdir'ing dot");
        result |= 1;
    } else if Errno::last() != Errno::EEXIST {
        result |= 2;
        eprintln!("Failed to mkdir .: {}", Errno::last());
    } else {
        eprintln!("mkdir'ing . failed with EEXIST.");
    }

    // 3. Try to mkdir ".." (this should fail with EEXIST)
    let path = CString::new("..").unwrap();
    if unsafe { nix::libc::mkdir(path.as_ptr(), 0o700) } == 0 {
        eprintln!("Unexpected success mkdir'ing ..");
        result |= 4;
    } else if Errno::last() != Errno::EEXIST {
        result |= 8;
        eprintln!("Failed to mkdir ..: {}", Errno::last());
    } else {
        eprintln!("mkdir'ing .. failed with EEXIST.");
    }

    // 4. Try to mkdir conftest.dir/./ (this should fail with ENOENT)
    let path = CString::new("conftest.dir/././././////").unwrap();
    if unsafe { nix::libc::mkdir(path.as_ptr(), 0o700) } == 0 {
        eprintln!("Unexpected success mkdir'ing path with dot as final component");
        result |= 16;
    } else if Errno::last() != Errno::ENOENT {
        result |= 32;
        eprintln!(
            "Failed to mkdir conftest.dir/././././////: {}",
            Errno::last()
        );
    } else {
        eprintln!("mkdir'ing path with dot as final component failed with ENOENT.");
    }

    // 5. Exit 0 on success, exit 1 if any fails
    if result == 0 {
        eprintln!("Test succeeded!");
        exit(0);
    } else {
        println!("Test failed with result: {}", result);
        exit(1);
    }
}

fn do_mkdir_symlinks() -> ! {
    let dir = Path::new("/proc/self/cwd/dir");
    let sym = Path::new("/proc/self/cwd/lnk");

    // Create a symlink.
    if let Err(errno) = symlink(dir, sym) {
        eprintln!("Skipping test: symlinks not supported on this file system: {errno}!");
        exit(127);
    }

    // Ensure directory does not exist.
    if let Err(errno) = unlink(dir) {
        if errno != Errno::ENOENT {
            eprintln!("Failed to remove dir before test: {errno}!");
            exit(1);
        }
    }

    // Step 1: Test creating directory through symlink.
    match mkdir(sym, Mode::from_bits_truncate(0o700)) {
        Ok(()) => {
            let _ = unlink(dir);
            println!("Unexpected behavior: Directory created through dangling symlink!");
            exit(3);
        }
        Err(Errno::EEXIST) => {
            eprintln!(
                "Expected behavior: File already exists when creating through dangling symlink!"
            );
        }
        Err(errno) => {
            eprintln!("Unexpected error when creating directory through symlink: {errno}!");
            exit(4);
        }
    }

    // Step 2: Test creating directory through symlink with trailing slash.
    // POSIX requires the creation of directories through a dangling
    // symlink with trailing slash, but GNU does not yet implement that.
    let mut sym_with_slash = PathBuf::from(sym);
    sym_with_slash.push("");
    match mkdir(&sym_with_slash, Mode::from_bits_truncate(0o700)) {
        Ok(()) => {
            // POSIX behavior
            if let Err(errno) = unlinkat(None, dir, UnlinkatFlags::RemoveDir) {
                eprintln!("Failed to remove dir: {errno}");
                exit(5);
            } else {
                println!("Expected POSIX behavior: Directory created through symlink with trailing slash");
            }
        }
        Err(Errno::EEXIST) => {
            // Directory already exists: GNU behavior
            println!("Expected GNU behavior: Directory already exists with trailing slash!");
        }
        Err(errno) => {
            eprintln!("Unexpected error when creating directory through symlink with trailing slash: {errno}");
            exit(6);
        }
    }

    // Step 3: Test creating directory through symlink with trailing dot.
    let sym_with_dot = sym.join(".");
    match mkdir(&sym_with_dot, Mode::from_bits_truncate(0o700)) {
        Ok(()) => {
            eprintln!(
                "Unexpected success when creating directory through symlink with trailing dot!"
            );
            exit(7);
        }
        Err(Errno::ENOENT) => {
            println!("Expected behavior: Directory not found when using trailing dot!");
        }
        Err(errno) => {
            eprintln!("Unexpected error when creating directory through symlink with trailing dot: {errno}!");
            exit(8);
        }
    }

    eprintln!("Test succeeded!");
    exit(0);
}

fn do_fstatat_trailing_slash() -> ! {
    // Create a symlink conftest.sym pointing to conftest.file
    if let Err(error) = symlink("conftest.file", "conftest.sym") {
        eprintln!("Failed to create symlink: {error}");
        exit(1);
    }

    let mut result = 0;
    // Try to newfstatat conftest.sym/ and expect it to fail with ENOENT
    match fstatat(None, "conftest.sym/", AtFlags::AT_SYMLINK_NOFOLLOW) {
        Ok(stat) => {
            eprintln!(
                "Failed: fstatat with trailing slash on dangling symlink succeeded: {stat:?}"
            );
            result |= 1;
        }
        Err(Errno::ENOENT) => {
            eprintln!(
                "Success: newfstatat with trailing slash on dangling symlink returned ENOENT."
            );
        }
        Err(error) => {
            eprintln!("Failed: newfstatat with trailing slash on dangling symlink failed with error: {error}");
            result |= 2;
        }
    }

    File::create("conftest.file").expect("failed to create test file");
    // Try to newfstatat conftest.sym/ and expect it to fail with ENOTDIR
    match fstatat(None, "conftest.sym/", AtFlags::AT_SYMLINK_NOFOLLOW) {
        Ok(stat) => {
            eprintln!(
                "Failed: newfstatat with trailing slash on symlink to non directory succeeded: {stat:?}"
            );
            result |= 4;
        }
        Err(Errno::ENOTDIR) => {
            eprintln!("Success: newfstatat with trailing slash on symlink to non directory returned ENOTDIR.");
        }
        Err(error) => {
            eprintln!("Failed: newfstatat with trailing slash on symlink to non directory failed with error: {error}");
            result |= 8;
        }
    }

    if result == 0 {
        eprintln!("Test succeded!");
        exit(0);
    } else {
        eprintln!("Test failed: {result}");
        exit(1);
    }
}

fn do_lstat_trailing_slash() -> ! {
    // Create a symlink conftest.sym pointing to conftest.file
    if let Err(error) = symlink("conftest.file", "conftest.sym") {
        eprintln!("Failed to create symlink: {error}");
        exit(1);
    }

    let mut result = 0;
    // Try to lstat conftest.sym/ and expect it to fail with ENOENT.
    // Note this may call newfstatat on arches such as aarch64.
    match lstat("conftest.sym/") {
        Ok(stat) => {
            eprintln!("Failed: lstat with trailing slash succeeded: {stat:?}");
            result |= 1;
        }
        Err(Errno::ENOENT) => {
            eprintln!("Success: lstat with trailing slash returned ENOENT.");
        }
        Err(error) => {
            eprintln!("Failed: lstat with trailing slash failed with error: {error}");
            result |= 2;
        }
    }

    File::create("conftest.file").expect("failed to create test file");
    // Try to lstat conftest.sym/ and expect it to fail with ENOTDIR.
    match lstat("conftest.sym/") {
        Ok(stat) => {
            eprintln!("Failed: lstat with trailing slash succeeded: {stat:?}");
            result |= 4;
        }
        Err(Errno::ENOTDIR) => {
            eprintln!("Success: lstat with trailing slash returned ENOTDIR.");
        }
        Err(error) => {
            eprintln!("Failed: lstat with trailing slash failed with error: {error}");
            result |= 8;
        }
    }

    if result == 0 {
        eprintln!("Test succeded!");
        exit(0);
    } else {
        eprintln!("Test failed: {result}");
        exit(1);
    }
}

fn do_openat_trailing_slash() -> ! {
    let mut result = 0;

    // Ensure files are cleaned up first
    let _ = unlink("conftest.tmp");
    let _ = unlink("conftest.lnk");
    let _ = unlinkat(None, "conftest.sl", UnlinkatFlags::RemoveDir);

    // Create files and symlinks required
    File::create("conftest.tmp").expect("Failed to create conftest.tmp");
    mkdir("conftest.sl", Mode::from_bits_truncate(0o700)).expect("Failed to mkdir conftest.sl");
    if let Err(error) = symlink("conftest.tmp", "conftest.lnk") {
        eprintln!("Failed to create symlink: {error}");
        result |= 1;
    }

    // Test openat() with trailing slash on symlink
    match openat(None, "conftest.lnk/", OFlag::O_RDONLY, Mode::empty()) {
        Ok(fd) => {
            eprintln!("openat should not succeed on symlink with trailing slash");
            result |= 2;
            let _ = close(fd);
        }
        Err(Errno::ENOTDIR) => {
            // Expected: openat should fail with ENOTDIR
            eprintln!("openat with trailing slash on symlink failed with ENOTDIR.");
        }
        Err(error) => {
            eprintln!("Unexpected error: {error}");
            result |= 4;
        }
    }

    // Test openat() with trailing slash and O_CREAT
    match openat(
        None,
        "conftest.sl/",
        OFlag::O_CREAT,
        Mode::from_bits_truncate(0o600),
    ) {
        Ok(fd) => {
            eprintln!("openat should not succeed with trailing slash and O_CREAT");
            result |= 8;
            let _ = close(fd);
        }
        Err(Errno::EISDIR) => {
            // Expected: openat should fail with EISDIR
            eprintln!("openat with trailing slash and O_CREAT failed with EISDIR.");
        }
        Err(error) => {
            eprintln!("Unexpected error: {error}");
            result |= 16;
        }
    }

    // Clean up
    let _ = unlink("conftest.tmp");
    let _ = unlink("conftest.lnk");
    let _ = unlinkat(None, "conftest.sl", UnlinkatFlags::RemoveDir);

    if result == 0 {
        eprintln!("Test succeded!");
        exit(0);
    } else {
        eprintln!("Test failed: {result}");
        exit(1);
    }
}

fn do_open_trailing_slash() -> ! {
    let mut result = 0;

    // Ensure files are cleaned up first
    let _ = unlink("conftest.tmp");
    let _ = unlink("conftest.lnk");
    let _ = unlinkat(None, "conftest.sl", UnlinkatFlags::RemoveDir);

    // Create files and symlinks required
    File::create("conftest.tmp").expect("Failed to create conftest.tmp");
    mkdir("conftest.sl", Mode::from_bits_truncate(0o700)).expect("Failed to mkdir conftest.sl");
    if let Err(error) = symlink("conftest.tmp", "conftest.lnk") {
        eprintln!("Failed to create symlink: {error}");
        result |= 1;
    }

    // Test open() with trailing slash on symlink
    match open("conftest.lnk/", OFlag::O_RDONLY, Mode::empty()) {
        Ok(fd) => {
            eprintln!("open should not succeed on symlink with trailing slash");
            result |= 2;
            let _ = close(fd);
        }
        Err(Errno::ENOTDIR) => {
            // Expected: open should fail with ENOTDIR
            eprintln!("open with trailing slash on symlink failed with ENOTDIR.");
        }
        Err(error) => {
            eprintln!("Unexpected error: {error}");
            result |= 4;
        }
    }

    // Test open() with trailing slash and O_CREAT
    match open(
        "conftest.sl/",
        OFlag::O_CREAT,
        Mode::from_bits_truncate(0o600),
    ) {
        Ok(fd) => {
            eprintln!("open should not succeed with trailing slash and O_CREAT");
            result |= 8;
            let _ = close(fd);
        }
        Err(Errno::EISDIR) => {
            // Expected: open should fail with EISDIR
            eprintln!("open with trailing slash and O_CREAT failed with EISDIR.");
        }
        Err(error) => {
            eprintln!("Unexpected error: {error}");
            result |= 16;
        }
    }

    // Clean up
    let _ = unlink("conftest.tmp");
    let _ = unlink("conftest.lnk");
    let _ = unlinkat(None, "conftest.sl", UnlinkatFlags::RemoveDir);

    if result == 0 {
        eprintln!("Test succeded!");
        exit(0);
    } else {
        eprintln!("Test failed: {result}");
        exit(1);
    }
}

fn do_emulate_open_fifo() -> ! {
    fn test_fifo_ipc() {
        let status = Command::new("sh")
            .arg("-c")
            .arg(
                r#"
set -e
rm -f in out
mkfifo in out
(while read -r line; do echo "$line"; done <in >out &)
exec 9>in
exec 8<out
trap 'exec 9>&-' EXIT
trap 'exec 8>&-' EXIT
echo >&9 one
read response <&8
test x"$response" = xone
echo >&9 two
read response <&8
test x"$response" = xtwo
true
"#,
            )
            .status()
            .expect("execute sh");

        if status.code().unwrap_or(127) != 0 {
            eprintln!("Input/output to FIFO failed: {status:?}");
            exit(1);
        }
    }

    // Run multiple times to increase chance of failure.
    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        test_fifo_ipc();

        i += 1;
        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Input/output using a FIFO works fine.");
    exit(0);
}

fn do_access_unsafe_paths() -> ! {
    let mut fails = 0i32;
    let pid = Pid::this();
    let paths = [
        "/dev/mem",
        "/dev/kmem",
        "/dev/port",
        "/dev/cpu/0/msr",
        "/proc/config",
        "/proc/config.gz",
        "/proc/dma",
        "/proc/fs/ext4",
        "/proc/interrupts",
        "/proc/iomem",
        "/proc/ioports",
        "/proc/irq/0",
        "/proc/kallsyms",
        "/proc/kcore",
        "/proc/key-users",
        "/proc/keys",
        "/proc/modules",
        "/proc/mtrr",
        "/proc/partitions",
        "/proc/softirqs",
        "/proc/swaps",
        "/proc/sysrq-trigger",
        "/proc/tty/drivers",
        "/proc/vmallocinfo",
        "/proc/self/auxv",
        "/proc/self/environ",
        "/proc/self/maps",
        "/proc/self/mem",
        "/proc/self/pagemap",
        "/proc/self/personality",
        "/proc/self/stack",
        "/proc/self/syscall",
        "/proc/self/wchan",
        &format!("/proc/self/task/{pid}/auxv"),
        &format!("/proc/self/task/{pid}/environ"),
        &format!("/proc/self/task/{pid}/maps"),
        &format!("/proc/self/task/{pid}/mem"),
        &format!("/proc/self/task/{pid}/pagemap"),
        &format!("/proc/self/task/{pid}/personality"),
        &format!("/proc/self/task/{pid}/stack"),
        &format!("/proc/self/task/{pid}/syscall"),
        &format!("/proc/self/task/{pid}/wchan"),
    ];
    let flags = [OFlag::O_RDONLY, OFlag::O_WRONLY, OFlag::O_RDWR];

    for path in paths {
        for flag in flags {
            eprintln!("\x1b[34m+++ open:{}+{:#x} +++\x1b[0m", path, flag.bits());
            match open(Path::new(path), flag, Mode::empty()) {
                Ok(fd) => {
                    let _ = close(fd);
                    eprintln!("Unexpected success opening file!");
                    fails += 1;
                }
                Err(Errno::ENOENT) => {
                    eprintln!("Failed as expected with error {}!", Errno::ENOENT);
                }
                Err(errno) => {
                    eprintln!("Unexpected fail with error {errno}!");
                    fails += 1;
                }
            }
        }
    }

    if fails == 0 {
        eprintln!("Test succeeded!");
    } else {
        eprintln!("Test failed with {fails} errors!");
    }
    exit(fails);
}

fn do_lstat_magiclinks() -> ! {
    let paths = [
        "/proc/self/cwd",
        "/proc/self/exe",
        "/proc/self/root",
        "/proc/self/fd/0",
        "/proc/self/fd/1",
        "/proc/self/fd/2",
    ];

    let mut fails = 0i32;
    for path in &paths {
        eprintln!("\x1b[34m+++ {path} +++\x1b[0m");
        match lstat(Path::new(path)) {
            Ok(stat) if stat.st_mode & nix::libc::S_IFMT == nix::libc::S_IFLNK => {
                eprintln!("Got symlink correctly from lstat!");
            }
            Ok(stat) => {
                eprintln!("Got bad mode {} from lstat!", stat.st_mode);
                fails += 1;
            }
            Err(e) => {
                eprintln!("Error lstating with error {e}!");
                fails += 1;
            }
        }
    }

    if fails == 0 {
        eprintln!("Test succeeded!");
    } else {
        eprintln!("Test failed with {fails} errors!");
    }
    exit(fails);
}

fn do_deny_magiclinks() -> ! {
    let paths = [
        "/proc/1/fd/0",
        "/proc/1/fd/1",
        "/proc/1/fd/2",
        "/proc/1/task/1/fd/0",
        "/proc/1/task/1/fd/1",
        "/proc/1/task/1/fd/2",
        "/proc/1/cwd",
        "/proc/1/exe",
        "/proc/1/root",
        "/proc/1/task/1/cwd",
        "/proc/1/task/1/exe",
        "/proc/1/task/1/root",
    ];

    let mut fails = 0i32;
    for path in &paths {
        eprintln!("\x1b[34m+++ {path} +++\x1b[0m");
        match open(Path::new(path), OFlag::O_RDONLY, Mode::empty()) {
            Ok(_) => {
                eprintln!("Unexpected success in opening {path}, expected ELOOP error!");
                fails += 1;
            }
            Err(Errno::ELOOP) => {
                eprintln!("Opening {path} returned ELOOP as expected.");
            }
            Err(e) => {
                eprintln!("Error opening {path} with unexpected error {e}!");
                fails += 1;
            }
        }
    }

    if fails == 0 {
        eprintln!("Test succeeded!");
    } else {
        eprintln!("Test failed with {fails} errors!");
    }
    exit(fails);
}

fn do_open_magiclinks() -> ! {
    let bases = ["cwd", "exe", "root"];

    let mut fails = 0i32;
    for base in &bases {
        let path = format!("/proc/self/{base}");

        // Step 1: Opening /proc/self/$base must succeed.
        match open(Path::new(&path), OFlag::O_RDONLY, Mode::empty()) {
            Ok(fd) => {
                let _ = close(fd);
                eprintln!("Opening {path} succeeded as expected!");
            }
            Err(Errno::ENOENT) if *base == "exe" => {
                // XXX: This happens on CI for reasons beyond me...
                eprintln!("Opening {path} returned ENOENT as expected!");
            }
            Err(e) => {
                eprintln!("Error opening {path} with error {e}!");
                fails += 1;
            }
        }

        // Step 2: Opening /proc/self/$base with O_NOFOLLOW must fail.
        match open(
            Path::new(&path),
            OFlag::O_RDONLY | OFlag::O_NOFOLLOW,
            Mode::empty(),
        ) {
            Ok(_) => {
                eprintln!("Unexpected success in opening {path}, expected ELOOP error!");
                fails += 1;
            }
            Err(Errno::ELOOP) => {
                eprintln!("Opening {path} returned ELOOP as expected.");
            }
            Err(e) => {
                eprintln!("Error opening {path} with unexpected error {e}!");
                fails += 1;
            }
        }

        let path = format!("/proc/1/{base}");

        // Step 3: Opening /proc/1/$base must fail.
        match open(Path::new(&path), OFlag::O_RDONLY, Mode::empty()) {
            Ok(fd) => {
                let _ = close(fd);
                eprintln!("Unexpected success in opening {path}, expected ELOOP error!");
                fails += 1;
            }
            Err(Errno::ELOOP) => {
                eprintln!("Opening {path} returned ELOOP as expected.");
            }
            Err(e) => {
                eprintln!("Error opening {path} with unexpected error {e}!");
                fails += 1;
            }
        }
    }

    if fails == 0 {
        eprintln!("Test succeeded!");
    } else {
        eprintln!("Test failed with {fails} errors!");
    }
    exit(fails);
}

fn do_path_resolution() -> ! {
    // Get the current directory's name
    let current_dir = env::current_dir().unwrap();

    // 0. Define the array of test cases
    #[allow(clippy::type_complexity)]
    let test_cases: [(&str, Option<&str>); 15] = [
        // absolute paths, relative paths, and chdir combinations
        ("./test_file.txt", None),
        ("test_file.txt", None),
        ("././test_file.txt", None),
        ("../test_file.txt", Some("./sub_dir")),
        ("../../test_file.txt", Some("./sub_dir/nested_sub_dir")),
        ("sub_dir/../test_file.txt", None),
        ("./sub_dir/../test_file.txt", None),
        ("../../test_file.txt", Some("./sub_dir/nested_sub_dir")),
        ("./../../test_file.txt", Some("./sub_dir/nested_sub_dir")),
        (".//./././//test_file.txt", None),
        ("./////test_file.txt", None),
        ("sub_dir/./../test_file.txt", None),
        ("sub_dir//nested_sub_dir/../..//test_file.txt", None),
        ("./sub_dir/./../test_file.txt", None),
        ("sub_dir/./.././test_file.txt", None),
    ];

    // 1. Create the test file in the current directory
    if let Err(error) = fs::create_dir_all(current_dir.join("./sub_dir/nested_sub_dir")) {
        eprintln!("Failed to create nested directories: {error}");
        exit(1);
    }
    let mut file = match File::create(current_dir.join("test_file.txt")) {
        Ok(f) => f,
        Err(error) => {
            eprintln!("Failed to create test file: {error}");
            exit(1);
        }
    };
    if let Err(error) =
        file.write_all(b"Heavy is the root of light. Still is the master of moving.")
    {
        eprintln!("Failed to write to test file: {error}");
        exit(1);
    }

    let mut fail_count = 0;

    // 2. Probe all test cases one by one
    for (path, chdir_opt) in &test_cases {
        if let Some(chdir) = chdir_opt {
            if let Err(error) = env::set_current_dir(current_dir.join(chdir)) {
                eprintln!("Failed to change directory to {chdir}: {error}");
                exit(1);
            }
        }

        if File::open(path).is_err() {
            eprintln!("Failed to open: {path}, after changing dir to: {chdir_opt:?}");
            fail_count += 1;
        }

        // Reset directory after each test
        if let Err(error) = env::set_current_dir(&current_dir) {
            eprintln!("Failed to reset current directory: {error}");
            exit(1);
        }
    }

    // 3. Exit with the number of test cases failed count
    if fail_count > 0 {
        eprintln!("path_resolution: {fail_count} test cases failed.");
        exit(fail_count);
    } else {
        println!("path_resolution: All test cases passed.");
        exit(0);
    }
}

fn do_utimensat_null() -> ! {
    // We need a proper file descriptor here,
    // e.g. using 0 (ie stdin) fails with EACCES on arm64.
    let file = File::create("utimensat-file").expect("create file");
    match unsafe { nix::libc::syscall(nix::libc::SYS_utimensat, file.as_raw_fd(), 0, 0, 0) } {
        -1 => {
            eprintln!(
                "utimensat with NULL arguments failed with error: {}",
                Errno::last()
            );
            exit(1);
        }
        _ => {
            eprintln!("utimensat with NULL arguments succeeded!");
            exit(0);
        }
    }
}

fn do_open_null_path() -> ! {
    // Attempt to open with NULL argument
    let fd = unsafe { nix::libc::open(std::ptr::null(), nix::libc::O_RDONLY) };

    if fd == -1 {
        let error = Errno::last();
        if error == Errno::EFAULT {
            eprintln!("Failed to open the file with error EFAULT.");
            exit(0);
        } else {
            eprintln!("Failed to open the file with unexpected error: {error}");
            exit(1);
        }
    } else {
        match fs::read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())) {
            Ok(link_path) => {
                eprintln!("Unexpectedly opened a file, it points to: {link_path:?}");
                let _ = close(fd);
                exit(1);
            }
            Err(error) => {
                eprintln!("Error reading the symbolic link: {error}");
                let _ = close(fd);
                exit(1);
            }
        }
    }
}

fn do_open_toolong_path() -> ! {
    // Constructing a path longer than PATH_MAX
    let long_name = PathBuf::from("x".repeat(nix::libc::PATH_MAX as usize + 7));
    let result = open(&long_name, OFlag::O_WRONLY | OFlag::O_CREAT, Mode::empty());

    match result {
        Ok(_) => {
            eprintln!("Successfully opened the file with a path longer than PATH_MAX.");
            exit(1);
        }
        Err(Errno::ENAMETOOLONG) => {
            eprintln!("Failed to open the file with error ENAMETOOLONG.");
            exit(0);
        }
        Err(error) => {
            eprintln!("Failed to open the file with unexpected error: {error}");
            exit(1);
        }
    };
}

fn do_kill_during_syscall() -> ! {
    // Create a pipe for parent-child communication
    let (pipe_r, pipe_w) = match pipe() {
        Ok((r, w)) => (r, w),
        Err(error) => {
            eprintln!("Failed to create pipe: {error}");
            exit(1);
        }
    };

    // Fork
    match unsafe { fork() } {
        Err(error) => {
            eprintln!("Failed to fork: {error}");
            exit(1);
        }
        Ok(ForkResult::Child) => {
            // This is the child process
            drop(pipe_w);

            // Wait for the parent's go-ahead
            let mut buf = [0u8; 1];
            if unsafe {
                nix::libc::read(
                    pipe_r.as_raw_fd(),
                    buf.as_mut_ptr() as *mut nix::libc::c_void,
                    1,
                )
            } <= 0
            {
                eprintln!("Failed to read from pipe: {}", Errno::last());
                unsafe { nix::libc::_exit(1) };
            }

            loop {
                let _ = File::open("/dev/null");
                // The file will be closed automatically when it goes out of scope
            }
        }
        Ok(ForkResult::Parent { child }) => {
            // This is the parent process
            drop(pipe_r);

            // Notify the child to start the loop
            let buf = [1u8; 1];
            if unsafe {
                nix::libc::write(
                    pipe_w.as_raw_fd(),
                    buf.as_ptr() as *const nix::libc::c_void,
                    1,
                )
            } <= 0
            {
                eprintln!("Failed to write to pipe: {}", Errno::last());
                exit(1);
            }

            // Get a random duration between 1 to 10 seconds using getrandom
            let mut random_duration = [0u8; 1];
            if unsafe {
                nix::libc::getrandom(random_duration.as_mut_ptr() as *mut nix::libc::c_void, 1, 0)
            } == -1
            {
                eprintln!(
                    "Failed to get random bytes using getrandom: {}",
                    Errno::last()
                );
                exit(1);
            }
            let wait_seconds = 1 + (random_duration[0] % 10) as u64;
            sleep(Duration::from_secs(wait_seconds));

            // Kill the child and wait a bit.
            unsafe { nix::libc::kill(child.as_raw(), nix::libc::SIGKILL) };
            sleep(Duration::from_secs(wait_seconds));

            // If we caused the sandbox poll thread to exit,
            // then the following open call must block forever.
            match File::open("/dev/null") {
                Ok(_) => {
                    eprintln!("Successfully opened file after killing child.");
                    exit(0);
                }
                Err(error) => {
                    eprintln!("Unexpected error opening /dev/null: {error}");
                    exit(1);
                }
            };
        }
    };
}

fn do_block_dev_random() -> ! {
    const BUF_SIZE: usize = 2; // arbitrary size for the test
    let mut buf = [0u8; BUF_SIZE];

    // Step 1: Access /dev/random
    match unsafe {
        nix::libc::getrandom(
            buf.as_mut_ptr() as *mut nix::libc::c_void,
            BUF_SIZE,
            nix::libc::GRND_RANDOM,
        )
    } {
        -1 if Errno::last() == Errno::EACCES => {
            eprintln!("Sandbox denied access to /dev/random.");
        }
        -1 => {
            eprintln!("Unexpected error accessing /dev/random: {}", Errno::last());
            exit(1);
        }
        _ => {
            eprintln!("Sandbox allowed access to /dev/random!");
            exit(1);
        }
    };

    // Step 2: Access /dev/random in non-blocking mode.
    match unsafe {
        nix::libc::getrandom(
            buf.as_mut_ptr() as *mut nix::libc::c_void,
            BUF_SIZE,
            nix::libc::GRND_RANDOM | nix::libc::GRND_NONBLOCK,
        )
    } {
        -1 if Errno::last() == Errno::EACCES => {
            eprintln!("Sandbox denied access to /dev/random in non-blocking mode.");
        }
        -1 => {
            eprintln!(
                "Unexpected error accessing /dev/random in non-blocking mode: {}",
                Errno::last()
            );
            exit(1);
        }
        _ => {
            eprintln!("Sandbox allowed access to /dev/random in non-blocking mode!");
            exit(1);
        }
    };

    // Step 3: Access /dev/urandom
    match unsafe { nix::libc::getrandom(buf.as_mut_ptr() as *mut nix::libc::c_void, BUF_SIZE, 0) } {
        -1 if Errno::last() == Errno::EACCES => {
            eprintln!("Sandbox denied access to /dev/urandom!");
            exit(1);
        }
        -1 => {
            eprintln!("Error accessing /dev/urandom: {}", Errno::last());
        }
        _ => {
            eprintln!("Sandbox allowed access to /dev/urandom.");
        }
    };

    // Step 4: Access /dev/urandom
    match unsafe {
        nix::libc::getrandom(
            buf.as_mut_ptr() as *mut nix::libc::c_void,
            BUF_SIZE,
            nix::libc::GRND_NONBLOCK,
        )
    } {
        -1 if Errno::last() == Errno::EACCES => {
            eprintln!("Sandbox denied access to /dev/urandom in non-blocking mode!");
            exit(1);
        }
        -1 => {
            eprintln!(
                "Error accessing /dev/urandom in non-blocking mode: {}",
                Errno::last()
            );
            exit(0);
        }
        _ => {
            eprintln!("Sandbox allowed access to /dev/urandom in non-blocking mode.");
            exit(0);
        }
    };
}

fn do_block_dev_urandom() -> ! {
    const BUF_SIZE: usize = 2; // arbitrary size for the test
    let mut buf = [0u8; BUF_SIZE];

    // Step 1: Access /dev/urandom
    match unsafe { nix::libc::getrandom(buf.as_mut_ptr() as *mut nix::libc::c_void, BUF_SIZE, 0) } {
        -1 if Errno::last() == Errno::EACCES => {
            eprintln!("Sandbox denied access to /dev/urandom.");
        }
        -1 => {
            eprintln!("Unexpected error accessing /dev/urandom: {}", Errno::last());
            exit(1);
        }
        _ => {
            eprintln!("Sandbox allowed access to /dev/urandom!");
            exit(1);
        }
    };

    // Step 2: Access /dev/urandom in non-blocking mode.
    match unsafe {
        nix::libc::getrandom(
            buf.as_mut_ptr() as *mut nix::libc::c_void,
            BUF_SIZE,
            nix::libc::GRND_NONBLOCK,
        )
    } {
        -1 if Errno::last() == Errno::EACCES => {
            eprintln!("Sandbox denied access to /dev/urandom in non-blocking mode.");
        }
        -1 => {
            eprintln!(
                "Unexpected error accessing /dev/urandom in non-blocking mode: {}",
                Errno::last()
            );
            exit(1);
        }
        _ => {
            eprintln!("Sandbox allowed access to /dev/urandom in non-blocking mode!");
            exit(1);
        }
    };

    // Step 3: Access /dev/random
    match unsafe {
        nix::libc::getrandom(
            buf.as_mut_ptr() as *mut nix::libc::c_void,
            BUF_SIZE,
            nix::libc::GRND_RANDOM,
        )
    } {
        -1 if Errno::last() == Errno::EACCES => {
            eprintln!("Sandbox denied access to /dev/random!");
            exit(1);
        }
        -1 => {
            eprintln!("Error accessing /dev/random: {}", Errno::last());
        }
        _ => {
            eprintln!("Sandbox allowed access to /dev/random.");
        }
    };

    // Step 4: Access /dev/random in non-blocking-mode.
    match unsafe {
        nix::libc::getrandom(
            buf.as_mut_ptr() as *mut nix::libc::c_void,
            BUF_SIZE,
            nix::libc::GRND_RANDOM | nix::libc::GRND_NONBLOCK,
        )
    } {
        -1 if Errno::last() == Errno::EACCES => {
            eprintln!("Sandbox denied access to /dev/random in non-blocking mode!");
            exit(1);
        }
        -1 => {
            eprintln!(
                "Error accessing /dev/random in non-blocking mode: {}",
                Errno::last()
            );
            exit(0);
        }
        _ => {
            eprintln!("Sandbox allowed access to /dev/random in non-blocking mode.");
            exit(0);
        }
    };
}

fn do_block_prctl_ptrace() -> ! {
    // Try to set the calling process as its own tracer.
    unsafe {
        nix::libc::prctl(
            nix::libc::PR_SET_PTRACER,
            Pid::this().as_raw() as u64,
            0,
            0,
            0,
        )
    };
    match Errno::last() {
        Errno::ENOSYS => {
            eprintln!("Successfully blocked by sandbox.");
            exit(0);
        }
        Errno::UnknownErrno => {
            eprintln!("Sandbox escape possible, prctl did not block the action.");
            exit(1);
        }
        errno => {
            eprintln!("Unexpected error: {errno}");
            exit(1);
        }
    }
}

fn do_block_ioctl_tiocsti() -> ! {
    let c = 'x';
    unsafe {
        nix::libc::ioctl(
            nix::libc::STDIN_FILENO,
            nix::libc::TIOCSTI,
            &c as *const _ as *const _,
        )
    };
    match Errno::last() {
        Errno::EACCES => {
            eprintln!("syd blocked write access to the controlling terminal.");
            exit(0);
        }
        Errno::UnknownErrno => {
            eprintln!("syd allowed write access to the controlling terminal.");
            exit(1);
        }
        errno => {
            eprintln!(
                "syd did not block write access to the controlling terminal properly: {errno}"
            );
            exit(1);
        }
    }
}

fn do_fstat_on_temp_file() -> ! {
    let fd = match openat(
        None,
        "",
        OFlag::O_WRONLY | OFlag::O_TMPFILE,
        Mode::from_bits_truncate(0o600),
    ) {
        Ok(fd) => fd,
        Err(error) => {
            eprintln!("Error creating file with O_TMPFILE: {error}");
            if error == Errno::EOPNOTSUPP {
                eprintln!("Filesystem does not support O_TMPFILE, skipping!");
                exit(0);
            } else {
                exit(1);
            }
        }
    };

    match fstat(fd) {
        Err(error) => {
            eprintln!("Failed to fstat the temporary file fd: {error}");
            exit(1);
        }
        Ok(stat) => {
            // Check if this is a regular file.
            if stat.st_mode & SFlag::S_IFMT.bits() != SFlag::S_IFREG.bits() {
                eprintln!("The stat did not return a regular file.");
                exit(1);
            }
        }
    }

    exit(0);
}

fn do_fstat_on_deleted_file() -> ! {
    let fd = match open(
        "test-deleted",
        OFlag::O_WRONLY | OFlag::O_CREAT,
        Mode::S_IRUSR | Mode::S_IWUSR,
    ) {
        Ok(fd) => fd,
        Err(error) => {
            eprintln!("Error creating test file: {error}");
            exit(1);
        }
    };

    let stat_orig = match fstat(fd) {
        Ok(stat) => stat,
        Err(error) => {
            eprintln!("Failed to stat file: {error}");
            exit(1);
        }
    };

    if let Err(error) = unlink("test-deleted") {
        eprintln!("Failed to remove test file: {error}");
        exit(1);
    }

    match fstat(fd) {
        Err(error) => {
            eprintln!("Failed to fstat the deleted file fd: {error}");
            exit(1);
        }
        Ok(stat) => {
            if stat.st_dev != stat_orig.st_dev || stat.st_ino != stat_orig.st_ino {
                eprintln!("fstat returned incorrect result");
                exit(1);
            }
        }
    }

    exit(0);
}

fn do_fstat_on_socket() -> ! {
    let fd = match socket(
        AddressFamily::Unix,
        SockType::Stream,
        SockFlag::empty(),
        None,
    ) {
        Ok(fd) => fd,
        Err(error) => {
            eprintln!("Failed to create socket: {error}");
            exit(1);
        }
    };

    match fstat(fd.as_raw_fd()) {
        Ok(stat) => {
            eprintln!("fstat on socket fd: {stat:?}");
            exit(0);
        }
        Err(error) => {
            eprintln!("Failed to fstat the socket fd: {error}");
            exit(1);
        }
    }
}

fn do_fstat_on_pipe() -> ! {
    let (pipe_r, pipe_w) = match pipe() {
        Ok((r, w)) => (r, w),
        Err(error) => {
            eprintln!("Failed to create pipe: {error}");
            exit(1);
        }
    };

    let mut r = 0;
    if let Err(error) = fstat(pipe_r.as_raw_fd()) {
        eprintln!("Failed to fstat the read end of the pipe: {error}");
        r += 1;
    }
    if let Err(error) = fstat(pipe_w.as_raw_fd()) {
        eprintln!("Failed to fstat the write end of the pipe: {error}");
        r += 1;
    }
    exit(r);
}

fn do_fchmodat_on_proc_fd() -> ! {
    // Step 1: Create a file
    let fd = match open(
        "fchmodat-test",
        OFlag::O_WRONLY | OFlag::O_CREAT,
        Mode::S_IRUSR | Mode::S_IWUSR,
    ) {
        Ok(fd) => fd,
        Err(error) => {
            eprintln!("Error creating test file: {error}");
            exit(1);
        }
    };

    // Step 2 & 3: Call fchmodat and assert new mode
    let new_mode = Mode::S_IRUSR;
    let fd_path = PathBuf::from(format!("/proc/self/fd/{}", fd.as_raw_fd()));
    if let Err(error) = fchmodat(None, &fd_path, new_mode, FchmodatFlags::FollowSymlink) {
        eprintln!("Failed to change mode of file: {error}");
        exit(1);
    }

    // Step 4: Stat the file and check the mode
    let file_stat = match stat("fchmodat-test") {
        Ok(stat) => stat,
        Err(error) => {
            eprintln!("Failed to stat file: {error}");
            exit(1);
        }
    };

    let actual_mode = file_stat.st_mode & 0o777;
    if actual_mode != new_mode.bits() {
        eprintln!(
            "File mode did not change as expected: {} != {}",
            actual_mode,
            new_mode.bits()
        );
        exit(1);
    }

    eprintln!("Test succeded!");
    exit(0);
}

fn do_linkat_on_fd() -> ! {
    // Step 1: Create file "linkat-file"
    let file = match File::create("linkat-file") {
        Ok(file) => file,
        Err(error) => {
            eprintln!("Error creating 'linkat-file': {error}");
            exit(1);
        }
    };

    // Step 2: Open "linkat-file"
    let fd = file.as_raw_fd();

    // Step 3: Use linkat to link
    let old_path = "";
    let new_path = "linkat-link";

    if old_path
        .with_nix_path(|oldcstr| {
            new_path.with_nix_path(|newcstr| unsafe {
                nix::libc::linkat(
                    fd,
                    oldcstr.as_ptr(),
                    nix::libc::AT_FDCWD,
                    newcstr.as_ptr(),
                    nix::libc::AT_EMPTY_PATH,
                )
            })
        })
        .unwrap()
        .unwrap()
        != 0
    {
        let errno = Errno::last();
        if errno == Errno::ENOENT {
            eprintln!("linkat returned ENOENT");
            eprintln!("Missing CAP_DAC_READ_SEARCH?");
            eprintln!("Skipping test!");
            exit(0);
        } else {
            eprintln!("Failed to create link using linkat: {}", Errno::last());
            exit(1);
        }
    }

    // Step 4: Check if "new-file" exists and is the same inode
    let stat_original = match stat("linkat-file") {
        Ok(stat) => stat,
        Err(error) => {
            eprintln!("Failed to stat 'linkat-file': {error}");
            exit(1);
        }
    };

    let stat_new = match stat("linkat-link") {
        Ok(stat) => stat,
        Err(error) => {
            eprintln!("Failed to stat 'linkat-link': {error}");
            exit(1);
        }
    };

    if stat_original.st_ino != stat_new.st_ino {
        eprintln!(
            "Inode numbers do not match: {} != {}",
            stat_original.st_ino, stat_new.st_ino
        );
        exit(1);
    }

    eprintln!("Test succeeded!");
    exit(0);
}

fn do_exec_in_inaccessible_directory() -> ! {
    // Create a directory
    let dir_name = "inaccessible_dir";
    if let Err(error) = mkdir(dir_name, Mode::S_IRWXU) {
        eprintln!("Error creating directory: {error}.");
        exit(1);
    }

    // Change into the directory
    if let Err(error) = chdir(dir_name) {
        eprintln!("Error changing into directory: {error}.");
        exit(1);
    }

    // Make the directory inaccessible
    if let Err(error) = fchmodat(None, ".", Mode::empty(), FchmodatFlags::FollowSymlink) {
        eprintln!("Error changing permissions: {error}");
        exit(1);
    }

    // Try to execute "bash -c true"
    let output = Command::new("bash").args(["-c", "true"]).output();

    match output {
        Ok(output) => {
            if !output.status.success() {
                eprintln!("Failed to execute \"bash -c true\"");
                eprintln!("Stdout: {}", String::from_utf8_lossy(&output.stdout));
                eprintln!("Stderr: {}", String::from_utf8_lossy(&output.stderr));
                exit(1);
            }
        }
        Err(error) => {
            eprintln!("Error executing \"bash -c true\": {error}.");
            exit(1);
        }
    }

    exit(0);
}

fn do_open_utf8_invalid() -> ! {
    // "test-" followed by invalid UTF-8 bytes
    let invalid_name = OsString::from_vec(
        b"test-"
            .iter()
            .copied()
            .chain(vec![0xFF, 0xFF, 0xFF])
            .collect(),
    );
    let invalid_path = OsStr::new(&invalid_name);

    let fd = match open(
        invalid_path,
        OFlag::O_WRONLY | OFlag::O_CREAT,
        Mode::S_IRUSR | Mode::S_IWUSR,
    ) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(error) => {
            eprintln!("Failed to create a file with invalid UTF-8 path: {error}.");
            exit(1);
        }
    };

    if let Err(error) = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.",
    ) {
        eprintln!("Failed to write to a file with invalid UTF-8 path: {error}.");
        exit(1);
    }

    if let Err(error) = unlink(invalid_path) {
        eprintln!("Failed to remove a file with invalid UTF-8 path: {error}.");
        exit(1);
    }

    eprintln!("File with invalid UTF-8 path was successfully created and written to.");
    exit(0);
}

fn do_force_umask_bypass_with_open() -> ! {
    let _ = umask(Mode::empty());
    let _ = fs::remove_file("noexec");

    let file = OpenOptions::new()
        .write(true)
        .create(true)
        .mode(0o755)
        .custom_flags(nix::libc::O_EXCL)
        .open("noexec")
        .expect("Failed to create file");
    drop(file);

    // Get the file metadata to retrieve the permissions.
    let metadata = fs::metadata("noexec").expect("Failed to get file metadata");
    let permissions = metadata.permissions();

    // Get the current permissions of the file.
    let current_mode = permissions.mode();

    // Check if the file is executable.
    if current_mode & 0o111 == 0o111 {
        eprintln!("Successfully set the executable bits!");
        eprintln!("Test failed: force_umask was bypassed!");
        exit(1);
    } else {
        eprintln!("Failed to set executable bits.");
        eprintln!("Test succeeded: force_umask was not bypassed!");
        exit(0);
    }
}

fn do_force_umask_bypass_with_mknod() -> ! {
    let _ = umask(Mode::empty());
    let _ = fs::remove_file("noexec");

    mknod("noexec", SFlag::S_IFREG, Mode::from_bits_truncate(0o755), 0)
        .expect("Failed to create file");

    // Get the file metadata to retrieve the permissions.
    let metadata = fs::metadata("noexec").expect("Failed to get file metadata");
    let permissions = metadata.permissions();

    // Get the current permissions of the file.
    let current_mode = permissions.mode();

    // Check if the file is executable.
    if current_mode & 0o111 == 0o111 {
        eprintln!("Successfully set the executable bits!");
        eprintln!("Test failed: force_umask was bypassed!");
        exit(1);
    } else {
        eprintln!("Failed to set executable bits.");
        eprintln!("Test succeeded: force_umask was not bypassed!");
        exit(0);
    }
}

fn do_force_umask_bypass_with_mkdir() -> ! {
    let _ = umask(Mode::empty());
    let _ = fs::remove_dir("noexec");
    let _ = fs::remove_file("noexec");

    mkdir("noexec", Mode::from_bits_truncate(0o755)).expect("Failed to create file");

    // Get the file metadata to retrieve the permissions.
    let metadata = fs::metadata("noexec").expect("Failed to get file metadata");
    let permissions = metadata.permissions();

    // Get the current permissions of the file.
    let current_mode = permissions.mode();

    // Check if the file is executable.
    if current_mode & 0o111 == 0o111 {
        eprintln!("Successfully set the executable bits!");
        eprintln!("Test failed: force_umask was bypassed!");
        exit(1);
    } else {
        eprintln!("Failed to set executable bits.");
        eprintln!("Test succeeded: force_umask was not bypassed!");
        exit(0);
    }
}

fn do_force_umask_bypass_with_fchmod() -> ! {
    let _ = umask(Mode::empty());
    let _ = fs::remove_file("noexec");

    let file = OpenOptions::new()
        .write(true)
        .create(true)
        .mode(0o644)
        .custom_flags(nix::libc::O_EXCL)
        .open("noexec")
        .expect("Failed to create file");
    drop(file);

    // Expects the file "noexec" to be present.
    let file = File::open("noexec").expect("Failed to open file");

    // Get the file metadata to retrieve the permissions.
    let metadata = fs::metadata("noexec").expect("Failed to get file metadata");
    let mut permissions = metadata.permissions();

    // Get the current permissions of the file.
    let current_mode = permissions.mode();

    // Check if the file is already executable.
    if current_mode & 0o111 == 0o111 {
        panic!("Unexpected file mode {current_mode:o} after create!");
    }

    // Add executable bits to the permissions.
    let new_mode = current_mode | 0o111;
    permissions.set_mode(new_mode);

    // Set the new permissions using nix's fchmod.
    fchmod(file.as_raw_fd(), Mode::from_bits_truncate(new_mode))
        .expect("Failed to change file permissions");

    // Verify if the permissions have been updated.
    let updated_metadata = fs::metadata("noexec").expect("Failed to get updated file metadata");
    let updated_mode = updated_metadata.permissions().mode();

    eprintln!("Mode change {current_mode:o} -> {updated_mode:o}.");
    if updated_mode & 0o111 == 0o111 {
        eprintln!("Successfully set the executable bits!");
        eprintln!("Test failed: force_umask was bypassed!");
        exit(1);
    } else {
        eprintln!("Failed to set executable bits.");
        eprintln!("Test succeeded: force_umask was not bypassed!");
        exit(0);
    }
}

fn do_honor_umask() -> ! {
    // Parsing the first argument as an octal mode
    let args: Vec<String> = std::env::args().collect();
    if args.len() < 2 {
        eprintln!("Expected exactly one argument for expected file mode");
        exit(1);
    }

    let mode_exp: u32 = u32::from_str_radix(&args[1], 8).expect("Failed to parse mode as octal");

    let path = "test";
    File::create(path).expect("Failed to create file");

    // Checking the file's mode
    let metadata = fs::metadata(path).expect("Failed to get metadata");
    let permissions = metadata.permissions();
    let mode = permissions.mode() & 0o777; // Masking to get the last 3 octal digits

    if mode == mode_exp {
        exit(0);
    } else {
        eprintln!("Mode {mode:o} != {mode_exp:o}");
        exit(1);
    }
}

fn do_emulate_otmpfile() -> ! {
    match open(
        "",
        OFlag::O_WRONLY | OFlag::O_TMPFILE,
        Mode::from_bits_truncate(0o600),
    ) {
        Ok(_) => exit(0),
        Err(error) => {
            eprintln!("Failed to open file with O_TMPFILE flag: {error}");
            if error == Errno::EOPNOTSUPP {
                eprintln!("Filesystem does not support O_TMPFILE, skipping!");
                exit(0);
            } else {
                exit(1);
            }
        }
    }
}

fn do_emulate_opath() -> ! {
    let fd = open(
        ".",
        OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_PATH,
        Mode::from_bits_truncate(0o600),
    )
    .expect("failed to open current directory");
    let file = openat(
        Some(fd),
        "emulate",
        OFlag::O_WRONLY | OFlag::O_CREAT,
        Mode::from_bits_truncate(0o600),
    )
    .expect("failed to open file with O_PATH fd");

    let _ = close(fd);
    let _ = close(file);

    exit(0);
}

fn do_umask_bypass_277() -> ! {
    let path = "umask";
    let prev_umask = umask(Mode::from_bits_truncate(0o277));

    // Create a file with 0777 permissions
    let fd = open(
        path,
        OFlag::O_CREAT | OFlag::O_WRONLY,
        Mode::from_bits_truncate(0o777),
    )
    .expect("Failed to create test file");

    // Reset umask to its previous value
    let _ = umask(prev_umask);

    // Close the file descriptor
    let _ = close(fd);

    // Check the file's permissions
    let metadata = fs::metadata(path).expect("Failed to retrieve test file metadata");
    let permissions = metadata.permissions().mode() & 0o777;

    // Verify that the umask was applied correctly
    if permissions == (0o777 & !0o277) {
        eprintln!("Umask was applied correctly.");
        exit(0);
    } else {
        eprintln!(
            "Umask was not applied correctly. Expected: {:o}, Found: {:o}",
            0o777 & !0o277,
            permissions
        );
        std::process::exit(1);
    }
}

fn do_umask_bypass_077() -> ! {
    let path = "umask";
    let prev_umask = umask(Mode::from_bits_truncate(0o077));

    // Create a file with 0777 permissions
    let fd = open(
        path,
        OFlag::O_CREAT | OFlag::O_WRONLY,
        Mode::from_bits_truncate(0o777),
    )
    .expect("Failed to create test file");

    // Reset umask to its previous value
    let _ = umask(prev_umask);

    // Close the file descriptor
    let _ = close(fd);

    // Check the file's permissions
    let metadata = fs::metadata(path).expect("Failed to retrieve test file metadata");
    let permissions = metadata.permissions().mode() & 0o777;

    // Verify that the umask was applied correctly
    if permissions == (0o777 & !0o077) {
        eprintln!("Umask was applied correctly.");
        exit(0);
    } else {
        eprintln!(
            "Umask was not applied correctly. Expected: {:o}, Found: {:o}",
            0o777 & !0o077,
            permissions
        );
        std::process::exit(1);
    }
}

fn do_devfd_escape_open() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("fd/{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_1() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("fd/./{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_2() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("./fd/{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_3() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("./fd/././{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_4() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("fd/../fd/{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_5() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("./././fd/{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_6() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("foo/../fd/{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_7() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("fd/foo/..//{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_8() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("fd/foo/.././{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_9() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("fd/foo/bar/../../{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_10() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("././fd/foo/../././{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_11() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("fd/./././foo/../{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_12() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("fd/bar/./../{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_13() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("foo/bar/../../fd/{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_14() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("foo/./bar/../../fd/{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_15() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("././foo/../fd/././{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_16() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("fd/././foo/bar/../.././{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_17() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("fd/foo/./bar/../../{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_18() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("./fd/./bar/.././{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_19() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("fd/.././fd/./{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_devfd_escape_open_relpath_20() -> ! {
    // Create and open a temporary test file with O_RDWR
    let fd = open("test", OFlag::O_RDWR | OFlag::O_CREAT, Mode::S_IRWXU).unwrap_or_else(|error| {
        eprintln!("Failed to create and open the test file: {error}.");
        exit(1);
    });
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    // Write some data to the file
    let _ = write(
        &fd,
        b"Heavy is the root of light. Still is the master of moving.\n",
    );

    // Stat the test file to get its attributes
    let test_stat = fstat(fd.as_raw_fd()).unwrap_or_else(|error| {
        eprintln!("Failed to stat the test file: {error}.");
        exit(1);
    });

    // Open /dev with O_PATH
    let dev_fd = open("/dev", OFlag::O_PATH, Mode::empty()).unwrap_or_else(|error| {
        eprintln!("Failed to open /dev with O_PATH: {error}.");
        exit(1);
    });

    // Construct the path to /dev/fd/{fd}
    let fd_path = format!("fd/./././././././{}", fd.as_raw_fd());
    let fd_path = Path::new(&fd_path);

    // Stat the file via /dev/fd/{fd}
    let linked_fd =
        openat(Some(dev_fd), fd_path, OFlag::O_RDONLY, Mode::empty()).unwrap_or_else(|error| {
            if error == Errno::ENOENT {
                eprintln!("Skipping test: /dev/fd does not exist!");
                exit(0);
            } else {
                eprintln!("Escaped sandbox due to failed access to file via /dev/fd/: {error}.");
                exit(1);
            }
        });

    let dev_fd_stat = fstat(linked_fd).unwrap_or_else(|error| {
        eprintln!("Escaped sandbox due to failed stat on the file via /dev/fd/: {error}.");
        exit(1);
    });

    // Check if the attributes match
    if dev_fd_stat.st_dev == test_stat.st_dev && dev_fd_stat.st_ino == test_stat.st_ino {
        eprintln!("Failed to escape sandbox, we accessed the identical file.");
        exit(0);
    } else {
        eprintln!("Escaped sandbox: File accessed via /dev/fd/ is different than the test file.");
        exit(1);
    }
}

fn do_procself_escape_open() -> ! {
    // Open /proc with O_PATH
    let proc_fd = open("/proc", OFlag::O_PATH, Mode::empty()).expect("Failed to open /proc");

    // Open /proc/self/status with the above file descriptor
    let fd = openat(Some(proc_fd), "self/status", OFlag::O_RDONLY, Mode::empty())
        .expect("Failed to open /proc/self/status using openat");

    // Close the /proc fd
    let _ = close(proc_fd);

    // Read the file
    let mut buf = vec![0; 128];
    let n = read(fd, &mut buf).expect("Failed to read /proc/self/status");

    // Close the status fd
    let _ = close(fd);

    // Perform a lossy conversion to UTF-8
    let content = String::from_utf8_lossy(&buf[..n]);

    // Check for `syd'
    if content.contains("Name:\tsyd\n") || content.contains("Name:\tsydbox\n") {
        eprintln!("Escaped sandbox by opening /proc as O_DIRECTORY.");
        eprintln!("Snippet from /proc/sydbox/status which is not /proc/pid/status:");
        eprintln!("{content}");
        exit(1);
    } else {
        exit(0);
    }
}

fn do_procself_escape_open_relpath_1() -> ! {
    // Open /proc with O_PATH
    let proc_fd = open("/proc", OFlag::O_PATH, Mode::empty()).expect("Failed to open /proc");

    // Open /proc/self/status with the above file descriptor
    let fd = openat(
        Some(proc_fd),
        "self/./status",
        OFlag::O_RDONLY,
        Mode::empty(),
    )
    .expect("Failed to open /proc/self/status using openat");

    // Close the /proc fd
    let _ = close(proc_fd);

    // Read the file
    let mut buf = vec![0; 128];
    let n = read(fd, &mut buf).expect("Failed to read /proc/self/status");

    // Close the status fd
    let _ = close(fd);

    // Perform a lossy conversion to UTF-8
    let content = String::from_utf8_lossy(&buf[..n]);

    // Check for `syd'
    if content.contains("Name:\tsyd\n") || content.contains("Name:\tsydbox\n") {
        eprintln!("Escaped sandbox by opening /proc as O_DIRECTORY.");
        eprintln!("Snippet from /proc/sydbox/status which is not /proc/pid/status:");
        eprintln!("{content}");
        exit(1);
    } else {
        exit(0);
    }
}

fn do_procself_escape_open_relpath_2() -> ! {
    // Open /proc with O_PATH
    let proc_fd = open("/proc", OFlag::O_PATH, Mode::empty()).expect("Failed to open /proc");

    // Open /proc/self/status with the above file descriptor
    let fd = openat(
        Some(proc_fd),
        "./self/status",
        OFlag::O_RDONLY,
        Mode::empty(),
    )
    .expect("Failed to open /proc/self/status using openat");

    // Close the /proc fd
    let _ = close(proc_fd);

    // Read the file
    let mut buf = vec![0; 128];
    let n = read(fd, &mut buf).expect("Failed to read /proc/self/status");

    // Close the status fd
    let _ = close(fd);

    // Perform a lossy conversion to UTF-8
    let content = String::from_utf8_lossy(&buf[..n]);

    // Check for `syd'
    if content.contains("Name:\tsyd\n") || content.contains("Name:\tsydbox\n") {
        eprintln!("Escaped sandbox by opening /proc as O_DIRECTORY.");
        eprintln!("Snippet from /proc/sydbox/status which is not /proc/pid/status:");
        eprintln!("{content}");
        exit(1);
    } else {
        exit(0);
    }
}

fn do_procself_escape_open_relpath_3() -> ! {
    // Open /proc with O_PATH
    let proc_fd = open("/proc", OFlag::O_PATH, Mode::empty()).expect("Failed to open /proc");

    // Open /proc/self/status with the above file descriptor
    let fd = openat(
        Some(proc_fd),
        "./self/././status",
        OFlag::O_RDONLY,
        Mode::empty(),
    )
    .expect("Failed to open /proc/self/status using openat");

    // Close the /proc fd
    let _ = close(proc_fd);

    // Read the file
    let mut buf = vec![0; 128];
    let n = read(fd, &mut buf).expect("Failed to read /proc/self/status");

    // Close the status fd
    let _ = close(fd);

    // Perform a lossy conversion to UTF-8
    let content = String::from_utf8_lossy(&buf[..n]);

    // Check for `syd'
    if content.contains("Name:\tsyd\n") || content.contains("Name:\tsydbox\n") {
        eprintln!("Escaped sandbox by opening /proc as O_DIRECTORY.");
        eprintln!("Snippet from /proc/sydbox/status which is not /proc/pid/status:");
        eprintln!("{content}");
        exit(1);
    } else {
        exit(0);
    }
}

fn do_procself_escape_open_relpath_4() -> ! {
    // Open /proc with O_PATH
    let proc_fd = open("/proc", OFlag::O_PATH, Mode::empty()).expect("Failed to open /proc");

    // Open /proc/self/status with the above file descriptor
    let fd = openat(
        Some(proc_fd),
        "self/../self/status",
        OFlag::O_RDONLY,
        Mode::empty(),
    )
    .expect("Failed to open /proc/self/status using openat");

    // Close the /proc fd
    let _ = close(proc_fd);

    // Read the file
    let mut buf = vec![0; 128];
    let n = read(fd, &mut buf).expect("Failed to read /proc/self/status");

    // Close the status fd
    let _ = close(fd);

    // Perform a lossy conversion to UTF-8
    let content = String::from_utf8_lossy(&buf[..n]);

    // Check for `syd'
    if content.contains("Name:\tsyd\n") || content.contains("Name:\tsydbox\n") {
        eprintln!("Escaped sandbox by opening /proc as O_DIRECTORY.");
        eprintln!("Snippet from /proc/sydbox/status which is not /proc/pid/status:");
        eprintln!("{content}");
        exit(1);
    } else {
        exit(0);
    }
}

fn do_procself_escape_open_relpath_5() -> ! {
    // Open /proc with O_PATH
    let proc_fd = open("/proc", OFlag::O_PATH, Mode::empty()).expect("Failed to open /proc");

    // Open /proc/self/status with the above file descriptor
    let fd = openat(
        Some(proc_fd),
        "./././self/status",
        OFlag::O_RDONLY,
        Mode::empty(),
    )
    .expect("Failed to open /proc/self/status using openat");

    // Close the /proc fd
    let _ = close(proc_fd);

    // Read the file
    let mut buf = vec![0; 128];
    let n = read(fd, &mut buf).expect("Failed to read /proc/self/status");

    // Close the status fd
    let _ = close(fd);

    // Perform a lossy conversion to UTF-8
    let content = String::from_utf8_lossy(&buf[..n]);

    // Check for `syd'
    if content.contains("Name:\tsyd\n") || content.contains("Name:\tsydbox\n") {
        eprintln!("Escaped sandbox by opening /proc as O_DIRECTORY.");
        eprintln!("Snippet from /proc/sydbox/status which is not /proc/pid/status:");
        eprintln!("{content}");
        exit(1);
    } else {
        exit(0);
    }
}

fn do_procself_escape_open_relpath_6() -> ! {
    // Open /proc with O_PATH
    let proc_fd = open("/proc", OFlag::O_PATH, Mode::empty()).expect("Failed to open /proc");

    // Open /proc/self/status with the above file descriptor
    let fd = openat(
        Some(proc_fd),
        "self/.././self/./status",
        OFlag::O_RDONLY,
        Mode::empty(),
    )
    .expect("Failed to open /proc/self/status using openat");

    // Close the /proc fd
    let _ = close(proc_fd);

    // Read the file
    let mut buf = vec![0; 128];
    let n = read(fd, &mut buf).expect("Failed to read /proc/self/status");

    // Close the status fd
    let _ = close(fd);

    // Perform a lossy conversion to UTF-8
    let content = String::from_utf8_lossy(&buf[..n]);

    // Check for `syd'
    if content.contains("Name:\tsyd\n") || content.contains("Name:\tsydbox\n") {
        eprintln!("Escaped sandbox by opening /proc as O_DIRECTORY.");
        eprintln!("Snippet from /proc/sydbox/status which is not /proc/pid/status:");
        eprintln!("{content}");
        exit(1);
    } else {
        exit(0);
    }
}

fn do_procself_escape_open_relpath_7() -> ! {
    // Open /proc with O_PATH
    let proc_fd = open("/proc", OFlag::O_PATH, Mode::empty()).expect("Failed to open /proc");

    // Open /proc/self/status with the above file descriptor
    let fd = openat(
        Some(proc_fd),
        "self/./././././././status",
        OFlag::O_RDONLY,
        Mode::empty(),
    )
    .expect("Failed to open /proc/self/status using openat");

    // Close the /proc fd
    let _ = close(proc_fd);

    // Read the file
    let mut buf = vec![0; 128];
    let n = read(fd, &mut buf).expect("Failed to read /proc/self/status");

    // Close the status fd
    let _ = close(fd);

    // Perform a lossy conversion to UTF-8
    let content = String::from_utf8_lossy(&buf[..n]);

    // Check for `syd'
    if content.contains("Name:\tsyd\n") || content.contains("Name:\tsydbox\n") {
        eprintln!("Escaped sandbox by opening /proc as O_DIRECTORY.");
        eprintln!("Snippet from /proc/sydbox/status which is not /proc/pid/status:");
        eprintln!("{content}");
        exit(1);
    } else {
        exit(0);
    }
}

fn do_procself_escape_symlink() -> ! {
    // symlink /proc/./self to self
    if let Err(error) = symlinkat("/proc/./self", None, "self") {
        eprintln!("Failed to symlink /proc/./self: {error}");
        exit(1);
    }

    // Open /proc/self/status with the above file descriptor
    let fd = match open("self/status", OFlag::O_RDONLY, Mode::empty()) {
        Ok(fd) => fd,
        Err(error) => {
            eprintln!("Failed to open /proc/self/status using open: {error}");
            exit(0);
        }
    };

    // Read the file
    let mut buf = vec![0; 128];
    let n = match read(fd, &mut buf) {
        Ok(n) => n,
        Err(error) => {
            eprintln!("Failed to read /proc/self/status: {error}");
            exit(0);
        }
    };

    // Close the status fd
    let _ = close(fd);

    // Perform a lossy conversion to UTF-8
    let content = String::from_utf8_lossy(&buf[..n]);

    // Check for `syd'
    if content.contains("Name:\tsyd\n") || content.contains("Name:\tsydbox\n") {
        eprintln!("Escaped sandbox by symlinking /proc/./self");
        eprintln!("Snippet from /proc/sydbox/status which is not /proc/pid/status:");
        eprintln!("{content}");
        exit(1);
    } else {
        exit(0);
    }
}

fn do_opath_escape() -> ! {
    // Open with O_PATH
    let fd = match open("/etc/passwd", OFlag::O_PATH, Mode::empty()) {
        Ok(fd) => fd,
        Err(error) => {
            eprintln!("Error opening /etc/passwd: {error}");
            exit(0);
        }
    };

    // Convert to a real fd with AT_EMPTY_PATH
    let real_fd = match openat(
        Some(fd),
        "",
        OFlag::O_RDONLY | OFlag::O_CLOEXEC,
        Mode::empty(),
    ) {
        Ok(real_fd) => {
            let _ = close(fd);
            real_fd
        }
        Err(error) => {
            let _ = close(fd);
            eprintln!("Error reopening O_PATH fd: {error}");
            exit(0);
        }
    };

    // Read from the fd
    let mut buf = [0u8; 1024];
    let n = match read(real_fd, &mut buf) {
        Ok(n) => {
            let _ = close(real_fd);
            n
        }
        Err(error) => {
            let _ = close(real_fd);
            eprintln!("Failed to read from /etc/passwd: {error}");
            exit(0);
        }
    };

    // Print the first line of /etc/passwd
    if let Some(line) = String::from_utf8_lossy(&buf[..n]).lines().next() {
        eprintln!("Escaped sandbox using a O_PATH file descriptor!");
        eprintln!("Snippet from /etc/passwd which is denylisted:");
        eprintln!("{line}");
        exit(1); // Report a failure
    } else {
        exit(0); // Report success if /etc/passwd is empty or unreadable
    }
}

// Map a denylisted library into memory with file descriptor
// modification attack (assumes ./lib-bad exists and is denylisted).
fn do_vfsmod_toctou_mmap() -> ! {
    mkdir("./lib-bad", Mode::from_bits_truncate(0o700)).unwrap();

    // The function aims to exploit a time-of-check-to-time-of-use (TOCTOU) race condition
    // by modifying the file descriptor during the system call.
    fn toctou_poc() -> bool {
        // STEP 1: SETUP
        // Create and write to the denylisted file.
        let denylisted_path = "./lib-bad/test.so";
        let denylisted_fd = open(
            denylisted_path,
            OFlag::O_RDWR | OFlag::O_CREAT | OFlag::O_TRUNC,
            Mode::S_IRWXU,
        )
        .unwrap();

        let denylisted_content = b"Heavy is the root of light. Still is the master of moving.\n";
        let denylisted_size = denylisted_content.len();
        let fd = unsafe { BorrowedFd::borrow_raw(denylisted_fd) };
        write(fd, denylisted_content).unwrap();

        // Prepare a thread which, when run, will attempt to modify the
        // file descriptor.
        let mut thread: pthread_t = unsafe { std::mem::zeroed() };

        unsafe {
            // STEP 2: START TOCTOU RACE
            // Create the new thread to initiate the attack.
            // The thread will try to overwrite the standard input file
            // descriptor (fd 0) during the mmap system call.
            match pthread_create(
                &mut thread,
                std::ptr::null(),
                modify_fd,
                &denylisted_fd as *const _ as *mut nix::libc::c_void,
            ) {
                0 => {}
                _ => panic!("Error creating thread: {}", Errno::last()),
            };

            // STEP 3: ATTEMPT TO MMAP FILE
            // Attempt to mmap using standard input (fd 0), but due to
            // the race condition, it may end up mapping the denylisted
            // file.
            let mmap_result = mmap(
                None,
                NonZeroUsize::new(denylisted_size).unwrap(),
                ProtFlags::PROT_READ | ProtFlags::PROT_EXEC,
                MapFlags::MAP_PRIVATE,
                std::io::stdin(),
                0, // offset is 0
            );

            // Join the attacker thread.
            pthread_join(thread, std::ptr::null_mut());
            let _ = close(denylisted_fd);

            // If we failed to mmap the file, the attack was
            // unsuccessful this round.
            match mmap_result {
                Ok(_) => true,
                Err(Errno::EACCES | Errno::EBADF) => false,
                Err(errno) => {
                    eprintln!("Unexpected mmap failure: {errno}");
                    true
                }
            }
        }
    }

    // Run multiple times to increase chance of failure.
    const TEST_DURATION: Duration = Duration::from_secs(150);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 150 seconds...");
    loop {
        if toctou_poc() {
            eprintln!("mmap with denylisted fd succeeded!");
            eprintln!("mmap VFS TOCTOU verified!");
            exit(1);
        }

        i += 1;
        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Test succeeded!");
    exit(0);
}

fn do_vfsmod_toctou_open_file() -> ! {
    fn toctou_poc() -> bool {
        // Attempt to open the benign file, but due to the race
        // condition, it may end up opening the malicious symlink.
        if let Ok(fd) = open("./benign", OFlag::O_RDONLY, Mode::empty()) {
            // Read the symbolic link to verify what was actually opened.
            let mut buf = itoa::Buffer::new();
            let mut lnk = PathBuf::from("/proc/self/fd");
            lnk.push(buf.format(fd));
            let result = readlink(&lnk);
            let _ = close(fd);
            if let Ok(p) = result {
                // Check if the opened file is "/etc/passwd".
                if p.as_bytes() == b"/etc/passwd" {
                    return true;
                }
            }
        }

        false
    }

    // Run multiple times to increase chance of failure.
    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        if toctou_poc() {
            eprintln!("TOCTOU attack succeeded: Opened /etc/passwd instead of the benign file.");
            exit(1);
        }

        i += 1;
        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Test succeeded!");
    exit(0);
}

fn do_vfsmod_toctou_open_path() -> ! {
    fn toctou_poc() -> bool {
        // Attempt to open the benign path, but due to the race
        // condition, it may end up opening the malicious symlink.
        if let Ok(fd) = open("./benign/passwd", OFlag::O_RDONLY, Mode::empty()) {
            // Read the symbolic link to verify what was actually opened.
            let mut buf = itoa::Buffer::new();
            let mut lnk = PathBuf::from("/proc/self/fd");
            lnk.push(buf.format(fd));
            let result = readlink(&lnk);
            let _ = close(fd);
            if let Ok(p) = result {
                // Check if the opened file is "/etc/passwd".
                if p.as_bytes() == b"/etc/passwd" {
                    return true;
                }
            }
        }

        false
    }

    // Run multiple times to increase chance of failure.
    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        if toctou_poc() {
            eprintln!("TOCTOU attack succeeded: Opened /etc/passwd instead of the benign file.");
            exit(1);
        }

        i += 1;
        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Test succeeded!");
    exit(0);
}

#[cfg(not(feature = "uring"))]
fn do_io_uring_escape() -> ! {
    eprintln!("uring feature disabled, skipping test!");
    exit(0);
}

#[cfg(feature = "uring")]
fn do_io_uring_escape() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        eprintln!("Pass 0 as first argument for normal operation.");
        eprintln!("Pass 1 as first argument to expect successful escape.");
        exit(1);
    }
    let (exit_succ, exit_fail) = match args[1].as_str() {
        "0" => (0, 1),
        "1" => (1, 0),
        _ => {
            eprintln!("Pass 0 as first argument for normal operation.");
            eprintln!("Pass 1 as first argument to expect successful escape.");
            exit(1);
        }
    };

    const FILE_PATH: &str = "/etc/passwd";
    const BUF_SIZE: usize = 1024;
    let path = std::ffi::CString::new(FILE_PATH).unwrap();

    let mut ring = match io_uring::IoUring::new(3) {
        Ok(ring) => ring,
        Err(error) => {
            if error.raw_os_error().unwrap_or(nix::libc::EINVAL) == nix::libc::ENOSYS {
                eprintln!(
                    "Error initializing io_uring: {}, this is fine.",
                    Errno::ENOSYS
                );
                exit(exit_succ);
            } else {
                eprintln!("Error initializing io_uring: {error}, unexpected error!");
                exit(exit_fail);
            }
        }
    };

    // Open the file using io_uring
    let open_at_opcode =
        io_uring::opcode::OpenAt::new(io_uring::types::Fd(nix::libc::AT_FDCWD), path.as_ptr());
    let open_entry = open_at_opcode.build();
    {
        let mut submission_queue = ring.submission();
        // SAFETY: We ensure that the buffer and the queue
        // entry live longer than the push operation, and that
        // the pointer to the file path remains valid.
        unsafe {
            if let Err(error) = submission_queue.push(&open_entry) {
                eprintln!("Failed to push open entry to submission queue: {error}.");
                exit(exit_succ);
            }
        }
        // Synchronize the submission queue.
        submission_queue.sync();
    }

    if let Err(error) = ring.submit() {
        eprintln!("Failed to submit open request: {error}.");
        exit(exit_succ);
    }

    let epoch = Instant::now();
    let timeout = Duration::from_secs(5);
    let mut open_completion = None;

    while epoch.elapsed() < timeout {
        if let Some(completion) = ring.completion().next() {
            open_completion = Some(completion);
            break;
        }
        // Check every 100ms for open completion.
        sleep(Duration::from_millis(100));
    }

    let open_completion = match open_completion {
        Some(completion) => completion,
        None => {
            eprintln!("No completion event for open operation");
            exit(exit_succ);
        }
    };

    let fd = match open_completion.result() {
        n if n < 0 => {
            eprintln!("Failed to open /etc/passwd using io_uring");
            exit(exit_succ);
        }
        n => n as std::os::fd::RawFd,
    };

    // Read the file using io_uring
    let mut buf = vec![0; BUF_SIZE];
    let read_opcode =
        io_uring::opcode::Read::new(io_uring::types::Fd(fd), buf.as_mut_ptr(), buf.len() as _);
    let read_entry = read_opcode.build();
    {
        let mut submission_queue = ring.submission();
        // SAFETY: We ensure that the buffer for reading and
        // the queue entry live longer than the push
        // operation.
        unsafe {
            if let Err(error) = submission_queue.push(&read_entry) {
                eprintln!("Failed to push read entry to submission queue: {error}.");
                exit(exit_succ);
            }
        }
        // Synchronize the submission queue.
        submission_queue.sync();
    }

    if let Err(error) = ring.submit() {
        eprintln!("Failed to submit read request: {error}.");
        exit(exit_succ);
    }

    let epoch = Instant::now();
    let timeout = Duration::from_secs(5);
    let mut read_completion = None;

    while epoch.elapsed() < timeout {
        if let Some(completion) = ring.completion().next() {
            read_completion = Some(completion);
            break;
        }
        // Check every 100ms for read completion.
        sleep(Duration::from_millis(100));
    }

    let read_completion = match read_completion {
        Some(completion) => completion,
        None => {
            eprintln!("No completion event for read operation.");
            exit(exit_succ);
        }
    };

    if read_completion.result() < 0 {
        eprintln!("Failed to read /etc/passwd using io_uring.");
        exit(exit_succ);
    }

    // Convert buffer to string and print first line
    let contents = String::from_utf8_lossy(&buf);
    if let Some(passwd) = contents.lines().next() {
        eprintln!("Escaped sandbox using io-uring interface!");
        eprintln!("Snippet from /etc/passwd which is denylisted:");
        eprintln!("{passwd}");
        exit(exit_fail);
    }

    exit(exit_succ);
}

fn do_ptrmod_toctou_exec_fail() -> ! {
    // STEP 0: SETUP executables
    let path = "toctou_exec";
    let data = vec![0u8; 64]; // Create a vector of zero bytes.
    fs::write(path, data).expect("Failed to write to file");

    let metadata = fs::metadata(path).expect("Failed to read file metadata");
    let mut permissions = metadata.permissions();
    permissions.set_mode(0o755); // This sets the file as executable (rwxr-xr-x).
    fs::set_permissions(path, permissions).expect("Failed to set file permissions");

    // The function exploits a time-of-check-to-time-of-use (TOCTOU) race condition
    // by modifying a pointer that references a file path during the exec system call.
    fn toctou_exec_poc() -> bool {
        // STEP 1: SETUP
        // Prepare a null-terminated string pointing to the non-executable file.
        let benign_path = b"/var/empty".to_vec();
        let mut benign_path_cstring = benign_path.clone();
        benign_path_cstring.push(0); // NUL-terminate for C-style string operations.

        // Obtain a mutable pointer to the string, to be modified in the TOCTOU attack.
        let ptr = benign_path_cstring.as_mut_ptr();

        // Prepare a thread which will attempt to modify the pointer
        // to point to a different file path.
        let mut thread: pthread_t = unsafe { std::mem::zeroed() };

        let arg = [
            b"empty\0".as_ptr() as *const nix::libc::c_char,
            std::ptr::null(),
        ];
        let arg = arg.as_ptr();
        let env = [std::ptr::null()];
        let env = env.as_ptr();

        unsafe {
            // STEP 2: START TOCTOU RACE
            // Create a new thread to initiate the attack, modifying the file path pointer.
            pthread_create(
                &mut thread,
                std::ptr::null(),
                modify_ptr_exec,
                ptr as *mut nix::libc::c_void,
            );

            // STEP 3: ATTEMPT TO EXECUTE FILE
            // Attempt to execute the benign file, but due to the race condition,
            // it may attempt to execute a different file.
            nix::libc::execve(ptr as *const nix::libc::c_char, arg, env);

            // If execve returns, it failed. Check errno to distinguish between
            // permission and bad format errors.
            if Errno::last() == Errno::ENOEXEC {
                eprintln!("execve failed with ENOEXEC.");
                return true; // Indicates TOCTOU success if we did get ENOEXEC.
            }

            pthread_join(thread, std::ptr::null_mut());
        }

        false
    }

    // Run multiple attempts to increase chance of catching the race condition.
    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        if toctou_exec_poc() {
            eprintln!("TOCTOU attack succeeded: execve attempted on modified path.");
            exit(1);
        }

        i += 1;
        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Test succeeded: TOCTOU attack did not result in an unexpected execve.");
    exit(0);
}

fn do_ptrmod_toctou_exec_success_quick() -> ! {
    // STEP 0: SETUP executable.
    // Create the script "toctou_exec" in the current directory.
    let path = "toctou_exec";
    let data = "#!/bin/false"; // Write a simple script.
    fs::write(path, data).expect("Failed to write to file");

    // Set permissions to make "exec" executable.
    let metadata = fs::metadata(path).expect("Failed to read file metadata");
    let mut permissions = metadata.permissions();
    permissions.set_mode(0o755); // This sets the file as executable (rwxr-xr-x).
    fs::set_permissions(path, permissions).expect("Failed to set file permissions");

    // The function exploits a time-of-check-to-time-of-use (TOCTOU) race condition
    // by modifying a pointer that references a file path during the exec system call.
    fn toctou_exec_poc() -> bool {
        // STEP 1: SETUP
        let benign_path = b"/var/empty".to_vec();
        let mut benign_path_cstring = benign_path.clone();
        benign_path_cstring.push(0); // NUL-terminate for C-style string operations.

        // Obtain a mutable pointer to the string, to be modified in the TOCTOU attack.
        let ptr = benign_path_cstring.as_mut_ptr();
        let arg = [
            b"false\0".as_ptr() as *const nix::libc::c_char,
            std::ptr::null(),
        ];
        let arg = arg.as_ptr();
        let env = [std::ptr::null()];
        let env = env.as_ptr();

        // Prepare a thread which will attempt to modify the pointer
        // to point to a different file path.
        let mut thread: pthread_t = unsafe { std::mem::zeroed() };

        unsafe {
            // STEP 2: START TOCTOU RACE
            // Create a new thread to initiate the attack, modifying the file path pointer.
            pthread_create(
                &mut thread,
                std::ptr::null(),
                modify_ptr_exec,
                ptr as *mut nix::libc::c_void,
            );

            // STEP 3: ATTEMPT TO EXECUTE FILE
            // Attempt to execute the benign file, but due to the race condition,
            // it may attempt to execute a different file.
            nix::libc::execve(ptr as *const nix::libc::c_char, arg, env);

            // If execve returns, it failed, continue trying.
            pthread_join(thread, std::ptr::null_mut());
        }

        false
    }

    // Run multiple attempts to increase chance of catching the race condition.
    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        if toctou_exec_poc() {
            eprintln!("TOCTOU attack succeeded: execve attempted on modified path.");
            exit(1);
        }

        i += 1;
        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Test succeeded: TOCTOU attack did not result in an unexpected execve.");
    exit(0);
}

fn do_ptrmod_toctou_exec_success_double_fork() -> ! {
    // STEP 0: SETUP executable.
    // Create the script "toctou_exec" in the current directory.
    let path = "toctou_exec";
    let data = "#!/bin/false"; // Write a simple script.
    fs::write(path, data).expect("Failed to write to file");

    // Set permissions to make "exec" executable.
    let metadata = fs::metadata(path).expect("Failed to read file metadata");
    let mut permissions = metadata.permissions();
    permissions.set_mode(0o755); // This sets the file as executable (rwxr-xr-x).
    fs::set_permissions(path, permissions).expect("Failed to set file permissions");

    // Double fork to attempt to escape ptrace sandbox, with correct error code handling.
    match unsafe { fork() } {
        Ok(ForkResult::Child) => match unsafe { fork() } {
            Ok(ForkResult::Child) => (), // Continue with the test in the grandchild
            Ok(ForkResult::Parent { child, .. }) => {
                // Intermediate parent waits for grandchild to ensure correct error code propagation.
                let status = waitpid(child, None).expect("Failed to wait on grandchild");
                if let WaitStatus::Exited(_, exit_code) = status {
                    exit(exit_code);
                } else if let WaitStatus::Signaled(_, SIGKILL, _) = status {
                    eprintln!("Grandchild was killed by SIGKILL!");
                    exit(0);
                } else {
                    eprintln!("Grandchild did not exit normally: {status:?}");
                    exit(1);
                }
            }
            Err(error) => panic!("Second fork failed: {error}"),
        },
        Ok(ForkResult::Parent { child, .. }) => {
            match waitpid(child, None).expect("Failed to wait on intermediate child") {
                WaitStatus::Exited(_, exit_code) => exit(exit_code),
                status => {
                    eprintln!("Intermediate child exited abnormally: {status:?}");
                    exit(1);
                }
            }
        }
        Err(error) => panic!("First fork failed: {error}"),
    }

    // The function exploits a time-of-check-to-time-of-use (TOCTOU) race condition
    // by modifying a pointer that references a file path during the exec system call.
    fn toctou_exec_poc() -> bool {
        // STEP 1: SETUP
        let benign_path = b"/var/empty".to_vec();
        let mut benign_path_cstring = benign_path.clone();
        benign_path_cstring.push(0); // NUL-terminate for C-style string operations.

        // Obtain a mutable pointer to the string, to be modified in the TOCTOU attack.
        let ptr = benign_path_cstring.as_mut_ptr();
        let arg = [
            b"false\0".as_ptr() as *const nix::libc::c_char,
            std::ptr::null(),
        ];
        let arg = arg.as_ptr();
        let env = [std::ptr::null()];
        let env = env.as_ptr();

        // Prepare a thread which will attempt to modify the pointer
        // to point to a different file path.
        let mut thread: pthread_t = unsafe { std::mem::zeroed() };

        unsafe {
            // STEP 2: START TOCTOU RACE
            // Create a new thread to initiate the attack, modifying the file path pointer.
            pthread_create(
                &mut thread,
                std::ptr::null(),
                modify_ptr_exec,
                ptr as *mut nix::libc::c_void,
            );

            // STEP 3: ATTEMPT TO EXECUTE FILE
            // Attempt to execute the benign file, but due to the race condition,
            // it may attempt to execute a different file.
            nix::libc::execve(ptr as *const nix::libc::c_char, arg, env);

            // If execve returns, it failed, continue trying.
            pthread_join(thread, std::ptr::null_mut());
        }

        false
    }

    // Run multiple attempts to increase chance of catching the race condition.
    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        if toctou_exec_poc() {
            eprintln!("TOCTOU attack succeeded: execve attempted on modified path.");
            exit(1);
        }

        i += 1;
        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Test succeeded: TOCTOU attack did not result in an unexpected execve.");
    exit(0);
}

fn do_ptrmod_toctou_open() -> ! {
    // The function aims to exploit a
    // time-of-check-to-time-of-use (TOCTOU) race condition by
    // modifying a pointer that references a file path during
    // the system call.
    fn toctou_poc() -> bool {
        // STEP 1: SETUP
        // Create a benign file that we'll try to open.
        fs::write(
            "src.syd-tmp",
            "Heavy is the root of light. Still is the master of moving.",
        )
        .unwrap();

        // Prepare a null-terminated string pointing to the benign file.
        let benign_path = b"src.syd-tmp".to_vec();
        let mut benign_path_cstring = benign_path.clone();
        benign_path_cstring.push(0); // NUL-terminate to make it
                                     // compatible with C-style
                                     // string operations.

        // Obtain a mutable pointer to the string.
        // This pointer is what will be modified in our TOCTOU attack.
        let ptr = benign_path_cstring.as_mut_ptr();

        // Prepare a thread which, when run, will repeatedly attempt to modify the pointer
        // to point to a different file path (i.e., /etc/passwd).
        let mut thread: pthread_t = unsafe { std::mem::zeroed() };

        unsafe {
            // STEP 2: START TOCTOU RACE
            // Create the new thread to initiate the attack.
            // The thread will try to overwrite the pointer during the `open` system call.
            match pthread_create(
                &mut thread,
                std::ptr::null(),
                modify_ptr,
                ptr as *mut nix::libc::c_void,
            ) {
                0 => {}
                e => panic!("Error creating thread: {}", Errno::from_raw(e)),
            };

            // STEP 3: ATTEMPT TO OPEN FILE
            // Attempt to open the benign file, but due to the race condition,
            // it may end up opening a different file (i.e., /etc/passwd).
            let fd = nix::libc::open(ptr as *const nix::libc::c_char, nix::libc::O_RDONLY);

            // Join the attacker thread.
            pthread_join(thread, std::ptr::null_mut());

            // If we failed to open the file, the attack was unsuccessful this round.
            if fd == -1 {
                return false;
            }

            // STEP 4: CHECK FOR SUCCESSFUL EXPLOITATION
            // If the attack was successful, we would've opened
            // /etc/passwd instead of the benign file.
            // Let's read the file contents and check.
            let mut file = File::from_raw_fd(fd);
            let mut content = String::new();
            file.read_to_string(&mut content).unwrap();

            // Check if we successfully read /etc/passwd
            if content.contains("root:") {
                let passwd = content.lines().next().unwrap_or("");
                eprintln!("Escaped sandbox using a pointer modification attack!");
                eprintln!("Snippet from /etc/passwd which is denylisted:");
                eprintln!("{passwd}");
                return true;
            }
        }

        false
    }

    // Run multiple times to increase chance of failure.
    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        if toctou_poc() {
            exit(1);
        }

        i += 1;
        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Test succeded!");
    exit(0);
}

fn do_ptrmod_toctou_creat() -> ! {
    // The function aims to exploit a
    // time-of-check-to-time-of-use (TOCTOU) race condition by
    // modifying a pointer that references a file path during
    // the system call.
    fn toctou_poc() -> bool {
        // STEP 1: SETUP
        // Create a benign file that we'll try to open.
        fs::write(
            "src.syd-tmp",
            "Heavy is the root of light. Still is the master of moving.",
        )
        .unwrap();

        // Prepare a null-terminated string pointing to the benign file.
        let benign_path = b"src.syd-tmp".to_vec();
        let mut benign_path_cstring = benign_path.clone();
        benign_path_cstring.push(0); // NUL-terminate to make it
                                     // compatible with C-style
                                     // string operations.

        // Obtain a mutable pointer to the string.
        // This pointer is what will be modified in our TOCTOU attack.
        let ptr = benign_path_cstring.as_mut_ptr();

        // Prepare a thread which, when run, will repeatedly attempt to modify the pointer
        // to point to a different file path (i.e., /etc/passwd).
        let mut thread: pthread_t = unsafe { std::mem::zeroed() };

        unsafe {
            // STEP 2: START TOCTOU RACE
            // Create the new thread to initiate the attack.
            // The thread will try to overwrite the pointer during the `open` system call.
            match pthread_create(
                &mut thread,
                std::ptr::null(),
                modify_ptr_creat,
                ptr as *mut nix::libc::c_void,
            ) {
                0 => {}
                e => panic!("Error creating thread: {}", Errno::from_raw(e)),
            };

            // STEP 3: ATTEMPT TO OPEN FILE
            // Attempt to open the benign file, but due to the race condition,
            // it may end up opening a different file (i.e., /etc/passwd).
            let fd = nix::libc::creat(ptr as *const nix::libc::c_char, 0o600);

            // Join the attacker thread.
            pthread_join(thread, std::ptr::null_mut());

            // If we failed to open the file, the attack was unsuccessful this round.
            if fd == -1 {
                return false;
            }
            let _ = nix::libc::close(fd);

            // STEP 4: CHECK FOR SUCCESSFUL EXPLOITATION
            // If the attack was successful, we would've
            // created `deny.syd-tmp' instead of the
            // the benign file. Let's stat the file and
            // check:
            if Path::new("./deny.syd-tmp").exists() {
                eprintln!("Escaped sandbox using a pointer modification attack!");
                eprintln!("Denylisted file `deny.syd-tmp' has been successfully created.");
                return true;
            }
        }

        false
    }

    // Run multiple times to increase chance of failure.
    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        if toctou_poc() {
            exit(1);
        }

        i += 1;
        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Test succeded!");
    exit(0);
}

fn do_ptrmod_toctou_opath() -> ! {
    // The function aims to exploit a
    // time-of-check-to-time-of-use (TOCTOU) race condition by
    // modifying a pointer that references a file path during
    // the system call.
    fn toctou_poc() -> bool {
        // STEP 1: SETUP
        // Create a benign file that we'll try to open.
        fs::write(
            "src.syd-tmp",
            "Heavy is the root of light. Still is the master of moving.",
        )
        .unwrap();

        // Prepare a null-terminated string pointing to the benign file.
        let benign_path = b"src.syd-tmp".to_vec();
        let mut benign_path_cstring = benign_path.clone();
        benign_path_cstring.push(0); // NUL-terminate to make it
                                     // compatible with C-style
                                     // string operations.

        // Obtain a mutable pointer to the string.
        // This pointer is what will be modified in our TOCTOU attack.
        let ptr = benign_path_cstring.as_mut_ptr();

        // Prepare a thread which, when run, will repeatedly attempt to modify the pointer
        // to point to a different file path (i.e., /etc/passwd).
        let mut thread: pthread_t = unsafe { std::mem::zeroed() };

        unsafe {
            // STEP 2: START TOCTOU RACE
            // Create the new thread to initiate the attack.
            // The thread will try to overwrite the pointer during the `open` system call.
            match pthread_create(
                &mut thread,
                std::ptr::null(),
                modify_ptr,
                ptr as *mut nix::libc::c_void,
            ) {
                0 => {}
                e => panic!("Error creating thread: {}", Errno::from_raw(e)),
            }

            // STEP 3: ATTEMPT TO OPEN FILE
            // Attempt to open the benign file, but due to the race condition,
            // it may end up opening a different file (i.e., /etc/passwd).
            let fd = nix::libc::open(ptr as *const nix::libc::c_char, nix::libc::O_PATH);

            // Join the attacker thread.
            pthread_join(thread, std::ptr::null_mut());

            // If we failed to open the file, the attack was unsuccessful this round.
            if fd == -1 {
                return false;
            }
            let fd = OwnedFd::from_raw_fd(fd);

            // STEP 4: CHECK FOR SUCCESSFUL EXPLOITATION
            // If the attack was successful, we would've opened
            // /etc/passwd instead of the benign file.
            // Let's read the proc symlink to check.
            match syd::fs::read_link(Path::new(&format!("/proc/self/fd/{}", fd.as_raw_fd()))) {
                Ok(path) if path == SmallPathBuf::from("/etc/passwd") => {
                    eprintln!("Leaked hidden path in sandbox using a pointer modification attack!");
                    eprintln!("Success opening /etc/passwd with O_PATH which is hidden:");
                    Command::new("sh")
                        .arg("-xc")
                        .arg(format!(
                            "readlink /proc/self/fd/{}; ls -la /etc /proc/self/fd",
                            fd.as_raw_fd()
                        ))
                        .stderr(Stdio::inherit())
                        .stdin(Stdio::inherit())
                        .stdout(Stdio::inherit())
                        .spawn()
                        .expect("exec ls")
                        .wait()
                        .expect("wait ls");
                    eprintln!();
                    return true;
                }
                _ => {
                    // If we failed to read the symbolic link,
                    // or it does not point to /etc/passwd,
                    // the attack was unsuccessful this round.
                    //
                    // Fall through.
                }
            }
        }

        false
    }

    // Run multiple times to increase chance of failure.
    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        if toctou_poc() {
            exit(1);
        }

        i += 1;
        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Test succeded!");
    exit(0);
}

fn do_symlinkat_toctou() -> ! {
    // Create a benign file
    fs::write(
        "src.syd-tmp",
        "Heavy is the root of light. Still is the master of moving.",
    )
    .unwrap();

    // Create a symlink that initially points to the benign file
    symlinkat("src.syd-tmp", None, "dst.syd-tmp").unwrap();

    // Define the main PoC as an inner function
    fn toctou_poc() -> bool {
        // Create an atomic flag for signaling the thread to stop
        let stop_flag = Arc::new(AtomicBool::new(false));
        let stop_flag_in_thread = Arc::clone(&stop_flag);

        // Spawn a thread to repeatedly try and change the symlink to point to /etc/passwd
        let handle = thread::spawn(move || {
            while !stop_flag_in_thread.load(Ordering::Relaxed) {
                let _ = fs::remove_file("dst.syd-tmp");
                let _ = symlinkat("/etc/passwd", None, "dst.syd-tmp");
                // Adjust this sleep for fine-tuning the race condition
                sleep(Duration::from_micros(10));
            }
        });

        let mut result = false;
        for _ in 0..100 {
            // Try to open the 'dst.syd-tmp' symlink, expecting it to be 'src.syd-tmp'
            let content = fs::read_to_string("dst.syd-tmp").unwrap_or_else(|_| String::from(""));
            if content.contains("root:") {
                let passwd = content.lines().next().unwrap_or("");
                eprintln!("Escaped sandbox using a symlink attack with the symlinkat syscall!");
                eprintln!("Snippet from /etc/passwd which is denylisted:");
                eprintln!("{passwd}");
                result = true;
                break;
            }
        }

        // Signal the thread to stop
        stop_flag.store(true, Ordering::Relaxed);
        // Wait for the thread to finish
        handle.join().unwrap();

        result
    }

    // Run multiple times to increase chance of failure.
    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        if toctou_poc() {
            exit(1);
        }

        i += 1;
        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Test succeded!");
    exit(0);
}

fn do_symlink_toctou() -> ! {
    // Create a benign file
    fs::write(
        "src.syd-tmp",
        "Heavy is the root of light. Still is the master of moving.",
    )
    .unwrap();

    // Create a symlink that initially points to the benign file
    symlink("src.syd-tmp", "dst.syd-tmp").unwrap();

    // Define the main PoC as an inner function
    fn toctou_poc() -> bool {
        // Create an atomic flag for signaling the thread to stop
        let stop_flag = Arc::new(AtomicBool::new(false));
        let stop_flag_in_thread = Arc::clone(&stop_flag);

        // Spawn a thread to repeatedly try and change the symlink to point to /etc/passwd
        let handle = thread::spawn(move || {
            while !stop_flag_in_thread.load(Ordering::Relaxed) {
                let _ = fs::remove_file("dst.syd-tmp");
                let _ = symlink("/etc/passwd", "dst.syd-tmp");
                // Adjust this sleep for fine-tuning the race condition
                sleep(Duration::from_micros(10));
            }
        });

        let mut result = false;
        for _ in 0..100 {
            // Try to open the 'dst.syd-tmp' symlink, expecting it to be 'src.syd-tmp'
            let content = fs::read_to_string("dst.syd-tmp").unwrap_or_else(|_| String::from(""));
            if content.contains("root:") {
                let passwd = content.lines().next().unwrap_or("");
                eprintln!("Escaped sandbox using a symlink attack!");
                eprintln!("Snippet from /etc/passwd which is denylisted:");
                eprintln!("{passwd}");
                result = true;
                break;
            }
        }

        // Signal the thread to stop
        stop_flag.store(true, Ordering::Relaxed);
        // Wait for the thread to finish
        handle.join().unwrap();

        result
    }

    // Run multiple times to increase chance of failure.
    const TEST_DURATION: Duration = Duration::from_secs(60);
    let epoch = Instant::now();
    let mut i = 0;
    let mut last_report = epoch;
    eprintln!("Starting test, duration: 60 seconds...");
    loop {
        if toctou_poc() {
            exit(1);
        }

        i += 1;
        let elapsed = epoch.elapsed();
        let since_last_report = last_report.elapsed();
        if elapsed >= TEST_DURATION {
            eprintln!("Timeout reached. Finalizing test.");
            break;
        } else if since_last_report.as_secs() >= 10 {
            last_report = Instant::now();
            eprintln!(
                "{} attempts in {} seconds, {} seconds left...",
                i,
                elapsed.as_secs(),
                TEST_DURATION.as_secs().saturating_sub(elapsed.as_secs())
            );
        }
    }

    eprintln!("Test succeded!");
    exit(0);
}

fn do_stat_bypass_with_exec() -> ! {
    // Try to access /bin/sh with X_OK and check for ENOENT
    match access("/bin/sh", AccessFlags::X_OK) {
        Ok(_) => {
            eprintln!("Unexpected success in accessing /bin/sh");
            exit(1);
        }
        Err(Errno::ENOENT) => eprintln!("ENOENT error as expected for /bin/sh"),
        Err(error) => {
            eprintln!("Unexpected error when accessing /bin/sh {error}");
            exit(1);
        }
    }

    // Try to access /bin/SH with X_OK and check for ENOENT
    match access("/bin/SH", AccessFlags::X_OK) {
        Ok(_) => {
            eprintln!("Unexpected success in accessing /bin/SH");
            exit(1);
        }
        Err(Errno::ENOENT) => eprintln!("ENOENT error as expected for /bin/SH"),
        Err(error) => {
            eprintln!("Unexpected error when accessing /bin/SH {error}");
            exit(1);
        }
    }

    // Exit normally if all checks pass
    exit(0);
}

fn do_stat_bypass_with_write() -> ! {
    // Try to write to /etc/passwd and check for ENOENT
    match open("/etc/passwd", OFlag::O_WRONLY, Mode::empty()) {
        Ok(_) => {
            eprintln!("Unexpected success in opening /etc/passwd");
            exit(1);
        }
        Err(Errno::ENOENT) => eprintln!("ENOENT error as expected for /etc/passwd"),
        Err(error) => {
            eprintln!("Unexpected error when opening /etc/passwd: {error}");
            exit(1);
        }
    }

    // Try to read from /etc/password and check for ENOENT
    match open("/etc/password", OFlag::O_WRONLY, Mode::empty()) {
        Ok(_) => {
            eprintln!("Unexpected success in opening /etc/password");
            exit(1);
        }
        Err(Errno::ENOENT) => eprintln!("ENOENT error as expected for /etc/password"),
        Err(error) => {
            eprintln!("Unexpected error when opening /etc/password: {error}");
            exit(1);
        }
    }

    // Exit normally if all checks pass
    exit(0);
}

fn do_stat_bypass_with_read() -> ! {
    // Try to read from /etc/passwd and check for ENOENT
    match open("/etc/passwd", OFlag::O_RDONLY, Mode::empty()) {
        Ok(_) => {
            eprintln!("Unexpected success in opening /etc/passwd");
            exit(1);
        }
        Err(Errno::ENOENT) => eprintln!("ENOENT error as expected for /etc/passwd"),
        Err(error) => {
            eprintln!("Unexpected error when opening /etc/passwd: {error}");
            exit(1);
        }
    }

    // Try to read from /etc/password and check for ENOENT
    match open("/etc/password", OFlag::O_RDONLY, Mode::empty()) {
        Ok(_) => {
            eprintln!("Unexpected success in opening /etc/password");
            exit(1);
        }
        Err(Errno::ENOENT) => eprintln!("ENOENT error as expected for /etc/password"),
        Err(error) => {
            eprintln!("Unexpected error when opening /etc/password: {error}");
            exit(1);
        }
    }

    // Exit normally if all checks pass
    exit(0);
}

// Resolve an interface number into an interface.
// TODO: Use nix' version once we upgrade this is from nix.git
fn if_indextoname(index: nix::libc::c_uint) -> nix::Result<CString> {
    // We need to allocate this anyway, so doing it directly is faster.
    let mut buf = vec![0u8; nix::libc::IF_NAMESIZE];

    let return_buf = unsafe { nix::libc::if_indextoname(index, buf.as_mut_ptr().cast()) };

    Errno::result(return_buf.cast())?;
    Ok(CStr::from_bytes_until_nul(buf.as_slice())
        .unwrap()
        .to_owned())
}

fn do_ifconfig_lo() -> ! {
    let name = CString::new("lo").expect("lo");
    assert_eq!(if_indextoname(1), Ok(name));

    exit(0);
}

fn do_toolong_unix_sendmsg() -> ! {
    let tmp = "tmpdir";
    let cwd = format!("{tmp}/{}", "d".repeat(108));
    let cwd = Path::new(&cwd);

    // 1. Create a long directory structure and chdir into it.
    if let Err(error) = fs::create_dir_all(cwd) {
        eprintln!("Failed to create long directory structure: {error}");
        exit(1);
    }
    if let Err(error) = chdir(cwd) {
        eprintln!("Failed to change directory: {error}");
        exit(1);
    }

    // 2. Setup UNIX socket server
    let mesg = "!".repeat((u8::MAX as usize).saturating_add(7));
    match unsafe { fork() } {
        Ok(ForkResult::Parent { child, .. }) => {
            let mut result = 0;
            // Parent process: Bind socket
            match UnixDatagram::bind("./socket") {
                Ok(sock) => {
                    // Give some time for the socket to be ready to receive.
                    sleep(Duration::from_secs(3));

                    let mut buf = vec![0; mesg.len()];
                    match sock.recv(&mut buf) {
                        Ok(n) if n == mesg.len() => {
                            eprintln!("Message received correctly!");
                        }
                        Ok(n) => {
                            eprintln!(
                                "Message received incorrectly, expected {} but got {}",
                                mesg.len(),
                                n
                            );
                            result |= 1;
                        }
                        Err(error) => {
                            eprintln!("Failed to receive message: {error}");
                            result |= 2;
                        }
                    }
                }
                Err(error) => {
                    eprintln!("Failed to bind: {error}");
                    result |= 4;
                }
            }

            // Wait for child to complete
            match waitpid(child, None) {
                Ok(WaitStatus::Exited(_, 0)) => {}
                Ok(WaitStatus::Exited(_, n)) => result |= n,
                Err(error) => {
                    eprintln!("Failed to waitpid: {error}");
                    exit(1);
                }
                _ => result |= 128,
            }

            if result == 0 {
                eprintln!("Test succeded!");
                exit(0);
            } else {
                eprintln!("Test failed: {result}");
                exit(1);
            }
        }
        Ok(ForkResult::Child) => {
            // Child process: Attempt to connect and then send to the socket
            sleep(Duration::from_secs(3)); // Ensure parent has time to bind

            let sock = match UnixDatagram::unbound() {
                Ok(s) => s,
                Err(error) => {
                    eprintln!("Failed to create socket: {error}");
                    exit(32);
                }
            };

            let addr = match UnixAddr::new("./socket") {
                Ok(a) => a,
                Err(error) => {
                    eprintln!("Failed to create socket address: {:?}", error);
                    exit(64);
                }
            };

            let data = mesg.as_bytes();
            let iov = [IoSlice::new(data)];
            let cmsgs = [];
            match sendmsg(
                sock.as_raw_fd(),
                &iov,
                &cmsgs,
                MsgFlags::empty(),
                Some(&addr),
            ) {
                Ok(n) if n == data.len() => {
                    eprintln!("Message sent successfully!");
                    exit(0);
                }
                Ok(n) => {
                    eprintln!(
                        "Partial message sent, expected {} but got {}",
                        data.len(),
                        n
                    );
                    exit(8);
                }
                Err(error) => {
                    eprintln!("Failed to send message: {:?}", error);
                    exit(16);
                }
            }
        }
        Err(error) => {
            eprintln!("Fork failed: {error}");
            exit(1);
        }
    }
}

fn do_toolong_unix_sendto() -> ! {
    let tmp = "tmpdir";
    let cwd = format!("{tmp}/{}", "d".repeat(108));
    let cwd = Path::new(&cwd);

    // 1. Create a long directory structure and chdir into it.
    if let Err(error) = fs::create_dir_all(cwd) {
        eprintln!("Failed to create long directory structure: {error}");
        exit(1);
    }
    if let Err(error) = chdir(cwd) {
        eprintln!("Failed to change directory: {error}");
        exit(1);
    }

    // 2. Setup UNIX socket server
    let mesg = "!".repeat((u8::MAX as usize).saturating_add(7));
    match unsafe { fork() } {
        Ok(ForkResult::Parent { child, .. }) => {
            let mut result = 0;
            // Parent process: Bind socket
            match UnixDatagram::bind("./socket") {
                Ok(sock) => {
                    // Give some time for the socket to be ready to receive.
                    sleep(Duration::from_secs(3));

                    let mut buf = vec![0; mesg.len()];
                    match sock.recv(&mut buf) {
                        Ok(n) if n == mesg.len() => {
                            eprintln!("Message received correctly!");
                        }
                        Ok(n) => {
                            eprintln!(
                                "Message received incorrectly, expected {} but got {}",
                                mesg.len(),
                                n
                            );
                            result |= 1;
                        }
                        Err(error) => {
                            eprintln!("Failed to receive message: {error}");
                            result |= 2;
                        }
                    }
                }
                Err(error) => {
                    eprintln!("Failed to bind: {error}");
                    result |= 4;
                }
            }

            // Wait for child to complete
            match waitpid(child, None) {
                Ok(WaitStatus::Exited(_, 0)) => {}
                Ok(WaitStatus::Exited(_, n)) => result |= n,
                Err(error) => {
                    eprintln!("Failed to waitpid: {error}");
                    exit(1);
                }
                _ => result |= 64,
            }

            if result == 0 {
                eprintln!("Test succeded!");
                exit(0);
            } else {
                eprintln!("Test failed: {result}");
                exit(1);
            }
        }
        Ok(ForkResult::Child) => {
            // Child process: Attempt to connect and then send to the socket
            sleep(Duration::from_secs(3)); // Ensure parent has time to bind

            let sock = match socket(
                AddressFamily::Unix,
                SockType::Datagram,
                SockFlag::empty(),
                None,
            ) {
                Ok(fd) => fd,
                Err(error) => {
                    eprintln!("Failed to create socket: {error}");
                    exit(32);
                }
            };

            let addr = UnixAddr::new("./socket").expect("Failed to create socket address");
            let data = mesg.as_bytes();
            match sendto(sock.as_raw_fd(), data, &addr, MsgFlags::empty()) {
                Ok(n) if n == data.len() => {
                    eprintln!("Message sent successfully!");
                    exit(0);
                }
                Ok(n) => {
                    eprintln!(
                        "Partial message sent, expected {} but got {}",
                        data.len(),
                        n
                    );
                    exit(8);
                }
                Err(error) => {
                    eprintln!("Failed to send message: {error}");
                    exit(16);
                }
            }
        }
        Err(error) => {
            eprintln!("Fork failed: {error}");
            exit(1);
        }
    }
}

fn do_toolong_unix_connect() -> ! {
    let tmp = "tmpdir";
    let cwd = format!("{tmp}/{}", "d".repeat(108));
    let cwd = Path::new(&cwd);

    // 1. Create a long directory structure and chdir into it.
    if let Err(error) = fs::create_dir_all(cwd) {
        eprintln!("Failed to create long directory structure: {error}");
        exit(1);
    }
    if let Err(error) = chdir(cwd) {
        eprintln!("Failed to change directory: {error}");
        exit(1);
    }

    // 2. Setup UNIX socket server
    let mesg = "!".repeat((u8::MAX as usize).saturating_add(7));
    match unsafe { fork() } {
        Ok(ForkResult::Parent { child, .. }) => {
            let mut result = 0;
            // Parent process: Bind socket
            match UnixListener::bind("./socket") {
                Ok(sock) => match sock.accept() {
                    Ok((mut cli, _)) => {
                        let mut buf = vec![0; mesg.len()];
                        match cli.read_exact(&mut buf) {
                            Ok(()) => {
                                if buf == mesg.as_bytes() {
                                    eprintln!("Message read correctly!");
                                } else {
                                    eprintln!("Message read incorrectly!");
                                    result |= 1;
                                }
                            }
                            Err(error) => {
                                eprintln!("Failed to receive message: {error}");
                                result |= 2;
                            }
                        }
                    }
                    Err(error) => {
                        eprintln!("Failed to accept connection: {error}");
                        result |= 4;
                    }
                },
                Err(error) => {
                    eprintln!("Failed to bind: {error}");
                    result |= 8;
                }
            }

            // Wait for child to complete
            match waitpid(child, None) {
                Ok(WaitStatus::Exited(_, 0)) => {}
                Ok(WaitStatus::Exited(_, n)) => result |= n,
                Err(error) => {
                    eprintln!("Failed to waitpid: {error}");
                    exit(1);
                }
                _ => result |= 64,
            }

            if result == 0 {
                eprintln!("Test succeded!");
                exit(0);
            } else {
                eprintln!("Test failed: {result}");
                exit(1);
            }
        }
        Ok(ForkResult::Child) => {
            // Child process: Attempt to connect and then send to the socket
            sleep(Duration::from_secs(3)); // Ensure parent has time to bind

            match UnixStream::connect("./socket") {
                Ok(mut stream) => {
                    if let Err(error) = stream.write_all(mesg.as_bytes()) {
                        eprintln!("Failed to send message: {error}");
                        exit(16);
                    } else {
                        eprintln!("Message sent successfully!");
                        exit(0);
                    }
                }
                Err(error) => {
                    eprintln!("Failed to connect: {error}");
                    exit(32);
                }
            }
        }
        Err(error) => {
            eprintln!("Fork failed: {error}");
            exit(1);
        }
    }
}

fn do_connect4_0() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        panic!("Expected only an IPv4 address as argument.");
    }
    let addr: Ipv4Addr = args[1].parse().expect("Invalid IPv4 address");
    let (read_fd, write_fd) = pipe().expect("Failed to create pipe");

    match unsafe { fork() } {
        Ok(ForkResult::Parent { .. }) => {
            // Close the write end of the pipe in the parent
            drop(write_fd);

            // Allow some time for the child process to start the listener
            sleep(Duration::from_secs(3));

            // Read port from the pipe
            let mut port_buf = [0; 2];
            nix::unistd::read(read_fd.as_raw_fd(), &mut port_buf)
                .expect("Failed to read from pipe");
            let port = u16::from_be_bytes(port_buf);

            let sock = SocketAddrV4::new(addr, port);

            // Attempt to connect to the address and exit with errno.
            exit(match TcpStream::connect(sock) {
                Ok(_) => {
                    // Successfully connected
                    0
                }
                Err(error) => {
                    eprintln!("Connect failed: {:?}", error);
                    error.raw_os_error().unwrap_or(-1)
                }
            });
        }
        Ok(ForkResult::Child) => {
            // Close the read end of the pipe in the child
            drop(read_fd);

            let sock = SocketAddrV4::new(addr, 0); // 0 means OS chooses the port
            let listener = TcpListener::bind(sock).expect("Failed to bind address");

            // Fetch the assigned port and write it to the pipe
            if let Ok(local_addr) = listener.local_addr() {
                let port_bytes = local_addr.port().to_be_bytes();
                write(write_fd, &port_bytes).expect("Failed to write to pipe");
            }

            listener
                .set_nonblocking(true)
                .expect("Failed to set socket to nonblocking mode.");

            let epoch = Instant::now();

            // Attempt to accept a connection and exit on the first established connection.
            loop {
                match listener.accept() {
                    Ok(_) => {
                        exit(0);
                    }
                    Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
                        if epoch.elapsed() > Duration::from_secs(10) {
                            eprintln!("Timed out waiting for a connection");
                            exit(Errno::ETIMEDOUT as i32);
                        }
                        sleep(Duration::from_millis(100));
                    }
                    Err(error) => {
                        eprintln!("Accept failed: {:?}", error);
                        exit(error.raw_os_error().unwrap_or(-1));
                    }
                };
            }
        }
        Err(error) => panic!("Fork failed: {:?}", error),
    };
}

fn do_connect6_0() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        panic!("Expected only an IPv6 address as argument.");
    }
    let addr: Ipv6Addr = args[1].parse().expect("Invalid IPv6 address");
    let (read_fd, write_fd) = pipe().expect("Failed to create pipe");

    match unsafe { fork() } {
        Ok(ForkResult::Parent { .. }) => {
            // Close the write end of the pipe in the parent
            drop(write_fd);

            // Allow some time for the child process to start the listener
            sleep(Duration::from_secs(3));

            // Read port from the pipe
            let mut port_buf = [0; 2];
            nix::unistd::read(read_fd.as_raw_fd(), &mut port_buf)
                .expect("Failed to read from pipe");
            let port = u16::from_be_bytes(port_buf);

            let sock = SocketAddrV6::new(addr, port, 0, 0);

            // Attempt to connect to the address and exit with errno.
            exit(match TcpStream::connect(sock) {
                Ok(_) => {
                    // Successfully connected
                    0
                }
                Err(error) => {
                    eprintln!("Connect failed: {:?}", error);
                    error.raw_os_error().unwrap_or(-1)
                }
            });
        }
        Ok(ForkResult::Child) => {
            // Close the read end of the pipe in the child
            drop(read_fd);

            // 0 in second argument means OS chooses the port.
            let sock = SocketAddrV6::new(addr, 0, 0, 0);
            let listener = TcpListener::bind(sock).expect("Failed to bind address");

            // Fetch the assigned port and write it to the pipe
            if let Ok(local_addr) = listener.local_addr() {
                let port_bytes = local_addr.port().to_be_bytes();
                write(write_fd, &port_bytes).expect("Failed to write to pipe");
            }

            listener
                .set_nonblocking(true)
                .expect("Failed to set socket to nonblocking mode.");

            let epoch = Instant::now();

            // Attempt to accept a connection and exit on the first established connection.
            loop {
                match listener.accept() {
                    Ok(_) => {
                        exit(0);
                    }
                    Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
                        if epoch.elapsed() > Duration::from_secs(10) {
                            eprintln!("Timed out waiting for a connection");
                            exit(Errno::ETIMEDOUT as i32);
                        }
                        sleep(Duration::from_millis(100));
                    }
                    Err(error) => {
                        eprintln!("Accept failed: {:?}", error);
                        exit(error.raw_os_error().unwrap_or(-1));
                    }
                };
            }
        }
        Err(error) => panic!("Fork failed: {:?}", error),
    };
}

fn do_connect4() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 3 {
        panic!("Expected an IPv4 address and port as arguments.");
    }
    let addr: Ipv4Addr = args[1].parse().expect("Invalid IPv4 address");
    let port: u16 = args[2].parse().expect("Invalid port number");
    let sock = SocketAddrV4::new(addr, port);

    match unsafe { fork() } {
        Ok(ForkResult::Parent { .. }) => {
            // Allow some time for the child process to start the listener
            sleep(Duration::from_secs(3));

            // Attempt to connect to the address and exit with errno.
            exit(match TcpStream::connect(sock) {
                Ok(_) => {
                    // Successfully connected
                    0
                }
                Err(error) => {
                    eprintln!("Connect failed: {error}");
                    error.raw_os_error().unwrap_or(-1)
                }
            });
        }
        Ok(ForkResult::Child) => {
            let listener = TcpListener::bind(sock).expect("Failed to bind address");
            listener
                .set_nonblocking(true)
                .expect("Failed to set socket to nonblocking mode.");

            let epoch = Instant::now();

            // Attempt to accept a connection and exit on the first established connection.
            loop {
                match listener.accept() {
                    Ok(_) => {
                        exit(0);
                    }
                    Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
                        if epoch.elapsed() > Duration::from_secs(10) {
                            eprintln!("Timed out waiting for a connection");
                            exit(Errno::ETIMEDOUT as i32);
                        }
                        sleep(Duration::from_millis(100));
                    }
                    Err(error) => {
                        eprintln!("Accept failed: {error}");
                        exit(error.raw_os_error().unwrap_or(-1));
                    }
                };
            }
        }
        Err(error) => panic!("Fork failed: {error}"),
    };
}

fn do_connect6() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 3 {
        panic!("Expected an IPv6 address and port as arguments.");
    }
    let addr: Ipv6Addr = args[1].parse().expect("Invalid IPv6 address");
    let port: u16 = args[2].parse().expect("Invalid port number");
    let sock = SocketAddrV6::new(addr, port, 0, 0);

    match unsafe { fork() } {
        Ok(ForkResult::Parent { .. }) => {
            // Allow some time for the child process to start the listener
            sleep(Duration::from_secs(3));

            // Attempt to connect to the address and exit with errno.
            exit(match TcpStream::connect(sock) {
                Ok(_) => {
                    // Successfully connected
                    0
                }
                Err(error) => {
                    eprintln!("Connect failed: {error}");
                    error.raw_os_error().unwrap_or(-1)
                }
            });
        }
        Ok(ForkResult::Child) => {
            let listener = TcpListener::bind(sock).expect("Failed to bind address");
            listener
                .set_nonblocking(true)
                .expect("Failed to set socket to nonblocking mode.");

            let epoch = Instant::now();

            // Attempt to accept a connection and exit on the first established connection.
            loop {
                match listener.accept() {
                    Ok(_) => {
                        exit(0);
                    }
                    Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
                        if epoch.elapsed() > Duration::from_secs(10) {
                            eprintln!("Timed out waiting for a connection");
                            exit(Errno::ETIMEDOUT as i32);
                        }
                        sleep(Duration::from_millis(100));
                    }
                    Err(error) => {
                        eprintln!("Accept failed: {error}");
                        exit(error.raw_os_error().unwrap_or(-1));
                    }
                };
            }
        }
        Err(error) => panic!("Fork failed: {error}"),
    };
}

fn do_fork() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 3 {
        panic!("Expected exit code and number of processes as arguments.");
    }
    eprintln!("do_fork: {args:?}");
    let xcode: i32 = args[1].parse().expect("Failed to parse the exit code.");
    if xcode < 0 || xcode > u8::MAX as i32 {
        panic!("Invalid exit code: {xcode}.");
    }
    let nproc: i32 = args[2]
        .parse()
        .expect("Failed to parse the number of processes.");
    if !(0..=4096).contains(&nproc) {
        panic!("Invalid number for number of processes.");
    }

    for i in 0..nproc {
        match unsafe { fork() } {
            Ok(ForkResult::Parent { .. }) => {
                // Avoid hitting the TTL.
                eprintln!("Iteration {i} of {nproc} done, sleeping for 1 second...");
                sleep(Duration::from_secs(1));
            }
            Ok(ForkResult::Child) => {
                sleep(Duration::from_secs(7));
                // SAFETY: In libc we trust.
                unsafe { _exit((i % 254) + 1) };
            }
            Err(errno) => {
                eprintln!("Failed to fork: {errno}.");
                exit(errno as i32);
            }
        }
    }

    exit(xcode);
}

fn do_thread() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 3 {
        panic!("Expected exit code and number of processes as arguments.");
    }
    let xcode: i32 = args[1].parse().expect("Failed to parse the exit code.");
    if xcode < 0 || xcode > u8::MAX as i32 {
        panic!("Invalid exit code: {xcode}.");
    }
    let nproc: i32 = args[2]
        .parse()
        .expect("Failed to parse the number of processes.");
    if !(0..=4096).contains(&nproc) {
        panic!("Invalid number for number of processes.");
    }

    for _ in 0..nproc {
        // We don't join the threads deliberately here.
        let _ = thread::spawn(|| {
            sleep(Duration::from_micros(4242));
        });
    }

    // SAFETY: In libc we trust.
    unsafe { _exit(xcode) };
}

/// Do a dlopen with RTLD_NOW!
fn do_dlopen_now() -> ! {
    // Parsing the first argument as a boolean
    let args: Vec<String> = std::env::args().collect();
    if args.len() < 2 {
        eprintln!("Expected exactly one argument for the dynamic library to load!");
        exit(1);
    }

    let lib = Path::new(&args[1]);

    if let Err(err) = unsafe {
        libloading::os::unix::Library::open(Some(lib), nix::libc::RTLD_NOW | nix::libc::RTLD_LOCAL)
    } {
        let err = err.to_string();
        eprintln!("Error during dlopen: {err}");
        if err.contains("cannot enable executable stack") {
            // This is the second layer that triggers, e.g. on Fedora.
            exit(128);
        } else if err.contains("wrong ELF class") {
            // 64bit<->32bit confusion, ignore.
            exit(128);
        } else {
            exit(Errno::EACCES as i32);
        }
    } else {
        exit(0);
    }
}

/// Do a dlopen with RTLD_LAZY!
fn do_dlopen_lazy() -> ! {
    // Parsing the first argument as a boolean
    let args: Vec<String> = std::env::args().collect();
    if args.len() < 2 {
        eprintln!("Expected exactly one argument for the dynamic library to load!");
        exit(1);
    }

    let lib = Path::new(&args[1]);

    if let Err(err) = unsafe {
        libloading::os::unix::Library::open(Some(lib), nix::libc::RTLD_LAZY | nix::libc::RTLD_LOCAL)
    } {
        let err = err.to_string();
        eprintln!("Error during dlopen: {err}");
        if err.contains("cannot enable executable stack") {
            // This is the second layer that triggers, e.g. on Fedora.
            exit(128);
        } else if err.contains("wrong ELF class") {
            // 64bit<->32bit confusion, ignore.
            exit(128);
        } else {
            exit(Errno::EACCES as i32);
        }
    } else {
        exit(0);
    }
}

/// Do a personality switch!
#[allow(unreachable_code)]
fn do_personality() -> ! {
    // Check if the target architecture is 32-bit and exit if true
    #[cfg(not(target_pointer_width = "64"))]
    {
        eprintln!("do_personality: Target is not 64-bit, skippping!");
        exit(0);
    }

    // Parsing the first argument as a boolean
    let args: Vec<String> = std::env::args().collect();
    if args.len() < 2 {
        eprintln!("Expected exactly one argument for expected success mode");
        exit(1);
    }

    let expecting_success: bool = args[1].parse().expect("arg1 is bool");

    // Attempt to set the process personality to ADDR_LIMIT_32BIT
    match personality::set(Persona::ADDR_LIMIT_32BIT) {
        // Check if setting personality was successful
        Ok(_) if expecting_success => exit(0),
        Ok(_) => exit(1),
        Err(errno) if expecting_success => {
            eprintln!("do_personality: Expected success, got {errno}");
            exit(1);
        }
        Err(Errno::EACCES) => {
            eprintln!("do_personality: Failed correctly with EACCES");
            exit(0);
        }
        Err(errno) => {
            eprintln!("do_personality: Failed incorrectly with {errno}");
            exit(1);
        }
    }
}

/// Check mmap: PROT_READ|PROT_EXEC with MAP_ANONYMOUS is killed.
fn do_mmap_prot_read_exec_with_map_anonymous() -> ! {
    let one_k_non_zero = NonZeroUsize::new(1024).unwrap();
    match unsafe {
        mmap(
            None,
            one_k_non_zero,
            ProtFlags::PROT_READ | ProtFlags::PROT_EXEC,
            MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE,
            BorrowedFd::borrow_raw(nix::libc::AT_FDCWD),
            0,
        )
    } {
        Ok(_) => exit(0),
        Err(errno) => exit(errno as i32),
    }
}

/// Check mmap: PROT_WRITE|PROT_EXEC with MAP_ANONYMOUS is killed.
fn do_mmap_prot_write_exec_with_map_anonymous() -> ! {
    let one_k_non_zero = NonZeroUsize::new(1024).unwrap();
    match unsafe {
        mmap(
            None,
            one_k_non_zero,
            ProtFlags::PROT_WRITE | ProtFlags::PROT_EXEC,
            MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE,
            BorrowedFd::borrow_raw(nix::libc::AT_FDCWD),
            0,
        )
    } {
        Ok(_) => exit(0),
        Err(errno) => exit(errno as i32),
    }
}

// Check mmap: PROT_READ|PROT_EXEC with backing file.
fn do_mmap_prot_read_exec_with_backing_file() -> ! {
    let fd = open(
        "./mmap",
        OFlag::O_RDWR | OFlag::O_CREAT | OFlag::O_TRUNC,
        Mode::S_IRWXU,
    )
    .unwrap();
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    let content = b"Heavy is the root of light. Still is the master of moving.\n";
    let content_size = NonZeroUsize::new(content.len()).unwrap();
    write(&fd, content).unwrap();

    match unsafe {
        mmap(
            None,
            content_size,
            ProtFlags::PROT_READ | ProtFlags::PROT_EXEC,
            MapFlags::MAP_PRIVATE,
            &fd,
            0,
        )
    } {
        Ok(_) => exit(0),
        Err(errno) => exit(errno as i32),
    }
}

// Check mmap: PROT_WRITE|PROT_EXEC with backing file.
fn do_mmap_prot_write_exec_with_backing_file() -> ! {
    let fd = open(
        "./mmap",
        OFlag::O_RDWR | OFlag::O_CREAT | OFlag::O_TRUNC,
        Mode::S_IRWXU,
    )
    .unwrap();
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    let content = b"Heavy is the root of light. Still is the master of moving.\n";
    let content_size = NonZeroUsize::new(content.len()).unwrap();
    write(&fd, content).unwrap();

    match unsafe {
        mmap(
            None,
            content_size,
            ProtFlags::PROT_WRITE | ProtFlags::PROT_EXEC,
            MapFlags::MAP_PRIVATE,
            &fd,
            0,
        )
    } {
        Ok(_) => exit(0),
        Err(errno) => exit(errno as i32),
    }
}

/// Check mmap: PROT_READ|PROT_EXEC with a writable FD, then try modifying the contents.
fn do_mmap_prot_exec_rdwr_fd() -> ! {
    // To test MDWE prctl without our seccomp filters,
    // we set it here optionally based on an envvar.
    if env::var("SYD_TEST_DO_MDWE").is_ok() {
        const PR_SET_MDWE: nix::libc::c_int = 65;
        const PR_MDWE_REFUSE_EXEC_GAIN: nix::libc::c_ulong = 1;

        match Errno::result(unsafe {
            nix::libc::prctl(PR_SET_MDWE, PR_MDWE_REFUSE_EXEC_GAIN, 0, 0, 0)
        }) {
            Ok(_) => {
                eprintln!("[*] Successfully enabled Memory-Deny-Write-Execute protections.");
            }
            Err(errno) => {
                eprintln!("[!] Failed to enable Memory-Deny-Write-Execute protections: {errno}");
                exit(nix::libc::ENOSYS); // Signal syd-test that MDWE is unsupported (or already enabled).
            }
        }
    }

    let fd = open(
        "./mmap",
        OFlag::O_RDWR | OFlag::O_CREAT | OFlag::O_TRUNC,
        Mode::S_IRWXU,
    )
    .unwrap();
    let fd = unsafe { OwnedFd::from_raw_fd(fd) };

    let data = b"Benign executable content\n";
    let size = NonZeroUsize::new(data.len()).unwrap();
    write(&fd, data).unwrap();

    // Map the file with read and execute permissions.
    // Make the mapping shared so updates are synced.
    let addr = unsafe {
        mmap(
            None,
            size,
            ProtFlags::PROT_READ | ProtFlags::PROT_EXEC,
            MapFlags::MAP_SHARED,
            &fd,
            0,
        )
    };

    // Handle error if mmap fails.
    let addr = match addr {
        Ok(addr) => {
            eprintln!("[*] Successful mmap with backing file and PROT_READ|PROT_EXEC");
            addr
        }
        Err(errno) => {
            eprintln!("[!] Failed to mmap with backing file and PROT_READ|PROT_EXEC: {errno}");
            exit(errno as i32);
        }
    };

    // Attempt to modify the mapped memory.
    let data = b"Malicious executable content\n";
    match lseek64(fd.as_raw_fd(), 0, Whence::SeekSet) {
        Ok(_) => {
            eprintln!("[*] Successful seek to beginning for the backing file.");
        }
        Err(errno) => {
            eprintln!("[!] Failed to seek to beginning for the backing file: {errno}");
            exit(errno as i32);
        }
    }
    match write(&fd, data) {
        Ok(_) => {
            eprintln!("[*] Successful write to backing file of readable memory mapping.");
            drop(fd);
        }
        Err(errno) => {
            eprintln!("[!] Failed to write to backing file of readable memory mapping: {errno}");
            exit(errno as i32);
        }
    }

    // Check if the malicious content was written.
    let data = unsafe { std::slice::from_raw_parts(addr.as_ptr() as *const u8, size.get()) };
    let repr = String::from_utf8_lossy(data);
    if data.starts_with(b"Malicious") {
        eprintln!("[!] Malicious content was written: {repr}");
        exit(Errno::EOWNERDEAD as i32);
    } else {
        eprintln!("[!] Malicious content was not written: {repr}");
        exit(0);
    }
}

fn do_sendmsg_scm_rights_one() -> ! {
    let mut result = 0;

    // Create a temporary file and write some data to it
    let file_path = "testfile.txt";
    match File::create(file_path) {
        Ok(mut file) => {
            if let Err(error) = writeln!(file, "Hello, world!") {
                eprintln!("Failed to write to the file: {error}!");
                result |= 1;
            }
        }
        Err(_) => {
            eprintln!("Failed to create the file.");
            result |= 2;
        }
    };

    // Setup UNIX socket pair
    let (parent_fd, child_fd) = match socketpair(
        AddressFamily::Unix,
        SockType::Stream,
        None,
        SockFlag::empty(),
    ) {
        Ok(fds) => fds,
        Err(_) => {
            eprintln!("Failed to create a socket pair.");
            exit(result | 4);
        }
    };

    match unsafe { fork() } {
        Ok(ForkResult::Parent { .. }) => {
            drop(child_fd);

            let stream = UnixStream::from(parent_fd);
            let mut buf = [0u8; 1024];
            let mut fd_buf = [-1; 1]; // Buffer to receive FD

            match stream.recv_with_fd(&mut buf, &mut fd_buf) {
                Ok((size, fd_count)) => {
                    if fd_count != 1 {
                        eprintln!("Didn't receive exactly one FD.");
                        result |= 16;
                    } else if let Ok(text) = std::str::from_utf8(&buf[..size]) {
                        if text != "Hello, world!" {
                            eprintln!("Message content mismatch.");
                            result |= 32;
                        }
                        let received_fd = fd_buf[0];
                        let mut received_file = unsafe { File::from_raw_fd(received_fd) };
                        let mut contents = String::new();
                        if received_file.read_to_string(&mut contents).is_ok() {
                            if contents != "Hello, world!\n" {
                                eprintln!("File content mismatch.");
                                result |= 64;
                            }
                        } else {
                            eprintln!("Failed to read from received file.");
                            result |= 128;
                        }
                    } else {
                        eprintln!("Received invalid UTF-8 data.");
                        result |= 256;
                    }
                }
                Err(_) => {
                    eprintln!("Failed to receive message and FD.");
                    result |= 8;
                }
            };
        }
        Ok(ForkResult::Child) => {
            let file_fd = match File::open(file_path) {
                Ok(file) => file.into_raw_fd(),
                Err(_) => {
                    eprintln!("Child process: failed to open the file.");
                    exit(512);
                }
            };

            drop(parent_fd);

            let stream = UnixStream::from(child_fd);
            let message = b"Hello, world!";

            if stream.send_with_fd(message, &[file_fd]).is_err() {
                eprintln!("Child process: failed to send message and FD.");
                exit(1024);
            }

            drop(stream);
            exit(0); // Exit child process successfully
        }
        Err(_) => {
            eprintln!("fork() failed.");
            result |= 512;
        }
    }

    if result != 0 {
        eprintln!("Test failed with errors: {result}");
        exit(result);
    } else {
        println!("Test succeeded!");
        exit(0);
    }
}

fn do_sendmsg_scm_rights_many() -> ! {
    let mut result = 0;

    // Create 7 temporary files and write data into them.
    for i in 0..7 {
        let file_path = format!("testfile-{i}.txt");
        match File::create(file_path) {
            Ok(mut file) => {
                if let Err(error) = writeln!(file, "file-{i}") {
                    eprintln!("Failed to write to the file: {error}!");
                    result |= 1;
                }
            }
            Err(_) => {
                eprintln!("Failed to create the file.");
                result |= 2;
            }
        };
    }

    // Setup UNIX socket pair
    let (parent_fd, child_fd) = match socketpair(
        AddressFamily::Unix,
        SockType::Stream,
        None,
        SockFlag::empty(),
    ) {
        Ok(fds) => fds,
        Err(_) => {
            eprintln!("Failed to create a socket pair.");
            exit(result | 4);
        }
    };

    match unsafe { fork() } {
        Ok(ForkResult::Parent { .. }) => {
            drop(child_fd);

            let stream = UnixStream::from(parent_fd);
            let mut buf = [0u8; 1024];
            let mut fd_buf = [-1; 7]; // Buffer to receive FD

            match stream.recv_with_fd(&mut buf, &mut fd_buf) {
                Ok((size, fd_count)) => {
                    if fd_count != 7 {
                        eprintln!("Didn't receive exactly seven FDs.");
                        result |= 16;
                    } else if let Ok(text) = std::str::from_utf8(&buf[..size]) {
                        if text != "Hello, world!" {
                            eprintln!("Message content mismatch.");
                            result |= 32;
                        }
                        for (i, received_fd) in fd_buf.iter().enumerate().take(fd_count) {
                            let mut received_file = unsafe { File::from_raw_fd(*received_fd) };
                            let mut contents = String::new();
                            if received_file.read_to_string(&mut contents).is_ok() {
                                if contents != format!("file-{i}\n") {
                                    eprintln!("File content mismatch.");
                                    result |= 64;
                                }
                            } else {
                                eprintln!("Failed to read from received file.");
                                result |= 128;
                            }
                        }
                    } else {
                        eprintln!("Received invalid UTF-8 data.");
                        result |= 256;
                    }
                }
                Err(_) => {
                    eprintln!("Failed to receive message and FD.");
                    result |= 8;
                }
            };
        }
        Ok(ForkResult::Child) => {
            let mut fds = Vec::new();
            for i in 0..7 {
                match File::open(format!("testfile-{i}.txt")) {
                    Ok(file) => {
                        fds.push(file.into_raw_fd());
                    }
                    Err(_) => {
                        eprintln!("Child process: failed to open the file.");
                        exit(512);
                    }
                };
            }

            drop(parent_fd);

            let stream = UnixStream::from(child_fd);
            let message = b"Hello, world!";

            if stream.send_with_fd(message, &fds).is_err() {
                eprintln!("Child process: failed to send message and FD.");
                exit(1024);
            }

            drop(stream);
            exit(0); // Exit child process successfully
        }
        Err(_) => {
            eprintln!("fork() failed.");
            result |= 512;
        }
    }

    if result != 0 {
        eprintln!("Test failed with errors: {result}");
        exit(result);
    } else {
        println!("Test succeeded!");
        exit(0);
    }
}

fn do_sendmmsg() -> ! {
    let (ssock, rsock) = match socketpair(
        AddressFamily::Unix,
        SockType::Datagram,
        None,
        SockFlag::empty(),
    ) {
        Ok(pair) => pair,
        Err(e) => {
            eprintln!("Failed to create socket pair: {}", e);
            exit(1);
        }
    };

    let msgs_to_send = [
        b"Message 1".to_vec(),
        b"Message 11".to_vec(),
        b"Message 111".to_vec(),
    ];

    // Sender thread
    let msgs_len = msgs_to_send.len();
    let sender = thread::spawn(move || {
        let iovs: Vec<IoSlice> = msgs_to_send.iter().map(|msg| IoSlice::new(msg)).collect();
        let iov_refs: Vec<&[IoSlice]> = iovs.iter().map(std::slice::from_ref).collect();
        let addresses: Vec<Option<SockaddrIn>> = vec![None; msgs_to_send.len()];

        let mut data = MultiHeaders::preallocate(msgs_len, None);
        match sendmmsg(
            ssock.as_raw_fd(),
            &mut data,
            &iov_refs,
            &addresses,
            [],
            MsgFlags::empty(),
        ) {
            Ok(results) => {
                // Iterate through each result and compare the number of bytes sent
                for (index, result) in results.enumerate() {
                    let expected_len = msgs_to_send[index].len();
                    if result.bytes != expected_len {
                        eprintln!(
                            "Mismatch in message {} length: expected {}, got {}",
                            index + 1,
                            expected_len,
                            result.bytes
                        );
                        exit(2);
                    }
                }
                println!("All messages sent with correct lengths.");
            }
            Err(e) => {
                eprintln!("Failed to send messages: {}", e);
                exit(3);
            }
        }
    });

    // Receiver thread
    let receiver = thread::spawn(move || {
        let mut recv_buf = vec![0u8; 1024];
        for i in 0..msgs_len {
            let mut iov = [IoSliceMut::new(&mut recv_buf)];
            match recvmsg::<()>(rsock.as_raw_fd(), &mut iov, None, MsgFlags::empty()) {
                Ok(msg) if msg.bytes != 9 + i => {
                    println!("Received message with invalid length {}", msg.bytes);
                    exit(4);
                }
                Ok(msg) => {
                    println!("Received message of length {}", msg.bytes);
                }
                Err(e) => {
                    eprintln!("Failed to receive messages: {}", e);
                    exit(5);
                }
            }
        }
    });

    sender.join().expect("The sender thread has panicked");
    receiver.join().expect("The receiver thread has panicked");

    println!("Successfully sent and received all messages using sendmmsg and recvmsg.");
    exit(0);
}

fn do_kcapi_hash_block() -> ! {
    let input = "Heavy is the root of light. Still is the master of moving."
        .as_bytes()
        .to_vec();
    let addr = AlgAddr::new("hash", "sha1");
    let sock = match socket(
        AddressFamily::Alg,
        SockType::SeqPacket,
        SockFlag::empty(),
        None,
    ) {
        Ok(fd) => fd,
        Err(errno) => {
            eprintln!("Failed to create socket: {errno}");
            exit(errno as i32);
        }
    };
    if let Err(errno) = bind(sock.as_raw_fd(), &addr) {
        eprintln!("Failed to bind socket: {errno}");
        exit(errno as i32);
    }
    let conn = match accept(sock.as_raw_fd()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to accept connection: {errno}");
            exit(errno as i32);
        }
    };
    if let Err(errno) = write(&conn, &input) {
        eprintln!("Failed to write data: {errno}");
        exit(errno as i32);
    }
    let mut digest = [0u8; 20]; // SHA1 produces a 20-byte digest
    if let Err(errno) = read(conn.as_raw_fd(), &mut digest) {
        eprintln!("Failed to read hash: {errno}");
        exit(errno as i32);
    }
    assert_eq!(
        digest.to_lower_hex_string(),
        "32291cb8857f449dc62e0b16fa67626e91331ac9"
    );
    eprintln!("Hash returned by the kernel matched expected hash!");
    exit(0);
}

fn do_kcapi_hash_stream() -> ! {
    let niter = 8;
    let input = "Heavy is the root of light. Still is the master of moving.\n"
        .as_bytes()
        .to_vec();
    let addr = AlgAddr::new("hash", "sha1");
    let sock = match socket(
        AddressFamily::Alg,
        SockType::SeqPacket,
        SockFlag::empty(),
        None,
    ) {
        Ok(fd) => fd,
        Err(errno) => {
            eprintln!("Failed to create socket: {errno}");
            exit(errno as i32);
        }
    };
    if let Err(errno) = bind(sock.as_raw_fd(), &addr) {
        eprintln!("Failed to bind socket: {errno}");
        exit(errno as i32);
    }
    let conn = match accept(sock.as_raw_fd()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to accept connection: {errno}");
            exit(errno as i32);
        }
    };

    // MSG_MORE is indicator for partial messages.
    let flags = MsgFlags::from_bits_retain(nix::libc::MSG_MORE);
    for _ in 0..niter {
        match send(conn.as_raw_fd(), &input, flags) {
            Ok(_) => (),
            Err(errno) => {
                eprintln!("Failed to send data with MSG_MORE: {errno}");
                exit(errno as i32);
            }
        }
    }

    // Send the last chunk without MSG_MORE to indicate the end of the stream
    match send(conn.as_raw_fd(), &[], MsgFlags::empty()) {
        Ok(_) => (),
        Err(errno) => {
            eprintln!("Failed to send final empty message: {errno}");
            exit(errno as i32);
        }
    }

    let mut digest = [0u8; 20]; // SHA1 produces a 20-byte digest
    match recv(conn.as_raw_fd(), &mut digest, MsgFlags::empty()) {
        Ok(_) => (),
        Err(errno) => {
            eprintln!("Failed to read hash: {errno}");
            exit(errno as i32);
        }
    }

    assert_eq!(
        digest.to_lower_hex_string(),
        "5ab8e42c94c1cb56c95446aaf7531981b77908a3"
    );
    eprintln!("Hash returned by the kernel matched expected hash!");
    exit(0);
}

fn do_kcapi_cipher_block() -> ! {
    let addr = AlgAddr::new("skcipher", "cbc(aes)");

    let sock = match socket(
        AddressFamily::Alg,
        SockType::SeqPacket,
        SockFlag::empty(),
        None,
    ) {
        Ok(fd) => fd,
        Err(errno) => {
            eprintln!("Failed to create socket: {errno}");
            exit(errno as i32);
        }
    };

    if let Err(errno) = bind(sock.as_raw_fd(), &addr) {
        eprintln!("Failed to bind socket: {errno}");
        exit(errno as i32);
    }

    // Set the encryption key
    let key = [
        0xde, 0xad, 0xca, 0x11, 0xde, 0xad, 0xca, 0x11, 0xde, 0xad, 0xca, 0x11, 0xde, 0xad, 0xca,
        0x11,
    ];
    if let Err(errno) = setsockopt(&sock, AlgSetKey::default(), &key) {
        eprintln!("Failed to set key: {errno}");
        exit(errno as i32);
    }

    let conn = match accept(sock.as_raw_fd()) {
        Ok(fd) => fd,
        Err(errno) => {
            eprintln!("Failed to accept connection: {errno}");
            exit(errno as i32);
        }
    };

    // Set up the IV
    let iv = [
        0xba, 0xdf, 0xee, 0xd1, 0xba, 0xdf, 0xee, 0xd1, 0xba, 0xdf, 0xee, 0xd1, 0xba, 0xdf, 0xee,
        0xd1,
    ];

    // Set up control messages for encryption operation and IV
    let cmsgs = vec![
        ControlMessage::AlgSetOp(&nix::libc::ALG_OP_ENCRYPT),
        ControlMessage::AlgSetIv(&iv),
    ];

    // This string should be a multiple of 16 characters or the openssl
    // command below will complain.
    let iov = [IoSlice::new(
        b"Heavy is the root of light. Still is the master of moving.......",
    )];
    if let Err(errno) = sendmsg::<AlgAddr>(conn, &iov, &cmsgs, MsgFlags::empty(), None) {
        eprintln!("Failed to send data: {errno}");
        exit(errno as i32);
    }

    // Allocate a buffer to receive the encrypted data. The size of the
    // buffer must match the expected output size, which for AES-128-CBC
    // is the same as the input size when the input is an exact multiple
    // of the AES block size (16 bytes).  In this case, the input
    // message is padded to 64 bytes, which is a multiple of 16.  Thus,
    // the encrypted output is also 64 bytes.  If the input size
    // changes, the buffer size must be adjusted accordingly to match
    // the nearest multiple of 16.
    let mut buf = vec![0u8; 64]; // Size must be a multiple of 16 for AES-128-CBC
    match recv(conn, &mut buf, MsgFlags::empty()) {
        Ok(_) => (),
        Err(errno) => {
            eprintln!("Failed to read data: {errno}");
            exit(errno as i32);
        }
    }

    // Expected result may be calculated with:
    // echo -n "$input" |\
    //  openssl enc -aes-128-cbc \
    //              -K deadca11deadca11deadca11deadca11 \
    //              -iv badfeed1badfeed1badfeed1badfeed1 \
    //              -nopad -nosalt | xxd -p | tr -d '\n'
    assert_eq!(
        buf.to_lower_hex_string(),
        "3bd8aa6245ccc9df999e845622ed80a978256646cd2e01118f095626533de65be98e98c3426e0d943c7a659401c9fe43a822796894241601879fbd71955c7920"
    );

    eprintln!("Encrypted data returned by the kernel matched expected data!");
    exit(0);
}

/// This function attempts to use `mmap` with `MAP_FIXED` on the NULL address,
/// which should succeed when unsandboxed and get killed when sandboed.
fn do_mmap_fixed_null() -> ! {
    let addr = None; // Target address (NULL).
    let length = NonZeroUsize::new(4096).unwrap(); // Size of the memory mapping.
    let prot = ProtFlags::PROT_READ | ProtFlags::PROT_WRITE;
    let flags = MapFlags::MAP_PRIVATE | MapFlags::MAP_FIXED; // Fixed mapping.
    let file = File::open("/dev/zero").unwrap();
    let offset = 0; // No offset needed for anonymous mapping.

    // Attempt to map memory at the NULL address with MAP_FIXED.
    let result = unsafe { mmap(addr, length, prot, flags, file, offset) };

    // Check if the mapping was successful.
    if let Err(errno) = result {
        eprintln!("Unexpected failure from mmap: {errno}");
        exit(errno as i32);
    } else {
        eprintln!("Unexpected success from mmap.");
        exit(1);
    }
}

/// mprotect PROT_EXEC a previously PROT_READ region.
fn do_mprotect_read_to_exec() -> ! {
    let one_k_non_zero = NonZeroUsize::new(1024).unwrap();

    // Preparation: Map a PROT_READ region.
    let mem_for_protect = match unsafe {
        mmap(
            None,
            one_k_non_zero,
            ProtFlags::PROT_READ,
            MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE,
            BorrowedFd::borrow_raw(-42),
            0,
        )
    } {
        Ok(mem) => mem,
        Err(errno) => {
            eprintln!("[!] mmap PROT_READ with MAP_ANONYMOUS failed: {errno}");
            exit(errno as i32);
        }
    };

    // mprotect PROT_EXEC a previously PROT_READ region.
    match unsafe { mprotect(mem_for_protect, 1024, ProtFlags::PROT_EXEC) } {
        Ok(_) => exit(0),
        Err(errno) => exit(errno as i32),
    }
}

/// mprotect PROT_WRITE|PROT_EXEC a previously PROT_READ region.
fn do_mprotect_read_to_write_exec() -> ! {
    let one_k_non_zero = NonZeroUsize::new(1024).unwrap();

    // Preparation: Map a PROT_READ region.
    let mem_for_protect = match unsafe {
        mmap(
            None,
            one_k_non_zero,
            ProtFlags::PROT_READ,
            MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE,
            BorrowedFd::borrow_raw(-42),
            0,
        )
    } {
        Ok(mem) => mem,
        Err(errno) => {
            eprintln!("[!] mmap PROT_READ with MAP_ANONYMOUS failed: {errno}");
            exit(errno as i32);
        }
    };

    // mprotect PROT_WRITE|PROT_EXEC a previously PROT_READ region.
    match unsafe {
        mprotect(
            mem_for_protect,
            1024,
            ProtFlags::PROT_WRITE | ProtFlags::PROT_EXEC,
        )
    } {
        Ok(_) => exit(0),
        Err(errno) => exit(errno as i32),
    }
}

/// mprotect PROT_EXEC a previously PROT_WRITE region.
fn do_mprotect_write_to_exec() -> ! {
    let one_k_non_zero = NonZeroUsize::new(1024).unwrap();

    // Preparation: Map a PROT_WRITE region.
    let mem_for_protect = match unsafe {
        mmap(
            None,
            one_k_non_zero,
            ProtFlags::PROT_WRITE,
            MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE,
            BorrowedFd::borrow_raw(-42),
            0,
        )
    } {
        Ok(mem) => mem,
        Err(errno) => {
            eprintln!("[!] mmap PROT_WRITE with MAP_ANONYMOUS failed: {errno}");
            exit(errno as i32);
        }
    };

    // mprotect PROT_EXEC a previously PROT_WRITE region.
    match unsafe { mprotect(mem_for_protect, 1024, ProtFlags::PROT_EXEC) } {
        Ok(_) => exit(0),
        Err(errno) => exit(errno as i32),
    }
}

/// mprotect PROT_READ|PROT_EXEC a previously PROT_WRITE region.
fn do_mprotect_write_to_read_exec() -> ! {
    let one_k_non_zero = NonZeroUsize::new(1024).unwrap();

    // Preparation: Map a PROT_WRITE region.
    let mem_for_protect = match unsafe {
        mmap(
            None,
            one_k_non_zero,
            ProtFlags::PROT_WRITE,
            MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE,
            BorrowedFd::borrow_raw(-42),
            0,
        )
    } {
        Ok(mem) => mem,
        Err(errno) => {
            eprintln!("[!] mmap PROT_WRITE with MAP_ANONYMOUS failed: {errno}");
            exit(errno as i32);
        }
    };

    // mprotect PROT_READ|PROT_EXEC a previously PROT_WRITE region.
    match unsafe {
        mprotect(
            mem_for_protect,
            1024,
            ProtFlags::PROT_READ | ProtFlags::PROT_EXEC,
        )
    } {
        Ok(_) => exit(0),
        Err(errno) => exit(errno as i32),
    }
}

/// Detect ptracer using traceme and attach operations.
fn do_detect_ptrace() -> ! {
    let mut result = 0;

    match traceme() {
        Ok(_) => {
            eprintln!("TRACEME succeded!");
            eprintln!("Success! ptracer was not detected!");
        }
        Err(errno) => {
            eprintln!("TRACEME failed: {errno}");
            eprintln!("Failure! ptracer was detected!");
            result |= 1;
        }
    }

    match attach(Pid::this()) {
        Ok(_) => {
            eprintln!("ATTACH succeeded!");
            eprintln!("Success! ptracer was not detected!");
        }
        Err(errno) => {
            eprintln!("ATTACH failed: {errno}");
            eprintln!("Failure! ptracer was detected!");
            result |= 2;
        }
    }

    match seize(Pid::this(), Options::empty()) {
        Ok(_) => {
            eprintln!("SEIZE succeeded!");
            eprintln!("Success! ptracer was not detected!");
        }
        Err(errno) => {
            eprintln!("SEIZE failed: {errno}");
            eprintln!("Failure! ptracer was detected!");
            result |= 4;
        }
    }

    if result == 0 {
        eprintln!("Test succeded!");
        exit(0);
    } else {
        eprintln!("Test failed: {result}");
        exit(1);
    }
}

/// Try really hard to segfault.
fn do_segv() -> ! {
    // Dereference a NULL pointer.
    unsafe {
        let ptr: *mut i32 = std::ptr::null_mut();
        *ptr = 42;
        std::hint::unreachable_unchecked();
    }
}

/// Attempt to create a socket with the given domain, type and protocol and exit with errno.
fn do_socket() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 4 {
        panic!("Expected only socket domain, type and protocol as argument.");
    }
    let domain: nix::libc::c_int = args[1].parse().expect("Invalid Socket Domain");
    let ty: nix::libc::c_int = args[2].parse().expect("Invalid Socket Type");
    let proto: nix::libc::c_int = args[3].parse().expect("Invalid Socket Protocol");

    let fd = unsafe { nix::libc::socket(domain, ty, proto) };
    let domain_repr = AddressFamily::from_i32(domain);
    let ty_repr = SockType::try_from(ty);
    if fd == -1 {
        let errno = Errno::last();
        eprintln!("socket({domain}={domain_repr:?}, {ty}={ty_repr:?}, {proto}) = {errno}");
        exit(errno as i32);
    } else {
        eprintln!(
            "socket({domain}={domain:?}, {ty}={ty_repr:?}, {proto}) = {}",
            fd.as_raw_fd()
        );
        let _ = close(fd);
        exit(0);
    }
}

/// Given a path, run lgetxattr on it and return errno
fn do_lgetxattr() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        panic!("Expected only a path as argument.");
    }
    let path = Path::new(&args[1]);
    let path = CString::new(path.as_os_str().as_bytes()).unwrap();
    let name = CString::new("user.test_xattr_support").unwrap();

    let mut buf = vec![0u8; 8];
    unsafe {
        nix::libc::lgetxattr(
            path.as_ptr(),
            name.as_ptr(),
            buf.as_mut_ptr() as *mut nix::libc::c_void,
            buf.len(),
        )
    };
    exit(Errno::last() as i32);
}

/// Check if truncate works sanely
fn do_truncate() -> ! {
    // Create and write to a file.
    let fd = match open(
        "./file",
        OFlag::O_RDWR | OFlag::O_TRUNC | OFlag::O_CREAT | OFlag::O_EXCL,
        Mode::S_IRUSR | Mode::S_IWUSR,
    ) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to create ./file: {errno}");
            exit(1);
        }
    };

    if let Err(errno) = write(&fd, b"Hello") {
        eprintln!("Failed to write to file: {errno}");
        exit(1);
    }

    drop(fd);

    // Verify initial size.
    let fd = match open("./file", OFlag::O_RDONLY, Mode::empty()) {
        Ok(fd) => fd,
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 5 {
                eprintln!("File size is {size} but expected 5");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    let _ = close(fd);

    // Test increasing the size.
    if let Err(errno) = truncate("./file", 314159) {
        eprintln!("Failed to truncate file: {errno}");
        exit(1);
    }

    let fd = match open("./file", OFlag::O_RDONLY, Mode::empty()) {
        Ok(fd) => fd,
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 314159 {
                eprintln!("File size is {size} but expected 314159");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    let _ = close(fd);

    // Test reducing the size.
    if let Err(errno) = truncate("./file", 3) {
        eprintln!("Failed to truncate file: {errno}");
        exit(1);
    }

    let fd = match open("./file", OFlag::O_RDONLY, Mode::empty()) {
        Ok(fd) => fd,
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 3 {
                eprintln!("File size is {size} but expected 3");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    let _ = close(fd);

    // Test reducing the size to 0.
    if let Err(errno) = truncate("./file", 0) {
        eprintln!("Failed to truncate file: {errno}");
        exit(1);
    }

    let fd = match open("./file", OFlag::O_RDONLY, Mode::empty()) {
        Ok(fd) => fd,
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 0 {
                eprintln!("File size is {size} but expected 0");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    let _ = close(fd);

    // Test behaviour for nonexistent files.
    match truncate("/nonexistent", 0) {
        Ok(_) => {
            eprintln!("Truncate on nonexistent file did not fail");
            exit(1);
        }
        Err(errno) if errno != Errno::ENOENT => {
            eprintln!("Unexpected error for nonexistent file: {errno}");
            exit(1);
        }
        _ => {}
    }

    // Test behaviour for directories.
    match truncate(".", 0) {
        Ok(_) => {
            eprintln!("Truncate on directory did not fail");
            exit(1);
        }
        Err(errno) if errno != Errno::EISDIR => {
            eprintln!("Unexpected error for directory: {errno}");
            exit(1);
        }
        _ => {}
    }

    // Test behaviour for trailing slashes.
    match truncate("./file/", 0) {
        Ok(_) => {
            eprintln!("Truncate on file with trailing slash did not fail");
            exit(1);
        }
        Err(errno) if errno != Errno::ENOTDIR => {
            eprintln!("Unexpected error for file with trailing slash: {errno}");
            exit(1);
        }
        _ => {}
    }

    // Test behaviour for invalid lengths.
    match truncate("./file", -3) {
        Ok(_) => {
            eprintln!("Truncate with invalid length did not fail");
            exit(1);
        }
        Err(errno) if errno != Errno::EINVAL => {
            eprintln!("Unexpected error for invalid length: {errno}");
            exit(1);
        }
        _ => {}
    }

    eprintln!("Truncate test succeeded!");
    exit(0);
}

/// Check if ftruncate works sanely
fn do_ftruncate() -> ! {
    // Create and write to a file.
    let fd = match open(
        "./file",
        OFlag::O_RDWR | OFlag::O_TRUNC | OFlag::O_CREAT | OFlag::O_EXCL,
        Mode::S_IRUSR | Mode::S_IWUSR,
    ) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to create ./file: {errno}");
            exit(1);
        }
    };

    if let Err(errno) = write(&fd, b"Hello") {
        eprintln!("Failed to write to file: {errno}");
        exit(1);
    }

    drop(fd);

    // Verify initial size.
    let fd = match open("./file", OFlag::O_RDWR, Mode::empty()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 5 {
                eprintln!("File size is {size} but expected 5");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    // Test increasing the size.
    if let Err(errno) = ftruncate(&fd, 314159) {
        eprintln!("Failed to truncate file: {errno}");
        exit(1);
    }

    drop(fd);

    let fd = match open("./file", OFlag::O_RDWR, Mode::empty()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 314159 {
                eprintln!("File size is {size} but expected 314159");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    // Test reducing the size.
    if let Err(errno) = ftruncate(&fd, 3) {
        eprintln!("Failed to truncate file: {errno}");
        exit(1);
    }

    drop(fd);

    let fd = match open("./file", OFlag::O_RDWR, Mode::empty()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 3 {
                eprintln!("File size is {size} but expected 3");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    // Test reducing the size to 0.
    if let Err(errno) = ftruncate(&fd, 0) {
        eprintln!("Failed to truncate file: {errno}");
        exit(1);
    }

    drop(fd);

    let fd = match open("./file", OFlag::O_RDWR, Mode::empty()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 0 {
                eprintln!("File size is {size} but expected 0");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    // Test behaviour for invalid lengths.
    match ftruncate(&fd, -3) {
        Ok(_) => {
            eprintln!("Truncate with invalid length did not fail");
            exit(1);
        }
        Err(errno) if errno != Errno::EINVAL => {
            eprintln!("Unexpected error for invalid length: {errno}");
            exit(1);
        }
        _ => {}
    }

    drop(fd);

    eprintln!("ftruncate test succeeded!");
    exit(0);
}

/// Check if truncate64 works sanely
fn do_truncate64() -> ! {
    // Create and write to a file.
    let fd = match open(
        "./file",
        OFlag::O_RDWR | OFlag::O_TRUNC | OFlag::O_CREAT | OFlag::O_EXCL,
        Mode::S_IRUSR | Mode::S_IWUSR,
    ) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to create ./file: {errno}");
            exit(1);
        }
    };

    if let Err(errno) = write(&fd, b"Hello") {
        eprintln!("Failed to write to file: {errno}");
        exit(1);
    }

    drop(fd);

    // Verify initial size.
    let fd = match open("./file", OFlag::O_RDONLY, Mode::empty()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 5 {
                eprintln!("File size is {size} but expected 5");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    drop(fd);

    // Test increasing the size.
    if let Err(errno) = truncate64("./file", 314159) {
        eprintln!("Failed to truncate file: {errno}");
        exit(1);
    }

    let fd = match open("./file", OFlag::O_RDONLY, Mode::empty()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 314159 {
                eprintln!("File size is {size} but expected 314159");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    drop(fd);

    // Test reducing the size.
    if let Err(errno) = truncate64("./file", 3) {
        eprintln!("Failed to truncate file: {errno}");
        exit(1);
    }

    let fd = match open("./file", OFlag::O_RDONLY, Mode::empty()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 3 {
                eprintln!("File size is {size} but expected 3");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    drop(fd);

    // Test reducing the size to 0.
    if let Err(errno) = truncate64("./file", 0) {
        eprintln!("Failed to truncate file: {errno}");
        exit(1);
    }

    let fd = match open("./file", OFlag::O_RDONLY, Mode::empty()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 0 {
                eprintln!("File size is {size} but expected 0");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    drop(fd);

    // Test behaviour for nonexistent files.
    match truncate64("/nonexistent", 0) {
        Ok(_) => {
            eprintln!("Truncate on nonexistent file did not fail");
            exit(1);
        }
        Err(errno) if errno != Errno::ENOENT => {
            eprintln!("Unexpected error for nonexistent file: {errno}");
            exit(1);
        }
        _ => {}
    }

    // Test behaviour for directories.
    match truncate64(".", 0) {
        Ok(_) => {
            eprintln!("Truncate on directory did not fail");
            exit(1);
        }
        Err(errno) if errno != Errno::EISDIR => {
            eprintln!("Unexpected error for directory: {errno}");
            exit(1);
        }
        _ => {}
    }

    // Test behaviour for trailing slashes.
    match truncate64("./file/", 0) {
        Ok(_) => {
            eprintln!("Truncate on file with trailing slash did not fail");
            exit(1);
        }
        Err(errno) if errno != Errno::ENOTDIR => {
            eprintln!("Unexpected error for file with trailing slash: {errno}");
            exit(1);
        }
        _ => {}
    }

    // Test behaviour for invalid lengths.
    match truncate64("./file", -3) {
        Ok(_) => {
            eprintln!("Truncate with invalid length did not fail");
            exit(1);
        }
        Err(errno) if errno != Errno::EINVAL => {
            eprintln!("Unexpected error for invalid length: {errno}");
            exit(1);
        }
        _ => {}
    }

    eprintln!("Truncate test succeeded!");
    exit(0);
}

/// Check if ftruncate64 works sanely
fn do_ftruncate64() -> ! {
    // Create and write to a file.
    let fd = match open(
        "./file",
        OFlag::O_RDWR | OFlag::O_TRUNC | OFlag::O_CREAT | OFlag::O_EXCL,
        Mode::S_IRUSR | Mode::S_IWUSR,
    ) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to create ./file: {errno}");
            exit(1);
        }
    };

    if let Err(errno) = write(&fd, b"Hello") {
        eprintln!("Failed to write to file: {errno}");
        exit(1);
    }

    drop(fd);

    // Verify initial size.
    let fd = match open("./file", OFlag::O_RDWR, Mode::empty()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 5 {
                eprintln!("File size is {size} but expected 5");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    // Test increasing the size.
    if let Err(errno) = ftruncate64(fd.as_raw_fd(), 314159) {
        eprintln!("Failed to truncate file: {errno}");
        exit(1);
    }

    drop(fd);

    let fd = match open("./file", OFlag::O_RDWR, Mode::empty()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 314159 {
                eprintln!("File size is {size} but expected 314159");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    // Test reducing the size.
    if let Err(errno) = ftruncate64(fd.as_raw_fd(), 3) {
        eprintln!("Failed to truncate file: {errno}");
        exit(1);
    }

    drop(fd);

    let fd = match open("./file", OFlag::O_RDWR, Mode::empty()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 3 {
                eprintln!("File size is {size} but expected 3");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    // Test reducing the size to 0.
    if let Err(errno) = ftruncate64(fd.as_raw_fd(), 0) {
        eprintln!("Failed to truncate file: {errno}");
        exit(1);
    }

    drop(fd);

    let fd = match open("./file", OFlag::O_RDWR, Mode::empty()) {
        Ok(fd) => unsafe { OwnedFd::from_raw_fd(fd) },
        Err(errno) => {
            eprintln!("Failed to open ./file: {errno}");
            exit(1);
        }
    };

    match lseek64(fd.as_raw_fd(), 0, Whence::SeekEnd) {
        Ok(size) => {
            if size != 0 {
                eprintln!("File size is {size} but expected 0");
                exit(1);
            }
        }
        Err(errno) => {
            eprintln!("Failed to seek: {errno}");
            exit(1);
        }
    }

    // Test behaviour for invalid lengths.
    match ftruncate64(fd.as_raw_fd(), -3) {
        Ok(_) => {
            eprintln!("Truncate with invalid length did not fail");
            exit(1);
        }
        Err(errno) if errno != Errno::EINVAL => {
            eprintln!("Unexpected error for invalid length: {errno}");
            exit(1);
        }
        _ => {}
    }

    drop(fd);

    eprintln!("fruncate64 test succeeded!");
    exit(0);
}

/// Check if readlink with the given argument succeeds.
fn do_readlink() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        panic!("Expected only a path as argument.");
    }

    let path = Path::new(&args[1]);
    match readlink(path).map(PathBuf::from) {
        Ok(target) => {
            eprintln!("readlink {} -> {}", path.display(), target.display());
            exit(0);
        }
        Err(errno) => {
            eprintln!("readlink {} failed: {errno}", path.display());
            exit(errno as i32);
        }
    }
}

/// Check if the process has the given capability and exit with success if that's true
fn do_hascap() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        panic!("Expected only a capability name as argument.");
    }

    eprintln!("Current list of Capabilities:");
    for capset in [
        syd::caps::CapSet::Ambient,
        syd::caps::CapSet::Bounding,
        syd::caps::CapSet::Effective,
        syd::caps::CapSet::Inheritable,
        syd::caps::CapSet::Permitted,
    ] {
        let caps = syd::caps::read(None, capset).unwrap_or_default();
        let mut caps = caps
            .into_iter()
            .map(|cap| cap.to_string())
            .collect::<Vec<_>>();
        caps.sort();
        let caps = caps.join(", ");
        eprintln!("{capset:?}: {caps}");
    }

    let cap = syd::caps::Capability::from_str(&syd::caps::to_canonical(&args[1])).expect("cap2str");
    if syd::caps::has_cap(None, syd::caps::CapSet::Permitted, cap).unwrap_or(false) {
        eprintln!("Process has the capability {cap} permitted!");
        exit(0);
    } else {
        eprintln!("Process does not have the capability {cap} permitted!");
        exit(Errno::ENOENT as i32);
    }
}

/// Given real, effective, and saved group ids, set group ids then get current GIDs and check if they match
fn do_setresgid() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 4 {
        panic!("Expected only real, effective and saved group IDs as argument.");
    }
    let rgid: nix::libc::c_long = args[1].parse().expect("Invalid Real Group ID");
    let egid: nix::libc::c_long = args[2].parse().expect("Invalid Effective Group ID");
    let sgid: nix::libc::c_long = args[3].parse().expect("Invalid Saved Group ID");

    let resgid = getresgid().expect("getresgid");
    let old_rgid = resgid.real;
    let old_egid = resgid.effective;
    let old_sgid = resgid.saved;
    if unsafe { nix::libc::syscall(nix::libc::SYS_setresgid, rgid, egid, sgid) } == -1 {
        let errno = Errno::last();
        eprintln!("setresgid failed: {errno}!");
        exit(errno as i32);
    }
    let resgid = getresgid().expect("getresgid");
    let cur_rgid = resgid.real.as_raw();
    let cur_egid = resgid.effective.as_raw();
    let cur_sgid = resgid.saved.as_raw();
    if rgid != -1 && i64::from(rgid) != i64::from(cur_rgid) {
        eprintln!("setresgid did not change real GID (current: {cur_rgid} old: {old_rgid} set: {rgid}), aborting!");
        unsafe { nix::libc::abort() };
    } else if rgid != -1 {
        eprintln!("setresgid successfully changed real GID from {old_rgid} to {cur_rgid}.");
    }
    if egid != -1 && i64::from(egid) != i64::from(cur_egid) {
        eprintln!("setresgid did not change effective GID (current: {cur_egid} old: {old_egid} set: {egid}), aborting!");
        unsafe { nix::libc::abort() };
    } else if egid != -1 {
        eprintln!("setresgid successfully changed effective GID from {old_egid} to {cur_egid}.");
    }
    if sgid != -1 && i64::from(sgid) != i64::from(cur_sgid) {
        eprintln!("setresgid did not change saved GID (current: {cur_sgid} old: {old_sgid} set: {sgid}), aborting!");
        unsafe { nix::libc::abort() };
    } else if sgid != -1 {
        eprintln!("setresgid successfully changed saved GID from {old_sgid} to {cur_sgid}.");
    }
    exit(0);
}

/// Given real and effective group ids, set group ids then get current GIDs and check if they match
fn do_setregid() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 3 {
        panic!("Expected only real and effective group IDs as argument.");
    }
    let rgid: nix::libc::c_long = args[1].parse().expect("Invalid Real Group ID");
    let egid: nix::libc::c_long = args[2].parse().expect("Invalid Effective Group ID");

    let resgid = getresgid().expect("getresgid");
    let old_rgid = resgid.real;
    let old_egid = resgid.effective;
    if unsafe { nix::libc::syscall(nix::libc::SYS_setregid, rgid, egid) } == -1 {
        let errno = Errno::last();
        eprintln!("setregid failed: {errno}!");
        exit(errno as i32);
    }
    let resgid = getresgid().expect("getresgid");
    let cur_rgid = resgid.real.as_raw();
    let cur_egid = resgid.effective.as_raw();
    if rgid != -1 && i64::from(rgid) != i64::from(cur_rgid) {
        eprintln!("setregid did not change real GID (current: {cur_rgid} old: {old_rgid} set: {rgid}), aborting!");
        unsafe { nix::libc::abort() };
    } else if rgid != -1 {
        eprintln!("setregid successfully changed real GID from {old_rgid} to {cur_rgid}.");
    }
    if egid != -1 && i64::from(egid) != i64::from(cur_egid) {
        eprintln!("setregid did not change effective GID (current: {cur_egid} old: {old_egid} set: {egid}), aborting!");
        unsafe { nix::libc::abort() };
    } else if egid != -1 {
        eprintln!("setregid successfully changed effective GID from {old_egid} to {cur_egid}.");
    }
    exit(0);
}

/// Given a group id, set group id then get current GID and check if they match
fn do_setgid() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        panic!("Expected only a group ID as argument.");
    }
    let gid: nix::libc::gid_t = args[1].parse().expect("Invalid User ID");
    let gid = Gid::from_raw(gid);
    let old = getgid();
    if let Err(errno) = setgid(gid) {
        eprintln!("setgid failed: {errno}!");
        exit(errno as i32);
    }
    let cur = getgid();
    if cur != gid {
        eprintln!("setgid did not work (current: {cur} old: {old} set: {gid}), aborting!");
        unsafe { nix::libc::abort() };
    }
    eprintln!("setgid successfully changed gid from {old} to {cur}.");
    exit(0);
}

/// Given real, effective, and saved user ids, set user ids then get current UIDs and check if they match
fn do_setresuid() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 4 {
        panic!("Expected only real, effective and saved user IDs as argument.");
    }
    let ruid: nix::libc::c_long = args[1].parse().expect("Invalid Real User ID");
    let euid: nix::libc::c_long = args[2].parse().expect("Invalid Effective User ID");
    let suid: nix::libc::c_long = args[3].parse().expect("Invalid Saved User ID");

    let resuid = getresuid().expect("getresuid");
    let old_ruid = resuid.real;
    let old_euid = resuid.effective;
    let old_suid = resuid.saved;
    if unsafe { nix::libc::syscall(nix::libc::SYS_setresuid, ruid, euid, suid) } == -1 {
        let errno = Errno::last();
        eprintln!("setresuid failed: {errno}!");
        exit(errno as i32);
    }
    let resuid = getresuid().expect("getresuid");
    let cur_ruid = resuid.real.as_raw();
    let cur_euid = resuid.effective.as_raw();
    let cur_suid = resuid.saved.as_raw();
    if ruid != -1 && i64::from(ruid) != i64::from(cur_ruid) {
        eprintln!("setresuid did not change real UID (current: {cur_ruid} old: {old_ruid} set: {ruid}), aborting!");
        unsafe { nix::libc::abort() };
    } else if ruid != -1 {
        eprintln!("setresuid successfully changed real UID from {old_ruid} to {cur_ruid}.");
    }
    if euid != -1 && i64::from(euid) != i64::from(cur_euid) {
        eprintln!("setresuid did not change effective UID (current: {cur_euid} old: {old_euid} set: {euid}), aborting!");
        unsafe { nix::libc::abort() };
    } else if euid != -1 {
        eprintln!("setresuid successfully changed effective UID from {old_euid} to {cur_euid}.");
    }
    if suid != -1 && i64::from(suid) != i64::from(cur_suid) {
        eprintln!("setresuid did not change saved UID (current: {cur_suid} old: {old_suid} set: {suid}), aborting!");
        unsafe { nix::libc::abort() };
    } else if suid != -1 {
        eprintln!("setresuid successfully changed saved UID from {old_suid} to {cur_suid}.");
    }
    exit(0);
}

/// Given real and effective user ids, set user ids then get current UIDs and check if they match
fn do_setreuid() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 3 {
        panic!("Expected only real and effective user IDs as argument.");
    }
    let ruid: nix::libc::c_long = args[1].parse().expect("Invalid Real User ID");
    let euid: nix::libc::c_long = args[2].parse().expect("Invalid Effective User ID");

    let resuid = getresuid().expect("getresuid");
    let old_ruid = resuid.real;
    let old_euid = resuid.effective;
    if unsafe { nix::libc::syscall(nix::libc::SYS_setreuid, ruid, euid) } == -1 {
        let errno = Errno::last();
        eprintln!("setreuid failed: {errno}!");
        exit(errno as i32);
    }
    let resuid = getresuid().expect("getresuid");
    let cur_ruid = resuid.real.as_raw();
    let cur_euid = resuid.effective.as_raw();
    if ruid != -1 && i64::from(ruid) != i64::from(cur_ruid) {
        eprintln!("setreuid did not change real UID (current: {cur_ruid} old: {old_ruid} set: {ruid}), aborting!");
        unsafe { nix::libc::abort() };
    } else if ruid != -1 {
        eprintln!("setreuid successfully changed real UID from {old_ruid} to {cur_ruid}.");
    }
    if euid != -1 && i64::from(euid) != i64::from(cur_euid) {
        eprintln!("setreuid did not change effective UID (current: {cur_euid} old: {old_euid} set: {euid}), aborting!");
        unsafe { nix::libc::abort() };
    } else if euid != -1 {
        eprintln!("setreuid successfully changed effective UID from {old_euid} to {cur_euid}.");
    }
    exit(0);
}

/// Given a user id, set user id then get current UID and check if they match
fn do_setuid() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        panic!("Expected only a user ID as argument.");
    }
    let uid: nix::libc::uid_t = args[1].parse().expect("Invalid User ID");
    let uid = Uid::from_raw(uid);
    let old = getuid();
    if let Err(errno) = setuid(uid) {
        eprintln!("setuid failed: {errno}!");
        exit(errno as i32);
    }
    let cur = getuid();
    if cur != uid {
        eprintln!("setuid did not work (current: {cur} old: {old} set: {uid}), aborting!");
        unsafe { nix::libc::abort() };
    }
    eprintln!("setuid successfully changed UID from {old} to {cur}.");
    exit(0);
}

/// Given an exit code, exit with this code.
fn do_getuid() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        panic!("Expected only a user ID as argument.");
    }
    let uid: nix::libc::uid_t = args[1].parse().expect("Invalid User ID");
    let uid = Uid::from_raw(uid);
    let cur = getuid();
    exit(if cur == uid { 0 } else { cur.as_raw() as i32 });
}

/// Try to execute the given path and return errno on failure
fn do_exec() -> ! {
    // Retrieve command-line arguments and skip the first one (program name).
    let args: Vec<CString> = std::env::args_os()
        .skip(1)
        .map(|arg| CString::new(arg.into_vec()).unwrap())
        .collect();

    // Ensure there is at least one argument to be used as the command.
    if args.is_empty() {
        eprintln!("Usage: SYD_TEST_DO=exec syd-test-do <command> [args...]");
        exit(127);
    }

    // Prepare the path and args for execv.
    let path = &args[0];
    let exec_args: Vec<&CStr> = args.iter().map(|arg| arg.as_c_str()).collect();

    // Call execv, which uses the current environment by default.
    #[allow(irrefutable_let_patterns)]
    let Err(err) = execv(path, &exec_args) else {
        unsafe { std::hint::unreachable_unchecked() }
    };
    eprintln!("Error executing command: {:?}", err);
    exit(err as i32);
}

/// Given a signal, send the current process group the signal and exit with errno
fn do_killpg_self() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        panic!("Expected a signal as argument.");
    }
    let sig = args[1].parse::<nix::libc::c_int>().expect("Invalid Signal");
    let sig = if sig == 0 {
        None
    } else {
        Some(Signal::try_from(sig).expect("Invalid Signal"))
    };

    let pgrp = getpgrp();
    eprintln!("Sending signal {sig:?} to the current process group {pgrp}...");

    match killpg(pgrp, sig) {
        Ok(_) => {
            eprintln!("Success!");
            exit(0);
        }
        Err(errno) => {
            eprintln!("Error: {errno}!");
            exit(errno as i32);
        }
    }
}

/// Given a tid and signal, send the signal to pid and exit with errno
fn do_tkill() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 3 {
        panic!("Expected a tid and signal as argument.");
    }
    let tid = args[1].parse::<nix::libc::pid_t>().expect("Invalid PID");
    let sig = args[2].parse::<nix::libc::c_int>().expect("Invalid Signal");

    eprintln!("Sending signal {sig} to thread {tid}...");
    if unsafe { nix::libc::syscall(nix::libc::SYS_tkill, tid, sig) } == 0 {
        eprintln!("Success!");
        exit(0);
    } else {
        let errno = Errno::last();
        eprintln!("Error: {errno}!");
        exit(errno as i32);
    }
}

/// Given a pid and signal, send the signal to pid and exit with errno
fn do_kill() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 3 {
        panic!("Expected a pid and signal as argument.");
    }
    let pid = Pid::from_raw(args[1].parse::<nix::libc::pid_t>().expect("Invalid PID"));
    let sig = args[2].parse::<nix::libc::c_int>().expect("Invalid Signal");
    let sig = if sig == 0 {
        None
    } else {
        Some(Signal::try_from(sig).expect("Invalid Signal"))
    };

    eprintln!("Sending signal {sig:?} to process {pid}...");
    match kill(pid, sig) {
        Ok(_) => {
            eprintln!("Success!");
            exit(0);
        }
        Err(errno) => {
            eprintln!("Error: {errno}!");
            exit(errno as i32);
        }
    }
}

/// Given an exit code, exit with this code.
fn do_exit() -> ! {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        panic!("Expected only an exit code as argument.");
    }
    let code: i32 = args[1].parse().expect("Invalid Exit Code");
    exit(code);
}

/// Gradually allocates memory and exits gracefully when memory is exhausted.
fn do_alloc() -> ! {
    let mut total_allocated: usize = 0;
    let mut allocations: Vec<Vec<u8>> = Vec::new();
    let mut current_alloc_size: usize = 1_024_000; // Start with 1 MB

    loop {
        // Check for integer overflow in allocation size
        let new_alloc_size = match current_alloc_size.checked_mul(2) {
            Some(size) => size,
            None => {
                eprintln!(
                    "Allocation size overflow. Total allocated: {} bytes",
                    syd::human_size(total_allocated)
                );
                exit(Errno::EOVERFLOW as i32);
            }
        };

        // Attempt to allocate memory
        let mut mem_block = vec![0u8; current_alloc_size];
        total_allocated += current_alloc_size;
        println!(
            "Allocated: {} bytes (Total: {} bytes)",
            syd::human_size(current_alloc_size),
            syd::human_size(total_allocated)
        );

        // Use the allocated memory to prevent it from being optimized out
        for byte in mem_block.iter_mut() {
            *byte = 7; // This operation ensures the memory is used
        }

        allocations.push(mem_block);

        // Update the allocation size for next iteration
        current_alloc_size = new_alloc_size;
    }
}

// Used by do_truncate64 test.
pub fn truncate64<P: ?Sized + NixPath>(path: &P, len: nix::libc::off64_t) -> Result<(), Errno> {
    let res = path.with_nix_path(|cstr| unsafe { nix::libc::truncate64(cstr.as_ptr(), len) })?;
    Errno::result(res).map(drop)
}
