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