Skip to content
Merged
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
10 changes: 10 additions & 0 deletions core/libs/prx/libc/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ target_sources(libc PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src/Random.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/HostEntropy.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/Time.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/AtomicBuiltins.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/FileAndHeap.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/FileLock.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/StdioExtras.cpp
Expand Down Expand Up @@ -157,6 +158,15 @@ if(BUILD_TESTING)
set_tests_properties(guest_wide_strings PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
add_test_executable(guest_atomic_builtins_tests ${LIBS_INCLUDE_DIR}/tests/GuestAtomicBuiltins.cpp)
target_include_directories(guest_atomic_builtins_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(guest_atomic_builtins_tests PRIVATE libc)
configure_windows_unwind(guest_atomic_builtins_tests)
add_test(NAME guest_atomic_builtins COMMAND guest_atomic_builtins_tests)
if(WIN32)
set_tests_properties(guest_atomic_builtins PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
add_test_executable(guest_wide_conversion_tests ${LIBS_INCLUDE_DIR}/tests/GuestWideConversion.cpp)
target_include_directories(guest_wide_conversion_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(guest_wide_conversion_tests PRIVATE libc)
Expand Down
95 changes: 95 additions & 0 deletions core/libs/prx/libc/src/AtomicBuiltins.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
#include <cstddef>
#include <cstdint>
#include <stdexcept>
#include <string>

#include "prx/libc/include/General.hpp"

namespace {

using Uint128 = unsigned __int128;

[[noreturn]] void ConsoleTrap(const char* function) {
throw std::runtime_error(std::string(function) + ": the console implementation traps (ud2)");
}

bool CompareExchange16(Uint128* target, Uint128& expected, Uint128 desired) {
std::uint64_t low = static_cast<std::uint64_t>(expected);
std::uint64_t high = static_cast<std::uint64_t>(expected >> 64);
bool exchanged;
asm volatile("lock cmpxchg16b %[target]"
: [target] "+m"(*target), "+a"(low), "+d"(high), "=@ccz"(exchanged)
: "b"(static_cast<std::uint64_t>(desired)), "c"(static_cast<std::uint64_t>(desired >> 64))
: "memory");
expected = (static_cast<Uint128>(high) << 64) | low;
return exchanged;
}

Uint128 ReadHalves(const Uint128* target) {
const auto* halves = reinterpret_cast<const volatile std::uint64_t*>(target);
const std::uint64_t low = halves[0];
const std::uint64_t high = halves[1];
return (static_cast<Uint128>(high) << 64) | low;
}

template<typename TOperation>
Uint128 FetchAndApply16(Uint128* target, TOperation operation) {
Uint128 expected = ReadHalves(target);
while (!CompareExchange16(target, expected, operation(expected))) {
}
return expected;
}

}

extern "C" {

void APS5_VABI __atomic_load_nid_postfix(std::size_t, void*, void*, int) { ConsoleTrap("__atomic_load"); }
void APS5_VABI __atomic_store_nid_postfix(std::size_t, void*, void*, int) { ConsoleTrap("__atomic_store"); }
void APS5_VABI __atomic_exchange_nid_postfix(std::size_t, void*, void*, void*, int) { ConsoleTrap("__atomic_exchange"); }

bool APS5_VABI __atomic_compare_exchange_nid_postfix(std::size_t, void*, void*, void*, int, int) {
ConsoleTrap("__atomic_compare_exchange");
}

bool APS5_VABI __atomic_is_lock_free_nid_postfix(std::size_t size, const void* pointer) {
const std::uintptr_t address = reinterpret_cast<std::uintptr_t>(pointer);
switch (size) {
case 0:
case 1:
return true;
case 2:
case 4:
case 8:
case 16:
return (address & (size - 1)) == 0;
default:
return false;
}
}

Uint128 APS5_VABI __sync_fetch_and_add_16_nid_postfix(Uint128* target, Uint128 value) {
return FetchAndApply16(target, [value](Uint128 current) { return current + value; });
}

Uint128 APS5_VABI __sync_fetch_and_sub_16_nid_postfix(Uint128* target, Uint128 value) {
return FetchAndApply16(target, [value](Uint128 current) { return current - value; });
}

Uint128 APS5_VABI __sync_fetch_and_and_16_nid_postfix(Uint128* target, Uint128 value) {
return FetchAndApply16(target, [value](Uint128 current) { return current & value; });
}

Uint128 APS5_VABI __sync_fetch_and_or_16_nid_postfix(Uint128* target, Uint128 value) {
return FetchAndApply16(target, [value](Uint128 current) { return current | value; });
}

Uint128 APS5_VABI __sync_fetch_and_xor_16_nid_postfix(Uint128* target, Uint128 value) {
return FetchAndApply16(target, [value](Uint128 current) { return current ^ value; });
}

Uint128 APS5_VABI __sync_lock_test_and_set_16_nid_postfix(Uint128* target, Uint128 value) {
return FetchAndApply16(target, [value](Uint128) { return value; });
}

}
86 changes: 86 additions & 0 deletions core/libs/tests/GuestAtomicBuiltins.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
#include "prx/libc/include/general/VabiMacros.hpp"
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <stdexcept>
#include <thread>

using Uint128 = unsigned __int128;

extern "C" {
void APS5_VABI __atomic_load_nid_postfix(std::size_t, void*, void*, int);
void APS5_VABI __atomic_store_nid_postfix(std::size_t, void*, void*, int);
void APS5_VABI __atomic_exchange_nid_postfix(std::size_t, void*, void*, void*, int);
bool APS5_VABI __atomic_compare_exchange_nid_postfix(std::size_t, void*, void*, void*, int, int);
bool APS5_VABI __atomic_is_lock_free_nid_postfix(std::size_t, const void*);
Uint128 APS5_VABI __sync_fetch_and_add_16_nid_postfix(Uint128*, Uint128);
Uint128 APS5_VABI __sync_fetch_and_sub_16_nid_postfix(Uint128*, Uint128);
Uint128 APS5_VABI __sync_fetch_and_and_16_nid_postfix(Uint128*, Uint128);
Uint128 APS5_VABI __sync_fetch_and_or_16_nid_postfix(Uint128*, Uint128);
Uint128 APS5_VABI __sync_fetch_and_xor_16_nid_postfix(Uint128*, Uint128);
Uint128 APS5_VABI __sync_lock_test_and_set_16_nid_postfix(Uint128*, Uint128);
}

static void Require(bool value) { if (!value) std::abort(); }

template<typename TFunction>
static void RequireThrows(TFunction function) {
try {
function();
} catch (const std::runtime_error&) {
return;
}
std::abort();
}

static Uint128 Make(std::uint64_t high, std::uint64_t low) { return (static_cast<Uint128>(high) << 64) | low; }

static void CheckLockFree() {
alignas(16) unsigned char buffer[32] = {};
Require(__atomic_is_lock_free_nid_postfix(0, buffer + 1) && __atomic_is_lock_free_nid_postfix(1, buffer + 3));
Require(__atomic_is_lock_free_nid_postfix(2, buffer + 2) && !__atomic_is_lock_free_nid_postfix(2, buffer + 1));
Require(__atomic_is_lock_free_nid_postfix(4, buffer + 4) && !__atomic_is_lock_free_nid_postfix(4, buffer + 2));
Require(__atomic_is_lock_free_nid_postfix(8, buffer + 8) && !__atomic_is_lock_free_nid_postfix(8, buffer + 4));
Require(__atomic_is_lock_free_nid_postfix(16, buffer + 16) && !__atomic_is_lock_free_nid_postfix(16, buffer + 8));
Require(!__atomic_is_lock_free_nid_postfix(3, buffer) && !__atomic_is_lock_free_nid_postfix(32, buffer));
}

static void CheckGenericTraps() {
alignas(16) unsigned char object[24] = {};
unsigned char other[24] = {};
RequireThrows([&] { __atomic_load_nid_postfix(sizeof(object), object, other, 5); });
RequireThrows([&] { __atomic_store_nid_postfix(sizeof(object), object, other, 5); });
RequireThrows([&] { __atomic_exchange_nid_postfix(sizeof(object), object, other, other, 5); });
RequireThrows([&] { __atomic_compare_exchange_nid_postfix(sizeof(object), object, other, other, 5, 5); });
}

static void CheckSixteenByte() {
alignas(16) Uint128 value = Make(1, ~0ull);
Require(__sync_fetch_and_add_16_nid_postfix(&value, 1) == Make(1, ~0ull) && value == Make(2, 0));
Require(__sync_fetch_and_sub_16_nid_postfix(&value, 1) == Make(2, 0) && value == Make(1, ~0ull));
Require(__sync_fetch_and_and_16_nid_postfix(&value, Make(1, 0xff00)) == Make(1, ~0ull) && value == Make(1, 0xff00));
Require(__sync_fetch_and_or_16_nid_postfix(&value, Make(4, 0xff)) == Make(1, 0xff00) && value == Make(5, 0xffff));
Require(__sync_fetch_and_xor_16_nid_postfix(&value, Make(5, 0xf0f0)) == Make(5, 0xffff) && value == Make(0, 0x0f0f));
Require(__sync_lock_test_and_set_16_nid_postfix(&value, Make(9, 9)) == Make(0, 0x0f0f) && value == Make(9, 9));
}

static void CheckConcurrentAdds() {
alignas(16) Uint128 counter = Make(0, ~0ull - 1000);
constexpr int Iterations = 20000;
auto worker = [&counter] {
for (int i = 0; i < Iterations; ++i) __sync_fetch_and_add_16_nid_postfix(&counter, 1);
};
std::thread first(worker);
std::thread second(worker);
first.join();
second.join();
Require(counter == Make(0, ~0ull - 1000) + 2 * Iterations);
}

int main() {
CheckLockFree();
CheckGenericTraps();
CheckSixteenByte();
CheckConcurrentAdds();
return 0;
}
1 change: 1 addition & 0 deletions docs/dev/debt/libc.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
- [acosl](../../../core/libs/prx/libc/src/Math.cpp) (libc) - computed by the host's math library, like the other libc math functions here, not by the console's (FreeBSD msun ld80 code in Sony's `libc.prx`): results can differ from the console's in the last bit, and on Linux glibc sets `errno` to `EDOM` for `acosl` outside [-1, 1] where msun only raises the floating-point exception. `long double` is the x87 80-bit format, as Sony's `frexpl` uses it (`fldt 0x8(%rsp)`, result in `st(0)`)
- [atanl, sinl, cosl, tanl, sinhl, coshl, tanhl, expl, exp2l, logl, log10l and powl](../../../core/libs/prx/libc/src/Math.cpp) (libc) - computed by the host's math library, as `acosl` is, not by the console's FreeBSD msun ld80 code: results can differ from the console's in the last bit (glibc's `log10l(1000)` is not exactly 3), and on Linux glibc sets `errno` to `EDOM` or `ERANGE` where msun only raises the floating-point exception. `ldexpl` and `truncl` are exact operations and give the console's result; `logb` and `remainder` give the console's value too, but on Linux glibc sets `errno` (`ERANGE` for `logb(0)`, `EDOM` for `remainder` by zero or of an infinity) where msun only raises the floating-point exception
- [std_execute_once](../../../core/libs/prx/libc/Export.cpp) (libc) - assumed to be the plain-named twin of `std::_Execute_once` (`_ZSt13_Execute_onceRSt9once_flagPFiPvS1_PS1_ES1_`, the callee of Dinkumware `call_once`): it delegates there and gets the [thread.once.callonce] semantics already verified for that symbol (one invocation per flag, concurrent callers block until it completes, and a failing or throwing invocation leaves the flag unready so the next caller runs it). The name equivalence is not confirmed on a title, and the callback convention (called with (null, arg, null), non-zero return meaning success) is the twin's, unverified for this symbol
- [__atomic_load, __atomic_store, __atomic_exchange and __atomic_compare_exchange](../../../core/libs/prx/libc/src/AtomicBuiltins.cpp) (libc) - the generic, size-parameterised libatomic entry points are a single `ud2` in the `libc.prx` bundled with PPSA08427 (disassembly), so the console traps on any call; these throw instead
- [Dinkumware mutexes and conditions](../../../core/libs/prx/libc/src/Threads.cpp) (libc) use pointer-to-handle arguments, matching the console aerolib signatures reported in [#3079](https://github.com/boykopovar/AnyPS5/pull/3079). The title's `_Mtx_lock` maps `0` to `_Thrd_success` (0), `0x8002000b` to `_Thrd_busy` (3), and other failures to `_Thrd_error` (4); its internal mutex init recognizes recursive flag `0x100`, while every other type uses default attributes. The observed relock failure for a plain mutex suggests those defaults are error-checking, but that has not been confirmed on hardware. The title's `_Mtx_unlock` and `_Cnd_wait` return success regardless of their internal result. The host implementation treats invalid ownership preconditions as no-ops, and throws for invalid handles, host wait errors and destroying a locked mutex as debug guards; those cases are not confirmed against the console.
- [random, srandom, initstate, setstate](../../../core/libs/prx/libc/src/Random.cpp) (libc) follow FreeBSD 11 [random.c](https://github.com/freebsd/freebsd-src/blob/4ab2e064d7950be84256d671a7ae93f87cc6aa36/lib/libc/stdlib/random.c): the additive feedback generator on a default 128-byte `TYPE_3` table, `good_rand` seeding, state sizes rounded down to 8, 32, 64, 128 or 256 bytes, and `setstate` returning the previous state or null for a rear position past the degree. `initstate` below 8 bytes returns null without setting errno, as that file and its manual do (glibc sets `EINVAL`). FreeBSD does not lock the generator; here every call is serialised by one lock, so concurrent callers draw the serial sequence between them. A null state throws, where FreeBSD faults. That the console's `libSceLibcInternal` uses this FreeBSD code and not another generator is unverified
- [qsort](../../../core/libs/prx/libc/src/FileAndHeap.cpp) (libc) follows FreeBSD 11 [qsort.c](https://github.com/freebsd/freebsd-src/blob/5ed7eb0d97ba4436218e810f61bd059acba984c2/lib/libc/stdlib/qsort.c): Bentley and McIlroy's quicksort, with insertion sort below 7 elements and after a partition pass that swaps nothing, so elements that compare equal end in FreeBSD's order and the comparator is called in the same sequence. That the console's libc uses this FreeBSD code is unverified
Expand Down
Loading