Skip to content

Commit f4ffacb

Browse files
committed
fix(runtime): canary mode gives no state to objects whose class forbids associated objects
objc_setAssociatedObject aborts the process for an instance of a class flagged RW_FORBIDS_ASSOCIATED_OBJECTS (Swift actors, for one). Under "scope": "all", a JS property write or a weak-collection key on such an object attached the canary's lifecycle token and terminated the app. StateForWrite now reads that flag on the object's class through objc_debug_class_rw_data_mask (resolved with dlsym) before creating a record, and declines when it is set or cannot be read: the object's JS properties stay on the canary and the weak collections key its wrapper, as WEAK_SWEEP already does for classes refusing weak references. Adds a fixture class flagged at runtime and a spec covering WeakMap, WeakSet, WeakRef, FinalizationRegistry and property writes on it, and extends the plain-object WeakMap/WeakRef spec to canary mode.
1 parent 2b4d85f commit f4ffacb

6 files changed

Lines changed: 119 additions & 11 deletions

File tree

‎NativeScript/runtime/WrapperLifetimeCanary.mm‎

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#include "WrapperLifetimeCanary.h"
22
#import <Foundation/Foundation.h>
3+
#include <dlfcn.h>
34
#include <objc/message.h>
45
#include <objc/runtime.h>
56
#include <atomic>
@@ -22,10 +23,14 @@
2223
// their class's own -dealloc (InstallDeallocHook) either way; for others:
2324
// - ASSOCIATION: a token associated with the object reports it from its
2425
// -dealloc, immediately and on any thread. The ObjC runtime aborts the
25-
// process for a class that forbids associated objects (no public query).
26+
// process for a class that forbids associated objects (Swift actors, for
27+
// one) and has no public query for it: ForbidsAssociatedObjects reads the
28+
// runtime's private flag instead.
2629
// - WEAK_SWEEP: each record holds a weak reference to the object, checked by a
27-
// sweep after every major collection, so state lingers until then. Classes
28-
// that refuse weak references keep their JS properties on the canary.
30+
// sweep after every major collection, so state lingers until then.
31+
// An object the chosen signal cannot watch (a class forbidding associated
32+
// objects, or refusing weak references) gets no state: its JS properties stay
33+
// on the canary and the weak collections key its wrapper.
2934
#define NS_CANARY_DEATH_ASSOCIATION 1
3035
#define NS_CANARY_DEATH_WEAK_SWEEP 2
3136
#ifndef NS_CANARY_DEATH_SIGNAL
@@ -222,6 +227,33 @@ bool IsExtendedInstance(id object) {
222227
return false;
223228
}
224229

