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>
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).
2831#define NS_CANARY_DEATH_SIGNAL NS_CANARY_DEATH_ASSOCIATION
2932#endif
3033
31- #if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP
3234extern " C" id objc_initWeakOrNil (id * location, id value);
3335extern " C" void objc_destroyWeak (id * location);
34- #endif
3536
3637using namespace v8 ;
3738
4546struct 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
6467namespace {
@@ -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
9395void 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.
113115void 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, ®istry->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, ®istry->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+
489552void WrapperLifetimeCanary::ConfigureInstanceTemplate (Local<ObjectTemplate> instanceTemplate) {
490553 if (GetWrapperLifetimeMode () != WrapperLifetimeMode::kCanary ) {
491554 return ;
0 commit comments