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
20 changes: 17 additions & 3 deletions NativeScript/runtime/ArgConverter.mm
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ bool IsKVOSubclassOf(Class klass, Class base) {
// kept must read as released.
NativeCallbackSelf::~NativeCallbackSelf() {
if (borrowed_ != nullptr && tns::GetValue(isolate_, receiver_) == borrowed_) {
tns::SetValue(isolate_, receiver_, nullptr);
tns::MarkReleased(isolate_, receiver_, tns::ReleasedReason::kDeallocated);
delete borrowed_;
}
}
Expand All @@ -95,6 +95,12 @@ bool IsKVOSubclassOf(Class klass, Class base) {
BaseDataWrapper* wrapper = tns::GetValue(isolate, receiver);

if (wrapper == nullptr) {
tns::ReleasedReason releasedReason = tns::GetReleasedReason(receiver);
if (releasedReason != tns::ReleasedReason::kNone) {
const char* jsNameStr = meta ? meta->jsName() : "<unknown>";
tns::ThrowReleasedObject(isolate, releasedReason,
std::string("method '") + jsNameStr + "' receiver");
}
// During fast view churn like HMR in development, JS objects can outlive their
// native wrappers briefly. In Debug, throw a catchable JS error instead of crashing.
// In Release, assert so crash reporting can capture unexpected cases.
Expand Down Expand Up @@ -169,8 +175,8 @@ bool IsKVOSubclassOf(Class klass, Class base) {
}

if (allocKlass != nil) {
// The +1 belongs to the initializer invoked below, which consumes it. Nothing
// between here and that call may throw, or the reference is lost.
// The +1 belongs to the initializer invoked below, which consumes it. If
// converting the arguments throws, CallFunction releases it instead.
target = [allocKlass alloc];
}

Expand Down Expand Up @@ -644,6 +650,14 @@ bool IsKVOSubclassOf(Class klass, Class base) {
*static_cast<id __strong*>(retValue) = data;
return true;
} else {
// Native code receives this value outside any JS frame, so a released
// wrapper is reported (never thrown) and returned as nil.
tns::ReleasedReason releasedReason = tns::GetReleasedReason(value);
if (releasedReason != tns::ReleasedReason::kNone) {
tns::ReportReleasedObject(isolate, value, releasedReason, "method return value", false);
memset(retValue, 0, sizeof(id));
return false;
}
id adapter = [[DictionaryAdapter alloc]
initWithJSObject:tns::ProxyReadSource(original, value).As<Object>()
isolate:isolate];
Expand Down
44 changes: 44 additions & 0 deletions NativeScript/runtime/Helpers.h
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,50 @@ void SetReleasedObjectPolicy(ReleasedObjectPolicy policy);
// field unchecked must go through this.
BaseDataWrapper* GetValueOrReport(v8::Isolate* isolate, const v8::Local<v8::Value>& val,
const char* operation);

// Why an ObjC object's wrapper no longer has its native object. Internal field
// 0, where the External would otherwise sit, holds a per-isolate Symbol for the
// reason: GetValue only reads Externals, so every existing caller sees "no
// wrapper". Reasons are recognised by identity, never by value, because other
// templates keep raw aligned pointers in field 0, which read back as arbitrary
// Smis.
enum class ReleasedReason : int32_t {
kNone = 0,
// The wrapper's finalizer released it while JS could still reach the
// wrapper (only possible through a graph a resurrected wrapper keeps alive).
kCollected = 1,
// __releaseNativeCounterpart.
kExplicit = 2,
// Runtime teardown.
kTeardown = 3,
// A receiver lent to JS while its object ran -dealloc.
kDeallocated = 4,
};
// Creates the isolate's markers, so marking never allocates in a finalizer.
void InitReleasedMarkers(v8::Isolate* isolate);
void MarkReleased(v8::Isolate* isolate, const v8::Local<v8::Object>& obj, ReleasedReason reason);
// Follows Proxies and `this.super` aliases to the wrapper they stand for.
ReleasedReason GetReleasedReason(const v8::Local<v8::Value>& val);
const char* ReleasedReasonMessage(ReleasedReason reason);
// Counts the access and throws the ReferenceError as a NativeScriptException,
// for paths that must not reach native code once the error is raised.
[[noreturn]] void ThrowReleasedObject(v8::Isolate* isolate, ReleasedReason reason,
const std::string& operation);

// Applies ReleasedObjectPolicy to a released ObjC wrapper reaching native code
// in place of its object. Throws a ReferenceError under kThrow when `canThrow`;
// otherwise schedules the `releasednativeaccess` event (deduplicated per
// object). The caller then passes nil (or NSNull where nil is not allowed).
// Returns false when it threw.
bool ReportReleasedObject(v8::Isolate* isolate, const v8::Local<v8::Value>& val,
ReleasedReason reason, const char* operation, bool canThrow);

// Whether the runtime warns when JS state on a wrapper is lost while its native
// object lives on. Process-wide; defaults to the app's debug flag, overridden by
// the "wrapperLifetime": { "warnings": bool } app config or ns:runtime's
// `wrapperLifetimeWarnings` key.
bool WrapperLifetimeWarningsEnabled();
void SetWrapperLifetimeWarnings(bool enabled);
void DeleteValue(v8::Isolate* isolate, const v8::Local<v8::Value>& val);
bool DeleteWrapperIfUnused(v8::Isolate* isolate, const v8::Local<v8::Value>& obj,
BaseDataWrapper* value);
Expand Down
178 changes: 167 additions & 11 deletions NativeScript/runtime/Helpers.mm
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@
#include <atomic>
#include <cerrno>
#include <mutex>
#include <optional>
#include <sstream>
#include <vector>
#include "Caches.h"
#include "ErrorEvents.h"
#include "NativeScriptException.h"
#include "ObjectManager.h"
#include "Runtime.h"
#include "RuntimeConfig.h"

Expand Down Expand Up @@ -538,31 +540,59 @@ void WriteDebugLine(tns::LogCategory category, const char* message) {
va_end(ap);
}

tns::BaseDataWrapper* tns::GetValueOrReport(Isolate* isolate, const Local<Value>& val,
const char* operation) {
BaseDataWrapper* wrapper = tns::GetValue(isolate, val);
if (wrapper != nullptr) {
return wrapper;
const char* tns::ReleasedReasonMessage(ReleasedReason reason) {
switch (reason) {
case tns::ReleasedReason::kCollected:
return "The native object was released when its wrapper was garbage collected";
case tns::ReleasedReason::kExplicit:
return "The native object was released by __releaseNativeCounterpart";
case tns::ReleasedReason::kTeardown:
return "The native object was released at runtime teardown";
case tns::ReleasedReason::kDeallocated:
return "The native object was deallocated after lending this receiver to JS from -dealloc";
case tns::ReleasedReason::kNone:
break;
}
return "The native object has been released or is not a valid native object";
}

std::string message =
std::string("The native object has been released or is not a valid native object (") +
operation + ")";
namespace {

// Shared by GetValueOrReport and ReportReleasedObject: one message format, one
// event, one deduplication marker.
bool ApplyReleasedObjectPolicy(Isolate* isolate, const Local<Value>& val, const char* text,
const char* operation, bool canThrow) {
if (tns::ObjectManager::LifetimeStats* stats = tns::ObjectManager::GetLifetimeStats(isolate)) {
stats->releasedAccesses++;
}
std::string message = std::string(text) + " (" + operation + ")";

if (GetReleasedObjectPolicy() == ReleasedObjectPolicy::kThrow) {
if (canThrow && tns::GetReleasedObjectPolicy() == tns::ReleasedObjectPolicy::kThrow) {
isolate->ThrowException(v8::Exception::ReferenceError(tns::ToV8String(isolate, message)));
return nullptr;
return false;
}

Local<Context> context = isolate->GetCurrentContext();
std::optional<Context::Scope> contextScope;
if (context.IsEmpty() && val->IsObject()) {
// Collection adapters convert elements from native callbacks that may not
// have entered a context.
context = tns::GetCreationContextOrCurrent(isolate, val.As<Object>());
if (!context.IsEmpty()) {
contextScope.emplace(context);
}
}
if (context.IsEmpty()) {
return true;
}
if (val->IsObject()) {
// One report per husk object: a released buffer touched in a tight loop
// must not flood the event queue.
Local<Private> reported =
Private::ForApi(isolate, tns::ToV8String(isolate, "ns:releasedAccessReported"));
Local<Object> obj = val.As<Object>();
if (obj->HasPrivate(context, reported).FromMaybe(false)) {
return nullptr;
return true;
}
obj->SetPrivate(context, reported, v8::True(isolate)).FromMaybe(false);
}
Expand All @@ -572,9 +602,135 @@ void WriteDebugLine(tns::LogCategory category, const char* message) {
auto* report =
new ReleasedAccessReport{isolate, v8::Global<v8::Value>(isolate, error), operation};
isolate->EnqueueMicrotask(DispatchReleasedAccessMicrotask, report);
return true;
}

std::atomic<int> wrapperLifetimeWarnings_{-1};

} // namespace

tns::BaseDataWrapper* tns::GetValueOrReport(Isolate* isolate, const Local<Value>& val,
const char* operation) {
BaseDataWrapper* wrapper = tns::GetValue(isolate, val);
if (wrapper != nullptr) {
return wrapper;
}
ApplyReleasedObjectPolicy(isolate, val, ReleasedReasonMessage(GetReleasedReason(val)), operation,
true);
return nullptr;
}

namespace {

constexpr int kReleasedReasonCount = static_cast<int>(tns::ReleasedReason::kDeallocated);

struct ReleasedMarkers {
v8::Eternal<v8::Symbol> reasons[kReleasedReasonCount];
};

} // namespace

void tns::InitReleasedMarkers(Isolate* isolate) {
ReleasedMarkers* markers = Caches::StateFor<ReleasedMarkers>(isolate);
if (markers == nullptr) {
return;
}
for (int i = 0; i < kReleasedReasonCount; i++) {
if (markers->reasons[i].IsEmpty()) {
markers->reasons[i].Set(isolate,
v8::Symbol::New(isolate, tns::ToV8String(isolate, "ns:released")));
}
}
}

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 &&
!markers->reasons[index].IsEmpty() && !target.IsEmpty() && target->IsObject() &&
target.As<Object>()->InternalFieldCount() > 0) {
target.As<Object>()->SetInternalField(0, markers->reasons[index].Get(isolate));
return;
}
// Wrappers kept in the `metadata` private have no field for the marker; they
// are only cleared, and read as plain objects afterwards.
tns::DeleteValue(isolate, obj);
}

tns::ReleasedReason tns::GetReleasedReason(const Local<Value>& val) {
Local<Value> target = tns::UnwrapProxy(val);
if (target.IsEmpty() || !target->IsObject()) {
return ReleasedReason::kNone;
}
Local<Object> obj = target.As<Object>();
if (obj->InternalFieldCount() < 1) {
return ReleasedReason::kNone;
}
Local<Value> field = obj->GetInternalField(0).As<v8::Value>();
if (field.IsEmpty()) {
return ReleasedReason::kNone;
}
if (field->IsObject()) {
Local<Object> receiver = SuperAliasReceiver(obj);
return receiver.IsEmpty() ? ReleasedReason::kNone : GetReleasedReason(receiver);
}
if (!field->IsSymbol()) {
return ReleasedReason::kNone;
}
Isolate* isolate = v8::Isolate::GetCurrent();
ReleasedMarkers* markers = Caches::ExistingStateFor<ReleasedMarkers>(isolate);
if (markers == nullptr) {
return ReleasedReason::kNone;
}
for (int i = 0; i < kReleasedReasonCount; i++) {
if (!markers->reasons[i].IsEmpty() && markers->reasons[i].Get(isolate) == field) {
return static_cast<ReleasedReason>(i + 1);
}
}
return ReleasedReason::kNone;
}

void tns::ThrowReleasedObject(Isolate* isolate, ReleasedReason reason,
const std::string& operation) {
if (tns::ObjectManager::LifetimeStats* stats = tns::ObjectManager::GetLifetimeStats(isolate)) {
stats->releasedAccesses++;
}
std::string message = std::string(ReleasedReasonMessage(reason)) + " (" + operation + ")";
throw NativeScriptException(
isolate, v8::Exception::ReferenceError(tns::ToV8String(isolate, message)), message);
}

bool tns::ReportReleasedObject(Isolate* isolate, const Local<Value>& val, ReleasedReason reason,
const char* operation, bool canThrow) {
return ApplyReleasedObjectPolicy(isolate, val, ReleasedReasonMessage(reason), operation,
canThrow);
}

bool tns::WrapperLifetimeWarningsEnabled() {
int value = wrapperLifetimeWarnings_.load(std::memory_order_relaxed);
if (value >= 0) {
return value != 0;
}
bool enabled = RuntimeConfig.IsDebug;
id config = Runtime::GetAppConfigValue("wrapperLifetime");
if ([config isKindOfClass:[NSDictionary class]]) {
id warnings = ((NSDictionary*)config)[@"warnings"];
if ([warnings isKindOfClass:[NSNumber class]]) {
enabled = [warnings boolValue];
}
}
int expected = -1;
wrapperLifetimeWarnings_.compare_exchange_strong(expected, enabled ? 1 : 0,
std::memory_order_relaxed);
return wrapperLifetimeWarnings_.load(std::memory_order_relaxed) != 0;
}

void tns::SetWrapperLifetimeWarnings(bool enabled) {
wrapperLifetimeWarnings_.store(enabled ? 1 : 0, std::memory_order_relaxed);
}

void tns::DeleteValue(Isolate* isolate, const Local<Value>& val) {
Local<Value> target = tns::UnwrapProxy(val);
if (target.IsEmpty() || target->IsNullOrUndefined() || !target->IsObject()) {
Expand Down
Loading
Loading