Skip to content

Commit af2d1c6

Browse files
committed
fix(runtime): protect a re-wrapped instance only when its class unprotects again
A wrapper that takes over a waiting release catches up on the protection a native retain would have given it. That protection is undone by the swizzled -release, which only __extends classes carry; an .extend() class conforms to TNSDerivedClass too, so its instance stayed protected and was never collected. The check now asks for the swizzle itself, through the superclass chain, so an observed instance of such a class is covered as well.
1 parent 06c7ba8 commit af2d1c6

9 files changed

Lines changed: 134 additions & 19 deletions

File tree

‎NativeScript/runtime/Caches.h‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,9 @@ class Caches {
118118
return cache->GetOrCreateState<T>();
119119
}
120120

121-
// Teardown only: the existing state, even after InvalidateIsolate, for a
122-
// subsystem that must finish work its state still holds. Never creates.
121+
// The existing state, even after InvalidateIsolate, for a subsystem that
122+
// must finish work its state still holds. Never creates, so a state made on
123+
// the isolate's thread can be read from any thread holding the Locker.
123124
template <typename T>
124125
static T* ExistingStateFor(v8::Isolate* isolate) {
125126
auto raw = isolate->GetData(0);

‎NativeScript/runtime/ClassBuilder.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ class ClassBuilder {
4242
const char* fallback);
4343
// `klass` or its nearest superclass not defined from JS.
4444
static Class FindNativeClass(Class klass);
45+
// Whether instances of `klass` run the -retain/-release pair that protects
46+
// and unprotects their wrapper, inherited ones included.
47+
static bool TracksNativeRetains(Class klass);
4548
// The implementation of `method` from FindNativeClass(klass).
4649
static IMP FindNotOverridenMethod(Class klass, SEL method);
4750
// Whether `klass`, not one of its superclasses, implements `selector`.

‎NativeScript/runtime/ClassBuilder.mm‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
405405
release(self, @selector(release));
406406
});
407407
class_addMethod(extendedClass, @selector(release), newRelease, "v@:");
408+
class_addProtocol(extendedClass, @protocol(TNSRetainTrackedClass));
408409

409410
info.GetReturnValue().SetUndefined();
410411
}).ToLocalChecked();
@@ -1101,6 +1102,15 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
11011102
return klass;
11021103
}
11031104

1105+
bool ClassBuilder::TracksNativeRetains(Class klass) {
1106+
for (; klass != nil; klass = class_getSuperclass(klass)) {
1107+
if (class_conformsToProtocol(klass, @protocol(TNSRetainTrackedClass))) {
1108+
return true;
1109+
}
1110+
}
1111+
return false;
1112+
}
1113+
11041114
IMP ClassBuilder::FindNotOverridenMethod(Class klass, SEL method) {
11051115
return class_getMethodImplementation(FindNativeClass(klass), method);
11061116
}

