From 52b4f0ee5e2455a1b72b349a08ad791dcc4e069a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo?= Date: Sun, 15 Dec 2024 09:17:36 -0300 Subject: [PATCH] Cross-platform TLS. (#34) * Cross-platform TLS. * Fix front() to back(), use Mutex. * Fix global variable namings. --------- Co-authored-by: Skyth <19259897+blueskythlikesclouds@users.noreply.github.com> --- UnleashedRecomp/kernel/imports.cpp | 34 ++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/UnleashedRecomp/kernel/imports.cpp b/UnleashedRecomp/kernel/imports.cpp index 85be3c39..8fb0962d 100644 --- a/UnleashedRecomp/kernel/imports.cpp +++ b/UnleashedRecomp/kernel/imports.cpp @@ -890,24 +890,50 @@ DWORD KeWaitForSingleObject(XDISPATCHER_HEADER* Object, DWORD WaitReason, DWORD return WaitForSingleObjectEx(handle, timeout, Alertable); } +static thread_local std::vector g_tlsValues; +static std::vector g_tlsFreeIndices; +static size_t g_tlsNextIndex = 0; +static Mutex g_tlsAllocationMutex; + +static void KeTlsEnsureTlsCapacity(size_t index) +{ + if (g_tlsValues.size() <= index) + { + g_tlsValues.resize(index + 1, 0); + } +} + uint32_t KeTlsGetValue(DWORD dwTlsIndex) { - return (uint32_t)TlsGetValue(dwTlsIndex); + KeTlsEnsureTlsCapacity(dwTlsIndex); + return g_tlsValues[dwTlsIndex]; } BOOL KeTlsSetValue(DWORD dwTlsIndex, DWORD lpTlsValue) { - return TlsSetValue(dwTlsIndex, (LPVOID)lpTlsValue); + KeTlsEnsureTlsCapacity(dwTlsIndex); + g_tlsValues[dwTlsIndex] = lpTlsValue; + return TRUE; } DWORD KeTlsAlloc() { - return TlsAlloc(); + std::lock_guard lock(g_tlsAllocationMutex); + if (!g_tlsFreeIndices.empty()) + { + size_t index = g_tlsFreeIndices.back(); + g_tlsFreeIndices.pop_back(); + return index; + } + + return g_tlsNextIndex++; } BOOL KeTlsFree(DWORD dwTlsIndex) { - return TlsFree(dwTlsIndex); + std::lock_guard lock(g_tlsAllocationMutex); + g_tlsFreeIndices.push_back(dwTlsIndex); + return TRUE; } DWORD XMsgInProcessCall(uint32_t app, uint32_t message, XDWORD* param1, XDWORD* param2)