Skip to content

Commit dcaf058

Browse files
authored
fix(runtime): release owned instance-method returns that hit a cached wrapper (#569)
Caches::Instances holds one retain per wrapped native object, so a result the caller owns (+1) that already has a JS wrapper carries a surplus reference. Interop::GetResult released it only for class methods and C functions. For instance methods the object leaked one retain per call: immutable.copy(), and X.alloc().init...() whenever the object got wrapped during the initializer (a JS initializer, or a native one calling a JS method on it), which meant those objects were never freed. Instance methods had been left out because JS implementations handed their results to native code at +0, so an owned return carried no real +1. That was a bug of its own: a native caller of a JS copyWithZone:, mutableCopyWithZone:, new-family method or owned-return getter released an object it did not own. - JS implementations hand owned results to native callers at +1 (ArgConverter::RetainOwnedResult): always for the copy, mutableCopy and new families and metadata-flagged owned returns, and for initializers and -awakeAfterUsingCoder: when the result is not the receiver. The classification comes from the method's metadata, or from the selector's method family where there is none, and is stored on the MethodCallbackWrapper. JS property getters take the same path. - Interop::ReleasesCachedOwnedReturn is the one rule for dropping a surplus +1, used by GetResult and ConstructObject: release unless the call consumed a receiver that existed before it. An initializer on a receiver allocated for the call releases whatever it answers, which is only balanced because JS initializers retain a non-receiver result. - -unarchiver:didDecodeObject: consumes its object argument and returns retained (Interop::ConsumesArgument, ReturnsRetained). A JS implementation that answers the argument is neither retained nor released; one that answers anything else has its result retained and the argument released, also on MethodCallback's early returns. A call from JS to a native implementation retains the argument it passes. - Owned results that JS receives as primitives (string, number, date, boolean, null) and owned block results release their +1 once the runtime holds what it keeps. For a JS function's own block that release can be the last reference and run the dispose helper inline. - ArgConverter::SetValue reports whether it wrote an object the caller does not own. Inferring that from the JS value afterwards retained a new DictionaryAdapter a second time, because the adapter attaches a wrapper to the object it adapts. - ConstructObject reads the cached handle before releasing: the release can be an adapter's last reference, which resets the handle. JS implementations of owned-return methods now return +1 to native callers, as ARC callers always assumed. A caller that ignores the method family (performSelector:, KVC) on a JS method exposed under a copy, mutableCopy or new name leaks one retain per call, as it does for a native method with such a name. Fixes #566
1 parent 84e49f0 commit dcaf058

10 files changed

Lines changed: 1431 additions & 99 deletions

File tree

‎NativeScript/runtime/ArgConverter.h‎

Lines changed: 38 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,23 +13,38 @@ namespace tns {
1313

1414
class ArgConverter;
1515

16+
// What native callers of a JS-implemented method own of the object it answers.
17+
enum class NativeReturnOwnership : uint8_t {
18+
Unowned,
19+
// A +1; the receiver stays the caller's.
20+
Owned,
21+
// A +1 in place of the receiver, whose reference the caller passed in.
22+
ReplacesReceiver,
23+
};
24+
1625
struct MethodCallbackWrapper {
1726
public:
18-
MethodCallbackWrapper(v8::Isolate* isolate,
19-
std::shared_ptr<v8::Persistent<v8::Value>> callback,
20-
const uint8_t initialParamIndex,
21-
const uint8_t paramsCount,
22-
const TypeEncoding* typeEncoding)
27+
MethodCallbackWrapper(
28+
v8::Isolate* isolate, std::shared_ptr<v8::Persistent<v8::Value>> callback,
29+
const uint8_t initialParamIndex, const uint8_t paramsCount,
30+
const TypeEncoding* typeEncoding,
31+
NativeReturnOwnership returnOwnership = NativeReturnOwnership::Unowned,
32+
int8_t consumedArgumentIndex = -1)
2333
: isolateWrapper_(isolate),
2434
callback_(callback),
2535
initialParamIndex_(initialParamIndex),
2636
paramsCount_(paramsCount),
27-
typeEncoding_(typeEncoding) {}
37+
typeEncoding_(typeEncoding),
38+
returnOwnership_(returnOwnership),
39+
consumedArgumentIndex_(consumedArgumentIndex) {}
2840
IsolateWrapper isolateWrapper_;
2941
std::shared_ptr<v8::Persistent<v8::Value>> callback_;
3042
const uint8_t initialParamIndex_;
3143
const uint8_t paramsCount_;
3244
const TypeEncoding* typeEncoding_;
45+
const NativeReturnOwnership returnOwnership_;
46+
// Interop::ConsumedObjectArgumentIndex of the implemented method.
47+
const int8_t consumedArgumentIndex_;
3348
};
3449

3550
class ArgConverter {
@@ -75,9 +90,24 @@ class ArgConverter {
7590
static const ProtocolMeta* FindProtocolMeta(Protocol* protocol);
7691
static void MethodCallback(ffi_cif* cif, void* retValue, void** argValues,
7792
void* userData);
93+
// For a JS implementation of the instance method `selector`; `meta` is null
94+
// for methods the metadata does not describe, which are classified by
95+
// their selector's method family.
96+
static NativeReturnOwnership ReturnOwnership(SEL selector,
97+
const MethodMeta* meta);
98+
// Gives the native caller of a JS implementation the reference it owns of
99+
// the object SetValue wrote into retValue; `writtenUnowned` is what
100+
// SetValue answered. `consumedArgument`, an argument the method took over,
101+
// already carries that reference when it is the result.
102+
static void RetainOwnedResult(NativeReturnOwnership ownership,
103+
void** argValues, void* retValue,
104+
bool writtenUnowned, id consumedArgument = nil);
78105
// returnSize is the ABI size of the return slot (cif->rtype->size); an
79-
// empty, null or undefined value zeroes all of it.
80-
static void SetValue(v8::Local<v8::Context> context, void* retValue,
106+
// empty, null or undefined value zeroes all of it. Answers whether it wrote
107+
// an object the caller does not own: a wrapped object, or a string made
108+
// for an id or interface slot. A plain JS object is written as a new
109+
// DictionaryAdapter the caller owns.
110+
static bool SetValue(v8::Local<v8::Context> context, void* retValue,
81111
size_t returnSize, v8::Local<v8::Value> value,
82112
const TypeEncoding* typeEncoding);
83113
// Returns (lazily creating) the per-isolate interop.escapeException brand

‎NativeScript/runtime/ArgConverter.mm‎

Lines changed: 84 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -36,45 +36,16 @@ bool IsDeallocating(id obj) {
3636
return !((BOOL (*)(id, SEL))imp)(obj, allowsWeakReference);
3737
}
3838

39-
// Clang's init method family: optional leading underscores, then "init", then
40-
// the end of the selector's first piece or anything but a lowercase letter.
41-
bool IsInitFamily(SEL selector) {
39+
// Clang's method family rule: optional leading underscores, then the family
40+
// name, then the end of the selector's first piece or anything but a
41+
// lowercase letter.
42+
bool InMethodFamily(SEL selector, const char* family) {
4243
const char* name = sel_getName(selector);
4344
while (*name == '_') {
4445
name++;
4546
}
46-
return strncmp(name, "init", 4) == 0 && (name[4] < 'a' || name[4] > 'z');
47-
}
48-
49-
// The native caller of an init-family method owns its result. SetValue hands
50-
// a wrapped object or a string over at +0: for the receiver that is the
51-
// reference the caller passed in, any other object needs its own. The
52-
// receiver is left alone: when a super initializer substituted it, that
53-
// initializer already released it, and nothing here can tell that case apart.
54-
void RetainInitializerResult(Isolate* isolate, void** argValues, void* retValue,
55-
const TypeEncoding* typeEncoding, Local<Value> value) {
56-
BinaryTypeEncodingType type = typeEncoding->type;
57-
if (type != BinaryTypeEncodingType::IdEncoding &&
58-
type != BinaryTypeEncodingType::InterfaceDeclarationReference &&
59-
type != BinaryTypeEncodingType::InstanceTypeEncoding) {
60-
return;
61-
}
62-
63-
id returned = *static_cast<id*>(retValue);
64-
if (returned == nil || returned == *static_cast<id*>(argValues[0]) ||
65-
!IsInitFamily(*static_cast<SEL*>(argValues[1]))) {
66-
return;
67-
}
68-
69-
// A plain JS object becomes a DictionaryAdapter SetValue already returns
70-
// at +1.
71-
value = tns::UnwrapProxy(value);
72-
BaseDataWrapper* wrapper = value->IsObject() ? tns::GetValue(isolate, value) : nullptr;
73-
bool atPlusZero =
74-
value->IsString() || (wrapper != nullptr && wrapper->Type() == WrapperType::ObjCObject);
75-
if (atPlusZero) {
76-
[returned retain];
77-
}
47+
size_t length = strlen(family);
48+
return strncmp(name, family, length) == 0 && (name[length] < 'a' || name[length] > 'z');
7849
}
7950

8051
// The borrowed wrapper WrapNativeCallbackSelf made for an object in -dealloc
@@ -192,7 +163,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
192163
target = [allocKlass alloc];
193164
}
194165

195-
ObjCMethodCall methodCall(context, meta, target, klass, args, callSuper);
166+
ObjCMethodCall methodCall(context, meta, target, klass, args, callSuper, allocKlass != nil);
196167
return Interop::CallFunction(methodCall);
197168
}
198169

@@ -364,6 +335,11 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
364335

365336
void ArgConverter::MethodCallback(ffi_cif* cif, void* retValue, void** argValues, void* userData) {
366337
MethodCallbackWrapper* data = static_cast<MethodCallbackWrapper*>(userData);
338+
// Owned by this call, which gives it up on every path unless it answers it.
339+
id consumedArgument =
340+
data->consumedArgumentIndex_ < 0
341+
? nil
342+
: *static_cast<id*>(argValues[data->initialParamIndex_ + data->consumedArgumentIndex_]);
367343

368344
Isolate* isolate = data->isolateWrapper_.Isolate();
369345

@@ -380,6 +356,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
380356
IsolatePin pin = data->isolateWrapper_.Pin();
381357
if (!pin || !data->isolateWrapper_.IsValid()) {
382358
memset(retValue, 0, cif->rtype->size);
359+
[consumedArgument release];
383360
return;
384361
}
385362

@@ -391,6 +368,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
391368
// what makes this second look reliable.
392369
if (!data->isolateWrapper_.IsValid()) {
393370
memset(retValue, 0, cif->rtype->size);
371+
[consumedArgument release];
394372
return;
395373
}
396374
Isolate::Scope isolate_scope(isolate);
@@ -512,25 +490,65 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
512490
if (!success) {
513491
memset(retValue, 0, cif->rtype->size);
514492
} else {
515-
ArgConverter::SetValue(context, retValue, cif->rtype->size, result, data->typeEncoding_);
516-
if (data->initialParamIndex_ == 2) {
517-
RetainInitializerResult(isolate, argValues, retValue, data->typeEncoding_, result);
518-
}
493+
bool writtenUnowned = ArgConverter::SetValue(context, retValue, cif->rtype->size, result,
494+
data->typeEncoding_);
495+
ArgConverter::RetainOwnedResult(data->returnOwnership_, argValues, retValue, writtenUnowned,
496+
consumedArgument);
519497
}
520498
} else {
521499
memset(retValue, 0, cif->rtype->size);
522500
}
501+
502+
// A wrapper JS made for the consumed argument holds a reference of its own.
503+
if (consumedArgument != nil && !(Interop::IsObjectEncoding(data->typeEncoding_) &&
504+
*static_cast<id*>(retValue) == consumedArgument)) {
505+
[consumedArgument release];
506+
}
523507
} // all V8 scopes destruct here
524508

525509
if (pendingThrow != nil) {
526510
@throw pendingThrow;
527511
}
528512
}
529513

530-
void ArgConverter::SetValue(Local<Context> context, void* retValue, size_t returnSize,
514+
// An owned result SetValue wrote at +0 gets a reference of its own, except a
515+
// receiver answered in place of itself: that is the reference the caller
516+
// passed in. The receiver is never released when another object is answered
517+
// instead: a super initializer that substituted it already did, and nothing
518+
// here can tell that case apart.
519+
void ArgConverter::RetainOwnedResult(NativeReturnOwnership ownership, void** argValues,
520+
void* retValue, bool writtenUnowned, id consumedArgument) {
521+
if (ownership == NativeReturnOwnership::Unowned || !writtenUnowned) {
522+
return;
523+
}
524+
525+
id returned = *static_cast<id*>(retValue);
526+
if (returned == nil || returned == consumedArgument ||
527+
(ownership == NativeReturnOwnership::ReplacesReceiver &&
528+
returned == *static_cast<id*>(argValues[0]))) {
529+
return;
530+
}
531+
532+
[returned retain];
533+
}
534+
535+
NativeReturnOwnership ArgConverter::ReturnOwnership(SEL selector, const MethodMeta* meta) {
536+
bool isInitializer = meta != nullptr ? meta->isInitializer() : InMethodFamily(selector, "init");
537+
if (Interop::ConsumesReceiver(selector, isInitializer)) {
538+
return NativeReturnOwnership::ReplacesReceiver;
539+
}
540+
541+
bool owned = meta != nullptr
542+
? meta->ownsReturnedCocoaObject()
543+
: InMethodFamily(selector, "copy") || InMethodFamily(selector, "mutableCopy") ||
544+
InMethodFamily(selector, "new") || Interop::ReturnsRetained(selector);
545+
return owned ? NativeReturnOwnership::Owned : NativeReturnOwnership::Unowned;
546+
}
547+
548+
bool ArgConverter::SetValue(Local<Context> context, void* retValue, size_t returnSize,
531549
Local<Value> value, const TypeEncoding* typeEncoding) {
532550
if (typeEncoding->type == BinaryTypeEncodingType::VoidEncoding) {
533-
return;
551+
return false;
534552
}
535553

536554
// Runs inside an ffi closure, where a C++ throw cannot propagate; a revoked
@@ -540,7 +558,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
540558
value = tns::UnwrapProxy(value);
541559
if (value.IsEmpty() || value->IsNullOrUndefined()) {
542560
memset(retValue, 0, std::max(returnSize, sizeof(ffi_arg)));
543-
return;
561+
return false;
544562
}
545563

546564
Isolate* isolate = v8::Isolate::GetCurrent();
@@ -551,52 +569,52 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
551569
if (tns::IsBool(value)) {
552570
bool boolValue = value.As<v8::Boolean>()->Value();
553571
*(ffi_arg*)retValue = (bool)boolValue;
554-
return;
572+
return false;
555573
} else if (tns::IsNumber(value)) {
556574
double numValue = tns::ToNumber(isolate, value);
557575
switch (type) {
558576
case BinaryTypeEncodingType::UShortEncoding: {
559577
*static_cast<unsigned short*>(retValue) = (unsigned short)numValue;
560-
return;
578+
return false;
561579
}
562580
case BinaryTypeEncodingType::ShortEncoding: {
563581
*static_cast<short*>(retValue) = (short)numValue;
564-
return;
582+
return false;
565583
}
566584
case BinaryTypeEncodingType::UIntEncoding: {
567585
*static_cast<unsigned int*>(retValue) = (unsigned int)numValue;
568-
return;
586+
return false;
569587
}
570588
case BinaryTypeEncodingType::IntEncoding: {
571589
*static_cast<int*>(retValue) = (int)numValue;
572-
return;
590+
return false;
573591
}
574592
case BinaryTypeEncodingType::ULongEncoding: {
575593
*static_cast<unsigned long*>(retValue) = (unsigned long)numValue;
576-
return;
594+
return false;
577595
}
578596
case BinaryTypeEncodingType::LongEncoding: {
579597
*static_cast<long*>(retValue) = (long)numValue;
580-
return;
598+
return false;
581599
}
582600
case BinaryTypeEncodingType::ULongLongEncoding: {
583601
*static_cast<unsigned long long*>(retValue) = (unsigned long long)numValue;
584-
return;
602+
return false;
585603
}
586604
case BinaryTypeEncodingType::LongLongEncoding: {
587605
*static_cast<long long*>(retValue) = (long long)numValue;
588-
return;
606+
return false;
589607
}
590608
case BinaryTypeEncodingType::FloatEncoding: {
591609
*static_cast<float*>(retValue) = (float)numValue;
592-
return;
610+
return false;
593611
}
594612
case BinaryTypeEncodingType::DoubleEncoding: {
595613
*static_cast<double*>(retValue) = numValue;
596-
return;
614+
return false;
597615
}
598616
default:
599-
return;
617+
return false;
600618
}
601619
} else if (value->IsString()) {
602620
if (type == BinaryTypeEncodingType::IdEncoding ||
@@ -607,7 +625,7 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
607625
auto ref = CFBridgingRetain(data);
608626
*(CFTypeRef*)retValue = ref;
609627
CFRelease(ref);
610-
return;
628+
return true;
611629
}
612630
} else if (value->IsObject()) {
613631
if (type == BinaryTypeEncodingType::InterfaceDeclarationReference ||
@@ -619,15 +637,15 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
619637
id data = wrapper->Data();
620638
memset(retValue, 0, sizeof(id));
621639
*static_cast<id __strong*>(retValue) = data;
622-
return;
640+
return true;
623641
} else {
624642
id adapter = [[DictionaryAdapter alloc]
625643
initWithJSObject:tns::ProxyReadSource(original, value).As<Object>()
626644
isolate:isolate];
627645
memset(retValue, 0, sizeof(id));
628646
*static_cast<id __strong*>(retValue) = adapter;
629647
// CFAutorelease(adapter);
630-
return;
648+
return false;
631649
}
632650
} else if (type == BinaryTypeEncodingType::StructDeclarationReference) {
633651
BaseDataWrapper* baseWrapper = tns::GetValue(isolate, value);
@@ -638,19 +656,20 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
638656
const StructMeta* structMeta = static_cast<const StructMeta*>(meta);
639657
const StructInfo& structInfo = FFICall::GetStructInfo(structMeta);
640658
Interop::InitializeStruct(context, retValue, structInfo.Fields(), value);
641-
return;
659+
return false;
642660
} else if (baseWrapper->Type() == WrapperType::Struct) {
643661
StructWrapper* structWrapper = static_cast<StructWrapper*>(baseWrapper);
644662
size_t size = structWrapper->StructInfo().FFIType()->size;
645663
void* data = structWrapper->Data();
646664
memcpy(retValue, data, size);
647-
return;
665+
return false;
648666
}
649667
}
650668
}
651669

652670
// TODO: Handle other return types, i.e. assign the retValue parameter from the v8 result
653671
tns::Assert(false, isolate);
672+
return false;
654673
}
655674

656675
void ArgConverter::ConstructObject(Local<Context> context, const FunctionCallbackInfo<Value>& info,
@@ -703,13 +722,16 @@ explicit BorrowedSelfScope(Isolate* isolate) : isolate(isolate) {}
703722
auto cache = Caches::Get(isolate);
704723
auto poInstance = ArgConverter::FindCachedInstance(isolate, cache, result);
705724
if (poInstance != nullptr) {
725+
// Read before the release below: when it drops a DictionaryAdapter's last
726+
// reference, the adapter's -dealloc resets this handle.
727+
Local<Value> cached = poInstance->Get(isolate);
706728
// An initializer that answered with an already wrapped object (a singleton,
707729
// a tagged pointer, a cached cluster instance) leaves us holding a +1 the
708730
// existing entry has no use for.
709-
if (resultIsOwned) {
731+
if (Interop::ReleasesCachedOwnedReturn(resultIsOwned, OwnedReturnReceiver::AllocatedForCall)) {
710732
[result release];
711733
}
712-
info.GetReturnValue().Set(poInstance->Get(isolate));
734+
info.GetReturnValue().Set(cached);
713735
} else {
714736
ObjCDataWrapper* wrapper = new ObjCDataWrapper(result);
715737
Local<Object> thiz = info.This();

0 commit comments

Comments
 (0)