‎NativeScript/runtime/DataWrapper.h‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -399,10 +399,10 @@ class UnmanagedTypeWrapper : public BaseDataWrapper {
399399
class ObjCDataWrapper : public BaseDataWrapper {
400400
public:
401401
ObjCDataWrapper(id data, const TypeEncoding* typeEncoding = nullptr)
402-
: data_(data),
402+
: bornOnRuntimeThread_(OnRuntimeThreadOf(v8::Isolate::TryGetCurrent())),
403+
data_(data),
403404
typeEncoding_(typeEncoding),
404-
klass_(object_getClass(data)),
405-
bornOnRuntimeThread_(OnRuntimeThreadOf(v8::Isolate::TryGetCurrent())) {}
405+
klass_(object_getClass(data)) {}
406406

407407
const WrapperType Type() { return WrapperType::ObjCObject; }
408408

@@ -442,11 +442,11 @@ class ObjCDataWrapper : public BaseDataWrapper {
442442
private:
443443
bool adapterClaim_ = false;
444444
bool borrowed_ = false;
445+
bool bornOnRuntimeThread_;
445446
ObjectWeakCallbackState* ownershipState_ = nullptr;
446447
id data_;
447448
const tns::TypeEncoding* typeEncoding_;
448449
Class klass_;
449-
bool bornOnRuntimeThread_;
450450
};
451451

452452
class ObjCClassWrapper : public BaseDataWrapper {

‎NativeScript/runtime/ObjectManager.h‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,10 @@ class ObjectManager {
7070
// release over as its own retain instead of retaining again; returns whether
7171
// it did. Once the entry's retain is settled, call ProtectIfNativelyRetained.
7272
static bool TakeDeferredRelease(v8::Isolate* isolate, id obj);
73-
// An extended class protects its wrapper when native code first retains the
74-
// object past the runtime's own retain. A native retain made while a release
75-
// waited found no wrapper to protect; this catches up.
73+
// A class that tracks native retains (ClassBuilder::TracksNativeRetains)
74+
// protects its wrapper when native code first retains the object past the
75+
// runtime's own retain. A native retain made while a release waited found no
76+
// wrapper to protect; this catches up.
7677
static void ProtectIfNativelyRetained(id obj, ObjCDataWrapper* wrapper);
7778

7879
private:

‎NativeScript/runtime/ObjectManager.mm‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
#include "EventLoop.h"
1313
#include "Helpers.h"
1414
#include "Runtime.h"
15-
#include "TNSDerivedClass.h"
1615

1716
using namespace v8;
1817
using namespace std;
@@ -112,9 +111,9 @@ void UnlinkRegistered(ObjectWeakCallbackState* state) {
112111
// Objects first wrapped on another thread are still released where the
113112
// collection runs.
114113
//
115-
// Every access holds the isolate's Locker: finalizers and
116-
// __releaseNativeCounterpart on any thread, and on the runtime's thread the
117-
// drain task, wrapper creation and teardown. So no other synchronization.
114+
// Every access holds the isolate's Locker: finalizers,
115+
// __releaseNativeCounterpart and wrapper creation on any thread, and on the
116+
// runtime's thread the drain task and teardown. So no other synchronization.
118117
struct DeferredReleases {
119118
// Object -> releases it is owed. An object stays alive while it is owed one,
120119
// so its address cannot be reused by another object meanwhile.
@@ -380,8 +379,8 @@ void DisposeHandle(v8::Isolate* isolate,
380379
}
381380

382381
void ObjectManager::ProtectIfNativelyRetained(id obj, ObjCDataWrapper* wrapper) {
383-
if (class_conformsToProtocol(object_getClass(obj), @protocol(TNSDerivedClass)) &&
384-
[obj retainCount] > 1) {
382+
// Only a class whose -release unprotects again may be protected here.
383+
if (ClassBuilder::TracksNativeRetains(object_getClass(obj)) && [obj retainCount] > 1) {
385384
wrapper->GcProtect();
386385
}
387386
}

‎NativeScript/runtime/TNSDerivedClass.h‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,11 @@
55

66
@end
77

8+
// Adopted by a derived class whose -retain and -release tell its instance's
9+
// wrapper when native code starts and stops owning the object. Subclasses
10+
// inherit those methods but not the conformance.
11+
@protocol TNSRetainTrackedClass
12+
13+
@end
14+
815
#endif /* TNSDerivedClass_h */

‎TestRunner/app/tests/GCFinalizerTests.js‎

Lines changed: 91 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,21 +46,25 @@ describe("GC finalizer callbacks", function () {
4646
}
4747
}, { name: "TNSApiDeallocThread" });
4848

49-
// Owned only through its wrapper, so its finalizer releases it.
50-
(function () {
51-
DeallocThread.alloc().init();
52-
})();
49+
// Owned only through its wrapper, so its finalizer releases it. Held
50+
// until the background block, so no collection on the main thread
51+
// gets to it first.
52+
var keep = DeallocThread.alloc().init();
5353

54+
var deallocsInBlock = -1;
5455
var queue = dispatch_get_global_queue(qos_class_t.QOS_CLASS_DEFAULT, 0);
5556
dispatch_async(queue, function () {
57+
keep = null;
5658
scrubStack();
5759
__collect();
5860
__collect();
61+
deallocsInBlock = threads.length;
5962
});
6063

6164
var attempts = 200;
6265
(function poll() {
6366
if (threads.length > 0 || --attempts === 0) {
67+
expect(deallocsInBlock).toBe(0);
6468
expect(threads).toEqual([true]);
6569
done();
6670
return;
@@ -100,6 +104,89 @@ describe("GC finalizer callbacks", function () {
100104
})();
101105
});
102106

107+
// A wrapper built for an object whose release still waits for the
108+
// runtime's thread adopts that release as its own retain. The block below
109+
// holds the Locker throughout, so the release cannot run in between.
110+
[
111+
{
112+
suffix: " (extend)",
113+
// No retain/release swizzle: natively held instances are not kept.
114+
keepsWrapper: false,
115+
define: function (onDealloc) {
116+
return TNSApi.extend({ methodCalledInDealloc: onDealloc }, { name: "TNSApiReleaseTakeover" });
117+
}
118+
},
119+
{
120+
suffix: " (__extends)",
121+
keepsWrapper: true,
122+
define: function (onDealloc) {
123+
return (function (_super) {
124+
__extends(TNSApiReleaseTakeoverTS, _super);
125+
function TNSApiReleaseTakeoverTS() {
126+
return (_super !== null && _super.apply(this, arguments)) || this;
127+
}
128+
TNSApiReleaseTakeoverTS.prototype.methodCalledInDealloc = onDealloc;
129+
return TNSApiReleaseTakeoverTS;
130+
})(TNSApi);
131+
}
132+
}
133+
].forEach(function (variant) {
134+
it("hands a waiting release to the wrapper that replaces it" + variant.suffix, function (done) {
135+
var threads = [];
136+
var Klass = variant.define(function () {
137+
threads.push(NSThread.isMainThread);
138+
});
139+
140+
var holder = NSMutableArray.alloc().init();
141+
(function () {
142+
holder.addObject(Klass.alloc().init());
143+
})();
144+
145+
var retainCount = -1;
146+
var queue = dispatch_get_global_queue(qos_class_t.QOS_CLASS_DEFAULT, 0);
147+
dispatch_async(queue, function () {
148+
__releaseNativeCounterpart(holder.objectAtIndex(0));
149+
var again = holder.objectAtIndex(0);
150+
again.marker = "kept";
151+
// The holder's reference and the adopted one.
152+
retainCount = again.retainCount();
153+
});
154+
155+
function collectAndWait(rounds, callback) {
156+
scrubStack();
157+
__collect();
158+
__collect();
159+
setTimeout(function () {
160+
if (rounds > 1) {
161+
collectAndWait(rounds - 1, callback);
162+
} else {
163+
callback();
164+
}
165+
}, 10);
166+
}
167+
168+
var attempts = 200;
169+
(function poll() {
170+
if (retainCount === -1 && --attempts > 0) {
171+
setTimeout(poll, 10);
172+
return;
173+
}
174+
expect(retainCount).toBe(2);
175+
collectAndWait(2, function () {
176+
expect(threads).toEqual([]);
177+
if (variant.keepsWrapper) {
178+
expect(holder.objectAtIndex(0).marker).toBe("kept");
179+
}
180+
holder.removeAllObjects();
181+
collectAndWait(3, function () {
182+
expect(threads).toEqual([true]);
183+
done();
184+
});
185+
});
186+
})();
187+
});
188+
});
189+
103190
// A GcProtected (natively retained) instance is resurrected by its
104191
// finalizer, but anything reachable only through it is queued in the same
105192
// GC and disposed — the resurrected parent then holds "husks" whose

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,13 @@ whose release is still queued takes that release over (keeping the retain counts
147147
classes' swizzle reads exact). Teardown drains the queue inline, since the event loop has stopped
148148
by then. For a worker, the runtime's thread is the worker's own thread, not the main thread.
149149

150+
While a release is queued the object is alive without a wrapper, where an inline release would
151+
have deallocated it and zeroed the weak references to it. A native callback reaching it in that
152+
window (a delegate method through a weak reference) builds a new wrapper, which takes the queued
153+
release over: the JS override runs on a blank `this`, without the state the collected wrapper
154+
held, and the object then lives as long as that new wrapper. Only an object that nothing but its
155+
wrapper owned, collected off the runtime's thread, has this window.
156+
150157
## Deliberate deviations from upstream's original
151158

152159
- **No `PENDING` state, no `NEAR_DEATH` for finalizers.** 14.9's `NodeState` is 2 bits with all

0 commit comments

Comments
 (0)