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
4 changes: 3 additions & 1 deletion NativeScript/inspector/InspectorSessions.mm
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ void flushProtocolNotifications() override {}

InspectorSessions::InspectorSessions(Isolate* isolate, int contextGroupId, Output output)
: isolate_(isolate), contextGroupId_(contextGroupId), output_(std::move(output)) {
if (auto* slot = tns::Caches::StateFor<SessionsSlot>(isolate_)) {
auto* slot = tns::Caches::IsTearingDown(isolate_) ? nullptr
: tns::Caches::StateFor<SessionsSlot>(isolate_);
if (slot != nullptr) {
slot->sessions = this;
isolate_->AddBeforeCallEnteredCallback(OnCallEntered);
isolate_->AddCallCompletedCallback(OnCallCompleted);
Expand Down
7 changes: 3 additions & 4 deletions NativeScript/runtime/ArgConverter.mm
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,6 @@ bool IsKVOSubclassOf(Class klass, Class base) {

Persistent<v8::Function>* ArgConverter::EmptyInstanceFunction(Isolate* isolate, CanaryKind kind) {
if (kind != CanaryKind::kNone) {
// Teardown-safe: a -dealloc receiver can be built after InvalidateIsolate,
// while deferred releases drain.
CanaryWrapperConstructors* canary =
Caches::ExistingStateFor<CanaryWrapperConstructors>(isolate);
size_t index = static_cast<size_t>(kind);
Expand Down Expand Up @@ -242,8 +240,9 @@ throw NativeScriptException(isolate, v8::Exception::TypeError(tns::ToV8String(is
Local<Private> ArgConverter::GetEscapeExceptionBrand(Isolate* isolate) {
auto cache = Caches::Get(isolate);
// Caches::Get never returns null — after isolate removal it returns a dummy
// cache — so validity is the real liveness check before touching V8 state.
if (cache == nullptr || !cache->IsValid()) {
// cache, which reads as tearing down — so the flag is the real liveness check
// before touching V8 state.
if (cache == nullptr || cache->IsTearingDown()) {
return Local<Private>();
}
if (cache->EscapeExceptionBrand == nullptr) {
Expand Down
2 changes: 1 addition & 1 deletion NativeScript/runtime/Caches.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace tns {
Caches::Caches(Isolate* isolate, const int& isolateId)
: PromiseRejections(std::make_unique<PromiseRejectionTracker>(isolate)),
isolate_(isolate),
isolateId_(isolateId),
tearingDown_(isolateId == -1),
gateId_(isolateId) {}

Caches::~Caches() {
Expand Down
49 changes: 31 additions & 18 deletions NativeScript/runtime/Caches.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#ifndef Caches_h
#define Caches_h

#include <atomic>
#include <memory>
#include <string>
#include <string_view>
Expand Down Expand Up @@ -102,25 +103,22 @@ class Caches {
// across runtimes tearing down on their own threads). The first call
// default-constructs T; it is destroyed with this Caches, under the teardown
// Locker while the isolate is still alive, so T may hold v8::Persistent
// members. Returns null once teardown has begun (InvalidateIsolate) or the
// isolate's Caches is gone — callers must bail, not recreate state. Access
// from the isolate's thread only, like every other member.
// members. Live, and created on demand, through the whole teardown until
// Caches::Remove; null only once the isolate's Caches is gone. A caller that
// must not start new work during teardown checks IsTearingDown itself.
// Access from the isolate's thread only, like every other member.
template <typename T>
static T* StateFor(v8::Isolate* isolate) {
auto raw = isolate->GetData(0);
if (raw == nullptr) {
return nullptr;
}
Caches* cache = reinterpret_cast<std::shared_ptr<Caches>*>(raw)->get();
if (!cache->IsValid()) {
return nullptr;
}
return cache->GetOrCreateState<T>();
}

// The existing state, even after InvalidateIsolate, for a subsystem that
// must finish work its state still holds. Never creates, so a state made on
// the isolate's thread can be read from any thread holding the Locker.
// The existing state, or null. Never creates, so a state made on the
// isolate's thread can be read from any thread holding the Locker.
template <typename T>
static T* ExistingStateFor(v8::Isolate* isolate) {
auto raw = isolate->GetData(0);
Expand All @@ -135,16 +133,31 @@ class Caches {
return static_cast<T*>(cache->stateSlots_[index].get());
}

inline int getIsolateId() { return isolateId_; }

// The id assigned at Init; unlike getIsolateId() it survives
// InvalidateIsolate, so it still names this isolate's gate during teardown.
// -1 for the stand-in Get() returns once the isolate's Caches is gone.
// The id assigned at Init; it names this isolate's gate for its whole life,
// teardown included. -1 for the stand-in Get() returns once the isolate's
// Caches is gone.
inline int getGateId() const { return gateId_; }

inline void InvalidateIsolate() { isolateId_ = -1; }

inline bool IsValid() { return isolateId_ != -1; }
// Set at the start of ~Runtime: from then on nothing may start new work for
// this isolate (post tasks, build or adopt wrappers, register callbacks,
// dispatch events). Per-isolate state stays reachable meanwhile, so work
// already under way can finish. The stand-in Get() returns reads as tearing
// down. Read from any thread.
inline void BeginTeardown() {
tearingDown_.store(true, std::memory_order_release);
}
inline bool IsTearingDown() const {
return tearingDown_.load(std::memory_order_acquire);
}
// Also true once the isolate's Caches is gone.
static bool IsTearingDown(v8::Isolate* isolate) {
auto raw = isolate->GetData(0);
if (raw == nullptr) {
return true;
}
Caches* cache = reinterpret_cast<std::shared_ptr<Caches>*>(raw)->get();
return cache->IsTearingDown();
}

void SetContext(v8::Local<v8::Context> context);
v8::Local<v8::Context> GetContext();
Expand Down Expand Up @@ -336,7 +349,7 @@ class Caches {
std::vector<StateSlot> stateSlots_;
v8::Isolate* isolate_;
std::shared_ptr<v8::Persistent<v8::Context>> context_;
int isolateId_;
std::atomic<bool> tearingDown_;
const int gateId_;
};

Expand Down
4 changes: 2 additions & 2 deletions NativeScript/runtime/ClassBuilder.mm
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) {
}
}
auto cache = Caches::Get(isolate);
auto isolateId = cache->getIsolateId();
auto isolateId = cache->getGateId();

Local<v8::Function> baseCtorFunc =
cache->CtorFuncs.find(item->meta_->name())->second->Get(isolate);
Expand Down Expand Up @@ -275,7 +275,7 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) {
Local<v8::Function> extendedClassCtorFunc = info[0].As<v8::Function>();
std::string extendedClassName = tns::ToString(isolate, extendedClassCtorFunc->GetName());

auto isolateId = cache->getIsolateId();
auto isolateId = cache->getGateId();
ScopeClassNameToIsolate(extendedClassName, isolateId);
__block Class extendedClass =
ClassBuilder::GetExtendedClass(baseClassName, extendedClassName, isolateId);
Expand Down
2 changes: 1 addition & 1 deletion NativeScript/runtime/EventLoop.mm
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) {
isolate_->PerformMicrotaskCheckpoint();
};
auto cache = Caches::Get(isolate_);
if (cache != nullptr && cache->IsValid() && cache->HasContext()) {
if (cache != nullptr && !cache->IsTearingDown() && cache->HasContext()) {
Context::Scope context_scope(cache->GetContext());
run();
} else {
Expand Down
1 change: 0 additions & 1 deletion NativeScript/runtime/Helpers.mm
Original file line number Diff line number Diff line change
Expand Up @@ -689,7 +689,6 @@ bool ApplyReleasedObjectPolicy(Isolate* isolate, const Local<Value>& val, const

void tns::MarkReleased(Isolate* isolate, const Local<Object>& obj, ReleasedReason reason) {
Local<Value> target = tns::UnwrapProxy(obj);
// Read without the validity check: teardown marks after InvalidateIsolate.
ReleasedMarkers* markers = Caches::ExistingStateFor<ReleasedMarkers>(isolate);
int index = static_cast<int>(reason) - 1;
if (markers != nullptr && index >= 0 && index < kReleasedReasonCount &&
Expand Down
4 changes: 2 additions & 2 deletions NativeScript/runtime/Interop.mm
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@
// deadlocks if this isolate is waiting for that Locker in turn.
// Blocks shared between isolates carry that risk.
//
// Validity is not the test here: the slot stays reachable after
// the isolate is invalidated, by JS still running under the Locker
// The teardown flag is not the test here: the slot stays reachable
// once teardown has begun, by JS still running under the Locker
// and by the teardown's own walk of registered objects. Until the
// gate closes, the wrapper is only freed once the slot is cleared.
{
Expand Down
2 changes: 1 addition & 1 deletion NativeScript/runtime/IsolateWrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ bool IsolateWrapper::IsValid() const {
return false;
}
std::shared_ptr<Caches> cache = GetCache();
return cache->IsValid() && cache->getGateId() == gateId_;
return !cache->IsTearingDown() && cache->getGateId() == gateId_;
}

namespace IsolateGates {
Expand Down
8 changes: 6 additions & 2 deletions NativeScript/runtime/LeakProbe.mm
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
bool ForEachInstance(Isolate* isolate, void* context,
void (*visit)(void* context, const Instance& instance)) {
std::shared_ptr<Caches> cache = Caches::Get(isolate);
if (cache == nullptr || !cache->IsValid()) {
if (cache == nullptr || cache->IsTearingDown()) {
return false;
}
// A wrapper built for an object whose previous wrapper's release is still
Expand Down Expand Up @@ -117,12 +117,16 @@ void DrainReleases(Isolate* isolate) {
}

void* IsolateState(Isolate* isolate) {
if (Caches::IsTearingDown(isolate)) {
return nullptr;
}
ProbeState* probe = Caches::StateFor<ProbeState>(isolate);
return probe != nullptr ? probe->state : nullptr;
}

bool SetIsolateState(Isolate* isolate, void* state, void (*destroy)(void*)) {
ProbeState* probe = Caches::StateFor<ProbeState>(isolate);
ProbeState* probe =
Caches::IsTearingDown(isolate) ? nullptr : Caches::StateFor<ProbeState>(isolate);
if (probe == nullptr) {
return false;
}
Expand Down
17 changes: 10 additions & 7 deletions NativeScript/runtime/Messaging.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,18 @@ struct MessagingState {
Global<Private> uncloneableBrand;
};

// The isolate's Caches is invalidated long before ~Runtime reaches the point
// where ports must be force-closed, and Caches::StateFor answers null from
// then on. This registry is the teardown sweep's way back to the state.
// State() refuses from the start of teardown, long before ~Runtime reaches the
// point where ports must be force-closed. This registry is the teardown
// sweep's way back to the state.
std::mutex g_statesMutex;
std::unordered_map<Isolate*, MessagingState*> g_states;

// Null once the isolate's Caches has been invalidated — callers bail rather
// than recreate state that would never be destroyed.
// Null once teardown has begun: no port is created, delivered to or tracked
// from then on, so the ports CloseAllPorts orphans are all there will be.
MessagingState* State(Isolate* isolate) {
if (Caches::IsTearingDown(isolate)) {
return nullptr;
}
MessagingState* state = Caches::StateFor<MessagingState>(isolate);
if (state == nullptr || state->isolate != nullptr) {
return state;
Expand Down Expand Up @@ -547,7 +550,7 @@ void NativeMessagePort::Close() {
void NativeMessagePort::EmitClose(Local<Object> wrapper) {
Isolate* isolate = this->isolateWrapper_.Isolate();
std::shared_ptr<Caches> cache = Caches::Get(isolate);
if (cache == nullptr || !cache->IsValid() || !cache->HasContext()) {
if (cache == nullptr || cache->IsTearingDown() || !cache->HasContext()) {
return;
}
Local<Context> context = cache->GetContext();
Expand Down Expand Up @@ -649,7 +652,7 @@ void NativeMessagePort::Drain() {
}
Isolate* isolate = this->isolateWrapper_.Isolate();
std::shared_ptr<Caches> cache = Caches::Get(isolate);
if (cache == nullptr || !cache->IsValid() || !cache->HasContext()) {
if (cache == nullptr || cache->IsTearingDown() || !cache->HasContext()) {
return;
}
HandleScope handleScope(isolate);
Expand Down
4 changes: 2 additions & 2 deletions NativeScript/runtime/MetadataBuilder.mm
Original file line number Diff line number Diff line change
Expand Up @@ -610,8 +610,8 @@ NamedPropertyHandlerConfiguration config(MetadataBuilder::GlobalPropertyGetter,
Isolate* isolate = v8::Isolate::GetCurrent();
StructTypeState* state = Caches::StateFor<StructTypeState>(isolate);
if (state == nullptr) {
// Teardown has begun: build without caching. Instances created in this
// window do not share a prototype with earlier ones; only finalizer-driven
// The isolate's Caches is gone: build without caching. Instances created
// then do not share a prototype with earlier ones; only finalizer-driven
// conversions can reach it.
return MetadataBuilder::CreateStructCtorTemplate(isolate, new StructTypeWrapper(structInfo));
}
Expand Down
2 changes: 1 addition & 1 deletion NativeScript/runtime/ModuleInternal.mm
Original file line number Diff line number Diff line change
Expand Up @@ -2104,7 +2104,7 @@ void FlushScriptCaches(Isolate* isolate) {

void QueuePendingScriptCache(Isolate* isolate, PendingScriptCache entry,
ModuleInternal::ScriptCacheKind kind) {
if (RuntimeConfig.IsDebug) {
if (RuntimeConfig.IsDebug || Caches::IsTearingDown(isolate)) {
return;
}
auto* queue = ScriptCacheQueueFor(isolate);
Expand Down
4 changes: 2 additions & 2 deletions NativeScript/runtime/ModuleInternalCallbacks.h
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ using ModuleHandleMap =
// v8::Module handles for `isolate`. Keyed by v8::Isolate* (not thread) because
// v8::Global<Module> handles are isolate-bound; see the long-form comment above
// the definition in ModuleInternalCallbacks.mm for the cross-isolate-handle bug
// this prevents. The map lives in a Caches state slot, so this returns null
// once the isolate's teardown has begun — callers must bail.
// this prevents. Null once the isolate's teardown has begun — callers must
// bail.
ModuleHandleMap* ModuleRegistryFor(v8::Isolate* isolate);

// Mark every in-flight async graph load owned by `isolate` dead and Reset
Expand Down
8 changes: 6 additions & 2 deletions NativeScript/runtime/ModuleInternalCallbacks.mm
Original file line number Diff line number Diff line change
Expand Up @@ -424,8 +424,12 @@ void WaitForChange(uint64_t seen, std::chrono::milliseconds timeout) {
};

// This isolate's loader state, or null once teardown has begun — callers must
// bail, not recreate state.
// bail: QuiesceModuleLoadsForIsolate kills only the loads that exist when it
// runs, so none may start after it.
ModuleLoaderState* ModuleLoaderStateFor(v8::Isolate* isolate) {
if (Caches::IsTearingDown(isolate)) {
return nullptr;
}
return Caches::StateFor<ModuleLoaderState>(isolate);
}

Expand Down Expand Up @@ -1690,7 +1694,7 @@ bool HasPendingAsyncModuleGraphWork() {
// load's shared_ptr past teardown, so the slot destructor alone cannot cover
// these. Called from QuiesceModuleLoadsForIsolate.
static void KillAsyncGraphLoadsForIsolate(v8::Isolate* isolate) {
// Runtime invalidates the Caches before quiescing, so StateFor would be null.
// Teardown has begun, so ModuleLoaderStateFor would be null.
auto* state = Caches::ExistingStateFor<ModuleLoaderState>(isolate);
if (state == nullptr) {
return;
Expand Down
2 changes: 1 addition & 1 deletion NativeScript/runtime/NativeScriptException.mm
Original file line number Diff line number Diff line change
Expand Up @@ -613,7 +613,7 @@ static bool GiveWorkerOnErrorAChance(Isolate* isolate, Local<Context> context, L
// HasPending is an atomic read: OnReject can run on any thread holding the
// v8::Locker, so pending_ itself must only be touched under the lock below.
// The event loop runs v8 tasks before Runtime::Init creates the context.
if (cache == nullptr || !cache->IsValid() || !cache->HasContext() ||
if (cache == nullptr || cache->IsTearingDown() || !cache->HasContext() ||
cache->PromiseRejections == nullptr || !cache->PromiseRejections->HasPending()) {
return;
}
Expand Down
17 changes: 13 additions & 4 deletions NativeScript/runtime/ObjectManager.mm
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@ bool NativelyOwnedWithoutJS(Isolate* isolate, id obj) {
}

void ReconcileOwnershipBeforeGC(Isolate* isolate, GCType, GCCallbackFlags) {
// The teardown walk deletes registrations without forgetting them, so
// `managed` can hold freed states from then on.
if (Caches::IsTearingDown(isolate)) {
return;
}
OwnershipTracking* tracking = Caches::StateFor<OwnershipTracking>(isolate);
if (tracking == nullptr) {
return;
Expand Down Expand Up @@ -199,7 +204,8 @@ void NoteStateLostCandidate(Isolate* isolate, Local<Object> obj, id target) {
return;
}

auto* state = Caches::StateFor<WrapperLifetimeState>(isolate);
auto* state =
Caches::IsTearingDown(isolate) ? nullptr : Caches::StateFor<WrapperLifetimeState>(isolate);
if (state == nullptr) {
discardSlot();
return;
Expand Down Expand Up @@ -312,9 +318,9 @@ void DrainDeferredReleases(DeferredReleases* pending) {
}

// The queue to hand a release to, or null when the caller releases inline.
// Created by Init, so a collection on another thread never creates it; read
// without the validity check because a collection can still run on another
// thread between InvalidateIsolate and teardown, which drains it.
// Created by Init, so a collection on another thread never creates it. A
// collection can still run on another thread once teardown has begun, which
// drains the queue.
DeferredReleases* DeferralQueue(Isolate* isolate, bool bornOnRuntimeThread) {
if (!bornOnRuntimeThread || OnRuntimeThreadOf(isolate)) {
return nullptr;
Expand Down Expand Up @@ -491,6 +497,9 @@ void DisposeHandle(v8::Isolate* isolate,

void ObjectManager::ManageOwnership(Isolate* isolate, ObjCDataWrapper* wrapper,
ObjectWeakCallbackState* state) {
if (Caches::IsTearingDown(isolate)) {
return;
}
OwnershipTracking* tracking = Caches::StateFor<OwnershipTracking>(isolate);
if (tracking == nullptr || state == nullptr) {
return;
Expand Down
4 changes: 2 additions & 2 deletions NativeScript/runtime/Runtime.mm
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ static bool ShouldEnableJit() {
Runtime::isolates_.erase(
std::remove(Runtime::isolates_.begin(), Runtime::isolates_.end(), this->isolate_),
Runtime::isolates_.end());
Caches::Get(isolate_)->InvalidateIsolate();
Caches::Get(isolate_)->BeginTeardown();
}
this->isolate_->TerminateExecution();

Expand Down Expand Up @@ -776,7 +776,7 @@ bool OnRuntimeThreadOf(v8::Isolate* isolate) {
// created which could happen under some specific embedding scenarios
if ((Isolate::TryGetCurrent() == isolate ||
(currentRuntime_ != nullptr && currentRuntime_->GetIsolate() == isolate)) &&
Caches::Get((Isolate*)isolate)->IsValid()) {
!Caches::Get((Isolate*)isolate)->IsTearingDown()) {
return true;
}
SpinLock lock(isolatesMutex_);
Expand Down
2 changes: 1 addition & 1 deletion NativeScript/runtime/StructuredSerialization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ Local<Private> BrandOf(Isolate* isolate, DomExceptionBrandState* state) {
return state->brand.Get(isolate);
}

// Empty once teardown has begun — callers bail to their fallback.
// Empty once the isolate's Caches is gone — callers bail to their fallback.
Local<Private> DomExceptionBrand(Isolate* isolate) {
auto* state = Caches::StateFor<DomExceptionBrandState>(isolate);
if (state == nullptr) {
Expand Down
Loading
Loading