Skip to content

Commit 2dc604f

Browse files
committed
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.
1 parent 9a514a7 commit 2dc604f

10 files changed

Lines changed: 301 additions & 22 deletions

‎test-app/runtime/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ add_library(
193193
src/main/cpp/IsolateTracked.cpp
194194
src/main/cpp/JEnv.cpp
195195
src/main/cpp/DesugaredInterfaceCompanionClassNameResolver.cpp
196+
src/main/cpp/DispatchOverrides.cpp
196197
src/main/cpp/JType.cpp
197198
src/main/cpp/JniSignatureParser.cpp
198199
src/main/cpp/JsArgConverter.cpp

‎test-app/runtime/src/main/cpp/CallbackHandlers.cpp‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,8 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local<Object> &j
214214
bool isInterface,
215215
const std::string &baseClassName,
216216
uint64_t defaultOverrides,
217-
const vector<string> *contentMemberNames) {
217+
const vector<string> *contentMemberNames,
218+
DispatchOverrides *dispatchOverrides) {
218219
bool success;
219220

220221
DEBUG_WRITE("RegisterInstance called for '%s'", fullClassName.c_str());
@@ -236,7 +237,7 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local<Object> &j
236237

237238
int javaObjectID = objectManager->GenerateNewObjectID();
238239

239-
objectManager->Link(jsObject, javaObjectID, nullptr);
240+
objectManager->Link(jsObject, javaObjectID, nullptr, dispatchOverrides);
240241

241242
// resolve constructor
242243
const auto &mi = MethodCache::ResolveConstructorSignature(argWrapper, fullClassName,
@@ -1228,7 +1229,8 @@ vector<string> CallbackHandlers::GetTypeMetadata(const string &name, int index)
12281229

12291230
Local<Value> CallbackHandlers::CallJSMethod(Isolate *isolate, JNIEnv *_env,
12301231
const Local<Object> &jsObject, const Local<String> &methodName,
1231-
const JavaCallArgs &args) {
1232+
const JavaCallArgs &args, DispatchOverrides *dispatchOverrides,
1233+
int methodNameId) {
12321234
SET_PROFILER_FRAME();
12331235

12341236
JEnv env(_env);
@@ -1249,6 +1251,11 @@ Local<Value> CallbackHandlers::CallJSMethod(Isolate *isolate, JNIEnv *_env,
12491251
EscapableHandleScope handleScope(isolate);
12501252

12511253
auto jsMethod = method.As<Function>();
1254+
#ifdef APPLICATION_IN_DEBUG
1255+
if (dispatchOverrides != nullptr) {
1256+
dispatchOverrides->Check(isolate, context, jsObject, methodName, methodNameId, jsMethod);
1257+
}
1258+
#endif
12521259
int argc = args.count;
12531260

12541261
constexpr int kInlineArgs = 16;

‎test-app/runtime/src/main/cpp/CallbackHandlers.h‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ namespace tns {
4242
bool isInterface,
4343
const std::string &baseClassName = std::string(),
4444
uint64_t defaultOverrides = 0,
45-
const std::vector<std::string> *contentMemberNames = nullptr);
45+
const std::vector<std::string> *contentMemberNames = nullptr,
46+
DispatchOverrides *dispatchOverrides = nullptr);
4647

4748
// Whether GetImplementedInterfaces would list any interface, without calling Java.
4849
static bool HasImplementedInterfaces(v8::Isolate *isolate, const v8::Local<v8::Object> &implementationObject);
@@ -97,7 +98,8 @@ namespace tns {
9798

9899
static v8::Local<v8::Value>
99100
CallJSMethod(v8::Isolate *isolate, JNIEnv *_env, const v8::Local<v8::Object> &jsObject,
100-
const v8::Local<v8::String> &methodName, const JavaCallArgs &args);
101+
const v8::Local<v8::String> &methodName, const JavaCallArgs &args,
102+
DispatchOverrides *dispatchOverrides = nullptr, int methodNameId = -1);
101103

102104
static v8::Local<v8::Value>
103105
GetJavaField(v8::Isolate *isolate, const v8::Local<v8::Object> &caller,
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
#include "DispatchOverrides.h"
2+
3+
#ifdef APPLICATION_IN_DEBUG
4+
5+
#include <android/log.h>
6+
7+
#include <sstream>
8+
9+
#include "ArgConverter.h"
10+
11+
using namespace v8;
12+
13+
namespace tns {
14+
15+
DispatchOverrides::DispatchOverrides(Isolate* isolate, Local<Object> implementationObject,
16+
std::string className)
17+
: className_(std::move(className)), implementationObject_(isolate, implementationObject) {
18+
auto context = isolate->GetCurrentContext();
19+
TryCatch tc(isolate);
20+
21+
Local<Array> names;
22+
if (!implementationObject
23+
->GetOwnPropertyNames(context, PropertyFilter::SKIP_SYMBOLS)
24+
.ToLocal(&names)) {
25+
return;
26+
}
27+
28+
auto valueKey = ArgConverter::ConvertToV8String(isolate, std::string("value"));
29+
uint32_t length = names->Length();
30+
captured_.reserve(length);
31+
for (uint32_t i = 0; i < length; i++) {
32+
Local<Value> name;
33+
if (!names->Get(context, i).ToLocal(&name) || !name->IsString()) {
34+
continue;
35+
}
36+
37+
Captured entry;
38+
entry.name.Reset(isolate, name.As<String>());
39+
40+
Local<Value> descriptor;
41+
Local<Value> value;
42+
if (implementationObject->GetOwnPropertyDescriptor(context, name.As<String>())
43+
.ToLocal(&descriptor) &&
44+
descriptor->IsObject() &&
45+
descriptor.As<Object>()->Get(context, valueKey).ToLocal(&value) &&
46+
value->IsFunction()) {
47+
entry.function.Reset(isolate, value.As<Function>());
48+
}
49+
50+
captured_.push_back(std::move(entry));
51+
}
52+
}
53+
54+
void DispatchOverrides::CheckSlow(Isolate* isolate, Local<Context> context,
55+
Local<Object> instance, Local<String> methodName,
56+
size_t index, Local<Function> method) {
57+
if (index >= byNameId_.size()) {
58+
byNameId_.resize(index + 1);
59+
}
60+
auto& entry = byNameId_[index];
61+
62+
if (!entry.bound) {
63+
entry.bound = true;
64+
65+
const Captured* captured = nullptr;
66+
for (const auto& candidate : captured_) {
67+
if (candidate.name.Get(isolate)->StringEquals(methodName)) {
68+
captured = &candidate;
69+
break;
70+
}
71+
}
72+
73+
if (captured != nullptr) {
74+
if (captured->function.IsEmpty()) {
75+
entry.quiet = true;
76+
return;
77+
}
78+
entry.expected.Reset(isolate, captured->function);
79+
if (entry.expected == method) {
80+
return;
81+
}
82+
} else if (!DefinedAfterExtend(isolate, context, instance, methodName)) {
83+
// The class does not implement the method, so the call resolved to
84+
// whatever it inherits.
85+
entry.expected.Reset(isolate, method);
86+
return;
87+
}
88+
}
89+
90+
entry.quiet = true;
91+
Warn(isolate, methodName, method);
92+
}
93+
94+
bool DispatchOverrides::DefinedAfterExtend(Isolate* isolate, Local<Context> context,
95+
Local<Object> instance, Local<String> name) {
96+
// HasRealNamedProperty runs neither interceptors nor getters.
97+
if (instance->HasRealNamedProperty(context, name).FromMaybe(false)) {
98+
return true;
99+
}
100+
101+
auto prototype = instance->GetPrototype();
102+
if (prototype->IsObject() &&
103+
prototype.As<Object>()->HasRealNamedProperty(context, name).FromMaybe(false)) {
104+
return true;
105+
}
106+
107+
return implementationObject_.Get(isolate)->HasRealNamedProperty(context, name).FromMaybe(false);
108+
}
109+
110+
void DispatchOverrides::Warn(Isolate* isolate, Local<String> methodName, Local<Function> method) {
111+
std::stringstream ss;
112+
ss << "Java called \"" << ArgConverter::ConvertToString(methodName) << "\" on " << className_
113+
<< " through a function other than the class's own implementation (an instance property "
114+
"or a method replaced after extend)";
115+
116+
int line = method->GetScriptLineNumber();
117+
if (line != Function::kLineOffsetNotFound) {
118+
auto resourceName = method->GetScriptOrigin().ResourceName();
119+
ss << " defined at "
120+
<< (resourceName->IsString() ? ArgConverter::ConvertToString(resourceName.As<String>())
121+
: std::string("<anonymous>"))
122+
<< ":" << line + 1 << ":" << method->GetScriptColumnNumber() + 1;
123+
}
124+
125+
ss << ". This may stop working in a future version, as on iOS. Define it on the class. "
126+
"Please report your use case.";
127+
128+
__android_log_write(ANDROID_LOG_WARN, "JS", ss.str().c_str());
129+
}
130+
131+
} // namespace tns
132+
133+
#endif // APPLICATION_IN_DEBUG
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
#ifndef DISPATCHOVERRIDES_H_
2+
#define DISPATCHOVERRIDES_H_
3+
4+
#include <string>
5+
#include <vector>
6+
7+
#include "v8.h"
8+
9+
namespace tns {
10+
11+
/*
12+
* The methods one extend() call's implementation object defined when the class
13+
* was created, checked in debug builds against what each Java->JS call actually
14+
* dispatches to. Java->JS calls look the method up on the instance per call, so
15+
* an own property of the instance or a method replaced after extend() wins; the
16+
* iOS runtime binds methods at extend time and never sees either. A mismatch is
17+
* logged once per class and method.
18+
*
19+
* Release builds compile none of this: the type stays incomplete and every
20+
* pointer to it is null.
21+
*/
22+
class DispatchOverrides;
23+
24+
#ifdef APPLICATION_IN_DEBUG
25+
26+
class DispatchOverrides {
27+
public:
28+
// Reads only own data properties, so no getter of the object runs.
29+
DispatchOverrides(v8::Isolate* isolate, v8::Local<v8::Object> implementationObject,
30+
std::string className);
31+
32+
DispatchOverrides(const DispatchOverrides&) = delete;
33+
DispatchOverrides& operator=(const DispatchOverrides&) = delete;
34+
35+
// method is the function the call resolved to on instance. Never throws and
36+
// never runs JS: microtasks would drain before the dispatched method.
37+
void Check(v8::Isolate* isolate, v8::Local<v8::Context> context,
38+
v8::Local<v8::Object> instance, v8::Local<v8::String> methodName,
39+
int methodNameId, v8::Local<v8::Function> method) {
40+
if (methodNameId < 0) {
41+
return;
42+
}
43+
auto index = static_cast<size_t>(methodNameId);
44+
if (index < byNameId_.size()) {
45+
const auto& entry = byNameId_[index];
46+
if (entry.quiet || entry.expected == method) {
47+
return;
48+
}
49+
}
50+
CheckSlow(isolate, context, instance, methodName, index, method);
51+
}
52+
53+
private:
54+
struct Captured {
55+
v8::Global<v8::String> name;
56+
// Empty when the property was an accessor or held no function.
57+
v8::Global<v8::Function> function;
58+
};
59+
60+
// Indexed by the id Java's MethodNameIds gives the method name; ids are
61+
// handed out on Java's first call with a name, so entries are bound lazily.
62+
struct Bound {
63+
bool bound = false;
64+
// Warned already, or a name that is never checked.
65+
bool quiet = false;
66+
v8::Global<v8::Function> expected;
67+
};
68+
69+
void CheckSlow(v8::Isolate* isolate, v8::Local<v8::Context> context,
70+
v8::Local<v8::Object> instance, v8::Local<v8::String> methodName,
71+
size_t index, v8::Local<v8::Function> method);
72+
73+
// Whether JS code put name on the instance or its class after extend():
74+
// an own property of the instance, of its prototype, or of the
75+
// implementation object.
76+
bool DefinedAfterExtend(v8::Isolate* isolate, v8::Local<v8::Context> context,
77+
v8::Local<v8::Object> instance, v8::Local<v8::String> name);
78+
79+
void Warn(v8::Isolate* isolate, v8::Local<v8::String> methodName,
80+
v8::Local<v8::Function> method);
81+
82+
std::string className_;
83+
v8::Global<v8::Object> implementationObject_;
84+
std::vector<Captured> captured_;
85+
std::vector<Bound> byNameId_;
86+
};
87+
88+
#endif // APPLICATION_IN_DEBUG
89+
90+
} // namespace tns
91+
92+
#endif // DISPATCHOVERRIDES_H_

‎test-app/runtime/src/main/cpp/MetadataNode.cpp‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ MetadataNode::MetadataNode(MetadataTreeNode* treeNode) :
194194
}
195195
}
196196

197-
Local<Object> MetadataNode::CreateExtendedJSWrapper(Isolate* isolate, ObjectManager* objectManager, const string& proxyClassName) {
197+
Local<Object> MetadataNode::CreateExtendedJSWrapper(Isolate* isolate, ObjectManager* objectManager, const string& proxyClassName, DispatchOverrides** dispatchOverrides) {
198198
Local<Object> extInstance;
199199

200200
auto cacheData = GetCachedExtendedClassData(isolate, proxyClassName);
@@ -226,6 +226,9 @@ Local<Object> MetadataNode::CreateExtendedJSWrapper(Isolate* isolate, ObjectMana
226226
}
227227
extInstance->SetInternalField(static_cast<int>(ObjectManager::MetadataNodeKeys::CallSuper), True(isolate));
228228
SetInstanceMetadata(isolate, extInstance, cacheData.node);
229+
if (dispatchOverrides != nullptr) {
230+
*dispatchOverrides = cacheData.dispatchOverrides;
231+
}
229232
}
230233
}
231234

@@ -1532,7 +1535,7 @@ void MetadataNode::ExtendedClassConstructorCallback(const v8::FunctionCallbackIn
15321535
string fullClassName = extData->fullClassName;
15331536

15341537
bool success = CallbackHandlers::RegisterInstance(isolate, thiz, fullClassName, argWrapper, implementationObject, false, extData->node->m_name, extData->defaultOverrides,
1535-
extData->contentMemberNames ? &*extData->contentMemberNames : nullptr);
1538+
extData->contentMemberNames ? &*extData->contentMemberNames : nullptr, extData->dispatchOverrides);
15361539
} catch (NativeScriptException& e) {
15371540
e.ReThrowToV8();
15381541
} catch (std::exception e) {
@@ -2294,7 +2297,9 @@ void MetadataNode::ExtendMethodCallback(const v8::FunctionCallbackInfo<v8::Value
22942297
// gets the constructor its first call site created, as all of them share the class.
22952298
if (isInterface && !hasDot && used.extendedCtorFunction != nullptr && usedClassName == fullExtendedName) {
22962299
auto usedCtorFunc = Local<Function>::New(isolate, *used.extendedCtorFunction);
2297-
cache->ExtendedCtorFuncCache.emplace(extendedCtorKey, ExtendedClassCacheData(usedCtorFunc, Local<ObjectTemplate>::New(isolate, *used.instanceTemplate), used.extendedName, used.node));
2300+
ExtendedClassCacheData usedData(usedCtorFunc, Local<ObjectTemplate>::New(isolate, *used.instanceTemplate), used.extendedName, used.node);
2301+
usedData.dispatchOverrides = used.dispatchOverrides;
2302+
cache->ExtendedCtorFuncCache.emplace(extendedCtorKey, usedData);
22982303
info.GetReturnValue().Set(usedCtorFunc);
22992304
return;
23002305
}
@@ -2307,6 +2312,9 @@ void MetadataNode::ExtendMethodCallback(const v8::FunctionCallbackInfo<v8::Value
23072312
auto extendedClassCallbackData = cache->Own<ExtendedClassCallbackData>(node, extendNameAndLocation, implementationObject, fullExtendedName);
23082313
extendedClassCallbackData->defaultOverrides = defaultOverrides;
23092314
extendedClassCallbackData->contentMemberNames = std::move(contentMemberNames);
2315+
#ifdef APPLICATION_IN_DEBUG
2316+
extendedClassCallbackData->dispatchOverrides = cache->Own<DispatchOverrides>(isolate, implementationObject, DottedClassName(fullExtendedName));
2317+
#endif
23102318
auto extendData = External::New(isolate, extendedClassCallbackData, v8::kExternalPointerTypeTagDefault);
23112319
auto extendFuncTemplate = FunctionTemplate::New(isolate, ExtendedClassConstructorCallback, extendData);
23122320
extendFuncTemplate->InstanceTemplate()->SetInternalFieldCount(static_cast<int>(ObjectManager::MetadataNodeKeys::END));
@@ -2335,14 +2343,17 @@ void MetadataNode::ExtendMethodCallback(const v8::FunctionCallbackInfo<v8::Value
23352343
}
23362344

23372345
ExtendedClassCacheData cacheData(extendFunc, extendFuncTemplate->InstanceTemplate(), fullExtendedName, node);
2346+
cacheData.dispatchOverrides = extendedClassCallbackData->dispatchOverrides;
23382347
cache->ExtendedCtorFuncCache.emplace(extendedCtorKey, cacheData);
23392348
// CreateExtendedJSWrapper looks instances created from Java up by their
23402349
// class name; the first extend of the class keeps serving those. Each
23412350
// entry needs its own handles: the cache destructor frees them per entry.
23422351
bool usesContentClassName = contentKeyed && fullClassName == contentClassName;
23432352
if (extendedCtorKey != fullExtendedName) {
23442353
if (cache->ExtendedCtorFuncCache.find(fullExtendedName) == cache->ExtendedCtorFuncCache.end()) {
2345-
cache->ExtendedCtorFuncCache.emplace(fullExtendedName, ExtendedClassCacheData(extendFunc, extendFuncTemplate->InstanceTemplate(), fullExtendedName, node));
2354+
ExtendedClassCacheData classData(extendFunc, extendFuncTemplate->InstanceTemplate(), fullExtendedName, node);
2355+
classData.dispatchOverrides = extendedClassCallbackData->dispatchOverrides;
2356+
cache->ExtendedCtorFuncCache.emplace(fullExtendedName, classData);
23462357
} else if (usesContentClassName) {
23472358
cache->SharedExtendedClasses.emplace(fullExtendedName, false);
23482359
}

‎test-app/runtime/src/main/cpp/MetadataNode.h‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ class MetadataNode {
5555

5656
static MetadataNode* GetNodeFromHandle(const v8::Local<v8::Object>& value);
5757

58-
static v8::Local<v8::Object> CreateExtendedJSWrapper(v8::Isolate* isolate, ObjectManager* objectManager, const std::string& proxyClassName);
58+
static v8::Local<v8::Object> CreateExtendedJSWrapper(v8::Isolate* isolate, ObjectManager* objectManager, const std::string& proxyClassName, DispatchOverrides** dispatchOverrides = nullptr);
5959

6060
static v8::Local<v8::Object> GetImplementationObject(v8::Isolate* isolate, const v8::Local<v8::Object>& object);
6161

@@ -313,6 +313,8 @@ class MetadataNode {
313313
std::string fullClassName;
314314
uint64_t defaultOverrides = 0;
315315
std::optional<std::vector<std::string>> contentMemberNames;
316+
// Owned by the MetadataNodeCache; null in release builds.
317+
DispatchOverrides* dispatchOverrides = nullptr;
316318
};
317319

318320
struct TypeMetadata {
@@ -356,6 +358,7 @@ class MetadataNode {
356358
v8::Persistent<v8::ObjectTemplate>* instanceTemplate;
357359
std::string extendedName;
358360
MetadataNode* node;
361+
DispatchOverrides* dispatchOverrides = nullptr;
359362
};
360363

361364
/*

0 commit comments

Comments
 (0)