Skip to content

Commit 0adee25

Browse files
authored
feat(runtime): wrapper lifetime diagnostics and released-object arguments (#558)
* 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. * fix(runtime): test ObjC tagged pointers through void* for Release builds clang rejects bit tests on ObjC object pointers under -Werror (-Wdeprecated-objc-pointer-introspection), which broke the x86_64 simulator archive. * fix(runtime): released-object marker by identity, throw before native calls - Under the "throw" policy a released argument now raises before the native call (tns::ThrowReleasedObject, a NativeScriptException) instead of setting a pending exception and calling native code with nil. - The released marker in internal field 0 is a per-isolate Symbol matched by identity. URL, URLSearchParams, URLPattern and MessagePort keep raw aligned pointers in field 0, which read back as Smis and were reported as released objects. - GetReleasedReason follows `this.super` aliases, and borrowed -dealloc receivers are marked (new kDeallocated reason) instead of cleared, so they report like other released wrappers rather than becoming a DictionaryAdapter or asserting in Release. - toString() on a released wrapper returns "[released <class>]" under "report" and throws under "throw", instead of returning the object. - State-lost confirmation steps behind releases an off-thread collection queued for the runtime thread, so a co-collected owner is not reported. The candidate's class and weak reference are taken before any V8 call, the retain count is read without JS overrides, the probe's retain is dropped before logging, and the x86_64 simulator's tagged pointers are recognised. - Markers, lifetime state and the warnings flag are created in ObjectManager::Init, never from a finalizer; a handle kept for a pending native owner counts as a resurrection. * fix(runtime): release the receiver allocated for an initializer whose arguments throw `alloc().initX(args)` allocates its receiver before the arguments are converted, and the initializer consumes it. When a conversion throws (a released object under the "throw" policy, or any other conversion error), the initializer never runs, so the receiver is released instead of leaking. The `new X(args)` initializer path gets the same guard. Docs: under either policy a method call or native property read on a released Objective-C object throws, and values handed to native code with no JS caller (JS-implemented method returns, collection elements) become nil or NSNull and report, under "throw" too. * fix(runtime): report argument errors from native block and function pointer calls JS calls into a native block or a native function pointer converted their arguments with no handler for NativeScriptException, so a conversion error (a released object under the "throw" policy among them) escaped the V8 callback and aborted the app. Both now rethrow it to JS. * style(runtime): clang-format
1 parent 1b39251 commit 0adee25

23 files changed

Lines changed: 1066 additions & 72 deletions

‎NativeScript/runtime/ArgConverter.mm‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ bool IsKVOSubclassOf(Class klass, Class base) {
7272
// kept must read as released.
7373
NativeCallbackSelf::~NativeCallbackSelf() {
7474
if (borrowed_ != nullptr && tns::GetValue(isolate_, receiver_) == borrowed_) {
75-
tns::SetValue(isolate_, receiver_, nullptr);
75+
tns::MarkReleased(isolate_, receiver_, tns::ReleasedReason::kDeallocated);
7676
delete borrowed_;
7777
}
7878
}
@@ -95,6 +95,12 @@ bool IsKVOSubclassOf(Class klass, Class base) {
9595
BaseDataWrapper* wrapper = tns::GetValue(isolate, receiver);
9696

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

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

@@ -644,6 +650,14 @@ bool IsKVOSubclassOf(Class klass, Class base) {
644650
*static_cast<id __strong*>(retValue) = data;
645651
return true;
646652
} else {
653+
// Native code receives this value outside any JS frame, so a released
654+
// wrapper is reported (never thrown) and returned as nil.
655+
tns::ReleasedReason releasedReason = tns::GetReleasedReason(value);
656+
if (releasedReason != tns::ReleasedReason::kNone) {
657+
tns::ReportReleasedObject(isolate, value, releasedReason, "method return value", false);
658+
memset(retValue, 0, sizeof(id));
659+
return false;
660+
}
647661
id adapter = [[DictionaryAdapter alloc]
648662
initWithJSObject:tns::ProxyReadSource(original, value).As<Object>()
649663
isolate:isolate];

‎NativeScript/runtime/Helpers.h‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,50 @@ void SetReleasedObjectPolicy(ReleasedObjectPolicy policy);
326326
// field unchecked must go through this.
327327
BaseDataWrapper* GetValueOrReport(v8::Isolate* isolate, const v8::Local<v8::Value>& val,
328328
const char* operation);
329+
330+
// Why an ObjC object's wrapper no longer has its native object. Internal field
331+
// 0, where the External would otherwise sit, holds a per-isolate Symbol for the
332+
// reason: GetValue only reads Externals, so every existing caller sees "no
333+
// wrapper". Reasons are recognised by identity, never by value, because other
334+
// templates keep raw aligned pointers in field 0, which read back as arbitrary
335+
// Smis.
336+
enum class ReleasedReason : int32_t {
337+
kNone = 0,
338+
// The wrapper's finalizer released it while JS could still reach the
339+
// wrapper (only possible through a graph a resurrected wrapper keeps alive).
340+
kCollected = 1,
341+
// __releaseNativeCounterpart.
342+
kExplicit = 2,
343+
// Runtime teardown.
344+
kTeardown = 3,
345+
// A receiver lent to JS while its object ran -dealloc.
346+
kDeallocated = 4,
347+
};
348+
// Creates the isolate's markers, so marking never allocates in a finalizer.
349+
void InitReleasedMarkers(v8::Isolate* isolate);
350+
void MarkReleased(v8::Isolate* isolate, const v8::Local<v8::Object>& obj, ReleasedReason reason);
351+
// Follows Proxies and `this.super` aliases to the wrapper they stand for.
352+
ReleasedReason GetReleasedReason(const v8::Local<v8::Value>& val);
353+
const char* ReleasedReasonMessage(ReleasedReason reason);
354+
// Counts the access and throws the ReferenceError as a NativeScriptException,
355+
// for paths that must not reach native code once the error is raised.
356+
[[noreturn]] void ThrowReleasedObject(v8::Isolate* isolate, ReleasedReason reason,
357+
const std::string& operation);
358+
359+
// Applies ReleasedObjectPolicy to a released ObjC wrapper reaching native code
360+
// in place of its object. Throws a ReferenceError under kThrow when `canThrow`;
361+
// otherwise schedules the `releasednativeaccess` event (deduplicated per
362+
// object). The caller then passes nil (or NSNull where nil is not allowed).
363+
// Returns false when it threw.
364+
bool ReportReleasedObject(v8::Isolate* isolate, const v8::Local<v8::Value>& val,
365+
ReleasedReason reason, const char* operation, bool canThrow);
366+
367+
// Whether the runtime warns when JS state on a wrapper is lost while its native
368+
// object lives on. Process-wide; defaults to the app's debug flag, overridden by
369+
// the "wrapperLifetime": { "warnings": bool } app config or ns:runtime's
370+
// `wrapperLifetimeWarnings` key.
371+
bool WrapperLifetimeWarningsEnabled();
372+
void SetWrapperLifetimeWarnings(bool enabled);
329373
void DeleteValue(v8::Isolate* isolate, const v8::Local<v8::Value>& val);
330374
bool DeleteWrapperIfUnused(v8::Isolate* isolate, const v8::Local<v8::Value>& obj,
331375
BaseDataWrapper* value);

‎NativeScript/runtime/Helpers.mm‎

Lines changed: 167 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

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

541-
tns::BaseDataWrapper* tns::GetValueOrReport(Isolate* isolate, const Local<Value>& val,
542-
const char* operation) {
543-
BaseDataWrapper* wrapper = tns::GetValue(isolate, val);
544-
if (wrapper != nullptr) {
545-
return wrapper;
543+
const char* tns::ReleasedReasonMessage(ReleasedReason reason) {
544+
switch (reason) {
545+
case tns::ReleasedReason::kCollected:
546+
return "The native object was released when its wrapper was garbage collected";
547+
case tns::ReleasedReason::kExplicit:
548+
return "The native object was released by __releaseNativeCounterpart";
549+
case tns::ReleasedReason::kTeardown:
550+
return "The native object was released at runtime teardown";
551+
case tns::ReleasedReason::kDeallocated:
552+
return "The native object was deallocated after lending this receiver to JS from -dealloc";
553+
case tns::ReleasedReason::kNone:
554+
break;
546555
}
556+
return "The native object has been released or is not a valid native object";
557+
}
547558

548-
std::string message =
549-
std::string("The native object has been released or is not a valid native object (") +
550-
operation + ")";
559+
namespace {
560+
561+
// Shared by GetValueOrReport and ReportReleasedObject: one message format, one
562+
// event, one deduplication marker.
563+
bool ApplyReleasedObjectPolicy(Isolate* isolate, const Local<Value>& val, const char* text,
564+
const char* operation, bool canThrow) {
565+
if (tns::ObjectManager::LifetimeStats* stats = tns::ObjectManager::GetLifetimeStats(isolate)) {
566+
stats->releasedAccesses++;
567+
}
568+
std::string message = std::string(text) + " (" + operation + ")";
551569

552-
if (GetReleasedObjectPolicy() == ReleasedObjectPolicy::kThrow) {
570+
if (canThrow && tns::GetReleasedObjectPolicy() == tns::ReleasedObjectPolicy::kThrow) {
553571
isolate->ThrowException(v8::Exception::ReferenceError(tns::ToV8String(isolate, message)));
554-
return nullptr;
572+
return false;
555573
}
556574

557575
Local<Context> context = isolate->GetCurrentContext();
576+
std::optional<Context::Scope> contextScope;
577+
if (context.IsEmpty() && val->IsObject()) {
578+
// Collection adapters convert elements from native callbacks that may not
579+
// have entered a context.
580+
context = tns::GetCreationContextOrCurrent(isolate, val.As<Object>());
581+
if (!context.IsEmpty()) {
582+
contextScope.emplace(context);
583+
}
584+
}
585+
if (context.IsEmpty()) {
586+
return true;
587+
}
558588
if (val->IsObject()) {
559589
// One report per husk object: a released buffer touched in a tight loop
560590
// must not flood the event queue.
561591
Local<Private> reported =
562592
Private::ForApi(isolate, tns::ToV8String(isolate, "ns:releasedAccessReported"));
563593
Local<Object> obj = val.As<Object>();
564594
if (obj->HasPrivate(context, reported).FromMaybe(false)) {
565-
return nullptr;
595+
return true;
566596
}
567597
obj->SetPrivate(context, reported, v8::True(isolate)).FromMaybe(false);
568598
}
@@ -572,9 +602,135 @@ void WriteDebugLine(tns::LogCategory category, const char* message) {
572602
auto* report =
573603
new ReleasedAccessReport{isolate, v8::Global<v8::Value>(isolate, error), operation};
574604
isolate->EnqueueMicrotask(DispatchReleasedAccessMicrotask, report);
605+
return true;
606+
}
607+
608+
std::atomic<int> wrapperLifetimeWarnings_{-1};
609+
610+
} // namespace
611+
612+
tns::BaseDataWrapper* tns::GetValueOrReport(Isolate* isolate, const Local<Value>& val,
613+
const char* operation) {
614+
BaseDataWrapper* wrapper = tns::GetValue(isolate, val);
615+
if (wrapper != nullptr) {
616+
return wrapper;
617+
}
618+
ApplyReleasedObjectPolicy(isolate, val, ReleasedReasonMessage(GetReleasedReason(val)), operation,
619+
true);
575620
return nullptr;
576621
}
577622

623+
namespace {
624+
625+
constexpr int kReleasedReasonCount = static_cast<int>(tns::ReleasedReason::kDeallocated);
626+
627+
struct ReleasedMarkers {
628+
v8::Eternal<v8::Symbol> reasons[kReleasedReasonCount];
629+
};
630+
631+
} // namespace
632+
633+
void tns::InitReleasedMarkers(Isolate* isolate) {
634+
ReleasedMarkers* markers = Caches::StateFor<ReleasedMarkers>(isolate);
635+
if (markers == nullptr) {
636+
return;
637+
}
638+
for (int i = 0; i < kReleasedReasonCount; i++) {
639+
if (markers->reasons[i].IsEmpty()) {
640+
markers->reasons[i].Set(isolate,
641+
v8::Symbol::New(isolate, tns::ToV8String(isolate, "ns:released")));
642+
}
643+
}
644+
}
645+
646+
void tns::MarkReleased(Isolate* isolate, const Local<Object>& obj, ReleasedReason reason) {
647+
Local<Value> target = tns::UnwrapProxy(obj);
648+
// Read without the validity check: teardown marks after InvalidateIsolate.
649+
ReleasedMarkers* markers = Caches::ExistingStateFor<ReleasedMarkers>(isolate);
650+
int index = static_cast<int>(reason) - 1;
651+
if (markers != nullptr && index >= 0 && index < kReleasedReasonCount &&
652+
!markers->reasons[index].IsEmpty() && !target.IsEmpty() && target->IsObject() &&
653+
target.As<Object>()->InternalFieldCount() > 0) {
654+
target.As<Object>()->SetInternalField(0, markers->reasons[index].Get(isolate));
655+
return;
656+
}
657+
// Wrappers kept in the `metadata` private have no field for the marker; they
658+
// are only cleared, and read as plain objects afterwards.
659+
tns::DeleteValue(isolate, obj);
660+
}
661+
662+
tns::ReleasedReason tns::GetReleasedReason(const Local<Value>& val) {
663+
Local<Value> target = tns::UnwrapProxy(val);
664+
if (target.IsEmpty() || !target->IsObject()) {
665+
return ReleasedReason::kNone;
666+
}
667+
Local<Object> obj = target.As<Object>();
668+
if (obj->InternalFieldCount() < 1) {
669+
return ReleasedReason::kNone;
670+
}
671+
Local<Value> field = obj->GetInternalField(0).As<v8::Value>();
672+
if (field.IsEmpty()) {
673+
return ReleasedReason::kNone;
674+
}
675+
if (field->IsObject()) {
676+
Local<Object> receiver = SuperAliasReceiver(obj);
677+
return receiver.IsEmpty() ? ReleasedReason::kNone : GetReleasedReason(receiver);
678+
}
679+
if (!field->IsSymbol()) {
680+
return ReleasedReason::kNone;
681+
}
682+
Isolate* isolate = v8::Isolate::GetCurrent();
683+
ReleasedMarkers* markers = Caches::ExistingStateFor<ReleasedMarkers>(isolate);
684+
if (markers == nullptr) {
685+
return ReleasedReason::kNone;
686+
}
687+
for (int i = 0; i < kReleasedReasonCount; i++) {
688+
if (!markers->reasons[i].IsEmpty() && markers->reasons[i].Get(isolate) == field) {
689+
return static_cast<ReleasedReason>(i + 1);
690+
}
691+
}
692+
return ReleasedReason::kNone;
693+
}
694+
695+
void tns::ThrowReleasedObject(Isolate* isolate, ReleasedReason reason,
696+
const std::string& operation) {
697+
if (tns::ObjectManager::LifetimeStats* stats = tns::ObjectManager::GetLifetimeStats(isolate)) {
698+
stats->releasedAccesses++;
699+
}
700+
std::string message = std::string(ReleasedReasonMessage(reason)) + " (" + operation + ")";
701+
throw NativeScriptException(
702+
isolate, v8::Exception::ReferenceError(tns::ToV8String(isolate, message)), message);
703+
}
704+
705+
bool tns::ReportReleasedObject(Isolate* isolate, const Local<Value>& val, ReleasedReason reason,
706+
const char* operation, bool canThrow) {
707+
return ApplyReleasedObjectPolicy(isolate, val, ReleasedReasonMessage(reason), operation,
708+
canThrow);
709+
}
710+
711+
bool tns::WrapperLifetimeWarningsEnabled() {
712+
int value = wrapperLifetimeWarnings_.load(std::memory_order_relaxed);
713+
if (value >= 0) {
714+
return value != 0;
715+
}
716+
bool enabled = RuntimeConfig.IsDebug;
717+
id config = Runtime::GetAppConfigValue("wrapperLifetime");
718+
if ([config isKindOfClass:[NSDictionary class]]) {
719+
id warnings = ((NSDictionary*)config)[@"warnings"];
720+
if ([warnings isKindOfClass:[NSNumber class]]) {
721+
enabled = [warnings boolValue];
722+
}
723+
}
724+
int expected = -1;
725+
wrapperLifetimeWarnings_.compare_exchange_strong(expected, enabled ? 1 : 0,
726+
std::memory_order_relaxed);
727+
return wrapperLifetimeWarnings_.load(std::memory_order_relaxed) != 0;
728+
}
729+
730+
void tns::SetWrapperLifetimeWarnings(bool enabled) {
731+
wrapperLifetimeWarnings_.store(enabled ? 1 : 0, std::memory_order_relaxed);
732+
}
733+
578734
void tns::DeleteValue(Isolate* isolate, const Local<Value>& val) {
579735
Local<Value> target = tns::UnwrapProxy(val);
580736
if (target.IsEmpty() || target->IsNullOrUndefined() || !target->IsObject()) {

0 commit comments

Comments
 (0)