230+
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION
231+
// The check objc_setAssociatedObject aborts on: RW_FORBIDS_ASSOCIATED_OBJECTS
232+
// in the class_rw_t flags of the object's own class, reached through the mask
233+
// libobjc exports for debuggers. Private layout (objc_class keeps `bits` after
234+
// isa, superclass and the cache; the flags lead class_rw_t), so anything it
235+
// cannot read, a missing mask or an unrealized class, counts as forbidding. Not
236+
// a message, as IsExtendedInstance.
237+
bool ForbidsAssociatedObjects(id object) {
238+
static const uintptr_t* rwDataMask =
239+
static_cast<const uintptr_t*>(dlsym(RTLD_DEFAULT, "objc_debug_class_rw_data_mask"));
240+
if (rwDataMask == nullptr) {
241+
return true;
242+
}
243+
struct ClassLayout {
244+
void* isa;
245+
void* superclass;
246+
void* cache[2];
247+
uintptr_t bits;
248+
};
249+
const auto* cls = static_cast<const ClassLayout*>((__bridge const void*)object_getClass(object));
250+
const auto* flags = reinterpret_cast<const uint32_t*>(cls->bits & *rwDataMask);
251+
constexpr uint32_t kRealized = 1u << 31;
252+
constexpr uint32_t kForbidsAssociatedObjects = 1u << 20;
253+
return flags == nullptr || (*flags & kRealized) == 0 || (*flags & kForbidsAssociatedObjects) != 0;
254+
}
255+
#endif
256+
225257
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_WEAK_SWEEP
226258
// Lets go of the state of every object that was deallocated. Runs as an event
227259
// loop task (under the Locker, on the runtime's thread), never inside the GC.
@@ -453,6 +485,11 @@ bool StateForWrite(Isolate* isolate, Local<Object> holder, Local<Object>* out) {
453485
bool replacesDied = canary->canaryRecord_ != nullptr;
454486
// A JS-extended class's own -dealloc reports its instances' deaths.
455487
bool extended = IsExtendedInstance(object);
488+
#if NS_CANARY_DEATH_SIGNAL == NS_CANARY_DEATH_ASSOCIATION
489+
if (!extended && ForbidsAssociatedObjects(object)) {
490+
return false;
491+
}
492+
#endif
456493
// Allocated before the lock: a collection this allocation starts can run
457494
// callbacks (the weak sweep's, a finalizer's -dealloc) that take it.
458495
Local<Object> freshState = Object::New(isolate, Null(isolate), nullptr, nullptr, 0);

‎TestFixtures/Marshalling/TNSAllocLog.h‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,4 +248,15 @@ id TNSOwnedPrimitivesObjectAt(TNSOwnedPrimitives* holder, NSUInteger index);
248248

249249
@end
250250

251+
// Hands out instances of a class made at runtime and flagged the way the ObjC
252+
// runtime flags Swift actors: objc_setAssociatedObject on one aborts the
253+
// process.
254+
@interface TNSAssociationForbidder : NSObject
255+
256+
+ (id)forbiddingInstance;
257+
// Whether the class of `object` carries that flag.
258+
+ (BOOL)forbidsAssociatedObjects:(id)object;
259+
260+
@end
261+
251262
#endif /* TNSAllocLog_h */

‎TestFixtures/Marshalling/TNSAllocLog.m‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#import "TNSAllocLog.h"
22
#import <objc/message.h>
3+
#import <objc/runtime.h>
34
#import "../TNSTestCommon.h"
45

56
@implementation TNSAllocLog
@@ -488,3 +489,33 @@ + (void)hookPlaceholder {
488489
}
489490

490491
@end
492+
493+
extern uintptr_t objc_debug_class_rw_data_mask;
494+
495+
// RW_FORBIDS_ASSOCIATED_OBJECTS, in the class_rw_t flags objc_class reaches
496+
// through `bits`, after isa, superclass and the cache.
497+
static const uint32_t TNSForbidsAssociatedObjectsFlag = 1u << 20;
498+
499+
static uint32_t* TNSClassRWFlags(Class cls) {
500+
uintptr_t bits = ((const uintptr_t*)(__bridge const void*)cls)[4];
501+
return (uint32_t*)(bits & objc_debug_class_rw_data_mask);
502+
}
503+
504+
@implementation TNSAssociationForbidder
505+
506+
+ (id)forbiddingInstance {
507+
static Class forbidding;
508+
static dispatch_once_t once;
509+
dispatch_once(&once, ^{
510+
forbidding = objc_allocateClassPair([NSObject class], "TNSAssociationForbiddingObject", 0);
511+
*TNSClassRWFlags(forbidding) |= TNSForbidsAssociatedObjectsFlag;
512+
objc_registerClassPair(forbidding);
513+
});
514+
return [[forbidding alloc] init];
515+
}
516+
517+
+ (BOOL)forbidsAssociatedObjects:(id)object {
518+
return (*TNSClassRWFlags(object_getClass(object)) & TNSForbidsAssociatedObjectsFlag) != 0;
519+
}
520+
521+
@end

‎TestRunner/app/tests/WrapperLifetimeModesTests.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ describe("Wrapper lifetime modes", function () {
136136
});
137137
});
138138

