fix: sync template sysroot, add script
This commit is contained in:
@@ -37,6 +37,22 @@ namespace heap_detail {
|
||||
inline FreeNode g_overflow{0, nullptr};
|
||||
inline bool g_initialized = false;
|
||||
|
||||
// Process-wide heap lock. Userspace threads share the heap, so the
|
||||
// public malloc/mfree/realloc entry points must serialize access to
|
||||
// g_buckets/g_overflow. Kept inline here (not in thread.h) because
|
||||
// thread.h depends on heap.h, and the internal helpers below are not
|
||||
// reentrant into the public API, so a plain spinlock suffices.
|
||||
inline volatile uint32_t g_heap_lock = 0;
|
||||
|
||||
static inline void heap_lock_acquire() {
|
||||
while (__atomic_exchange_n(&g_heap_lock, 1, __ATOMIC_ACQUIRE) != 0) {
|
||||
syscall0(Montauk::SYS_YIELD);
|
||||
}
|
||||
}
|
||||
static inline void heap_lock_release() {
|
||||
__atomic_store_n(&g_heap_lock, 0, __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
static inline Header* get_header(void* block) {
|
||||
return (Header*)((uint8_t*)block - sizeof(Header));
|
||||
}
|
||||
@@ -146,15 +162,17 @@ namespace heap_detail {
|
||||
inline void* malloc(uint64_t size) {
|
||||
using namespace heap_detail;
|
||||
|
||||
// Guard against overflow: size + Header must not wrap
|
||||
if (size > UINT64_MAX - sizeof(Header) - 15)
|
||||
return nullptr;
|
||||
|
||||
heap_lock_acquire();
|
||||
|
||||
if (!g_initialized) {
|
||||
grow(16 * 0x1000); // seed with 64 KiB
|
||||
g_initialized = true;
|
||||
}
|
||||
|
||||
// Guard against overflow: size + Header must not wrap
|
||||
if (size > UINT64_MAX - sizeof(Header) - 15)
|
||||
return nullptr;
|
||||
|
||||
uint64_t needed = size + sizeof(Header);
|
||||
needed = (needed + 15) & ~15ULL;
|
||||
|
||||
@@ -162,8 +180,10 @@ namespace heap_detail {
|
||||
|
||||
if (idx >= 0) {
|
||||
// Small allocation — use segregated bucket (O(1))
|
||||
if (g_buckets[idx] == nullptr && !refill_bucket(idx))
|
||||
if (g_buckets[idx] == nullptr && !refill_bucket(idx)) {
|
||||
heap_lock_release();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
FreeNode* node = g_buckets[idx];
|
||||
g_buckets[idx] = node->next;
|
||||
@@ -171,20 +191,22 @@ namespace heap_detail {
|
||||
Header* header = (Header*)node;
|
||||
header->magic = HEADER_MAGIC;
|
||||
header->size = size;
|
||||
heap_lock_release();
|
||||
return (void*)((uint8_t*)header + sizeof(Header));
|
||||
}
|
||||
|
||||
// Large allocation — search overflow list
|
||||
void* block = take_from_overflow(needed);
|
||||
if (block == nullptr) {
|
||||
if (!grow(needed)) return nullptr;
|
||||
if (!grow(needed)) { heap_lock_release(); return nullptr; }
|
||||
block = take_from_overflow(needed);
|
||||
if (block == nullptr) return nullptr;
|
||||
if (block == nullptr) { heap_lock_release(); return nullptr; }
|
||||
}
|
||||
|
||||
Header* header = (Header*)block;
|
||||
header->magic = HEADER_MAGIC;
|
||||
header->size = size;
|
||||
heap_lock_release();
|
||||
return (void*)((uint8_t*)header + sizeof(Header));
|
||||
}
|
||||
|
||||
@@ -195,8 +217,10 @@ namespace heap_detail {
|
||||
|
||||
Header* header = get_header(ptr);
|
||||
|
||||
if (header->magic == FREED_MAGIC) return; // double-free
|
||||
if (header->magic != HEADER_MAGIC) return; // corrupt
|
||||
heap_lock_acquire();
|
||||
|
||||
if (header->magic == FREED_MAGIC) { heap_lock_release(); return; } // double-free
|
||||
if (header->magic != HEADER_MAGIC) { heap_lock_release(); return; } // corrupt
|
||||
header->magic = FREED_MAGIC;
|
||||
|
||||
uint64_t blockSize = header->size + sizeof(Header);
|
||||
@@ -214,15 +238,18 @@ namespace heap_detail {
|
||||
// Large block — sorted insert with coalescing
|
||||
insert_overflow((void*)header, blockSize);
|
||||
}
|
||||
heap_lock_release();
|
||||
}
|
||||
|
||||
inline void* realloc(void* ptr, uint64_t size) {
|
||||
if (ptr == nullptr) return malloc(size);
|
||||
|
||||
// Read old size under the lock to avoid racing with another
|
||||
// thread that might be freeing/recycling this header.
|
||||
heap_detail::heap_lock_acquire();
|
||||
auto* header = heap_detail::get_header(ptr);
|
||||
uint64_t old = header->size;
|
||||
|
||||
// Compute actual block size (accounting for bucket rounding)
|
||||
uint64_t oldBlock = (old + sizeof(heap_detail::Header) + 15) & ~15ULL;
|
||||
int idx = heap_detail::bucket_index(oldBlock);
|
||||
if (idx >= 0) oldBlock = heap_detail::BUCKET_SIZES[idx];
|
||||
@@ -230,8 +257,10 @@ namespace heap_detail {
|
||||
uint64_t newNeed = (size + sizeof(heap_detail::Header) + 15) & ~15ULL;
|
||||
if (newNeed <= oldBlock) {
|
||||
header->size = size;
|
||||
heap_detail::heap_lock_release();
|
||||
return ptr;
|
||||
}
|
||||
heap_detail::heap_lock_release();
|
||||
|
||||
void* newBlock = malloc(size);
|
||||
if (newBlock == nullptr) return nullptr;
|
||||
|
||||
@@ -120,6 +120,12 @@ namespace montauk {
|
||||
inline int spawn(const char* path, const char* args = nullptr) {
|
||||
return (int)syscall2(Montauk::SYS_SPAWN, (uint64_t)path, (uint64_t)args);
|
||||
}
|
||||
inline int chdir(const char* path) {
|
||||
return (int)syscall1(Montauk::SYS_CHDIR, (uint64_t)path);
|
||||
}
|
||||
inline int getcwd(char* buf, uint64_t maxLen) {
|
||||
return (int)syscall2(Montauk::SYS_GETCWD, (uint64_t)buf, maxLen);
|
||||
}
|
||||
|
||||
// Console
|
||||
inline void print(const char* text) { syscall1(Montauk::SYS_PRINT, (uint64_t)text); }
|
||||
@@ -135,6 +141,13 @@ namespace montauk {
|
||||
inline int readdir(const char* path, const char** names, int max) {
|
||||
return (int)syscall3(Montauk::SYS_READDIR, (uint64_t)path, (uint64_t)names, (uint64_t)max);
|
||||
}
|
||||
// Paginated directory read: returns entries [startIndex, startIndex+max).
|
||||
// Call repeatedly with increasing startIndex (advancing by the returned
|
||||
// count) until it returns 0 to enumerate directories of any size.
|
||||
inline int readdir_at(const char* path, const char** names, int max, int startIndex) {
|
||||
return (int)syscall4(Montauk::SYS_READDIR_AT, (uint64_t)path, (uint64_t)names,
|
||||
(uint64_t)max, (uint64_t)startIndex);
|
||||
}
|
||||
|
||||
// File write/create
|
||||
inline int fwrite(int handle, const uint8_t* buf, uint64_t off, uint64_t size) {
|
||||
@@ -149,12 +162,20 @@ namespace montauk {
|
||||
inline int fmkdir(const char* path) {
|
||||
return (int)syscall1(Montauk::SYS_FMKDIR, (uint64_t)path);
|
||||
}
|
||||
inline int frename(const char* oldPath, const char* newPath) {
|
||||
return (int)syscall2(Montauk::SYS_FRENAME, (uint64_t)oldPath, (uint64_t)newPath);
|
||||
}
|
||||
inline int drivelist(int* outDrives, int max) {
|
||||
return (int)syscall2(Montauk::SYS_DRIVELIST, (uint64_t)outDrives, (uint64_t)max);
|
||||
}
|
||||
inline int drivelabel(int drive, char* outLabel, int maxLen) {
|
||||
return (int)syscall3(Montauk::SYS_DRIVELABEL, (uint64_t)drive, (uint64_t)outLabel, (uint64_t)maxLen);
|
||||
}
|
||||
// Returns the kernel BlockDeviceKind backing the drive: 0=unknown/ramdisk,
|
||||
// 1=SATA, 2=SATAPI, 3=NVMe, 4=USB MSC.
|
||||
inline int drivekind(int drive) {
|
||||
return (int)syscall1(Montauk::SYS_DRIVEKIND, (uint64_t)drive);
|
||||
}
|
||||
|
||||
// Memory
|
||||
inline void* alloc(uint64_t size) { return (void*)syscall1(Montauk::SYS_ALLOC, size); }
|
||||
@@ -171,6 +192,9 @@ namespace montauk {
|
||||
inline bool is_key_available() { return (bool)syscall0(Montauk::SYS_ISKEYAVAILABLE); }
|
||||
inline void getkey(Montauk::KeyEvent* out) { syscall1(Montauk::SYS_GETKEY, (uint64_t)out); }
|
||||
inline char getchar() { return (char)syscall0(Montauk::SYS_GETCHAR); }
|
||||
inline uint64_t input_wait(uint64_t observedSerial, uint64_t timeoutMs) {
|
||||
return (uint64_t)syscall2(Montauk::SYS_INPUT_WAIT, observedSerial, timeoutMs);
|
||||
}
|
||||
|
||||
// Networking
|
||||
inline int32_t ping(uint32_t ip, uint32_t timeoutMs = 3000) {
|
||||
@@ -221,6 +245,81 @@ namespace montauk {
|
||||
(uint64_t)maxLen, (uint64_t)srcIp, (uint64_t)srcPort);
|
||||
}
|
||||
|
||||
// Generic IPC
|
||||
inline int dup_handle(int handle) {
|
||||
return (int)syscall1(Montauk::SYS_DUPHANDLE, (uint64_t)handle);
|
||||
}
|
||||
inline uint32_t wait_handle(int handle, uint32_t wantedSignals, uint64_t timeoutMs = ~0ULL) {
|
||||
return (uint32_t)syscall3(Montauk::SYS_WAIT_HANDLE, (uint64_t)handle,
|
||||
(uint64_t)wantedSignals, timeoutMs);
|
||||
}
|
||||
inline int stream_create(int* outReadHandle, int* outWriteHandle, uint32_t capacity = 0) {
|
||||
return (int)syscall3(Montauk::SYS_STREAM_CREATE, (uint64_t)outReadHandle,
|
||||
(uint64_t)outWriteHandle, (uint64_t)capacity);
|
||||
}
|
||||
inline int stream_read(int handle, void* buf, int maxLen) {
|
||||
return (int)syscall3(Montauk::SYS_STREAM_READ, (uint64_t)handle, (uint64_t)buf, (uint64_t)maxLen);
|
||||
}
|
||||
inline int stream_write(int handle, const void* data, int len) {
|
||||
return (int)syscall3(Montauk::SYS_STREAM_WRITE, (uint64_t)handle, (uint64_t)data, (uint64_t)len);
|
||||
}
|
||||
inline int mailbox_create(int* outSendHandle, int* outRecvHandle) {
|
||||
return (int)syscall2(Montauk::SYS_MAILBOX_CREATE, (uint64_t)outSendHandle, (uint64_t)outRecvHandle);
|
||||
}
|
||||
inline int mailbox_send(int handle, uint32_t msgType, const void* data, uint16_t len, int attachHandle = -1) {
|
||||
return (int)syscall5(Montauk::SYS_MAILBOX_SEND, (uint64_t)handle, (uint64_t)msgType,
|
||||
(uint64_t)data, (uint64_t)len, (uint64_t)(int64_t)attachHandle);
|
||||
}
|
||||
inline int mailbox_recv(int handle, uint32_t* outMsgType, void* data,
|
||||
uint16_t* inOutLen, int* outAttachHandle = nullptr) {
|
||||
return (int)syscall5(Montauk::SYS_MAILBOX_RECV, (uint64_t)handle, (uint64_t)outMsgType,
|
||||
(uint64_t)data, (uint64_t)inOutLen, (uint64_t)outAttachHandle);
|
||||
}
|
||||
inline int waitset_create() {
|
||||
return (int)syscall0(Montauk::SYS_WAITSET_CREATE);
|
||||
}
|
||||
inline int waitset_add(int waitsetHandle, int targetHandle, uint32_t signals) {
|
||||
return (int)syscall3(Montauk::SYS_WAITSET_ADD, (uint64_t)waitsetHandle,
|
||||
(uint64_t)targetHandle, (uint64_t)signals);
|
||||
}
|
||||
inline int waitset_remove(int waitsetHandle, int index) {
|
||||
return (int)syscall2(Montauk::SYS_WAITSET_REMOVE, (uint64_t)waitsetHandle, (uint64_t)index);
|
||||
}
|
||||
inline int waitset_wait(int waitsetHandle, Montauk::IpcWaitResult* outReady, uint64_t timeoutMs = ~0ULL) {
|
||||
return (int)syscall3(Montauk::SYS_WAITSET_WAIT, (uint64_t)waitsetHandle, (uint64_t)outReady, timeoutMs);
|
||||
}
|
||||
inline int proc_open(int pid) {
|
||||
return (int)syscall1(Montauk::SYS_PROC_OPEN, (uint64_t)pid);
|
||||
}
|
||||
inline int surface_create(uint64_t byteSize) {
|
||||
return (int)syscall1(Montauk::SYS_SURFACE_CREATE, byteSize);
|
||||
}
|
||||
inline void* surface_map(int handle) {
|
||||
return (void*)syscall1(Montauk::SYS_SURFACE_MAP, (uint64_t)handle);
|
||||
}
|
||||
inline int surface_resize(int handle, uint64_t newSize) {
|
||||
return (int)syscall2(Montauk::SYS_SURFACE_RESIZE, (uint64_t)handle, newSize);
|
||||
}
|
||||
|
||||
// Shared library support
|
||||
inline int load_lib(const char* path) {
|
||||
return (int)syscall1(Montauk::SYS_LOAD_LIB, (uint64_t)path);
|
||||
}
|
||||
inline int unload_lib(int handle) {
|
||||
return (int)syscall1(Montauk::SYS_UNLOAD_LIB, (uint64_t)handle);
|
||||
}
|
||||
inline void* dlsym(int handle, uint64_t symbolOffset) {
|
||||
return (void*)syscall2(Montauk::SYS_DLSYM, (uint64_t)handle, symbolOffset);
|
||||
}
|
||||
inline uint64_t get_libbase(int handle) {
|
||||
return (uint64_t)syscall1(Montauk::SYS_GETLIBBASE, (uint64_t)handle);
|
||||
}
|
||||
|
||||
// Crash report retrieval
|
||||
inline int crash_report(Montauk::CrashReportInfo* out) {
|
||||
return (int)syscall1(Montauk::SYS_CRASH_REPORT, (uint64_t)out);
|
||||
}
|
||||
|
||||
// Process management
|
||||
inline void waitpid(int pid) { syscall1(Montauk::SYS_WAITPID, (uint64_t)pid); }
|
||||
|
||||
@@ -273,6 +372,19 @@ namespace montauk {
|
||||
__builtin_unreachable();
|
||||
}
|
||||
|
||||
inline int suspend() {
|
||||
return (int)syscall0(Montauk::SYS_SUSPEND);
|
||||
}
|
||||
|
||||
// Graceful power-off request channel. The desktop posts a pending action
|
||||
// (Montauk::POWER_REQ_SHUTDOWN / POWER_REQ_REBOOT) then exits; login.elf
|
||||
// reads it with POWER_REQ_QUERY (read-and-clear), runs the shutdown stages,
|
||||
// and finally calls shutdown()/reset(). Returns the pending action for a
|
||||
// query, or 0 when posting one.
|
||||
inline int power_request(int action) {
|
||||
return (int)syscall1(Montauk::SYS_POWER_REQUEST, (uint64_t)(int64_t)action);
|
||||
}
|
||||
|
||||
// Mouse
|
||||
inline void mouse_state(Montauk::MouseState* out) { syscall1(Montauk::SYS_MOUSESTATE, (uint64_t)out); }
|
||||
inline void set_mouse_bounds(int32_t maxX, int32_t maxY) {
|
||||
@@ -340,6 +452,11 @@ namespace montauk {
|
||||
inline int fs_mount(int partIndex, int driveNum) {
|
||||
return (int)syscall2(Montauk::SYS_FSMOUNT, (uint64_t)partIndex, (uint64_t)driveNum);
|
||||
}
|
||||
// Flush all block-device write caches and cleanly unmount disk-backed
|
||||
// volumes ahead of power-off. Returns the number of volumes unmounted.
|
||||
inline int fs_sync() {
|
||||
return (int)syscall0(Montauk::SYS_FS_SYNC);
|
||||
}
|
||||
inline int fs_format(const Montauk::FsFormatParams* params) {
|
||||
return (int)syscall1(Montauk::SYS_FSFORMAT, (uint64_t)params);
|
||||
}
|
||||
@@ -381,6 +498,33 @@ namespace montauk {
|
||||
inline int audio_bt_status(int handle) {
|
||||
return audio_ctl(handle, Montauk::AUDIO_CTL_BT_STATUS, 0);
|
||||
}
|
||||
inline int audio_set_master_volume(int percent) {
|
||||
return audio_ctl(-1, Montauk::AUDIO_CTL_SET_MASTER_VOLUME, percent);
|
||||
}
|
||||
inline int audio_get_master_volume() {
|
||||
return audio_ctl(-1, Montauk::AUDIO_CTL_GET_MASTER_VOLUME, 0);
|
||||
}
|
||||
inline int audio_set_master_mute(bool muted) {
|
||||
return audio_ctl(-1, Montauk::AUDIO_CTL_SET_MASTER_MUTE, muted ? 1 : 0);
|
||||
}
|
||||
inline int audio_get_master_mute() {
|
||||
return audio_ctl(-1, Montauk::AUDIO_CTL_GET_MASTER_MUTE, 0);
|
||||
}
|
||||
inline int audio_set_mute(int handle, bool muted) {
|
||||
return audio_ctl(handle, Montauk::AUDIO_CTL_SET_MUTE, muted ? 1 : 0);
|
||||
}
|
||||
inline int audio_get_mute(int handle) {
|
||||
return audio_ctl(handle, Montauk::AUDIO_CTL_GET_MUTE, 0);
|
||||
}
|
||||
inline int audio_list(Montauk::AudioStreamInfo* buf, int maxCount) {
|
||||
return (int)syscall2(Montauk::SYS_AUDIOLIST, (uint64_t)buf, (uint64_t)maxCount);
|
||||
}
|
||||
// Returns the current mixer state serial. With timeoutMs > 0 the call
|
||||
// blocks until the serial differs from `prevSerial` or the timeout
|
||||
// elapses. With timeoutMs == 0 it returns immediately (cheap snapshot).
|
||||
inline uint64_t audio_wait(uint64_t prevSerial, uint64_t timeoutMs) {
|
||||
return syscall2(Montauk::SYS_AUDIOWAIT, prevSerial, timeoutMs);
|
||||
}
|
||||
|
||||
// Bluetooth
|
||||
inline int bt_scan(Montauk::BtScanResult* buf, int maxCount, uint32_t timeoutMs) {
|
||||
@@ -402,6 +546,30 @@ namespace montauk {
|
||||
// Kernel introspection
|
||||
inline void memstats(Montauk::MemStats* out) { syscall1(Montauk::SYS_MEMSTATS, (uint64_t)out); }
|
||||
|
||||
// User management
|
||||
inline int setuser(int pid, const char* name) {
|
||||
return (int)syscall2(Montauk::SYS_SETUSER, (uint64_t)pid, (uint64_t)name);
|
||||
}
|
||||
inline int getuser(char* buf, uint64_t maxLen) {
|
||||
return (int)syscall2(Montauk::SYS_GETUSER, (uint64_t)buf, maxLen);
|
||||
}
|
||||
|
||||
// Clipboard
|
||||
inline int clipboard_set_text(const char* data, uint32_t len) {
|
||||
return (int)syscall2(Montauk::SYS_CLIPBOARD_SET_TEXT, (uint64_t)data, (uint64_t)len);
|
||||
}
|
||||
inline int clipboard_get_info(Montauk::ClipboardInfo* out) {
|
||||
return (int)syscall1(Montauk::SYS_CLIPBOARD_GET_INFO, (uint64_t)out);
|
||||
}
|
||||
inline int clipboard_get_text(char* buf, uint32_t bufLen, uint32_t* outLen,
|
||||
uint64_t* outSerial = nullptr) {
|
||||
return (int)syscall4(Montauk::SYS_CLIPBOARD_GET_TEXT, (uint64_t)buf, (uint64_t)bufLen,
|
||||
(uint64_t)outLen, (uint64_t)outSerial);
|
||||
}
|
||||
inline int clipboard_clear() {
|
||||
return (int)syscall0(Montauk::SYS_CLIPBOARD_CLEAR);
|
||||
}
|
||||
|
||||
// Window server
|
||||
inline int win_create(const char* title, int w, int h, Montauk::WinCreateResult* result) {
|
||||
return (int)syscall4(Montauk::SYS_WINCREATE, (uint64_t)title, (uint64_t)w, (uint64_t)h, (uint64_t)result);
|
||||
@@ -421,6 +589,9 @@ namespace montauk {
|
||||
inline uint64_t win_map(int id) {
|
||||
return (uint64_t)syscall1(Montauk::SYS_WINMAP, (uint64_t)id);
|
||||
}
|
||||
inline int win_unmap(int id) {
|
||||
return (int)syscall1(Montauk::SYS_WINUNMAP, (uint64_t)id);
|
||||
}
|
||||
inline int win_sendevent(int id, const Montauk::WinEvent* event) {
|
||||
return (int)syscall2(Montauk::SYS_WINSENDEVENT, (uint64_t)id, (uint64_t)event);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* thread.h
|
||||
* Userspace threading primitives for MontaukOS
|
||||
* Copyright (c) 2026 Daniel Hammer
|
||||
*
|
||||
* Threads share their parent's address space, IPC handles, cwd, and
|
||||
* heap allocator. The caller owns the thread stack: thread_spawn
|
||||
* allocates one out of the user heap and the kernel uses it verbatim.
|
||||
*
|
||||
* Lifetimes:
|
||||
* - thread_spawn returns a positive TID on success.
|
||||
* - thread_join blocks until the target TID exits, frees its kernel
|
||||
* stack, then returns its exit code via *out_code.
|
||||
* - thread_exit terminates only the current thread. If the main thread
|
||||
* calls exit() (SYS_EXIT) the whole process tears down, killing any
|
||||
* surviving sibling threads.
|
||||
* - thread_self returns the calling thread's TID.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <Api/Syscall.hpp>
|
||||
#include <montauk/syscall.h>
|
||||
#include <montauk/heap.h>
|
||||
|
||||
namespace montauk {
|
||||
|
||||
// Default per-thread stack size (64 KiB). Enough for typical app work;
|
||||
// matches the main thread's 32 KiB lower bound with headroom for
|
||||
// TrueType rendering call chains.
|
||||
static constexpr uint64_t DEFAULT_THREAD_STACK_BYTES = 64 * 1024;
|
||||
|
||||
using ThreadEntry = int (*)(void* arg);
|
||||
|
||||
// Terminate the calling thread. Never returns. If called by the main
|
||||
// thread this is equivalent to exit() (the whole process exits).
|
||||
[[noreturn]] inline void thread_exit(int code = 0) {
|
||||
syscall1(Montauk::SYS_THREAD_EXIT, (uint64_t)code);
|
||||
__builtin_unreachable();
|
||||
}
|
||||
|
||||
namespace detail {
|
||||
struct ThreadCtx {
|
||||
ThreadEntry user_entry;
|
||||
void* user_arg;
|
||||
void* stack_base;
|
||||
};
|
||||
|
||||
// Userspace trampoline: bridges from the raw entry the kernel jumps
|
||||
// to into the typed entry, then funnels into SYS_THREAD_EXIT. We
|
||||
// route the exit through libc rather than relying on a kernel-side
|
||||
// exit stub on the user stack -- the kernel never writes to user
|
||||
// memory on this path.
|
||||
//
|
||||
// The thread's stack itself is intentionally not freed here: we are
|
||||
// still running on it. It is reclaimed when the process exits, or
|
||||
// the joiner may free it explicitly after thread_join.
|
||||
[[noreturn]] inline void thread_trampoline(detail::ThreadCtx* ctx) {
|
||||
int code = ctx->user_entry(ctx->user_arg);
|
||||
montauk::mfree(ctx);
|
||||
thread_exit(code);
|
||||
}
|
||||
}
|
||||
|
||||
// Spawn a new thread that begins executing `entry(arg)`. Returns the
|
||||
// new TID on success, or -1 on failure. The thread's stack is
|
||||
// allocated from the user heap; it is leaked on thread exit (the
|
||||
// thread itself cannot free the stack it is running on). The kernel
|
||||
// reclaims it on process exit. Callers that need to spawn many short-
|
||||
// lived threads should pool stacks themselves.
|
||||
inline int thread_spawn(ThreadEntry entry, void* arg,
|
||||
uint64_t stack_bytes = 0) {
|
||||
if (entry == nullptr) return -1;
|
||||
if (stack_bytes == 0) stack_bytes = DEFAULT_THREAD_STACK_BYTES;
|
||||
stack_bytes = (stack_bytes + 15) & ~15ULL;
|
||||
|
||||
void* stack = montauk::malloc(stack_bytes);
|
||||
if (stack == nullptr) return -1;
|
||||
auto* ctx = (detail::ThreadCtx*)montauk::malloc(sizeof(detail::ThreadCtx));
|
||||
if (ctx == nullptr) {
|
||||
montauk::mfree(stack);
|
||||
return -1;
|
||||
}
|
||||
ctx->user_entry = entry;
|
||||
ctx->user_arg = arg;
|
||||
ctx->stack_base = stack;
|
||||
|
||||
uint64_t stack_top = ((uint64_t)stack + stack_bytes) & ~0xFULL;
|
||||
int tid = (int)syscall3(Montauk::SYS_THREAD_SPAWN,
|
||||
(uint64_t)&detail::thread_trampoline,
|
||||
(uint64_t)ctx, stack_top);
|
||||
if (tid < 0) {
|
||||
montauk::mfree(ctx);
|
||||
montauk::mfree(stack);
|
||||
return -1;
|
||||
}
|
||||
return tid;
|
||||
}
|
||||
|
||||
// Block until the thread identified by `tid` terminates. Returns 0 on
|
||||
// success (with the thread's exit code in *out_code if non-null) or
|
||||
// -1 if `tid` is not a joinable sibling.
|
||||
inline int thread_join(int tid, int* out_code = nullptr) {
|
||||
return (int)syscall2(Montauk::SYS_THREAD_JOIN,
|
||||
(uint64_t)tid, (uint64_t)out_code);
|
||||
}
|
||||
|
||||
// Return the calling thread's TID (== getpid() for the main thread).
|
||||
inline int thread_self() {
|
||||
return (int)syscall0(Montauk::SYS_THREAD_SELF);
|
||||
}
|
||||
|
||||
// Lightweight mutex backed by a single atomic word + the kernel
|
||||
// yield syscall. Adequate for short critical sections; a heavier
|
||||
// primitive can wrap mailbox_recv when blocking semantics are needed.
|
||||
struct Mutex {
|
||||
volatile uint32_t locked = 0;
|
||||
|
||||
void lock() {
|
||||
while (__atomic_exchange_n(&locked, 1, __ATOMIC_ACQUIRE) != 0) {
|
||||
montauk::yield();
|
||||
}
|
||||
}
|
||||
|
||||
bool try_lock() {
|
||||
return __atomic_exchange_n(&locked, 1, __ATOMIC_ACQUIRE) == 0;
|
||||
}
|
||||
|
||||
void unlock() {
|
||||
__atomic_store_n(&locked, 0, __ATOMIC_RELEASE);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user