#!/usr/bin/env bash
# The Linux containment tests on a kernel of the architecture itself, in a
# virtual machine (qemu-system), for the architectures no machine at hand
# runs natively:
#
#   scripts/vm.sh                 riscv64, riscv32 and arm
#   scripts/vm.sh ARCH...         these: riscv64, riscv32, arm
#
# qemu-user, which runs the rest of the tests for those architectures,
# emulates a program and answers its system calls itself: it has no
# `clone3`, creates no process in a new namespace and has no `seccomp`,
# no `ptrace`, no Landlock and no call that lists mounts.
# Here the test programs run on a real kernel, as root, with everything:
# this is the only place where the `clone3` path of `spawn` executes on
# riscv64 and riscv32 (on arm it also does on an aarch64 kernel, natively:
# scripts/privileged.sh), and where their registers are read from a
# tracee.
#
# What runs: a kernel built for the purpose, and an initial file system
# that holds nothing but static programs of this crate: tests/vm_init.rs as
# `/init`, which mounts what a system has and runs the tests of
# `process::linux` and `fs::linux` with OSCALL_REQUIRE_PRIVILEGED=1 (a
# test that would skip fails). There is no shell and no libc in it, which
# is why those tests run no program but themselves. The tests of io_uring
# (`io::linux`) run there too, with OSCALL_REQUIRE_IO_URING=1: qemu-user
# has no io_uring, so this is the only place where they execute on these
# architectures.
#
# It needs docker, for an image with the compiler of the kernel (clang) and
# qemu, built on first use, and the toolchains of the targets: stable with
# the musl targets for riscv64 and arm, and for riscv32 what
# scripts/riscv32.sh needs (a nightly toolchain with `rust-src`; it builds
# musl). The kernel is built once per architecture, in target/vm (about a
# minute on a few cores); the sources (150 MB) are downloaded from
# kernel.org and checked.
set -euo pipefail
cd "$(dirname "$0")/.."

export CARGO_TARGET_DIR="${OSCALL_TARGET_DIR:-$PWD/target}"
VM_DIR="$CARGO_TARGET_DIR/vm"
KERNEL_VERSION=6.18.52
KERNEL_SHA256=2b69564f7d4fea0c859b1959ba33709ee6e9139bd100e30a853b57159a8221b8
IMAGE=oscall-vm
# The tests that run no program but themselves.
TESTS=(process_linux process_linux_single process_linux_security
    process_linux_landlock process_linux_trace fs_linux mem_linux io_linux)
# How long a machine may take to boot and run them, in seconds.
TIMEOUT="${OSCALL_VM_TIMEOUT:-900}"

if ! command -v docker >/dev/null; then
    echo "docker not found" >&2
    exit 1
fi

archs=("$@")
[ ${#archs[@]} -gt 0 ] || archs=(riscv64 riscv32 arm)

# What the kernel needs to boot in qemu's `virt` machine and to have what
# the tests are about, on top of the smallest configuration it has
# (`tinyconfig`).
kernel_config() {
    cat <<'EOF'
CONFIG_PRINTK=y
CONFIG_BUG=y
CONFIG_SMP=y
CONFIG_MULTIUSER=y
CONFIG_BINFMT_ELF=y
CONFIG_BLK_DEV_INITRD=y
CONFIG_RD_GZIP=y
CONFIG_KERNEL_GZIP=y
CONFIG_TTY=y
CONFIG_UNIX98_PTYS=y
CONFIG_PROC_FS=y
CONFIG_PROC_SYSCTL=y
CONFIG_SYSFS=y
CONFIG_TMPFS=y
CONFIG_TMPFS_XATTR=y
CONFIG_SHMEM=y
CONFIG_DEVTMPFS=y
CONFIG_FUTEX=y
CONFIG_EPOLL=y
CONFIG_SIGNALFD=y
CONFIG_TIMERFD=y
CONFIG_EVENTFD=y
CONFIG_POSIX_TIMERS=y
CONFIG_ADVISE_SYSCALLS=y
CONFIG_FILE_LOCKING=y
CONFIG_HIGH_RES_TIMERS=y
CONFIG_NAMESPACES=y
CONFIG_UTS_NS=y
CONFIG_IPC_NS=y
CONFIG_USER_NS=y
CONFIG_PID_NS=y
CONFIG_NET_NS=y
CONFIG_SYSVIPC=y
CONFIG_NET=y
CONFIG_UNIX=y
CONFIG_INET=y
CONFIG_CGROUPS=y
CONFIG_CGROUP_PIDS=y
CONFIG_MEMCG=y
CONFIG_SECCOMP=y
CONFIG_SECCOMP_FILTER=y
CONFIG_SECURITY=y
CONFIG_SECURITY_LANDLOCK=y
CONFIG_CROSS_MEMORY_ATTACH=y
CONFIG_IO_URING=y
EOF
    case "$1" in
        riscv*)
            cat <<'EOF'
CONFIG_ARCH_VIRT=y
CONFIG_MMU=y
CONFIG_FPU=y
CONFIG_RISCV_ISA_C=y
CONFIG_RISCV_SBI=y
CONFIG_SERIAL_8250=y
CONFIG_SERIAL_8250_CONSOLE=y
CONFIG_SERIAL_OF_PLATFORM=y
EOF
            ;;
    esac
    case "$1" in
        riscv64)
            # Time namespaces need a vDSO with clocks, which the 32-bit
            # kernels of these architectures do not have.
            echo CONFIG_64BIT=y
            echo CONFIG_ARCH_RV64I=y
            echo CONFIG_TIME_NS=y
            ;;
        riscv32)
            # What arch/riscv/configs/32-bit.config says.
            cat <<'EOF'
