Skip to content

Commit 9c4895a

Browse files
authored
perf: faster object arguments and receiver lookups (#2145)
### Description Four changes to the JS→Java call path that cost something on every object argument, receiver lookup, overloaded call or extended-class construction. One commit each. #### 1. Skip cast and null markers when an argument is a Java wrapper Converting an object argument read two private symbols from it: the numeric cast marker, then the null-node marker after the Java lookup. Each read also walked to the object's creation context. Both markers are only ever put on plain objects: the `long()`/`byte()`/… cast objects (`Object::New`), `LongNumber` instances (no internal fields) and the `.null` sentinel (`Object::New`). So an argument with the runtime's internal fields (a Java wrapper or an extended-class instance) now goes straight to the Java lookup. Objects without internal fields keep the full path: TypeScript subclass instances, typed arrays, plain objects and Proxies. The same skip applies to the overload signature key (`MethodCache::AppendType`) and to the argument arrays built for overload resolution. The `Local<Private>` overloads of `V8GetPrivateValue`/`V8SetPrivateValue` now use the current context instead of the creation context. A private-symbol access is an own lookup that skips interceptors, proxy traps and access checks (`LookupIterator::ComputeConfiguration` → `OWN_SKIP_INTERCEPTOR`, and private names bypass `ACCESS_CHECK`). It runs no JS and does not depend on the context. The creation context remains the fallback when no context is entered. #### 2. Keep parsed signatures on resolved method cache entries Constructors with arguments and overloaded methods resolve through `MethodCache`. Each such call parsed the JNI signature into a `vector<string>` before converting its arguments. The tokens are now parsed once, stored on the `CacheMethodInfo` before it is published, and immutable afterwards, so no locking changes. Independent of #2137, which touches the signature-key scratch in the same file; the two merge cleanly. #### 3. Cache the resolved class of a JS-extended class Every `new` of a JS-extended class looked its generated class up in the process-wide class cache, taking its shared lock and hashing the full class name. The extended class's per-isolate callback data now keeps the global ref once resolved. The class cache never drops or replaces an entry, so the ref stays valid. Plain Java class construction is unchanged. #### 4. Skip the jweak check while Java holds the object strongly Each LRU cache hit in `ObjectManager::GetJavaObjectByJsObject` ran `ValidateWeakGlobalRefCallback`, which calls `IsSameObject(jweak, NULL)`: a JNI call with a thread-state transition. That cost lands on every instance call (receiver) and every object argument. It is now skipped while the wrapper's link has `javaWeakened == false`. Wrappers whose Java side was weakened keep the check. **Why the check exists (#1881).** #1881 added the validator because cached jweaks read null while the object "exists". That PR had no repro. Reading the code at the time shows two causes, neither an ART bug: - **Id rebinding during construction.** `Runtime.initInstance` took `currentObjectId` without clearing it or checking the class, and the id stayed published for the whole Java constructor. A binding instance that Java created inside a JS-driven constructor (a custom view inflated by it, an instance made by reflection) registered under the outer object's id. A lookup in that window cached a jweak to the nested instance. When the outer registration replaced it and the nested instance was collected, the jweak read null while the table held the live outer object. Re-fetching then "fixed" it. #2099 later gated the id by class and made it single-use. - **A weak Java side behind a live wrapper.** The old finalizer weakened the Java side synchronously and resurrected the wrapper. A wrapper handed back to JS later was never re-strengthened, so the jweak could be legitimately cleared while JS held the wrapper. For these the validator turns a null into a "cleared object reference" error. **Invariant on main.** If a linked state has `!javaWeakened`, Java's `ObjectTable` holds that id's object strongly, and that object is the one the cached jweak names: - `ObjectTable` is weakened only by `processFinalizedBatch` → `weakenAndCheckAlive`. - A wrapper reacquired while queued is dropped from the batch. A wrapper reacquired after weakening keeps `javaWeakened`. - Each `remove()` path either clears `linked` or deletes the state. - Ids are never reused, and every runtime has its own table and cache. Two cases broke the invariant and are closed in the same commit: - **A finalizer batch that failed part way.** Example: an OOM allocating a `WeakRef` could leave objects weak in Java with `javaWeakened` still false. The flag is now set before the Java call. - **Same-class nested construction, still possible on main.** Java can create an instance of exactly the class under construction during the outer constructor's `super()`, before the outer's `initInstance`. That instance takes the reserved id until `registerConstructedInstance` replaces it, and a jweak cached in that window names it. On main, calls on the constructed object reach the nested instance until it is collected, and then the validator re-fetches. `RegisterInstance` now drops the cached entry after registration. The new `SelfNesting` spec covers this. With B1 but without that eviction, the spec aborts with `JNI DETECTED ERROR IN APPLICATION: can't call int com.tns.tests.SelfNesting.getTag() on null object`. ### Measurements Release APKs (`-Poptimized -Prelease`, arm64) run on a phone through the #2092 harness (`debug.ns.jnibench`). The labels are cumulative: - base is `main` (56c7b0b); - then +B2, +B3, +B4 and +B1, one commit each. Every round reinstalls and speed-compiles each label. The first launch after an install is discarded and only the relaunch is measured. Each round runs base, +B2, +B3, +B4, +B1, then base2, which is the base APK again (A/A). 6 rounds. ns per call: median over launches of each launch's median (min..max over launches). | row | base | base2 (A/A) | +B2 | +B3 | +B4 | +B1 | A/A | B2 | B3 | B4 | B1 | total | |---|---|---|---|---|---|---|---|---|---|---|---|---| | instance.noop() | 229 (229..238) | 230 (228..231) | 230 (230..232) | 231 (229..232) | 231 (230..235) | 197 (194..200) | +0.1% | +0.4% | +0.1% | +0.1% | -14.6% | -14.1% | | instance.takeObject(Object) | 487 (482..490) | 487 (481..490) | 372 (368..374) | 368 (365..370) | 373 (369..374) | 306 (305..310) | -0.1% | -23.7% | -1.1% | +1.5% | -18.0% | -37.2% | | instance.takeObjects(Object x3) | 1046 (1035..1050) | 1048 (1043..1058) | 669 (665..700) | 663 (658..668) | 675 (668..684) | 548 (545..550) | +0.1% | -36.0% | -0.9% | +1.7% | -18.7% | -47.6% | | overloaded static Math.max(int,int) | 663 (659..666) | 667 (658..675) | 679 (662..692) | 551 (548..560) | 544 (539..547) | 537 (536..542) | +0.6% | +2.4% | -18.9% | -1.3% | -1.2% | -19.0% | | new Object.extend({})() | 3700 (3551..3901) | 3788 (3414..3856) | 3638 (3550..3752) | 3777 (3596..4015) | 3573 (3339..3675) | 3619 (3370..3717) | +2.4% | -1.7% | +3.8% | -5.4% | +1.3% | -2.2% | | static.noop() | 89 (88..89) | 89 (89..92) | 90 (89..90) | 88 (88..89) | 88 (88..89) | 89 (89..90) | +0.8% | +1.4% | -1.9% | +0.2% | +0.7% | +0.3% | Rows that are bimodal per launch on this phone. No deltas are given because the A/A pair alone differs by more than any step: | row | base | base2 (A/A) | +B1 (all four) | A/A gap | |---|---|---|---|---| | new java.lang.Object() | 1598 (1413..2782) | 1816 (1526..2112) | 1771 (1407..2855) | +13.6%: inconclusive | | new java.lang.StringBuilder(String) | 2047 (1886..6246) | 2868 (2403..4278) | 3162 (1760..3808) | +40.1%: inconclusive | | overloaded static String.valueOf(Object) | 2378 (2362..4163) | 3165 (2349..3913) | 2042 (1798..2231) | +33.1%: inconclusive | | field.get int | 158 (157..257) | 207 (157..257) | 140 (121..198) | +31.5%: inconclusive | - **Stable rows:** the A/A gap is at most 2.4%, and every label's launches fall in a narrow band. - B2 cuts `takeObject` by 24% and `takeObjects` by 36%. - B3 cuts the overloaded `Math.max` call by 19%. - B1 cuts `instance.noop` by 15% and the object-argument rows by 18-19%. - **B4:** `new Object.extend({})()` moves -5.4% at the B4 step, against a 2.4% A/A gap and ±4% at the other steps. That is suggestive, not conclusive. - **Bimodal rows:** each launch of these lands in one of two clusters. On `new java.lang.StringBuilder(String)` the clusters sit near 1.8-2.6 µs and 3.1-4.3 µs: - base had 1 of 6 launches in the slow cluster; - base2, the same APK, had 3 of 6; - +B1 had 4 of 6, and its fast launches (1760 and 1784 ns) are the fastest of any label. The medians therefore reflect which cluster each launch fell into, not the code. ### Related Pull Requests - #1881 added the jweak check that item 4 now skips for strongly held objects. - #2099 fixed the construction id reuse that caused most of #1881's null jweaks. - #2137 (open) touches `MethodCache.cpp` and `CallbackHandlers.cpp` too. This branch merges with it cleanly. ### Does your pull request have unit tests? Yes, see Testing. ### Testing - New `testObjectArgumentPath.js`: - wrapper, extended-class and TypeScript-subclass instances as object arguments, repeated; - a released wrapper as an argument; - `long`/`char`/`double`/`float` casts, typed nulls and wrappers through a warm overload cache; - a cast through a single-signature method; - constructor overloads on a warm cache; - repeated and interleaved extended-class construction, with and without arguments; - a wrapper reacquired after its Java side was weakened and then collected, which must throw rather than pass null; - a reachable wrapper after warm instance calls and a collection; - the same-class nested construction above, with a new `SelfNesting` fixture. - Full suite on an arm64 API 36.1 emulator, rebased on 56c7b0b: **1799 specs, 0 failures** with `enableMultithreadedJavascript` on, and **1799, 0 failures** with it off.
1 parent d5b32f8 commit 9c4895a

17 files changed

Lines changed: 329 additions & 73 deletions

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ require("./tests/testRuntimeImplementedAPIs");
8686
require("./tests/testsInstanceOfOperator");
8787
require("./tests/testProxyReceivers");
8888
require("./tests/testReleaseNativeCounterpart");
89+
require("./tests/testObjectArgumentPath");
8990
require("./tests/testJSONObjects");
9091
require("./tests/kotlin/companions/testCompanionObjectsSupport");
9192
require("./tests/kotlin/properties/testPropertiesSupport");
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
describe("Object arguments and cached call signatures", function () {
2+
function roundTrip(obj) {
3+
return java.util.Collections.singletonList(obj).get(0);
4+
}
5+
6+
it("passes a Java wrapper as an object argument on every call", function () {
7+
var list = new java.util.ArrayList();
8+
for (var i = 0; i < 3; i++) {
9+
expect(roundTrip(list)).toBe(list);
10+
}
11+
});
12+
13+
it("passes an extended class instance as an object argument", function () {
14+
var Extended = java.lang.Object.extend({
15+
toString: function () {
16+
return "extended arg";
17+
}
18+
});
19+
var instance = new Extended();
20+
for (var i = 0; i < 3; i++) {
21+
expect(roundTrip(instance)).toBe(instance);
22+
expect(new java.lang.StringBuilder().append(instance).toString()).toBe("extended arg");
23+
}
24+
});
25+
26+
it("passes a TypeScript subclass instance as an object argument", function () {
27+
var TsButton = (function (_super) {
28+
__extends(TsButton, _super);
29+
function TsButton() {
30+
var _this = _super.call(this) || this;
31+
_this.label = "ts arg";
32+
return _this;
33+
}
34+
TsButton.prototype.toString = function () {
35+
return this.label;
36+
};
37+
return TsButton;
38+
})(com.tns.tests.Button1);
39+
40+
var button = new TsButton();
41+
for (var i = 0; i < 3; i++) {
42+
expect(roundTrip(button)).toBe(button);
43+
expect(new java.lang.StringBuilder().append(button).toString()).toBe("ts arg");
44+
}
45+
});
46+
47+
it("rejects a released wrapper as an object argument", function () {
48+
var released = new java.lang.Object();
49+
global.__releaseNativeCounterpart(released);
50+
expect(function () {
51+
roundTrip(released);
52+
}).toThrow();
53+
});
54+
55+
it("resolves numeric casts, typed nulls and wrappers on a warm overload cache", function () {
56+
var list = new java.util.ArrayList();
57+
var sb = new java.lang.StringBuilder();
58+
for (var i = 0; i < 3; i++) {
59+
sb.append(long(5));
60+
sb.append(char("x"));
61+
sb.append(double(1));
62+
sb.append(float(2));
63+
sb.append(java.lang.String.null);
64+
sb.append(java.lang.Object.null);
65+
sb.append(list);
66+
sb.append("|");
67+
}
68+
var round = "5x1.02.0nullnull[]|";
69+
expect(sb.toString()).toBe(round + round + round);
70+
});
71+
72+
it("passes a numeric cast to a method with a single signature", function () {
73+
for (var i = 0; i < 3; i++) {
74+
expect(java.lang.Long.toHexString(long("4294967296"))).toBe("100000000");
75+
}
76+
});
77+
78+
it("constructs through each overload on a warm constructor cache", function () {
79+
for (var i = 0; i < 3; i++) {
80+
expect(new java.lang.StringBuilder("ab").toString()).toBe("ab");
81+
expect(new java.lang.StringBuilder(32).capacity()).toBe(32);
82+
expect(new java.lang.StringBuilder(new java.lang.StringBuilder("cs")).toString()).toBe("cs");
83+
var plain = new java.lang.Object();
84+
expect(plain.getClass().getName()).toBe("java.lang.Object");
85+
}
86+
});
87+
88+
it("constructs extended classes repeatedly, interleaved and with arguments", function () {
89+
var Counting = java.util.ArrayList.extend({
90+
size: function () {
91+
return this.super.size() + 100;
92+
}
93+
});
94+
var Named = java.lang.Object.extend({
95+
toString: function () {
96+
return "named";
97+
}
98+
});
99+
var source = new java.util.ArrayList();
100+
source.add("a");
101+
102+
var seen = [];
103+
for (var i = 0; i < 20; i++) {
104+
var empty = new Counting();
105+
empty.add("x");
106+
expect(empty.size()).toBe(101);
107+
expect(new Counting(10).size()).toBe(100);
108+
expect(new Counting(source).size()).toBe(101);
109+
var named = new Named();
110+
expect(named.toString()).toBe("named");
111+
expect(seen.indexOf(empty)).toBe(-1);
112+
seen.push(empty);
113+
}
114+
});
115+
116+
describe("cached Java objects of linked wrappers", function () {
117+
var Holder = com.tns.tests.WrapperHolder;
118+
119+
function collectJava() {
120+
for (var i = 0; i < 3; i++) {
121+
java.lang.Runtime.getRuntime().gc();
122+
java.lang.System.runFinalization();
123+
}
124+
}
125+
126+
afterEach(function () {
127+
Holder.held = null;
128+
});
129+
130+
it("never pass null for a wrapper whose Java object was collected after Java weakened it", function () {
131+
(function () {
132+
Holder.held = new java.lang.StringBuilder("weakened");
133+
})();
134+
gc();
135+
// Any Java call flushes the collected wrapper, weakening its Java object.
136+
collectJava();
137+
var again = Holder.held;
138+
Holder.held = null;
139+
collectJava();
140+
141+
var passed;
142+
try {
143+
passed = java.util.Collections.singletonList(again).get(0);
144+
} catch (e) {
145+
passed = "threw";
146+
}
147+
expect(passed === again || passed === "threw").toBe(true);
148+
});
149+
150+
it("resolve a reachable wrapper after warm instance calls and a collection", function () {
151+
var sb = new java.lang.StringBuilder("warm");
152+
for (var i = 0; i < 50; i++) {
153+
expect(sb.length()).toBe(4);
154+
}
155+
for (var j = 0; j < 2000; j++) {
156+
new java.lang.Object();
157+
}
158+
gc();
159+
collectJava();
160+
expect(sb.toString()).toBe("warm");
161+
expect(java.util.Collections.singletonList(sb).get(0)).toBe(sb);
162+
});
163+
164+
it("resolve a constructed instance after Java made another of its class during the constructor", function () {
165+
var Outer = com.tns.tests.SelfNesting.extend({
166+
touch: function () {
167+
this.super.touch();
168+
},
169+
selfNestingSpec: true
170+
});
171+
var outer = new Outer(true);
172+
expect(outer.getTag()).toBe(2);
173+
collectJava();
174+
expect(outer.getTag()).toBe(2);
175+
});
176+
});
177+
});
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.tns.tests;
2+
3+
/** Creates an instance of its own runtime class while its constructor runs. */
4+
public class SelfNesting {
5+
private final int tag;
6+
7+
public SelfNesting() {
8+
tag = 1;
9+
}
10+
11+
public SelfNesting(boolean nest) throws Exception {
12+
tag = 2;
13+
if (nest) {
14+
SelfNesting nested = getClass().getConstructor().newInstance();
15+
nested.touch();
16+
}
17+
}
18+
19+
public int getTag() {
20+
return tag;
21+
}
22+
23+
public void touch() {
24+
}
25+
}

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

Lines changed: 18 additions & 7 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+
jclass *resolvedClass) {
218219
bool success;
219220

220221
DEBUG_WRITE("RegisterInstance called for '%s'", fullClassName.c_str());
@@ -230,9 +231,15 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local<Object> &j
230231

231232
// The default-overriding class does not depend on the implementation object, whose
232233
// properties ResolveClass would otherwise read, getters included.
233-
jclass generatedJavaClass = ResolveClass(isolate, baseClassName, fullClassName,
234-
defaultOverrides != 0 ? Local<Object>() : implementationObject,
235-
isInterface, contentMemberNames);
234+
jclass generatedJavaClass = resolvedClass != nullptr ? *resolvedClass : nullptr;
235+
if (generatedJavaClass == nullptr) {
236+
generatedJavaClass = ResolveClass(isolate, baseClassName, fullClassName,
237+
defaultOverrides != 0 ? Local<Object>() : implementationObject,
238+
isInterface, contentMemberNames);
239+
if (resolvedClass != nullptr) {
240+
*resolvedClass = generatedJavaClass;
241+
}
242+
}
236243

237244
int javaObjectID = objectManager->GenerateNewObjectID();
238245

@@ -253,7 +260,7 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local<Object> &j
253260
instance = env.NewObject(generatedJavaClass, mi.mid);
254261
} else {
255262
// resolve arguments before passing them on to the constructor
256-
JsArgConverter argConverter(argWrapper.args, mi.signature);
263+
JsArgConverter argConverter(argWrapper.args, mi.parsedSig);
257264
auto ctorArgs = argConverter.ToArgs();
258265

259266
instance = env.NewObjectA(generatedJavaClass, mi.mid, ctorArgs);
@@ -268,6 +275,9 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local<Object> &j
268275

269276
jlong usedJavaMemory = env.CallLongMethod(runtime->GetJavaRuntime(), REGISTER_CONSTRUCTED_INSTANCE_ID,
270277
instance, javaObjectID);
278+
// While the constructor ran, an instance of the same class that Java created could take
279+
// this id until the registration above replaced it; a jweak cached then names that one.
280+
objectManager->ForgetCachedJavaObject(javaObjectID);
271281

272282
AdjustAmountOfExternalAllocatedMemory(isolate, usedJavaMemory);
273283

@@ -505,9 +515,10 @@ void CallbackHandlers::CallJavaMethod(const Local<Object> &caller, const string
505515
methodName.c_str());
506516
}
507517

