diff --git a/Makefile b/Makefile index a1c9368..6d30bc1 100644 --- a/Makefile +++ b/Makefile @@ -36,7 +36,7 @@ SRCS_CXX := SRCS_ASM := SRCS_C := user/hello_musl.c user/hello_dyn.c user/fb_test.c user/evdev_smoke.c \ user/unix_echo_server.c user/unix_echo_client.c user/unix_sock_smoke.c \ - user/test_milo.c + user/test_milo.c user/wl_compositor.c user/wl_client.c # Include architecture, core modules, and modular DDK drivers MILO_DDK_DIR := . @@ -85,7 +85,7 @@ HOST_COV_OBJS := $(patsubst %.cpp, $(HOST_COV_DIR)/%.o, $(HOST_TEST_SRCS)) HOST_COV_DEPS := $(HOST_COV_OBJS:.o=.d) HOST_COV_BIN := $(HOST_COV_DIR)/kernel_host_coverage -.PHONY: all clean distclean clean-tests run debug gdb lint format format-check lint-report license-check quality \ +.PHONY: all clean distclean clean-tests run run-vnc debug gdb lint format format-check lint-report license-check quality \ test-host compile_commands.json ai-dump setup-musl setup-busybox setup-bash setup-debian-bash setup-hooks loc export-ddk all: $(BUILD_DIR)/$(TARGET) $(INITRD) @@ -169,6 +169,8 @@ UNIX_SRV_BIN := $(if $(HAS_MUSL_CC),$(BUILD_DIR)/user/unix_echo_server) UNIX_CLI_BIN := $(if $(HAS_MUSL_CC),$(BUILD_DIR)/user/unix_echo_client) UNIX_SMOKE_BIN := $(if $(HAS_MUSL_CC),$(BUILD_DIR)/user/unix_sock_smoke) TEST_MILO_USER_BIN := $(if $(HAS_MUSL_CC),$(BUILD_DIR)/user/test_milo) +WL_COMPOSITOR_BIN := $(if $(HAS_MUSL_CC),$(BUILD_DIR)/user/wl_compositor) +WL_CLIENT_BIN := $(if $(HAS_MUSL_CC),$(BUILD_DIR)/user/wl_client) MUSL_LDSO_LIB := $(wildcard $(MUSL_SYSROOT)/lib/libc.so) LINUX_VER := 6.6.63 @@ -221,6 +223,14 @@ $(BUILD_DIR)/user/test_milo: user/test_milo.c @mkdir -p $(dir $@) $(MUSL_CC) -static -O2 -Wall -Wextra $< -o $@ +$(BUILD_DIR)/user/wl_compositor: user/wl_compositor.c user/wl_proto.h + @mkdir -p $(dir $@) + $(MUSL_CC) -static -O2 -Wall -Wextra -Werror $< -o $@ + +$(BUILD_DIR)/user/wl_client: user/wl_client.c user/wl_proto.h + @mkdir -p $(dir $@) + $(MUSL_CC) -static -O2 -Wall -Wextra -Werror -pthread $< -o $@ + # --- BusyBox Initrd (initrds/busybox.cpio) --- BUSYBOX_VER := 1.36.1 BUSYBOX_BIN := $(BUILD_DIR)/busybox-$(BUSYBOX_VER)/busybox @@ -236,7 +246,7 @@ $(BUSYBOX_BIN): sed -i 's/CONFIG_TC=y/# CONFIG_TC is not set/' .config && \ $(MAKE) -j$$(nproc) CROSS_COMPILE=aarch64-linux-musl- CC="$(MUSL_CC)" -$(BUSYBOX_CPIO): $(BUILD_DIR)/user/hello $(MUSL_USER_BIN) $(DYN_USER_BIN) $(FB_USER_BIN) $(EVDEV_USER_BIN) $(UNIX_SRV_BIN) $(UNIX_CLI_BIN) $(UNIX_SMOKE_BIN) $(TEST_MILO_USER_BIN) $(wildcard $(BUSYBOX_BIN)) +$(BUSYBOX_CPIO): $(BUILD_DIR)/user/hello $(MUSL_USER_BIN) $(DYN_USER_BIN) $(FB_USER_BIN) $(EVDEV_USER_BIN) $(UNIX_SRV_BIN) $(UNIX_CLI_BIN) $(UNIX_SMOKE_BIN) $(TEST_MILO_USER_BIN) $(WL_COMPOSITOR_BIN) $(WL_CLIENT_BIN) $(wildcard $(BUSYBOX_BIN)) @rm -rf $(BUSYBOX_ROOTFS_DIR) @mkdir -p $(INITRDS_DIR) $(BUSYBOX_ROOTFS_DIR)/bin $(BUSYBOX_ROOTFS_DIR)/lib $(BUSYBOX_ROOTFS_DIR)/dev $(BUSYBOX_ROOTFS_DIR)/proc $(BUSYBOX_ROOTFS_DIR)/tmp @echo "milo-initrd-v1" > $(BUSYBOX_ROOTFS_DIR)/init.txt @@ -265,6 +275,12 @@ $(BUSYBOX_CPIO): $(BUILD_DIR)/user/hello $(MUSL_USER_BIN) $(DYN_USER_BIN) $(FB_U @if [ -f "$(BUILD_DIR)/user/test_milo" ]; then \ install -m 0755 $(BUILD_DIR)/user/test_milo $(BUSYBOX_ROOTFS_DIR)/bin/test_milo; \ fi + @if [ -f "$(BUILD_DIR)/user/wl_compositor" ]; then \ + install -m 0755 $(BUILD_DIR)/user/wl_compositor $(BUSYBOX_ROOTFS_DIR)/bin/wl_compositor; \ + fi + @if [ -f "$(BUILD_DIR)/user/wl_client" ]; then \ + install -m 0755 $(BUILD_DIR)/user/wl_client $(BUSYBOX_ROOTFS_DIR)/bin/wl_client; \ + fi @if [ -f "$(MUSL_SYSROOT)/lib/libc.so" ]; then \ install -m 0755 $(MUSL_SYSROOT)/lib/libc.so $(BUSYBOX_ROOTFS_DIR)/lib/libc.so && \ ln -sf libc.so $(BUSYBOX_ROOTFS_DIR)/lib/ld-musl-aarch64.so.1 && \ @@ -307,7 +323,7 @@ $(BASH_BIN): $(MAKE) -j$$(nproc) && \ aarch64-linux-musl-strip bash -$(BASH_CPIO): $(BUILD_DIR)/user/hello $(MUSL_USER_BIN) $(DYN_USER_BIN) $(FB_USER_BIN) $(EVDEV_USER_BIN) $(UNIX_SRV_BIN) $(UNIX_CLI_BIN) $(UNIX_SMOKE_BIN) $(TEST_MILO_USER_BIN) $(BASH_BIN) +$(BASH_CPIO): $(BUILD_DIR)/user/hello $(MUSL_USER_BIN) $(DYN_USER_BIN) $(FB_USER_BIN) $(EVDEV_USER_BIN) $(UNIX_SRV_BIN) $(UNIX_CLI_BIN) $(UNIX_SMOKE_BIN) $(TEST_MILO_USER_BIN) $(WL_COMPOSITOR_BIN) $(WL_CLIENT_BIN) $(BASH_BIN) @rm -rf $(BASH_ROOTFS_DIR) @mkdir -p $(INITRDS_DIR) $(BASH_ROOTFS_DIR)/bin $(BASH_ROOTFS_DIR)/lib $(BASH_ROOTFS_DIR)/dev $(BASH_ROOTFS_DIR)/proc $(BASH_ROOTFS_DIR)/tmp @echo "milo-initrd-v1" > $(BASH_ROOTFS_DIR)/init.txt @@ -336,6 +352,12 @@ $(BASH_CPIO): $(BUILD_DIR)/user/hello $(MUSL_USER_BIN) $(DYN_USER_BIN) $(FB_USER @if [ -f "$(BUILD_DIR)/user/test_milo" ]; then \ install -m 0755 $(BUILD_DIR)/user/test_milo $(BASH_ROOTFS_DIR)/bin/test_milo; \ fi + @if [ -f "$(BUILD_DIR)/user/wl_compositor" ]; then \ + install -m 0755 $(BUILD_DIR)/user/wl_compositor $(BASH_ROOTFS_DIR)/bin/wl_compositor; \ + fi + @if [ -f "$(BUILD_DIR)/user/wl_client" ]; then \ + install -m 0755 $(BUILD_DIR)/user/wl_client $(BASH_ROOTFS_DIR)/bin/wl_client; \ + fi @if [ -f "$(MUSL_SYSROOT)/lib/libc.so" ]; then \ install -m 0755 $(MUSL_SYSROOT)/lib/libc.so $(BASH_ROOTFS_DIR)/lib/libc.so && \ ln -sf libc.so $(BASH_ROOTFS_DIR)/lib/ld-musl-aarch64.so.1 && \ @@ -347,12 +369,12 @@ $(BASH_CPIO): $(BUILD_DIR)/user/hello $(MUSL_USER_BIN) $(DYN_USER_BIN) $(FB_USER setup-bash: $(BASH_CPIO) # --- Precompiled Debian arm64 GNU Bash Initrd (initrds/debian-bash.cpio) --- -$(DEBIAN_BASH_CPIO): $(BUILD_DIR)/user/hello $(MUSL_USER_BIN) $(DYN_USER_BIN) $(FB_USER_BIN) $(EVDEV_USER_BIN) $(UNIX_SRV_BIN) $(UNIX_CLI_BIN) $(UNIX_SMOKE_BIN) $(TEST_MILO_USER_BIN) scripts/setup_debian_bash.sh +$(DEBIAN_BASH_CPIO): $(BUILD_DIR)/user/hello $(MUSL_USER_BIN) $(DYN_USER_BIN) $(FB_USER_BIN) $(EVDEV_USER_BIN) $(UNIX_SRV_BIN) $(UNIX_CLI_BIN) $(UNIX_SMOKE_BIN) $(TEST_MILO_USER_BIN) $(WL_COMPOSITOR_BIN) $(WL_CLIENT_BIN) scripts/setup_debian_bash.sh @rm -rf $(DEBIAN_BASH_ROOTFS_DIR) @mkdir -p $(INITRDS_DIR) $(DEBIAN_BASH_ROOTFS_DIR)/bin $(DEBIAN_BASH_ROOTFS_DIR)/lib $(DEBIAN_BASH_ROOTFS_DIR)/dev $(DEBIAN_BASH_ROOTFS_DIR)/proc $(DEBIAN_BASH_ROOTFS_DIR)/tmp @echo "milo-initrd-v1" > $(DEBIAN_BASH_ROOTFS_DIR)/init.txt @install -m 0755 $(BUILD_DIR)/user/hello $(DEBIAN_BASH_ROOTFS_DIR)/bin/hello - @for bin in hello_musl hello_dyn fb_test evdev_smoke unix_echo_server unix_echo_client unix_sock_smoke test_milo; do \ + @for bin in hello_musl hello_dyn fb_test evdev_smoke unix_echo_server unix_echo_client unix_sock_smoke test_milo wl_compositor wl_client; do \ if [ -f "$(BUILD_DIR)/user/$$bin" ]; then \ install -m 0755 "$(BUILD_DIR)/user/$$bin" "$(DEBIAN_BASH_ROOTFS_DIR)/bin/$$bin"; \ fi; \ @@ -382,21 +404,23 @@ distclean: dump-for-ai-*.txt dump-index.txt # QEMU Executable & Flags -QEMU ?= qemu-system-aarch64 -QEMUFLAGS := -M virt \ - -cpu cortex-a57 \ - -m 256M \ - -nographic \ - -kernel $(BUILD_DIR)/$(TARGET) \ - -initrd $(INITRD) \ - -global virtio-mmio.force-legacy=false \ - -drive file=disk.img,format=raw,if=none,id=hd0 \ - -device virtio-blk-device,drive=hd0 \ - -netdev user,id=net0 \ - -device virtio-net-device,netdev=net0 \ - -device virtio-gpu-device \ - -device virtio-keyboard-device \ - -device virtio-tablet-device +QEMU ?= qemu-system-aarch64 +QEMU_VNC_DISPLAY ?= 0.0.0.0:0 +QEMU_COMMON_FLAGS := -M virt \ + -cpu cortex-a57 \ + -m 256M \ + -kernel $(BUILD_DIR)/$(TARGET) \ + -initrd $(INITRD) \ + -global virtio-mmio.force-legacy=false \ + -drive file=disk.img,format=raw,if=none,id=hd0 \ + -device virtio-blk-device,drive=hd0 \ + -netdev user,id=net0 \ + -device virtio-net-device,netdev=net0 \ + -device virtio-gpu-device \ + -device virtio-keyboard-device \ + -device virtio-tablet-device +QEMUFLAGS := $(QEMU_COMMON_FLAGS) -nographic +QEMU_VNC_FLAGS := $(QEMU_COMMON_FLAGS) -vnc $(QEMU_VNC_DISPLAY) -serial mon:stdio GDB ?= gdb-multiarch DISK_IMG ?= disk.img @@ -412,6 +436,10 @@ disk: $(DISK_IMG) run: $(BUILD_DIR)/$(TARGET) $(INITRD) $(DISK_IMG) $(QEMU) $(QEMUFLAGS) +run-vnc: $(BUILD_DIR)/$(TARGET) $(INITRD) $(DISK_IMG) + @echo "Starting QEMU with VNC on $(QEMU_VNC_DISPLAY) (connect VNC viewer to localhost:5900; press Ctrl-A X to exit)" + $(QEMU) $(QEMU_VNC_FLAGS) + debug: $(BUILD_DIR)/$(TARGET) $(INITRD) @echo "Starting QEMU in debug mode. Connect with: make gdb" $(QEMU) $(QEMUFLAGS) -s -S @@ -421,7 +449,7 @@ gdb: $(BUILD_DIR)/kernel.elf $(GDB) $(BUILD_DIR)/kernel.elf -ex "target remote localhost:1234" -ex "layout split" # Find all project source/header files for formatting/linting targets -HDRS := $(shell find include kernel arch tests drivers -name '*.hpp' -o -name '*.h' 2>/dev/null) +HDRS := $(shell find include kernel arch tests drivers user -name '*.hpp' -o -name '*.h' 2>/dev/null) TEST_FORMAT_SRCS := $(HOST_TEST_CASE_SRCS) # --- Compilation Database Generation (incremental, without clean rebuilds) --- diff --git a/kernel/fs/Inode.hpp b/kernel/fs/Inode.hpp index 43291ef..bfbc5c1 100644 --- a/kernel/fs/Inode.hpp +++ b/kernel/fs/Inode.hpp @@ -19,6 +19,8 @@ struct InodeOperations { int32_t (*truncate)(Inode* inode, uint64_t new_size){nullptr}; int32_t (*readlink)(Inode* inode, char* buf, size_t buf_size, size_t* out_len){nullptr}; int32_t (*mknod)(Inode* dir, Dentry* target, uint32_t mode, uint64_t rdev){nullptr}; + int32_t (*get_page)(Inode* inode, uint64_t page_offset, size_t page_size, + uintptr_t& out_paddr){nullptr}; }; class Inode final { diff --git a/kernel/fs/devfs/devfs.cpp b/kernel/fs/devfs/devfs.cpp index 78a0a34..1453218 100644 --- a/kernel/fs/devfs/devfs.cpp +++ b/kernel/fs/devfs/devfs.cpp @@ -1354,6 +1354,7 @@ int32_t devfs_init_and_mount() noexcept { return reg_res; } (void)devfs_ensure_subdir("input", 0755U); + (void)devfs_ensure_subdir("shm", 01777U); devfs_register_fb0(); return kOk; } diff --git a/kernel/fs/tmpfs/tmpfs.cpp b/kernel/fs/tmpfs/tmpfs.cpp index b2c49a3..0957be9 100644 --- a/kernel/fs/tmpfs/tmpfs.cpp +++ b/kernel/fs/tmpfs/tmpfs.cpp @@ -6,6 +6,7 @@ #include "hal/cpu.hpp" #include "hal/platform.hpp" #include "mm/AddressSpace.hpp" +#include "mm/heap.hpp" #include "mm/pfa.hpp" #include @@ -24,6 +25,9 @@ class TmpfsNode final { TmpfsNode(TmpfsNode&&) = delete; TmpfsNode& operator=(TmpfsNode&&) = delete; + static constexpr size_t kDirectPages = 32U; + static constexpr size_t kIndirectPages = kTmpfsMaxPagesPerFile - kDirectPages; + [[nodiscard]] bool is_active() const noexcept { return m_active; } void activate() noexcept { @@ -36,41 +40,82 @@ class TmpfsNode final { m_active = false; } + void reset_for_reinit() noexcept { + for (size_t idx = 0U; idx < kDirectPages; ++idx) { + m_direct[idx] = 0U; + } + m_indirect = nullptr; + m_active = false; + } + [[nodiscard]] uintptr_t page_at(size_t page_idx) const noexcept { - return (page_idx < kTmpfsMaxPagesPerFile) ? m_pages[page_idx] : 0U; + if (page_idx < kDirectPages) { + return m_direct[page_idx]; + } + if (m_indirect != nullptr && page_idx < kTmpfsMaxPagesPerFile) { + return m_indirect[page_idx - kDirectPages]; + } + return 0U; } [[nodiscard]] uintptr_t ensure_page(size_t page_idx, size_t page_size) noexcept { if (page_idx >= kTmpfsMaxPagesPerFile) { return 0U; } - if (m_pages[page_idx] == 0U) { + uintptr_t* slot = nullptr; + if (page_idx < kDirectPages) { + slot = &m_direct[page_idx]; + } else { + if (m_indirect == nullptr) { + m_indirect = static_cast( + Kernel::MM::kzalloc(kIndirectPages * sizeof(uintptr_t), alignof(uintptr_t))); + if (m_indirect == nullptr) { + return 0U; + } + } + slot = &m_indirect[page_idx - kDirectPages]; + } + if (*slot == 0U) { const uintptr_t frame = Kernel::MM::alloc_frame(); if (frame == 0U) { return 0U; } auto* const page_kva = reinterpret_cast(Kernel::MM::phys_to_virt(frame)); std::memset(page_kva, 0, page_size); - m_pages[page_idx] = frame; + *slot = frame; } - return m_pages[page_idx]; + return *slot; } void truncate_pages(uint64_t new_size, size_t page_size) noexcept { const auto keep_pages = static_cast((new_size + page_size - 1U) / page_size); - for (size_t page_idx = keep_pages; page_idx < kTmpfsMaxPagesPerFile; ++page_idx) { - if (m_pages[page_idx] != 0U) { - Kernel::MM::free_frame(m_pages[page_idx]); - m_pages[page_idx] = 0U; + for (size_t page_idx = keep_pages; page_idx < kDirectPages; ++page_idx) { + if (m_direct[page_idx] != 0U) { + Kernel::MM::page_put(m_direct[page_idx]); + m_direct[page_idx] = 0U; + } + } + if (m_indirect != nullptr) { + const size_t start = (keep_pages > kDirectPages) ? (keep_pages - kDirectPages) : 0U; + for (size_t idx = start; idx < kIndirectPages; ++idx) { + if (m_indirect[idx] != 0U) { + Kernel::MM::page_put(m_indirect[idx]); + m_indirect[idx] = 0U; + } + } + if (keep_pages <= kDirectPages) { + Kernel::MM::kfree(m_indirect); + m_indirect = nullptr; } } const auto tail_off = static_cast(new_size % page_size); if (tail_off != 0U) { const auto tail_idx = static_cast(new_size / page_size); - if (tail_idx < kTmpfsMaxPagesPerFile && m_pages[tail_idx] != 0U) { + const uintptr_t tail_pa = page_at(tail_idx); + if (tail_pa != 0U) { auto* const page_kva = - reinterpret_cast(Kernel::MM::phys_to_virt(m_pages[tail_idx])); + reinterpret_cast(Kernel::MM::phys_to_virt(tail_pa)); std::memset(page_kva + tail_off, 0, page_size - tail_off); } } @@ -78,20 +123,32 @@ class TmpfsNode final { private: void release_all_pages() noexcept { - for (uintptr_t& paddr : m_pages) { - if (paddr != 0U) { - Kernel::MM::free_frame(paddr); - paddr = 0U; + for (size_t idx = 0U; idx < kDirectPages; ++idx) { + if (m_direct[idx] != 0U) { + Kernel::MM::page_put(m_direct[idx]); + m_direct[idx] = 0U; + } + } + if (m_indirect != nullptr) { + for (size_t idx = 0U; idx < kIndirectPages; ++idx) { + if (m_indirect[idx] != 0U) { + Kernel::MM::page_put(m_indirect[idx]); + m_indirect[idx] = 0U; + } } + Kernel::MM::kfree(m_indirect); + m_indirect = nullptr; } } - uintptr_t m_pages[kTmpfsMaxPagesPerFile]{}; + uintptr_t m_direct[kDirectPages]{}; + uintptr_t* m_indirect{nullptr}; bool m_active{false}; }; TmpfsNode g_tmpfs_nodes[kTmpfsMaxInodes]{}; Superblock* g_tmpfs_sb = nullptr; +Superblock g_memfd_fallback_sb{}; uint64_t g_next_tmpfs_ino = 2ULL; [[nodiscard]] uint64_t current_time_ns() noexcept { @@ -482,6 +539,29 @@ int32_t tmpfs_rename(Inode* old_dir, Dentry* old_dentry, Inode* new_dir, return kOk; } +int32_t tmpfs_get_page(Inode* inode, uint64_t page_offset, size_t page_size, + uintptr_t& out_paddr) noexcept { + out_paddr = 0U; + if (inode == nullptr || page_size == 0U || inode->is_dir()) { + return kEinval; + } + auto* const node = static_cast(inode->get_fs_private()); + if (node == nullptr) { + return kEio; + } + const auto page_idx = static_cast(page_offset / page_size); + if (page_idx >= kTmpfsMaxPagesPerFile) { + return kEnospc; + } + const uintptr_t frame = node->ensure_page(page_idx, page_size); + if (frame == 0U) { + return kEnomem; + } + Kernel::MM::page_get(frame); + out_paddr = frame; + return kOk; +} + const SuperblockOperations kTmpfsSbOps{ .sync_fs = nullptr, .alloc_inode = nullptr, @@ -498,6 +578,7 @@ const InodeOperations kTmpfsInodeOps{ .truncate = tmpfs_truncate, .readlink = nullptr, .mknod = tmpfs_mknod, + .get_page = tmpfs_get_page, }; const FileOperations kTmpfsFileOps{ @@ -516,7 +597,7 @@ const FileOperations kTmpfsFileOps{ void tmpfs_reset() noexcept { for (auto& slot : g_tmpfs_nodes) { - slot.reset(); + slot.reset_for_reinit(); } g_tmpfs_sb = nullptr; g_next_tmpfs_ino = 2ULL; @@ -589,4 +670,54 @@ int32_t tmpfs_init_and_mount() noexcept { return kOk; } +int32_t tmpfs_create_anon_file(uint32_t open_flags, File** out_file) noexcept { + if (out_file == nullptr) { + return kEinval; + } + *out_file = nullptr; + + TmpfsNode* const node = alloc_tmpfs_node(); + if (node == nullptr) { + return kEnomem; + } + + Superblock* sb = g_tmpfs_sb; + if (sb == nullptr) { + g_memfd_fallback_sb.set_fs_type("tmpfs"); + g_memfd_fallback_sb.set_block_size(4096U); + g_memfd_fallback_sb.set_flags(0U); + g_memfd_fallback_sb.set_ops(&kTmpfsSbOps); + g_memfd_fallback_sb.set_active(true); + sb = &g_memfd_fallback_sb; + } + + auto inode = RefPtr::adopt(vfs_alloc_inode(sb)); + if (!inode) { + node->reset(); + return kEnomem; + } + + const uint64_t now_ns = current_time_ns(); + inode->set_ino(g_next_tmpfs_ino++); + inode->set_mode(kModeReg | 0600U); + inode->set_nlink(0U); + inode->set_size(0U); + inode->set_atime_ns(now_ns); + inode->set_mtime_ns(now_ns); + inode->set_ctime_ns(now_ns); + inode->set_i_ops(&kTmpfsInodeOps); + inode->set_f_ops(&kTmpfsFileOps); + inode->set_fs_private(node); + + File* const file = vfs_alloc_file(); + if (file == nullptr) { + return kEnomem; + } + file->set_inode(inode.detach()); + file->set_flags(open_flags); + file->set_f_ops(&kTmpfsFileOps); + *out_file = file; + return kOk; +} + } // namespace Kernel::FS \ No newline at end of file diff --git a/kernel/fs/tmpfs/tmpfs.hpp b/kernel/fs/tmpfs/tmpfs.hpp index fcddd0a..627aeef 100644 --- a/kernel/fs/tmpfs/tmpfs.hpp +++ b/kernel/fs/tmpfs/tmpfs.hpp @@ -11,7 +11,7 @@ namespace Kernel::FS { inline constexpr size_t kTmpfsMaxInodes = 256U; -inline constexpr size_t kTmpfsMaxPagesPerFile = 256U; // 1 MiB per file (256 * 4 KiB) +inline constexpr size_t kTmpfsMaxPagesPerFile = 1024U; // 4 MiB per file (1024 * 4 KiB) void tmpfs_reset() noexcept; @@ -21,4 +21,7 @@ void tmpfs_reset() noexcept; // Creates a tmpfs instance and mounts it at `/tmp`. [[nodiscard]] int32_t tmpfs_init_and_mount() noexcept; +// Creates an anonymous tmpfs-backed regular File (for memfd_create). +[[nodiscard]] int32_t tmpfs_create_anon_file(uint32_t open_flags, File** out_file) noexcept; + } // namespace Kernel::FS \ No newline at end of file diff --git a/kernel/ipc/EventLoop.cpp b/kernel/ipc/EventLoop.cpp new file mode 100644 index 0000000..a9d7651 --- /dev/null +++ b/kernel/ipc/EventLoop.cpp @@ -0,0 +1,736 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#include "ipc/EventLoop.hpp" + +#include "fs/Vfs.hpp" +#include "hal/cpu.hpp" +#include "hal/platform.hpp" +#include "process/Process.hpp" +#include "process/Signal.hpp" +#include "process/scheduler.hpp" +#include "sync/IrqGuard.hpp" +#include "time/Duration.hpp" +#include "uapi/sys.hpp" + +#include +#include + +namespace Kernel::IPC { + +namespace { + +constexpr uint64_t kNsPerSec = 1000000000ULL; +constexpr uint64_t kMaxEventFdCounter = UINT64_MAX - 1ULL; + +[[nodiscard]] uint64_t monotonic_now_ns() noexcept { + const uint64_t freq = HAL::Platform::timer_frequency_hz(); + const uint64_t ticks = HAL::Platform::timer_counter_ticks(); + if (freq == 0ULL) { + return 0ULL; + } + const uint64_t secs = ticks / freq; + const uint64_t rem = ticks % freq; + return (secs * kNsPerSec) + ((rem * kNsPerSec) / freq); +} + +[[nodiscard]] bool has_signal_interrupt() noexcept { + const auto* const cur = Kernel::Process::Process::current(); + return cur != nullptr && Kernel::Process::has_unblocked_pending_signal(*cur); +} + +void yield_or_poll_once() noexcept { + if (Kernel::Process::Process::has_runnable()) { + Kernel::Scheduler::yield(); + } else { + HAL::get_cpu().poll_interrupts_once(); + } +} + +[[nodiscard]] bool timespec_valid_nonneg(const linux_timespec& ts) noexcept { + return ts.tv_sec >= 0 && ts.tv_nsec >= 0 && ts.tv_nsec < static_cast(kNsPerSec); +} + +[[nodiscard]] uint64_t timespec_to_ns(const linux_timespec& ts) noexcept { + return (static_cast(ts.tv_sec) * kNsPerSec) + static_cast(ts.tv_nsec); +} + +[[nodiscard]] linux_timespec ns_to_timespec(uint64_t ns) noexcept { + return linux_timespec{ + .tv_sec = static_cast(ns / kNsPerSec), + .tv_nsec = static_cast(ns % kNsPerSec), + }; +} + +[[nodiscard]] bool attach_anon_inode(Kernel::FS::File* file, + const Kernel::FS::FileOperations* f_ops) noexcept { + auto* const inode = Kernel::FS::vfs_alloc_inode(nullptr); + if (inode == nullptr) { + return false; + } + inode->set_ino(4ULL); + inode->set_mode(Kernel::FS::kModeReg | 0600U); + inode->set_f_ops(f_ops); + file->set_inode(inode); + return true; +} + +// --- EventFd FileOperations --- + +int64_t eventfd_file_read(Kernel::FS::File* file, void* buf, size_t count, + uint64_t* /*offset*/) noexcept { + if (file == nullptr || file->get_private_data() == nullptr) { + return Kernel::FS::kEbadf; + } + if (count < sizeof(uint64_t) || buf == nullptr) { + return Kernel::FS::kEinval; + } + auto* const efd = static_cast(file->get_private_data()); + const bool nonblock = (file->get_flags() & Kernel::FS::kOpenNonBlock) != 0U; + uint64_t val = 0ULL; + const int64_t rc = efd->read_value(val, nonblock); + if (rc < 0) { + return rc; + } + std::memcpy(buf, &val, sizeof(val)); + return static_cast(sizeof(val)); +} + +int64_t eventfd_file_write(Kernel::FS::File* file, const void* buf, size_t count, + uint64_t* /*offset*/) noexcept { + if (file == nullptr || file->get_private_data() == nullptr) { + return Kernel::FS::kEbadf; + } + if (count < sizeof(uint64_t) || buf == nullptr) { + return Kernel::FS::kEinval; + } + auto* const efd = static_cast(file->get_private_data()); + const bool nonblock = (file->get_flags() & Kernel::FS::kOpenNonBlock) != 0U; + uint64_t add_val = 0ULL; + std::memcpy(&add_val, buf, sizeof(add_val)); + const int64_t rc = efd->write_value(add_val, nonblock); + if (rc < 0) { + return rc; + } + return static_cast(sizeof(add_val)); +} + +int32_t eventfd_file_release(Kernel::FS::Inode* /*inode*/, Kernel::FS::File* file) noexcept { + if (file == nullptr || file->get_private_data() == nullptr) { + return Kernel::FS::kOk; + } + auto* const efd = static_cast(file->get_private_data()); + file->set_private_data(nullptr); + efd->release(); + return Kernel::FS::kOk; +} + +int64_t eventfd_file_lseek(Kernel::FS::File* /*file*/, int64_t /*offset*/, + Kernel::FS::SeekWhence /*whence*/) noexcept { + return Kernel::FS::kEspipe; +} + +int16_t eventfd_file_poll(Kernel::FS::File* file, int16_t events) noexcept { + if (file == nullptr || file->get_private_data() == nullptr) { + return Kernel::UAPI::POLLNVAL; + } + const auto* const efd = static_cast(file->get_private_data()); + return efd->poll(events); +} + +const Kernel::FS::FileOperations kEventFdFileOps{ + .read = eventfd_file_read, + .write = eventfd_file_write, + .open = nullptr, + .release = eventfd_file_release, + .lseek = eventfd_file_lseek, + .ioctl = nullptr, + .fsync = nullptr, + .readdir = nullptr, + .poll = eventfd_file_poll, + .mmap = nullptr, +}; + +// --- TimerFd FileOperations --- + +int64_t timerfd_file_read(Kernel::FS::File* file, void* buf, size_t count, + uint64_t* /*offset*/) noexcept { + if (file == nullptr || file->get_private_data() == nullptr) { + return Kernel::FS::kEbadf; + } + if (count < sizeof(uint64_t) || buf == nullptr) { + return Kernel::FS::kEinval; + } + auto* const tfd = static_cast(file->get_private_data()); + const bool nonblock = (file->get_flags() & Kernel::FS::kOpenNonBlock) != 0U; + uint64_t expirations = 0ULL; + const int64_t rc = tfd->read_expirations(expirations, nonblock); + if (rc < 0) { + return rc; + } + std::memcpy(buf, &expirations, sizeof(expirations)); + return static_cast(sizeof(expirations)); +} + +int32_t timerfd_file_release(Kernel::FS::Inode* /*inode*/, Kernel::FS::File* file) noexcept { + if (file == nullptr || file->get_private_data() == nullptr) { + return Kernel::FS::kOk; + } + auto* const tfd = static_cast(file->get_private_data()); + file->set_private_data(nullptr); + tfd->release(); + return Kernel::FS::kOk; +} + +int64_t timerfd_file_lseek(Kernel::FS::File* /*file*/, int64_t /*offset*/, + Kernel::FS::SeekWhence /*whence*/) noexcept { + return Kernel::FS::kEspipe; +} + +int16_t timerfd_file_poll(Kernel::FS::File* file, int16_t events) noexcept { + if (file == nullptr || file->get_private_data() == nullptr) { + return Kernel::UAPI::POLLNVAL; + } + auto* const tfd = static_cast(file->get_private_data()); + return tfd->poll(events); +} + +const Kernel::FS::FileOperations kTimerFdFileOps{ + .read = timerfd_file_read, + .write = nullptr, + .open = nullptr, + .release = timerfd_file_release, + .lseek = timerfd_file_lseek, + .ioctl = nullptr, + .fsync = nullptr, + .readdir = nullptr, + .poll = timerfd_file_poll, + .mmap = nullptr, +}; + +// --- Epoll FileOperations --- + +int32_t epoll_file_release(Kernel::FS::Inode* /*inode*/, Kernel::FS::File* file) noexcept { + if (file == nullptr || file->get_private_data() == nullptr) { + return Kernel::FS::kOk; + } + auto* const ep = static_cast(file->get_private_data()); + file->set_private_data(nullptr); + ep->release(); + return Kernel::FS::kOk; +} + +int64_t epoll_file_lseek(Kernel::FS::File* /*file*/, int64_t /*offset*/, + Kernel::FS::SeekWhence /*whence*/) noexcept { + return Kernel::FS::kEspipe; +} + +int16_t epoll_file_poll(Kernel::FS::File* file, int16_t events) noexcept { + if (file == nullptr || file->get_private_data() == nullptr) { + return Kernel::UAPI::POLLNVAL; + } + auto* const ep = static_cast(file->get_private_data()); + return ep->poll(events); +} + +const Kernel::FS::FileOperations kEpollFileOps{ + .read = nullptr, + .write = nullptr, + .open = nullptr, + .release = epoll_file_release, + .lseek = epoll_file_lseek, + .ioctl = nullptr, + .fsync = nullptr, + .readdir = nullptr, + .poll = epoll_file_poll, + .mmap = nullptr, +}; + +} // namespace + +// ========================================================================== +// EventFd Implementation +// ========================================================================== + +EventFd::EventFd(uint64_t initval, bool semaphore) noexcept + : m_refs(1U), m_counter(initval), m_semaphore(semaphore) {} + +void EventFd::retain() noexcept { + m_refs.fetch_add(1U, std::memory_order_acq_rel); +} + +void EventFd::release() noexcept { + if (m_refs.fetch_sub(1U, std::memory_order_acq_rel) == 1U) { + delete this; + } +} + +int64_t EventFd::read_value(uint64_t& out_val, bool nonblock) noexcept { + while (true) { + { + const Sync::IrqGuard irq_guard; + if (m_counter > 0ULL) { + if (m_semaphore) { + out_val = 1ULL; + --m_counter; + } else { + out_val = m_counter; + m_counter = 0ULL; + } + m_write_wq.wake_all(); + return static_cast(sizeof(uint64_t)); + } + if (nonblock) { + return Kernel::FS::kEagain; + } + if (has_signal_interrupt()) { + return Kernel::FS::kEintr; + } + } + m_read_wq.sleep(); + } +} + +int64_t EventFd::write_value(uint64_t add_val, bool nonblock) noexcept { + if (add_val == UINT64_MAX) { + return Kernel::FS::kEinval; + } + while (true) { + { + const Sync::IrqGuard irq_guard; + if (add_val <= (kMaxEventFdCounter - m_counter)) { + m_counter += add_val; + if (m_counter > 0ULL) { + m_read_wq.wake_all(); + } + return static_cast(sizeof(uint64_t)); + } + if (nonblock) { + return Kernel::FS::kEagain; + } + if (has_signal_interrupt()) { + return Kernel::FS::kEintr; + } + } + m_write_wq.sleep(); + } +} + +int16_t EventFd::poll(int16_t events) const noexcept { + const Sync::IrqGuard irq_guard; + uint16_t revents = 0U; + const auto req = static_cast(events); + constexpr auto kPollInBits = + static_cast(static_cast(Kernel::UAPI::POLLIN) | + static_cast(Kernel::UAPI::POLLRDNORM)); + constexpr auto kPollOutBits = + static_cast(static_cast(Kernel::UAPI::POLLOUT) | + static_cast(Kernel::UAPI::POLLWRNORM)); + if (m_counter > 0ULL) { + revents |= static_cast(req & kPollInBits); + } + if (m_counter < kMaxEventFdCounter) { + revents |= static_cast(req & kPollOutBits); + } + return static_cast(revents); +} + +int32_t EventFd::create_file(uint64_t initval, uint32_t open_flags, bool semaphore, + Kernel::FS::File** out_file) noexcept { + if (out_file == nullptr) { + return Kernel::FS::kEinval; + } + *out_file = nullptr; + + auto* const efd = new (std::nothrow) EventFd(initval, semaphore); + if (efd == nullptr) { + return Kernel::FS::kEnomem; + } + + Kernel::FS::File* const file = Kernel::FS::vfs_alloc_file(); + if (file == nullptr || !attach_anon_inode(file, &kEventFdFileOps)) { + if (file != nullptr) { + file->release(); + } + efd->release(); + return Kernel::FS::kEnomem; + } + + file->set_flags(Kernel::FS::kOpenReadWrite | (open_flags & Kernel::FS::kOpenNonBlock)); + file->set_f_ops(&kEventFdFileOps); + file->set_private_data(efd); + *out_file = file; + return Kernel::FS::kOk; +} + +// ========================================================================== +// TimerFd Implementation +// ========================================================================== + +TimerFd::TimerFd(int32_t clockid) noexcept : m_refs(1U), m_clockid(clockid) {} + +void TimerFd::retain() noexcept { + m_refs.fetch_add(1U, std::memory_order_acq_rel); +} + +void TimerFd::release() noexcept { + if (m_refs.fetch_sub(1U, std::memory_order_acq_rel) == 1U) { + delete this; + } +} + +void TimerFd::advance_locked(uint64_t now_ns) noexcept { + if (!m_armed || now_ns < m_next_expiry_ns) { + return; + } + if (m_interval_ns == 0ULL) { + ++m_expirations; + m_armed = false; + m_next_expiry_ns = 0ULL; + return; + } + const uint64_t elapsed = now_ns - m_next_expiry_ns; + const uint64_t ticks = (elapsed / m_interval_ns) + 1ULL; + m_expirations += ticks; + m_next_expiry_ns += ticks * m_interval_ns; +} + +int32_t TimerFd::settime(uint32_t flags, const linux_itimerspec& new_spec, + linux_itimerspec* old_spec) noexcept { + if ((flags & ~Kernel::UAPI::TFD_TIMER_ABSTIME) != 0U) { + return Kernel::FS::kEinval; + } + if (!timespec_valid_nonneg(new_spec.it_value) || !timespec_valid_nonneg(new_spec.it_interval)) { + return Kernel::FS::kEinval; + } + + const Sync::IrqGuard irq_guard; + const uint64_t now_ns = monotonic_now_ns(); + advance_locked(now_ns); + + if (old_spec != nullptr) { + old_spec->it_interval = ns_to_timespec(m_interval_ns); + if (m_armed && m_next_expiry_ns > now_ns) { + old_spec->it_value = ns_to_timespec(m_next_expiry_ns - now_ns); + } else { + old_spec->it_value = linux_timespec{0, 0}; + } + } + + const uint64_t val_ns = timespec_to_ns(new_spec.it_value); + const uint64_t int_ns = timespec_to_ns(new_spec.it_interval); + + m_expirations = 0ULL; + m_interval_ns = int_ns; + if (val_ns == 0ULL) { + m_armed = false; + m_next_expiry_ns = 0ULL; + } else { + m_armed = true; + m_next_expiry_ns = + ((flags & Kernel::UAPI::TFD_TIMER_ABSTIME) != 0U) ? val_ns : (now_ns + val_ns); + } + return Kernel::FS::kOk; +} + +void TimerFd::gettime(linux_itimerspec& out_spec) noexcept { + const Sync::IrqGuard irq_guard; + const uint64_t now_ns = monotonic_now_ns(); + advance_locked(now_ns); + out_spec.it_interval = ns_to_timespec(m_interval_ns); + if (m_armed && m_next_expiry_ns > now_ns) { + out_spec.it_value = ns_to_timespec(m_next_expiry_ns - now_ns); + } else { + out_spec.it_value = linux_timespec{0, 0}; + } +} + +int64_t TimerFd::read_expirations(uint64_t& out_count, bool nonblock) noexcept { + while (true) { + { + const Sync::IrqGuard irq_guard; + advance_locked(monotonic_now_ns()); + if (m_expirations > 0ULL) { + out_count = m_expirations; + m_expirations = 0ULL; + return static_cast(sizeof(uint64_t)); + } + if (nonblock) { + return Kernel::FS::kEagain; + } + if (has_signal_interrupt()) { + return Kernel::FS::kEintr; + } + } + yield_or_poll_once(); + } +} + +int16_t TimerFd::poll(int16_t events) noexcept { + const Sync::IrqGuard irq_guard; + advance_locked(monotonic_now_ns()); + if (m_expirations > 0ULL) { + constexpr auto kPollInBits = + static_cast(static_cast(Kernel::UAPI::POLLIN) | + static_cast(Kernel::UAPI::POLLRDNORM)); + return static_cast(static_cast(events) & kPollInBits); + } + return 0; +} + +int32_t TimerFd::create_file(int32_t clockid, uint32_t open_flags, + Kernel::FS::File** out_file) noexcept { + if (out_file == nullptr) { + return Kernel::FS::kEinval; + } + *out_file = nullptr; + + auto* const tfd = new (std::nothrow) TimerFd(clockid); + if (tfd == nullptr) { + return Kernel::FS::kEnomem; + } + + Kernel::FS::File* const file = Kernel::FS::vfs_alloc_file(); + if (file == nullptr || !attach_anon_inode(file, &kTimerFdFileOps)) { + if (file != nullptr) { + file->release(); + } + tfd->release(); + return Kernel::FS::kEnomem; + } + + file->set_flags(Kernel::FS::kOpenReadOnly | (open_flags & Kernel::FS::kOpenNonBlock)); + file->set_f_ops(&kTimerFdFileOps); + file->set_private_data(tfd); + *out_file = file; + return Kernel::FS::kOk; +} + +TimerFd* TimerFd::from_file(Kernel::FS::File* file) noexcept { + if (file == nullptr || file->get_f_ops() != &kTimerFdFileOps) { + return nullptr; + } + return static_cast(file->get_private_data()); +} + +// ========================================================================== +// EpollInstance Implementation +// ========================================================================== + +void EpollInstance::retain() noexcept { + m_refs.fetch_add(1U, std::memory_order_acq_rel); +} + +void EpollInstance::release() noexcept { + if (m_refs.fetch_sub(1U, std::memory_order_acq_rel) == 1U) { + delete this; + } +} + +int32_t EpollInstance::ctl(int32_t op, int32_t target_fd, const Kernel::FS::File* target_file, + const linux_epoll_event* event) noexcept { + if (target_fd < 0 || target_file == nullptr) { + return Kernel::FS::kEbadf; + } + + const Sync::IrqGuard irq_guard; + + WatchEntry* existing = nullptr; + WatchEntry* free_slot = nullptr; + for (auto& slot : m_watches) { + if (slot.active && slot.fd == target_fd && slot.file == target_file) { + existing = &slot; + break; + } + if (!slot.active && free_slot == nullptr) { + free_slot = &slot; + } + } + + if (op == Kernel::UAPI::EPOLL_CTL_ADD) { + if (event == nullptr) { + return Kernel::FS::kEfault; + } + if (existing != nullptr) { + return Kernel::FS::kEexist; + } + if (free_slot == nullptr) { + return Kernel::FS::kEnomem; + } + free_slot->active = true; + free_slot->armed = true; + free_slot->fd = target_fd; + free_slot->file = target_file; + free_slot->events = event->events | Kernel::UAPI::EPOLLERR | Kernel::UAPI::EPOLLHUP; + free_slot->last_ready = 0U; + free_slot->data = event->data; + return Kernel::FS::kOk; + } + + if (op == Kernel::UAPI::EPOLL_CTL_MOD) { + if (event == nullptr) { + return Kernel::FS::kEfault; + } + if (existing == nullptr) { + return Kernel::FS::kEnoent; + } + existing->armed = true; + existing->events = event->events | Kernel::UAPI::EPOLLERR | Kernel::UAPI::EPOLLHUP; + existing->last_ready = 0U; + existing->data = event->data; + return Kernel::FS::kOk; + } + + if (op == Kernel::UAPI::EPOLL_CTL_DEL) { + if (existing == nullptr) { + return Kernel::FS::kEnoent; + } + *existing = WatchEntry{}; + return Kernel::FS::kOk; + } + + return Kernel::FS::kEinval; +} + +int32_t EpollInstance::poll_ready(Kernel::Process::Process& proc, linux_epoll_event* out_events, + size_t max_events) noexcept { + if (out_events == nullptr || max_events == 0U) { + return 0; + } + + size_t ready_count = 0U; + for (auto& watch : m_watches) { + if (!watch.active || !watch.armed) { + continue; + } + Kernel::FS::File* const cur_file = proc.fds().get_file(static_cast(watch.fd)); + if (cur_file == nullptr || cur_file != watch.file) { + // Target FD was closed; auto-evict stale watch + watch = WatchEntry{}; + continue; + } + + constexpr auto kPollInBits = + static_cast(static_cast(Kernel::UAPI::POLLIN) | + static_cast(Kernel::UAPI::POLLRDNORM)); + constexpr auto kPollOutBits = + static_cast(static_cast(Kernel::UAPI::POLLOUT) | + static_cast(Kernel::UAPI::POLLWRNORM)); + uint16_t poll_mask_u = 0U; + if ((watch.events & Kernel::UAPI::EPOLLIN) != 0U) { + poll_mask_u = static_cast(poll_mask_u | kPollInBits); + } + if ((watch.events & Kernel::UAPI::EPOLLOUT) != 0U) { + poll_mask_u = static_cast(poll_mask_u | kPollOutBits); + } + + const auto rev_u = static_cast( + Kernel::FS::vfs_poll(cur_file, static_cast(poll_mask_u))); + uint32_t ep_rev = 0U; + if ((rev_u & kPollInBits) != 0U) { + ep_rev |= (watch.events & Kernel::UAPI::EPOLLIN); + } + if ((rev_u & kPollOutBits) != 0U) { + ep_rev |= (watch.events & Kernel::UAPI::EPOLLOUT); + } + if ((rev_u & static_cast(Kernel::UAPI::POLLERR)) != 0U) { + ep_rev |= Kernel::UAPI::EPOLLERR; + } + if ((rev_u & static_cast(Kernel::UAPI::POLLHUP)) != 0U) { + ep_rev |= Kernel::UAPI::EPOLLHUP; + if ((watch.events & Kernel::UAPI::EPOLLRDHUP) != 0U) { + ep_rev |= Kernel::UAPI::EPOLLRDHUP; + } + } + + const bool edge_triggered = (watch.events & Kernel::UAPI::EPOLLET) != 0U; + const uint32_t trigger_bits = edge_triggered ? (ep_rev & ~watch.last_ready) : ep_rev; + watch.last_ready = ep_rev; + + if (trigger_bits != 0U) { + if (ready_count < max_events) { + out_events[ready_count].events = ep_rev; + out_events[ready_count]._pad = 0U; + out_events[ready_count].data = watch.data; + ++ready_count; + if ((watch.events & Kernel::UAPI::EPOLLONESHOT) != 0U) { + watch.armed = false; + } + } else { + break; + } + } + } + + return static_cast(ready_count); +} + +int16_t EpollInstance::poll(int16_t events) noexcept { + auto* const proc = Kernel::Process::Process::current(); + if (proc == nullptr) { + return 0; + } + linux_epoll_event probe{}; + for (const auto& watch : m_watches) { + if (!watch.active || !watch.armed) { + continue; + } + Kernel::FS::File* const cur_file = proc->fds().get_file(static_cast(watch.fd)); + if (cur_file == nullptr || cur_file != watch.file) { + continue; + } + uint16_t poll_mask_u = 0U; + if ((watch.events & Kernel::UAPI::EPOLLIN) != 0U) { + poll_mask_u = + static_cast(poll_mask_u | static_cast(Kernel::UAPI::POLLIN)); + } + if ((watch.events & Kernel::UAPI::EPOLLOUT) != 0U) { + poll_mask_u = + static_cast(poll_mask_u | static_cast(Kernel::UAPI::POLLOUT)); + } + if (Kernel::FS::vfs_poll(cur_file, static_cast(poll_mask_u)) != 0) { + (void)probe; + constexpr auto kPollInBits = + static_cast(static_cast(Kernel::UAPI::POLLIN) | + static_cast(Kernel::UAPI::POLLRDNORM)); + return static_cast(static_cast(events) & kPollInBits); + } + } + return 0; +} + +int32_t EpollInstance::create_file(Kernel::FS::File** out_file) noexcept { + if (out_file == nullptr) { + return Kernel::FS::kEinval; + } + *out_file = nullptr; + + auto* const ep = new (std::nothrow) EpollInstance(); + if (ep == nullptr) { + return Kernel::FS::kEnomem; + } + + Kernel::FS::File* const file = Kernel::FS::vfs_alloc_file(); + if (file == nullptr || !attach_anon_inode(file, &kEpollFileOps)) { + if (file != nullptr) { + file->release(); + } + ep->release(); + return Kernel::FS::kEnomem; + } + + file->set_flags(Kernel::FS::kOpenReadWrite); + file->set_f_ops(&kEpollFileOps); + file->set_private_data(ep); + *out_file = file; + return Kernel::FS::kOk; +} + +EpollInstance* EpollInstance::from_file(Kernel::FS::File* file) noexcept { + if (file == nullptr || file->get_f_ops() != &kEpollFileOps) { + return nullptr; + } + return static_cast(file->get_private_data()); +} + +} // namespace Kernel::IPC diff --git a/kernel/ipc/EventLoop.hpp b/kernel/ipc/EventLoop.hpp new file mode 100644 index 0000000..7ccf1de --- /dev/null +++ b/kernel/ipc/EventLoop.hpp @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#pragma once + +#include "fs/File.hpp" +#include "process/wait_queue.hpp" +#include "uapi/event.hpp" + +#include +#include +#include + +namespace Kernel::Process { +class Process; +} // namespace Kernel::Process + +namespace Kernel::IPC { + +inline constexpr size_t kEpollMaxWatches = 64U; + +class EventFd final { + public: + EventFd(uint64_t initval, bool semaphore) noexcept; + ~EventFd() noexcept = default; + + EventFd(const EventFd&) = delete; + EventFd& operator=(const EventFd&) = delete; + EventFd(EventFd&&) = delete; + EventFd& operator=(EventFd&&) = delete; + + void retain() noexcept; + void release() noexcept; + + [[nodiscard]] int64_t read_value(uint64_t& out_val, bool nonblock) noexcept; + [[nodiscard]] int64_t write_value(uint64_t add_val, bool nonblock) noexcept; + [[nodiscard]] int16_t poll(int16_t events) const noexcept; + + [[nodiscard]] static int32_t create_file(uint64_t initval, uint32_t open_flags, bool semaphore, + Kernel::FS::File** out_file) noexcept; + + private: + std::atomic m_refs{1U}; + uint64_t m_counter{0ULL}; + bool m_semaphore{false}; + Process::WaitQueue m_read_wq; + Process::WaitQueue m_write_wq; +}; + +class TimerFd final { + public: + explicit TimerFd(int32_t clockid) noexcept; + ~TimerFd() noexcept = default; + + TimerFd(const TimerFd&) = delete; + TimerFd& operator=(const TimerFd&) = delete; + TimerFd(TimerFd&&) = delete; + TimerFd& operator=(TimerFd&&) = delete; + + void retain() noexcept; + void release() noexcept; + + [[nodiscard]] int32_t settime(uint32_t flags, const linux_itimerspec& new_spec, + linux_itimerspec* old_spec) noexcept; + void gettime(linux_itimerspec& out_spec) noexcept; + [[nodiscard]] int64_t read_expirations(uint64_t& out_count, bool nonblock) noexcept; + [[nodiscard]] int16_t poll(int16_t events) noexcept; + + [[nodiscard]] static int32_t create_file(int32_t clockid, uint32_t open_flags, + Kernel::FS::File** out_file) noexcept; + [[nodiscard]] static TimerFd* from_file(Kernel::FS::File* file) noexcept; + + private: + void advance_locked(uint64_t now_ns) noexcept; + + std::atomic m_refs{1U}; + int32_t m_clockid{1}; + bool m_armed{false}; + uint64_t m_next_expiry_ns{0ULL}; + uint64_t m_interval_ns{0ULL}; + uint64_t m_expirations{0ULL}; +}; + +class EpollInstance final { + public: + EpollInstance() noexcept = default; + ~EpollInstance() noexcept = default; + + EpollInstance(const EpollInstance&) = delete; + EpollInstance& operator=(const EpollInstance&) = delete; + EpollInstance(EpollInstance&&) = delete; + EpollInstance& operator=(EpollInstance&&) = delete; + + void retain() noexcept; + void release() noexcept; + + [[nodiscard]] int32_t ctl(int32_t op, int32_t target_fd, const Kernel::FS::File* target_file, + const linux_epoll_event* event) noexcept; + [[nodiscard]] int32_t poll_ready(Kernel::Process::Process& proc, linux_epoll_event* out_events, + size_t max_events) noexcept; + [[nodiscard]] int16_t poll(int16_t events) noexcept; + + [[nodiscard]] static int32_t create_file(Kernel::FS::File** out_file) noexcept; + [[nodiscard]] static EpollInstance* from_file(Kernel::FS::File* file) noexcept; + + private: + struct WatchEntry { + bool active{false}; + bool armed{true}; + int32_t fd{-1}; + const Kernel::FS::File* file{nullptr}; + uint32_t events{0U}; + uint32_t last_ready{0U}; + uint64_t data{0ULL}; + }; + + std::atomic m_refs{1U}; + WatchEntry m_watches[kEpollMaxWatches]{}; +}; + +} // namespace Kernel::IPC diff --git a/kernel/kernel.mk b/kernel/kernel.mk index 3aea683..8163543 100644 --- a/kernel/kernel.mk +++ b/kernel/kernel.mk @@ -26,6 +26,7 @@ KERNEL_CORE_SRCS := \ kernel/fs/rootfs/rootfs.cpp \ kernel/fs/tmpfs/tmpfs.cpp \ kernel/input/InputQueue.cpp \ + kernel/ipc/EventLoop.cpp \ kernel/ipc/Pipe.cpp \ kernel/loader/elf64.cpp \ kernel/loader/elf_loader.cpp \ @@ -40,6 +41,8 @@ KERNEL_CORE_SRCS := \ kernel/process/scheduler.cpp \ kernel/process/stack_builder.cpp \ kernel/process/wait_queue.cpp \ + kernel/sync/Futex.cpp \ + kernel/syscalls/EventSyscalls.cpp \ kernel/syscalls/FileSyscalls.cpp \ kernel/syscalls/MemorySyscalls.cpp \ kernel/syscalls/SocketSyscalls.cpp \ diff --git a/kernel/main.cpp b/kernel/main.cpp index ab6d595..ea1ad99 100644 --- a/kernel/main.cpp +++ b/kernel/main.cpp @@ -254,7 +254,17 @@ extern "C" void kmain(uintptr_t dtb_paddr) { if (Kernel::FS::rootfs_mount_from_initrd(g_initrd_loc) == Kernel::FS::kOk && Kernel::FS::devfs_init_and_mount() == Kernel::FS::kOk && Kernel::FS::tmpfs_init_and_mount() == Kernel::FS::kOk) { - Kernel::Log::info("kernel", "VFS rootfs (/), devfs (/dev), and tmpfs (/tmp) mounted."); + Kernel::FS::Superblock* shm_sb = nullptr; + if (Kernel::FS::tmpfs_create_sb(&shm_sb) == Kernel::FS::kOk && shm_sb != nullptr) { + if (Kernel::FS::vfs_mount("/dev/shm", shm_sb) != Kernel::FS::kOk) { + if (Kernel::FS::Dentry* const root = shm_sb->get_root(); root != nullptr) { + root->release(); + } + Kernel::FS::vfs_free_superblock(shm_sb); + } + } + Kernel::Log::info("kernel", + "VFS rootfs (/), devfs (/dev), tmpfs (/tmp, /dev/shm) mounted."); } else { Kernel::Log::warn("kernel", "VFS initialization failed."); } diff --git a/kernel/mm/AddressSpace.cpp b/kernel/mm/AddressSpace.cpp index 6b8a457..a96948c 100644 --- a/kernel/mm/AddressSpace.cpp +++ b/kernel/mm/AddressSpace.cpp @@ -75,7 +75,7 @@ void AddressSpace::clear_vmas() noexcept { const uintptr_t page_mask = page_size - 1U; for (size_t idx = 0U; idx < m_vma_count; ++idx) { - if (m_vmas[idx].inode != nullptr && m_vmas[idx].inode->is_chr() && + if (m_vmas[idx].inode != nullptr && (m_vmas[idx].map_flags & Kernel::UAPI::MAP_SHARED) != 0ULL) { for (uintptr_t page_vaddr = m_vmas[idx].start_vaddr; page_vaddr < m_vmas[idx].end_vaddr; page_vaddr += page_size) { @@ -462,8 +462,13 @@ bool AddressSpace::resolve_file_backed_page(uintptr_t root_paddr, uintptr_t vadd vma->file_offset + static_cast(aligned_vaddr - vma->start_vaddr); uintptr_t cached_paddr = 0U; - const int32_t pc_rc = Kernel::FS::PageCache::instance().get_or_load_page( - vma->inode, page_offset, page_size, cached_paddr); + int32_t pc_rc = Kernel::FS::kEinval; + if (vma->inode->get_i_ops() != nullptr && vma->inode->get_i_ops()->get_page != nullptr) { + pc_rc = vma->inode->get_i_ops()->get_page(vma->inode, page_offset, page_size, cached_paddr); + } else { + pc_rc = Kernel::FS::PageCache::instance().get_or_load_page(vma->inode, page_offset, + page_size, cached_paddr); + } if (pc_rc != Kernel::FS::kOk || cached_paddr == 0U) { return false; } diff --git a/kernel/net/af_unix.cpp b/kernel/net/af_unix.cpp index e73ef71..1ab55a3 100644 --- a/kernel/net/af_unix.cpp +++ b/kernel/net/af_unix.cpp @@ -43,6 +43,17 @@ bool has_signal_interrupt() noexcept { return cur != nullptr && Kernel::Process::has_unblocked_pending_signal(*cur); } +void release_rights_batch(UnixRightsBatch& batch) noexcept { + for (size_t idx = 0U; idx < batch.count && idx < kUnixMaxRightsPerMsg; ++idx) { + if (batch.files[idx] != nullptr) { + (void)Kernel::FS::vfs_close(batch.files[idx]); + batch.files[idx] = nullptr; + } + } + batch.count = 0U; + batch.byte_pos = 0ULL; +} + void emit_sigpipe_if_needed(bool nosignal) noexcept { if (nosignal) { return; @@ -136,9 +147,26 @@ void UnixSocket::retain() noexcept { void UnixSocket::release() noexcept { if (m_refs.fetch_sub(1U, std::memory_order_acq_rel) == 1U) { if (m_owns_rings) { + while (m_owned_ring_a.rights_count > 0U) { + release_rights_batch(m_owned_ring_a.rights_queue[m_owned_ring_a.rights_head]); + m_owned_ring_a.rights_head = + (m_owned_ring_a.rights_head + 1U) % kUnixMaxRightsBatches; + --m_owned_ring_a.rights_count; + } + while (m_owned_ring_b.rights_count > 0U) { + release_rights_batch(m_owned_ring_b.rights_queue[m_owned_ring_b.rights_head]); + m_owned_ring_b.rights_head = + (m_owned_ring_b.rights_head + 1U) % kUnixMaxRightsBatches; + --m_owned_ring_b.rights_count; + } m_owned_ring_a.~StreamRing(); m_owned_ring_b.~StreamRing(); } + while (m_dgram.count > 0U) { + release_rights_batch(m_dgram.slots[m_dgram.head].rights); + m_dgram.head = (m_dgram.head + 1U) % kUnixMaxDgrams; + --m_dgram.count; + } delete this; } } @@ -579,11 +607,36 @@ void UnixSocket::close_endpoint() noexcept { if (peer_to_release != nullptr) { peer_to_release->release(); } - delete ring_a_to_delete; - delete ring_b_to_delete; + if (ring_a_to_delete != nullptr) { + while (ring_a_to_delete->rights_count > 0U) { + release_rights_batch(ring_a_to_delete->rights_queue[ring_a_to_delete->rights_head]); + ring_a_to_delete->rights_head = + (ring_a_to_delete->rights_head + 1U) % kUnixMaxRightsBatches; + --ring_a_to_delete->rights_count; + } + delete ring_a_to_delete; + } + if (ring_b_to_delete != nullptr) { + while (ring_b_to_delete->rights_count > 0U) { + release_rights_batch(ring_b_to_delete->rights_queue[ring_b_to_delete->rights_head]); + ring_b_to_delete->rights_head = + (ring_b_to_delete->rights_head + 1U) % kUnixMaxRightsBatches; + --ring_b_to_delete->rights_count; + } + delete ring_b_to_delete; + } } int64_t UnixSocket::stream_read(void* dst, size_t count, bool nonblock) noexcept { + return stream_read_with_rights(dst, count, nonblock, nullptr); +} + +int64_t UnixSocket::stream_read_with_rights(void* dst, size_t count, bool nonblock, + UnixRightsBatch* out_rights) noexcept { + if (out_rights != nullptr) { + out_rights->count = 0U; + out_rights->byte_pos = 0ULL; + } if (m_type != Kernel::UAPI::SOCK_STREAM) { return Kernel::FS::kEopnotsupp; } @@ -597,6 +650,11 @@ int64_t UnixSocket::stream_read(void* dst, size_t count, bool nonblock) noexcept auto* const out = static_cast(dst); while (true) { + UnixRightsBatch dropped_rights{}; + bool have_dropped_rights = false; + int64_t read_ret = 0; + bool should_return = false; + { const Sync::IrqGuard irq_guard; if (m_state == UnixSocketState::Unbound || m_state == UnixSocketState::Bound || @@ -607,34 +665,82 @@ int64_t UnixSocket::stream_read(void* dst, size_t count, bool nonblock) noexcept return 0; } if (m_rx_ring->count > 0U) { - const size_t to_read = (count < m_rx_ring->count) ? count : m_rx_ring->count; + size_t to_read = (count < m_rx_ring->count) ? count : m_rx_ring->count; + const uint64_t read_start_pos = m_rx_ring->total_read; + + // Respect rights batch boundaries so each message receives its exact SCM_RIGHTS + if (m_rx_ring->rights_count > 0U) { + const UnixRightsBatch& head_batch = + m_rx_ring->rights_queue[m_rx_ring->rights_head]; + if (head_batch.byte_pos > read_start_pos) { + const uint64_t until_rights = head_batch.byte_pos - read_start_pos; + if (until_rights < static_cast(to_read)) { + to_read = static_cast(until_rights); + } + } else { + // Pop this rights batch since our read begins at/after its byte_pos + if (m_rx_ring->rights_count > 1U) { + const size_t next_idx = + (m_rx_ring->rights_head + 1U) % kUnixMaxRightsBatches; + const uint64_t next_pos = m_rx_ring->rights_queue[next_idx].byte_pos; + if (next_pos > read_start_pos) { + const uint64_t until_next = next_pos - read_start_pos; + if (until_next < static_cast(to_read)) { + to_read = static_cast(until_next); + } + } + } + if (out_rights != nullptr) { + *out_rights = head_batch; + } else { + dropped_rights = head_batch; + have_dropped_rights = true; + } + m_rx_ring->rights_queue[m_rx_ring->rights_head] = UnixRightsBatch{}; + m_rx_ring->rights_head = + (m_rx_ring->rights_head + 1U) % kUnixMaxRightsBatches; + --m_rx_ring->rights_count; + } + } + for (size_t idx = 0U; idx < to_read; ++idx) { out[idx] = m_rx_ring->buf[m_rx_ring->head]; m_rx_ring->head = (m_rx_ring->head + 1U) % kUnixStreamBufSize; } m_rx_ring->count -= to_read; + m_rx_ring->total_read += to_read; if (m_peer != nullptr) { m_peer->m_write_wq.wake_all(); } - return static_cast(to_read); - } - if (m_rx_ring->peer_closed || m_rx_ring->write_shutdown || - m_state == UnixSocketState::Closed) { + read_ret = static_cast(to_read); + should_return = true; + } else if (m_rx_ring->peer_closed || m_rx_ring->write_shutdown || + m_state == UnixSocketState::Closed) { return 0; // EOF - } - if (nonblock) { + } else if (nonblock) { return Kernel::FS::kEagain; - } - if (has_signal_interrupt()) { + } else if (has_signal_interrupt()) { return Kernel::FS::kEintr; } } + + if (have_dropped_rights) { + release_rights_batch(dropped_rights); + } + if (should_return) { + return read_ret; + } m_read_wq.sleep(); } } int64_t UnixSocket::stream_write(const void* src, size_t count, bool nonblock, bool nosignal) noexcept { + return stream_write_with_rights(src, count, nonblock, nosignal, nullptr); +} + +int64_t UnixSocket::stream_write_with_rights(const void* src, size_t count, bool nonblock, + bool nosignal, UnixRightsBatch* in_rights) noexcept { if (m_type != Kernel::UAPI::SOCK_STREAM) { return Kernel::FS::kEopnotsupp; } @@ -647,6 +753,7 @@ int64_t UnixSocket::stream_write(const void* src, size_t count, bool nonblock, const auto* const in = static_cast(src); size_t total_written = 0U; + bool rights_pending = (in_rights != nullptr && in_rights->count > 0U); while (total_written < count) { { @@ -664,7 +771,18 @@ int64_t UnixSocket::stream_write(const void* src, size_t count, bool nonblock, return Kernel::FS::kEpipe; } - if (m_tx_ring->count < kUnixStreamBufSize) { + const bool rights_space_ok = + (!rights_pending || m_tx_ring->rights_count < kUnixMaxRightsBatches); + if (m_tx_ring->count < kUnixStreamBufSize && rights_space_ok) { + if (rights_pending) { + in_rights->byte_pos = m_tx_ring->total_written; + m_tx_ring->rights_queue[m_tx_ring->rights_tail] = *in_rights; + m_tx_ring->rights_tail = (m_tx_ring->rights_tail + 1U) % kUnixMaxRightsBatches; + ++m_tx_ring->rights_count; + *in_rights = UnixRightsBatch{}; + rights_pending = false; + } + const size_t space = kUnixStreamBufSize - m_tx_ring->count; const size_t rem = count - total_written; const size_t batch = (rem < space) ? rem : space; @@ -674,6 +792,7 @@ int64_t UnixSocket::stream_write(const void* src, size_t count, bool nonblock, m_tx_ring->tail = (m_tx_ring->tail + 1U) % kUnixStreamBufSize; } m_tx_ring->count += batch; + m_tx_ring->total_written += batch; total_written += batch; if (m_peer != nullptr) { m_peer->m_read_wq.wake_all(); @@ -700,7 +819,7 @@ int64_t UnixSocket::stream_write(const void* src, size_t count, bool nonblock, int64_t UnixSocket::dgram_sendto(const void* src, size_t len, const linux_sockaddr_un* dest_addr, bool has_dest, bool nonblock, bool nosignal, - Kernel::FS::Dentry* cwd) noexcept { + Kernel::FS::Dentry* cwd, UnixRightsBatch* in_rights) noexcept { if (m_type != Kernel::UAPI::SOCK_DGRAM) { return Kernel::FS::kEopnotsupp; } @@ -766,6 +885,12 @@ int64_t UnixSocket::dgram_sendto(const void* src, size_t len, const linux_sockad if (len > 0U) { std::memcpy(slot.data, src, len); } + if (in_rights != nullptr && in_rights->count > 0U) { + slot.rights = *in_rights; + *in_rights = UnixRightsBatch{}; + } else { + slot.rights = UnixRightsBatch{}; + } dest_sock->m_dgram.tail = (dest_sock->m_dgram.tail + 1U) % kUnixMaxDgrams; ++dest_sock->m_dgram.count; dest_sock->m_read_wq.wake_all(); @@ -783,7 +908,11 @@ int64_t UnixSocket::dgram_sendto(const void* src, size_t len, const linux_sockad } int64_t UnixSocket::dgram_recvfrom(void* dst, size_t max_len, linux_sockaddr_un* out_src_addr, - bool nonblock) noexcept { + bool nonblock, UnixRightsBatch* out_rights) noexcept { + if (out_rights != nullptr) { + out_rights->count = 0U; + out_rights->byte_pos = 0ULL; + } if (m_type != Kernel::UAPI::SOCK_DGRAM) { return Kernel::FS::kEopnotsupp; } @@ -792,6 +921,10 @@ int64_t UnixSocket::dgram_recvfrom(void* dst, size_t max_len, linux_sockaddr_un* } while (true) { + UnixRightsBatch dropped_rights{}; + bool have_dropped_rights = false; + int64_t recv_ret = 0; + bool should_return = false; { const Sync::IrqGuard irq_guard; if (m_dgram.count > 0U) { @@ -805,24 +938,36 @@ int64_t UnixSocket::dgram_recvfrom(void* dst, size_t max_len, linux_sockaddr_un* if (out_src_addr != nullptr) { *out_src_addr = slot.sender_addr; } + if (slot.rights.count > 0U) { + if (out_rights != nullptr) { + *out_rights = slot.rights; + } else { + dropped_rights = slot.rights; + have_dropped_rights = true; + } + slot.rights = UnixRightsBatch{}; + } const size_t msg_len = slot.len; slot.len = 0U; m_dgram.head = (m_dgram.head + 1U) % kUnixMaxDgrams; --m_dgram.count; m_write_wq.wake_all(); - return static_cast(msg_len); - } - - if (m_dgram.read_shutdown || (m_dgram.closed && m_dgram.count == 0U)) { + recv_ret = static_cast(msg_len); + should_return = true; + } else if (m_dgram.read_shutdown || (m_dgram.closed && m_dgram.count == 0U)) { return 0; - } - if (nonblock) { + } else if (nonblock) { return Kernel::FS::kEagain; - } - if (has_signal_interrupt()) { + } else if (has_signal_interrupt()) { return Kernel::FS::kEintr; } } + if (have_dropped_rights) { + release_rights_batch(dropped_rights); + } + if (should_return) { + return recv_ret; + } m_read_wq.sleep(); } } diff --git a/kernel/net/af_unix.hpp b/kernel/net/af_unix.hpp index 7c0574e..804c467 100644 --- a/kernel/net/af_unix.hpp +++ b/kernel/net/af_unix.hpp @@ -20,6 +20,14 @@ inline constexpr size_t kUnixMaxBacklog = 16U; inline constexpr size_t kUnixMaxDgrams = 64U; inline constexpr size_t kUnixMaxDgramPayload = 2048U; inline constexpr size_t kUnixMaxBoundSockets = 64U; +inline constexpr size_t kUnixMaxRightsPerMsg = 16U; +inline constexpr size_t kUnixMaxRightsBatches = 16U; + +struct UnixRightsBatch { + Kernel::FS::File* files[kUnixMaxRightsPerMsg]{}; + size_t count{0U}; + uint64_t byte_pos{0ULL}; +}; enum class UnixSocketState : uint8_t { Unbound = 0U, @@ -33,6 +41,7 @@ struct UnixDgramMessage { linux_sockaddr_un sender_addr{}; size_t len{0U}; uint8_t data[kUnixMaxDgramPayload]{}; + UnixRightsBatch rights{}; }; class UnixSocket final { @@ -69,15 +78,22 @@ class UnixSocket final { void close_endpoint() noexcept; [[nodiscard]] int64_t stream_read(void* dst, size_t count, bool nonblock) noexcept; + [[nodiscard]] int64_t stream_read_with_rights(void* dst, size_t count, bool nonblock, + UnixRightsBatch* out_rights) noexcept; [[nodiscard]] int64_t stream_write(const void* src, size_t count, bool nonblock, bool nosignal) noexcept; + [[nodiscard]] int64_t stream_write_with_rights(const void* src, size_t count, bool nonblock, + bool nosignal, + UnixRightsBatch* in_rights) noexcept; [[nodiscard]] int64_t dgram_sendto(const void* src, size_t len, const linux_sockaddr_un* dest_addr, bool has_dest, bool nonblock, bool nosignal, - Kernel::FS::Dentry* cwd = nullptr) noexcept; + Kernel::FS::Dentry* cwd = nullptr, + UnixRightsBatch* in_rights = nullptr) noexcept; [[nodiscard]] int64_t dgram_recvfrom(void* dst, size_t max_len, linux_sockaddr_un* out_src_addr, - bool nonblock) noexcept; + bool nonblock, + UnixRightsBatch* out_rights = nullptr) noexcept; [[nodiscard]] int16_t poll(int16_t events) const noexcept; @@ -100,11 +116,17 @@ class UnixSocket final { size_t head{0U}; size_t tail{0U}; size_t count{0U}; + uint64_t total_written{0ULL}; + uint64_t total_read{0ULL}; bool peer_closed{false}; bool write_shutdown{false}; bool heap_allocated{false}; uint32_t refs{0U}; uint8_t buf[kUnixStreamBufSize]{}; + UnixRightsBatch rights_queue[kUnixMaxRightsBatches]{}; + size_t rights_head{0U}; + size_t rights_tail{0U}; + size_t rights_count{0U}; }; struct DgramQueue { diff --git a/kernel/process/Process.cpp b/kernel/process/Process.cpp index b6ad707..7c17abc 100644 --- a/kernel/process/Process.cpp +++ b/kernel/process/Process.cpp @@ -9,6 +9,7 @@ #include "mm/heap.hpp" #include "mm/pfa.hpp" #include "process/scheduler.hpp" +#include "sync/Futex.hpp" #include "sync/IrqGuard.hpp" #include @@ -76,8 +77,6 @@ bool has_any_non_zombie_process() noexcept { namespace Kernel::Process { -Process::~Process() noexcept = default; - bool Process::setsid() noexcept { if (m_pgid == m_pid) { return false; @@ -144,14 +143,14 @@ void Process::accumulate_child_ticks(const Process& child) noexcept { // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) void Process::attach_elf(Loader::LoadedElf&& loaded) noexcept { - m_address_space = static_cast(loaded.address_space); + m_shared->address_space = static_cast(loaded.address_space); m_entry_point = loaded.entry_point; if (loaded.max_vaddr != 0U) { - m_brk_start = loaded.max_vaddr; - m_brk_current = loaded.max_vaddr; + m_shared->brk_start = loaded.max_vaddr; + m_shared->brk_current = loaded.max_vaddr; } - if (m_mmap_next_vaddr == 0U) { - m_mmap_next_vaddr = HAL::get_platform_info().user_mmap_base; + if (m_shared->mmap_next_vaddr == 0U) { + m_shared->mmap_next_vaddr = HAL::get_platform_info().user_mmap_base; } } @@ -172,7 +171,7 @@ void Process::prepare_kstack() noexcept { } int64_t Process::execute() noexcept { - if (!m_address_space.is_valid()) { + if (m_shared == nullptr || !m_shared->address_space.is_valid()) { Kernel::Log::warn(kProcTag, "execute rejected invalid address space pid={}", m_pid); return -1; } @@ -210,15 +209,29 @@ Process* Process::create(uint32_t ppid) noexcept { } auto* const proc = new (raw_proc) Process{}; + void* const raw_shared = MM::kzalloc(sizeof(SharedProcessState), alignof(SharedProcessState)); + if (raw_shared == nullptr) { + proc->~Process(); + MM::kfree(proc); + return nullptr; + } + proc->m_shared = new (raw_shared) SharedProcessState{}; + const uintptr_t kstack_pa = Kernel::MM::alloc_frames(KERNEL_STACK_PAGES); if (kstack_pa == 0U) { + proc->m_shared->~SharedProcessState(); + MM::kfree(proc->m_shared); + proc->m_shared = nullptr; proc->~Process(); MM::kfree(proc); return nullptr; } - if (!proc->m_fds.init(INITIAL_FD_CAPACITY)) { + if (!proc->m_shared->fds.init(INITIAL_FD_CAPACITY)) { Kernel::MM::free_frames(kstack_pa, KERNEL_STACK_PAGES); + proc->m_shared->~SharedProcessState(); + MM::kfree(proc->m_shared); + proc->m_shared = nullptr; proc->~Process(); MM::kfree(proc); return nullptr; @@ -232,6 +245,8 @@ Process* Process::create(uint32_t ppid) noexcept { g_next_pid = 1U; } proc->m_pid = g_next_pid++; + proc->m_tgid = proc->m_pid; + proc->m_is_thread = false; proc->m_ppid = ppid; proc->m_pgid = (ppid == 0U) ? proc->m_pid : 0U; proc->m_sid = (ppid == 0U) ? proc->m_pid : 0U; @@ -261,15 +276,18 @@ Process* Process::create(uint32_t ppid) noexcept { if (stderr_file != nullptr) { (void)Kernel::FS::vfs_close(stderr_file); } - proc->m_fds.destroy(); + proc->m_shared->fds.destroy(); Kernel::MM::free_frames(kstack_pa, KERNEL_STACK_PAGES); + proc->m_shared->~SharedProcessState(); + MM::kfree(proc->m_shared); + proc->m_shared = nullptr; proc->~Process(); MM::kfree(proc); return nullptr; } - (void)proc->m_fds.install(0U, stdin_file, 0U); - (void)proc->m_fds.install(1U, stdout_file, 0U); - (void)proc->m_fds.install(2U, stderr_file, 0U); + (void)proc->m_shared->fds.install(0U, stdin_file, 0U); + (void)proc->m_shared->fds.install(1U, stdout_file, 0U); + (void)proc->m_shared->fds.install(2U, stderr_file, 0U); proc->m_global_prev = g_process_list_tail; proc->m_global_next = nullptr; @@ -283,7 +301,83 @@ Process* Process::create(uint32_t ppid) noexcept { return proc; } +Process* Process::create_thread(Process& parent) noexcept { + const Sync::IrqGuard irq_guard; + + if (parent.m_shared == nullptr || active_count() >= default_rlimit_nproc()) { + return nullptr; + } + + void* const raw_proc = MM::kzalloc(sizeof(Process), alignof(Process)); + if (raw_proc == nullptr) { + return nullptr; + } + auto* const thread = new (raw_proc) Process{}; + + const uintptr_t kstack_pa = Kernel::MM::alloc_frames(KERNEL_STACK_PAGES); + if (kstack_pa == 0U) { + thread->~Process(); + MM::kfree(thread); + return nullptr; + } + + const size_t page_size = HAL::get_platform_info().page_size; + thread->m_kstack_paddr = kstack_pa; + thread->m_kstack_top = MM::phys_to_virt(kstack_pa) + (KERNEL_STACK_PAGES * page_size); + + parent.m_shared->refs.fetch_add(1U, std::memory_order_acq_rel); + thread->m_shared = parent.m_shared; + + if (g_next_pid == 0U) { + g_next_pid = 1U; + } + thread->m_pid = g_next_pid++; + thread->m_tgid = parent.m_tgid; + thread->m_is_thread = true; + thread->m_ppid = parent.m_ppid; + thread->m_pgid = parent.m_pgid; + thread->m_sid = parent.m_sid; + thread->m_umask = parent.m_umask; + thread->m_rlim_nofile_cur = parent.m_rlim_nofile_cur; + thread->m_rlim_nofile_max = parent.m_rlim_nofile_max; + thread->m_rlim_nproc_cur = parent.m_rlim_nproc_cur; + thread->m_rlim_nproc_max = parent.m_rlim_nproc_max; + thread->m_entry_point = parent.m_entry_point; + thread->m_state = ProcessState::Ready; + thread->set_cwd(parent.cwd()); + thread->set_exe_path(parent.exe_path()); + + thread->m_global_prev = g_process_list_tail; + thread->m_global_next = nullptr; + if (g_process_list_tail != nullptr) { + g_process_list_tail->m_global_next = thread; + } else { + g_process_list_head = thread; + } + g_process_list_tail = thread; + + return thread; +} + void Process::destroy(Process& proc) noexcept { + const bool is_root_session_leader = + !proc.m_is_thread && proc.m_ppid == 0U && proc.m_sid != 0U && proc.m_sid == proc.m_pid; + const uint32_t session_id = proc.m_sid; + + // When destroying a thread-group leader, reap any remaining sibling threads in that group + // first. + if (!proc.m_is_thread && proc.m_tgid != 0U) { + Process* sibling = g_process_list_head; + while (sibling != nullptr) { + Process* const next = sibling->m_global_next; + if (sibling != &proc && sibling->m_is_thread && sibling->m_tgid == proc.m_tgid) { + destroy(*sibling); + } + sibling = next; + } + } + + SharedProcessState* shared_to_free = nullptr; { const Sync::IrqGuard irq_guard; @@ -313,17 +407,22 @@ void Process::destroy(Process& proc) noexcept { record_reaped_ticks(proc.m_pid, proc.m_utime + proc.m_stime); - // Idempotent teardown of dynamic fd_table, user stack, address space, kstack, and PCB - proc.m_fds.destroy(); + SharedProcessState* const shared = proc.m_shared; + proc.m_shared = nullptr; + const bool is_last_owner = + (shared != nullptr) && (shared->refs.fetch_sub(1U, std::memory_order_acq_rel) == 1U); - if (!proc.m_address_space.is_valid() && proc.m_user_stack.phys_base != 0U && - proc.m_user_stack.num_pages > 0U) { - Kernel::MM::free_frames(proc.m_user_stack.phys_base, proc.m_user_stack.num_pages); + if (is_last_owner) { + shared->fds.destroy(); + if (!shared->address_space.is_valid() && proc.m_user_stack.phys_base != 0U && + proc.m_user_stack.num_pages > 0U) { + Kernel::MM::free_frames(proc.m_user_stack.phys_base, proc.m_user_stack.num_pages); + } + shared->address_space.destroy(); + shared_to_free = shared; } proc.m_user_stack = UserStack{}; - proc.m_address_space.destroy(); - if (proc.m_kstack_paddr != 0U) { Kernel::MM::free_frames(proc.m_kstack_paddr, KERNEL_STACK_PAGES); proc.m_kstack_paddr = 0U; @@ -331,8 +430,30 @@ void Process::destroy(Process& proc) noexcept { } } + if (shared_to_free != nullptr) { + shared_to_free->~SharedProcessState(); + MM::kfree(shared_to_free); + } proc.~Process(); MM::kfree(&proc); + + // When destroying a root session leader (e.g., interactive shell launched from kernel shell), + // reap any remaining zombie session children so background jobs never leak PCBs or frames. + if (is_root_session_leader) { + bool reaped = true; + while (reaped) { + reaped = false; + for (Process* other = g_process_list_head; other != nullptr; + other = other->m_global_next) { + if (!other->m_is_thread && other->m_sid == session_id && + other->m_state == ProcessState::Zombie) { + destroy(*other); + reaped = true; + break; + } + } + } + } } Process* Process::find_by_pid(uint32_t pid) noexcept { @@ -384,6 +505,48 @@ void init_user_cpu_context(HAL::CpuContext& ctx, uintptr_t entry_point, uintptr_ HAL::get_cpu().init_user_context(ctx, entry_point, sp_el0, argc, argv_vaddr); } +[[noreturn]] void exit_current_thread(int64_t exit_code) noexcept { + auto& cpu = HAL::get_cpu(); + cpu.disable_interrupts(); + + auto* const proc = Process::current(); + if (proc == nullptr) { + while (true) { + cpu.halt(); + } + } + + if (proc->clear_child_tid() != 0U) { + const uintptr_t tid_ptr = proc->clear_child_tid(); + const uint32_t zero_tid = 0U; + (void)MM::copy_to_user(proc->address_space(), tid_ptr, &zero_tid, sizeof(zero_tid)); + (void)Sync::futex_wake_in_as(proc->address_space(), tid_ptr, 1U); + proc->set_clear_child_tid(0U); + } + + bool has_live_sibling = false; + for (Process* p = Process::list_head(); p != nullptr; p = p->next_global()) { + if (p != proc && p->tgid() == proc->tgid() && p->state() != ProcessState::Unused && + p->state() != ProcessState::Zombie) { + has_live_sibling = true; + break; + } + } + + if (has_live_sibling) { + proc->set_exit_status(exit_code); + proc->set_state(ProcessState::Zombie); + record_reaped_ticks(proc->pid(), proc->utime() + proc->stime()); + Scheduler::remove(proc); + Scheduler::schedule(); + while (true) { + cpu.halt(); + } + } + + exit_current_process(exit_code); +} + [[noreturn]] void exit_current_process(int64_t exit_code) noexcept { auto& cpu = HAL::get_cpu(); cpu.disable_interrupts(); @@ -403,32 +566,50 @@ void init_user_cpu_context(HAL::CpuContext& ctx, uintptr_t entry_point, uintptr_ } } - Kernel::Log::debug(kProcTag, "exit_current_process pid={} ppid={} code={}", proc->pid(), - proc->ppid(), exit_code); + Kernel::Log::debug(kProcTag, "exit_current_process pid={} tgid={} ppid={} code={}", proc->pid(), + proc->tgid(), proc->ppid(), exit_code); + + // Terminate all sibling threads in the same thread group + const uint32_t group_tgid = proc->tgid(); + for (Process* sibling = Process::list_head(); sibling != nullptr; + sibling = sibling->next_global()) { + if (sibling != proc && sibling->tgid() == group_tgid && + sibling->state() != ProcessState::Unused) { + if (!sibling->is_thread()) { + sibling->set_exit_status(exit_code); + } + sibling->set_state(ProcessState::Zombie); + Scheduler::remove(sibling); + if (sibling->active_wait_queue() != nullptr) { + sibling->active_wait_queue()->remove(sibling); + } + } + } proc->set_exit_status(exit_code); proc->set_state(ProcessState::Zombie); record_reaped_ticks(proc->pid(), proc->utime() + proc->stime()); - // Close all open descriptors & free fd_table immediately so downstream - // pipe readers receive EOF before the parent calls wait4() - proc->fds().destroy(); - if (proc->clear_child_tid() != 0U) { + const uintptr_t tid_ptr = proc->clear_child_tid(); const uint32_t zero_tid = 0U; - MM::copy_to_user(proc->address_space(), proc->clear_child_tid(), &zero_tid, - sizeof(zero_tid)); + (void)MM::copy_to_user(proc->address_space(), tid_ptr, &zero_tid, sizeof(zero_tid)); + (void)Sync::futex_wake_in_as(proc->address_space(), tid_ptr, 1U); proc->set_clear_child_tid(0U); } + // Close all open descriptors & free fd_table immediately so downstream + // pipe readers receive EOF before the parent calls wait4() + proc->fds().destroy(); + // Reparent any orphaned children to PID 1 - auto* const init_proc = (proc->pid() != 1U) ? Process::find_by_pid(1U) : nullptr; + auto* const init_proc = (group_tgid != 1U) ? Process::find_by_pid(1U) : nullptr; const uint32_t adopt_pid = (init_proc != nullptr) ? 1U : 0U; bool adopted_zombie = false; for (auto* child = Process::list_head(); child != nullptr; child = child->next_global()) { - if (child != proc && child->state() != ProcessState::Unused && - child->ppid() == proc->pid()) { + if (child != proc && !child->is_thread() && child->state() != ProcessState::Unused && + child->ppid() == group_tgid) { child->set_ppid(adopt_pid); if (child->state() == ProcessState::Zombie) { adopted_zombie = true; @@ -436,6 +617,27 @@ void init_user_cpu_context(HAL::CpuContext& ctx, uintptr_t entry_point, uintptr_ } } + // If a root session leader exits with no PID 1 init daemon to adopt background jobs, + // hang up remaining session members so interactive shells return cleanly to the kernel shell. + if (!proc->is_thread() && proc->ppid() == 0U && proc->sid() == group_tgid && + init_proc == nullptr) { + const uint64_t hup_bit = 1ULL << (SIG_HUP - 1U); + for (auto* member = Process::list_head(); member != nullptr; + member = member->next_global()) { + if (member != proc && member->tgid() != group_tgid && member->sid() == group_tgid && + member->state() != ProcessState::Unused && + member->state() != ProcessState::Zombie) { + if (member->state() == ProcessState::Stopped) { + send_signal(*member, SIG_CONT); + } + const bool hup_ignored = + (member->signals().action(SIG_HUP).handler == KERNEL_SIG_IGN); + const bool hup_blocked = (member->signals().blocked() & hup_bit) != 0ULL; + send_signal(*member, (hup_ignored || hup_blocked) ? SIG_KILL : SIG_HUP); + } + } + } + if (adopted_zombie && init_proc != nullptr) { send_signal(*init_proc, SIG_CHLD); init_proc->child_wait_queue().wake_all(); diff --git a/kernel/process/Process.hpp b/kernel/process/Process.hpp index 2e666b9..ccbc3cb 100644 --- a/kernel/process/Process.hpp +++ b/kernel/process/Process.hpp @@ -12,6 +12,7 @@ #include "process/stack_builder.hpp" #include "process/wait_queue.hpp" +#include #include #include @@ -26,10 +27,20 @@ constexpr size_t MAX_PATH_LEN = 256U; enum class ProcessState : uint8_t { Unused = 0, Ready, Running, Blocked, Stopped, Zombie }; +struct SharedProcessState { + std::atomic refs{1U}; + MM::AddressSpace address_space; + FdTable fds; + SignalTable signals; + uintptr_t brk_start{0U}; + uintptr_t brk_current{0U}; + uintptr_t mmap_next_vaddr{0U}; +}; + class Process { public: Process() = default; - ~Process() noexcept; + ~Process() noexcept = default; Process(const Process&) = delete; Process& operator=(const Process&) = delete; @@ -38,6 +49,7 @@ class Process { // --- Static Lifecycle & Global Process Table --- [[nodiscard]] static Process* create(uint32_t ppid = 0U) noexcept; + [[nodiscard]] static Process* create_thread(Process& parent) noexcept; static void destroy(Process& proc) noexcept; [[nodiscard]] static Process* find_by_pid(uint32_t pid) noexcept; [[nodiscard]] static Process* list_head() noexcept; @@ -48,6 +60,8 @@ class Process { // --- Identity & Job Control --- [[nodiscard]] constexpr uint32_t pid() const noexcept { return m_pid; } + [[nodiscard]] constexpr uint32_t tgid() const noexcept { return m_tgid; } + [[nodiscard]] constexpr bool is_thread() const noexcept { return m_is_thread; } [[nodiscard]] constexpr uint32_t ppid() const noexcept { return m_ppid; } constexpr void set_ppid(uint32_t new_ppid) noexcept { m_ppid = new_ppid; } @@ -89,16 +103,18 @@ class Process { [[nodiscard]] constexpr size_t cstime() const noexcept { return m_cstime; } // --- Memory, Stack, Resource Limits & Paths --- - [[nodiscard]] MM::AddressSpace& address_space() noexcept { return m_address_space; } - [[nodiscard]] const MM::AddressSpace& address_space() const noexcept { return m_address_space; } + [[nodiscard]] MM::AddressSpace& address_space() noexcept { return m_shared->address_space; } + [[nodiscard]] const MM::AddressSpace& address_space() const noexcept { + return m_shared->address_space; + } - [[nodiscard]] constexpr uintptr_t brk_start() const noexcept { return m_brk_start; } - constexpr void set_brk_start(uintptr_t addr) noexcept { m_brk_start = addr; } - [[nodiscard]] constexpr uintptr_t brk_current() const noexcept { return m_brk_current; } - constexpr void set_brk_current(uintptr_t addr) noexcept { m_brk_current = addr; } + [[nodiscard]] uintptr_t brk_start() const noexcept { return m_shared->brk_start; } + void set_brk_start(uintptr_t addr) noexcept { m_shared->brk_start = addr; } + [[nodiscard]] uintptr_t brk_current() const noexcept { return m_shared->brk_current; } + void set_brk_current(uintptr_t addr) noexcept { m_shared->brk_current = addr; } - [[nodiscard]] constexpr uintptr_t mmap_next_vaddr() const noexcept { return m_mmap_next_vaddr; } - constexpr void set_mmap_next_vaddr(uintptr_t addr) noexcept { m_mmap_next_vaddr = addr; } + [[nodiscard]] uintptr_t mmap_next_vaddr() const noexcept { return m_shared->mmap_next_vaddr; } + void set_mmap_next_vaddr(uintptr_t addr) noexcept { m_shared->mmap_next_vaddr = addr; } [[nodiscard]] constexpr uintptr_t entry_point() const noexcept { return m_entry_point; } constexpr void set_entry_point(uintptr_t addr) noexcept { m_entry_point = addr; } @@ -136,11 +152,11 @@ class Process { constexpr void set_clear_child_tid(uintptr_t tidptr) noexcept { m_clear_child_tid = tidptr; } // --- Subsystem Accessors & Execution --- - [[nodiscard]] FdTable& fds() noexcept { return m_fds; } - [[nodiscard]] const FdTable& fds() const noexcept { return m_fds; } + [[nodiscard]] FdTable& fds() noexcept { return m_shared->fds; } + [[nodiscard]] const FdTable& fds() const noexcept { return m_shared->fds; } - [[nodiscard]] SignalTable& signals() noexcept { return m_signals; } - [[nodiscard]] const SignalTable& signals() const noexcept { return m_signals; } + [[nodiscard]] SignalTable& signals() noexcept { return m_shared->signals; } + [[nodiscard]] const SignalTable& signals() const noexcept { return m_shared->signals; } [[nodiscard]] WaitQueue& child_wait_queue() noexcept { return m_child_wait_queue; } [[nodiscard]] const WaitQueue& child_wait_queue() const noexcept { return m_child_wait_queue; } @@ -205,19 +221,15 @@ class Process { uint64_t m_rlim_nofile_max{DEFAULT_RLIMIT_NOFILE_MAX}; uint64_t m_rlim_nproc_cur{0ULL}; uint64_t m_rlim_nproc_max{0ULL}; - MM::AddressSpace m_address_space; + SharedProcessState* m_shared{nullptr}; uintptr_t m_kstack_paddr{0U}; uintptr_t m_kstack_top{0U}; uintptr_t m_entry_point{0U}; - uintptr_t m_brk_start{0U}; - uintptr_t m_brk_current{0U}; - uintptr_t m_mmap_next_vaddr{0U}; uintptr_t m_clear_child_tid{0U}; UserStack m_user_stack{}; WaitQueue m_child_wait_queue; - SignalTable m_signals; - FdTable m_fds; uint32_t m_pid{0U}; + uint32_t m_tgid{0U}; uint32_t m_ppid{0U}; uint32_t m_pgid{0U}; uint32_t m_sid{0U}; @@ -225,6 +237,7 @@ class Process { uint32_t m_timeslice{0U}; uint32_t m_stop_signal{0U}; ProcessState m_state{ProcessState::Unused}; + bool m_is_thread{false}; bool m_stop_reported{false}; bool m_continued{false}; bool m_kctx_initialized{false}; @@ -263,6 +276,7 @@ inline int64_t enter_user_context(const HAL::CpuContext* ctx) noexcept { return HAL::get_cpu().enter_user_context(*ctx); } +[[noreturn]] void exit_current_thread(int64_t exit_code) noexcept; [[noreturn]] void exit_current_process(int64_t exit_code) noexcept; } // namespace Kernel::Process diff --git a/kernel/shell/shell.cpp b/kernel/shell/shell.cpp index cf7ff58..be157d1 100644 --- a/kernel/shell/shell.cpp +++ b/kernel/shell/shell.cpp @@ -228,6 +228,7 @@ void run_all_tests() noexcept { cmd_test_net(); cmd_test_af_unix(); cmd_test_unix_socket(); + cmd_test_wayland(); // Quiesce timer PPI and return to deterministic masked boot context before block IRQ test HAL::Platform::disable_timer_irq(); HAL::get_cpu().disable_interrupts(); @@ -619,6 +620,7 @@ void print_help() noexcept { " test blk - Test Virtio-MMIO block device async I/O & IRQ wakeup\r\n" " test af_unix - Test AF_UNIX sockets, VFS S_IFSOCK mknod, stream/dgram & poll\r\n" " test unix_sock - Test EL0 AF_UNIX socket syscalls & echo server/client\r\n" + " test wayland - Test Wayland compositor + wl_shm client on /dev/fb0 & evdev\r\n" " test ddk - Test modular DDK DummyDriver & KernelPlatformServices\r\n" " test all [-v] - Run entire verification test suite (-v for verbose)\r\n" " logs [flags] - Dump captured kernel logs (--json, --tail N, --level L, " @@ -682,6 +684,7 @@ bool dispatch_test_suite(const char* buf, bool verbose) noexcept { {"test net", cmd_test_net}, {"test af_unix", cmd_test_af_unix}, {"test unix_sock", cmd_test_unix_socket}, + {"test wayland", cmd_test_wayland}, {"test blk", cmd_test_blk}, {"test stack_abi", cmd_test_stack_and_abi}, {"test distro_abi", cmd_test_distro_abi}, diff --git a/kernel/shell/tests/shell_tests.hpp b/kernel/shell/tests/shell_tests.hpp index c3bde59..ed0cb78 100644 --- a/kernel/shell/tests/shell_tests.hpp +++ b/kernel/shell/tests/shell_tests.hpp @@ -49,6 +49,7 @@ void cmd_test_demand_paging() noexcept; void run_lazy_memory_acceptance_suite() noexcept; void cmd_test_af_unix() noexcept; void cmd_test_unix_socket() noexcept; +void cmd_test_wayland() noexcept; void cmd_test_distro_abi() noexcept; void cmd_test_ddk() noexcept; diff --git a/kernel/shell/tests/test_wayland.cpp b/kernel/shell/tests/test_wayland.cpp new file mode 100644 index 0000000..5345039 --- /dev/null +++ b/kernel/shell/tests/test_wayland.cpp @@ -0,0 +1,262 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#include "boot/fdt.hpp" +#include "core/log.hpp" +#include "drivers/virtio/virtio_input.hpp" +#include "fs/Vfs.hpp" +#include "fs/cpio.hpp" +#include "hal/platform.hpp" +#include "input/InputEvent.hpp" +#include "loader/elf64.hpp" +#include "loader/elf_loader.hpp" +#include "mm/AddressSpace.hpp" +#include "mm/heap.hpp" +#include "mm/pfa.hpp" +#include "process/Process.hpp" +#include "process/scheduler.hpp" +#include "process/stack_builder.hpp" +#include "shell/tests/shell_tests.hpp" +#include "shell/tests/test_common.hpp" +#include "uapi/input.hpp" + +#include +#include +#include + +extern Kernel::Boot::InitrdLocation g_initrd_loc; + +namespace Kernel::Shell::Tests { + +namespace { + +Kernel::Process::Process* spawn_initrd_process(const char* bin_path, int argc, + const char* const* argv) noexcept { + Kernel::FS::CpioEntry entry{}; + const Kernel::FS::CpioStatus cpio_st = Kernel::FS::cpio_lookup( + reinterpret_cast(Kernel::MM::phys_to_virt(g_initrd_loc.start_paddr)), + g_initrd_loc.size, bin_path, entry); + if (cpio_st != Kernel::FS::CpioStatus::Success || !entry.is_regular_file) { + return nullptr; + } + + auto load_res = Kernel::Loader::load_elf(entry.data, entry.size); + if (!load_res.is_ok()) { + return nullptr; + } + + auto* const proc = Kernel::Process::Process::create(0U); + if (proc == nullptr) { + load_res->address_space.destroy(); + return nullptr; + } + proc->set_exe_path(bin_path); + + Kernel::Loader::Elf64_auxv_t auxv[Kernel::Process::STANDARD_AUXV_COUNT]{}; + const size_t auxv_count = Kernel::Process::populate_standard_auxv( + *load_res, auxv, Kernel::Process::STANDARD_AUXV_COUNT); + proc->attach_elf(static_cast(*load_res)); + + auto stack_res = Kernel::Process::UserStackBuilder::create_and_map(proc->address_space()); + if (!stack_res.is_ok()) { + Kernel::Process::Process::destroy(*proc); + return nullptr; + } + proc->set_user_stack(stack_res.value()); + + const char* const envp[] = {"PATH=/bin", "XDG_RUNTIME_DIR=/tmp", "WAYLAND_DISPLAY=wayland-0", + nullptr}; + if (!Kernel::Process::UserStackBuilder::build_abi_layout(proc->user_stack(), argc, argv, envp, + auxv, auxv_count) + .is_ok()) { + Kernel::Process::Process::destroy(*proc); + return nullptr; + } + + Kernel::Process::init_user_cpu_context(proc->context(), proc->entry_point(), + proc->user_stack().final_sp_el0, proc->user_stack().argc, + proc->user_stack().argv_vaddr); + return proc; +} + +uint32_t read_fb_pixel(const Kernel::Drivers::Video::Framebuffer& fb, uint32_t x, + uint32_t y) noexcept { + if (x >= fb.width() || y >= fb.height()) { + return 0U; + } + const auto* const base = reinterpret_cast(fb.virt_base()); + uint32_t pixel = 0U; + std::memcpy(&pixel, + base + (static_cast(y) * static_cast(fb.stride())) + + (static_cast(x) * sizeof(uint32_t)), + sizeof(pixel)); + return pixel; +} + +} // namespace + +void cmd_test_wayland() noexcept { + Kernel::Log::info(kTestTag, + "Running Wayland Compositor + wl_shm Client (/dev/fb0 & evdev) Suite..."); + + // 1. Verify /dev/shm is mounted + Kernel::FS::Dentry* shm_dir = nullptr; + const int32_t shm_rc = Kernel::FS::vfs_namei("/dev/shm", nullptr, &shm_dir); + assert_test(shm_rc == Kernel::FS::kOk && shm_dir != nullptr && + shm_dir->get_inode() != nullptr && shm_dir->get_inode()->is_dir(), + "/dev/shm directory is mounted on tmpfs"); + if (shm_dir != nullptr) { + shm_dir->release(); + } + + if (!g_initrd_loc.valid || g_initrd_loc.start_paddr == 0U || g_initrd_loc.size == 0U) { + Kernel::Log::error(kTestTag, "No valid initrd loaded."); + return; + } + + auto* const fb = HAL::Platform::primary_framebuffer(); + assert_test(fb != nullptr && fb->is_initialized(), + "Primary /dev/fb0 framebuffer initialized for Wayland compositing"); + if (fb == nullptr || !fb->is_initialized()) { + return; + } + + // Clear framebuffer to 0 before compositor launch so we can prove rendered output + std::memset(reinterpret_cast(fb->virt_base()), 0, fb->size_bytes()); + + const size_t pages_before = Kernel::MM::pfa_allocated_pages_count(); + const auto heap_before = Kernel::MM::heap_get_stats(); + const size_t procs_before = Kernel::Process::Process::active_count(); + + const char* const comp_argv[] = {"/bin/wl_compositor", "--max-frames", "3", + "--timeout-ms", "5000", nullptr}; + const char* const cli_argv[] = {"/bin/wl_client", "--frames", "3", + "--wait-input-ms", "120", nullptr}; + + auto* const comp_proc = spawn_initrd_process("/bin/wl_compositor", 5, comp_argv); + assert_test(comp_proc != nullptr, "Loaded /bin/wl_compositor ELF64 binary"); + auto* const cli_proc = spawn_initrd_process("/bin/wl_client", 5, cli_argv); + assert_test(cli_proc != nullptr, "Loaded /bin/wl_client ELF64 binary"); + if (comp_proc == nullptr || cli_proc == nullptr) { + if (comp_proc != nullptr) { + Kernel::Process::Process::destroy(*comp_proc); + } + if (cli_proc != nullptr) { + Kernel::Process::Process::destroy(*cli_proc); + } + return; + } + + // Inject synthetic evdev events into event0 (keyboard) and event1 (tablet) so + // wl_compositor reads them via epoll and forwards them over the Wayland socket + auto* const kbd = HAL::Platform::input_device(0U); + if (kbd != nullptr) { + kbd->event_stream_queue().push(Kernel::Input::InputEvent{ + .timestamp_ns = 1000000ULL, + .device_id = 0U, + .device_kind = kbd->device_kind(), + .kind = Kernel::Input::InputEventKind::Key, + .raw_type = Kernel::UAPI::EV_KEY, + .code = Kernel::UAPI::KEY_A, + .value = Kernel::UAPI::KEY_VALUE_PRESS, + }); + kbd->event_stream_queue().push(Kernel::Input::InputEvent{ + .timestamp_ns = 1000500ULL, + .device_id = 0U, + .device_kind = kbd->device_kind(), + .kind = Kernel::Input::InputEventKind::Sync, + .raw_type = Kernel::UAPI::EV_SYN, + .code = Kernel::UAPI::SYN_REPORT, + .value = 0, + }); + } + auto* const tab = HAL::Platform::input_device(1U); + if (tab != nullptr) { + tab->event_stream_queue().push(Kernel::Input::InputEvent{ + .timestamp_ns = 1001000ULL, + .device_id = 1U, + .device_kind = tab->device_kind(), + .kind = Kernel::Input::InputEventKind::AbsoluteAxis, + .raw_type = Kernel::UAPI::EV_ABS, + .code = Kernel::UAPI::ABS_X, + .value = 16384, + }); + tab->event_stream_queue().push(Kernel::Input::InputEvent{ + .timestamp_ns = 1001500ULL, + .device_id = 1U, + .device_kind = tab->device_kind(), + .kind = Kernel::Input::InputEventKind::AbsoluteAxis, + .raw_type = Kernel::UAPI::EV_ABS, + .code = Kernel::UAPI::ABS_Y, + .value = 16384, + }); + tab->event_stream_queue().push(Kernel::Input::InputEvent{ + .timestamp_ns = 1002000ULL, + .device_id = 1U, + .device_kind = tab->device_kind(), + .kind = Kernel::Input::InputEventKind::Sync, + .raw_type = Kernel::UAPI::EV_SYN, + .code = Kernel::UAPI::SYN_REPORT, + .value = 0, + }); + } + + // Run compositor and client concurrently under the kernel scheduler + const uintptr_t orig_root = Kernel::MM::AddressSpace::current_root_paddr(); + auto* const prev_proc = Kernel::Process::Process::current(); + + Kernel::Scheduler::enqueue(comp_proc); + Kernel::Scheduler::enqueue(cli_proc); + while (comp_proc->state() != Kernel::Process::ProcessState::Zombie || + cli_proc->state() != Kernel::Process::ProcessState::Zombie) { + Kernel::Scheduler::run_until_idle(); + } + + Kernel::MM::AddressSpace::activate_root(orig_root); + Kernel::Process::Process::set_current(prev_proc); + + const int64_t comp_rc = comp_proc->exit_status(); + const int64_t cli_rc = cli_proc->exit_status(); + + assert_test(cli_rc == 0, + "/bin/wl_client connected, passed memfd via SCM_RIGHTS, rendered 3 frames on " + "pthread/futex worker, and exited 0"); + assert_test(comp_rc == 0, + "/bin/wl_compositor mapped wl_shm via SCM_RIGHTS, ran epoll/eventfd/timerfd/" + "evdev loop, composited 3 frames to /dev/fb0, and exited 0"); + + // Verify rendered pixels on /dev/fb0 (top bar + centered client surface) + const uint32_t topbar_px = read_fb_pixel(*fb, 10U, 10U); + const uint32_t center_px = read_fb_pixel(*fb, fb->width() / 2U, fb->height() / 2U); + assert_test(topbar_px == 0xFF1F3B4DU, + "/dev/fb0 top bar contains expected compositor backdrop pixel (0xFF1F3B4D)"); + assert_test(center_px != 0U && center_px != 0xFF18202CU, + "/dev/fb0 center contains rendered client wl_shm surface pixel"); + + if (kbd != nullptr) { + assert_test(kbd->event_stream_queue().empty(), + "wl_compositor drained /dev/input/event0 keyboard queue via epoll"); + } + if (tab != nullptr) { + assert_test(tab->event_stream_queue().empty(), + "wl_compositor drained /dev/input/event1 tablet queue via epoll"); + } + + (void)Kernel::FS::vfs_unlink("/tmp/wayland-0"); + Kernel::Process::Process::destroy(*cli_proc); + Kernel::Process::Process::destroy(*comp_proc); + + const size_t procs_after = Kernel::Process::Process::active_count(); + const size_t pages_after = Kernel::MM::pfa_allocated_pages_count(); + const auto heap_after = Kernel::MM::heap_get_stats(); + const size_t non_slab_before = pages_before - heap_before.slab_pages; + const size_t non_slab_after = pages_after - heap_after.slab_pages; + assert_test(procs_after == procs_before && + heap_after.active_slab_objects == heap_before.active_slab_objects && + heap_after.compound_pages == heap_before.compound_pages && + non_slab_after == non_slab_before, + "Wayland compositor + wl_shm client released all PCBs, threads, heap objects, and " + "PFA frames"); +} + +} // namespace Kernel::Shell::Tests diff --git a/kernel/sync/Futex.cpp b/kernel/sync/Futex.cpp new file mode 100644 index 0000000..d5188bc --- /dev/null +++ b/kernel/sync/Futex.cpp @@ -0,0 +1,217 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#include "sync/Futex.hpp" + +#include "hal/cpu.hpp" +#include "hal/platform.hpp" +#include "process/Process.hpp" +#include "process/Signal.hpp" +#include "process/scheduler.hpp" +#include "process/wait_queue.hpp" +#include "sync/IrqGuard.hpp" +#include "uapi/errno.hpp" + +namespace Kernel::Sync { + +namespace { + +constexpr size_t kFutexBuckets = 64U; +constexpr size_t kMaxFutexWaiters = 64U; +constexpr uint64_t kNsPerSec = 1000000000ULL; + +struct FutexWaiter { + bool active{false}; + bool woken{false}; + uintptr_t key_paddr{0U}; + Kernel::Process::Process* proc{nullptr}; +}; + +FutexWaiter g_futex_waiters[kMaxFutexWaiters]{}; +Kernel::Process::WaitQueue g_futex_buckets[kFutexBuckets]{}; + +[[nodiscard]] size_t futex_bucket_index(uintptr_t key_paddr) noexcept { + return (key_paddr >> 2U) % kFutexBuckets; +} + +[[nodiscard]] uint64_t monotonic_now_ns() noexcept { + const uint64_t freq = HAL::Platform::timer_frequency_hz(); + const uint64_t ticks = HAL::Platform::timer_counter_ticks(); + if (freq == 0ULL) { + return 0ULL; + } + const uint64_t secs = ticks / freq; + const uint64_t rem = ticks % freq; + return (secs * kNsPerSec) + ((rem * kNsPerSec) / freq); +} + +[[nodiscard]] bool resolve_futex_key(Kernel::MM::AddressSpace& as, uintptr_t uaddr, + uintptr_t& out_paddr) noexcept { + out_paddr = 0U; + if ((uaddr & 3U) != 0U || uaddr >= Kernel::MM::user_addr_space_limit()) { + return false; + } + const uintptr_t root = as.root_paddr(); + if (root == 0U) { + return false; + } + HAL::PageFlags flags = HAL::PageFlags::None; + if (as.query_user_page(uaddr, out_paddr, flags)) { + return true; + } + if (HAL::AddressSpaceBackend::resolve_demand_zero_page(root, uaddr, false, out_paddr)) { + return true; + } + return Kernel::MM::AddressSpace::resolve_file_backed_page(root, uaddr, false, false, out_paddr); +} + +} // namespace + +void futex_reset() noexcept { + const IrqGuard irq_guard; + for (auto& slot : g_futex_waiters) { + slot = FutexWaiter{}; + } + for (auto& bucket : g_futex_buckets) { + bucket.wake_all(); + } +} + +int64_t futex_wake_in_as(Kernel::MM::AddressSpace& as, uintptr_t uaddr, + uint32_t max_wake) noexcept { + if ((uaddr & 3U) != 0U) { + return Kernel::UAPI::ERR_EINVAL; + } + if (uaddr >= Kernel::MM::user_addr_space_limit()) { + return Kernel::UAPI::ERR_EFAULT; + } + if (max_wake == 0U) { + return 0; + } + + uintptr_t key_paddr = 0U; + if (!resolve_futex_key(as, uaddr, key_paddr)) { + return Kernel::UAPI::ERR_EFAULT; + } + + uint32_t woken_count = 0U; + { + const IrqGuard irq_guard; + for (auto& waiter : g_futex_waiters) { + if (woken_count >= max_wake) { + break; + } + if (waiter.active && !waiter.woken && waiter.key_paddr == key_paddr) { + waiter.woken = true; + ++woken_count; + } + } + if (woken_count > 0U) { + g_futex_buckets[futex_bucket_index(key_paddr)].wake_all(); + } + } + + return static_cast(woken_count); +} + +int64_t futex_wake(uintptr_t uaddr, uint32_t max_wake) noexcept { + auto* const proc = Kernel::Process::Process::current(); + if (proc == nullptr) { + return Kernel::UAPI::ERR_EINVAL; + } + return futex_wake_in_as(proc->address_space(), uaddr, max_wake); +} + +int64_t futex_wait(uintptr_t uaddr, uint32_t expected_val, bool has_timeout, uint64_t timeout_ns, + bool abs_timeout) noexcept { + auto* const proc = Kernel::Process::Process::current(); + if (proc == nullptr) { + return Kernel::UAPI::ERR_EINVAL; + } + if ((uaddr & 3U) != 0U) { + return Kernel::UAPI::ERR_EINVAL; + } + + uintptr_t key_paddr = 0U; + if (!resolve_futex_key(proc->address_space(), uaddr, key_paddr)) { + return Kernel::UAPI::ERR_EFAULT; + } + + uint32_t cur_val = 0U; + if (Kernel::MM::copy_from_user(proc->address_space(), &cur_val, uaddr, sizeof(cur_val)) < 0) { + return Kernel::UAPI::ERR_EFAULT; + } + if (cur_val != expected_val) { + return Kernel::UAPI::ERR_EAGAIN; + } + + uint64_t deadline_ns = 0ULL; + if (has_timeout) { + deadline_ns = abs_timeout ? timeout_ns : (monotonic_now_ns() + timeout_ns); + } + + size_t waiter_idx = kMaxFutexWaiters; + { + const IrqGuard irq_guard; + // Re-check atomically under IrqGuard before enqueuing + const auto* const word_kva = + reinterpret_cast(Kernel::MM::phys_to_virt(key_paddr)); + if (*word_kva != expected_val) { + return Kernel::UAPI::ERR_EAGAIN; + } + for (size_t idx = 0U; idx < kMaxFutexWaiters; ++idx) { + if (!g_futex_waiters[idx].active) { + g_futex_waiters[idx] = FutexWaiter{ + .active = true, + .woken = false, + .key_paddr = key_paddr, + .proc = proc, + }; + waiter_idx = idx; + break; + } + } + } + + if (waiter_idx >= kMaxFutexWaiters) { + return Kernel::UAPI::ERR_ENOMEM; + } + + auto& bucket = g_futex_buckets[futex_bucket_index(key_paddr)]; + int64_t result = 0; + + while (true) { + { + const IrqGuard irq_guard; + if (g_futex_waiters[waiter_idx].woken) { + g_futex_waiters[waiter_idx] = FutexWaiter{}; + result = 0; + break; + } + if (has_timeout && monotonic_now_ns() >= deadline_ns) { + g_futex_waiters[waiter_idx] = FutexWaiter{}; + result = Kernel::UAPI::ERR_ETIMEDOUT; + break; + } + if (Kernel::Process::has_unblocked_pending_signal(*proc)) { + g_futex_waiters[waiter_idx] = FutexWaiter{}; + result = Kernel::UAPI::ERR_EINTR; + break; + } + } + + if (has_timeout) { + if (Kernel::Process::Process::has_runnable()) { + Kernel::Scheduler::yield(); + } else { + HAL::get_cpu().poll_interrupts_once(); + } + } else { + bucket.sleep(); + } + } + + return result; +} + +} // namespace Kernel::Sync diff --git a/kernel/sync/Futex.hpp b/kernel/sync/Futex.hpp new file mode 100644 index 0000000..4ecbfc9 --- /dev/null +++ b/kernel/sync/Futex.hpp @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#pragma once + +#include "mm/AddressSpace.hpp" + +#include + +namespace Kernel::Sync { + +void futex_reset() noexcept; + +[[nodiscard]] int64_t futex_wait(uintptr_t uaddr, uint32_t expected_val, bool has_timeout, + uint64_t timeout_ns, bool abs_timeout = false) noexcept; + +[[nodiscard]] int64_t futex_wake(uintptr_t uaddr, uint32_t max_wake) noexcept; + +[[nodiscard]] int64_t futex_wake_in_as(Kernel::MM::AddressSpace& as, uintptr_t uaddr, + uint32_t max_wake) noexcept; + +} // namespace Kernel::Sync diff --git a/kernel/syscalls/EventSyscalls.cpp b/kernel/syscalls/EventSyscalls.cpp new file mode 100644 index 0000000..44434d3 --- /dev/null +++ b/kernel/syscalls/EventSyscalls.cpp @@ -0,0 +1,358 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#include "hal/platform.hpp" +#include "ipc/EventLoop.hpp" +#include "sync/Futex.hpp" +#include "syscalls/SyscallInternal.hpp" +#include "uapi/event.hpp" + +namespace Kernel::Syscalls { + +int64_t sys_eventfd2(uint32_t initval, uint32_t flags) noexcept { + auto* const proc = Kernel::Process::Process::current(); + if (proc == nullptr) { + return ERR_EINVAL; + } + constexpr uint32_t kAllowedFlags = + Kernel::UAPI::EFD_SEMAPHORE | Kernel::UAPI::EFD_NONBLOCK | Kernel::UAPI::EFD_CLOEXEC; + if ((flags & ~kAllowedFlags) != 0U) { + return ERR_EINVAL; + } + + const int fd = proc->fds().allocate(proc->rlim_nofile().rlim_cur); + if (fd < 0) { + return fd; + } + + const uint32_t open_flags = + ((flags & Kernel::UAPI::EFD_NONBLOCK) != 0U) ? Kernel::FS::kOpenNonBlock : 0U; + const bool semaphore = (flags & Kernel::UAPI::EFD_SEMAPHORE) != 0U; + + Kernel::FS::File* efd_file = nullptr; + const int32_t rc = Kernel::IPC::EventFd::create_file(initval, open_flags, semaphore, &efd_file); + if (rc != Kernel::FS::kOk || efd_file == nullptr) { + return (rc != Kernel::FS::kOk) ? rc : ERR_ENOMEM; + } + + const uint32_t fd_flags = + ((flags & Kernel::UAPI::EFD_CLOEXEC) != 0U) ? Kernel::Process::FD_FLAG_CLOEXEC : 0U; + if (!proc->fds().install(static_cast(fd), efd_file, fd_flags)) { + (void)Kernel::FS::vfs_close(efd_file); + return ERR_EMFILE; + } + return fd; +} + +int64_t sys_epoll_create1(uint32_t flags) noexcept { + auto* const proc = Kernel::Process::Process::current(); + if (proc == nullptr) { + return ERR_EINVAL; + } + if ((flags & ~Kernel::UAPI::EPOLL_CLOEXEC) != 0U) { + return ERR_EINVAL; + } + + const int fd = proc->fds().allocate(proc->rlim_nofile().rlim_cur); + if (fd < 0) { + return fd; + } + + Kernel::FS::File* ep_file = nullptr; + const int32_t rc = Kernel::IPC::EpollInstance::create_file(&ep_file); + if (rc != Kernel::FS::kOk || ep_file == nullptr) { + return (rc != Kernel::FS::kOk) ? rc : ERR_ENOMEM; + } + + const uint32_t fd_flags = + ((flags & Kernel::UAPI::EPOLL_CLOEXEC) != 0U) ? Kernel::Process::FD_FLAG_CLOEXEC : 0U; + if (!proc->fds().install(static_cast(fd), ep_file, fd_flags)) { + (void)Kernel::FS::vfs_close(ep_file); + return ERR_EMFILE; + } + return fd; +} + +int64_t sys_epoll_ctl(int32_t epfd, int32_t op, int32_t target_fd, uintptr_t user_event) noexcept { + auto* const proc = Kernel::Process::Process::current(); + if (proc == nullptr) { + return ERR_EINVAL; + } + if (epfd < 0 || target_fd < 0) { + return ERR_EBADF; + } + if (epfd == target_fd) { + return ERR_EINVAL; + } + + Kernel::FS::File* const ep_file = proc->fds().get_file(static_cast(epfd)); + if (ep_file == nullptr) { + return ERR_EBADF; + } + auto* const ep = Kernel::IPC::EpollInstance::from_file(ep_file); + if (ep == nullptr) { + return ERR_EINVAL; + } + + Kernel::FS::File* const target_file = proc->fds().get_file(static_cast(target_fd)); + if (target_file == nullptr) { + return ERR_EBADF; + } + + linux_epoll_event ev{}; + const linux_epoll_event* ev_ptr = nullptr; + if (op != Kernel::UAPI::EPOLL_CTL_DEL) { + if (user_event == 0U) { + return ERR_EFAULT; + } + if (Kernel::MM::copy_from_user(proc->address_space(), &ev, user_event, sizeof(ev)) < 0) { + return ERR_EFAULT; + } + ev_ptr = &ev; + } + + return ep->ctl(op, target_fd, target_file, ev_ptr); +} + +int64_t sys_epoll_pwait(int32_t epfd, uintptr_t user_events, int32_t maxevents, int32_t timeout_ms, + uintptr_t user_sigmask, uint64_t sigsetsize) noexcept { + auto* const proc = Kernel::Process::Process::current(); + if (proc == nullptr) { + return ERR_EINVAL; + } + if (epfd < 0) { + return ERR_EBADF; + } + if (maxevents <= 0) { + return ERR_EINVAL; + } + if (user_events == 0U) { + return ERR_EFAULT; + } + + Kernel::FS::File* const ep_file = proc->fds().get_file(static_cast(epfd)); + if (ep_file == nullptr) { + return ERR_EBADF; + } + auto* const ep = Kernel::IPC::EpollInstance::from_file(ep_file); + if (ep == nullptr) { + return ERR_EINVAL; + } + + const uintptr_t root_paddr = proc->address_space().root_paddr(); + const size_t capped_max = (static_cast(maxevents) < Kernel::IPC::kEpollMaxWatches) + ? static_cast(maxevents) + : Kernel::IPC::kEpollMaxWatches; + if (!validate_user_write_range(root_paddr, user_events, + capped_max * sizeof(linux_epoll_event))) { + return ERR_EFAULT; + } + + bool swapped_mask = false; + uint64_t saved_mask = 0ULL; + if (user_sigmask != 0U) { + if (sigsetsize != sizeof(uint64_t)) { + return ERR_EINVAL; + } + uint64_t new_mask = 0ULL; + if (Kernel::MM::copy_from_user(root_paddr, &new_mask, user_sigmask, sizeof(new_mask)) < 0) { + return ERR_EFAULT; + } + saved_mask = proc->signals().blocked(); + proc->signals().set_blocked(new_mask); + swapped_mask = true; + } + + auto restore_mask_normal = [&]() noexcept { + if (swapped_mask) { + proc->signals().set_blocked(saved_mask); + } + }; + auto restore_mask_eintr = [&]() noexcept { + if (swapped_mask) { + proc->signals().preserve_saved_mask_for_eintr(saved_mask); + } + }; + + const bool zero_timeout = (timeout_ms == 0); + const bool has_timeout = (timeout_ms > 0); + uint64_t deadline_ticks = 0ULL; + if (has_timeout) { + const uint64_t freq = HAL::Platform::timer_frequency_hz(); + const uint64_t start_ticks = HAL::Platform::timer_counter_ticks(); + const uint64_t wait_ticks = Kernel::Time::Duration::from_microseconds( + static_cast(timeout_ms) * uint64_t{1000}) + .to_timer_ticks(freq); + deadline_ticks = start_ticks + wait_ticks; + } + + linux_epoll_event k_events[Kernel::IPC::kEpollMaxWatches]{}; + while (true) { + const int32_t ready = ep->poll_ready(*proc, k_events, capped_max); + if (ready > 0) { + if (Kernel::MM::copy_to_user(root_paddr, user_events, k_events, + static_cast(ready) * sizeof(linux_epoll_event)) < + 0) { + restore_mask_normal(); + return ERR_EFAULT; + } + restore_mask_normal(); + return ready; + } + if (zero_timeout || + (has_timeout && HAL::Platform::timer_counter_ticks() >= deadline_ticks)) { + restore_mask_normal(); + return 0; + } + if (Kernel::Process::has_unblocked_pending_signal(*proc)) { + restore_mask_eintr(); + return ERR_EINTR; + } + wait_for_event_or_tick(); + } +} + +int64_t sys_timerfd_create(int32_t clockid, uint32_t flags) noexcept { + auto* const proc = Kernel::Process::Process::current(); + if (proc == nullptr) { + return ERR_EINVAL; + } + if (clockid != 0 && clockid != 1) { // CLOCK_REALTIME (0) or CLOCK_MONOTONIC (1) + return ERR_EINVAL; + } + constexpr uint32_t kAllowedFlags = Kernel::UAPI::TFD_NONBLOCK | Kernel::UAPI::TFD_CLOEXEC; + if ((flags & ~kAllowedFlags) != 0U) { + return ERR_EINVAL; + } + + const int fd = proc->fds().allocate(proc->rlim_nofile().rlim_cur); + if (fd < 0) { + return fd; + } + + const uint32_t open_flags = + ((flags & Kernel::UAPI::TFD_NONBLOCK) != 0U) ? Kernel::FS::kOpenNonBlock : 0U; + Kernel::FS::File* tfd_file = nullptr; + const int32_t rc = Kernel::IPC::TimerFd::create_file(clockid, open_flags, &tfd_file); + if (rc != Kernel::FS::kOk || tfd_file == nullptr) { + return (rc != Kernel::FS::kOk) ? rc : ERR_ENOMEM; + } + + const uint32_t fd_flags = + ((flags & Kernel::UAPI::TFD_CLOEXEC) != 0U) ? Kernel::Process::FD_FLAG_CLOEXEC : 0U; + if (!proc->fds().install(static_cast(fd), tfd_file, fd_flags)) { + (void)Kernel::FS::vfs_close(tfd_file); + return ERR_EMFILE; + } + return fd; +} + +int64_t sys_timerfd_settime(int32_t fd, uint32_t flags, uintptr_t user_new_value, + uintptr_t user_old_value) noexcept { + auto* const proc = Kernel::Process::Process::current(); + if (proc == nullptr) { + return ERR_EINVAL; + } + if (fd < 0) { + return ERR_EBADF; + } + if (user_new_value == 0U) { + return ERR_EFAULT; + } + + Kernel::FS::File* const tfd_file = proc->fds().get_file(static_cast(fd)); + if (tfd_file == nullptr) { + return ERR_EBADF; + } + auto* const tfd = Kernel::IPC::TimerFd::from_file(tfd_file); + if (tfd == nullptr) { + return ERR_EINVAL; + } + + linux_itimerspec new_spec{}; + if (Kernel::MM::copy_from_user(proc->address_space(), &new_spec, user_new_value, + sizeof(new_spec)) < 0) { + return ERR_EFAULT; + } + + linux_itimerspec old_spec{}; + const int32_t rc = tfd->settime(flags, new_spec, (user_old_value != 0U) ? &old_spec : nullptr); + if (rc < 0) { + return rc; + } + if (user_old_value != 0U && Kernel::MM::copy_to_user(proc->address_space(), user_old_value, + &old_spec, sizeof(old_spec)) < 0) { + return ERR_EFAULT; + } + return 0; +} + +int64_t sys_timerfd_gettime(int32_t fd, uintptr_t user_curr_value) noexcept { + auto* const proc = Kernel::Process::Process::current(); + if (proc == nullptr) { + return ERR_EINVAL; + } + if (fd < 0) { + return ERR_EBADF; + } + if (user_curr_value == 0U) { + return ERR_EFAULT; + } + + Kernel::FS::File* const tfd_file = proc->fds().get_file(static_cast(fd)); + if (tfd_file == nullptr) { + return ERR_EBADF; + } + auto* const tfd = Kernel::IPC::TimerFd::from_file(tfd_file); + if (tfd == nullptr) { + return ERR_EINVAL; + } + + linux_itimerspec curr_spec{}; + tfd->gettime(curr_spec); + if (Kernel::MM::copy_to_user(proc->address_space(), user_curr_value, &curr_spec, + sizeof(curr_spec)) < 0) { + return ERR_EFAULT; + } + return 0; +} + +int64_t sys_futex(uintptr_t uaddr, uint32_t op, uint32_t val, uintptr_t user_timeout, + uintptr_t uaddr2, uint32_t val3) noexcept { + (void)uaddr2; + (void)val3; + + auto* const proc = Kernel::Process::Process::current(); + if (proc == nullptr) { + return ERR_EINVAL; + } + + const uint32_t cmd = op & Kernel::UAPI::FUTEX_CMD_MASK; + if (cmd == Kernel::UAPI::FUTEX_WAIT || cmd == Kernel::UAPI::FUTEX_WAIT_BITSET) { + bool has_timeout = false; + uint64_t timeout_ns = 0ULL; + const bool abs_timeout = (cmd == Kernel::UAPI::FUTEX_WAIT_BITSET); + if (user_timeout != 0U) { + linux_timespec ts{}; + if (Kernel::MM::copy_from_user(proc->address_space(), &ts, user_timeout, sizeof(ts)) < + 0) { + return ERR_EFAULT; + } + if (ts.tv_sec < 0 || ts.tv_nsec < 0 || ts.tv_nsec >= 1000000000LL) { + return ERR_EINVAL; + } + has_timeout = true; + timeout_ns = (static_cast(ts.tv_sec) * 1000000000ULL) + + static_cast(ts.tv_nsec); + } + return Kernel::Sync::futex_wait(uaddr, val, has_timeout, timeout_ns, abs_timeout); + } + + if (cmd == Kernel::UAPI::FUTEX_WAKE || cmd == Kernel::UAPI::FUTEX_WAKE_BITSET) { + return Kernel::Sync::futex_wake(uaddr, val); + } + + return ERR_ENOSYS; +} + +} // namespace Kernel::Syscalls diff --git a/kernel/syscalls/FileSyscalls.cpp b/kernel/syscalls/FileSyscalls.cpp index 6684537..54a4325 100644 --- a/kernel/syscalls/FileSyscalls.cpp +++ b/kernel/syscalls/FileSyscalls.cpp @@ -2,6 +2,7 @@ // Copyright (c) 2026 Marco Buschini #include "fs/devfs/devfs.hpp" +#include "fs/tmpfs/tmpfs.hpp" #include "hal/platform.hpp" #include "ipc/Pipe.hpp" #include "syscalls/SyscallInternal.hpp" @@ -1660,4 +1661,42 @@ int64_t sys_pselect6(int32_t nfds, uintptr_t user_rfds, uintptr_t user_wfds, uin } } +int64_t sys_memfd_create(uintptr_t user_name, uint32_t flags) noexcept { + auto* const proc = Kernel::Process::Process::current(); + if (proc == nullptr) { + return ERR_EINVAL; + } + if ((flags & ~(Kernel::UAPI::MFD_CLOEXEC | Kernel::UAPI::MFD_ALLOW_SEALING)) != 0U) { + return ERR_EINVAL; + } + + char name_buf[250]{}; + size_t name_len = 0U; + const int64_t copy_rc = copy_user_cstring(proc->address_space().root_paddr(), user_name, + name_buf, sizeof(name_buf), name_len); + if (copy_rc < 0) { + return copy_rc; + } + (void)name_len; + + const int fd = proc->fds().allocate(proc->rlim_nofile().rlim_cur); + if (fd < 0) { + return fd; + } + + Kernel::FS::File* memfd_file = nullptr; + const int32_t rc = Kernel::FS::tmpfs_create_anon_file(Kernel::FS::kOpenReadWrite, &memfd_file); + if (rc != Kernel::FS::kOk || memfd_file == nullptr) { + return (rc != Kernel::FS::kOk) ? rc : ERR_ENOMEM; + } + + const uint32_t fd_flags = + ((flags & Kernel::UAPI::MFD_CLOEXEC) != 0U) ? Kernel::Process::FD_FLAG_CLOEXEC : 0U; + if (!proc->fds().install(static_cast(fd), memfd_file, fd_flags)) { + (void)Kernel::FS::vfs_close(memfd_file); + return ERR_EMFILE; + } + return fd; +} + } // namespace Kernel::Syscalls diff --git a/kernel/syscalls/ProcessSyscalls.cpp b/kernel/syscalls/ProcessSyscalls.cpp index c6738d4..7afeb99 100644 --- a/kernel/syscalls/ProcessSyscalls.cpp +++ b/kernel/syscalls/ProcessSyscalls.cpp @@ -87,6 +87,22 @@ int64_t sys_setsid() noexcept { const auto* const cur = Kernel::Process::Process::current(); Kernel::Log::debug(kSysProcTag, "sys_exit pid={} raw={:x} code={}", (cur != nullptr) ? cur->pid() : 0U, Kernel::Log::hex(raw_status), exit_code); + if (cur != nullptr) { + Kernel::Process::exit_current_thread(exit_code); + } + HAL::get_cpu().return_to_kernel(exit_code); + while (true) { + HAL::get_cpu().halt(); + } +} + +[[noreturn]] void sys_exit_group(uint64_t raw_status) noexcept { + const auto exit_code = + static_cast(static_cast(static_cast(raw_status))); + const auto* const cur = Kernel::Process::Process::current(); + Kernel::Log::debug(kSysProcTag, "sys_exit_group pid={} tgid={} raw={:x} code={}", + (cur != nullptr) ? cur->pid() : 0U, (cur != nullptr) ? cur->tgid() : 0U, + Kernel::Log::hex(raw_status), exit_code); if (cur != nullptr) { Kernel::Process::exit_current_process(exit_code); } @@ -97,10 +113,46 @@ int64_t sys_setsid() noexcept { } int64_t sys_getpid() noexcept { + const auto* const proc = Kernel::Process::Process::current(); + return (proc != nullptr) ? static_cast(proc->tgid()) : 0; +} + +int64_t sys_gettid() noexcept { const auto* const proc = Kernel::Process::Process::current(); return (proc != nullptr) ? static_cast(proc->pid()) : 0; } +int64_t sys_tkill(int32_t tid, uint64_t sig) noexcept { + if (tid <= 0 || sig > 64ULL) { + return ERR_EINVAL; + } + auto* const target = Kernel::Process::Process::find_by_pid(static_cast(tid)); + if (target == nullptr || target->state() == Kernel::Process::ProcessState::Unused || + target->state() == Kernel::Process::ProcessState::Zombie) { + return ERR_ESRCH; + } + if (sig != 0ULL) { + Kernel::Process::send_signal(*target, static_cast(sig)); + } + return 0; +} + +int64_t sys_tgkill(int32_t tgid, int32_t tid, uint64_t sig) noexcept { + if (tgid <= 0 || tid <= 0 || sig > 64ULL) { + return ERR_EINVAL; + } + auto* const target = Kernel::Process::Process::find_by_pid(static_cast(tid)); + if (target == nullptr || target->tgid() != static_cast(tgid) || + target->state() == Kernel::Process::ProcessState::Unused || + target->state() == Kernel::Process::ProcessState::Zombie) { + return ERR_ESRCH; + } + if (sig != 0ULL) { + Kernel::Process::send_signal(*target, static_cast(sig)); + } + return 0; +} + int64_t sys_getppid() noexcept { const auto* const proc = Kernel::Process::Process::current(); return (proc != nullptr) ? static_cast(proc->ppid()) : 0; @@ -202,17 +254,70 @@ int64_t sys_set_tid_address(uintptr_t tidptr) noexcept { int64_t sys_clone(HAL::CpuContext& parent_ctx, uint64_t flags, uintptr_t child_stack, uintptr_t parent_tid, uint64_t tls, uintptr_t child_tid) noexcept { - (void)tls; - auto* const parent = Kernel::Process::Process::current(); if (parent == nullptr) { return ERR_EINVAL; } + const bool is_thread_clone = (flags & CLONE_THREAD) != 0ULL; + if (is_thread_clone) { + constexpr uint64_t REQUIRED_THREAD_FLAGS = + CLONE_VM | CLONE_THREAD | CLONE_FILES | CLONE_SIGHAND; + constexpr uint64_t ALLOWED_THREAD_FLAGS = + REQUIRED_THREAD_FLAGS | CLONE_FS | CLONE_SETTLS | CLONE_SYSVSEM | CLONE_PARENT_SETTID | + CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | CLONE_DETACHED | CSIGNAL_MASK; + if ((flags & REQUIRED_THREAD_FLAGS) != REQUIRED_THREAD_FLAGS || + (flags & ~ALLOWED_THREAD_FLAGS) != 0ULL) { + return ERR_EINVAL; + } + if (child_stack == 0U || child_stack >= Kernel::MM::user_addr_space_limit()) { + return ERR_EINVAL; + } + if (Kernel::Process::Process::active_count() >= parent->rlim_nproc().rlim_cur) { + return ERR_EAGAIN; + } + + auto* const thread = Kernel::Process::Process::create_thread(*parent); + if (thread == nullptr) { + return ERR_EAGAIN; + } + + const auto tid_s32 = static_cast(thread->pid()); + if ((flags & CLONE_PARENT_SETTID) != 0ULL && parent_tid != 0U) { + if (Kernel::MM::copy_to_user(parent->address_space(), parent_tid, &tid_s32, + sizeof(tid_s32)) < 0) { + Kernel::Process::Process::destroy(*thread); + return ERR_EFAULT; + } + } + if ((flags & CLONE_CHILD_SETTID) != 0ULL && child_tid != 0U) { + if (Kernel::MM::copy_to_user(thread->address_space(), child_tid, &tid_s32, + sizeof(tid_s32)) < 0) { + Kernel::Process::Process::destroy(*thread); + return ERR_EFAULT; + } + } + if ((flags & CLONE_CHILD_CLEARTID) != 0ULL) { + thread->set_clear_child_tid(child_tid); + } + + auto& cpu = HAL::get_cpu(); + thread->context() = parent_ctx; + cpu.set_user_stack_pointer(thread->context(), child_stack); + if ((flags & CLONE_SETTLS) != 0ULL) { + cpu.set_user_tls_pointer(thread->context(), static_cast(tls)); + } + cpu.set_syscall_return(thread->context(), 0); + thread->set_kctx_initialized(false); + Kernel::Scheduler::enqueue(thread); + return static_cast(thread->pid()); + } + constexpr uint64_t UNSUPPORTED_CLONE_FLAGS = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_VFORK | CLONE_THREAD; - constexpr uint64_t ALLOWED_CLONE_FLAGS = - CSIGNAL_MASK | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID; + constexpr uint64_t ALLOWED_CLONE_FLAGS = CSIGNAL_MASK | CLONE_PARENT_SETTID | + CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | + CLONE_SETTLS; if ((flags & UNSUPPORTED_CLONE_FLAGS) != 0ULL || (flags & ~ALLOWED_CLONE_FLAGS) != 0ULL) { return ERR_EINVAL; @@ -231,7 +336,7 @@ int64_t sys_clone(HAL::CpuContext& parent_ctx, uint64_t flags, uintptr_t child_s return ERR_EAGAIN; } - auto* const child = Kernel::Process::Process::create(parent->pid()); + auto* const child = Kernel::Process::Process::create(parent->tgid()); if (child == nullptr) { return ERR_EAGAIN; } @@ -280,12 +385,18 @@ int64_t sys_clone(HAL::CpuContext& parent_ctx, uint64_t flags, uintptr_t child_s return ERR_EFAULT; } } + if ((flags & CLONE_CHILD_CLEARTID) != 0ULL) { + child->set_clear_child_tid(child_tid); + } auto& cpu = HAL::get_cpu(); child->context() = parent_ctx; if (child_stack != 0U) { cpu.set_user_stack_pointer(child->context(), child_stack); } + if ((flags & CLONE_SETTLS) != 0ULL) { + cpu.set_user_tls_pointer(child->context(), static_cast(tls)); + } cpu.set_syscall_return(child->context(), 0); child->set_kctx_initialized(false); Kernel::Scheduler::enqueue(child); @@ -657,10 +768,11 @@ int64_t sys_wait4(int32_t target_pid, uintptr_t user_wstatus, uint64_t options, for (auto* candidate = Kernel::Process::Process::list_head(); candidate != nullptr; candidate = candidate->next_global()) { - if (candidate->state() == Kernel::Process::ProcessState::Unused) { + if (candidate->state() == Kernel::Process::ProcessState::Unused || + candidate->is_thread()) { continue; } - if (candidate->ppid() != parent->pid()) { + if (candidate->ppid() != parent->tgid()) { continue; } if (target_pid > 0 && candidate->pid() != static_cast(target_pid)) { diff --git a/kernel/syscalls/SocketSyscalls.cpp b/kernel/syscalls/SocketSyscalls.cpp index e063a79..c5e4b18 100644 --- a/kernel/syscalls/SocketSyscalls.cpp +++ b/kernel/syscalls/SocketSyscalls.cpp @@ -790,6 +790,167 @@ int64_t sys_shutdown(uint64_t raw_fd, int32_t how) noexcept { return sock->shutdown_rw(how); } +namespace { + +void release_rights_batch_files(Kernel::Net::UnixRightsBatch& batch) noexcept { + for (size_t idx = 0U; idx < batch.count && idx < Kernel::Net::kUnixMaxRightsPerMsg; ++idx) { + if (batch.files[idx] != nullptr) { + (void)Kernel::FS::vfs_close(batch.files[idx]); + batch.files[idx] = nullptr; + } + } + batch.count = 0U; + batch.byte_pos = 0ULL; +} + +int64_t parse_scm_rights_from_user(Kernel::Process::Process& proc, uintptr_t root_paddr, + const linux_msghdr& msg, + Kernel::Net::UnixRightsBatch& out_rights) noexcept { + out_rights = Kernel::Net::UnixRightsBatch{}; + const auto ctrl_addr = reinterpret_cast(msg.msg_control); + const size_t ctrl_len = msg.msg_controllen; + if (ctrl_addr == 0U || ctrl_len == 0U) { + return 0; + } + if (ctrl_len > 4096U) { + return ERR_EINVAL; + } + + size_t off = 0U; + while (off + sizeof(linux_cmsghdr) <= ctrl_len) { + linux_cmsghdr cmsg{}; + if (Kernel::MM::copy_from_user(root_paddr, &cmsg, ctrl_addr + off, sizeof(cmsg)) < 0) { + release_rights_batch_files(out_rights); + return ERR_EFAULT; + } + if (cmsg.cmsg_len < sizeof(linux_cmsghdr) || cmsg.cmsg_len > (ctrl_len - off)) { + release_rights_batch_files(out_rights); + return ERR_EINVAL; + } + + if (cmsg.cmsg_level == Kernel::UAPI::SOL_SOCKET && + cmsg.cmsg_type == Kernel::UAPI::SCM_RIGHTS) { + const size_t data_len = cmsg.cmsg_len - sizeof(linux_cmsghdr); + const size_t num_fds = data_len / sizeof(int32_t); + if (out_rights.count + num_fds > Kernel::Net::kUnixMaxRightsPerMsg) { + release_rights_batch_files(out_rights); + return ERR_EINVAL; + } + for (size_t i = 0U; i < num_fds; ++i) { + int32_t raw_fd = -1; + const uintptr_t fd_uaddr = + ctrl_addr + off + sizeof(linux_cmsghdr) + (i * sizeof(int32_t)); + if (Kernel::MM::copy_from_user(root_paddr, &raw_fd, fd_uaddr, sizeof(raw_fd)) < 0) { + release_rights_batch_files(out_rights); + return ERR_EFAULT; + } + if (raw_fd < 0) { + release_rights_batch_files(out_rights); + return ERR_EBADF; + } + Kernel::FS::File* const file = proc.fds().get_file(static_cast(raw_fd)); + if (file == nullptr) { + release_rights_batch_files(out_rights); + return ERR_EBADF; + } + file->retain(); + out_rights.files[out_rights.count++] = file; + } + } + + const size_t step = Kernel::UAPI::cmsg_align(cmsg.cmsg_len); + if (step == 0U || step > (ctrl_len - off)) { + break; + } + off += step; + } + + return 0; +} + +int64_t deliver_scm_rights_to_user(Kernel::Process::Process& proc, uintptr_t root_paddr, + linux_msghdr& msg, int32_t recv_flags, + Kernel::Net::UnixRightsBatch& rights) noexcept { + constexpr auto kCtruncFlag = static_cast(Kernel::UAPI::MSG_CTRUNC); + uint32_t msg_flags_u = static_cast(msg.msg_flags) & ~kCtruncFlag; + msg.msg_flags = static_cast(msg_flags_u); + if (rights.count == 0U) { + msg.msg_controllen = 0U; + return 0; + } + + const auto ctrl_addr = reinterpret_cast(msg.msg_control); + const size_t ctrl_cap = msg.msg_controllen; + const uint32_t fd_flags = ((static_cast(recv_flags) & + static_cast(Kernel::UAPI::MSG_CMSG_CLOEXEC)) != 0U) + ? Kernel::Process::FD_FLAG_CLOEXEC + : 0U; + + if (ctrl_addr == 0U || ctrl_cap < sizeof(linux_cmsghdr) + sizeof(int32_t)) { + msg_flags_u |= kCtruncFlag; + msg.msg_flags = static_cast(msg_flags_u); + msg.msg_controllen = 0U; + release_rights_batch_files(rights); + return 0; + } + + const size_t max_fds_fit = (ctrl_cap - sizeof(linux_cmsghdr)) / sizeof(int32_t); + size_t to_install = (rights.count < max_fds_fit) ? rights.count : max_fds_fit; + if (to_install < rights.count) { + msg_flags_u |= kCtruncFlag; + msg.msg_flags = static_cast(msg_flags_u); + } + + int32_t installed_fds[Kernel::Net::kUnixMaxRightsPerMsg]{}; + size_t installed_count = 0U; + + for (size_t idx = 0U; idx < to_install; ++idx) { + const int slot = proc.fds().allocate(proc.rlim_nofile().rlim_cur); + if (slot < 0) { + msg_flags_u |= kCtruncFlag; + msg.msg_flags = static_cast(msg_flags_u); + break; + } + if (!proc.fds().install(static_cast(slot), rights.files[idx], fd_flags)) { + msg_flags_u |= kCtruncFlag; + msg.msg_flags = static_cast(msg_flags_u); + break; + } + rights.files[idx] = nullptr; // Ownership transferred to FdTable + installed_fds[installed_count++] = static_cast(slot); + } + + // Close any remaining files that did not fit + release_rights_batch_files(rights); + + if (installed_count == 0U) { + msg.msg_controllen = 0U; + return 0; + } + + const size_t cmsg_len = sizeof(linux_cmsghdr) + (installed_count * sizeof(int32_t)); + const size_t cmsg_space = Kernel::UAPI::cmsg_align(cmsg_len); + const linux_cmsghdr cmsg{ + .cmsg_len = cmsg_len, + .cmsg_level = Kernel::UAPI::SOL_SOCKET, + .cmsg_type = Kernel::UAPI::SCM_RIGHTS, + }; + + if (Kernel::MM::copy_to_user(root_paddr, ctrl_addr, &cmsg, sizeof(cmsg)) < 0 || + Kernel::MM::copy_to_user(root_paddr, ctrl_addr + sizeof(cmsg), installed_fds, + installed_count * sizeof(int32_t)) < 0) { + for (size_t idx = 0U; idx < installed_count; ++idx) { + proc.fds().close(static_cast(installed_fds[idx])); + } + return ERR_EFAULT; + } + + msg.msg_controllen = (cmsg_space <= ctrl_cap) ? cmsg_space : cmsg_len; + return 0; +} + +} // namespace + int64_t sys_sendmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept { auto* const proc = Kernel::Process::Process::current(); if (proc == nullptr) { @@ -831,6 +992,12 @@ int64_t sys_sendmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept } } + Kernel::Net::UnixRightsBatch in_rights{}; + const int64_t rights_rc = parse_scm_rights_from_user(*proc, root_paddr, msg, in_rights); + if (rights_rc < 0) { + return rights_rc; + } + const uint32_t combined_flags = static_cast(flags) | static_cast(msg.msg_flags); const bool nonblock = @@ -849,6 +1016,7 @@ int64_t sys_sendmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept linux_iovec iov{}; if (Kernel::MM::copy_from_user(root_paddr, &iov, iov_addr + (idx * sizeof(linux_iovec)), sizeof(iov)) < 0) { + release_rights_batch_files(in_rights); if (cwd != nullptr) { cwd->release(); } @@ -862,18 +1030,22 @@ int64_t sys_sendmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept const size_t rem = seg_len - seg_off; const size_t chunk = (rem < sizeof(kbuf)) ? rem : sizeof(kbuf); if (Kernel::MM::copy_from_user(root_paddr, kbuf, seg_base + seg_off, chunk) < 0) { + release_rights_batch_files(in_rights); if (cwd != nullptr) { cwd->release(); } return (total_sent > 0U) ? static_cast(total_sent) : ERR_EFAULT; } + Kernel::Net::UnixRightsBatch* const rights_arg = + (in_rights.count > 0U) ? &in_rights : nullptr; const int64_t sent = (sock->sock_type() == Kernel::UAPI::SOCK_DGRAM) ? sock->dgram_sendto(kbuf, chunk, has_dest ? &dest_sun : nullptr, has_dest, - nonblock, nosignal, cwd) - : sock->stream_write(kbuf, chunk, nonblock, nosignal); + nonblock, nosignal, cwd, rights_arg) + : sock->stream_write_with_rights(kbuf, chunk, nonblock, nosignal, rights_arg); if (sent < 0) { + release_rights_batch_files(in_rights); if (cwd != nullptr) { cwd->release(); } @@ -883,6 +1055,7 @@ int64_t sys_sendmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept seg_off += static_cast(sent); total_sent += static_cast(sent); if (static_cast(sent) < chunk) { + release_rights_batch_files(in_rights); if (cwd != nullptr) { cwd->release(); } @@ -892,14 +1065,18 @@ int64_t sys_sendmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept } if (total_iov_bytes == 0U && sock->sock_type() == Kernel::UAPI::SOCK_DGRAM) { + Kernel::Net::UnixRightsBatch* const rights_arg = + (in_rights.count > 0U) ? &in_rights : nullptr; const int64_t z_rc = sock->dgram_sendto(nullptr, 0U, has_dest ? &dest_sun : nullptr, - has_dest, nonblock, nosignal, cwd); + has_dest, nonblock, nosignal, cwd, rights_arg); + release_rights_batch_files(in_rights); if (cwd != nullptr) { cwd->release(); } return z_rc; } + release_rights_batch_files(in_rights); if (cwd != nullptr) { cwd->release(); } @@ -950,11 +1127,13 @@ int64_t sys_recvmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept uint8_t kbuf[Kernel::Net::kUnixMaxDgramPayload]{}; linux_sockaddr_un src_sun{}; + Kernel::Net::UnixRightsBatch out_rights{}; if (sock->sock_type() == Kernel::UAPI::SOCK_DGRAM) { const size_t cap = (total_iov_bytes < sizeof(kbuf)) ? total_iov_bytes : sizeof(kbuf); - const int64_t recvd = sock->dgram_recvfrom(kbuf, cap, &src_sun, nonblock); + const int64_t recvd = sock->dgram_recvfrom(kbuf, cap, &src_sun, nonblock, &out_rights); if (recvd < 0) { + release_rights_batch_files(out_rights); return recvd; } @@ -964,6 +1143,7 @@ int64_t sys_recvmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept linux_iovec iov{}; if (Kernel::MM::copy_from_user(root_paddr, &iov, iov_addr + (idx * sizeof(linux_iovec)), sizeof(iov)) < 0) { + release_rights_batch_files(out_rights); return ERR_EFAULT; } const auto seg_len = static_cast(iov.iov_len); @@ -972,6 +1152,7 @@ int64_t sys_recvmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept if (to_copy > 0U && Kernel::MM::copy_to_user(root_paddr, static_cast(iov.iov_base), kbuf + copied_total, to_copy) < 0) { + release_rights_batch_files(out_rights); return ERR_EFAULT; } copied_total += to_copy; @@ -982,6 +1163,7 @@ int64_t sys_recvmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept ? static_cast(msg.msg_namelen) : sizeof(src_sun); if (Kernel::MM::copy_to_user(root_paddr, name_addr, &src_sun, copy_n) < 0) { + release_rights_batch_files(out_rights); return ERR_EFAULT; } size_t path_len = 0U; @@ -990,9 +1172,15 @@ int64_t sys_recvmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept } msg.msg_namelen = static_cast(sizeof(linux_sa_family_t) + path_len + 1U); - if (Kernel::MM::copy_to_user(root_paddr, user_msg, &msg, sizeof(msg)) < 0) { - return ERR_EFAULT; - } + } + + const int64_t cmsg_rc = + deliver_scm_rights_to_user(*proc, root_paddr, msg, flags, out_rights); + if (cmsg_rc < 0) { + return cmsg_rc; + } + if (Kernel::MM::copy_to_user(root_paddr, user_msg, &msg, sizeof(msg)) < 0) { + return ERR_EFAULT; } return static_cast(copied_total); @@ -1003,6 +1191,7 @@ int64_t sys_recvmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept linux_iovec iov{}; if (Kernel::MM::copy_from_user(root_paddr, &iov, iov_addr + (idx * sizeof(linux_iovec)), sizeof(iov)) < 0) { + release_rights_batch_files(out_rights); return (total_read > 0U) ? static_cast(total_read) : ERR_EFAULT; } const auto seg_len = static_cast(iov.iov_len); @@ -1013,9 +1202,18 @@ int64_t sys_recvmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept while (seg_off < seg_len) { const size_t rem = seg_len - seg_off; const size_t chunk = (rem < sizeof(kbuf)) ? rem : sizeof(kbuf); - const int64_t nread = sock->stream_read(kbuf, chunk, nonblock); + const bool read_nonblock = nonblock || (total_read > 0U); + Kernel::Net::UnixRightsBatch* const rights_ptr = + (total_read == 0U && out_rights.count == 0U) ? &out_rights : nullptr; + const int64_t nread = + sock->stream_read_with_rights(kbuf, chunk, read_nonblock, rights_ptr); if (nread < 0) { - return (total_read > 0U) ? static_cast(total_read) : nread; + if (total_read > 0U) { + hit_eof_or_short = true; + break; + } + release_rights_batch_files(out_rights); + return nread; } if (nread == 0) { hit_eof_or_short = true; @@ -1023,11 +1221,12 @@ int64_t sys_recvmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept } if (Kernel::MM::copy_to_user(root_paddr, seg_base + seg_off, kbuf, static_cast(nread)) < 0) { + release_rights_batch_files(out_rights); return (total_read > 0U) ? static_cast(total_read) : ERR_EFAULT; } seg_off += static_cast(nread); total_read += static_cast(nread); - if (static_cast(nread) < chunk) { + if (static_cast(nread) < chunk || out_rights.count > 0U) { hit_eof_or_short = true; break; } @@ -1044,6 +1243,7 @@ int64_t sys_recvmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept ? static_cast(msg.msg_namelen) : sizeof(paddr); if (Kernel::MM::copy_to_user(root_paddr, name_addr, &paddr, copy_n) < 0) { + release_rights_batch_files(out_rights); return ERR_EFAULT; } size_t path_len = 0U; @@ -1051,9 +1251,14 @@ int64_t sys_recvmsg(uint64_t raw_fd, uintptr_t user_msg, int32_t flags) noexcept ++path_len; } msg.msg_namelen = static_cast(sizeof(linux_sa_family_t) + path_len + 1U); - if (Kernel::MM::copy_to_user(root_paddr, user_msg, &msg, sizeof(msg)) < 0) { - return ERR_EFAULT; - } + } + + const int64_t cmsg_rc = deliver_scm_rights_to_user(*proc, root_paddr, msg, flags, out_rights); + if (cmsg_rc < 0) { + return cmsg_rc; + } + if (Kernel::MM::copy_to_user(root_paddr, user_msg, &msg, sizeof(msg)) < 0) { + return ERR_EFAULT; } return static_cast(total_read); diff --git a/kernel/syscalls/SyscallDispatcher.cpp b/kernel/syscalls/SyscallDispatcher.cpp index 6b38172..c3d38a7 100644 --- a/kernel/syscalls/SyscallDispatcher.cpp +++ b/kernel/syscalls/SyscallDispatcher.cpp @@ -15,6 +15,10 @@ namespace { // Linux AArch64 Syscall Numbers constexpr uint64_t SYS_GETCWD = 17U; +constexpr uint64_t SYS_EVENTFD2 = 19U; +constexpr uint64_t SYS_EPOLL_CREATE1 = 20U; +constexpr uint64_t SYS_EPOLL_CTL = 21U; +constexpr uint64_t SYS_EPOLL_PWAIT = 22U; constexpr uint64_t SYS_DUP = 23U; constexpr uint64_t SYS_DUP3 = 24U; constexpr uint64_t SYS_FCNTL = 25U; @@ -45,15 +49,21 @@ constexpr uint64_t SYS_NEWFSTATAT = 79U; constexpr uint64_t SYS_FSTAT = 80U; constexpr uint64_t SYS_FSYNC = 82U; constexpr uint64_t SYS_FDATASYNC = 83U; +constexpr uint64_t SYS_TIMERFD_CREATE = 85U; +constexpr uint64_t SYS_TIMERFD_SETTIME = 86U; +constexpr uint64_t SYS_TIMERFD_GETTIME = 87U; constexpr uint64_t SYS_UTIMENSAT = 88U; constexpr uint64_t SYS_EXIT = 93U; constexpr uint64_t SYS_EXIT_GROUP = 94U; constexpr uint64_t SYS_SET_TID_ADDRESS = 96U; +constexpr uint64_t SYS_FUTEX = 98U; constexpr uint64_t SYS_SET_ROBUST_LIST = 99U; constexpr uint64_t SYS_NANOSLEEP = 101U; constexpr uint64_t SYS_CLOCK_GETTIME = 113U; constexpr uint64_t SYS_SCHED_YIELD = 124U; constexpr uint64_t SYS_KILL = 129U; +constexpr uint64_t SYS_TKILL = 130U; +constexpr uint64_t SYS_TGKILL = 131U; constexpr uint64_t SYS_RT_SIGACTION = 134U; constexpr uint64_t SYS_RT_SIGPROCMASK = 135U; constexpr uint64_t SYS_RT_SIGRETURN = 139U; @@ -72,6 +82,7 @@ constexpr uint64_t SYS_GETUID = 174U; constexpr uint64_t SYS_GETEUID = 175U; constexpr uint64_t SYS_GETGID = 176U; constexpr uint64_t SYS_GETEGID = 177U; +constexpr uint64_t SYS_GETTID = 178U; constexpr uint64_t SYS_SYSINFO = 179U; constexpr uint64_t SYS_SOCKET = 198U; constexpr uint64_t SYS_SOCKETPAIR = 199U; @@ -99,6 +110,7 @@ constexpr uint64_t SYS_WAIT4 = 260U; constexpr uint64_t SYS_PRLIMIT64 = 261U; constexpr uint64_t SYS_RENAMEAT2 = 276U; constexpr uint64_t SYS_GETRANDOM = 278U; +constexpr uint64_t SYS_MEMFD_CREATE = 279U; constexpr uint64_t SYS_FACCESSAT2 = 439U; } // namespace @@ -123,6 +135,32 @@ class SyscallDispatcher : public HAL::TrapHandler { cpu.get_syscall_arg(ctx, 1U)); break; + case SYS_EVENTFD2: + ret_val = sys_eventfd2(static_cast(cpu.get_syscall_arg(ctx, 0U)), + static_cast(cpu.get_syscall_arg(ctx, 1U))); + break; + + case SYS_EPOLL_CREATE1: + ret_val = sys_epoll_create1(static_cast(cpu.get_syscall_arg(ctx, 0U))); + break; + + case SYS_EPOLL_CTL: + ret_val = sys_epoll_ctl( + static_cast(static_cast(cpu.get_syscall_arg(ctx, 0U))), + static_cast(static_cast(cpu.get_syscall_arg(ctx, 1U))), + static_cast(static_cast(cpu.get_syscall_arg(ctx, 2U))), + static_cast(cpu.get_syscall_arg(ctx, 3U))); + break; + + case SYS_EPOLL_PWAIT: + ret_val = sys_epoll_pwait( + static_cast(static_cast(cpu.get_syscall_arg(ctx, 0U))), + static_cast(cpu.get_syscall_arg(ctx, 1U)), + static_cast(static_cast(cpu.get_syscall_arg(ctx, 2U))), + static_cast(static_cast(cpu.get_syscall_arg(ctx, 3U))), + static_cast(cpu.get_syscall_arg(ctx, 4U)), cpu.get_syscall_arg(ctx, 5U)); + break; + case SYS_DUP: ret_val = sys_dup(cpu.get_syscall_arg(ctx, 0U)); break; @@ -313,6 +351,26 @@ class SyscallDispatcher : public HAL::TrapHandler { ret_val = sys_fsync(cpu.get_syscall_arg(ctx, 0U), 1); break; + case SYS_TIMERFD_CREATE: + ret_val = sys_timerfd_create( + static_cast(static_cast(cpu.get_syscall_arg(ctx, 0U))), + static_cast(cpu.get_syscall_arg(ctx, 1U))); + break; + + case SYS_TIMERFD_SETTIME: + ret_val = sys_timerfd_settime( + static_cast(static_cast(cpu.get_syscall_arg(ctx, 0U))), + static_cast(cpu.get_syscall_arg(ctx, 1U)), + static_cast(cpu.get_syscall_arg(ctx, 2U)), + static_cast(cpu.get_syscall_arg(ctx, 3U))); + break; + + case SYS_TIMERFD_GETTIME: + ret_val = sys_timerfd_gettime( + static_cast(static_cast(cpu.get_syscall_arg(ctx, 0U))), + static_cast(cpu.get_syscall_arg(ctx, 1U))); + break; + case SYS_UTIMENSAT: ret_val = sys_utimensat( static_cast(static_cast(cpu.get_syscall_arg(ctx, 0U))), @@ -321,13 +379,24 @@ class SyscallDispatcher : public HAL::TrapHandler { break; case SYS_EXIT: - case SYS_EXIT_GROUP: sys_exit(cpu.get_syscall_arg(ctx, 0U)); + case SYS_EXIT_GROUP: + sys_exit_group(cpu.get_syscall_arg(ctx, 0U)); + case SYS_SET_TID_ADDRESS: ret_val = sys_set_tid_address(static_cast(cpu.get_syscall_arg(ctx, 0U))); break; + case SYS_FUTEX: + ret_val = sys_futex(static_cast(cpu.get_syscall_arg(ctx, 0U)), + static_cast(cpu.get_syscall_arg(ctx, 1U)), + static_cast(cpu.get_syscall_arg(ctx, 2U)), + static_cast(cpu.get_syscall_arg(ctx, 3U)), + static_cast(cpu.get_syscall_arg(ctx, 4U)), + static_cast(cpu.get_syscall_arg(ctx, 5U))); + break; + case SYS_SET_ROBUST_LIST: ret_val = (cpu.get_syscall_arg(ctx, 1U) == 24ULL) ? 0 : ERR_EINVAL; break; @@ -353,6 +422,19 @@ class SyscallDispatcher : public HAL::TrapHandler { cpu.get_syscall_arg(ctx, 1U)); break; + case SYS_TKILL: + ret_val = + sys_tkill(static_cast(static_cast(cpu.get_syscall_arg(ctx, 0U))), + cpu.get_syscall_arg(ctx, 1U)); + break; + + case SYS_TGKILL: + ret_val = sys_tgkill( + static_cast(static_cast(cpu.get_syscall_arg(ctx, 0U))), + static_cast(static_cast(cpu.get_syscall_arg(ctx, 1U))), + cpu.get_syscall_arg(ctx, 2U)); + break; + case SYS_RT_SIGACTION: ret_val = sys_rt_sigaction( cpu.get_syscall_arg(ctx, 0U), static_cast(cpu.get_syscall_arg(ctx, 1U)), @@ -427,6 +509,10 @@ class SyscallDispatcher : public HAL::TrapHandler { ret_val = 0; break; + case SYS_GETTID: + ret_val = sys_gettid(); + break; + case SYS_SYSINFO: ret_val = sys_sysinfo(static_cast(cpu.get_syscall_arg(ctx, 0U))); break; @@ -621,6 +707,11 @@ class SyscallDispatcher : public HAL::TrapHandler { cpu.get_syscall_arg(ctx, 1U), cpu.get_syscall_arg(ctx, 2U)); break; + case SYS_MEMFD_CREATE: + ret_val = sys_memfd_create(static_cast(cpu.get_syscall_arg(ctx, 0U)), + static_cast(cpu.get_syscall_arg(ctx, 1U))); + break; + default: Kernel::Log::debug("sys", "ENOSYS nr={} a0={:x} a1={:x} a2={:x}", syscall_num, Kernel::Log::hex(cpu.get_syscall_arg(ctx, 0U)), diff --git a/kernel/syscalls/SyscallInternal.hpp b/kernel/syscalls/SyscallInternal.hpp index f4992a1..84964a6 100644 --- a/kernel/syscalls/SyscallInternal.hpp +++ b/kernel/syscalls/SyscallInternal.hpp @@ -130,6 +130,7 @@ void build_dentry_path(const Kernel::FS::Dentry* target, char* out, size_t cap) // Process lifecycle & job-control syscalls (ProcessSyscalls.cpp) [[noreturn]] void sys_exit(uint64_t raw_status) noexcept; +[[noreturn]] void sys_exit_group(uint64_t raw_status) noexcept; [[nodiscard]] int64_t sys_clone(HAL::CpuContext& parent_ctx, uint64_t flags, uintptr_t child_stack, uintptr_t parent_tid, uint64_t tls, uintptr_t child_tid) noexcept; [[nodiscard]] int64_t sys_execve(HAL::CpuContext& ctx, uintptr_t user_pathname, uintptr_t user_argv, @@ -137,7 +138,10 @@ void build_dentry_path(const Kernel::FS::Dentry* target, char* out, size_t cap) [[nodiscard]] int64_t sys_wait4(int32_t target_pid, uintptr_t user_wstatus, uint64_t options, uintptr_t user_rusage) noexcept; [[nodiscard]] int64_t sys_getpid() noexcept; +[[nodiscard]] int64_t sys_gettid() noexcept; [[nodiscard]] int64_t sys_getppid() noexcept; +[[nodiscard]] int64_t sys_tkill(int32_t tid, uint64_t sig) noexcept; +[[nodiscard]] int64_t sys_tgkill(int32_t tgid, int32_t tid, uint64_t sig) noexcept; [[nodiscard]] int64_t sys_set_tid_address(uintptr_t tidptr) noexcept; [[nodiscard]] int64_t sys_setpgid(int32_t raw_pid, int32_t raw_pgid) noexcept; [[nodiscard]] int64_t sys_getpgid(int32_t raw_pid) noexcept; @@ -194,5 +198,21 @@ void build_dentry_path(const Kernel::FS::Dentry* target, char* out, size_t cap) [[nodiscard]] int64_t sys_pselect6(int32_t nfds, uintptr_t user_rfds, uintptr_t user_wfds, uintptr_t user_efds, uintptr_t user_tmo, uintptr_t user_sigpack) noexcept; +[[nodiscard]] int64_t sys_memfd_create(uintptr_t user_name, uint32_t flags) noexcept; + +// Event loop syscalls (EventSyscalls.cpp) +[[nodiscard]] int64_t sys_eventfd2(uint32_t initval, uint32_t flags) noexcept; +[[nodiscard]] int64_t sys_epoll_create1(uint32_t flags) noexcept; +[[nodiscard]] int64_t sys_epoll_ctl(int32_t epfd, int32_t op, int32_t target_fd, + uintptr_t user_event) noexcept; +[[nodiscard]] int64_t sys_epoll_pwait(int32_t epfd, uintptr_t user_events, int32_t maxevents, + int32_t timeout_ms, uintptr_t user_sigmask, + uint64_t sigsetsize) noexcept; +[[nodiscard]] int64_t sys_timerfd_create(int32_t clockid, uint32_t flags) noexcept; +[[nodiscard]] int64_t sys_timerfd_settime(int32_t fd, uint32_t flags, uintptr_t user_new_value, + uintptr_t user_old_value) noexcept; +[[nodiscard]] int64_t sys_timerfd_gettime(int32_t fd, uintptr_t user_curr_value) noexcept; +[[nodiscard]] int64_t sys_futex(uintptr_t uaddr, uint32_t op, uint32_t val, uintptr_t user_timeout, + uintptr_t uaddr2, uint32_t val3) noexcept; } // namespace Kernel::Syscalls \ No newline at end of file diff --git a/kernel/uapi/errno.hpp b/kernel/uapi/errno.hpp index 82931f2..5ec2c17 100644 --- a/kernel/uapi/errno.hpp +++ b/kernel/uapi/errno.hpp @@ -56,6 +56,7 @@ inline constexpr int64_t ERR_EADDRNOTAVAIL = -99; inline constexpr int64_t ERR_EISCONN = -106; inline constexpr int64_t ERR_ENOTCONN = -107; inline constexpr int64_t ERR_ESHUTDOWN = -108; +inline constexpr int64_t ERR_ETIMEDOUT = -110; inline constexpr int64_t ERR_ECONNREFUSED = -111; } // namespace Kernel::UAPI \ No newline at end of file diff --git a/kernel/uapi/event.hpp b/kernel/uapi/event.hpp new file mode 100644 index 0000000..88680a6 --- /dev/null +++ b/kernel/uapi/event.hpp @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#pragma once + +#include "uapi/time.hpp" + +#include +#include +#include + +#ifdef HOST_TEST +#undef EPOLL_CLOEXEC +#undef EPOLL_CTL_ADD +#undef EPOLL_CTL_DEL +#undef EPOLL_CTL_MOD +#undef EPOLLIN +#undef EPOLLPRI +#undef EPOLLOUT +#undef EPOLLERR +#undef EPOLLHUP +#undef EPOLLRDHUP +#undef EPOLLONESHOT +#undef EPOLLET +#undef EFD_SEMAPHORE +#undef EFD_NONBLOCK +#undef EFD_CLOEXEC +#undef TFD_NONBLOCK +#undef TFD_CLOEXEC +#undef TFD_TIMER_ABSTIME +#endif + +namespace Kernel::UAPI { + +// epoll flags & operations (Linux AArch64 ABI) +inline constexpr uint32_t EPOLL_CLOEXEC = 0x80000U; +inline constexpr int32_t EPOLL_CTL_ADD = 1; +inline constexpr int32_t EPOLL_CTL_DEL = 2; +inline constexpr int32_t EPOLL_CTL_MOD = 3; + +inline constexpr uint32_t EPOLLIN = 0x0001U; +inline constexpr uint32_t EPOLLPRI = 0x0002U; +inline constexpr uint32_t EPOLLOUT = 0x0004U; +inline constexpr uint32_t EPOLLERR = 0x0008U; +inline constexpr uint32_t EPOLLHUP = 0x0010U; +inline constexpr uint32_t EPOLLRDHUP = 0x2000U; +inline constexpr uint32_t EPOLLONESHOT = 1U << 30U; +inline constexpr uint32_t EPOLLET = 1U << 31U; + +// eventfd2() flags +inline constexpr uint32_t EFD_SEMAPHORE = 0x0001U; +inline constexpr uint32_t EFD_NONBLOCK = 0x0800U; +inline constexpr uint32_t EFD_CLOEXEC = 0x80000U; + +// timerfd flags +inline constexpr uint32_t TFD_NONBLOCK = 0x0800U; +inline constexpr uint32_t TFD_CLOEXEC = 0x80000U; +inline constexpr uint32_t TFD_TIMER_ABSTIME = 0x0001U; + +} // namespace Kernel::UAPI + +// Linux AArch64 LP64 struct epoll_event (16 bytes, naturally aligned) +extern "C" struct linux_epoll_event { + uint32_t events; + uint32_t _pad; + uint64_t data; +}; +static_assert(std::is_standard_layout_v, + "linux_epoll_event must be standard layout"); +static_assert(std::is_trivial_v, "linux_epoll_event must be trivial"); +static_assert(sizeof(linux_epoll_event) == 16U, + "linux_epoll_event must match Linux AArch64 LP64 ABI (16 bytes)"); +static_assert(offsetof(linux_epoll_event, events) == 0U); +static_assert(offsetof(linux_epoll_event, data) == 8U); + +// Linux AArch64 LP64 struct itimerspec (32 bytes) +extern "C" struct linux_itimerspec { + linux_timespec it_interval; + linux_timespec it_value; +}; +static_assert(std::is_standard_layout_v, + "linux_itimerspec must be standard layout"); +static_assert(std::is_trivial_v, "linux_itimerspec must be trivial"); +static_assert(sizeof(linux_itimerspec) == 32U, + "linux_itimerspec must match Linux AArch64 LP64 ABI (32 bytes)"); +static_assert(offsetof(linux_itimerspec, it_interval) == 0U); +static_assert(offsetof(linux_itimerspec, it_value) == 16U); diff --git a/kernel/uapi/fs.hpp b/kernel/uapi/fs.hpp index ee37e79..a66f4b2 100644 --- a/kernel/uapi/fs.hpp +++ b/kernel/uapi/fs.hpp @@ -45,12 +45,18 @@ #undef DT_LNK #undef DT_SOCK #undef UIO_MAXIOV +#undef MFD_CLOEXEC +#undef MFD_ALLOW_SEALING #endif namespace Kernel::UAPI { inline constexpr size_t UIO_MAXIOV = 1024U; +// memfd_create() flags +inline constexpr uint32_t MFD_CLOEXEC = 0x0001U; +inline constexpr uint32_t MFD_ALLOW_SEALING = 0x0002U; + // *at() directory descriptor & lookup flags inline constexpr int32_t AT_FDCWD = -100; inline constexpr uint64_t AT_SYMLINK_NOFOLLOW = 0x100ULL; diff --git a/kernel/uapi/socket.hpp b/kernel/uapi/socket.hpp index d7ca034..2e104ba 100644 --- a/kernel/uapi/socket.hpp +++ b/kernel/uapi/socket.hpp @@ -16,6 +16,8 @@ #undef SOCK_CLOEXEC #undef MSG_DONTWAIT #undef MSG_NOSIGNAL +#undef MSG_CTRUNC +#undef MSG_CMSG_CLOEXEC #undef SHUT_RD #undef SHUT_WR #undef SHUT_RDWR @@ -37,8 +39,15 @@ inline constexpr int32_t SOCK_NONBLOCK = 0x800; inline constexpr int32_t SOCK_CLOEXEC = 0x80000; // Message flags +inline constexpr int32_t MSG_CTRUNC = 0x08; inline constexpr int32_t MSG_DONTWAIT = 0x40; inline constexpr int32_t MSG_NOSIGNAL = 0x4000; +inline constexpr int32_t MSG_CMSG_CLOEXEC = 0x40000000; + +constexpr size_t cmsg_align(size_t len) noexcept { + constexpr size_t kAlign = sizeof(size_t); + return (len + kAlign - 1U) & ~(kAlign - 1U); +} // shutdown() how constants inline constexpr int32_t SHUT_RD = 0; diff --git a/kernel/uapi/sys.hpp b/kernel/uapi/sys.hpp index bbabff0..955a8e7 100644 --- a/kernel/uapi/sys.hpp +++ b/kernel/uapi/sys.hpp @@ -17,7 +17,17 @@ #undef CLONE_PARENT_SETTID #undef CLONE_CHILD_CLEARTID #undef CLONE_CHILD_SETTID +#undef CLONE_SETTLS +#undef CLONE_SYSVSEM +#undef CLONE_DETACHED #undef CSIGNAL_MASK +#undef FUTEX_WAIT +#undef FUTEX_WAKE +#undef FUTEX_WAIT_BITSET +#undef FUTEX_WAKE_BITSET +#undef FUTEX_PRIVATE_FLAG +#undef FUTEX_CLOCK_REALTIME +#undef FUTEX_CMD_MASK #undef PROT_NONE #undef PROT_READ #undef PROT_WRITE @@ -48,11 +58,23 @@ inline constexpr uint64_t CLONE_FILES = 0x00000400ULL; inline constexpr uint64_t CLONE_SIGHAND = 0x00000800ULL; inline constexpr uint64_t CLONE_VFORK = 0x00004000ULL; inline constexpr uint64_t CLONE_THREAD = 0x00010000ULL; +inline constexpr uint64_t CLONE_SYSVSEM = 0x00040000ULL; +inline constexpr uint64_t CLONE_SETTLS = 0x00080000ULL; inline constexpr uint64_t CLONE_PARENT_SETTID = 0x00100000ULL; inline constexpr uint64_t CLONE_CHILD_CLEARTID = 0x00200000ULL; +inline constexpr uint64_t CLONE_DETACHED = 0x00400000ULL; inline constexpr uint64_t CLONE_CHILD_SETTID = 0x01000000ULL; inline constexpr uint64_t CSIGNAL_MASK = 0x000000FFULL; +// Linux futex() operations & flags +inline constexpr uint32_t FUTEX_WAIT = 0U; +inline constexpr uint32_t FUTEX_WAKE = 1U; +inline constexpr uint32_t FUTEX_WAIT_BITSET = 9U; +inline constexpr uint32_t FUTEX_WAKE_BITSET = 10U; +inline constexpr uint32_t FUTEX_PRIVATE_FLAG = 128U; +inline constexpr uint32_t FUTEX_CLOCK_REALTIME = 256U; +inline constexpr uint32_t FUTEX_CMD_MASK = ~(FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME); + // Linux wait4() options inline constexpr uint64_t WAIT_WNOHANG = 0x00000001ULL; inline constexpr uint64_t WAIT_WUNTRACED = 0x00000002ULL; diff --git a/tests/host/mocks/host_hal.cpp b/tests/host/mocks/host_hal.cpp index 48ef998..2a49760 100644 --- a/tests/host/mocks/host_hal.cpp +++ b/tests/host/mocks/host_hal.cpp @@ -632,6 +632,10 @@ void AddressSpaceBackend::destroy_root(uintptr_t root_paddr) noexcept { } // namespace HAL +namespace { +uint64_t g_mock_timer_ticks = 0ULL; +} // namespace + namespace HAL::Platform { uint64_t timer_frequency_hz() noexcept { @@ -639,7 +643,7 @@ uint64_t timer_frequency_hz() noexcept { } uint64_t timer_counter_ticks() noexcept { - return 0ULL; + return g_mock_timer_ticks; } void init_irq_controller() noexcept {} @@ -708,7 +712,7 @@ uint64_t GenericTimer::frequency_hz() noexcept { } uint64_t GenericTimer::counter_ticks() noexcept { - return 0ULL; + return g_mock_timer_ticks; } } // namespace HAL::QemuVirt @@ -728,6 +732,7 @@ void reset_host_hal() noexcept { entry = MockPageMapping{}; } g_current_root = 0U; + g_mock_timer_ticks = 0ULL; g_fail_create_root = false; g_map_calls_remaining = static_cast(-1); g_stats = MockStats{}; @@ -743,6 +748,10 @@ void set_fail_map_after(size_t successful_maps_before_failure) noexcept { g_map_calls_remaining = successful_maps_before_failure; } +void advance_timer_ticks(uint64_t ticks) noexcept { + g_mock_timer_ticks += ticks; +} + MockStats get_mock_stats() noexcept { return g_stats; } diff --git a/tests/host/mocks/host_hal.hpp b/tests/host/mocks/host_hal.hpp index b68ff82..768d0df 100644 --- a/tests/host/mocks/host_hal.hpp +++ b/tests/host/mocks/host_hal.hpp @@ -28,6 +28,7 @@ void reset_host_hal() noexcept; // Configures simulated failure injection for AddressSpaceBackend mocks. void set_fail_create_root(bool should_fail) noexcept; void set_fail_map_after(size_t successful_maps_before_failure) noexcept; +void advance_timer_ticks(uint64_t ticks) noexcept; // Queries mock telemetry and simulated physical memory. MockStats get_mock_stats() noexcept; diff --git a/tests/host/wayland_abi_test.cpp b/tests/host/wayland_abi_test.cpp new file mode 100644 index 0000000..9796947 --- /dev/null +++ b/tests/host/wayland_abi_test.cpp @@ -0,0 +1,593 @@ +// 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/platform.hpp" +#include "mm/AddressSpace.hpp" +#include "mm/heap.hpp" +#include "mm/pfa.hpp" +#include "mocks/host_hal.hpp" +#include "net/af_unix.hpp" +#include "process/Process.hpp" +#include "sync/Futex.hpp" +#include "syscalls/SyscallInternal.hpp" +#include "uapi/errno.hpp" +#include "uapi/event.hpp" +#include "uapi/fs.hpp" +#include "uapi/socket.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 kBufA = kUserPageBase + 0x000U; +constexpr uintptr_t kBufB = kUserPageBase + 0x200U; +constexpr uintptr_t kBufC = kUserPageBase + 0x400U; +constexpr uintptr_t kStructA = kUserPageBase + 0x600U; +constexpr uintptr_t kStructB = kUserPageBase + 0x800U; +constexpr uintptr_t kCtrlA = kUserPageBase + 0xA00U; +constexpr uintptr_t kCtrlB = kUserPageBase + 0xC00U; +constexpr uintptr_t kBadAddr = kUserPageBase + 0x8000U; + +void init_wayland_host_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(); + Kernel::Sync::futex_reset(); + + 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 ScopedUserProc final { + Kernel::Process::Process* proc{nullptr}; + Kernel::Process::Process* prev{nullptr}; + uintptr_t scratch_pa{0U}; + + ScopedUserProc() 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()); + scratch_pa = Kernel::MM::alloc_frame(); + REQUIRE(scratch_pa != 0U); + REQUIRE(proc->address_space().map_user_page(kUserPageBase, scratch_pa, + HAL::PageFlags::User | HAL::PageFlags::Read | + HAL::PageFlags::Write)); + Kernel::Process::Process::set_current(proc); + } + + ~ScopedUserProc() 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 (scratch_pa != 0U) { + Kernel::MM::free_frame(scratch_pa); + } + } + + ScopedUserProc(const ScopedUserProc&) = delete; + ScopedUserProc& operator=(const ScopedUserProc&) = delete; + ScopedUserProc(ScopedUserProc&&) = delete; + ScopedUserProc& operator=(ScopedUserProc&&) = delete; + + [[nodiscard]] uintptr_t root() const noexcept { return proc->address_space().root_paddr(); } + + void activate() const noexcept { Kernel::Process::Process::set_current(proc); } + + void write_str(uintptr_t va, const char* str) const noexcept { + REQUIRE(Kernel::MM::copy_to_user(root(), va, str, std::strlen(str) + 1U) == 0); + } +}; + +void send_with_fd(const ScopedUserProc& ctx, int32_t sock_fd, const char* payload, + size_t payload_len, int32_t pass_fd, int64_t expected_rc) noexcept { + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kBufA, payload, payload_len) == 0); + const linux_iovec iov{.iov_base = kBufA, .iov_len = payload_len}; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructA, &iov, sizeof(iov)) == 0); + + uint8_t ctrl[32]{}; + const size_t cmsg_len = sizeof(linux_cmsghdr) + sizeof(int32_t); + const size_t ctrl_len = cmsg_align(cmsg_len); + const linux_cmsghdr hdr{ + .cmsg_len = cmsg_len, + .cmsg_level = SOL_SOCKET, + .cmsg_type = SCM_RIGHTS, + }; + std::memcpy(ctrl, &hdr, sizeof(hdr)); + std::memcpy(ctrl + sizeof(hdr), &pass_fd, sizeof(pass_fd)); + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kCtrlA, ctrl, ctrl_len) == 0); + + const linux_msghdr msg{ + .msg_name = nullptr, + .msg_namelen = 0U, + ._pad0 = 0U, + .msg_iov = reinterpret_cast(kStructA), + .msg_iovlen = 1U, + .msg_control = reinterpret_cast(kCtrlA), + .msg_controllen = ctrl_len, + .msg_flags = 0, + ._pad1 = 0U, + }; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructB, &msg, sizeof(msg)) == 0); + CHECK(sys_sendmsg(static_cast(sock_fd), kStructB, 0U) == expected_rc); +} + +} // namespace + +TEST_CASE("Wayland ABI: SCM_RIGHTS over AF_UNIX stream/dgram, CLOEXEC, CTRUNC, and framing", + "[wayland][scm_rights][af_unix]") { + init_wayland_host_env(); + + // Verify UAPI struct ABI constants + CHECK(sizeof(linux_epoll_event) == 16U); + CHECK(offsetof(linux_epoll_event, data) == 8U); + CHECK(sizeof(linux_itimerspec) == 32U); + CHECK(sizeof(linux_cmsghdr) == 16U); + + { + ScopedUserProc ctx; + + // Create SOCK_STREAM socketpair + constexpr auto kStreamNb = static_cast(static_cast(SOCK_STREAM) | + static_cast(SOCK_NONBLOCK)); + REQUIRE(sys_socketpair(AF_UNIX, kStreamNb, 0, kStructA) == 0); + int32_t sp[2]{-1, -1}; + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), sp, kStructA, sizeof(sp)) == 0); + REQUIRE(sp[0] >= 0); + REQUIRE(sp[1] >= 0); + + // Create a memfd and write known data into it + ctx.write_str(kBufC, "wl_shm_test"); + const int64_t mfd = sys_memfd_create(kBufC, MFD_CLOEXEC); + REQUIRE(mfd >= 0); + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kBufB, "PIXELDATA", 9U) == 0); + REQUIRE(sys_write(static_cast(mfd), kBufB, 9U) == 9); + + // Send two back-to-back messages with SCM_RIGHTS to verify stream boundary framing + send_with_fd(ctx, sp[0], "A1", 2U, static_cast(mfd), 2); + send_with_fd(ctx, sp[0], "B2", 2U, static_cast(mfd), 2); + + // First recvmsg with MSG_CMSG_CLOEXEC must NOT coalesce past the second rights batch + const linux_iovec riov{.iov_base = kBufB, .iov_len = 16U}; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructA, &riov, sizeof(riov)) == 0); + const size_t ctrl_cap = cmsg_align(sizeof(linux_cmsghdr) + sizeof(int32_t)); + linux_msghdr rmsg{ + .msg_name = nullptr, + .msg_namelen = 0U, + ._pad0 = 0U, + .msg_iov = reinterpret_cast(kStructA), + .msg_iovlen = 1U, + .msg_control = reinterpret_cast(kCtrlB), + .msg_controllen = ctrl_cap, + .msg_flags = 0, + ._pad1 = 0U, + }; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructB, &rmsg, sizeof(rmsg)) == 0); + REQUIRE(sys_recvmsg(static_cast(sp[1]), kStructB, MSG_CMSG_CLOEXEC) == 2); + + char got[8]{}; + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), got, kBufB, 2U) == 0); + CHECK(std::memcmp(got, "A1", 2U) == 0); + + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), &rmsg, kStructB, sizeof(rmsg)) == 0); + CHECK((static_cast(rmsg.msg_flags) & static_cast(MSG_CTRUNC)) == 0U); + CHECK(rmsg.msg_controllen == ctrl_cap); + + uint8_t rctrl[32]{}; + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), rctrl, kCtrlB, ctrl_cap) == 0); + linux_cmsghdr rcmsg{}; + int32_t recvd_fd = -1; + std::memcpy(&rcmsg, rctrl, sizeof(rcmsg)); + std::memcpy(&recvd_fd, rctrl + sizeof(rcmsg), sizeof(recvd_fd)); + CHECK(rcmsg.cmsg_level == SOL_SOCKET); + CHECK(rcmsg.cmsg_type == SCM_RIGHTS); + REQUIRE(recvd_fd >= 0); + CHECK(recvd_fd != mfd); + + // MSG_CMSG_CLOEXEC must set FD_CLOEXEC on received FD + CHECK(sys_fcntl(static_cast(recvd_fd), F_GETFD, 0U) == 1); + + // Verify received FD points to the exact same memfd file content + REQUIRE(sys_lseek(static_cast(recvd_fd), 0, SEEK_SET) == 0); + REQUIRE(sys_read(static_cast(recvd_fd), kBufC, 9U) == 9); + char read_back[16]{}; + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), read_back, kBufC, 9U) == 0); + CHECK(std::memcmp(read_back, "PIXELDATA", 9U) == 0); + REQUIRE(sys_close(static_cast(recvd_fd)) == 0); + + // Second recvmsg with too-small msg_controllen must set MSG_CTRUNC without leaking FDs + rmsg.msg_control = reinterpret_cast(kCtrlB); + rmsg.msg_controllen = 8U; // smaller than sizeof(linux_cmsghdr) + sizeof(int32_t) + rmsg.msg_flags = 0; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructB, &rmsg, sizeof(rmsg)) == 0); + REQUIRE(sys_recvmsg(static_cast(sp[1]), kStructB, 0U) == 2); + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), &rmsg, kStructB, sizeof(rmsg)) == 0); + CHECK((static_cast(rmsg.msg_flags) & static_cast(MSG_CTRUNC)) != 0U); + CHECK(rmsg.msg_controllen == 0U); + + // Invalid FD in SCM_RIGHTS returns ERR_EBADF + send_with_fd(ctx, sp[0], "X", 1U, 99, ERR_EBADF); + + // Leave an unread FD queued in socket and close both ends: must clean up cleanly + send_with_fd(ctx, sp[0], "U", 1U, static_cast(mfd), 1); + REQUIRE(sys_close(static_cast(mfd)) == 0); + REQUIRE(sys_close(static_cast(sp[0])) == 0); + REQUIRE(sys_close(static_cast(sp[1])) == 0); + + // Also test SOCK_DGRAM SCM_RIGHTS + constexpr auto kDgramNb = static_cast(static_cast(SOCK_DGRAM) | + static_cast(SOCK_NONBLOCK)); + REQUIRE(sys_socketpair(AF_UNIX, kDgramNb, 0, kStructA) == 0); + int32_t dg[2]{-1, -1}; + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), dg, kStructA, sizeof(dg)) == 0); + const int64_t efd = sys_eventfd2(7U, EFD_NONBLOCK | EFD_CLOEXEC); + REQUIRE(efd >= 0); + send_with_fd(ctx, dg[0], "DG", 2U, static_cast(efd), 2); + REQUIRE(sys_close(static_cast(efd)) == 0); + + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructA, &riov, sizeof(riov)) == 0); + rmsg.msg_control = reinterpret_cast(kCtrlB); + rmsg.msg_controllen = ctrl_cap; + rmsg.msg_flags = 0; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructB, &rmsg, sizeof(rmsg)) == 0); + REQUIRE(sys_recvmsg(static_cast(dg[1]), kStructB, 0U) == 2); + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), rctrl, kCtrlB, ctrl_cap) == 0); + int32_t dg_efd = -1; + std::memcpy(&dg_efd, rctrl + sizeof(linux_cmsghdr), sizeof(dg_efd)); + REQUIRE(dg_efd >= 0); + CHECK(sys_fcntl(static_cast(dg_efd), F_GETFD, 0U) == 0); // no MSG_CMSG_CLOEXEC + REQUIRE(sys_read(static_cast(dg_efd), kBufC, 8U) == 8); + uint64_t counter = 0ULL; + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), &counter, kBufC, sizeof(counter)) == 0); + CHECK(counter == 7ULL); + REQUIRE(sys_close(static_cast(dg_efd)) == 0); + REQUIRE(sys_close(static_cast(dg[0])) == 0); + REQUIRE(sys_close(static_cast(dg[1])) == 0); + } +} + +TEST_CASE("Wayland ABI: memfd_create and cross-process MAP_SHARED zero-copy pages on tmpfs", + "[wayland][memfd][tmpfs][mmap]") { + init_wayland_host_env(); + + // Warm up slab caches for Process / SharedProcessState / FdTable + { ScopedUserProc warmup; } + const size_t baseline_free = Kernel::MM::pfa_free_pages_count(); + { + ScopedUserProc proc_a; + ScopedUserProc proc_b; + + proc_a.activate(); + CHECK(sys_memfd_create(kBadAddr, 0U) == ERR_EFAULT); + proc_a.write_str(kBufA, "wl_pool"); + CHECK(sys_memfd_create(kBufA, 0xFFFFU) == ERR_EINVAL); + + const int64_t mfd_a = sys_memfd_create(kBufA, MFD_CLOEXEC); + REQUIRE(mfd_a >= 0); + CHECK(sys_fcntl(static_cast(mfd_a), F_GETFD, 0U) == 1); + + // Size > 32 pages (36 pages = 144 KiB) to also exercise TmpfsNode::m_indirect + constexpr uint64_t kLargeSize = 36ULL * 4096ULL; + REQUIRE(sys_ftruncate(static_cast(mfd_a), static_cast(kLargeSize)) == 0); + + // Map MAP_SHARED in Process A + const int64_t map_a = sys_mmap(0U, kLargeSize, PROT_READ | PROT_WRITE, MAP_SHARED, + static_cast(mfd_a), 0ULL); + REQUIRE(map_a > 0); + + // Share the exact same File* into Process B (simulating SCM_RIGHTS handoff) + auto* const file_a = proc_a.proc->fds().at(static_cast(mfd_a))->file(); + REQUIRE(file_a != nullptr); + file_a->retain(); + proc_b.activate(); + const int mfd_b = proc_b.proc->fds().allocate(proc_b.proc->rlim_nofile().rlim_cur); + REQUIRE(mfd_b >= 0); + REQUIRE(proc_b.proc->fds().install(static_cast(mfd_b), file_a, 0U)); + + const int64_t map_b = sys_mmap(0U, kLargeSize, PROT_READ | PROT_WRITE, MAP_SHARED, + static_cast(mfd_b), 0ULL); + REQUIRE(map_b > 0); + + // Close both FDs before faulting pages — MAP_SHARED VMAs must retain the inode! + proc_a.activate(); + REQUIRE(sys_close(static_cast(mfd_a)) == 0); + proc_b.activate(); + REQUIRE(sys_close(static_cast(mfd_b)) == 0); + + // Fault both page 0 (direct) and page 34 (indirect) in Process A and Process B + for (const uint64_t off : {0ULL, 34ULL * 4096ULL}) { + uintptr_t pa_a = 0U; + uintptr_t pa_b = 0U; + REQUIRE(Kernel::MM::AddressSpace::resolve_file_backed_page( + proc_a.root(), static_cast(map_a) + static_cast(off), true, + false, pa_a)); + REQUIRE(Kernel::MM::AddressSpace::resolve_file_backed_page( + proc_b.root(), static_cast(map_b) + static_cast(off), true, + false, pa_b)); + CHECK(pa_a != 0U); + CHECK(pa_a == pa_b); // Exact same physical frame shared zero-copy! + + // Write via Process A, read via Process B + const uint32_t magic = 0xCAFE0000U | static_cast(off >> 12U); + REQUIRE(Kernel::MM::copy_to_user( + proc_a.root(), static_cast(map_a) + static_cast(off), + &magic, sizeof(magic)) == 0); + uint32_t observed = 0U; + REQUIRE(Kernel::MM::copy_from_user(proc_b.root(), &observed, + static_cast(map_b) + + static_cast(off), + sizeof(observed)) == 0); + CHECK(observed == magic); + } + } + // After both processes tear down, every tmpfs page + indirect table must be freed + CHECK(Kernel::MM::pfa_free_pages_count() == baseline_free); +} + +TEST_CASE("Wayland ABI: eventfd2, timerfd, and epoll_create1/ctl/pwait semantics", + "[wayland][epoll][eventfd][timerfd]") { + init_wayland_host_env(); + ScopedUserProc ctx; + + // 1. eventfd2 (normal counter + EFD_SEMAPHORE + EFD_NONBLOCK + EFD_CLOEXEC) + CHECK(sys_eventfd2(0U, 0xFFFFU) == ERR_EINVAL); + const int64_t efd = sys_eventfd2(2U, EFD_NONBLOCK | EFD_CLOEXEC); + REQUIRE(efd >= 0); + CHECK(sys_fcntl(static_cast(efd), F_GETFD, 0U) == 1); + + uint64_t val = 5ULL; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kBufA, &val, sizeof(val)) == 0); + REQUIRE(sys_write(static_cast(efd), kBufA, sizeof(val)) == 8); + // Overflow write (UINT64_MAX) rejected with EINVAL + const uint64_t max_u64 = UINT64_MAX; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kBufA, &max_u64, sizeof(max_u64)) == 0); + CHECK(sys_write(static_cast(efd), kBufA, sizeof(max_u64)) == ERR_EINVAL); + + val = 0ULL; + REQUIRE(sys_read(static_cast(efd), kBufB, sizeof(val)) == 8); + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), &val, kBufB, sizeof(val)) == 0); + CHECK(val == 7ULL); + // Now empty -> EAGAIN + CHECK(sys_read(static_cast(efd), kBufB, sizeof(val)) == ERR_EAGAIN); + + // Semaphore mode decrements by 1 per read + const int64_t sem_efd = sys_eventfd2(2U, EFD_SEMAPHORE | EFD_NONBLOCK); + REQUIRE(sem_efd >= 0); + REQUIRE(sys_read(static_cast(sem_efd), kBufB, 8U) == 8); + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), &val, kBufB, 8U) == 0); + CHECK(val == 1ULL); + REQUIRE(sys_read(static_cast(sem_efd), kBufB, 8U) == 8); + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), &val, kBufB, 8U) == 0); + CHECK(val == 1ULL); + CHECK(sys_read(static_cast(sem_efd), kBufB, 8U) == ERR_EAGAIN); + + // 2. timerfd_create / timerfd_settime / timerfd_gettime + CHECK(sys_timerfd_create(99, 0U) == ERR_EINVAL); + CHECK(sys_timerfd_create(1, 0xFFFFU) == ERR_EINVAL); + const int64_t tfd = sys_timerfd_create(1 /*CLOCK_MONOTONIC*/, TFD_NONBLOCK | TFD_CLOEXEC); + REQUIRE(tfd >= 0); + CHECK(sys_fcntl(static_cast(tfd), F_GETFD, 0U) == 1); + // Disarmed read -> EAGAIN + CHECK(sys_read(static_cast(tfd), kBufB, 8U) == ERR_EAGAIN); + + // Arm periodic 100ms timer (freq = 62.5 MHz => 6,250,000 ticks per 100ms) + const linux_itimerspec spec{ + .it_interval = {.tv_sec = 0, .tv_nsec = 100'000'000}, + .it_value = {.tv_sec = 0, .tv_nsec = 100'000'000}, + }; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructA, &spec, sizeof(spec)) == 0); + REQUIRE(sys_timerfd_settime(static_cast(tfd), 0U, kStructA, kStructB) == 0); + + // Before expiry: gettime shows remaining ~100ms, read returns EAGAIN + linux_itimerspec cur{}; + REQUIRE(sys_timerfd_gettime(static_cast(tfd), kStructB) == 0); + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), &cur, kStructB, sizeof(cur)) == 0); + CHECK(cur.it_value.tv_nsec > 0); + CHECK(cur.it_interval.tv_nsec == 100'000'000); + CHECK(sys_read(static_cast(tfd), kBufB, 8U) == ERR_EAGAIN); + + // Advance mock clock by 250ms (2 expirations: at 100ms and 200ms) + const uint64_t ticks_per_100ms = HAL::Platform::timer_frequency_hz() / 10ULL; + HostTest::advance_timer_ticks((ticks_per_100ms * 2ULL) + (ticks_per_100ms / 2ULL)); + + // 3. epoll_create1 / epoll_ctl / epoll_pwait + CHECK(sys_epoll_create1(0xFFFFU) == ERR_EINVAL); + const int64_t epfd = sys_epoll_create1(EPOLL_CLOEXEC); + REQUIRE(epfd >= 0); + CHECK(sys_fcntl(static_cast(epfd), F_GETFD, 0U) == 1); + + // Self-watch rejected with EINVAL + linux_epoll_event ev{.events = EPOLLIN, ._pad = 0U, .data = 42ULL}; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructA, &ev, sizeof(ev)) == 0); + CHECK(sys_epoll_ctl(static_cast(epfd), EPOLL_CTL_ADD, static_cast(epfd), + kStructA) == ERR_EINVAL); + + // Add timerfd + eventfd (with EPOLLET) + ev = linux_epoll_event{.events = EPOLLIN, ._pad = 0U, .data = 0x1111ULL}; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructA, &ev, sizeof(ev)) == 0); + REQUIRE(sys_epoll_ctl(static_cast(epfd), EPOLL_CTL_ADD, static_cast(tfd), + kStructA) == 0); + CHECK(sys_epoll_ctl(static_cast(epfd), EPOLL_CTL_ADD, static_cast(tfd), + kStructA) == ERR_EEXIST); + + ev = linux_epoll_event{.events = EPOLLIN | EPOLLET, ._pad = 0U, .data = 0x2222ULL}; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructA, &ev, sizeof(ev)) == 0); + REQUIRE(sys_epoll_ctl(static_cast(epfd), EPOLL_CTL_ADD, static_cast(efd), + kStructA) == 0); + + // epoll_pwait(timeout=0) must return timerfd ready (eventfd is currently 0) + REQUIRE(sys_epoll_pwait(static_cast(epfd), kStructB, 4, 0, 0U, 0U) == 1); + linux_epoll_event out_evs[4]{}; + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), out_evs, kStructB, sizeof(linux_epoll_event)) == + 0); + CHECK((out_evs[0].events & EPOLLIN) != 0U); + CHECK(out_evs[0].data == 0x1111ULL); + + // Reading timerfd returns 2 expirations and clears readiness + REQUIRE(sys_read(static_cast(tfd), kBufB, 8U) == 8); + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), &val, kBufB, 8U) == 0); + CHECK(val == 2ULL); + CHECK(sys_epoll_pwait(static_cast(epfd), kStructB, 4, 0, 0U, 0U) == 0); + + // Signal eventfd -> EPOLLET fires once, then suppresses until drained and re-signaled + val = 1ULL; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kBufA, &val, 8U) == 0); + REQUIRE(sys_write(static_cast(efd), kBufA, 8U) == 8); + REQUIRE(sys_epoll_pwait(static_cast(epfd), kStructB, 4, 0, 0U, 0U) == 1); + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), out_evs, kStructB, sizeof(linux_epoll_event)) == + 0); + CHECK(out_evs[0].data == 0x2222ULL); + CHECK(sys_epoll_pwait(static_cast(epfd), kStructB, 4, 0, 0U, 0U) == 0); + + // Test EPOLLONESHOT via EPOLL_CTL_MOD + ev = linux_epoll_event{.events = EPOLLIN | EPOLLONESHOT, ._pad = 0U, .data = 0x3333ULL}; + REQUIRE(Kernel::MM::copy_to_user(ctx.root(), kStructA, &ev, sizeof(ev)) == 0); + REQUIRE(sys_epoll_ctl(static_cast(epfd), EPOLL_CTL_MOD, static_cast(efd), + kStructA) == 0); + REQUIRE(sys_epoll_pwait(static_cast(epfd), kStructB, 4, 0, 0U, 0U) == 1); + REQUIRE(Kernel::MM::copy_from_user(ctx.root(), out_evs, kStructB, sizeof(linux_epoll_event)) == + 0); + CHECK(out_evs[0].data == 0x3333ULL); + // Disarmed by EPOLLONESHOT even though eventfd still has count == 1 + CHECK(sys_epoll_pwait(static_cast(epfd), kStructB, 4, 0, 0U, 0U) == 0); + + // Delete & missing FD errors + REQUIRE(sys_epoll_ctl(static_cast(epfd), EPOLL_CTL_DEL, static_cast(tfd), + 0U) == 0); + CHECK(sys_epoll_ctl(static_cast(epfd), EPOLL_CTL_DEL, static_cast(tfd), 0U) == + ERR_ENOENT); + + // Close watched efd without DEL -> epoll auto-evicts without crashing + REQUIRE(sys_close(static_cast(efd)) == 0); + CHECK(sys_epoll_pwait(static_cast(epfd), kStructB, 4, 0, 0U, 0U) == 0); + + REQUIRE(sys_close(static_cast(sem_efd)) == 0); + REQUIRE(sys_close(static_cast(tfd)) == 0); + REQUIRE(sys_close(static_cast(epfd)) == 0); +} + +TEST_CASE("Wayland ABI: CLONE_THREAD SharedProcessState and sys_futex semantics", + "[wayland][threads][futex]") { + init_wayland_host_env(); + + // Warm up slab caches for Process / SharedProcessState / EventFd + { + ScopedUserProc warmup; + const int64_t tmp_efd = sys_eventfd2(0U, EFD_NONBLOCK); + REQUIRE(tmp_efd >= 0); + REQUIRE(sys_close(static_cast(tmp_efd)) == 0); + } + const size_t baseline_free = Kernel::MM::pfa_free_pages_count(); + { + ScopedUserProc leader; + auto* const sibling = Kernel::Process::Process::create_thread(*leader.proc); + REQUIRE(sibling != nullptr); + + // Thread group invariants + CHECK(sibling->is_thread()); + CHECK(!leader.proc->is_thread()); + CHECK(sibling->tgid() == leader.proc->pid()); + CHECK(sibling->pid() != leader.proc->pid()); + CHECK(sibling->address_space().root_paddr() == leader.proc->address_space().root_paddr()); + CHECK(&sibling->fds() == &leader.proc->fds()); + CHECK(&sibling->signals() == &leader.proc->signals()); + + // FD opened by sibling is immediately visible to leader + Kernel::Process::Process::set_current(sibling); + const int64_t efd = sys_eventfd2(42U, EFD_NONBLOCK); + REQUIRE(efd >= 0); + + leader.activate(); + REQUIRE(sys_read(static_cast(efd), kBufA, 8U) == 8); + uint64_t got = 0ULL; + REQUIRE(Kernel::MM::copy_from_user(leader.root(), &got, kBufA, sizeof(got)) == 0); + CHECK(got == 42ULL); + REQUIRE(sys_close(static_cast(efd)) == 0); + + // Futex error paths & immediate returns + CHECK(sys_futex(kBufA + 1U, FUTEX_WAIT, 0U, 0U, 0U, 0U) == ERR_EINVAL); // unaligned + CHECK(sys_futex(kBufA, 99U, 0U, 0U, 0U, 0U) == ERR_ENOSYS); // unknown op + + const uint32_t word = 123U; + REQUIRE(Kernel::MM::copy_to_user(leader.root(), kBufA, &word, sizeof(word)) == 0); + // Mismatch returns ERR_EAGAIN immediately + CHECK(sys_futex(kBufA, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 999U, 0U, 0U, 0U) == ERR_EAGAIN); + // Zero timeout on matching value returns ERR_ETIMEDOUT immediately + const linux_timespec zero_ts{.tv_sec = 0, .tv_nsec = 0}; + REQUIRE(Kernel::MM::copy_to_user(leader.root(), kStructA, &zero_ts, sizeof(zero_ts)) == 0); + CHECK(sys_futex(kBufA, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 123U, kStructA, 0U, 0U) == + ERR_ETIMEDOUT); + // FUTEX_WAKE with no waiters returns 0 + CHECK(sys_futex(kBufA, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1U, 0U, 0U, 0U) == 0); + + // Destroy sibling first, then leader via RAII destructor + Kernel::Process::Process::destroy(*sibling); + } + CHECK(Kernel::MM::pfa_free_pages_count() == baseline_free); +} + +TEST_CASE("Wayland ABI: Root session leader teardown reaps zombie session children", + "[wayland][process][session]") { + init_wayland_host_env(); + + { ScopedUserProc warmup; } + const size_t baseline_free = Kernel::MM::pfa_free_pages_count(); + const size_t baseline_procs = Kernel::Process::Process::active_count(); + + { + ScopedUserProc leader; + REQUIRE(leader.proc->ppid() == 0U); + REQUIRE(leader.proc->sid() == leader.proc->pid()); + + // Spawn a background child in the same session and transition it to Zombie + auto* const bg_child = Kernel::Process::Process::create(leader.proc->pid()); + REQUIRE(bg_child != nullptr); + bg_child->set_sid(leader.proc->sid()); + bg_child->set_pgid(bg_child->pid()); + auto bg_as = Kernel::MM::AddressSpace::create(); + REQUIRE(bg_as.is_ok()); + bg_child->address_space() = static_cast(bg_as.value()); + bg_child->set_state(Kernel::Process::ProcessState::Zombie); + + CHECK(Kernel::Process::Process::active_count() == baseline_procs + 2U); + // leader destructor calls Process::destroy(*leader.proc), which must reap bg_child too + } + + CHECK(Kernel::Process::Process::active_count() == baseline_procs); + CHECK(Kernel::MM::pfa_free_pages_count() == baseline_free); +} diff --git a/user/wl_client.c b/user/wl_client.c new file mode 100644 index 0000000..21df242 --- /dev/null +++ b/user/wl_client.c @@ -0,0 +1,600 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#define _GNU_SOURCE +#include "wl_proto.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef SYS_memfd_create +#define SYS_memfd_create 279 +#endif +#ifndef MFD_CLOEXEC +#define MFD_CLOEXEC 0x0001U +#endif + +#define BUF_WIDTH 320 +#define BUF_HEIGHT 240 +#define BUF_STRIDE (BUF_WIDTH * 4) +#define BUF_SIZE (BUF_STRIDE * BUF_HEIGHT) + +/* Client-allocated Wayland object IDs (ID 1 is wl_display) */ +#define ID_REGISTRY 2U +#define ID_SYNC_INIT 3U +#define ID_COMPOSITOR 4U +#define ID_SHM 5U +#define ID_SEAT 6U +#define ID_SYNC_BIND 7U +#define ID_SURFACE 8U +#define ID_SHM_POOL 9U +#define ID_BUFFER 10U +#define ID_POINTER 11U +#define ID_KEYBOARD 12U +#define ID_FRAME_CB_BASE 100U + +struct render_worker_state { + uint32_t* pixels; + uint32_t width; + uint32_t height; + volatile uint32_t req_seq; + volatile uint32_t done_seq; + volatile uint32_t frame_index; + volatile uint32_t stop; + long worker_tid; +}; + +static long futex_wait_u32(volatile uint32_t* addr, uint32_t expected) { + return syscall(SYS_futex, (void*)addr, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, expected, NULL, NULL, + 0); +} + +static long futex_wake_u32(volatile uint32_t* addr, uint32_t count) { + return syscall(SYS_futex, (void*)addr, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, count, NULL, NULL, 0); +} + +static void render_frame_pixels(uint32_t* pixels, uint32_t w, uint32_t h, uint32_t frame) { + uint32_t box_x = 24U + ((frame * 48U) % (w - 88U)); + uint32_t box_y = 24U + ((frame * 32U) % (h - 88U)); + + for (uint32_t y = 0U; y < h; ++y) { + uint32_t* row = pixels + ((size_t)y * (size_t)w); + for (uint32_t x = 0U; x < w; ++x) { + /* Crisp border */ + if (x < 3U || x >= w - 3U || y < 3U || y >= h - 3U) { + row[x] = 0xFFFACC15U; /* Warm gold border */ + continue; + } + /* Animated bright accent square */ + if (x >= box_x && x < box_x + 56U && y >= box_y && y < box_y + 56U) { + row[x] = 0xFF38BDF8U; /* Sky blue accent */ + continue; + } + /* Smooth multi-channel gradient shifted per frame */ + uint32_t r = ((x * 255U) / w + (frame * 37U)) & 0xFFU; + uint32_t g = ((y * 255U) / h + (frame * 23U)) & 0xFFU; + uint32_t b = (180U + ((x + y) / 4U)) & 0xFFU; + row[x] = 0xFF000000U | (r << 16U) | (g << 8U) | b; + } + } +} + +static void* render_worker_main(void* arg) { + struct render_worker_state* st = (struct render_worker_state*)arg; + st->worker_tid = syscall(SYS_gettid); + + uint32_t last_seen = 0U; + for (;;) { + while (__atomic_load_n(&st->req_seq, __ATOMIC_ACQUIRE) == last_seen && + __atomic_load_n(&st->stop, __ATOMIC_ACQUIRE) == 0U) { + (void)futex_wait_u32(&st->req_seq, last_seen); + } + if (__atomic_load_n(&st->stop, __ATOMIC_ACQUIRE) != 0U) { + break; + } + uint32_t cur = __atomic_load_n(&st->req_seq, __ATOMIC_ACQUIRE); + uint32_t frame = __atomic_load_n(&st->frame_index, __ATOMIC_ACQUIRE); + render_frame_pixels(st->pixels, st->width, st->height, frame); + last_seen = cur; + __atomic_store_n(&st->done_seq, cur, __ATOMIC_RELEASE); + (void)futex_wake_u32(&st->done_seq, 1U); + } + return NULL; +} + +struct client_ctx { + int sock_fd; + int epoll_fd; + uint8_t rx_buf[4096]; + size_t rx_len; + + uint32_t global_compositor; + uint32_t global_shm; + uint32_t global_seat; + uint32_t seat_caps; + int has_argb8888; + int sync_init_done; + int sync_bind_done; + uint32_t last_frame_cb_done; + uint32_t buffer_releases; + uint32_t pointer_events; + uint32_t keyboard_events; + int protocol_error; +}; + +static void dispatch_event(struct client_ctx* c, uint32_t obj_id, uint16_t opcode, + const uint8_t* payload, uint32_t payload_len) { + struct wl_reader r; + wl_r_init(&r, payload, payload_len); + + if (obj_id == WL_DISPLAY_ID) { + if (opcode == WL_DISPLAY_EVENT_ERROR) { + uint32_t err_obj = 0U, code = 0U; + char msg[128]; + if (wl_r_u32(&r, &err_obj) == 0 && wl_r_u32(&r, &code) == 0 && + wl_r_str(&r, msg, sizeof(msg)) == 0) { + fprintf(stderr, "[wl_client] wl_display.error obj=%u code=%u: %s\n", err_obj, code, + msg); + } + c->protocol_error = 1; + } + return; + } + + if (obj_id == ID_REGISTRY && opcode == WL_REGISTRY_EVENT_GLOBAL) { + uint32_t name = 0U, ver = 0U; + char iface[64]; + if (wl_r_u32(&r, &name) == 0 && wl_r_str(&r, iface, sizeof(iface)) == 0 && + wl_r_u32(&r, &ver) == 0) { + (void)ver; + if (strcmp(iface, "wl_compositor") == 0) { + c->global_compositor = name; + } else if (strcmp(iface, "wl_shm") == 0) { + c->global_shm = name; + } else if (strcmp(iface, "wl_seat") == 0) { + c->global_seat = name; + } + } + return; + } + + if (obj_id == ID_SHM && opcode == WL_SHM_EVENT_FORMAT) { + uint32_t fmt = 0U; + if (wl_r_u32(&r, &fmt) == 0 && fmt == WL_SHM_FORMAT_ARGB8888) { + c->has_argb8888 = 1; + } + return; + } + + if (obj_id == ID_SEAT && opcode == WL_SEAT_EVENT_CAPABILITIES) { + uint32_t caps = 0U; + if (wl_r_u32(&r, &caps) == 0) { + c->seat_caps = caps; + } + return; + } + + if (obj_id == ID_BUFFER && opcode == WL_BUFFER_EVENT_RELEASE) { + c->buffer_releases++; + return; + } + + if (obj_id == ID_POINTER) { + if (opcode == WL_POINTER_EVENT_MOTION) { + uint32_t t = 0U, sx = 0U, sy = 0U; + if (wl_r_u32(&r, &t) == 0 && wl_r_u32(&r, &sx) == 0 && wl_r_u32(&r, &sy) == 0) { + c->pointer_events++; + printf("[wl_client] wl_pointer.motion (%d, %d)\n", wl_fixed_to_int(sx), + wl_fixed_to_int(sy)); + fflush(stdout); + } + } else if (opcode == WL_POINTER_EVENT_BUTTON) { + uint32_t ser = 0U, t = 0U, btn = 0U, state = 0U; + if (wl_r_u32(&r, &ser) == 0 && wl_r_u32(&r, &t) == 0 && wl_r_u32(&r, &btn) == 0 && + wl_r_u32(&r, &state) == 0) { + c->pointer_events++; + printf("[wl_client] wl_pointer.button btn=%u state=%u\n", btn, state); + fflush(stdout); + } + } + return; + } + + if (obj_id == ID_KEYBOARD) { + if (opcode == WL_KEYBOARD_EVENT_KEY) { + uint32_t ser = 0U, t = 0U, key = 0U, state = 0U; + if (wl_r_u32(&r, &ser) == 0 && wl_r_u32(&r, &t) == 0 && wl_r_u32(&r, &key) == 0 && + wl_r_u32(&r, &state) == 0) { + c->keyboard_events++; + printf("[wl_client] wl_keyboard.key code=%u state=%u\n", key, state); + fflush(stdout); + } + } + return; + } + + if (opcode == WL_CALLBACK_EVENT_DONE) { + if (obj_id == ID_SYNC_INIT) { + c->sync_init_done = 1; + } else if (obj_id == ID_SYNC_BIND) { + c->sync_bind_done = 1; + } else if (obj_id >= ID_FRAME_CB_BASE) { + c->last_frame_cb_done = obj_id; + } + } +} + +static int pump_events(struct client_ctx* c, int timeout_ms) { + struct epoll_event evs[4]; + int n = epoll_pwait(c->epoll_fd, evs, 4, timeout_ms, NULL); + if (n < 0) { + return (errno == EINTR) ? 0 : -1; + } + if (n == 0) { + return 0; + } + + for (;;) { + if (c->rx_len >= sizeof(c->rx_buf)) { + return -1; + } + size_t nfd = 0U; + ssize_t r = wl_recv_chunk(c->sock_fd, c->rx_buf + c->rx_len, sizeof(c->rx_buf) - c->rx_len, + NULL, 0U, &nfd); + if (r < 0) { + if (errno == EINTR) { + continue; + } + if (errno == EAGAIN || errno == EWOULDBLOCK) { + break; + } + return -1; + } + if (r == 0) { + return -1; + } + c->rx_len += (size_t)r; + + size_t consumed = 0U; + while (c->rx_len - consumed >= WL_MSG_HEADER_BYTES) { + uint32_t obj_id = 0U, word1 = 0U; + memcpy(&obj_id, c->rx_buf + consumed, 4); + memcpy(&word1, c->rx_buf + consumed + 4, 4); + uint16_t opcode = (uint16_t)(word1 & 0xFFFFU); + uint32_t msg_size = (word1 >> 16U) & 0xFFFFU; + if (msg_size < WL_MSG_HEADER_BYTES || msg_size > WL_MAX_MSG_BYTES) { + return -1; + } + if (c->rx_len - consumed < msg_size) { + break; + } + dispatch_event(c, obj_id, opcode, c->rx_buf + consumed + WL_MSG_HEADER_BYTES, + msg_size - WL_MSG_HEADER_BYTES); + consumed += msg_size; + } + if (consumed > 0U) { + size_t rem = c->rx_len - consumed; + if (rem > 0U) { + memmove(c->rx_buf, c->rx_buf + consumed, rem); + } + c->rx_len = rem; + } + } + return 0; +} + +static void resolve_socket_path(char* dst, size_t cap, const char* cli_socket) { + if (cli_socket != NULL && cli_socket[0] != '\0') { + snprintf(dst, cap, "%s", cli_socket); + return; + } + const char* xdg = getenv("XDG_RUNTIME_DIR"); + const char* disp = getenv("WAYLAND_DISPLAY"); + if (xdg == NULL || xdg[0] == '\0') { + xdg = "/tmp"; + } + if (disp == NULL || disp[0] == '\0') { + disp = "wayland-0"; + } + if (disp[0] == '/') { + snprintf(dst, cap, "%s", disp); + } else { + snprintf(dst, cap, "%s/%s", xdg, disp); + } +} + +int main(int argc, char** argv) { + const char* cli_socket = NULL; + uint32_t num_frames = 3U; + uint32_t wait_input_ms = 0U; + + for (int i = 1; i < argc; ++i) { + if (strcmp(argv[i], "--socket") == 0 && i + 1 < argc) { + cli_socket = argv[++i]; + } else if (strcmp(argv[i], "--frames") == 0 && i + 1 < argc) { + num_frames = (uint32_t)strtoul(argv[++i], NULL, 10); + if (num_frames == 0U) { + num_frames = 1U; + } + } else if (strcmp(argv[i], "--wait-input-ms") == 0 && i + 1 < argc) { + wait_input_ms = (uint32_t)strtoul(argv[++i], NULL, 10); + } + } + + char socket_path[108]; + resolve_socket_path(socket_path, sizeof(socket_path), cli_socket); + + int sock_fd = -1; + struct sockaddr_un addr; + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path); + + for (int attempt = 0; attempt < 50; ++attempt) { + sock_fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (sock_fd < 0) { + perror("socket"); + return 1; + } + if (connect(sock_fd, (const struct sockaddr*)&addr, sizeof(addr)) == 0) { + break; + } + close(sock_fd); + sock_fd = -1; + usleep(40000); + } + if (sock_fd < 0) { + fprintf(stderr, "[wl_client] Failed to connect to %s\n", socket_path); + return 1; + } + + int fl = fcntl(sock_fd, F_GETFL, 0); + if (fl >= 0) { + (void)fcntl(sock_fd, F_SETFL, fl | O_NONBLOCK); + } + + struct client_ctx ctx; + memset(&ctx, 0, sizeof(ctx)); + ctx.sock_fd = sock_fd; + ctx.epoll_fd = epoll_create1(EPOLL_CLOEXEC); + if (ctx.epoll_fd < 0) { + perror("epoll_create1"); + close(sock_fd); + return 1; + } + struct epoll_event ev; + memset(&ev, 0, sizeof(ev)); + ev.events = EPOLLIN; + ev.data.fd = sock_fd; + if (epoll_ctl(ctx.epoll_fd, EPOLL_CTL_ADD, sock_fd, &ev) != 0) { + perror("epoll_ctl"); + close(ctx.epoll_fd); + close(sock_fd); + return 1; + } + + /* 1. Request global registry + initial sync */ + struct wl_writer w; + wl_w_begin(&w, WL_DISPLAY_ID, WL_DISPLAY_GET_REGISTRY); + wl_w_u32(&w, ID_REGISTRY); + if (wl_send_msg(sock_fd, &w, -1) != 0) { + fprintf(stderr, "[wl_client] Failed to send get_registry\n"); + return 1; + } + wl_w_begin(&w, WL_DISPLAY_ID, WL_DISPLAY_SYNC); + wl_w_u32(&w, ID_SYNC_INIT); + if (wl_send_msg(sock_fd, &w, -1) != 0) { + fprintf(stderr, "[wl_client] Failed to send sync\n"); + return 1; + } + + for (int i = 0; i < 40 && !ctx.sync_init_done && !ctx.protocol_error; ++i) { + if (pump_events(&ctx, 50) != 0) { + fprintf(stderr, "[wl_client] Disconnected during registry sync\n"); + return 1; + } + } + if (!ctx.sync_init_done || ctx.global_compositor == 0U || ctx.global_shm == 0U) { + fprintf(stderr, "[wl_client] Missing required globals (comp=%u shm=%u)\n", + ctx.global_compositor, ctx.global_shm); + return 1; + } + + /* 2. Bind wl_compositor, wl_shm, wl_seat */ + wl_w_begin(&w, ID_REGISTRY, WL_REGISTRY_BIND); + wl_w_u32(&w, ctx.global_compositor); + wl_w_str(&w, "wl_compositor"); + wl_w_u32(&w, 4U); + wl_w_u32(&w, ID_COMPOSITOR); + (void)wl_send_msg(sock_fd, &w, -1); + + wl_w_begin(&w, ID_REGISTRY, WL_REGISTRY_BIND); + wl_w_u32(&w, ctx.global_shm); + wl_w_str(&w, "wl_shm"); + wl_w_u32(&w, 1U); + wl_w_u32(&w, ID_SHM); + (void)wl_send_msg(sock_fd, &w, -1); + + if (ctx.global_seat != 0U) { + wl_w_begin(&w, ID_REGISTRY, WL_REGISTRY_BIND); + wl_w_u32(&w, ctx.global_seat); + wl_w_str(&w, "wl_seat"); + wl_w_u32(&w, 5U); + wl_w_u32(&w, ID_SEAT); + (void)wl_send_msg(sock_fd, &w, -1); + + wl_w_begin(&w, ID_SEAT, WL_SEAT_GET_POINTER); + wl_w_u32(&w, ID_POINTER); + (void)wl_send_msg(sock_fd, &w, -1); + + wl_w_begin(&w, ID_SEAT, WL_SEAT_GET_KEYBOARD); + wl_w_u32(&w, ID_KEYBOARD); + (void)wl_send_msg(sock_fd, &w, -1); + } + + wl_w_begin(&w, WL_DISPLAY_ID, WL_DISPLAY_SYNC); + wl_w_u32(&w, ID_SYNC_BIND); + (void)wl_send_msg(sock_fd, &w, -1); + + for (int i = 0; i < 40 && !ctx.sync_bind_done && !ctx.protocol_error; ++i) { + if (pump_events(&ctx, 50) != 0) { + fprintf(stderr, "[wl_client] Disconnected during bind sync\n"); + return 1; + } + } + if (!ctx.sync_bind_done || !ctx.has_argb8888) { + fprintf(stderr, "[wl_client] Compositor did not advertise ARGB8888 format\n"); + return 1; + } + + /* 3. Create wl_shm backing memfd + MAP_SHARED + transfer FD via SCM_RIGHTS */ + int shm_fd = (int)syscall(SYS_memfd_create, "milo_wl_shm", MFD_CLOEXEC); + if (shm_fd < 0) { + perror("memfd_create"); + return 1; + } + if (ftruncate(shm_fd, BUF_SIZE) != 0) { + perror("ftruncate"); + close(shm_fd); + return 1; + } + void* shm_map = mmap(NULL, BUF_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); + if (shm_map == MAP_FAILED) { + perror("mmap memfd"); + close(shm_fd); + return 1; + } + + wl_w_begin(&w, ID_COMPOSITOR, WL_COMPOSITOR_CREATE_SURFACE); + wl_w_u32(&w, ID_SURFACE); + (void)wl_send_msg(sock_fd, &w, -1); + + wl_w_begin(&w, ID_SHM, WL_SHM_CREATE_POOL); + wl_w_u32(&w, ID_SHM_POOL); + wl_w_i32(&w, BUF_SIZE); + if (wl_send_msg(sock_fd, &w, shm_fd) != 0) { + fprintf(stderr, "[wl_client] Failed to pass memfd via SCM_RIGHTS\n"); + munmap(shm_map, BUF_SIZE); + close(shm_fd); + return 1; + } + /* Close local FD immediately after SCM_RIGHTS transfer; MAP_SHARED remains valid */ + close(shm_fd); + + wl_w_begin(&w, ID_SHM_POOL, WL_SHM_POOL_CREATE_BUFFER); + wl_w_u32(&w, ID_BUFFER); + wl_w_i32(&w, 0); + wl_w_i32(&w, BUF_WIDTH); + wl_w_i32(&w, BUF_HEIGHT); + wl_w_i32(&w, BUF_STRIDE); + wl_w_u32(&w, WL_SHM_FORMAT_ARGB8888); + (void)wl_send_msg(sock_fd, &w, -1); + + /* 4. Start threaded renderer using pthread (CLONE_THREAD) + futex */ + struct render_worker_state worker; + memset(&worker, 0, sizeof(worker)); + worker.pixels = (uint32_t*)shm_map; + worker.width = BUF_WIDTH; + worker.height = BUF_HEIGHT; + + pthread_t render_tid; + if (pthread_create(&render_tid, NULL, render_worker_main, &worker) != 0) { + fprintf(stderr, "[wl_client] pthread_create failed\n"); + munmap(shm_map, BUF_SIZE); + return 1; + } + + /* 5. Render & commit frames synchronized with wl_surface.frame callbacks */ + for (uint32_t f = 0U; f < num_frames; ++f) { + uint32_t seq = f + 1U; + __atomic_store_n(&worker.frame_index, f, __ATOMIC_RELEASE); + __atomic_store_n(&worker.req_seq, seq, __ATOMIC_RELEASE); + (void)futex_wake_u32(&worker.req_seq, 1U); + + while (__atomic_load_n(&worker.done_seq, __ATOMIC_ACQUIRE) < seq) { + (void)futex_wait_u32(&worker.done_seq, seq - 1U); + } + + uint32_t cb_id = ID_FRAME_CB_BASE + f; + wl_w_begin(&w, ID_SURFACE, WL_SURFACE_ATTACH); + wl_w_u32(&w, ID_BUFFER); + wl_w_i32(&w, 0); + wl_w_i32(&w, 0); + (void)wl_send_msg(sock_fd, &w, -1); + + wl_w_begin(&w, ID_SURFACE, WL_SURFACE_DAMAGE); + wl_w_i32(&w, 0); + wl_w_i32(&w, 0); + wl_w_i32(&w, BUF_WIDTH); + wl_w_i32(&w, BUF_HEIGHT); + (void)wl_send_msg(sock_fd, &w, -1); + + wl_w_begin(&w, ID_SURFACE, WL_SURFACE_FRAME); + wl_w_u32(&w, cb_id); + (void)wl_send_msg(sock_fd, &w, -1); + + wl_w_begin(&w, ID_SURFACE, WL_SURFACE_COMMIT); + (void)wl_send_msg(sock_fd, &w, -1); + + for (int tries = 0; tries < 60 && ctx.last_frame_cb_done != cb_id && !ctx.protocol_error; + ++tries) { + if (pump_events(&ctx, 50) != 0) { + fprintf(stderr, "[wl_client] Disconnected awaiting frame %u callback\n", f); + break; + } + } + if (ctx.last_frame_cb_done != cb_id) { + fprintf(stderr, "[wl_client] Timed out waiting for frame %u callback\n", f); + __atomic_store_n(&worker.stop, 1U, __ATOMIC_RELEASE); + (void)futex_wake_u32(&worker.req_seq, 1U); + pthread_join(render_tid, NULL); + munmap(shm_map, BUF_SIZE); + return 1; + } + } + + /* Optional wait window for evdev pointer/keyboard events */ + if (wait_input_ms > 0U) { + uint32_t steps = (wait_input_ms + 49U) / 50U; + for (uint32_t s = 0U; s < steps; ++s) { + if (pump_events(&ctx, 50) != 0) { + break; + } + } + } + + __atomic_store_n(&worker.stop, 1U, __ATOMIC_RELEASE); + (void)futex_wake_u32(&worker.req_seq, 1U); + pthread_join(render_tid, NULL); + + /* Cleanly destroy Wayland resources */ + wl_w_begin(&w, ID_BUFFER, WL_BUFFER_DESTROY); + (void)wl_send_msg(sock_fd, &w, -1); + wl_w_begin(&w, ID_SHM_POOL, WL_SHM_POOL_DESTROY); + (void)wl_send_msg(sock_fd, &w, -1); + wl_w_begin(&w, ID_SURFACE, WL_SURFACE_DESTROY); + (void)wl_send_msg(sock_fd, &w, -1); + + munmap(shm_map, BUF_SIZE); + close(ctx.epoll_fd); + close(sock_fd); + + printf("[wl_client] Completed %u frame(s) (releases=%u worker_tid=%ld ptr_ev=%u key_ev=%u)\n", + num_frames, ctx.buffer_releases, worker.worker_tid, ctx.pointer_events, + ctx.keyboard_events); + fflush(stdout); + return (ctx.buffer_releases >= num_frames && worker.worker_tid > 0 && !ctx.protocol_error) ? 0 + : 1; +} diff --git a/user/wl_compositor.c b/user/wl_compositor.c new file mode 100644 index 0000000..c650f11 --- /dev/null +++ b/user/wl_compositor.c @@ -0,0 +1,1111 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#define _GNU_SOURCE +#include "wl_proto.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MAX_CLIENTS 4 +#define MAX_POOLS 8 +#define MAX_BUFFERS 16 +#define MAX_SURFACES 8 +#define MAX_EVDEV 2 +#define CLIENT_RX_CAP 4096 +#define CLIENT_FD_CAP 16 + +enum ep_tag { + EP_LISTEN = 1, + EP_EVENTFD = 2, + EP_TIMERFD = 3, + EP_EVDEV0 = 4, + EP_EVDEV1 = 5, + EP_CLIENT_BASE = 16, +}; + +struct shm_pool { + int in_use; + uint32_t id; + int fd; + size_t size; + uint8_t* map; +}; + +struct shm_buffer { + int in_use; + uint32_t id; + uint32_t pool_id; + int32_t offset; + int32_t width; + int32_t height; + int32_t stride; + uint32_t format; +}; + +struct wl_surface_state { + int in_use; + uint32_t id; + uint32_t pending_buffer_id; + int has_pending_buffer; + uint32_t active_buffer_id; + uint32_t frame_cb_id; +}; + +struct wl_client { + int active; + int fd; + uint8_t rx_buf[CLIENT_RX_CAP]; + size_t rx_len; + int rx_fds[CLIENT_FD_CAP]; + size_t rx_fd_count; + + uint32_t registry_id; + uint32_t compositor_id; + uint32_t shm_id; + uint32_t seat_id; + uint32_t pointer_id; + uint32_t keyboard_id; + int pointer_entered; + int keyboard_entered; + + struct shm_pool pools[MAX_POOLS]; + struct shm_buffer buffers[MAX_BUFFERS]; + struct wl_surface_state surfaces[MAX_SURFACES]; +}; + +struct fb_backend { + int fd; + uint8_t* map; + uint32_t width; + uint32_t height; + uint32_t stride; + uint32_t smem_len; + int active; +}; + +struct compositor { + int epoll_fd; + int listen_fd; + int wake_efd; + int timer_fd; + int evdev_fds[MAX_EVDEV]; + struct fb_backend fb; + struct wl_client clients[MAX_CLIENTS]; + + char socket_path[108]; + uint32_t serial; + uint32_t frames_committed; + uint32_t input_events_forwarded; + uint32_t timer_ticks; + uint32_t max_frames; + int shutdown_requested; + + int32_t cursor_x; + int32_t cursor_y; + int cursor_visible; +}; + +static volatile sig_atomic_t g_sig_stop = 0; + +static void on_signal(int sig) { + (void)sig; + g_sig_stop = 1; +} + +static uint32_t now_msec(void) { + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) { + return 0U; + } + return (uint32_t)((uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L)); +} + +static void fb_fill_rect(struct fb_backend* fb, int32_t x, int32_t y, int32_t w, int32_t h, + uint32_t argb) { + if (!fb->active || fb->map == NULL) { + return; + } + if (x < 0) { + w += x; + x = 0; + } + if (y < 0) { + h += y; + y = 0; + } + if (w <= 0 || h <= 0) { + return; + } + if ((uint32_t)x >= fb->width || (uint32_t)y >= fb->height) { + return; + } + if ((uint32_t)(x + w) > fb->width) { + w = (int32_t)fb->width - x; + } + if ((uint32_t)(y + h) > fb->height) { + h = (int32_t)fb->height - y; + } + for (int32_t row = 0; row < h; ++row) { + uint32_t* dst = (uint32_t*)(fb->map + ((size_t)(y + row) * (size_t)fb->stride)); + for (int32_t col = 0; col < w; ++col) { + dst[x + col] = argb; + } + } +} + +static void fb_draw_backdrop(struct compositor* comp) { + if (!comp->fb.active) { + return; + } + /* Dark slate desktop backdrop with teal top bar */ + fb_fill_rect(&comp->fb, 0, 0, (int32_t)comp->fb.width, (int32_t)comp->fb.height, 0xFF18202CU); + fb_fill_rect(&comp->fb, 0, 0, (int32_t)comp->fb.width, 24, 0xFF1F3B4DU); + fb_fill_rect(&comp->fb, 0, 24, (int32_t)comp->fb.width, 2, 0xFF38BDF8U); +} + +static void fb_draw_cursor(struct compositor* comp) { + if (!comp->fb.active || !comp->cursor_visible) { + return; + } + int32_t cx = comp->cursor_x; + int32_t cy = comp->cursor_y; + fb_fill_rect(&comp->fb, cx - 6, cy - 1, 13, 3, 0xFFFFFFFFU); + fb_fill_rect(&comp->fb, cx - 1, cy - 6, 3, 13, 0xFFFFFFFFU); + fb_fill_rect(&comp->fb, cx - 1, cy - 1, 3, 3, 0xFFFF3B30U); +} + +static void fb_flush(struct compositor* comp) { + if (!comp->fb.active) { + return; + } + (void)ioctl(comp->fb.fd, MILO_FBIO_FLUSH, 0); +} + +static struct shm_pool* find_pool(struct wl_client* c, uint32_t id) { + for (int i = 0; i < MAX_POOLS; ++i) { + if (c->pools[i].in_use && c->pools[i].id == id) { + return &c->pools[i]; + } + } + return NULL; +} + +static struct shm_buffer* find_buffer(struct wl_client* c, uint32_t id) { + for (int i = 0; i < MAX_BUFFERS; ++i) { + if (c->buffers[i].in_use && c->buffers[i].id == id) { + return &c->buffers[i]; + } + } + return NULL; +} + +static struct wl_surface_state* find_surface(struct wl_client* c, uint32_t id) { + for (int i = 0; i < MAX_SURFACES; ++i) { + if (c->surfaces[i].in_use && c->surfaces[i].id == id) { + return &c->surfaces[i]; + } + } + return NULL; +} + +static void composite_all(struct compositor* comp) { + if (!comp->fb.active) { + return; + } + fb_draw_backdrop(comp); + + for (int ci = 0; ci < MAX_CLIENTS; ++ci) { + struct wl_client* c = &comp->clients[ci]; + if (!c->active) { + continue; + } + for (int si = 0; si < MAX_SURFACES; ++si) { + struct wl_surface_state* surf = &c->surfaces[si]; + if (!surf->in_use || surf->active_buffer_id == 0U) { + continue; + } + struct shm_buffer* buf = find_buffer(c, surf->active_buffer_id); + if (buf == NULL) { + continue; + } + struct shm_pool* pool = find_pool(c, buf->pool_id); + if (pool == NULL || pool->map == NULL) { + continue; + } + if (buf->width <= 0 || buf->height <= 0 || buf->stride < buf->width * 4) { + continue; + } + size_t needed = (size_t)buf->offset + ((size_t)buf->height * (size_t)buf->stride); + if (buf->offset < 0 || needed > pool->size) { + continue; + } + + /* Center client window on /dev/fb0 with a clean frame + titlebar */ + int32_t ox = ((int32_t)comp->fb.width - buf->width) / 2; + int32_t oy = ((int32_t)comp->fb.height - buf->height) / 2; + if (ox < 8) { + ox = 8; + } + if (oy < 36) { + oy = 36; + } + + fb_fill_rect(&comp->fb, ox - 2, oy - 22, buf->width + 4, buf->height + 24, 0xFF38BDF8U); + fb_fill_rect(&comp->fb, ox, oy - 20, buf->width, 20, 0xFF0F172AU); + fb_fill_rect(&comp->fb, ox + 8, oy - 14, 8, 8, 0xFFEF4444U); + fb_fill_rect(&comp->fb, ox + 22, oy - 14, 8, 8, 0xFFF59E0BU); + fb_fill_rect(&comp->fb, ox + 36, oy - 14, 8, 8, 0xFF22C55EU); + + const uint8_t* src_base = pool->map + (size_t)buf->offset; + for (int32_t y = 0; y < buf->height; ++y) { + int32_t dy = oy + y; + if (dy < 0 || (uint32_t)dy >= comp->fb.height) { + continue; + } + const uint32_t* src_row = + (const uint32_t*)(src_base + ((size_t)y * (size_t)buf->stride)); + uint32_t* dst_row = + (uint32_t*)(comp->fb.map + ((size_t)dy * (size_t)comp->fb.stride)); + for (int32_t x = 0; x < buf->width; ++x) { + int32_t dx = ox + x; + if (dx < 0 || (uint32_t)dx >= comp->fb.width) { + continue; + } + dst_row[dx] = src_row[x]; + } + } + } + } + + fb_draw_cursor(comp); + fb_flush(comp); +} + +static int client_pop_fd(struct wl_client* c) { + if (c->rx_fd_count == 0U) { + return -1; + } + int fd = c->rx_fds[0]; + if (c->rx_fd_count > 1U) { + memmove(&c->rx_fds[0], &c->rx_fds[1], (c->rx_fd_count - 1U) * sizeof(int)); + } + c->rx_fd_count--; + return fd; +} + +static void client_destroy(struct compositor* comp, int idx) { + struct wl_client* c = &comp->clients[idx]; + if (!c->active) { + return; + } + for (int i = 0; i < MAX_POOLS; ++i) { + if (c->pools[i].in_use) { + if (c->pools[i].map != NULL) { + munmap(c->pools[i].map, c->pools[i].size); + } + if (c->pools[i].fd >= 0) { + close(c->pools[i].fd); + } + } + } + for (size_t i = 0U; i < c->rx_fd_count; ++i) { + if (c->rx_fds[i] >= 0) { + close(c->rx_fds[i]); + } + } + if (c->fd >= 0) { + (void)epoll_ctl(comp->epoll_fd, EPOLL_CTL_DEL, c->fd, NULL); + close(c->fd); + } + memset(c, 0, sizeof(*c)); + c->fd = -1; +} + +static void send_callback_done(struct wl_client* c, uint32_t cb_id, uint32_t data) { + struct wl_writer w; + wl_w_begin(&w, cb_id, WL_CALLBACK_EVENT_DONE); + wl_w_u32(&w, data); + (void)wl_send_msg(c->fd, &w, -1); + + wl_w_begin(&w, WL_DISPLAY_ID, WL_DISPLAY_EVENT_DELETE_ID); + wl_w_u32(&w, cb_id); + (void)wl_send_msg(c->fd, &w, -1); +} + +static void send_global(struct wl_client* c, uint32_t reg_id, uint32_t name, const char* iface, + uint32_t ver) { + struct wl_writer w; + wl_w_begin(&w, reg_id, WL_REGISTRY_EVENT_GLOBAL); + wl_w_u32(&w, name); + wl_w_str(&w, iface); + wl_w_u32(&w, ver); + (void)wl_send_msg(c->fd, &w, -1); +} + +static void handle_client_message(struct compositor* comp, struct wl_client* c, uint32_t obj_id, + uint16_t opcode, const uint8_t* payload, uint32_t payload_len) { + struct wl_reader r; + wl_r_init(&r, payload, payload_len); + + if (obj_id == WL_DISPLAY_ID) { + if (opcode == WL_DISPLAY_SYNC) { + uint32_t cb_id = 0U; + if (wl_r_u32(&r, &cb_id) == 0) { + send_callback_done(c, cb_id, ++comp->serial); + } + } else if (opcode == WL_DISPLAY_GET_REGISTRY) { + uint32_t reg_id = 0U; + if (wl_r_u32(&r, ®_id) == 0) { + c->registry_id = reg_id; + send_global(c, reg_id, WL_GLOBAL_COMPOSITOR, "wl_compositor", 4U); + send_global(c, reg_id, WL_GLOBAL_SHM, "wl_shm", 1U); + send_global(c, reg_id, WL_GLOBAL_SEAT, "wl_seat", 5U); + } + } + return; + } + + if (obj_id == c->registry_id && c->registry_id != 0U) { + if (opcode == WL_REGISTRY_BIND) { + uint32_t name = 0U; + char iface[64]; + uint32_t ver = 0U; + uint32_t new_id = 0U; + if (wl_r_u32(&r, &name) == 0 && wl_r_str(&r, iface, sizeof(iface)) == 0 && + wl_r_u32(&r, &ver) == 0 && wl_r_u32(&r, &new_id) == 0) { + (void)ver; + if (name == WL_GLOBAL_COMPOSITOR || strcmp(iface, "wl_compositor") == 0) { + c->compositor_id = new_id; + } else if (name == WL_GLOBAL_SHM || strcmp(iface, "wl_shm") == 0) { + c->shm_id = new_id; + struct wl_writer w; + wl_w_begin(&w, new_id, WL_SHM_EVENT_FORMAT); + wl_w_u32(&w, WL_SHM_FORMAT_ARGB8888); + (void)wl_send_msg(c->fd, &w, -1); + + wl_w_begin(&w, new_id, WL_SHM_EVENT_FORMAT); + wl_w_u32(&w, WL_SHM_FORMAT_XRGB8888); + (void)wl_send_msg(c->fd, &w, -1); + } else if (name == WL_GLOBAL_SEAT || strcmp(iface, "wl_seat") == 0) { + c->seat_id = new_id; + struct wl_writer w; + wl_w_begin(&w, new_id, WL_SEAT_EVENT_CAPABILITIES); + wl_w_u32(&w, WL_SEAT_CAP_POINTER | WL_SEAT_CAP_KEYBOARD); + (void)wl_send_msg(c->fd, &w, -1); + + wl_w_begin(&w, new_id, WL_SEAT_EVENT_NAME); + wl_w_str(&w, "seat0"); + (void)wl_send_msg(c->fd, &w, -1); + } + } + } + return; + } + + if (obj_id == c->compositor_id && c->compositor_id != 0U) { + if (opcode == WL_COMPOSITOR_CREATE_SURFACE) { + uint32_t surf_id = 0U; + if (wl_r_u32(&r, &surf_id) == 0) { + for (int i = 0; i < MAX_SURFACES; ++i) { + if (!c->surfaces[i].in_use) { + memset(&c->surfaces[i], 0, sizeof(c->surfaces[i])); + c->surfaces[i].in_use = 1; + c->surfaces[i].id = surf_id; + break; + } + } + } + } + return; + } + + if (obj_id == c->shm_id && c->shm_id != 0U) { + if (opcode == WL_SHM_CREATE_POOL) { + uint32_t pool_id = 0U; + int32_t size = 0; + int pool_fd = client_pop_fd(c); + if (wl_r_u32(&r, &pool_id) == 0 && wl_r_i32(&r, &size) == 0 && pool_fd >= 0 && + size > 0) { + void* mapped = mmap(NULL, (size_t)size, PROT_READ, MAP_SHARED, pool_fd, 0); + if (mapped != MAP_FAILED) { + int stored = 0; + for (int i = 0; i < MAX_POOLS; ++i) { + if (!c->pools[i].in_use) { + c->pools[i].in_use = 1; + c->pools[i].id = pool_id; + c->pools[i].fd = pool_fd; + c->pools[i].size = (size_t)size; + c->pools[i].map = (uint8_t*)mapped; + stored = 1; + break; + } + } + if (!stored) { + munmap(mapped, (size_t)size); + close(pool_fd); + } else { + printf("[wl_compositor] Mapped wl_shm_pool id=%u size=%d via SCM_RIGHTS " + "fd=%d\n", + pool_id, size, pool_fd); + fflush(stdout); + } + } else { + fprintf(stderr, "[wl_compositor] mmap wl_shm_pool failed: %s\n", + strerror(errno)); + close(pool_fd); + } + } else if (pool_fd >= 0) { + close(pool_fd); + } + } + return; + } + + if (obj_id == c->seat_id && c->seat_id != 0U) { + uint32_t new_id = 0U; + if (opcode == WL_SEAT_GET_POINTER && wl_r_u32(&r, &new_id) == 0) { + c->pointer_id = new_id; + c->pointer_entered = 0; + } else if (opcode == WL_SEAT_GET_KEYBOARD && wl_r_u32(&r, &new_id) == 0) { + c->keyboard_id = new_id; + c->keyboard_entered = 0; + } + return; + } + + struct shm_pool* pool = find_pool(c, obj_id); + if (pool != NULL) { + if (opcode == WL_SHM_POOL_CREATE_BUFFER) { + uint32_t buf_id = 0U; + int32_t offset = 0, width = 0, height = 0, stride = 0; + uint32_t format = 0U; + if (wl_r_u32(&r, &buf_id) == 0 && wl_r_i32(&r, &offset) == 0 && + wl_r_i32(&r, &width) == 0 && wl_r_i32(&r, &height) == 0 && + wl_r_i32(&r, &stride) == 0 && wl_r_u32(&r, &format) == 0) { + for (int i = 0; i < MAX_BUFFERS; ++i) { + if (!c->buffers[i].in_use) { + c->buffers[i].in_use = 1; + c->buffers[i].id = buf_id; + c->buffers[i].pool_id = pool->id; + c->buffers[i].offset = offset; + c->buffers[i].width = width; + c->buffers[i].height = height; + c->buffers[i].stride = stride; + c->buffers[i].format = format; + break; + } + } + } + } else if (opcode == WL_SHM_POOL_DESTROY) { + if (pool->map != NULL) { + munmap(pool->map, pool->size); + } + if (pool->fd >= 0) { + close(pool->fd); + } + memset(pool, 0, sizeof(*pool)); + pool->fd = -1; + } + return; + } + + struct shm_buffer* buf = find_buffer(c, obj_id); + if (buf != NULL) { + if (opcode == WL_BUFFER_DESTROY) { + memset(buf, 0, sizeof(*buf)); + } + return; + } + + struct wl_surface_state* surf = find_surface(c, obj_id); + if (surf != NULL) { + if (opcode == WL_SURFACE_ATTACH) { + uint32_t buf_id = 0U; + int32_t x = 0, y = 0; + if (wl_r_u32(&r, &buf_id) == 0 && wl_r_i32(&r, &x) == 0 && wl_r_i32(&r, &y) == 0) { + surf->pending_buffer_id = buf_id; + surf->has_pending_buffer = 1; + } + } else if (opcode == WL_SURFACE_DAMAGE) { + /* Full surface composite on commit */ + } else if (opcode == WL_SURFACE_FRAME) { + uint32_t cb_id = 0U; + if (wl_r_u32(&r, &cb_id) == 0) { + surf->frame_cb_id = cb_id; + } + } else if (opcode == WL_SURFACE_COMMIT) { + if (surf->has_pending_buffer) { + surf->active_buffer_id = surf->pending_buffer_id; + surf->has_pending_buffer = 0; + } + composite_all(comp); + comp->frames_committed++; + + /* Ensure pointer/keyboard enter sent once a surface is live */ + if (c->pointer_id != 0U && !c->pointer_entered) { + struct wl_writer w; + wl_w_begin(&w, c->pointer_id, WL_POINTER_EVENT_ENTER); + wl_w_u32(&w, ++comp->serial); + wl_w_u32(&w, surf->id); + wl_w_u32(&w, wl_fixed_from_int(comp->cursor_x)); + wl_w_u32(&w, wl_fixed_from_int(comp->cursor_y)); + (void)wl_send_msg(c->fd, &w, -1); + c->pointer_entered = 1; + } + if (c->keyboard_id != 0U && !c->keyboard_entered) { + struct wl_writer w; + wl_w_begin(&w, c->keyboard_id, WL_KEYBOARD_EVENT_ENTER); + wl_w_u32(&w, ++comp->serial); + wl_w_u32(&w, surf->id); + wl_w_u32(&w, 0U); /* empty keys wl_array */ + (void)wl_send_msg(c->fd, &w, -1); + c->keyboard_entered = 1; + } + + if (surf->active_buffer_id != 0U) { + struct wl_writer w; + wl_w_begin(&w, surf->active_buffer_id, WL_BUFFER_EVENT_RELEASE); + (void)wl_send_msg(c->fd, &w, -1); + } + if (surf->frame_cb_id != 0U) { + uint32_t cb_id = surf->frame_cb_id; + surf->frame_cb_id = 0U; + send_callback_done(c, cb_id, now_msec()); + } + printf("[wl_compositor] Committed frame #%u (surface=%u buffer=%u)\n", + comp->frames_committed, surf->id, surf->active_buffer_id); + fflush(stdout); + } else if (opcode == WL_SURFACE_DESTROY) { + memset(surf, 0, sizeof(*surf)); + } + } +} + +static void handle_client_readable(struct compositor* comp, int idx) { + struct wl_client* c = &comp->clients[idx]; + if (!c->active) { + return; + } + + for (;;) { + if (c->rx_len >= sizeof(c->rx_buf)) { + client_destroy(comp, idx); + return; + } + int new_fds[8]; + size_t nfd = 0U; + ssize_t n = wl_recv_chunk(c->fd, c->rx_buf + c->rx_len, sizeof(c->rx_buf) - c->rx_len, + new_fds, 8U, &nfd); + if (n < 0) { + if (errno == EINTR) { + continue; + } + if (errno == EAGAIN || errno == EWOULDBLOCK) { + break; + } + client_destroy(comp, idx); + return; + } + if (n == 0) { + client_destroy(comp, idx); + return; + } + + c->rx_len += (size_t)n; + for (size_t i = 0U; i < nfd; ++i) { + if (c->rx_fd_count < CLIENT_FD_CAP) { + c->rx_fds[c->rx_fd_count++] = new_fds[i]; + } else if (new_fds[i] >= 0) { + close(new_fds[i]); + } + } + + size_t consumed = 0U; + while (c->rx_len - consumed >= WL_MSG_HEADER_BYTES) { + uint32_t obj_id = 0U; + uint32_t word1 = 0U; + memcpy(&obj_id, c->rx_buf + consumed, 4); + memcpy(&word1, c->rx_buf + consumed + 4, 4); + uint16_t opcode = (uint16_t)(word1 & 0xFFFFU); + uint32_t msg_size = (word1 >> 16U) & 0xFFFFU; + if (msg_size < WL_MSG_HEADER_BYTES || msg_size > WL_MAX_MSG_BYTES) { + client_destroy(comp, idx); + return; + } + if (c->rx_len - consumed < msg_size) { + break; + } + handle_client_message(comp, c, obj_id, opcode, + c->rx_buf + consumed + WL_MSG_HEADER_BYTES, + msg_size - WL_MSG_HEADER_BYTES); + consumed += msg_size; + } + if (consumed > 0U) { + size_t rem = c->rx_len - consumed; + if (rem > 0U) { + memmove(c->rx_buf, c->rx_buf + consumed, rem); + } + c->rx_len = rem; + } + } +} + +static void handle_evdev_readable(struct compositor* comp, int ev_idx) { + int fd = comp->evdev_fds[ev_idx]; + if (fd < 0) { + return; + } + + struct input_event evs[16]; + int cursor_moved = 0; + for (;;) { + ssize_t n = read(fd, evs, sizeof(evs)); + if (n <= 0) { + break; + } + size_t count = (size_t)n / sizeof(struct input_event); + for (size_t i = 0U; i < count; ++i) { + uint16_t type = evs[i].type; + uint16_t code = evs[i].code; + int32_t val = evs[i].value; + + if (type == EV_ABS) { + int32_t max_w = comp->fb.active ? (int32_t)comp->fb.width : 1280; + int32_t max_h = comp->fb.active ? (int32_t)comp->fb.height : 800; + if (code == ABS_X) { + comp->cursor_x = (int32_t)(((int64_t)val * (int64_t)max_w) / 32768LL); + comp->cursor_visible = 1; + cursor_moved = 1; + } else if (code == ABS_Y) { + comp->cursor_y = (int32_t)(((int64_t)val * (int64_t)max_h) / 32768LL); + comp->cursor_visible = 1; + cursor_moved = 1; + } + } else if (type == EV_REL) { + if (code == REL_X) { + comp->cursor_x += val; + comp->cursor_visible = 1; + cursor_moved = 1; + } else if (code == REL_Y) { + comp->cursor_y += val; + comp->cursor_visible = 1; + cursor_moved = 1; + } + } else if (type == EV_KEY) { + if (code == KEY_ESC && val != 0) { + uint64_t one = 1ULL; + comp->shutdown_requested = 1; + (void)write(comp->wake_efd, &one, sizeof(one)); + } + int is_btn = (code >= BTN_MOUSE && code < BTN_JOYSTICK); + for (int ci = 0; ci < MAX_CLIENTS; ++ci) { + struct wl_client* c = &comp->clients[ci]; + if (!c->active) { + continue; + } + if (is_btn && c->pointer_id != 0U) { + struct wl_writer w; + wl_w_begin(&w, c->pointer_id, WL_POINTER_EVENT_BUTTON); + wl_w_u32(&w, ++comp->serial); + wl_w_u32(&w, now_msec()); + wl_w_u32(&w, (uint32_t)code); + wl_w_u32(&w, (val != 0) ? 1U : 0U); + (void)wl_send_msg(c->fd, &w, -1); + + wl_w_begin(&w, c->pointer_id, WL_POINTER_EVENT_FRAME); + (void)wl_send_msg(c->fd, &w, -1); + comp->input_events_forwarded++; + } else if (!is_btn && c->keyboard_id != 0U) { + struct wl_writer w; + wl_w_begin(&w, c->keyboard_id, WL_KEYBOARD_EVENT_KEY); + wl_w_u32(&w, ++comp->serial); + wl_w_u32(&w, now_msec()); + wl_w_u32(&w, (uint32_t)code); + wl_w_u32(&w, (val != 0) ? 1U : 0U); + (void)wl_send_msg(c->fd, &w, -1); + comp->input_events_forwarded++; + } + } + } + } + } + + if (cursor_moved) { + if (comp->cursor_x < 0) { + comp->cursor_x = 0; + } + if (comp->cursor_y < 0) { + comp->cursor_y = 0; + } + if (comp->fb.active) { + if (comp->cursor_x >= (int32_t)comp->fb.width) { + comp->cursor_x = (int32_t)comp->fb.width - 1; + } + if (comp->cursor_y >= (int32_t)comp->fb.height) { + comp->cursor_y = (int32_t)comp->fb.height - 1; + } + } + for (int ci = 0; ci < MAX_CLIENTS; ++ci) { + struct wl_client* c = &comp->clients[ci]; + if (!c->active || c->pointer_id == 0U) { + continue; + } + struct wl_writer w; + wl_w_begin(&w, c->pointer_id, WL_POINTER_EVENT_MOTION); + wl_w_u32(&w, now_msec()); + wl_w_u32(&w, wl_fixed_from_int(comp->cursor_x)); + wl_w_u32(&w, wl_fixed_from_int(comp->cursor_y)); + (void)wl_send_msg(c->fd, &w, -1); + + wl_w_begin(&w, c->pointer_id, WL_POINTER_EVENT_FRAME); + (void)wl_send_msg(c->fd, &w, -1); + comp->input_events_forwarded++; + } + composite_all(comp); + } +} + +static int any_active_clients(const struct compositor* comp) { + for (int i = 0; i < MAX_CLIENTS; ++i) { + if (comp->clients[i].active) { + return 1; + } + } + return 0; +} + +static int init_fb(struct compositor* comp, int no_fb) { + comp->fb.fd = -1; + comp->fb.active = 0; + if (no_fb) { + return 0; + } + + int fd = open("/dev/fb0", O_RDWR | O_CLOEXEC); + if (fd < 0) { + fprintf(stderr, "[wl_compositor] /dev/fb0 unavailable (%s); continuing headless\n", + strerror(errno)); + return 0; + } + + struct milo_fb_var_screeninfo vinfo; + struct milo_fb_fix_screeninfo finfo; + memset(&vinfo, 0, sizeof(vinfo)); + memset(&finfo, 0, sizeof(finfo)); + if (ioctl(fd, MILO_FBIOGET_VSCREENINFO, &vinfo) != 0 || + ioctl(fd, MILO_FBIOGET_FSCREENINFO, &finfo) != 0 || vinfo.xres == 0U || vinfo.yres == 0U || + finfo.smem_len == 0U) { + close(fd); + return -1; + } + + void* map = mmap(NULL, finfo.smem_len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (map == MAP_FAILED) { + close(fd); + return -1; + } + + comp->fb.fd = fd; + comp->fb.map = (uint8_t*)map; + comp->fb.width = vinfo.xres; + comp->fb.height = vinfo.yres; + comp->fb.stride = finfo.line_length; + comp->fb.smem_len = finfo.smem_len; + comp->fb.active = 1; + comp->cursor_x = (int32_t)(vinfo.xres / 2U); + comp->cursor_y = (int32_t)(vinfo.yres / 2U); + comp->cursor_visible = 1; + + fb_draw_backdrop(comp); + fb_draw_cursor(comp); + fb_flush(comp); + printf("[wl_compositor] Initialized /dev/fb0 %ux%u (stride=%u)\n", vinfo.xres, vinfo.yres, + finfo.line_length); + fflush(stdout); + return 0; +} + +static void resolve_socket_path(char* dst, size_t cap, const char* cli_socket) { + if (cli_socket != NULL && cli_socket[0] != '\0') { + snprintf(dst, cap, "%s", cli_socket); + return; + } + const char* xdg = getenv("XDG_RUNTIME_DIR"); + const char* disp = getenv("WAYLAND_DISPLAY"); + if (xdg == NULL || xdg[0] == '\0') { + xdg = "/tmp"; + } + if (disp == NULL || disp[0] == '\0') { + disp = "wayland-0"; + } + if (disp[0] == '/') { + snprintf(dst, cap, "%s", disp); + } else { + snprintf(dst, cap, "%s/%s", xdg, disp); + } +} + +int main(int argc, char** argv) { + const char* cli_socket = NULL; + const char* ready_file = NULL; + uint32_t max_frames = 0U; + uint32_t timeout_ms = 0U; + int no_fb = 0; + + for (int i = 1; i < argc; ++i) { + if (strcmp(argv[i], "--socket") == 0 && i + 1 < argc) { + cli_socket = argv[++i]; + } else if (strcmp(argv[i], "--max-frames") == 0 && i + 1 < argc) { + max_frames = (uint32_t)strtoul(argv[++i], NULL, 10); + } else if (strcmp(argv[i], "--timeout-ms") == 0 && i + 1 < argc) { + timeout_ms = (uint32_t)strtoul(argv[++i], NULL, 10); + } else if (strcmp(argv[i], "--ready-file") == 0 && i + 1 < argc) { + ready_file = argv[++i]; + } else if (strcmp(argv[i], "--no-fb") == 0) { + no_fb = 1; + } + } + + signal(SIGINT, on_signal); + signal(SIGTERM, on_signal); + signal(SIGHUP, on_signal); + signal(SIGPIPE, SIG_IGN); + + struct compositor comp; + memset(&comp, 0, sizeof(comp)); + comp.epoll_fd = -1; + comp.listen_fd = -1; + comp.wake_efd = -1; + comp.timer_fd = -1; + comp.evdev_fds[0] = -1; + comp.evdev_fds[1] = -1; + comp.max_frames = max_frames; + for (int i = 0; i < MAX_CLIENTS; ++i) { + comp.clients[i].fd = -1; + } + + resolve_socket_path(comp.socket_path, sizeof(comp.socket_path), cli_socket); + if (init_fb(&comp, no_fb) != 0) { + fprintf(stderr, "[wl_compositor] Failed to initialize /dev/fb0\n"); + return 1; + } + + comp.epoll_fd = epoll_create1(EPOLL_CLOEXEC); + if (comp.epoll_fd < 0) { + perror("epoll_create1"); + return 1; + } + + comp.wake_efd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); + if (comp.wake_efd < 0) { + perror("eventfd"); + return 1; + } + struct epoll_event ev; + memset(&ev, 0, sizeof(ev)); + ev.events = EPOLLIN; + ev.data.u64 = EP_EVENTFD; + if (epoll_ctl(comp.epoll_fd, EPOLL_CTL_ADD, comp.wake_efd, &ev) != 0) { + perror("epoll_ctl eventfd"); + return 1; + } + + comp.timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); + if (comp.timer_fd < 0) { + perror("timerfd_create"); + return 1; + } + struct itimerspec its; + memset(&its, 0, sizeof(its)); + its.it_value.tv_nsec = 50000000L; /* 50 ms */ + its.it_interval.tv_nsec = 50000000L; /* 50 ms periodic heartbeat */ + if (timerfd_settime(comp.timer_fd, 0, &its, NULL) != 0) { + perror("timerfd_settime"); + return 1; + } + ev.events = EPOLLIN; + ev.data.u64 = EP_TIMERFD; + if (epoll_ctl(comp.epoll_fd, EPOLL_CTL_ADD, comp.timer_fd, &ev) != 0) { + perror("epoll_ctl timerfd"); + return 1; + } + + static const char* const evdev_paths[MAX_EVDEV] = { + "/dev/input/event0", + "/dev/input/event1", + }; + for (int i = 0; i < MAX_EVDEV; ++i) { + int efd = open(evdev_paths[i], O_RDONLY | O_NONBLOCK | O_CLOEXEC); + if (efd >= 0) { + comp.evdev_fds[i] = efd; + ev.events = EPOLLIN; + ev.data.u64 = (uint64_t)(EP_EVDEV0 + i); + (void)epoll_ctl(comp.epoll_fd, EPOLL_CTL_ADD, efd, &ev); + } + } + + (void)unlink(comp.socket_path); + comp.listen_fd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); + if (comp.listen_fd < 0) { + perror("socket AF_UNIX"); + return 1; + } + struct sockaddr_un addr; + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", comp.socket_path); + if (bind(comp.listen_fd, (const struct sockaddr*)&addr, sizeof(addr)) != 0) { + perror("bind"); + return 1; + } + if (listen(comp.listen_fd, 8) != 0) { + perror("listen"); + return 1; + } + ev.events = EPOLLIN; + ev.data.u64 = EP_LISTEN; + if (epoll_ctl(comp.epoll_fd, EPOLL_CTL_ADD, comp.listen_fd, &ev) != 0) { + perror("epoll_ctl listen"); + return 1; + } + + if (ready_file != NULL && ready_file[0] != '\0') { + int rfd = open(ready_file, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (rfd >= 0) { + (void)write(rfd, "ready\n", 6); + close(rfd); + } + } + + printf("[wl_compositor] Listening on %s (epoll + eventfd + timerfd + evdev)\n", + comp.socket_path); + fflush(stdout); + + uint32_t start_ms = now_msec(); + uint32_t done_ms = 0U; + struct epoll_event events[16]; + + while (!g_sig_stop && !comp.shutdown_requested) { + int n = epoll_pwait(comp.epoll_fd, events, 16, 100, NULL); + if (n < 0) { + if (errno == EINTR) { + continue; + } + perror("epoll_pwait"); + break; + } + + for (int i = 0; i < n; ++i) { + uint64_t tag = events[i].data.u64; + if (tag == EP_LISTEN) { + for (;;) { + int cfd = accept4(comp.listen_fd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC); + if (cfd < 0) { + break; + } + int slot = -1; + for (int ci = 0; ci < MAX_CLIENTS; ++ci) { + if (!comp.clients[ci].active) { + slot = ci; + break; + } + } + if (slot < 0) { + close(cfd); + continue; + } + memset(&comp.clients[slot], 0, sizeof(comp.clients[slot])); + comp.clients[slot].active = 1; + comp.clients[slot].fd = cfd; + struct epoll_event cev; + memset(&cev, 0, sizeof(cev)); + cev.events = EPOLLIN; + cev.data.u64 = (uint64_t)(EP_CLIENT_BASE + slot); + if (epoll_ctl(comp.epoll_fd, EPOLL_CTL_ADD, cfd, &cev) != 0) { + close(cfd); + comp.clients[slot].active = 0; + comp.clients[slot].fd = -1; + } + } + } else if (tag == EP_EVENTFD) { + uint64_t val = 0ULL; + (void)read(comp.wake_efd, &val, sizeof(val)); + } else if (tag == EP_TIMERFD) { + uint64_t exp = 0ULL; + if (read(comp.timer_fd, &exp, sizeof(exp)) == (ssize_t)sizeof(exp)) { + comp.timer_ticks += (uint32_t)exp; + } + } else if (tag == EP_EVDEV0) { + handle_evdev_readable(&comp, 0); + } else if (tag == EP_EVDEV1) { + handle_evdev_readable(&comp, 1); + } else if (tag >= EP_CLIENT_BASE && tag < EP_CLIENT_BASE + MAX_CLIENTS) { + handle_client_readable(&comp, (int)(tag - EP_CLIENT_BASE)); + } + } + + uint32_t cur_ms = now_msec(); + if (comp.max_frames > 0U && comp.frames_committed >= comp.max_frames) { + if (done_ms == 0U) { + done_ms = cur_ms; + } + if (!any_active_clients(&comp) || (cur_ms - done_ms) >= 500U) { + break; + } + } + if (timeout_ms > 0U && (cur_ms - start_ms) >= timeout_ms) { + break; + } + } + + printf("[wl_compositor] Shutting down (frames=%u input_events=%u timer_ticks=%u)\n", + comp.frames_committed, comp.input_events_forwarded, comp.timer_ticks); + fflush(stdout); + + for (int i = 0; i < MAX_CLIENTS; ++i) { + client_destroy(&comp, i); + } + for (int i = 0; i < MAX_EVDEV; ++i) { + if (comp.evdev_fds[i] >= 0) { + close(comp.evdev_fds[i]); + } + } + if (comp.listen_fd >= 0) { + close(comp.listen_fd); + } + if (comp.timer_fd >= 0) { + close(comp.timer_fd); + } + if (comp.wake_efd >= 0) { + close(comp.wake_efd); + } + if (comp.epoll_fd >= 0) { + close(comp.epoll_fd); + } + if (comp.fb.active) { + munmap(comp.fb.map, comp.fb.smem_len); + close(comp.fb.fd); + } + (void)unlink(comp.socket_path); + if (ready_file != NULL && ready_file[0] != '\0') { + (void)unlink(ready_file); + } + return 0; +} diff --git a/user/wl_proto.h b/user/wl_proto.h new file mode 100644 index 0000000..dabaf7a --- /dev/null +++ b/user/wl_proto.h @@ -0,0 +1,371 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#ifndef MILO_USER_WL_PROTO_H +#define MILO_USER_WL_PROTO_H + +#include +#include +#include +#include +#include +#include + +/* ------------------------------------------------------------------------- + * Minimal Wayland Wire Protocol Constants & Helpers (LP64 Little-Endian) + * Wire header: [uint32_t object_id][uint32_t (size_bytes << 16) | opcode] + * ------------------------------------------------------------------------- */ + +#define WL_DISPLAY_ID 1U + +/* wl_display requests / events */ +#define WL_DISPLAY_SYNC 0U +#define WL_DISPLAY_GET_REGISTRY 1U +#define WL_DISPLAY_EVENT_ERROR 0U +#define WL_DISPLAY_EVENT_DELETE_ID 1U + +/* wl_registry requests / events */ +#define WL_REGISTRY_BIND 0U +#define WL_REGISTRY_EVENT_GLOBAL 0U +#define WL_REGISTRY_EVENT_GLOBAL_REMOVE 1U + +/* wl_callback events */ +#define WL_CALLBACK_EVENT_DONE 0U + +/* wl_compositor requests */ +#define WL_COMPOSITOR_CREATE_SURFACE 0U + +/* wl_shm requests / events & pixel formats */ +#define WL_SHM_CREATE_POOL 0U +#define WL_SHM_EVENT_FORMAT 0U +#define WL_SHM_FORMAT_ARGB8888 0U +#define WL_SHM_FORMAT_XRGB8888 1U + +/* wl_shm_pool requests */ +#define WL_SHM_POOL_CREATE_BUFFER 0U +#define WL_SHM_POOL_DESTROY 1U +#define WL_SHM_POOL_RESIZE 2U + +/* wl_buffer requests / events */ +#define WL_BUFFER_DESTROY 0U +#define WL_BUFFER_EVENT_RELEASE 0U + +/* wl_surface requests */ +#define WL_SURFACE_DESTROY 0U +#define WL_SURFACE_ATTACH 1U +#define WL_SURFACE_DAMAGE 2U +#define WL_SURFACE_FRAME 3U +#define WL_SURFACE_COMMIT 6U + +/* wl_seat requests / events & capability flags */ +#define WL_SEAT_GET_POINTER 0U +#define WL_SEAT_GET_KEYBOARD 1U +#define WL_SEAT_EVENT_CAPABILITIES 0U +#define WL_SEAT_EVENT_NAME 1U +#define WL_SEAT_CAP_POINTER 1U +#define WL_SEAT_CAP_KEYBOARD 2U + +/* wl_pointer events */ +#define WL_POINTER_EVENT_ENTER 0U +#define WL_POINTER_EVENT_LEAVE 1U +#define WL_POINTER_EVENT_MOTION 2U +#define WL_POINTER_EVENT_BUTTON 3U +#define WL_POINTER_EVENT_FRAME 5U + +/* wl_keyboard events */ +#define WL_KEYBOARD_EVENT_ENTER 1U +#define WL_KEYBOARD_EVENT_LEAVE 2U +#define WL_KEYBOARD_EVENT_KEY 3U + +/* Global advertisement names */ +#define WL_GLOBAL_COMPOSITOR 1U +#define WL_GLOBAL_SHM 2U +#define WL_GLOBAL_SEAT 3U + +#define WL_MSG_HEADER_BYTES 8U +#define WL_MAX_MSG_BYTES 512U + +static inline uint32_t wl_align4(uint32_t n) { + return (n + 3U) & ~3U; +} + +static inline uint32_t wl_fixed_from_int(int32_t v) { + return (uint32_t)(v * 256); +} + +static inline int32_t wl_fixed_to_int(uint32_t f) { + return ((int32_t)f) / 256; +} + +struct wl_writer { + uint8_t buf[WL_MAX_MSG_BYTES]; + uint32_t len; +}; + +static inline void wl_w_begin(struct wl_writer* w, uint32_t obj_id, uint16_t opcode) { + memset(w->buf, 0, sizeof(w->buf)); + memcpy(w->buf + 0, &obj_id, 4); + uint32_t word1 = (uint32_t)opcode; + memcpy(w->buf + 4, &word1, 4); + w->len = WL_MSG_HEADER_BYTES; +} + +static inline int wl_w_u32(struct wl_writer* w, uint32_t v) { + if (w->len + 4U > sizeof(w->buf)) { + return -1; + } + memcpy(w->buf + w->len, &v, 4); + w->len += 4U; + return 0; +} + +static inline int wl_w_i32(struct wl_writer* w, int32_t v) { + return wl_w_u32(w, (uint32_t)v); +} + +static inline int wl_w_str(struct wl_writer* w, const char* s) { + uint32_t slen = (uint32_t)strlen(s) + 1U; + uint32_t padded = wl_align4(slen); + if (w->len + 4U + padded > sizeof(w->buf)) { + return -1; + } + memcpy(w->buf + w->len, &slen, 4); + w->len += 4U; + memcpy(w->buf + w->len, s, slen); + if (padded > slen) { + memset(w->buf + w->len + slen, 0, padded - slen); + } + w->len += padded; + return 0; +} + +static inline uint32_t wl_w_finish(struct wl_writer* w) { + uint32_t word1 = 0U; + memcpy(&word1, w->buf + 4, 4); + word1 = (word1 & 0xFFFFU) | (w->len << 16U); + memcpy(w->buf + 4, &word1, 4); + return w->len; +} + +struct wl_reader { + const uint8_t* data; + uint32_t len; + uint32_t pos; +}; + +static inline void wl_r_init(struct wl_reader* r, const uint8_t* payload, uint32_t payload_len) { + r->data = payload; + r->len = payload_len; + r->pos = 0U; +} + +static inline int wl_r_u32(struct wl_reader* r, uint32_t* out) { + if (r->pos + 4U > r->len) { + return -1; + } + memcpy(out, r->data + r->pos, 4); + r->pos += 4U; + return 0; +} + +static inline int wl_r_i32(struct wl_reader* r, int32_t* out) { + uint32_t tmp = 0U; + if (wl_r_u32(r, &tmp) != 0) { + return -1; + } + *out = (int32_t)tmp; + return 0; +} + +static inline int wl_r_str(struct wl_reader* r, char* out, size_t out_cap) { + uint32_t slen = 0U; + if (wl_r_u32(r, &slen) != 0) { + return -1; + } + uint32_t padded = wl_align4(slen); + if (r->pos + padded > r->len) { + return -1; + } + if (out != NULL && out_cap > 0U) { + size_t copy_len = (slen > 0U) ? (size_t)(slen - 1U) : 0U; + if (copy_len >= out_cap) { + copy_len = out_cap - 1U; + } + if (copy_len > 0U) { + memcpy(out, r->data + r->pos, copy_len); + } + out[copy_len] = '\0'; + } + r->pos += padded; + return 0; +} + +static inline int wl_send_msg(int sock_fd, struct wl_writer* w, int pass_fd) { + uint32_t total = wl_w_finish(w); + uint32_t sent = 0U; + int fd_to_send = pass_fd; + + while (sent < total) { + struct iovec iov; + iov.iov_base = w->buf + sent; + iov.iov_len = total - sent; + + struct msghdr msg; + memset(&msg, 0, sizeof(msg)); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + + union { + char buf[CMSG_SPACE(sizeof(int))]; + struct cmsghdr align; + } ctrl; + + if (fd_to_send >= 0) { + memset(&ctrl, 0, sizeof(ctrl)); + msg.msg_control = ctrl.buf; + msg.msg_controllen = sizeof(ctrl.buf); + struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + cmsg->cmsg_len = CMSG_LEN(sizeof(int)); + memcpy(CMSG_DATA(cmsg), &fd_to_send, sizeof(int)); + } + + ssize_t n = sendmsg(sock_fd, &msg, MSG_NOSIGNAL); + if (n < 0) { + if (errno == EINTR) { + continue; + } + if (errno == EAGAIN || errno == EWOULDBLOCK) { + usleep(1000); + continue; + } + return -1; + } + if (n == 0) { + return -1; + } + sent += (uint32_t)n; + fd_to_send = -1; + } + return 0; +} + +static inline ssize_t wl_recv_chunk(int sock_fd, uint8_t* dst, size_t dst_cap, int* out_fds, + size_t max_fds, size_t* out_nfd) { + if (out_nfd != NULL) { + *out_nfd = 0U; + } + struct iovec iov; + iov.iov_base = dst; + iov.iov_len = dst_cap; + + union { + char buf[CMSG_SPACE(sizeof(int) * 8U)]; + struct cmsghdr align; + } ctrl; + memset(&ctrl, 0, sizeof(ctrl)); + + struct msghdr msg; + memset(&msg, 0, sizeof(msg)); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = ctrl.buf; + msg.msg_controllen = sizeof(ctrl.buf); + + ssize_t n = recvmsg(sock_fd, &msg, MSG_CMSG_CLOEXEC); + if (n <= 0) { + return n; + } + + size_t nfd = 0U; + for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) { + if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) { + size_t data_bytes = (size_t)cmsg->cmsg_len - CMSG_LEN(0); + size_t count = data_bytes / sizeof(int); + const unsigned char* raw = CMSG_DATA(cmsg); + for (size_t i = 0U; i < count; ++i) { + int rfd = -1; + memcpy(&rfd, raw + (i * sizeof(int)), sizeof(int)); + if (out_fds != NULL && nfd < max_fds) { + out_fds[nfd++] = rfd; + } else if (rfd >= 0) { + close(rfd); + } + } + } + } + if (out_nfd != NULL) { + *out_nfd = nfd; + } + return n; +} + +/* ------------------------------------------------------------------------- + * Milo /dev/fb0 UAPI (Linux fbdev compatible) + * ------------------------------------------------------------------------- */ + +#define MILO_FBIOGET_VSCREENINFO 0x4600UL +#define MILO_FBIOGET_FSCREENINFO 0x4602UL +#define MILO_FBIO_FLUSH 0x4620UL + +struct milo_fb_bitfield { + uint32_t offset; + uint32_t length; + uint32_t msb_right; +}; + +struct milo_fb_var_screeninfo { + uint32_t xres; + uint32_t yres; + uint32_t xres_virtual; + uint32_t yres_virtual; + uint32_t xoffset; + uint32_t yoffset; + uint32_t bits_per_pixel; + uint32_t grayscale; + struct milo_fb_bitfield red; + struct milo_fb_bitfield green; + struct milo_fb_bitfield blue; + struct milo_fb_bitfield transp; + uint32_t nonstd; + uint32_t activate; + uint32_t height; + uint32_t width; + uint32_t accel_flags; + uint32_t pixclock; + uint32_t left_margin; + uint32_t right_margin; + uint32_t upper_margin; + uint32_t lower_margin; + uint32_t hsync_len; + uint32_t vsync_len; + uint32_t sync; + uint32_t vmode; + uint32_t rotate; + uint32_t colorspace; + uint32_t reserved[4]; +}; + +struct milo_fb_fix_screeninfo { + char id[16]; + uint64_t smem_start; + uint32_t smem_len; + uint32_t type; + uint32_t type_aux; + uint32_t visual; + uint16_t xpanstep; + uint16_t ypanstep; + uint16_t ywrapstep; + uint16_t pad0; + uint32_t line_length; + uint32_t pad1; + uint64_t mmio_start; + uint32_t mmio_len; + uint32_t accel; + uint16_t capabilities; + uint16_t reserved[2]; + uint16_t pad2; +}; + +#endif /* MILO_USER_WL_PROTO_H */