CONFIG_ARCH_RV32I=y
CONFIG_32BIT=y
# CONFIG_PORTABLE is not set
CONFIG_NONPORTABLE=y
EOF
            ;;
        arm)
            cat <<'EOF'
CONFIG_MMU=y
CONFIG_ARCH_MULTI_V7=y
CONFIG_ARM_PATCH_PHYS_VIRT=y
CONFIG_AUTO_ZRELADDR=y
CONFIG_COMPAT_32BIT_TIME=y
CONFIG_ARCH_VIRT=y
CONFIG_AEABI=y
CONFIG_VFP=y
CONFIG_NEON=y
CONFIG_ARM_THUMB=y
CONFIG_KUSER_HELPERS=y
CONFIG_ARM_PSCI=y
CONFIG_SERIAL_AMBA_PL011=y
CONFIG_SERIAL_AMBA_PL011_CONSOLE=y
EOF
            ;;
    esac
}

# The name the kernel sources give the architecture $1, the kernel image
# they build, qemu's name, its machine, and the console.
kernel_arch() {
    case "$1" in
        riscv64 | riscv32) echo riscv ;;
        arm) echo arm ;;
    esac
}
kernel_image() {
    case "$1" in
        riscv64 | riscv32) echo arch/riscv/boot/Image ;;
        arm) echo arch/arm/boot/zImage ;;
    esac
}
qemu_command() {
    case "$1" in
        riscv64) echo "qemu-system-riscv64 -M virt -cpu rv64" ;;
        riscv32) echo "qemu-system-riscv32 -M virt -cpu rv32" ;;
        arm) echo "qemu-system-arm -M virt -cpu cortex-a15" ;;
    esac
}
console() {
    case "$1" in
        riscv64 | riscv32) echo ttyS0 ;;
        arm) echo ttyAMA0 ;;
    esac
}
rust_target() {
    case "$1" in
        riscv64) echo riscv64gc-unknown-linux-musl ;;
        riscv32) echo riscv32gc-unknown-linux-musl ;;
        arm) echo armv7-unknown-linux-musleabihf ;;
    esac
}

# Runs a command in the image, as the caller, with target/vm as /vm.
in_image() {
    docker run --rm --user "$(id -u):$(id -g)" -v "$VM_DIR":/vm -w /vm "$IMAGE" "$@"
}

for arch in "${archs[@]}"; do
    if [ -z "$(rust_target "$arch")" ]; then
        echo "unknown architecture $arch: riscv64, riscv32 or arm" >&2
        exit 1
    fi
done