518+
const std::vector<std::string> *parsedSig = mi != nullptr ? &mi->parsedSig : nullptr;
508519
JsArgConverter argConverter = (entry != nullptr && entry->isExtensionFunction)
509-
? JsArgConverter(caller, args, *sig, entry)
510-
: JsArgConverter(args, false, *sig, entry);
520+
? JsArgConverter(caller, args, *sig, entry, parsedSig)
521+
: JsArgConverter(args, false, *sig, entry, parsedSig);
511522

512523

513524
if (!argConverter.IsValid()) {

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

Lines changed: 2 additions & 1 deletion
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+
jclass *resolvedClass = 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);

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

Lines changed: 32 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -89,25 +89,33 @@ namespace {
8989
}
9090
}
9191

92+
void JsArgConverter::SetTokens(const string &methodSignature, MetadataEntry *entry,
93+
const std::vector<std::string> *parsedSignature) {
94+
if (parsedSignature != nullptr) {
95+
m_tokens = parsedSignature;
96+
} else if ((entry != nullptr) && (entry->getIsResolved())) {
97+
if (entry->parsedSig.empty()) {
98+
JniSignatureParser parser(methodSignature);
99+
entry->parsedSig = parser.Parse();
100+
}
101+
m_tokens = &entry->parsedSig;
102+
} else {
103+
JniSignatureParser parser(methodSignature);
104+
m_ownedTokens = parser.Parse();
105+
}
106+
}
107+
92108
JsArgConverter::JsArgConverter(const Local<Object> &caller,
93109
const v8::FunctionCallbackInfo<Value> &args,
94-
const string &methodSignature, MetadataEntry *entry)
110+
const string &methodSignature, MetadataEntry *entry,
111+
const std::vector<std::string> *parsedSignature)
95112
: m_isolate(args.GetIsolate()), m_isValid(true),
96113
m_error(Error()) {
97114
int v8ProvidedArgumentsLength = args.Length();
98115
m_argsLen = 1 + v8ProvidedArgumentsLength;
99116

100117
if (m_argsLen > 0) {
101-
if ((entry != nullptr) && (entry->getIsResolved())) {
102-
if (entry->parsedSig.empty()) {
103-
JniSignatureParser parser(methodSignature);
104-
entry->parsedSig = parser.Parse();
105-
}
106-
m_tokens = &entry->parsedSig;
107-
} else {
108-
JniSignatureParser parser(methodSignature);
109-
m_ownedTokens = parser.Parse();
110-
}
118+
SetTokens(methodSignature, entry, parsedSignature);
111119

112120
m_isValid = ConvertArg(caller, 0);
113121

@@ -127,22 +135,14 @@ JsArgConverter::JsArgConverter(const Local<Object> &caller,
127135

128136
JsArgConverter::JsArgConverter(const v8::FunctionCallbackInfo<Value> &args,
129137
bool hasImplementationObject, const string &methodSignature,
130-
MetadataEntry *entry)
138+
MetadataEntry *entry,
139+
const std::vector<std::string> *parsedSignature)
131140
: m_isolate(args.GetIsolate()), m_isValid(true),
132141
m_error(Error()) {
133142
m_argsLen = !hasImplementationObject ? args.Length() : args.Length() - 1;
134143

135144
if (m_argsLen > 0) {
136-
if ((entry != nullptr) && (entry->getIsResolved())) {
137-
if (entry->parsedSig.empty()) {
138-
JniSignatureParser parser(methodSignature);
139-
entry->parsedSig = parser.Parse();
140-
}
141-
m_tokens = &entry->parsedSig;
142-
} else {
143-
JniSignatureParser parser(methodSignature);
144-
m_ownedTokens = parser.Parse();
145-
}
145+
SetTokens(methodSignature, entry, parsedSignature);
146146

147147
for (int i = 0; i < m_argsLen; i++) {
148148
m_isValid = ConvertArg(args[i], i);
@@ -155,16 +155,11 @@ JsArgConverter::JsArgConverter(const v8::FunctionCallbackInfo<Value> &args,
155155
}
156156

157157
JsArgConverter::JsArgConverter(const v8::FunctionCallbackInfo<Value> &args,
158-
const string &methodSignature)
158+
const std::vector<std::string> &parsedSignature)
159159
: m_isolate(args.GetIsolate()), m_isValid(true),
160-
m_error(Error()) {
160+
m_tokens(&parsedSignature), m_error(Error()) {
161161
m_argsLen = args.Length();
162162

163-
if (m_argsLen > 0) {
164-
JniSignatureParser parser(methodSignature);
165-
m_ownedTokens = parser.Parse();
166-
}
167-
168163
for (int i = 0; i < m_argsLen; i++) {
169164
m_isValid = ConvertArg(args[i], i);
170165

@@ -321,7 +316,10 @@ bool JsArgConverter::ConvertArg(const Local<Value> &jsArg, int index) {
321316
auto context = m_isolate->GetCurrentContext();
322317
auto jsObject = arg->ToObject(context).ToLocalChecked();
323318

324-
auto castType = NumericCasts::GetCastType(m_isolate, jsObject);
319+
// Cast markers and the null sentinel are only put on plain objects, never on a
320+
// Java wrapper (an object with the runtime's internal fields).
321+
bool isWrapper = ObjectManager::HasMetadataField(jsObject);
322+
auto castType = isWrapper ? CastType::None : NumericCasts::GetCastType(m_isolate, jsObject);
325323

326324
Local<Value> castValue;
327325
JniLocalRef obj;
@@ -419,8 +417,10 @@ bool JsArgConverter::ConvertArg(const Local<Value> &jsArg, int index) {
419417
? GetOrLinkJavaBuffer(m_objectManager, jsObject)
420418
: m_objectManager->GetJavaObjectByJsObject(jsObject);
421419

422-
V8GetPrivateValue(m_isolate, jsObject, V8StringConstants::GetNullNodePrivate(m_isolate),
423-
castValue);
420+
if (!isWrapper) {
421+
V8GetPrivateValue(m_isolate, jsObject, V8StringConstants::GetNullNodePrivate(m_isolate),
422+
castValue);
423+
}
424424

425425
if (!castValue.IsEmpty()) {
426426
SetConvertedObject(index, nullptr);

0 commit comments

Comments
 (0)