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]>
This commit is contained in:
2026-07-16 18:48:25 +02:00
co-authored by Claude Fable 5
parent 75184e0651
commit 5db2bd4c7c
8 changed files with 222 additions and 4 deletions
+1
View File
@@ -402,6 +402,7 @@ ifneq ($(wildcard $(NATIVE_BIN)/as),)
cp lib/libc/crt1.o lib/libc/crti.o lib/libc/crtn.o $(BINDIR)/sdk/lib/
ar rcs $(BINDIR)/sdk/lib/libm.a
ar rcs $(BINDIR)/sdk/lib/libstdc++.a
../toolchain/local/bin/x86_64-montauk-gcc -O2 ../toolchain/files/tls-test.c -o $(BINDIR)/sdk/bin/tls-test.elf
else
@echo "devkit: toolchain/native/ not built; skipping native dev tools"
endif