#include "prx/libkernel_sys/include/Api.hpp" #include "prx/libkernel/Time/include/Time.hpp" #include "prx/libc/include/Api.hpp" #include #include #include #include #include #include #include "SceTypes.hpp" #include "prx/libc/include/General.hpp" #include "prx/libc/include/HostEntropy.hpp" static_assert(sizeof(GuestUuid) == 16); namespace { constexpr int GuestEfault = 14; constexpr int GuestEinval = 22; constexpr int GuestClockRealtime = 0; constexpr int UuidgenMaxCount = 2048; constexpr std::uint64_t UuidTimeMask = (std::uint64_t{1} << 60) - 1; constexpr std::uint64_t UuidGregorianOffset = 0x01B21DD213814000ULL; std::mutex uuidMutex; std::array uuidNode{}; bool uuidNodeReady = false; std::uint64_t uuidLastTime = 0; std::uint16_t uuidLastSequence = 0; int Fail(int error) { *__error_nid_postfix() = error; return -1; } std::uint64_t UuidTime() { KernelTimespec now{}; if (clock_gettime_nid_postfix(GuestClockRealtime, &now) != 0) throw std::runtime_error("uuidgen: clock_gettime(CLOCK_REALTIME) failed"); const auto ticks = UuidGregorianOffset + static_cast(now.tv_sec) * 10000000ULL + static_cast(now.tv_nsec) / 100; return ticks & UuidTimeMask; } } extern "C" { int APS5_VABI uuidgen_nid_postfix(GuestUuid* store, int count) { if (count < 1 || count > UuidgenMaxCount) return Fail(GuestEinval); std::uint64_t time = 0; std::uint16_t sequence = 0; std::array node{}; { std::lock_guard lock(uuidMutex); if (!uuidNodeReady) { HostEntropy_nid_no_patch(uuidNode.data(), uuidNode.size()); uuidNode[0] |= 0x01; uuidNodeReady = true; } node = uuidNode; time = UuidTime(); if (uuidLastTime == 0) { HostEntropy_nid_no_patch(&sequence, sizeof(sequence)); sequence &= 0x3fff; } else if (uuidLastTime >= time) { sequence = static_cast((uuidLastSequence + 1) & 0x3fff); } else { sequence = uuidLastSequence; } uuidLastSequence = sequence; uuidLastTime = (time + static_cast(count) - 1) & UuidTimeMask; } std::vector generated(static_cast(count)); const auto variantSequence = static_cast(sequence | 0x8000); for (int index = 0; index < count; ++index, ++time) { generated[index].timeLow = static_cast(time); generated[index].timeMid = static_cast(time >> 32); generated[index].timeHiAndVersion = static_cast(((time >> 48) & 0x0fff) | 0x1000); generated[index].clockSeqHiAndReserved = static_cast(variantSequence >> 8); generated[index].clockSeqLow = static_cast(variantSequence); std::memcpy(generated[index].node, node.data(), node.size()); } if (!GuestCopyOut_nid_no_patch(store, generated.data(), sizeof(GuestUuid) * static_cast(count))) { return Fail(GuestEfault); } return 0; } }