From dd46a378b3989cd492f87a7e51f7a16125d3199f Mon Sep 17 00:00:00 2001 From: Max Wash Date: Sun, 22 Mar 2026 19:08:42 +0000 Subject: [PATCH] lib: c: pthread: implement pthread_self --- lib/libc/pthread/sys/x86_64/pthread_self.S | 6 ++-- lib/libc/pthread/thread/pthread.h | 1 + lib/libc/pthread/thread/pthread_self.c | 36 ++++++++++++++++++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/lib/libc/pthread/sys/x86_64/pthread_self.S b/lib/libc/pthread/sys/x86_64/pthread_self.S index cf8a2d8..1bc7808 100644 --- a/lib/libc/pthread/sys/x86_64/pthread_self.S +++ b/lib/libc/pthread/sys/x86_64/pthread_self.S @@ -1,9 +1,9 @@ .code64 -.global pthread_self -.type pthread_self, @function +.global __pthread_self +.type __pthread_self, @function -pthread_self: +__pthread_self: push %rbp mov %rsp, %rbp diff --git a/lib/libc/pthread/thread/pthread.h b/lib/libc/pthread/thread/pthread.h index cfd2873..3854097 100644 --- a/lib/libc/pthread/thread/pthread.h +++ b/lib/libc/pthread/thread/pthread.h @@ -16,6 +16,7 @@ struct __pthread { void *thr_result; }; +extern struct __pthread *__pthread_self(void); extern void __pthread_unmap_exit( kern_handle_t address_space, void *unmap_base, diff --git a/lib/libc/pthread/thread/pthread_self.c b/lib/libc/pthread/thread/pthread_self.c index e69de29..982a68b 100644 --- a/lib/libc/pthread/thread/pthread_self.c +++ b/lib/libc/pthread/thread/pthread_self.c @@ -0,0 +1,36 @@ +#include "pthread.h" + +#include +#include +#include +#include + +static struct __pthread main_thread = {0}; + +struct __pthread *pthread_self(void) +{ + static int init = 0; + if (!init) { + kern_handle_t self_handle = KERN_HANDLE_INVALID; + kern_status_t status = thread_self(&self_handle); + if (status != KERN_OK) { + /* TODO set an errno value in a way that doesn't result + * in a recursive call to pthread_self */ + return NULL; + } + struct __pthread *self = &main_thread; + self->thr_self = self; + self->thr_handle = self_handle; + self->thr_map_base = self; + self->thr_map_size = sizeof *self; + thread_config_set( + self_handle, + THREAD_CFG_GSBASE, + &self, + sizeof(void *)); + init = 1; + return self; + } + + return __pthread_self(); +}