From c0c38d7bb5041ac351cee74a689d3764c059ece7 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 12 Nov 2026 16:32:57 -0300 Subject: [PATCH 1/6] 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. --- NativeScript/runtime/ArgConverter.mm | 21 ++ NativeScript/runtime/Helpers.h | 34 +++ NativeScript/runtime/Helpers.mm | 121 +++++++++- NativeScript/runtime/Interop.mm | 17 ++ NativeScript/runtime/MetadataBuilder.mm | 6 + NativeScript/runtime/NsBuiltinModules.cpp | 51 +++- NativeScript/runtime/ObjectManager.h | 21 ++ NativeScript/runtime/ObjectManager.mm | 176 +++++++++++++- NativeScript/runtime/js/ns-runtime.js | 4 +- TestRunner/app/tests/NsRuntimeTests.js | 1 + TestRunner/app/tests/SuperAliasTests.js | 2 +- TestRunner/app/tests/WrapperLifetimeTests.js | 241 +++++++++++++++++++ TestRunner/app/tests/index.js | 1 + docs/knowledge/v8-resurrecting-finalizers.md | 20 +- docs/ns-builtin-modules.md | 23 ++ types/ns-runtime.d.ts | 35 +++ 16 files changed, 753 insertions(+), 21 deletions(-) create mode 100644 TestRunner/app/tests/WrapperLifetimeTests.js diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 49053bf6a..b4ea5b366 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -95,6 +95,19 @@ 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() : ""; + std::string operation = std::string("method '") + jsNameStr + "' receiver"; + if (tns::ObjectManager::LifetimeStats* stats = + tns::ObjectManager::GetLifetimeStats(isolate)) { + stats->releasedAccesses++; + } + std::string message = + std::string(tns::ReleasedReasonMessage(releasedReason)) + " (" + operation + ")"; + throw NativeScriptException( + isolate, Exception::ReferenceError(tns::ToV8String(isolate, message)), message); + } // 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. @@ -644,6 +657,14 @@ bool IsKVOSubclassOf(Class klass, Class base) { *static_cast(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() isolate:isolate]; diff --git a/NativeScript/runtime/Helpers.h b/NativeScript/runtime/Helpers.h index 75a9df55b..645fa51c4 100644 --- a/NativeScript/runtime/Helpers.h +++ b/NativeScript/runtime/Helpers.h @@ -326,6 +326,40 @@ void SetReleasedObjectPolicy(ReleasedObjectPolicy policy); // field unchecked must go through this. BaseDataWrapper* GetValueOrReport(v8::Isolate* isolate, const v8::Local& val, const char* operation); + +// Why an ObjC object's wrapper no longer has its native object. Stored as a +// small integer in internal field 0, where an External would otherwise sit: +// GetValue only reads Externals, so every existing caller sees "no wrapper", +// and writing it allocates nothing inside the finalizer drain. +enum class ReleasedReason : int32_t { + // Zero is never a reason: other templates' embedder fields can hold Smi 0. + 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, +}; +void MarkReleased(v8::Isolate* isolate, const v8::Local& obj, ReleasedReason reason); +ReleasedReason GetReleasedReason(const v8::Local& val); +const char* ReleasedReasonMessage(ReleasedReason reason); + +// 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& 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& val); bool DeleteWrapperIfUnused(v8::Isolate* isolate, const v8::Local& obj, BaseDataWrapper* value); diff --git a/NativeScript/runtime/Helpers.mm b/NativeScript/runtime/Helpers.mm index 8d9e8505a..d22535ffe 100644 --- a/NativeScript/runtime/Helpers.mm +++ b/NativeScript/runtime/Helpers.mm @@ -12,11 +12,13 @@ #include #include #include +#include #include #include #include "Caches.h" #include "ErrorEvents.h" #include "NativeScriptException.h" +#include "ObjectManager.h" #include "Runtime.h" #include "RuntimeConfig.h" @@ -538,23 +540,49 @@ void WriteDebugLine(tns::LogCategory category, const char* message) { va_end(ap); } -tns::BaseDataWrapper* tns::GetValueOrReport(Isolate* isolate, const Local& 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::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& 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 = isolate->GetCurrentContext(); + std::optional 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()); + 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. @@ -562,7 +590,7 @@ void WriteDebugLine(tns::LogCategory category, const char* message) { Private::ForApi(isolate, tns::ToV8String(isolate, "ns:releasedAccessReported")); Local obj = val.As(); if (obj->HasPrivate(context, reported).FromMaybe(false)) { - return nullptr; + return true; } obj->SetPrivate(context, reported, v8::True(isolate)).FromMaybe(false); } @@ -572,9 +600,80 @@ void WriteDebugLine(tns::LogCategory category, const char* message) { auto* report = new ReleasedAccessReport{isolate, v8::Global(isolate, error), operation}; isolate->EnqueueMicrotask(DispatchReleasedAccessMicrotask, report); + return true; +} + +std::atomic wrapperLifetimeWarnings_{-1}; + +} // namespace + +tns::BaseDataWrapper* tns::GetValueOrReport(Isolate* isolate, const Local& 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; } +void tns::MarkReleased(Isolate* isolate, const Local& obj, ReleasedReason reason) { + Local target = tns::UnwrapProxy(obj); + if (!target.IsEmpty() && target->IsObject() && target.As()->InternalFieldCount() > 0) { + target.As()->SetInternalField(0, + v8::Integer::New(isolate, static_cast(reason))); + 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& val) { + Local target = tns::UnwrapProxy(val); + if (target.IsEmpty() || !target->IsObject()) { + return ReleasedReason::kNone; + } + Local obj = target.As(); + if (obj->InternalFieldCount() < 1) { + return ReleasedReason::kNone; + } + Local field = obj->GetInternalField(0).As(); + if (field.IsEmpty() || !field->IsInt32()) { + return ReleasedReason::kNone; + } + return static_cast(field.As()->Value()); +} + +bool tns::ReportReleasedObject(Isolate* isolate, const Local& 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& val) { Local target = tns::UnwrapProxy(val); if (target.IsEmpty() || target->IsNullOrUndefined() || !target->IsObject()) { diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index 2ee515287..2a2635a39 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -825,6 +825,16 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Localtype == BinaryTypeEncodingType::InterfaceDeclarationReference) { std::string name = typeEncoding->details.interfaceDeclarationReference.name.valuePtr(); @@ -915,6 +925,13 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Local() isolate:isolate]; // CFAutorelease(adapter); diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index fa9729a3f..9cc15564c 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -55,6 +55,12 @@ bool ResolveProxyReceiver(Isolate* isolate, Local& receiver, const char* (wrapper->Type() == WrapperType::ObjCObject || wrapper->Type() == WrapperType::ObjCAllocObject); if (!isClass && !isInstance) { + if (tns::GetReleasedReason(target) != tns::ReleasedReason::kNone) { + // A released wrapper: the call reports it the same way as on the + // target directly. + receiver = target.As(); + return true; + } reason = "on a Proxy whose target is not a native object"; } } diff --git a/NativeScript/runtime/NsBuiltinModules.cpp b/NativeScript/runtime/NsBuiltinModules.cpp index 902626c93..200afb3c6 100644 --- a/NativeScript/runtime/NsBuiltinModules.cpp +++ b/NativeScript/runtime/NsBuiltinModules.cpp @@ -8,6 +8,7 @@ #include "Helpers.h" #include "Interop.h" #include "Messaging.h" +#include "ObjectManager.h" #include "ModuleInternalCallbacks.h" #include "Runtime.h" #include "StructuredSerialization.h" @@ -101,6 +102,7 @@ std::string Canonicalize(const std::string& specifier) { // deliberately not registered — it is boot-time nativescript.config only. constexpr const char* kReleasedObjectPolicyKey = "releasedObjectPolicy"; constexpr const char* kDebugKey = "debug"; +constexpr const char* kWrapperLifetimeWarningsKey = "wrapperLifetimeWarnings"; void ThrowTypeError(Isolate* isolate, const std::string& message) { isolate->ThrowException( @@ -139,6 +141,17 @@ void SetConfigCallback(const FunctionCallbackInfo& info) { } return; } + if (key == kWrapperLifetimeWarningsKey) { + if (!EnsureMainIsolateWrite(isolate, key)) { + return; + } + if (!info[1]->IsBoolean()) { + ThrowTypeError(isolate, "'" + key + "' must be a boolean"); + return; + } + tns::SetWrapperLifetimeWarnings(info[1]->IsTrue()); + return; + } if (key == kDebugKey) { if (!EnsureMainIsolateWrite(isolate, key)) { return; @@ -187,9 +200,40 @@ void GetConfigCallback(const FunctionCallbackInfo& info) { tns::ToV8String(isolate, tns::EnabledLogCategoryNames())); return; } + if (key == kWrapperLifetimeWarningsKey) { + info.GetReturnValue().Set(tns::WrapperLifetimeWarningsEnabled()); + return; + } ThrowTypeError(isolate, "Unknown runtime config key: '" + key + "'"); } +// Counters for the calling isolate; see ObjectManager::LifetimeStats. +void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local context = isolate->GetCurrentContext(); + Local result = Object::New(isolate); + tns::ObjectManager::LifetimeStats* stats = tns::ObjectManager::GetLifetimeStats(isolate); + if (stats == nullptr) { + info.GetReturnValue().Set(result); + return; + } + const std::pair fields[] = { + {"resurrections", stats->resurrections}, + {"collected", stats->collected}, + {"releasedExplicitly", stats->releasedExplicitly}, + {"releasedAccesses", stats->releasedAccesses}, + {"stateLostCandidates", stats->stateLostCandidates}, + {"stateLostConfirmed", stats->stateLostConfirmed}, + }; + for (const auto& [name, value] : fields) { + result + ->Set(context, tns::ToV8String(isolate, name), + v8::Number::New(isolate, static_cast(value))) + .FromMaybe(false); + } + info.GetReturnValue().Set(result); +} + const Registration* Find(const std::string& specifier) { for (const Registration& registration : kRegistry) { if (specifier == registration.specifier) { @@ -218,12 +262,17 @@ MaybeLocal NsModuleBinding(Local context) { MaybeLocal NsRuntimeBinding(Local context) { Isolate* isolate = v8::Isolate::GetCurrent(); Local binding = Object::New(isolate); - Local setConfig, getConfig; + Local setConfig, getConfig, getWrapperLifetimeStats; if (!v8::Function::New(context, SetConfigCallback).ToLocal(&setConfig) || !v8::Function::New(context, GetConfigCallback).ToLocal(&getConfig) || + !v8::Function::New(context, GetWrapperLifetimeStatsCallback) + .ToLocal(&getWrapperLifetimeStats) || !binding->Set(context, tns::ToV8String(isolate, "setConfig"), setConfig) .FromMaybe(false) || !binding->Set(context, tns::ToV8String(isolate, "getConfig"), getConfig) + .FromMaybe(false) || + !binding->Set(context, tns::ToV8String(isolate, "getWrapperLifetimeStats"), + getWrapperLifetimeStats) .FromMaybe(false)) { return MaybeLocal(); } diff --git a/NativeScript/runtime/ObjectManager.h b/NativeScript/runtime/ObjectManager.h index 23fda66a2..ddd866f2d 100644 --- a/NativeScript/runtime/ObjectManager.h +++ b/NativeScript/runtime/ObjectManager.h @@ -45,6 +45,27 @@ struct ObjectWeakCallbackState { class ObjectManager { public: + // Per-isolate wrapper lifetime counters. Kept in every build: plain integers + // bumped only on cold paths (finalizers, released-object reports), exposed + // through ns:runtime's getWrapperLifetimeStats(). + struct LifetimeStats { + // An ObjC wrapper's finalizer refused disposal because native code still + // retains its object (IsGcProtected), keeping the wrapper alive. + uint64_t resurrections = 0; + // An ObjC wrapper's finalizer released its native object. + uint64_t collected = 0; + // __releaseNativeCounterpart released a native object. + uint64_t releasedExplicitly = 0; + // JS handed a released wrapper to native code or used it as a receiver. + uint64_t releasedAccesses = 0; + // A finalized ObjC wrapper carried JS properties while something other + // than the wrapper still retained its object, and whether that object was + // still alive a runloop turn later (see WrapperLifetimeWarningsEnabled). + uint64_t stateLostCandidates = 0; + uint64_t stateLostConfirmed = 0; + }; + static LifetimeStats* GetLifetimeStats(v8::Isolate* isolate); + static void Init(v8::Isolate* isolate, v8::Local globalTemplate); static std::shared_ptr> Register( diff --git a/NativeScript/runtime/ObjectManager.mm b/NativeScript/runtime/ObjectManager.mm index 36a832e91..cbe6bb268 100644 --- a/NativeScript/runtime/ObjectManager.mm +++ b/NativeScript/runtime/ObjectManager.mm @@ -12,6 +12,16 @@ #include "FFICall.h" #include "Helpers.h" #include "Runtime.h" +#include +#include +#include +#include +#include + +// Exported by libobjc; not declared in a public header for MRC code. +extern "C" id objc_initWeak(id* location, id value); +extern "C" id objc_loadWeakRetained(id* location); +extern "C" void objc_destroyWeak(id* location); using namespace v8; using namespace std; @@ -80,6 +90,129 @@ void ReconcileOwnershipBeforeGC(Isolate* isolate, GCType, GCCallbackFlags) { } } +// A finalized wrapper that carried JS properties while something other than +// the wrapper still retained its object. Confirmed a runloop turn later, so a +// co-queued owner or a pending autorelease does not produce a warning. +struct StateLostCandidate { + id* weakSlot; + std::string description; + std::string className; + std::string properties; +}; + +struct WrapperLifetimeState { + ObjectManager::LifetimeStats stats; + std::vector candidates; + bool confirmPosted = false; + std::unordered_set warnedClasses; + + ~WrapperLifetimeState() { + for (StateLostCandidate& candidate : candidates) { + objc_destroyWeak(candidate.weakSlot); + delete candidate.weakSlot; + } + } +}; + +bool IsTaggedPointer(id obj) { +#if defined(__arm64__) + return reinterpret_cast(obj) < 0; +#else + return (reinterpret_cast(obj) & 1) != 0; +#endif +} + +void ConfirmStateLost(Isolate* isolate) { + auto* state = Caches::StateFor(isolate); + if (state == nullptr) { + return; + } + state->confirmPosted = false; + std::vector candidates; + candidates.swap(state->candidates); + for (StateLostCandidate& candidate : candidates) { + id obj = objc_loadWeakRetained(candidate.weakSlot); + if (obj != nil) { + state->stats.stateLostConfirmed++; + if (state->warnedClasses.insert(candidate.className).second) { + Log("NativeScript: JS properties (%s) set on %s were lost when its JavaScript wrapper was " + "garbage collected, but the native object is still alive. If native code hands it " + "back, it gets a new wrapper without them. Keep a JS reference to the object while " + "its JS state is needed. Reported once per class; disable with \"wrapperLifetime\": " + "{ \"warnings\": false }.", + candidate.properties.c_str(), candidate.description.c_str()); + } + [obj release]; + } + objc_destroyWeak(candidate.weakSlot); + delete candidate.weakSlot; + } +} + +// Called from the finalizer drain just before the wrapper releases `target`. +void NoteStateLostCandidate(Isolate* isolate, Local obj, id target) { + if (IsTaggedPointer(target)) { + return; + } + NSUInteger count = [target retainCount]; + if (count <= 1 || count >= (NSUIntegerMax >> 1)) { + return; + } + SEL allowsWeak = sel_registerName("allowsWeakReference"); + if ([target respondsToSelector:allowsWeak] && + !reinterpret_cast(objc_msgSend)(target, allowsWeak)) { + return; + } + + HandleScope handleScope(isolate); + TryCatch tryCatch(isolate); + Local context = tns::GetCreationContextOrCurrent(isolate, obj); + Local names; + if (context.IsEmpty() || + !obj->GetOwnPropertyNames(context, PropertyFilter::SKIP_SYMBOLS).ToLocal(&names) || + names->Length() == 0) { + return; + } + + auto* state = Caches::StateFor(isolate); + if (state == nullptr) { + return; + } + state->stats.stateLostCandidates++; + + std::string properties; + uint32_t shown = std::min(names->Length(), 5); + for (uint32_t i = 0; i < shown; i++) { + Local name; + if (!names->Get(context, i).ToLocal(&name)) { + continue; + } + if (!properties.empty()) { + properties += ", "; + } + properties += tns::ToString(isolate, name); + } + if (names->Length() > shown) { + properties += ", ..."; + } + + const char* className = object_getClassName(target); + char description[256]; + snprintf(description, sizeof(description), "<%s: %p>", className, (void*)target); + + id* slot = new id(nil); + objc_initWeak(slot, target); + state->candidates.push_back({slot, description, className, properties}); + + if (!state->confirmPosted) { + Runtime* runtime = Runtime::GetRuntime(isolate); + std::shared_ptr loop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; + if (loop != nullptr && loop->PostInternal([isolate]() { ConfirmStateLost(isolate); })) { + state->confirmPosted = true; + } + } +} + } // namespace namespace { @@ -417,11 +550,19 @@ void DisposeHandle(v8::Isolate* isolate, BaseDataWrapper* wrapper = tns::GetValue(isolate, value); // NSLog(@"dispose %p", wrapper); if (wrapper == nullptr) { - tns::SetValue(isolate, obj, nullptr); + if (tns::GetReleasedReason(obj) == tns::ReleasedReason::kNone) { + tns::SetValue(isolate, obj, nullptr); + } return true; } + const WrapperType type = wrapper->Type(); if (wrapper->IsGcProtected() && !isFinalDisposal) { + if (type == WrapperType::ObjCObject) { + if (LifetimeStats* stats = GetLifetimeStats(isolate)) { + stats->resurrections++; + } + } return false; } @@ -437,7 +578,7 @@ void DisposeHandle(v8::Isolate* isolate, } std::shared_ptr cache = Caches::Get(isolate); - switch (wrapper->Type()) { + switch (type) { case WrapperType::Struct: // Lives in the struct object's ArrayBuffer storage, which the GC frees. return true; @@ -455,6 +596,19 @@ void DisposeHandle(v8::Isolate* isolate, cache->Instances.erase(it); } } + if (!isFinalDisposal) { + if (LifetimeStats* stats = GetLifetimeStats(isolate)) { + stats->collected++; + } + if (tns::WrapperLifetimeWarningsEnabled()) { + NoteStateLostCandidate(isolate, obj, target); + // It allocates, so a nested collection may have run finalizers + // whose JS released this object explicitly. + if (tns::GetValue(isolate, obj) != wrapper) { + return true; + } + } + } if (objCObjectWrapper->IsAdapterClaim()) { // The adapter's -dealloc retires this wrapper; it must run first. [target release]; @@ -555,7 +709,13 @@ void DisposeHandle(v8::Isolate* isolate, // so only a wrapper still sitting in it is ours to free. if (tns::GetValue(isolate, obj) == wrapper) { delete wrapper; - tns::DeleteValue(isolate, obj); + if (type == WrapperType::ObjCObject) { + tns::MarkReleased(isolate, obj, + isFinalDisposal ? tns::ReleasedReason::kTeardown + : tns::ReleasedReason::kCollected); + } else { + tns::DeleteValue(isolate, obj); + } } return true; } @@ -673,13 +833,21 @@ void DisposeHandle(v8::Isolate* isolate, // again. if (!adapterClaim && tns::GetValue(isolate, value) == wrapper) { delete wrapper; - tns::SetValue(isolate, value.As(), nullptr); + tns::MarkReleased(isolate, value.As(), tns::ReleasedReason::kExplicit); + } + if (LifetimeStats* stats = GetLifetimeStats(isolate)) { + stats->releasedExplicitly++; } } } bool ObjectManager::IsInstanceOf(id obj, Class clazz) { return [obj isKindOfClass:clazz]; } +ObjectManager::LifetimeStats* ObjectManager::GetLifetimeStats(Isolate* isolate) { + auto* state = Caches::StateFor(isolate); + return state != nullptr ? &state->stats : nullptr; +} + long ObjectManager::GetRetainCount(id obj) { if (!obj) { return 0; diff --git a/NativeScript/runtime/js/ns-runtime.js b/NativeScript/runtime/js/ns-runtime.js index 03abfd7aa..f34642f55 100644 --- a/NativeScript/runtime/js/ns-runtime.js +++ b/NativeScript/runtime/js/ns-runtime.js @@ -1,7 +1,7 @@ "use strict"; // The `ns:runtime` builtin module: runtime-level configuration, native -// exception escaping and external-memory accounting. See +// exception escaping, external-memory accounting and wrapper lifetime counters. See // docs/ns-builtin-modules.md for the contract and the key registry — keys, // their value domains, and their scope (process-wide vs per-isolate) are // defined and validated on the native side, so this file stays a thin, frozen @@ -13,6 +13,7 @@ const { escapeException, setExternalSize, getExternalSize, + getWrapperLifetimeStats, } = binding; const { ObjectFreeze } = primordials; @@ -21,4 +22,5 @@ exports.getConfig = getConfig; exports.escapeException = escapeException; exports.setExternalSize = setExternalSize; exports.getExternalSize = getExternalSize; +exports.getWrapperLifetimeStats = getWrapperLifetimeStats; ObjectFreeze(exports); diff --git a/TestRunner/app/tests/NsRuntimeTests.js b/TestRunner/app/tests/NsRuntimeTests.js index 1b1b28687..3b2623d03 100644 --- a/TestRunner/app/tests/NsRuntimeTests.js +++ b/TestRunner/app/tests/NsRuntimeTests.js @@ -14,6 +14,7 @@ describe("ns:runtime", function () { "escapeException", "getConfig", "getExternalSize", + "getWrapperLifetimeStats", "setConfig", "setExternalSize", ]); diff --git a/TestRunner/app/tests/SuperAliasTests.js b/TestRunner/app/tests/SuperAliasTests.js index 26b4b62b1..2c072e8fe 100644 --- a/TestRunner/app/tests/SuperAliasTests.js +++ b/TestRunner/app/tests/SuperAliasTests.js @@ -33,7 +33,7 @@ describe("this.super aliases", function () { } catch (e) { error = e; } - expect(error === null ? "" : String(error.message)).toContain("disposed native object"); + expect(error === null ? "" : String(error.message)).toMatch(/disposed native object|native object was released/); } function superGetter(cls) { diff --git a/TestRunner/app/tests/WrapperLifetimeTests.js b/TestRunner/app/tests/WrapperLifetimeTests.js new file mode 100644 index 000000000..0ebeb62f5 --- /dev/null +++ b/TestRunner/app/tests/WrapperLifetimeTests.js @@ -0,0 +1,241 @@ +describe("Wrapper lifetime", function () { + var runtime = require("ns:runtime"); + + function releasedObject() { + var obj = NSObject.alloc().init(); + __releaseNativeCounterpart(obj); + return obj; + } + + function stats() { + return runtime.getWrapperLifetimeStats(); + } + + // The state-lost confirmation runs on the event loop's internal lane, not + // necessarily before the next timer. + function afterTurns(turns, callback) { + setTimeout(function () { + if (turns > 1) { + afterTurns(turns - 1, callback); + } else { + callback(); + } + }, 10); + } + + afterEach(function () { + runtime.setConfig("releasedObjectPolicy", "report"); + }); + + describe("released objects reaching native code", function () { + it("passes nil, not a dictionary, for a released argument under the report policy", function (done) { + var released = releasedObject(); + var events = []; + var onReleased = function (e) { + events.push(e); + }; + global.addEventListener("releasednativeaccess", onReleased); + + var dict = NSMutableDictionary.new(); + dict.setValueForKey(released, "key"); + expect(dict.count).toBe(0); + + setTimeout(function () { + global.removeEventListener("releasednativeaccess", onReleased); + expect(events.length).toBe(1); + expect(events[0].error.message).toMatch(/__releaseNativeCounterpart/); + expect(events[0].error.message).toMatch(/native argument/); + done(); + }); + }); + + it("throws a ReferenceError for a released argument under the throw policy", function () { + var released = releasedObject(); + runtime.setConfig("releasedObjectPolicy", "throw"); + var dict = NSMutableDictionary.new(); + expect(function () { + dict.setValueForKey(released, "key"); + }).toThrowError(ReferenceError, /released by __releaseNativeCounterpart/); + expect(dict.count).toBe(0); + }); + + it("uses NSNull for a released collection element", function () { + var released = releasedObject(); + var array = NSArray.arrayWithArray([released]); + expect(array.count).toBe(1); + var element = array.objectAtIndex(0); + expect(element === null || element instanceof NSNull).toBe(true); + }); + + it("throws a ReferenceError when a released object is a method receiver", function () { + var released = releasedObject(); + expect(function () { + released.isEqual(null); + }).toThrowError(ReferenceError, /released by __releaseNativeCounterpart/); + }); + + it("throws a ReferenceError when reading a property of a released object", function () { + var released = releasedObject(); + expect(function () { + return released.description; + }).toThrowError(ReferenceError, /released by __releaseNativeCounterpart/); + }); + + it("marks the target when released through a Proxy", function () { + var target = NSObject.alloc().init(); + var proxy = new Proxy(target, {}); + __releaseNativeCounterpart(proxy); + expect(function () { + target.isEqual(null); + }).toThrowError(ReferenceError, /released by __releaseNativeCounterpart/); + expect(function () { + proxy.isEqual(null); + }).toThrowError(ReferenceError, /released by __releaseNativeCounterpart/); + }); + + it("counts explicit releases and released accesses", function () { + var before = stats(); + var released = releasedObject(); + expect(stats().releasedExplicitly).toBe(before.releasedExplicitly + 1); + try { + released.isEqual(null); + } catch (e) { + } + expect(stats().releasedAccesses).toBe(before.releasedAccesses + 1); + }); + }); + + // A natively retained JS-extended object is resurrected by its finalizer, + // while a native object referenced only from its JS state is released in + // the same collection: the shape behind native crashes where the released + // object reached UIKit as a dictionary. Zero husks is a legal (if unlucky) + // outcome, as in GCFinalizerTests. + it("names garbage collection as the reason for an object released under a resurrected holder", function () { + var Holder = (function (_super) { + __extends(Holder, _super); + function Holder() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + return Holder; + })(NSObject); + + var N = 16; + var owner = NSMutableArray.alloc().init(); + var before = stats(); + (function create() { + for (var i = 0; i < N; i++) { + var holder = Holder.alloc().init(); + holder.state = { item: NSObject.alloc().init() }; + owner.addObject(holder); + } + })(); + (function scrub(n) { + return n > 0 ? scrub(n - 1) + n : 0; + })(300); + __collect(); + __collect(); + + expect(stats().resurrections).toBeGreaterThan(before.resurrections); + + var husks = 0; + for (var i = 0; i < N; i++) { + var holder = owner.objectAtIndex(i); + if (holder.state === undefined) { + continue; + } + try { + holder.state.item.isEqual(null); + } catch (e) { + expect(e instanceof ReferenceError).toBe(true); + expect(e.message).toMatch(/garbage collected/); + husks++; + } + } + TNSLog("wrapper lifetime spec: " + husks + "/" + N + " husks formed"); + }); + + it("reports JS state lost on a wrapper whose native object lives on", function (done) { + var previous = runtime.getConfig("wrapperLifetimeWarnings"); + runtime.setConfig("wrapperLifetimeWarnings", true); + var N = 16; + var owner = NSMutableArray.alloc().init(); + var before = stats(); + (function create() { + for (var i = 0; i < N; i++) { + var obj = NSObject.alloc().init(); + obj.jsState = i; + owner.addObject(obj); + } + })(); + (function scrub(n) { + return n > 0 ? scrub(n - 1) + n : 0; + })(300); + __collect(); + __collect(); + + afterTurns(5, function () { + var after = stats(); + runtime.setConfig("wrapperLifetimeWarnings", previous); + expect(after.stateLostCandidates).toBeGreaterThan(before.stateLostCandidates); + expect(after.stateLostConfirmed).toBeGreaterThan(before.stateLostConfirmed); + expect(owner.objectAtIndex(0).jsState).toBeUndefined(); + done(); + }); + }); + + it("does not report state lost when nothing native keeps the object", function (done) { + var previous = runtime.getConfig("wrapperLifetimeWarnings"); + runtime.setConfig("wrapperLifetimeWarnings", true); + // Settle earlier specs' garbage first, so only this spec's objects + // can move the counter. + __collect(); + __collect(); + afterTurns(5, function () { + var before = stats(); + (function create() { + for (var i = 0; i < 16; i++) { + var obj = NSObject.alloc().init(); + obj.jsState = i; + } + })(); + (function scrub(n) { + return n > 0 ? scrub(n - 1) + n : 0; + })(300); + __collect(); + __collect(); + + afterTurns(5, function () { + var after = stats(); + runtime.setConfig("wrapperLifetimeWarnings", previous); + expect(after.stateLostConfirmed).toBe(before.stateLostConfirmed); + done(); + }); + }); + }); + + it("exposes numeric counters", function () { + var current = stats(); + expect(Object.keys(current).sort()).toEqual([ + "collected", + "releasedAccesses", + "releasedExplicitly", + "resurrections", + "stateLostCandidates", + "stateLostConfirmed", + ]); + Object.keys(current).forEach(function (key) { + expect(typeof current[key]).toBe("number"); + }); + }); + + it("validates the wrapperLifetimeWarnings config key", function () { + var previous = runtime.getConfig("wrapperLifetimeWarnings"); + expect(typeof previous).toBe("boolean"); + expect(function () { + runtime.setConfig("wrapperLifetimeWarnings", "yes"); + }).toThrowError(TypeError, /'wrapperLifetimeWarnings' must be a boolean/); + runtime.setConfig("wrapperLifetimeWarnings", !previous); + expect(runtime.getConfig("wrapperLifetimeWarnings")).toBe(!previous); + runtime.setConfig("wrapperLifetimeWarnings", previous); + }); +}); diff --git a/TestRunner/app/tests/index.js b/TestRunner/app/tests/index.js index 958befa3d..d2b51fb0f 100644 --- a/TestRunner/app/tests/index.js +++ b/TestRunner/app/tests/index.js @@ -140,6 +140,7 @@ require("./GCFinalizerTests"); require("./NativeCallbackSelfTests"); require("./JSAccessorEncodingTests"); require("./JSAccessorReceiverTests"); +require("./WrapperLifetimeTests"); require("./BlockCacheRaceTests"); require("./WorkerConcurrentStartupTests"); require("./WorkerOptionsTests"); diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index 799831f88..01ce1ee8d 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -182,9 +182,12 @@ both JS-unreachable and one references the other, **both** are queued: - `n1`'s callback finds `IsGcProtected()` and re-arms. `n1` comes back holding a JS object whose native half is gone. `DisposeValue` does neuter the -husk (`delete wrapper` then `tns::DeleteValue`, which sets internal field 0 to `Undefined`), so -it is not a dangling `BaseDataWrapper*` — but consumers that read the field without checking, -`Pointer.cpp` among them, will read `Undefined` as an `External` and dereference it. +husk (`delete wrapper`, then internal field 0 is overwritten), so it is not a dangling +`BaseDataWrapper*` — but consumers that read the field without checking, `Pointer.cpp` among +them, would read it as an `External` and dereference it. ObjC object husks get a +`tns::ReleasedReason` Smi in the field (`tns::MarkReleased`: collected, released explicitly +through `__releaseNativeCounterpart`, or teardown); other wrapper types get `Undefined`. +`tns::GetValue` only reads `External`s, so both read as "no wrapper". **This is not fixable by deferring the release or by re-checking liveness after the drain.** Every queued node is rooted by `IterateFinalizerHandlesAsRoots()` and treated as a strong @@ -220,6 +223,17 @@ both struct field accessors, the two `InteropTypes.mm` argument readers, and the get/set, toString). Regression spec: *"throws instead of crashing when touching a released object through a resurrected parent"* in `GCFinalizerTests.js`. +An ObjC object husk reaching native code where an object is expected used to fall through to a +`DictionaryAdapter` standing in for it (a released `UIColor` reached UIKit as one and raised +`unrecognized selector`). The `ReleasedReason` marker now catches it on those paths, through +`tns::ReportReleasedObject()` with the same policy: an argument (`Interop::WriteValue`) becomes +`nil` or throws; a collection element (`Interop::ToObject`) becomes `NSNull`; a JS-implemented +method's return value (`ArgConverter::SetValue`) becomes `nil` (both report only, since native +code is on the stack); a method or property call on the husk (`ArgConverter::Invoke`, Proxy +receivers included) always throws. `ns:runtime`'s `getWrapperLifetimeStats()` counts +resurrections, collections, explicit releases and released-object accesses. Specs: +`WrapperLifetimeTests.js`. + Two facts worth knowing when reasoning about which objects can husk: - `Pointer`/`interop.alloc` objects never husk at runtime — `Caches::PointerInstances` diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 060b5eff9..1efc29b6b 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -103,6 +103,7 @@ defined and validated natively; the module surface is a thin frozen wrapper. | `escapeException(error)` | Returns an `Error` branded to cross the next JS-to-native boundary as a native exception rather than being reported in JS (see [error-handling.md](error-handling.md#forwarding-a-throw-to-native-interopescapeexception)). An already-branded value is returned unchanged; no argument throws `TypeError`. | | `setExternalSize(target, bytes)` | Reports `bytes` of native memory held by a native object, pointer, reference, block or function reference to the garbage collector, replacing any earlier size (`0` clears it). Throws `TypeError` for any other value, `RangeError` for a byte count outside 0–2^34. | | `getExternalSize(target)` | The size currently charged to `target`, `0` when there is none. | +| `getWrapperLifetimeStats()` | Wrapper lifetime counters for the calling isolate (see [Wrapper lifetime counters](#wrapper-lifetime-counters)). | The last three are also members of the global `interop` (see [The global `interop`](#the-global-interop)); the module and the global hold @@ -114,6 +115,7 @@ Config keys: |---|---|---|---| | `releasedObjectPolicy` | `"report"` \| `"throw"` | process-wide (main-isolate writes only; read live by every isolate) | `"report"` | | `debug` | comma-separated category list, e.g. `"esm,fetch"` | process-wide (main-isolate writes only; read live by every isolate) | the `NS_DEBUG` environment variable, or `""` | +| `wrapperLifetimeWarnings` | `true` \| `false` | process-wide (main-isolate writes only; read live by every isolate) | the app config `"wrapperLifetime": { "warnings": … }`, or on in debug builds | ```js const { setConfig, getConfig } = require("ns:runtime"); @@ -141,6 +143,27 @@ The `TypeError` messages are part of the contract: | process-wide key written from a worker | `'' is process-wide and can only be set from the main isolate` | | invalid `releasedObjectPolicy` value | `'releasedObjectPolicy' must be 'report' or 'throw'` | | non-string `debug` value | `'debug' must be a comma-separated category string (), or '' to disable tracing` | +| non-boolean `wrapperLifetimeWarnings` value | `'wrapperLifetimeWarnings' must be a boolean` | + +### Wrapper lifetime counters + +`getWrapperLifetimeStats()` returns counters for the calling isolate, kept in +every build (they only cost an increment on finalizer and error paths): + +| counter | counts | +|---|---| +| `resurrections` | finalizers that kept a wrapper alive because native code still retained its object (JS-extended classes) | +| `collected` | finalizers that released their native object | +| `releasedExplicitly` | native objects released through `__releaseNativeCounterpart` | +| `releasedAccesses` | times JS passed a released wrapper to native code, used it as a method receiver, or touched a released pointer, reference or struct | +| `stateLostCandidates` | collected wrappers carrying JS properties whose object was still retained by something else (only while `wrapperLifetimeWarnings` is on) | +| `stateLostConfirmed` | candidates whose object was still alive a runloop turn later; each class is also reported once in the log | + +A wrapper whose native object was released keeps its JS identity. Passing it +to native code follows `releasedObjectPolicy`: under `"report"` the argument +or return value becomes `nil` (`NSNull` inside a collection) and a +`releasednativeaccess` event fires; under `"throw"` an argument throws a +`ReferenceError`. Calling a method on it always throws a `ReferenceError`. Remote-module security (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) is **not** part of this surface. Those diff --git a/types/ns-runtime.d.ts b/types/ns-runtime.d.ts index 37a74c68e..b60ea136a 100644 --- a/types/ns-runtime.d.ts +++ b/types/ns-runtime.d.ts @@ -31,6 +31,35 @@ declare module "ns:runtime" { * Available in release builds too. Process-wide; main-isolate writes only. */ debug: string; + /** + * Whether the runtime logs a warning (once per class) when JS properties + * on a native object's wrapper are lost because the wrapper was garbage + * collected while native code still owned the object. + * + * Defaults to on in debug builds and off otherwise; the app config key + * `"wrapperLifetime": { "warnings": boolean }` overrides the default. + * Process-wide; main-isolate writes only. + */ + wrapperLifetimeWarnings: boolean; + } + + /** + * Wrapper lifetime counters for the calling isolate, maintained in every + * build. + */ + export interface WrapperLifetimeStats { + /** Finalizers that kept a wrapper alive because native code still retained its object. */ + resurrections: number; + /** Finalizers that released their native object. */ + collected: number; + /** Native objects released through `__releaseNativeCounterpart`. */ + releasedExplicitly: number; + /** Times JS passed a released wrapper to native code or called a method on it. */ + releasedAccesses: number; + /** Collected wrappers with JS properties whose object was still retained elsewhere. */ + stateLostCandidates: number; + /** Candidates whose object was still alive a runloop turn later (warnings enabled only). */ + stateLostConfirmed: number; } /** @@ -81,4 +110,10 @@ declare module "ns:runtime" { * runtime itself, `0` when there is none. */ export function getExternalSize(target: unknown): number; + + /** + * Wrapper lifetime counters for the calling isolate. The state-lost + * counters only advance while `wrapperLifetimeWarnings` is on. + */ + export function getWrapperLifetimeStats(): WrapperLifetimeStats; } From 9e0a551f18385ce992fec9fbb18e9b62d52dc3da Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 12 Nov 2026 16:58:46 -0300 Subject: [PATCH 2/6] 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. --- NativeScript/runtime/ObjectManager.mm | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/NativeScript/runtime/ObjectManager.mm b/NativeScript/runtime/ObjectManager.mm index cbe6bb268..2b99eec13 100644 --- a/NativeScript/runtime/ObjectManager.mm +++ b/NativeScript/runtime/ObjectManager.mm @@ -115,10 +115,12 @@ void ReconcileOwnershipBeforeGC(Isolate* isolate, GCType, GCCallbackFlags) { }; bool IsTaggedPointer(id obj) { + // Through void*: clang rejects bit tests on ObjC object pointers. + uintptr_t bits = reinterpret_cast(static_cast(obj)); #if defined(__arm64__) - return reinterpret_cast(obj) < 0; + return (bits >> 63) != 0; #else - return (reinterpret_cast(obj) & 1) != 0; + return (bits & 1) != 0; #endif } From 5d352b9edcb3c82e9d7aec70812c1ee8a6b6916a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 16 Nov 2026 22:16:40 -0300 Subject: [PATCH 3/6] 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 ]" 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. --- NativeScript/runtime/ArgConverter.mm | 13 +- NativeScript/runtime/Helpers.h | 20 ++- NativeScript/runtime/Helpers.mm | 66 +++++++++- NativeScript/runtime/Interop.mm | 5 +- NativeScript/runtime/MetadataBuilder.mm | 13 ++ NativeScript/runtime/ObjectManager.mm | 88 +++++++++---- .../app/tests/JSAccessorReceiverTests.js | 14 +- .../app/tests/NativeCallbackSelfTests.js | 7 +- TestRunner/app/tests/SuperAliasTests.js | 2 +- TestRunner/app/tests/WrapperLifetimeTests.js | 120 ++++++++++++++---- docs/knowledge/v8-resurrecting-finalizers.md | 13 +- docs/ns-builtin-modules.md | 10 +- types/ns-runtime.d.ts | 4 +- 13 files changed, 278 insertions(+), 97 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index b4ea5b366..4747022e6 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -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_; } } @@ -98,15 +98,8 @@ bool IsKVOSubclassOf(Class klass, Class base) { tns::ReleasedReason releasedReason = tns::GetReleasedReason(receiver); if (releasedReason != tns::ReleasedReason::kNone) { const char* jsNameStr = meta ? meta->jsName() : ""; - std::string operation = std::string("method '") + jsNameStr + "' receiver"; - if (tns::ObjectManager::LifetimeStats* stats = - tns::ObjectManager::GetLifetimeStats(isolate)) { - stats->releasedAccesses++; - } - std::string message = - std::string(tns::ReleasedReasonMessage(releasedReason)) + " (" + operation + ")"; - throw NativeScriptException( - isolate, Exception::ReferenceError(tns::ToV8String(isolate, message)), message); + 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. diff --git a/NativeScript/runtime/Helpers.h b/NativeScript/runtime/Helpers.h index 645fa51c4..70a686044 100644 --- a/NativeScript/runtime/Helpers.h +++ b/NativeScript/runtime/Helpers.h @@ -327,12 +327,13 @@ void SetReleasedObjectPolicy(ReleasedObjectPolicy policy); BaseDataWrapper* GetValueOrReport(v8::Isolate* isolate, const v8::Local& val, const char* operation); -// Why an ObjC object's wrapper no longer has its native object. Stored as a -// small integer in internal field 0, where an External would otherwise sit: -// GetValue only reads Externals, so every existing caller sees "no wrapper", -// and writing it allocates nothing inside the finalizer drain. +// 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 { - // Zero is never a reason: other templates' embedder fields can hold Smi 0. 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). @@ -341,10 +342,19 @@ enum class ReleasedReason : int32_t { 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& obj, ReleasedReason reason); +// Follows Proxies and `this.super` aliases to the wrapper they stand for. ReleasedReason GetReleasedReason(const v8::Local& 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`; diff --git a/NativeScript/runtime/Helpers.mm b/NativeScript/runtime/Helpers.mm index d22535ffe..9c75fe37d 100644 --- a/NativeScript/runtime/Helpers.mm +++ b/NativeScript/runtime/Helpers.mm @@ -548,6 +548,8 @@ void WriteDebugLine(tns::LogCategory category, const char* message) { 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; } @@ -618,11 +620,38 @@ bool ApplyReleasedObjectPolicy(Isolate* isolate, const Local& val, const return nullptr; } +namespace { + +constexpr int kReleasedReasonCount = static_cast(tns::ReleasedReason::kDeallocated); + +struct ReleasedMarkers { + v8::Eternal reasons[kReleasedReasonCount]; +}; + +} // namespace + +void tns::InitReleasedMarkers(Isolate* isolate) { + ReleasedMarkers* markers = Caches::StateFor(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& obj, ReleasedReason reason) { Local target = tns::UnwrapProxy(obj); - if (!target.IsEmpty() && target->IsObject() && target.As()->InternalFieldCount() > 0) { - target.As()->SetInternalField(0, - v8::Integer::New(isolate, static_cast(reason))); + // Read without the validity check: teardown marks after InvalidateIsolate. + ReleasedMarkers* markers = Caches::ExistingStateFor(isolate); + int index = static_cast(reason) - 1; + if (markers != nullptr && index >= 0 && index < kReleasedReasonCount && + !markers->reasons[index].IsEmpty() && !target.IsEmpty() && target->IsObject() && + target.As()->InternalFieldCount() > 0) { + target.As()->SetInternalField(0, markers->reasons[index].Get(isolate)); return; } // Wrappers kept in the `metadata` private have no field for the marker; they @@ -640,10 +669,37 @@ bool ApplyReleasedObjectPolicy(Isolate* isolate, const Local& val, const return ReleasedReason::kNone; } Local field = obj->GetInternalField(0).As(); - if (field.IsEmpty() || !field->IsInt32()) { + if (field.IsEmpty()) { return ReleasedReason::kNone; } - return static_cast(field.As()->Value()); + if (field->IsObject()) { + Local 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(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(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& val, ReleasedReason reason, diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index 2a2635a39..01100225b 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -829,7 +829,10 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, LocalGetConstructorName()); + info.GetReturnValue().Set(tns::ToV8String(isolate, "[released " + name + "]")); + } + return; + } + } + if (wrapper == nullptr || wrapper->Type() != WrapperType::ObjCObject) { info.GetReturnValue().Set(thiz); return; diff --git a/NativeScript/runtime/ObjectManager.mm b/NativeScript/runtime/ObjectManager.mm index 2b99eec13..77d917ca4 100644 --- a/NativeScript/runtime/ObjectManager.mm +++ b/NativeScript/runtime/ObjectManager.mm @@ -55,9 +55,9 @@ void ApplyOwnership(ObjectWeakCallbackState* state, bool nativelyOwned) { } } -// Runs in a GC prologue, where JS may not run, so only a native -retainCount -// is read. Objects without one read as unowned. -bool NativelyOwnedWithoutJS(OwnershipTracking* tracking, id obj) { +// For callers that may not enter JS (the GC prologue, the finalizer drain), so +// only a native -retainCount is read. Objects without one read as 0. +NSUInteger RetainCountWithoutJS(OwnershipTracking* tracking, id obj) { Class cls = object_getClass(obj); IMP imp; if (tracking != nullptr) { @@ -70,7 +70,11 @@ bool NativelyOwnedWithoutJS(OwnershipTracking* tracking, id obj) { } else { imp = ObjectManager::NativeRetainCountImp(cls); } - return imp != nullptr && ((NSUInteger (*)(id, SEL))imp)(obj, @selector(retainCount)) > 1; + return imp != nullptr ? ((NSUInteger (*)(id, SEL))imp)(obj, @selector(retainCount)) : 0; +} + +bool NativelyOwnedWithoutJS(OwnershipTracking* tracking, id obj) { + return RetainCountWithoutJS(tracking, obj) > 1; } bool NativelyOwnedWithoutJS(Isolate* isolate, id obj) { @@ -91,8 +95,10 @@ void ReconcileOwnershipBeforeGC(Isolate* isolate, GCType, GCCallbackFlags) { } // A finalized wrapper that carried JS properties while something other than -// the wrapper still retained its object. Confirmed a runloop turn later, so a -// co-queued owner or a pending autorelease does not produce a warning. +// the wrapper still retained its object. Confirmed on a later internal task, +// once the releases a collection on another thread queued for the runtime +// thread have run, so a co-collected owner does not produce a warning. + struct StateLostCandidate { id* weakSlot; std::string description; @@ -104,6 +110,8 @@ void ReconcileOwnershipBeforeGC(Isolate* isolate, GCType, GCCallbackFlags) { ObjectManager::LifetimeStats stats; std::vector candidates; bool confirmPosted = false; + // Times the pending confirmation stepped behind queued releases. + int confirmDeferrals = 0; std::unordered_set warnedClasses; ~WrapperLifetimeState() { @@ -117,24 +125,36 @@ void ReconcileOwnershipBeforeGC(Isolate* isolate, GCType, GCCallbackFlags) { bool IsTaggedPointer(id obj) { // Through void*: clang rejects bit tests on ObjC object pointers. uintptr_t bits = reinterpret_cast(static_cast(obj)); -#if defined(__arm64__) - return (bits >> 63) != 0; -#else +#if defined(__x86_64__) && (TARGET_OS_OSX || TARGET_OS_MACCATALYST) return (bits & 1) != 0; +#else + return (bits >> 63) != 0; #endif } +bool ReleasesPendingOnRuntimeThread(Isolate* isolate); +bool PostStateLostConfirmation(Isolate* isolate); + void ConfirmStateLost(Isolate* isolate) { auto* state = Caches::StateFor(isolate); if (state == nullptr) { return; } + // The internal lane is FIFO, so posting again runs after the queued drain. + // Bounded, in case collections elsewhere keep queueing releases. + if (ReleasesPendingOnRuntimeThread(isolate) && state->confirmDeferrals < 4 && + PostStateLostConfirmation(isolate)) { + state->confirmDeferrals++; + return; + } state->confirmPosted = false; + state->confirmDeferrals = 0; std::vector candidates; candidates.swap(state->candidates); for (StateLostCandidate& candidate : candidates) { id obj = objc_loadWeakRetained(candidate.weakSlot); if (obj != nil) { + [obj release]; state->stats.stateLostConfirmed++; if (state->warnedClasses.insert(candidate.className).second) { Log("NativeScript: JS properties (%s) set on %s were lost when its JavaScript wrapper was " @@ -144,7 +164,6 @@ void ConfirmStateLost(Isolate* isolate) { "{ \"warnings\": false }.", candidate.properties.c_str(), candidate.description.c_str()); } - [obj release]; } objc_destroyWeak(candidate.weakSlot); delete candidate.weakSlot; @@ -156,7 +175,8 @@ void NoteStateLostCandidate(Isolate* isolate, Local obj, id target) { if (IsTaggedPointer(target)) { return; } - NSUInteger count = [target retainCount]; + NSUInteger count = + RetainCountWithoutJS(Caches::ExistingStateFor(isolate), target); if (count <= 1 || count >= (NSUIntegerMax >> 1)) { return; } @@ -165,6 +185,17 @@ void NoteStateLostCandidate(Isolate* isolate, Local obj, id target) { !reinterpret_cast(objc_msgSend)(target, allowsWeak)) { return; } + // The V8 calls below can run a nested collection whose JS releases target, + // so it is not touched after them. + const char* className = object_getClassName(target); + char description[256]; + snprintf(description, sizeof(description), "<%s: %p>", className, (void*)target); + id* slot = new id(nil); + objc_initWeak(slot, target); + auto discardSlot = [slot]() { + objc_destroyWeak(slot); + delete slot; + }; HandleScope handleScope(isolate); TryCatch tryCatch(isolate); @@ -173,11 +204,13 @@ void NoteStateLostCandidate(Isolate* isolate, Local obj, id target) { if (context.IsEmpty() || !obj->GetOwnPropertyNames(context, PropertyFilter::SKIP_SYMBOLS).ToLocal(&names) || names->Length() == 0) { + discardSlot(); return; } auto* state = Caches::StateFor(isolate); if (state == nullptr) { + discardSlot(); return; } state->stats.stateLostCandidates++; @@ -198,20 +231,10 @@ void NoteStateLostCandidate(Isolate* isolate, Local obj, id target) { properties += ", ..."; } - const char* className = object_getClassName(target); - char description[256]; - snprintf(description, sizeof(description), "<%s: %p>", className, (void*)target); - - id* slot = new id(nil); - objc_initWeak(slot, target); state->candidates.push_back({slot, description, className, properties}); if (!state->confirmPosted) { - Runtime* runtime = Runtime::GetRuntime(isolate); - std::shared_ptr loop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; - if (loop != nullptr && loop->PostInternal([isolate]() { ConfirmStateLost(isolate); })) { - state->confirmPosted = true; - } + state->confirmPosted = PostStateLostConfirmation(isolate); } } @@ -315,6 +338,17 @@ void PostDrain(Isolate* isolate, DeferredReleases* pending) { }); } +bool ReleasesPendingOnRuntimeThread(Isolate* isolate) { + DeferredReleases* pending = Caches::ExistingStateFor(isolate); + return pending != nullptr && pending->drainPosted; +} + +bool PostStateLostConfirmation(Isolate* isolate) { + Runtime* runtime = Runtime::GetRuntime(isolate); + std::shared_ptr loop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; + return loop != nullptr && loop->PostInternal([isolate]() { ConfirmStateLost(isolate); }); +} + void ReleaseOnRuntimeThread(Isolate* isolate, id obj, bool bornOnRuntimeThread) { DeferredReleases* pending = DeferralQueue(isolate, bornOnRuntimeThread); if (pending == nullptr) { @@ -344,6 +378,11 @@ void BlockReleaseOnRuntimeThread(Isolate* isolate, const void* block, bool bornO ReconcileOwnershipBeforeGC, static_cast(kGCTypeMarkSweepCompact | kGCTypeIncrementalMarking)); Caches::StateFor(isolate); + // Created here so a collection on another thread never allocates them, and + // the warnings flag is read from the app config before any finalizer asks. + tns::InitReleasedMarkers(isolate); + Caches::StateFor(isolate); + tns::WrapperLifetimeWarningsEnabled(); } std::shared_ptr> ObjectManager::Register(Local context, @@ -575,6 +614,9 @@ void DisposeHandle(v8::Isolate* isolate, ObjCDataWrapper* objcWrapper = static_cast(wrapper); if (objcWrapper->OwnershipState() != nullptr && NativelyOwnedWithoutJS(isolate, objcWrapper->Data())) { + if (LifetimeStats* stats = GetLifetimeStats(isolate)) { + stats->resurrections++; + } return false; } } @@ -763,7 +805,7 @@ void DisposeHandle(v8::Isolate* isolate, ObjCDataWrapper* objcWrapper = static_cast(wrapper); if (objcWrapper->IsBorrowed()) { if (tns::GetValue(isolate, value) == wrapper) { - tns::SetValue(isolate, value.As(), nullptr); + tns::MarkReleased(isolate, value.As(), tns::ReleasedReason::kExplicit); delete wrapper; } return; diff --git a/TestRunner/app/tests/JSAccessorReceiverTests.js b/TestRunner/app/tests/JSAccessorReceiverTests.js index db6022cd6..c5715325c 100644 --- a/TestRunner/app/tests/JSAccessorReceiverTests.js +++ b/TestRunner/app/tests/JSAccessorReceiverTests.js @@ -255,11 +255,8 @@ describe("JS accessor receivers", function () { } catch (e) { error = e; } - if (error !== null) { - expect(error.message).toContain("disposed native object"); - } else { - expect(value).toBeUndefined(); - } + expect(value).toBeUndefined(); + expect(String(error && error.message)).toMatch(/native object was deallocated/); saved = null; expect(deallocs()).toBe(1); done(); @@ -343,11 +340,8 @@ describe("JS accessor receivers", function () { } catch (e) { error = e; } - if (error !== null) { - expect(error.message).toContain("disposed native object"); - } else { - expect(value).toBeUndefined(); - } + expect(value).toBeUndefined(); + expect(String(error && error.message)).toMatch(/native object was deallocated/); saved = null; done(); }); diff --git a/TestRunner/app/tests/NativeCallbackSelfTests.js b/TestRunner/app/tests/NativeCallbackSelfTests.js index 923399e9a..ee5dfc139 100644 --- a/TestRunner/app/tests/NativeCallbackSelfTests.js +++ b/TestRunner/app/tests/NativeCallbackSelfTests.js @@ -436,11 +436,8 @@ describe("Native callback self wrappers", function () { } catch (e) { error = e; } - if (error !== null) { - expect(error.message).toContain("disposed native object"); - } else { - expect(value).toBeUndefined(); - } + expect(value).toBeUndefined(); + expect(String(error && error.message)).toMatch(/native object was deallocated/); saved = null; done(); }); diff --git a/TestRunner/app/tests/SuperAliasTests.js b/TestRunner/app/tests/SuperAliasTests.js index 2c072e8fe..6fa59ae2d 100644 --- a/TestRunner/app/tests/SuperAliasTests.js +++ b/TestRunner/app/tests/SuperAliasTests.js @@ -33,7 +33,7 @@ describe("this.super aliases", function () { } catch (e) { error = e; } - expect(error === null ? "" : String(error.message)).toMatch(/disposed native object|native object was released/); + expect(error === null ? "" : String(error.message)).toMatch(/native object was (released|deallocated)/); } function superGetter(cls) { diff --git a/TestRunner/app/tests/WrapperLifetimeTests.js b/TestRunner/app/tests/WrapperLifetimeTests.js index 0ebeb62f5..f49627a52 100644 --- a/TestRunner/app/tests/WrapperLifetimeTests.js +++ b/TestRunner/app/tests/WrapperLifetimeTests.js @@ -11,16 +11,11 @@ describe("Wrapper lifetime", function () { return runtime.getWrapperLifetimeStats(); } - // The state-lost confirmation runs on the event loop's internal lane, not - // necessarily before the next timer. - function afterTurns(turns, callback) { - setTimeout(function () { - if (turns > 1) { - afterTurns(turns - 1, callback); - } else { - callback(); - } - }, 10); + // The state-lost confirmation runs on the event loop's internal lane, after + // any releases queued for the runtime thread; not necessarily before the + // next timer. + function afterConfirmation(callback) { + setTimeout(callback, 100); } afterEach(function () { @@ -49,14 +44,46 @@ describe("Wrapper lifetime", function () { }); }); - it("throws a ReferenceError for a released argument under the throw policy", function () { + it("throws a ReferenceError for a released argument under the throw policy, before the call", function () { var released = releasedObject(); runtime.setConfig("releasedObjectPolicy", "throw"); var dict = NSMutableDictionary.new(); + dict.setValueForKey("kept", "key"); expect(function () { dict.setValueForKey(released, "key"); }).toThrowError(ReferenceError, /released by __releaseNativeCounterpart/); - expect(dict.count).toBe(0); + expect(dict.valueForKey("key")).toBe("kept"); + + var array = NSMutableArray.new(); + expect(function () { + array.addObject(released); + }).toThrowError(ReferenceError, /released by __releaseNativeCounterpart \(native argument\)/); + expect(array.count).toBe(0); + }); + + it("does not read another template's internal field as a released marker", function () { + var before = stats(); + var url = new URL("https://example.com/path"); + var error = null; + try { + NSObject.prototype.isEqual.call(url, null); + } catch (e) { + error = e; + } + expect(error).not.toBeNull(); + expect(String(error && error.message)).not.toMatch(/native object was released/); + expect(stats().releasedAccesses).toBe(before.releasedAccesses); + expect(url.pathname).toBe("/path"); + }); + + it("gives a released object's toString a string under the report policy and throws under throw", function () { + var released = releasedObject(); + expect(released.toString()).toBe("[released NSObject]"); + expect(String(new Proxy(released, {}))).toBe("[released NSObject]"); + runtime.setConfig("releasedObjectPolicy", "throw"); + expect(function () { + released.toString(); + }).toThrowError(ReferenceError, /released by __releaseNativeCounterpart \(toString receiver\)/); }); it("uses NSNull for a released collection element", function () { @@ -173,44 +200,83 @@ describe("Wrapper lifetime", function () { __collect(); __collect(); - afterTurns(5, function () { + afterConfirmation(function () { var after = stats(); runtime.setConfig("wrapperLifetimeWarnings", previous); expect(after.stateLostCandidates).toBeGreaterThan(before.stateLostCandidates); expect(after.stateLostConfirmed).toBeGreaterThan(before.stateLostConfirmed); - expect(owner.objectAtIndex(0).jsState).toBeUndefined(); + var lost = 0; + for (var i = 0; i < N; i++) { + if (owner.objectAtIndex(i).jsState === undefined) { + lost++; + } + } + expect(lost).toBeGreaterThan(0); done(); }); }); - it("does not report state lost when nothing native keeps the object", function (done) { + // Runs `create` after earlier specs' garbage has settled, collects, and + // hands the counters from before and after the confirmation to `check`. + function measureStateLost(create, check, done) { var previous = runtime.getConfig("wrapperLifetimeWarnings"); runtime.setConfig("wrapperLifetimeWarnings", true); - // Settle earlier specs' garbage first, so only this spec's objects - // can move the counter. __collect(); __collect(); - afterTurns(5, function () { + afterConfirmation(function () { var before = stats(); - (function create() { - for (var i = 0; i < 16; i++) { - var obj = NSObject.alloc().init(); - obj.jsState = i; - } - })(); + create(); (function scrub(n) { return n > 0 ? scrub(n - 1) + n : 0; })(300); __collect(); __collect(); - - afterTurns(5, function () { + afterConfirmation(function () { var after = stats(); runtime.setConfig("wrapperLifetimeWarnings", previous); - expect(after.stateLostConfirmed).toBe(before.stateLostConfirmed); + check(before, after); done(); }); }); + } + + it("does not report state lost when nothing native keeps the object", function (done) { + measureStateLost(function () { + for (var i = 0; i < 16; i++) { + var obj = NSObject.alloc().init(); + obj.jsState = i; + } + }, function (before, after) { + expect(after.stateLostConfirmed).toBe(before.stateLostConfirmed); + }, done); + }); + + it("does not report state lost when the other owner is collected too", function (done) { + measureStateLost(function () { + var owner = NSMutableArray.alloc().init(); + for (var i = 0; i < 16; i++) { + var obj = NSObject.alloc().init(); + obj.jsState = i; + owner.addObject(obj); + } + }, function (before, after) { + console.log("wrapper lifetime spec: " + (after.stateLostCandidates - before.stateLostCandidates) + + " candidates with a co-collected owner"); + expect(after.stateLostConfirmed).toBe(before.stateLostConfirmed); + }, done); + }); + + it("does not report state lost for an object only the autorelease pool still holds", function (done) { + measureStateLost(function () { + for (var i = 0; i < 16; i++) { + var obj = NSMutableArray.array(); + obj.jsState = i; + } + }, function (before, after) { + console.log("wrapper lifetime spec: " + (after.stateLostCandidates - before.stateLostCandidates) + + " candidates held by the autorelease pool"); + expect(after.stateLostConfirmed).toBe(before.stateLostConfirmed); + }, done); }); it("exposes numeric counters", function () { diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index 01ce1ee8d..869cdd201 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -184,10 +184,13 @@ both JS-unreachable and one references the other, **both** are queued: `n1` comes back holding a JS object whose native half is gone. `DisposeValue` does neuter the husk (`delete wrapper`, then internal field 0 is overwritten), so it is not a dangling `BaseDataWrapper*` — but consumers that read the field without checking, `Pointer.cpp` among -them, would read it as an `External` and dereference it. ObjC object husks get a -`tns::ReleasedReason` Smi in the field (`tns::MarkReleased`: collected, released explicitly -through `__releaseNativeCounterpart`, or teardown); other wrapper types get `Undefined`. -`tns::GetValue` only reads `External`s, so both read as "no wrapper". +them, would read it as an `External` and dereference it. ObjC object husks get a per-isolate +`tns::ReleasedReason` Symbol in the field (`tns::MarkReleased`: collected, released explicitly +through `__releaseNativeCounterpart`, teardown, or a receiver lent to JS from `-dealloc`); +other wrapper types get `Undefined`. `tns::GetValue` only reads `External`s, so both read as +"no wrapper". The reason is matched by identity, not as a number: URL, URLSearchParams, +URLPattern and MessagePort keep a raw aligned pointer in field 0, which reads back as a Smi +in builds without pointer compression. **This is not fixable by deferring the release or by re-checking liveness after the drain.** Every queued node is rooted by `IterateFinalizerHandlesAsRoots()` and treated as a strong @@ -227,7 +230,7 @@ An ObjC object husk reaching native code where an object is expected used to fal `DictionaryAdapter` standing in for it (a released `UIColor` reached UIKit as one and raised `unrecognized selector`). The `ReleasedReason` marker now catches it on those paths, through `tns::ReportReleasedObject()` with the same policy: an argument (`Interop::WriteValue`) becomes -`nil` or throws; a collection element (`Interop::ToObject`) becomes `NSNull`; a JS-implemented +`nil` or throws before the call (`tns::ThrowReleasedObject`); a collection element (`Interop::ToObject`) becomes `NSNull`; a JS-implemented method's return value (`ArgConverter::SetValue`) becomes `nil` (both report only, since native code is on the stack); a method or property call on the husk (`ArgConverter::Invoke`, Proxy receivers included) always throws. `ns:runtime`'s `getWrapperLifetimeStats()` counts diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 1efc29b6b..2189ac18e 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -105,7 +105,7 @@ defined and validated natively; the module surface is a thin frozen wrapper. | `getExternalSize(target)` | The size currently charged to `target`, `0` when there is none. | | `getWrapperLifetimeStats()` | Wrapper lifetime counters for the calling isolate (see [Wrapper lifetime counters](#wrapper-lifetime-counters)). | -The last three are also members of the global `interop` (see +`escapeException`, `setExternalSize` and `getExternalSize` are also members of the global `interop` (see [The global `interop`](#the-global-interop)); the module and the global hold the same function objects. @@ -157,13 +157,17 @@ every build (they only cost an increment on finalizer and error paths): | `releasedExplicitly` | native objects released through `__releaseNativeCounterpart` | | `releasedAccesses` | times JS passed a released wrapper to native code, used it as a method receiver, or touched a released pointer, reference or struct | | `stateLostCandidates` | collected wrappers carrying JS properties whose object was still retained by something else (only while `wrapperLifetimeWarnings` is on) | -| `stateLostConfirmed` | candidates whose object was still alive a runloop turn later; each class is also reported once in the log | +| `stateLostConfirmed` | candidates whose object was still alive a runloop turn later, once releases queued for the runtime thread ran; each class is also reported once in the log | A wrapper whose native object was released keeps its JS identity. Passing it to native code follows `releasedObjectPolicy`: under `"report"` the argument or return value becomes `nil` (`NSNull` inside a collection) and a `releasednativeaccess` event fires; under `"throw"` an argument throws a -`ReferenceError`. Calling a method on it always throws a `ReferenceError`. +`ReferenceError`. Calling a method on it always throws a `ReferenceError`; +`toString()` returns `"[released ]"` under `"report"` and throws under +`"throw"`. An `NSNull` element still breaks native code that expects a typed +value there (an attributes dictionary holding a released `UIColor`, say); the +event names the element so the cause can be found. Remote-module security (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) is **not** part of this surface. Those diff --git a/types/ns-runtime.d.ts b/types/ns-runtime.d.ts index b60ea136a..8d0ee8890 100644 --- a/types/ns-runtime.d.ts +++ b/types/ns-runtime.d.ts @@ -54,11 +54,11 @@ declare module "ns:runtime" { collected: number; /** Native objects released through `__releaseNativeCounterpart`. */ releasedExplicitly: number; - /** Times JS passed a released wrapper to native code or called a method on it. */ + /** Times JS passed a released wrapper to native code, called a method on it, or touched a released pointer, reference or struct. */ releasedAccesses: number; /** Collected wrappers with JS properties whose object was still retained elsewhere. */ stateLostCandidates: number; - /** Candidates whose object was still alive a runloop turn later (warnings enabled only). */ + /** Candidates whose object was still alive a runloop turn later, once queued releases ran (warnings enabled only). */ stateLostConfirmed: number; } From 5cbbc48fbe38f3dced01894bcf725ec9daad5c52 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 16 Nov 2026 22:41:24 -0300 Subject: [PATCH 4/6] 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. --- NativeScript/runtime/ArgConverter.mm | 4 ++-- NativeScript/runtime/Interop.mm | 20 +++++++++++++++++--- TestFixtures/Marshalling/TNSAllocLog.h | 2 ++ TestFixtures/Marshalling/TNSAllocLog.m | 4 ++++ TestRunner/app/tests/WrapperLifetimeTests.js | 11 +++++++++++ docs/ns-builtin-modules.md | 14 +++++++++++--- 6 files changed, 47 insertions(+), 8 deletions(-) diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 4747022e6..56bfc32b1 100644 --- a/NativeScript/runtime/ArgConverter.mm +++ b/NativeScript/runtime/ArgConverter.mm @@ -175,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]; } diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index 01100225b..88b5940fe 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -231,7 +231,13 @@ static int ConsumedArgumentIndex(SEL selector) { Interop::SetValue(call.ArgumentBuffer(0), target); Interop::SetValue(call.ArgumentBuffer(1), selector); - Interop::SetFFIParams(context, typeEncoding, &call, argsCount, initialParameterIndex, args); + try { + Interop::SetFFIParams(context, typeEncoding, &call, argsCount, initialParameterIndex, args); + } catch (...) { + // `target` was allocated for this initializer, which would have consumed it. + [target release]; + throw; + } ffi_call(parametrizedCall->Cif, FFI_FN(functionPointer), call.ResultBuffer(), call.ArgsArray()); @@ -1919,8 +1925,16 @@ throw NativeScriptException( methodCall.typeEncoding_->type == BinaryTypeEncodingType::InstanceTypeEncoding; bool marshalToPrimitive = methodCall.isPrimitiveFunction_ || !isInstanceReturnType; - Interop::SetFFIParams(methodCall.context_, methodCall.typeEncoding_, &call, argsCount, - initialParameterIndex, methodCall.args_); + try { + Interop::SetFFIParams(methodCall.context_, methodCall.typeEncoding_, &call, argsCount, + initialParameterIndex, methodCall.args_); + } catch (...) { + // The initializer that would have consumed it never runs. + if (methodCall.receiverAllocatedForCall_) { + [methodCall.target_ release]; + } + throw; + } if (initialParameterIndex > 1) { int consumed = ConsumedObjectArgumentIndex(methodCall.selector_, methodCall.typeEncoding_, diff --git a/TestFixtures/Marshalling/TNSAllocLog.h b/TestFixtures/Marshalling/TNSAllocLog.h index a5767a50d..0fb6c3505 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.h +++ b/TestFixtures/Marshalling/TNSAllocLog.h @@ -8,6 +8,8 @@ //- (void)release; - (instancetype)init; +// Ignores `object`. +- (instancetype)initWithObject:(id)object; - (void)dealloc; @end diff --git a/TestFixtures/Marshalling/TNSAllocLog.m b/TestFixtures/Marshalling/TNSAllocLog.m index 5f9623197..3d751e6ca 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -17,6 +17,10 @@ - (instancetype)init { return [super init]; } +- (instancetype)initWithObject:(id)object { + return [self init]; +} + - (void)dealloc { TNSLog(@"TNSAllocLog dealloc"); } diff --git a/TestRunner/app/tests/WrapperLifetimeTests.js b/TestRunner/app/tests/WrapperLifetimeTests.js index f49627a52..1c5058c35 100644 --- a/TestRunner/app/tests/WrapperLifetimeTests.js +++ b/TestRunner/app/tests/WrapperLifetimeTests.js @@ -61,6 +61,17 @@ describe("Wrapper lifetime", function () { expect(array.count).toBe(0); }); + it("releases the receiver allocated for an initializer whose argument throws", function () { + var released = releasedObject(); + runtime.setConfig("releasedObjectPolicy", "throw"); + TNSClearOutput(); + expect(function () { + TNSAllocLog.alloc().initWithObject(released); + }).toThrowError(ReferenceError, /native argument/); + expect((TNSGetOutput().match(/TNSAllocLog dealloc/g) || []).length).toBe(1); + TNSClearOutput(); + }); + it("does not read another template's internal field as a released marker", function () { var before = stats(); var url = new URL("https://example.com/path"); diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 2189ac18e..7a4d38a7e 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -181,9 +181,10 @@ Controls what happens when JS touches a wrapper whose native counterpart has already been released (a state a resurrected object can expose — see the iOS runtime's `docs/knowledge/v8-resurrecting-finalizers.md`): -- `"report"` (default): the operation no-ops — reads produce `undefined`, - writes are skipped, `toString` yields a ``-style - placeholder — and a cancelable `releasednativeaccess` event fires on +- `"report"` (default): the operation no-ops — pointer, reference and struct + reads produce `undefined`, writes are skipped, `toString` yields a + ``-style placeholder — and a cancelable + `releasednativeaccess` event fires on `globalThis` (`event.error` carries a `ReferenceError` whose stack names the touch site; `event.operation` names the API surface, e.g. `"struct field assignment"`). Reports are deduplicated per released object. @@ -192,6 +193,13 @@ runtime's `docs/knowledge/v8-resurrecting-finalizers.md`): - `"throw"`: the touch throws a catchable `ReferenceError` synchronously, and no event fires. +Under either policy, calling a method on a released Objective-C object or +reading one of its native properties throws a `ReferenceError`: there is no +value to stand in for the result. Native code that receives a released object +with no JS caller to throw to (the return value of a JS-implemented method, +an element of a collection native code is reading) gets `nil` or `NSNull` and +the event fires, under `"throw"` too. + ```js const { setConfig } = require("ns:runtime"); From b3d6ccda9d4444b21f564370ba3c944612124b0e Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 16 Nov 2026 23:00:03 -0300 Subject: [PATCH 5/6] 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. --- NativeScript/runtime/Interop.mm | 50 +++++++++++-------- TestFixtures/Marshalling/TNSAllocLog.h | 2 + TestFixtures/Marshalling/TNSAllocLog.m | 5 ++ .../Marshalling/TNSFunctionPointers.h | 2 + .../Marshalling/TNSFunctionPointers.m | 7 +++ TestFixtures/exported-symbols.txt | 1 + TestRunner/app/tests/WrapperLifetimeTests.js | 13 +++++ 7 files changed, 59 insertions(+), 21 deletions(-) diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index 88b5940fe..ea51039cd 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -1281,31 +1281,35 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Local& info) { - Local ext = info.Data().As(); - BlockWrapper* wrapper = - static_cast(ext->Value(v8::kExternalPointerTypeTagDefault)); + Isolate* isolate = info.GetIsolate(); + try { + Local ext = info.Data().As(); + BlockWrapper* wrapper = + static_cast(ext->Value(v8::kExternalPointerTypeTagDefault)); - JSBlock* block = static_cast(wrapper->Block()); + JSBlock* block = static_cast(wrapper->Block()); - const TypeEncoding* typeEncoding = wrapper->Encodings(); - int argsCount = typeEncoding->details.block.signature.count; - const TypeEncoding* enc = typeEncoding->details.block.signature.first(); + const TypeEncoding* typeEncoding = wrapper->Encodings(); + int argsCount = typeEncoding->details.block.signature.count; + const TypeEncoding* enc = typeEncoding->details.block.signature.first(); - ParametrizedCall* parametrizedCall = ParametrizedCall::Get(enc, 1, argsCount); - FFICall call(parametrizedCall); + ParametrizedCall* parametrizedCall = ParametrizedCall::Get(enc, 1, argsCount); + FFICall call(parametrizedCall); - V8FunctionCallbackArgs args(info); - Isolate* isolate = info.GetIsolate(); - Local context = isolate->GetCurrentContext(); - Interop::SetValue(call.ArgumentBuffer(0), block); - Interop::SetFFIParams(context, enc, &call, argsCount, 1, args); + V8FunctionCallbackArgs args(info); + Local context = isolate->GetCurrentContext(); + Interop::SetValue(call.ArgumentBuffer(0), block); + Interop::SetFFIParams(context, enc, &call, argsCount, 1, args); - ffi_call(parametrizedCall->Cif, FFI_FN(block->invoke), call.ResultBuffer(), - call.ArgsArray()); + ffi_call(parametrizedCall->Cif, FFI_FN(block->invoke), call.ResultBuffer(), + call.ArgsArray()); - Local result = Interop::GetResult(context, enc, &call, true); + Local result = Interop::GetResult(context, enc, &call, true); - info.GetReturnValue().Set(result); + info.GetReturnValue().Set(result); + } catch (NativeScriptException& ex) { + ex.ReThrowToV8(isolate); + } }, ext) .ToLocal(&callback); @@ -1345,10 +1349,14 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, LocalParametersEncoding(); Local context = isolate->GetCurrentContext(); - CMethodCall methodCall(context, functionPointer, typeEncoding, args, false, false); - Local result = Interop::CallFunction(methodCall); + try { + CMethodCall methodCall(context, functionPointer, typeEncoding, args, false, false); + Local result = Interop::CallFunction(methodCall); - info.GetReturnValue().Set(result); + info.GetReturnValue().Set(result); + } catch (NativeScriptException& ex) { + ex.ReThrowToV8(isolate); + } }, ext) .ToLocal(&func); diff --git a/TestFixtures/Marshalling/TNSAllocLog.h b/TestFixtures/Marshalling/TNSAllocLog.h index 0fb6c3505..028be8046 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.h +++ b/TestFixtures/Marshalling/TNSAllocLog.h @@ -10,6 +10,8 @@ - (instancetype)init; // Ignores `object`. - (instancetype)initWithObject:(id)object; +// Answers a block that ignores its argument. ++ (void (^)(id))objectSink; - (void)dealloc; @end diff --git a/TestFixtures/Marshalling/TNSAllocLog.m b/TestFixtures/Marshalling/TNSAllocLog.m index 3d751e6ca..15c07cd2d 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -21,6 +21,11 @@ - (instancetype)initWithObject:(id)object { return [self init]; } ++ (void (^)(id))objectSink { + return ^(id object) { + }; +} + - (void)dealloc { TNSLog(@"TNSAllocLog dealloc"); } diff --git a/TestFixtures/Marshalling/TNSFunctionPointers.h b/TestFixtures/Marshalling/TNSFunctionPointers.h index 708ee3cd3..fb693212e 100644 --- a/TestFixtures/Marshalling/TNSFunctionPointers.h +++ b/TestFixtures/Marshalling/TNSFunctionPointers.h @@ -1,6 +1,8 @@ #include "TNSRecords.h" long long (*functionWhichReturnsSimpleFunctionPointer())(long long); +// Answers a function that ignores its argument. +void (*functionWhichReturnsObjectFunctionPointer())(id); void functionWithSimpleFunctionPointer(int (*f)(int)); void functionWithComplexFunctionPointer(TNSNestedStruct (*f)(char p1, short p2, int p3, long p4, long long p5, unsigned char p6, unsigned short p7, unsigned int p8, unsigned long p9, unsigned long long p10, float p11, double p12, SEL p13, Class p14, Protocol* p15, NSObject* p16, TNSNestedStruct p17)); diff --git a/TestFixtures/Marshalling/TNSFunctionPointers.m b/TestFixtures/Marshalling/TNSFunctionPointers.m index 9b4149b21..4b489a635 100644 --- a/TestFixtures/Marshalling/TNSFunctionPointers.m +++ b/TestFixtures/Marshalling/TNSFunctionPointers.m @@ -8,6 +8,13 @@ long long (*functionWhichReturnsSimpleFunctionPointer())(long long) { return _simpleFunctionImplementation; } +static void _objectFunctionImplementation(id object) { +} + +void (*functionWhichReturnsObjectFunctionPointer())(id) { + return _objectFunctionImplementation; +} + void functionWithSimpleFunctionPointer(int (*f)(int)) { int result = f(2); TNSLog([NSString stringWithFormat:@"%d", result]); diff --git a/TestFixtures/exported-symbols.txt b/TestFixtures/exported-symbols.txt index 63d355dfd..8773d3a5d 100644 --- a/TestFixtures/exported-symbols.txt +++ b/TestFixtures/exported-symbols.txt @@ -8,6 +8,7 @@ _functionReturnsNSRetained _functionReturnsUnmanaged _functionThrowsException _functionWhichReturnsSimpleFunctionPointer +_functionWhichReturnsObjectFunctionPointer _functionWith_BoolPtr _functionWith_VoidPtr _functionWithBool diff --git a/TestRunner/app/tests/WrapperLifetimeTests.js b/TestRunner/app/tests/WrapperLifetimeTests.js index 1c5058c35..5f02b45e0 100644 --- a/TestRunner/app/tests/WrapperLifetimeTests.js +++ b/TestRunner/app/tests/WrapperLifetimeTests.js @@ -72,6 +72,19 @@ describe("Wrapper lifetime", function () { TNSClearOutput(); }); + it("throws a catchable ReferenceError for a released argument to a native block or function pointer", function () { + var released = releasedObject(); + runtime.setConfig("releasedObjectPolicy", "throw"); + var sink = TNSAllocLog.objectSink(); + expect(function () { + sink(released); + }).toThrowError(ReferenceError, /native argument/); + var fn = functionWhichReturnsObjectFunctionPointer(); + expect(function () { + fn(released); + }).toThrowError(ReferenceError, /native argument/); + }); + it("does not read another template's internal field as a released marker", function () { var before = stats(); var url = new URL("https://example.com/path"); From e7a9671625b44f3afcd78c8aecf2b9d2abddac5f Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 03:51:35 -0300 Subject: [PATCH 6/6] style(runtime): clang-format --- NativeScript/runtime/Helpers.mm | 3 ++- NativeScript/runtime/NsBuiltinModules.cpp | 10 ++++++---- NativeScript/runtime/ObjectManager.mm | 15 +++++++-------- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/NativeScript/runtime/Helpers.mm b/NativeScript/runtime/Helpers.mm index 9c75fe37d..76ce2be28 100644 --- a/NativeScript/runtime/Helpers.mm +++ b/NativeScript/runtime/Helpers.mm @@ -704,7 +704,8 @@ throw NativeScriptException( bool tns::ReportReleasedObject(Isolate* isolate, const Local& val, ReleasedReason reason, const char* operation, bool canThrow) { - return ApplyReleasedObjectPolicy(isolate, val, ReleasedReasonMessage(reason), operation, canThrow); + return ApplyReleasedObjectPolicy(isolate, val, ReleasedReasonMessage(reason), operation, + canThrow); } bool tns::WrapperLifetimeWarningsEnabled() { diff --git a/NativeScript/runtime/NsBuiltinModules.cpp b/NativeScript/runtime/NsBuiltinModules.cpp index 200afb3c6..d35f4cf7d 100644 --- a/NativeScript/runtime/NsBuiltinModules.cpp +++ b/NativeScript/runtime/NsBuiltinModules.cpp @@ -8,8 +8,8 @@ #include "Helpers.h" #include "Interop.h" #include "Messaging.h" -#include "ObjectManager.h" #include "ModuleInternalCallbacks.h" +#include "ObjectManager.h" #include "Runtime.h" #include "StructuredSerialization.h" #include "TextEncoding.h" @@ -212,7 +212,8 @@ void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); Local context = isolate->GetCurrentContext(); Local result = Object::New(isolate); - tns::ObjectManager::LifetimeStats* stats = tns::ObjectManager::GetLifetimeStats(isolate); + tns::ObjectManager::LifetimeStats* stats = + tns::ObjectManager::GetLifetimeStats(isolate); if (stats == nullptr) { info.GetReturnValue().Set(result); return; @@ -271,8 +272,9 @@ MaybeLocal NsRuntimeBinding(Local context) { .FromMaybe(false) || !binding->Set(context, tns::ToV8String(isolate, "getConfig"), getConfig) .FromMaybe(false) || - !binding->Set(context, tns::ToV8String(isolate, "getWrapperLifetimeStats"), - getWrapperLifetimeStats) + !binding + ->Set(context, tns::ToV8String(isolate, "getWrapperLifetimeStats"), + getWrapperLifetimeStats) .FromMaybe(false)) { return MaybeLocal(); } diff --git a/NativeScript/runtime/ObjectManager.mm b/NativeScript/runtime/ObjectManager.mm index 77d917ca4..a00bfa20a 100644 --- a/NativeScript/runtime/ObjectManager.mm +++ b/NativeScript/runtime/ObjectManager.mm @@ -1,8 +1,12 @@ #include "ObjectManager.h" #include #include +#include +#include #include +#include #include +#include #include #include "Caches.h" #include "ClassBuilder.h" @@ -12,11 +16,6 @@ #include "FFICall.h" #include "Helpers.h" #include "Runtime.h" -#include -#include -#include -#include -#include // Exported by libobjc; not declared in a public header for MRC code. extern "C" id objc_initWeak(id* location, id value); @@ -754,9 +753,9 @@ void DisposeHandle(v8::Isolate* isolate, if (tns::GetValue(isolate, obj) == wrapper) { delete wrapper; if (type == WrapperType::ObjCObject) { - tns::MarkReleased(isolate, obj, - isFinalDisposal ? tns::ReleasedReason::kTeardown - : tns::ReleasedReason::kCollected); + tns::MarkReleased( + isolate, obj, + isFinalDisposal ? tns::ReleasedReason::kTeardown : tns::ReleasedReason::kCollected); } else { tns::DeleteValue(isolate, obj); }