forked from NativeScript/android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsArgConverter.cpp
More file actions
698 lines (587 loc) · 24.6 KB
/
JsArgConverter.cpp
File metadata and controls
698 lines (587 loc) · 24.6 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
#include "JsArgConverter.h"
#include "ObjectManager.h"
#include "JniSignatureParser.h"
#include "JsArgToArrayConverter.h"
#include "ArgConverter.h"
#include "V8StringConstants.h"
#include "NumericCasts.h"
#include "NativeScriptException.h"
#include "Runtime.h"
#include "V8GlobalHelpers.h"
#include <cstdlib>
using namespace v8;
using namespace std;
using namespace tns;
JsArgConverter::JsArgConverter(const Local<Object> &caller,
const v8::FunctionCallbackInfo<Value> &args,
const string &methodSignature, MetadataEntry *entry)
: m_isolate(args.GetIsolate()), m_methodSignature(methodSignature), m_isValid(true),
m_error(Error()) {
int v8ProvidedArgumentsLength = args.Length();
m_argsLen = 1 + v8ProvidedArgumentsLength;
if (m_argsLen > 0) {
if ((entry != nullptr) && (entry->getIsResolved())) {
if (entry->parsedSig.empty()) {
JniSignatureParser parser(m_methodSignature);
entry->parsedSig = parser.Parse();
}
m_tokens = entry->parsedSig;
} else {
JniSignatureParser parser(m_methodSignature);
m_tokens = parser.Parse();
}
m_isValid = ConvertArg(caller, 0);
if (!m_isValid) {
throw NativeScriptException("Error while converting argument!");
}
for (int i = 0; i < v8ProvidedArgumentsLength; i++) {
m_isValid = ConvertArg(args[i], i + 1);
if (!m_isValid) {
break;
}
}
}
}
JsArgConverter::JsArgConverter(const v8::FunctionCallbackInfo<Value> &args,
bool hasImplementationObject, const string &methodSignature,
MetadataEntry *entry)
: m_isolate(args.GetIsolate()), m_methodSignature(methodSignature), m_isValid(true),
m_error(Error()) {
m_argsLen = !hasImplementationObject ? args.Length() : args.Length() - 1;
if (m_argsLen > 0) {
if ((entry != nullptr) && (entry->getIsResolved())) {
if (entry->parsedSig.empty()) {
JniSignatureParser parser(m_methodSignature);
entry->parsedSig = parser.Parse();
}
m_tokens = entry->parsedSig;
} else {
JniSignatureParser parser(m_methodSignature);
m_tokens = parser.Parse();
}
for (int i = 0; i < m_argsLen; i++) {
m_isValid = ConvertArg(args[i], i);
if (!m_isValid) {
break;
}
}
}
}
JsArgConverter::JsArgConverter(const v8::FunctionCallbackInfo<Value> &args,
const string &methodSignature)
: m_isolate(args.GetIsolate()), m_methodSignature(methodSignature), m_isValid(true),
m_error(Error()) {
m_argsLen = args.Length();
JniSignatureParser parser(m_methodSignature);
m_tokens = parser.Parse();
for (int i = 0; i < m_argsLen; i++) {
m_isValid = ConvertArg(args[i], i);
if (!m_isValid) {
break;
}
}
}
tns::BufferCastType JsArgConverter::GetCastType(const v8::Local<v8::ArrayBufferView> &view) {
if (view->IsUint16Array() || view->IsInt16Array()) {
return tns::BufferCastType::Short;
} else if (view->IsUint32Array() || view->IsInt32Array()) {
return tns::BufferCastType::Int;
} else if (view->IsFloat32Array()) {
return tns::BufferCastType::Float;
} else if (view->IsFloat64Array()) {
return tns::BufferCastType::Double;
} else if (view->IsBigUint64Array() || view->IsBigInt64Array()) {
return tns::BufferCastType::Long;
}
return tns::BufferCastType::Byte;
}
bool JsArgConverter::ConvertArg(const Local<Value> &arg, int index) {
bool success = false;
char buff[1024];
const auto &typeSignature = m_tokens.at(index);
if (arg.IsEmpty()) {
SetConvertedObject(index, nullptr);
success = false;
} else if (arg->IsArray()) {
success = typeSignature[0] == '[';
if (success) {
auto jsArr = Local<Array>::Cast(arg);
success = ConvertJavaScriptArray(jsArr, index);
}
if (!success) {
sprintf(buff, "Cannot convert array to %s at index %d", typeSignature.c_str(), index);
}
} else if (arg->IsNumber() || arg->IsNumberObject()) {
success = ConvertJavaScriptNumber(arg, index);
if (!success) {
sprintf(buff, "Cannot convert number to %s at index %d", typeSignature.c_str(), index);
}
} else if (arg->IsBoolean() || arg->IsBooleanObject()) {
success = ConvertJavaScriptBoolean(arg, index);
if (!success) {
sprintf(buff, "Cannot convert boolean to %s at index %d", typeSignature.c_str(), index);
}
} else if (arg->IsString() || arg->IsStringObject()) {
success = ConvertJavaScriptString(arg, index);
if (!success) {
sprintf(buff, "Cannot convert string to %s at index %d", typeSignature.c_str(), index);
}
} else if (arg->IsObject()) {
auto context = m_isolate->GetCurrentContext();
auto jsObject = arg->ToObject(context).ToLocalChecked();
auto castType = NumericCasts::GetCastType(m_isolate, jsObject);
Local<Value> castValue;
JniLocalRef obj;
auto runtime = Runtime::GetRuntime(m_isolate);
auto objectManager = runtime->GetObjectManager();
JEnv env;
switch (castType) {
case CastType::Char:
castValue = NumericCasts::GetCastValue(jsObject);
if (castValue->IsString()) {
string value = ArgConverter::ConvertToString(
castValue->ToString(context).ToLocalChecked());
m_args[index].c = (jchar) value[0];
success = true;
}
break;
case CastType::Byte:
castValue = NumericCasts::GetCastValue(jsObject);
if (castValue->IsString()) {
string strValue = ArgConverter::ConvertToString(
castValue->ToString(context).ToLocalChecked());
int byteArg = atoi(strValue.c_str());
jbyte value = (jbyte) byteArg;
success = ConvertFromCastFunctionObject(value, index);
} else if (castValue->IsInt32()) {
jbyte value = (jbyte) castValue->ToInt32(context).ToLocalChecked()->Int32Value(
context).ToChecked();
success = ConvertFromCastFunctionObject(value, index);
}
break;
case CastType::Short:
castValue = NumericCasts::GetCastValue(jsObject);
if (castValue->IsString()) {
string strValue = ArgConverter::ConvertToString(
castValue->ToString(context).ToLocalChecked());
int shortArg = atoi(strValue.c_str());
jshort value = (jshort) shortArg;
success = ConvertFromCastFunctionObject(value, index);
} else if (castValue->IsInt32()) {
jshort value = (jshort) castValue->ToInt32(
context).ToLocalChecked()->Int32Value(context).ToChecked();
success = ConvertFromCastFunctionObject(value, index);
}
break;
case CastType::Long:
castValue = NumericCasts::GetCastValue(jsObject);
if (castValue->IsString()) {
string strValue = ArgConverter::ConvertToString(
castValue->ToString(context).ToLocalChecked());
int64_t longArg = atoll(strValue.c_str());
jlong value = (jlong) longArg;
success = ConvertFromCastFunctionObject(value, index);
} else if (castValue->IsInt32()) {
jlong value = (jlong) castValue->ToInt32(
context).ToLocalChecked()->IntegerValue(context).ToChecked();
success = ConvertFromCastFunctionObject(value, index);
}
break;
case CastType::Float:
castValue = NumericCasts::GetCastValue(jsObject);
if (castValue->IsNumber()) {
double floatArg = castValue->ToNumber(context).ToLocalChecked()->NumberValue(
context).ToChecked();
jfloat value = (jfloat) floatArg;
success = ConvertFromCastFunctionObject(value, index);
}
break;
case CastType::Double:
castValue = NumericCasts::GetCastValue(jsObject);
if (castValue->IsNumber()) {
double doubleArg = castValue->ToNumber(context).ToLocalChecked()->NumberValue(
context).ToChecked();
jdouble value = (jdouble) doubleArg;
success = ConvertFromCastFunctionObject(value, index);
}
break;
case CastType::None:
obj = objectManager->GetJavaObjectByJsObject(jsObject);
if (obj.IsNull() && (jsObject->IsTypedArray() || jsObject->IsArrayBuffer() ||
jsObject->IsArrayBufferView())) {
BufferCastType bufferCastType = tns::BufferCastType::Byte;
shared_ptr<BackingStore> store;
size_t offset = 0;
size_t length;
uint8_t *data = nullptr;
if (jsObject->IsArrayBuffer()) {
auto array = jsObject.As<v8::ArrayBuffer>();
store = array->GetBackingStore();
length = array->ByteLength();
data = static_cast<uint8_t *>(store->Data());
} else if (jsObject->IsArrayBufferView()) {
auto array = jsObject.As<v8::ArrayBufferView>();
offset = array->ByteOffset();
length = array->ByteLength();
store = array->Buffer()->GetBackingStore();
data = static_cast<uint8_t *>(store->Data()) + offset;
bufferCastType = JsArgConverter::GetCastType(array);
} else {
auto array = jsObject.As<v8::TypedArray>();
offset = array->ByteOffset();
store = array->Buffer()->GetBackingStore();
length = array->ByteLength();
data = static_cast<uint8_t *>(store->Data()) + offset;
bufferCastType = JsArgConverter::GetCastType(array);
}
auto directBuffer = env.NewDirectByteBuffer(
data,
length);
auto directBufferClazz = env.GetObjectClass(directBuffer);
auto byteOrderId = env.GetMethodID(directBufferClazz, "order",
"(Ljava/nio/ByteOrder;)Ljava/nio/ByteBuffer;");
auto byteOrderClazz = env.FindClass("java/nio/ByteOrder");
auto byteOrderEnumId = env.GetStaticMethodID(byteOrderClazz, "nativeOrder",
"()Ljava/nio/ByteOrder;");
auto nativeByteOrder = env.CallStaticObjectMethodA(byteOrderClazz,
byteOrderEnumId,
nullptr);
directBuffer = env.CallObjectMethod(directBuffer, byteOrderId, nativeByteOrder);
jobject buffer;
if (bufferCastType == BufferCastType::Short) {
auto id = env.GetMethodID(directBufferClazz, "asShortBuffer",
"()Ljava/nio/ShortBuffer;");
buffer = env.CallObjectMethodA(directBuffer, id, nullptr);
} else if (bufferCastType == BufferCastType::Int) {
auto id = env.GetMethodID(directBufferClazz, "asIntBuffer",
"()Ljava/nio/IntBuffer;");
buffer = env.CallObjectMethodA(directBuffer, id, nullptr);
} else if (bufferCastType == BufferCastType::Long) {
auto id = env.GetMethodID(directBufferClazz, "asLongBuffer",
"()Ljava/nio/LongBuffer;");
buffer = env.CallObjectMethodA(directBuffer, id, nullptr);
} else if (bufferCastType == BufferCastType::Float) {
auto id = env.GetMethodID(directBufferClazz, "asFloatBuffer",
"()Ljava/nio/FloatBuffer;");
buffer = env.CallObjectMethodA(directBuffer, id, nullptr);
} else if (bufferCastType == BufferCastType::Double) {
auto id = env.GetMethodID(directBufferClazz, "asDoubleBuffer",
"()Ljava/nio/DoubleBuffer;");
buffer = env.CallObjectMethodA(directBuffer, id, nullptr);
} else {
buffer = directBuffer;
}
buffer = env.NewGlobalRef(buffer);
int id = objectManager->GetOrCreateObjectId(buffer);
auto clazz = env.GetObjectClass(buffer);
objectManager->Link(jsObject, id, clazz);
obj = objectManager->GetJavaObjectByJsObject(jsObject);
}
V8GetPrivateValue(m_isolate, jsObject, ArgConverter::ConvertToV8String(m_isolate,
V8StringConstants::NULL_NODE_NAME),
castValue);
if (!castValue.IsEmpty()) {
SetConvertedObject(index, nullptr);
success = true;
break;
}
success = !obj.IsNull();
if (success) {
SetConvertedObject(index, obj.Move(), obj.IsGlobal());
} else {
sprintf(buff, "Cannot convert object to %s at index %d", typeSignature.c_str(),
index);
}
break;
default:
throw NativeScriptException("Unsupported cast type");
}
} else if (arg->IsUndefined() || arg->IsNull()) {
SetConvertedObject(index, nullptr);
success = true;
} else {
SetConvertedObject(index, nullptr);
success = false;
}
if (!success) {
m_error.index = index;
m_error.msg = string(buff);
}
return success;
}
void JsArgConverter::SetConvertedObject(int index, jobject obj, bool isGlobal) {
m_args[index].l = obj;
if ((obj != nullptr) && !isGlobal) {
m_args_refs[m_args_refs_size++] = index;
}
}
bool JsArgConverter::ConvertJavaScriptNumber(const Local<Value> &jsValue, int index) {
bool success = true;
jvalue value = {
0
};
const auto &typeSignature = m_tokens.at(index);
auto context = m_isolate->GetCurrentContext();
const char typePrefix = typeSignature[0];
switch (typePrefix) {
case 'B': // byte
value.b = (jbyte) jsValue->Int32Value(context).ToChecked();
break;
case 'S': // short
value.s = (jshort) jsValue->Int32Value(context).ToChecked();
break;
case 'I': // int
value.i = (jint) jsValue->Int32Value(context).ToChecked();
break;
case 'J': // long
// TODO: refactor the whole method
if (jsValue->IsNumberObject()) {
auto numObj = Local<NumberObject>::Cast(jsValue);
value.j = (jlong) numObj->ValueOf();
} else {
value.j = (jlong) jsValue->IntegerValue(context).ToChecked();
}
break;
case 'F': // float
value.f = (jfloat) jsValue->NumberValue(context).ToChecked();
break;
case 'D': // double
value.d = (jdouble) jsValue->NumberValue(context).ToChecked();
break;
default:
success = false;
break;
}
if (success) {
m_args[index] = value;
}
return success;
}
bool JsArgConverter::ConvertJavaScriptBoolean(const Local<Value> &jsValue, int index) {
bool success;
const auto &typeSignature = m_tokens.at(index);
auto context = m_isolate->GetCurrentContext();
if (typeSignature == "Z") {
bool argValue;
if (jsValue->IsBoolean()) {
argValue = jsValue->BooleanValue(m_isolate);
} else {
auto boolObj = Local<BooleanObject>::Cast(jsValue);
Local<Value> val;
boolObj->Get(context, V8StringConstants::GetValueOf(m_isolate)).ToLocal(&val);
if (!val.IsEmpty() && val->IsFunction()) {
argValue = val.As<Function>()->Call(context, boolObj, 0,
nullptr).ToLocalChecked()->BooleanValue(
m_isolate);
} else {
argValue = false;
}
}
jboolean value = argValue ? JNI_TRUE : JNI_FALSE;
m_args[index].z = value;
success = true;
} else {
success = false;
}
return success;
}
bool JsArgConverter::ConvertJavaScriptString(const Local<Value> &jsValue, int index) {
jstring stringObject = ArgConverter::ConvertToJavaString(jsValue);
SetConvertedObject(index, stringObject);
return true;
}
bool JsArgConverter::ConvertJavaScriptArray(const Local<Array> &jsArr, int index) {
bool success = true;
jarray arr = nullptr;
jsize arrLength = jsArr->Length();
const auto &arraySignature = m_tokens.at(index);
auto context = m_isolate->GetCurrentContext();
string elementType = arraySignature.substr(1);
const char elementTypePrefix = elementType[0];
jclass elementClass;
string strippedClassName;
JEnv env;
switch (elementTypePrefix) {
case 'Z': {
arr = env.NewBooleanArray(arrLength);
jboolean bools[arrLength];
for (jsize i = 0; i < arrLength; i++) {
bools[i] = jsArr
->Get(context, i)
.ToLocalChecked()
->BooleanValue(m_isolate);
}
env.SetBooleanArrayRegion((jbooleanArray) arr, 0, arrLength, bools);
break;
}
case 'B': {
arr = env.NewByteArray(arrLength);
jbyte bytes[arrLength];
for (jsize i = 0; i < arrLength; i++) {
bytes[i] = jsArr
->Get(context, i)
.ToLocalChecked()
->Int32Value(context)
.ToChecked();
}
env.SetByteArrayRegion((jbyteArray) arr, 0, arrLength, bytes);
break;
}
case 'C': {
arr = env.NewCharArray(arrLength);
jchar chars[arrLength];
for (jsize i = 0; i < arrLength; i++) {
String::Utf8Value utf8(m_isolate, jsArr->Get(context, i).ToLocalChecked()->ToString(
context).ToLocalChecked());
JniLocalRef s(env.NewString((jchar *) *utf8, 1));
const char *singleChar = env.GetStringUTFChars(s, nullptr);
chars[i] = *singleChar;
env.ReleaseStringUTFChars(s, singleChar);
}
env.SetCharArrayRegion((jcharArray) arr, 0, arrLength, chars);
break;
}
case 'S': {
arr = env.NewShortArray(arrLength);
jshort shorts[arrLength];
for (jsize i = 0; i < arrLength; i++) {
shorts[i] = jsArr
->Get(context, i)
.ToLocalChecked()
->Int32Value(context)
.ToChecked();
}
env.SetShortArrayRegion((jshortArray) arr, 0, arrLength, shorts);
break;
}
case 'I': {
arr = env.NewIntArray(arrLength);
jint ints[arrLength];
for (jsize i = 0; i < arrLength; i++) {
ints[i] = jsArr
->Get(context, i)
.ToLocalChecked()
->Int32Value(context)
.ToChecked();
}
env.SetIntArrayRegion((jintArray) arr, 0, arrLength, ints);
break;
}
case 'J': {
arr = env.NewLongArray(arrLength);
jlong longs[arrLength];
for (jsize i = 0; i < arrLength; i++) {
longs[i] = jsArr
->Get(context, i)
.ToLocalChecked()
->NumberValue(context)
.ToChecked();
}
env.SetLongArrayRegion((jlongArray) arr, 0, arrLength, longs);
break;
}
case 'F': {
arr = env.NewFloatArray(arrLength);
jfloat floats[arrLength];
for (jsize i = 0; i < arrLength; i++) {
floats[i] = jsArr
->Get(context, i)
.ToLocalChecked()
->NumberValue(context)
.ToChecked();
}
env.SetFloatArrayRegion((jfloatArray) arr, 0, arrLength, floats);
break;
}
case 'D': {
arr = env.NewDoubleArray(arrLength);
jdouble doubles[arrLength];
for (jsize i = 0; i < arrLength; i++) {
doubles[i] = jsArr
->Get(context, i)
.ToLocalChecked()
->NumberValue(context)
.ToChecked();
}
env.SetDoubleArrayRegion((jdoubleArray) arr, 0, arrLength, doubles);
break;
}
case 'L':
strippedClassName = elementType.substr(1, elementType.length() - 2);
elementClass = env.FindClass(strippedClassName);
arr = env.NewObjectArray(arrLength, elementClass, nullptr);
for (int i = 0; i < arrLength; i++) {
auto v = jsArr->Get(context, i).ToLocalChecked();
JsArgToArrayConverter c(context, v, false, (int) Type::Null);
jobject o = c.GetConvertedArg();
env.SetObjectArrayElement((jobjectArray) arr, i, o);
}
break;
default:
success = false;
break;
}
if (success) {
SetConvertedObject(index, arr);
}
return success;
}
template<typename T>
bool JsArgConverter::ConvertFromCastFunctionObject(T value, int index) {
bool success = false;
const auto &typeSignature = m_tokens.at(index);
const char typeSignaturePrefix = typeSignature[0];
switch (typeSignaturePrefix) {
case 'B':
m_args[index].b = (jbyte) value;
success = true;
break;
case 'S':
m_args[index].s = (jshort) value;
success = true;
break;
case 'I':
m_args[index].i = (jint) value;
success = true;
break;
case 'J':
m_args[index].j = (jlong) value;
success = true;
break;
case 'F':
m_args[index].f = (jfloat) value;
success = true;
break;
case 'D':
m_args[index].d = (jdouble) value;
success = true;
break;
default:
success = false;
break;
}
return success;
}
int JsArgConverter::Length() const {
return m_argsLen;
}
bool JsArgConverter::IsValid() const {
return m_isValid;
}
jvalue *JsArgConverter::ToArgs() {
return m_args;
}
JsArgConverter::Error JsArgConverter::GetError() const {
return m_error;
}
JsArgConverter::~JsArgConverter() {
if (m_argsLen > 0) {
JEnv env;
for (int i = 0; i < m_args_refs_size; i++) {
int index = m_args_refs[i];
if (index != -1) {
env.DeleteLocalRef(m_args[index].l);
}
}
}
}