mkdir -p "$VM_DIR"
echo "== image $IMAGE"
docker build -q -t "$IMAGE" - >/dev/null <<'EOF'
FROM debian:trixie-slim
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends \
        bc bison ca-certificates clang cpio flex gzip libc6-dev lld llvm make xz-utils \
        qemu-system-arm qemu-system-misc \
    && rm -rf /var/lib/apt/lists/*
EOF

# The kernel of the architecture $1: target/vm/kernel-$1, built again when
# its version or its configuration changes.
kernel() {
    local arch="$1" stamp
    stamp="$KERNEL_VERSION $(kernel_config "$arch" | sha256sum | cut -d' ' -f1)"
    if [ -f "$VM_DIR/kernel-$arch" ] && [ "$(cat "$VM_DIR/kernel-$arch.stamp" 2>/dev/null)" = "$stamp" ]; then
        return
    fi
    local sources="linux-$KERNEL_VERSION"
    if [ ! -f "$VM_DIR/$sources/Makefile" ]; then
        echo "== download linux $KERNEL_VERSION"
        local major="${KERNEL_VERSION%%.*}"
        curl -sSfL -o "$VM_DIR/$sources.tar.xz" \
            "https://cdn.kernel.org/pub/linux/kernel/v$major.x/$sources.tar.xz"
        echo "$KERNEL_SHA256  $VM_DIR/$sources.tar.xz" | sha256sum -c --quiet
        rm -rf "${VM_DIR:?}/$sources"
        in_image tar -xf "$sources.tar.xz"
        rm -f "$VM_DIR/$sources.tar.xz"
    fi
    echo "== build linux $KERNEL_VERSION for $arch"
    rm -rf "${VM_DIR:?}/build-$arch"
    mkdir -p "$VM_DIR/build-$arch"
    kernel_config "$arch" >"$VM_DIR/build-$arch/oscall.config"
    local make="make -s -C $sources O=/vm/build-$arch ARCH=$(kernel_arch "$arch") LLVM=1"
    make+=" KBUILD_BUILD_USER=oscall KBUILD_BUILD_HOST=vm"
    # The options are given to `tinyconfig` itself (KCONFIG_ALLCONFIG):
    # appended afterwards, those that depend on a choice it made would be
    # dropped. Then each one is checked to be there.
    in_image sh -ec "
        cat $sources/kernel/configs/tiny-base.config build-$arch/oscall.config >build-$arch/all.config
        $make KCONFIG_ALLCONFIG=/vm/build-$arch/all.config allnoconfig
        missing=0
        for option in \$(grep '^CONFIG_' build-$arch/oscall.config); do
            if ! grep -qx \"\$option\" build-$arch/.config; then
                echo \"the kernel configuration lacks \$option\" >&2
                missing=1
            fi
        done
        [ \$missing = 0 ]
        $make -j\$(nproc) $(basename "$(kernel_image "$arch")")
        cp build-$arch/$(kernel_image "$arch") kernel-$arch.tmp
    "
    mv "$VM_DIR/kernel-$arch.tmp" "$VM_DIR/kernel-$arch"
    echo "$stamp" >"$VM_DIR/kernel-$arch.stamp"
    rm -rf "${VM_DIR:?}/build-$arch"
}

# Builds the test programs for the architecture $1.
build_tests() {
    local arch="$1" target test_args=(--test vm_init)
    target="$(rust_target "$arch")"
    for test in "${TESTS[@]}"; do
        test_args+=(--test "$test")
    done
    echo "== build tests for $target"
    if [ "$arch" = riscv32 ]; then
        # No emulator is needed to build.
        OSCALL_QEMU_RISCV32="${OSCALL_QEMU_RISCV32:-true}" \
            scripts/riscv32.sh --all-features --no-run >/dev/null
    else
        local env_name
        env_name="$(tr 'a-z-' 'A-Z_' <<<"$target")"
        env "CARGO_TARGET_${env_name}_LINKER=rust-lld" \
            "CARGO_TARGET_${env_name}_RUSTFLAGS=-C target-feature=+crt-static -C link-self-contained=yes" \
            cargo test -q --no-run --all-features --target "$target" "${test_args[@]}"
    fi
}

# The newest program of the test $2 built for the target $1.
program() {
    find "$CARGO_TARGET_DIR/$1/debug" -type f -perm -u+x -name "$2-*" ! -name '*.*' \
        -printf '%T@ %p\n' | sort -n | tail -1 | cut -d' ' -f2-
}

status=0
for arch in "${archs[@]}"; do
    target="$(rust_target "$arch")"
    kernel "$arch"
    build_tests "$arch"

    root="$VM_DIR/root-$arch"
    rm -rf "$root"
    mkdir -p "$root/tests"
    cp "$(program "$target" vm_init)" "$root/init"
    for test in "${TESTS[@]}"; do
        cp "$(program "$target" "$test")" "$root/tests/$test"
    done
    (cd "$root" && find . | cpio -o -H newc --quiet | gzip -1) >"$VM_DIR/initramfs-$arch.gz"
    rm -rf "$root"

    echo "== test vm $arch (linux $KERNEL_VERSION)"
    log="$VM_DIR/console-$arch.log"
    # The machine switches itself off when the tests are done, which ends
    # qemu; `panic=-1` makes a kernel that panics reboot, which ends it
    # too (-no-reboot).
    # shellcheck disable=SC2046
    in_image timeout "$TIMEOUT" $(qemu_command "$arch") -m 1024 -smp 2 \
        -nographic -no-reboot -nic none -kernel "kernel-$arch" -initrd "initramfs-$arch.gz" \
        -append "console=$(console "$arch") rdinit=/init panic=-1 quiet OSCALL_VM_INIT=1" \
        </dev/null 2>&1 | tr -d '\r' | tee "$log" || true
    if ! grep -q '^== oscall-vm: passed$' "$log"; then
        echo "== vm $arch failed" >&2
        status=1
    fi
done
[ "$status" -eq 0 ] || exit 1
echo "== ok"
