Skip to content

Commit 0fe5c75

Browse files
committed
feat(runtime): canary mode mirrors JS properties onto the canary
kNonMasking interceptors never see a write or define over a name the prototype chain has, so `this.onTap = this.onTap.bind(this)`, fields named `copy` and `Object.defineProperty` over a prototype member stayed on the canary and were lost when it was replaced. The canary's named interceptor is now masking, with only a setter, a deleter and a definer. Each one copies its write into the state object and declines, so V8 also applies it to the canary: - Reads find real own properties and never call into C++: expando reads cost what they cost on a plain object. - The setter classifies the name itself, because after it declines V8 adds a new name to the canary without calling the definer. A read-only name or an accessor (a native property, a JS getter/setter, an accessor defined on the canary) is left to V8 and never becomes state, so native setters run as before. - A canary built for an object with state, and the receiver a JS-implemented -dealloc runs with, get the state's properties copied onto them with their attributes and accessors (Hydrate). A record replaced under a live canary (its token was removed) is seeded from the canary. The state object stays the source of truth and keeps its lifetime. Costs: every write to a canary goes through the setter, and building a canary for an object with state copies each of its properties. Class fields still need v8-buildscripts#13: before it, the definer gets inverted attributes for a cold field and is bypassed once the field initializer is warm.
1 parent c46b96d commit 0fe5c75

9 files changed

Lines changed: 529 additions & 144 deletions

File tree

‎NativeScript/runtime/ArgConverter.mm‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1278,6 +1278,7 @@ bool IsKVOSubclassOf(Class klass, Class base) {
12781278
wrapper->MarkBorrowed();
12791279
Local<Object> receiver = NewEmptyInstance(context, cache->EmptyObjCtorFunc.get());
12801280
CreateJsWrapper(context, wrapper, receiver);
1281+
WrapperLifetimeCanary::Hydrate(isolate, receiver);
12811282
*borrowed = wrapper;
12821283
return receiver;
12831284
}

