Skip to content

Commit 85550e2

Browse files
committed
fix(runtime): canary mode review fixes
- A JS-implemented -dealloc replaced the class's death hook, so instances never reported their death: their state stayed rooted and the record, keyed by the freed address, was handed to the next object allocated there. WrapDealloc reports the death once the JS method returns, on the metadata, exposedMethods and prototype-replacement paths. - The state object is allocated before the registry lock: a collection the allocation starts can run callbacks that take it. - The weak sweep is posted from a GC epilogue, behind the collection's release drain. - IsExtendedInstance checks the protocol through the superclasses without messaging the class; objc_initWeakOrNil is only referenced by the weak sweep build. - Outside canary mode an NSArray's Symbol.iterator keeps its array again, so an unbound call still iterates it. - Docs: a JS property named like a prototype member is defined on the canary itself and does not survive its replacement; the state-lost warnings do nothing in canary mode. - Specs: a JS -dealloc class reports its deaths, the prototype-name limit, the unbound iterator; the association spec uses an object that carries a token, and the hand-back spec checks the old canary died.
1 parent 406891f commit 85550e2

8 files changed

Lines changed: 164 additions & 31 deletions

File tree

‎NativeScript/runtime/ClassBuilder.mm‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -742,7 +742,14 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
742742
IMP methodBody =
743743
Interop::CreateMethod(2, argsCount, typeEncoding, ArgConverter::MethodCallback, userData);
744744
std::string typeInfo = GetTypeEncoding(typeEncoding, argsCount);
745-
tns::Assert(class_addMethod(extendedClass, selector, methodBody, typeInfo.c_str()), isolate);
745+
IMP installed = WrapperLifetimeCanary::WrapDealloc(selector, methodBody);
746+
if (installed != methodBody) {
747+
// Replaces the canary dealloc hook the class already carries.
748+
class_replaceMethod(extendedClass, selector, installed, typeInfo.c_str());
749+
} else {
750+
tns::Assert(class_addMethod(extendedClass, selector, methodBody, typeInfo.c_str()),
751+
isolate);
752+
}
746753
}
747754
}
748755

@@ -849,7 +856,9 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
849856
IMP methodBody =
850857
Interop::CreateMethod(2, argsCount, typeEncoding, ArgConverter::MethodCallback, userData);
851858
std::string typeInfo = GetTypeEncoding(typeEncoding, argsCount);
852-
class_replaceMethod(extendedClass, selector, methodBody, typeInfo.c_str());
859+
class_replaceMethod(extendedClass, selector,
860+
WrapperLifetimeCanary::WrapDealloc(selector, methodBody),
861+
typeInfo.c_str());
853862
}
854863
}
855864
}

‎NativeScript/runtime/MetadataBuilder.mm‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1403,7 +1403,7 @@ void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName,
14031403
!ClassBuilder::ImplementsItself(klass, selector) && class_respondsToSelector(klass, alias);
14041404
Method method = class_getInstanceMethod(klass, inheritsAlias ? alias : selector);
14051405
IMP original = method != nullptr ? method_getImplementation(method) : nullptr;
1406-
class_replaceMethod(klass, selector, imp, types);
1406+
class_replaceMethod(klass, selector, WrapperLifetimeCanary::WrapDealloc(selector, imp), types);
14071407
if (original != nullptr) {
14081408
class_addMethod(klass, alias, original, types);
14091409
}

‎NativeScript/runtime/SymbolIterator.mm‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#include <Foundation/Foundation.h>
33
#include "ArgConverter.h"
44
#include "Helpers.h"
5+
#include "WrapperLifetime.h"
56

67
using namespace v8;
78

