Repository navigation
Expand file tree
/
Copy pathMethodCache.cpp
More file actions
298 lines (242 loc) · 11.3 KB
/
Copy pathMethodCache.cpp
File metadata and controls
298 lines (242 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#include "MethodCache.h"
#include <shared_mutex>
#include "JniLocalRef.h"
#include "JsArgToArrayConverter.h"
#include "MetadataNode.h"
#include "NativeScriptAssert.h"
#include "Util.h"
#include "V8GlobalHelpers.h"
#include "ArgConverter.h"
#include "V8StringConstants.h"
#include "NumericCasts.h"
#include "NativeScriptException.h"
#include "Runtime.h"
#include "ObjectManager.h"
using namespace v8;
/*
* s_mthod_ctor_signature_cache is process-wide and string-keyed: it holds only
* JNI handles, so sharing it across runtimes is correct -- but every runtime
* resolves into it from its own thread, and workers run concurrently. Shared
* for lookups (the common case by far), exclusive only to publish a new entry.
* Never held across the JNI resolution itself: two threads may resolve the
* same signature, which is idempotent, and the first one published wins.
*/
static std::shared_mutex signatureCacheMutex;
using namespace std;
using namespace tns;
void MethodCache::Init() {
JEnv env;
RUNTIME_CLASS = env.FindClass("com/tns/Runtime");
NS_CHECK(RUNTIME_CLASS != nullptr);
RESOLVE_METHOD_OVERLOAD_METHOD_ID = env.GetMethodID(RUNTIME_CLASS, "resolveMethodOverload", "(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;");
NS_CHECK(RESOLVE_METHOD_OVERLOAD_METHOD_ID != nullptr);
RESOLVE_CONSTRUCTOR_SIGNATURE_ID = env.GetMethodID(RUNTIME_CLASS, "resolveConstructorSignature", "(Ljava/lang/Class;[Ljava/lang/Object;)Ljava/lang/String;");
NS_CHECK(RESOLVE_CONSTRUCTOR_SIGNATURE_ID != nullptr);
}
static const MethodCache::CacheMethodInfo s_unresolved;
const MethodCache::CacheMethodInfo& MethodCache::ResolveMethodSignature(const string& className, const string& methodName, const FunctionCallbackInfo<Value>& args, bool isStatic) {
CacheMethodInfo method_info;
auto& signatureKey = Runtime::GetRuntime(args.GetIsolate())->GetSignatureKeyScratch();
EncodeSignature(signatureKey, className, methodName, args, isStatic);
{
std::shared_lock<std::shared_mutex> lock(signatureCacheMutex);
auto it = s_mthod_ctor_signature_cache.find(signatureKey);
if (it != s_mthod_ctor_signature_cache.end()) {
return it->second;
}
}
// Resolving calls into Java, which may call back into JS and reuse the scratch key.
string encoded_method_signature = signatureKey;
auto signature = ResolveJavaMethod(args, className, methodName);
DEBUG_WRITE("ResolveMethodSignature %s='%s'", encoded_method_signature.c_str(), signature.c_str());
if (!signature.empty()) {
JEnv env;
auto clazz = env.FindClass(className);
NS_DCHECK(clazz != nullptr);
method_info.clazz = clazz;
method_info.signature = signature;
method_info.returnType = MetadataReader::ParseReturnType(method_info.signature);
method_info.retType = MetadataReader::GetReturnType(method_info.returnType);
method_info.isStatic = isStatic;
method_info.mid = isStatic
? env.GetStaticMethodID(clazz, methodName, signature)
:
env.GetMethodID(clazz, methodName, signature);
std::unique_lock<std::shared_mutex> lock(signatureCacheMutex);
return s_mthod_ctor_signature_cache.emplace(encoded_method_signature, method_info).first->second;
}
return s_unresolved;
}
const MethodCache::CacheMethodInfo& MethodCache::ResolveConstructorSignature(const ArgsWrapper& argWrapper, const string& fullClassName, jclass javaClass, bool isInterface) {
CacheMethodInfo constructor_info;
auto& args = argWrapper.args;
static const string kConstructorName = "<init>";
auto& signatureKey = Runtime::GetRuntime(args.GetIsolate())->GetSignatureKeyScratch();
EncodeSignature(signatureKey, fullClassName, kConstructorName, args, false);
{
std::shared_lock<std::shared_mutex> lock(signatureCacheMutex);
auto it = s_mthod_ctor_signature_cache.find(signatureKey);
if (it != s_mthod_ctor_signature_cache.end()) {
return it->second;
}
}
string encoded_ctor_signature = signatureKey;
auto signature = ResolveConstructor(args, javaClass, isInterface);
DEBUG_WRITE("ResolveConstructorSignature %s='%s'", encoded_ctor_signature.c_str(), signature.c_str());
if (!signature.empty()) {
JEnv env;
constructor_info.clazz = javaClass;
constructor_info.signature = signature;
constructor_info.mid = env.GetMethodID(javaClass, "<init>", signature);
// Runtime.resolveConstructorSignature answers this for no Java arguments only for an
// interface proxy; any other class would need a one-argument call to resolve to it.
bool hasJavaArgs = !isInterface && args.Length() > 0;
constructor_info.isInterfaceProxy = !hasJavaArgs && signature == "(Ljava/lang/reflect/InvocationHandler;)V";
std::unique_lock<std::shared_mutex> lock(signatureCacheMutex);
return s_mthod_ctor_signature_cache.emplace(encoded_ctor_signature, constructor_info).first->second;
}
return s_unresolved;
}
// Encoded signature <className>.S/I.<methodName>.<argsCount>.<arg1class>.<...>
void MethodCache::EncodeSignature(string& sig, const string& className, const string& methodName, const FunctionCallbackInfo<Value>& args, bool isStatic) {
int len = args.Length();
sig.clear();
sig.append(className);
sig.append(isStatic ? ".S." : ".I.");
sig.append(methodName);
sig.append(".");
sig.append(std::to_string(len));
for (int i = 0; i < len; i++) {
sig.append(".");
AppendType(sig, args.GetIsolate(), args[i]);
}
}
void MethodCache::AppendType(string& type, Isolate* isolate, const v8::Local<v8::Value>& jsValue) {
// Overloads resolve against what a Proxy wraps.
auto value = ObjectManager::UnwrapProxy(jsValue);
if (value->IsObject()) {
auto context = isolate->GetCurrentContext();
auto objVal = value->ToObject(context).ToLocalChecked();
Local<Value> nullNode; //out
V8GetPrivateValue(isolate, objVal, V8StringConstants::GetNullNodePrivate(isolate), nullNode);
if (!nullNode.IsEmpty()) {
auto treeNode = reinterpret_cast<MetadataNode*>(nullNode.As<External>()->Value(v8::kExternalPointerTypeTagDefault));
if (treeNode != nullptr) {
type += treeNode->GetName();
} else {
type += "<unknown>";
}
DEBUG_WRITE("Parameter of type %s with NULL value is passed to the method.", type.c_str());
return;
}
}
if (value->IsArray()) {
type += "array";
} else if (value->IsArrayBuffer() || value->IsSharedArrayBuffer() || value->IsInt8Array() || value->IsUint8Array() || value->IsUint8ClampedArray()) {
type += "bytebuffer";
} else if (value->IsInt16Array() || value->IsUint16Array()) {
type += "shortbuffer";
} else if (value->IsInt32Array() || value->IsUint32Array()) {
type += "intbuffer";
} else if (value->IsBigUint64Array() || value->IsBigInt64Array()) {
type += "longbuffer";
} else if (value->IsFloat32Array()) {
type += "floatbuffer";
} else if (value->IsFloat64Array()) {
type += "doublebuffer";
} else if (value->IsBoolean() || value->IsBooleanObject() || value->IsFalse() || value->IsTrue()) {
type += "bool";
} else if (value->IsDataView()) {
type += "view";
} else if (value->IsDate()) {
type += "date";
} else if (value->IsFunction()) {
type += "function";
} else if (value->IsInt32() || value->IsUint32()) {
type += "int";
} else if (value->IsNull() || value->IsUndefined()) {
type += "null";
} else if (value->IsString() || value->IsStringObject()) {
type += "string";
} else if (value->IsNumber() || value->IsNumberObject()) {
// Not NumberValue: a user valueOf could call into Java and reuse the thread's key.
double d = value->IsNumberObject() ? value.As<NumberObject>()->ValueOf()
: value.As<Number>()->Value();
int64_t i = (int64_t) d;
bool isInteger = d == i;
type += isInteger ? "intnumber" : "doublenumber";
} else if (value->IsObject()) {
auto context = isolate->GetCurrentContext();
auto object = value->ToObject(context).ToLocalChecked();
auto castType = NumericCasts::GetCastType(isolate, object);
MetadataNode* node;
switch (castType) {
case CastType::Char:
type += "char";
break;
case CastType::Byte:
type += "byte";
break;
case CastType::Short:
type += "short";
break;
case CastType::Long:
type += "long";
break;
case CastType::Float:
type += "float";
break;
case CastType::Double:
type += "double";
break;
case CastType::None:
node = MetadataNode::GetNodeFromHandle(object);
if (node != nullptr) {
type += node->GetName();
} else {
type += "<unknown>";
}
break;
default:
throw NativeScriptException("Unsupported cast type");
}
}
}
string MethodCache::ResolveJavaMethod(const FunctionCallbackInfo<Value>& args, const string& className, const string& methodName) {
JEnv env;
JsArgToArrayConverter argConverter(args, false);
auto canonicalClassName = Util::ConvertFromJniToCanonicalName(className);
JniLocalRef jsClassName(env.NewStringUTF(canonicalClassName.c_str()));
JniLocalRef jsMethodName(env.NewStringUTF(methodName.c_str()));
jobjectArray arrArgs = argConverter.ToJavaArray();
auto runtime = Runtime::GetRuntime(args.GetIsolate());
jstring signature = (jstring) env.CallObjectMethod(runtime->GetJavaRuntime(), RESOLVE_METHOD_OVERLOAD_METHOD_ID, (jstring) jsClassName, (jstring) jsMethodName, arrArgs);
string resolvedSignature;
const char* str = env.GetStringUTFChars(signature, nullptr);
resolvedSignature = string(str);
env.ReleaseStringUTFChars(signature, str);
env.DeleteLocalRef(signature);
return resolvedSignature;
}
string MethodCache::ResolveConstructor(const FunctionCallbackInfo<Value>& args, jclass javaClass, bool isInterface) {
JEnv env;
string resolvedSignature;
JsArgToArrayConverter argConverter(args, isInterface);
if (argConverter.IsValid()) {
jobjectArray javaArgs = argConverter.ToJavaArray();
auto runtime = Runtime::GetRuntime(args.GetIsolate());
jstring signature = (jstring) env.CallObjectMethod(runtime->GetJavaRuntime(), RESOLVE_CONSTRUCTOR_SIGNATURE_ID, javaClass, javaArgs);
const char* str = env.GetStringUTFChars(signature, nullptr);
resolvedSignature = string(str);
env.ReleaseStringUTFChars(signature, str);
env.DeleteLocalRef(signature);
} else {
JsArgToArrayConverter::Error err = argConverter.GetError();
throw NativeScriptException(err.msg);
}
return resolvedSignature;
}
robin_hood::unordered_node_map<string, MethodCache::CacheMethodInfo> MethodCache::s_mthod_ctor_signature_cache;
jclass MethodCache::RUNTIME_CLASS = nullptr;
jmethodID MethodCache::RESOLVE_METHOD_OVERLOAD_METHOD_ID = nullptr;
jmethodID MethodCache::RESOLVE_CONSTRUCTOR_SIGNATURE_ID = nullptr;