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
23 changes: 21 additions & 2 deletions NativeScript/runtime/ArgConverter.mm
Original file line number Diff line number Diff line change
Expand Up @@ -744,9 +744,20 @@ bool IsKVOSubclassOf(Class klass, Class base) {
tns::SetValue(isolate, thiz, wrapper);
std::shared_ptr<Persistent<Value>> poThiz = ObjectManager::Register(context, thiz);
cache->Instances.emplace(result, poThiz);
if (!resultIsOwned) {
// An initializer can answer with an existing object whose release is still
// waiting (see CreateJsWrapper).
bool tookOver = ObjectManager::TakeDeferredRelease(isolate, result);
if (tookOver && resultIsOwned) {
[result release];
} else if (!tookOver && !resultIsOwned) {
[result retain];
}
if (tookOver) {
// Only releases of objects that first reached JS on the runtime's
// thread are ever queued.
wrapper->SetBornOnRuntimeThread();
ObjectManager::ProtectIfNativelyRetained(isolate, result, wrapper);
}
ExternalMemory::ChargeEstimatedSize(isolate, thiz);
}
}
Expand Down Expand Up @@ -1014,7 +1025,15 @@ bool IsKVOSubclassOf(Class klass, Class base) {
receiver = poValue->Get(isolate).As<Object>();
tns::SetValue(isolate, receiver, wrapper);
cache->Instances.emplace(target, poValue);
[target retain];
// An extended class reads its retain count to decide whether native
// code owns the object, so a pending release is taken over, not stacked.
if (!ObjectManager::TakeDeferredRelease(isolate, target)) {
[target retain];
} else if (wrapper->Type() == WrapperType::ObjCObject) {
ObjCDataWrapper* objcWrapper = static_cast<ObjCDataWrapper*>(wrapper);
objcWrapper->SetBornOnRuntimeThread();
ObjectManager::ProtectIfNativelyRetained(isolate, target, objcWrapper);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
} else {
tns::SetValue(isolate, receiver, wrapper);
Expand Down
17 changes: 17 additions & 0 deletions NativeScript/runtime/Caches.h
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,23 @@ class Caches {
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.
template <typename T>
static T* ExistingStateFor(v8::Isolate* isolate) {
auto raw = isolate->GetData(0);
if (raw == nullptr) {
return nullptr;
}
Caches* cache = reinterpret_cast<std::shared_ptr<Caches>*>(raw)->get();
size_t index = StateSlotIndexFor<T>();
if (index >= cache->stateSlots_.size()) {
return nullptr;
}
return static_cast<T*>(cache->stateSlots_[index].get());
}

inline int getIsolateId() { return isolateId_; }

// The id assigned at Init; unlike getIsolateId() it survives
Expand Down
4 changes: 4 additions & 0 deletions NativeScript/runtime/ClassBuilder.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ class ClassBuilder {
const char* fallback);
// `klass` or its nearest superclass not defined from JS.
static Class FindNativeClass(Class klass);
// Whether instances of `klass` run a -retain/-release pair that protects
// and unprotects their wrapper in `isolate`: one this isolate installed, on
// `klass` or a class it inherits from.
static bool TracksNativeRetains(v8::Isolate* isolate, Class klass);
// The implementation of `method` from FindNativeClass(klass).
static IMP FindNotOverridenMethod(Class klass, SEL method);
// Whether `klass`, not one of its superclasses, implements `selector`.
Expand Down
25 changes: 25 additions & 0 deletions NativeScript/runtime/ClassBuilder.mm
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include <Foundation/Foundation.h>
#include <numeric>
#include <sstream>
#include <unordered_set>
#include "ArgConverter.h"
#include "BuiltinLoader.h"
#include "Caches.h"
Expand Down Expand Up @@ -29,6 +30,14 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
name += std::to_string(isolateId);
}
}

// The classes an isolate gave the -retain/-release pair that protects and
// unprotects an instance's wrapper. The pair looks the wrapper up in that
// isolate only, so another isolate's wrapper of the same instance is never
// unprotected by it.
struct RetainTrackedClasses {
std::unordered_set<void*> classes;
};
} // namespace

Local<FunctionTemplate> ClassBuilder::GetExtendFunction(Isolate* isolate,
Expand Down Expand Up @@ -405,6 +414,9 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
release(self, @selector(release));
});
class_addMethod(extendedClass, @selector(release), newRelease, "v@:");
if (auto* tracked = Caches::StateFor<RetainTrackedClasses>(isolate)) {
tracked->classes.insert((__bridge void*)extendedClass);
}

info.GetReturnValue().SetUndefined();
}).ToLocalChecked();
Expand Down Expand Up @@ -1101,6 +1113,19 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
return klass;
}

