Skip to content

Commit 12ff142

Browse files
committed
feat(runtime): wrapper lifetime diagnostics and released-object arguments
A JS object whose ObjC wrapper was released (a resurrected holder's graph can keep it reachable) used to reach native code as a DictionaryAdapter standing in for the object, so UIKit received a dictionary where it expected, for example, a UIColor. A method call on it asserted in Release. Released ObjC wrappers now carry a ReleasedReason in internal field 0 (collected, released through __releaseNativeCounterpart, or teardown). GetValue only reads Externals, so existing callers are unaffected. Where an object is expected, the marker routes the value through releasedObjectPolicy: an argument becomes nil (report) or throws a ReferenceError (throw), a collection element becomes NSNull, a JS-implemented method's return value becomes nil, and a method or property call on it always throws a ReferenceError, also through a Proxy. ns:runtime gains getWrapperLifetimeStats() (resurrections, collections, explicit releases, released-object accesses, state-lost candidates and confirmations, counted on cold paths in every build) and the wrapperLifetimeWarnings key. With warnings on (default in debug builds, or "wrapperLifetime": { "warnings": bool } in the app config), a collected wrapper that carried JS properties while its object was still retained elsewhere is checked again a runloop turn later through a weak reference, and a still-alive object is reported once per class.
1 parent 95b52af commit 12ff142

15 files changed

Lines changed: 757 additions & 20 deletions

‎NativeScript/runtime/ArgConverter.mm‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,19 @@
3535
BaseDataWrapper* wrapper = tns::GetValue(isolate, receiver);
3636

3737
if (wrapper == nullptr) {
38+
tns::ReleasedReason releasedReason = tns::GetReleasedReason(receiver);
39+
if (releasedReason != tns::ReleasedReason::kNone) {
40+
const char* jsNameStr = meta ? meta->jsName() : "<unknown>";
41+
std::string operation = std::string("method '") + jsNameStr + "' receiver";
42+
if (tns::ObjectManager::LifetimeStats* stats =
43+
tns::ObjectManager::GetLifetimeStats(isolate)) {
44+
stats->releasedAccesses++;
45+
}
46+
std::string message =
47+
std::string(tns::ReleasedReasonMessage(releasedReason)) + " (" + operation + ")";
48+
throw NativeScriptException(
49+
isolate, Exception::ReferenceError(tns::ToV8String(isolate, message)), message);
50+
}
3851
// During fast view churn like HMR in development, JS objects can outlive their
3952
// native wrappers briefly. In Debug, throw a catchable JS error instead of crashing.
4053
// In Release, assert so crash reporting can capture unexpected cases.
@@ -542,6 +555,14 @@
542555
*static_cast<id __strong*>(retValue) = data;
543556
return;
544557
} else {
558+
// Native code receives this value outside any JS frame, so a released
559+
// wrapper is reported (never thrown) and returned as nil.
560+
tns::ReleasedReason releasedReason = tns::GetReleasedReason(value);
561+
if (releasedReason != tns::ReleasedReason::kNone) {
562+
tns::ReportReleasedObject(isolate, value, releasedReason, "method return value", false);
563+
memset(retValue, 0, sizeof(id));
564+
return;
565+
}
545566
id adapter = [[DictionaryAdapter alloc]
546567
initWithJSObject:tns::ProxyReadSource(original, value).As<Object>()
547568
isolate:isolate];

‎NativeScript/runtime/Helpers.h‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,40 @@ void SetReleasedObjectPolicy(ReleasedObjectPolicy policy);
316316
// field unchecked must go through this.
317317
BaseDataWrapper* GetValueOrReport(v8::Isolate* isolate, const v8::Local<v8::Value>& val,
318318
const char* operation);
319+
320+
// Why an ObjC object's wrapper no longer has its native object. Stored as a
321+
// small integer in internal field 0, where an External would otherwise sit:
322+
// GetValue only reads Externals, so every existing caller sees "no wrapper",
323+
// and writing it allocates nothing inside the finalizer drain.
324+
enum class ReleasedReason : int32_t {
325+
// Zero is never a reason: other templates' embedder fields can hold Smi 0.
326+
kNone = 0,
327+
// The wrapper's finalizer released it while JS could still reach the
328+
// wrapper (only possible through a graph a resurrected wrapper keeps alive).
329+
kCollected = 1,
330+
// __releaseNativeCounterpart.
331+
kExplicit = 2,
332+
// Runtime teardown.
333+
kTeardown = 3,
334+
};
335+
void MarkReleased(v8::Isolate* isolate, const v8::Local<v8::Object>& obj, ReleasedReason reason);
336+
ReleasedReason GetReleasedReason(const v8::Local<v8::Value>& val);
337+
const char* ReleasedReasonMessage(ReleasedReason reason);
338+
339+
// Applies ReleasedObjectPolicy to a released ObjC wrapper reaching native code
340+
// in place of its object. Throws a ReferenceError under kThrow when `canThrow`;
341+
// otherwise schedules the `releasednativeaccess` event (deduplicated per
342+
// object). The caller then passes nil (or NSNull where nil is not allowed).
343+
// Returns false when it threw.
344+
bool ReportReleasedObject(v8::Isolate* isolate, const v8::Local<v8::Value>& val,
345+
ReleasedReason reason, const char* operation, bool canThrow);
346+
347+
// Whether the runtime warns when JS state on a wrapper is lost while its native
348+
// object lives on. Process-wide; defaults to the app's debug flag, overridden by
349+
// the "wrapperLifetime": { "warnings": bool } app config or ns:runtime's
350+
// `wrapperLifetimeWarnings` key.
351+
bool WrapperLifetimeWarningsEnabled();
352+
void SetWrapperLifetimeWarnings(bool enabled);
319353
void DeleteValue(v8::Isolate* isolate, const v8::Local<v8::Value>& val);
320354
bool DeleteWrapperIfUnused(v8::Isolate* isolate, const v8::Local<v8::Value>& obj,
321355
BaseDataWrapper* value);

‎NativeScript/runtime/Helpers.mm‎

Lines changed: 110 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@
1212
#include <atomic>
1313
#include <cerrno>
1414
#include <mutex>
15+
#include <optional>
1516
#include <sstream>
1617
#include <vector>
1718
#include "Caches.h"
1819
#include "ErrorEvents.h"
1920
#include "NativeScriptException.h"
21+
#include "ObjectManager.h"
2022
#include "Runtime.h"
2123
#include "RuntimeConfig.h"
2224

@@ -519,31 +521,57 @@ void WriteDebugLine(tns::LogCategory category, const char* message) {
519521
va_end(ap);
520522
}
521523

522-
tns::BaseDataWrapper* tns::GetValueOrReport(Isolate* isolate, const Local<Value>& val,
523-
const char* operation) {
524-
BaseDataWrapper* wrapper = tns::GetValue(isolate, val);
525-
if (wrapper != nullptr) {
526-
return wrapper;
524+
const char* tns::ReleasedReasonMessage(ReleasedReason reason) {
525+
switch (reason) {
526+
case tns::ReleasedReason::kCollected:
527+
return "The native object was released when its wrapper was garbage collected";
528+
case tns::ReleasedReason::kExplicit:
529+
return "The native object was released by __releaseNativeCounterpart";
530+
case tns::ReleasedReason::kTeardown:
531+
return "The native object was released at runtime teardown";
532+
case tns::ReleasedReason::kNone:
533+
break;
527534
}
535+
return "The native object has been released or is not a valid native object";
536+
}
528537

529-
std::string message =
530-
std::string("The native object has been released or is not a valid native object (") +
531-
operation + ")";
538+
namespace {
539+
540+
// Shared by GetValueOrReport and ReportReleasedObject: one message format, one
541+
// event, one deduplication marker.
542+
bool ApplyReleasedObjectPolicy(Isolate* isolate, const Local<Value>& val, const char* text,
543+
const char* operation, bool canThrow) {
544+
if (tns::ObjectManager::LifetimeStats* stats = tns::ObjectManager::GetLifetimeStats(isolate)) {
545+
stats->releasedAccesses++;
546+
}
547+
std::string message = std::string(text) + " (" + operation + ")";
532548

533-
if (GetReleasedObjectPolicy() == ReleasedObjectPolicy::kThrow) {
549+
if (canThrow && tns::GetReleasedObjectPolicy() == tns::ReleasedObjectPolicy::kThrow) {
534550
isolate->ThrowException(v8::Exception::ReferenceError(tns::ToV8String(isolate, message)));
535-
return nullptr;
551+
return false;
536552
}
537553

538554
Local<Context> context = isolate->GetCurrentContext();
555+
std::optional<Context::Scope> contextScope;
556+
if (context.IsEmpty() && val->IsObject()) {
557+
// Collection adapters convert elements from native callbacks that may not
558+
// have entered a context.
559+
context = tns::GetCreationContextOrCurrent(isolate, val.As<Object>());
560+
if (!context.IsEmpty()) {
561+
contextScope.emplace(context);
562+
}
563+
}
564+
if (context.IsEmpty()) {
565+
return true;
566+
}
539567
if (val->IsObject()) {
540568
// One report per husk object: a released buffer touched in a tight loop
541569
// must not flood the event queue.
542570
Local<Private> reported =
543571
Private::ForApi(isolate, tns::ToV8String(isolate, "ns:releasedAccessReported"));
544572
Local<Object> obj = val.As<Object>();
545573
if (obj->HasPrivate(context, reported).FromMaybe(false)) {
546-
return nullptr;
574+
return true;
547575
}
548576
obj->SetPrivate(context, reported, v8::True(isolate)).FromMaybe(false);
549577
}
@@ -553,9 +581,80 @@ void WriteDebugLine(tns::LogCategory category, const char* message) {
553581
auto* report =
554582
new ReleasedAccessReport{isolate, v8::Global<v8::Value>(isolate, error), operation};
555583
isolate->EnqueueMicrotask(DispatchReleasedAccessMicrotask, report);
584+
return true;
585+
}
586+
587+
std::atomic<int> wrapperLifetimeWarnings_{-1};
588+
589+
} // namespace
590+
591+
tns::BaseDataWrapper* tns::GetValueOrReport(Isolate* isolate, const Local<Value>& val,
592+
const char* operation) {
593+
BaseDataWrapper* wrapper = tns::GetValue(isolate, val);
594+
if (wrapper != nullptr) {
595+
return wrapper;
596+
}
597+
ApplyReleasedObjectPolicy(isolate, val, ReleasedReasonMessage(GetReleasedReason(val)), operation,
598+
true);
556599
return nullptr;
557600
}
558601

602+
void tns::MarkReleased(Isolate* isolate, const Local<Object>& obj, ReleasedReason reason) {
603+
Local<Value> target = tns::UnwrapProxy(obj);
604+
if (!target.IsEmpty() && target->IsObject() && target.As<Object>()->InternalFieldCount() > 0) {
605+
target.As<Object>()->SetInternalField(0,
606+
v8::Integer::New(isolate, static_cast<int32_t>(reason)));
607+
return;
608+
}
609+
// Wrappers kept in the `metadata` private have no field for the marker; they
610+
// are only cleared, and read as plain objects afterwards.
611+
tns::DeleteValue(isolate, obj);
612+
}
613+
614+
tns::ReleasedReason tns::GetReleasedReason(const Local<Value>& val) {
615+
Local<Value> target = tns::UnwrapProxy(val);
616+
if (target.IsEmpty() || !target->IsObject()) {
617+
return ReleasedReason::kNone;
618+
}
619+
Local<Object> obj = target.As<Object>();
620+
if (obj->InternalFieldCount() < 1) {
621+
return ReleasedReason::kNone;
622+
}
623+
Local<Value> field = obj->GetInternalField(0).As<v8::Value>();
624+
if (field.IsEmpty() || !field->IsInt32()) {
625+
return ReleasedReason::kNone;
626+
}
627+
return static_cast<ReleasedReason>(field.As<v8::Int32>()->Value());
628+
}
629+
630+
bool tns::ReportReleasedObject(Isolate* isolate, const Local<Value>& val, ReleasedReason reason,
631+
const char* operation, bool canThrow) {
632+
return ApplyReleasedObjectPolicy(isolate, val, ReleasedReasonMessage(reason), operation, canThrow);
633+
}
634+
635+
bool tns::WrapperLifetimeWarningsEnabled() {
636+
int value = wrapperLifetimeWarnings_.load(std::memory_order_relaxed);
637+
if (value >= 0) {
638+
return value != 0;
639+
}
640+
bool enabled = RuntimeConfig.IsDebug;
641+
id config = Runtime::GetAppConfigValue("wrapperLifetime");
642+
if ([config isKindOfClass:[NSDictionary class]]) {
643+
id warnings = ((NSDictionary*)config)[@"warnings"];
644+
if ([warnings isKindOfClass:[NSNumber class]]) {
645+
enabled = [warnings boolValue];
646+
}
647+
}
648+
int expected = -1;
649+
wrapperLifetimeWarnings_.compare_exchange_strong(expected, enabled ? 1 : 0,
650+
std::memory_order_relaxed);
651+
return wrapperLifetimeWarnings_.load(std::memory_order_relaxed) != 0;
652+
}
653+
654+
void tns::SetWrapperLifetimeWarnings(bool enabled) {
655+
wrapperLifetimeWarnings_.store(enabled ? 1 : 0, std::memory_order_relaxed);
656+
}
657+
559658
void tns::DeleteValue(Isolate* isolate, const Local<Value>& val) {
560659
Local<Value> target = tns::UnwrapProxy(val);
561660
if (target.IsEmpty() || target->IsNullOrUndefined() || !target->IsObject()) {

‎NativeScript/runtime/Interop.mm‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -776,6 +776,16 @@ static bool SnapshotArrayLike(Isolate* isolate, Local<Object> object, Local<v8::
776776
return;
777777
}
778778

779+
// A wrapper whose native object was released must never reach native code
780+
// as a DictionaryAdapter standing in for it.
781+
tns::ReleasedReason releasedReason = tns::GetReleasedReason(obj);
782+
if (releasedReason != tns::ReleasedReason::kNone) {
783+
tns::ReportReleasedObject(isolate, obj, releasedReason, "native argument", true);
784+
id none = nil;
785+
Interop::SetValue(dest, none);
786+
return;
787+
}
788+
779789
bool isNSArray = false;
780790
if (typeEncoding->type == BinaryTypeEncodingType::InterfaceDeclarationReference) {
781791
std::string name = typeEncoding->details.interfaceDeclarationReference.name.valuePtr();
@@ -866,6 +876,13 @@ static bool SnapshotArrayLike(Isolate* isolate, Local<Object> object, Local<v8::
866876
break;
867877
}
868878
} else {
879+
// nil is not a legal collection element, and this runs inside adapter
880+
// callbacks where nothing can be thrown.
881+
tns::ReleasedReason releasedReason = tns::GetReleasedReason(arg);
882+
if (releasedReason != tns::ReleasedReason::kNone) {
883+
tns::ReportReleasedObject(isolate, arg, releasedReason, "collection element", false);
884+
return [NSNull null];
885+
}
869886
DictionaryAdapter* adapter = [[DictionaryAdapter alloc] initWithJSObject:source.As<Object>()
870887
isolate:isolate];
871888
// CFAutorelease(adapter);

‎NativeScript/runtime/MetadataBuilder.mm‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@ bool ResolveProxyReceiver(Isolate* isolate, Local<Object>& receiver, const char*
5454
(wrapper->Type() == WrapperType::ObjCObject ||
5555
wrapper->Type() == WrapperType::ObjCAllocObject);
5656
if (!isClass && !isInstance) {
57+
if (tns::GetReleasedReason(target) != tns::ReleasedReason::kNone) {
58+
// A released wrapper: the call reports it the same way as on the
59+
// target directly.
60+
receiver = target.As<Object>();
61+
return true;
62+
}
5763
reason = "on a Proxy whose target is not a native object";
5864
}
5965
}

‎NativeScript/runtime/NsBuiltinModules.cpp‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include "Helpers.h"
99
#include "Interop.h"
1010
#include "Messaging.h"
11+
#include "ObjectManager.h"
1112
#include "ModuleInternalCallbacks.h"
1213
#include "Runtime.h"
1314
#include "StructuredSerialization.h"
@@ -101,6 +102,7 @@ std::string Canonicalize(const std::string& specifier) {
101102
// deliberately not registered — it is boot-time nativescript.config only.
102103
constexpr const char* kReleasedObjectPolicyKey = "releasedObjectPolicy";
103104
constexpr const char* kDebugKey = "debug";
105+
constexpr const char* kWrapperLifetimeWarningsKey = "wrapperLifetimeWarnings";
104106

105107
void ThrowTypeError(Isolate* isolate, const std::string& message) {
106108
isolate->ThrowException(
@@ -139,6 +141,17 @@ void SetConfigCallback(const FunctionCallbackInfo<Value>& info) {
139141
}
140142
return;
141143
}
144+
if (key == kWrapperLifetimeWarningsKey) {
145+
if (!EnsureMainIsolateWrite(isolate, key)) {
146+
return;
147+
}
148+
if (!info[1]->IsBoolean()) {
149+
ThrowTypeError(isolate, "'" + key + "' must be a boolean");
150+
return;
151+
}
152+
tns::SetWrapperLifetimeWarnings(info[1]->IsTrue());
153+
return;
154+
}
142155
if (key == kDebugKey) {
143156
if (!EnsureMainIsolateWrite(isolate, key)) {
144157
return;
@@ -187,9 +200,40 @@ void GetConfigCallback(const FunctionCallbackInfo<Value>& info) {
187200
tns::ToV8String(isolate, tns::EnabledLogCategoryNames()));
188201
return;
189202
}
203+
if (key == kWrapperLifetimeWarningsKey) {
204+
info.GetReturnValue().Set(tns::WrapperLifetimeWarningsEnabled());
205+
return;
206+
}
190207
ThrowTypeError(isolate, "Unknown runtime config key: '" + key + "'");
191208
}
192209

210+
// Counters for the calling isolate; see ObjectManager::LifetimeStats.
211+
void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo<Value>& info) {
212+
Isolate* isolate = info.GetIsolate();
213+
Local<Context> context = isolate->GetCurrentContext();
214+
Local<Object> result = Object::New(isolate);
215+
tns::ObjectManager::LifetimeStats* stats = tns::ObjectManager::GetLifetimeStats(isolate);
216+
if (stats == nullptr) {
217+
info.GetReturnValue().Set(result);
218+
return;
219+
}
220+
const std::pair<const char*, uint64_t> fields[] = {
221+
{"resurrections", stats->resurrections},
222+
{"collected", stats->collected},
223+
{"releasedExplicitly", stats->releasedExplicitly},
224+
{"releasedAccesses", stats->releasedAccesses},
225+
{"stateLostCandidates", stats->stateLostCandidates},
226+
{"stateLostConfirmed", stats->stateLostConfirmed},
227+
};
228+
for (const auto& [name, value] : fields) {
229+
result
230+
->Set(context, tns::ToV8String(isolate, name),
231+
v8::Number::New(isolate, static_cast<double>(value)))
232+
.FromMaybe(false);
233+
}
234+
info.GetReturnValue().Set(result);
235+
}
236+
193237
const Registration* Find(const std::string& specifier) {
194238
for (const Registration& registration : kRegistry) {
195239
if (specifier == registration.specifier) {
@@ -218,12 +262,17 @@ MaybeLocal<Object> NsModuleBinding(Local<Context> context) {
218262
MaybeLocal<Object> NsRuntimeBinding(Local<Context> context) {
219263
Isolate* isolate = v8::Isolate::GetCurrent();
220264
Local<Object> binding = Object::New(isolate);
221-
Local<v8::Function> setConfig, getConfig;
265+
Local<v8::Function> setConfig, getConfig, getWrapperLifetimeStats;
222266
if (!v8::Function::New(context, SetConfigCallback).ToLocal(&setConfig) ||
223267
!v8::Function::New(context, GetConfigCallback).ToLocal(&getConfig) ||
268+
!v8::Function::New(context, GetWrapperLifetimeStatsCallback)
269+
.ToLocal(&getWrapperLifetimeStats) ||
224270
!binding->Set(context, tns::ToV8String(isolate, "setConfig"), setConfig)
225271
.FromMaybe(false) ||
226272
!binding->Set(context, tns::ToV8String(isolate, "getConfig"), getConfig)
273+
.FromMaybe(false) ||
274+
!binding->Set(context, tns::ToV8String(isolate, "getWrapperLifetimeStats"),
275+
getWrapperLifetimeStats)
227276
.FromMaybe(false)) {
228277
return MaybeLocal<Object>();
229278
}

0 commit comments

Comments
 (0)