From eb30f5b59e014bec3668c6487221c461f6d39fbf Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 14:17:21 -0300 Subject: [PATCH 1/6] feat(runtime): warn when Java dispatches past a class's own method Java->JS calls look the method up on the JS instance per call, so an own property of the instance (a per-instance override, a spy, a TypeScript class-field arrow function) or a method replaced after extend() is what runs. The iOS runtime binds a class's methods when it is extended and never sees either. Before deciding whether to align Android with iOS, we want to know how often apps rely on this. In debug builds (APPLICATION_IN_DEBUG), each extend() now captures the implementation object's own function-valued data properties. The class's record is reached from the wrapper's link state, which the call path already fetches, and it is keyed lazily by Java's method-name id. A call that resolves to a different function than the captured one is logged once per class and method under the JS tag, with the location of the function that ran. For a name the class does not define, the first call resolves to whatever the class inherits, unless the instance, its prototype or the implementation object owns the name. Behaviour is unchanged: the call still goes to the function it reaches today. Release builds (nativescript-optimized) compile none of it. Instances of `new SomeInterface({...})` are not checked yet: their implementation object is per instance, so a per-class record does not apply to them. --- test-app/runtime/CMakeLists.txt | 1 + .../runtime/src/main/cpp/CallbackHandlers.cpp | 13 +- .../runtime/src/main/cpp/CallbackHandlers.h | 6 +- .../src/main/cpp/DispatchOverrides.cpp | 133 ++++++++++++++++++ .../runtime/src/main/cpp/DispatchOverrides.h | 92 ++++++++++++ .../runtime/src/main/cpp/MetadataNode.cpp | 19 ++- test-app/runtime/src/main/cpp/MetadataNode.h | 11 +- .../runtime/src/main/cpp/ObjectManager.cpp | 63 +++++++-- test-app/runtime/src/main/cpp/ObjectManager.h | 29 +++- test-app/runtime/src/main/cpp/Runtime.cpp | 18 ++- 10 files changed, 346 insertions(+), 39 deletions(-) create mode 100644 test-app/runtime/src/main/cpp/DispatchOverrides.cpp create mode 100644 test-app/runtime/src/main/cpp/DispatchOverrides.h diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index 96ae3d008..283cbd8f0 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -211,6 +211,7 @@ add_library( src/main/cpp/IsolateTracked.cpp src/main/cpp/JEnv.cpp src/main/cpp/DesugaredInterfaceCompanionClassNameResolver.cpp + src/main/cpp/DispatchOverrides.cpp src/main/cpp/JType.cpp src/main/cpp/JniSignatureParser.cpp src/main/cpp/JsArgConverter.cpp diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index 1e9e69fb1..f09ccf718 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -216,7 +216,8 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local &j uint64_t defaultOverrides, const vector *contentMemberNames, jclass *resolvedClass, - const Persistent *instanceTemplate) { + const Persistent *instanceTemplate, + DispatchOverrides *dispatchOverrides) { bool success; DEBUG_WRITE("RegisterInstance called for '%s'", fullClassName.c_str()); @@ -250,7 +251,7 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local &j !implementationObject.IsEmpty() || isInterface ? ObjectManager::LinkKind::kExtended : ObjectManager::LinkKind::kPlain, - instanceTemplate); + instanceTemplate, dispatchOverrides); // resolve constructor const auto &mi = MethodCache::ResolveConstructorSignature(argWrapper, fullClassName, @@ -1247,7 +1248,8 @@ vector CallbackHandlers::GetTypeMetadata(const string &name, int index) Local CallbackHandlers::CallJSMethod(Isolate *isolate, JNIEnv *_env, const Local &jsObject, const Local &methodName, - const JavaCallArgs &args) { + const JavaCallArgs &args, DispatchOverrides *dispatchOverrides, + int methodNameId) { SET_PROFILER_FRAME(); JEnv env(_env); @@ -1268,6 +1270,11 @@ Local CallbackHandlers::CallJSMethod(Isolate *isolate, JNIEnv *_env, EscapableHandleScope handleScope(isolate); auto jsMethod = method.As(); +#ifdef APPLICATION_IN_DEBUG + if (dispatchOverrides != nullptr) { + dispatchOverrides->Check(isolate, context, jsObject, methodName, methodNameId, jsMethod); + } +#endif int argc = args.count; constexpr int kInlineArgs = 16; diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.h b/test-app/runtime/src/main/cpp/CallbackHandlers.h index cc05eaa47..f58a19db7 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.h +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.h @@ -44,7 +44,8 @@ namespace tns { uint64_t defaultOverrides = 0, const std::vector *contentMemberNames = nullptr, jclass *resolvedClass = nullptr, - const v8::Persistent *instanceTemplate = nullptr); + const v8::Persistent *instanceTemplate = nullptr, + DispatchOverrides *dispatchOverrides = nullptr); // Whether GetImplementedInterfaces would list any interface, without calling Java. static bool HasImplementedInterfaces(v8::Isolate *isolate, const v8::Local &implementationObject); @@ -99,7 +100,8 @@ namespace tns { static v8::Local CallJSMethod(v8::Isolate *isolate, JNIEnv *_env, const v8::Local &jsObject, - const v8::Local &methodName, const JavaCallArgs &args); + const v8::Local &methodName, const JavaCallArgs &args, + DispatchOverrides *dispatchOverrides = nullptr, int methodNameId = -1); static v8::Local GetJavaField(v8::Isolate *isolate, const v8::Local &caller, diff --git a/test-app/runtime/src/main/cpp/DispatchOverrides.cpp b/test-app/runtime/src/main/cpp/DispatchOverrides.cpp new file mode 100644 index 000000000..4d3e443f2 --- /dev/null +++ b/test-app/runtime/src/main/cpp/DispatchOverrides.cpp @@ -0,0 +1,133 @@ +#include "DispatchOverrides.h" + +#ifdef APPLICATION_IN_DEBUG + +#include + +#include + +#include "ArgConverter.h" + +using namespace v8; + +namespace tns { + +DispatchOverrides::DispatchOverrides(Isolate* isolate, Local implementationObject, + std::string className) + : className_(std::move(className)), implementationObject_(isolate, implementationObject) { + auto context = isolate->GetCurrentContext(); + TryCatch tc(isolate); + + Local names; + if (!implementationObject + ->GetOwnPropertyNames(context, PropertyFilter::SKIP_SYMBOLS) + .ToLocal(&names)) { + return; + } + + auto valueKey = ArgConverter::ConvertToV8String(isolate, std::string("value")); + uint32_t length = names->Length(); + captured_.reserve(length); + for (uint32_t i = 0; i < length; i++) { + Local name; + if (!names->Get(context, i).ToLocal(&name) || !name->IsString()) { + continue; + } + + Captured entry; + entry.name.Reset(isolate, name.As()); + + Local descriptor; + Local value; + if (implementationObject->GetOwnPropertyDescriptor(context, name.As()) + .ToLocal(&descriptor) && + descriptor->IsObject() && + descriptor.As()->Get(context, valueKey).ToLocal(&value) && + value->IsFunction()) { + entry.function.Reset(isolate, value.As()); + } + + captured_.push_back(std::move(entry)); + } +} + +void DispatchOverrides::CheckSlow(Isolate* isolate, Local context, + Local instance, Local methodName, + size_t index, Local method) { + if (index >= byNameId_.size()) { + byNameId_.resize(index + 1); + } + auto& entry = byNameId_[index]; + + if (!entry.bound) { + entry.bound = true; + + const Captured* captured = nullptr; + for (const auto& candidate : captured_) { + if (candidate.name.Get(isolate)->StringEquals(methodName)) { + captured = &candidate; + break; + } + } + + if (captured != nullptr) { + if (captured->function.IsEmpty()) { + entry.quiet = true; + return; + } + entry.expected.Reset(isolate, captured->function); + if (entry.expected == method) { + return; + } + } else if (!DefinedAfterExtend(isolate, context, instance, methodName)) { + // The class does not implement the method, so the call resolved to + // whatever it inherits. + entry.expected.Reset(isolate, method); + return; + } + } + + entry.quiet = true; + Warn(isolate, methodName, method); +} + +bool DispatchOverrides::DefinedAfterExtend(Isolate* isolate, Local context, + Local instance, Local name) { + // HasRealNamedProperty runs neither interceptors nor getters. + if (instance->HasRealNamedProperty(context, name).FromMaybe(false)) { + return true; + } + + auto prototype = instance->GetPrototype(); + if (prototype->IsObject() && + prototype.As()->HasRealNamedProperty(context, name).FromMaybe(false)) { + return true; + } + + return implementationObject_.Get(isolate)->HasRealNamedProperty(context, name).FromMaybe(false); +} + +void DispatchOverrides::Warn(Isolate* isolate, Local methodName, Local method) { + std::stringstream ss; + ss << "Java called \"" << ArgConverter::ConvertToString(methodName) << "\" on " << className_ + << " through a function other than the class's own implementation (an instance property " + "or a method replaced after extend)"; + + int line = method->GetScriptLineNumber(); + if (line != Function::kLineOffsetNotFound) { + auto resourceName = method->GetScriptOrigin().ResourceName(); + ss << " defined at " + << (resourceName->IsString() ? ArgConverter::ConvertToString(resourceName.As()) + : std::string("")) + << ":" << line + 1 << ":" << method->GetScriptColumnNumber() + 1; + } + + ss << ". This may stop working in a future version, as on iOS. Define it on the class. " + "Please report your use case."; + + __android_log_write(ANDROID_LOG_WARN, "JS", ss.str().c_str()); +} + +} // namespace tns + +#endif // APPLICATION_IN_DEBUG diff --git a/test-app/runtime/src/main/cpp/DispatchOverrides.h b/test-app/runtime/src/main/cpp/DispatchOverrides.h new file mode 100644 index 000000000..e80bdfb82 --- /dev/null +++ b/test-app/runtime/src/main/cpp/DispatchOverrides.h @@ -0,0 +1,92 @@ +#ifndef DISPATCHOVERRIDES_H_ +#define DISPATCHOVERRIDES_H_ + +#include +#include + +#include "v8.h" + +namespace tns { + +/* + * The methods one extend() call's implementation object defined when the class + * was created, checked in debug builds against what each Java->JS call actually + * dispatches to. Java->JS calls look the method up on the instance per call, so + * an own property of the instance or a method replaced after extend() wins; the + * iOS runtime binds methods at extend time and never sees either. A mismatch is + * logged once per class and method. + * + * Release builds compile none of this: the type stays incomplete and every + * pointer to it is null. + */ +class DispatchOverrides; + +#ifdef APPLICATION_IN_DEBUG + +class DispatchOverrides { + public: + // Reads only own data properties, so no getter of the object runs. + DispatchOverrides(v8::Isolate* isolate, v8::Local implementationObject, + std::string className); + + DispatchOverrides(const DispatchOverrides&) = delete; + DispatchOverrides& operator=(const DispatchOverrides&) = delete; + + // method is the function the call resolved to on instance. Never throws and + // never runs JS: microtasks would drain before the dispatched method. + void Check(v8::Isolate* isolate, v8::Local context, + v8::Local instance, v8::Local methodName, + int methodNameId, v8::Local method) { + if (methodNameId < 0) { + return; + } + auto index = static_cast(methodNameId); + if (index < byNameId_.size()) { + const auto& entry = byNameId_[index]; + if (entry.quiet || entry.expected == method) { + return; + } + } + CheckSlow(isolate, context, instance, methodName, index, method); + } + + private: + struct Captured { + v8::Global name; + // Empty when the property was an accessor or held no function. + v8::Global function; + }; + + // Indexed by the id Java's MethodNameIds gives the method name; ids are + // handed out on Java's first call with a name, so entries are bound lazily. + struct Bound { + bool bound = false; + // Warned already, or a name that is never checked. + bool quiet = false; + v8::Global expected; + }; + + void CheckSlow(v8::Isolate* isolate, v8::Local context, + v8::Local instance, v8::Local methodName, + size_t index, v8::Local method); + + // Whether JS code put name on the instance or its class after extend(): + // an own property of the instance, of its prototype, or of the + // implementation object. + bool DefinedAfterExtend(v8::Isolate* isolate, v8::Local context, + v8::Local instance, v8::Local name); + + void Warn(v8::Isolate* isolate, v8::Local methodName, + v8::Local method); + + std::string className_; + v8::Global implementationObject_; + std::vector captured_; + std::vector byNameId_; +}; + +#endif // APPLICATION_IN_DEBUG + +} // namespace tns + +#endif // DISPATCHOVERRIDES_H_ diff --git a/test-app/runtime/src/main/cpp/MetadataNode.cpp b/test-app/runtime/src/main/cpp/MetadataNode.cpp index 241bd8281..ba45f2e13 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.cpp +++ b/test-app/runtime/src/main/cpp/MetadataNode.cpp @@ -199,7 +199,8 @@ MetadataNode::MetadataNode(MetadataTreeNode* treeNode) : } Local MetadataNode::CreateExtendedJSWrapper(Isolate* isolate, ObjectManager* objectManager, const string& proxyClassName, - const Persistent** instanceTemplate) { + const Persistent** instanceTemplate, + DispatchOverrides** dispatchOverrides) { Local extInstance; auto cacheData = GetCachedExtendedClassData(isolate, proxyClassName); @@ -219,6 +220,7 @@ Local MetadataNode::CreateExtendedJSWrapper(Isolate* isolate, ObjectMana // running its constructor callback. auto context = Runtime::GetRuntime(isolate)->GetContext(); *instanceTemplate = cacheData.instanceTemplate; + *dispatchOverrides = cacheData.dispatchOverrides; if (cacheData.instanceTemplate->Get(isolate)->NewInstance(context).ToLocal(&extInstance)) { // V8 may copy instances from a cached instantiation of the template, which keeps the // prototype the class had then. This only matters if code reassigns the extended @@ -1605,7 +1607,8 @@ void MetadataNode::ExtendedClassConstructorCallback(const v8::FunctionCallbackIn bool success = CallbackHandlers::RegisterInstance(isolate, thiz, extData->fullClassName, argWrapper, implementationObject, false, extData->node->m_name, extData->defaultOverrides, extData->contentMemberNames ? &*extData->contentMemberNames : nullptr, &extData->resolvedClass, - &extData->instanceTemplate); + &extData->instanceTemplate, + extData->dispatchOverrides); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception e) { @@ -2369,7 +2372,9 @@ void MetadataNode::ExtendMethodCallback(const v8::FunctionCallbackInfo::New(isolate, *used.extendedCtorFunction); - cache->ExtendedCtorFuncCache.emplace(extendedCtorKey, ExtendedClassCacheData(usedCtorFunc, Local::New(isolate, *used.instanceTemplate), used.extendedName, used.node)); + ExtendedClassCacheData usedData(usedCtorFunc, Local::New(isolate, *used.instanceTemplate), used.extendedName, used.node); + usedData.dispatchOverrides = used.dispatchOverrides; + cache->ExtendedCtorFuncCache.emplace(extendedCtorKey, usedData); info.GetReturnValue().Set(usedCtorFunc); return; } @@ -2382,6 +2387,9 @@ void MetadataNode::ExtendMethodCallback(const v8::FunctionCallbackInfoOwn(node, extendNameAndLocation, implementationObject, fullExtendedName); extendedClassCallbackData->defaultOverrides = defaultOverrides; extendedClassCallbackData->contentMemberNames = std::move(contentMemberNames); +#ifdef APPLICATION_IN_DEBUG + extendedClassCallbackData->dispatchOverrides = cache->Own(isolate, implementationObject, DottedClassName(fullExtendedName)); +#endif auto extendData = External::New(isolate, extendedClassCallbackData, v8::kExternalPointerTypeTagDefault); auto extendFuncTemplate = FunctionTemplate::New(isolate, ExtendedClassConstructorCallback, extendData); extendFuncTemplate->InstanceTemplate()->SetInternalFieldCount(static_cast(ObjectManager::MetadataNodeKeys::END)); @@ -2414,6 +2422,7 @@ void MetadataNode::ExtendMethodCallback(const v8::FunctionCallbackInfoInstanceTemplate(), fullExtendedName, node); + cacheData.dispatchOverrides = extendedClassCallbackData->dispatchOverrides; cache->ExtendedCtorFuncCache.emplace(extendedCtorKey, cacheData); // CreateExtendedJSWrapper looks instances created from Java up by their // class name; the first extend of the class keeps serving those. Each @@ -2421,7 +2430,9 @@ void MetadataNode::ExtendMethodCallback(const v8::FunctionCallbackInfoExtendedCtorFuncCache.find(fullExtendedName) == cache->ExtendedCtorFuncCache.end()) { - cache->ExtendedCtorFuncCache.emplace(fullExtendedName, ExtendedClassCacheData(extendFunc, extendFuncTemplate->InstanceTemplate(), fullExtendedName, node)); + ExtendedClassCacheData classData(extendFunc, extendFuncTemplate->InstanceTemplate(), fullExtendedName, node); + classData.dispatchOverrides = extendedClassCallbackData->dispatchOverrides; + cache->ExtendedCtorFuncCache.emplace(fullExtendedName, classData); } else if (usesContentClassName) { cache->SharedExtendedClasses.emplace(fullExtendedName, false); } diff --git a/test-app/runtime/src/main/cpp/MetadataNode.h b/test-app/runtime/src/main/cpp/MetadataNode.h index b856ba61f..2a3f42976 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.h +++ b/test-app/runtime/src/main/cpp/MetadataNode.h @@ -70,10 +70,12 @@ class MetadataNode { static MetadataNode* GetNodeFromHandle(v8::Isolate* isolate, const v8::Local& value); - // instanceTemplate receives the template the wrapper was made from, which - // lives as long as this runtime's metadata cache. + // instanceTemplate and dispatchOverrides receive the template the wrapper was + // made from and its class's DispatchOverrides (null in release builds), which + // live as long as this runtime's metadata cache. static v8::Local CreateExtendedJSWrapper(v8::Isolate* isolate, ObjectManager* objectManager, const std::string& proxyClassName, - const v8::Persistent** instanceTemplate); + const v8::Persistent** instanceTemplate, + DispatchOverrides** dispatchOverrides); static v8::Local GetImplementationObject(v8::Isolate* isolate, const v8::Local& object); @@ -350,6 +352,8 @@ class MetadataNode { // The class cache's global ref for fullClassName once resolved; that cache never // drops or replaces an entry. jclass resolvedClass = nullptr; + // Owned by the MetadataNodeCache; null in release builds. + DispatchOverrides* dispatchOverrides = nullptr; }; struct TypeMetadata { @@ -393,6 +397,7 @@ class MetadataNode { v8::Persistent* instanceTemplate; std::string extendedName; MetadataNode* node; + DispatchOverrides* dispatchOverrides = nullptr; }; /* diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 20a2d4093..d48fcdb47 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -394,14 +394,27 @@ void ObjectManager::RegisterStrong(jobject object, int javaObjectID) { object, javaObjectID); } -Local ObjectManager::GetJsObjectByJavaObject(int javaObjectID) { +Local ObjectManager::GetJsObjectByJavaObject( + int javaObjectID, DispatchOverrides** dispatchOverrides) { auto isolate = m_isolate; EscapableHandleScope handleScope(isolate); auto state = m_idToObject.Find(javaObjectID); if (state == nullptr) { - return handleScope.Escape(RebuildCanary(javaObjectID)); + auto canary = RebuildCanary(javaObjectID); +#ifdef APPLICATION_IN_DEBUG + // A rebuilt canary is linked under javaObjectID. + if (dispatchOverrides != nullptr && !canary.IsEmpty()) { + *dispatchOverrides = m_idToObject.Find(javaObjectID)->dispatchOverrides; + } +#endif + return handleScope.Escape(canary); } +#ifdef APPLICATION_IN_DEBUG + if (dispatchOverrides != nullptr) { + *dispatchOverrides = state->dispatchOverrides; + } +#endif return handleScope.Escape(JsObjectFor(state)); } @@ -451,14 +464,26 @@ void ObjectManager::ReleaseUnwrappedArgs(const JavaCallArgs& args) { } } -Local ObjectManager::GetLinkedJsObjectByJavaObject(int javaObjectID) { +Local ObjectManager::GetLinkedJsObjectByJavaObject( + int javaObjectID, DispatchOverrides** dispatchOverrides) { auto state = m_idToObject.Find(javaObjectID); if (state == nullptr) { - return RebuildCanary(javaObjectID); + auto canary = RebuildCanary(javaObjectID); +#ifdef APPLICATION_IN_DEBUG + if (dispatchOverrides != nullptr && !canary.IsEmpty()) { + *dispatchOverrides = m_idToObject.Find(javaObjectID)->dispatchOverrides; + } +#endif + return canary; } if (!state->linked) { return Local(); } +#ifdef APPLICATION_IN_DEBUG + if (dispatchOverrides != nullptr) { + *dispatchOverrides = state->dispatchOverrides; + } +#endif return JsObjectFor(state); } @@ -569,7 +594,7 @@ Local ObjectManager::CreateJSWrapperHelper(jint javaObjectID, JEnv env; clazz = env.FindClass(className); } - Link(jsWrapper, javaObjectID, clazz, LinkKind::kPlain, nullptr, record); + Link(jsWrapper, javaObjectID, clazz, LinkKind::kPlain, nullptr, nullptr, record); } return jsWrapper; } @@ -579,12 +604,14 @@ Local ObjectManager::CreateJSWrapperHelper(jint javaObjectID, */ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, jclass clazz, LinkKind kind, - const Persistent* instanceTemplate) { - Link(object, javaObjectID, clazz, kind, instanceTemplate, std::nullopt); + const Persistent* instanceTemplate, + DispatchOverrides* dispatchOverrides) { + Link(object, javaObjectID, clazz, kind, instanceTemplate, dispatchOverrides, std::nullopt); } void ObjectManager::Link(const Local& object, uint32_t javaObjectID, jclass clazz, LinkKind kind, const Persistent* instanceTemplate, + DispatchOverrides* dispatchOverrides, std::optional record, bool hydrate) { if (!IsJsRuntimeObject(object)) { string errMsg("Trying to link invalid 'this' to a Java object"); @@ -597,6 +624,9 @@ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, jcl object->GetIdentityHash(), javaObjectID); auto state = new ObjectWeakCallbackState(this, javaObjectID, clazz, isolate, object); +#ifdef APPLICATION_IN_DEBUG + state->dispatchOverrides = dispatchOverrides; +#endif // Array buffers carry no Metadata field and cannot hold the canary handlers. state->canary = WrapperLifetimeCanary::Enabled() && HasMetadataField(object); @@ -619,7 +649,7 @@ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, jcl (void) inserted; if (state->canary) { - state->record = AdoptCanary(object, javaObjectID, kind, instanceTemplate, + state->record = AdoptCanary(object, javaObjectID, kind, instanceTemplate, dispatchOverrides, record.has_value() ? *record : FindCanaryRecord(javaObjectID), hydrate); if (state->record != nullptr && !state->record->key.IsEmpty()) { @@ -630,7 +660,8 @@ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, jcl ObjectManager::CanaryRecord* ObjectManager::AdoptCanary( const Local& object, uint32_t javaObjectID, LinkKind kind, - const Persistent* instanceTemplate, CanaryRecord* record, bool hydrate) { + const Persistent* instanceTemplate, DispatchOverrides* dispatchOverrides, + CanaryRecord* record, bool hydrate) { if (record == nullptr) { if (kind != LinkKind::kExtended) { return nullptr; @@ -649,7 +680,7 @@ ObjectManager::CanaryRecord* ObjectManager::AdoptCanary( instanceTemplate, object->GetPrototype(), object->GetInternalField(static_cast(MetadataNodeKeys::CallSuper)).As(), object->GetInternalField(static_cast(MetadataNodeKeys::Metadata)).As(), - implementationObject); + implementationObject, dispatchOverrides); record = NewCanaryRecord(javaObjectID); record->cls = cls; cls->records++; @@ -683,18 +714,20 @@ ObjectManager::CanaryRecord::~CanaryRecord() { ObjectManager::CanaryClass* ObjectManager::CanaryClassFor( const Persistent* instanceTemplate, const Local& prototype, const Local& callSuper, const Local& metadata, - const Local& implementationObject) { + const Local& implementationObject, DispatchOverrides* dispatchOverrides) { auto address = reinterpret_cast(instanceTemplate); CanaryClass*& slot = m_canaryClasses[((address >> 4) ^ (address >> 9)) % kCanaryClassSlots]; // Global == Local compares the objects, and an empty handle equals only an empty one. if (slot != nullptr && slot->instanceTemplate == instanceTemplate && slot->prototype == prototype && slot->callSuper == callSuper && - slot->metadata == metadata && slot->implementationObject == implementationObject) { + slot->metadata == metadata && slot->implementationObject == implementationObject && + slot->dispatchOverrides == dispatchOverrides) { return slot; } auto isolate = m_isolate; auto cls = new CanaryClass(); cls->instanceTemplate = instanceTemplate; + cls->dispatchOverrides = dispatchOverrides; cls->prototype.Reset(isolate, prototype); cls->callSuper.Reset(isolate, callSuper); cls->metadata.Reset(isolate, metadata); @@ -903,7 +936,8 @@ Local ObjectManager::RebuildCanary(int javaObjectID, CanaryRecord* recor if (!record->shell.IsEmpty()) { Local canary = record->shell.Get(isolate)->Clone(isolate); m_lifetimeStats.canaryRebuilds++; - Link(canary, javaObjectID, record->clazz, LinkKind::kExtended, nullptr, record, false); + Link(canary, javaObjectID, record->clazz, LinkKind::kExtended, nullptr, + record->cls->dispatchOverrides, record, false); return handleScope.Escape(canary); } @@ -931,7 +965,8 @@ Local ObjectManager::RebuildCanary(int javaObjectID, CanaryRecord* recor cls->implementationObject.Get(isolate)); } m_lifetimeStats.canaryRebuilds++; - Link(canary, javaObjectID, record->clazz, LinkKind::kExtended, nullptr, record); + Link(canary, javaObjectID, record->clazz, LinkKind::kExtended, nullptr, cls->dispatchOverrides, + record); // Taken before JS can reach the canary, so it holds nothing JS adds later // (#private brands, weak-collection keys); Link sets each clone's JsInfo. Local shell = canary->Clone(isolate); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index fe4bcf5b0..7678a33dc 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -11,6 +11,7 @@ #include #include "ArgsWrapper.h" +#include "DispatchOverrides.h" #include "JEnv.h" #include "JniLocalRef.h" #include "LRUCache.h" @@ -67,7 +68,10 @@ class ObjectManager { void RegisterStrong(jobject object, int javaObjectID); - v8::Local GetJsObjectByJavaObject(int javaObjectID); + // dispatchOverrides, when given, receives the wrapper's DispatchOverrides (null in + // release builds). + v8::Local GetJsObjectByJavaObject( + int javaObjectID, DispatchOverrides** dispatchOverrides = nullptr); // Settles the wrappers collected since the last flush. Called on JS<->Java calls and // constructions; field and array-element reads that hand JS a Java object skip it and @@ -102,7 +106,8 @@ class ObjectManager { // As GetJsObjectByJavaObject, but empty once the wrapper's link to the Java object was // released. Ids are never reused, so an id read without the isolate lock that names a // dead canary's record still names that record's object. - v8::Local GetLinkedJsObjectByJavaObject(int javaObjectID); + v8::Local GetLinkedJsObjectByJavaObject( + int javaObjectID, DispatchOverrides** dispatchOverrides = nullptr); v8::Local CreateJSWrapper(jint javaObjectID, const std::string& typeName); @@ -124,10 +129,12 @@ class ObjectManager { // instanceTemplate is the template object was made from, alive as long as // the runtime's metadata cache. Canary mode needs it for an extended link: - // a canary rebuilt later is an instance of it. + // a canary rebuilt later is an instance of it. dispatchOverrides belongs to + // the same cache. void Link(const v8::Local& object, uint32_t javaObjectID, jclass clazz, LinkKind kind = LinkKind::kPlain, - const v8::Persistent* instanceTemplate = nullptr); + const v8::Persistent* instanceTemplate = nullptr, + DispatchOverrides* dispatchOverrides = nullptr); void ReleaseNativeCounterpart(v8::Local& object); @@ -367,6 +374,9 @@ class ObjectManager { CanaryRecord* record = nullptr; // A canary of a keyed object that takeRekeys has not returned yet. bool rekeyPending = false; +#ifdef APPLICATION_IN_DEBUG + DispatchOverrides* dispatchOverrides = nullptr; +#endif }; // Canary mode: what a canary built later for a JS-extended instance starts @@ -378,6 +388,8 @@ class ObjectManager { v8::Global metadata; v8::Global implementationObject; const v8::Persistent* instanceTemplate = nullptr; + // What a rebuilt canary's link checks Java's calls against; null in release builds. + DispatchOverrides* dispatchOverrides = nullptr; uint32_t records = 0; // The m_canaryClasses slot offering it to new records, or null. CanaryClass** slot = nullptr; @@ -474,7 +486,8 @@ class ObjectManager { // hydrate false: object already carries the state's properties. void Link(const v8::Local& object, uint32_t javaObjectID, jclass clazz, LinkKind kind, const v8::Persistent* instanceTemplate, - std::optional record, bool hydrate = true); + DispatchOverrides* dispatchOverrides, std::optional record, + bool hydrate = true); // Registers a new canary: creates an extended instance's record, and // hydrates a canary for an object that already has state. record is @@ -482,7 +495,8 @@ class ObjectManager { CanaryRecord* AdoptCanary(const v8::Local& object, uint32_t javaObjectID, LinkKind kind, const v8::Persistent* instanceTemplate, - CanaryRecord* record, bool hydrate); + DispatchOverrides* dispatchOverrides, CanaryRecord* record, + bool hydrate); // The live canary state of holder, or null. ObjectWeakCallbackState* CanaryOf(const v8::Local& holder); @@ -577,7 +591,8 @@ class ObjectManager { const v8::Local& prototype, const v8::Local& callSuper, const v8::Local& metadata, - const v8::Local& implementationObject); + const v8::Local& implementationObject, + DispatchOverrides* dispatchOverrides); // Owns the records. ObjectIdIndex m_canaryRecords; size_t m_canaryRecordCount = 0; diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index 2737174a6..a9d74baab 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -622,8 +622,10 @@ jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj, // javaObjectID may be a hint read without the isolate lock; resolve it exactly when it // names neither a linked wrapper nor a canary that can be rebuilt. Local jsObject; + DispatchOverrides* dispatchOverrides = nullptr; if (javaObjectID != -1) { - jsObject = m_objectManager->GetLinkedJsObjectByJavaObject(javaObjectID); + jsObject = m_objectManager->GetLinkedJsObjectByJavaObject(javaObjectID, + &dispatchOverrides); } if (jsObject.IsEmpty() && javaObject != nullptr) { auto registeredAs = javaObjectID; @@ -645,7 +647,8 @@ jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj, throw NativeScriptException("Cannot find object id for an instance of " + m_objectManager->GetClassName(javaObject)); } - jsObject = m_objectManager->GetJsObjectByJavaObject(javaObjectID); + jsObject = m_objectManager->GetJsObjectByJavaObject(javaObjectID, + &dispatchOverrides); } if (jsObject.IsEmpty()) { stringstream ss; @@ -663,7 +666,8 @@ jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj, auto jsMethodName = GetCallbackMethodName(this, m_isolate, _env, methodName, methodNameId); auto jsResult = CallbackHandlers::CallJSMethod(m_isolate, env, jsObject, - jsMethodName, args); + jsMethodName, args, + dispatchOverrides, methodNameId); // Type::Null is the id of void.class: the Java caller discards the result. if (retType == static_cast(Type::Null)) { @@ -708,8 +712,9 @@ void Runtime::CreateJSInstanceNative(JNIEnv* _env, jobject obj, DEBUG_WRITE("createJSInstanceNative class %s", jniName.c_str()); const Persistent* instanceTemplate = nullptr; - jsInstance = MetadataNode::CreateExtendedJSWrapper(isolate, m_objectManager, - jniName, &instanceTemplate); + DispatchOverrides* dispatchOverrides = nullptr; + jsInstance = MetadataNode::CreateExtendedJSWrapper( + isolate, m_objectManager, jniName, &instanceTemplate, &dispatchOverrides); if (jsInstance.IsEmpty()) { throw NativeScriptException( @@ -728,7 +733,8 @@ void Runtime::CreateJSInstanceNative(JNIEnv* _env, jobject obj, jclass clazz = env.FindClass(jniName); m_objectManager->Link(jsInstance, javaObjectID, clazz, - ObjectManager::LinkKind::kExtended, instanceTemplate); + ObjectManager::LinkKind::kExtended, instanceTemplate, + dispatchOverrides); } jint Runtime::GenerateNewObjectId(JNIEnv* env, jobject obj) { From d09de5abd46bf7ae7e62af4ada7b482da7a7241e Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 14:17:21 -0300 Subject: [PATCH 2/6] test(runtime): cover the dispatch-override warning Specs for a class's own method (no warning), an instance own property, a TypeScript class field, a method replaced on the implementation object and one added to the class prototype after extend(), a Java-created instance, and repeated calls on several instances (one warning). Each spec checks the JS function Java reached and counts the warning in logcat through a LogcatUtil helper that leaves the log in place. --- test-app/app/src/main/assets/app/mainpage.js | 1 + .../app/tests/testDispatchOverrideWarnings.js | 137 ++++++++++++++++++ .../main/java/com/tns/tests/LogcatUtil.java | 16 ++ 3 files changed, 154 insertions(+) create mode 100644 test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index 6a9d28837..786802226 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -71,6 +71,7 @@ require("./tests/testWrapperLifetimeLeaks"); require("./tests/testsMemoryManagement"); require("./tests/testFieldGetSet"); require("./tests/extendedClassesTests"); +require("./tests/testDispatchOverrideWarnings"); require("./tests/extendClassNameTests"); require("./tests/testJniReferenceLeak"); require("./tests/testNativeModules"); diff --git a/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js b/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js new file mode 100644 index 000000000..4293a1343 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js @@ -0,0 +1,137 @@ +// Java->JS calls look the method up on the instance on every call, so an own +// property of the instance or a method replaced after extend() is what runs. Debug +// builds keep calling it but log a warning once per class and method, since the +// iOS runtime binds the class's methods at extend time instead. Every spec extends +// a class of its own: the warning names the class, and each is logged only once. +// Interfaces are named in full so the static binding generator implements them. +describe("Java->JS calls through a function other than the class's own", function () { + var LogcatUtil = com.tns.tests.LogcatUtil; + + function runFromJava(runnable) { + new java.util.concurrent.FutureTask(runnable, null).run(); + } + + function warnings(className) { + return LogcatUtil.countJsWarnings(className, 'Java called "run" on '); + } + + it("calls the class's own method without a warning", function () { + var runs = 0; + var C = java.lang.Object.extend("DispatchWarnOwnMethod", { + interfaces: [java.lang.Runnable], + run: function () { runs++; } + }); + var instance = new C(); + + runFromJava(instance); + runFromJava(new C()); + + expect(runs).toBe(2); + expect(warnings("DispatchWarnOwnMethod")).toBe(0); + }); + + it("calls an instance's own property and warns", function () { + var classRuns = 0; + var ownRuns = 0; + var C = java.lang.Object.extend("DispatchWarnInstanceProperty", { + interfaces: [java.lang.Runnable], + run: function () { classRuns++; } + }); + var instance = new C(); + instance.run = function () { ownRuns++; }; + + runFromJava(instance); + + expect(ownRuns).toBe(1); + expect(classRuns).toBe(0); + expect(warnings("DispatchWarnInstanceProperty")).toBe(1); + }); + + it("calls a TypeScript class field and warns", function () { + var fieldRuns = 0; + var FieldClass = (function (_super) { + __extends(DispatchWarnClassField, _super); + function DispatchWarnClassField() { + var _this = _super.call(this) || this; + _this.run = function () { fieldRuns++; }; + return _this; + } + DispatchWarnClassField = __decorate([ + Interfaces([java.lang.Runnable]) + ], DispatchWarnClassField); + return DispatchWarnClassField; + }(java.lang.Object)); + var instance = new FieldClass(); + + runFromJava(instance); + + expect(fieldRuns).toBe(1); + expect(warnings("DispatchWarnClassField")).toBe(1); + }); + + it("calls a method replaced after extend and warns", function () { + var originalRuns = 0; + var replacedRuns = 0; + var implementation = { + interfaces: [java.lang.Runnable], + run: function () { originalRuns++; } + }; + var C = java.lang.Object.extend("DispatchWarnReplacedMethod", implementation); + var instance = new C(); + implementation.run = function () { replacedRuns++; }; + + runFromJava(instance); + + expect(replacedRuns).toBe(1); + expect(originalRuns).toBe(0); + expect(warnings("DispatchWarnReplacedMethod")).toBe(1); + }); + + it("calls a method added to the class's prototype after extend and warns", function () { + var originalRuns = 0; + var addedRuns = 0; + var C = java.lang.Object.extend("DispatchWarnPrototypeMethod", { + interfaces: [java.lang.Runnable], + run: function () { originalRuns++; } + }); + C.prototype.run = function () { addedRuns++; }; + + runFromJava(new C()); + + expect(addedRuns).toBe(1); + expect(originalRuns).toBe(0); + expect(warnings("DispatchWarnPrototypeMethod")).toBe(1); + }); + + it("warns once however often and on however many instances the call repeats", function () { + var ownRuns = 0; + var C = java.lang.Object.extend("DispatchWarnRepeated", { + interfaces: [java.lang.Runnable], + run: function () {} + }); + for (var i = 0; i < 3; i++) { + var instance = new C(); + instance.run = function () { ownRuns++; }; + runFromJava(instance); + runFromJava(instance); + } + + expect(ownRuns).toBe(6); + expect(warnings("DispatchWarnRepeated")).toBe(1); + }); + + it("calls an instance's own property on an instance Java created and warns", function () { + var ownRuns = 0; + var C = java.lang.Object.extend("DispatchWarnJavaCreated", { + interfaces: [java.lang.Runnable], + run: function () {} + }); + var instance = com.tns.tests.JavaCreated.newInstance(new C().getClass()); + instance.run = function () { ownRuns++; }; + + runFromJava(instance); + + expect(ownRuns).toBe(1); + expect(warnings("DispatchWarnJavaCreated")).toBe(1); + }); +}); diff --git a/test-app/app/src/main/java/com/tns/tests/LogcatUtil.java b/test-app/app/src/main/java/com/tns/tests/LogcatUtil.java index ff30fad25..7ebb3e4be 100644 --- a/test-app/app/src/main/java/com/tns/tests/LogcatUtil.java +++ b/test-app/app/src/main/java/com/tns/tests/LogcatUtil.java @@ -21,4 +21,20 @@ public static boolean logcatContainsString(String str) throws Exception { return output.contains(str); } + + // Lines this app logged under the JS tag at warning level or above that contain both + // strings. Leaves the log in place, so earlier lines count too. + public static int countJsWarnings(String needle, String otherNeedle) throws Exception { + Process process = Runtime.getRuntime().exec(new String[]{"logcat", "-d", "-v", "raw", "-s", "JS:W"}); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); + int count = 0; + String line; + while ((line = bufferedReader.readLine()) != null) { + if (line.contains(needle) && line.contains(otherNeedle)) { + count++; + } + } + process.waitFor(); + return count; + } } From 75f3de356147c61c1cae30a85d73d51ba2671422 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 14:26:30 -0300 Subject: [PATCH 3/6] test(runtime): count only this process's dispatch warnings The log outlives the app, so a second run on the same device counted the warnings of the first. Lines are now matched to android.os.Process.myPid(); logcat's --pid filter needs API 24. --- .../app/src/main/java/com/tns/tests/LogcatUtil.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/test-app/app/src/main/java/com/tns/tests/LogcatUtil.java b/test-app/app/src/main/java/com/tns/tests/LogcatUtil.java index 7ebb3e4be..b90e5dafa 100644 --- a/test-app/app/src/main/java/com/tns/tests/LogcatUtil.java +++ b/test-app/app/src/main/java/com/tns/tests/LogcatUtil.java @@ -22,14 +22,20 @@ public static boolean logcatContainsString(String str) throws Exception { return output.contains(str); } - // Lines this app logged under the JS tag at warning level or above that contain both - // strings. Leaves the log in place, so earlier lines count too. + // Lines this process logged under the JS tag at warning level or above that contain + // both strings. Leaves the log in place, so earlier lines of this process count too. public static int countJsWarnings(String needle, String otherNeedle) throws Exception { - Process process = Runtime.getRuntime().exec(new String[]{"logcat", "-d", "-v", "raw", "-s", "JS:W"}); + // -v brief prefixes each line with "W/JS ( 1234): "; --pid needs API 24. + String pidTag = "(" + android.os.Process.myPid() + "):"; + Process process = Runtime.getRuntime().exec(new String[]{"logcat", "-d", "-v", "brief", "-s", "JS:W"}); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); int count = 0; String line; while ((line = bufferedReader.readLine()) != null) { + int prefixEnd = line.indexOf("):"); + if (prefixEnd < 0 || !line.substring(0, prefixEnd + 2).replace(" ", "").endsWith(pidTag)) { + continue; + } if (line.contains(needle) && line.contains(otherNeedle)) { count++; } From b4e542dc7e2e767392378fbc5842b2e778632984 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 14:43:17 -0300 Subject: [PATCH 4/6] feat(runtime): warn on own-property dispatch for interface literals `new SomeInterface({...})` gives every instance its own implementation object, so it has no per-class record to compare against. For wrappers without a record, debug builds now check whether the receiver itself owns the method name and, if so, log the same warning once per Java class and method per runtime. This costs one own-property lookup per Java->JS call on those instances, in debug builds only; records keep the pointer compare. ObjectManager::GetJavaClass now returns null for an object without a link instead of dereferencing a null info. Specs: a plain interface literal called from Java does not warn; one whose instance gets its own `run` still runs it and warns once over two calls. --- .../app/tests/testDispatchOverrideWarnings.js | 34 +++++++++++++- .../runtime/src/main/cpp/CallbackHandlers.cpp | 2 + .../src/main/cpp/DispatchOverrides.cpp | 47 +++++++++++++++++-- .../runtime/src/main/cpp/DispatchOverrides.h | 14 +++++- .../runtime/src/main/cpp/ObjectManager.cpp | 4 +- 5 files changed, 91 insertions(+), 10 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js b/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js index 4293a1343..f4ce79d02 100644 --- a/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js +++ b/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js @@ -1,8 +1,8 @@ // Java->JS calls look the method up on the instance on every call, so an own // property of the instance or a method replaced after extend() is what runs. Debug // builds keep calling it but log a warning once per class and method, since the -// iOS runtime binds the class's methods at extend time instead. Every spec extends -// a class of its own: the warning names the class, and each is logged only once. +// iOS runtime binds the class's methods at extend time instead. Every extend() spec +// uses a class of its own: the warning names the class, and each is logged only once. // Interfaces are named in full so the static binding generator implements them. describe("Java->JS calls through a function other than the class's own", function () { var LogcatUtil = com.tns.tests.LogcatUtil; @@ -120,6 +120,36 @@ describe("Java->JS calls through a function other than the class's own", functio expect(warnings("DispatchWarnRepeated")).toBe(1); }); + // Every `new Runnable({...})` shares one Java class, so the spec without an override + // runs first and both count only the warnings their own calls add. + it("calls an interface implementation's method without a warning", function () { + var runs = 0; + var runnable = new java.lang.Runnable({ run: function () { runs++; } }); + var className = String(runnable.getClass().getName()); + var before = warnings(className); + + runFromJava(runnable); + + expect(runs).toBe(1); + expect(warnings(className)).toBe(before); + }); + + it("calls an own property of an interface implementation and warns once", function () { + var implementationRuns = 0; + var ownRuns = 0; + var runnable = new java.lang.Runnable({ run: function () { implementationRuns++; } }); + var className = String(runnable.getClass().getName()); + var before = warnings(className); + runnable.run = function () { ownRuns++; }; + + runFromJava(runnable); + runFromJava(runnable); + + expect(ownRuns).toBe(2); + expect(implementationRuns).toBe(0); + expect(warnings(className)).toBe(before + 1); + }); + it("calls an instance's own property on an instance Java created and warns", function () { var ownRuns = 0; var C = java.lang.Object.extend("DispatchWarnJavaCreated", { diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index f09ccf718..74279aaaa 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -1273,6 +1273,8 @@ Local CallbackHandlers::CallJSMethod(Isolate *isolate, JNIEnv *_env, #ifdef APPLICATION_IN_DEBUG if (dispatchOverrides != nullptr) { dispatchOverrides->Check(isolate, context, jsObject, methodName, methodNameId, jsMethod); + } else { + DispatchOverrides::CheckInstanceProperty(isolate, context, jsObject, methodName, methodNameId, jsMethod); } #endif int argc = args.count; diff --git a/test-app/runtime/src/main/cpp/DispatchOverrides.cpp b/test-app/runtime/src/main/cpp/DispatchOverrides.cpp index 4d3e443f2..e7a87ff3b 100644 --- a/test-app/runtime/src/main/cpp/DispatchOverrides.cpp +++ b/test-app/runtime/src/main/cpp/DispatchOverrides.cpp @@ -4,9 +4,14 @@ #include +#include +#include #include +#include #include "ArgConverter.h" +#include "ObjectManager.h" +#include "RuntimeState.h" using namespace v8; @@ -88,7 +93,7 @@ void DispatchOverrides::CheckSlow(Isolate* isolate, Local context, } entry.quiet = true; - Warn(isolate, methodName, method); + Warn(className_, methodName, method); } bool DispatchOverrides::DefinedAfterExtend(Isolate* isolate, Local context, @@ -107,9 +112,45 @@ bool DispatchOverrides::DefinedAfterExtend(Isolate* isolate, Local cont return implementationObject_.Get(isolate)->HasRealNamedProperty(context, name).FromMaybe(false); } -void DispatchOverrides::Warn(Isolate* isolate, Local methodName, Local method) { +namespace { +// Keyed by jclass: an instance holds its class's global ref from the class cache, +// which has one per class. +struct InstancePropertyWarnings { + std::set> warned; +}; +} // namespace + +void DispatchOverrides::CheckInstanceProperty(Isolate* isolate, Local context, + Local instance, Local methodName, + int methodNameId, Local method) { + if (methodNameId < 0 || + !instance->HasRealNamedProperty(context, methodName).FromMaybe(false)) { + return; + } + + auto* runtime = Runtime::TryGetRuntime(isolate); + if (runtime == nullptr) { + return; + } + auto* warnings = RuntimeState::For(runtime); + if (warnings == nullptr) { + return; + } + + jclass clazz = runtime->GetObjectManager()->GetJavaClass(instance); + if (!warnings->warned.emplace(clazz, methodNameId).second) { + return; + } + + std::string className = clazz != nullptr ? ObjectManager::GetClassName(clazz) : "a Java object"; + std::replace(className.begin(), className.end(), '/', '.'); + Warn(className, methodName, method); +} + +void DispatchOverrides::Warn(const std::string& className, Local methodName, + Local method) { std::stringstream ss; - ss << "Java called \"" << ArgConverter::ConvertToString(methodName) << "\" on " << className_ + ss << "Java called \"" << ArgConverter::ConvertToString(methodName) << "\" on " << className << " through a function other than the class's own implementation (an instance property " "or a method replaced after extend)"; diff --git a/test-app/runtime/src/main/cpp/DispatchOverrides.h b/test-app/runtime/src/main/cpp/DispatchOverrides.h index e80bdfb82..0f068edd8 100644 --- a/test-app/runtime/src/main/cpp/DispatchOverrides.h +++ b/test-app/runtime/src/main/cpp/DispatchOverrides.h @@ -32,6 +32,16 @@ class DispatchOverrides { DispatchOverrides(const DispatchOverrides&) = delete; DispatchOverrides& operator=(const DispatchOverrides&) = delete; + /* + * For an instance whose class has no record: `new SomeInterface({...})` gives + * each instance its own implementation object, its prototype, so only an own + * property of the instance is reported. Same contract as Check. + */ + static void CheckInstanceProperty(v8::Isolate* isolate, v8::Local context, + v8::Local instance, + v8::Local methodName, int methodNameId, + v8::Local method); + // method is the function the call resolved to on instance. Never throws and // never runs JS: microtasks would drain before the dispatched method. void Check(v8::Isolate* isolate, v8::Local context, @@ -76,8 +86,8 @@ class DispatchOverrides { bool DefinedAfterExtend(v8::Isolate* isolate, v8::Local context, v8::Local instance, v8::Local name); - void Warn(v8::Isolate* isolate, v8::Local methodName, - v8::Local method); + static void Warn(const std::string& className, v8::Local methodName, + v8::Local method); std::string className_; v8::Global implementationObject_; diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index d48fcdb47..5d9552785 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -358,9 +358,7 @@ jclass ObjectManager::GetJavaClass(const Local& instance) { DEBUG_WRITE("GetClass called"); JSInstanceInfo* jsInfo = GetJSInstanceInfo(instance); - jclass clazz = jsInfo->objectClazz; - - return clazz; + return jsInfo != nullptr ? jsInfo->objectClazz : nullptr; } void ObjectManager::SetJavaClass(const Local& instance, jclass clazz) { From 08d7ae3f8906ff454d4d6224062d1f044de0e009 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 23 Nov 2026 01:35:17 -0300 Subject: [PATCH 5/6] fix(runtime): read only an own value from a captured descriptor An accessor's property descriptor has no own value, so reading one walked to Object.prototype and could run a getter defined there during extend(). --- .../app/tests/testDispatchOverrideWarnings.js | 27 +++++++++++++++++++ .../src/main/cpp/DispatchOverrides.cpp | 3 +++ 2 files changed, 30 insertions(+) diff --git a/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js b/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js index f4ce79d02..3c653e1a0 100644 --- a/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js +++ b/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js @@ -164,4 +164,31 @@ describe("Java->JS calls through a function other than the class's own", functio expect(ownRuns).toBe(1); expect(warnings("DispatchWarnJavaCreated")).toBe(1); }); + + // The getter on Object.prototype.value is installed only around extend(): while it + // is there, Object.defineProperty reads every accessor descriptor as having a value. + it("runs no inherited getter while extend() captures an accessor", function () { + var inheritedReads = 0; + var implementation = { + interfaces: [java.lang.Runnable], + run: function () {} + }; + Object.defineProperty(implementation, "state", { + get: function () { return 1; }, + enumerable: true, + configurable: true + }); + + Object.defineProperty(Object.prototype, "value", { + get: function () { inheritedReads++; return undefined; }, + configurable: true + }); + try { + java.lang.Object.extend("DispatchWarnAccessorCapture", implementation); + } finally { + delete Object.prototype.value; + } + + expect(inheritedReads).toBe(0); + }); }); diff --git a/test-app/runtime/src/main/cpp/DispatchOverrides.cpp b/test-app/runtime/src/main/cpp/DispatchOverrides.cpp index e7a87ff3b..65c402f56 100644 --- a/test-app/runtime/src/main/cpp/DispatchOverrides.cpp +++ b/test-app/runtime/src/main/cpp/DispatchOverrides.cpp @@ -42,11 +42,14 @@ DispatchOverrides::DispatchOverrides(Isolate* isolate, Local implementat Captured entry; entry.name.Reset(isolate, name.As()); + // A descriptor inherits from Object.prototype, and an accessor's has no own + // value: reading it there could run a getter. Local descriptor; Local value; if (implementationObject->GetOwnPropertyDescriptor(context, name.As()) .ToLocal(&descriptor) && descriptor->IsObject() && + descriptor.As()->HasOwnProperty(context, valueKey).FromMaybe(false) && descriptor.As()->Get(context, valueKey).ToLocal(&value) && value->IsFunction()) { entry.function.Reset(isolate, value.As()); From 1b7f896e7fed9c8ecc1eef37fe3e6ee1c9e32aad Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 23 Nov 2026 01:35:34 -0300 Subject: [PATCH 6/6] fix(runtime): warn when an instance supplies a member the class held no function for A class member defined as a non-function data property, such as run: null, was exempt like an accessor, so Java calling a function an instance assigned under that name logged nothing. Only accessors stay exempt now. --- .../app/tests/testDispatchOverrideWarnings.js | 16 +++++++++++++ .../src/main/cpp/DispatchOverrides.cpp | 23 +++++++++++-------- .../runtime/src/main/cpp/DispatchOverrides.h | 5 +++- 3 files changed, 34 insertions(+), 10 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js b/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js index 3c653e1a0..d16ae277a 100644 --- a/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js +++ b/test-app/app/src/main/assets/app/tests/testDispatchOverrideWarnings.js @@ -103,6 +103,22 @@ describe("Java->JS calls through a function other than the class's own", functio expect(warnings("DispatchWarnPrototypeMethod")).toBe(1); }); + it("calls an instance's function for a member the class defined as null and warns", function () { + var ownRuns = 0; + var C = java.lang.Object.extend("DispatchWarnNullMember", { + interfaces: [java.lang.Runnable], + run: null + }); + var instance = new C(); + instance.run = function () { ownRuns++; }; + + runFromJava(instance); + runFromJava(instance); + + expect(ownRuns).toBe(2); + expect(warnings("DispatchWarnNullMember")).toBe(1); + }); + it("warns once however often and on however many instances the call repeats", function () { var ownRuns = 0; var C = java.lang.Object.extend("DispatchWarnRepeated", { diff --git a/test-app/runtime/src/main/cpp/DispatchOverrides.cpp b/test-app/runtime/src/main/cpp/DispatchOverrides.cpp index 65c402f56..fefc78aba 100644 --- a/test-app/runtime/src/main/cpp/DispatchOverrides.cpp +++ b/test-app/runtime/src/main/cpp/DispatchOverrides.cpp @@ -45,14 +45,16 @@ DispatchOverrides::DispatchOverrides(Isolate* isolate, Local implementat // A descriptor inherits from Object.prototype, and an accessor's has no own // value: reading it there could run a getter. Local descriptor; - Local value; if (implementationObject->GetOwnPropertyDescriptor(context, name.As()) .ToLocal(&descriptor) && descriptor->IsObject() && - descriptor.As()->HasOwnProperty(context, valueKey).FromMaybe(false) && - descriptor.As()->Get(context, valueKey).ToLocal(&value) && - value->IsFunction()) { - entry.function.Reset(isolate, value.As()); + descriptor.As()->HasOwnProperty(context, valueKey).FromMaybe(false)) { + entry.dataProperty = true; + Local value; + if (descriptor.As()->Get(context, valueKey).ToLocal(&value) && + value->IsFunction()) { + entry.function.Reset(isolate, value.As()); + } } captured_.push_back(std::move(entry)); @@ -79,13 +81,16 @@ void DispatchOverrides::CheckSlow(Isolate* isolate, Local context, } if (captured != nullptr) { - if (captured->function.IsEmpty()) { + if (!captured->dataProperty) { entry.quiet = true; return; } - entry.expected.Reset(isolate, captured->function); - if (entry.expected == method) { - return; + // A data property that held no function never matches what Java calls. + if (!captured->function.IsEmpty()) { + entry.expected.Reset(isolate, captured->function); + if (entry.expected == method) { + return; + } } } else if (!DefinedAfterExtend(isolate, context, instance, methodName)) { // The class does not implement the method, so the call resolved to diff --git a/test-app/runtime/src/main/cpp/DispatchOverrides.h b/test-app/runtime/src/main/cpp/DispatchOverrides.h index 0f068edd8..e72306934 100644 --- a/test-app/runtime/src/main/cpp/DispatchOverrides.h +++ b/test-app/runtime/src/main/cpp/DispatchOverrides.h @@ -63,8 +63,11 @@ class DispatchOverrides { private: struct Captured { v8::Global name; - // Empty when the property was an accessor or held no function. + // Empty unless the property was a data property holding a function. v8::Global function; + // False for an accessor, whose calls are never checked: what they resolve + // to depends on its getter. + bool dataProperty = false; }; // Indexed by the id Java's MethodNameIds gives the method name; ids are