bool ClassBuilder::TracksNativeRetains(Isolate* isolate, Class klass) {
RetainTrackedClasses* tracked = Caches::ExistingStateFor<RetainTrackedClasses>(isolate);
if (tracked == nullptr || tracked->classes.empty()) {
return false;
}
for (; klass != nil; klass = class_getSuperclass(klass)) {
if (tracked->classes.count((__bridge void*)klass) != 0) {
return true;
}
}
return false;
}

IMP ClassBuilder::FindNotOverridenMethod(Class klass, SEL method) {
return class_getMethodImplementation(FindNativeClass(klass), method);
}
Expand Down
23 changes: 21 additions & 2 deletions NativeScript/runtime/DataWrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ class WorkerInspectorClient;

namespace tns {

// Whether the calling thread is the one `isolate`'s runtime runs on (its event
// loop's thread). JS can also run on other threads, any that take the
// isolate's Locker. Several runtimes may share a thread. Defined in Runtime.mm.
bool OnRuntimeThreadOf(v8::Isolate* isolate);

class PrimitiveDataWrapper;
struct ObjectWeakCallbackState;
class EventLoop;
Expand Down Expand Up @@ -394,7 +399,8 @@ class UnmanagedTypeWrapper : public BaseDataWrapper {
class ObjCDataWrapper : public BaseDataWrapper {
public:
ObjCDataWrapper(id data, const TypeEncoding* typeEncoding = nullptr)
: data_(data),
: bornOnRuntimeThread_(OnRuntimeThreadOf(v8::Isolate::TryGetCurrent())),
data_(data),
typeEncoding_(typeEncoding),
klass_(object_getClass(data)) {}

Expand All @@ -409,6 +415,11 @@ class ObjCDataWrapper : public BaseDataWrapper {
bool IsAdapterClaim() { return this->adapterClaim_; }
void MarkAdapterClaim() { this->adapterClaim_ = true; }

// Whether the object first reached JS on its runtime's thread, the stand-in
// for "belongs to that thread": its native release must happen there too.
bool BornOnRuntimeThread() { return this->bornOnRuntimeThread_; }
void SetBornOnRuntimeThread() { this->bornOnRuntimeThread_ = true; }

const TypeEncoding* TypeEncoding() { return this->typeEncoding_; }

// The class Data() had when this wrapper was built. Data() alone cannot tell
Expand All @@ -431,6 +442,7 @@ class ObjCDataWrapper : public BaseDataWrapper {
private:
bool adapterClaim_ = false;
bool borrowed_ = false;
bool bornOnRuntimeThread_;
ObjectWeakCallbackState* ownershipState_ = nullptr;
id data_;
const tns::TypeEncoding* typeEncoding_;
Expand Down Expand Up @@ -502,7 +514,10 @@ class AnonymousFunctionWrapper : public BaseDataWrapper {
class BlockWrapper : public BaseDataWrapper {
public:
BlockWrapper(void* block, const TypeEncoding* typeEncoding, bool ownsBlock)
: block_(block), typeEncoding_(typeEncoding), ownsBlock_(ownsBlock) {}
: block_(block),
typeEncoding_(typeEncoding),
ownsBlock_(ownsBlock),
bornOnRuntimeThread_(OnRuntimeThreadOf(v8::Isolate::TryGetCurrent())) {}

const WrapperType Type() { return WrapperType::Block; }

Expand All @@ -512,10 +527,14 @@ class BlockWrapper : public BaseDataWrapper {

bool OwnsBlock() { return this->ownsBlock_; }

// See ObjCDataWrapper::BornOnRuntimeThread.
bool BornOnRuntimeThread() { return this->bornOnRuntimeThread_; }

private:
void* block_;
const TypeEncoding* typeEncoding_;
bool ownsBlock_;
bool bornOnRuntimeThread_;
};

class FunctionReferenceTypeWrapper : public BaseDataWrapper {
Expand Down
13 changes: 13 additions & 0 deletions NativeScript/runtime/ObjectManager.h
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,19 @@ class ObjectManager {
static void ReconcileOwnership(v8::Isolate* isolate,
ObjCDataWrapper* wrapper);

// A collection can run on any thread that holds the isolate's Locker, but
// the native releases it causes are handed to the runtime's thread. A new
// Instances entry for an object whose release is still waiting takes that
// release over as its own retain instead of retaining again; returns whether
// it did. Once the entry holds its reference, call ProtectIfNativelyRetained.
static bool TakeDeferredRelease(v8::Isolate* isolate, id obj);
// A class that tracks native retains (ClassBuilder::TracksNativeRetains)
// protects its wrapper when native code first retains the object past the
// runtime's own retain. A native retain made while a release waited found no
// wrapper to protect; this catches up. A surplus reference the caller drops
// afterwards goes through -release, which unprotects again.
static void ProtectIfNativelyRetained(v8::Isolate* isolate, id obj, ObjCDataWrapper* wrapper);

private:
static void ReleaseNativeCounterpartCallback(
const v8::FunctionCallbackInfo<v8::Value>& info);
Expand Down
Loading
Loading