Skip to content

Commit a494cbb

Browse files
committed
perf: return primitive callback results as raw bits
A JS callback result for a primitive Java return type went through JsArgToArrayConverter: a jobject[1] allocation, a JNI NewObject of the wrapper, a local-ref round trip, then the generated binding unboxed it. For boolean/int/long/float/double the native side now writes the value as raw bits into a long[2] the caller passes, and Java boxes it with valueOf. Only the cases the boxed conversion maps to exactly the declared wrapper take this path; every other value, including those that end in a ClassCastException or a defaulted null today, still goes through the boxed conversion, so the results are unchanged (pinned by the previous commit's spec).
1 parent 9f8d1ed commit a494cbb

4 files changed

Lines changed: 130 additions & 7 deletions

File tree

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

Lines changed: 91 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,11 @@
5454
#include "include/libplatform/libplatform.h"
5555
#include "sys/system_properties.h"
5656

57+
#include <cfloat>
58+
#include <climits>
59+
#include <cmath>
60+
#include <cstring>
61+
5762
#ifdef APPLICATION_IN_DEBUG
5863
// #include "NetworkDomainCallbackHandlers.h"
5964
#include "JsV8InspectorClient.h"
@@ -497,10 +502,86 @@ jobject Runtime::RunScript(JNIEnv* _env, jobject obj, jstring scriptFile) {
497502
return res;
498503
}
499504

505+
/*
506+
* The primitive-returning cases of JsArgToArrayConverter::ConvertArg that box
507+
* into exactly the declared wrapper type, which is all the generated binding's
508+
* cast accepts. Everything else keeps the boxed conversion, including the
509+
* values it turns into a ClassCastException or a defaulted null.
510+
*/
511+
static bool TryGetPrimitiveReturnBits(Isolate* isolate,
512+
const Local<Value>& value, Type type,
513+
jlong& bits) {
514+
if (value.IsEmpty()) {
515+
return false;
516+
}
517+
518+
if (type == Type::Boolean) {
519+
if (!value->IsBoolean() && !value->IsBooleanObject()) {
520+
return false;
521+
}
522+
// ToBoolean, as the boxed path does: a Boolean object is always true.
523+
bits = value->BooleanValue(isolate) ? 1 : 0;
524+
return true;
525+
}
526+
527+
// Number objects are left to the boxed path: reading one calls valueOf,
528+
// which must not run twice if this path then declines.
529+
if (!value->IsNumber()) {
530+
return false;
531+
}
532+
533+
if (type == Type::Int && value->IsInt32()) {
534+
bits = value.As<Int32>()->Value();
535+
return true;
536+
}
537+
538+
double d = value.As<Number>()->Value();
539+
// Beyond int64 the boxed path's double -> int64 cast is undefined.
540+
constexpr double kTwoPow63 = 9223372036854775808.0;
541+
if (std::isfinite(d) && std::fabs(d) >= kTwoPow63) {
542+
return false;
543+
}
544+
bool isWholeNumber =
545+
std::isfinite(d) && d == static_cast<double>(static_cast<int64_t>(d));
546+
547+
switch (type) {
548+
case Type::Int:
549+
if (isWholeNumber && INT_MIN <= d && d <= INT_MAX) {
550+
bits = static_cast<jint>(d);
551+
return true;
552+
}
553+
return false;
554+
case Type::Long:
555+
if (isWholeNumber) {
556+
bits = static_cast<jlong>(d);
557+
return true;
558+
}
559+
return false;
560+
case Type::Float:
561+
if (!isWholeNumber && FLT_MIN <= d && d <= FLT_MAX) {
562+
float f = static_cast<jfloat>(d);
563+
int32_t raw;
564+
memcpy(&raw, &f, sizeof(raw));
565+
bits = raw;
566+
return true;
567+
}
568+
return false;
569+
case Type::Double:
570+
if (!isWholeNumber) {
571+
memcpy(&bits, &d, sizeof(bits));
572+
return true;
573+
}
574+
return false;
575+
default:
576+
return false;
577+
}
578+
}
579+
500580
jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj,
501581
jint javaObjectID, jstring methodName,
502582
jint retType, jboolean isConstructor,
503-
const JavaCallArgs& args) {
583+
const JavaCallArgs& args,
584+
jlongArray primitiveResult) {
504585
SET_PROFILER_FRAME();
505586

506587
auto isolate = m_isolate;
@@ -540,6 +621,15 @@ jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj,
540621
return nullptr;
541622
}
542623

