AuroraRuntime/Source/Threading/Primitives/ThreadCookie.hpp
2023-03-22 13:42:07 +00:00

55 lines
2.2 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();
}
#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_IS_32BIT)
__asm {
mov eax, fs:[0x18]
mov eax, [eax + 0x24]
ret
}
#else
return ::GetCurrentThreadIDFast();
#endif
#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
}
}