Skip to content

Commit 36d7777

Browse files
authored
feat: warn when Java calls a non-class method (#2139)
### Description **Current behaviour.** A Java→JS call looks the method up on the JS instance on every call (`jsObject->Get(context, methodName)` in `CallbackHandlers::CallJSMethod`). So whatever the instance reaches at call time runs: - an own property of the instance: a per-instance override (`listener.onClick = …`), a test spy, or a TypeScript class-field arrow function (`onClick = (v) => …` in a `@NativeClass` class); - a method reassigned on the class or its implementation object after `extend()`. The iOS runtime binds a class's methods when the class is extended and never sees either case. Before deciding whether Android should match iOS, this PR measures how much real apps depend on the current behaviour. **What this adds (debug builds only, no behaviour change).** - **Capture.** `extend()` records the implementation object's own function-valued data properties (`DispatchOverrides`, one per class). It reads property descriptors, so no getter runs. The record is owned by the runtime's `MetadataNodeCache`, so each worker isolate has its own, and its `v8::Global`s are released at runtime teardown while the isolate is still alive. - **Lookup key.** `ObjectManager::Link` stores a pointer to the class's record in the wrapper's link state. Java→JS calls already fetch that state to find the JS object, so getting the record costs one field load. This covers instances made by the JS constructor, by the TypeScript `__extends` path and by Java (`CreateJSInstanceNative`). Inside the record, entries are indexed by Java's method-name id (`MethodNameIds`). Those ids are assigned on Java's first call with each name, so each class+method entry is bound by name on its first call. - **Check.** After the lookup, the function the call reached is compared with the captured one (handle identity). On a mismatch the runtime logs this once per class and method under the `JS` tag (logcat): > Java called "onClick" on com.tns.gen.…MyListener through a function other than the class's own implementation (an instance property or a method replaced after extend) defined at file:///…/main-page.js:12:5. This may stop working in a future version, as on iOS. Define it on the class. Please report your use case. If the class doesn't define the name at all, the first call is accepted as the class's own implementation when it resolves to something the class inherits. It warns only if the instance, its prototype or the implementation object owns the name; that is the class-field-only case. - **No JS runs during the check.** It doesn't call `console.warn`, because a JS call at depth 0 would drain microtasks before the dispatched method runs. It doesn't throw either. After the check, the call still goes to the function it reaches today. **Cost.** - **Release apps** (`nativescript-optimized`, no `APPLICATION_IN_DEBUG`): the capture, the per-wrapper link-state field and the check are all behind `#ifdef`. What remains is two extra arguments passed through `CallJSMethod`, which release builds ignore, and two pointer fields in the per-class cache structs that are always null. - **Debug apps** (`nativescript-optimized-with-inspector`, `-O3`), per Java→JS call: one load of the record pointer from the link state the call already holds, then a null check, a bounds check, a flag test and a handle comparison. There is no extra property lookup and no call. In the arm64 disassembly of `CallJSMethod`, the inlined check is 17 instructions (6 loads, 6 well-predicted branches). The slow path runs once per class+method. - **Full suite** (1782 specs, emulator): no failures. The only warnings logged were the seven this PR's own specs expect, so no existing spec relies on an instance override being called from Java. - **Interface literals** (`new SomeInterface({...})`, debug builds only): one own-property lookup on the receiver per Java→JS call. - **Extend time:** one own-property-names pass with a descriptor read for each name. - **Memory (debug only):** each class record has an entry table indexed by the process-wide method-name id, so it costs 16 bytes × the highest id Java has called on that class. **`new SomeInterface({...})` instances.** Each of these gets its own implementation object as its prototype, so there's no per-class record to compare against. For any wrapper without a record, debug builds instead check whether the receiver itself owns the method name (`HasRealNamedProperty`, which runs neither interceptors nor getters). If it does, the runtime logs the same warning once per Java class and method in each runtime. A function reassigned on the implementation object itself isn't detected on these instances. **Goal.** Collect reports from real apps that hit this warning before deciding whether to bind methods at extend time, as iOS does. ### Does your commit message include the wording below to reference a specific issue in this repo? No. ### Related Pull Requests None. ### Does your pull request have [unit tests](https://github.com/NativeScript/NativeScript/blob/master/running-tests.md)? Yes. `testDispatchOverrideWarnings.js` covers these cases: - a class's own method: called, no warning; - an instance own property: called, warns; - a TypeScript class field (TS emit with `@Interfaces`): called, warns; - a method replaced on the implementation object after `extend()`: warns; - a method added to the class prototype after `extend()`: warns; - a plain `new java.lang.Runnable({ run })`: called, no warning; - the same with `r.run = …` afterwards: the own property is called, and two calls give one warning; - an instance created from Java with an own property: warns; - three instances called twice each: one warning. Each spec checks that Java actually reached the JS function. It counts warnings with a new `LogcatUtil.countJsWarnings`, which reads `logcat -d -s JS:W` without clearing the log and counts only this process's lines; the existing `logcatContainsString` clears the log first. The branch for a name the class doesn't define but inherits has no spec: I couldn't build a binding that routes such a name to JS. The warning goes to logcat only, not to the DevTools console. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Debug builds now warn when Java-to-JavaScript method dispatch differs from the implementation captured when a class was extended. * Warnings identify the method and class, and are limited to one per method and class, including across repeated calls and instances. * **Bug Fixes** * Improved handling of Java objects that have no associated JavaScript instance information. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 8063043 commit 36d7777

13 files changed

Lines changed: 644 additions & 42 deletions

File tree

‎test-app/app/src/main/assets/app/mainpage.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ require("./tests/testWrapperLifetimeLeaks");
7171
require("./tests/testsMemoryManagement");
7272
require("./tests/testFieldGetSet");
7373
require("./tests/extendedClassesTests");
74+
require("./tests/testDispatchOverrideWarnings");
7475
require("./tests/extendClassNameTests");
7576
require("./tests/testJniReferenceLeak");
7677
require("./tests/testNativeModules");
Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
// Java->JS calls look the method up on the instance on every call, so an own
2+
// property of the instance or a method replaced after extend() is what runs. Debug
3+
// builds keep calling it but log a warning once per class and method, since the
4+
// iOS runtime binds the class's methods at extend time instead. Every extend() spec
5+
// uses a class of its own: the warning names the class, and each is logged only once.
6+
// Interfaces are named in full so the static binding generator implements them.
7+
describe("Java->JS calls through a function other than the class's own", function () {
8+
var LogcatUtil = com.tns.tests.LogcatUtil;
9+
10+
function runFromJava(runnable) {
11+
new java.util.concurrent.FutureTask(runnable, null).run();
12+
}
13+
14+
function warnings(className) {
15+
return LogcatUtil.countJsWarnings(className, 'Java called "run" on ');
16+
}
17+
18+
it("calls the class's own method without a warning", function () {
19+
var runs = 0;
20+
var C = java.lang.Object.extend("DispatchWarnOwnMethod", {
21+
interfaces: [java.lang.Runnable],
22+
run: function () { runs++; }
23+
});
24+
var instance = new C();
25+
26+
runFromJava(instance);
27+
runFromJava(new C());
28+
29+
expect(runs).toBe(2);
30+
expect(warnings("DispatchWarnOwnMethod")).toBe(0);
31+
});
32+
33+
it("calls an instance's own property and warns", function () {
34+
var classRuns = 0;
35+
var ownRuns = 0;
36+
var C = java.lang.Object.extend("DispatchWarnInstanceProperty", {
37+
interfaces: [java.lang.Runnable],
38+
run: function () { classRuns++; }
39+
});
40+
var instance = new C();
41+
instance.run = function () { ownRuns++; };
42+
43+
runFromJava(instance);
44+
45+
expect(ownRuns).toBe(1);
46+
expect(classRuns).toBe(0);
47+
expect(warnings("DispatchWarnInstanceProperty")).toBe(1);
48+
});
49+
50+
it("calls a TypeScript class field and warns", function () {
51+
var fieldRuns = 0;
52+
var FieldClass = (function (_super) {
53+
__extends(DispatchWarnClassField, _super);
54+
function DispatchWarnClassField() {
55+
var _this = _super.call(this) || this;
56+
_this.run = function () { fieldRuns++; };
57+
return _this;
58+
}
59+
DispatchWarnClassField = __decorate([
60+
Interfaces([java.lang.Runnable])
61+
], DispatchWarnClassField);
62+
return DispatchWarnClassField;
63+
}(java.lang.Object));
64+
var instance = new FieldClass();
65+
66+
runFromJava(instance);
67+
68+
expect(fieldRuns).toBe(1);
69+
expect(warnings("DispatchWarnClassField")).toBe(1);
70+
});
71+
72+
it("calls a method replaced after extend and warns", function () {
73+
var originalRuns = 0;
74+
var replacedRuns = 0;
75+
var implementation = {
76+
interfaces: [java.lang.Runnable],
77+
run: function () { originalRuns++; }
78+
};
79+
var C = java.lang.Object.extend("DispatchWarnReplacedMethod", implementation);
80+
var instance = new C();
81+
implementation.run = function () { replacedRuns++; };
82+
83+
runFromJava(instance);
84+
85+
expect(replacedRuns).toBe(1);
86+
expect(originalRuns).toBe(0);
87+
expect(warnings("DispatchWarnReplacedMethod")).toBe(1);
88+
});
89+
90+
it("calls a method added to the class's prototype after extend and warns", function () {
91+
var originalRuns = 0;
92+
var addedRuns = 0;
93+
var C = java.lang.Object.extend("DispatchWarnPrototypeMethod", {
94+
interfaces: [java.lang.Runnable],
95+
run: function () { originalRuns++; }
96+
});
97+
C.prototype.run = function () { addedRuns++; };
98+
99+
runFromJava(new C());
100+
101+
expect(addedRuns).toBe(1);
102+
expect(originalRuns).toBe(0);
103+
expect(warnings("DispatchWarnPrototypeMethod")).toBe(1);
104+
});
105+
106+
it("calls an instance's function for a member the class defined as null and warns", function () {
107+
var ownRuns = 0;
108+
var C = java.lang.Object.extend("DispatchWarnNullMember", {
109+
interfaces: [java.lang.Runnable],
110+
run: null
111+
});
112+
var instance = new C();
113+
instance.run = function () { ownRuns++; };
114+
115+
runFromJava(instance);
116+
runFromJava(instance);
117+
118+
expect(ownRuns).toBe(2);
119+
expect(warnings("DispatchWarnNullMember")).toBe(1);
120+
});
121+
122+
it("warns once however often and on however many instances the call repeats", function () {
123+
var ownRuns = 0;
124+
var C = java.lang.Object.extend("DispatchWarnRepeated", {
125+
interfaces: [java.lang.Runnable],
126+
run: function () {}
127+
});
128+
for (var i = 0; i < 3; i++) {
129+
var instance = new C();
130+
instance.run = function () { ownRuns++; };
131+
runFromJava(instance);
132+
runFromJava(instance);
133+
}
134+
135+
expect(ownRuns).toBe(6);
136+
expect(warnings("DispatchWarnRepeated")).toBe(1);
137+
});
138+
139+
// Every `new Runnable({...})` shares one Java class, so the spec without an override
140+
// runs first and both count only the warnings their own calls add.
141+
it("calls an interface implementation's method without a warning", function () {
142+
var runs = 0;
143+
var runnable = new java.lang.Runnable({ run: function () { runs++; } });
144+
var className = String(runnable.getClass().getName());
145+
var before = warnings(className);
146+
147+
runFromJava(runnable);
148+
149+
expect(runs).toBe(1);
150+
expect(warnings(className)).toBe(before);
151+
});
152+
153+
it("calls an own property of an interface implementation and warns once", function () {
154+
var implementationRuns = 0;
155+
var ownRuns = 0;
156+
var runnable = new java.lang.Runnable({ run: function () { implementationRuns++; } });
157+
var className = String(runnable.getClass().getName());
158+
var before = warnings(className);
159+
runnable.run = function () { ownRuns++; };
160+
161+
runFromJava(runnable);
162+
runFromJava(runnable);
163+
164+
expect(ownRuns).toBe(2);
165+
expect(implementationRuns).toBe(0);
166+
expect(warnings(className)).toBe(before + 1);
167+
});
168+
169+
it("calls an instance's own property on an instance Java created and warns", function () {
170+
var ownRuns = 0;
171+
var C = java.lang.Object.extend("DispatchWarnJavaCreated", {
172+
interfaces: [java.lang.Runnable],
173+
run: function () {}
174+
});
175+
var instance = com.tns.tests.JavaCreated.newInstance(new C().getClass());
176+
instance.run = function () { ownRuns++; };
177+
178+
runFromJava(instance);
179+
180+
expect(ownRuns).toBe(1);
181+
expect(warnings("DispatchWarnJavaCreated")).toBe(1);
182+
});
183+
184+
// The getter on Object.prototype.value is installed only around extend(): while it
185+
// is there, Object.defineProperty reads every accessor descriptor as having a value.
186+
it("runs no inherited getter while extend() captures an accessor", function () {
187+
var inheritedReads = 0;
188+
var implementation = {
189+
interfaces: [java.lang.Runnable],
190+
run: function () {}
191+
};
192+
Object.defineProperty(implementation, "state", {
193+
get: function () { return 1; },
194+
enumerable: true,
195+
configurable: true
196+
});
197+
198+
Object.defineProperty(Object.prototype, "value", {
199+
get: function () { inheritedReads++; return undefined; },
200+
configurable: true
201+
});
202+
try {
203+
java.lang.Object.extend("DispatchWarnAccessorCapture", implementation);
204+
} finally {
205+
delete Object.prototype.value;
206+
}
207+
208+
expect(inheritedReads).toBe(0);
209+
});
210+
});

‎test-app/app/src/main/java/com/tns/tests/LogcatUtil.java‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,26 @@ public static boolean logcatContainsString(String str) throws Exception {
2121

2222
return output.contains(str);
2323
}
24+
25+
// Lines this process logged under the JS tag at warning level or above that contain
26+
// both strings. Leaves the log in place, so earlier lines of this process count too.
27+
public static int countJsWarnings(String needle, String otherNeedle) throws Exception {
28+
// -v brief prefixes each line with "W/JS ( 1234): "; --pid needs API 24.
29+
String pidTag = "(" + android.os.Process.myPid() + "):";
30+
Process process = Runtime.getRuntime().exec(new String[]{"logcat", "-d", "-v", "brief", "-s", "JS:W"});
31+
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
32+
int count = 0;
33+
String line;
34+
while ((line = bufferedReader.readLine()) != null) {
35+
int prefixEnd = line.indexOf("):");
36+
if (prefixEnd < 0 || !line.substring(0, prefixEnd + 2).replace(" ", "").endsWith(pidTag)) {
37+
continue;
38+
}
39+
if (line.contains(needle) && line.contains(otherNeedle)) {
40+
count++;
41+
}
42+
}
43+
process.waitFor();
44+
return count;
45+
}
2446
}