‎NativeScript/runtime/ObjectManager.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ struct ObjectWeakCallbackState {
5555
bool lifetimeTracked_ = false;
5656
// The handle is currently strong.
5757
bool lifetimeStrong_ = false;
58-
// Canary mode: the wrapper forwards JS properties to a state object that
58+
// Canary mode: the wrapper mirrors JS properties into a state object that
5959
// outlives it (WrapperLifetimeCanary), found through this record once the
6060
// object has state.
6161
bool lifetimeCanary_ = false;

‎NativeScript/runtime/WrapperLifetime.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ enum class WrapperLifetimeMode {
2323
// Phantom callbacks, no resurrection: the wrapper is a canary that dies with
2424
// its JS references. JS properties set on it live on a separate state object
2525
// that stays alive until the native object is deallocated, and a canary
26-
// built for the same object later shares it (WrapperLifetimeCanary).
26+
// built for the same object later gets them back (WrapperLifetimeCanary).
2727
kCanary,
2828
};
2929

‎NativeScript/runtime/WrapperLifetime.mm‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,9 @@ void ReleaseAll(Isolate* isolate, RootedState* rooted) {
360360
state->lifetimeCanary_ = IsInScope(target);
361361
if (state->lifetimeCanary_) {
362362
state->canaryRecord_ = WrapperLifetimeCanary::Find(isolate, target);
363+
if (state->canaryRecord_ != nullptr) {
364+
WrapperLifetimeCanary::Hydrate(isolate, handle->Get(isolate).As<Object>());
365+
}
363366
}
364367
MakeWeak(state);
365368
} else if (IsInScope(target)) {

‎NativeScript/runtime/WrapperLifetimeCanary.h‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@ struct CanaryRecord;
1212
// The canary wrapper lifetime mode (WrapperLifetimeMode::kCanary).
1313
//
1414
// An ObjC object's wrapper is a canary: a phantom-weak JS object that dies
15-
// with its JS references, releasing the runtime's retain on the object. JS
16-
// properties set on a canary are forwarded by kNonMasking named interceptors
17-
// to a state object, so prototype members (native methods and properties,
18-
// JS-extended class methods) never reach these handlers. A canary built later
19-
// for the same object forwards to the same state.
15+
// with its JS references, releasing the runtime's retain on the object. A
16+
// masking named interceptor with only a setter, deleter and definer mirrors
17+
// every JS property written to a canary into a state object and then declines,
18+
// so the property also lands on the canary and reads never leave V8. Writes to
19+
// native properties and other inherited accessors are not state. A canary
20+
// built later for the same object gets the state's properties copied back
21+
// (Hydrate). The state object is the source of truth.
2022
//
2123
// The state object is rooted from its first write until the native object is
2224
// deallocated. A JS-extended class's own -dealloc reports its instances; for
@@ -58,6 +60,10 @@ class WrapperLifetimeCanary {
5860
// canary to share. Null otherwise.
5961
static std::shared_ptr<CanaryRecord> Find(v8::Isolate* isolate, id object);
6062

63+
// Copies the state of a new canary's object, or of a -dealloc receiver's,
64+
// onto that wrapper. No-op without state, or unless the mode is canary.
65+
static void Hydrate(v8::Isolate* isolate, v8::Local<v8::Object> wrapper);
66+
6167
// Teardown: lets go of every state object while the isolate is alive. Tokens
6268
// that outlive the isolate find the registry closed.
6369
static void CloseForTeardown(v8::Isolate* isolate);

‎NativeScript/runtime/WrapperLifetimeCanary.mm‎

Lines changed: 154 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,66 @@ void PostDrain(const std::shared_ptr<CanaryRegistry>& registry) {
356356
return it != state->registry->records.end() ? it->second : nullptr;
357357
}
358358

359+
// Set while this thread copies properties between a canary and its state, so
360+
// the canary's definer lets those defines through. Per thread rather than per
361+
// isolate: the copy runs no JS, so only its own defines reach an interceptor
362+
// on this thread meanwhile.
363+
thread_local bool copyingProperties_ = false;
364+
365+
Local<Value> DescriptorField(Isolate* isolate, Local<Context> context, Local<Object> descriptor,
366+
const char* name) {
367+
Local<Value> value;
368+
return descriptor->Get(context, tns::ToV8String(isolate, name)).ToLocal(&value)
369+
? value
370+
: Local<Value>(v8::Undefined(isolate));
371+
}
372+
373+
// Copies `from`'s own string- and symbol-keyed properties onto `to`, with their
374+
// attributes; an accessor keeps its functions, which run with whichever object
375+
// they are reached through as `this`.
376+
void CopyOwnProperties(Isolate* isolate, Local<Context> context, Local<Object> from,
377+
Local<Object> to) {
378+
HandleScope scope(isolate);
379+
TryCatch tc(isolate);
380+
bool wasCopying = copyingProperties_;
381+
copyingProperties_ = true;
382+
Local<v8::Array> names;
383+
if (from->GetPropertyNames(context, KeyCollectionMode::kOwnOnly, PropertyFilter::ALL_PROPERTIES,
384+
IndexFilter::kSkipIndices, KeyConversionMode::kConvertToString)
385+
.ToLocal(&names)) {
386+
for (uint32_t i = 0; i < names->Length(); i++) {
387+
Local<Value> name;
388+
if (!names->Get(context, i).ToLocal(&name) || !name->IsName()) {
389+
continue;
390+
}
391+
Local<v8::Name> key = name.As<v8::Name>();
392+
if (!from->HasRealNamedCallbackProperty(context, key).FromMaybe(true)) {
393+
PropertyAttribute attributes;
394+
Local<Value> value;
395+
if (from->GetRealNamedPropertyAttributes(context, key).To(&attributes) &&
396+
from->GetRealNamedProperty(context, key).ToLocal(&value)) {
397+
(void)to->DefineOwnProperty(context, key, value, attributes);
398+
}
399+
continue;
400+
}
401+
Local<Value> descriptorValue;
402+
if (!from->GetOwnPropertyDescriptor(context, key).ToLocal(&descriptorValue) ||
403+
!descriptorValue->IsObject()) {
404+
continue;
405+
}
406+
Local<Object> descriptor = descriptorValue.As<Object>();
407+
PropertyDescriptor accessor(DescriptorField(isolate, context, descriptor, "get"),
408+
DescriptorField(isolate, context, descriptor, "set"));
409+
accessor.set_enumerable(
410+
DescriptorField(isolate, context, descriptor, "enumerable")->BooleanValue(isolate));
411+
accessor.set_configurable(
412+
DescriptorField(isolate, context, descriptor, "configurable")->BooleanValue(isolate));
413+
(void)to->DefineProperty(context, key, accessor);
414+
}
415+
}
416+
copyingProperties_ = wasCopying;
417+
}
418+
359419
// The state object of the holder, if it has one.
360420
bool ExistingState(Isolate* isolate, Local<Object> holder, Local<Object>* out) {
361421
ObjectWeakCallbackState* canary = CanaryOf(isolate, holder);
@@ -381,6 +441,9 @@ bool StateForWrite(Isolate* isolate, Local<Object> holder, Local<Object>* out) {
381441
return false;
382442
}
383443
id object = canary->lifetimeTarget_;
444+
// The record died under a live canary (its token was removed): the
445+
// canary's properties seed the new state.
446+
bool replacesDied = canary->canaryRecord_ != nullptr;
384447
// A JS-extended class's own -dealloc reports its instances' deaths.
385448
bool extended = IsExtendedInstance(object);
386449
// Allocated before the lock: a collection this allocation starts can run
@@ -432,6 +495,13 @@ bool StateForWrite(Isolate* isolate, Local<Object> holder, Local<Object>* out) {
432495
if (ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(isolate)) {
433496
stats->canaryStates++;
434497
}
498+
if (replacesDied) {
499+
CopyOwnProperties(isolate, isolate->GetCurrentContext(), holder, freshState);
500+
}
501+
} else if (Usable(canary->canaryRecord_)) {
502+
// Joined state another wrapper of the object wrote: the canary mirrors it.
503+
CopyOwnProperties(isolate, isolate->GetCurrentContext(),
504+
Local<Object>::New(isolate, canary->canaryRecord_->state), holder);
435505
}
436506
}
437507
if (!Usable(canary->canaryRecord_)) {
@@ -445,123 +515,102 @@ bool HasOwn(Local<Context> context, Local<Object> state, Local<v8::Name> propert
445515
return state->HasOwnProperty(context, property).FromMaybe(false);
446516
}
447517

448-
Intercepted Getter(Local<v8::Name> property, const PropertyCallbackInfo<Value>& info) {
449-
Isolate* isolate = info.GetIsolate();
450-
Local<Object> state;
451-
if (!ExistingState(isolate, info.Holder(), &state)) {
452-
return Intercepted::kNo;
453-
}
454-
Local<Context> context = isolate->GetCurrentContext();
455-
if (!HasOwn(context, state, property)) {
456-
return Intercepted::kNo;
457-
}
458-
Local<Value> value;
459-
// An accessor defined through the canary runs with the canary as `this`
460-
// (interceptors do not see the receiver, only the holder).
461-
if (state->Get(context, property, info.Holder()).ToLocal(&value)) {
462-
info.GetReturnValue().Set(value);
518+
// The object of `holder`'s prototype chain, `holder` included, with a real own
519+
// `property`, interceptors skipped; empty if there is none.
520+
Local<Object> OwnerOf(Local<Context> context, Local<Object> holder, Local<v8::Name> property) {
521+
Local<Object> object = holder;
522+
while (!object->HasRealNamedProperty(context, property).FromMaybe(false)) {
523+
Local<Value> prototype = object->GetPrototype();
524+
if (!prototype->IsObject()) {
525+
return Local<Object>();
526+
}
527+
object = prototype.As<Object>();
463528
}
464-
return Intercepted::kYes;
529+
return object;
465530
}
466531

532+
// The handlers mirror: each copies its write into the state and declines, so
533+
// V8 also applies it to the canary, where reads find a real own property and
534+
// never call into C++. There is no getter, query, enumerator or descriptor
535+
// callback for the same reason. The handlers are masking, so they also see
536+
// names the prototype chain has. After the setter declines, V8 adds a new name
537+
// to the canary without calling the definer, so the setter itself decides what
538+
// becomes state.
467539
Intercepted Setter(Local<v8::Name> property, Local<Value> value,
468540
const PropertyCallbackInfo<v8::Boolean>& info) {
469541
Isolate* isolate = info.GetIsolate();
470-
Local<Object> state;
471-
if (!StateForWrite(isolate, info.Holder(), &state)) {
472-
return Intercepted::kNo;
473-
}
474-
Local<Context> context = isolate->GetCurrentContext();
475-
Maybe<bool> result = state->HasRealNamedCallbackProperty(context, property).FromMaybe(false)
476-
? state->Set(context, property, value, info.Holder())
477-
: state->Set(context, property, value);
478-
if (result.IsJust()) {
479-
info.GetReturnValue().Set(result.FromJust());
480-
}
481-
return Intercepted::kYes;
482-
}
483-
484-
Intercepted Query(Local<v8::Name> property, const PropertyCallbackInfo<v8::Integer>& info) {
485-
Isolate* isolate = info.GetIsolate();
486-
Local<Object> state;
487-
if (!ExistingState(isolate, info.Holder(), &state)) {
488-
return Intercepted::kNo;
542+
Local<Object> holder = info.Holder();
543+
ObjectWeakCallbackState* canary = CanaryOf(isolate, holder);
544+
std::shared_ptr<CanaryRecord> borrowed;
545+
if (canary == nullptr) {
546+
borrowed = BorrowedRecord(isolate, holder);
547+
if (!Usable(borrowed)) {
548+
return Intercepted::kNo;
549+
}
489550
}
551+
CanaryRecord* record = canary != nullptr ? canary->canaryRecord_.get() : borrowed.get();
490552
Local<Context> context = isolate->GetCurrentContext();
491-
if (!HasOwn(context, state, property)) {
492-
return Intercepted::kNo;
553+
if (record != nullptr && !record->died.load(std::memory_order_acquire) &&
554+
!record->state.IsEmpty()) {
555+
// Own on the state means own on the canary: a rewrite of a JS property.
556+
Local<Object> state = Local<Object>::New(isolate, record->state);
557+
if (HasOwn(context, state, property)) {
558+
if (!state->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) {
559+
(void)state->Set(context, property, value);
560+
}
561+
return Intercepted::kNo;
562+
}
493563
}
564+
// Searches the prototype chain too: absent there means a new name.
494565
PropertyAttribute attributes;
495-
if (state->GetPropertyAttributes(context, property).To(&attributes)) {
496-
info.GetReturnValue().Set(v8::Integer::New(isolate, attributes));
566+
if (holder->GetRealNamedPropertyAttributes(context, property).To(&attributes)) {
567+
// V8 rejects a write to a read-only property and runs an accessor's
568+
// setter: a native property's (an accessor pair on its class's
569+
// prototype), a JS one's, or one defined on the canary, which runs with
570+
// the canary as `this` and so mirrors whatever it writes. None is state.
571+
if ((attributes & ReadOnly) != 0) {
572+
return Intercepted::kNo;
573+
}
574+
Local<Object> owner = OwnerOf(context, holder, property);
575+
if (owner.IsEmpty() || owner->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) {
576+
return Intercepted::kNo;
577+
}
497578
}
498-
return Intercepted::kYes;
499-
}
500-
501-
Intercepted Deleter(Local<v8::Name> property, const PropertyCallbackInfo<v8::Boolean>& info) {
502-
Isolate* isolate = info.GetIsolate();
503579
Local<Object> state;
504-
if (!ExistingState(isolate, info.Holder(), &state)) {
580+
if (!StateForWrite(isolate, holder, &state)) {
505581
return Intercepted::kNo;
506582
}
507-
Local<Context> context = isolate->GetCurrentContext();
508583
if (!HasOwn(context, state, property)) {
509-
return Intercepted::kNo;
584+
(void)state->CreateDataProperty(context, property, value);
585+
} else if (!state->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) {
586+
(void)state->Set(context, property, value);
510587
}
511-
bool deleted;
512-
if (state->Delete(context, property).To(&deleted)) {
513-
info.GetReturnValue().Set(deleted);
514-
}
515-
return Intercepted::kYes;
588+
return Intercepted::kNo;
516589
}
517590

518-
void Enumerator(const PropertyCallbackInfo<v8::Array>& info) {
591+
Intercepted Deleter(Local<v8::Name> property, const PropertyCallbackInfo<v8::Boolean>& info) {
519592
Isolate* isolate = info.GetIsolate();
520593
Local<Object> state;
521-
if (!ExistingState(isolate, info.Holder(), &state)) {
522-
return;
523-
}
524-
Local<Context> context = isolate->GetCurrentContext();
525-
Local<v8::Array> names;
526-
if (state
527-
->GetPropertyNames(context, KeyCollectionMode::kOwnOnly, PropertyFilter::ALL_PROPERTIES,
528-
IndexFilter::kSkipIndices)
529-
.ToLocal(&names)) {
530-
info.GetReturnValue().Set(names);
594+
if (ExistingState(isolate, info.Holder(), &state)) {
595+
(void)state->Delete(isolate->GetCurrentContext(), property);
531596
}
597+
return Intercepted::kNo;
532598
}
533599

600+
// Object.defineProperty, define-semantics class fields and `super.x = v` on a
601+
// receiver that lacks `x` reach here.
534602
Intercepted Definer(Local<v8::Name> property, const PropertyDescriptor& descriptor,
535603
const PropertyCallbackInfo<v8::Boolean>& info) {
536-
Isolate* isolate = info.GetIsolate();
537-
Local<Object> state;
538-
if (!StateForWrite(isolate, info.Holder(), &state)) {
604+
if (copyingProperties_) {
539605
return Intercepted::kNo;
540606
}
541-
Local<Context> context = isolate->GetCurrentContext();
542-
bool defined;
543-
if (state->DefineProperty(context, property, const_cast<PropertyDescriptor&>(descriptor))
544-
.To(&defined)) {
545-
info.GetReturnValue().Set(defined);
546-
}
547-
return Intercepted::kYes;
548-
}
549-
550-
Intercepted Descriptor(Local<v8::Name> property, const PropertyCallbackInfo<Value>& info) {
551607
Isolate* isolate = info.GetIsolate();
552608
Local<Object> state;
553-
if (!ExistingState(isolate, info.Holder(), &state)) {
554-
return Intercepted::kNo;
555-
}
556-
Local<Context> context = isolate->GetCurrentContext();
557-
if (!HasOwn(context, state, property)) {
558-
return Intercepted::kNo;
609+
if (StateForWrite(isolate, info.Holder(), &state)) {
610+
(void)state->DefineProperty(isolate->GetCurrentContext(), property,
611+
const_cast<PropertyDescriptor&>(descriptor));
559612
}
560-
Local<Value> descriptor;
561-
if (state->GetOwnPropertyDescriptor(context, property).ToLocal(&descriptor)) {
562-
info.GetReturnValue().Set(descriptor);
563-
}
564-
return Intercepted::kYes;
613+
return Intercepted::kNo;
565614
}
566615

567616
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP
@@ -659,8 +708,24 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) {
659708
return;
660709
}
661710
instanceTemplate->SetHandler(NamedPropertyHandlerConfiguration(
662-
Getter, Setter, Query, Deleter, Enumerator, Definer, Descriptor, Local<Value>(),
663-
PropertyHandlerFlags::kNonMasking));
711+
nullptr, Setter, nullptr, Deleter, nullptr, Definer, nullptr, Local<Value>(),
712+
PropertyHandlerFlags::kNone));
713+
}
714+
715+
void WrapperLifetimeCanary::Hydrate(Isolate* isolate, Local<Object> wrapper) {
716+
if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) {
717+
return;
718+
}
719+
HandleScope scope(isolate);
720+
Local<Object> state;
721+
if (!ExistingState(isolate, wrapper, &state)) {
722+
return;
723+
}
724+
Local<Context> context = isolate->GetCurrentContext();
725+
if (context.IsEmpty()) {
726+
context = Caches::Get(isolate)->GetContext();
727+
}
728+
CopyOwnProperties(isolate, context, state, wrapper);
664729
}
665730

666731
std::shared_ptr<CanaryRecord> WrapperLifetimeCanary::Find(Isolate* isolate, id object) {

0 commit comments

Comments
 (0)