diff --git a/Makefile b/Makefile index 068e83e..1fb4e61 100644 --- a/Makefile +++ b/Makefile @@ -73,6 +73,9 @@ 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 \ + 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/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/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 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); +}