‎test-app/runtime/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,7 @@ add_library(
211211
src/main/cpp/IsolateTracked.cpp
212212
src/main/cpp/JEnv.cpp
213213
src/main/cpp/DesugaredInterfaceCompanionClassNameResolver.cpp
214+
src/main/cpp/DispatchOverrides.cpp
214215
src/main/cpp/JType.cpp
215216
src/main/cpp/JniSignatureParser.cpp
216217
src/main/cpp/JsArgConverter.cpp

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

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,8 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local<Object> &j
216216
uint64_t defaultOverrides,
217217
const vector<string> *contentMemberNames,
218218
jclass *resolvedClass,
219-
const Persistent<ObjectTemplate> *instanceTemplate) {
219+
const Persistent<ObjectTemplate> *instanceTemplate,
220+
DispatchOverrides *dispatchOverrides) {
220221
bool success;
221222

222223
DEBUG_WRITE("RegisterInstance called for '%s'", fullClassName.c_str());
@@ -250,7 +251,7 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local<Object> &j
250251
!implementationObject.IsEmpty() || isInterface
251252
? ObjectManager::LinkKind::kExtended
252253
: ObjectManager::LinkKind::kPlain,
253-
instanceTemplate);
254+
instanceTemplate, dispatchOverrides);
254255

