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
169 changes: 130 additions & 39 deletions core/libs/prx/libSceNKWebKit/src/ParallelEnvironment.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,50 @@
*/

#include "prx/libc/include/general/VabiMacros.hpp"
#include "prx/libc/include/General.hpp"
#include "prx/libc/include/GuestArena.hpp"
#include "prx/libkernel/include/Api.hpp"
#include "prx/libSceNKWebKit/include/ParallelEnvironmentExports.hpp"
#include "prx/libSceNKWebKit/include/WtfExports.hpp"

#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <mutex>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <vector>

namespace {

using NKWebKit::WtfAbi::ParallelEnvironment;
using NKWebKit::WtfAbi::ParallelEnvironmentFunction;
using NKWebKit::WtfAbi::ParallelEnvironmentThread;
using NKWebKit::WtfAbi::ParallelEnvironmentThreadVector;

struct ParallelEnvironmentPrefix {
ParallelEnvironmentFunction threadFunction;
std::size_t sizeOfParameter;
int numberOfJobs;
};

static_assert(std::is_trivially_copyable_v<ParallelEnvironment>);
static_assert(std::is_trivially_copyable_v<ParallelEnvironmentPrefix>);
static_assert(std::is_trivially_copyable_v<ParallelEnvironmentThreadVector>);
static_assert(offsetof(ParallelEnvironmentPrefix, threadFunction) == offsetof(ParallelEnvironment, threadFunction));
static_assert(offsetof(ParallelEnvironmentPrefix, sizeOfParameter) == offsetof(ParallelEnvironment, sizeOfParameter));
static_assert(offsetof(ParallelEnvironmentPrefix, numberOfJobs) == offsetof(ParallelEnvironment, numberOfJobs));
constexpr std::size_t kPrefixWriteBytes = offsetof(ParallelEnvironment, numberOfJobs) + sizeof(int);

void RequireReadableGuestBytes(const void* pointer, std::size_t size, const char* function) {
if (!size) return;
if (!pointer) NotImplementedAt_nid_no_patch(function, __FILE__, __LINE__);
GuestArena::GuestArenaPrepareHostRead_nid_no_patch(pointer, size);
if (!GuestReadable_nid_no_patch(pointer, size))
NotImplementedAt_nid_no_patch(function, __FILE__, __LINE__);
}

struct Worker : ParallelEnvironmentThread {
std::mutex lock;
Expand All @@ -56,10 +84,6 @@ struct Worker : ParallelEnvironmentThread {
Worker() : ParallelEnvironmentThread{1} {}
};

Worker& WorkerOf(ParallelEnvironmentThread* shared) {
return *static_cast<Worker*>(shared);
}

std::vector<Worker*>& ThreadPool() {
static std::vector<Worker*>* const pool = new std::vector<Worker*>;
return *pool;
Expand Down Expand Up @@ -98,33 +122,119 @@ bool TryLockFor(Worker& worker, ParallelEnvironment* parent) {
return true;
}

void Construct(ParallelEnvironment* self, ParallelEnvironmentFunction threadFunction, std::size_t sizeOfParameter, int requestedJobNumber) {
struct ConstructGuard {
std::vector<Worker*> taken;
unsigned retainedCount{0};
ParallelEnvironmentThread** buffer{nullptr};
bool armed{true};

~ConstructGuard() {
if (!armed) return;
for (unsigned index = 0; index < retainedCount; ++index) --taken[index]->refCount;
for (Worker* worker : taken) {
std::lock_guard lock(worker->lock);
worker->parent = nullptr;
}
if (buffer) _ZN3WTF8fastFreeEPv(buffer);
}

ConstructGuard() = default;
ConstructGuard(const ConstructGuard&) = delete;
ConstructGuard& operator=(const ConstructGuard&) = delete;
};

void Construct(ParallelEnvironment* self, ParallelEnvironmentFunction threadFunction, std::size_t sizeOfParameter, int requestedJobNumber, const char* function) {
if (!self) throw std::invalid_argument("null WTF::ParallelEnvironment");
const GuestArena::HostWrite writeGuard(self, sizeof(ParallelEnvironment));
if (!writeGuard.Open() || !GuestWritable_nid_no_patch(self, sizeof(ParallelEnvironment)))
NotImplementedAt_nid_no_patch(function, __FILE__, __LINE__);
const int maxNumberOfCores = _ZN3WTF22numberOfProcessorCoresEv();
if (!requestedJobNumber || requestedJobNumber > maxNumberOfCores) requestedJobNumber = maxNumberOfCores;
const int maxNumberOfNewThreads = requestedJobNumber - 1;
std::vector<Worker*> taken;
ConstructGuard guard;
if (maxNumberOfCores > 0) guard.taken.reserve(static_cast<std::size_t>(maxNumberOfCores));
{
std::lock_guard poolLock(ThreadPoolLock());
std::vector<Worker*>& pool = ThreadPool();
for (int index = 0; index < maxNumberOfCores && taken.size() < static_cast<unsigned>(maxNumberOfNewThreads); ++index) {
for (int index = 0; index < maxNumberOfCores && guard.taken.size() < static_cast<unsigned>(maxNumberOfNewThreads); ++index) {
if (pool.size() < static_cast<unsigned>(index) + 1U) pool.push_back(new Worker);
if (TryLockFor(*pool[index], self)) taken.push_back(pool[index]);
if (TryLockFor(*pool[index], self)) guard.taken.push_back(pool[index]);
}
}
const auto count = static_cast<unsigned>(taken.size());
ParallelEnvironmentThread** buffer = nullptr;
const auto count = static_cast<unsigned>(guard.taken.size());
if (count) {
buffer = static_cast<ParallelEnvironmentThread**>(_ZN3WTF10fastMallocEm(count * sizeof(ParallelEnvironmentThread*)));
guard.buffer = static_cast<ParallelEnvironmentThread**>(_ZN3WTF10fastMallocEm(count * sizeof(ParallelEnvironmentThread*)));
for (unsigned index = 0; index < count; ++index) {
++taken[index]->refCount;
buffer[index] = taken[index];
++guard.taken[index]->refCount;
guard.retainedCount = index + 1;
guard.buffer[index] = guard.taken[index];
}
}
self->threadFunction = threadFunction;
self->sizeOfParameter = sizeOfParameter;
self->numberOfJobs = static_cast<int>(count) + 1;
self->threads = {buffer, count, count};
const ParallelEnvironmentPrefix prefix{threadFunction, sizeOfParameter, static_cast<int>(count) + 1};
const ParallelEnvironmentThreadVector threads{guard.buffer, count, count};
if (!GuestCopyOut_nid_no_patch(self, &prefix, kPrefixWriteBytes))
NotImplementedAt_nid_no_patch(function, __FILE__, __LINE__);
if (!GuestCopyOut_nid_no_patch(reinterpret_cast<unsigned char*>(self) + offsetof(ParallelEnvironment, threads), &threads, sizeof(threads)))
NotImplementedAt_nid_no_patch(function, __FILE__, __LINE__);
guard.armed = false;
}

void Execute(ParallelEnvironment* self, void* parameters, const char* function) {
if (!self) throw std::invalid_argument("null WTF::ParallelEnvironment");
ParallelEnvironment local{};
if (!GuestCopyIn_nid_no_patch(&local, self, sizeof(local)))
NotImplementedAt_nid_no_patch(function, __FILE__, __LINE__);
if (!local.threadFunction) throw std::invalid_argument("WTF::ParallelEnvironment::execute: null thread function");

std::vector<Worker*> workers;
if (local.threads.size) {
if (!local.threads.buffer) NotImplementedAt_nid_no_patch(function, __FILE__, __LINE__);
if (local.threads.size > std::numeric_limits<std::size_t>::max() / sizeof(ParallelEnvironmentThread*))
NotImplementedAt_nid_no_patch(function, __FILE__, __LINE__);
const std::size_t totalBytes = static_cast<std::size_t>(local.threads.size) * sizeof(ParallelEnvironmentThread*);
const auto baseAddress = reinterpret_cast<std::uintptr_t>(local.threads.buffer);
if (totalBytes > std::numeric_limits<std::uintptr_t>::max() - baseAddress)
NotImplementedAt_nid_no_patch(function, __FILE__, __LINE__);
RequireReadableGuestBytes(local.threads.buffer, totalBytes, function);
std::vector<ParallelEnvironmentThread*> rawThreads(local.threads.size);
if (!GuestCopyIn_nid_no_patch(rawThreads.data(), local.threads.buffer, totalBytes))
NotImplementedAt_nid_no_patch(function, __FILE__, __LINE__);
workers.reserve(local.threads.size);
std::lock_guard poolLock(ThreadPoolLock());
const std::vector<Worker*>& pool = ThreadPool();
for (ParallelEnvironmentThread* entry : rawThreads) {
if (!entry) NotImplementedAt_nid_no_patch(function, __FILE__, __LINE__);
Worker* matched = nullptr;
for (Worker* candidate : pool) {
if (static_cast<ParallelEnvironmentThread*>(candidate) == entry) {
matched = candidate;
break;
}
}
if (!matched) NotImplementedAt_nid_no_patch(function, __FILE__, __LINE__);
for (Worker* existing : workers) {
if (existing == matched) NotImplementedAt_nid_no_patch(function, __FILE__, __LINE__);
}
workers.push_back(matched);
}
}

auto currentAddress = reinterpret_cast<std::uintptr_t>(parameters);
for (Worker* worker : workers) {
{
std::lock_guard lock(worker->lock);
worker->threadFunction = local.threadFunction;
worker->parameters = reinterpret_cast<void*>(currentAddress);
worker->running = true;
}
worker->condition.notify_one();
currentAddress += local.sizeOfParameter;
}
local.threadFunction(reinterpret_cast<void*>(currentAddress));
for (Worker* worker : workers) {
std::unique_lock lock(worker->lock);
worker->condition.wait(lock, [worker] { return !worker->running; });
}
}

} // namespace
Expand All @@ -133,35 +243,16 @@ extern "C" {

void APS5_VABI _ZN3WTF19ParallelEnvironmentC1EPFvPvEmi(
ParallelEnvironment* self, ParallelEnvironmentFunction threadFunction, std::size_t sizeOfParameter, int requestedJobNumber) {
Construct(self, threadFunction, sizeOfParameter, requestedJobNumber);
Construct(self, threadFunction, sizeOfParameter, requestedJobNumber, __func__);
}

void APS5_VABI _ZN3WTF19ParallelEnvironmentC2EPFvPvEmi(
ParallelEnvironment* self, ParallelEnvironmentFunction threadFunction, std::size_t sizeOfParameter, int requestedJobNumber) {
Construct(self, threadFunction, sizeOfParameter, requestedJobNumber);
Construct(self, threadFunction, sizeOfParameter, requestedJobNumber, __func__);
}

void APS5_VABI _ZN3WTF19ParallelEnvironment7executeEPv(ParallelEnvironment* self, void* parameters) {
if (!self) throw std::invalid_argument("null WTF::ParallelEnvironment");
if (!self->threadFunction) throw std::invalid_argument("WTF::ParallelEnvironment::execute: null thread function");
auto* currentParameter = static_cast<unsigned char*>(parameters);
for (unsigned index = 0; index < self->threads.size; ++index) {
Worker& worker = WorkerOf(self->threads.buffer[index]);
{
std::lock_guard lock(worker.lock);
worker.threadFunction = self->threadFunction;
worker.parameters = currentParameter;
worker.running = true;
}
worker.condition.notify_one();
currentParameter += self->sizeOfParameter;
}
self->threadFunction(currentParameter);
for (unsigned index = 0; index < self->threads.size; ++index) {
Worker& worker = WorkerOf(self->threads.buffer[index]);
std::unique_lock lock(worker.lock);
worker.condition.wait(lock, [&worker] { return !worker.running; });
}
Execute(self, parameters, __func__);
}

}
116 changes: 116 additions & 0 deletions core/libs/prx/libSceNKWebKit/tests/ParallelEnvironment.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,19 @@
#include <memory>
#include <set>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#else
#include <sys/mman.h>
#include <unistd.h>
#endif

using NKWebKit::WtfAbi::ParallelEnvironment;
using NKWebKit::WtfAbi::ParallelEnvironmentThread;

Expand Down Expand Up @@ -279,6 +289,111 @@ static void TestAnEnvironmentThatNeverRuns() {
next.Run();
}

struct GuardedPages {
unsigned char* base{nullptr};
std::size_t pageSize{0};

GuardedPages() {
#ifdef _WIN32
SYSTEM_INFO info{};
GetSystemInfo(&info);
pageSize = info.dwPageSize;
base = static_cast<unsigned char*>(VirtualAlloc(nullptr, pageSize * 3, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
Require(base != nullptr);
DWORD previous = 0;
Require(VirtualProtect(base + pageSize, pageSize, PAGE_READONLY, &previous) != 0);
Require(VirtualProtect(base + pageSize * 2, pageSize, PAGE_NOACCESS, &previous) != 0);
#else
const long size = sysconf(_SC_PAGESIZE);
Require(size > 0);
pageSize = static_cast<std::size_t>(size);
void* mapped = mmap(nullptr, pageSize * 3, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
Require(mapped != MAP_FAILED);
base = static_cast<unsigned char*>(mapped);
Require(mprotect(base + pageSize, pageSize, PROT_READ) == 0);
Require(mprotect(base + pageSize * 2, pageSize, PROT_NONE) == 0);
#endif
}

~GuardedPages() {
if (!base) return;
#ifdef _WIN32
Require(VirtualFree(base, 0, MEM_RELEASE) != 0);
#else
Require(munmap(base, pageSize * 3) == 0);
#endif
}

unsigned char* ReadOnly() const { return base + pageSize; }
unsigned char* Guard() const { return base + pageSize * 2; }
};

template<typename TFunction>
static bool ThrowsNotImplemented(TFunction&& function, const char* symbol) {
try {
function();
} catch (const std::runtime_error& error) {
return std::string(error.what()) == std::string(symbol) + " not implemented";
}
return false;
}

static void TestGuestPointers() {
GuardedPages pages;
Parameter parameter;
auto* readOnly = reinterpret_cast<ParallelEnvironment*>(pages.ReadOnly());
auto* guard = reinterpret_cast<ParallelEnvironment*>(pages.Guard());
auto* dangling = reinterpret_cast<ParallelEnvironment*>(0x10);
unsigned char* splitWritable = pages.ReadOnly() - 16;
std::memset(splitWritable, 0x5A, 16);

Require(ThrowsNotImplemented([&] { construct(readOnly, &Work, sizeof(Parameter), 2); }, "_ZN3WTF19ParallelEnvironmentC1EPFvPvEmi"));
Require(ThrowsNotImplemented([&] { _ZN3WTF19ParallelEnvironmentC2EPFvPvEmi(guard, &Work, sizeof(Parameter), 2); }, "_ZN3WTF19ParallelEnvironmentC2EPFvPvEmi"));
Require(ThrowsNotImplemented([&] { construct(dangling, &Work, sizeof(Parameter), 2); }, "_ZN3WTF19ParallelEnvironmentC1EPFvPvEmi"));
Require(ThrowsNotImplemented([&] { construct(reinterpret_cast<ParallelEnvironment*>(splitWritable), &Work, sizeof(Parameter), 2); }, "_ZN3WTF19ParallelEnvironmentC1EPFvPvEmi"));
for (std::size_t i = 0; i < 16; ++i) Require(splitWritable[i] == 0x5A);

Require(ThrowsNotImplemented([&] { execute(guard, &parameter); }, "_ZN3WTF19ParallelEnvironment7executeEPv"));
Require(ThrowsNotImplemented([&] { execute(dangling, &parameter); }, "_ZN3WTF19ParallelEnvironment7executeEPv"));
Require(ThrowsNotImplemented([&] { execute(reinterpret_cast<ParallelEnvironment*>(pages.Guard() - 16), &parameter); }, "_ZN3WTF19ParallelEnvironment7executeEPv"));

ParallelEnvironment badBuffer{};
badBuffer.threadFunction = &Work;
badBuffer.sizeOfParameter = sizeof(Parameter);
badBuffer.numberOfJobs = 2;
badBuffer.threads.buffer = reinterpret_cast<ParallelEnvironmentThread**>(pages.Guard());
badBuffer.threads.capacity = 1;
badBuffer.threads.size = 1;
Require(ThrowsNotImplemented([&] { execute(&badBuffer, &parameter); }, "_ZN3WTF19ParallelEnvironment7executeEPv"));
Require(parameter.calls.load() == 0);

ParallelEnvironmentThread* forgedWorker = reinterpret_cast<ParallelEnvironmentThread*>(pages.Guard());
ParallelEnvironment badWorker{};
badWorker.threadFunction = &Work;
badWorker.sizeOfParameter = sizeof(Parameter);
badWorker.numberOfJobs = 2;
badWorker.threads.buffer = &forgedWorker;
badWorker.threads.capacity = 1;
badWorker.threads.size = 1;
Require(ThrowsNotImplemented([&] { execute(&badWorker, &parameter); }, "_ZN3WTF19ParallelEnvironment7executeEPv"));
Require(parameter.calls.load() == 0);

if (cores >= 2) {
Environment validEnv(2);
ParallelEnvironmentThread* duplicateWorkers[2] = {validEnv.Thread(0), validEnv.Thread(0)};
ParallelEnvironment dupEnv{};
dupEnv.threadFunction = &Work;
dupEnv.sizeOfParameter = sizeof(Parameter);
dupEnv.numberOfJobs = 3;
dupEnv.threads.buffer = duplicateWorkers;
dupEnv.threads.capacity = 2;
dupEnv.threads.size = 2;
Require(ThrowsNotImplemented([&] { execute(&dupEnv, &parameter); }, "_ZN3WTF19ParallelEnvironment7executeEPv"));
Require(parameter.calls.load() == 0);
validEnv.Run();
}
}

int main() {
std::thread([] {
std::this_thread::sleep_for(std::chrono::seconds(20));
Expand All @@ -299,6 +414,7 @@ int main() {
TestSimultaneousConstruction();
TestInvalidArguments();
TestAnEnvironmentThatNeverRuns();
TestGuestPointers();
std::puts("libSceNKWebKit parallel environment tests passed");
return 0;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# libSceNKWebKit

## add Functional

- [ParallelEnvironment guest pointer fault behavior](../../../core/libs/prx/libSceNKWebKit/src/ParallelEnvironment.cpp) (libSceNKWebKit) - Console fault behavior for invalid guest pointers in `WTF::ParallelEnvironment` constructors and `execute` is unmeasured; constructors preflight writable guest storage under `GuestArena::HostWrite`, copy initialized field ranges through `GuestCopyOut_nid_no_patch` while preserving struct padding and rolling back acquired worker pool entries on failure, and `execute` copies `ParallelEnvironment` and its thread pointer table through `GuestCopyIn_nid_no_patch` and verifies unique live worker-pool membership before dispatching, calling `NotImplementedAt_nid_no_patch` on unmapped, unreadable, unwritable, or invalid worker pointers. Closes when: console behavior for invalid guest pointers in `WTF::ParallelEnvironment` exports is verified on hardware.