Commit 69ba923d authored by jan.koester's avatar jan.koester
Browse files

pthread: worker threads get a guard page below their stack

Thread stacks were a plain mmap: running off one overwrote whatever lay
below, and Rust's std (which expects glibc's guard pages on *-linux-gnu)
panicked "there is no guard page" in every spawned thread. The mapping
now has a PROT_NONE guard (one page by default, pthread_attr_setguardsize
rounds up to pages) below the unchanged usable stack; a stack the caller
provides has none (POSIX). pthread_attr_getguardsize reports it, and
pthread_getattr_np reports the thread's real guard (the main thread: the
kernel's guard gap, one page).

e2e: getattr_np on a worker reports the guard, a worker's stack overflow
ends in SIGSEGV; clock_nanosleep's guardsize checks follow. 171/171.
With this a Rust program built by rustc on FenrirOS runs threads, and a
panic caught with catch_unwind unwinds through systempp's _Unwind_* ABI.

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 6f589c43
Loading
Loading
Loading
Loading
+47 −8
Changes for src/linux/thread.cpp: 47 added lines, 8 removed lines.
Original line number Diff line number Diff line
@@ -391,11 +391,34 @@ void sys::thread::runKeyDestructors() {
    __run_key_destructors(_specific);
}

static size_t __thread_page_size() {
    long p = sysconf(_SC_PAGESIZE);
    return p > 0 ? (size_t)p : 4096;
}

sys::threadattr::threadattr(){
    _stack=nullptr;
    _stacksize=DEFAULT_STACKSIZE;
    _owned=false;
    _detachattr=false;
    _guardsize=__thread_page_size();
    _guardreported=false;
    _mapbase=nullptr;
}

void sys::threadattr::setGuardSize(size_t guardsize){
    size_t page = __thread_page_size();
    _guardsize = (guardsize + page - 1) / page * page;
}

size_t sys::threadattr::getGuardSize() const{
    /* a stack the caller provided has no guard of ours (POSIX) */
    return (_stack && !_owned && !_guardreported) ? 0 : _guardsize;
}

void sys::threadattr::reportGuardSize(size_t guardsize){
    _guardsize=guardsize;
    _guardreported=true;
}

