diff --git a/NativeScript/runtime/ArgConverter.mm b/NativeScript/runtime/ArgConverter.mm index 49053bf6a..56bfc32b1 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_; } } @@ -95,6 +95,12 @@ bool IsKVOSubclassOf(Class klass, Class base) { BaseDataWrapper* wrapper = tns::GetValue(isolate, receiver); if (wrapper == nullptr) { + tns::ReleasedReason releasedReason = tns::GetReleasedReason(receiver); + if (releasedReason != tns::ReleasedReason::kNone) { + const char* jsNameStr = meta ? meta->jsName() : ""; + tns::ThrowReleasedObject(isolate, releasedReason, + std::string("method '") + jsNameStr + "' receiver"); + } // During fast view churn like HMR in development, JS objects can outlive their // native wrappers briefly. In Debug, throw a catchable JS error instead of crashing. // In Release, assert so crash reporting can capture unexpected cases. @@ -169,8 +175,8 @@ bool IsKVOSubclassOf(Class klass, Class base) { } if (allocKlass != nil) { - // The +1 belongs to the initializer invoked below, which consumes it. Nothing - // between here and that call may throw, or the reference is lost. + // The +1 belongs to the initializer invoked below, which consumes it. If + // converting the arguments throws, CallFunction releases it instead. target = [allocKlass alloc]; } @@ -644,6 +650,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..70a686044 100644 --- a/NativeScript/runtime/Helpers.h +++ b/NativeScript/runtime/Helpers.h @@ -326,6 +326,50 @@ 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. Internal field +// 0, where the External would otherwise sit, holds a per-isolate Symbol for the +// reason: GetValue only reads Externals, so every existing caller sees "no +// wrapper". Reasons are recognised by identity, never by value, because other +// templates keep raw aligned pointers in field 0, which read back as arbitrary +// Smis. +enum class ReleasedReason : int32_t { + kNone = 0, + // The wrapper's finalizer released it while JS could still reach the + // wrapper (only possible through a graph a resurrected wrapper keeps alive). + kCollected = 1, + // __releaseNativeCounterpart. + kExplicit = 2, + // Runtime teardown. + kTeardown = 3, + // A receiver lent to JS while its object ran -dealloc. + kDeallocated = 4, +}; +// Creates the isolate's markers, so marking never allocates in a finalizer. +void InitReleasedMarkers(v8::Isolate* isolate); +void MarkReleased(v8::Isolate* isolate, const v8::Local& 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`; +// 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..76ce2be28 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,51 @@ 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::kDeallocated: + return "The native object was deallocated after lending this receiver to JS from -dealloc"; + case tns::ReleasedReason::kNone: + break; } + return "The native object has been released or is not a valid native object"; +} - std::string message = - std::string("The native object has been released or is not a valid native object (") + - operation + ")"; +namespace { + +// Shared by GetValueOrReport and ReportReleasedObject: one message format, one +// event, one deduplication marker. +bool ApplyReleasedObjectPolicy(Isolate* isolate, const Local& 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 +592,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 +602,135 @@ 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; } +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); + // 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 + // 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()) { + return ReleasedReason::kNone; + } + 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, + 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..ea51039cd 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()); @@ -825,6 +831,19 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Localtype == BinaryTypeEncodingType::InterfaceDeclarationReference) { std::string name = typeEncoding->details.interfaceDeclarationReference.name.valuePtr(); @@ -915,6 +934,13 @@ static bool SnapshotArrayLike(Isolate* isolate, Local object, Local() isolate:isolate]; // CFAutorelease(adapter); @@ -1255,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); @@ -1319,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); @@ -1899,8 +1933,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/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index fa9729a3f..2bc2ffad1 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"; } } @@ -806,6 +812,19 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own } BaseDataWrapper* wrapper = tns::GetValue(isolate, thiz); + if (wrapper == nullptr) { + tns::ReleasedReason releasedReason = tns::GetReleasedReason(thiz); + if (releasedReason != tns::ReleasedReason::kNone) { + // String coercion (logging, template literals) still gets a string under + // the report policy. + if (tns::ReportReleasedObject(isolate, thiz, releasedReason, "toString receiver", true)) { + std::string name = tns::ToString(isolate, thiz->GetConstructorName()); + 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/NsBuiltinModules.cpp b/NativeScript/runtime/NsBuiltinModules.cpp index 902626c93..d35f4cf7d 100644 --- a/NativeScript/runtime/NsBuiltinModules.cpp +++ b/NativeScript/runtime/NsBuiltinModules.cpp @@ -9,6 +9,7 @@ #include "Interop.h" #include "Messaging.h" #include "ModuleInternalCallbacks.h" +#include "ObjectManager.h" #include "Runtime.h" #include "StructuredSerialization.h" #include "TextEncoding.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,41 @@ 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 +263,18 @@ 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..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" @@ -13,6 +17,11 @@ #include "Helpers.h" #include "Runtime.h" +// 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; @@ -45,9 +54,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) { @@ -60,7 +69,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) { @@ -80,6 +93,150 @@ void ReconcileOwnershipBeforeGC(Isolate* isolate, GCType, GCCallbackFlags) { } } +// A finalized wrapper that carried JS properties while something other than +// 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; + std::string className; + std::string properties; +}; + +struct WrapperLifetimeState { + 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() { + for (StateLostCandidate& candidate : candidates) { + objc_destroyWeak(candidate.weakSlot); + delete candidate.weakSlot; + } + } +}; + +bool IsTaggedPointer(id obj) { + // Through void*: clang rejects bit tests on ObjC object pointers. + uintptr_t bits = reinterpret_cast(static_cast(obj)); +#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 " + "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()); + } + } + 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 = + RetainCountWithoutJS(Caches::ExistingStateFor(isolate), target); + if (count <= 1 || count >= (NSUIntegerMax >> 1)) { + return; + } + SEL allowsWeak = sel_registerName("allowsWeakReference"); + if ([target respondsToSelector:allowsWeak] && + !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); + Local context = tns::GetCreationContextOrCurrent(isolate, obj); + Local names; + 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++; + + 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 += ", ..."; + } + + state->candidates.push_back({slot, description, className, properties}); + + if (!state->confirmPosted) { + state->confirmPosted = PostStateLostConfirmation(isolate); + } +} + } // namespace namespace { @@ -180,6 +337,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) { @@ -209,6 +377,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, @@ -417,11 +590,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; } @@ -432,12 +613,15 @@ 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; } } 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 +639,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 +752,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; } @@ -601,7 +804,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; @@ -673,13 +876,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/TestFixtures/Marshalling/TNSAllocLog.h b/TestFixtures/Marshalling/TNSAllocLog.h index a5767a50d..028be8046 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.h +++ b/TestFixtures/Marshalling/TNSAllocLog.h @@ -8,6 +8,10 @@ //- (void)release; - (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 5f9623197..15c07cd2d 100644 --- a/TestFixtures/Marshalling/TNSAllocLog.m +++ b/TestFixtures/Marshalling/TNSAllocLog.m @@ -17,6 +17,15 @@ - (instancetype)init { return [super init]; } +- (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/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/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..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)).toContain("disposed native object"); + 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 new file mode 100644 index 000000000..5f02b45e0 --- /dev/null +++ b/TestRunner/app/tests/WrapperLifetimeTests.js @@ -0,0 +1,331 @@ +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, after + // any releases queued for the runtime thread; not necessarily before the + // next timer. + function afterConfirmation(callback) { + setTimeout(callback, 100); + } + + 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, 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.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("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("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"); + 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 () { + 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(); + + afterConfirmation(function () { + var after = stats(); + runtime.setConfig("wrapperLifetimeWarnings", previous); + expect(after.stateLostCandidates).toBeGreaterThan(before.stateLostCandidates); + expect(after.stateLostConfirmed).toBeGreaterThan(before.stateLostConfirmed); + var lost = 0; + for (var i = 0; i < N; i++) { + if (owner.objectAtIndex(i).jsState === undefined) { + lost++; + } + } + expect(lost).toBeGreaterThan(0); + 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); + __collect(); + __collect(); + afterConfirmation(function () { + var before = stats(); + create(); + (function scrub(n) { + return n > 0 ? scrub(n - 1) + n : 0; + })(300); + __collect(); + __collect(); + afterConfirmation(function () { + var after = stats(); + runtime.setConfig("wrapperLifetimeWarnings", previous); + 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 () { + 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..869cdd201 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -182,9 +182,15 @@ 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 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 @@ -220,6 +226,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 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 +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..7a4d38a7e 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -103,8 +103,9 @@ 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 +`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. @@ -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,31 @@ 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, 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`; +`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 @@ -154,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. @@ -165,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"); diff --git a/types/ns-runtime.d.ts b/types/ns-runtime.d.ts index 37a74c68e..8d0ee8890 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, 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, once queued releases ran (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; }