@@ -10,18 +11,27 @@
1011
void SymbolIterator::Set(Local<Context> context, Local<Value> object) {
1112
Isolate* isolate = v8::Isolate::GetCurrent();
1213

13-
// Iterates its receiver rather than capturing `object`: in the canary
14-
// wrapper lifetime mode this property lives on the object's state, which a
15-
// reference back to the object would keep alive until native death.
14+
// In the canary wrapper lifetime mode it iterates its receiver: this
15+
// property lives on the object's state there, which a reference back to the
16+
// object would keep alive until native death. Elsewhere it keeps `object`, so
17+
// an unbound call still iterates it.
18+
Local<Value> captured = GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary
19+
? Local<Value>()
20+
: object;
1621
Local<v8::Function> iterator;
17-
bool success = v8::Function::New(context,
18-
[](const FunctionCallbackInfo<Value>& args) {
19-
Isolate* isolate = args.GetIsolate();
20-
Local<Context> context = isolate->GetCurrentContext();
21-
Local<Object> result =
22-
CreateIteratorObject(context, args.This());
23-
args.GetReturnValue().Set(result);
24-
})
22+
bool success = v8::Function::New(
23+
context,
24+
[](const FunctionCallbackInfo<Value>& args) {
25+
Isolate* isolate = args.GetIsolate();
26+
Local<Context> context = isolate->GetCurrentContext();
27+
Local<Value> target = args.Data();
28+
if (target.IsEmpty() || target->IsUndefined()) {
29+
target = args.This();
30+
}
31+
Local<Object> result = CreateIteratorObject(context, target);
32+
args.GetReturnValue().Set(result);
33+
},
34+
captured)
2535
.ToLocal(&iterator);
2636
tns::Assert(success, isolate);
2737

‎NativeScript/runtime/WrapperLifetimeCanary.h‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#ifndef WrapperLifetimeCanary_h
22
#define WrapperLifetimeCanary_h
33

4+
#include <objc/runtime.h>
45
#include <memory>
56
#include "Common.h"
67

@@ -21,9 +22,9 @@ struct CanaryRecord;
2122
// deallocated. A JS-extended class's own -dealloc reports its instances; for
2223
// other objects an associated token's -dealloc does, or a sweep of weak
2324
// references after major collections finds it (NS_CANARY_DEATH_SIGNAL in the
24-
// .mm chooses). It cannot be rooted
25-
// only once the canary dies instead: a state reachable only through the canary
26-
// is garbage in the same collection, before any phantom callback runs. The
25+
// .mm chooses). It cannot be rooted only once the canary dies instead: a state
26+
// reachable only through the canary is garbage in the same collection, before
27+
// any phantom callback runs. The
2728
// cost is that state referencing its own canary (a closure over `this`, a
2829
// WeakMap value naming the object) keeps the canary, and through its retain the
2930
// native object, alive. This is the portable contract, the one the Node-API
@@ -43,6 +44,12 @@ class WrapperLifetimeCanary {
4344
// the mode is canary.
4445
static void InstallDeallocHook(Class extendedClass);
4546

47+
// The IMP to install for `selector` on a JS-extended class: a JS-implemented
48+
// -dealloc replaces the hook above, so it reports the death itself once the
49+
// JS method returns. `imp` unchanged for any other selector, or unless the
50+
// mode is canary.
51+
static IMP WrapDealloc(SEL selector, IMP imp);
52+
4653
// Installs the forwarding handlers on an ObjC instance template. No-op unless
4754
// the mode is canary.
4855
static void ConfigureInstanceTemplate(v8::Local<v8::ObjectTemplate> instanceTemplate);

‎NativeScript/runtime/WrapperLifetimeCanary.mm‎

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@
3131
#define NS_CANARY_DEATH_SIGNAL NS_CANARY_DEATH_ASSOCIATION
3232
#endif
3333

34+
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP
3435
extern "C" id objc_initWeakOrNil(id* location, id value);
36+
#endif
3537
extern "C" void objc_destroyWeak(id* location);
3638

3739
using namespace v8;
@@ -170,8 +172,15 @@ void ReportDeallocToAllRegistries(void* object) {
170172
}
171173
}
172174

175+
// Not a message: a root class without -conformsToProtocol: would crash under
176+
// scope "all". Walks the superclasses for key-value observing's subclass.
173177
bool IsExtendedInstance(id object) {
174-
return [object_getClass(object) conformsToProtocol:@protocol(TNSDerivedClass)];
178+
for (Class cls = object_getClass(object); cls != nil; cls = class_getSuperclass(cls)) {
179+
if (class_conformsToProtocol(cls, @protocol(TNSDerivedClass))) {
180+
return true;
181+
}
182+
}
183+
return false;
175184
}
176185

177186
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP
@@ -298,14 +307,12 @@ bool StateForWrite(Isolate* isolate, Local<Object> holder, Local<Object>* out) {
298307
if (registry == nullptr) {
299308
return false;
300309
}
301-
if (registry->loop.expired()) {
302-
if (Runtime* runtime = Runtime::GetRuntime(isolate)) {
303-
registry->loop = runtime->GetEventLoop();
304-
}
305-
}
306310
id object = canary->lifetimeTarget_;
307311
// A JS-extended class's own -dealloc reports its instances' deaths.
308312
bool extended = IsExtendedInstance(object);
313+
// Allocated before the lock: a collection this allocation starts can run
314+
// callbacks (the weak sweep's, a finalizer's -dealloc) that take it.
315+
Local<Object> freshState = Object::New(isolate, Null(isolate), nullptr, nullptr, 0);
309316
bool created = false;
310317
{
311318
std::lock_guard<std::mutex> lock(registry->mutex);
@@ -320,12 +327,14 @@ bool StateForWrite(Isolate* isolate, Local<Object> holder, Local<Object>* out) {
320327
if (slot == nullptr) {
321328
auto record = std::make_shared<CanaryRecord>();
322329
record->reportsDeath = extended || NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION;
330+
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP
323331
if (!record->reportsDeath && objc_initWeakOrNil(&record->object, object) == nil) {
324332
// The class refuses weak references.
325333
registry->records.erase((__bridge void*)object);
326334
return false;
327335
}
328-
record->state.Reset(isolate, Object::New(isolate, Null(isolate), nullptr, nullptr, 0));
336+
#endif
337+
record->state.Reset(isolate, freshState);
329338
slot = std::move(record);
330339
registry->count.fetch_add(1, std::memory_order_relaxed);
331340
created = true;
@@ -479,8 +488,9 @@ Intercepted Descriptor(Local<v8::Name> property, const PropertyCallbackInfo<Valu
479488
}
480489

481490
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP
482-
// Posts a sweep after each major collection: dead objects' weak references are
483-
// zeroed by then. Only posts; the GC is no place to reset handles.
491+
// Posts a sweep when a major collection ends, behind the release drain the
492+
// collection queued: objects it released are gone by the time the sweep runs.
493+
// Only posts; the GC is no place to reset handles.
484494
void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) {
485495
CanaryState* state = Caches::StateFor<CanaryState>(isolate);
486496
if (state == nullptr || state->registry->count.load(std::memory_order_relaxed) == 0) {
@@ -521,8 +531,7 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) {
521531
registries_.push_back(state->registry);
522532
}
523533
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP
524-
isolate->AddGCPrologueCallback(
525-
PostSweepAfterGC, static_cast<GCType>(kGCTypeMarkSweepCompact | kGCTypeIncrementalMarking));
534+
isolate->AddGCEpilogueCallback(PostSweepAfterGC, kGCTypeMarkSweepCompact);
526535
#endif
527536
}
528537

@@ -549,6 +558,18 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) {
549558
class_addMethod(extendedClass, @selector(dealloc), dealloc, "v@:");
550559
}
551560

561+
IMP WrapperLifetimeCanary::WrapDealloc(SEL selector, IMP imp) {
562+
if (selector != @selector(dealloc) ||
563+
GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) {
564+
return imp;
565+
}
566+
return imp_implementationWithBlock(^(id self) {
567+
void* object = (__bridge void*)self;
568+
reinterpret_cast<void (*)(id, SEL)>(imp)(self, @selector(dealloc));
569+
ReportDeallocToAllRegistries(object);
570+
});
571+
}
572+
552573
void WrapperLifetimeCanary::ConfigureInstanceTemplate(Local<ObjectTemplate> instanceTemplate) {
553574
if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) {
554575
return;

‎TestRunner/app/tests/WrapperLifetimeModesTests.js‎

Lines changed: 81 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,12 +350,17 @@ describe("Wrapper lifetime modes", function () {
350350

351351
it("hands back a native object's JS properties on a new wrapper after the old one died", function (done) {
352352
var owner = NSMutableArray.new();
353+
var first;
353354
(function () {
354355
var obj = Extended.new();
355356
obj.tag = "kept";
356357
owner.addObject(obj);
358+
first = new WeakRef(obj);
357359
})();
358360
settle(2, function () {
361+
if (canary) {
362+
expect(first.deref()).toBeUndefined();
363+
}
359364
var obj = owner.objectAtIndex(0);
360365
if (keepsState) {
361366
expect(obj.tag).toBe("kept");
@@ -364,6 +369,80 @@ describe("Wrapper lifetime modes", function () {
364369
});
365370
});
366371

372+
// kNonMasking interceptors only see names the prototype chain lacks: a JS
373+
// property shadowing a prototype member is defined on the wrapper itself,
374+
// so in canary mode it goes with the wrapper. A documented limit.
375+
it("keeps a JS property that shadows a prototype member only while its canary lives", function (done) {
376+
var owner = NSMutableArray.new();
377+
(function () {
378+
var obj = Extended.new();
379+
obj.isEqual = function () {
380+
return "shadow";
381+
};
382+
obj.tag = "kept";
383+
owner.addObject(obj);
384+
})();
385+
settle(2, function () {
386+
var obj = owner.objectAtIndex(0);
387+
if (canary) {
388+
expect(obj.tag).toBe("kept");
389+
expect(obj.isEqual(obj)).toBe(true);
390+
} else if (rooted) {
391+
expect(obj.isEqual(obj)).toBe("shadow");
392+
}
393+
done();
394+
});
395+
});
396+
397+
// A JS-implemented dealloc replaces the class's own death hook, so it
398+
// reports the death itself, after the JS method ran.
399+
it("lets the JS state go when a JS-implemented dealloc ran", function (done) {
400+
var N = 8;
401+
var seen = [];
402+
var WithDealloc = TNSAllocLog.extend({
403+
dealloc: function () {
404+
seen.push(true);
405+
this.super.dealloc();
406+
}
407+
}, { name: "WrapperLifetimeModesJSDealloc" });
408+
var owner = NSMutableArray.new();
409+
settle(2, function () {
410+
var before = runtime.getWrapperLifetimeStats();
411+
(function () {
412+
for (var i = 0; i < N; i++) {
413+
var obj = WithDealloc.new();
414+
obj.tag = "state";
415+
owner.addObject(obj);
416+
}
417+
})();
418+
settle(2, function () {
419+
owner.removeAllObjects();
420+
settle(3, function () {
421+
var after = runtime.getWrapperLifetimeStats();
422+
expect(seen.length).toBe(N);
423+
if (canary) {
424+
expect(after.canaryNativeDeaths - before.canaryNativeDeaths).not.toBeLessThan(N);
425+
}
426+
done();
427+
});
428+
});
429+
});
430+
});
431+
432+
it("iterates an NSArray through an unbound Symbol.iterator outside canary mode", function () {
433+
if (canary) {
434+
return;
435+
}
436+
var array = NSArray.arrayWithArray(["a", "b"]);
437+
var iterate = array[Symbol.iterator];
438+
var iterator = iterate();
439+
var values = [];
440+
for (var step = iterator.next(); !step.done; step = iterator.next()) {
441+
values.push(step.value);
442+
}
443+
expect(values).toEqual(["a", "b"]);
444+
});
445+
367446
it("leaves plain objects outside the extended scope without forwarding", function (done) {
368447
var owner = NSMutableArray.new();
369448
(function () {
@@ -453,7 +532,8 @@ describe("Wrapper lifetime modes", function () {
453532
if (typeof objc_removeAssociatedObjects !== "function") {
454533
return;
455534
}
456-
var obj = Extended.new();
535+
// Only objects outside JS-extended classes carry the token.
536+
var obj = scope === "all" ? TNSAllocLog.new() : Extended.new();
457537
obj.tag = "first";
458538
objc_removeAssociatedObjects(obj);
459539
expect([undefined, "first"]).toContain(obj.tag);

‎docs/knowledge/v8-resurrecting-finalizers.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@ JS-referencing native cycles alive (ARC rules: break them with a `WeakRef`). Spe
253253
when the TestRunner app config selects `"mode": "rooted"`.
254254

255255
The state-lost warnings (`wrapperLifetimeWarnings`) watch for resurrecting finalizers and stay
256-
silent in the rooted mode. Under `"scope": "extended"` there, a plain (not JS-extended) wrapper
256+
silent in the rooted and canary modes. Under `"scope": "extended"` in the rooted mode, a plain (not JS-extended) wrapper
257257
is a phantom handle that a scavenge can collect, so JS properties set on plain objects that
258258
native code owns are lost without a warning.
259259

@@ -281,6 +281,10 @@ What does notice is whatever keys on the canary without keeping it: `WeakMap` ke
281281
of the old canary, and native `#private` fields, which are branded on it. Other
282282
limits: `Object.freeze`, `seal` and `preventExtensions` throw on a canary (V8 refuses them on
283283
objects with interceptors); index-keyed properties are not forwarded and die with the canary;
284+
so does a property named like anything on the prototype chain (a class method rebound with
285+
`this.onTap = this.onTap.bind(this)`, a field called `copy` or `toString`, any
286+
`Object.defineProperty` or define-semantics class field over such a name): a `kNonMasking`
287+
interceptor is skipped for a name the chain has, so V8 defines it on the canary itself;
284288
a write through an object whose prototype is a canary lands in the canary's state, since
285289
interceptors see the holder but not the receiver. Relies on
286290
V8's own-property lookup through `kNonMasking` interceptors when the prototype has a named

‎types/ns-runtime.d.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,9 @@ declare module "ns:runtime" {
5555
* references; JS properties set on it live on a state object kept until
5656
* the native object is deallocated, and a wrapper built for the object
5757
* later has them again. Weak references to the old wrapper (WeakMap keys,
58-
* WeakRef) and native `#private` fields do not carry over.
58+
* WeakRef), native `#private` fields, index-keyed properties and
59+
* properties named like a member of the prototype chain (a rebound class
60+
* method, a field called `copy`) do not carry over.
5961
* State that references its own object keeps that object alive.
6062
*/
6163
wrapperLifetimeMode: "resurrecting" | "rooted" | "canary";

0 commit comments

Comments
 (0)