From 0304fc82021de3685787fd92ae6b30faa70f1c5b Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 15:26:55 -0300 Subject: [PATCH 1/4] perf(runtime): skip cast and null markers when an argument is a Java wrapper Converting an object argument read two private symbols from it: the numeric cast marker, then the null-node marker after the Java lookup. Both are only ever put on plain objects (cast objects, LongNumber instances and the .null sentinel), never on an object with the runtime's internal fields, so a Java wrapper or extended-class instance now goes straight to the Java lookup. Objects without internal fields (TypeScript subclass instances, typed arrays, plain objects) keep the full path. The same applies to the overload signature key and to argument arrays built for overload resolution. The Local helpers now use the current context instead of walking to the object's creation context: a private-symbol access is an own lookup that skips interceptors, proxy traps and access checks, so it runs no JS and does not depend on the context. The creation context is still the fallback when no context is entered. --- test-app/app/src/main/assets/app/mainpage.js | 1 + .../app/tests/testObjectArgumentPath.js | 77 +++++++++++++++++++ .../runtime/src/main/cpp/JsArgConverter.cpp | 11 ++- .../src/main/cpp/JsArgToArrayConverter.cpp | 10 ++- .../runtime/src/main/cpp/MetadataNode.cpp | 2 + test-app/runtime/src/main/cpp/MethodCache.cpp | 7 +- test-app/runtime/src/main/cpp/NumericCasts.h | 2 + .../runtime/src/main/cpp/V8GlobalHelpers.cpp | 11 ++- 8 files changed, 111 insertions(+), 10 deletions(-) create mode 100644 test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index a89f86029..f6126dcdc 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -86,6 +86,7 @@ require("./tests/testRuntimeImplementedAPIs"); require("./tests/testsInstanceOfOperator"); require("./tests/testProxyReceivers"); require("./tests/testReleaseNativeCounterpart"); +require("./tests/testObjectArgumentPath"); require("./tests/testJSONObjects"); require("./tests/kotlin/companions/testCompanionObjectsSupport"); require("./tests/kotlin/properties/testPropertiesSupport"); diff --git a/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js b/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js new file mode 100644 index 000000000..e9caadf91 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js @@ -0,0 +1,77 @@ +describe("Object arguments and cached call signatures", function () { + function roundTrip(obj) { + return java.util.Collections.singletonList(obj).get(0); + } + + it("passes a Java wrapper as an object argument on every call", function () { + var list = new java.util.ArrayList(); + for (var i = 0; i < 3; i++) { + expect(roundTrip(list)).toBe(list); + } + }); + + it("passes an extended class instance as an object argument", function () { + var Extended = java.lang.Object.extend({ + toString: function () { + return "extended arg"; + } + }); + var instance = new Extended(); + for (var i = 0; i < 3; i++) { + expect(roundTrip(instance)).toBe(instance); + expect(new java.lang.StringBuilder().append(instance).toString()).toBe("extended arg"); + } + }); + + it("passes a TypeScript subclass instance as an object argument", function () { + var TsButton = (function (_super) { + __extends(TsButton, _super); + function TsButton() { + var _this = _super.call(this) || this; + _this.label = "ts arg"; + return _this; + } + TsButton.prototype.toString = function () { + return this.label; + }; + return TsButton; + })(com.tns.tests.Button1); + + var button = new TsButton(); + for (var i = 0; i < 3; i++) { + expect(roundTrip(button)).toBe(button); + expect(new java.lang.StringBuilder().append(button).toString()).toBe("ts arg"); + } + }); + + it("rejects a released wrapper as an object argument", function () { + var released = new java.lang.Object(); + global.__releaseNativeCounterpart(released); + expect(function () { + roundTrip(released); + }).toThrow(); + }); + + it("resolves numeric casts, typed nulls and wrappers on a warm overload cache", function () { + var list = new java.util.ArrayList(); + var sb = new java.lang.StringBuilder(); + for (var i = 0; i < 3; i++) { + sb.append(long(5)); + sb.append(char("x")); + sb.append(double(1)); + sb.append(float(2)); + sb.append(java.lang.String.null); + sb.append(java.lang.Object.null); + sb.append(list); + sb.append("|"); + } + var round = "5x1.02.0nullnull[]|"; + expect(sb.toString()).toBe(round + round + round); + }); + + it("passes a numeric cast to a method with a single signature", function () { + for (var i = 0; i < 3; i++) { + expect(java.lang.Long.toHexString(long("4294967296"))).toBe("100000000"); + } + }); +}); diff --git a/test-app/runtime/src/main/cpp/JsArgConverter.cpp b/test-app/runtime/src/main/cpp/JsArgConverter.cpp index 898f65635..4ea92aab5 100644 --- a/test-app/runtime/src/main/cpp/JsArgConverter.cpp +++ b/test-app/runtime/src/main/cpp/JsArgConverter.cpp @@ -321,7 +321,10 @@ bool JsArgConverter::ConvertArg(const Local &jsArg, int index) { auto context = m_isolate->GetCurrentContext(); auto jsObject = arg->ToObject(context).ToLocalChecked(); - auto castType = NumericCasts::GetCastType(m_isolate, jsObject); + // Cast markers and the null sentinel are only put on plain objects, never on a + // Java wrapper (an object with the runtime's internal fields). + bool isWrapper = ObjectManager::HasMetadataField(jsObject); + auto castType = isWrapper ? CastType::None : NumericCasts::GetCastType(m_isolate, jsObject); Local castValue; JniLocalRef obj; @@ -419,8 +422,10 @@ bool JsArgConverter::ConvertArg(const Local &jsArg, int index) { ? GetOrLinkJavaBuffer(m_objectManager, jsObject) : m_objectManager->GetJavaObjectByJsObject(jsObject); - V8GetPrivateValue(m_isolate, jsObject, V8StringConstants::GetNullNodePrivate(m_isolate), - castValue); + if (!isWrapper) { + V8GetPrivateValue(m_isolate, jsObject, V8StringConstants::GetNullNodePrivate(m_isolate), + castValue); + } if (!castValue.IsEmpty()) { SetConvertedObject(index, nullptr); diff --git a/test-app/runtime/src/main/cpp/JsArgToArrayConverter.cpp b/test-app/runtime/src/main/cpp/JsArgToArrayConverter.cpp index 82ea5e3f7..8f616e7ff 100644 --- a/test-app/runtime/src/main/cpp/JsArgToArrayConverter.cpp +++ b/test-app/runtime/src/main/cpp/JsArgToArrayConverter.cpp @@ -142,7 +142,9 @@ bool JsArgToArrayConverter::ConvertArg(Local context, const LocalIsObject()) { auto jsObj = arg->ToObject(context).ToLocalChecked(); - auto castType = NumericCasts::GetCastType(isolate, jsObj); + // Cast markers and the null sentinel are never put on a Java wrapper. + bool isWrapper = ObjectManager::HasMetadataField(jsObj); + auto castType = isWrapper ? CastType::None : NumericCasts::GetCastType(isolate, jsObj); Local castValue; jchar charValue; @@ -252,8 +254,10 @@ bool JsArgToArrayConverter::ConvertArg(Local context, const LocalGetJavaObjectByJsObject(jsObj); - V8GetPrivateValue(isolate, jsObj, V8StringConstants::GetNullNodePrivate(isolate), - castValue); + if (!isWrapper) { + V8GetPrivateValue(isolate, jsObj, V8StringConstants::GetNullNodePrivate(isolate), + castValue); + } if (!castValue.IsEmpty()) { auto node = reinterpret_cast(castValue.As()->Value(v8::kExternalPointerTypeTagDefault)); diff --git a/test-app/runtime/src/main/cpp/MetadataNode.cpp b/test-app/runtime/src/main/cpp/MetadataNode.cpp index db6f8c36e..2bc708fd0 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.cpp +++ b/test-app/runtime/src/main/cpp/MetadataNode.cpp @@ -491,6 +491,8 @@ void MetadataNode::NullObjectAccessorGetterCallback(const FunctionCallbackInfo nullObject; if (!thiz->GetPrivate(context, nullObjectKey).ToLocal(&nullObject) || !nullObject->IsObject()) { auto node = reinterpret_cast(info.Data().As()->Value(v8::kExternalPointerTypeTagDefault)); + // A plain object: argument conversion never reads the null-node private + // from a Java wrapper. auto sentinel = Object::New(isolate); V8SetPrivateValue(isolate, sentinel, V8StringConstants::GetNullNodePrivate(isolate), External::New(isolate, node, v8::kExternalPointerTypeTagDefault)); // Function::New does not cache its template in the context, so the diff --git a/test-app/runtime/src/main/cpp/MethodCache.cpp b/test-app/runtime/src/main/cpp/MethodCache.cpp index d114a239c..039c12a8e 100644 --- a/test-app/runtime/src/main/cpp/MethodCache.cpp +++ b/test-app/runtime/src/main/cpp/MethodCache.cpp @@ -140,7 +140,10 @@ void MethodCache::AppendType(string& type, Isolate* isolate, const v8::LocalIsObject()) { + // Cast markers and the null sentinel are never put on a Java wrapper. + bool isWrapper = value->IsObject() && ObjectManager::HasMetadataField(value.As()); + + if (value->IsObject() && !isWrapper) { auto context = isolate->GetCurrentContext(); auto objVal = value->ToObject(context).ToLocalChecked(); Local nullNode; //out @@ -199,7 +202,7 @@ void MethodCache::AppendType(string& type, Isolate* isolate, const v8::LocalIsObject()) { auto context = isolate->GetCurrentContext(); auto object = value->ToObject(context).ToLocalChecked(); - auto castType = NumericCasts::GetCastType(isolate, object); + auto castType = isWrapper ? CastType::None : NumericCasts::GetCastType(isolate, object); MetadataNode* node; switch (castType) { diff --git a/test-app/runtime/src/main/cpp/NumericCasts.h b/test-app/runtime/src/main/cpp/NumericCasts.h index 3e3d3f7cd..54eae81ed 100644 --- a/test-app/runtime/src/main/cpp/NumericCasts.h +++ b/test-app/runtime/src/main/cpp/NumericCasts.h @@ -27,6 +27,8 @@ class NumericCasts { static v8::Local GetCastValue(v8::Isolate* isolate, const v8::Local& object); + // object must have no internal fields: argument conversion never reads a cast + // marker from a Java wrapper. static void MarkAsLong(v8::Isolate* isolate, const v8::Local& object, const v8::Local& value); private: diff --git a/test-app/runtime/src/main/cpp/V8GlobalHelpers.cpp b/test-app/runtime/src/main/cpp/V8GlobalHelpers.cpp index a9cd161d5..f3b4c2673 100644 --- a/test-app/runtime/src/main/cpp/V8GlobalHelpers.cpp +++ b/test-app/runtime/src/main/cpp/V8GlobalHelpers.cpp @@ -108,10 +108,17 @@ bool tns::V8SetPrivateValue(Isolate* isolate, const Local& obj, const Lo return res.FromMaybe(false); } +// A private-symbol access is an own-property lookup that skips interceptors, proxy traps +// and access checks, so it runs no JS and its result does not depend on the context. +static Local PrivateAccessContext(Isolate* isolate, const Local& obj) { + auto context = isolate->GetCurrentContext(); + return context.IsEmpty() ? tns::GetCreationContextOrCurrent(isolate, obj) : context; +} + // An absent private reads as undefined, so one GetPrivate replaces the // HasPrivate + GetPrivate pair; callers never store undefined under these keys. bool tns::V8GetPrivateValue(Isolate* isolate, const Local& obj, const Local& privateKey, Local& out) { - auto context = GetCreationContextOrCurrent(isolate, obj); + auto context = PrivateAccessContext(isolate, obj); Local value; if (!obj->GetPrivate(context, privateKey).ToLocal(&value)) { throw tns::NativeScriptException("Failed to Get Private Value"); @@ -126,7 +133,7 @@ bool tns::V8GetPrivateValue(Isolate* isolate, const Local& obj, const Lo } bool tns::V8SetPrivateValue(Isolate* isolate, const Local& obj, const Local& privateKey, const Local& value) { - auto context = GetCreationContextOrCurrent(isolate, obj); + auto context = PrivateAccessContext(isolate, obj); auto res = obj->SetPrivate(context, privateKey, value); if (res.IsNothing()) { From 9e4dd488d6da6f7025e3becbe6702528a42cfdd3 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 15:27:12 -0300 Subject: [PATCH 2/4] perf(runtime): keep parsed signatures on resolved method cache entries A call resolved through MethodCache (constructors with arguments, overloaded methods) parsed the JNI signature into a vector of type strings on every call before converting its arguments. The tokens are now parsed once, when the entry is created, and stored on it before it is published to the cache; the entry is immutable afterwards, so readers need no extra locking. --- .../app/tests/testObjectArgumentPath.js | 10 ++++ .../runtime/src/main/cpp/CallbackHandlers.cpp | 7 +-- .../runtime/src/main/cpp/JsArgConverter.cpp | 53 +++++++++---------- .../runtime/src/main/cpp/JsArgConverter.h | 11 ++-- test-app/runtime/src/main/cpp/MethodCache.cpp | 7 ++- test-app/runtime/src/main/cpp/MethodCache.h | 3 ++ 6 files changed, 54 insertions(+), 37 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js b/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js index e9caadf91..c69d64cf3 100644 --- a/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js +++ b/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js @@ -74,4 +74,14 @@ describe("Object arguments and cached call signatures", function () { expect(java.lang.Long.toHexString(long("4294967296"))).toBe("100000000"); } }); + + it("constructs through each overload on a warm constructor cache", function () { + for (var i = 0; i < 3; i++) { + expect(new java.lang.StringBuilder("ab").toString()).toBe("ab"); + expect(new java.lang.StringBuilder(32).capacity()).toBe(32); + expect(new java.lang.StringBuilder(new java.lang.StringBuilder("cs")).toString()).toBe("cs"); + var plain = new java.lang.Object(); + expect(plain.getClass().getName()).toBe("java.lang.Object"); + } + }); }); diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index 51a88bad3..93e08d1f4 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -253,7 +253,7 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local &j instance = env.NewObject(generatedJavaClass, mi.mid); } else { // resolve arguments before passing them on to the constructor - JsArgConverter argConverter(argWrapper.args, mi.signature); + JsArgConverter argConverter(argWrapper.args, mi.parsedSig); auto ctorArgs = argConverter.ToArgs(); instance = env.NewObjectA(generatedJavaClass, mi.mid, ctorArgs); @@ -505,9 +505,10 @@ void CallbackHandlers::CallJavaMethod(const Local &caller, const string methodName.c_str()); } + const std::vector *parsedSig = mi != nullptr ? &mi->parsedSig : nullptr; JsArgConverter argConverter = (entry != nullptr && entry->isExtensionFunction) - ? JsArgConverter(caller, args, *sig, entry) - : JsArgConverter(args, false, *sig, entry); + ? JsArgConverter(caller, args, *sig, entry, parsedSig) + : JsArgConverter(args, false, *sig, entry, parsedSig); if (!argConverter.IsValid()) { diff --git a/test-app/runtime/src/main/cpp/JsArgConverter.cpp b/test-app/runtime/src/main/cpp/JsArgConverter.cpp index 4ea92aab5..392a6ad59 100644 --- a/test-app/runtime/src/main/cpp/JsArgConverter.cpp +++ b/test-app/runtime/src/main/cpp/JsArgConverter.cpp @@ -89,25 +89,33 @@ namespace { } } +void JsArgConverter::SetTokens(const string &methodSignature, MetadataEntry *entry, + const std::vector *parsedSignature) { + if (parsedSignature != nullptr) { + m_tokens = parsedSignature; + } else if ((entry != nullptr) && (entry->getIsResolved())) { + if (entry->parsedSig.empty()) { + JniSignatureParser parser(methodSignature); + entry->parsedSig = parser.Parse(); + } + m_tokens = &entry->parsedSig; + } else { + JniSignatureParser parser(methodSignature); + m_ownedTokens = parser.Parse(); + } +} + JsArgConverter::JsArgConverter(const Local &caller, const v8::FunctionCallbackInfo &args, - const string &methodSignature, MetadataEntry *entry) + const string &methodSignature, MetadataEntry *entry, + const std::vector *parsedSignature) : m_isolate(args.GetIsolate()), m_isValid(true), m_error(Error()) { int v8ProvidedArgumentsLength = args.Length(); m_argsLen = 1 + v8ProvidedArgumentsLength; if (m_argsLen > 0) { - if ((entry != nullptr) && (entry->getIsResolved())) { - if (entry->parsedSig.empty()) { - JniSignatureParser parser(methodSignature); - entry->parsedSig = parser.Parse(); - } - m_tokens = &entry->parsedSig; - } else { - JniSignatureParser parser(methodSignature); - m_ownedTokens = parser.Parse(); - } + SetTokens(methodSignature, entry, parsedSignature); m_isValid = ConvertArg(caller, 0); @@ -127,22 +135,14 @@ JsArgConverter::JsArgConverter(const Local &caller, JsArgConverter::JsArgConverter(const v8::FunctionCallbackInfo &args, bool hasImplementationObject, const string &methodSignature, - MetadataEntry *entry) + MetadataEntry *entry, + const std::vector *parsedSignature) : m_isolate(args.GetIsolate()), m_isValid(true), m_error(Error()) { m_argsLen = !hasImplementationObject ? args.Length() : args.Length() - 1; if (m_argsLen > 0) { - if ((entry != nullptr) && (entry->getIsResolved())) { - if (entry->parsedSig.empty()) { - JniSignatureParser parser(methodSignature); - entry->parsedSig = parser.Parse(); - } - m_tokens = &entry->parsedSig; - } else { - JniSignatureParser parser(methodSignature); - m_ownedTokens = parser.Parse(); - } + SetTokens(methodSignature, entry, parsedSignature); for (int i = 0; i < m_argsLen; i++) { m_isValid = ConvertArg(args[i], i); @@ -155,16 +155,11 @@ JsArgConverter::JsArgConverter(const v8::FunctionCallbackInfo &args, } JsArgConverter::JsArgConverter(const v8::FunctionCallbackInfo &args, - const string &methodSignature) + const std::vector &parsedSignature) : m_isolate(args.GetIsolate()), m_isValid(true), - m_error(Error()) { + m_tokens(&parsedSignature), m_error(Error()) { m_argsLen = args.Length(); - if (m_argsLen > 0) { - JniSignatureParser parser(methodSignature); - m_ownedTokens = parser.Parse(); - } - for (int i = 0; i < m_argsLen; i++) { m_isValid = ConvertArg(args[i], i); diff --git a/test-app/runtime/src/main/cpp/JsArgConverter.h b/test-app/runtime/src/main/cpp/JsArgConverter.h index 12787019e..42cbcadcd 100644 --- a/test-app/runtime/src/main/cpp/JsArgConverter.h +++ b/test-app/runtime/src/main/cpp/JsArgConverter.h @@ -24,11 +24,14 @@ namespace tns { class JsArgConverter { public: - JsArgConverter(const v8::Local& caller, const v8::FunctionCallbackInfo& args, const std::string& methodSignature, MetadataEntry* entry); + // parsedSignature, when given, is methodSignature already parsed and must outlive the + // converter. + JsArgConverter(const v8::Local& caller, const v8::FunctionCallbackInfo& args, const std::string& methodSignature, MetadataEntry* entry, const std::vector* parsedSignature = nullptr); - JsArgConverter(const v8::FunctionCallbackInfo& args, bool hasImplementationObject, const std::string& methodSignature, MetadataEntry* entry); + JsArgConverter(const v8::FunctionCallbackInfo& args, bool hasImplementationObject, const std::string& methodSignature, MetadataEntry* entry, const std::vector* parsedSignature = nullptr); - JsArgConverter(const v8::FunctionCallbackInfo& args, const std::string& methodSignature); + // parsedSignature must outlive the converter. + JsArgConverter(const v8::FunctionCallbackInfo& args, const std::vector& parsedSignature); JsArgConverter(const JsArgConverter&) = delete; @@ -69,6 +72,8 @@ namespace tns { private: + void SetTokens(const std::string& methodSignature, MetadataEntry* entry, const std::vector* parsedSignature); + bool ConvertArg(const v8::Local& jsArg, int index); bool ConvertJavaScriptArray(const v8::Local& source, size_t length, int index); diff --git a/test-app/runtime/src/main/cpp/MethodCache.cpp b/test-app/runtime/src/main/cpp/MethodCache.cpp index 039c12a8e..36d9b53bc 100644 --- a/test-app/runtime/src/main/cpp/MethodCache.cpp +++ b/test-app/runtime/src/main/cpp/MethodCache.cpp @@ -2,6 +2,7 @@ #include #include "JniLocalRef.h" +#include "JniSignatureParser.h" #include "JsArgToArrayConverter.h" #include "MetadataNode.h" #include "NativeScriptAssert.h" @@ -69,6 +70,7 @@ const MethodCache::CacheMethodInfo& MethodCache::ResolveMethodSignature(const st NS_DCHECK(clazz != nullptr); method_info.clazz = clazz; method_info.signature = signature; + method_info.parsedSig = JniSignatureParser(signature).Parse(); method_info.returnType = MetadataReader::ParseReturnType(method_info.signature); method_info.retType = MetadataReader::GetReturnType(method_info.returnType); method_info.isStatic = isStatic; @@ -78,7 +80,7 @@ const MethodCache::CacheMethodInfo& MethodCache::ResolveMethodSignature(const st env.GetMethodID(clazz, methodName, signature); std::unique_lock lock(signatureCacheMutex); - return s_mthod_ctor_signature_cache.emplace(encoded_method_signature, method_info).first->second; + return s_mthod_ctor_signature_cache.emplace(encoded_method_signature, std::move(method_info)).first->second; } return s_unresolved; @@ -107,6 +109,7 @@ const MethodCache::CacheMethodInfo& MethodCache::ResolveConstructorSignature(con JEnv env; constructor_info.clazz = javaClass; constructor_info.signature = signature; + constructor_info.parsedSig = JniSignatureParser(signature).Parse(); constructor_info.mid = env.GetMethodID(javaClass, "", signature); // Runtime.resolveConstructorSignature answers this for no Java arguments only for an // interface proxy; any other class would need a one-argument call to resolve to it. @@ -114,7 +117,7 @@ const MethodCache::CacheMethodInfo& MethodCache::ResolveConstructorSignature(con constructor_info.isInterfaceProxy = !hasJavaArgs && signature == "(Ljava/lang/reflect/InvocationHandler;)V"; std::unique_lock lock(signatureCacheMutex); - return s_mthod_ctor_signature_cache.emplace(encoded_ctor_signature, constructor_info).first->second; + return s_mthod_ctor_signature_cache.emplace(encoded_ctor_signature, std::move(constructor_info)).first->second; } return s_unresolved; diff --git a/test-app/runtime/src/main/cpp/MethodCache.h b/test-app/runtime/src/main/cpp/MethodCache.h index 127eff086..56f5e3785 100644 --- a/test-app/runtime/src/main/cpp/MethodCache.h +++ b/test-app/runtime/src/main/cpp/MethodCache.h @@ -2,6 +2,7 @@ #define METHODCACHE_H_ #include +#include #include #include "v8.h" #include "JEnv.h" @@ -23,6 +24,8 @@ class MethodCache { retType(MethodReturnType::Unknown), mid(nullptr), clazz(nullptr), isStatic(false), isInterfaceProxy(false) { } std::string signature; + // signature parsed into argument types; set before the entry is published. + std::vector parsedSig; std::string returnType; MethodReturnType retType; jmethodID mid; From ab9dac6472605d6ba2952db7244e5eed69469781 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 15:27:17 -0300 Subject: [PATCH 3/4] perf(runtime): cache the resolved class of a JS-extended class Every `new` of a JS-extended class looked its generated Java class up in the process-wide class cache, taking its shared lock and hashing the full class name. The extended class's per-isolate callback data now keeps the global ref once resolved; the class cache never drops or replaces an entry, so the ref stays valid. Plain Java class construction is unchanged. --- .../app/tests/testObjectArgumentPath.js | 28 +++++++++++++++++++ .../runtime/src/main/cpp/CallbackHandlers.cpp | 15 +++++++--- .../runtime/src/main/cpp/CallbackHandlers.h | 3 +- .../runtime/src/main/cpp/MetadataNode.cpp | 3 +- test-app/runtime/src/main/cpp/MetadataNode.h | 3 ++ 5 files changed, 46 insertions(+), 6 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js b/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js index c69d64cf3..89c263183 100644 --- a/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js +++ b/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js @@ -84,4 +84,32 @@ describe("Object arguments and cached call signatures", function () { expect(plain.getClass().getName()).toBe("java.lang.Object"); } }); + + it("constructs extended classes repeatedly, interleaved and with arguments", function () { + var Counting = java.util.ArrayList.extend({ + size: function () { + return this.super.size() + 100; + } + }); + var Named = java.lang.Object.extend({ + toString: function () { + return "named"; + } + }); + var source = new java.util.ArrayList(); + source.add("a"); + + var seen = []; + for (var i = 0; i < 20; i++) { + var empty = new Counting(); + empty.add("x"); + expect(empty.size()).toBe(101); + expect(new Counting(10).size()).toBe(100); + expect(new Counting(source).size()).toBe(101); + var named = new Named(); + expect(named.toString()).toBe("named"); + expect(seen.indexOf(empty)).toBe(-1); + seen.push(empty); + } + }); }); diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index 93e08d1f4..b46c733c7 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -214,7 +214,8 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local &j bool isInterface, const std::string &baseClassName, uint64_t defaultOverrides, - const vector *contentMemberNames) { + const vector *contentMemberNames, + jclass *resolvedClass) { bool success; DEBUG_WRITE("RegisterInstance called for '%s'", fullClassName.c_str()); @@ -230,9 +231,15 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local &j // The default-overriding class does not depend on the implementation object, whose // properties ResolveClass would otherwise read, getters included. - jclass generatedJavaClass = ResolveClass(isolate, baseClassName, fullClassName, - defaultOverrides != 0 ? Local() : implementationObject, - isInterface, contentMemberNames); + jclass generatedJavaClass = resolvedClass != nullptr ? *resolvedClass : nullptr; + if (generatedJavaClass == nullptr) { + generatedJavaClass = ResolveClass(isolate, baseClassName, fullClassName, + defaultOverrides != 0 ? Local() : implementationObject, + isInterface, contentMemberNames); + if (resolvedClass != nullptr) { + *resolvedClass = generatedJavaClass; + } + } int javaObjectID = objectManager->GenerateNewObjectID(); diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.h b/test-app/runtime/src/main/cpp/CallbackHandlers.h index 1bd3865fd..d9f9d71b6 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.h +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.h @@ -42,7 +42,8 @@ namespace tns { bool isInterface, const std::string &baseClassName = std::string(), uint64_t defaultOverrides = 0, - const std::vector *contentMemberNames = nullptr); + const std::vector *contentMemberNames = nullptr, + jclass *resolvedClass = nullptr); // Whether GetImplementedInterfaces would list any interface, without calling Java. static bool HasImplementedInterfaces(v8::Isolate *isolate, const v8::Local &implementationObject); diff --git a/test-app/runtime/src/main/cpp/MetadataNode.cpp b/test-app/runtime/src/main/cpp/MetadataNode.cpp index 2bc708fd0..15eb80cac 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.cpp +++ b/test-app/runtime/src/main/cpp/MetadataNode.cpp @@ -1527,7 +1527,8 @@ void MetadataNode::ExtendedClassConstructorCallback(const v8::FunctionCallbackIn ArgsWrapper argWrapper(info, ArgType::Class); bool success = CallbackHandlers::RegisterInstance(isolate, thiz, extData->fullClassName, argWrapper, implementationObject, false, extData->node->m_name, extData->defaultOverrides, - extData->contentMemberNames ? &*extData->contentMemberNames : nullptr); + extData->contentMemberNames ? &*extData->contentMemberNames : nullptr, + &extData->resolvedClass); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception e) { diff --git a/test-app/runtime/src/main/cpp/MetadataNode.h b/test-app/runtime/src/main/cpp/MetadataNode.h index 3313d2a3b..2cad92ba9 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.h +++ b/test-app/runtime/src/main/cpp/MetadataNode.h @@ -319,6 +319,9 @@ class MetadataNode { std::string fullClassName; uint64_t defaultOverrides = 0; std::optional> contentMemberNames; + // The class cache's global ref for fullClassName once resolved; that cache never + // drops or replaces an entry. + jclass resolvedClass = nullptr; }; struct TypeMetadata { From 766e992945b63fa8d404b4e6512db9fc78f4315a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 15:29:36 -0300 Subject: [PATCH 4/4] perf(runtime): skip the jweak check while Java holds the object strongly Every cache hit in GetJavaObjectByJsObject asked JNI whether the cached weak global ref was cleared (IsSameObject, a thread-state transition). While a linked wrapper's Java side has not been weakened, Java's ObjectTable holds the object strongly under its id, so the jweak cached for that id cannot have been cleared and the check is skipped. Wrappers whose Java side was weakened (and may have been handed back to JS since) keep it. Two cases broke that invariant and are closed here: - A finalizer batch that failed part way could leave objects weakened on the Java side with javaWeakened still false. The flag is now set before the call, so a failure leaves it conservative. - While JS constructs an object, an instance of the same class that Java creates inside the constructor takes the reserved id until registerConstructedInstance replaces it. A jweak cached in that window named the nested instance, so calls on the constructed object reached the nested one (and, once it was collected, relied on the jweak check). The cached entry is now dropped after registration. --- .../app/tests/testObjectArgumentPath.js | 62 +++++++++++++++++++ .../main/java/com/tns/tests/SelfNesting.java | 25 ++++++++ .../runtime/src/main/cpp/CallbackHandlers.cpp | 3 + test-app/runtime/src/main/cpp/LRUCache.h | 11 ++-- .../runtime/src/main/cpp/ObjectManager.cpp | 24 +++---- test-app/runtime/src/main/cpp/ObjectManager.h | 13 +++- 6 files changed, 118 insertions(+), 20 deletions(-) create mode 100644 test-app/app/src/main/java/com/tns/tests/SelfNesting.java diff --git a/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js b/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js index 89c263183..785312e35 100644 --- a/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js +++ b/test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js @@ -112,4 +112,66 @@ describe("Object arguments and cached call signatures", function () { seen.push(empty); } }); + + describe("cached Java objects of linked wrappers", function () { + var Holder = com.tns.tests.WrapperHolder; + + function collectJava() { + for (var i = 0; i < 3; i++) { + java.lang.Runtime.getRuntime().gc(); + java.lang.System.runFinalization(); + } + } + + afterEach(function () { + Holder.held = null; + }); + + it("never pass null for a wrapper whose Java object was collected after Java weakened it", function () { + (function () { + Holder.held = new java.lang.StringBuilder("weakened"); + })(); + gc(); + // Any Java call flushes the collected wrapper, weakening its Java object. + collectJava(); + var again = Holder.held; + Holder.held = null; + collectJava(); + + var passed; + try { + passed = java.util.Collections.singletonList(again).get(0); + } catch (e) { + passed = "threw"; + } + expect(passed === again || passed === "threw").toBe(true); + }); + + it("resolve a reachable wrapper after warm instance calls and a collection", function () { + var sb = new java.lang.StringBuilder("warm"); + for (var i = 0; i < 50; i++) { + expect(sb.length()).toBe(4); + } + for (var j = 0; j < 2000; j++) { + new java.lang.Object(); + } + gc(); + collectJava(); + expect(sb.toString()).toBe("warm"); + expect(java.util.Collections.singletonList(sb).get(0)).toBe(sb); + }); + + it("resolve a constructed instance after Java made another of its class during the constructor", function () { + var Outer = com.tns.tests.SelfNesting.extend({ + touch: function () { + this.super.touch(); + }, + selfNestingSpec: true + }); + var outer = new Outer(true); + expect(outer.getTag()).toBe(2); + collectJava(); + expect(outer.getTag()).toBe(2); + }); + }); }); diff --git a/test-app/app/src/main/java/com/tns/tests/SelfNesting.java b/test-app/app/src/main/java/com/tns/tests/SelfNesting.java new file mode 100644 index 000000000..baa553a03 --- /dev/null +++ b/test-app/app/src/main/java/com/tns/tests/SelfNesting.java @@ -0,0 +1,25 @@ +package com.tns.tests; + +/** Creates an instance of its own runtime class while its constructor runs. */ +public class SelfNesting { + private final int tag; + + public SelfNesting() { + tag = 1; + } + + public SelfNesting(boolean nest) throws Exception { + tag = 2; + if (nest) { + SelfNesting nested = getClass().getConstructor().newInstance(); + nested.touch(); + } + } + + public int getTag() { + return tag; + } + + public void touch() { + } +} diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index b46c733c7..819f836ae 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -275,6 +275,9 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local &j jlong usedJavaMemory = env.CallLongMethod(runtime->GetJavaRuntime(), REGISTER_CONSTRUCTED_INSTANCE_ID, instance, javaObjectID); + // While the constructor ran, an instance of the same class that Java created could take + // this id until the registration above replaced it; a jweak cached then names that one. + objectManager->ForgetCachedJavaObject(javaObjectID); AdjustAmountOfExternalAllocatedMemory(isolate, usedJavaMemory); diff --git a/test-app/runtime/src/main/cpp/LRUCache.h b/test-app/runtime/src/main/cpp/LRUCache.h index 87ed14cba..adda08abc 100644 --- a/test-app/runtime/src/main/cpp/LRUCache.h +++ b/test-app/runtime/src/main/cpp/LRUCache.h @@ -51,13 +51,14 @@ class LRUCache { NS_CHECK((0 < m_capacity) && (m_capacity < 10000)); } - // Obtain value of the cached function for k - value_type operator()(const key_type& k) { + // Obtain value of the cached function for k. validate=false skips the validity + // callback for a hit the caller knows is still valid. + value_type operator()(const key_type& k, bool validate = true) { // Attempt to find existing record auto it = m_key_to_value.find(k); - if (m_cacheValidCallback != nullptr && it != m_key_to_value.end()) { + if (validate && m_cacheValidCallback != nullptr && it != m_key_to_value.end()) { //check if cache is still valid if (!m_cacheValidCallback(k, (*it).second.first, m_state)) { //cache is not valid anymore, evict the key @@ -122,8 +123,6 @@ class LRUCache { m_key_tracker.clear(); } - private: - void evictKey(const key_type& key) { auto it = m_key_to_value.find(key); if (it != m_key_to_value.end()) { @@ -135,6 +134,8 @@ class LRUCache { } } + private: + // Record a fresh key-value pair in the cache void insert(const key_type& k, const value_type& v) { // Method is only called on cache misses diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 71395e499..d96d4068d 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -110,7 +110,8 @@ JniLocalRef ObjectManager::GetJavaObjectByJsObject( if (jsInstanceInfo != nullptr) { jweak existingObject; try { - existingObject = GetJavaObjectByID(jsInstanceInfo->javaObjectID); + existingObject = GetJavaObjectByID(jsInstanceInfo->javaObjectID, + jsInstanceInfo->javaWeakened); } catch (const NativeScriptException& e) { // this captures usually the error auto className = GetClassName(jsInstanceInfo->objectClazz); @@ -286,10 +287,8 @@ bool ObjectManager::IsJsRuntimeObject(const v8::Local& object) { internalFieldCount == V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT; } -jweak ObjectManager::GetJavaObjectByID(uint32_t javaObjectID) { - jweak obj = m_cache(javaObjectID); - - return obj; +jweak ObjectManager::GetJavaObjectByID(uint32_t javaObjectID, bool validate) { + return m_cache(javaObjectID, validate); } jobject ObjectManager::GetJavaObjectByIDImpl(uint32_t javaObjectID) { @@ -682,6 +681,11 @@ void ObjectManager::FlushFinalizedBatch() { return; } + // Before the call: one that fails part way may already have weakened some of them. + for (jint id : weaken) { + m_idToObject.Find(id)->javaWeakened = true; + } + JEnv env; JNIEnv* raw = env; auto toJava = [raw](const std::vector& ids) -> jintArray { @@ -726,8 +730,7 @@ void ObjectManager::FlushFinalizedBatch() { return; } - auto settle = [this, raw](const std::vector& ids, jintArray array, - bool weakened) { + auto settle = [this, raw](const std::vector& ids, jintArray array) { if (ids.empty()) { return; } @@ -744,13 +747,10 @@ void ObjectManager::FlushFinalizedBatch() { continue; } state->queued = false; - if (weakened) { - state->javaWeakened = true; - } } }; - settle(weaken, (jintArray) weakenArray, true); - settle(check, (jintArray) checkArray, false); + settle(weaken, (jintArray) weakenArray); + settle(check, (jintArray) checkArray); } void ObjectManager::ReleaseCollectedWrapper(int javaObjectID) { diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 469a18898..62c1217d1 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -49,6 +49,10 @@ class ObjectManager { void UpdateCache(int objectID, jobject obj); + // Drops the jweak cached for objectID, after Java may have registered a different object + // under it. + void ForgetCachedJavaObject(int objectID) { m_cache.evictKey(objectID); } + jclass GetJavaClass(const v8::Local& instance); void SetJavaClass(const v8::Local& instance, jclass clazz); @@ -182,8 +186,9 @@ class ObjectManager { // Cleared by ReleaseNativeCounterpart; the registration itself lives until the // wrapper is collected. bool linked = true; - // The Java side holds the object weakly; a finalization now only asks - // whether it is still alive. + // The Java side may hold the object weakly; a finalization now only asks + // whether it is still alive. While false, Java holds the object strongly under + // javaObjectID, so a jweak cached for that id still names it. bool javaWeakened = false; // Queued in a finalizer batch that has not been flushed yet. bool queued = false; @@ -261,7 +266,9 @@ class ObjectManager { // A flush failed; crossings leave the retry to the delayed task. bool m_flushBackingOff = false; - jweak GetJavaObjectByID(uint32_t javaObjectID); + // validate=false only while the Java side holds the object strongly: its jweak + // cannot have been cleared then. + jweak GetJavaObjectByID(uint32_t javaObjectID, bool validate); jobject GetJavaObjectByIDImpl(uint32_t javaObjectID);