Files
danielandClaude Fable 5 5db2bd4c7c feat: TLS runtime - PT_TLS loading and per-thread FS base
MontaukOS binaries could not use thread-local storage: the ELF loader
ignored PT_TLS and no FS base was ever programmed, so any %fs access
(initial-exec/local-exec TLS, e.g. libbfd's _Thread_local error state)
page faulted at address 0. This is the kernel prerequisite for
cc1plus/libstdc++ in the GCC port.

ELF loader: parse PT_TLS and build the main thread's TLS block above
the loaded image (x86-64 variant II ABI: block below the thread
pointer, TP = base + align_up(memsz, align), .tdata copied from the
template, .tbss zeroed, ABI self-pointer stored at [TP]). The
template description is kept on the process for thread spawns.

Scheduler: fsBase per thread, loaded into IA32_FS_BASE at every
dispatch site through a per-CPU cache - TLS-free processes cost one
MSR write per CPU ever, and userspace cannot desync the cache since
CR4.FSGSBASE stays off. SYS_THREAD_SPAWN gives each new thread its
own TLS block copied from the template (allocated from the process
heap; reclaimed at process teardown).

Ships tls-test.elf in the SDK (built by the devkit target): checks
.tdata values, .tbss zeroing, and the %fs:0 self-pointer, exiting
nonzero on failure. Boot-smoke verified; existing TLS-free programs
are unaffected.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-16 18:48:25 +02:00

38 lines
1.1 KiB
C

/*
* tls-test.c
* Verifies the MontaukOS TLS runtime: PT_TLS loading, FS base,
* .tdata initialization, .tbss zeroing, and the ABI self-pointer.
* Built by the devkit target and shipped at 0:/sdk/bin/tls-test.elf.
*/
#include <stdio.h>
#include <stdint.h>
__thread int tls_int = 41;
__thread char tls_str[32] = "montauk-tls";
__thread int tls_bss[8]; /* .tbss, must arrive zeroed */
int main(void) {
int ok = 1;
tls_int++;
tls_bss[3] = 7;
printf("tls_int = %d (want 42)\n", tls_int);
printf("tls_str = %s (want montauk-tls)\n", tls_str);
printf("tls_bss = %d,%d (want 0,7)\n", tls_bss[0], tls_bss[3]);
if (tls_int != 42) ok = 0;
if (tls_str[0] != 'm' || tls_str[10] != 's') ok = 0;
if (tls_bss[0] != 0 || tls_bss[3] != 7) ok = 0;
/* The thread pointer must hold a self-pointer at %fs:0. */
uint64_t self;
__asm__("mov %%fs:0, %0" : "=r"(self));
printf("fs:0 self = 0x%lx\n", (unsigned long)self);
if (self == 0) ok = 0;
printf(ok ? "TLS OK\n" : "TLS BROKEN\n");
return ok ? 0 : 1;
}