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
46 changes: 9 additions & 37 deletions test-app/runtime/src/main/cpp/Runtime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -145,14 +145,7 @@ Runtime::Runtime(JNIEnv* env, jobject runtime, int id)
}
}

Runtime* Runtime::GetRuntime(int runtimeId) {
// A runtime is only destroyed on its own thread, which is busy in this call,
// so the calling thread's own runtime needs neither the lock nor the map.
auto& current = s_current;
if (runtimeId == current.id) {
return current.runtime;
}

Runtime* Runtime::GetRuntimeSlow(int runtimeId) {
Runtime* runtime = nullptr;
{
std::lock_guard<std::mutex> lock(s_runtimeCacheMutex);
Expand All @@ -169,18 +162,8 @@ Runtime* Runtime::GetRuntime(int runtimeId) {
return runtime;
}

Runtime* Runtime::GetRuntime(v8::Isolate* isolate) {
/*
* Hot path, called from V8 callbacks on the isolate's own thread. The slot
* is written once in PrepareV8Runtime before the isolate runs any JS, so
* reading it requires no lock.
*/
auto runtime = TryGetRuntime(isolate);
if (runtime != nullptr) {
return runtime;
}

// covers the window during isolate setup before SetData has run
Runtime* Runtime::GetRuntimeSlow(v8::Isolate* isolate) {
Runtime* runtime;
{
std::lock_guard<std::mutex> lock(s_runtimeCacheMutex);
auto it = s_isolate2RuntimesCache.find(isolate);
Expand All @@ -196,18 +179,6 @@ Runtime* Runtime::GetRuntime(v8::Isolate* isolate) {
return runtime;
}

Runtime* Runtime::GetRuntimeFromIsolateData(v8::Isolate* isolate) {
auto runtime = TryGetRuntime(isolate);

if (runtime == nullptr) {
stringstream ss;
ss << "Cannot find runtime for isolate: " << isolate;
throw NativeScriptException(ss.str());
}

return runtime;
}

ObjectManager* Runtime::GetObjectManager(v8::Isolate* isolate) {
return GetRuntime(isolate)->GetObjectManager();
}
Expand Down Expand Up @@ -600,9 +571,10 @@ struct CallbackMethodNames {
std::vector<v8::Global<v8::String>> byId;
};

Local<String> GetCallbackMethodName(Isolate* isolate, JNIEnv* env,
jstring methodName, jint methodNameId) {
auto* names = RuntimeState::For<CallbackMethodNames>(isolate);
Local<String> GetCallbackMethodName(Runtime* runtime, Isolate* isolate,
JNIEnv* env, jstring methodName,
jint methodNameId) {
auto* names = RuntimeState::For<CallbackMethodNames>(runtime);
if (names == nullptr || methodNameId < 0) {
return ArgConverter::jstringToInternalizedV8String(isolate, env, methodName);
}
Expand Down Expand Up @@ -664,7 +636,7 @@ jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj,
jsObject->GetIdentityHash());

auto jsMethodName =
GetCallbackMethodName(m_isolate, _env, methodName, methodNameId);
GetCallbackMethodName(this, m_isolate, _env, methodName, methodNameId);
auto jsResult = CallbackHandlers::CallJSMethod(m_isolate, env, jsObject,
jsMethodName, args);

Expand Down Expand Up @@ -1410,7 +1382,7 @@ v8::Platform* Runtime::platform = nullptr;
int Runtime::m_androidVersion = Runtime::GetAndroidVersion();
std::shared_ptr<EventLoop> Runtime::s_mainEventLoop;

thread_local Runtime::CurrentRuntime Runtime::s_current;
constinit thread_local Runtime::CurrentRuntime Runtime::s_current;
thread_local PendingIsolateSetup Runtime::s_pendingIsolateSetup;

void Runtime::SetPendingIsolateSetup(PendingIsolateSetup setup) {
Expand Down
37 changes: 32 additions & 5 deletions test-app/runtime/src/main/cpp/Runtime.h
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,28 @@ class Runtime {
*/
static void SetPendingIsolateSetup(PendingIsolateSetup setup);

static Runtime* GetRuntime(int runtimeId);

static Runtime* GetRuntime(v8::Isolate* isolate);
static Runtime* GetRuntime(int runtimeId) {
// A runtime is only destroyed on its own thread, which is busy in
// this call, so the calling thread's own runtime needs neither the
// lock nor the map.
auto& current = s_current;
if (runtimeId == current.id) [[likely]] {
return current.runtime;
}
return GetRuntimeSlow(runtimeId);
}

static Runtime* GetRuntimeFromIsolateData(v8::Isolate* isolate);
/*
* Hot path, called from V8 callbacks on the isolate's own thread. The
* slot is written once in PrepareV8Runtime before the isolate runs any
* JS, so reading it requires no lock.
*/
static Runtime* GetRuntime(v8::Isolate* isolate) {
if (auto* runtime = TryGetRuntime(isolate)) [[likely]] {
return runtime;
}
return GetRuntimeSlow(isolate);
}

/*
* The runtime for this isolate, or null. Unlike the accessors above it
Expand Down Expand Up @@ -363,6 +380,14 @@ class Runtime {
}

private:
// Another thread's runtime, looked up under the lock; throws when the
// id names no live runtime.
static Runtime* GetRuntimeSlow(int runtimeId);

// Covers the window during isolate setup before the data slot is set;
// throws when the isolate has no runtime.
static Runtime* GetRuntimeSlow(v8::Isolate* isolate);

Runtime(JNIEnv* env, jobject runtime, int id);

int m_id;
Expand Down Expand Up @@ -490,7 +515,9 @@ class Runtime {
Runtime* runtime = nullptr;
int id = -1;
};
static thread_local CurrentRuntime s_current;
// constinit lets other translation units read it without first
// calling its thread-local initialization hook.
static constinit thread_local CurrentRuntime s_current;
static thread_local PendingIsolateSetup s_pendingIsolateSetup;

#ifdef APPLICATION_IN_DEBUG
Expand Down
33 changes: 28 additions & 5 deletions test-app/runtime/src/main/cpp/RuntimeState.cpp
Original file line number Diff line number Diff line change
@@ -1,13 +1,36 @@
#include "RuntimeState.h"

#include <atomic>

#include "NativeScriptAssert.h"

namespace tns {

size_t RuntimeState::NextSlotIndex() {
// Slot indices are claimed the first time a state type is used, which can
// happen on any runtime's thread -- two workers touching two different
// subsystems for the first time race here.
size_t RuntimeState::ClaimSlotIndex() {
// Constant-initialized: called from the dynamic initializers of
// RuntimeState::kSlotIndex, in whatever order the library runs them.
static std::atomic<size_t> next{0};
return next.fetch_add(1, std::memory_order_relaxed);
size_t index = next.fetch_add(1, std::memory_order_relaxed);
NS_CHECK(index < kCapacity);
return index;
}

void RuntimeState::Clear() {
disposed_ = true;

// Every slot is emptied before any state is destroyed, so a destructor
// that looks up state, its own included, gets null.
void* values[kCapacity];
for (size_t i = 0; i < kCapacity; i++) {
values[i] = slots_[i];
slots_[i] = nullptr;
}

for (size_t i = kCapacity; i-- > 0;) {
if (values[i] != nullptr) {
deleters_[i](values[i]);
}
}
}

} // namespace tns
76 changes: 45 additions & 31 deletions test-app/runtime/src/main/cpp/RuntimeState.h
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
#ifndef TEST_APP_RUNTIMESTATE_H
#define TEST_APP_RUNTIMESTATE_H

#include <atomic>
#include <cstddef>
#include <memory>
#include <vector>

#include "Runtime.h"
#include "v8.h"
Expand All @@ -23,7 +20,7 @@ namespace tns {
*
* Hanging the state off the Runtime removes the sharing instead of guarding it:
* nothing is shared, so there is nothing to race on and no lock on the access
* path (a lookup is an isolate data-slot read plus a vector index). It also
* path (a lookup is an isolate data-slot read plus an array index). It also
* removes the per-isolate erase at teardown -- the whole bag is destroyed once,
* on the runtime's own thread, while the isolate is still alive, which is what
* v8::Persistent members require.
Expand All @@ -34,6 +31,8 @@ namespace tns {
* auto* state = RuntimeState::For<MyState>(isolate);
* if (state == nullptr) return; // runtime is tearing down
*
* or with For<MyState>(runtime) where the Runtime is already at hand.
*
* The first call for a runtime default-constructs the state; it is destroyed
* with the runtime.
*/
Expand All @@ -47,49 +46,59 @@ class RuntimeState {
template <typename T>
static T* For(v8::Isolate* isolate);

template <typename T>
static T* For(Runtime* runtime);

~RuntimeState() {
Clear();
}

/*
* Destroys every state object. Runs on the runtime's own thread from
* DestroyRuntime, before the isolate is disposed.
*/
void Clear() {
disposed_ = true;
slots_.clear();
}
void Clear();

// More state types than this abort the library load; raise it then.
static constexpr size_t kCapacity = 32;

private:
// One slot index per state type, handed out on first use from any thread.
static size_t NextSlotIndex();
static size_t ClaimSlotIndex();

// One slot index per state type, claimed while the library loads so a
// lookup reads a plain constant instead of a function-local static's
// guard. ClaimSlotIndex's counter is constant-initialized, so it is ready
// whichever translation unit's initializers run first.
template <typename T>
static size_t SlotIndexFor() {
static const size_t index = NextSlotIndex();
return index;
}
static inline const size_t kSlotIndex = ClaimSlotIndex();

// Type-erased so Runtime need not know any subsystem's state type; the
// deleter restores the type at destruction.
using Slot = std::unique_ptr<void, void (*)(void*)>;
template <typename T>
T* Get() {
if (void* value = slots_[kSlotIndex<T>]) [[likely]] {
return static_cast<T*>(value);
}
return Create<T>();
}

template <typename T>
T* GetOrCreate() {
[[gnu::noinline]] T* Create() {
// Clear empties every slot, so a lookup during or after teardown
// ends up here.
if (disposed_) {
return nullptr;
}

size_t index = SlotIndexFor<T>();
while (slots_.size() <= index) {
slots_.emplace_back(nullptr, [](void*) {});
}

Slot& slot = slots_[index];
if (slot == nullptr) {
slot = Slot(new T(), [](void* value) { delete static_cast<T*>(value); });
}

return static_cast<T*>(slot.get());
const size_t index = kSlotIndex<T>;
T* value = new T();
slots_[index] = value;
deleters_[index] = [](void* p) { delete static_cast<T*>(p); };
return value;
}

std::vector<Slot> slots_;
// Type-erased so Runtime need not know any subsystem's state type; the
// deleter restores the type at destruction.
void* slots_[kCapacity] = {};
void (*deleters_[kCapacity])(void*) = {};
bool disposed_ = false;
};

Expand All @@ -102,12 +111,17 @@ T* RuntimeState::For(v8::Isolate* isolate) {
return nullptr;
}

return For<T>(runtime);
}

template <typename T>
T* RuntimeState::For(Runtime* runtime) {
RuntimeState* state = runtime->GetState();
if (state == nullptr) {
return nullptr;
}

return state->GetOrCreate<T>();
return state->Get<T>();
}

} // namespace tns
Expand Down