diff --git a/NativeScript/ffi/objc/napi/ObjCBridge.h b/NativeScript/ffi/objc/napi/ObjCBridge.h index 96a55ecf..b9c773f2 100644 --- a/NativeScript/ffi/objc/napi/ObjCBridge.h +++ b/NativeScript/ffi/objc/napi/ObjCBridge.h @@ -426,6 +426,7 @@ class ObjCBridgeState { void unregisterObject(id object) noexcept; bool unregisterObjectIfRefMatches(id object, napi_ref ref) noexcept; + bool releaseObjectWrapper(napi_env env, napi_value wrapper); void detachObject(id object) noexcept; void trackObject(id object) noexcept; bool isTrackedObjectAlive(id object) const noexcept; diff --git a/NativeScript/ffi/objc/napi/ObjCBridge.mm b/NativeScript/ffi/objc/napi/ObjCBridge.mm index fe330f37..f2f23c2c 100644 --- a/NativeScript/ffi/objc/napi/ObjCBridge.mm +++ b/NativeScript/ffi/objc/napi/ObjCBridge.mm @@ -1291,6 +1291,11 @@ NAPI_EXPORT void nativescript_init(void* _env, const char* metadata_path, registerInterop(env, global); registerInlineFunctions(env); + napi_value releaseNativeCounterpart; + napi_create_function(env, "__releaseNativeCounterpart", NAPI_AUTO_LENGTH, + JS_releaseNativeCounterpart, nullptr, &releaseNativeCounterpart); + napi_set_named_property(env, global, "__releaseNativeCounterpart", releaseNativeCounterpart); + bridgeState->registerVarGlobals(env, global); bridgeState->registerEnumGlobals(env, global); bridgeState->registerStructGlobals(env, global); diff --git a/NativeScript/ffi/objc/napi/Object.h b/NativeScript/ffi/objc/napi/Object.h index 3174bb91..c3e511e5 100644 --- a/NativeScript/ffi/objc/napi/Object.h +++ b/NativeScript/ffi/objc/napi/Object.h @@ -8,6 +8,7 @@ namespace nativescript { void initProxyFactory(napi_env env, ObjCBridgeState* bridgeState); void attachObjectLifecycleAssociation(napi_env env, id object); void transferOwnershipToNative(napi_env env, napi_value value, id object); +napi_value JS_releaseNativeCounterpart(napi_env env, napi_callback_info cbinfo); } // namespace nativescript diff --git a/NativeScript/ffi/objc/napi/Object.mm b/NativeScript/ffi/objc/napi/Object.mm index 7058a4e7..841f849f 100644 --- a/NativeScript/ffi/objc/napi/Object.mm +++ b/NativeScript/ffi/objc/napi/Object.mm @@ -138,6 +138,7 @@ void transferOwnershipToNative(napi_env env, napi_value value, id object) { namespace { constexpr const char* kNativePointerProperty = "__ns_native_ptr"; +constexpr const char* kProxyTargetProperty = "__ns_proxy_target"; napi_value findConstructorForClassObject(napi_env env, ObjCBridgeState* bridgeState, Class cls, napi_value fallback = nullptr) { @@ -184,6 +185,61 @@ napi_value findConstructorForClassObject(napi_env env, ObjCBridgeState* bridgeSt } } // namespace +napi_value JS_releaseNativeCounterpart(napi_env env, napi_callback_info cbinfo) { + size_t argc = 1; + napi_value arg = nullptr; + napi_get_cb_info(env, cbinfo, &argc, &arg, nullptr, nullptr); + + if (argc != 1) { + std::string message = + "Actual arguments count: \"" + std::to_string(argc) + "\". Expected: \"1\"."; + napi_throw_error(env, nullptr, message.c_str()); + return nullptr; + } + + auto bridgeState = ObjCBridgeState::InstanceData(env); + if (bridgeState != nullptr && bridgeState->releaseObjectWrapper(env, arg)) { + return nullptr; + } + + // A wrapper released earlier keeps a null native pointer; releasing it again + // is a no-op, as on Android. + napi_valuetype argType = napi_undefined; + napi_typeof(env, arg, &argType); + if (argType == napi_object) { + bool hasNativePointer = false; + napi_value nativePointer = nullptr; + napi_valuetype nativePointerType = napi_undefined; + if (napi_has_named_property(env, arg, kNativePointerProperty, &hasNativePointer) == napi_ok && + hasNativePointer && + napi_get_named_property(env, arg, kNativePointerProperty, &nativePointer) == napi_ok && + napi_typeof(env, nativePointer, &nativePointerType) == napi_ok && + nativePointerType == napi_null) { + return nullptr; + } + } + + std::string description = ""; + napi_value coerced = nullptr; + size_t length = 0; + if (napi_coerce_to_string(env, arg, &coerced) == napi_ok && + napi_get_value_string_utf8(env, coerced, nullptr, 0, &length) == napi_ok) { + description.resize(length + 1); + napi_get_value_string_utf8(env, coerced, description.data(), length + 1, &length); + description.resize(length); + } else { + bool hasException = false; + napi_value exception = nullptr; + if (napi_is_exception_pending(env, &hasException) == napi_ok && hasException) { + napi_get_and_clear_last_exception(env, &exception); + } + } + + std::string message = description + " is an object which is not a native wrapper."; + napi_throw_error(env, nullptr, message.c_str()); + return nullptr; +} + const char* nativeObjectProxySource = R"( (function (object, isArray, transferOwnershipToNative) { let isTransfered = false; @@ -333,6 +389,10 @@ function bindTargetMethod(target, name) { return undefined; } + if (name === "__ns_proxy_target") { + return target; + } + if (isArray) { const index = Number(name); if (!isNaN(index)) { @@ -811,6 +871,57 @@ napi_value findConstructorForObject(napi_env env, ObjCBridgeState* bridgeState, return true; } +bool ObjCBridgeState::releaseObjectWrapper(napi_env env, napi_value wrapper) { + // Pointers, references and class constructors are napi-wrapped too, so the + // unwrapped value is only treated as an id once objectRefs vouches for it. + void* wrapped = nullptr; + napi_ref ref = nullptr; + if (napi_unwrap(env, wrapper, &wrapped) == napi_ok && wrapped != nullptr) { + std::lock_guard lock(objectRefsMutex); + auto it = objectRefs.find((id)wrapped); + if (it != objectRefs.end()) { + ref = it->second; + } + } + + bool isRegisteredWrapper = false; + napi_value registered = ref != nullptr ? get_ref_value(env, ref) : nullptr; + if (registered == nullptr || + napi_strict_equals(env, registered, wrapper, &isRegisteredWrapper) != napi_ok || + !isRegisteredWrapper) { + return false; + } + + id object = (id)wrapped; + if (takeObjectRef(object, ref) == nullptr) { + return false; + } + + detachObject(object); + objc_setAssociatedObject(object, JSWrapperObjectAssociationKey, nil, + OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + // Without its wrap and native pointer the wrapper no longer resolves to the + // object, so later use throws instead of reaching freed memory. + napi_remove_wrap(env, wrapper, nullptr); + // Proxied wrappers forward method calls to their target, which carries its + // own wrap of the same object. + napi_value proxyTarget = nullptr; + napi_valuetype proxyTargetType = napi_undefined; + if (napi_get_named_property(env, wrapper, kProxyTargetProperty, &proxyTarget) == napi_ok && + napi_typeof(env, proxyTarget, &proxyTargetType) == napi_ok && + proxyTargetType == napi_object) { + napi_remove_wrap(env, proxyTarget, nullptr); + } + + napi_value releasedPointer = nullptr; + napi_get_null(env, &releasedPointer); + napi_set_named_property(env, wrapper, kNativePointerProperty, releasedPointer); + + [object release]; + return true; +} + void ObjCBridgeState::detachObject(id object) noexcept { takeObjectRef(object); removeRoundTripObject(object); diff --git a/packages/objc-node-api/index.d.ts b/packages/objc-node-api/index.d.ts index fff83d9b..94df55f7 100644 --- a/packages/objc-node-api/index.d.ts +++ b/packages/objc-node-api/index.d.ts @@ -7,6 +7,14 @@ declare global { // deno-lint-ignore ban-types function NativeClass(cls: Function): void; + /** + * Releases the native object behind `obj` now instead of when `obj` is + * garbage collected. Calling native methods on `obj` afterwards throws. + * Releasing an already released wrapper does nothing. Throws if called + * with other than one argument or if `obj` is not a native object wrapper. + */ + function __releaseNativeCounterpart(obj: NativeObject): void; + class NativeObject implements interop.PointerObject { readonly __brand__: interop.PointerObject["__brand__"]; diff --git a/platforms/apple/test/runtime/runner/app/tests/ApiTests.js b/platforms/apple/test/runtime/runner/app/tests/ApiTests.js index e67510ec..9889247c 100644 --- a/platforms/apple/test/runtime/runner/app/tests/ApiTests.js +++ b/platforms/apple/test/runtime/runner/app/tests/ApiTests.js @@ -721,6 +721,52 @@ describe(module.id, function () { expect(() => __releaseNativeCounterpart(undefined)).toThrowError(getNotANativeWrapperRegex(undefined)); }); + it("throws when the released wrapper is used", function () { + if (!isFunction(global.__releaseNativeCounterpart)) { + pending("__releaseNativeCounterpart is not available in this runtime."); + return; + } + + var p = TNSAllocLog.alloc().init(); + __releaseNativeCounterpart(p); + + expect(() => p.self()).toThrowError(/no native counterpart/); + }); + + it("does nothing when the wrapper is already released", function () { + if (!isFunction(global.__releaseNativeCounterpart)) { + pending("__releaseNativeCounterpart is not available in this runtime."); + return; + } + + var p = TNSAllocLog.alloc().init(); + __releaseNativeCounterpart(p); + + expect(() => __releaseNativeCounterpart(p)).not.toThrow(); + expect(TNSGetOutput()).toBe("TNSAllocLog initTNSAllocLog dealloc"); + }); + + it("keeps a js derived instance usable from native code that still retains it", function () { + if (!isFunction(global.__releaseNativeCounterpart)) { + pending("__releaseNativeCounterpart is not available in this runtime."); + return; + } + + var P = TNSAllocLog.extend({ + description: function () { + return "released-derived"; + } + }); + + var p = P.alloc().init(); + var holder = NSMutableArray.alloc().init(); + holder.addObject(p); + __releaseNativeCounterpart(p); + + expect(TNSGetOutput()).toBe("TNSAllocLog init"); + expect(holder.description).toContain("released-derived"); + }); + // it("sets object to nil", function () { // var arr = NSArray.arrayWithArray([1,2,3]); // expect(arr.count).toBe(3);