From 2f31d7bc1dee74c8211d38f55a71845b14d16251 Mon Sep 17 00:00:00 2001 From: marcobuschini Date: Fri, 4 Dec 2026 09:49:59 +0000 Subject: [PATCH 1/4] test(syscalls): add host unit tests for FileSyscalls and SyscallHelpers (#258) - Add host-only snitch unit tests in `tests/host/file_syscalls_test.cpp` and `tests/host/syscall_helpers_test.cpp` and register them in `Makefile` - Update `sys_chdir()` in `kernel/syscalls/FileSyscalls.cpp` to use `normalize_vfs_path()` when possible instead of `build_dentry_path()` --- Makefile | 2 + kernel/syscalls/FileSyscalls.cpp | 7 +- tests/host/file_syscalls_test.cpp | 406 ++++++++++++++++++++++++++++ tests/host/syscall_helpers_test.cpp | 236 ++++++++++++++++ 4 files changed, 650 insertions(+), 1 deletion(-) create mode 100644 tests/host/file_syscalls_test.cpp create mode 100644 tests/host/syscall_helpers_test.cpp diff --git a/Makefile b/Makefile index 068e83e..b7d6189 100644 --- a/Makefile +++ b/Makefile @@ -73,6 +73,8 @@ HOST_ONLY_TEST_SRCS := \ tests/host/distro_abi_test.cpp \ tests/host/ddk_dummy_test.cpp \ tests/host/ddk_kernel_services_test.cpp \ + tests/host/file_syscalls_test.cpp \ + tests/host/syscall_helpers_test.cpp \ drivers/dummy/DummyDriver.cpp \ tests/host/socket_syscall_test.cpp \ tests/host/gicv2_test.cpp \ diff --git a/kernel/syscalls/FileSyscalls.cpp b/kernel/syscalls/FileSyscalls.cpp index c6026b5..6684537 100644 --- a/kernel/syscalls/FileSyscalls.cpp +++ b/kernel/syscalls/FileSyscalls.cpp @@ -66,7 +66,12 @@ int64_t sys_chdir(uintptr_t user_path) noexcept { return ERR_ENOTDIR; } - build_dentry_path(target, proc->mutable_cwd(), Kernel::Process::MAX_PATH_LEN); + char normalized[Kernel::Process::MAX_PATH_LEN]{}; + if (normalize_vfs_path(proc->cwd(), raw_path, normalized, sizeof(normalized))) { + cstr_copy(proc->mutable_cwd(), normalized, Kernel::Process::MAX_PATH_LEN); + } else { + build_dentry_path(target, proc->mutable_cwd(), Kernel::Process::MAX_PATH_LEN); + } target->release(); return 0; } diff --git a/tests/host/file_syscalls_test.cpp b/tests/host/file_syscalls_test.cpp new file mode 100644 index 0000000..b5ceff5 --- /dev/null +++ b/tests/host/file_syscalls_test.cpp @@ -0,0 +1,406 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#include "fs/Vfs.hpp" +#include "fs/devfs/devfs.hpp" +#include "fs/rootfs/rootfs.hpp" +#include "fs/tmpfs/tmpfs.hpp" +#include "mm/AddressSpace.hpp" +#include "mm/heap.hpp" +#include "mm/pfa.hpp" +#include "mocks/host_hal.hpp" +#include "process/Process.hpp" +#include "syscalls/SyscallInternal.hpp" +#include "uapi/errno.hpp" +#include "uapi/fs.hpp" +#include "uapi/sys.hpp" + +#include +#include +#include +#include + +namespace { + +using namespace Kernel::FS; +using namespace Kernel::Syscalls; +using namespace Kernel::UAPI; + +constexpr uintptr_t kUserPageBase = 0x00400000ULL; +constexpr uintptr_t kStrArea = kUserPageBase + 0x000U; +constexpr uintptr_t kStrArea2 = kUserPageBase + 0x200U; +constexpr uintptr_t kDataArea = kUserPageBase + 0x400U; +constexpr uintptr_t kStructArea = kUserPageBase + 0x800U; +constexpr uintptr_t kBadUserAddr = kUserPageBase + 0x4000U; + +void init_file_syscalls_env() noexcept { + HostTest::reset_host_hal(); + HAL::get_mmu().activate(); + + Kernel::Boot::MemoryMap mem_map{}; + mem_map.regions[0] = Kernel::Boot::MemoryRegion{ + .base_paddr = HostTest::SIM_RAM_BASE, + .size = HostTest::SIM_RAM_SIZE, + }; + mem_map.count = 1U; + mem_map.min_paddr = HostTest::SIM_RAM_BASE; + mem_map.max_paddr = HostTest::SIM_RAM_BASE + HostTest::SIM_RAM_SIZE; + mem_map.total_usable_bytes = HostTest::SIM_RAM_SIZE; + + Kernel::MM::pfa_init(mem_map, HostTest::SIM_RAM_BASE, + HostTest::SIM_RAM_BASE + HostTest::SIM_PAGE_SIZE, 0U, 0U, 0U, 0U, nullptr); + Kernel::MM::heap_init(); + + vfs_reset(); + rootfs_reset(); + devfs_reset(); + tmpfs_reset(); + REQUIRE(rootfs_mount_cpio(nullptr, 0U) == kOk); + REQUIRE(devfs_init_and_mount() == kOk); + REQUIRE(tmpfs_init_and_mount() == kOk); +} + +struct ScopedFileProcess final { + Kernel::Process::Process* proc{nullptr}; + Kernel::Process::Process* prev{nullptr}; + uintptr_t page_paddr{0U}; + + ScopedFileProcess() noexcept + : proc(Kernel::Process::Process::create(0U)), prev(Kernel::Process::Process::current()) { + REQUIRE(proc != nullptr); + auto as_res = Kernel::MM::AddressSpace::create(); + REQUIRE(as_res.is_ok()); + proc->address_space() = static_cast(as_res.value()); + page_paddr = Kernel::MM::alloc_frame(); + REQUIRE(page_paddr != 0U); + REQUIRE(proc->address_space().map_user_page(kUserPageBase, page_paddr, + HAL::PageFlags::User | HAL::PageFlags::Read | + HAL::PageFlags::Write)); + Kernel::Process::Process::set_current(proc); + } + + ~ScopedFileProcess() noexcept { + Kernel::Process::Process::set_current(prev); + if (proc != nullptr) { + proc->address_space().unmap_user_page(kUserPageBase); + proc->address_space().destroy(); + Kernel::Process::Process::destroy(*proc); + } + if (page_paddr != 0U) { + Kernel::MM::free_frame(page_paddr); + } + } + + ScopedFileProcess(const ScopedFileProcess&) = delete; + ScopedFileProcess& operator=(const ScopedFileProcess&) = delete; + ScopedFileProcess(ScopedFileProcess&&) = delete; + ScopedFileProcess& operator=(ScopedFileProcess&&) = delete; + + [[nodiscard]] uintptr_t root() const noexcept { return proc->address_space().root_paddr(); } + + void write_str(uintptr_t va, const char* s) const noexcept { + REQUIRE(Kernel::MM::copy_to_user(root(), va, s, std::strlen(s) + 1U) == 0); + } +}; + +} // namespace + +TEST_CASE("FileSyscalls directory, path, openat, rename, getdents64, and unlinkat paths", + "[syscalls][file]") { + init_file_syscalls_env(); + ScopedFileProcess ctx; + + // getcwd + CHECK(sys_getcwd(kBadUserAddr, 64U) == ERR_EFAULT); + CHECK(sys_getcwd(kDataArea, 1U) == ERR_ERANGE); + REQUIRE(sys_getcwd(kDataArea, 64U) > 0); + char cwd[64]{}; + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), cwd, kDataArea, sizeof(cwd)) == 0); + CHECK(std::strcmp(cwd, "/") == 0); + + // mkdirat & chdir + ctx.write_str(kStrArea, "/tmp/dir1"); + CHECK(sys_mkdirat(AT_FDCWD, kBadUserAddr, 0755U) == ERR_EFAULT); + REQUIRE(sys_mkdirat(AT_FDCWD, kStrArea, 0755U) == 0); + CHECK(sys_mkdirat(AT_FDCWD, kStrArea, 0755U) == ERR_EEXIST); + + ctx.write_str(kStrArea2, "/tmp/missing"); + CHECK(sys_chdir(kStrArea2) == ERR_ENOENT); + CHECK(sys_chdir(kBadUserAddr) == ERR_EFAULT); + REQUIRE(sys_chdir(kStrArea) == 0); + + REQUIRE(sys_getcwd(kDataArea, 64U) > 0); + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), cwd, kDataArea, sizeof(cwd)) == 0); + CHECK(std::strcmp(cwd, "/tmp/dir1") == 0); + + // openat: relative to cwd, O_CREAT|O_EXCL, O_DIRECTORY error, EROFS on rootfs + ctx.write_str(kStrArea, "alpha.txt"); + const int64_t fd = sys_openat(AT_FDCWD, kStrArea, O_CREAT | O_RDWR, 0644U); + REQUIRE(fd >= 0); + CHECK(sys_openat(AT_FDCWD, kStrArea, O_CREAT | O_EXCL | O_RDWR, 0644U) == ERR_EEXIST); + CHECK(sys_openat(AT_FDCWD, kStrArea, O_RDONLY | O_DIRECTORY, 0U) == ERR_ENOTDIR); + CHECK(sys_openat(99, kStrArea, O_RDONLY, 0U) == ERR_EBADF); + CHECK(sys_openat(AT_FDCWD, kBadUserAddr, O_RDONLY, 0U) == ERR_EFAULT); + ctx.write_str(kStrArea2, "/ro_file"); + CHECK(sys_openat(AT_FDCWD, kStrArea2, O_CREAT | O_WRONLY, 0644U) == ERR_EROFS); + REQUIRE(sys_close(static_cast(fd)) == 0); + + // chdir back to "/" and test chdir on regular file + ctx.write_str(kStrArea2, "/tmp/dir1/alpha.txt"); + CHECK(sys_chdir(kStrArea2) == ERR_ENOTDIR); + ctx.write_str(kStrArea2, "/"); + REQUIRE(sys_chdir(kStrArea2) == 0); + + // renameat / renameat2 + ctx.write_str(kStrArea, "/tmp/dir1/alpha.txt"); + ctx.write_str(kStrArea2, "/tmp/dir1/beta.txt"); + CHECK(sys_renameat2(AT_FDCWD, kStrArea, AT_FDCWD, kStrArea2, 0xFFFFU) == ERR_EINVAL); + REQUIRE(sys_renameat(AT_FDCWD, kStrArea, AT_FDCWD, kStrArea2) == 0); + + // getdents64 on /tmp/dir1 + ctx.write_str(kStrArea, "/tmp/dir1"); + const int64_t dfd = sys_openat(AT_FDCWD, kStrArea, O_RDONLY | O_DIRECTORY, 0U); + REQUIRE(dfd >= 0); + CHECK(sys_getdents64(99U, kDataArea, 256U) == ERR_EBADF); + CHECK(sys_getdents64(static_cast(dfd), kDataArea, 8U) == 0); + CHECK(sys_getdents64(static_cast(dfd), kBadUserAddr, 256U) == ERR_EFAULT); + const int64_t dent_bytes = sys_getdents64(static_cast(dfd), kDataArea, 256U); + CHECK(dent_bytes > 0); + REQUIRE(sys_close(static_cast(dfd)) == 0); + + // unlinkat file and directory + ctx.write_str(kStrArea, "/tmp/dir1"); + CHECK(sys_unlinkat(AT_FDCWD, kStrArea, 0U) == ERR_EISDIR); + ctx.write_str(kStrArea2, "/tmp/dir1/beta.txt"); + REQUIRE(sys_unlinkat(AT_FDCWD, kStrArea2, 0U) == 0); + REQUIRE(sys_unlinkat(AT_FDCWD, kStrArea, AT_REMOVEDIR) == 0); +} + +TEST_CASE("FileSyscalls read, write, writev, lseek, truncate, stat, chmod, chown, and access", + "[syscalls][file]") { + init_file_syscalls_env(); + ScopedFileProcess ctx; + + ctx.write_str(kStrArea, "/tmp/io_test.bin"); + const int64_t fd = sys_openat(AT_FDCWD, kStrArea, O_CREAT | O_RDWR, 0644U); + REQUIRE(fd >= 0); + const auto ufd = static_cast(fd); + + // write & writev + const char part1[] = "hello "; + const char part2[] = "milo"; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kDataArea, part1, 6U) == 0); + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kDataArea + 16U, part2, 4U) == 0); + const linux_iovec iov[2] = { + {.iov_base = kDataArea, .iov_len = 6U}, + {.iov_base = kDataArea + 16U, .iov_len = 4U}, + }; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructArea, iov, sizeof(iov)) == 0); + CHECK(sys_writev(ufd, kStructArea, 0U) == 0); + CHECK(sys_writev(99U, kStructArea, 2U) == ERR_EBADF); + CHECK(sys_writev(ufd, kBadUserAddr, 2U) == ERR_EFAULT); + REQUIRE(sys_writev(ufd, kStructArea, 2U) == 10); + + // lseek & read + CHECK(sys_lseek(99U, 0, SEEK_SET) == ERR_EBADF); + CHECK(sys_lseek(ufd, 0, 99U) == ERR_EINVAL); + CHECK(sys_lseek(ufd, 0, SEEK_END) == 10); + CHECK(sys_lseek(ufd, -4, SEEK_CUR) == 6); + CHECK(sys_lseek(ufd, 0, SEEK_SET) == 0); + + CHECK(sys_read(99U, kDataArea + 64U, 10U) == ERR_EBADF); + CHECK(sys_read(ufd, kBadUserAddr, 10U) == ERR_EFAULT); + REQUIRE(sys_read(ufd, kDataArea + 64U, 10U) == 10); + char readback[16]{}; + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), readback, kDataArea + 64U, 10U) == 0); + CHECK(std::memcmp(readback, "hello milo", 10U) == 0); + + // ftruncate & truncate + CHECK(sys_ftruncate(ufd, -1) == ERR_EINVAL); + CHECK(sys_ftruncate(99U, 4) == ERR_EBADF); + REQUIRE(sys_ftruncate(ufd, 5) == 0); + CHECK(sys_truncate(kStrArea, -1) == ERR_EINVAL); + REQUIRE(sys_truncate(kStrArea, 3) == 0); + + // fstat & newfstatat + CHECK(sys_fstat(99U, kStructArea) == ERR_EBADF); + CHECK(sys_fstat(ufd, kBadUserAddr) == ERR_EFAULT); + REQUIRE(sys_fstat(ufd, kStructArea) == 0); + linux_stat st{}; + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), &st, kStructArea, sizeof(st)) == 0); + CHECK(st.st_size == 3); + + REQUIRE(sys_newfstatat(AT_FDCWD, kStrArea, kStructArea, 0U) == 0); + ctx.write_str(kStrArea2, "/tmp/missing_stat"); + CHECK(sys_newfstatat(AT_FDCWD, kStrArea2, kStructArea, 0U) == ERR_ENOENT); + + // fsync, fchmod, fchmodat, fchown, fchownat, utimensat, faccessat, readlinkat + CHECK(sys_fsync(ufd, 0) == 0); + CHECK(sys_fsync(99U, 1) == ERR_EBADF); + CHECK(sys_fchmod(ufd, 0600U) == 0); + CHECK(sys_fchmod(99U, 0600U) == ERR_EBADF); + CHECK(sys_fchmodat(AT_FDCWD, kStrArea, 0644U, 0U) == 0); + CHECK(sys_fchown(ufd, 1000U, 1000U) == 0); + CHECK(sys_fchownat(AT_FDCWD, kStrArea, 0U, 0U, 0U) == 0); + CHECK(sys_utimensat(AT_FDCWD, kStrArea, 0U, 0U) == 0); + CHECK(sys_faccessat(AT_FDCWD, kStrArea, 0U, 0U) == 0); + CHECK(sys_faccessat2(AT_FDCWD, kStrArea, 0U, 0U) == 0); + CHECK(sys_readlinkat(AT_FDCWD, kStrArea, kDataArea, 32U) == ERR_EINVAL); + + REQUIRE(sys_close(ufd) == 0); + CHECK(sys_close(ufd) == ERR_EBADF); +} + +TEST_CASE("FileSyscalls pipe2, dup, dup3, fcntl, ioctl, ppoll, and pselect6", + "[syscalls][file][ipc]") { + init_file_syscalls_env(); + ScopedFileProcess ctx; + + // pipe2 + CHECK(sys_pipe2(kBadUserAddr, 0U) == ERR_EFAULT); + CHECK(sys_pipe2(kStructArea, 0x1234U) == ERR_EINVAL); + REQUIRE(sys_pipe2(kStructArea, O_CLOEXEC | O_NONBLOCK) == 0); + + int32_t fds[2]{-1, -1}; + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), fds, kStructArea, sizeof(fds)) == 0); + REQUIRE(fds[0] >= 0); + REQUIRE(fds[1] >= 0); + + // dup & dup3 + CHECK(sys_dup(99U) == ERR_EBADF); + const int64_t dup_fd = sys_dup(static_cast(fds[0])); + REQUIRE(dup_fd >= 0); + CHECK(sys_dup3(static_cast(fds[0]), static_cast(fds[0]), 0U) == ERR_EINVAL); + CHECK(sys_dup3(static_cast(fds[0]), 12U, 0x1234U) == ERR_EINVAL); + REQUIRE(sys_dup3(static_cast(fds[0]), 12U, O_CLOEXEC) == 12); + REQUIRE(sys_close(12U) == 0); + REQUIRE(sys_close(static_cast(dup_fd)) == 0); + + // fcntl + CHECK(sys_fcntl(99U, F_GETFD, 0U) == ERR_EBADF); + CHECK(sys_fcntl(static_cast(fds[0]), F_GETFD, 0U) == 1); + REQUIRE(sys_fcntl(static_cast(fds[0]), F_SETFD, 0U) == 0); + CHECK(sys_fcntl(static_cast(fds[0]), F_GETFD, 0U) == 0); + CHECK(sys_fcntl(static_cast(fds[0]), 9999U, 0U) == ERR_EINVAL); + const int64_t fcntl_dup = sys_fcntl(static_cast(fds[0]), F_DUPFD_CLOEXEC, 15U); + REQUIRE(fcntl_dup == 15); + REQUIRE(sys_close(static_cast(fcntl_dup)) == 0); + + // write to pipe and poll/pselect6 + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kDataArea, "ping", 4U) == 0); + REQUIRE(sys_write(static_cast(fds[1]), kDataArea, 4U) == 4); + + linux_pollfd pfd{.fd = fds[0], .events = 0x0001 /*POLLIN*/, .revents = 0}; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructArea, &pfd, sizeof(pfd)) == 0); + const uint64_t zero_ts[2] = {0ULL, 0ULL}; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructArea + 64U, zero_ts, sizeof(zero_ts)) == 0); + CHECK(sys_ppoll(kBadUserAddr, 1U, 0U, 0U, 0U) == ERR_EFAULT); + REQUIRE(sys_ppoll(kStructArea, 1U, kStructArea + 64U, 0U, 0U) == 1); + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), &pfd, kStructArea, sizeof(pfd)) == 0); + CHECK((static_cast(pfd.revents) & 0x0001U) != 0U); + + uint64_t rfds = (1ULL << static_cast(fds[0])); + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructArea + 128U, &rfds, sizeof(rfds)) == 0); + CHECK(sys_pselect6(-1, 0U, 0U, 0U, 0U, 0U) == ERR_EINVAL); + REQUIRE(sys_pselect6(fds[0] + 1, kStructArea + 128U, 0U, 0U, kStructArea + 64U, 0U) == 1); + + // ioctl on /dev/null -> ERR_ENOTTY + ctx.write_str(kStrArea, "/dev/null"); + const int64_t null_fd = sys_openat(AT_FDCWD, kStrArea, O_RDWR, 0U); + REQUIRE(null_fd >= 0); + CHECK(sys_ioctl(static_cast(null_fd), 0x5401ULL, 0U) == ERR_ENOTTY); + CHECK(sys_ioctl(99U, 0x5401ULL, 0U) == ERR_EBADF); + REQUIRE(sys_close(static_cast(null_fd)) == 0); + + REQUIRE(sys_close(static_cast(fds[0])) == 0); + REQUIRE(sys_close(static_cast(fds[1])) == 0); +} + +TEST_CASE("FileSyscalls extended fcntl, stat, utimensat, access, renameat2, ioctl, and poll " + "branches", + "[syscalls][file]") { + init_file_syscalls_env(); + ScopedFileProcess ctx; + + // Create two files in /tmp to exercise renameat2 RENAME_NOREPLACE & utimensat + ctx.write_str(kStrArea, "/tmp/src_a"); + ctx.write_str(kStrArea2, "/tmp/dst_b"); + const int64_t fa = sys_openat(AT_FDCWD, kStrArea, O_CREAT | O_RDWR, 0644U); + const int64_t fb = sys_openat(AT_FDCWD, kStrArea2, O_CREAT | O_RDWR, 0644U); + REQUIRE(fa >= 0); + REQUIRE(fb >= 0); + + // RENAME_NOREPLACE fails with EEXIST when dst exists; relative path w/ bad dirfd -> EBADF + CHECK(sys_renameat2(AT_FDCWD, kStrArea, AT_FDCWD, kStrArea2, 1U /*RENAME_NOREPLACE*/) == + ERR_EEXIST); + ctx.write_str(kDataArea + 128U, "rel_src"); + CHECK(sys_renameat2(99, kDataArea + 128U, AT_FDCWD, kStrArea2, 0U) == ERR_EBADF); + + // fcntl F_DUPFD, F_GETFL, F_SETFL + const int64_t dup_min = sys_fcntl(static_cast(fa), F_DUPFD, 10U); + REQUIRE(dup_min == 10); + CHECK(sys_fcntl(10U, F_GETFL, 0U) >= 0); + CHECK(sys_fcntl(10U, F_SETFL, O_NONBLOCK) == 0); + CHECK(sys_close(10U) == 0); + + // newfstatat with AT_EMPTY_PATH (0x1000) and empty string + ctx.write_str(kDataArea, ""); + CHECK(sys_newfstatat(static_cast(fa), kDataArea, kStructArea, 0x1000U) == 0); + CHECK(sys_newfstatat(99, kDataArea, kStructArea, 0x1000U) == ERR_EBADF); + + // utimensat with explicit timespec[2] and invalid nsec + const uint64_t valid_times[4] = {100ULL, 500ULL, 200ULL, 600ULL}; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructArea, valid_times, sizeof(valid_times)) == + 0); + CHECK(sys_utimensat(AT_FDCWD, kStrArea, kStructArea, 0U) == 0); + CHECK(sys_utimensat(AT_FDCWD, kStrArea, kBadUserAddr, 0U) == ERR_EFAULT); + + const uint64_t bad_times[4] = {100ULL, 2000000000ULL, 200ULL, 0ULL}; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructArea, bad_times, sizeof(bad_times)) == 0); + CHECK(sys_utimensat(AT_FDCWD, kStrArea, kStructArea, 0U) == ERR_EINVAL); + + // faccessat2 R/W/X checks and missing file + CHECK(sys_faccessat2(AT_FDCWD, kStrArea, 4U | 2U /*R_OK|W_OK*/, 0U) == 0); + CHECK(sys_faccessat2(AT_FDCWD, kStrArea, 1U /*X_OK*/, 0U) == ERR_EACCES); + CHECK(sys_faccessat2(AT_FDCWD, kBadUserAddr, 0U, 0U) == ERR_EFAULT); + + // write/read 0 bytes and read-only / write-only checks + CHECK(sys_write(static_cast(fa), kDataArea, 0U) == 0); + CHECK(sys_read(static_cast(fa), kDataArea, 0U) == 0); + + // /dev/console ioctl TCGETS & TIOCGWINSZ + ctx.write_str(kStrArea, "/dev/console"); + const int64_t con_fd = sys_openat(AT_FDCWD, kStrArea, O_RDWR, 0U); + REQUIRE(con_fd >= 0); + CHECK(sys_ioctl(static_cast(con_fd), 0x5401ULL /*TCGETS*/, kStructArea) == 0); + CHECK(sys_ioctl(static_cast(con_fd), 0x5413ULL /*TIOCGWINSZ*/, kStructArea) == 0); + CHECK(sys_ioctl(static_cast(con_fd), 0x5401ULL, kBadUserAddr) == ERR_EFAULT); + REQUIRE(sys_close(static_cast(con_fd)) == 0); + + // pipe nonblocking EAGAIN, ppoll POLLOUT + POLLNVAL, pselect6 wfds/efds + REQUIRE(sys_pipe2(kStructArea, O_NONBLOCK) == 0); + int32_t pfds[2]{-1, -1}; + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), pfds, kStructArea, sizeof(pfds)) == 0); + CHECK(sys_read(static_cast(pfds[0]), kDataArea, 8U) == ERR_EAGAIN); + + const linux_pollfd poll_arr[2] = { + {.fd = pfds[1], .events = 0x0004 /*POLLOUT*/, .revents = 0}, + {.fd = 99, .events = 0x0001, .revents = 0}, + }; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructArea, poll_arr, sizeof(poll_arr)) == 0); + const uint64_t zero_ts[2] = {0ULL, 0ULL}; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructArea + 64U, zero_ts, sizeof(zero_ts)) == 0); + CHECK(sys_ppoll(kStructArea, 2U, kStructArea + 64U, 0U, 0U) == 2); + + uint64_t wfds = (1ULL << static_cast(pfds[1])); + uint64_t efds = 0ULL; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructArea + 128U, &wfds, sizeof(wfds)) == 0); + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructArea + 136U, &efds, sizeof(efds)) == 0); + CHECK(sys_pselect6(pfds[1] + 1, 0U, kStructArea + 128U, kStructArea + 136U, kStructArea + 64U, + 0U) == 1); + + REQUIRE(sys_close(static_cast(pfds[0])) == 0); + REQUIRE(sys_close(static_cast(pfds[1])) == 0); + REQUIRE(sys_close(static_cast(fa)) == 0); + REQUIRE(sys_close(static_cast(fb)) == 0); +} diff --git a/tests/host/syscall_helpers_test.cpp b/tests/host/syscall_helpers_test.cpp new file mode 100644 index 0000000..86ebaf2 --- /dev/null +++ b/tests/host/syscall_helpers_test.cpp @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#include "fs/Vfs.hpp" +#include "fs/devfs/devfs.hpp" +#include "fs/rootfs/rootfs.hpp" +#include "fs/tmpfs/tmpfs.hpp" +#include "mm/AddressSpace.hpp" +#include "mm/heap.hpp" +#include "mm/pfa.hpp" +#include "mocks/host_hal.hpp" +#include "process/Process.hpp" +#include "syscalls/SyscallInternal.hpp" +#include "uapi/errno.hpp" +#include "uapi/fs.hpp" + +#include +#include +#include +#include + +namespace { + +using namespace Kernel::FS; +using namespace Kernel::Syscalls; +using namespace Kernel::UAPI; + +constexpr uintptr_t kUserPageBase = 0x00400000ULL; + +void init_helpers_env() noexcept { + HostTest::reset_host_hal(); + HAL::get_mmu().activate(); + + Kernel::Boot::MemoryMap mem_map{}; + mem_map.regions[0] = Kernel::Boot::MemoryRegion{ + .base_paddr = HostTest::SIM_RAM_BASE, + .size = HostTest::SIM_RAM_SIZE, + }; + mem_map.count = 1U; + mem_map.min_paddr = HostTest::SIM_RAM_BASE; + mem_map.max_paddr = HostTest::SIM_RAM_BASE + HostTest::SIM_RAM_SIZE; + mem_map.total_usable_bytes = HostTest::SIM_RAM_SIZE; + + Kernel::MM::pfa_init(mem_map, HostTest::SIM_RAM_BASE, + HostTest::SIM_RAM_BASE + HostTest::SIM_PAGE_SIZE, 0U, 0U, 0U, 0U, nullptr); + Kernel::MM::heap_init(); + + vfs_reset(); + rootfs_reset(); + devfs_reset(); + tmpfs_reset(); + REQUIRE(rootfs_mount_cpio(nullptr, 0U) == kOk); + REQUIRE(devfs_init_and_mount() == kOk); + REQUIRE(tmpfs_init_and_mount() == kOk); +} + +struct ScopedHelperProcess final { + Kernel::Process::Process* proc{nullptr}; + Kernel::Process::Process* prev{nullptr}; + uintptr_t page_paddr{0U}; + + ScopedHelperProcess() noexcept + : proc(Kernel::Process::Process::create(0U)), prev(Kernel::Process::Process::current()) { + REQUIRE(proc != nullptr); + auto as_res = Kernel::MM::AddressSpace::create(); + REQUIRE(as_res.is_ok()); + proc->address_space() = static_cast(as_res.value()); + page_paddr = Kernel::MM::alloc_frame(); + REQUIRE(page_paddr != 0U); + REQUIRE(proc->address_space().map_user_page(kUserPageBase, page_paddr, + HAL::PageFlags::User | HAL::PageFlags::Read | + HAL::PageFlags::Write)); + Kernel::Process::Process::set_current(proc); + } + + ~ScopedHelperProcess() noexcept { + Kernel::Process::Process::set_current(prev); + if (proc != nullptr) { + proc->address_space().unmap_user_page(kUserPageBase); + proc->address_space().destroy(); + Kernel::Process::Process::destroy(*proc); + } + if (page_paddr != 0U) { + Kernel::MM::free_frame(page_paddr); + } + } + + ScopedHelperProcess(const ScopedHelperProcess&) = delete; + ScopedHelperProcess& operator=(const ScopedHelperProcess&) = delete; + ScopedHelperProcess(ScopedHelperProcess&&) = delete; + ScopedHelperProcess& operator=(ScopedHelperProcess&&) = delete; +}; + +} // namespace + +TEST_CASE("SyscallHelpers string, path normalization, and monotonic time utilities", + "[syscalls][helpers]") { + init_helpers_env(); + + CHECK(cstr_len("hello") == 5U); + CHECK(cstr_eq("abc", "abc")); + CHECK_FALSE(cstr_eq("abc", "abd")); + + char buf[8]{}; + cstr_copy(nullptr, "ignored", 4U); + cstr_copy(buf, nullptr, sizeof(buf)); + CHECK(buf[0] == '\0'); + cstr_copy(buf, "truncated_text", sizeof(buf)); + CHECK(cstr_eq(buf, "truncat")); + + char path[64]{}; + CHECK_FALSE(normalize_vfs_path("/", nullptr, path, sizeof(path))); + CHECK_FALSE(normalize_vfs_path("/", "/a", nullptr, 4U)); + CHECK_FALSE(normalize_vfs_path("/", "/a", path, 1U)); + CHECK(normalize_vfs_path("/tmp/sub", "file.txt", path, sizeof(path))); + CHECK(cstr_eq(path, "/tmp/sub/file.txt")); + CHECK(normalize_vfs_path("/tmp/sub", ".././other/../../etc", path, sizeof(path))); + CHECK(cstr_eq(path, "/etc")); + CHECK(normalize_vfs_path("/tmp", "/", path, sizeof(path))); + CHECK(cstr_eq(path, "/")); + + CHECK(monotonic_now_ns() == monotonic_now().nanoseconds()); +} + +TEST_CASE("SyscallHelpers user range validation, cstring copy, and string array staging", + "[syscalls][helpers]") { + init_helpers_env(); + ScopedHelperProcess ctx; + const uintptr_t root = ctx.proc->address_space().root_paddr(); + + // Range validation edge cases + CHECK(validate_user_read_range(root, kUserPageBase, 0U)); + CHECK_FALSE(validate_user_read_range(root, Kernel::MM::user_addr_space_limit(), 1U)); + CHECK_FALSE(validate_user_read_range(0U, kUserPageBase, 16U)); + CHECK_FALSE(validate_user_read_range(root, Kernel::MM::user_addr_space_limit() - 4U, 8U)); + CHECK(validate_user_read_range(root, kUserPageBase, 64U)); + CHECK(validate_user_write_range(root, kUserPageBase, 64U)); + CHECK_FALSE(validate_user_read_range(root, kUserPageBase + 4096U, 8U)); + + // Demand-zero and CoW page validation + const uintptr_t dz_va = kUserPageBase + 0x2000U; + REQUIRE(ctx.proc->address_space().map_demand_zero(dz_va, + HAL::PageFlags::User | HAL::PageFlags::Read)); + CHECK(validate_user_read_range(root, dz_va, 16U)); + CHECK_FALSE(validate_user_write_range(root, dz_va, 16U)); + ctx.proc->address_space().unmap_user_page(dz_va); + + const uintptr_t cow_va = kUserPageBase + 0x4000U; + const uintptr_t cow_pa = Kernel::MM::alloc_frame(); + REQUIRE(cow_pa != 0U); + REQUIRE(HAL::AddressSpaceBackend::map_cow_user_page( + root, cow_va, cow_pa, HAL::PageFlags::User | HAL::PageFlags::Read)); + CHECK(validate_user_write_range(root, cow_va, 16U)); + ctx.proc->address_space().unmap_user_page(cow_va); + Kernel::MM::free_frame(cow_pa); + + // copy_user_cstring + char dst[16]{}; + size_t len = 0U; + CHECK(copy_user_cstring(root, 0U, dst, sizeof(dst), len) == ERR_EFAULT); + CHECK(copy_user_cstring(root, kUserPageBase + 4096U, dst, sizeof(dst), len) == ERR_EFAULT); + + const char msg[] = "milo-helper"; + REQUIRE(Kernel::MM::copy_to_user(root, kUserPageBase, msg, sizeof(msg)) == 0); + CHECK(copy_user_cstring(root, kUserPageBase, dst, 4U, len) == ERR_E2BIG); + CHECK(copy_user_cstring(root, kUserPageBase, dst, sizeof(dst), len) == 0); + CHECK(len == sizeof(msg) - 1U); + CHECK(cstr_eq(dst, "milo-helper")); + + // stage_user_string_array + const char* ptrs[4]{}; + char pool[64]{}; + size_t pool_off = 0U; + int count = -1; + CHECK(stage_user_string_array(root, 0U, ptrs, 3U, pool, sizeof(pool), pool_off, count) == 0); + CHECK(count == 0); + + const uintptr_t str1_va = kUserPageBase + 0x100U; + const uintptr_t str2_va = kUserPageBase + 0x120U; + REQUIRE(Kernel::MM::copy_to_user(root, str1_va, "arg0", 5U) == 0); + REQUIRE(Kernel::MM::copy_to_user(root, str2_va, "arg1", 5U) == 0); + + const uint64_t arr[3] = {str1_va, str2_va, 0ULL}; + const uintptr_t arr_va = kUserPageBase + 0x200U; + REQUIRE(Kernel::MM::copy_to_user(root, arr_va, arr, sizeof(arr)) == 0); + + pool_off = 0U; + CHECK(stage_user_string_array(root, arr_va, ptrs, 3U, pool, sizeof(pool), pool_off, count) == + 0); + CHECK(count == 2); + CHECK(cstr_eq(ptrs[0], "arg0")); + CHECK(cstr_eq(ptrs[1], "arg1")); + + pool_off = 0U; + CHECK(stage_user_string_array(root, arr_va, ptrs, 1U, pool, sizeof(pool), pool_off, count) == + ERR_E2BIG); + CHECK(stage_user_string_array(root, kUserPageBase + 4096U, ptrs, 3U, pool, sizeof(pool), + pool_off, count) == ERR_EFAULT); +} + +TEST_CASE("SyscallHelpers dirfd resolution and dentry path construction", "[syscalls][helpers]") { + init_helpers_env(); + ScopedHelperProcess ctx; + + Dentry* base = nullptr; + REQUIRE(resolve_dirfd_dentry(*ctx.proc, AT_FDCWD, base) == 0); + REQUIRE(base != nullptr); + char out_path[64]{}; + build_dentry_path(base, out_path, sizeof(out_path)); + CHECK(cstr_eq(out_path, "/")); + base->release(); + + CHECK(resolve_dirfd_dentry(*ctx.proc, 99, base) == ERR_EBADF); + + // Regular file FD -> ERR_ENOTDIR + REQUIRE(Kernel::MM::copy_to_user(ctx.proc->address_space().root_paddr(), kUserPageBase, + "/tmp/notadir", 13U) == 0); + const int64_t file_fd = sys_openat(AT_FDCWD, kUserPageBase, O_CREAT | O_RDWR, 0644U); + REQUIRE(file_fd >= 0); + CHECK(resolve_dirfd_dentry(*ctx.proc, static_cast(file_fd), base) == ERR_ENOTDIR); + CHECK(sys_close(static_cast(file_fd)) == 0); + + // Directory FD -> succeeds and build_dentry_path returns "/tmp/sub" + REQUIRE(vfs_mkdir("/tmp/sub", 0755U) == kOk); + REQUIRE(Kernel::MM::copy_to_user(ctx.proc->address_space().root_paddr(), kUserPageBase, + "/tmp/sub", 9U) == 0); + const int64_t dir_fd = sys_openat(AT_FDCWD, kUserPageBase, O_RDONLY | O_DIRECTORY, 0U); + REQUIRE(dir_fd >= 0); + REQUIRE(resolve_dirfd_dentry(*ctx.proc, static_cast(dir_fd), base) == 0); + REQUIRE(base != nullptr); + // build_dentry_path walks the mount's dentry parent chain ("/sub" inside tmpfs) + build_dentry_path(base, out_path, sizeof(out_path)); + CHECK(cstr_eq(out_path, "/sub")); + base->release(); + CHECK(sys_close(static_cast(dir_fd)) == 0); +} From baa21d802aa6c4b4943fd516c3eb059dd4920f85 Mon Sep 17 00:00:00 2001 From: marcobuschini Date: Fri, 4 Dec 2026 10:19:21 +0000 Subject: [PATCH 2/4] test(process): add host unit tests for Process, FdTable, Signal, Scheduler, and WaitQueue (#259) - Add host-only snitch unit tests in `tests/host/process_subsystem_test.cpp` and register them in `Makefile`, raising `kernel/process/*` coverage to 87% lines and 75% branches - Implement `HostCpuControl` register, SP, PC, PSTATE, and TLS accessors in `tests/host/mocks/host_hal.cpp` to test signal frame delivery and return - Fix `deliver_pending_signals()` in `kernel/process/Signal.cpp` to copy `SigAction` by value so `SA_RESETHAND` does not zero `act.handler` before setting user PC --- Makefile | 1 + kernel/process/Signal.cpp | 2 +- tests/host/mocks/host_hal.cpp | 34 +- tests/host/process_subsystem_test.cpp | 744 ++++++++++++++++++++++++++ 4 files changed, 758 insertions(+), 23 deletions(-) create mode 100644 tests/host/process_subsystem_test.cpp diff --git a/Makefile b/Makefile index b7d6189..1fb4e61 100644 --- a/Makefile +++ b/Makefile @@ -75,6 +75,7 @@ HOST_ONLY_TEST_SRCS := \ tests/host/ddk_kernel_services_test.cpp \ tests/host/file_syscalls_test.cpp \ tests/host/syscall_helpers_test.cpp \ + tests/host/process_subsystem_test.cpp \ drivers/dummy/DummyDriver.cpp \ tests/host/socket_syscall_test.cpp \ tests/host/gicv2_test.cpp \ diff --git a/kernel/process/Signal.cpp b/kernel/process/Signal.cpp index e540d2c..b415d5a 100644 --- a/kernel/process/Signal.cpp +++ b/kernel/process/Signal.cpp @@ -226,7 +226,7 @@ void deliver_pending_signals(HAL::CpuContext& ctx) noexcept { exit_current_process(128 + static_cast(sig)); } - const SigAction& act = proc->signals().action(sig); + const SigAction act = proc->signals().action(sig); if (act.handler == KERNEL_SIG_IGN) { proc->signals().restore_saved_mask_if_any(); return; diff --git a/tests/host/mocks/host_hal.cpp b/tests/host/mocks/host_hal.cpp index 0a689a5..48ef998 100644 --- a/tests/host/mocks/host_hal.cpp +++ b/tests/host/mocks/host_hal.cpp @@ -175,55 +175,45 @@ class HostCpuControl final : public HAL::CpuControl { } void set_user_stack_pointer(HAL::CpuContext& ctx, uintptr_t user_sp) const noexcept override { - (void)ctx; - (void)user_sp; + ctx.opaque[31] = static_cast(user_sp); } void set_user_tls_pointer(HAL::CpuContext& ctx, uintptr_t tls) const noexcept override { - (void)ctx; - (void)tls; + ctx.opaque[34] = static_cast(tls); } uintptr_t get_user_tls_pointer(const HAL::CpuContext& ctx) const noexcept override { - (void)ctx; - return 0U; + return static_cast(ctx.opaque[34]); } uint64_t get_reg(const HAL::CpuContext& ctx, size_t index) const noexcept override { - (void)ctx; - (void)index; - return 0ULL; + return (index < 31U) ? ctx.opaque[index] : 0ULL; } void set_reg(HAL::CpuContext& ctx, size_t index, uint64_t value) const noexcept override { - (void)ctx; - (void)index; - (void)value; + if (index < 31U) { + ctx.opaque[index] = value; + } } uintptr_t get_user_stack_pointer(const HAL::CpuContext& ctx) const noexcept override { - (void)ctx; - return 0U; + return static_cast(ctx.opaque[31]); } uintptr_t get_user_pc(const HAL::CpuContext& ctx) const noexcept override { - (void)ctx; - return 0U; + return static_cast(ctx.opaque[32]); } void set_user_pc(HAL::CpuContext& ctx, uintptr_t program_counter) const noexcept override { - (void)ctx; - (void)program_counter; + ctx.opaque[32] = static_cast(program_counter); } uint64_t get_user_pstate(const HAL::CpuContext& ctx) const noexcept override { - (void)ctx; - return 0ULL; + return ctx.opaque[33]; } void set_user_pstate(HAL::CpuContext& ctx, uint64_t pstate) const noexcept override { - (void)ctx; - (void)pstate; + ctx.opaque[33] = pstate; } uint64_t sanitize_user_pstate(uint64_t pstate) const noexcept override { return pstate; } diff --git a/tests/host/process_subsystem_test.cpp b/tests/host/process_subsystem_test.cpp new file mode 100644 index 0000000..41e3d2b --- /dev/null +++ b/tests/host/process_subsystem_test.cpp @@ -0,0 +1,744 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#include "fs/Vfs.hpp" +#include "fs/devfs/devfs.hpp" +#include "fs/rootfs/rootfs.hpp" +#include "fs/tmpfs/tmpfs.hpp" +#include "hal/cpu.hpp" +#include "mm/AddressSpace.hpp" +#include "mm/heap.hpp" +#include "mm/pfa.hpp" +#include "mocks/host_hal.hpp" +#include "process/FdTable.hpp" +#include "process/Process.hpp" +#include "process/Signal.hpp" +#include "process/scheduler.hpp" +#include "process/wait_queue.hpp" +#include "sync/IrqGuard.hpp" +#include "uapi/signal.hpp" + +#include +#include +#include +#include + +namespace { + +using namespace Kernel::FS; +using namespace Kernel::Process; +using namespace Kernel::Scheduler; + +constexpr uintptr_t kUserPageBase = 0x00400000ULL; + +void init_process_env() noexcept { + HostTest::reset_host_hal(); + HAL::get_mmu().activate(); + HAL::get_cpu().enable_interrupts(); + + Kernel::Boot::MemoryMap mem_map{}; + mem_map.regions[0] = Kernel::Boot::MemoryRegion{ + .base_paddr = HostTest::SIM_RAM_BASE, + .size = HostTest::SIM_RAM_SIZE, + }; + mem_map.count = 1U; + mem_map.min_paddr = HostTest::SIM_RAM_BASE; + mem_map.max_paddr = HostTest::SIM_RAM_BASE + HostTest::SIM_RAM_SIZE; + mem_map.total_usable_bytes = HostTest::SIM_RAM_SIZE; + + Kernel::MM::pfa_init(mem_map, HostTest::SIM_RAM_BASE, + HostTest::SIM_RAM_BASE + HostTest::SIM_PAGE_SIZE, 0U, 0U, 0U, 0U, nullptr); + Kernel::MM::heap_init(); + + vfs_reset(); + rootfs_reset(); + devfs_reset(); + tmpfs_reset(); + REQUIRE(rootfs_mount_cpio(nullptr, 0U) == kOk); + REQUIRE(devfs_init_and_mount() == kOk); + REQUIRE(tmpfs_init_and_mount() == kOk); + + Process::set_current(nullptr); + Kernel::Scheduler::init(); +} + +void cleanup_all_processes() noexcept { + Process::set_current(nullptr); + while (Process* head = Process::list_head()) { + Process::destroy(*head); + } + Kernel::Scheduler::init(); +} + +File* open_console_file(uint32_t flags) noexcept { + File* file = nullptr; + REQUIRE(devfs_open_console(flags, &file) == kOk); + REQUIRE(file != nullptr); + return file; +} + +TEST_CASE("FdTable lifecycle, growth, dup, cloexec, and clone", "[process][fdtable]") { + init_process_env(); + + FdTable uninit; + REQUIRE(!uninit.is_initialized()); + REQUIRE(uninit.capacity() == 0U); + REQUIRE(uninit.at(0U) == nullptr); + REQUIRE(static_cast(uninit).at(0U) == nullptr); + REQUIRE(uninit.get_file(0U) == nullptr); + REQUIRE(!uninit.install(0U, nullptr, 0U)); + REQUIRE(!uninit.dup_slot(0U, 1U, false)); + uninit.close(0U); + uninit.close_cloexec(); + uninit.destroy(); + + FdTable table; + REQUIRE(table.init(0U)); // defaults to INITIAL_FD_CAPACITY + REQUIRE(table.is_initialized()); + REQUIRE(table.capacity() == INITIAL_FD_CAPACITY); + + // Re-init destroys previous entries + File* f0 = open_console_file(kOpenReadOnly); + REQUIRE(table.install(0U, f0, FD_FLAG_CLOEXEC)); + REQUIRE(table.get_file(0U) == f0); + REQUIRE(table.at(0U)->has_cloexec()); + REQUIRE(table.at(0U)->is_readable()); + REQUIRE(!table.at(0U)->is_writable()); + REQUIRE(table.at(0U)->is_tty()); + REQUIRE(table.init(4U)); + REQUIRE(table.capacity() == 4U); + REQUIRE(table.get_file(0U) == nullptr); + + // Out-of-bounds checks + REQUIRE(table.at(4U) == nullptr); + REQUIRE(static_cast(table).at(4U) == nullptr); + REQUIRE(table.get_file(4U) == nullptr); + REQUIRE(!table.install(4U, nullptr, 0U)); + table.close(4U); + table.close(1U); // closing already-closed slot + + // ensure_capacity bounds & growth + REQUIRE(!table.ensure_capacity(10U, 8U)); + REQUIRE(table.ensure_capacity(3U, 8U)); + REQUIRE(table.ensure_capacity(6U, 6U)); + REQUIRE(table.capacity() == 6U); + + // allocate with min_fd >= max_fds -> EMFILE (-24) + REQUIRE(table.allocate(6U, 6U) == -24); + REQUIRE(table.allocate(4U, 5U) == -24); + + // allocate on uninitialized table grows automatically + FdTable lazy; + REQUIRE(lazy.allocate(8U, 2U) == 2); + REQUIRE(lazy.capacity() >= 3U); + + // Fill slots 0..5 and test growth & EMFILE + for (size_t i = 0U; i < 6U; ++i) { + File* f = open_console_file(kOpenReadWrite); + REQUIRE(table.install(i, f, (i % 2U == 0U) ? FD_FLAG_CLOEXEC : 0U)); + } + // Overwrite open slot 0 + File* replacement = open_console_file(kOpenWriteOnly); + REQUIRE(table.install(0U, replacement, FD_FLAG_CLOEXEC)); + REQUIRE(table.get_file(0U) == replacement); + REQUIRE(table.at(0U)->is_writable()); + REQUIRE(!table.at(0U)->is_readable()); + + // All 6 slots full, max_fds == 6 -> EMFILE + REQUIRE(table.allocate(6U, 0U) == -24); + // With max_fds == 10, allocate grows capacity and returns slot 6 + const int grown_fd = table.allocate(10U, 0U); + REQUIRE(grown_fd == 6); + REQUIRE(table.capacity() > 6U); + + // dup_slot + REQUIRE(!table.dup_slot(0U, 999U, false)); + REQUIRE(table.dup_slot(0U, 0U, true)); // self-dup is no-op + REQUIRE(table.dup_slot(1U, 0U, true)); // clears cloexec & closes old slot 1 + REQUIRE(table.get_file(1U) == replacement); + REQUIRE(!table.at(1U)->has_cloexec()); + REQUIRE(table.dup_slot(6U, 0U, false)); // keeps cloexec + REQUIRE(table.at(6U)->has_cloexec()); + REQUIRE(table.dup_slot(7U, 8U, false)); // dup closed slot -> closed slot + + // close_cloexec closes 0, 2, 4, 6 but keeps 1, 3, 5 + table.close_cloexec(); + REQUIRE(table.get_file(0U) == nullptr); + REQUIRE(table.get_file(2U) == nullptr); + REQUIRE(table.get_file(4U) == nullptr); + REQUIRE(table.get_file(6U) == nullptr); + REQUIRE(table.get_file(1U) == replacement); + REQUIRE(table.get_file(3U) != nullptr); + REQUIRE(table.get_file(5U) != nullptr); + + // clone_from smaller -> larger and then empty source + FdTable cloned; + REQUIRE(cloned.init(2U)); + File* dummy = open_console_file(kOpenReadOnly); + REQUIRE(cloned.install(0U, dummy, 0U)); + REQUIRE(cloned.clone_from(table)); + REQUIRE(cloned.capacity() >= table.capacity()); + REQUIRE(cloned.get_file(1U) == replacement); + + // Move constructor and move assignment + FdTable moved_ctor(static_cast(cloned)); + REQUIRE(moved_ctor.is_initialized()); + REQUIRE(!cloned.is_initialized()); + + FdTable moved_assign; + REQUIRE(moved_assign.init(2U)); + moved_assign = static_cast(moved_ctor); + REQUIRE(moved_assign.is_initialized()); + REQUIRE(!moved_ctor.is_initialized()); + + REQUIRE(moved_assign.clone_from(uninit)); + REQUIRE(!moved_assign.is_initialized()); +} + +TEST_CASE("WaitQueue sleep, wake_one, wake_all, and remove", "[process][waitqueue]") { + init_process_env(); + + WaitQueue wq; + REQUIRE(wq.empty()); + + // sleep with null current is a no-op + wq.sleep(); + REQUIRE(wq.empty()); + + // wake_one / wake_all / remove on empty + wq.wake_one(); + wq.wake_all(); + wq.remove(nullptr); + + Process* p1 = Process::create(0U); + Process* p2 = Process::create(0U); + Process* p3 = Process::create(0U); + REQUIRE(p1 != nullptr); + REQUIRE(p2 != nullptr); + REQUIRE(p3 != nullptr); + + wq.remove(p1); // not on queue + + Process::set_current(p1); + wq.sleep(); + REQUIRE(p1->state() == ProcessState::Blocked); + REQUIRE(p1->active_wait_queue() == &wq); + + // Sleeping again while already on wq does not double-enqueue + Process::set_current(p1); + wq.sleep(); + REQUIRE(wq.size() == 1U); + + Process::set_current(p2); + wq.sleep(); + Process::set_current(p3); + wq.sleep(); + REQUIRE(wq.size() == 3U); + + // Remove middle (p2), then tail (p3), then head (p1) + wq.remove(p2); + REQUIRE(wq.size() == 2U); + REQUIRE(p2->active_wait_queue() == nullptr); + + wq.remove(p3); + REQUIRE(wq.size() == 1U); + + wq.wake_one(); + REQUIRE(wq.empty()); + REQUIRE(p1->state() == ProcessState::Ready); + REQUIRE(p1->is_on_runqueue()); + + // Re-sleep p1, p2, p3 and wake_all + Process::set_current(p1); + wq.sleep(); + Process::set_current(p2); + wq.sleep(); + Process::set_current(p3); + wq.sleep(); + REQUIRE(wq.size() == 3U); + + wq.wake_all(); + REQUIRE(wq.empty()); + REQUIRE(p1->state() == ProcessState::Ready); + REQUIRE(p2->state() == ProcessState::Ready); + REQUIRE(p3->state() == ProcessState::Ready); + + cleanup_all_processes(); +} + +TEST_CASE("Runqueue and Scheduler transitions and timer preemption", "[process][scheduler]") { + init_process_env(); + + Runqueue rq; + REQUIRE(rq.empty()); + REQUIRE(rq.dequeue() == nullptr); + rq.enqueue(nullptr); + rq.remove(nullptr); + + Process* p1 = Process::create(0U); + Process* p2 = Process::create(0U); + Process* p3 = Process::create(0U); + REQUIRE(p1 != nullptr); + REQUIRE(p2 != nullptr); + REQUIRE(p3 != nullptr); + + rq.remove(p1); // not on runqueue + rq.enqueue(p1); + rq.enqueue(p1); // duplicate ignored + rq.enqueue(p2); + rq.enqueue(p3); + REQUIRE(rq.size() == 3U); + + // Remove middle, tail, head + rq.remove(p2); + REQUIRE(rq.size() == 2U); + rq.remove(p3); + REQUIRE(rq.size() == 1U); + rq.remove(p1); + REQUIRE(rq.empty()); + + rq.enqueue(p1); + rq.enqueue(p2); + REQUIRE(rq.dequeue() == p1); + REQUIRE(rq.dequeue() == p2); + REQUIRE(rq.dequeue() == nullptr); + + // Global scheduler API + REQUIRE(idle_context() != nullptr); + on_timer_tick(false); // null current + Kernel::Scheduler::yield(); // null current, empty runqueue + REQUIRE(!is_in_atomic_context()); + { + const Kernel::Sync::IrqGuard guard; + REQUIRE(is_in_atomic_context()); + } + REQUIRE(!is_in_atomic_context()); + + Kernel::Scheduler::enqueue(nullptr); + Kernel::Scheduler::remove(nullptr); + + // Zombie / Unused ignored by enqueue + p3->set_state(ProcessState::Zombie); + Kernel::Scheduler::enqueue(p3); + REQUIRE(!p3->is_on_runqueue()); + + // Valid address space activation during schedule() + auto as_res = Kernel::MM::AddressSpace::create(); + REQUIRE(as_res.is_ok()); + p2->address_space() = static_cast(as_res.value()); + + p1->reset_timeslice(0U); + p2->reset_timeslice(0U); + Kernel::Scheduler::enqueue(p1); + Kernel::Scheduler::enqueue(p2); + + // yield() with no current -> picks p1 + Kernel::Scheduler::yield(); + REQUIRE(Process::current() == p1); + REQUIRE(p1->state() == ProcessState::Running); + REQUIRE(p1->is_kctx_initialized()); + REQUIRE(p1->timeslice() == DEFAULT_TIMESLICE_TICKS); + + // Timer ticks decrement timeslice and preempt p1 -> p2 + const uint64_t ticks_before = timer_ticks(); + on_timer_tick(true); + REQUIRE(timer_ticks() == ticks_before + 1U); + REQUIRE(p1->utime() == 1U); + on_timer_tick(false); + REQUIRE(p1->stime() == 1U); + on_timer_tick(false); + on_timer_tick(true); // 4th tick hits 0 -> schedule() switches to p2 + REQUIRE(Process::current() == p2); + REQUIRE(p2->state() == ProcessState::Running); + REQUIRE(p1->state() == ProcessState::Ready); + + // Stale non-Ready entry on runqueue is skipped + p1->set_state(ProcessState::Blocked); + Kernel::Scheduler::yield(); // p2 stays Running because p1 was skipped and rq is now empty + REQUIRE(Process::current() == p2); + + // Yield with p2 Running and empty runqueue resets timeslice and keeps p2 Running + Kernel::Scheduler::yield(); + REQUIRE(Process::current() == p2); + REQUIRE(p2->timeslice() == DEFAULT_TIMESLICE_TICKS); + + // Enqueue Blocked process on a waitqueue removes it from the waitqueue + WaitQueue wq; + Process::set_current(p1); + wq.sleep(); + REQUIRE(p1->active_wait_queue() == &wq); + Kernel::Scheduler::enqueue(p1); + REQUIRE(p1->active_wait_queue() == nullptr); + REQUIRE(p1->state() == ProcessState::Ready); + + // Yield with p2 Running and p1 Ready with timeslice == 0 + p1->reset_timeslice(0U); + Process::set_current(p2); + Kernel::Scheduler::yield(); + REQUIRE(Process::current() == p1); + REQUIRE(p1->timeslice() == DEFAULT_TIMESLICE_TICKS); + + // Yield from Zombie prev to Ready next + p1->set_state(ProcessState::Zombie); + Kernel::Scheduler::yield(); + REQUIRE(Process::current() == p2); + + // Zombie current with empty runqueue switches to idle + p2->set_state(ProcessState::Zombie); + Kernel::Scheduler::yield(); + REQUIRE(Process::current() == nullptr); + + // run_until_idle when no active processes (all Stopped/Zombie) returns immediately + p1->set_state(ProcessState::Stopped); + run_until_idle(); + + cleanup_all_processes(); +} + +TEST_CASE("SignalTable masks, actions, wakeup, and frame delivery/restore", "[process][signal]") { + init_process_env(); + + SignalTable sigs; + uint32_t out_sig = 0U; + REQUIRE(!sigs.dequeue_next(out_sig)); + REQUIRE(!sigs.has_unblocked_pending()); + REQUIRE(!sigs.is_deliverable_for_wakeup(0U)); + REQUIRE(!sigs.is_deliverable_for_wakeup(MAX_SIGNALS + 1U)); + REQUIRE(sigs.is_deliverable_for_wakeup(SIG_KILL)); + REQUIRE(sigs.is_deliverable_for_wakeup(SIG_STOP)); + REQUIRE(!sigs.is_deliverable_for_wakeup(SIG_CHLD)); + REQUIRE(!sigs.is_deliverable_for_wakeup(SIG_CONT)); + REQUIRE(sigs.is_deliverable_for_wakeup(SIG_INT)); + + // Unmaskable bits cannot be blocked + sigs.block((1ULL << (SIG_KILL - 1U)) | (1ULL << (SIG_STOP - 1U)) | (1ULL << (SIG_INT - 1U))); + REQUIRE((sigs.blocked() & SignalTable::UNMASKABLE_MASK) == 0ULL); + REQUIRE(!sigs.is_deliverable_for_wakeup(SIG_INT)); + sigs.unblock(1ULL << (SIG_INT - 1U)); + REQUIRE(sigs.is_deliverable_for_wakeup(SIG_INT)); + + // Pending & dequeue + sigs.pend(0U); + sigs.pend(MAX_SIGNALS + 1U); + sigs.pend(SIG_INT); + sigs.block(1ULL << (SIG_INT - 1U)); + REQUIRE(!sigs.has_unblocked_pending()); + REQUIRE(!sigs.dequeue_next(out_sig)); + sigs.pend(SIG_KILL); + REQUIRE(sigs.has_unblocked_pending()); + REQUIRE(sigs.dequeue_next(out_sig)); + REQUIRE(out_sig == SIG_KILL); + + // Ignored / default-ignored pending signals + sigs.unblock(1ULL << (SIG_INT - 1U)); + REQUIRE(sigs.dequeue_next(out_sig)); + REQUIRE(out_sig == SIG_INT); + sigs.pend(SIG_CHLD); + REQUIRE(!sigs.has_unblocked_pending()); + REQUIRE(sigs.dequeue_next(out_sig)); + REQUIRE(out_sig == SIG_CHLD); + sigs.pend(SIG_CONT); + REQUIRE(!sigs.has_unblocked_pending()); + REQUIRE(sigs.dequeue_next(out_sig)); + REQUIRE(out_sig == SIG_CONT); + + // Actions & exec reset + REQUIRE(sigs.action(0U).handler == KERNEL_SIG_DFL); + REQUIRE(!sigs.set_action(0U, SigAction{})); + REQUIRE(!sigs.set_action(SIG_KILL, SigAction{})); + REQUIRE(!sigs.set_action(SIG_STOP, SigAction{})); + + SigAction ign_act{.handler = KERNEL_SIG_IGN, .flags = 0ULL, .restorer = 0ULL, .mask = 0ULL}; + SigAction caught_act{.handler = 0x401000ULL, .flags = 0ULL, .restorer = 0ULL, .mask = 0ULL}; + REQUIRE(sigs.set_action(SIG_HUP, ign_act)); + REQUIRE(sigs.set_action(SIG_TERM, caught_act)); + sigs.pend(SIG_HUP); + REQUIRE(!sigs.has_unblocked_pending()); + REQUIRE(sigs.dequeue_next(out_sig)); + + sigs.reset_caught_for_exec(); + REQUIRE(sigs.action(SIG_HUP).handler == KERNEL_SIG_IGN); + REQUIRE(sigs.action(SIG_TERM).handler == KERNEL_SIG_DFL); + + // Temp/saved mask helpers + sigs.set_blocked(1ULL << (SIG_HUP - 1U)); + const uint64_t prev_mask = sigs.swap_temp_mask(1ULL << (SIG_TERM - 1U)); + REQUIRE(prev_mask == (1ULL << (SIG_HUP - 1U))); + sigs.preserve_saved_mask_for_eintr(prev_mask); + REQUIRE(sigs.consume_saved_or_blocked_mask() == prev_mask); + REQUIRE(sigs.consume_saved_or_blocked_mask() == (1ULL << (SIG_TERM - 1U))); + sigs.preserve_saved_mask_for_eintr(prev_mask); + sigs.restore_saved_mask_if_any(); + REQUIRE(sigs.blocked() == prev_mask); + + // clone_from + SignalTable cloned_sigs; + cloned_sigs.clone_from(sigs); + REQUIRE(cloned_sigs.blocked() == sigs.blocked()); + REQUIRE(cloned_sigs.action(SIG_HUP).handler == KERNEL_SIG_IGN); + + // Process group, wakeup, stop/continue, and custom signal frame delivery/restore + Process* parent = Process::create(0U); + Process* child = Process::create(parent->pid()); + REQUIRE(parent != nullptr); + REQUIRE(child != nullptr); + child->set_pgid(parent->pgid()); + + auto as_res = Kernel::MM::AddressSpace::create(); + REQUIRE(as_res.is_ok()); + child->address_space() = static_cast(as_res.value()); + const uintptr_t stack_pa = Kernel::MM::alloc_frame(); + REQUIRE(stack_pa != 0U); + REQUIRE(child->address_space().map_user_page(kUserPageBase, stack_pa, + HAL::PageFlags::User | HAL::PageFlags::Read | + HAL::PageFlags::Write)); + + // deliver_pending_signals with null current and with no pending signal + HAL::CpuContext ctx{}; + deliver_pending_signals(ctx); + REQUIRE(restore_signal_frame(ctx) == -1); + send_signal(*child, 0U); + Process::set_current(child); + deliver_pending_signals(ctx); + + // Blocked child on wait queue stays blocked on ignored/blocked signal, then wakes on SIG_TERM + WaitQueue wq; + Process::set_current(child); + wq.sleep(); + REQUIRE(child->state() == ProcessState::Blocked); + send_signal(*child, SIG_CHLD); + REQUIRE(child->state() == ProcessState::Blocked); + signal_process_group(0U, SIG_TERM); + signal_process_group(parent->pgid(), 0U); + signal_process_group(parent->pgid(), SIG_TERM); + REQUIRE(child->state() == ProcessState::Ready); + REQUIRE(has_unblocked_pending_signal(*child)); + + // SIG_CONT on non-stopped process and on Zombie process + send_signal(*child, SIG_CONT); + parent->set_state(ProcessState::Zombie); + send_signal(*parent, SIG_TERM); + signal_process_group(parent->pgid(), SIG_CHLD); + parent->set_state(ProcessState::Ready); + + // Clear pending and test stop -> SIG_CONT + while (child->signals().dequeue_next(out_sig)) { + } + child->set_state(ProcessState::Running); + Process::set_current(child); + send_signal(*child, SIG_TSTP); + deliver_pending_signals(ctx); + HAL::get_cpu().enable_interrupts(); + REQUIRE(child->state() == ProcessState::Stopped); + REQUIRE(child->stop_signal() == SIG_TSTP); + + send_signal(*child, SIG_CONT); + REQUIRE(child->state() == ProcessState::Ready); + REQUIRE(child->is_continued()); + + // Deliver IGN and SIG_CHLD + Process::set_current(child); + REQUIRE(child->signals().dequeue_next(out_sig)); // dequeue SIG_CONT + send_signal(*child, SIG_HUP); + REQUIRE(child->signals().set_action(SIG_HUP, ign_act)); + deliver_pending_signals(ctx); + send_signal(*child, SIG_CHLD); + deliver_pending_signals(ctx); + + // Custom handler delivery (SA_FLAG_RESTORER) and restore_signal_frame + auto& cpu = HAL::get_cpu(); + cpu.set_user_stack_pointer(ctx, kUserPageBase + 0xF00U); + cpu.set_user_pc(ctx, 0x400123ULL); + cpu.set_user_pstate(ctx, 0x10ULL); + cpu.set_user_tls_pointer(ctx, 0x400800ULL); + cpu.set_reg(ctx, 0U, 42ULL); + cpu.set_reg(ctx, 5U, 0x12345678ULL); + + SigAction user_act{ + .handler = 0x400500ULL, + .flags = SA_FLAG_RESTORER | Kernel::UAPI::SA_RESETHAND, + .restorer = 0x400600ULL, + .mask = (1ULL << (SIG_ALRM - 1U)), + }; + REQUIRE(child->signals().set_action(SIG_HUP, user_act)); + send_signal(*child, SIG_HUP); + deliver_pending_signals(ctx); + + REQUIRE(cpu.get_user_pc(ctx) == 0x400500ULL); + REQUIRE(cpu.get_reg(ctx, 0U) == SIG_HUP); + REQUIRE(cpu.get_reg(ctx, 30U) == 0x400600ULL); + REQUIRE(child->signals().action(SIG_HUP).handler == KERNEL_SIG_DFL); + + const int64_t restored_x0 = restore_signal_frame(ctx); + REQUIRE(restored_x0 == 42); + REQUIRE(cpu.get_user_pc(ctx) == 0x400123ULL); + REQUIRE(cpu.get_reg(ctx, 5U) == 0x12345678ULL); + + // Fallback trampoline restorer + SA_NODEFER + SigAction tramp_act{ + .handler = 0x400700ULL, + .flags = Kernel::UAPI::SA_NODEFER, + .restorer = 0ULL, + .mask = 0ULL, + }; + REQUIRE(child->signals().set_action(SIG_HUP, tramp_act)); + send_signal(*child, SIG_HUP); + deliver_pending_signals(ctx); + REQUIRE(cpu.get_user_pc(ctx) == 0x400700ULL); + + child->address_space().unmap_user_page(kUserPageBase); + Kernel::MM::free_frame(stack_pa); + cleanup_all_processes(); +} + +TEST_CASE("Process lifecycle, identity, accounting, paths, and cleanup", "[process][pcb]") { + init_process_env(); + + REQUIRE(Process::find_by_pid(0U) == nullptr); + REQUIRE(Process::find_by_pid(9999U) == nullptr); + REQUIRE(last_cpu_ticks_for_pid(0U) == 0ULL); + REQUIRE(last_cpu_ticks_for_pid(9999U) == 0ULL); + + Process* p1 = Process::create(0U); + Process* p2 = Process::create(p1->pid()); + Process* p3 = Process::create(p1->pid()); + REQUIRE(p1 != nullptr); + REQUIRE(p2 != nullptr); + REQUIRE(p3 != nullptr); + + REQUIRE(Process::active_count() == 3U); + REQUIRE(Process::has_runnable()); + REQUIRE(Process::find_by_pid(p2->pid()) == p2); + + // setsid & umask + REQUIRE(!p1->setsid()); // already group leader (ppid == 0) + REQUIRE(p2->setsid()); // ppid != 0 -> pgid != pid initially + REQUIRE(p2->pgid() == p2->pid()); + REQUIRE(p2->sid() == p2->pid()); + REQUIRE(p2->set_umask(01777U) == 0022U); + REQUIRE(p2->umask() == 0777U); + + // Stop / continue consumption + uint32_t stop_sig = 0U; + REQUIRE(!p2->consume_stop_report(stop_sig)); + REQUIRE(!p2->consume_continued()); + p2->mark_stopped(SIG_STOP); + REQUIRE(p2->is_stop_reported() == false); + REQUIRE(p2->consume_stop_report(stop_sig)); + REQUIRE(stop_sig == SIG_STOP); + REQUIRE(p2->is_stop_reported()); + REQUIRE(!p2->consume_stop_report(stop_sig)); + p2->mark_continued(); + REQUIRE(p2->consume_continued()); + REQUIRE(!p2->consume_continued()); + + // CPU accounting & child accumulation + p2->record_cpu_tick(true); + p2->record_cpu_tick(false); + REQUIRE(last_cpu_ticks_for_pid(p2->pid()) == 2ULL); + p1->accumulate_child_ticks(*p2); + REQUIRE(p1->cutime() == 1U); + REQUIRE(p1->cstime() == 1U); + + // Paths (including nullptr and > MAX_PATH_LEN truncation) + char long_path[MAX_PATH_LEN + 16U]; + std::memset(long_path, 'a', sizeof(long_path) - 1U); + long_path[sizeof(long_path) - 1U] = '\0'; + p2->set_cwd(long_path); + REQUIRE(std::strlen(p2->cwd()) == MAX_PATH_LEN - 1U); + p2->set_exe_path(nullptr); + REQUIRE(p2->exe_path()[0] == '\0'); + p2->set_exe_path("/bin/sh"); + REQUIRE(std::strcmp(p2->exe_path(), "/bin/sh") == 0); + p2->mutable_cwd()[0] = '/'; + p2->mutable_cwd()[1] = '\0'; + + // Limits & tid & ELF attach + p2->set_rlim_nofile(RLimit64{.rlim_cur = 32U, .rlim_max = 64U}); + REQUIRE(p2->rlim_nofile().rlim_cur == 32U); + p2->set_rlim_nproc(RLimit64{.rlim_cur = 16U, .rlim_max = 32U}); + REQUIRE(p2->rlim_nproc().rlim_max == 32U); + p2->set_clear_child_tid(0x401234ULL); + REQUIRE(p2->clear_child_tid() == 0x401234ULL); + + Kernel::Loader::LoadedElf loaded{}; + loaded.entry_point = 0x401000ULL; + loaded.max_vaddr = 0x408000ULL; + p2->attach_elf(static_cast(loaded)); + REQUIRE(p2->entry_point() == 0x401000ULL); + REQUIRE(p2->brk_start() == 0x408000ULL); + REQUIRE(p2->brk_current() == 0x408000ULL); + REQUIRE(p2->mmap_next_vaddr() != 0U); + + // execute() with invalid address space returns -1 + REQUIRE(p2->execute() == -1); + + // execute() with valid address space in Zombie state exits cleanly + auto as_res = Kernel::MM::AddressSpace::create(); + REQUIRE(as_res.is_ok()); + p2->address_space() = static_cast(as_res.value()); + p2->set_state(ProcessState::Zombie); + p2->set_exit_status(7); + REQUIRE(p2->execute() == 7); + + // Reaped ticks cache preserved after destroy + const uint32_t reaped_pid = p2->pid(); + Process::destroy(*p2); // middle node + REQUIRE(last_cpu_ticks_for_pid(reaped_pid) == 2ULL); + + // Destroy tail (p3) with user_stack attached and active wait queue + WaitQueue wq; + Process::set_current(p3); + wq.sleep(); + const uintptr_t ustack_pa = Kernel::MM::alloc_frame(); + REQUIRE(ustack_pa != 0U); + UserStack ustack{}; + ustack.phys_base = ustack_pa; + ustack.num_pages = 1U; + p3->set_user_stack(ustack); + Process::destroy(*p3); + REQUIRE(wq.empty()); + + // TTY foreground pgid & user context helpers + set_foreground_pgid(p1->pgid()); + REQUIRE(get_foreground_pgid() == p1->pgid()); + HAL::CpuContext uctx{}; + init_user_cpu_context(uctx, 0x401000ULL, 0x402000ULL, 1ULL, 0x403000ULL); + REQUIRE(enter_user_context(nullptr) == -1); + REQUIRE(enter_user_context(&uctx) == 0); + + // prepare_kstack on zeroed stack_top is a no-op + Process uninit_proc; + uninit_proc.prepare_kstack(); + REQUIRE(!uninit_proc.is_kctx_initialized()); + REQUIRE(!uninit_proc.tick_timeslice() || uninit_proc.timeslice() == 0U); + + // attach_elf with max_vaddr == 0 leaves brk unchanged + Kernel::Loader::LoadedElf empty_elf{}; + p1->set_mmap_next_vaddr(0x50000000ULL); + p1->attach_elf(static_cast(empty_elf)); + REQUIRE(p1->mmap_next_vaddr() == 0x50000000ULL); + + // has_runnable() true for Running, false when only Stopped/Zombie processes exist + p1->set_state(ProcessState::Running); + REQUIRE(Process::has_runnable()); + p1->set_state(ProcessState::Stopped); + REQUIRE(!Process::has_runnable()); + + // Destroy current process clears Process::current() + Process::set_current(p1); + Process::destroy(*p1); + REQUIRE(Process::current() == nullptr); + REQUIRE(!Process::has_runnable()); + + // Hitting default_rlimit_nproc() returns nullptr + const size_t limit = default_rlimit_nproc(); + for (size_t i = 0U; i < limit; ++i) { + REQUIRE(Process::create(0U) != nullptr); + } + REQUIRE(Process::create(0U) == nullptr); + + cleanup_all_processes(); +} + +} // namespace From 14639db8cf2d6e67106ddbb7b5ea01add49b4ac9 Mon Sep 17 00:00:00 2001 From: marcobuschini Date: Fri, 4 Dec 2026 10:50:45 +0000 Subject: [PATCH 3/4] test(coverage): add and expand host unit tests for CPIO, FDT, Virtio-Blk, and Duration (#260) - Add `tests/host/cpio_duration_test.cpp` covering `CpioArchive`, `cpio_lookup()`, malformed archive error paths, and `Duration` conversions - Expand `tests/host/fdt_test.cpp` to cover header validation, memory regions, reservations, initrd bounds, `fw_cfg`, and cell/interrupt edge cases - Expand `tests/host/virtio_blk_test.cpp` for `bind_from_bus()`, error paths, multi-chunk I/O, deferred IRQ polling, and `MMIO_INTERRUPT_ACK` checks - Register `cpio_duration_test.cpp` and `virtio_blk_test.cpp` in `Makefile`, raising target coverage to 92% lines / 77% branches --- Makefile | 2 + tests/host/cpio_duration_test.cpp | 223 +++++++++++++++++++++++++++ tests/host/fdt_test.cpp | 247 +++++++++++++++++++++++++++++- tests/host/virtio_blk_test.cpp | 128 ++++++++++++++-- 4 files changed, 589 insertions(+), 11 deletions(-) create mode 100644 tests/host/cpio_duration_test.cpp diff --git a/Makefile b/Makefile index 1fb4e61..a8e6bf3 100644 --- a/Makefile +++ b/Makefile @@ -76,6 +76,8 @@ HOST_ONLY_TEST_SRCS := \ tests/host/file_syscalls_test.cpp \ tests/host/syscall_helpers_test.cpp \ tests/host/process_subsystem_test.cpp \ + tests/host/cpio_duration_test.cpp \ + tests/host/virtio_blk_test.cpp \ drivers/dummy/DummyDriver.cpp \ tests/host/socket_syscall_test.cpp \ tests/host/gicv2_test.cpp \ diff --git a/tests/host/cpio_duration_test.cpp b/tests/host/cpio_duration_test.cpp new file mode 100644 index 0000000..0b55359 --- /dev/null +++ b/tests/host/cpio_duration_test.cpp @@ -0,0 +1,223 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#include "fs/cpio.hpp" +#include "time/Duration.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace Kernel::FS; +using namespace Kernel::Time; + +void write_hex8(char* dst, uint32_t val) noexcept { + static constexpr char kHex[] = "0123456789abcdef"; + for (size_t i = 0U; i < 8U; ++i) { + dst[7U - i] = kHex[val & 0xFU]; + val >>= 4U; + } +} + +void append_cpio_entry(std::vector& buf, const char* magic, std::string_view name, + uint32_t mode, const void* payload, uint32_t payload_size, + bool include_nul = true) noexcept { + CpioNewcHeader hdr{}; + std::fill_n(reinterpret_cast(&hdr), sizeof(hdr), '0'); + std::memcpy(hdr.c_magic, magic, 6U); + write_hex8(hdr.c_mode, mode); + write_hex8(hdr.c_filesize, payload_size); + const auto namesize = static_cast(name.size() + 1U); + write_hex8(hdr.c_namesize, namesize); + + const auto* hdr_bytes = reinterpret_cast(&hdr); + buf.insert(buf.end(), hdr_bytes, hdr_bytes + sizeof(hdr)); + + for (char ch : name) { + buf.push_back(static_cast(ch)); + } + buf.push_back(include_nul ? 0U : static_cast('X')); + + while ((buf.size() & 3U) != 0U) { + buf.push_back(0U); + } + + if (payload != nullptr && payload_size > 0U) { + const auto* data = static_cast(payload); + buf.insert(buf.end(), data, data + payload_size); + while ((buf.size() & 3U) != 0U) { + buf.push_back(0U); + } + } +} + +TEST_CASE("CpioArchive status strings, validation, lookup, and error paths", "[fs][cpio]") { + CHECK(std::strcmp(cpio_status_str(CpioStatus::Success), "Success") == 0); + CHECK(std::strcmp(cpio_status_str(CpioStatus::ArchiveTooSmall), "ArchiveTooSmall") == 0); + CHECK(std::strcmp(cpio_status_str(CpioStatus::InvalidMagic), "InvalidMagic") == 0); + CHECK(std::strcmp(cpio_status_str(CpioStatus::MalformedHeader), "MalformedHeader") == 0); + CHECK(std::strcmp(cpio_status_str(CpioStatus::CorruptedPadding), "CorruptedPadding") == 0); + CHECK(std::strcmp(cpio_status_str(CpioStatus::PathTooLong), "PathTooLong") == 0); + CHECK(std::strcmp(cpio_status_str(CpioStatus::FileNotFound), "FileNotFound") == 0); + CHECK(std::strcmp(cpio_status_str(CpioStatus::UnexpectedEndOfArchive), + "UnexpectedEndOfArchive") == 0); + + CpioEntry entry{}; + CHECK_FALSE(CpioArchive(nullptr, 128U).is_valid()); + CHECK_FALSE(CpioArchive("070701", 6U).is_valid()); + CHECK(cpio_lookup(nullptr, 0U, "a", entry) == CpioStatus::ArchiveTooSmall); + + std::array bad_hdr{}; + std::memset(bad_hdr.data(), '0', bad_hdr.size()); + std::memcpy(bad_hdr.data(), "070703", 6U); + CHECK_FALSE(CpioArchive(bad_hdr.data(), bad_hdr.size()).is_valid()); + CHECK(cpio_lookup(bad_hdr.data(), bad_hdr.size(), "a", entry) == CpioStatus::InvalidMagic); + + std::memcpy(bad_hdr.data(), "07070X", 6U); + CHECK_FALSE(CpioArchive(bad_hdr.data(), bad_hdr.size()).is_valid()); + std::memcpy(bad_hdr.data(), "070702", 6U); + CHECK(CpioArchive(bad_hdr.data(), bad_hdr.size()).is_valid()); + CHECK(cpio_lookup(bad_hdr.data(), bad_hdr.size(), nullptr, entry) == CpioStatus::FileNotFound); + CHECK(cpio_lookup(bad_hdr.data(), bad_hdr.size(), "", entry) == CpioStatus::FileNotFound); + + // Valid archive with dir, regular file (070702), symlink, and TRAILER!!! + std::vector archive; + append_cpio_entry(archive, CPIO_NEWC_MAGIC_NOCRC, "bin", CPIO_MODE_DIR | 0755U, nullptr, 0U); + const char file_data[] = "hello"; + append_cpio_entry(archive, CPIO_NEWC_MAGIC_CRC, "./bin/hello", CPIO_MODE_REGULAR | 0644U, + file_data, 5U); + const char link_target[] = "/bin/hello"; + append_cpio_entry(archive, CPIO_NEWC_MAGIC_NOCRC, "bin/hi", CPIO_MODE_SYMLINK | 0777U, + link_target, 10U); + append_cpio_entry(archive, CPIO_NEWC_MAGIC_NOCRC, CPIO_TRAILER_NAME, 0U, nullptr, 0U); + + CHECK(cpio_lookup(archive.data(), archive.size(), "/bin", entry) == CpioStatus::Success); + CHECK(entry.is_directory); + CHECK_FALSE(entry.is_regular_file); + + CHECK(cpio_lookup(archive.data(), archive.size(), "bin/hello", entry) == CpioStatus::Success); + CHECK(entry.is_regular_file); + CHECK(entry.size == 5U); + CHECK(std::memcmp(entry.data, "hello", 5U) == 0); + + CHECK(cpio_lookup(archive.data(), archive.size(), "bin/hi", entry) == CpioStatus::Success); + CHECK_FALSE(entry.is_directory); + CHECK_FALSE(entry.is_regular_file); + + CHECK(cpio_lookup(archive.data(), archive.size(), "missing", entry) == + CpioStatus::FileNotFound); + + // Void callback path in for_each + size_t count = 0U; + const CpioArchive valid_arch(archive.data(), archive.size()); + CHECK(valid_arch.for_each([&](const CpioEntry&) { ++count; }) == CpioStatus::Success); + CHECK(count == 3U); + + // Truncated archive without TRAILER!!! propagates UnexpectedEndOfArchive + std::vector no_trailer; + append_cpio_entry(no_trailer, CPIO_NEWC_MAGIC_NOCRC, "a", CPIO_MODE_REGULAR, "x", 1U); + CHECK(cpio_lookup(no_trailer.data(), no_trailer.size(), "missing", entry) == + CpioStatus::UnexpectedEndOfArchive); + CHECK(CpioArchive(no_trailer.data(), no_trailer.size() - 1U).for_each([](const CpioEntry&) { + }) == CpioStatus::UnexpectedEndOfArchive); + + // Bad hex in header + std::vector bad_hex = no_trailer; + bad_hex[offsetof(CpioNewcHeader, c_namesize)] = 'z'; + CHECK(CpioArchive(bad_hex.data(), bad_hex.size()).for_each([](const CpioEntry&) {}) == + CpioStatus::MalformedHeader); + + // namesize == 0 and namesize >= 4096 + std::vector zero_name = no_trailer; + write_hex8(reinterpret_cast(zero_name.data() + offsetof(CpioNewcHeader, c_namesize)), + 0U); + CHECK(CpioArchive(zero_name.data(), zero_name.size()).for_each([](const CpioEntry&) {}) == + CpioStatus::MalformedHeader); + write_hex8(reinterpret_cast(zero_name.data() + offsetof(CpioNewcHeader, c_namesize)), + 4096U); + CHECK(CpioArchive(zero_name.data(), zero_name.size()).for_each([](const CpioEntry&) {}) == + CpioStatus::PathTooLong); + + // Non-null-terminated name + std::vector no_nul; + append_cpio_entry(no_nul, CPIO_NEWC_MAGIC_NOCRC, "ab", CPIO_MODE_REGULAR, nullptr, 0U, false); + CHECK(CpioArchive(no_nul.data(), no_nul.size()).for_each([](const CpioEntry&) {}) == + CpioStatus::MalformedHeader); + + // Corrupted name padding (name "ab" -> 110 + 3 = 113 bytes + 3 bytes padding to 116) + std::vector bad_pad; + append_cpio_entry(bad_pad, CPIO_NEWC_MAGIC_NOCRC, "ab", CPIO_MODE_REGULAR, nullptr, 0U); + bad_pad[sizeof(CpioNewcHeader) + 3U] = 0xAAU; + CHECK(CpioArchive(bad_pad.data(), bad_pad.size()).for_each([](const CpioEntry&) {}) == + CpioStatus::CorruptedPadding); + + // Corrupted payload padding (payload "x" -> 1 byte + 3 bytes padding) + std::vector bad_pay_pad = no_trailer; + bad_pay_pad[bad_pay_pad.size() - 1U] = 0x55U; + CHECK(CpioArchive(bad_pay_pad.data(), bad_pay_pad.size()).for_each([](const CpioEntry&) {}) == + CpioStatus::CorruptedPadding); +} + +TEST_CASE("Duration conversions, ticks, timespec, and overflow guards", "[time][duration]") { + const Duration z = Duration::zero(); + CHECK(z.is_zero()); + CHECK(z.nanoseconds() == 0ULL); + CHECK(z.to_timer_ticks(1000ULL) == 0ULL); + + const Duration us = Duration::from_microseconds(1500ULL); + CHECK_FALSE(us.is_zero()); + CHECK(us.nanoseconds() == 1500000ULL); + + const Duration ns = Duration::from_nanoseconds(2500000500ULL); + const linux_timespec ts = ns.to_linux_timespec(); + CHECK(ts.tv_sec == 2); + CHECK(ts.tv_nsec == 500000500); + + const linux_timeval tv = ns.to_linux_timeval(); + CHECK(tv.tv_sec == 2); + CHECK(tv.tv_usec == 500000); + + // from_ticks (runtime inputs so constexpr functions execute at runtime) + volatile uint64_t zero_u = 0ULL; + volatile uint64_t ticks_val = 1500ULL; + volatile uint64_t freq_val = 1000ULL; + CHECK(Duration::from_ticks(ticks_val, zero_u).is_zero()); + CHECK(Duration::from_ticks(zero_u, freq_val).is_zero()); + const Duration t_dur = Duration::from_ticks(ticks_val, freq_val); + CHECK(t_dur.nanoseconds() == 1500000000ULL); + + // to_timer_ticks (including rounding up sub-second remainder) + volatile uint64_t one_ns = 1ULL; + volatile uint64_t two_s_ns = 2000000000ULL; + CHECK(Duration::from_nanoseconds(one_ns).to_timer_ticks(zero_u) == 0ULL); + CHECK(Duration::from_nanoseconds(one_ns).to_timer_ticks(freq_val) == 1ULL); + CHECK(Duration::from_nanoseconds(two_s_ns).to_timer_ticks(freq_val) == 2000ULL); + + // from_linux_timespec validation & overflow + Duration out{}; + volatile int64_t neg_val = -1; + volatile int64_t sec_over = INT64_MAX; + volatile int64_t nsec_bad = static_cast(Duration::NS_PER_SEC); + CHECK_FALSE( + Duration::from_linux_timespec(linux_timespec{.tv_sec = neg_val, .tv_nsec = 0}, out)); + CHECK_FALSE( + Duration::from_linux_timespec(linux_timespec{.tv_sec = 0, .tv_nsec = neg_val}, out)); + CHECK_FALSE( + Duration::from_linux_timespec(linux_timespec{.tv_sec = 0, .tv_nsec = nsec_bad}, out)); + CHECK_FALSE( + Duration::from_linux_timespec(linux_timespec{.tv_sec = sec_over, .tv_nsec = 0}, out)); + + volatile int64_t sec_ok = 3; + volatile int64_t nsec_ok = 250; + REQUIRE( + Duration::from_linux_timespec(linux_timespec{.tv_sec = sec_ok, .tv_nsec = nsec_ok}, out)); + CHECK(out.nanoseconds() == 3000000250ULL); +} + +} // namespace diff --git a/tests/host/fdt_test.cpp b/tests/host/fdt_test.cpp index 8983050..ed99980 100644 --- a/tests/host/fdt_test.cpp +++ b/tests/host/fdt_test.cpp @@ -16,10 +16,18 @@ constexpr uint32_t FDT_MAGIC = 0xD00DFEEDU; constexpr uint32_t FDT_BEGIN_NODE = 0x00000001U; constexpr uint32_t FDT_END_NODE = 0x00000002U; constexpr uint32_t FDT_PROP = 0x00000003U; +constexpr uint32_t FDT_NOP = 0x00000004U; constexpr uint32_t FDT_END = 0x00000009U; class SyntheticDtbBuilder { public: + void add_nop() noexcept { push_be32(FDT_NOP); } + + void add_memreserve(uint64_t addr, uint64_t size) noexcept { + REQUIRE(m_rsv_count < m_rsv.size()); + m_rsv[m_rsv_count++] = RsvEntry{.addr = addr, .size = size}; + } + void begin_node(std::string_view name) noexcept { push_be32(FDT_BEGIN_NODE); for (char chr : name) { @@ -61,13 +69,25 @@ class SyntheticDtbBuilder { align4(); } + void prop_raw(std::string_view name, const void* data, size_t len) noexcept { + const uint32_t nameoff = add_string(name); + push_be32(FDT_PROP); + push_be32(static_cast(len)); + push_be32(nameoff); + const auto* bytes = static_cast(data); + for (size_t idx = 0U; idx < len; ++idx) { + push_byte(bytes[idx]); + } + align4(); + } + uintptr_t finalize() noexcept { push_be32(FDT_END); constexpr size_t HEADER_SIZE = 40U; - constexpr size_t RSVMAP_SIZE = 16U; // Empty terminator (0, 0) + const size_t rsvmap_size = (m_rsv_count + 1U) * 16U; // entries + (0, 0) terminator const size_t off_rsvmap = HEADER_SIZE; - const size_t off_struct = off_rsvmap + RSVMAP_SIZE; + const size_t off_struct = off_rsvmap + rsvmap_size; const size_t off_strings = off_struct + m_struct_len; const size_t total_size = off_strings + m_strings_len; REQUIRE(total_size <= m_blob.size()); @@ -84,11 +104,19 @@ class SyntheticDtbBuilder { write_be32(m_blob.data() + 32U, static_cast(m_strings_len)); write_be32(m_blob.data() + 36U, static_cast(m_struct_len)); + for (size_t i = 0U; i < m_rsv_count; ++i) { + write_be64(m_blob.data() + off_rsvmap + (i * 16U), m_rsv[i].addr); + write_be64(m_blob.data() + off_rsvmap + (i * 16U) + 8U, m_rsv[i].size); + } + std::memcpy(m_blob.data() + off_struct, m_struct.data(), m_struct_len); std::memcpy(m_blob.data() + off_strings, m_strings.data(), m_strings_len); return reinterpret_cast(m_blob.data()); } + uint8_t* blob_data() noexcept { return m_blob.data(); } + static void patch_be32(uint8_t* dst, uint32_t val) noexcept { write_be32(dst, val); } + private: static void write_be32(uint8_t* dst, uint32_t val) noexcept { dst[0] = static_cast((val >> 24U) & 0xFFU); @@ -97,6 +125,11 @@ class SyntheticDtbBuilder { dst[3] = static_cast(val & 0xFFU); } + static void write_be64(uint8_t* dst, uint64_t val) noexcept { + write_be32(dst, static_cast(val >> 32U)); + write_be32(dst + 4U, static_cast(val & 0xFFFFFFFFULL)); + } + void push_byte(uint8_t byte_val) noexcept { REQUIRE(m_struct_len < m_struct.size()); m_struct[m_struct_len++] = byte_val; @@ -125,6 +158,13 @@ class SyntheticDtbBuilder { return offset; } + struct RsvEntry { + uint64_t addr{0ULL}; + uint64_t size{0ULL}; + }; + + std::array m_rsv{}; + size_t m_rsv_count{0U}; std::array m_struct{}; size_t m_struct_len{0U}; std::array m_strings{}; @@ -199,4 +239,207 @@ TEST_CASE("FDT virtio enumeration handles null or corrupt DTB safely", "[fdt][vi Kernel::Boot::VirtioMmioList devices{}; CHECK_FALSE(Kernel::Boot::find_virtio_mmio_devices(0U, devices)); CHECK(devices.count == 0U); + CHECK(Kernel::Boot::find_virtio_mmio_devices(0U).count == 0U); +} + +TEST_CASE("FDT validates headers and rejects malformed offsets", "[fdt][header]") { + CHECK_FALSE(Kernel::Boot::validate_header(0U)); + + SyntheticDtbBuilder builder{}; + builder.begin_node(""); + builder.end_node(); + const uintptr_t dtb_paddr = builder.finalize(); + + size_t totalsize = 0U; + REQUIRE(Kernel::Boot::validate_header(dtb_paddr, &totalsize)); + CHECK(totalsize >= 40U); + REQUIRE(Kernel::Boot::validate_header(dtb_paddr, nullptr)); + + // Bad magic + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 0U, 0xDEADBEEFU); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 0U, FDT_MAGIC); + + // totalsize too small + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 4U, 16U); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 4U, static_cast(totalsize)); + + // off_dt_struct out of bounds + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 8U, + static_cast(totalsize + 4U)); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 8U, 56U); + + // off_dt_strings out of bounds + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 12U, + static_cast(totalsize + 4U)); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 12U, static_cast(totalsize)); + + // off_mem_rsvmap out of bounds and < FDT_HEADER_SIZE + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 16U, + static_cast(totalsize + 4U)); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 16U, 8U); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 8U, 8U); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 12U, 8U); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); +} + +TEST_CASE("FDT parses memory regions, reservations, initrd, and fw_cfg", "[fdt][memory]") { + // Null DTB fallback behavior + const Kernel::Boot::MemoryMap fallback = Kernel::Boot::find_memory_regions(0U); + CHECK(fallback.count == 1U); + CHECK(fallback.total_usable_bytes > 0U); + CHECK(Kernel::Boot::find_memory_reservations(0U).count == 0U); + CHECK_FALSE(Kernel::Boot::find_initrd(0U).valid); + CHECK_FALSE(Kernel::Boot::find_fw_cfg_device(0U).valid); + + // 64-bit memory regions (overlapping + separate + disabled + device_type), reservations, 64-bit + // initrd, fw_cfg + SyntheticDtbBuilder builder{}; + builder.add_memreserve(0x40000000ULL, 0x10000ULL); + builder.add_memreserve(0x41000000ULL, 0ULL); // zero-size ignored + builder.add_memreserve(0x42000000ULL, 0x20000ULL); + + builder.begin_node(""); + builder.add_nop(); + builder.prop_u32("#address-cells", 2U); + builder.prop_u32("#size-cells", 2U); + + // Memory node 1 (out of order, overlaps node 2) + builder.begin_node("memory@41000000"); + const uint32_t mem1[4] = {0U, 0x41000000U, 0U, 0x01000000U}; + builder.prop_u32_array("reg", mem1, 4U); + builder.end_node(); + + // Memory node 2 (via device_type = "memory") + builder.begin_node("ram-bank"); + builder.prop_string("device_type", "memory"); + const uint32_t mem2[4] = {0U, 0x40000000U, 0U, 0x01200000U}; + builder.prop_u32_array("reg", mem2, 4U); + builder.end_node(); + + // Separate memory node 3 + builder.begin_node("memory@50000000"); + const uint32_t mem3[4] = {0U, 0x50000000U, 0U, 0x00800000U}; + builder.prop_u32_array("reg", mem3, 4U); + builder.end_node(); + + // Disabled memory node (ignored) + builder.begin_node("memory@60000000"); + builder.prop_string("status", "disabled"); + const uint32_t mem_dis[4] = {0U, 0x60000000U, 0U, 0x01000000U}; + builder.prop_u32_array("reg", mem_dis, 4U); + builder.end_node(); + + // chosen node with 64-bit initrd bounds + builder.begin_node("chosen"); + builder.add_nop(); + const uint32_t initrd_start[2] = {0U, 0x44000000U}; + const uint32_t initrd_end[2] = {0U, 0x44100000U}; + builder.prop_u32_array("linux,initrd-start", initrd_start, 2U); + builder.prop_u32_array("linux,initrd-end", initrd_end, 2U); + builder.end_node(); + + // Disabled fw_cfg then valid fw_cfg + builder.begin_node("fw-cfg@9010000"); + builder.prop_string("compatible", "qemu,fw-cfg-mmio"); + builder.prop_string("status", "fail"); + const uint32_t fw_dis[4] = {0U, 0x09010000U, 0U, 0x18U}; + builder.prop_u32_array("reg", fw_dis, 4U); + builder.end_node(); + + builder.begin_node("fw-cfg@9020000"); + builder.prop_string("compatible", "qemu,fw-cfg-mmio"); + const uint32_t fw_reg[4] = {0U, 0x09020000U, 0U, 0x18U}; + builder.prop_u32_array("reg", fw_reg, 4U); + builder.end_node(); + + // Virtio with PPI + 1-cell IRQ + compatible list + builder.begin_node("virtio_mmio@a000200"); + const char compat_list[] = "vendor,custom\0virtio,mmio"; + builder.prop_raw("compatible", compat_list, sizeof(compat_list)); + const uint32_t vreg[4] = {0U, 0x0A000200U, 0U, 0x200U}; + builder.prop_u32_array("reg", vreg, 4U); + const uint32_t ppi_irq[3] = {1U, 11U, 4U}; // PPI 11 -> INTID 27 + builder.prop_u32_array("interrupts", ppi_irq, 3U); + builder.end_node(); + + builder.begin_node("virtio_mmio@a000600"); + builder.prop_string("compatible", "virtio,mmio"); + const uint32_t vreg2[4] = {0U, 0x0A000600U, 0U, 0x200U}; + builder.prop_u32_array("reg", vreg2, 4U); + builder.prop_u32("interrupts", 20U); // 1-cell SPI 20 -> INTID 52 + builder.end_node(); + + builder.end_node(); + const uintptr_t dtb_paddr = builder.finalize(); + + Kernel::Boot::MemoryMap mmap{}; + REQUIRE(Kernel::Boot::find_memory_regions(dtb_paddr, mmap)); + REQUIRE(mmap.count == 2U); + CHECK(mmap.regions[0].base_paddr == 0x40000000ULL); + CHECK(mmap.regions[0].size == 0x02000000U); // 0x40000000..0x42000000 merged + CHECK(mmap.regions[1].base_paddr == 0x50000000ULL); + CHECK(mmap.min_paddr == 0x40000000ULL); + CHECK(mmap.max_paddr == 0x50800000ULL); + CHECK(mmap.total_usable_bytes == 0x02800000U); + + const Kernel::Boot::ReserveMap rsv = Kernel::Boot::find_memory_reservations(dtb_paddr); + REQUIRE(rsv.count == 2U); + CHECK(rsv.entries[0].base_paddr == 0x40000000ULL); + CHECK(rsv.entries[0].size == 0x10000U); + CHECK(rsv.entries[1].base_paddr == 0x42000000ULL); + + const Kernel::Boot::InitrdLocation initrd = Kernel::Boot::find_initrd(dtb_paddr); + REQUIRE(initrd.valid); + CHECK(initrd.start_paddr == 0x44000000ULL); + CHECK(initrd.end_paddr == 0x44100000ULL); + CHECK(initrd.size == 0x100000U); + + const Kernel::Boot::FwCfgDevice fw = Kernel::Boot::find_fw_cfg_device(dtb_paddr); + REQUIRE(fw.valid); + CHECK(fw.base_paddr == 0x09020000ULL); + CHECK(fw.size == 0x18U); + + const Kernel::Boot::VirtioMmioList vlist = Kernel::Boot::find_virtio_mmio_devices(dtb_paddr); + REQUIRE(vlist.count == 2U); + CHECK(vlist.devices[0].irq_intid == 27U); + CHECK(vlist.devices[1].irq_intid == 52U); +} + +TEST_CASE("FDT handles 32-bit cells, invalid initrd, and empty memory fallback", "[fdt][cells]") { + SyntheticDtbBuilder builder{}; + builder.begin_node(""); + builder.prop_u32("#address-cells", 1U); + builder.prop_u32("#size-cells", 1U); + + builder.begin_node("chosen@0"); + builder.prop_u32("linux,initrd-start", 0x45000000U); + builder.prop_u32("linux,initrd-end", 0x45000000U); // end <= start -> invalid + builder.end_node(); + + builder.begin_node("virtio_mmio@a000000"); + builder.prop_string("compatible", "virtio,mmio"); + const uint32_t vreg[2] = {0x0A000000U, 0x200U}; + builder.prop_u32_array("reg", vreg, 2U); + builder.end_node(); + + builder.end_node(); + const uintptr_t dtb_paddr = builder.finalize(); + + // No memory nodes -> falls back to platform RAM base + FALLBACK_RAM_SIZE + const Kernel::Boot::MemoryMap mmap = Kernel::Boot::find_memory_regions(dtb_paddr); + CHECK(mmap.count == 1U); + CHECK_FALSE(Kernel::Boot::find_initrd(dtb_paddr).valid); + + const Kernel::Boot::VirtioMmioList vlist = Kernel::Boot::find_virtio_mmio_devices(dtb_paddr); + REQUIRE(vlist.count == 1U); + CHECK(vlist.devices[0].base_paddr == 0x0A000000ULL); + CHECK(vlist.devices[0].size == 0x200U); + CHECK_FALSE(vlist.devices[0].has_irq); } \ No newline at end of file diff --git a/tests/host/virtio_blk_test.cpp b/tests/host/virtio_blk_test.cpp index dccc70d..5e3859b 100644 --- a/tests/host/virtio_blk_test.cpp +++ b/tests/host/virtio_blk_test.cpp @@ -59,9 +59,9 @@ struct RecordedRequest { class SimulatedVirtioBlkBackend { public: explicit SimulatedVirtioBlkBackend(uint64_t capacity_sectors, uint16_t max_queue_size = 64U) - : m_storage(static_cast(capacity_sectors) * 512U, 0U), + : m_mmio_paddr(Kernel::MM::alloc_frame()), + m_storage(static_cast(capacity_sectors) * 512U, 0U), m_capacity_sectors(capacity_sectors) { - m_mmio_paddr = Kernel::MM::alloc_frame(); REQUIRE(m_mmio_paddr != 0U); m_mmio_regs = reinterpret_cast(Kernel::MM::phys_to_virt(m_mmio_paddr)); std::memset(const_cast(m_mmio_regs), 0, Arch::AArch64::PAGE_SIZE); @@ -81,6 +81,11 @@ class SimulatedVirtioBlkBackend { } } + SimulatedVirtioBlkBackend(const SimulatedVirtioBlkBackend&) = delete; + SimulatedVirtioBlkBackend& operator=(const SimulatedVirtioBlkBackend&) = delete; + SimulatedVirtioBlkBackend(SimulatedVirtioBlkBackend&&) = delete; + SimulatedVirtioBlkBackend& operator=(SimulatedVirtioBlkBackend&&) = delete; + void attach(VirtioBlkDevice& dev) noexcept { dev.set_host_notify_callback(&SimulatedVirtioBlkBackend::on_notify, this); } @@ -94,6 +99,7 @@ class SimulatedVirtioBlkBackend { } void set_forced_status(uint8_t status) noexcept { m_forced_status = status; } + void set_deferred_irq(bool deferred) noexcept { m_deferred_irq = deferred; } [[nodiscard]] const std::vector& history() const noexcept { return m_history; } [[nodiscard]] const std::vector& storage() const noexcept { return m_storage; } @@ -182,18 +188,22 @@ class SimulatedVirtioBlkBackend { } write_reg32(MMIO_INTERRUPT_STATUS, VIRTIO_MMIO_INT_VRING); - driver.handle_irq(); - CHECK(read_reg32(MMIO_INTERRUPT_STATUS) == 0U); + if (!m_deferred_irq) { + driver.handle_irq(); + CHECK((read_reg32(0x064U) & VIRTIO_MMIO_INT_VRING) != 0U); + write_reg32(MMIO_INTERRUPT_STATUS, 0U); + } } uintptr_t m_mmio_paddr{0U}; volatile uint8_t* m_mmio_regs{nullptr}; - std::vector m_storage{}; + std::vector m_storage; uint64_t m_capacity_sectors{0ULL}; uint16_t m_last_avail_idx{0U}; uint16_t m_used_idx{0U}; uint8_t m_forced_status{VIRTIO_BLK_S_OK}; - std::vector m_history{}; + bool m_deferred_irq{false}; + std::vector m_history; }; } // namespace @@ -245,9 +255,9 @@ TEST_CASE("VirtioBlkDevice 3-descriptor chains, LBA offsets, and error translati CHECK(wr.desc1_flags == VRING_DESC_F_NEXT); // WRITE clear for writes CHECK(wr.desc2_flags == VRING_DESC_F_WRITE); - CHECK(std::memcmp(backend.storage().data() + 4U * 512U, tx.data(), 1024U) == 0); - CHECK(backend.storage()[3U * 512U + 511U] == 0U); - CHECK(backend.storage()[6U * 512U] == 0U); + CHECK(std::memcmp(backend.storage().data() + (size_t{4U} * 512U), tx.data(), 1024U) == 0); + CHECK(backend.storage()[(size_t{3U} * 512U) + 511U] == 0U); + CHECK(backend.storage()[size_t{6U} * 512U] == 0U); std::array rx{}; REQUIRE(blk.read_sectors(4ULL, 2U, rx.data()) == 0); @@ -285,4 +295,104 @@ TEST_CASE("VirtioBlkDevice 3-descriptor chains, LBA offsets, and error translati blk.shutdown(); } + + SECTION("exercises bind_from_bus, init/bind errors, multi-chunk I/O, and IRQ edge cases") { + // Uninitialized operations fail with -EINVAL + VirtioBlkDevice uninit_blk{}; + std::array scratch{}; + CHECK(uninit_blk.read_sectors(0ULL, 1U, scratch.data()) == -EINVAL); + CHECK(uninit_blk.write_sectors(0ULL, 1U, scratch.data()) == -EINVAL); + CHECK(uninit_blk.flush() == -EINVAL); + uninit_blk.handle_irq(); // null/uninitialized slot + VirtioBlkDevice::irq_trampoline(0U, nullptr); + + // init() fails on invalid magic + SimulatedVirtioBlkBackend bad_magic(/*capacity_sectors=*/8ULL); + bad_magic.write_reg32(MMIO_MAGIC_VALUE, 0U); + CHECK_FALSE(uninit_blk.init(bad_magic.mmio_paddr())); + + // init() fails on zero capacity + SimulatedVirtioBlkBackend zero_cap(/*capacity_sectors=*/0ULL); + CHECK_FALSE(uninit_blk.init(zero_cap.mmio_paddr())); + + // bind() fails on wrong device_id and zero queue size + VirtioMmioSlot slot{}; + SimulatedVirtioBlkBackend wrong_dev(/*capacity_sectors=*/8ULL); + wrong_dev.write_reg32(MMIO_DEVICE_ID, VIRTIO_DEV_ID_NET); + REQUIRE(slot.probe_slot(VirtioMmioSlotConfig{ + .slot_index = 0U, + .base_paddr = wrong_dev.mmio_paddr(), + .region_size = Arch::AArch64::PAGE_SIZE, + .spi_irq = 0U, + })); + CHECK_FALSE(VirtioBlkDevice::bind_from_bus(slot, nullptr)); + CHECK_FALSE(VirtioBlkDevice::bind_from_bus(slot, &uninit_blk)); + + SimulatedVirtioBlkBackend zero_q(/*capacity_sectors=*/8ULL, /*max_queue_size=*/0U); + VirtioMmioSlot slot_zq{}; + REQUIRE(slot_zq.probe_slot(VirtioMmioSlotConfig{ + .slot_index = 1U, + .base_paddr = zero_q.mmio_paddr(), + .region_size = Arch::AArch64::PAGE_SIZE, + .spi_irq = 0U, + })); + CHECK_FALSE(uninit_blk.bind(slot_zq)); + + // Valid bind_from_bus, re-bind, re-init, multi-chunk (> MAX_SECTORS_PER_CHUNK), and + // deferred IRQ + SimulatedVirtioBlkBackend backend(/*capacity_sectors=*/16ULL); + backend.write_reg32(MMIO_DEVICE_FEATURES, 1U); + VirtioMmioSlot valid_slot{}; + REQUIRE(valid_slot.probe_slot(VirtioMmioSlotConfig{ + .slot_index = 2U, + .base_paddr = backend.mmio_paddr(), + .region_size = Arch::AArch64::PAGE_SIZE, + .spi_irq = 0U, + })); + REQUIRE(VirtioBlkDevice::bind_from_bus(valid_slot, &uninit_blk)); + + SimulatedVirtioBlkBackend backend2(/*capacity_sectors=*/16ULL); + backend2.write_reg32(MMIO_DEVICE_FEATURES, 1U); + VirtioMmioSlot valid_slot2{}; + REQUIRE(valid_slot2.probe_slot(VirtioMmioSlotConfig{ + .slot_index = 3U, + .base_paddr = backend2.mmio_paddr(), + .region_size = Arch::AArch64::PAGE_SIZE, + .spi_irq = 0U, + })); + REQUIRE(uninit_blk.bind(valid_slot2)); // re-bind shuts down cleanly + + SimulatedVirtioBlkBackend backend3(/*capacity_sectors=*/16ULL); + backend3.write_reg32(MMIO_DEVICE_FEATURES, 1U); + REQUIRE(uninit_blk.init(backend3.mmio_paddr())); // re-init shuts down cleanly + + backend3.attach(uninit_blk); + backend3.set_deferred_irq(true); + + constexpr size_t kMultiCount = 8U; // > MAX_SECTORS_PER_CHUNK (7) + std::array multi_tx{}; + for (size_t i = 0U; i < multi_tx.size(); ++i) { + multi_tx[i] = static_cast(i & 0xFFU); + } + REQUIRE(uninit_blk.write_sectors(0ULL, kMultiCount, multi_tx.data()) == 0); + + std::array multi_rx{}; + REQUIRE(uninit_blk.read_sectors(0ULL, kMultiCount, multi_rx.data()) == 0); + CHECK(std::memcmp(multi_rx.data(), multi_tx.data(), multi_tx.size()) == 0); + + // Flush OK & unknown status -> -EIO + CHECK(uninit_blk.flush() == 0); + backend3.set_forced_status(0x7FU); + CHECK(uninit_blk.write_sectors(0ULL, 1U, multi_tx.data()) == -EIO); + CHECK(uninit_blk.read_sectors(0ULL, 1U, multi_rx.data()) == -EIO); + + // handle_irq with 0 and non-VRING status, plus irq_trampoline + backend3.write_reg32(MMIO_INTERRUPT_STATUS, 0U); + uninit_blk.handle_irq(); + backend3.write_reg32(MMIO_INTERRUPT_STATUS, VIRTIO_MMIO_INT_CONFIG); + VirtioBlkDevice::irq_trampoline(0U, &uninit_blk); + CHECK((backend3.read_reg32(0x064U) & VIRTIO_MMIO_INT_CONFIG) != 0U); + + uninit_blk.shutdown(); + } } \ No newline at end of file From 437310f96691241f137e39b30d4cecfe1f94c0ff Mon Sep 17 00:00:00 2001 From: marcobuschini Date: Fri, 4 Dec 2026 11:24:05 +0000 Subject: [PATCH 4/4] test(coverage): expand MM, VFS, Socket, and Loader branch coverage (#261) - Expand `tests/host/socket_syscall_test.cpp` for accept/accept4, getsockname/ getpeername, sockopt, shutdown, DGRAM addressing, and multi-iovec sendmsg/recvmsg - Expand `tests/host/vma_test.cpp` for `sys_brk`, `sys_mmap`, `sys_munmap`, `sys_mprotect` error/boundary paths, and `AddressSpace::clone()` with `MAP_SHARED` - Expand `tests/host/elf_interp_test.cpp` for `load_elf()` error/OOM/`PT_PHDR` paths and non-PIE `load_elf_interpreter()` - Expand `tests/host/ext2_test.cpp` for mount errors, `O_EXCL`/`O_TRUNC`/`O_APPEND`, `vfs_lseek`, cross-directory `vfs_rename`, `vfs_readdir`, and VFS error codes --- tests/host/elf_interp_test.cpp | 74 +++++++++++ tests/host/ext2_test.cpp | 88 +++++++++++++ tests/host/socket_syscall_test.cpp | 200 +++++++++++++++++++++++++++++ tests/host/vma_test.cpp | 118 +++++++++++++++++ 4 files changed, 480 insertions(+) diff --git a/tests/host/elf_interp_test.cpp b/tests/host/elf_interp_test.cpp index bf0b09b..2df8a1d 100644 --- a/tests/host/elf_interp_test.cpp +++ b/tests/host/elf_interp_test.cpp @@ -321,3 +321,77 @@ TEST_CASE("load_elf handles shared boundary page and rolls back cleanly on mappi CHECK(overflow_res.error() == Kernel::Loader::ElfStatus::SegmentOutOfBounds); } } + +TEST_CASE("elf_loader PT_PHDR, OOM, and invalid ELF paths", "[elf][loader]") { + init_interp_test_env(); + + // InvalidElf + const uint8_t bad_bytes[16]{}; + auto bad_res = Kernel::Loader::load_elf(bad_bytes, sizeof(bad_bytes)); + REQUIRE(bad_res.is_err()); + CHECK(bad_res.error() == Kernel::Loader::ElfLoaderError::InvalidElf); + + // NoLoadSegments (valid ET_EXEC header with 1 PT_NULL phdr, 0 PT_LOAD) + std::array zero_load{}; + auto* ehdr = reinterpret_cast(zero_load.data()); + ehdr->e_ident[0] = 0x7FU; + ehdr->e_ident[1] = 'E'; + ehdr->e_ident[2] = 'L'; + ehdr->e_ident[3] = 'F'; + ehdr->e_ident[4] = Kernel::Loader::ELFCLASS64; + ehdr->e_ident[5] = Kernel::Loader::ELFDATA2LSB; + ehdr->e_ident[6] = Kernel::Loader::EV_CURRENT; + ehdr->e_type = Kernel::Loader::ET_EXEC; + ehdr->e_machine = HAL::get_platform_info().elf_machine; + ehdr->e_version = 1U; + ehdr->e_entry = 0x400000ULL; + ehdr->e_phoff = sizeof(Kernel::Loader::Elf64_Ehdr); + ehdr->e_ehsize = sizeof(Kernel::Loader::Elf64_Ehdr); + ehdr->e_phentsize = sizeof(Kernel::Loader::Elf64_Phdr); + ehdr->e_phnum = 1U; + auto no_seg_res = Kernel::Loader::load_elf(zero_load.data(), zero_load.size()); + REQUIRE(no_seg_res.is_err()); + CHECK(no_seg_res.error() == Kernel::Loader::ElfLoaderError::NoLoadSegments); + + // PT_PHDR + PT_LOAD + OutOfMemory (fail_create_root) + ehdr->e_phnum = 2U; + auto* phdrs = reinterpret_cast(zero_load.data() + ehdr->e_phoff); + phdrs[0].p_type = Kernel::Loader::PT_PHDR; + phdrs[0].p_offset = ehdr->e_phoff; + phdrs[0].p_vaddr = 0x400040ULL; + phdrs[0].p_filesz = 2U * sizeof(Kernel::Loader::Elf64_Phdr); + phdrs[0].p_memsz = 2U * sizeof(Kernel::Loader::Elf64_Phdr); + phdrs[0].p_align = 8U; + + phdrs[1].p_type = Kernel::Loader::PT_LOAD; + phdrs[1].p_flags = Kernel::Loader::PF_R | Kernel::Loader::PF_X; + phdrs[1].p_offset = 0U; + phdrs[1].p_vaddr = 0x400000ULL; + phdrs[1].p_filesz = 0x100U; + phdrs[1].p_memsz = 0x100U; + phdrs[1].p_align = 0x1000U; + + HostTest::set_fail_create_root(true); + auto oom_res = Kernel::Loader::load_elf(zero_load.data(), zero_load.size()); + HostTest::set_fail_create_root(false); + REQUIRE(oom_res.is_err()); + CHECK(oom_res.error() == Kernel::Loader::ElfLoaderError::OutOfMemory); + + auto ok_res = Kernel::Loader::load_elf(zero_load.data(), zero_load.size()); + REQUIRE(ok_res.is_ok()); + CHECK(ok_res.value().phdr_vaddr == 0x400040ULL); + + // load_elf_interpreter with non-PIE ET_EXEC interpreter + std::array interp_exec{}; + std::memcpy(interp_exec.data(), zero_load.data(), zero_load.size()); + auto* interp_phdrs = reinterpret_cast( + interp_exec.data() + sizeof(Kernel::Loader::Elf64_Ehdr)); + interp_phdrs[0].p_vaddr = 0x600040ULL; + interp_phdrs[1].p_vaddr = 0x600000ULL; + auto interp_res = Kernel::Loader::load_elf_interpreter( + interp_exec.data(), interp_exec.size(), ok_res.value().address_space, 0x500000ULL); + REQUIRE(interp_res.is_ok()); + CHECK(interp_res.value().base_addr == 0x600000ULL); + + ok_res.value().address_space.destroy(); +} diff --git a/tests/host/ext2_test.cpp b/tests/host/ext2_test.cpp index 3c29070..791746a 100644 --- a/tests/host/ext2_test.cpp +++ b/tests/host/ext2_test.cpp @@ -244,4 +244,92 @@ TEST_CASE("ext2 mkdir, dirent insertion, rec_len coalescing on unlink, rename, a REQUIRE(Kernel::FS::vfs_namei("/mnt/disk/sub", nullptr, &dentry) == Kernel::FS::kEnoent); REQUIRE(Kernel::FS::ext2_umount("/mnt/disk", superblock) == Kernel::FS::kOk); +} + +TEST_CASE("ext2 truncate, readdir, lseek, cross-dir rename, symlinks, and mount errors", + "[ext2][vfs]") { + setup_vfs_with_rootfs(); + + // Null / invalid mount parameters + Kernel::FS::Superblock* bad_sb = nullptr; + REQUIRE(Kernel::FS::ext2_mount(nullptr, "/mnt/disk", &bad_sb) != Kernel::FS::kOk); + + RamBlockDevice bad_dev(kTestDiskBytes); + REQUIRE(Kernel::FS::ext2_mount(&bad_dev, "/mnt/disk", &bad_sb) != Kernel::FS::kOk); // bad magic + + RamBlockDevice dev(kTestDiskBytes); + format_ext2_1k(dev); + Kernel::FS::Superblock* sb = nullptr; + REQUIRE(Kernel::FS::ext2_mount(&dev, "/mnt/disk", &sb) == Kernel::FS::kOk); + + // O_CREAT | O_EXCL, O_APPEND, lseek, truncate, readdir + Kernel::FS::File* f = nullptr; + REQUIRE(Kernel::FS::vfs_open("/mnt/disk/data.bin", + Kernel::FS::kOpenReadWrite | Kernel::FS::kOpenCreate | + Kernel::FS::kOpenExcl, + 0644U, &f) == Kernel::FS::kOk); + // Write 16 KiB (spans direct + singly-indirect blocks) + std::vector big(16384U, 0xABU); + REQUIRE(Kernel::FS::vfs_write(f, big.data(), big.size()) == 16384); + REQUIRE(Kernel::FS::vfs_lseek(f, 0, Kernel::FS::SeekWhence::kSet) == 0); + REQUIRE(Kernel::FS::vfs_lseek(f, 100, Kernel::FS::SeekWhence::kCur) == 100); + REQUIRE(Kernel::FS::vfs_lseek(f, 0, Kernel::FS::SeekWhence::kEnd) == 16384); + REQUIRE(Kernel::FS::vfs_close(f) == Kernel::FS::kOk); + + // O_EXCL fails when file exists + REQUIRE(Kernel::FS::vfs_open("/mnt/disk/data.bin", + Kernel::FS::kOpenReadWrite | Kernel::FS::kOpenCreate | + Kernel::FS::kOpenExcl, + 0644U, &f) == Kernel::FS::kEexist); + + // O_TRUNC frees indirect + data blocks + REQUIRE(Kernel::FS::vfs_open("/mnt/disk/data.bin", + Kernel::FS::kOpenReadWrite | Kernel::FS::kOpenTrunc, 0644U, + &f) == Kernel::FS::kOk); + REQUIRE(Kernel::FS::vfs_write(f, "xy", 2U) == 2); + REQUIRE(Kernel::FS::vfs_close(f) == Kernel::FS::kOk); + + // O_APPEND + REQUIRE(Kernel::FS::vfs_open("/mnt/disk/data.bin", + Kernel::FS::kOpenReadWrite | Kernel::FS::kOpenAppend, 0644U, + &f) == Kernel::FS::kOk); + REQUIRE(Kernel::FS::vfs_write(f, "z", 1U) == 1); + REQUIRE(Kernel::FS::vfs_close(f) == Kernel::FS::kOk); + Kernel::FS::Dentry* d_data = nullptr; + REQUIRE(Kernel::FS::vfs_namei("/mnt/disk/data.bin", nullptr, &d_data) == Kernel::FS::kOk); + CHECK(d_data->get_inode()->get_size() == 3U); + d_data->release(); + + // Cross-directory rename + REQUIRE(Kernel::FS::vfs_mkdir("/mnt/disk/d1", 0755U) == Kernel::FS::kOk); + REQUIRE(Kernel::FS::vfs_mkdir("/mnt/disk/d2", 0755U) == Kernel::FS::kOk); + REQUIRE(Kernel::FS::vfs_rename("/mnt/disk/data.bin", "/mnt/disk/d1/moved.bin") == + Kernel::FS::kOk); + REQUIRE(Kernel::FS::vfs_rename("/mnt/disk/d1/moved.bin", "/mnt/disk/d2/moved2.bin") == + Kernel::FS::kOk); + + // readdir on /mnt/disk/d2 + Kernel::FS::File* dir = nullptr; + REQUIRE(Kernel::FS::vfs_open("/mnt/disk/d2", + Kernel::FS::kOpenReadOnly | Kernel::FS::kOpenDirectory, 0U, + &dir) == Kernel::FS::kOk); + Kernel::FS::DirEntryInfo entry{}; + size_t dirent_count = 0U; + while (Kernel::FS::vfs_readdir(dir, &entry) == Kernel::FS::kOk) { + ++dirent_count; + } + CHECK(dirent_count == 1U); // "moved2.bin" ("." and ".." skipped by ext2 readdir) + REQUIRE(Kernel::FS::vfs_close(dir) == Kernel::FS::kOk); + + // Error paths: open dir for write -> EISDIR, mkdir existing -> EEXIST, unlink dir -> EISDIR + REQUIRE(Kernel::FS::vfs_open("/mnt/disk/d2", Kernel::FS::kOpenWriteOnly, 0U, &f) == + Kernel::FS::kEisdir); + REQUIRE(Kernel::FS::vfs_mkdir("/mnt/disk/d2", 0755U) == Kernel::FS::kEexist); + REQUIRE(Kernel::FS::vfs_unlink("/mnt/disk/d2") == Kernel::FS::kEisdir); + REQUIRE(Kernel::FS::vfs_rmdir("/mnt/disk/d2/moved2.bin") == Kernel::FS::kEnotdir); + + REQUIRE(Kernel::FS::vfs_unlink("/mnt/disk/d2/moved2.bin") == Kernel::FS::kOk); + REQUIRE(Kernel::FS::vfs_rmdir("/mnt/disk/d2") == Kernel::FS::kOk); + REQUIRE(Kernel::FS::vfs_rmdir("/mnt/disk/d1") == Kernel::FS::kOk); + REQUIRE(Kernel::FS::ext2_umount("/mnt/disk", sb) == Kernel::FS::kOk); } \ No newline at end of file diff --git a/tests/host/socket_syscall_test.cpp b/tests/host/socket_syscall_test.cpp index 2c0ea11..467d8fa 100644 --- a/tests/host/socket_syscall_test.cpp +++ b/tests/host/socket_syscall_test.cpp @@ -349,3 +349,203 @@ TEST_CASE("Socket syscalls support stream/dgram transfer, sendmsg/recvmsg, socko const size_t final_slabs = Kernel::MM::heap_get_stats().slab_pages; CHECK((final_free + final_slabs) == (baseline_free + baseline_slabs)); } + +TEST_CASE("Socket syscalls cover accept, dgram addr, sockopt, shutdown, and iovec error paths", + "[syscalls][af_unix][errors]") { + init_socket_syscall_env(); + const size_t baseline_free = Kernel::MM::pfa_free_pages_count(); + const size_t baseline_slabs = Kernel::MM::heap_get_stats().slab_pages; + + auto* const proc = Kernel::Process::Process::create(0U); + REQUIRE(proc != nullptr); + auto as_res = Kernel::MM::AddressSpace::create(); + REQUIRE(as_res.is_ok()); + proc->address_space() = static_cast(as_res.value()); + + auto* const prev_proc = Kernel::Process::Process::current(); + Kernel::Process::Process::set_current(proc); + + constexpr uintptr_t USER_PAGE = 0x28000000ULL; + const uintptr_t user_paddr = Kernel::MM::alloc_frame(); + REQUIRE(user_paddr != 0U); + REQUIRE(proc->address_space().map_user_page(USER_PAGE, user_paddr, + HAL::PageFlags::User | HAL::PageFlags::Read | + HAL::PageFlags::Write)); + + // socketpair error paths + CHECK(sys_socketpair(AF_UNIX, SOCK_STREAM, 0, USER_PAGE + 0x4000U) == ERR_EFAULT); + CHECK(sys_socketpair(999, SOCK_STREAM, 0, USER_PAGE) == ERR_EAFNOSUPPORT); + + // Non-blocking stream + accept / accept4 / getsockname / getpeername / shutdown + const auto nb_stream = + static_cast(static_cast(SOCK_STREAM) | kSockNonblockFlag); + const int64_t srv = sys_socket(AF_UNIX, nb_stream, 0); + const int64_t cli = sys_socket(AF_UNIX, nb_stream, 0); + REQUIRE(srv >= 0); + REQUIRE(cli >= 0); + + const linux_sockaddr_un sun = make_sun("/tmp/sc_err.sock"); + REQUIRE(Kernel::MM::copy_to_user(proc->address_space(), USER_PAGE, &sun, sizeof(sun)) == 0); + REQUIRE(sys_bind(static_cast(srv), USER_PAGE, sizeof(sun)) == 0); + REQUIRE(sys_listen(static_cast(srv), 2) == 0); + + // accept4 with invalid flags and EAGAIN on non-blocking + CHECK(sys_accept4(static_cast(srv), 0U, 0U, 0x1234) == ERR_EINVAL); + const int64_t nb_srv = sys_socket( + AF_UNIX, static_cast(static_cast(SOCK_STREAM) | kSockNonblockFlag), 0); + REQUIRE(nb_srv >= 0); + const linux_sockaddr_un nb_sun = make_sun("/tmp/sc_nb_err.sock"); + REQUIRE(Kernel::MM::copy_to_user(proc->address_space(), USER_PAGE + 0x80U, &nb_sun, + sizeof(nb_sun)) == 0); + REQUIRE(sys_bind(static_cast(nb_srv), USER_PAGE + 0x80U, sizeof(nb_sun)) == 0); + REQUIRE(sys_listen(static_cast(nb_srv), 2) == 0); + CHECK(sys_accept4(static_cast(nb_srv), 0U, 0U, 0) == ERR_EAGAIN); + + // Connect + accept(3-arg) with null addr + REQUIRE(sys_connect(static_cast(cli), USER_PAGE, sizeof(sun)) == 0); + const int64_t acc = sys_accept(static_cast(srv), 0U, 0U); + REQUIRE(acc >= 0); + + // getsockname & getpeername (valid + bad pointers) + const linux_socklen_t cap = sizeof(linux_sockaddr_un); + REQUIRE(Kernel::MM::copy_to_user(proc->address_space(), USER_PAGE + 0x180U, &cap, + sizeof(cap)) == 0); + CHECK(sys_getsockname(static_cast(srv), USER_PAGE + 0x100U, USER_PAGE + 0x180U) == 0); + CHECK(sys_getpeername(static_cast(cli), USER_PAGE + 0x100U, USER_PAGE + 0x180U) == 0); + CHECK(sys_getsockname(static_cast(srv), USER_PAGE + 0x4000U, USER_PAGE + 0x180U) == + ERR_EFAULT); + CHECK(sys_getpeername(static_cast(srv), USER_PAGE + 0x100U, USER_PAGE + 0x180U) == + ERR_ENOTCONN); + + // getsockopt kSoRcvBuf & error paths + int32_t opt_out = 0; + linux_socklen_t opt_len = sizeof(opt_out); + REQUIRE(Kernel::MM::copy_to_user(proc->address_space(), USER_PAGE + 0x240U, &opt_len, + sizeof(opt_len)) == 0); + CHECK(sys_getsockopt(static_cast(cli), kSolSocket, kSoRcvBuf, USER_PAGE + 0x200U, + USER_PAGE + 0x240U) == 0); + REQUIRE(Kernel::MM::copy_from_user(proc->address_space(), &opt_out, USER_PAGE + 0x200U, + sizeof(opt_out)) == 0); + CHECK(opt_out > 0); + + CHECK(sys_getsockopt(static_cast(cli), 999, kSoType, USER_PAGE + 0x200U, + USER_PAGE + 0x240U) == ERR_ENOPROTOOPT); + CHECK(sys_getsockopt(static_cast(cli), kSolSocket, 999, USER_PAGE + 0x200U, + USER_PAGE + 0x240U) == ERR_ENOPROTOOPT); + CHECK(sys_setsockopt(static_cast(cli), 999, kSoRcvBuf, USER_PAGE + 0x200U, + sizeof(int32_t)) == ERR_ENOPROTOOPT); + CHECK(sys_setsockopt(static_cast(cli), kSolSocket, 999, USER_PAGE + 0x200U, + sizeof(int32_t)) == ERR_ENOPROTOOPT); + CHECK(sys_setsockopt(static_cast(cli), kSolSocket, kSoRcvBuf, USER_PAGE + 0x200U, + 1U) == ERR_EINVAL); + + // shutdown edge cases + CHECK(sys_shutdown(999U, SHUT_RD) == ERR_EBADF); + CHECK(sys_shutdown(0U, SHUT_RD) == ERR_ENOTSOCK); + CHECK(sys_shutdown(static_cast(cli), 99) == ERR_EINVAL); + CHECK(sys_shutdown(static_cast(cli), SHUT_WR) == 0); + CHECK(sys_recvfrom(static_cast(acc), USER_PAGE + 0x300U, 16ULL, MSG_DONTWAIT, 0U, + 0U) == 0); // EOF after peer SHUT_WR + + // Unconnected SOCK_DGRAM sendto/recvfrom with dest_addr/src_addr & MSG_DONTWAIT + const auto nb_dgram = + static_cast(static_cast(SOCK_DGRAM) | kSockNonblockFlag); + const int64_t dg_srv = sys_socket(AF_UNIX, nb_dgram, 0); + const int64_t dg_cli = sys_socket(AF_UNIX, nb_dgram, 0); + REQUIRE(dg_srv >= 0); + REQUIRE(dg_cli >= 0); + const linux_sockaddr_un dg_sun = make_sun("/tmp/sc_dg_err.sock"); + REQUIRE(Kernel::MM::copy_to_user(proc->address_space(), USER_PAGE + 0x300U, &dg_sun, + sizeof(dg_sun)) == 0); + REQUIRE(sys_bind(static_cast(dg_srv), USER_PAGE + 0x300U, sizeof(dg_sun)) == 0); + + // Empty recvfrom with MSG_DONTWAIT -> EAGAIN + CHECK(sys_recvfrom(static_cast(dg_srv), USER_PAGE + 0x380U, 16ULL, MSG_DONTWAIT, 0U, + 0U) == ERR_EAGAIN); + + // sendto with dest_addr + recvfrom with src_addr + static constexpr char kDgPayload[] = "dg"; + REQUIRE(Kernel::MM::copy_to_user(proc->address_space(), USER_PAGE + 0x360U, kDgPayload, 2U) == + 0); + CHECK(sys_sendto(static_cast(dg_cli), USER_PAGE + 0x360U, 2ULL, 0, USER_PAGE + 0x300U, + sizeof(dg_sun)) == 2); + CHECK(sys_recvfrom(static_cast(dg_srv), USER_PAGE + 0x380U, 16ULL, MSG_DONTWAIT, + USER_PAGE + 0x100U, USER_PAGE + 0x180U) == 2); + + // sendto / recvfrom error paths: bad buf, len == 0 + CHECK(sys_sendto(static_cast(dg_cli), USER_PAGE + 0x4000U, 4ULL, 0, 0U, 0ULL) == + ERR_EFAULT); + CHECK(sys_recvfrom(static_cast(dg_srv), USER_PAGE + 0x4000U, 4ULL, MSG_DONTWAIT, 0U, + 0U) == ERR_EFAULT); + CHECK(sys_sendto(static_cast(dg_cli), USER_PAGE + 0x360U, 0ULL, 0, USER_PAGE + 0x300U, + sizeof(dg_sun)) == 0); + CHECK(sys_recvfrom(static_cast(dg_srv), USER_PAGE + 0x380U, 16ULL, MSG_DONTWAIT, 0U, + 0U) == 0); + + // sendmsg / recvmsg error paths: bad msg ptr, iovlen == 0, multi-iovec with msg_name + CHECK(sys_sendmsg(static_cast(dg_cli), USER_PAGE + 0x4000U, 0) == ERR_EFAULT); + CHECK(sys_recvmsg(static_cast(dg_srv), USER_PAGE + 0x4000U, MSG_DONTWAIT) == + ERR_EFAULT); + + const linux_iovec multi_iov[2]{ + {.iov_base = USER_PAGE + 0x360U, .iov_len = 1U}, + {.iov_base = USER_PAGE + 0x361U, .iov_len = 1U}, + }; + REQUIRE(Kernel::MM::copy_to_user(proc->address_space(), USER_PAGE + 0x500U, multi_iov, + sizeof(multi_iov)) == 0); + const linux_msghdr dg_tx_msg{ + .msg_name = reinterpret_cast(USER_PAGE + 0x300U), + .msg_namelen = sizeof(dg_sun), + ._pad0 = 0U, + .msg_iov = reinterpret_cast(USER_PAGE + 0x500U), + .msg_iovlen = 2U, + .msg_control = nullptr, + .msg_controllen = 0U, + .msg_flags = 0, + ._pad1 = 0U, + }; + REQUIRE(Kernel::MM::copy_to_user(proc->address_space(), USER_PAGE + 0x540U, &dg_tx_msg, + sizeof(dg_tx_msg)) == 0); + CHECK(sys_sendmsg(static_cast(dg_cli), USER_PAGE + 0x540U, 0) == 2); + + const linux_msghdr dg_rx_msg{ + .msg_name = reinterpret_cast(USER_PAGE + 0x100U), + .msg_namelen = sizeof(linux_sockaddr_un), + ._pad0 = 0U, + .msg_iov = reinterpret_cast(USER_PAGE + 0x500U), + .msg_iovlen = 2U, + .msg_control = nullptr, + .msg_controllen = 0U, + .msg_flags = 0, + ._pad1 = 0U, + }; + REQUIRE(Kernel::MM::copy_to_user(proc->address_space(), USER_PAGE + 0x580U, &dg_rx_msg, + sizeof(dg_rx_msg)) == 0); + CHECK(sys_recvmsg(static_cast(dg_srv), USER_PAGE + 0x580U, MSG_DONTWAIT) == 1); + CHECK(sys_recvmsg(static_cast(dg_srv), USER_PAGE + 0x580U, MSG_DONTWAIT) == 1); + CHECK(sys_recvmsg(static_cast(dg_srv), USER_PAGE + 0x580U, MSG_DONTWAIT) == + ERR_EAGAIN); + + (void)sys_close(static_cast(dg_cli)); + (void)sys_close(static_cast(dg_srv)); + (void)sys_close(static_cast(acc)); + (void)sys_close(static_cast(cli)); + (void)sys_close(static_cast(srv)); + (void)sys_close(static_cast(nb_srv)); + (void)vfs_unlink("/tmp/sc_err.sock"); + (void)vfs_unlink("/tmp/sc_nb_err.sock"); + (void)vfs_unlink("/tmp/sc_dg_err.sock"); + + (void)proc->address_space().unmap_user_page(USER_PAGE); + if (Kernel::MM::page_ref_count(user_paddr) > 1U) { + Kernel::MM::page_put(user_paddr); + } + Kernel::MM::free_frame(user_paddr); + Kernel::Process::Process::set_current(prev_proc); + Kernel::Process::Process::destroy(*proc); + vfs_reset(); + + const size_t final_free = Kernel::MM::pfa_free_pages_count(); + const size_t final_slabs = Kernel::MM::heap_get_stats().slab_pages; + CHECK((final_free + final_slabs) == (baseline_free + baseline_slabs)); +} diff --git a/tests/host/vma_test.cpp b/tests/host/vma_test.cpp index fc4e666..8f0f9ab 100644 --- a/tests/host/vma_test.cpp +++ b/tests/host/vma_test.cpp @@ -778,6 +778,124 @@ TEST_CASE("File-backed VMA page cache faulting, MAP_PRIVATE CoW isolation, and s 1U) == 0); CHECK(verify_priv == 0x77U); + Kernel::Process::Process::set_current(prev_proc); + Kernel::Process::Process::destroy(*proc); + Kernel::FS::page_cache_reset(); + Kernel::FS::vfs_reset(); +} + +TEST_CASE("MemorySyscalls brk, mmap, munmap, mprotect edge cases and null-current guards", + "[vma][syscalls][mm]") { + init_vma_test_env(); + + // Null current process guards + auto* const prev_proc = Kernel::Process::Process::current(); + Kernel::Process::Process::set_current(nullptr); + CHECK(Kernel::Syscalls::sys_brk(0x400000U) == 0); + CHECK( + Kernel::Syscalls::sys_mmap(0U, 4096U, Kernel::Syscalls::PROT_READ, + Kernel::Syscalls::MAP_PRIVATE | Kernel::Syscalls::MAP_ANONYMOUS, + static_cast(-1), 0U) == Kernel::Syscalls::ERR_EINVAL); + CHECK(Kernel::Syscalls::sys_munmap(0x40000000U, 4096U) == Kernel::Syscalls::ERR_EINVAL); + CHECK(Kernel::Syscalls::sys_mprotect(0x40000000U, 4096U, Kernel::Syscalls::PROT_READ) == + Kernel::Syscalls::ERR_EINVAL); + + auto* const proc = Kernel::Process::Process::create(0U); + REQUIRE(proc != nullptr); + auto as_res = Kernel::MM::AddressSpace::create(); + REQUIRE(as_res.is_ok()); + proc->address_space() = static_cast(as_res.value()); + Kernel::Process::Process::set_current(proc); + + // sys_brk growth, ceiling, and shrink + proc->set_brk_start(0x400000U); + proc->set_brk_current(0x400000U); + proc->set_mmap_next_vaddr(0x40000000U); + CHECK(Kernel::Syscalls::sys_brk(0U) == 0x400000); + CHECK(Kernel::Syscalls::sys_brk(0x300000U) == 0x400000); + CHECK(Kernel::Syscalls::sys_brk(0x50000000U) == 0x400000); // > brk_ceiling + CHECK(Kernel::Syscalls::sys_brk(0x403000U) == 0x403000); + CHECK(Kernel::Syscalls::sys_brk(0x401000U) == 0x401000); // shrink unmaps pages + + // sys_mmap validation & error paths + CHECK( + Kernel::Syscalls::sys_mmap(0U, 0U, Kernel::Syscalls::PROT_READ, + Kernel::Syscalls::MAP_PRIVATE | Kernel::Syscalls::MAP_ANONYMOUS, + static_cast(-1), 0U) == Kernel::Syscalls::ERR_EINVAL); + CHECK(Kernel::Syscalls::sys_mmap( + 0U, 4096U, 0x99U, Kernel::Syscalls::MAP_PRIVATE | Kernel::Syscalls::MAP_ANONYMOUS, + static_cast(-1), 0U) == Kernel::Syscalls::ERR_EINVAL); + CHECK(Kernel::Syscalls::sys_mmap(0U, 4096U, Kernel::Syscalls::PROT_READ, + Kernel::Syscalls::MAP_SHARED | Kernel::Syscalls::MAP_PRIVATE | + Kernel::Syscalls::MAP_ANONYMOUS, + static_cast(-1), + 0U) == Kernel::Syscalls::ERR_EINVAL); + // Non-anon with negative fd / huge fd / bad fd + CHECK(Kernel::Syscalls::sys_mmap(0U, 4096U, Kernel::Syscalls::PROT_READ, + Kernel::Syscalls::MAP_PRIVATE, static_cast(-1), + 0U) == Kernel::Syscalls::ERR_EINVAL); + CHECK(Kernel::Syscalls::sys_mmap(0U, 4096U, Kernel::Syscalls::PROT_READ, + Kernel::Syscalls::MAP_PRIVATE, 0x100000000ULL, + 0U) == Kernel::Syscalls::ERR_EBADF); + CHECK(Kernel::Syscalls::sys_mmap(0U, 4096U, Kernel::Syscalls::PROT_READ, + Kernel::Syscalls::MAP_PRIVATE, 99U, + 0U) == Kernel::Syscalls::ERR_EBADF); + + // Read-only fd 0 with PROT_WRITE | MAP_SHARED -> EACCES + CHECK(Kernel::Syscalls::sys_mmap(0U, 4096U, Kernel::Syscalls::PROT_WRITE, + Kernel::Syscalls::MAP_SHARED, 0U, + 0U) == Kernel::Syscalls::ERR_EACCES); + + // MAP_FIXED out of valid arena -> ENOMEM + CHECK( + Kernel::Syscalls::sys_mmap(0x10000U, 4096U, Kernel::Syscalls::PROT_READ, + Kernel::Syscalls::MAP_PRIVATE | Kernel::Syscalls::MAP_ANONYMOUS | + Kernel::Syscalls::MAP_FIXED, + static_cast(-1), 0U) == Kernel::Syscalls::ERR_ENOMEM); + + // High arena fallback when lower arena is exhausted (mmap_next_vaddr == MMAP_ARENA_FLOOR) + proc->set_mmap_next_vaddr(Kernel::Syscalls::MMAP_ARENA_FLOOR); + const int64_t high_map = Kernel::Syscalls::sys_mmap( + 0U, 8192U, Kernel::Syscalls::PROT_READ | Kernel::Syscalls::PROT_WRITE, + Kernel::Syscalls::MAP_PRIVATE | Kernel::Syscalls::MAP_ANONYMOUS, static_cast(-1), + 0U); + REQUIRE(high_map >= 0x80000000LL); + // Demand-zero page + mprotect(PROT_NONE) + mprotect(PROT_EXEC) + REQUIRE(proc->address_space().map_demand_zero(static_cast(high_map), + HAL::PageFlags::User | HAL::PageFlags::Read | + HAL::PageFlags::Write)); + CHECK(Kernel::Syscalls::sys_mprotect(static_cast(high_map), 4096U, + Kernel::Syscalls::PROT_NONE) == 0); + CHECK(Kernel::Syscalls::sys_mprotect(static_cast(high_map), 4096U, + Kernel::Syscalls::PROT_READ | + Kernel::Syscalls::PROT_EXEC) == 0); + CHECK(Kernel::Syscalls::sys_munmap(static_cast(high_map), 8192U) == 0); + + // sys_munmap & sys_mprotect error branches + CHECK(Kernel::Syscalls::sys_munmap(0x1000U, 4096U) == Kernel::Syscalls::ERR_EINVAL); + CHECK(Kernel::Syscalls::sys_munmap(0x40000001U, 4096U) == Kernel::Syscalls::ERR_EINVAL); + CHECK(Kernel::Syscalls::sys_mprotect(0x40000001U, 4096U, Kernel::Syscalls::PROT_READ) == + Kernel::Syscalls::ERR_EINVAL); + CHECK(Kernel::Syscalls::sys_mprotect(0x40000000U, 4096U, 0x99U) == + Kernel::Syscalls::ERR_EINVAL); + CHECK(Kernel::Syscalls::sys_mprotect(0x40000000U, 0U, Kernel::Syscalls::PROT_READ) == 0); + CHECK(Kernel::Syscalls::sys_mprotect(0x40000000U, UINT64_MAX, Kernel::Syscalls::PROT_READ) == + Kernel::Syscalls::ERR_ENOMEM); + CHECK(Kernel::Syscalls::sys_mprotect(Kernel::MM::user_addr_space_limit(), 4096U, + Kernel::Syscalls::PROT_READ) == + Kernel::Syscalls::ERR_ENOMEM); + + // AddressSpace clone_from with MAP_SHARED VMA + const int64_t shared_map = Kernel::Syscalls::sys_mmap( + 0x30000000U, 4096U, Kernel::Syscalls::PROT_READ | Kernel::Syscalls::PROT_WRITE, + Kernel::Syscalls::MAP_SHARED | Kernel::Syscalls::MAP_ANONYMOUS | + Kernel::Syscalls::MAP_FIXED, + static_cast(-1), 0U); + REQUIRE(shared_map == 0x30000000LL); + auto child_as = proc->address_space().clone(); + REQUIRE(child_as.is_ok()); + child_as.value().destroy(); + Kernel::Process::Process::set_current(prev_proc); Kernel::Process::Process::destroy(*proc); Kernel::FS::page_cache_reset();