diff --git a/NativeScript/runtime/MetadataBuilder.h b/NativeScript/runtime/MetadataBuilder.h index f87d7a6df..0b525fd54 100644 --- a/NativeScript/runtime/MetadataBuilder.h +++ b/NativeScript/runtime/MetadataBuilder.h @@ -12,6 +12,8 @@ namespace tns { +struct NativeSetters; + class MetadataBuilder { public: static void RegisterConstantsOnGlobalObject( @@ -30,6 +32,18 @@ class MetadataBuilder { void* data, StructStorage storage, v8::Local parent); + // Runs the setter of `owner`'s native property `property` on `receiver`, as + // the property's accessor would, and returns true. Returns false, having + // run nothing, unless `owner` is a native class's prototype, still holding + // the accessor pair it was built with for `property`, which has a setter. + // The caller establishes that `owner` is where `receiver`'s prototype chain + // finds `property`. Only canary mode records the accessors this needs. + static bool TrySetNativeProperty(v8::Isolate* isolate, + v8::Local context, + v8::Local owner, + v8::Local property, + v8::Local receiver, + v8::Local value); private: // The binding of an object whose static type adds protocols to `meta`: a @@ -102,18 +116,21 @@ class MetadataBuilder { v8::Local ctorFuncTemplate, const BaseClassMeta* meta, KnownUnknownClassPair pair, robin_hood::unordered_map& names); + // `setters`, when given, records each accessor pair installed. static void RegisterInstanceProperties( v8::Local context, v8::Local ctorFuncTemplate, const BaseClassMeta* meta, std::string className, KnownUnknownClassPair pair, - robin_hood::unordered_map& names); + robin_hood::unordered_map& names, + NativeSetters* setters = nullptr); static void RegisterInstanceProtocols( v8::Local context, v8::Local ctorFuncTemplate, const BaseClassMeta* meta, std::string className, KnownUnknownClassPair pair, - robin_hood::unordered_map& names); + robin_hood::unordered_map& names, + NativeSetters* setters = nullptr); static void RegisterAdditionalProtocols( v8::Local context, v8::Local ctorFuncTemplate, @@ -181,6 +198,13 @@ class MetadataBuilder { private: Class klass_ = nil; }; + + friend struct NativeSetters; + + static void SetNativeProperty(v8::Isolate* isolate, + CacheItem* item, + v8::Local receiver, + v8::Local value); }; } // namespace tns diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index 6bd249b64..fbcd6f46e 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -16,6 +16,7 @@ #include "SymbolLoader.h" #include "Tasks.h" #include "Worker.h" +#include "WrapperLifetime.h" #include "WrapperLifetimeCanary.h" using namespace v8; @@ -88,6 +89,124 @@ bool ResolveProxyReceiver(Isolate* isolate, Local& receiver, const char* constexpr int32_t kStructFieldIndexMask = (1 << kStructViewSlotShift) - 1; } // namespace +// The native property setters a native class's prototype was built with, for +// TrySetNativeProperty. JS can replace one only by defining the name on that +// prototype, which its definer sees, and a name the prototype's own handlers +// see defined or assigned is forgotten for good. A deleted accessor needs no +// such care: the prototype then no longer has the property. +struct NativeSetters { + struct Entry { + Global name; + MetadataBuilder::CacheItem* item; + }; + + // In the order RegisterInstanceProperties installed them: a later accessor + // of a name replaces the earlier one on the prototype. + std::vector*>> installed; + // By the name's identity hash. Names reaching an interceptor are internalized, + // so a lookup compares identities. + robin_hood::unordered_map> byHash; + + Entry* Find(Local name) { + auto it = byHash.find(name->GetIdentityHash()); + if (it == byHash.end()) { + return nullptr; + } + for (Entry& entry : it->second) { + if (entry.name == name) { + return &entry; + } + } + return nullptr; + } + + // Moves `installed` into `byHash`, keeping the last accessor of each name. + void Index(Isolate* isolate) { + for (const auto& [jsName, item] : installed) { + Local name = + v8::String::NewFromUtf8(isolate, jsName.c_str(), NewStringType::kInternalized) + .ToLocalChecked(); + MetadataBuilder::CacheItem* setter = item->meta_->hasSetter() ? item : nullptr; + if (Entry* entry = Find(name)) { + entry->item = setter; + } else if (setter != nullptr) { + byHash[name->GetIdentityHash()].push_back({Global(isolate, name), setter}); + } + } + installed.clear(); + installed.shrink_to_fit(); + } + + void Forget(Isolate* isolate, Local name) { + auto it = byHash.find(name->GetIdentityHash()); + if (it == byHash.end()) { + return; + } + for (Entry& entry : it->second) { + if (entry.name.Get(isolate)->StrictEquals(name)) { + entry.item = nullptr; + } + } + } +}; + +namespace { + +// Per-isolate: each native class prototype carries its NativeSetters under a +// private key. +struct NativeSetterState { + Global key; + std::vector> prototypes; +}; + +void PublishNativeSetters(Isolate* isolate, Local context, Local prototype, + std::unique_ptr setters) { + NativeSetterState* state = Caches::StateFor(isolate); + if (state == nullptr) { + return; + } + if (state->key.IsEmpty()) { + state->key.Reset(isolate, Private::New(isolate, tns::ToV8String(isolate, "nativeSetters"))); + } + setters->Index(isolate); + bool marked = false; + if (!prototype + ->SetPrivate(context, state->key.Get(isolate), + External::New(isolate, setters.get(), v8::kExternalPointerTypeTagDefault)) + .To(&marked) || + !marked) { + return; + } + state->prototypes.push_back(std::move(setters)); +} + +NativeSetters* NativeSettersOf(Isolate* isolate, Local context, Local prototype) { + NativeSetterState* state = Caches::ExistingStateFor(isolate); + if (state == nullptr || state->key.IsEmpty()) { + return nullptr; + } + Local marker; + if (!prototype->GetPrivate(context, state->key.Get(isolate)).ToLocal(&marker) || + !marker->IsExternal()) { + return nullptr; + } + return static_cast( + marker.As()->Value(v8::kExternalPointerTypeTagDefault)); +} + +// From a native class prototype's own handlers, which see JS define or assign +// `property` on that prototype. +void ForgetNativeSetter(Isolate* isolate, Local prototype, Local property) { + if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) { + return; + } + if (NativeSetters* setters = NativeSettersOf(isolate, isolate->GetCurrentContext(), prototype)) { + setters->Forget(isolate, property); + } +} + +} // namespace + void MetadataBuilder::RegisterConstantsOnGlobalObject(Isolate* isolate, Local globalTemplate, bool isWorkerThread) { @@ -599,11 +718,15 @@ throw NativeScriptException( } } + std::unique_ptr setters; + if (GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary) { + setters = std::make_unique(); + } MetadataBuilder::RegisterInstanceProperties(context, ctorFuncTemplate, meta, meta->name(), pair, - instanceMembers); + instanceMembers, setters.get()); MetadataBuilder::RegisterInstanceMethods(context, ctorFuncTemplate, meta, pair, instanceMembers); MetadataBuilder::RegisterInstanceProtocols(context, ctorFuncTemplate, meta, meta->name(), pair, - instanceMembers); + instanceMembers, setters.get()); ctorFuncTemplate->PrototypeTemplate()->Set( tns::ToV8String(isolate, "toString"), FunctionTemplate::New(isolate, MetadataBuilder::ToStringFunctionCallback)); @@ -647,6 +770,19 @@ NamedPropertyHandlerConfiguration config(nullptr, MetadataBuilder::SwizzledInsta } ObjectManager::Register(context, ctorFunc); + Local prototypeValue; + success = ctorFunc->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&prototypeValue); + tns::Assert(success, isolate); + Local prototype = prototypeValue.As(); + + Persistent* poPrototype = new Persistent(isolate, prototype); + cache->Prototypes.emplace(meta, poPrototype); + // Before the constructor is exposed: a JS accessor on the global can run + // during the Set and redefine prototype members, which must find the tracker. + if (setters != nullptr) { + PublishNativeSetters(isolate, context, prototype, std::move(setters)); + } + Local global = context->Global(); auto jsNameV8String = tns::ToV8String(isolate, meta->jsName()); auto maybeSet = global->Set(context, jsNameV8String, ctorFunc); @@ -666,14 +802,6 @@ NamedPropertyHandlerConfiguration config(nullptr, MetadataBuilder::SwizzledInsta MetadataBuilder::RegisterStaticProtocols(context, ctorFunc, meta, meta->name(), pair, staticMembers); - Local prototypeValue; - success = ctorFunc->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&prototypeValue); - tns::Assert(success, isolate); - Local prototype = prototypeValue.As(); - - Persistent* poPrototype = new Persistent(isolate, prototype); - cache->Prototypes.emplace(meta, poPrototype); - return ctorFuncTemplate; } @@ -889,7 +1017,7 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own void MetadataBuilder::RegisterInstanceProperties( Local context, Local ctorFuncTemplate, const BaseClassMeta* meta, const std::string className, KnownUnknownClassPair pair, - robin_hood::unordered_map& names) { + robin_hood::unordered_map& names, NativeSetters* setters) { Isolate* isolate = v8::Isolate::GetCurrent(); Local proto = ctorFuncTemplate->PrototypeTemplate(); @@ -917,6 +1045,9 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own Local setter = FunctionTemplate::New(isolate, PropertySetterCallback, ext); proto->SetAccessorProperty(tns::ToV8String(isolate, propMeta->jsName()), getter, setter, PropertyAttribute::None); + if (setters != nullptr) { + setters->installed.emplace_back(propMeta->jsName(), item); + } names.emplace(propertyName, accessors); } } @@ -925,11 +1056,11 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own void MetadataBuilder::RegisterInstanceProtocols( Local context, Local ctorFuncTemplate, const BaseClassMeta* meta, const std::string className, KnownUnknownClassPair pair, - robin_hood::unordered_map& names) { + robin_hood::unordered_map& names, NativeSetters* setters) { if (meta->type() == MetaType::ProtocolType) { MetadataBuilder::RegisterInstanceMethods(context, ctorFuncTemplate, meta, pair, names); MetadataBuilder::RegisterInstanceProperties(context, ctorFuncTemplate, meta, className, pair, - names); + names, setters); } for (auto itProto = meta->protocols->begin(); itProto != meta->protocols->end(); itProto++) { @@ -938,7 +1069,7 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own if (m != nullptr) { const BaseClassMeta* protoMeta = static_cast(m); MetadataBuilder::RegisterInstanceProtocols(context, ctorFuncTemplate, protoMeta, className, - pair, names); + pair, names, setters); } } } @@ -1185,9 +1316,13 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own } void MetadataBuilder::PropertySetterCallback(const FunctionCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); CacheItem* item = static_cast*>( info.Data().As()->Value(v8::kExternalPointerTypeTagDefault)); + SetNativeProperty(info.GetIsolate(), item, info.This(), info[0]); +} + +void MetadataBuilder::SetNativeProperty(Isolate* isolate, CacheItem* item, + Local receiver, Local value) { if (!item->meta_->hasSetter()) { Local error = Exception::Error(tns::ToV8String(isolate, "Attempted to assign to readonly property.")); @@ -1195,18 +1330,31 @@ void CollectInstanceMemberNames(const BaseClassMeta* meta, Class klass, bool own return; } - Local receiver = info.This(); if (!ResolveProxyReceiver(isolate, receiver, "set native property", item->meta_->jsName(), false)) { return; } - Local value = info[0]; V8SimpleValueArgs args(value); Local context = isolate->GetCurrentContext(); MetadataBuilder::InvokeMethod(context, item->meta_->setter(), receiver, args, item->ResolveClass(), true); } +bool MetadataBuilder::TrySetNativeProperty(Isolate* isolate, Local context, + Local owner, Local property, + Local receiver, Local value) { + NativeSetters* setters = NativeSettersOf(isolate, context, owner); + if (setters == nullptr) { + return false; + } + NativeSetters::Entry* entry = setters->Find(property); + if (entry == nullptr || entry->item == nullptr) { + return false; + } + SetNativeProperty(isolate, entry->item, receiver, value); + return true; +} + void MetadataBuilder::PropertyNameGetterCallback(const FunctionCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); CacheItem* item = static_cast*>( @@ -1421,6 +1569,7 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, v8::Intercepted MetadataBuilder::SwizzledInstanceMethodCallback( Local property, Local value, const PropertyCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); + ForgetNativeSetter(isolate, info.Holder(), property); std::string methodName = tns::ToString(isolate, property); CacheItem* item = static_cast*>( @@ -1466,6 +1615,7 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, Local property, const PropertyDescriptor& desc, const PropertyCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); + ForgetNativeSetter(isolate, info.Holder(), property); std::string propertyName = tns::ToString(isolate, property); CacheItem* item = static_cast*>( diff --git a/NativeScript/runtime/WrapperLifetimeCanary.mm b/NativeScript/runtime/WrapperLifetimeCanary.mm index 880e0fe02..7a2610a58 100644 --- a/NativeScript/runtime/WrapperLifetimeCanary.mm +++ b/NativeScript/runtime/WrapperLifetimeCanary.mm @@ -13,6 +13,7 @@ #include "DataWrapper.h" #include "EventLoop.h" #include "Helpers.h" +#include "MetadataBuilder.h" #include "ObjectManager.h" #include "Runtime.h" #import "TNSDerivedClass.h" @@ -621,15 +622,28 @@ Intercepted Setter(Local property, Local value, // setter: a native property's (an accessor pair on its class's // prototype), a JS one's, or one defined on the canary, which runs with // the canary as `this` and so mirrors whatever it writes. None is state. - // Calling the setter from here was measured slower than V8's own lookup + // Calling a JS setter from here was measured slower than V8's own lookup // after the decline: the API hands a setter out only in a descriptor - // object, and keeping one (or a native property's metadata) across - // writes needs to know when JS changes a prototype, which V8 never says. + // object. A native property's setter runs from here when its class's + // prototype vouches that the accessor found is still its own. if ((attributes & ReadOnly) != 0) { return Intercepted::kNo; } Local owner = OwnerOf(context, holder, property); - if (owner.IsEmpty() || owner->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) { + if (owner.IsEmpty()) { + return Intercepted::kNo; + } + Maybe accessor = owner->HasRealNamedCallbackProperty(context, property); + if (accessor.IsNothing()) { + return Intercepted::kNo; + } + if (accessor.FromJust()) { + // The setter can run JS, a collection or a -dealloc: neither the canary + // nor its record is touched after it. + if (MetadataBuilder::TrySetNativeProperty(isolate, context, owner, property, holder, value)) { + info.GetReturnValue().Set(true); + return Intercepted::kYes; + } return Intercepted::kNo; } } diff --git a/docs/knowledge/v8-resurrecting-finalizers.md b/docs/knowledge/v8-resurrecting-finalizers.md index 9e05926e4..1e64ccd9c 100644 --- a/docs/knowledge/v8-resurrecting-finalizers.md +++ b/docs/knowledge/v8-resurrecting-finalizers.md @@ -269,9 +269,14 @@ rebound with `this.onTap = this.onTap.bind(this)`, a field called `copy`, any `Object.defineProperty` over a prototype name), and those are state like any other. The setter classifies the prototype chain itself, because once it declines V8 adds a new name to the canary without calling the definer: a name that resolves to an inherited accessor (a -native property, a JS getter/setter) or a read-only data member is left to V8 and never -becomes state, so native setters run as before. The state is rooted from its first write -until the native object is deallocated (or, with the default death signal below, until its +native property, a JS getter/setter) or a read-only data member never becomes state. When the +first object on the chain with the name is a native class prototype that still records a +native setter for it, the handler runs that setter itself +(`MetadataBuilder::TrySetNativeProperty`, the same code as the accessor's setter callback). +Everything else is left to V8: a JS accessor, a read-only member, a native property without a +setter, and a name JS assigned or defined on that prototype, which its own setter and definer +interceptors forget for good. The state is rooted from its first write until the native +object is deallocated (or, with the default death signal below, until its token is released), and stays the source of truth: a canary built later for the same object, or the receiver a JS-implemented `-dealloc` runs with, gets the state's properties copied onto it with their attributes and accessors. The costs, measured on a @@ -279,8 +284,11 @@ Release simulator build: the handler is installed per template, so every write t wrapper goes through the setter, and V8 looks the name up again after it declines. Under `"extended"`, a plain wrapper's expando write takes about 64 ns instead of 17 and a native property store about 200 ns instead of 120. On a canary, where the setter also classifies the -name, an expando write takes about 100 ns and a native property store about 310 ns instead of -125 (380 instead of 115 four prototypes up). Building a canary for an object with state costs +name, an expando write takes about 100 ns. A native property store took about 310 ns instead +of 125 (380 instead of 115 four prototypes up) while the handler left it to V8; running the +setter from the handler brings it from about 324 to 289 ns two prototypes up and from 396 to +324 for a `UIButton` `tag` four up (323 to 292 and 392 to 334 under `"all"`, where a plain +`UIButton`'s goes from 322 to 266). Building a canary for an object with state costs about 330 ns per state property. Instances of JS-extended classes report their own deallocation: the runtime gives each extended class a `-dealloc` that marks the instance's records dying in every isolate, calls the superclass's (which can be a JS one the class @@ -314,7 +322,10 @@ rooted at canary death instead, because a state reachable only through the canar the same collection. The cost: state that references its own object (a closure over `this`) keeps it alive. A canary built after a death is a new object, but `===` cannot tell: only one canary lives at a time, and anything still referencing the old one would have kept it alive. -What could notice is whatever keys on the canary without keeping it. The weak collections +An explicit release is different: `__releaseNativeCounterpart` drops the object's +`Caches::Instances` entry but not its state, so if the object lives on, the next native return +of it builds a new canary with the state's properties while JS can still hold the released +one, and `===` tells them apart. What could notice is whatever keys on the canary without keeping it. The weak collections don't: in canary mode a builtin (`js/weak-collections.js`) replaces `WeakMap`, `WeakSet`, `WeakRef` and `FinalizationRegistry` with subclasses that key an in-scope native object (a canary: not a plain object under `"extended"`, a tagged pointer, a block, or an object of a class diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 958e96329..de03f098d 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -151,7 +151,9 @@ The `TypeError` messages are part of the contract: ### Wrapper lifetime counters `getWrapperLifetimeStats()` returns counters for the calling isolate, kept in -every build (they only cost an increment on finalizer and error paths): +every build. Most cost an increment only on finalizer, GC-callback and error +paths or when a state object is created; `canaryInterceptedWrites` costs one +on every write to a canary: | counter | counts | |---|---| @@ -165,7 +167,7 @@ every build (they only cost an increment on finalizer and error paths): | `demotions` | `"rooted"` only: strong wrappers made weak at a major collection because native code no longer retained their object | | `queuedReleases` | `"rooted"` and `"canary"`: collected wrappers whose native object was queued for release on the runtime's thread | | `canaryStates` | `"canary"` only: state objects created to hold native objects' JS properties | -| `canaryNativeDeaths` | `"canary"` only: state objects let go of because their native object was deallocated | +| `canaryNativeDeaths` | `"canary"` only: state objects let go of because their native object was deallocated or, with the default death signal, because `objc_removeAssociatedObjects` released its lifecycle token while the object was still alive | | `canaryInterceptedWrites` | `"canary"` only: writes to canaries the runtime's write handler saw. Other wrappers have no handler | A wrapper whose native object was released keeps its JS identity. Passing it diff --git a/types/ns-runtime.d.ts b/types/ns-runtime.d.ts index ba86f6d78..3dac00807 100644 --- a/types/ns-runtime.d.ts +++ b/types/ns-runtime.d.ts @@ -56,8 +56,12 @@ declare module "ns:runtime" { * prototype member (a rebound class method, a field called `copy`), are * also copied to a state object kept until the native object is * deallocated, and a wrapper built for the object later gets them back - * with their attributes. Native property writes still reach the native - * setter. Writes cost more than in the other modes; reads do not. + * with their attributes while that state object lives. An object that + * is not JS-extended is tracked through an associated token, so + * `objc_removeAssociatedObjects` on it lets its state object go while + * it lives, and one whose class forbids associated objects (or, under + * the alternative death signal, refuses weak references) gets none. + * Native property writes still reach the native setter. Writes cost more than in the other modes; reads do not. * WeakMap, WeakSet, WeakRef and FinalizationRegistry key such native * objects by their lifetime in this mode, so they carry over too; a * WeakMap value that references its own native key keeps that object @@ -101,7 +105,7 @@ declare module "ns:runtime" { queuedReleases: number; /** `"canary"` only: state objects created for native objects' JS properties. */ canaryStates: number; - /** `"canary"` only: state objects let go of because their native object was deallocated. */ + /** `"canary"` only: state objects let go of because their native object was deallocated, or because `objc_removeAssociatedObjects` released its lifecycle token. */ canaryNativeDeaths: number; /** `"canary"` only: writes to canaries the runtime's write handler saw. */ canaryInterceptedWrites: number;