From 4b3b64a2ad987de89bcb55562189d07b33df9ee5 Mon Sep 17 00:00:00 2001 From: Faumaray Date: Tue, 11 Nov 2025 18:32:04 +0300 Subject: [PATCH] Initial commit --- .envrc | 1 + .gitignore | 4 + CMakeLists.txt | 82 +++++++++++ flake.lock | 61 ++++++++ flake.nix | 39 +++++ linker.ld | 23 +++ src/main_demo.cpp | 18 +++ src/rt/abi.cppm | 13 ++ src/rt/alloc.cppm | 34 +++++ src/rt/alloc_ops.cpp | 18 +++ src/rt/byteorder.cppm | 33 +++++ src/rt/constants.cppm | 43 ++++++ src/rt/cstring.cppm | 27 ++++ src/rt/cwd.cppm | 35 +++++ src/rt/dirent.cppm | 33 +++++ src/rt/entry.cppm | 40 +++++ src/rt/env.cppm | 30 ++++ src/rt/epoll.cppm | 65 +++++++++ src/rt/errno.cppm | 12 ++ src/rt/exit.cppm | 20 +++ src/rt/fd.cppm | 37 +++++ src/rt/format.cppm | 174 ++++++++++++++++++++++ src/rt/fs.cppm | 50 +++++++ src/rt/linux/sys.cppm | 91 ++++++++++++ src/rt/linux/syscall.cppm | 24 +++ src/rt/linux/syscall_shim.S | 79 ++++++++++ src/rt/linux/sysnums.cppm | 23 +++ src/rt/linux/sysnums_poll_net.cppm | 27 ++++ src/rt/linux/sysnums_proc.cppm | 26 ++++ src/rt/linux/sysnums_thread.cppm | 9 ++ src/rt/mem.cppm | 27 ++++ src/rt/mmap.cppm | 34 +++++ src/rt/net.cppm | 142 ++++++++++++++++++ src/rt/panic.cppm | 15 ++ src/rt/path.cppm | 51 +++++++ src/rt/pathops.cppm | 227 +++++++++++++++++++++++++++++ src/rt/platform/darwin_macho.cppm | 10 ++ src/rt/platform/linux_x86_64.cppm | 37 +++++ src/rt/platform/windows_pe.cppm | 10 ++ src/rt/poll.cppm | 51 +++++++ src/rt/printf.cppm | 20 +++ src/rt/proc_exec.cppm | 64 ++++++++ src/rt/process.cppm | 34 +++++ src/rt/random.cppm | 23 +++ src/rt/sched.cppm | 15 ++ src/rt/signals.cppm | 82 +++++++++++ src/rt/snprintf.cppm | 45 ++++++ src/rt/spawn.cppm | 31 ++++ src/rt/stat.cppm | 61 ++++++++ src/rt/string.cppm | 14 ++ src/rt/sys.cppm | 22 +++ src/rt/thread.cppm | 66 +++++++++ src/rt/time.cppm | 56 +++++++ src/rt/timerfd.cppm | 52 +++++++ src/rt/types.cppm | 36 +++++ src/start_x86_64.S | 12 ++ 56 files changed, 2408 insertions(+) create mode 100644 .envrc create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 linker.ld create mode 100644 src/main_demo.cpp create mode 100644 src/rt/abi.cppm create mode 100644 src/rt/alloc.cppm create mode 100644 src/rt/alloc_ops.cpp create mode 100644 src/rt/byteorder.cppm create mode 100644 src/rt/constants.cppm create mode 100644 src/rt/cstring.cppm create mode 100644 src/rt/cwd.cppm create mode 100644 src/rt/dirent.cppm create mode 100644 src/rt/entry.cppm create mode 100644 src/rt/env.cppm create mode 100644 src/rt/epoll.cppm create mode 100644 src/rt/errno.cppm create mode 100644 src/rt/exit.cppm create mode 100644 src/rt/fd.cppm create mode 100644 src/rt/format.cppm create mode 100644 src/rt/fs.cppm create mode 100644 src/rt/linux/sys.cppm create mode 100644 src/rt/linux/syscall.cppm create mode 100644 src/rt/linux/syscall_shim.S create mode 100644 src/rt/linux/sysnums.cppm create mode 100644 src/rt/linux/sysnums_poll_net.cppm create mode 100644 src/rt/linux/sysnums_proc.cppm create mode 100644 src/rt/linux/sysnums_thread.cppm create mode 100644 src/rt/mem.cppm create mode 100644 src/rt/mmap.cppm create mode 100644 src/rt/net.cppm create mode 100644 src/rt/panic.cppm create mode 100644 src/rt/path.cppm create mode 100644 src/rt/pathops.cppm create mode 100644 src/rt/platform/darwin_macho.cppm create mode 100644 src/rt/platform/linux_x86_64.cppm create mode 100644 src/rt/platform/windows_pe.cppm create mode 100644 src/rt/poll.cppm create mode 100644 src/rt/printf.cppm create mode 100644 src/rt/proc_exec.cppm create mode 100644 src/rt/process.cppm create mode 100644 src/rt/random.cppm create mode 100644 src/rt/sched.cppm create mode 100644 src/rt/signals.cppm create mode 100644 src/rt/snprintf.cppm create mode 100644 src/rt/spawn.cppm create mode 100644 src/rt/stat.cppm create mode 100644 src/rt/string.cppm create mode 100644 src/rt/sys.cppm create mode 100644 src/rt/thread.cppm create mode 100644 src/rt/time.cppm create mode 100644 src/rt/timerfd.cppm create mode 100644 src/rt/types.cppm create mode 100644 src/start_x86_64.S diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..8392d15 --- /dev/null +++ b/.envrc @@ -0,0 +1 @@ +use flake \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cbe14cc --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.direnv +*build* +.idea + diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..ed2a8a6 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,82 @@ +cmake_minimum_required(VERSION 3.29) # 3.29+ has solid C++ modules support + +set(CMAKE_EXPERIMENTAL_CXX_IMPORT_STD "a9e1cf81-9932-4810-974b-6eccaf14e457") +set(CMAKE_CXX_STANDARD 26) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_MODULE_STD 1) +set(CMAKE_CXX_EXTENSIONS OFF) +set(CMAKE_EXPERIMENTAL_CXX_MODULE_DYNDEP ON) + +project(freestanding_rt LANGUAGES C CXX ASM) + +# Freestanding, no CRT, no stdlib +add_compile_options( + $<$:-ffreestanding> + $<$:-fno-exceptions> + $<$:-fno-rtti> + $<$:-fno-stack-protector> + $<$:-fvisibility=hidden> + $<$:-fno-builtin> +) + +# Linker: no stdlib, custom entry, keep sections +add_link_options( + -nostdlib + -static + -Wl,--gc-sections + -Wl,-z,nostart-stop-gc + -Wl,-T,${CMAKE_SOURCE_DIR}/linker.ld +) + +# ========================= +# Source auto-discovery +# ========================= +file(GLOB_RECURSE RT_MODULES CONFIGURE_DEPENDS + "${CMAKE_SOURCE_DIR}/src/**/*.cppm" + "${CMAKE_SOURCE_DIR}/src/**/*.ixx" +) +file(GLOB_RECURSE RT_SOURCES CONFIGURE_DEPENDS + "${CMAKE_SOURCE_DIR}/src/**/*.cpp" + "${CMAKE_SOURCE_DIR}/src/**/*.c" + "${CMAKE_SOURCE_DIR}/src/**/*.S" +) + +set(START_SRC "${CMAKE_SOURCE_DIR}/src/start_x86_64.S") + +list(REMOVE_ITEM RT_SOURCES "${START_SRC}") +list(FILTER RT_SOURCES EXCLUDE REGEX ".*/main_demo\\.cpp$") + +# ========================= +# Build runtime as an exe (demo) and as a static archive (future link) +# ========================= +add_library(rt_static STATIC ${RT_SOURCES}) +target_sources(rt_static + PUBLIC + FILE_SET cxx_modules TYPE CXX_MODULES + BASE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/src" + FILES ${RT_MODULES} +) +target_include_directories(rt_static PRIVATE "${CMAKE_SOURCE_DIR}/src") +set_target_properties(rt_static PROPERTIES LINKER_LANGUAGE CXX) + +# Primary demo binary to prove bring-up works (remove later) +add_executable(freestanding_rt + ${START_SRC} + src/main_demo.cpp) +target_link_libraries(freestanding_rt PRIVATE rt_static) +target_include_directories(freestanding_rt PRIVATE "${CMAKE_SOURCE_DIR}/src") + +target_link_options(freestanding_rt PRIVATE + -Wl,-e,_start + -no-pie + -nostdlib + -static + -Wl,--gc-sections + -Wl,-z,nostart-stop-gc + -Wl,-T,${CMAKE_SOURCE_DIR}/linker.ld +) +set_target_properties(freestanding_rt PROPERTIES + ENABLE_EXPORTS OFF + OUTPUT_NAME "freestanding_rt" + LINK_DEPENDS "${CMAKE_SOURCE_DIR}/linker.ld" +) diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..07d5f28 --- /dev/null +++ b/flake.lock @@ -0,0 +1,61 @@ +{ + "nodes": { + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1731533236, + "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1762596750, + "narHash": "sha256-rXXuz51Bq7DHBlfIjN7jO8Bu3du5TV+3DSADBX7/9YQ=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "b6a8526db03f735b89dd5ff348f53f752e7ddc8e", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "flake-utils": "flake-utils", + "nixpkgs": "nixpkgs" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..3509d15 --- /dev/null +++ b/flake.nix @@ -0,0 +1,39 @@ +{ + description = "Gradle C++ cross-compile (Linux → Windows/Mac)"; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + flake-utils.url = "github:numtide/flake-utils"; + }; + + outputs = + { + self, + nixpkgs, + flake-utils, + }: + flake-utils.lib.eachDefaultSystem ( + system: + let + pkgs = import nixpkgs { inherit system; }; + in + { + devShells.default = pkgs.mkShell { + name = "CppShell"; + + nativeBuildInputs = with pkgs; [ + gcc15Stdenv + gcc15 + ninja + cmake + clang-tools + ]; + + buildInputs = with pkgs; [ + ]; + + shellHook = ''''; + }; + } + ); +} diff --git a/linker.ld b/linker.ld new file mode 100644 index 0000000..a15a721 --- /dev/null +++ b/linker.ld @@ -0,0 +1,23 @@ +ENTRY(_start) + +SECTIONS +{ + . = 0x400000; + + .text : { + *(.text*) + } + + .rodata : { + *(.rodata*) + } + + .data : { + *(.data*) + } + + .bss : { + *(.bss*) + *(COMMON) + } +} diff --git a/src/main_demo.cpp b/src/main_demo.cpp new file mode 100644 index 0000000..9a27d80 --- /dev/null +++ b/src/main_demo.cpp @@ -0,0 +1,18 @@ +import rt.printf; +import rt.errno; +import rt.time; +import rt.timerfd; +import rt.snprintf; + +extern "C" int main() { + rt::time::timespec t{0, 50'000'000}; // 50ms + rt::time::nanosleep(&t, nullptr); + + int tfd = rt::timerfd::create(rt::timerfd::CLOCK_MONOTONIC, rt::timerfd::TFD_NONBLOCK); + rt::printf::dprintf(1, "timerfd=%d errno=%d\n", tfd, rt::get_errno()); + + char buf[64]; + rt::printf::snprintf(buf, sizeof(buf), "hello %d %x\n", 42, 0xBEEF); + rt::printf::dprintf(1, "%s", buf); + return 0; +} diff --git a/src/rt/abi.cppm b/src/rt/abi.cppm new file mode 100644 index 0000000..ae2e2f9 --- /dev/null +++ b/src/rt/abi.cppm @@ -0,0 +1,13 @@ +export module rt.abi; + +export namespace rt::abi { + using usize = __UINTPTR_TYPE__; + using isize = __INTPTR_TYPE__; + + // argv/envp triple extracted from raw stack + struct args { + int argc; + char** argv; + char** envp; + }; +} diff --git a/src/rt/alloc.cppm b/src/rt/alloc.cppm new file mode 100644 index 0000000..b740339 --- /dev/null +++ b/src/rt/alloc.cppm @@ -0,0 +1,34 @@ +export module rt.alloc; + +import rt.mem; +import rt.panic; + +namespace rt::alloc { + namespace { + alignas(16) static unsigned char arena[1 << 20]; // 1 MiB demo + static __SIZE_TYPE__ off = 0; + } + + export void* malloc(__SIZE_TYPE__ n) noexcept { + if (n == 0) n = 1; + const __SIZE_TYPE__ aligned = (n + 15) & ~static_cast<__SIZE_TYPE__>(15); + if (off + aligned > sizeof(arena)) return nullptr; + void* p = arena + off; + off += aligned; + return p; + } + + export void free(void*) noexcept { + // bump-alloc demo: no-op + } + + // Internal helpers used by the global operators (defined in alloc_ops.cpp) + export void* operator_new(__SIZE_TYPE__ n) noexcept { + if (void* p = malloc(n)) return p; + rt::panic("rt.alloc: out of memory\n"); + } + + export void operator_delete(void* p) noexcept { + free(p); + } +} diff --git a/src/rt/alloc_ops.cpp b/src/rt/alloc_ops.cpp new file mode 100644 index 0000000..f6fde3b --- /dev/null +++ b/src/rt/alloc_ops.cpp @@ -0,0 +1,18 @@ +// Non-module TU that provides the global operators. +// It imports the rt.alloc module and calls its helpers. + +import rt.alloc; + +using size_t = __SIZE_TYPE__; + +void* operator new(size_t n) noexcept { return rt::alloc::operator_new(n); } +void operator delete(void* p) noexcept { rt::alloc::operator_delete(p); } + +void* operator new[](size_t n) noexcept { return rt::alloc::operator_new(n); } +void operator delete[](void* p) noexcept { rt::alloc::operator_delete(p); } + +void* operator new(size_t, void* p) noexcept { return p; } +void operator delete(void*, void*) noexcept {} + +void* operator new[](size_t, void* p) noexcept { return p; } +void operator delete[](void*, void*) noexcept {} diff --git a/src/rt/byteorder.cppm b/src/rt/byteorder.cppm new file mode 100644 index 0000000..f0470d6 --- /dev/null +++ b/src/rt/byteorder.cppm @@ -0,0 +1,33 @@ +export module rt.byteorder; + +import rt.types; + +namespace rt { + export rt_u16 bswap16(rt_u16 x) noexcept { + return (rt_u16)((x >> 8) | (x << 8)); + } + export rt_u32 bswap32(rt_u32 x) noexcept { + return (x >> 24) | + ((x >> 8) & 0x0000FF00u) | + ((x << 8) & 0x00FF0000u) | + (x << 24); + } + export rt_u64 bswap64(rt_u64 x) noexcept { + return ((x & 0x00000000000000FFull) << 56) | + ((x & 0x000000000000FF00ull) << 40) | + ((x & 0x0000000000FF0000ull) << 24) | + ((x & 0x00000000FF000000ull) << 8) | + ((x & 0x000000FF00000000ull) >> 8) | + ((x & 0x0000FF0000000000ull) >> 24) | + ((x & 0x00FF000000000000ull) >> 40) | + ((x & 0xFF00000000000000ull) >> 56); + } + + // assume little-endian host (x86-64); adjust if you add BE later + export rt_u16 htons(rt_u16 x) noexcept { return bswap16(x); } + export rt_u16 ntohs(rt_u16 x) noexcept { return bswap16(x); } + export rt_u32 htonl(rt_u32 x) noexcept { return bswap32(x); } + export rt_u32 ntohl(rt_u32 x) noexcept { return bswap32(x); } + export rt_u64 htonll(rt_u64 x) noexcept { return bswap64(x); } + export rt_u64 ntohll(rt_u64 x) noexcept { return bswap64(x); } +} diff --git a/src/rt/constants.cppm b/src/rt/constants.cppm new file mode 100644 index 0000000..139d926 --- /dev/null +++ b/src/rt/constants.cppm @@ -0,0 +1,43 @@ +export module rt.constants; + +namespace rt { + // AT_FDCWD + export constexpr int AT_FDCWD = -100; + + // open flags + export constexpr int O_RDONLY = 0x0000; + export constexpr int O_WRONLY = 0x0001; + export constexpr int O_RDWR = 0x0002; + export constexpr int O_CREAT = 0x0040; + export constexpr int O_EXCL = 0x0080; + export constexpr int O_TRUNC = 0x0200; + export constexpr int O_APPEND = 0x0400; + export constexpr int O_NONBLOCK = 0x0800; + export constexpr int O_CLOEXEC = 0x80000; + + // lseek whence + export constexpr int SEEK_SET = 0; + export constexpr int SEEK_CUR = 1; + export constexpr int SEEK_END = 2; + + // mmap prot/flags + export constexpr int PROT_NONE = 0x0; + export constexpr int PROT_READ = 0x1; + export constexpr int PROT_WRITE = 0x2; + export constexpr int PROT_EXEC = 0x4; + + export constexpr int MAP_SHARED = 0x01; + export constexpr int MAP_PRIVATE = 0x02; + export constexpr int MAP_FIXED = 0x10; + export constexpr int MAP_ANONYMOUS = 0x20; + + // dirent d_type + export constexpr unsigned char DT_UNKNOWN = 0; + export constexpr unsigned char DT_FIFO = 1; + export constexpr unsigned char DT_CHR = 2; + export constexpr unsigned char DT_DIR = 4; + export constexpr unsigned char DT_BLK = 6; + export constexpr unsigned char DT_REG = 8; + export constexpr unsigned char DT_LNK = 10; + export constexpr unsigned char DT_SOCK = 12; +} diff --git a/src/rt/cstring.cppm b/src/rt/cstring.cppm new file mode 100644 index 0000000..54ede5b --- /dev/null +++ b/src/rt/cstring.cppm @@ -0,0 +1,27 @@ +export module rt.cstring; + +namespace rt::cstring { + export unsigned long strlen(const char* s) noexcept { + unsigned long n = 0; if (!s) return 0; while (s[n]) ++n; return n; + } + export int strcmp(const char* a, const char* b) noexcept { + while (*a && (*a==*b)) { ++a; ++b; } return (unsigned char)*a - (unsigned char)*b; + } + export int strncmp(const char* a, const char* b, unsigned long n) noexcept { + for (unsigned long i=0; i(raw_sp); + int argc = static_cast(*sp); + char** argv = reinterpret_cast(sp + 1); + char** envp = argv + argc + 1; + return {argc, argv, envp}; + } + + // Extremely simple runtime target probe. For now, assume Linux if + // ELF syscall succeeds; extend with richer PE/Mach-O detection when polyglot. + void attach_backend() { +#if defined(__x86_64__) + sys::attach(rt::platform::linux_x86_64::vtab()); +#else + rt::panic("rt: unsupported arch for now (need backend)\n"); +#endif + } +} + +export extern "C" [[noreturn]] void runtime_entry(void* raw_sp) { + attach_backend(); + auto a = parse_args(raw_sp); + rt::_env_set(a.argc, a.argv, a.envp); + int rc = main(a.argc, a.argv, a.envp); + rt::sys::exit(rc); +} diff --git a/src/rt/env.cppm b/src/rt/env.cppm new file mode 100644 index 0000000..3137fb4 --- /dev/null +++ b/src/rt/env.cppm @@ -0,0 +1,30 @@ +export module rt.env; + +namespace rt { + // internal storage set by runtime_entry + static int g_argc = 0; + static char** g_argv = nullptr; + static char** g_envp = nullptr; + + // set by runtime_entry (not exported) + export void _env_set(int argc, char** argv, char** envp) noexcept { + g_argc = argc; g_argv = argv; g_envp = envp; + } + + export int argc() noexcept { return g_argc; } + export char** argv() noexcept { return g_argv; } + export char** envp() noexcept { return g_envp; } + + // simple getenv (linear scan), returns pointer into envp + export const char* getenv(const char* key) noexcept { + if (!key) return nullptr; + unsigned long klen = 0; while (key[klen]) ++klen; + for (char** e = g_envp; e && *e; ++e) { + const char* s = *e; + unsigned long i = 0; + while (i < klen && s[i] && s[i] == key[i]) ++i; + if (i == klen && s[i] == '=') return s + i + 1; + } + return nullptr; + } +} diff --git a/src/rt/epoll.cppm b/src/rt/epoll.cppm new file mode 100644 index 0000000..7b864bb --- /dev/null +++ b/src/rt/epoll.cppm @@ -0,0 +1,65 @@ +export module rt.epoll; + +import rt.errno; +import rt.types; + +#if defined(__linux__) && defined(__x86_64__) +import rt.linux.sysnums_poll_net; +#endif + +namespace rt::epoll { + // event flags + export constexpr rt_u32 EPOLLIN = 0x001; + export constexpr rt_u32 EPOLLOUT = 0x004; + export constexpr rt_u32 EPOLLERR = 0x008; + export constexpr rt_u32 EPOLLHUP = 0x010; + export constexpr rt_u32 EPOLLRDHUP = 0x2000; + + // ctl ops + export constexpr int EPOLL_CTL_ADD = 1; + export constexpr int EPOLL_CTL_DEL = 2; + export constexpr int EPOLL_CTL_MOD = 3; + + export struct epoll_event { + rt_u32 events; + rt_u64 data; // user data + }; + + export int create1(int flags) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r):"a"(rt::linux::__NR_epoll_create1),"D"(flags):"rcx","r11","memory"); + if (r<0){ rt::set_errno((int)-r); return -1; } return (int)r; +#else + rt::set_errno(38); return -1; +#endif + } + + export int ctl(int epfd, int op, int fd, epoll_event* ev) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r) + : "a"(rt::linux::__NR_epoll_ctl), "D"(epfd), "S"(op), "d"(fd), "r"(ev) + : "rcx","r11","memory"); + if (r<0){ rt::set_errno((int)-r); return -1; } return 0; +#else + rt::set_errno(38); return -1; +#endif + } + + export int wait(int epfd, epoll_event* evs, int maxevents, int timeout_ms) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; + register long r10 __asm__("r10") = (long)timeout_ms; // 4th + register long r8 __asm__("r8") = 0L; // 5th (sigmask) + register long r9 __asm__("r9") = 0L; // 6th (sigsetsize) + asm volatile("syscall" + : "=a"(r) + : "a"(rt::linux::__NR_epoll_pwait), + "D"(epfd), "S"(evs), "d"(maxevents), + "r"(r10), "r"(r8), "r"(r9) + : "rcx","r11","memory"); + if (r < 0) { rt::set_errno((int)-r); return -1; } return (int)r; +#else + rt::set_errno(38); return -1; +#endif + } +} diff --git a/src/rt/errno.cppm b/src/rt/errno.cppm new file mode 100644 index 0000000..8e5b0de --- /dev/null +++ b/src/rt/errno.cppm @@ -0,0 +1,12 @@ +export module rt.errno; + +namespace rt { + // POSIX-like errno for freestanding land. + // Thread-local by default; adjust if you build threads. + static int errno_value = 0; + + export int* errno_ptr() noexcept { return &errno_value; } + export void set_errno(int e) noexcept { errno_value = e; } + export int get_errno() noexcept { return errno_value; } + export extern "C" int* __errno_location() noexcept { return &errno_value; } +} diff --git a/src/rt/exit.cppm b/src/rt/exit.cppm new file mode 100644 index 0000000..73c5fdb --- /dev/null +++ b/src/rt/exit.cppm @@ -0,0 +1,20 @@ +export module rt.exit; + +#if defined(__linux__) && defined(__x86_64__) +import rt.linux.sys; +#endif + +namespace rt { + export [[noreturn]] void _exit(int code) noexcept { +#if defined(__linux__) && defined(__x86_64__) + linux::sys_exit(code); +#else + __builtin_trap(); +#endif + } + + // Minimal abort: trap. (You can route to panic if desired.) + export [[noreturn]] void abort() noexcept { + __builtin_trap(); + } +} diff --git a/src/rt/fd.cppm b/src/rt/fd.cppm new file mode 100644 index 0000000..4739dad --- /dev/null +++ b/src/rt/fd.cppm @@ -0,0 +1,37 @@ +export module rt.fd; + +import rt.errno; + +#if defined(__linux__) && defined(__x86_64__) +import rt.linux.sysnums_poll_net; +#endif + +namespace rt { + export int dup(int oldfd) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r):"a"(rt::linux::__NR_dup),"D"(oldfd):"rcx","r11","memory"); + if (r<0){ set_errno((int)-r); return -1; } return (int)r; +#else + set_errno(38); return -1; +#endif + } + + export int dup3(int oldfd, int newfd, int flags) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r):"a"(rt::linux::__NR_dup3),"D"(oldfd),"S"(newfd),"d"(flags):"rcx","r11","memory"); + if (r<0){ set_errno((int)-r); return -1; } return (int)r; +#else + set_errno(38); return -1; +#endif + } + + // pipe2: fds[0]=read, fds[1]=write + export int pipe2(int fds[2], int flags) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r):"a"(rt::linux::__NR_pipe2),"D"(fds),"S"(flags):"rcx","r11","memory"); + if (r<0){ set_errno((int)-r); return -1; } return 0; +#else + set_errno(38); return -1; +#endif + } +} diff --git a/src/rt/format.cppm b/src/rt/format.cppm new file mode 100644 index 0000000..60cc45b --- /dev/null +++ b/src/rt/format.cppm @@ -0,0 +1,174 @@ +export module rt.format; + +import rt.string; +import rt.mem; + +namespace rt::format { + using sink_fn = bool(*)(void*, const char*, unsigned long); + + inline bool sink_write(sink_fn sink, void* cookie, const char* s, unsigned long n) { + return sink ? sink(cookie, s, n) : false; + } + + // Unsigned integer -> string with base and zero-padding support + inline unsigned long itoa_u_pad(unsigned long v, unsigned base, char* buf, + unsigned long cap, bool upper, + unsigned width, bool zpad) { + if (cap == 0) return 0; + const char* digs = upper ? "0123456789ABCDEF" : "0123456789abcdef"; + char tmp[32]; unsigned t = 0; + do { + tmp[t++] = digs[v % base]; + v /= base; + } while (v && t < sizeof(tmp)); + + unsigned need = t; + if (width > need) need = width; + unsigned long n = (need < cap - 1) ? need : (cap - 1); + + // left pad with '0' if requested and width > digits + unsigned pad = (n > t) ? (n - t) : 0; + unsigned long i = 0; + for (; i < pad; ++i) buf[i] = zpad ? '0' : ' '; + for (unsigned j = 0; j < t && i < n; ++j) buf[i++] = tmp[t - 1 - j]; + buf[n] = 0; + return n; + } + + // Signed with padding (dispatches to unsigned after sign handling) + inline unsigned long itoa_s_pad(long v, char* buf, unsigned long cap, + unsigned width, bool zpad) { + if (cap == 0) return 0; + if (v < 0) { + if (cap < 2) return 0; + // Handle sign; width applies to digits only + unsigned long n = itoa_u_pad((unsigned long)(-v), 10, buf + 1, cap - 1, false, width, zpad); + // If zero-pad requested, keep '-' before zeros: e.g., "-00012" + // We already wrote digits with any zeros; just put '-' at front. + buf[0] = '-'; + return n + 1; + } else { + return itoa_u_pad((unsigned long)v, 10, buf, cap, false, width, zpad); + } + } + + // Minimal parser state + struct fmt_state { + bool zero_pad; + unsigned width; + enum class len { none, l, ll, z } length; + }; + + inline const char* parse_flags_width_len(const char* p, fmt_state& st) { + st.zero_pad = false; + st.width = 0; + st.length = fmt_state::len::none; + + // flags + bool parsing = true; + while (parsing) { + switch (*p) { + case '0': st.zero_pad = true; ++p; break; + default: parsing = false; break; + } + } + // width + while (*p >= '0' && *p <= '9') { + st.width = st.width * 10 + (unsigned)(*p - '0'); + ++p; + } + // length + if (*p == 'l') { + ++p; + if (*p == 'l') { st.length = fmt_state::len::ll; ++p; } + else st.length = fmt_state::len::l; + } else if (*p == 'z') { + ++p; st.length = fmt_state::len::z; + } + return p; + } + + export long vprint(sink_fn sink, void* cookie, const char* fmt, __builtin_va_list ap) { + unsigned long out = 0; + for (const char* p = fmt; *p; ++p) { + if (*p != '%') { + if (!sink_write(sink, cookie, p, 1)) return -1; + ++out; continue; + } + ++p; + if (*p == '%') { if (!sink_write(sink, cookie, "%", 1)) return -1; ++out; continue; } + + fmt_state st{}; + p = parse_flags_width_len(p, st); + char buf[64]; + + switch (*p) { + case 's': { + const char* s = __builtin_va_arg(ap, const char*); + if (!s) s = "(null)"; + unsigned long n = 0; while (s[n]) ++n; + if (!sink_write(sink, cookie, s, n)) return -1; out += n; break; + } + case 'c': { + char c = (char)__builtin_va_arg(ap, int); + if (!sink_write(sink, cookie, &c, 1)) return -1; ++out; break; + } + case 'd': { // signed + long v; + if (st.length == fmt_state::len::ll) v = __builtin_va_arg(ap, long long); + else if (st.length == fmt_state::len::l) v = __builtin_va_arg(ap, long); + else if (st.length == fmt_state::len::z) v = (long)__builtin_va_arg(ap, __SIZE_TYPE__); + else v = __builtin_va_arg(ap, int); + unsigned long n = itoa_s_pad(v, buf, sizeof(buf), st.width, st.zero_pad); + if (!sink_write(sink, cookie, buf, n)) return -1; out += n; break; + } + case 'u': { // unsigned + unsigned long uv; + if (st.length == fmt_state::len::ll) uv = __builtin_va_arg(ap, unsigned long long); + else if (st.length == fmt_state::len::l) uv = __builtin_va_arg(ap, unsigned long); + else if (st.length == fmt_state::len::z) uv = (unsigned long)__builtin_va_arg(ap, __SIZE_TYPE__); + else uv = __builtin_va_arg(ap, unsigned int); + unsigned long n = itoa_u_pad(uv, 10, buf, sizeof(buf), false, st.width, st.zero_pad); + if (!sink_write(sink, cookie, buf, n)) return -1; out += n; break; + } + case 'o': { // octal + unsigned long uv; + if (st.length == fmt_state::len::ll) uv = __builtin_va_arg(ap, unsigned long long); + else if (st.length == fmt_state::len::l) uv = __builtin_va_arg(ap, unsigned long); + else if (st.length == fmt_state::len::z) uv = (unsigned long)__builtin_va_arg(ap, __SIZE_TYPE__); + else uv = __builtin_va_arg(ap, unsigned int); + unsigned long n = itoa_u_pad(uv, 8, buf, sizeof(buf), false, st.width, st.zero_pad); + if (!sink_write(sink, cookie, buf, n)) return -1; out += n; break; + } + case 'x': case 'X': { // hex + unsigned long uv; + if (st.length == fmt_state::len::ll) uv = __builtin_va_arg(ap, unsigned long long); + else if (st.length == fmt_state::len::l) uv = __builtin_va_arg(ap, unsigned long); + else if (st.length == fmt_state::len::z) uv = (unsigned long)__builtin_va_arg(ap, __SIZE_TYPE__); + else uv = __builtin_va_arg(ap, unsigned int); + unsigned long n = itoa_u_pad(uv, 16, buf, sizeof(buf), *p=='X', st.width, st.zero_pad); + if (!sink_write(sink, cookie, buf, n)) return -1; out += n; break; + } + case 'p': { // pointer (always 0x + hex, width ignored) + unsigned long uv = (unsigned long)__builtin_va_arg(ap, void*); + if (!sink_write(sink, cookie, "0x", 2)) return -1; out += 2; + unsigned long n = itoa_u_pad(uv, 16, buf, sizeof(buf), false, 1, true); + if (!sink_write(sink, cookie, buf, n)) return -1; out += n; break; + } + default: { + // unknown: print literally + if (!sink_write(sink, cookie, "%", 1)) return -1; ++out; + if (!sink_write(sink, cookie, p, 1)) return -1; ++out; + } + } + } + return (long)out; + } + + export long print(sink_fn sink, void* cookie, const char* fmt, ...) { + __builtin_va_list ap; __builtin_va_start(ap, fmt); + long r = vprint(sink, cookie, fmt, ap); + __builtin_va_end(ap); + return r; + } +} diff --git a/src/rt/fs.cppm b/src/rt/fs.cppm new file mode 100644 index 0000000..5354e56 --- /dev/null +++ b/src/rt/fs.cppm @@ -0,0 +1,50 @@ +export module rt.fs; +import rt.errno; +import rt.panic; + +#if defined(__linux__) && defined(__x86_64__) +import rt.linux.sys; +#endif + +namespace rt { + // openat() so we can later support dirfds and AT_* flags + export long openat(int dfd, const char* path, long flags, long mode) noexcept { +#if defined(__linux__) && defined(__x86_64__) + return linux::sys_openat(dfd, path, flags, mode); +#else + set_errno(38 /*ENOSYS*/); return -1; +#endif + } + + export long close(int fd) noexcept { +#if defined(__linux__) && defined(__x86_64__) + return linux::sys_close(fd); +#else + set_errno(38); return -1; +#endif + } + + export long read(int fd, void* buf, unsigned long len) noexcept { +#if defined(__linux__) && defined(__x86_64__) + return linux::sys_read(fd, buf, len); +#else + set_errno(38); return -1; +#endif + } + + export long write(int fd, const void* buf, unsigned long len) noexcept { +#if defined(__linux__) && defined(__x86_64__) + return linux::sys_write(fd, buf, len); +#else + set_errno(38); return -1; +#endif + } + + export long lseek(int fd, long off, int whence) noexcept { +#if defined(__linux__) && defined(__x86_64__) + return linux::sys_lseek(fd, off, whence); +#else + set_errno(38); return -1; +#endif + } +} diff --git a/src/rt/linux/sys.cppm b/src/rt/linux/sys.cppm new file mode 100644 index 0000000..30e192e --- /dev/null +++ b/src/rt/linux/sys.cppm @@ -0,0 +1,91 @@ +export module rt.linux.sys; +import rt.linux.sysnums; +import rt.linux.sysnums_proc; +import rt.errno; + +extern "C" long rt_linux_sys_wait4(int, int*, int, void*); + +namespace rt::linux { + // Raw syscall helpers (0..6 args). Negative return -> -errno. + // Callers translate to errno via to_errno() below. + inline long do_syscall0(long n) { + long r; asm volatile("syscall" : "=a"(r) : "a"(n) : "rcx","r11","memory"); return r; + } + inline long do_syscall1(long n, long a) { + long r; asm volatile("syscall" : "=a"(r) : "a"(n),"D"(a) : "rcx","r11","memory"); return r; + } + inline long do_syscall2(long n, long a, long b) { + long r; asm volatile("syscall" : "=a"(r) : "a"(n),"D"(a),"S"(b) : "rcx","r11","memory"); return r; + } + inline long do_syscall3(long n, long a, long b, long c) { + long r; asm volatile("syscall" : "=a"(r) : "a"(n),"D"(a),"S"(b),"d"(c) : "rcx","r11","memory"); return r; + } + inline long do_syscall4(long n, long a, long b, long c, long d) { + long r; register long r10 __asm__("r10") = d; + asm volatile("syscall" : "=a"(r) : "a"(n),"D"(a),"S"(b),"d"(c),"r"(r10) : "rcx","r11","memory"); return r; + } + inline long do_syscall5(long n, long a, long b, long c, long d, long e) { + long r; register long r10 __asm__("r10") = d; register long r8 __asm__("r8") = e; + asm volatile("syscall" : "=a"(r) : "a"(n),"D"(a),"S"(b),"d"(c),"r"(r10),"r"(r8) : "rcx","r11","memory"); return r; + } + inline long do_syscall6(long n, long a, long b, long c, long d, long e, long f) { + long r; register long r10 __asm__("r10") = d; register long r8 __asm__("r8") = e; register long r9 __asm__("r9") = f; + asm volatile("syscall" : "=a"(r) : "a"(n),"D"(a),"S"(b),"d"(c),"r"(r10),"r"(r8),"r"(r9) : "rcx","r11","memory"); return r; + } + + inline long to_errno(long r) { + if (r < 0) { rt::set_errno((int)-r); return -1; } + return r; + } + + // ---- exported minimal API (Linux-only) ---- + export long sys_write(int fd, const void* buf, unsigned long len) noexcept { + return to_errno(do_syscall3(__NR_write, fd, (long)buf, (long)len)); + } + export [[noreturn]] void sys_exit(int code) noexcept { + (void)do_syscall1(__NR_exit, code); + __builtin_unreachable(); + } + export long sys_read(int fd, void* buf, unsigned long len) noexcept { + return to_errno(do_syscall3(__NR_read, fd, (long)buf, (long)len)); + } + export long sys_close(int fd) noexcept { + return to_errno(do_syscall1(__NR_close, fd)); + } + // openat flags are passed through as-is + export long sys_openat(int dfd, const char* path, long flags, long mode) noexcept { + return to_errno(do_syscall4(__NR_openat, dfd, (long)path, flags, mode)); + } + export long sys_lseek(int fd, long off, int whence) noexcept { + return to_errno(do_syscall3(__NR_lseek, fd, off, whence)); + } + export long sys_mmap(void* addr, unsigned long len, long prot, long flags, int fd, long off) noexcept { + return to_errno(do_syscall6(__NR_mmap, (long)addr, (long)len, prot, flags, fd, off)); + } + export long sys_munmap(void* addr, unsigned long len) noexcept { + return to_errno(do_syscall2(__NR_munmap, (long)addr, (long)len)); + } + export long sys_mprotect(void* addr, unsigned long len, long prot) noexcept { + return to_errno(do_syscall3(__NR_mprotect, (long)addr, (long)len, prot)); + } + export long sys_nanosleep(const void* req_ts, void* rem_ts) noexcept { + return to_errno(do_syscall2(__NR_nanosleep, (long)req_ts, (long)rem_ts)); + } + export long sys_clock_gettime(int clk_id, void* ts) noexcept { + return to_errno(do_syscall2(__NR_clock_gettime, clk_id, (long)ts)); + } + + export long sys_wait4(int pid, int* status, int options, void* rusage) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long ret; + register long a4 __asm__("r10") = (long)rusage; // pin 4th arg + asm volatile("mov $61, %%rax \n\tsyscall" + : "=a"(ret) + : "D"(pid), "S"(status), "d"(options), "r"(a4) + : "rcx","r11","memory"); + return ret; // <0 → -errno +#else + return -38; // ENOSYS +#endif + } +} diff --git a/src/rt/linux/syscall.cppm b/src/rt/linux/syscall.cppm new file mode 100644 index 0000000..26a2623 --- /dev/null +++ b/src/rt/linux/syscall.cppm @@ -0,0 +1,24 @@ +export module rt.linux.syscall; + +// Decls for the .S shims +extern "C" long __rt_linux_syscall0(long); +extern "C" long __rt_linux_syscall1(long,long); +extern "C" long __rt_linux_syscall2(long,long,long); +extern "C" long __rt_linux_syscall3(long,long,long,long); +extern "C" long __rt_linux_syscall4(long,long,long,long,long); +extern "C" long __rt_linux_syscall5(long,long,long,long,long,long); +extern "C" long __rt_linux_syscall6(long,long,long,long,long,long,long); + +namespace rt::linux { + export inline long sc0(long nr) { return __rt_linux_syscall0(nr); } + export inline long sc1(long nr, long a1) { return __rt_linux_syscall1(nr,a1); } + export inline long sc2(long nr, long a1, long a2) { return __rt_linux_syscall2(nr,a1,a2); } + export inline long sc3(long nr, long a1, long a2, long a3) { return __rt_linux_syscall3(nr,a1,a2,a3); } + export inline long sc4(long nr, long a1, long a2, long a3, long a4) { return __rt_linux_syscall4(nr,a1,a2,a3,a4); } + export inline long sc5(long nr, long a1, long a2, long a3, long a4, long a5) { + return __rt_linux_syscall5(nr,a1,a2,a3,a4,a5); + } + export inline long sc6(long nr, long a1, long a2, long a3, long a4, long a5, long a6) { + return __rt_linux_syscall6(nr,a1,a2,a3,a4,a5,a6); + } +} diff --git a/src/rt/linux/syscall_shim.S b/src/rt/linux/syscall_shim.S new file mode 100644 index 0000000..6b1fd89 --- /dev/null +++ b/src/rt/linux/syscall_shim.S @@ -0,0 +1,79 @@ + .text + + # long __rt_linux_syscall0(long nr) + .globl __rt_linux_syscall0 + .type __rt_linux_syscall0, @function +__rt_linux_syscall0: + mov %rdi, %rax # nr + syscall + ret + + # long __rt_linux_syscall1(long nr, long a1) + .globl __rt_linux_syscall1 + .type __rt_linux_syscall1, @function +__rt_linux_syscall1: + mov %rdi, %rax # nr + mov %rsi, %rdi # a1 + syscall + ret + + # long __rt_linux_syscall2(long nr, long a1, long a2) + .globl __rt_linux_syscall2 + .type __rt_linux_syscall2, @function +__rt_linux_syscall2: + mov %rdi, %rax + mov %rsi, %rdi + mov %rdx, %rsi + syscall + ret + + # long __rt_linux_syscall3(long nr, long a1, long a2, long a3) + .globl __rt_linux_syscall3 + .type __rt_linux_syscall3, @function +__rt_linux_syscall3: + mov %rdi, %rax + mov %rsi, %rdi + mov %rdx, %rsi + mov %rcx, %rdx # SysV a3 is rcx in our C ABI position + syscall + ret + + # long __rt_linux_syscall4(long nr, long a1, long a2, long a3, long a4) + .globl __rt_linux_syscall4 + .type __rt_linux_syscall4, @function +__rt_linux_syscall4: + mov %rdi, %rax + mov %rsi, %rdi + mov %rdx, %rsi + mov %rcx, %rdx + mov %r8, %r10 # kernel needs arg4 in r10 + syscall + ret + + # long __rt_linux_syscall5(long nr, long a1, long a2, long a3, long a4, long a5) + .globl __rt_linux_syscall5 + .type __rt_linux_syscall5, @function +__rt_linux_syscall5: + mov %rdi, %rax + mov %rsi, %rdi + mov %rdx, %rsi + mov %rcx, %rdx + mov %r8, %r10 + # a5 already in r9? No: SysV puts it in r8; kernel wants r8. Keep r8. + mov %r9, %r8 + syscall + ret + + # long __rt_linux_syscall6(long nr, long a1, long a2, long a3, long a4, long a5, long a6) + .globl __rt_linux_syscall6 + .type __rt_linux_syscall6, @function +__rt_linux_syscall6: + mov %rdi, %rax + mov %rsi, %rdi + mov %rdx, %rsi + mov %rcx, %rdx + mov %r8, %r10 + mov %r9, %r8 + mov 8(%rsp), %r9 # a6 is on stack at call-site per SysV; load to r9 + syscall + ret diff --git a/src/rt/linux/sysnums.cppm b/src/rt/linux/sysnums.cppm new file mode 100644 index 0000000..44a0506 --- /dev/null +++ b/src/rt/linux/sysnums.cppm @@ -0,0 +1,23 @@ +export module rt.linux.sysnums; + +namespace rt::linux { + // minimal set; extend as needed + export constexpr long __NR_read = 0; + export constexpr long __NR_write = 1; + export constexpr long __NR_openat = 257; + export constexpr long __NR_close = 3; + export constexpr long __NR_fstat = 5; // newfstatat is 262 if you need it + export constexpr long __NR_lseek = 8; + export constexpr long __NR_mmap = 9; + export constexpr long __NR_mprotect = 10; + export constexpr long __NR_munmap = 11; + export constexpr long __NR_nanosleep = 35; + export constexpr long __NR_clock_gettime = 228; + export constexpr long __NR_exit = 60; + export constexpr long __NR_newfstatat = 262; + export constexpr long __NR_getdents64 = 217; + export constexpr long __NR_getrandom = 318; + export constexpr long __NR_getpid = 39; + export constexpr long __NR_getuid = 102; + export constexpr long __NR_geteuid = 107; +} diff --git a/src/rt/linux/sysnums_poll_net.cppm b/src/rt/linux/sysnums_poll_net.cppm new file mode 100644 index 0000000..0fcfcfe --- /dev/null +++ b/src/rt/linux/sysnums_poll_net.cppm @@ -0,0 +1,27 @@ +export module rt.linux.sysnums_poll_net; + +namespace rt::linux { + // fds & polling + export constexpr long __NR_dup = 32; + export constexpr long __NR_dup3 = 292; + export constexpr long __NR_pipe2 = 293; + export constexpr long __NR_poll = 7; + export constexpr long __NR_ppoll = 271; + + // epoll + export constexpr long __NR_epoll_create1 = 291; + export constexpr long __NR_epoll_ctl = 233; + export constexpr long __NR_epoll_pwait = 281; // epoll_wait is 232 + + // sockets + export constexpr long __NR_socket = 41; + export constexpr long __NR_connect = 42; + export constexpr long __NR_accept4 = 288; + export constexpr long __NR_bind = 49; + export constexpr long __NR_listen = 50; + export constexpr long __NR_setsockopt= 54; + export constexpr long __NR_getsockopt= 55; + export constexpr long __NR_sendto = 44; + export constexpr long __NR_recvfrom = 45; + export constexpr long __NR_shutdown = 48; +} diff --git a/src/rt/linux/sysnums_proc.cppm b/src/rt/linux/sysnums_proc.cppm new file mode 100644 index 0000000..2a8d29e --- /dev/null +++ b/src/rt/linux/sysnums_proc.cppm @@ -0,0 +1,26 @@ +export module rt.linux.sysnums_proc; + +namespace rt::linux { + // process + export constexpr long __NR_fork = 57; + export constexpr long __NR_vfork = 58; + export constexpr long __NR_execve = 59; + export constexpr long __NR_wait4 = 61; + + // cwd / path + export constexpr long __NR_getcwd = 79; + export constexpr long __NR_chdir = 80; + export constexpr long __NR_readlinkat = 267; + + // fs admin (subset) + export constexpr long __NR_unlinkat = 263; + export constexpr long __NR_linkat = 265; + export constexpr long __NR_symlinkat= 266; + export constexpr long __NR_renameat2= 316; + export constexpr long __NR_utimensat= 280; + + // signals + export constexpr long __NR_rt_sigaction = 13; + export constexpr long __NR_rt_sigprocmask = 14; + // tgkill already in sysnums_thread +} diff --git a/src/rt/linux/sysnums_thread.cppm b/src/rt/linux/sysnums_thread.cppm new file mode 100644 index 0000000..1335deb --- /dev/null +++ b/src/rt/linux/sysnums_thread.cppm @@ -0,0 +1,9 @@ +export module rt.linux.sysnums_thread; + +namespace rt::linux { + export constexpr long __NR_clone = 56; + export constexpr long __NR_futex = 202; + export constexpr long __NR_set_tid_address = 218; + export constexpr long __NR_tgkill = 234; + export constexpr long __NR_sched_yield = 24; +} diff --git a/src/rt/mem.cppm b/src/rt/mem.cppm new file mode 100644 index 0000000..31c060c --- /dev/null +++ b/src/rt/mem.cppm @@ -0,0 +1,27 @@ +export module rt.mem; + +export namespace rt::mem { + void* memcpy(void* dst, const void* src, __SIZE_TYPE__ n) noexcept { + auto* d = static_cast(dst); + auto* s = static_cast(src); + for (__SIZE_TYPE__ i = 0; i < n; ++i) d[i] = s[i]; + return dst; + } + + void* memmove(void* dst, const void* src, __SIZE_TYPE__ n) noexcept { + auto* d = static_cast(dst); + auto* s = static_cast(src); + if (d < s) { + for (__SIZE_TYPE__ i = 0; i < n; ++i) d[i] = s[i]; + } else if (d > s) { + for (__SIZE_TYPE__ i = n; i > 0; --i) d[i-1] = s[i-1]; + } + return dst; + } + + void* memset(void* dst, int c, __SIZE_TYPE__ n) noexcept { + auto* d = static_cast(dst); + for (__SIZE_TYPE__ i = 0; i < n; ++i) d[i] = static_cast(c); + return dst; + } +} diff --git a/src/rt/mmap.cppm b/src/rt/mmap.cppm new file mode 100644 index 0000000..6a4a649 --- /dev/null +++ b/src/rt/mmap.cppm @@ -0,0 +1,34 @@ +export module rt.mmap; +import rt.errno; + +#if defined(__linux__) && defined(__x86_64__) +import rt.linux.sys; +#endif + +namespace rt { + // Common PROT/FLAGS are passed through verbatim for Linux; define your own in a header later. + export void* mmap(void* addr, unsigned long len, long prot, long flags, int fd, long off) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r = linux::sys_mmap(addr, len, prot, flags, fd, off); + return (r == -1) ? (void*)0 : (void*)r; +#else + set_errno(38); return (void*)0; +#endif + } + + export long munmap(void* addr, unsigned long len) noexcept { +#if defined(__linux__) && defined(__x86_64__) + return linux::sys_munmap(addr, len); +#else + set_errno(38); return -1; +#endif + } + + export long mprotect(void* addr, unsigned long len, long prot) noexcept { +#if defined(__linux__) && defined(__x86_64__) + return linux::sys_mprotect(addr, len, prot); +#else + set_errno(38); return -1; +#endif + } +} diff --git a/src/rt/net.cppm b/src/rt/net.cppm new file mode 100644 index 0000000..ded1bd7 --- /dev/null +++ b/src/rt/net.cppm @@ -0,0 +1,142 @@ +export module rt.net; + +import rt.errno; +import rt.types; + +#if defined(__linux__) && defined(__x86_64__) + import rt.linux.sysnums_poll_net; +#endif + +namespace rt::net { + // families, types, protocols (subset) + export constexpr int AF_INET = 2; + export constexpr int SOCK_STREAM = 1; + export constexpr int SOCK_DGRAM = 2; + export constexpr int SOCK_NONBLOCK = 0x800; + export constexpr int SOCK_CLOEXEC = 0x80000; + export constexpr int IPPROTO_TCP = 6; + export constexpr int IPPROTO_UDP = 17; + + // shutdown how + export constexpr int SHUT_RD = 0; + export constexpr int SHUT_WR = 1; + export constexpr int SHUT_RDWR = 2; + + export struct in_addr { rt_u32 s_addr; }; // network byte order + export struct sockaddr { + rt_u16 sa_family; + char sa_data[14]; + }; + export struct sockaddr_in { + rt_u16 sin_family; + rt_u16 sin_port; // network byte order + in_addr sin_addr; + rt_u8 sin_zero[8]{}; + }; + + export int socket(int domain, int type, int protocol) noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r) + : "a"(rt::linux::__NR_socket), "D"(domain), "S"(type), "d"(protocol) + : "rcx","r11","memory"); + if (r<0){ rt::set_errno((int)-r); return -1; } return (int)r; + #else + rt::set_errno(38); return -1; + #endif + } + + export int connect(int fd, const sockaddr* addr, unsigned int len) noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r) + : "a"(rt::linux::__NR_connect), "D"(fd), "S"(addr), "d"(len) + : "rcx","r11","memory"); + if (r<0){ rt::set_errno((int)-r); return -1; } return 0; + #else + rt::set_errno(38); return -1; + #endif + } + + export int bind(int fd, const sockaddr* addr, unsigned int len) noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r) + : "a"(rt::linux::__NR_bind), "D"(fd), "S"(addr), "d"(len) + : "rcx","r11","memory"); + if (r<0){ rt::set_errno((int)-r); return -1; } return 0; + #else + rt::set_errno(38); return -1; + #endif + } + + export int listen(int fd, int backlog) noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r) + : "a"(rt::linux::__NR_listen), "D"(fd), "S"(backlog) + : "rcx","r11","memory"); + if (r<0){ rt::set_errno((int)-r); return -1; } return 0; + #else + rt::set_errno(38); return -1; + #endif + } + + export int accept4(int fd, sockaddr* addr, unsigned int* len, int flags) noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; register long r10 __asm__("r10") = flags; + asm volatile("syscall":"=a"(r) + : "a"(rt::linux::__NR_accept4), "D"(fd), "S"(addr), "d"(len), "r"(r10) + : "rcx","r11","memory"); + if (r<0){ rt::set_errno((int)-r); return -1; } return (int)r; + #else + rt::set_errno(38); return -1; + #endif + } + + export long sendto(int fd, const void* buf, unsigned long len, int flags, + const sockaddr* to, unsigned int tolen) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; + register long r10 __asm__("r10") = (long)flags; // 4th + register long r8 __asm__("r8") = (long)to; // 5th + register long r9 __asm__("r9") = (long)tolen; // 6th + asm volatile("syscall" + : "=a"(r) + : "a"(rt::linux::__NR_sendto), + "D"(fd), "S"(buf), "d"(len), + "r"(r10), "r"(r8), "r"(r9) + : "rcx","r11","memory"); + if (r < 0) { rt::set_errno((int)-r); return -1; } return r; +#else + rt::set_errno(38); return -1; +#endif + } + + export long recvfrom(int fd, void* buf, unsigned long len, int flags, + sockaddr* from, unsigned int* fromlen) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; + register long r10 __asm__("r10") = (long)flags; // 4th + register long r8 __asm__("r8") = (long)from; // 5th + register long r9 __asm__("r9") = (long)fromlen; // 6th + asm volatile("syscall" + : "=a"(r) + : "a"(rt::linux::__NR_recvfrom), + "D"(fd), "S"(buf), "d"(len), + "r"(r10), "r"(r8), "r"(r9) + : "rcx","r11","memory"); + if (r < 0) { rt::set_errno((int)-r); return -1; } return r; +#else + rt::set_errno(38); return -1; +#endif + } + + + export int shutdown(int fd, int how) noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r) + : "a"(rt::linux::__NR_shutdown), "D"(fd), "S"(how) + : "rcx","r11","memory"); + if (r<0){ rt::set_errno((int)-r); return -1; } return 0; + #else + rt::set_errno(38); return -1; + #endif + } +} diff --git a/src/rt/panic.cppm b/src/rt/panic.cppm new file mode 100644 index 0000000..8a1915b --- /dev/null +++ b/src/rt/panic.cppm @@ -0,0 +1,15 @@ +export module rt.panic; +import rt.sys; +import rt.string; + +export namespace rt { + [[noreturn]] void panic(const char* msg) noexcept { + sys::write(2, msg, string::strlen(msg)); + sys::exit(1); + __builtin_unreachable(); + } + + [[noreturn]] void unreachable() noexcept { + panic("rt: unreachable reached\n"); + } +} diff --git a/src/rt/path.cppm b/src/rt/path.cppm new file mode 100644 index 0000000..33e61c7 --- /dev/null +++ b/src/rt/path.cppm @@ -0,0 +1,51 @@ +export module rt.path; + +import rt.mem; +import rt.string; + +namespace rt { + // returns ptr to base name within given C-string (no allocation) + export const char* basename(const char* path) noexcept { + if (!path || !*path) return path ? path : ""; + const char* p = path; + const char* base = path; + for (; *p; ++p) if (*p == '/') base = p + 1; + return *base ? base : base - 1; // if path ends with '/', keep last segment as "" + } + + // writes dirname of path into out (buffer size out_cap). returns length written, or -1 if too small. + export long dirname(const char* path, char* out, unsigned long out_cap) noexcept { + if (!path || !*path) { if (out_cap) { out[0] = '.'; if (out_cap>1) out[1]=0; } return (out_cap>=2)?1:-1; } + const char* end = path; + for (; *end; ++end) {} + // strip trailing slashes + while (end > path && end[-1] == '/') --end; + // find previous slash + const char* slash = end; + while (slash > path && slash[-1] != '/') --slash; + unsigned long len = (slash == path) ? 1 : (unsigned long)(slash - path - (path[0]=='/'?0:0)); + if (slash == path) { // root or no slash + if (out_cap < 2) return -1; + out[0] = '/'; out[1] = 0; return 1; + } + if (len >= out_cap) return -1; + for (unsigned long i = 0; i < len; ++i) out[i] = path[i]; + out[len] = 0; + return static_cast(len); + } + + // join a + "/" + b into out; handles slashes simply + export long join(const char* a, const char* b, char* out, unsigned long cap) noexcept { + unsigned long la = 0; while (a && a[la]) ++la; + unsigned long lb = 0; while (b && b[lb]) ++lb; + bool need_sep = la && lb && a[la-1] != '/' && b[0] != '/'; + unsigned long need = la + (need_sep?1:0) + lb + 1; + if (need > cap) return -1; + for (unsigned long i = 0; i < la; ++i) out[i] = a[i]; + unsigned long k = la; + if (need_sep) out[k++] = '/'; + for (unsigned long i = 0; i < lb; ++i) out[k++] = b[i]; + out[k] = 0; + return static_cast(k); + } +} diff --git a/src/rt/pathops.cppm b/src/rt/pathops.cppm new file mode 100644 index 0000000..40729f9 --- /dev/null +++ b/src/rt/pathops.cppm @@ -0,0 +1,227 @@ +export module rt.pathops; + +import rt.errno; +import rt.types; +import rt.constants; +import rt.cstring; + +#if defined(__linux__) && defined(__x86_64__) + import rt.linux.sysnums_proc; +#endif + +namespace rt::pathops { + // readlinkat(dfd, path, buf, bufsz) — returns length (no NUL), or -1 w/ errno + export long readlinkat(int dfd, const char* path, char* buf, rt_usize bufsz) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; + register long r10 __asm__("r10") = (long)bufsz; // arg4 + asm volatile("syscall" + : "=a"(r) + : "a"(rt::linux::__NR_readlinkat), + "D"(dfd), "S"(path), "d"(buf), + "r"(r10) // bind r10 in THIS asm + : "rcx","r11","memory"); + if (r < 0) { rt::set_errno((int)-r); return -1; } + return r; // bytes (no NUL) +#else + rt::set_errno(38); return -1; +#endif + } + + + // simple helpers (unlink/link/symlink/rename/utimens) + export int unlinkat(int dfd, const char* path, int flags) noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r) + : "a"(rt::linux::__NR_unlinkat), "D"(dfd), "S"(path), "d"(flags) + : "rcx","r11","memory"); + if (r<0){ rt::set_errno((int)-r); return -1; } return 0; + #else + rt::set_errno(38); return -1; + #endif + } + export int linkat(int odfd, const char* op, int ndfd, const char* np, int flags) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; + register long r10 __asm__("r10") = (long)np; // arg4 + register long r8 __asm__("r8") = (long)flags; // arg5 + asm volatile("syscall" + : "=a"(r) + : "a"(rt::linux::__NR_linkat), + "D"(odfd), "S"(op), "d"(ndfd), + "r"(r10), "r"(r8) + : "rcx","r11","memory"); + if (r < 0) { rt::set_errno((int)-r); return -1; } + return 0; +#else + rt::set_errno(38); return -1; +#endif + } + + export int symlinkat(const char* target, int dfd, const char* linkpath) noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r) + : "a"(rt::linux::__NR_symlinkat), "D"(target), "S"(dfd), "d"(linkpath) + : "rcx","r11","memory"); + if (r<0){ rt::set_errno((int)-r); return -1; } return 0; + #else + rt::set_errno(38); return -1; + #endif + } + export int renameat2(int odfd, const char* op, int ndfd, const char* np, unsigned flags) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; + register long r10 __asm__("r10") = (long)np; // arg4 + register long r8 __asm__("r8") = (long)flags; // arg5 + asm volatile("syscall" + : "=a"(r) + : "a"(rt::linux::__NR_renameat2), + "D"(odfd), "S"(op), "d"(ndfd), + "r"(r10), "r"(r8) + : "rcx","r11","memory"); + if (r < 0) { rt::set_errno((int)-r); return -1; } + return 0; +#else + rt::set_errno(38); return -1; +#endif + } + + + // realpath (no allocation): resolves symlinks up to max_depth, writes absolute path to out. + // returns out on success or nullptr on error; sets errno. + export char* realpath_at(int dfd, const char* path, char* out, rt_usize out_cap, int max_depth) noexcept { + if (!path || !out || out_cap == 0) { rt::set_errno(22); return (char*)0; } // EINVAL + + // Scratch that lives for the whole call + char rem[4096]; + char target[4096]; + + // Seed output as absolute (normalize to absolute) + out[0] = '/'; out[1] = 0; + rt_usize out_len = 1; + + // Initialize remaining path with a collapsed copy of `path` + { + const char* s = path; + // collapse leading '/' + while (*s == '/') ++s; + rt_usize k = 0; + for (; *s && k < sizeof(rem) - 1; ++s) rem[k++] = *s; + rem[k] = 0; + } + + auto append_seg = [&](const char* seg, rt_usize seg_len) -> bool { + if (out_len > 1 && out[out_len - 1] != '/') { + if (out_len + 1 >= out_cap) { rt::set_errno(34); return false; } // ERANGE + out[out_len++] = '/'; + } + if (out_len + seg_len >= out_cap) { rt::set_errno(34); return false; } + for (rt_usize i = 0; i < seg_len; ++i) out[out_len++] = seg[i]; + out[out_len] = 0; + return true; + }; + + while (true) { + // skip leading slashes in rem + const char* p = rem; + while (*p == '/') ++p; + if (!*p) break; + + // capture next segment into a temp buffer BEFORE we mutate `rem` + const char* seg_ptr = p; + while (*p && *p != '/') ++p; + rt_usize seg_len = (rt_usize)(p - seg_ptr); + + if (seg_len == 0) { + // only slashes left + // advance rem to end + rem[0] = 0; + break; + } + + // Copy segment safely + char segbuf[512]; + if (seg_len >= sizeof(segbuf)) { rt::set_errno(34); return (char*)0; } // ERANGE + for (rt_usize i = 0; i < seg_len; ++i) segbuf[i] = seg_ptr[i]; + + // Advance `p` over any subsequent slashes and compact into `rem` + while (*p == '/') ++p; + { + rt_usize i = 0; + for (; p[i] && i < sizeof(rem) - 1; ++i) rem[i] = p[i]; + rem[i] = 0; + } + + // Handle "." and ".." + if (seg_len == 1 && segbuf[0] == '.') continue; + if (seg_len == 2 && segbuf[0] == '.' && segbuf[1] == '.') { + if (out_len > 1) { + if (out[out_len - 1] == '/') --out_len; + while (out_len > 1 && out[out_len - 1] != '/') --out_len; + out[out_len] = 0; + } + continue; + } + + // Append this segment + if (!append_seg(segbuf, seg_len)) return (char*)0; + + // Try resolving symlink at current `out` + if (max_depth > 0) { + long n; + // readlinkat(dfd, out, target, sizeof(target)-1) with arg4 in r10 + #if defined(__linux__) && defined(__x86_64__) + { + register long r10 __asm__("r10") = (long)(sizeof(target) - 1); + asm volatile("syscall" + : "=a"(n) + : "a"(rt::linux::__NR_readlinkat), + "D"(rt::AT_FDCWD), "S"(out), "d"(target), "r"(r10) + : "rcx","r11","memory"); + } + #else + n = -38; // ENOSYS + #endif + if (n < 0) { + // not a symlink or error: ignore unless it's a hard error we care about + } else if (n > 0) { + target[n] = 0; + // Absolute target resets out; relative pops the last segment + if (target[0] == '/') { + out_len = 1; out[0] = '/'; out[1] = 0; + } else { + if (out_len && out[out_len - 1] == '/') --out_len; + while (out_len > 1 && out[out_len - 1] != '/') --out_len; + out[out_len] = 0; + } + + // Compose new remaining path: target + (existing rem if any) + char combined[4096]; + rt_usize k = 0; + // copy target + for (; target[k] && k < sizeof(combined) - 1; ++k) combined[k] = target[k]; + // add '/' between target and rem if both non-empty + if (combined[0] && rem[0] && k < sizeof(combined) - 1) combined[k++] = '/'; + for (rt_usize i = 0; rem[i] && k < sizeof(combined) - 1; ++i) combined[k++] = rem[i]; + combined[k] = 0; + + // overwrite rem with combined + rt_usize i = 0; + for (; combined[i] && i < sizeof(rem) - 1; ++i) rem[i] = combined[i]; + rem[i] = 0; + + --max_depth; + continue; // process the new path + } + } + } + + if (out_len > 1 && out[out_len - 1] == '/') { out[--out_len] = 0; } + return out; + } + + // convenience realpath relative to CWD + export char* realpath(const char* path, char* out, rt_usize out_cap, int max_depth = 16) noexcept { + return realpath_at(rt::AT_FDCWD, path, out, out_cap, max_depth); + } +} diff --git a/src/rt/platform/darwin_macho.cppm b/src/rt/platform/darwin_macho.cppm new file mode 100644 index 0000000..c4b0156 --- /dev/null +++ b/src/rt/platform/darwin_macho.cppm @@ -0,0 +1,10 @@ +export module rt.platform.darwin_macho; +import rt.panic; +import rt.sys; + +export namespace rt::platform::darwin_macho { + const rt::sys::vtable* vtab() noexcept { + // TODO: implement macOS xnu syscall veneer in future + rt::panic("rt: Darwin backend not implemented yet\n"); + } +} diff --git a/src/rt/platform/linux_x86_64.cppm b/src/rt/platform/linux_x86_64.cppm new file mode 100644 index 0000000..29ea63c --- /dev/null +++ b/src/rt/platform/linux_x86_64.cppm @@ -0,0 +1,37 @@ +export module rt.platform.linux_x86_64; +import rt.sys; + +namespace { + inline long sys_write(long fd, long buf, long len) { + long ret; + asm volatile( + "syscall" + : "=a"(ret) + : "a"(1), "D"(fd), "S"(buf), "d"(len) + : "rcx", "r11", "memory" + ); + return ret; + } + [[noreturn]] inline void sys_exit(long code) { + asm volatile( + "syscall" + : + : "a"(60), "D"(code) + : "rcx", "r11", "memory" + ); + __builtin_unreachable(); + } + + constexpr rt::sys::vtable LINUX_VT = { + /* write */ [](int fd, const void* buf, __SIZE_TYPE__ len) noexcept -> long { + return sys_write(fd, (long)buf, (long)len); + }, + /* exit */ [](int code) noexcept -> void { + sys_exit(code); + } + }; +} + +export namespace rt::platform::linux_x86_64 { + const rt::sys::vtable* vtab() noexcept { return &LINUX_VT; } +} diff --git a/src/rt/platform/windows_pe.cppm b/src/rt/platform/windows_pe.cppm new file mode 100644 index 0000000..e0ddaf3 --- /dev/null +++ b/src/rt/platform/windows_pe.cppm @@ -0,0 +1,10 @@ +export module rt.platform.windows_pe; +import rt.panic; +import rt.sys; + +export namespace rt::platform::windows_pe { + const rt::sys::vtable* vtab() noexcept { + // TODO: implement using ntdll Zw/Nt calls in future + rt::panic("rt: Windows backend not implemented yet\n"); + } +} diff --git a/src/rt/poll.cppm b/src/rt/poll.cppm new file mode 100644 index 0000000..ba8f2d0 --- /dev/null +++ b/src/rt/poll.cppm @@ -0,0 +1,51 @@ +export module rt.poll; + +import rt.errno; + +#if defined(__linux__) && defined(__x86_64__) +import rt.linux.sysnums_poll_net; +#endif + +namespace rt::polling { + export struct pollfd { int fd; short events; short revents; }; + export constexpr short POLLIN = 0x001; + export constexpr short POLLOUT = 0x004; + export constexpr short POLLERR = 0x008; + export constexpr short POLLHUP = 0x010; + export constexpr short POLLNVAL= 0x020; + + // poll(fds, nfds, timeout_ms) + export int poll(pollfd* fds, unsigned long nfds, int timeout_ms) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r) + : "a"(rt::linux::__NR_poll), "D"(fds), "S"(nfds), "d"(timeout_ms) + : "rcx","r11","memory"); + if (r<0){ rt::set_errno((int)-r); return -1; } return (int)r; +#else + rt::set_errno(38); return -1; +#endif + } + + // ppoll(fds, nfds, ts, sigmask) + export struct timespec { long tv_sec; long tv_nsec; }; + export int ppoll(pollfd* fds, unsigned long nfds, + const timespec* ts, const void* sigmask, + unsigned long sigsetsize) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; + register long r10 __asm__("r10") = (long)sigmask; // 4th + register long r8 __asm__("r8") = (long)sigsetsize; // 5th + register long r9 __asm__("r9") = 0L; // 6th (unused) + asm volatile("syscall" + : "=a"(r) + : "a"(rt::linux::__NR_ppoll), + "D"(fds), "S"(nfds), "d"(ts), + "r"(r10), "r"(r8), "r"(r9) + : "rcx","r11","memory"); + if (r < 0) { rt::set_errno((int)-r); return -1; } return (int)r; +#else + rt::set_errno(38); return -1; +#endif + } + +} diff --git a/src/rt/printf.cppm b/src/rt/printf.cppm new file mode 100644 index 0000000..78b5e56 --- /dev/null +++ b/src/rt/printf.cppm @@ -0,0 +1,20 @@ +export module rt.printf; + +import rt.format; +import rt.fs; + +namespace rt::printf { + // sink that writes to an fd using rt::write + inline bool fd_sink(void* cookie, const char* s, unsigned long n) { + int fd = (int)(long)cookie; + long w = rt::write(fd, s, n); + return (w == (long)n); + } + + export long dprintf(int fd, const char* fmt, ...) { + __builtin_va_list ap; __builtin_va_start(ap, fmt); + long r = rt::format::vprint(&fd_sink, (void*)(long)fd, fmt, ap); + __builtin_va_end(ap); + return r; + } +} diff --git a/src/rt/proc_exec.cppm b/src/rt/proc_exec.cppm new file mode 100644 index 0000000..0142582 --- /dev/null +++ b/src/rt/proc_exec.cppm @@ -0,0 +1,64 @@ +export module rt.proc_exec; + +import rt.errno; +import rt.types; + +#if defined(__linux__) && defined(__x86_64__) + import rt.linux.sysnums_proc; + import rt.linux.sys; +#endif + +namespace rt::proc { + // wait status helpers (classic layout) + export inline bool WIFEXITED(int status) { return ((status & 0x7f) == 0); } + export inline rt_u8 WEXITSTATUS(int s) { return (rt_u8)((s >> 8) & 0xff); } + export inline bool WIFSIGNALED(int s) { return (((s & 0x7f) != 0) && (((s & 0x7f)+1) >> 1) > 0); } + export inline rt_u8 WTERMSIG(int s) { return (rt_u8)(s & 0x7f); } + export constexpr int WNOHANG = 1; + + + export int fork() noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r):"a"(rt::linux::__NR_fork):"rcx","r11","memory"); + if (r < 0) { rt::set_errno((int)-r); return -1; } return (int)r; // 0 in child, pid in parent + #else + rt::set_errno(38); return -1; + #endif + } + + export int vfork() noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r):"a"(rt::linux::__NR_vfork):"rcx","r11","memory"); + if (r < 0) { rt::set_errno((int)-r); return -1; } return (int)r; + #else + rt::set_errno(38); return -1; + #endif + } + + // argv/envp must be null-terminated vectors + export int execve(const char* path, char* const argv[], char* const envp[]) noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r) + : "a"(rt::linux::__NR_execve), "D"(path), "S"(argv), "d"(envp) + : "rcx","r11","memory"); + // on success, no return; on failure, -errno + rt::set_errno((int)-r); return -1; + #else + rt::set_errno(38); return -1; + #endif + } + + export int wait4(int pid, int* status, int options) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r = rt::linux::sys_wait4(pid, status, options, nullptr); + if (r < 0) { rt::set_errno((int)-r); return -1; } + return (int)r; // child pid (or 0 if WNOHANG and no state changes) +#else + rt::set_errno(38); return -1; +#endif + } + + export int waitpid(int pid, int* status, int options) noexcept { + return wait4(pid, status, options); + } +} diff --git a/src/rt/process.cppm b/src/rt/process.cppm new file mode 100644 index 0000000..aa3e63a --- /dev/null +++ b/src/rt/process.cppm @@ -0,0 +1,34 @@ +export module rt.process; + +#if defined(__linux__) && defined(__x86_64__) +import rt.linux.sysnums; +#endif + +namespace rt { + export int getpid() noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall" : "=a"(r) : "a"(rt::linux::__NR_getpid) : "rcx","r11","memory"); + return static_cast(r); +#else + return 0; +#endif + } + + export unsigned getuid() noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall" : "=a"(r) : "a"(rt::linux::__NR_getuid) : "rcx","r11","memory"); + return static_cast(r); +#else + return 0; +#endif + } + + export unsigned geteuid() noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall" : "=a"(r) : "a"(rt::linux::__NR_geteuid) : "rcx","r11","memory"); + return static_cast(r); +#else + return 0; +#endif + } +} diff --git a/src/rt/random.cppm b/src/rt/random.cppm new file mode 100644 index 0000000..8fbc595 --- /dev/null +++ b/src/rt/random.cppm @@ -0,0 +1,23 @@ +export module rt.random; + +import rt.errno; + +#if defined(__linux__) && defined(__x86_64__) +import rt.linux.sysnums; +#endif + +namespace rt { + // flags: 0 / GRND_NONBLOCK(0x0001) / GRND_RANDOM(0x0002) + export long getrandom(void* buf, unsigned long len, unsigned int flags) noexcept { +#if defined(__linux__) && defined(__x86_64__) + auto call = [](long n, long a, long b, long c){ + long r; asm volatile("syscall" : "=a"(r) : "a"(n),"D"(a),"S"(b),"d"(c) : "rcx","r11","memory"); return r; + }; + long r = call(rt::linux::__NR_getrandom, (long)buf, (long)len, flags); + if (r < 0) { set_errno((int)-r); return -1; } + return r; +#else + set_errno(38); return -1; +#endif + } +} diff --git a/src/rt/sched.cppm b/src/rt/sched.cppm new file mode 100644 index 0000000..3b0615a --- /dev/null +++ b/src/rt/sched.cppm @@ -0,0 +1,15 @@ +export module rt.sched; + +#if defined(__linux__) && defined(__x86_64__) +import rt.thread; // provides sched_yield() +#endif + +namespace rt::sched { + export int yield() noexcept { +#if defined(__linux__) && defined(__x86_64__) + return rt::thread::sched_yield(); +#else + return 0; +#endif + } +} diff --git a/src/rt/signals.cppm b/src/rt/signals.cppm new file mode 100644 index 0000000..72d3aa6 --- /dev/null +++ b/src/rt/signals.cppm @@ -0,0 +1,82 @@ +export module rt.signals; + +import rt.errno; +import rt.types; + +#if defined(__linux__) && defined(__x86_64__) + import rt.linux.sysnums_proc; + import rt.linux.sysnums_thread; // tgkill +#endif + +namespace rt::sig { + // Kernel-sized mask for x86-64: 64 signals → 64-bit mask (8 bytes) + export struct sigset_t { rt_u64 mask; }; + + // how + export constexpr int SIG_BLOCK = 0; + export constexpr int SIG_UNBLOCK = 1; + export constexpr int SIG_SETMASK = 2; + + // common signals (subset) + export constexpr int SIGPIPE = 13; + export constexpr int SIGTERM = 15; + export constexpr int SIGINT = 2; + export constexpr int SIGKILL = 9; + export constexpr int SIGHUP = 1; + export constexpr int SIGCHLD = 17; + + export using sighandler_t = void(*)(int); + + // Kernel rt_sigaction layout on x86-64 + export struct k_sigaction { + sighandler_t sa_handler; + rt_u64 sa_flags; + void (*sa_restorer)(void); // may be null; SA_RESTORER not required here + sigset_t sa_mask; + }; + + export int sigaction(int signum, const k_sigaction* act, k_sigaction* old) noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; + // size of *kernel* sigset_t = 8 bytes on x86-64 + register long r10 __asm__("r10") = (long)sizeof(sigset_t); + asm volatile("syscall" + : "=a"(r) + : "a"(rt::linux::__NR_rt_sigaction), + "D"(signum), "S"(act), "d"(old), "r"(r10) + : "rcx","r11","memory"); + if (r < 0) { rt::set_errno((int)-r); return -1; } return 0; + #else + rt::set_errno(38); return -1; + #endif + } + + export int sigprocmask(int how, const sigset_t* set, sigset_t* old) noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; + register long r10 __asm__("r10") = (long)sizeof(sigset_t); // 8 bytes + asm volatile("syscall" + : "=a"(r) + : "a"(rt::linux::__NR_rt_sigprocmask), + "D"(how), "S"(set), "d"(old), "r"(r10) + : "rcx","r11","memory"); + if (r < 0) { rt::set_errno((int)-r); return -1; } return 0; + #else + rt::set_errno(38); return -1; + #endif + } + + export int tgkill(int tgid, int tid, int sig) noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; + asm volatile("syscall" + : "=a"(r) + : "a"(rt::linux::__NR_tgkill), + "D"(tgid), "S"(tid), "d"(sig) + : "rcx","r11","memory"); + if (r < 0) { rt::set_errno((int)-r); return -1; } return 0; + #else + rt::set_errno(38); return -1; + #endif + } +} diff --git a/src/rt/snprintf.cppm b/src/rt/snprintf.cppm new file mode 100644 index 0000000..c1146bd --- /dev/null +++ b/src/rt/snprintf.cppm @@ -0,0 +1,45 @@ +export module rt.snprintf; + +import rt.format; // must provide: long vprint(bool(*sink)(void*, const char*, unsigned long), +// void* cookie, const char* fmt, __builtin_va_list ap) + +namespace rt::printf { + + export struct BufSink { + char* dst; + unsigned long cap; // total capacity (n) + unsigned long len; // bytes actually stored (<= cap ? cap-1 : cap-1) + }; + + // Always return true so rt.format::vprint can count the full "would-have-written" length. + static bool sink_write(void* cookie, const char* s, unsigned long n) { + auto* bs = (BufSink*)cookie; + if (!bs || !bs->dst || bs->cap == 0) return true; // counting only, no writes + + // space left for payload keeping room for the final NUL + unsigned long room = (bs->len < bs->cap) ? (bs->cap - 1 - bs->len) : 0; + unsigned long take = n < room ? n : room; + for (unsigned long i = 0; i < take; ++i) bs->dst[bs->len++] = s[i]; + return true; + } + + // Returns number of chars that would have been written (excluding NUL), even if truncated. + export int vsnprintf(char* dst, unsigned long n, const char* fmt, __builtin_va_list ap) noexcept { + BufSink bs{ dst, n, 0 }; + long total = rt::format::vprint(&sink_write, (void*)&bs, fmt, ap); // total "would-have-written" + // NUL-terminate when possible per POSIX + if (dst && n) { + if (bs.len >= n) bs.len = n - 1; + dst[bs.len] = '\0'; + } + return (int)total; // If you want EOVERFLOW handling for >INT_MAX, clamp here. + } + + export int snprintf(char* dst, unsigned long n, const char* fmt, ...) noexcept { + __builtin_va_list ap; + __builtin_va_start(ap, fmt); + int r = vsnprintf(dst, n, fmt, ap); + __builtin_va_end(ap); + return r; + } +} diff --git a/src/rt/spawn.cppm b/src/rt/spawn.cppm new file mode 100644 index 0000000..f86ecef --- /dev/null +++ b/src/rt/spawn.cppm @@ -0,0 +1,31 @@ +export module rt.spawn; + +import rt.errno; +import rt.proc_exec; // fork/execve/waitpid from your module + +namespace rt::spawn { + // spawn child to run path with argv/envp; parent returns child pid (>=0) or -1 on error + export int spawn_pid(const char* path, char* const argv[], char* const envp[]) noexcept { + int pid = rt::proc::fork(); + if (pid < 0) return -1; // fork failed + if (pid == 0) { + // child + rt::proc::execve(path, (char* const*)argv, (char* const*)envp); + // if exec fails: + rt::set_errno(127); + __builtin_trap(); // or _exit(127) if you have it + } + return pid; + } + + // spawn and wait (WNOHANG=0) → returns child exit code or -1 + export int spawn_wait(const char* path, char* const argv[], char* const envp[]) noexcept { + int pid = spawn_pid(path, argv, envp); + if (pid < 0) return -1; + int st = 0; + int r = rt::proc::waitpid(pid, &st, 0); + if (r < 0) return -1; + if ( (st & 0x7f) == 0 ) return (st >> 8) & 0xff; // exit code + return -1; // signaled + } +} diff --git a/src/rt/stat.cppm b/src/rt/stat.cppm new file mode 100644 index 0000000..356295f --- /dev/null +++ b/src/rt/stat.cppm @@ -0,0 +1,61 @@ +export module rt.stat; + +import rt.errno; + +#if defined(__linux__) && defined(__x86_64__) + import rt.linux.sys; + import rt.linux.sysnums; +#endif +extern long rt_linux_do_syscall2(long, long, long); // local alias trick avoided; use wrapper below + +namespace rt { + // very small stat layout (64-bit); extend as needed + export struct stat64 { + unsigned long st_dev; + unsigned long st_ino; + unsigned long st_nlink; + unsigned int st_mode; + unsigned int st_uid; + unsigned int st_gid; + unsigned int __pad0; + unsigned long st_rdev; + long st_size; + long st_blksize; + long st_blocks; + long st_atime; long st_atime_nsec; + long st_mtime; long st_mtime_nsec; + long st_ctime; long st_ctime_nsec; + long __reserved[3]; + }; + + // fstat via legacy __NR_fstat (works on x86_64) + export long fstat(int fd, stat64* st) noexcept { + #if defined(__linux__) && defined(__x86_64__) + // reuse linux raw syscall helpers from rt.linux.sys + // We can't reach the internal helpers, so expose via thin inline in this TU: + auto call = [](long n, long a, long b) { + long r; asm volatile("syscall" : "=a"(r) : "a"(n),"D"(a),"S"(b) : "rcx","r11","memory"); return r; + }; + long r = call(rt::linux::__NR_fstat, fd, (long)st); + if (r < 0) { set_errno((int)-r); return -1; } + return r; + #else + set_errno(38); return -1; + #endif + } + + // newfstatat / fstatat(2) + export long newfstatat(int dfd, const char* path, stat64* st, int flags) noexcept { + #if defined(__linux__) && defined(__x86_64__) + auto call = [](long n, long a, long b, long c, long d){ + long r; register long r10 __asm__("r10") = d; + asm volatile("syscall" : "=a"(r) : "a"(n),"D"(a),"S"(b),"d"(c),"r"(r10) : "rcx","r11","memory"); return r; + }; + long r = call(rt::linux::__NR_newfstatat, dfd, (long)path, (long)st, flags); + if (r < 0) { set_errno((int)-r); return -1; } + return r; + #else + set_errno(38); return -1; + #endif + } +} diff --git a/src/rt/string.cppm b/src/rt/string.cppm new file mode 100644 index 0000000..d35d84d --- /dev/null +++ b/src/rt/string.cppm @@ -0,0 +1,14 @@ +export module rt.string; + +export namespace rt::string { + __SIZE_TYPE__ strlen(const char* s) noexcept { + __SIZE_TYPE__ n = 0; + while (s[n]) ++n; + return n; + } + + int strcmp(const char* a, const char* b) noexcept { + for (; *a && (*a == *b); ++a, ++b) {} + return static_cast(*a) - static_cast(*b); + } +} diff --git a/src/rt/sys.cppm b/src/rt/sys.cppm new file mode 100644 index 0000000..8168475 --- /dev/null +++ b/src/rt/sys.cppm @@ -0,0 +1,22 @@ +export module rt.sys; +import rt.abi; // keep only what you actually use + +export namespace rt::sys { + struct vtable { + long (*write)(int fd, const void* buf, __SIZE_TYPE__ len) noexcept; + [[noreturn]] void (*exit)(int code) noexcept; + }; + + inline const vtable* g = nullptr; + + long write(int fd, const void* buf, __SIZE_TYPE__ len) noexcept { + return g ? g->write(fd, buf, len) : 0L; + } + + [[noreturn]] void exit(int code) noexcept { + if (g) g->exit(code); + __builtin_trap(); // no import of rt.panic here + } + + void attach(const vtable* vt) noexcept { g = vt; } +} diff --git a/src/rt/thread.cppm b/src/rt/thread.cppm new file mode 100644 index 0000000..2656f17 --- /dev/null +++ b/src/rt/thread.cppm @@ -0,0 +1,66 @@ +export module rt.thread; + +import rt.errno; +import rt.types; +import rt.time; + +#if defined(__linux__) && defined(__x86_64__) + import rt.linux.sysnums_thread; +#endif + +namespace rt::thread { + // futex operations (subset) + export constexpr int FUTEX_WAIT = 0; + export constexpr int FUTEX_WAKE = 1; + export constexpr int FUTEX_PRIVATE_FLAG = 128; + + // low-level futex + export long futex(rt_i32* uaddr, int op, rt_i32 val, const rt::time::timespec* timeout, + rt_i32* uaddr2, rt_i32 val3) noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; + register long r10 __asm__("r10") = (long)timeout; + register long r8 __asm__("r8") = (long)uaddr2; + register long r9 __asm__("r9") = (long)val3; + asm volatile("syscall" + : "=a"(r) + : "a"(rt::linux::__NR_futex), "D"(uaddr), "S"(op), "d"(val), + "r"(r10), "r"(r8), "r"(r9) + : "rcx","r11","memory"); + if (r < 0) { rt::set_errno((int)-r); return -1; } return r; + #else + rt::set_errno(38); return -1; + #endif + } + + // sched_yield + export int sched_yield() noexcept { + #if defined(__linux__) && defined(__x86_64__) + long r; asm volatile("syscall":"=a"(r):"a"(rt::linux::__NR_sched_yield):"rcx","r11","memory"); + if (r < 0) { rt::set_errno((int)-r); return -1; } return 0; + #else + rt::set_errno(38); return -1; + #endif + } + + // minimal spin+futex mutex + export struct mutex { + // 0 = unlocked, 1 = locked + rt_i32 state{0}; + }; + + export void mutex_lock(mutex* m) noexcept { + // simple TAS spin, then futex wait + while (__atomic_exchange_n(&m->state, 1, __ATOMIC_ACQUIRE) == 1) { + // if already locked, futex WAIT until it changes + rt_i32 expected = 1; + futex(&m->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, expected, nullptr, nullptr, 0); + } + } + + export void mutex_unlock(mutex* m) noexcept { + __atomic_store_n(&m->state, 0, __ATOMIC_RELEASE); + // wake one waiter + futex(&m->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1, nullptr, nullptr, 0); + } +} diff --git a/src/rt/time.cppm b/src/rt/time.cppm new file mode 100644 index 0000000..8bcf3c8 --- /dev/null +++ b/src/rt/time.cppm @@ -0,0 +1,56 @@ +export module rt.time; +import rt.errno; + +#if defined(__linux__) && defined(__x86_64__) +import rt.linux.sys; +import rt.linux.syscall; +#endif + +namespace rt::time { + // simple timespec (avoid libc headers) + export struct timespec { long tv_sec; long tv_nsec; }; + + export constexpr int CLOCK_REALTIME = 0; + export constexpr int CLOCK_MONOTONIC = 1; + + export int nanosleep(const timespec* req, timespec* rem) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r = rt::linux::sc2(35, (long)req, (long)rem); // __NR_nanosleep + if (r < 0) { rt::set_errno((int)-r); return -1; } + return 0; +#else + rt::set_errno(38); return -1; +#endif + } + + export int clock_nanosleep(int clk, int flags, const timespec* req, timespec* rem) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r = rt::linux::sc4(230, (long)clk, (long)flags, (long)req, (long)rem); // __NR_clock_nanosleep + if (r < 0) { rt::set_errno((int)-r); return -1; } + return 0; +#else + rt::set_errno(38); return -1; +#endif + } + + // CLOCK_REALTIME=0, CLOCK_MONOTONIC=1 (Linux) + export long clock_gettime(int clk_id, timespec* ts) noexcept { +#if defined(__linux__) && defined(__x86_64__) + return linux::sys_clock_gettime(clk_id, ts); +#else + set_errno(38); return -1; +#endif + } + export unsigned sleep(unsigned seconds) noexcept { + timespec req{ (long)seconds, 0 }, rem{0,0}; + int r = nanosleep(&req, &rem); + if (r == 0) return 0; + // if interrupted, return unslept seconds + return (unsigned)rem.tv_sec; + } + + export int usleep(unsigned usec) noexcept { + timespec req{ (long)(usec / 1000000u), (long)((usec % 1000000u) * 1000u) }; + return nanosleep(&req, (timespec*)0); + } +} diff --git a/src/rt/timerfd.cppm b/src/rt/timerfd.cppm new file mode 100644 index 0000000..710d9c8 --- /dev/null +++ b/src/rt/timerfd.cppm @@ -0,0 +1,52 @@ +export module rt.timerfd; + +import rt.errno; +import rt.time; +#if defined(__linux__) && defined(__x86_64__) +import rt.linux.syscall; +#endif + +namespace rt::timerfd { + // structures matching kernel uapi + export struct itimerspec { rt::time::timespec it_interval; rt::time::timespec it_value; }; + + // flags / clock ids + export constexpr int CLOCK_REALTIME = 0; + export constexpr int CLOCK_MONOTONIC = 1; + export constexpr int TFD_CLOEXEC = 0x80000; + export constexpr int TFD_NONBLOCK = 0x800; + export constexpr int TFD_TIMER_ABSTIME= 1; + + // timerfd_create(clockid, flags) + export int create(int clockid, int flags) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r = rt::linux::sc2(283, (long)clockid, (long)flags); + if (r < 0) { rt::set_errno((int)-r); return -1; } + return (int)r; +#else + rt::set_errno(38); return -1; +#endif + } + + // timerfd_settime(fd, flags, new_value*, old_value*) + export int settime(int fd, int flags, const itimerspec* nv, itimerspec* ov) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r = rt::linux::sc4(286, (long)fd, (long)flags, (long)nv, (long)ov); + if (r < 0) { rt::set_errno((int)-r); return -1; } + return 0; +#else + rt::set_errno(38); return -1; +#endif + } + + // timerfd_gettime(fd, curr_value*) + export int gettime(int fd, itimerspec* out) noexcept { +#if defined(__linux__) && defined(__x86_64__) + long r = rt::linux::sc2(287, (long)fd, (long)out); + if (r < 0) { rt::set_errno((int)-r); return -1; } + return 0; +#else + rt::set_errno(38); return -1; +#endif + } +} diff --git a/src/rt/types.cppm b/src/rt/types.cppm new file mode 100644 index 0000000..94de290 --- /dev/null +++ b/src/rt/types.cppm @@ -0,0 +1,36 @@ +export module rt.types; + +// exact-width integers using compiler-provided types (no libc/stdlib) +namespace rt::types { + using u8 = __UINT8_TYPE__; + using u16 = __UINT16_TYPE__; + using u32 = __UINT32_TYPE__; + using u64 = __UINT64_TYPE__; + + using i8 = __INT8_TYPE__; + using i16 = __INT16_TYPE__; + using i32 = __INT32_TYPE__; + using i64 = __INT64_TYPE__; + + using usize = __SIZE_TYPE__; + using isize = __PTRDIFF_TYPE__; + + using uptr = __UINTPTR_TYPE__; + using iptr = __INTPTR_TYPE__; +} + +export using rt_u8 = rt::types::u8; +export using rt_u16 = rt::types::u16; +export using rt_u32 = rt::types::u32; +export using rt_u64 = rt::types::u64; + +export using rt_i8 = rt::types::i8; +export using rt_i16 = rt::types::i16; +export using rt_i32 = rt::types::i32; +export using rt_i64 = rt::types::i64; + +export using rt_usize = rt::types::usize; +export using rt_isize = rt::types::isize; + +export using rt_uptr = rt::types::uptr; +export using rt_iptr = rt::types::iptr; diff --git a/src/start_x86_64.S b/src/start_x86_64.S new file mode 100644 index 0000000..10bdc8d --- /dev/null +++ b/src/start_x86_64.S @@ -0,0 +1,12 @@ + .section .text + .globl _start + .type _start, @function +_start: + xor %rbp, %rbp + mov %rsp, %rdi # runtime_entry(void* raw_sp) + call runtime_entry + # If it ever returns: + mov $60, %rax # SYS_exit + mov $127, %rdi + syscall + hlt