139-
it("keeps WeakMap entries and WeakRef targets of natively owned objects when every wrapper is rooted", function (done) {
139+
it("keeps WeakMap entries and WeakRef targets of natively owned objects when every wrapper is in scope", function (done) {
140140
var owner = NSMutableArray.new();
141141
var map = new WeakMap();
142142
var ref;
@@ -148,7 +148,7 @@ describe("Wrapper lifetime modes", function () {
148148
})();
149149
settle(2, function () {
150150
var obj = owner.objectAtIndex(0);
151-
if (rooted && scope === "all") {
151+
if (keepsState && scope === "all") {
152152
expect(map.get(obj)).toBe("value");
153153
expect(ref.deref()).toBe(obj);
154154
}

‎TestRunner/app/tests/WrapperLifetimeWeakCollectionsTests.js‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,31 @@ describe("Weak collections of native objects", function () {
244244
});
245245
});
246246

247+
// Under canary mode such an object gets no state: the token that would
248+
// report its deallocation cannot be associated with it.
249+
it("keys an object whose class forbids associated objects by its wrapper", function () {
250+
var obj = TNSAssociationForbidder.forbiddingInstance();
251+
expect(TNSAssociationForbidder.forbidsAssociatedObjects(obj)).toBe(true);
252+
var before = runtime.getWrapperLifetimeStats();
253+
var map = new WeakMap();
254+
map.set(obj, "value");
255+
expect(map.get(obj)).toBe("value");
256+
var set = new WeakSet();
257+
set.add(obj);
258+
expect(set.has(obj)).toBe(true);
259+
expect(new WeakRef(obj).deref()).toBe(obj);
260+
var registry = new FinalizationRegistry(function () {});
261+
registry.register(obj, "held", obj);
262+
expect(registry.unregister(obj)).toBe(true);
263+
obj.tag = "kept";
264+
Object.defineProperty(obj, "defined", { value: 1, configurable: true });
265+
expect(obj.tag).toBe("kept");
266+
expect(obj.defined).toBe(1);
267+
if (canary) {
268+
expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(before.canaryStates);
269+
}
270+
});
271+
247272
it("keeps working as the standard collections for other keys", function () {
248273
var key = {};
249274
var map = new WeakMap([[key, 1]]);

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

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -288,17 +288,21 @@ inherits, whose receiver still reads the state), and then retires them. For othe
288288
a compile-time choice (`NS_CANARY_DEATH_SIGNAL` in `WrapperLifetimeCanary.mm`): by default a
289289
token associated with the
290290
object reports it from its `-dealloc`, immediately and on any thread, but the ObjC runtime aborts
291-
the process for a class that forbids associated objects, and there is no public query for that.
292-
Code that calls `objc_removeAssociatedObjects` on a live object releases the token too, which
291+
the process for a class that forbids associated objects (Swift actors, for one), and there is no
292+
public query for that. The runtime checks the flag `objc_setAssociatedObject` aborts on
293+
(`RW_FORBIDS_ASSOCIATED_OBJECTS` in the object's class's `class_rw_t`, reached through the
294+
`objc_debug_class_rw_data_mask` libobjc exports for debuggers) before it attaches a token; an
295+
object it flags, or whose class it cannot read, gets no state: its JS properties stay on the
296+
canary and are gone after a replacement, and the weak collections key its wrapper. Code that
297+
calls `objc_removeAssociatedObjects` on a live object releases the token too, which
293298
retires the state as if the object had died: the next write through the canary starts a new
294299
state from the canary's properties, but if the canary dies before such a write, a canary built
295300
later starts without them. The alternative keeps an ObjC weak reference in each record
296301
(`objc_initWeakOrNil`, which declines instead of aborting for classes that refuse weak
297302
references) and sweeps the records after every major collection, so state lingers until then.
298303
An instance of a class that refuses weak references and is not JS-extended gets no state
299-
under it: its properties live on the canary alone and are gone after a replacement. With the
300-
default, `"scope": "all"` is experimental because of that abort; `"extended"` attaches no
301-
tokens at all. It cannot be
304+
under it, in the same way. With the default, `"scope": "all"` stays experimental because that
305+
check reads private runtime layout; `"extended"` attaches no tokens at all. It cannot be
302306
rooted at canary death instead, because a state reachable only through the canary is garbage in
303307
the same collection. The cost: state that references its own object (a closure over `this`)
304308
keeps it alive. A canary built after a death is a new object, but `===` cannot tell: only one
@@ -307,7 +311,7 @@ What could notice is whatever keys on the canary without keeping it. The weak co
307311
don't: in canary mode a builtin (`js/weak-collections.js`) replaces `WeakMap`, `WeakSet`,
308312
`WeakRef` and `FinalizationRegistry` with subclasses that key an in-scope native object (a
309313
canary: not a plain object under `"extended"`, a tagged pointer, a block, or an object of a class
310-
refusing weak references) by an opaque, frozen key held by its state, so entries and targets live
314+
refusing weak references or forbidding associated objects) by an opaque, frozen key held by its state, so entries and targets live
311315
exactly as long as the native object, and `WeakRef.prototype.deref` returns the live canary, a new
312316
one, or `undefined` once the object is gone. Lookups never create that key, and a Proxy around a
313317
native object stays a key of its own. The cost is the other side of the same rooting: a `WeakMap`

0 commit comments

Comments
 (0)