624+
jlong bits;
625+
if (primitiveResult != nullptr &&
626+
TryGetPrimitiveReturnBits(m_isolate, jsResult, static_cast<Type>(retType),
627+
bits)) {
628+
jlong out[2] = {bits, 1};
629+
_env->SetLongArrayRegion(primitiveResult, 0, 2, out);
630+
return nullptr;
631+
}
632+
543633
int classReturnType = retType;
544634
jobject javaObject =
545635
ConvertJsValueToJavaObject(env, jsResult, classReturnType);

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ class Runtime {
172172
void RunModule(const char *moduleName);
173173
void RunWorker(const std::string& filePath);
174174
jobject RunScript(JNIEnv* _env, jobject obj, jstring scriptFile);
175-
jobject CallJSMethodNative(JNIEnv* _env, jobject obj, jint javaObjectID, jstring methodName, jint retType, jboolean isConstructor, const JavaCallArgs& args);
175+
jobject CallJSMethodNative(JNIEnv* _env, jobject obj, jint javaObjectID, jstring methodName, jint retType, jboolean isConstructor, const JavaCallArgs& args, jlongArray primitiveResult);
176176
void CreateJSInstanceNative(JNIEnv* _env, jobject obj, jobject javaObject, jint javaObjectID, jstring className);
177177
jint GenerateNewObjectId(JNIEnv* env, jobject obj);
178178
void AdjustAmountOfExternalAllocatedMemory();

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_runScript(JNIEnv* _env, jobjec
194194
return result;
195195
}
196196

197-
extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _env, jobject obj, jint runtimeId, jint javaObjectID, jstring methodName, jint retType, jboolean isConstructor, jintArray argTypes, jlongArray argValues, jobjectArray argRefs) {
197+
extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _env, jobject obj, jint runtimeId, jint javaObjectID, jstring methodName, jint retType, jboolean isConstructor, jintArray argTypes, jlongArray argValues, jobjectArray argRefs, jlongArray primitiveResult) {
198198
JEnv::EntryScope envScope(_env);
199199
jobject result = nullptr;
200200

@@ -211,7 +211,7 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _en
211211
v8::Context::Scope context_scope(context);
212212

213213
try {
214-
result = runtime->CallJSMethodNative(_env, obj, javaObjectID, methodName, retType, isConstructor, JavaCallArgs{argTypes, argValues, argRefs});
214+
result = runtime->CallJSMethodNative(_env, obj, javaObjectID, methodName, retType, isConstructor, JavaCallArgs{argTypes, argValues, argRefs}, primitiveResult);
215215
} catch (NativeScriptException& e) {
216216
e.ReThrowToJava();
217217
} catch (std::exception e) {

‎test-app/runtime/src/main/java/com/tns/Runtime.java‎

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ private native void initNativeScript(int runtimeId, String filesPath, String nat
4343

4444
private native Object runScript(int runtimeId, String filePath) throws NativeScriptException;
4545

46-
private native Object callJSMethodNative(int runtimeId, int javaObjectID, String methodName, int retType, boolean isConstructor, int[] argTypes, long[] argValues, Object[] argRefs) throws NativeScriptException;
46+
private native Object callJSMethodNative(int runtimeId, int javaObjectID, String methodName, int retType, boolean isConstructor, int[] argTypes, long[] argValues, Object[] argRefs, long[] primitiveResult) throws NativeScriptException;
4747

4848
private native void createJSInstanceNative(int runtimeId, Object javaObject, int javaObjectID, String canonicalName);
4949

@@ -1409,8 +1409,10 @@ private Object dispatchCallJSMethodNative(final Object javaObject, final String
14091409
if (enableMultithreadedJavascript || isWorkThread) {
14101410
int javaObjectID = resolveJavaObjectID(javaObject, methodName);
14111411
PackagedArgs packagedArgs = packageArgs(tmpArgs);
1412+
long[] primitiveResult = newPrimitiveResult(returnType);
14121413
try {
1413-
ret = callJSMethodNative(getRuntimeId(), javaObjectID, methodName, returnType, isConstructor, packagedArgs.types, packagedArgs.values, packagedArgs.refs);
1414+
ret = callJSMethodNative(getRuntimeId(), javaObjectID, methodName, returnType, isConstructor, packagedArgs.types, packagedArgs.values, packagedArgs.refs, primitiveResult);
1415+
ret = takePrimitiveResult(ret, returnType, primitiveResult);
14141416
} catch (NativeScriptException e) {
14151417
// With multithreaded JS the owner can be torn down between the
14161418
// routing check and the native call, which then throws
@@ -1449,7 +1451,8 @@ public void run() {
14491451
return;
14501452
}
14511453
final PackagedArgs packagedArgs = packageArgs(tmpArgs);
1452-
arr[0] = callJSMethodNative(getRuntimeId(), javaObjectID, methodName, returnType, isCtor, packagedArgs.types, packagedArgs.values, packagedArgs.refs);
1454+
final long[] primitiveResult = newPrimitiveResult(returnType);
1455+
arr[0] = takePrimitiveResult(callJSMethodNative(getRuntimeId(), javaObjectID, methodName, returnType, isCtor, packagedArgs.types, packagedArgs.values, packagedArgs.refs, primitiveResult), returnType, primitiveResult);
14531456
} catch (NativeScriptException e) {
14541457
if (discardUncaughtJsExceptions && !e.isEscapedFromJs()) {
14551458
String errorMessage = "Error on \"" + Thread.currentThread().getName() + "\" thread for callJSMethodNative\n";
@@ -1533,6 +1536,36 @@ private static Object discardCall(String methodName, Class<?> retType, String re
15331536
: null;
15341537
}
15351538

1539+
/*
1540+
* For return types the native side can hand back as raw bits instead of a
1541+
* boxed object: it writes {bits, 1} here and returns null, or leaves the
1542+
* array untouched and returns the boxed value as before.
1543+
*/
1544+
private static long[] newPrimitiveResult(int returnType) {
1545+
boolean raw = returnType == TypeIDs.Boolean || returnType == TypeIDs.Int || returnType == TypeIDs.Long
1546+
|| returnType == TypeIDs.Float || returnType == TypeIDs.Double;
1547+
return raw ? new long[2] : null;
1548+
}
1549+
1550+
private static Object takePrimitiveResult(Object nativeResult, int returnType, long[] primitiveResult) {
1551+
if (primitiveResult == null || primitiveResult[1] == 0) {
1552+
return nativeResult;
1553+
}
1554+
1555+
long bits = primitiveResult[0];
1556+
if (returnType == TypeIDs.Boolean) {
1557+
return bits != 0;
1558+
} else if (returnType == TypeIDs.Int) {
1559+
return (int) bits;
1560+
} else if (returnType == TypeIDs.Long) {
1561+
return bits;
1562+
} else if (returnType == TypeIDs.Float) {
1563+
return Float.intBitsToFloat((int) bits);
1564+
} else {
1565+
return Double.longBitsToDouble(bits);
1566+
}
1567+
}
1568+
15361569
private static Object defaultPrimitiveValue(Class<?> type) {
15371570
if (type == boolean.class) {
15381571
return Boolean.FALSE;

0 commit comments

Comments
 (0)