void sys::threadattr::setDetached(bool detached){
@@ -407,19 +430,28 @@ bool sys::threadattr::getDetached() const{
}

sys::threadattr::~threadattr(){
    if(_owned && _stack)
        munmap(_stack,_stacksize);
    if(_owned && _mapbase)
        munmap(_mapbase,_guardsize+_stacksize);
}

void sys::threadattr::_finalize(){
    if(!_stack){
        void *mem=mmap(nullptr,_stacksize,PROT_READ|PROT_WRITE,
        /* guard page(s) at the low end, below the usable stack (it grows
         * down): an overflow faults there, as with glibc/musl threads --
         * Rust's std even panics "there is no guard page" without one */
        void *mem=mmap(nullptr,_guardsize+_stacksize,PROT_READ|PROT_WRITE,
            MAP_PRIVATE|MAP_ANONYMOUS|MAP_STACK,-1,0);
        if(mem==MAP_FAILED){
            SystemException excep;
            throw excep[SystemException::Error] << "Failed to allocate thread stack !";
        }
        _stack=(char*)mem;
        if(_guardsize && mprotect(mem,_guardsize,PROT_NONE)!=0){
            munmap(mem,_guardsize+_stacksize);
            SystemException excep;
            throw excep[SystemException::Error] << "Failed to protect the thread stack guard !";
        }
        _mapbase=(char*)mem;
        _stack=(char*)mem+_guardsize;
        _owned=true;
    }
}
@@ -701,6 +733,11 @@ extern "C" {
        sys::threadattr* na = new sys::threadattr();
        na->setStack(stackaddr);
        na->setStackSize(stacksize);
        /* the thread's own guard (worker threads: the page below their
         * mapped stack; the main thread: the kernel's stack guard gap) --
         * a setStack()'d attr would otherwise report none */
        size_t guard = thread ? ((sys::thread*)thread)->getAttr()->getGuardSize() : __thread_page_size();
        na->reportGuardSize(guard);
        *attr = na;
        return 0;
    }
@@ -806,12 +843,14 @@ extern "C" {

    int pthread_attr_getguardsize(const pthread_attr_t *__restrict__ attr,
                                  size_t *__restrict__ guardsize){
        if (!attr || !guardsize) return EINVAL;
        *guardsize = 0;
        if (!attr || !*attr || !guardsize) return EINVAL;
        *guardsize = ((sys::threadattr*)*attr)->getGuardSize();
        return 0;
    }
    int pthread_attr_setguardsize(pthread_attr_t *attr, size_t){
        return attr ? 0 : EINVAL;
    int pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize){
        if (!attr || !*attr) return EINVAL;
        ((sys::threadattr*)*attr)->setGuardSize(guardsize);
        return 0;
    }

    int pthread_attr_getstacksize(const pthread_attr_t *__restrict__ attr,
+21 −0
Changes for src/test/e2e/CMakeLists.txt: 21 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -4072,3 +4072,24 @@ add_test(NAME e2e_pthread_exit COMMAND e2e_pthread_exit)
# the old pthread_exit ended the whole process with status 0 -- that must
# not count as a pass
set_tests_properties(e2e_pthread_exit PROPERTIES PASS_REGULAR_EXPRESSION "OK: pthread_exit")

add_executable(e2e_thread_guard_page thread_guard_page_test.cpp)
set_target_properties(e2e_thread_guard_page PROPERTIES OUTPUT_NAME "thread_guard_page_test")
target_compile_options(e2e_thread_guard_page PRIVATE -fPIE)
target_link_options(e2e_thread_guard_page PRIVATE
    -nostdlib -pie
    -Wl,--hash-style=sysv
    -Wl,--dynamic-linker,$<TARGET_FILE_DIR:systempp>/ld-linux-${CMAKE_SYSTEM_PROCESSOR}.so
    -Wl,-rpath,$<TARGET_FILE_DIR:systempp>
)
target_link_libraries(e2e_thread_guard_page PRIVATE
    $<TARGET_OBJECTS:crti>
    $<TARGET_OBJECTS:Scrt1>
    $<TARGET_OBJECTS:crtbeginS>
    $<TARGET_OBJECTS:crtn>
    systempp
)
add_dependencies(e2e_thread_guard_page crti Scrt1 crtbeginS crtn systempp)

add_test(NAME e2e_thread_guard_page COMMAND e2e_thread_guard_page)
set_tests_properties(e2e_thread_guard_page PROPERTIES PASS_REGULAR_EXPRESSION "OK: thread guard page")
+7 −3
Changes for src/test/e2e/clock_nanosleep_test.cpp: 7 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -5,6 +5,7 @@
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

static double now(clockid_t c) { struct timespec t; clock_gettime(c, &t); return t.tv_sec + t.tv_nsec / 1e9; }
#define CHECK(cond, ...) do { if (!(cond)) { printf("FAIL: " __VA_ARGS__); printf("\n"); return 1; } } while (0)
@@ -27,10 +28,13 @@ int main() {

    CHECK(clock_nanosleep(-12345, 0, &d, nullptr) == EINVAL, "invalid clock must return EINVAL itself");

    /* threads have a guard page: one page by default, settable (rounded
     * up to pages) */
    pthread_attr_t a; pthread_attr_init(&a);
    size_t g = 99;
    CHECK(pthread_attr_setguardsize(&a, 4096) == 0, "setguardsize");
    CHECK(pthread_attr_getguardsize(&a, &g) == 0 && g == 0, "getguardsize %zu", g);
    size_t g = 0, page = (size_t)sysconf(_SC_PAGESIZE);
    CHECK(pthread_attr_getguardsize(&a, &g) == 0 && g == page, "default guardsize %zu, want %zu", g, page);
    CHECK(pthread_attr_setguardsize(&a, 3 * page - 5) == 0, "setguardsize");
    CHECK(pthread_attr_getguardsize(&a, &g) == 0 && g == 3 * page, "getguardsize %zu, want %zu", g, 3 * page);
    pthread_attr_destroy(&a);
    printf("OK: clock_nanosleep\n");
    return 0;
+49 −0
Changes for src/test/e2e/thread_guard_page_test.cpp: 49 added lines, 0 removed lines.
Original line number Diff line number Diff line
/* Worker threads have a guard page below their stack: pthread_getattr_np()
 * on the thread itself reports it (Rust's std panics "there is no guard
 * page" otherwise), and running off the stack faults with SIGSEGV instead
 * of overwriting whatever lies below. */
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

#define CHECK(cond, ...) do { if (!(cond)) { printf("FAIL: " __VA_ARGS__); printf("\n"); return 1; } } while (0)

static size_t g_guard = 0;
static void* report(void*) {
    pthread_attr_t a;
    if (pthread_getattr_np(pthread_self(), &a) == 0) {
        pthread_attr_getguardsize(&a, &g_guard);
        pthread_attr_destroy(&a);
    }
    return nullptr;
}

__attribute__((noinline)) static int recurse(volatile char* prev, int depth) {
    volatile char buf[4096];
    buf[0] = (char)depth; buf[4095] = prev ? prev[0] : 0;
    return recurse(buf, depth + 1) + buf[100];
}
static void* overflow(void*) { recurse(nullptr, 0); return nullptr; }

int main() {
    pthread_t t;
    CHECK(pthread_create(&t, nullptr, report, nullptr) == 0, "create");
    pthread_join(t, nullptr);
    CHECK(g_guard >= (size_t)sysconf(_SC_PAGESIZE), "thread guard size %zu", g_guard);

    pid_t pid = fork();
    if (pid == 0) {
        pthread_t o;
        pthread_create(&o, nullptr, overflow, nullptr);
        pthread_join(o, nullptr);
        _exit(0);   /* not reached: the overflow must fault */
    }
    int status = 0;
    waitpid(pid, &status, 0);
    CHECK(WIFSIGNALED(status) && WTERMSIG(status) == SIGSEGV,
          "stack overflow in a thread: status %#x, want SIGSEGV", status);
    printf("OK: thread guard page\n");
    return 0;
}
+11 −0
Changes for src/thread.h: 11 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -45,6 +45,14 @@ namespace sys {
         * is detached right after it starts */
        void setDetached(bool detached);
        bool getDetached() const;
        /* the PROT_NONE page(s) below a stack this attr maps itself (a stack
         * overflow faults instead of overwriting memory below it); 0 for a
         * stack set with setStack() */
        void setGuardSize(size_t guardsize);
        size_t getGuardSize() const;
        /* pthread_getattr_np: the guard the described thread really has,
         * reported even though the attr only describes (setStack) */
        void reportGuardSize(size_t guardsize);

    private:
        void _finalize();
@@ -53,6 +61,9 @@ namespace sys {
        size_t _stacksize;
        bool _owned;
        bool _detachattr;
        size_t _guardsize;
        bool _guardreported;
        char* _mapbase;  /* start of the mapping: the guard, then the stack */

        friend class thread;
    };