Skip to content

Commit c18453e

Browse files
committed
feat(runtime): JS-extended classes report their own deallocation in canary mode
In canary mode every JS-extended class gets a -dealloc that reports the instance to every isolate's canary registry (an instance can have state in an isolate other than the one that defined its class), then calls the superclass's. Their records need no associated token or weak reference, so the default "extended" scope attaches no associations at all.
1 parent 0e4abb6 commit c18453e

5 files changed

Lines changed: 123 additions & 26 deletions

File tree

‎NativeScript/runtime/ClassBuilder.mm‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
9292
tns::Assert(extendedClass != nil, isolate);
9393
class_addProtocol(extendedClass, @protocol(TNSDerivedClass));
9494
class_addProtocol(object_getClass(extendedClass), @protocol(TNSDerivedClass));
95+
WrapperLifetimeCanary::InstallDeallocHook(extendedClass);
9596

9697
if (!nativeSignature.IsEmpty()) {
9798
ClassBuilder::ExposeDynamicMembers(context, extendedClass, implementationObject,
@@ -238,6 +239,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
238239
tns::Assert(extendedClass != nil, isolate);
239240
class_addProtocol(extendedClass, @protocol(TNSDerivedClass));
240241
class_addProtocol(object_getClass(extendedClass), @protocol(TNSDerivedClass));
242+
WrapperLifetimeCanary::InstallDeallocHook(extendedClass);
241243

242244
extendedClassName = class_getName(extendedClass);
243245

‎NativeScript/runtime/WrapperLifetimeCanary.h‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,9 @@ struct CanaryRecord;
1818
// for the same object forwards to the same state.
1919
//
2020
// The state object is rooted from its first write until the native object is
21-
// deallocated, reported by an associated token's -dealloc or found by a sweep
22-
// of weak references after major collections (NS_CANARY_DEATH_SIGNAL in the
21+
// deallocated. A JS-extended class's own -dealloc reports its instances; for
22+
// other objects an associated token's -dealloc does, or a sweep of weak
23+
// references after major collections finds it (NS_CANARY_DEATH_SIGNAL in the
2324
// .mm chooses). It cannot be rooted
2425
// only once the canary dies instead: a state reachable only through the canary
2526
// is garbage in the same collection, before any phantom callback runs. The
@@ -37,6 +38,11 @@ class WrapperLifetimeCanary {
3738
public:
3839
static void Init(v8::Isolate* isolate);
3940

41+
// Gives a JS-extended class a -dealloc that reports its instances' deaths,
42+
// so their state needs no associated token or weak reference. No-op unless
43+
// the mode is canary.
44+
static void InstallDeallocHook(Class extendedClass);
45+
4046
// Installs the forwarding handlers on an ObjC instance template. No-op unless
4147
// the mode is canary.
4248
static void ConfigureInstanceTemplate(v8::Local<v8::ObjectTemplate> instanceTemplate);

‎NativeScript/runtime/WrapperLifetimeCanary.mm‎

Lines changed: 84 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#include "WrapperLifetimeCanary.h"
22
#import <Foundation/Foundation.h>
3+
#include <objc/message.h>
34
#include <objc/runtime.h>
45
#include <atomic>
56
#include <memory>
@@ -12,10 +13,12 @@
1213
#include "Helpers.h"
1314
#include "ObjectManager.h"
1415
#include "Runtime.h"
16+
#import "TNSDerivedClass.h"
1517
#include "WrapperLifetime.h"
1618

1719
// How canary mode learns that a native object with state was deallocated, so
18-
// its state can be let go of:
20+
// its state can be let go of. Instances of JS-extended classes are reported by
21+
// their class's own -dealloc (InstallDeallocHook) either way; for others:
1922
// - ASSOCIATION: a token associated with the object reports it from its
2023
// -dealloc, immediately and on any thread. The ObjC runtime aborts the
2124
// process for a class that forbids associated objects (no public query).
@@ -28,10 +31,8 @@
2831
#define NS_CANARY_DEATH_SIGNAL NS_CANARY_DEATH_ASSOCIATION
2932
#endif
3033

31-
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP
3234
extern "C" id objc_initWeakOrNil(id* location, id value);
3335
extern "C" void objc_destroyWeak(id* location);
34-
#endif
3536

3637
using namespace v8;
3738

@@ -45,20 +46,22 @@
4546
struct CanaryRecord {
4647
Global<Object> state;
4748
std::atomic<bool> died{false};
48-
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP
49-
// Zeroed by the ObjC runtime when the object is deallocated, on any thread.
49+
// Something reports this object's deallocation: a JS-extended class's
50+
// -dealloc, or the associated token. Otherwise only the weak reference below
51+
// tells, when a sweep reads it.
52+
bool reportsDeath = false;
53+
// An ObjC weak reference to the object, zeroed by the runtime when it is
54+
// deallocated, on any thread. Set for records nothing reports.
5055
id object = nil;
5156

5257
~CanaryRecord() { objc_destroyWeak(&object); }
5358

5459
// A racy read is enough: the slot only goes from the object to nil, and is
5560
// never dereferenced here.
5661
bool ObjectAlive() const {
57-
return __atomic_load_n(reinterpret_cast<void* const*>(&object), __ATOMIC_ACQUIRE) != nullptr;
62+
return reportsDeath ||
63+
__atomic_load_n(reinterpret_cast<void* const*>(&object), __ATOMIC_ACQUIRE) != nullptr;
5864
}
59-
#else
60-
bool ObjectAlive() const { return true; }
61-
#endif
6265
};
6366

6467
namespace {
@@ -89,7 +92,6 @@ bool ObjectAlive() const {
8992
std::shared_ptr<CanaryRegistry> registry = std::make_shared<CanaryRegistry>();
9093
};
9194

92-
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION
9395
void DrainDead(const std::shared_ptr<CanaryRegistry>& registry) {
9496
std::vector<std::shared_ptr<CanaryRecord>> dead;
9597
{
@@ -109,8 +111,11 @@ void DrainDead(const std::shared_ptr<CanaryRegistry>& registry) {
109111
}
110112
}
111113

112-
// From the token's -dealloc, on whichever thread deallocates the object.
114+
// From a reporter's -dealloc, on whichever thread deallocates the object.
113115
void NativeDied(const std::shared_ptr<CanaryRegistry>& registry, void* object) {
116+
if (registry->count.load(std::memory_order_relaxed) == 0) {
117+
return;
118+
}
114119
std::shared_ptr<EventLoop> loop;
115120
{
116121
std::lock_guard<std::mutex> lock(registry->mutex);
@@ -139,7 +144,35 @@ void NativeDied(const std::shared_ptr<CanaryRegistry>& registry, void* object) {
139144
registry->drainPosted = false;
140145
}
141146
}
142-
#endif
147+
148+
// Every isolate's registry, for the extended classes' -dealloc: an instance can
149+
// have state in an isolate other than the one that defined its class.
150+
std::mutex registriesMutex_;
151+
std::vector<std::weak_ptr<CanaryRegistry>> registries_;
152+
153+
void ReportDeallocToAllRegistries(void* object) {
154+
std::vector<std::shared_ptr<CanaryRegistry>> live;
155+
{
156+
std::lock_guard<std::mutex> lock(registriesMutex_);
157+
for (auto it = registries_.begin(); it != registries_.end();) {
158+
if (std::shared_ptr<CanaryRegistry> registry = it->lock()) {
159+
if (registry->count.load(std::memory_order_relaxed) > 0) {
160+
live.push_back(std::move(registry));
161+
}
162+
++it;
163+
} else {
164+
it = registries_.erase(it);
165+
}
166+
}
167+
}
168+
for (const std::shared_ptr<CanaryRegistry>& registry : live) {
169+
NativeDied(registry, object);
170+
}
171+
}
172+
173+
bool IsExtendedInstance(id object) {
174+
return [object_getClass(object) conformsToProtocol:@protocol(TNSDerivedClass)];
175+
}
143176

144177
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP
145178
// Lets go of the state of every object that was deallocated. Runs as an event
@@ -271,6 +304,8 @@ bool StateForWrite(Isolate* isolate, Local<Object> holder, Local<Object>* out) {
271304
}
272305
}
273306
id object = canary->lifetimeTarget_;
307+
// A JS-extended class's own -dealloc reports its instances' deaths.
308+
bool extended = IsExtendedInstance(object);
274309
bool created = false;
275310
{
276311
std::lock_guard<std::mutex> lock(registry->mutex);
@@ -284,13 +319,12 @@ bool StateForWrite(Isolate* isolate, Local<Object> holder, Local<Object>* out) {
284319
std::shared_ptr<CanaryRecord>& slot = registry->records[(__bridge void*)object];
285320
if (slot == nullptr) {
286321
auto record = std::make_shared<CanaryRecord>();
287-
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP
288-
if (objc_initWeakOrNil(&record->object, object) == nil) {
322+
record->reportsDeath = extended || NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION;
323+
if (!record->reportsDeath && objc_initWeakOrNil(&record->object, object) == nil) {
289324
// The class refuses weak references.
290325
registry->records.erase((__bridge void*)object);
291326
return false;
292327
}
293-
#endif
294328
record->state.Reset(isolate, Object::New(isolate, Null(isolate), nullptr, nullptr, 0));
295329
slot = std::move(record);
296330
registry->count.fetch_add(1, std::memory_order_relaxed);
@@ -300,12 +334,14 @@ bool StateForWrite(Isolate* isolate, Local<Object> holder, Local<Object>* out) {
300334
}
301335
if (created) {
302336
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION
303-
TNSCanaryLifecycleToken* token = [[TNSCanaryLifecycleToken alloc] init];
304-
token->registry_ = registry;
305-
token->object_ = (__bridge void*)object;
306-
objc_setAssociatedObject(object, &registry->associationKey, token,
307-
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
308-
[token release];
337+
if (!extended) {
338+
TNSCanaryLifecycleToken* token = [[TNSCanaryLifecycleToken alloc] init];
339+
token->registry_ = registry;
340+
token->object_ = (__bridge void*)object;
341+
objc_setAssociatedObject(object, &registry->associationKey, token,
342+
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
343+
[token release];
344+
}
309345
#endif
310346
if (ObjectManager::LifetimeStats* stats = ObjectManager::GetLifetimeStats(isolate)) {
311347
stats->canaryStates++;
@@ -480,12 +516,39 @@ void PostSweepAfterGC(Isolate* isolate, GCType, GCCallbackFlags) {
480516
if (Runtime* runtime = Runtime::GetRuntime(isolate)) {
481517
state->registry->loop = runtime->GetEventLoop();
482518
}
519+
{
520+
std::lock_guard<std::mutex> lock(registriesMutex_);
521+
registries_.push_back(state->registry);
522+
}
483523
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP
484524
isolate->AddGCPrologueCallback(
485525
PostSweepAfterGC, static_cast<GCType>(kGCTypeMarkSweepCompact | kGCTypeIncrementalMarking));
486526
#endif
487527
}
488528

529+
void WrapperLifetimeCanary::InstallDeallocHook(Class extendedClass) {
530+
if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) {
531+
return;
532+
}
533+
static std::mutex hookedMutex;
534+
static std::unordered_map<Class, bool> hooked;
535+
{
536+
std::lock_guard<std::mutex> lock(hookedMutex);
537+
if (hooked[extendedClass]) {
538+
return;
539+
}
540+
hooked[extendedClass] = true;
541+
}
542+
Class superclass = class_getSuperclass(extendedClass);
543+
IMP dealloc = imp_implementationWithBlock(^(id self) {
544+
ReportDeallocToAllRegistries((__bridge void*)self);
545+
struct objc_super super = {.receiver = self, .super_class = superclass};
546+
reinterpret_cast<void (*)(struct objc_super*, SEL)>(objc_msgSendSuper)(&super,
547+
@selector(dealloc));
548+
});
549+
class_addMethod(extendedClass, @selector(dealloc), dealloc, "v@:");
550+
}
551+
489552
void WrapperLifetimeCanary::ConfigureInstanceTemplate(Local<ObjectTemplate> instanceTemplate) {
490553
if (GetWrapperLifetimeMode() != WrapperLifetimeMode::kCanary) {
491554
return;

‎TestRunner/app/tests/WrapperLifetimeModesTests.js‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,31 @@ describe("Wrapper lifetime modes", function () {
374374
});
375375
});
376376

377+
// Plain objects have no class -dealloc of ours: an associated token or a
378+
// weak-reference sweep reports them.
379+
it("lets a plain native object's JS state go when the object is deallocated", function (done) {
380+
var owner = NSMutableArray.new();
381+
var before = runtime.getWrapperLifetimeStats();
382+
var watched;
383+
(function () {
384+
var obj = TNSAllocLog.new();
385+
obj.tag = "state";
386+
owner.addObject(obj);
387+
watched = watch(obj);
388+
})();
389+
settle(2, function () {
390+
owner.removeAllObjects();
391+
settle(3, function () {
392+
var after = runtime.getWrapperLifetimeStats();
393+
expect(alive(watched)).toBe(0);
394+
if (canary && scope === "all") {
395+
expect(after.canaryNativeDeaths).toBeGreaterThan(before.canaryNativeDeaths);
396+
}
397+
done();
398+
});
399+
});
400+
});
401+
377402
// The documented cost of the canary contract: state that references its own
378403
// object keeps the state, the object's wrapper and the native object alive
379404
// until native code would have released it anyway, which nothing does here.

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -254,15 +254,16 @@ that dies with its JS references, releasing the runtime's retain through the sam
254254
`kNonMasking` named interceptors on the instance templates forward JS properties to a
255255
null-prototype state object, so prototype members never reach them. The state is rooted from
256256
its first write until the native object is deallocated; a canary built later for the same
257-
object forwards to the same state. How the deallocation is noticed is a compile-time choice
257+
object forwards to the same state. Instances of JS-extended classes report their own
258+
deallocation: the runtime gives each extended class a `-dealloc` that tells every isolate's
259+
registry, then calls the superclass's. For other objects it is a compile-time choice
258260
(`NS_CANARY_DEATH_SIGNAL` in `WrapperLifetimeCanary.mm`): by default a token associated with the
259261
object reports it from its `-dealloc`, immediately and on any thread, but the ObjC runtime aborts
260262
the process for a class that forbids associated objects, and there is no public query for that;
261263
the alternative keeps an ObjC weak reference in each record (`objc_initWeakOrNil`, which declines
262264
instead of aborting for classes that refuse weak references) and sweeps the records after every
263265
major collection, so state lingers until then. With the default, `"scope": "all"` is
264-
experimental for that reason; with `"extended"` only instances of JS-extended classes get a
265-
token (the flag is inherited, so a JS subclass of a forbidding class would still abort). It cannot be
266+
experimental for that reason; `"extended"` attaches no tokens at all. It cannot be
266267
rooted at canary death instead, because a state reachable only through the canary is garbage in
267268
the same collection. The cost: state that references its own object (a closure over `this`)
268269
keeps it alive. A canary built after a death is a new object, but `===` cannot tell: only one

0 commit comments

Comments
 (0)