255256
// resolve constructor
256257
const auto &mi = MethodCache::ResolveConstructorSignature(argWrapper, fullClassName,
@@ -1247,7 +1248,8 @@ vector<string> CallbackHandlers::GetTypeMetadata(const string &name, int index)
12471248

12481249
Local<Value> CallbackHandlers::CallJSMethod(Isolate *isolate, JNIEnv *_env,
12491250
const Local<Object> &jsObject, const Local<String> &methodName,
1250-
const JavaCallArgs &args) {
1251+
const JavaCallArgs &args, DispatchOverrides *dispatchOverrides,
1252+
int methodNameId) {
12511253
SET_PROFILER_FRAME();
12521254

12531255
JEnv env(_env);
@@ -1268,6 +1270,13 @@ Local<Value> CallbackHandlers::CallJSMethod(Isolate *isolate, JNIEnv *_env,
12681270
EscapableHandleScope handleScope(isolate);
12691271

12701272
auto jsMethod = method.As<Function>();
1273+
#ifdef APPLICATION_IN_DEBUG
1274+
if (dispatchOverrides != nullptr) {
1275+
dispatchOverrides->Check(isolate, context, jsObject, methodName, methodNameId, jsMethod);
1276+
} else {
1277+
DispatchOverrides::CheckInstanceProperty(isolate, context, jsObject, methodName, methodNameId, jsMethod);
1278+
}
1279+
#endif
12711280
int argc = args.count;
12721281

12731282
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
@@ -44,7 +44,8 @@ namespace tns {
4444
uint64_t defaultOverrides = 0,
4545
const std::vector<std::string> *contentMemberNames = nullptr,
4646
jclass *resolvedClass = nullptr,
47-
const v8::Persistent<v8::ObjectTemplate> *instanceTemplate = nullptr);
47+
const v8::Persistent<v8::ObjectTemplate> *instanceTemplate = nullptr,
48+
DispatchOverrides *dispatchOverrides = nullptr);
4849

4950
// Whether GetImplementedInterfaces would list any interface, without calling Java.
5051
static bool HasImplementedInterfaces(v8::Isolate *isolate, const v8::Local<v8::Object> &implementationObject);
@@ -99,7 +100,8 @@ namespace tns {
99100

100101
static v8::Local<v8::Value>
101102
CallJSMethod(v8::Isolate *isolate, JNIEnv *_env, const v8::Local<v8::Object> &jsObject,
102-
const v8::Local<v8::String> &methodName, const JavaCallArgs &args);
103+
const v8::Local<v8::String> &methodName, const JavaCallArgs &args,
104+
DispatchOverrides *dispatchOverrides = nullptr, int methodNameId = -1);
103105

104106
static v8::Local<v8::Value>
105107
GetJavaField(v8::Isolate *isolate, const v8::Local<v8::Object> &caller,

0 commit comments

Comments
 (0)