Repository navigation
Expand file tree
/
Copy pathInterop.mm
More file actions
2107 lines (1866 loc) · 88.1 KB
/
Copy pathInterop.mm
File metadata and controls
2107 lines (1866 loc) · 88.1 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
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 "Interop.h"
#include <Foundation/Foundation.h>
#include <sstream>
#include "ArgConverter.h"
#include "ArrayAdapter.h"
#include "Caches.h"
#include "Constants.h"
#include "DictionaryAdapter.h"
#include "ExtVector.h"
#include "ExternalMemory.h"
#include "Helpers.h"
#include "NSDataAdapter.h"
#include "NativeScriptException.h"
#include "ObjectManager.h"
#include "OneByteStringResource.h"
#include "Pointer.h"
#include "Reference.h"
#include "Runtime.h"
#include "RuntimeConfig.h"
#include "SymbolLoader.h"
#include "UnmanagedType.h"
#include "WrapperLifetime.h"
#include "robin_hood.h"
using namespace v8;
namespace tns {
static constexpr uint64_t kUint64AllBitsSet = static_cast<uint64_t>(int64_t{-1});
static constexpr int64_t kMinSafeInteger =
static_cast<int64_t>(kUint64AllBitsSet << 53) + 1; // -9007199254740991 (-(2^53-1))
static constexpr int64_t kMaxSafeInteger = -kMinSafeInteger; // 9007199254740991 (2^53-1)
Interop::JSBlock::JSBlockDescriptor Interop::JSBlock::kJSBlockDescriptor = {
.reserved = 0,
.size = sizeof(JSBlock),
.copy = [](JSBlock* dst, const JSBlock* src) {},
.dispose =
[](JSBlock* block) {
if (block->descriptor == &JSBlock::kJSBlockDescriptor) {
MethodCallbackWrapper* wrapper = static_cast<MethodCallbackWrapper*>(block->userData);
BlockWrapper* blockWrapper = block->blockWrapper;
// Runs on whatever thread drops the last native reference. That is
// safe inline: callback_ is a strong, unregistered persistent, so
// resetting it never touches the finalizer drain's bookkeeping,
// and a foreign-thread Locker into the block's own isolate is
// legitimate now that extended class names are worker-scoped.
// A thread holding another isolate's Locker is the exception: it
// gets here when that isolate was handed this block, and it
// deadlocks if this isolate is waiting for that Locker in turn.
// Blocks shared between isolates carry that risk.
//
// The teardown flag is not the test here: the slot stays reachable
// once teardown has begun, by JS still running under the Locker
// and by the teardown's own walk of registered objects. Until the
// gate closes, the wrapper is only freed once the slot is cleared.
{
IsolatePin pin = wrapper->isolateWrapper_.Pin();
if (pin) {
Isolate* isolate = wrapper->isolateWrapper_.Isolate();
v8::Locker locker(isolate);
if (!wrapper->isolateWrapper_.IsTornDown()) {
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<Value> callback = wrapper->callback_->Get(isolate);
if (!callback.IsEmpty() && callback->IsObject()) {
// The slot may hold another wrapper by now; only our own is
// cleared from it.
if (tns::GetValue(isolate, callback) == blockWrapper) {
tns::DeleteValue(isolate, callback);
}
}
// Unconditional: an already-detached callback still owns its
// node, and dropping the persistent without a reset would leave
// that node rooted forever.
wrapper->callback_->Reset();
}
}
}
// Outside the gate: once the teardown is done the cache slot is
// unreachable and nothing else can free the wrapper.
delete blockWrapper;
delete wrapper;
ffi_closure_free(block->ffiClosure);
block->~JSBlock();
}
}};
// libclosure's flags layout (Block_private.h): bit 0 is set once the last
// release has started disposing the block, bits 1-15 hold the refcount, and a
// saturated refcount latches the block alive.
static constexpr int32_t kBlockDeallocating = 0x0001;
static constexpr int32_t kBlockRefcountMask = 0xfffe;
bool Interop::IsJSBlock(const void* block) {
return static_cast<const JSBlock*>(block)->descriptor == &JSBlock::kJSBlockDescriptor;
}
Local<Value> Interop::JSBlockCallback(Isolate* isolate, const void* block) {
const JSBlock* jsBlock = static_cast<const JSBlock*>(block);
// Dispose frees the callback wrapper after it releases the Locker, so only
// a block not yet disposing is read; one that starts disposing now waits
// for the caller's Locker before it touches the wrapper.
if (!IsJSBlock(block) ||
(__atomic_load_n(&jsBlock->flags, __ATOMIC_ACQUIRE) & kBlockDeallocating) != 0) {
return Local<Value>();
}
MethodCallbackWrapper* wrapper = static_cast<MethodCallbackWrapper*>(jsBlock->userData);
if (wrapper == nullptr || wrapper->isolateWrapper_.Isolate() != isolate ||
wrapper->callback_ == nullptr || wrapper->callback_->IsEmpty()) {
return Local<Value>();
}
return wrapper->callback_->Get(isolate);
}
// libclosure's increment ignores the deallocating bit, so Block_copy would hand
// out a block whose dispose is already waiting for the isolate's Locker and
// which libclosure frees right after. This CASes the same word libclosure does.
bool Interop::TryRetainJSBlock(JSBlock* block) {
volatile int32_t* flags = &block->flags;
int32_t old = __atomic_load_n(flags, __ATOMIC_RELAXED);
while (true) {
if ((old & kBlockDeallocating) || (old & kBlockRefcountMask) == 0) {
return false;
}
if ((old & kBlockRefcountMask) == kBlockRefcountMask) {
return true;
}
if (__atomic_compare_exchange_n(flags, &old, old + 2, true, __ATOMIC_ACQ_REL,
__ATOMIC_RELAXED)) {
return true;
}
}
}
std::pair<IMP, ffi_closure*> Interop::CreateMethodInternal(const uint8_t initialParamIndex,
const uint8_t argsCount,
const TypeEncoding* typeEncoding,
FFIMethodCallback callback,
void* userData) {
void* functionPointer;
ffi_closure* closure =
static_cast<ffi_closure*>(ffi_closure_alloc(sizeof(ffi_closure), &functionPointer));
ParametrizedCall* call =
ParametrizedCall::Get(typeEncoding, initialParamIndex, initialParamIndex + argsCount);
ffi_status status = ffi_prep_closure_loc(closure, call->Cif, callback, userData, functionPointer);
tns::Assert(status == FFI_OK);
return std::make_pair((IMP)functionPointer, closure);
}
IMP Interop::CreateMethod(const uint8_t initialParamIndex, const uint8_t argsCount,
const TypeEncoding* typeEncoding, FFIMethodCallback callback,
void* userData) {
std::pair<IMP, ffi_closure*> result =
Interop::CreateMethodInternal(initialParamIndex, argsCount, typeEncoding, callback, userData);
return result.first;
}
CFTypeRef Interop::CreateBlock(const uint8_t initialParamIndex, const uint8_t argsCount,
const TypeEncoding* typeEncoding, FFIMethodCallback callback,
void* userData) {
JSBlock* blockPointer = reinterpret_cast<JSBlock*>(malloc(sizeof(JSBlock)));
std::pair<IMP, ffi_closure*> result =
Interop::CreateMethodInternal(initialParamIndex, argsCount, typeEncoding, callback, userData);
*blockPointer = {
.isa = nullptr,
// this block is created with a refcount of 1
// this means we "own" it and need to free it
.flags =
JSBlock::BLOCK_HAS_COPY_DISPOSE | JSBlock::BLOCK_NEEDS_FREE | (1 /* ref count */ << 1),
.reserved = 0,
.invoke = (void*)result.first,
.descriptor = &JSBlock::kJSBlockDescriptor,
.userData = userData,
.ffiClosure = result.second,
.blockWrapper = nullptr,
};
object_setClass((__bridge id)blockPointer, objc_getClass("__NSMallocBlock__"));
// transfer ownership back to ARC (see refcount comment above)
return CFBridgingRelease(blockPointer);
}
Local<Value> Interop::CallFunction(CMethodCall& methodCall) {
return Interop::CallFunctionInternal(methodCall);
}
Local<Value> Interop::CallFunction(ObjCMethodCall& methodCall) {
return Interop::CallFunctionInternal(methodCall);
}
bool Interop::ConsumesReceiver(SEL selector, bool isInitializer) {
return isInitializer || selector == @selector(awakeAfterUsingCoder:);
}
// -[NSKeyedUnarchiverDelegate unarchiver:didDecodeObject:] is the only SDK
// method with an NS_RELEASES_ARGUMENT parameter; it also returns retained.
static int ConsumedArgumentIndex(SEL selector) {
return selector == @selector(unarchiver:didDecodeObject:) ? 1 : -1;
}
bool Interop::ConsumesArgument(SEL selector, int index) {
return index >= 0 && index == ConsumedArgumentIndex(selector);
}
int Interop::ConsumedObjectArgumentIndex(SEL selector, const TypeEncoding* typeEncoding,
int paramsCount) {
int index = ConsumedArgumentIndex(selector);
if (index < 0 || index >= paramsCount) {
return -1;
}
for (int i = 0; i <= index; i++) {
typeEncoding = typeEncoding->next();
}
return IsObjectEncoding(typeEncoding) ? index : -1;
}
bool Interop::IsObjectEncoding(const TypeEncoding* typeEncoding) {
BinaryTypeEncodingType type = typeEncoding->type;
return type == BinaryTypeEncodingType::IdEncoding ||
type == BinaryTypeEncodingType::InterfaceDeclarationReference ||
type == BinaryTypeEncodingType::InstanceTypeEncoding;
}
bool Interop::ReturnsRetained(SEL selector) { return ConsumesArgument(selector, 1); }
// Balanced only while every owned result other than a consumed receiver
// reaches here at +1, JS-implemented methods included: MethodCallback retains
// what a JS implementation answers at +0, and for initializers anything but
// the receiver. AllocatedForCall does not check that the result is the
// receiver, so narrowing that retain makes this over-release.
bool Interop::ReleasesCachedOwnedReturn(bool ownsReturnedObject, OwnedReturnReceiver receiver) {
return ownsReturnedObject && receiver != OwnedReturnReceiver::Consumed;
}
id Interop::CallInitializer(Local<Context> context, const MethodMeta* methodMeta, id target,
Class clazz, V8Args& args) {
const TypeEncoding* typeEncoding = methodMeta->encodings()->first();
SEL selector = methodMeta->selector();
void* functionPointer = (void*)objc_msgSend;
int initialParameterIndex = 2;
int argsCount = initialParameterIndex + (int)args.Length();
ParametrizedCall* parametrizedCall =
ParametrizedCall::Get(typeEncoding, initialParameterIndex, argsCount);
FFICall call(parametrizedCall);
Interop::SetValue(call.ArgumentBuffer(0), target);
Interop::SetValue(call.ArgumentBuffer(1), selector);
try {
Interop::SetFFIParams(context, typeEncoding, &call, argsCount, initialParameterIndex, args);
} catch (...) {
// `target` was allocated for this initializer, which would have consumed it.
[target release];
throw;
}
ffi_call(parametrizedCall->Cif, FFI_FN(functionPointer), call.ResultBuffer(), call.ArgsArray());
id result = call.GetResult<id>();
return result;
}
void Interop::SetFFIParams(Local<Context> context, const TypeEncoding* typeEncoding, FFICall* call,
const int argsCount, const int initialParameterIndex, V8Args& args) {
const TypeEncoding* enc = typeEncoding;
for (int i = initialParameterIndex; i < argsCount; i++) {
enc = enc->next();
Local<Value> arg = args[i - initialParameterIndex];
void* argBuffer = call->ArgumentBuffer(i);
Interop::WriteValue(context, enc, argBuffer, arg);
}
}
bool Interop::isRefTypeEqual(const TypeEncoding* typeEncoding, const char* clazz) {
std::string n(&typeEncoding->details.interfaceDeclarationReference.name.value());
return n.compare(clazz) == 0;
}
// this is experimental. Maybe we can have something like this to wrap all Local<Value> to avoid
// extra v8 calls
class ValueCache {
public:
enum IsOfType { UNDEFINED, TYPES_YES, TYPE_NO };
inline bool isObject() {
if (this->_isObject == UNDEFINED) {
this->_isObject = this->_arg->IsObject() ? TYPES_YES : TYPE_NO;
}
return this->_isObject == TYPES_YES;
}
inline bool isString() {
if (this->_isString == UNDEFINED) {
this->_isString = tns::IsString(this->_arg) ? TYPES_YES : TYPE_NO;
}
return this->_isString == TYPES_YES;
}
inline bool isBool() {
if (this->_isBool == UNDEFINED) {
this->_isBool = tns::IsBool(this->_arg) ? TYPES_YES : TYPE_NO;
}
return this->_isBool == TYPES_YES;
}
ValueCache(Local<Value>& arg)
: _arg(arg) {
};
private:
Local<Value>& _arg;
IsOfType _isString = UNDEFINED;
IsOfType _isBool = UNDEFINED;
IsOfType _isObject = UNDEFINED;
};
// Array.prototype.slice over `object`, so a Proxy's length and element reads
// go through its traps. False when a read throws (the exception is left
// pending) or the result is not an Array.
static bool SnapshotArrayLike(Isolate* isolate, Local<Object> object, Local<v8::Array>& result) {
Local<v8::Function> sliceFunc;
auto cache = Caches::Get(isolate);
Persistent<v8::Function>* poSliceFunc = cache->SliceFunc.get();
if (poSliceFunc != nullptr) {
sliceFunc = poSliceFunc->Get(isolate);
} else {
std::string source = "Array.prototype.slice";
Local<Context> context = isolate->GetCurrentContext();
Local<Script> script;
if (!Script::Compile(context, tns::ToV8String(isolate, source)).ToLocal(&script)) {
tns::Assert(false, isolate);
}
tns::Assert(!script.IsEmpty(), isolate);
Local<Value> tempSliceFunc;
if (!script->Run(context).ToLocal(&tempSliceFunc)) {
tns::Assert(false, isolate);
}
tns::Assert(tempSliceFunc->IsFunction(), isolate);
sliceFunc = tempSliceFunc.As<v8::Function>();
cache->SliceFunc = std::make_unique<Persistent<v8::Function>>(isolate, sliceFunc);
}
Local<Context> context = tns::GetCreationContextOrCurrent(isolate, object);
Local<Value> value;
if (!sliceFunc->Call(context, object, 0, nullptr).ToLocal(&value) || !value->IsArray()) {
return false;
}
result = value.As<v8::Array>();
return true;
}
void Interop::WriteTypeValue(Local<Context> context, BaseDataWrapper* typeWrapper, void* dest,
Local<Value> arg) {
Isolate* isolate = v8::Isolate::GetCurrent();
Local<Value> original = arg;
arg = tns::UnwrapProxyOrThrow(isolate, arg);
ValueCache argHelper(arg);
bool isEmptyOrUndefined = arg.IsEmpty() || arg->IsNullOrUndefined();
bool success = false;
if (typeWrapper->Type() == WrapperType::StructType) {
if (isEmptyOrUndefined) {
StructTypeWrapper* structTypeWrapper = static_cast<StructTypeWrapper*>(typeWrapper);
const StructInfo& structInfo = structTypeWrapper->StructInfo();
memset(dest, 0, structInfo.FFIType()->size);
success = true;
} else if (argHelper.isObject()) {
BaseDataWrapper* wrapper = tns::GetValue(isolate, arg);
if (wrapper != nullptr) {
if (wrapper->Type() == WrapperType::Struct) {
StructWrapper* structWrapper = static_cast<StructWrapper*>(wrapper);
void* buffer = structWrapper->Data();
size_t size = structWrapper->StructInfo().FFIType()->size;
memcpy(dest, buffer, size);
success = true;
}
} else {
// Create the structure using the struct initializer syntax
StructTypeWrapper* structTypeWrapper = static_cast<StructTypeWrapper*>(typeWrapper);
const StructInfo& structInfo = structTypeWrapper->StructInfo();
Interop::InitializeStruct(context, dest, structInfo.Fields(),
tns::ProxyReadSource(original, arg));
success = true;
}
}
}
if (!success) {
tns::Assert(false, isolate);
}
}
void Interop::WriteValue(Local<Context> context, const TypeEncoding* typeEncoding, void* dest,
Local<Value> arg) {
Isolate* isolate = v8::Isolate::GetCurrent();
// Classification and native-wrapper lookups use the Proxy target, whose type
// and internal fields a Proxy hides; JS-backed reads go through `source`.
Local<Value> original = arg;
arg = tns::UnwrapProxyOrThrow(isolate, arg);
Local<Value> source = tns::ProxyReadSource(original, arg);
ValueCache argHelper(arg);
if (arg.IsEmpty() || arg->IsNullOrUndefined()) {
ffi_type* ffiType = FFICall::GetArgumentType(typeEncoding, true);
size_t size = ffiType->size;
FFICall::DisposeFFIType(ffiType, typeEncoding);
memset(dest, 0, size);
} else if (argHelper.isBool()) {
if (typeEncoding->type == BinaryTypeEncodingType::InterfaceDeclarationReference &&
isRefTypeEqual(typeEncoding, "NSNumber")) {
bool value = tns::ToBool(arg);
NSNumber* num = [NSNumber numberWithBool:value];
Interop::SetValue(dest, num);
} else if (typeEncoding->type == BinaryTypeEncodingType::IdEncoding) {
bool value = tns::ToBool(arg);
NSObject* o = @(value);
Interop::SetValue(dest, o);
} else {
bool value = tns::ToBool(arg);
Interop::SetValue(dest, value);
}
} else if (argHelper.isString() &&
typeEncoding->type == BinaryTypeEncodingType::SelectorEncoding) {
std::string str = tns::ToString(isolate, arg);
Interop::SetValue(dest, sel_registerName(str.c_str()));
} else if (typeEncoding->type == BinaryTypeEncodingType::CStringEncoding) {
if (arg->IsString()) {
// Always copy: an external one-byte string's resource (e.g. one made by
// node_api_create_external_string_latin1) holds Latin-1 with no NUL
// terminator, so its data can't be handed to native code as a C string.
OneByteStringResource* resource =
OneByteStringResource::NewUtf8Copy(isolate, arg.As<v8::String>());
// The external string only ties the copy's lifetime to the GC; it is
// never read as a string.
bool success = v8::String::NewExternalOneByte(isolate, resource).ToLocal(&arg);
tns::Assert(success, isolate);
Interop::SetValue(dest, resource->data());
} else {
BaseDataWrapper* wrapper = tns::GetValue(isolate, arg);
if (wrapper == nullptr) {
bool isArrayBuffer = false;
void* data = tns::TryGetBufferFromArrayBuffer(arg, isArrayBuffer);
if (isArrayBuffer) {
Interop::SetValue(dest, data);
return;
}
}
tns::Assert(wrapper != nullptr, isolate);
if (wrapper->Type() == WrapperType::Pointer) {
PointerWrapper* pw = static_cast<PointerWrapper*>(wrapper);
void* data = pw->Data();
Interop::SetValue(dest, data);
} else if (wrapper->Type() == WrapperType::Reference) {
ReferenceWrapper* refWrapper = static_cast<ReferenceWrapper*>(wrapper);
tns::Assert(refWrapper->Value() != nullptr, isolate);
Local<Value> value = refWrapper->Value()->Get(isolate);
wrapper = tns::GetValue(isolate, value);
tns::Assert(wrapper != nullptr && wrapper->Type() == WrapperType::Pointer, isolate);
PointerWrapper* pw = static_cast<PointerWrapper*>(wrapper);
void* data = pw->Data();
Interop::SetValue(dest, data);
} else {
// Unsupported wrapprt type for CString
tns::Assert(false, isolate);
}
}
} else if (argHelper.isString() &&
typeEncoding->type == BinaryTypeEncodingType::UnicharEncoding) {
Local<v8::String> str;
uint32_t length = 0;
unichar c = 0;
if (tns::ToStringLocal(isolate, arg, str)) {
// Scoped so the view's no-GC window closes before anything can throw.
v8::String::ValueView view(isolate, str);
length = view.length();
if (length == 1) {
c = view.is_one_byte() ? view.data8()[0] : view.data16()[0];
}
}
if (length > 1) {
throw NativeScriptException("Only one character string can be converted to unichar.");
}
Interop::SetValue(dest, c);
} else if (argHelper.isString() &&
(typeEncoding->type == BinaryTypeEncodingType::InterfaceDeclarationReference ||
typeEncoding->type == BinaryTypeEncodingType::IdEncoding)) {
NSString* result = tns::ToNSString(isolate, arg);
Interop::SetValue(dest, result);
} else if (Interop::IsNumbericType(typeEncoding->type) || tns::IsNumber(arg)) {
double value = tns::ToNumber(isolate, arg);
if (typeEncoding->type == BinaryTypeEncodingType::InterfaceDeclarationReference ||
typeEncoding->type == BinaryTypeEncodingType::IdEncoding) {
// NSNumber
NSNumber* num = [NSNumber numberWithDouble:value];
Interop::SetValue(dest, num);
} else if (typeEncoding->type == BinaryTypeEncodingType::UShortEncoding) {
Interop::SetNumericValue<unsigned short>(dest, value);
} else if (typeEncoding->type == BinaryTypeEncodingType::ShortEncoding) {
Interop::SetNumericValue<short>(dest, value);
} else if (typeEncoding->type == BinaryTypeEncodingType::UIntEncoding) {
Interop::SetNumericValue<unsigned int>(dest, value);
} else if (typeEncoding->type == BinaryTypeEncodingType::IntEncoding) {
Interop::SetNumericValue<int>(dest, value);
} else if (typeEncoding->type == BinaryTypeEncodingType::ULongEncoding) {
Interop::SetNumericValue<unsigned long>(dest, value);
} else if (typeEncoding->type == BinaryTypeEncodingType::LongEncoding) {
Interop::SetNumericValue<long>(dest, value);
} else if (typeEncoding->type == BinaryTypeEncodingType::ULongLongEncoding) {
Interop::SetNumericValue<unsigned long long>(dest, value);
} else if (typeEncoding->type == BinaryTypeEncodingType::LongLongEncoding) {
Interop::SetNumericValue<long long>(dest, value);
} else if (typeEncoding->type == BinaryTypeEncodingType::FloatEncoding) {
Interop::SetNumericValue<float>(dest, value);
} else if (typeEncoding->type == BinaryTypeEncodingType::DoubleEncoding) {
Interop::SetNumericValue<double>(dest, value);
} else if (typeEncoding->type == BinaryTypeEncodingType::UCharEncoding) {
Interop::SetNumericValue<unsigned char>(dest, value);
} else if (typeEncoding->type == BinaryTypeEncodingType::CharEncoding) {
Interop::SetNumericValue<char>(dest, value);
} else {
tns::Assert(false, isolate);
}
} else if (typeEncoding->type == BinaryTypeEncodingType::ExtVectorEncoding) {
BaseDataWrapper* wrapper = tns::GetValue(isolate, arg);
tns::Assert(wrapper != nullptr && wrapper->Type() == WrapperType::ExtVector, isolate);
ExtVectorWrapper* extVectorWrapper = static_cast<ExtVectorWrapper*>(wrapper);
void* data = extVectorWrapper->Data();
size_t size = extVectorWrapper->FFIType()->size;
memcpy(dest, data, size);
} else if (typeEncoding->type == BinaryTypeEncodingType::PointerEncoding) {
const TypeEncoding* innerType = typeEncoding->details.pointer.getInnerType();
BaseDataWrapper* wrapper = tns::GetValue(isolate, arg);
if (innerType->type == BinaryTypeEncodingType::VoidEncoding) {
bool isArrayBuffer = false;
void* buffer = tns::TryGetBufferFromArrayBuffer(arg, isArrayBuffer);
if (isArrayBuffer) {
Interop::SetValue(dest, buffer);
return;
}
tns::Assert(wrapper != nullptr, isolate);
if (wrapper->Type() == WrapperType::Pointer) {
PointerWrapper* pointerWrapper = static_cast<PointerWrapper*>(wrapper);
void* data = pointerWrapper->Data();
Interop::SetValue(dest, data);
} else if (wrapper->Type() == WrapperType::Reference) {
void* data = Reference::GetWrappedPointer(context, arg, typeEncoding);
Interop::SetValue(dest, data);
} else {
// TODO:
tns::Assert(false, isolate);
}
} else {
void* data = nullptr;
if (wrapper == nullptr &&
innerType->type == BinaryTypeEncodingType::StructDeclarationReference) {
const Meta* meta =
ArgConverter::GetMeta(innerType->details.declarationReference.name.valuePtr());
tns::Assert(meta != nullptr && meta->type() == MetaType::Struct, isolate);
const StructMeta* structMeta = static_cast<const StructMeta*>(meta);
const StructInfo& structInfo = FFICall::GetStructInfo(structMeta);
// TODO: How to free this?
// this is used when you have js obj and wants to pass the data as a struct ponter
// (MyStruct*) we create a new MyStruct with a snapshot of the jsObject and pass that in but
// when should we delete it? currently it's up to the function called to delete it we could
// delete after the function call, but if the fuction stores that then it's a memory leak we
// could also just store it as a wrapper in the object, binding it to the object lifecycle
// but that also means refactoring a lot of "if(wrapper == nullptr)" because essentially the
// wrapper should be treated as a nullptr, except when deating with
// StructDeclarationReference
data = malloc(structInfo.FFIType()->size);
Interop::InitializeStruct(context, data, structInfo.Fields(), source);
} else {
if (wrapper == nullptr) {
bool isArrayBuffer = false;
void* data = tns::TryGetBufferFromArrayBuffer(arg, isArrayBuffer);
if (isArrayBuffer) {
Interop::SetValue(dest, data);
return;
}
}
tns::Assert(wrapper != nullptr, isolate);
if (wrapper->Type() == WrapperType::Pointer) {
PointerWrapper* pointerWrapper = static_cast<PointerWrapper*>(wrapper);
data = pointerWrapper->Data();
} else if (wrapper->Type() == WrapperType::Reference) {
ReferenceWrapper* referenceWrapper = static_cast<ReferenceWrapper*>(wrapper);
Local<Value> value = referenceWrapper->Value() != nullptr
? referenceWrapper->Value()->Get(isolate)
: Local<Value>();
ffi_type* ffiType = FFICall::GetArgumentType(innerType);
data = calloc(1, ffiType->size);
FFICall::DisposeFFIType(ffiType, innerType);
referenceWrapper->SetData(data, true);
referenceWrapper->SetEncoding(innerType);
// Initialize the ref/out parameter value before passing it to the function call
if (!value.IsEmpty()) {
Interop::WriteValue(context, innerType, data, value);
}
} else if (wrapper->Type() == WrapperType::Struct) {
StructWrapper* structWrapper = static_cast<StructWrapper*>(wrapper);
data = structWrapper->Data();
} else {
tns::Assert(false, isolate);
}
}
Interop::SetValue(dest, data);
}
} else if (argHelper.isObject() &&
typeEncoding->type == BinaryTypeEncodingType::FunctionPointerEncoding) {
BaseDataWrapper* wrapper = tns::GetValue(isolate, arg.As<Object>());
tns::Assert(wrapper != nullptr, isolate);
if (wrapper->Type() == WrapperType::Pointer) {
PointerWrapper* pointerWrapper = static_cast<PointerWrapper*>(wrapper);
void* data = pointerWrapper->Data();
Interop::SetValue(dest, data);
} else if (wrapper->Type() == WrapperType::AnonymousFunction) {
AnonymousFunctionWrapper* functionWrapper = static_cast<AnonymousFunctionWrapper*>(wrapper);
void* data = functionWrapper->Data();
Interop::SetValue(dest, data);
} else if (wrapper->Type() == WrapperType::FunctionReference) {
tns::Assert(wrapper != nullptr && wrapper->Type() == WrapperType::FunctionReference, isolate);
FunctionReferenceWrapper* funcWrapper = static_cast<FunctionReferenceWrapper*>(wrapper);
const TypeEncoding* functionTypeEncoding =
typeEncoding->details.functionPointer.signature.first();
int argsCount = typeEncoding->details.functionPointer.signature.count - 1;
// A trampoline handed to native code (directly or through
// interop.handleof) has no ownership protocol and can never be freed, so
// build at most one per reference and signature instead of one per write.
void* functionPointer =
funcWrapper->Encoding() == functionTypeEncoding ? funcWrapper->Data() : nullptr;
if (functionPointer == nullptr) {
Local<Value> callbackValue = funcWrapper->Function()->Get(isolate);
tns::Assert(callbackValue->IsFunction(), isolate);
Local<v8::Function> callback = callbackValue.As<v8::Function>();
std::shared_ptr<Persistent<Value>> poCallback =
std::make_shared<Persistent<Value>>(isolate, callback);
MethodCallbackWrapper* userData =
new MethodCallbackWrapper(isolate, poCallback, 0, argsCount, functionTypeEncoding);
functionPointer = (void*)Interop::CreateMethod(0, argsCount, functionTypeEncoding,
ArgConverter::MethodCallback, userData);
funcWrapper->SetData(functionPointer, functionTypeEncoding);
}
Interop::SetValue(dest, functionPointer);
} else {
tns::Assert(false, isolate);
}
} else if (arg->IsFunction() && typeEncoding->type == BinaryTypeEncodingType::BlockEncoding) {
const TypeEncoding* blockTypeEncoding = typeEncoding->details.block.signature.first();
int argsCount = typeEncoding->details.block.signature.count - 1;
CFTypeRef blockPtr = nullptr;
BaseDataWrapper* baseWrapper = tns::GetValue(isolate, arg);
if (baseWrapper != nullptr && baseWrapper->Type() == WrapperType::Block) {
BlockWrapper* wrapper = static_cast<BlockWrapper*>(baseWrapper);
// The callee takes the block at +0 and copies it if it needs to keep it,
// so the reference that keeps it alive across the call must be balanced:
// the JSBlock dispose helper owns the ffi closure and the callback wrapper
// and only runs once the last reference goes away.
if (wrapper->OwnsBlock()) {
// A native block, or another isolate's JS block; the wrapper's own
// Block_copy keeps it alive.
blockPtr = CFAutorelease(Block_copy(wrapper->Block()));
} else if (TryRetainJSBlock(static_cast<JSBlock*>(wrapper->Block()))) {
// Reading the block is safe even when its last release raced ahead:
// until the isolate's teardown closes its gate, dispose clears this
// slot under the Locker this thread holds, before libclosure frees
// the block.
blockPtr = CFAutorelease(wrapper->Block());
}
}
if (blockPtr == nullptr) {
std::shared_ptr<Persistent<Value>> poCallback =
std::make_shared<Persistent<Value>>(isolate, arg);
MethodCallbackWrapper* userData =
new MethodCallbackWrapper(isolate, poCallback, 1, argsCount, blockTypeEncoding);
blockPtr = Interop::CreateBlock(1, argsCount, blockTypeEncoding, ArgConverter::MethodCallback,
userData);
BlockWrapper* wrapper = new BlockWrapper((void*)blockPtr, blockTypeEncoding, false);
reinterpret_cast<JSBlock*>((void*)blockPtr)->blockWrapper = wrapper;
tns::SetValue(isolate, arg.As<v8::Function>(), wrapper);
}
Interop::SetValue(dest, blockPtr);
} else if (argHelper.isObject() &&
typeEncoding->type == BinaryTypeEncodingType::StructDeclarationReference) {
BaseDataWrapper* wrapper = tns::GetValue(isolate, arg);
if (wrapper != nullptr) {
if (wrapper->Type() == WrapperType::Struct) {
StructWrapper* structWrapper = static_cast<StructWrapper*>(wrapper);
void* buffer = structWrapper->Data();
size_t size = structWrapper->StructInfo().FFIType()->size;
memcpy(dest, buffer, size);
} else if (wrapper->Type() == WrapperType::Reference) {
void* data = Reference::GetWrappedPointer(context, arg, typeEncoding);
tns::Assert(data != nullptr, isolate);
ffi_type* ffiType = FFICall::GetArgumentType(typeEncoding);
size_t size = ffiType->size;
FFICall::DisposeFFIType(ffiType, typeEncoding);
memcpy(dest, data, size);
} else {
tns::Assert(false, isolate);
}
} else {
// Create the structure using the struct initializer syntax
const char* structName = typeEncoding->details.declarationReference.name.valuePtr();
const Meta* meta = ArgConverter::GetMeta(structName);
tns::Assert(meta != nullptr && meta->type() == MetaType::Struct, isolate);
const StructMeta* structMeta = static_cast<const StructMeta*>(meta);
const StructInfo& structInfo = FFICall::GetStructInfo(structMeta);
Interop::InitializeStruct(context, dest, structInfo.Fields(), source);
}
} else if (argHelper.isObject() &&
typeEncoding->type == BinaryTypeEncodingType::AnonymousStructEncoding) {
BaseDataWrapper* wrapper = tns::GetValue(isolate, arg);
if (wrapper != nullptr && wrapper->Type() == WrapperType::Struct) {
size_t fieldsCount = typeEncoding->details.anonymousRecord.fieldsCount;
const TypeEncoding* fieldEncoding =
typeEncoding->details.anonymousRecord.getFieldsEncodings();
const String* fieldNames = typeEncoding->details.anonymousRecord.getFieldNames();
const StructInfo& structInfo = FFICall::GetStructInfo(fieldsCount, fieldEncoding, fieldNames);
StructWrapper* structWrapper = static_cast<StructWrapper*>(wrapper);
void* data = structWrapper->Data();
size_t size = structInfo.FFIType()->size;
memcpy(dest, data, size);
} else {
// Anonymous structs can only be initialized with plain javascript objects
tns::Assert(wrapper == nullptr, isolate);
size_t fieldsCount = typeEncoding->details.anonymousRecord.fieldsCount;
const TypeEncoding* fieldEncoding =
typeEncoding->details.anonymousRecord.getFieldsEncodings();
const String* fieldNames = typeEncoding->details.anonymousRecord.getFieldNames();
const StructInfo& structInfo = FFICall::GetStructInfo(fieldsCount, fieldEncoding, fieldNames);
Interop::InitializeStruct(context, dest, structInfo.Fields(), source);
}
} else if (arg->IsFunction() && typeEncoding->type == BinaryTypeEncodingType::ProtocolEncoding) {
Local<Object> obj = arg.As<Object>();
BaseDataWrapper* wrapper = tns::GetValue(isolate, obj);
tns::Assert(wrapper != nullptr && wrapper->Type() == WrapperType::ObjCProtocol, isolate);
ObjCProtocolWrapper* protoWrapper = static_cast<ObjCProtocolWrapper*>(wrapper);
Protocol* proto = protoWrapper->Proto();
Interop::SetValue(dest, proto);
} else if (argHelper.isObject() && typeEncoding->type == BinaryTypeEncodingType::ClassEncoding) {
Local<Object> obj = arg.As<Object>();
BaseDataWrapper* wrapper = tns::GetValue(isolate, obj);
tns::Assert(wrapper != nullptr && wrapper->Type() == WrapperType::ObjCClass, isolate);
ObjCClassWrapper* classWrapper = static_cast<ObjCClassWrapper*>(wrapper);
Class clazz = classWrapper->Klass();
Interop::SetValue(dest, clazz);
} else if (arg->IsDate()) {
Local<Date> date = arg.As<Date>();
double time = date->ValueOf();
NSDate* nsDate = [NSDate dateWithTimeIntervalSince1970:(time / 1000)];
Interop::SetValue(dest, nsDate);
} else if (typeEncoding->type == BinaryTypeEncodingType::IncompleteArrayEncoding) {
bool isArrayBuffer = false;
void* data = tns::TryGetBufferFromArrayBuffer(arg, isArrayBuffer);
if (!isArrayBuffer) {
data = Reference::GetWrappedPointer(context, arg, typeEncoding);
}
Interop::SetValue(dest, data);
} else if (typeEncoding->type == BinaryTypeEncodingType::ConstantArrayEncoding) {
if (arg->IsArray()) {
Local<v8::Array> array = Interop::ToArray(source.As<Object>());
Local<Context> context = isolate->GetCurrentContext();
const TypeEncoding* innerType = typeEncoding->details.constantArray.getInnerType();
ffi_type* ffiType = FFICall::GetArgumentType(innerType);
uint32_t length = array->Length();
for (uint32_t i = 0; i < length; i++) {
Local<Value> element;
bool success = array->Get(context, i).ToLocal(&element);
tns::Assert(success, isolate);
void* ptr = (uint8_t*)dest + i * ffiType->size;
Interop::WriteValue(context, innerType, ptr, element);
}
FFICall::DisposeFFIType(ffiType, innerType);
} else {
void* data = Reference::GetWrappedPointer(context, arg, typeEncoding);
Interop::SetValue(dest, data);
}
} else if (argHelper.isObject()) {
Local<Object> obj = arg.As<Object>();
BaseDataWrapper* wrapper = tns::GetValue(isolate, obj);
if (wrapper != nullptr) {
if (wrapper->Type() == WrapperType::Enum) {
EnumDataWrapper* enumWrapper = static_cast<EnumDataWrapper*>(wrapper);
if (!enumWrapper->HasCachedValue()) {
Local<Context> context = isolate->GetCurrentContext();
std::string jsCode = enumWrapper->JSCode();
Local<Script> script;
if (!Script::Compile(context, tns::ToV8String(isolate, jsCode)).ToLocal(&script)) {
tns::Assert(false, isolate);
}
tns::Assert(!script.IsEmpty(), isolate);
Local<Value> result;
if (!script->Run(context).ToLocal(&result)) {
tns::Assert(false, isolate);
}
tns::Assert(result->IsNumber(), isolate);
enumWrapper->SetCachedValue(result.As<Number>()->Value());
}
SetValue(dest, enumWrapper->CachedValue());
} else if (wrapper->Type() == WrapperType::Pointer) {
PointerWrapper* pointerWrapper = static_cast<PointerWrapper*>(wrapper);
void* data = pointerWrapper->Data();
Interop::SetValue(dest, data);
} else if (wrapper->Type() == WrapperType::ObjCObject) {
ObjCDataWrapper* objCDataWrapper = static_cast<ObjCDataWrapper*>(wrapper);
WrapperLifetime::Escape(objCDataWrapper);
id data = objCDataWrapper->Data();
Interop::SetValue(dest, data);
} else if (wrapper->Type() == WrapperType::ObjCClass) {
ObjCClassWrapper* classWrapper = static_cast<ObjCClassWrapper*>(wrapper);
id data = classWrapper->Klass();
Interop::SetValue(dest, data);
} else {
tns::Assert(false, isolate);
}
return;
}
// A wrapper whose native object was released must never reach native code
// as a DictionaryAdapter standing in for it.
tns::ReleasedReason releasedReason = tns::GetReleasedReason(obj);
if (releasedReason != tns::ReleasedReason::kNone) {
if (tns::GetReleasedObjectPolicy() == tns::ReleasedObjectPolicy::kThrow) {
tns::ThrowReleasedObject(isolate, releasedReason, "native argument");
}
tns::ReportReleasedObject(isolate, obj, releasedReason, "native argument", false);
id none = nil;
Interop::SetValue(dest, none);
return;
}
bool isNSArray = false;
if (typeEncoding->type == BinaryTypeEncodingType::InterfaceDeclarationReference) {
std::string name = typeEncoding->details.interfaceDeclarationReference.name.valuePtr();
isNSArray = name == "NSArray";
}
if ((obj->IsArrayBuffer() || obj->IsArrayBufferView() || obj->IsSharedArrayBuffer()) &&
!isNSArray) {
Local<ArrayBuffer> buffer = arg.As<ArrayBuffer>();
NSDataAdapter* adapter = [[NSDataAdapter alloc] initWithJSObject:buffer isolate:isolate];
Interop::SetValue(dest, CFBridgingRelease(adapter));
// CFAutorelease(adapter);
} else if (tns::IsArrayOrArrayLike(isolate, obj)) {
Local<v8::Array> array = Interop::ToArray(source.As<Object>());
ArrayAdapter* adapter = [[ArrayAdapter alloc] initWithJSObject:array isolate:isolate];
Interop::SetValue(dest, CFBridgingRelease(adapter));
// CFAutorelease(adapter);
} else {
DictionaryAdapter* adapter = [[DictionaryAdapter alloc] initWithJSObject:source.As<Object>()
isolate:isolate];
Interop::SetValue(dest, CFBridgingRelease(adapter));
// CFAutorelease(adapter);
}
} else {
tns::Assert(false, isolate);
}
}
id Interop::ToObject(Local<Context> context, v8::Local<v8::Value> arg) {
Isolate* isolate = v8::Isolate::GetCurrent();
// Runs inside adapter callbacks invoked by native code, where a C++ throw
// cannot propagate; a revoked proxy reads as nil.
Local<Value> original = arg;
arg = tns::UnwrapProxy(arg);
Local<Value> source = tns::ProxyReadSource(original, arg);
if (arg.IsEmpty() || arg->IsNullOrUndefined()) {
return nil;
} else if (tns::IsString(arg)) {
NSString* result = tns::ToNSString(isolate, arg);
return result;
} else if (tns::IsNumber(arg)) {
double value = tns::ToNumber(isolate, arg);
return @(value);
} else if (arg->IsDate()) {
Local<Date> date = arg.As<Date>();
double time = date->ValueOf();
NSDate* nsDate = [NSDate dateWithTimeIntervalSince1970:(time / 1000)];
return nsDate;
} else if (tns::IsBool(arg)) {
bool value = tns::ToBool(arg);
return @(value);
} else if (arg->IsArray()) {
Local<v8::Array> array = arg.As<v8::Array>();
if (source->IsProxy()) {
// Reported like the adapters' other read failures: a C++ throw or an
// @throw under the caller's V8 scopes cannot leave this frame.
TryCatch tc(isolate);
if (!SnapshotArrayLike(isolate, source.As<Object>(), array)) {
if (tc.HasCaught()) {
ArgConverter::HandleBoundaryException(context, tc);
}
return nil;
}
}
ArrayAdapter* adapter = [[ArrayAdapter alloc] initWithJSObject:array isolate:isolate];
return adapter;
} else if (arg->IsObject()) {
if (BaseDataWrapper* wrapper = tns::GetValue(isolate, arg)) {
switch (wrapper->Type()) {
case WrapperType::ObjCObject: {
ObjCDataWrapper* wr = static_cast<ObjCDataWrapper*>(wrapper);
WrapperLifetime::Escape(wr);
return wr->Data();
break;
}
case WrapperType::ObjCClass: {
ObjCClassWrapper* wr = static_cast<ObjCClassWrapper*>(wrapper);
return wr->Klass();
break;
}
case WrapperType::ObjCProtocol: {
ObjCProtocolWrapper* wr = static_cast<ObjCProtocolWrapper*>(wrapper);
return wr->Proto();
break;
}
default:
// TODO: Unsupported object type
tns::Assert(false, isolate);
break;
}
} else {
// nil is not a legal collection element, and this runs inside adapter
// callbacks where nothing can be thrown.
tns::ReleasedReason releasedReason = tns::GetReleasedReason(arg);
if (releasedReason != tns::ReleasedReason::kNone) {
tns::ReportReleasedObject(isolate, arg, releasedReason, "collection element", false);
return [NSNull null];
}
DictionaryAdapter* adapter = [[DictionaryAdapter alloc] initWithJSObject:source.As<Object>()
isolate:isolate];
// CFAutorelease(adapter);
return adapter;
}
}
// TODO: Handle other possible types
tns::Assert(false, isolate);
return nil;
}
Local<Value> Interop::StructToValue(Local<Context> context, void* result,
const StructInfo& structInfo, Local<Object> parentStruct) {
Isolate* isolate = v8::Isolate::GetCurrent();
std::shared_ptr<Caches> cache = Caches::Get(isolate);
tns::Assert(cache != nullptr && cache->StructInstanceFactory != nullptr, isolate);
if (parentStruct.IsEmpty()) {
return cache->StructInstanceFactory(context, structInfo, result, StructStorage::kCopy,
Local<Object>());
}
return cache->StructInstanceFactory(context, structInfo, result, StructStorage::kAlias,
parentStruct);
}
void Interop::InitializeStruct(Local<Context> context, void* destBuffer,
const std::vector<StructField>& fields, Local<Value> inititalizer) {
ptrdiff_t position = 0;
Interop::InitializeStruct(context, destBuffer, fields, inititalizer, position);
}
void Interop::InitializeStruct(Local<Context> context, void* destBuffer,
const std::vector<StructField>& fields, Local<Value> inititalizer,
ptrdiff_t& position) {