Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions core/libs/prx/libc/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@ if(BUILD_TESTING)
if(WIN32)
set_tests_properties(guest_owned_memory PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
add_test_executable(guest_emutls_tests ${LIBS_INCLUDE_DIR}/tests/GuestEmutls.cpp)
target_include_directories(guest_emutls_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(guest_emutls_tests PRIVATE libc)
configure_windows_unwind(guest_emutls_tests)
add_test(NAME guest_emutls COMMAND guest_emutls_tests)
add_asan_test_options(guest_emutls allocator_may_return_null=1)
if(WIN32)
set_tests_properties(guest_emutls PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()

if(WIN32)
add_test_executable(guest_owned_memory_limits_tests ${LIBS_INCLUDE_DIR}/tests/GuestOwnedMemoryLimits.cpp)
Expand Down Expand Up @@ -302,6 +312,7 @@ if(ANYPS5_ENABLE_TSAN)
endif()

target_sources(libc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/BinaryWordIo.cpp)
target_sources(libc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/Emutls.cpp)
target_sources(libc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/LegacySignals.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/SigvecExport.cpp)

if(BUILD_TESTING)
Expand Down
2 changes: 2 additions & 0 deletions core/libs/prx/libc/include/Api.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "prx/libc/include/GuestLocale.hpp"
#include "prx/libc/include/GuestDirectory.hpp"
#include "prx/libc/include/GuestErrno.hpp"
#include "prx/libc/include/GuestEmutls.hpp"
#include "prx/libc/include/FileStream.hpp"
#include "prx/libc/include/exceptions/Unwind.hpp"
#include "prx/libc/include/exceptions/Runtime.hpp"
Expand Down Expand Up @@ -220,6 +221,7 @@ char* APS5_VABI gets_s_nid_postfix(char* buffer, std::size_t size);
void* APS5_VABI __cxa_demangle_nid_postfix(const char* mangled, char* buf, std::size_t* len, int* status);
int APS5_VABI __cxa_thread_atexit_impl_nid_postfix(void (APS5_VABI *func)(void*), void* arg, void* dso);
int APS5_VABI __cxa_thread_atexit_nid_postfix(void (APS5_VABI *func)(void*), void* arg, void* dso);
void* APS5_VABI __emutls_get_address_nid_postfix(GuestEmutlsControl* control);
int APS5_VABI LibcInternalExtCxaThreadAtexit_nid_postfix(void (APS5_VABI *destructor)(void*), void* object, void* moduleId);
const std::error_category* APS5_VABI _ZSt17iostream_categoryv_nid_postfix();
const std::error_category* APS5_VABI IostreamCategory_nid_no_patch();
Expand Down
15 changes: 15 additions & 0 deletions core/libs/prx/libc/include/GuestEmutls.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#pragma once

#include <cstddef>
#include <cstdint>

struct GuestEmutlsControl {
std::uintptr_t size;
std::uintptr_t alignment;
std::uintptr_t index;
const void* initialValue;
};

static_assert(sizeof(GuestEmutlsControl) == 32);
static_assert(offsetof(GuestEmutlsControl, index) == 16);
static_assert(offsetof(GuestEmutlsControl, initialValue) == 24);
149 changes: 149 additions & 0 deletions core/libs/prx/libc/src/Emutls.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
#include "prx/libc/include/Api.hpp"
#include "prx/libc/include/General.hpp"
#include <algorithm>
#include <bit>
#include <cerrno>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <memory>
#include <mutex>
#include <new>
#include <stdexcept>
#ifdef _WIN32
#include <malloc.h>
#endif

namespace {

void* AllocateAligned(std::size_t size, std::size_t alignment) noexcept {
#ifdef _WIN32
return _aligned_malloc(size, alignment);
#else
void* pointer = nullptr;
return posix_memalign(&pointer, alignment, size) == 0 ? pointer : nullptr;
#endif
}

struct AlignedDelete {
void operator()(void* pointer) const noexcept {
#ifdef _WIN32
_aligned_free(pointer);
#else
std::free(pointer);
#endif
}
};

using Allocation = std::unique_ptr<void, AlignedDelete>;

class ThreadInstances {
struct Entry {
std::uintptr_t index;
void* block;
};

Entry* entries = nullptr;
std::size_t count = 0;
std::size_t capacity = 0;

std::size_t Position(std::uintptr_t index) const noexcept {
if (count == 0) return 0;
const auto* found = std::lower_bound(entries, entries + count, index,
[](const Entry& entry, std::uintptr_t key) { return entry.index < key; });
return static_cast<std::size_t>(found - entries);
}

public:
ThreadInstances() = default;
ThreadInstances(const ThreadInstances&) = delete;
ThreadInstances& operator=(const ThreadInstances&) = delete;

~ThreadInstances() {
for (std::size_t i = 0; i < count; ++i) AlignedDelete{}(entries[i].block);
std::free(entries);
}

void* Find(std::uintptr_t index) const noexcept {
const auto position = Position(index);
return position < count && entries[position].index == index ? entries[position].block : nullptr;
}

bool Insert(std::uintptr_t index, Allocation& block) noexcept {
if (count == capacity) {
if (capacity > std::numeric_limits<std::size_t>::max() / sizeof(Entry) / 2)
return false;
const auto newCapacity = capacity == 0 ? 8 : capacity * 2;
auto* grown = static_cast<Entry*>(std::realloc(entries, newCapacity * sizeof(Entry)));
if (!grown) return false;
entries = grown;
capacity = newCapacity;
}
const auto position = Position(index);
if (position < count)
std::memmove(entries + position + 1, entries + position, (count - position) * sizeof(Entry));
entries[position] = {index, block.release()};
++count;
return true;
}
};

std::mutex controlMutex;
std::uintptr_t nextIndex = 0;
thread_local ThreadInstances instances;

}

extern "C" void* APS5_VABI __emutls_get_address_nid_postfix(GuestEmutlsControl* control) {
if (control == nullptr) throw std::invalid_argument("__emutls_get_address: null control");
const int savedErrno = errno;
GuestEmutlsControl guest{};
std::uintptr_t index;
{
std::lock_guard lock(controlMutex);
if (!GuestCopyIn_nid_no_patch(&guest, control, sizeof(guest)))
throw std::invalid_argument("__emutls_get_address: unreadable control");
const auto alignment = std::max(guest.alignment, static_cast<std::uintptr_t>(sizeof(void*)));
if (!std::has_single_bit(alignment))
throw std::invalid_argument("__emutls_get_address: invalid alignment");
index = guest.index;
if (index == 0) {
if (nextIndex == std::numeric_limits<std::uintptr_t>::max())
throw std::overflow_error("__emutls_get_address: index overflow");
index = nextIndex + 1;
if (!GuestCopyOut_nid_no_patch(&control->index, &index, sizeof(index)))
throw std::invalid_argument("__emutls_get_address: unwritable index");
nextIndex = index;
} else {
nextIndex = std::max(nextIndex, index);
}
}

const auto alignment = std::max(guest.alignment, static_cast<std::uintptr_t>(sizeof(void*)));

if (void* found = instances.Find(index)) {
errno = savedErrno;
return found;
}

Allocation block(AllocateAligned(std::max(guest.size, std::uintptr_t{1}), alignment));
if (!block) {
errno = savedErrno;
throw std::bad_alloc{};
}
if (guest.initialValue != nullptr) {
if (!GuestCopyIn_nid_no_patch(block.get(), guest.initialValue, guest.size))
throw std::invalid_argument("__emutls_get_address: unreadable template");
} else {
std::memset(block.get(), 0, guest.size);
}
void* result = block.get();
if (!instances.Insert(index, block)) {
errno = savedErrno;
throw std::bad_alloc{};
}
errno = savedErrno;
return result;
}
117 changes: 117 additions & 0 deletions core/libs/tests/GuestEmutls.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
#include "prx/libc/include/Api.hpp"
#include <array>
#include <atomic>
#include <barrier>
#include <cerrno>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <limits>
#include <new>
#include <source_location>
#include <stdexcept>
#include <thread>

static void Require(bool condition, std::source_location location = std::source_location::current()) {
if (!condition) {
std::fprintf(stderr, "check failed at line %u\n", location.line());
std::abort();
}
}

template<typename F>
static void Reject(F&& call, std::source_location location = std::source_location::current()) {
bool rejected = false;
try { call(); }
catch (const std::invalid_argument&) { rejected = true; }
Require(rejected, location);
}

int main() {
std::array<std::byte, 32> initial{};
for (std::size_t i = 0; i < initial.size(); ++i)
initial[i] = static_cast<std::byte>(i + 1);
GuestEmutlsControl control{initial.size(), 64, 0, initial.data()};
errno = E2BIG;
auto* first = static_cast<std::byte*>(__emutls_get_address_nid_postfix(&control));
Require(first && reinterpret_cast<std::uintptr_t>(first) % 64 == 0);
Require(control.index != 0 && errno == E2BIG);
for (std::size_t i = 0; i < initial.size(); ++i) Require(first[i] == initial[i]);
first[0] = std::byte{0xa5};
Require(__emutls_get_address_nid_postfix(&control) == first && first[0] == std::byte{0xa5});

GuestEmutlsControl zero{16, 0, 0, nullptr};
auto* zeroBytes = static_cast<std::byte*>(__emutls_get_address_nid_postfix(&zero));
Require(zeroBytes && zero.index != 0 && zero.index != control.index);
for (std::size_t i = 0; i < zero.size; ++i) Require(zeroBytes[i] == std::byte{});

GuestEmutlsControl concurrent{initial.size(), 64, 0, initial.data()};
std::array<void*, 2> addresses{};
std::atomic<bool> start{false};
std::barrier hold{3};
std::array<std::thread, 2> workers;
for (std::size_t i = 0; i < workers.size(); ++i) {
workers[i] = std::thread([&, i] {
while (!start.load(std::memory_order_acquire)) std::this_thread::yield();
auto* bytes = static_cast<std::byte*>(__emutls_get_address_nid_postfix(&concurrent));
Require(bytes && bytes[0] == initial[0]);
bytes[0] = static_cast<std::byte>(i + 0x40);
addresses[i] = bytes;
hold.arrive_and_wait();
Require(__emutls_get_address_nid_postfix(&concurrent) == bytes);
hold.arrive_and_wait();
});
}
start.store(true, std::memory_order_release);
hold.arrive_and_wait();
Require(concurrent.index != 0 && addresses[0] && addresses[1]);
Require(addresses[0] != addresses[1] && addresses[0] != first && addresses[1] != first);
hold.arrive_and_wait();
for (auto& worker : workers) worker.join();
auto* mainBytes = static_cast<std::byte*>(__emutls_get_address_nid_postfix(&concurrent));
Require(mainBytes && mainBytes != first && mainBytes[0] == initial[0]);

Reject([&] { __emutls_get_address_nid_postfix(nullptr); });
Reject([&] { __emutls_get_address_nid_postfix(reinterpret_cast<GuestEmutlsControl*>(1)); });
GuestEmutlsControl badAlignment{8, 12, 0, nullptr};
Reject([&] { __emutls_get_address_nid_postfix(&badAlignment); });
GuestEmutlsControl badTemplate{8, 8, 0, reinterpret_cast<const void*>(1)};
Reject([&] { __emutls_get_address_nid_postfix(&badTemplate); });

GuestEmutlsControl tooLarge{std::numeric_limits<std::uintptr_t>::max() / 2, 64, 0, nullptr};
bool allocationFailed = false;
try { __emutls_get_address_nid_postfix(&tooLarge); }
catch (const std::bad_alloc&) { allocationFailed = true; }
Require(allocationFailed);

const auto assignedIndex = tooLarge.index;
tooLarge.size = 16;
auto* retried = static_cast<std::byte*>(__emutls_get_address_nid_postfix(&tooLarge));
Require(assignedIndex != 0 && tooLarge.index == assignedIndex);
Require(retried && reinterpret_cast<std::uintptr_t>(retried) % 64 == 0);
for (std::size_t i = 0; i < tooLarge.size; ++i) Require(retried[i] == std::byte{});
Require(__emutls_get_address_nid_postfix(&tooLarge) == retried);

constexpr std::size_t controlCount = 12;
std::array<GuestEmutlsControl, controlCount> controls{};
for (auto& entry : controls) {
entry.size = 1;
Require(__emutls_get_address_nid_postfix(&entry) != nullptr);
}
Require(__emutls_get_address_nid_postfix(&control) == first);
std::thread reverseOrder([&] {
std::array<void*, controlCount> reverseAddresses{};
for (std::size_t i = controls.size(); i-- > 0;) {
auto* bytes = static_cast<std::byte*>(__emutls_get_address_nid_postfix(&controls[i]));
Require(bytes && bytes[0] == std::byte{});
bytes[0] = static_cast<std::byte>(i + 1);
reverseAddresses[i] = bytes;
}
for (std::size_t i = 0; i < controls.size(); ++i) {
auto* bytes = static_cast<std::byte*>(__emutls_get_address_nid_postfix(&controls[i]));
Require(bytes == reverseAddresses[i] && bytes[0] == static_cast<std::byte>(i + 1));
}
});
reverseOrder.join();
}
5 changes: 5 additions & 0 deletions docs/dev/debt/changes/feat-libc-emutls-address.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# libc

## add Functional

- [__emutls_get_address](../../../core/libs/prx/libc/src/Emutls.cpp) (libc) - implements the 64-bit GCC/LLVM compiler-emulated TLS control layout, allocating an aligned copy of each variable's template per host thread and returning that thread's stable address. The control index is shared across threads and initialized once. The console firmware provider and behavior when guest fibers share a host thread have not been measured; Azahar PPSA99169's exact unresolved import is the motivation, but the title was not run with this change.
Loading