forked from NativeScript/android
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMetadataNode.cpp
2252 lines (1838 loc) · 89.9 KB
/
MetadataNode.cpp
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "MetadataNode.h"
#include "NativeScriptAssert.h"
#include "Constants.h"
#include "Util.h"
#include "V8GlobalHelpers.h"
#include "ArgConverter.h"
#include "V8StringConstants.h"
#include "SimpleProfiler.h"
#include "CallbackHandlers.h"
#include "NativeScriptException.h"
#include "Runtime.h"
#include <sstream>
#include <cctype>
#include <dirent.h>
#include <errno.h>
#include <android/log.h>
#include <unistd.h>
#include "ManualInstrumentation.h"
#include "JSONObjectHelper.h"
#include "v8.h"
using namespace v8;
using namespace std;
using namespace tns;
void MetadataNode::Init(Isolate* isolate) {
auto key = ArgConverter::ConvertToV8String(isolate, "tns::MetadataKey");
auto cache = GetMetadataNodeCache(isolate);
cache->MetadataKey = new Persistent<String>(isolate, key);
}
Local<ObjectTemplate> MetadataNode::GetOrCreateArrayObjectTemplate(Isolate* isolate) {
auto it = s_arrayObjectTemplates.find(isolate);
if (it != s_arrayObjectTemplates.end()) {
return it->second->Get(isolate);
}
auto arrayObjectTemplate = ObjectTemplate::New(isolate);
arrayObjectTemplate->SetInternalFieldCount(static_cast<int>(ObjectManager::MetadataNodeKeys::END));
arrayObjectTemplate->SetIndexedPropertyHandler(ArrayIndexedPropertyGetterCallback, ArrayIndexedPropertySetterCallback);
s_arrayObjectTemplates.emplace(std::make_pair(isolate, new Persistent<ObjectTemplate>(isolate, arrayObjectTemplate)));
return arrayObjectTemplate;
}
MetadataNode::MetadataNode(MetadataTreeNode* treeNode) :
m_treeNode(treeNode) {
uint8_t nodeType = s_metadataReader.GetNodeType(treeNode);
m_name = s_metadataReader.ReadTypeName(m_treeNode);
uint8_t parentNodeType = s_metadataReader.GetNodeType(treeNode->parent);
m_isArray = s_metadataReader.IsNodeTypeArray(parentNodeType);
bool isInterface = s_metadataReader.IsNodeTypeInterface(nodeType);
if (!m_isArray && isInterface) {
bool isPrefix;
auto impTypeName = s_metadataReader.ReadInterfaceImplementationTypeName(m_treeNode, isPrefix);
m_implType = isPrefix
? (impTypeName + m_name)
:
impTypeName;
}
}
Local<Object> MetadataNode::CreateExtendedJSWrapper(Isolate* isolate, ObjectManager* objectManager, const string& proxyClassName) {
Local<Object> extInstance;
auto cacheData = GetCachedExtendedClassData(isolate, proxyClassName);
if (cacheData.node != nullptr) {
extInstance = objectManager->GetEmptyObject(isolate);
extInstance->SetInternalField(static_cast<int>(ObjectManager::MetadataNodeKeys::CallSuper), True(isolate));
auto extdCtorFunc = Local<Function>::New(isolate, *cacheData.extendedCtorFunction);
auto context = Runtime::GetRuntime(isolate)->GetContext();
extInstance->SetPrototype(context, extdCtorFunc->Get(context, V8StringConstants::GetPrototype(isolate)).ToLocalChecked());
extInstance->Set(context, ArgConverter::ConvertToV8String(isolate, "constructor"), extdCtorFunc);
SetInstanceMetadata(isolate, extInstance, cacheData.node);
}
return extInstance;
}
MetadataNode* MetadataNode::GetOrCreate(const string& className) {
MetadataNode* node = nullptr;
auto it = s_name2NodeCache.find(className);
if (it == s_name2NodeCache.end()) {
MetadataTreeNode* treeNode = GetOrCreateTreeNodeByName(className);
node = GetOrCreateInternal(treeNode);
s_name2NodeCache.emplace(className, node);
} else {
node = it->second;
}
return node;
}
MetadataNode* MetadataNode::GetOrCreateInternal(MetadataTreeNode* treeNode) {
MetadataNode* result = nullptr;
auto it = s_treeNode2NodeCache.find(treeNode);
if (it != s_treeNode2NodeCache.end()) {
result = it->second;
} else {
result = new MetadataNode(treeNode);
s_treeNode2NodeCache.emplace(treeNode, result);
}
return result;
}
MetadataTreeNode* MetadataNode::GetOrCreateTreeNodeByName(const string& className) {
MetadataTreeNode* result = nullptr;
auto itFound = s_name2TreeNodeCache.find(className);
if (itFound != s_name2TreeNodeCache.end()) {
result = itFound->second;
} else {
result = s_metadataReader.GetOrCreateTreeNodeByName(className);
s_name2TreeNodeCache.emplace(className, result);
}
return result;
}
string MetadataNode::GetName() {
return m_name;
}
bool MetadataNode::IsNodeTypeInterface() {
uint8_t nodeType = s_metadataReader.GetNodeType(m_treeNode);
return s_metadataReader.IsNodeTypeInterface(nodeType);
}
string MetadataNode::GetTypeMetadataName(Isolate* isolate, Local<Value>& value) {
auto data = GetTypeMetadata(isolate, value.As<Function>());
return data->name;
}
Local<Object> MetadataNode::CreateWrapper(Isolate* isolate) {
EscapableHandleScope handle_scope(isolate);
Local<Object> obj;
uint8_t nodeType = s_metadataReader.GetNodeType(m_treeNode);
bool isClass = s_metadataReader.IsNodeTypeClass(nodeType),
isInterface = s_metadataReader.IsNodeTypeInterface(nodeType);
if (isClass || isInterface) {
obj = GetConstructorFunction(isolate);
} else if (s_metadataReader.IsNodeTypePackage(nodeType)) {
obj = CreatePackageObject(isolate);
} else {
stringstream ss;
ss << "(InternalError): Can't create proxy for this type=" << static_cast<int>(nodeType);
throw NativeScriptException(ss.str());
}
return handle_scope.Escape(obj);
}
Local<Object> MetadataNode::CreateJSWrapper(Isolate* isolate, ObjectManager* objectManager) {
Local<Object> obj;
if (m_isArray) {
obj = CreateArrayWrapper(isolate);
} else {
obj = objectManager->GetEmptyObject(isolate);
if (!obj.IsEmpty()) {
auto ctorFunc = GetConstructorFunction(isolate);
auto context = isolate->GetCurrentContext();
obj->Set(context, ArgConverter::ConvertToV8String(isolate, "constructor"), ctorFunc);
obj->SetPrototype(context, ctorFunc->Get(context, V8StringConstants::GetPrototype(isolate)).ToLocalChecked());
SetInstanceMetadata(isolate, obj, this);
}
}
return obj;
}
void MetadataNode::ArrayLengthGetterCallack(Local<Name> property, const PropertyCallbackInfo<Value>& info) {
try {
auto thiz = info.This();
auto isolate = info.GetIsolate();
auto length = CallbackHandlers::GetArrayLength(isolate, thiz);
info.GetReturnValue().Set(length);
} catch (NativeScriptException& e) {
e.ReThrowToV8();
} catch (std::exception e) {
stringstream ss;
ss << "Error: c++ exception: " << e.what() << endl;
NativeScriptException nsEx(ss.str());
nsEx.ReThrowToV8();
} catch (...) {
NativeScriptException nsEx(std::string("Error: c++ exception!"));
nsEx.ReThrowToV8();
}
}
Local<Object> MetadataNode::CreateArrayWrapper(Isolate* isolate) {
auto node = GetOrCreate("java/lang/Object");
auto ctorFunc = node->GetConstructorFunction(isolate);
auto arrayObjectTemplate = GetOrCreateArrayObjectTemplate(isolate);
auto context = isolate->GetCurrentContext();
auto arr = arrayObjectTemplate->NewInstance(context).ToLocalChecked();
arr->SetPrototype(context, ctorFunc->Get(context, V8StringConstants::GetPrototype(isolate)).ToLocalChecked());
arr->SetAccessor(context, ArgConverter::ConvertToV8String(isolate, "length"), ArrayLengthGetterCallack, nullptr, Local<Value>(), AccessControl::ALL_CAN_READ, PropertyAttribute::DontDelete);
SetInstanceMetadata(isolate, arr, this);
return arr;
}
Local<Object> MetadataNode::CreatePackageObject(Isolate* isolate) {
auto packageObj = Object::New(isolate);
auto ptrChildren = this->m_treeNode->children;
if (ptrChildren != nullptr) {
auto ctx = isolate->GetCurrentContext();
auto extData = External::New(isolate, this);
const auto& children = *ptrChildren;
for (auto childNode: children) {
packageObj->SetAccessor(ctx, ArgConverter::ConvertToV8String(isolate, childNode->name),
PackageGetterCallback,
nullptr,
extData);
}
}
return packageObj;
}
void MetadataNode::SetClassAccessor(Local<Function>& ctorFunction) {
auto isolate = ctorFunction->GetIsolate();
auto classFieldName = ArgConverter::ConvertToV8String(isolate, "class");
auto context = isolate->GetCurrentContext();
ctorFunction->SetAccessor(context, classFieldName, ClassAccessorGetterCallback, nullptr, Local<Value>(), AccessControl::ALL_CAN_READ, PropertyAttribute::DontDelete);
}
void MetadataNode::ClassAccessorGetterCallback(Local<Name> property, const PropertyCallbackInfo<Value>& info) {
try {
auto thiz = info.This();
auto isolate = info.GetIsolate();
auto data = GetTypeMetadata(isolate, thiz.As<Function>());
auto value = CallbackHandlers::FindClass(isolate, data->name);
info.GetReturnValue().Set(value);
} catch (NativeScriptException& e) {
e.ReThrowToV8();
} catch (std::exception e) {
stringstream ss;
ss << "Error: c++ exception: " << e.what() << endl;
NativeScriptException nsEx(ss.str());
nsEx.ReThrowToV8();
} catch (...) {
NativeScriptException nsEx(std::string("Error: c++ exception!"));
nsEx.ReThrowToV8();
}
}
void MetadataNode::NullObjectAccessorGetterCallback(Local<Name> property,const PropertyCallbackInfo<Value>& info) {
try {
DEBUG_WRITE("NullObjectAccessorGetterCallback called");
auto isolate = info.GetIsolate();
auto thiz = info.This();
Local<Value> hiddenVal;
V8GetPrivateValue(isolate, thiz, V8StringConstants::GetNullNodeName(isolate), hiddenVal);
if (hiddenVal.IsEmpty()) {
auto node = reinterpret_cast<MetadataNode*>(info.Data().As<External>()->Value());
V8SetPrivateValue(isolate, thiz, V8StringConstants::GetNullNodeName(isolate), External::New(isolate, node));
auto funcTemplate = FunctionTemplate::New(isolate, MetadataNode::NullValueOfCallback);
auto context = isolate->GetCurrentContext();
thiz->Delete(context, V8StringConstants::GetValueOf(isolate));
thiz->Set(context, V8StringConstants::GetValueOf(isolate), funcTemplate->GetFunction(context).ToLocalChecked());
}
info.GetReturnValue().Set(thiz);
} catch (NativeScriptException& e) {
e.ReThrowToV8();
} catch (std::exception e) {
stringstream ss;
ss << "Error: c++ exception: " << e.what() << endl;
NativeScriptException nsEx(ss.str());
nsEx.ReThrowToV8();
} catch (...) {
NativeScriptException nsEx(std::string("Error: c++ exception!"));
nsEx.ReThrowToV8();
}
}
void MetadataNode::NullValueOfCallback(const FunctionCallbackInfo<Value>& args) {
try {
auto isolate = args.GetIsolate();
args.GetReturnValue().SetNull();
} catch (NativeScriptException& e) {
e.ReThrowToV8();
} catch (std::exception e) {
stringstream ss;
ss << "Error: c++ exception: " << e.what() << endl;
NativeScriptException nsEx(ss.str());
nsEx.ReThrowToV8();
} catch (...) {
NativeScriptException nsEx(std::string("Error: c++ exception!"));
nsEx.ReThrowToV8();
}
}
void MetadataNode::FieldAccessorGetterCallback(Local<Name> property, const PropertyCallbackInfo<Value>& info) {
try {
auto thiz = info.This();
auto fieldCallbackData = reinterpret_cast<FieldCallbackData*>(info.Data().As<External>()->Value());
auto &fieldCallbackMetadata = fieldCallbackData->metadata;
if ((!fieldCallbackMetadata.isStatic && thiz->StrictEquals(info.Holder()))
// check whether there's a declaring type to get the class from it
|| (fieldCallbackMetadata.getDeclaringType() == "")) {
info.GetReturnValue().SetUndefined();
return;
}
auto isolate = info.GetIsolate();
auto value = CallbackHandlers::GetJavaField(isolate, thiz, fieldCallbackData);
info.GetReturnValue().Set(value);
} catch (NativeScriptException& e) {
e.ReThrowToV8();
} catch (std::exception e) {
stringstream ss;
ss << "Error: c++ exception: " << e.what() << endl;
NativeScriptException nsEx(ss.str());
nsEx.ReThrowToV8();
} catch (...) {
NativeScriptException nsEx(std::string("Error: c++ exception!"));
nsEx.ReThrowToV8();
}
}
void MetadataNode::FieldAccessorSetterCallback(Local<Name> property, Local<Value> value, const PropertyCallbackInfo<void>& info) {
try {
auto thiz = info.This();
auto fieldCallbackData = reinterpret_cast<FieldCallbackData*>(info.Data().As<External>()->Value());
auto &fieldCallbackMetadata = fieldCallbackData->metadata;
if (!fieldCallbackMetadata.isStatic && thiz->StrictEquals(info.Holder())) {
auto isolate = info.GetIsolate();
info.GetReturnValue().Set(v8::Undefined(isolate));
return;
}
if (fieldCallbackMetadata.getIsFinal()) {
stringstream ss;
ss << "You are trying to set \"" << fieldCallbackMetadata.getName() << "\" which is a final field! Final fields can only be read.";
string exceptionMessage = ss.str();
throw NativeScriptException(exceptionMessage);
} else {
auto isolate = info.GetIsolate();
CallbackHandlers::SetJavaField(isolate, thiz, value, fieldCallbackData);
info.GetReturnValue().Set(value);
}
} catch (NativeScriptException& e) {
e.ReThrowToV8();
} catch (std::exception e) {
stringstream ss;
ss << "Error: c++ exception: " << e.what() << endl;
NativeScriptException nsEx(ss.str());
nsEx.ReThrowToV8();
} catch (...) {
NativeScriptException nsEx(std::string("Error: c++ exception!"));
nsEx.ReThrowToV8();
}
}
void MetadataNode::PropertyAccessorGetterCallback(Local<Name> property, const PropertyCallbackInfo<Value>& info) {
try {
auto isolate = info.GetIsolate();
auto context = isolate->GetCurrentContext();
auto thiz = info.This();
auto propertyCallbackData = reinterpret_cast<PropertyCallbackData*>(info.Data().As<External>()->Value());
std::string getterMethodName = propertyCallbackData->getterMethodName;
if(getterMethodName == ""){
throw NativeScriptException("Missing getter method for property: " + propertyCallbackData->propertyName);
}
auto getter = thiz->Get(context, v8::String::NewFromUtf8(isolate, getterMethodName.c_str()).ToLocalChecked()).ToLocalChecked();
auto value = getter.As<Function>()->Call(context, thiz, 0, nullptr).ToLocalChecked();
info.GetReturnValue().Set(value);
} catch (NativeScriptException& e) {
e.ReThrowToV8();
} catch (std::exception e) {
stringstream ss;
ss << "Error: c++ exception: " << e.what() << endl;
NativeScriptException nsEx(ss.str());
nsEx.ReThrowToV8();
} catch (...) {
NativeScriptException nsEx(std::string("Error: c++ exception!"));
nsEx.ReThrowToV8();
}
}
void MetadataNode::PropertyAccessorSetterCallback(Local<Name> property, Local<Value> value, const PropertyCallbackInfo<void>& info) {
try {
auto isolate = info.GetIsolate();
auto context = isolate->GetCurrentContext();
auto thiz = info.This();
auto propertyCallbackData = reinterpret_cast<PropertyCallbackData*>(info.Data().As<External>()->Value());
std::string setterMethodName = propertyCallbackData->setterMethodName;
if(setterMethodName == ""){
throw NativeScriptException("Missing setter method for property: " + propertyCallbackData->propertyName);
}
auto setter = thiz->Get(context, v8::String::NewFromUtf8(isolate, setterMethodName.c_str()).ToLocalChecked()).ToLocalChecked();
setter.As<Function>()->Call(context, thiz, 1, &value).ToLocalChecked();
info.GetReturnValue().Set(value);
} catch (NativeScriptException& e) {
e.ReThrowToV8();
} catch (std::exception e) {
stringstream ss;
ss << "Error: c++ exception: " << e.what() << endl;
NativeScriptException nsEx(ss.str());
nsEx.ReThrowToV8();
} catch (...) {
NativeScriptException nsEx(std::string("Error: c++ exception!"));
nsEx.ReThrowToV8();
}
}
void MetadataNode::SuperAccessorGetterCallback(Local<Name> property, const PropertyCallbackInfo<Value>& info) {
try {
auto thiz = info.This();
auto isolate = info.GetIsolate();
auto key = ArgConverter::ConvertToV8String(isolate, "supervalue");
Local<Value> hidenVal;
V8GetPrivateValue(isolate, thiz, key, hidenVal);
auto superValue = hidenVal.As<Object>();
if (superValue.IsEmpty()) {
auto runtime = Runtime::GetRuntime(isolate);
auto objectManager = runtime->GetObjectManager();
auto context = isolate->GetCurrentContext();
superValue = objectManager->GetEmptyObject(isolate);
superValue->Delete(context, V8StringConstants::GetToString(isolate));
superValue->Delete(context, V8StringConstants::GetValueOf(isolate));
superValue->SetInternalField(static_cast<int>(ObjectManager::MetadataNodeKeys::CallSuper), True(isolate));
superValue->SetPrototype(context, thiz->GetPrototype().As<Object>()->GetPrototype().As<Object>()->GetPrototype());
V8SetPrivateValue(isolate, thiz, key, superValue);
objectManager->CloneLink(thiz, superValue);
DEBUG_WRITE("superValue.GetPrototype=%d", superValue->GetPrototype().As<Object>()->GetIdentityHash());
auto node = GetInstanceMetadata(isolate, thiz);
SetInstanceMetadata(isolate, superValue, node);
}
info.GetReturnValue().Set(superValue);
} catch (NativeScriptException& e) {
e.ReThrowToV8();
} catch (std::exception e) {
stringstream ss;
ss << "Error: c++ exception: " << e.what() << endl;
NativeScriptException nsEx(ss.str());
nsEx.ReThrowToV8();
} catch (...) {
NativeScriptException nsEx(std::string("Error: c++ exception!"));
nsEx.ReThrowToV8();
}
}
class MetadataNode::PrototypeTemplateFiller {
public:
explicit PrototypeTemplateFiller(Local<ObjectTemplate> protoTemplate)
: m_protoTemplate(protoTemplate) {}
void FillPrototypeMethod(Isolate *isolate, const std::string& name,
MethodCallbackData* methodInfo) {
if (m_addedNames.count(name) != 0) {
DEBUG_WRITE("Not defining method prototype.%s which has already been added", name.c_str());
return;
}
Local<External> funcData = External::New(isolate, methodInfo);
Local<FunctionTemplate> funcTemplate = FunctionTemplate::New(isolate, MetadataNode::MethodCallback, funcData);
Local<String> nameString = ArgConverter::ConvertToV8String(isolate, name);
m_protoTemplate->Set(nameString, funcTemplate);
m_addedNames.insert(name);
}
void FillPrototypeField(Isolate* isolate, const std::string& name, FieldCallbackData* fieldInfo,
AccessControl access = AccessControl::DEFAULT) {
if (m_addedNames.count(name) != 0) {
DEBUG_WRITE("Not defining field prototype.%s which already exists", name.c_str());
return;
}
Local<External> fieldData = External::New(isolate, fieldInfo);
Local<Name> nameString = ArgConverter::ConvertToV8String(isolate, name);
m_protoTemplate->SetAccessor(nameString, MetadataNode::FieldAccessorGetterCallback,
MetadataNode::FieldAccessorSetterCallback, fieldData, access,
PropertyAttribute::DontDelete);
m_addedNames.insert(name);
}
void FillPrototypeProperty(Isolate* isolate, const std::string& name,
PropertyCallbackData* propertyInfo) {
if (m_addedNames.count(name) != 0) {
DEBUG_WRITE("Not defining property prototype.%s which already exists", name.c_str());
return;
}
Local<External> propertyData = External::New(isolate, propertyInfo);
Local<Name> nameString = ArgConverter::ConvertToV8String(isolate, name);
m_protoTemplate->SetAccessor(nameString, MetadataNode::PropertyAccessorGetterCallback,
MetadataNode::PropertyAccessorSetterCallback, propertyData,
AccessControl::DEFAULT, PropertyAttribute::DontDelete);
m_addedNames.insert(name);
}
private:
Local<ObjectTemplate> m_protoTemplate;
std::unordered_set<std::string> m_addedNames;
};
std::vector<MetadataNode::MethodCallbackData*> MetadataNode::SetInstanceMembers(
Isolate* isolate, Local<FunctionTemplate>& ctorFuncTemplate,
PrototypeTemplateFiller& protoFiller,
vector<MethodCallbackData*>& instanceMethodsCallbackData,
const vector<MethodCallbackData*>& baseInstanceMethodsCallbackData,
MetadataTreeNode* treeNode, uint8_t* &curPtr) {
auto hasCustomMetadata = treeNode->metadata != nullptr;
if (hasCustomMetadata) {
return SetInstanceMembersFromRuntimeMetadata(
isolate, protoFiller, instanceMethodsCallbackData,
baseInstanceMethodsCallbackData, treeNode);
}
return SetInstanceMethodsFromStaticMetadata(
isolate, ctorFuncTemplate, protoFiller, instanceMethodsCallbackData,
baseInstanceMethodsCallbackData, treeNode, curPtr);
}
vector<MetadataNode::MethodCallbackData *> MetadataNode::SetInstanceMethodsFromStaticMetadata(
Isolate *isolate, Local<FunctionTemplate> &ctorFuncTemplate,
PrototypeTemplateFiller& protoFiller,
vector<MethodCallbackData *> &instanceMethodsCallbackData,
const vector<MethodCallbackData *> &baseInstanceMethodsCallbackData,
MetadataTreeNode *treeNode, uint8_t* &curPtr) {
SET_PROFILER_FRAME();
std::vector<MethodCallbackData *> instanceMethodData;
curPtr = s_metadataReader.GetValueData() + treeNode->offsetValue + 1;
auto nodeType = s_metadataReader.GetNodeType(treeNode);
auto curType = s_metadataReader.ReadTypeName(treeNode);
curPtr += sizeof(uint16_t /* baseClassId */);
if (s_metadataReader.IsNodeTypeInterface(nodeType)) {
curPtr += sizeof(uint8_t) + sizeof(uint32_t);
}
string lastMethodName;
MethodCallbackData *callbackData = nullptr;
auto context = isolate->GetCurrentContext();
robin_hood::unordered_map<std::string, MethodCallbackData *> collectedExtensionMethodDatas;
auto extensionFunctionsCount = *reinterpret_cast<uint16_t *>(curPtr);
curPtr += sizeof(uint16_t);
for (auto i = 0; i < extensionFunctionsCount; i++) {
auto entry = MetadataReader::ReadExtensionFunctionEntry(&curPtr);
auto &methodName = entry.getName();
if (methodName!= lastMethodName) {
//
callbackData = tryGetExtensionMethodCallbackData(collectedExtensionMethodDatas,
methodName);
if (callbackData == nullptr) {
callbackData = new MethodCallbackData(this);
protoFiller.FillPrototypeMethod(isolate, methodName, callbackData);
lastMethodName = methodName;
std::pair<std::string, MethodCallbackData *> p(methodName, callbackData);
collectedExtensionMethodDatas.emplace(p);
}
}
callbackData->candidates.push_back(std::move(entry));
}
//get candidates from instance methods metadata
auto instanceMethodCount = *reinterpret_cast<uint16_t *>(curPtr);
curPtr += sizeof(uint16_t);
for (auto i = 0; i < instanceMethodCount; i++) {
auto entry = MetadataReader::ReadInstanceMethodEntry(&curPtr);
// attach a function to the prototype of a javascript Object
auto &methodName = entry.getName();
if (methodName != lastMethodName) {
// See if we have tracked the callback data before (meaning another version of entry.name exists with different parameters)
callbackData = tryGetExtensionMethodCallbackData(collectedExtensionMethodDatas,
methodName);
if (callbackData == nullptr) {
callbackData = new MethodCallbackData(this);
// If we have no tracking of this callback data, create tracking so that we can find it if need be for future itterations where the entry.name is the same...
std::pair<std::string, MethodCallbackData *> p(methodName, callbackData);
collectedExtensionMethodDatas.emplace(p);
}
instanceMethodData.push_back(callbackData);
instanceMethodsCallbackData.push_back(callbackData);
auto itBegin = baseInstanceMethodsCallbackData.begin();
auto itEnd = baseInstanceMethodsCallbackData.end();
auto itFound = find_if(itBegin, itEnd, [&methodName](MethodCallbackData *x) {
return x->candidates.front().name == methodName;
});
if (itFound != itEnd) {
callbackData->parent = *itFound;
}
if (s_profilerEnabled) {
Local<External> funcData = External::New(isolate, callbackData);
Local<FunctionTemplate> funcTemplate = FunctionTemplate::New(isolate, MethodCallback, funcData);
auto func = funcTemplate->GetFunction(context).ToLocalChecked();
std::string origin = Constants::APP_ROOT_FOLDER_PATH + GetOrCreateInternal(treeNode)->m_name;
Local<Function> wrapperFunc = Wrap(isolate, func, methodName, origin,
false /* isCtorFunc */);
Local<Function> ctorFunc = ctorFuncTemplate->GetFunction(context).ToLocalChecked();
Local<Value> protoVal;
ctorFunc->Get(context,
ArgConverter::ConvertToV8String(isolate, "prototype")).ToLocal(
&protoVal);
Local<String> funcName = ArgConverter::ConvertToV8String(isolate, methodName);
if (!protoVal.IsEmpty() && !protoVal->IsUndefined() && !protoVal->IsNull()) {
protoVal.As<Object>()->Set(context, funcName, wrapperFunc);
}
} else {
protoFiller.FillPrototypeMethod(isolate, methodName, callbackData);
}
lastMethodName = methodName;
}
callbackData->candidates.push_back(std::move(entry));
}
//get candidates from instance fields metadata
auto instanceFieldCout = *reinterpret_cast<uint16_t*>(curPtr);
curPtr += sizeof(uint16_t);
for (auto i = 0; i < instanceFieldCout; i++) {
auto entry = MetadataReader::ReadInstanceFieldEntry(&curPtr);
auto fieldName = entry.getName();
auto fieldInfo = new FieldCallbackData(entry);
fieldInfo->metadata.declaringType = curType;
protoFiller.FillPrototypeField(isolate, fieldName, fieldInfo);
}
auto kotlinPropertiesCount = *reinterpret_cast<uint16_t*>(curPtr);
curPtr += sizeof(uint16_t);
for (int i = 0; i < kotlinPropertiesCount; ++i) {
uint32_t nameOffset = *reinterpret_cast<uint32_t*>(curPtr);
string propertyName = s_metadataReader.ReadName(nameOffset);
curPtr += sizeof(uint32_t);
auto hasGetter = *reinterpret_cast<uint16_t*>(curPtr);
curPtr += sizeof(uint16_t);
std::string getterMethodName = "";
if(hasGetter>=1){
auto entry = MetadataReader::ReadInstanceMethodEntry(&curPtr);
getterMethodName = entry.getName();
}
auto hasSetter = *reinterpret_cast<uint16_t*>(curPtr);
curPtr += sizeof(uint16_t);
std::string setterMethodName = "";
if(hasSetter >= 1){
auto entry = MetadataReader::ReadInstanceMethodEntry(&curPtr);
setterMethodName = entry.getName();
}
auto propertyInfo = new PropertyCallbackData(propertyName, getterMethodName, setterMethodName);
protoFiller.FillPrototypeProperty(isolate, propertyName, propertyInfo);
}
return instanceMethodData;
}
MetadataNode::MethodCallbackData *MetadataNode::tryGetExtensionMethodCallbackData(
const robin_hood::unordered_map<std::string, MethodCallbackData *> &collectedMethodCallbackDatas,
const std::string &lookupName) {
if (collectedMethodCallbackDatas.empty()) {
return nullptr;
}
auto iter = collectedMethodCallbackDatas.find(lookupName);
if (iter != collectedMethodCallbackDatas.end()) {
return iter->second;
}
return nullptr;
}
vector<MetadataNode::MethodCallbackData*> MetadataNode::SetInstanceMembersFromRuntimeMetadata(
Isolate* isolate, PrototypeTemplateFiller& protoFiller,
vector<MethodCallbackData*>& instanceMethodsCallbackData,
const vector<MethodCallbackData*>& baseInstanceMethodsCallbackData,
MetadataTreeNode* treeNode) {
SET_PROFILER_FRAME();
assert(treeNode->metadata != nullptr);
std::vector<MethodCallbackData*> instanceMethodData;
string line;
const string& metadata = *treeNode->metadata;
stringstream s(metadata);
string kind;
string name;
string signature;
int paramCount;
getline(s, line); // type line
getline(s, line); // base class line
string lastMethodName;
MethodCallbackData* callbackData = nullptr;
while (getline(s, line)) {
stringstream tmp(line);
tmp >> kind >> name >> signature >> paramCount;
char chKind = kind[0];
// method or field
assert((chKind == 'M') || (chKind == 'F'));
MetadataEntry entry(nullptr, NodeType::Field);
entry.name = name;
entry.sig = signature;
entry.paramCount = paramCount;
entry.isStatic = false;
if (chKind == 'M') {
if (entry.name != lastMethodName) {
callbackData = new MethodCallbackData(this);
instanceMethodData.push_back(callbackData);
instanceMethodsCallbackData.push_back(callbackData);
auto itBegin = baseInstanceMethodsCallbackData.begin();
auto itEnd = baseInstanceMethodsCallbackData.end();
auto itFound = find_if(itBegin, itEnd, [&entry] (MethodCallbackData *x) {
return x->candidates.front().name == entry.name;
});
if (itFound != itEnd) {
callbackData->parent = *itFound;
}
protoFiller.FillPrototypeMethod(isolate, entry.name, callbackData);
lastMethodName = entry.name;
}
callbackData->candidates.push_back(std::move(entry));
} else if (chKind == 'F') {
auto access = entry.isFinal ? AccessControl::ALL_CAN_READ : AccessControl::DEFAULT;
auto* fieldInfo = new FieldCallbackData(entry);
protoFiller.FillPrototypeField(isolate, entry.name, fieldInfo, access);
}
}
return instanceMethodData;
}
void MetadataNode::SetStaticMembers(Isolate* isolate, Local<Function>& ctorFunction, MetadataTreeNode* treeNode, uint8_t* &curPtr) {
auto hasCustomMetadata = treeNode->metadata != nullptr;
auto context = isolate->GetCurrentContext();
if (!hasCustomMetadata) {
string lastMethodName;
MethodCallbackData* callbackData = nullptr;
auto origin = Constants::APP_ROOT_FOLDER_PATH + GetOrCreateInternal(treeNode)->m_name;
//get candidates from static methods metadata
auto staticMethodCout = *reinterpret_cast<uint16_t*>(curPtr);
curPtr += sizeof(uint16_t);
for (auto i = 0; i < staticMethodCout; i++) {
auto entry = MetadataReader::ReadStaticMethodEntry(&curPtr);
auto &methodName = entry.getName();
if (methodName != lastMethodName) {
callbackData = new MethodCallbackData(this);
auto funcData = External::New(isolate, callbackData);
auto funcTemplate = FunctionTemplate::New(isolate, MethodCallback, funcData);
auto func = funcTemplate->GetFunction(context).ToLocalChecked();
auto funcName = ArgConverter::ConvertToV8String(isolate, methodName);
ctorFunction->Set(context, funcName, Wrap(isolate, func, methodName, origin, false /* isCtorFunc */));
lastMethodName = methodName;
}
callbackData->candidates.push_back(std::move(entry));
}
//attach .extend function
auto extendFuncName = V8StringConstants::GetExtend(isolate);
auto extendFuncTemplate = FunctionTemplate::New(isolate, ExtendMethodCallback, External::New(isolate, this));
ctorFunction->Set(context, extendFuncName, extendFuncTemplate->GetFunction(context).ToLocalChecked());
//get candidates from static fields metadata
auto staticFieldCout = *reinterpret_cast<uint16_t*>(curPtr);
curPtr += sizeof(uint16_t);
for (auto i = 0; i < staticFieldCout; i++) {
auto entry = MetadataReader::ReadStaticFieldEntry(&curPtr);
auto fieldName = ArgConverter::ConvertToV8String(isolate, entry.getName());
auto fieldData = External::New(isolate, new FieldCallbackData(entry));
ctorFunction->SetAccessor(context, fieldName, FieldAccessorGetterCallback, FieldAccessorSetterCallback, fieldData, AccessControl::DEFAULT, PropertyAttribute::DontDelete);
}
auto nullObjectName = V8StringConstants::GetNullObject(isolate);
Local<Value> nullObjectData = External::New(isolate, this);
ctorFunction->SetAccessor(context, nullObjectName, NullObjectAccessorGetterCallback, nullptr, nullObjectData);
SetClassAccessor(ctorFunction);
}
}
void MetadataNode::SetInnerTypes(v8::Isolate* isolate, Local<Function>& ctorFunction, MetadataTreeNode *treeNode) {
if (treeNode->children != nullptr) {
auto context = isolate->GetCurrentContext();
const auto &children = *treeNode->children;
for (auto curChild: children) {
ctorFunction->SetAccessor(
context,
v8::String::NewFromUtf8(isolate, curChild->name.c_str()).ToLocalChecked(),
InnerTypeAccessorGetterCallback, nullptr, v8::External::New(isolate, curChild)
);
}
}
}
void MetadataNode::InnerTypeAccessorGetterCallback(v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
v8::HandleScope handleScope(isolate);
MetadataTreeNode* curChild = static_cast<MetadataTreeNode*>(v8::External::Cast(*info.Data())->Value());
auto childNode = GetOrCreateInternal(curChild);
auto itFound = childNode->m_poCtorCachePerIsolate.find(isolate);
if (itFound != childNode->m_poCtorCachePerIsolate.end()) {
info.GetReturnValue().Set(itFound->second->Get(isolate));
return;
}
auto innerTypeCtorFuncTemplate= childNode->GetConstructorFunctionTemplate(isolate, curChild);
if(innerTypeCtorFuncTemplate.IsEmpty()) {
info.GetReturnValue().Set(v8::Undefined(isolate));
return;
}
auto innerTypeCtorFunc = Local<Function>::New(isolate, *GetOrCreateInternal(curChild)->GetPersistentConstructorFunction(isolate));
auto innerTypeName = ArgConverter::ConvertToV8String(isolate, curChild->name);
// TODO: remove this once we solve https://github.com/NativeScript/android/pull/1771
// this avoids a crash, but the companion object is still unaccessible
TryCatch tc(isolate);
info.GetReturnValue().Set(innerTypeCtorFunc);
}
Local<FunctionTemplate> MetadataNode::GetConstructorFunctionTemplate(Isolate* isolate, MetadataTreeNode* treeNode) {
std::vector<MethodCallbackData*> instanceMethodsCallbackData;
v8::HandleScope handleScope(isolate);
auto ft = GetConstructorFunctionTemplate(isolate, treeNode, instanceMethodsCallbackData);
return ft;
}
Local<FunctionTemplate> MetadataNode::GetConstructorFunctionTemplate(Isolate* isolate, MetadataTreeNode* treeNode, vector<MethodCallbackData*>& instanceMethodsCallbackData) {
SET_PROFILER_FRAME();
tns::instrumentation::Frame frame;
//try get cached "ctorFuncTemplate"
Local<FunctionTemplate> ctorFuncTemplate;
auto cache = GetMetadataNodeCache(isolate);
auto itFound = cache->CtorFuncCache.find(treeNode);
if (itFound != cache->CtorFuncCache.end()) {
auto& ctorCacheItem = itFound->second;
instanceMethodsCallbackData = ctorCacheItem.instanceMethodCallbacks;
ctorFuncTemplate = Local<FunctionTemplate>::New(isolate, *ctorCacheItem.ft);
return ctorFuncTemplate;
}
//
auto node = GetOrCreateInternal(treeNode);
JEnv env;
// if we already have an exception (which will be rethrown later)
// then we don't want to ignore the next exception
bool ignoreFindClassException = env.ExceptionCheck() == JNI_FALSE;
auto currentClass = env.FindClass(node->m_name);
if (ignoreFindClassException && env.ExceptionCheck()) {
env.ExceptionClear();
// JNI found an exception looking up this class
// but we don't care, because this means this class doesn't exist
// like when you try to get a class that only exists in a higher API level
ctorFuncTemplate.Clear();
auto pft = new Persistent<FunctionTemplate>(isolate, ctorFuncTemplate);
CtorCacheData ctorCacheItem(pft, instanceMethodsCallbackData);
cache->CtorFuncCache.emplace(treeNode, ctorCacheItem);
return ctorFuncTemplate;
}
auto ctorCallbackData = External::New(isolate, node);
auto isInterface = s_metadataReader.IsNodeTypeInterface(treeNode->type);
auto funcCallback = isInterface ? InterfaceConstructorCallback : ClassConstructorCallback;
ctorFuncTemplate = FunctionTemplate::New(isolate, funcCallback, ctorCallbackData);
auto currentNode = treeNode;
std::string finalName(currentNode->name);
while (currentNode->parent) {
if (!currentNode->parent->name.empty()) {
finalName = currentNode->parent->name + "." + finalName;
}
currentNode = currentNode->parent;
}
ctorFuncTemplate->SetClassName(v8::String::NewFromUtf8(isolate, finalName.c_str()).ToLocalChecked());
ctorFuncTemplate->InstanceTemplate()->SetInternalFieldCount(static_cast<int>(ObjectManager::MetadataNodeKeys::END));
Local<Function> baseCtorFunc;
std::vector<MethodCallbackData*> baseInstanceMethodsCallbackData;
auto tmpTreeNode = treeNode;
std::vector<MetadataTreeNode*> skippedBaseTypes;
while (true) {
auto baseTreeNode = s_metadataReader.GetBaseClassNode(tmpTreeNode);
if (CheckClassHierarchy(env, currentClass, treeNode, baseTreeNode, skippedBaseTypes)) {
tmpTreeNode = baseTreeNode;
continue;
}
if ((baseTreeNode != treeNode) && (baseTreeNode != nullptr) && (baseTreeNode->offsetValue > 0)) {
auto baseFuncTemplate = GetConstructorFunctionTemplate(isolate, baseTreeNode, baseInstanceMethodsCallbackData);
if (!baseFuncTemplate.IsEmpty()) {
ctorFuncTemplate->Inherit(baseFuncTemplate);
baseCtorFunc = Local<Function>::New(isolate, *GetOrCreateInternal(baseTreeNode)->GetPersistentConstructorFunction(isolate));
}
}
break;
}
PrototypeTemplateFiller protoFiller{ctorFuncTemplate->PrototypeTemplate()};
uint8_t* curPtr = nullptr;
auto instanceMethodData = node->SetInstanceMembers(
isolate, ctorFuncTemplate, protoFiller, instanceMethodsCallbackData,
baseInstanceMethodsCallbackData, treeNode, curPtr);
if (!skippedBaseTypes.empty()) {
node->SetMissingBaseMethods(isolate, skippedBaseTypes, instanceMethodData, protoFiller);
}
auto context = isolate->GetCurrentContext();
auto ctorFunc = ctorFuncTemplate->GetFunction(context).ToLocalChecked();
auto origin = Constants::APP_ROOT_FOLDER_PATH + node->m_name;
auto wrappedCtorFunc = Wrap(isolate, ctorFunc, node->m_treeNode->name, origin, true /* isCtorFunc */);
node->SetStaticMembers(isolate, wrappedCtorFunc, treeNode, curPtr);
// insert isolate-specific persistent function handle
node->m_poCtorCachePerIsolate.insert({isolate, new Persistent<Function>(isolate, wrappedCtorFunc)});
if (!baseCtorFunc.IsEmpty()) {
auto currentContext = isolate->GetCurrentContext();