AuroraRuntime/Source/Threading/Primitives/ThreadCookie.hpp

65 lines
2.8 KiB
C++

/***
Copyright (C) 2023 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: ThreadCookie.hpp
Date: 2023-3-14
Author: Reece
***/
#pragma once
#if defined(AURORA_IS_MODERNNT_DERIVED) && defined(AURORA_IS_64BIT)
extern "C"
{
AuUInt32 GetCurrentThreadIDFast();
}
#elif defined(AURORA_IS_LINUX_DERIVED) && defined(AURORA_ARCH_X64)
unsigned long long __readfsqword(unsigned int) noexcept;
#endif
namespace Aurora::Threading::Primitives
{
#if defined(AURORA_IS_MODERNNT_DERIVED)
using ThreadCookie_t = AuUInt32; // nt optimization: always use non-pointers (thread ids) as cookies
#else
using ThreadCookie_t = AuUInt;
#endif
static auline ThreadCookie_t GetThreadCookie()
{
#if defined(AURORA_IS_MODERNNT_DERIVED)
#if defined(AURORA_ARCH_X86)
__asm {
mov eax, fs:[0x18]
mov eax, [eax + 0x24]
ret
}
#elif defined(AURORA_ARCH_X64)
return ::GetCurrentThreadIDFast();
#else
return GetCurrentThreadId();
#endif
#elif defined(AURORA_IS_LINUX_DERIVED) && defined(AURORA_ARCH_X64)
// _readfsbase_u64 is the modern gcc/intel/msft version of __readgsqword that we need.
// glibc uses fs[0] = "self" with a note pthreads doesnt use this, fs[1]=dtv counter,fs[2]=self (see: tcbhead_t)
// musl uses fs[0] = pSelf, dtv counter, * unused *, * unused *
return (ThreadCookie_t)__readfsqword(0);
//return (ThreadCookie_t)_readfsbase_u64(0);
#elif defined(AURORA_IS_POSIX_DERIVED)
// pthread_self is usually a c-friendly a macro in a header that reads from a segment
// though the result is always a pointer wide
// this should be faster than the worst case of syscall wrappers of nonstandard get thread id of whatever family of os
// example: https://elixir.bootlin.com/musl/v1.1.1/source/arch/arm/pthread_arch.h#L14
// https://elixir.bootlin.com/musl/v1.1.1/source/arch/x32/pthread_arch.h#L1
// powermac segment? https://github.com/phracker/MacOSX-SDKs/blob/041600eda65c6a668f66cb7d56b7d1da3e8bcc93/MacOSX10.3.0.sdk/System/Library/Frameworks/Kernel.framework/Versions/A/Headers/ppc/cpu_capabilities.h#L142
// modern mac? https://github.com/apple/darwin-libpthread/blob/2b46cbcc56ba33791296cd9714b2c90dae185ec7/src/pthread.c#L891
// x86_32 darwin? movl %gs:0x0, %edx https://github.com/apple/darwin-libpthread/blob/2b46cbcc56ba33791296cd9714b2c90dae185ec7/src/pthread_asm.s#L162
// glibc is just slow nested c cancer
// exactly what youd expect at peak freetard
// wont be our problem when we start linking against muslc to get away from their crap
return (ThreadCookie_t)pthread_self();
#else
return (ThreadCookie_t)Threads::GetThreadId();
#endif
}
}