forked from ccgus/CocoaScript
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMOUtilities.m
1125 lines (955 loc) · 43.6 KB
/
MOUtilities.m
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
//
// MOUtilities.m
// Mocha
//
// Created by Logan Collins on 5/11/12.
// Copyright (c) 2012 Sunflower Softworks. All rights reserved.
//
#import "MOUtilities.h"
#import "MochaRuntime_Private.h"
#import "MOFunctionArgument.h"
#import "MOMethod_Private.h"
#import "MOClosure_Private.h"
#import "MOFunctionArgument.h"
#import "MOUndefined.h"
#import "MOJavaScriptObject.h"
#import "MOPointerValue.h"
#import "MOPointer_Private.h"
#import "MOBridgeSupportController.h"
#import "MOBridgeSupportSymbol.h"
#import "MOBox.h"
#import "MOAllocator.h"
#import "CODebugController.h"
#import <objc/runtime.h>
#import <objc/message.h>
#import <dlfcn.h>
#if TARGET_OS_IPHONE
#import "ffi.h"
#else
#import <ffi/ffi.h>
#endif
@interface NSMethodSignature (Mocha)
- (NSString *)typeEncoding;
@end
@implementation NSMethodSignature (Mocha)
- (NSString *)typeEncoding {
NSString *encoding = [NSString stringWithFormat: @"%s", [self methodReturnType]];
for (NSUInteger i = 0;i < [self numberOfArguments];++i) {
const char *argType = [self getArgumentTypeAtIndex:i];
encoding = [encoding stringByAppendingFormat: @"%s", argType];
}
return encoding;
}
@end
#pragma mark -
#pragma mark Values
JSValueRef MOJSValueToType(JSContextRef ctx, JSObjectRef objectJS, JSType type, JSValueRef *exception) {
MOBox *box = (__bridge MOBox *)(JSObjectGetPrivate(objectJS));
if (box != nil) {
// Boxed object
id object = [box representedObject];
if ([object isKindOfClass:[NSString class]]) {
JSStringRef string = JSStringCreateWithCFString((__bridge CFStringRef)object);
JSValueRef value = JSValueMakeString(ctx, string);
JSStringRelease(string);
return value;
}
else if ([object isKindOfClass:[NSNumber class]]) {
double doubleValue = [object doubleValue];
return JSValueMakeNumber(ctx, doubleValue);
}
// Convert the object's description to a string as a last ditch effort
NSString *description = [object description];
JSStringRef string = JSStringCreateWithCFString((__bridge CFStringRef)description);
JSValueRef value = JSValueMakeString(ctx, string);
JSStringRelease(string);
return value;
}
return NULL;
}
NSString * MOJSValueToString(JSContextRef ctx, JSValueRef value, JSValueRef *exception) {
if (value == NULL || JSValueIsNull(ctx, value)) {
return nil;
}
JSStringRef resultStringJS = JSValueToStringCopy(ctx, value, exception);
NSString *resultString = (NSString *)CFBridgingRelease(JSStringCopyCFString(kCFAllocatorDefault, resultStringJS));
JSStringRelease(resultStringJS);
return resultString;
}
#pragma mark -
#pragma mark Invocation
JSValueRef _MOSelectorInvoke(id target, SEL selector, JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef *exception) {
Mocha *runtime = [Mocha runtimeWithContext:ctx];
NSMethodSignature *methodSignature = [target methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
[invocation retainArguments]; // need to do this for release builds, because it seems ARC likes to let go of our strings early otherwise.
[invocation setTarget:target];
[invocation setSelector:selector];
NSUInteger methodArgumentCount = [methodSignature numberOfArguments] - 2;
if (methodArgumentCount != argumentCount) {
NSString *reason = [NSString stringWithFormat:@"ObjC method %@ requires %lu %@, but JavaScript passed %zd %@", NSStringFromSelector(selector), methodArgumentCount, (methodArgumentCount == 1 ? @"argument" : @"arguments"), argumentCount, (argumentCount == 1 ? @"argument" : @"arguments")];
NSException *e = [NSException exceptionWithName:MORuntimeException reason:reason userInfo:nil];
if (exception != NULL) {
*exception = [runtime JSValueForObject:e];
}
return NULL;
}
// Build arguments
for (size_t i=0; i<argumentCount; i++) {
JSValueRef argument = arguments[i];
id object = [runtime objectForJSValue:argument unboxObjects:NO];
NSUInteger argIndex = i + 2;
const char * argType = [methodSignature getArgumentTypeAtIndex:argIndex];
// debug(@"argIndex: %ld", argIndex);
// MOBox
if ([object isKindOfClass:[MOBox class]]) {
id value = [object representedObject];
[invocation setArgument:&value atIndex:argIndex];
}
// NSNumber
else if ([object isKindOfClass:[NSNumber class]]) {
// long
if (strcmp(argType, @encode(long)) == 0
|| strcmp(argType, @encode(unsigned long)) == 0) {
long val = [object longValue];
[invocation setArgument:&val atIndex:argIndex];
}
// short
else if (strcmp(argType, @encode(short)) == 0
|| strcmp(argType, @encode(unsigned short)) == 0) {
short val = [object shortValue];
[invocation setArgument:&val atIndex:argIndex];
}
// char
else if (strcmp(argType, @encode(char)) == 0
|| strcmp(argType, @encode(unsigned char)) == 0) {
char val = [object charValue];
[invocation setArgument:&val atIndex:argIndex];
}
// long long
else if (strcmp(argType, @encode(long long)) == 0
|| strcmp(argType, @encode(unsigned long long)) == 0) {
long long val = [object longLongValue];
[invocation setArgument:&val atIndex:argIndex];
}
// float
else if (strcmp(argType, @encode(float)) == 0) {
float val = [object floatValue];
[invocation setArgument:&val atIndex:argIndex];
}
// double
else if (strcmp(argType, @encode(double)) == 0) {
double val = [object doubleValue];
[invocation setArgument:&val atIndex:argIndex];
}
// BOOL
else if (strcmp(argType, @encode(bool)) == 0
|| strcmp(argType, @encode(_Bool)) == 0) {
BOOL val = [object boolValue];
[invocation setArgument:&val atIndex:argIndex];
}
// int
else {
int val = [object intValue];
[invocation setArgument:&val atIndex:argIndex];
}
}
// id
else {
[invocation setArgument:&object atIndex:argIndex];
}
}
// Invoke
[invocation invoke];
// Build return value
const char * returnType = [methodSignature methodReturnType];
JSValueRef returnValue = NULL;
if (strcmp(returnType, @encode(void)) == 0) {
returnValue = JSValueMakeUndefined(ctx);
}
// id
else if (strcmp(returnType, @encode(id)) == 0
|| strcmp(returnType, @encode(Class)) == 0) {
id object = nil;
[invocation getReturnValue:&object];
returnValue = [runtime JSValueForObject:object];
}
// SEL
/*else if (strcmp(returnType, @encode(SEL)) == 0) {
SEL selector = NULL;
[invocation getReturnValue:&selector];
returnValue = object;
}*/
// void *
else if (strcmp(returnType, @encode(void *)) == 0) {
void *pointer = NULL;
[invocation getReturnValue:&pointer];
MOPointerValue * __autoreleasing object = [[MOPointerValue alloc] initWithPointerValue:pointer typeEncoding:nil];
returnValue = (__bridge void *)object;
}
// bool
else if (strcmp(returnType, @encode(bool)) == 0
|| strcmp(returnType, @encode(_Bool)) == 0) {
BOOL value;
[invocation getReturnValue:&value];
returnValue = [runtime JSValueForObject:[NSNumber numberWithBool:value]];
}
// int
else if (strcmp(returnType, @encode(int)) == 0
|| strcmp(returnType, @encode(unsigned int)) == 0) {
int value;
[invocation getReturnValue:&value];
returnValue = [runtime JSValueForObject:[NSNumber numberWithInt:value]];
}
// long
else if (strcmp(returnType, @encode(long)) == 0
|| strcmp(returnType, @encode(unsigned long)) == 0) {
long value;
[invocation getReturnValue:&value];
returnValue = [runtime JSValueForObject:[NSNumber numberWithLong:value]];
}
// long long
else if (strcmp(returnType, @encode(long long)) == 0
|| strcmp(returnType, @encode(unsigned long long)) == 0) {
long long value;
[invocation getReturnValue:&value];
returnValue = [runtime JSValueForObject:[NSNumber numberWithLongLong:value]];
}
// short
else if (strcmp(returnType, @encode(short)) == 0
|| strcmp(returnType, @encode(unsigned short)) == 0) {
short value;
[invocation getReturnValue:&value];
returnValue = [runtime JSValueForObject:[NSNumber numberWithShort:value]];
}
// char
else if (strcmp(returnType, @encode(char)) == 0
|| strcmp(returnType, @encode(unsigned char)) == 0) {
char value;
[invocation getReturnValue:&value];
returnValue = [runtime JSValueForObject:[NSNumber numberWithChar:value]];
}
// float
else if (strcmp(returnType, @encode(float)) == 0) {
float value;
[invocation getReturnValue:&value];
returnValue = [runtime JSValueForObject:[NSNumber numberWithFloat:value]];
}
// double
else if (strcmp(returnType, @encode(double)) == 0) {
double value;
[invocation getReturnValue:&value];
returnValue = [runtime JSValueForObject:[NSNumber numberWithDouble:value]];
}
return returnValue;
}
JSValueRef _MOFunctionInvoke(id function, JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef *exception) {
Mocha *runtime = [Mocha runtimeWithContext:ctx];
JSValueRef value = NULL;
BOOL objCCall = NO;
BOOL blockCall = NO;
NSMutableArray *argumentEncodings = nil;
void* callAddress = NULL;
NSUInteger callAddressArgumentCount = 0;
BOOL variadic = NO;
unsigned int fixedArgumentCount = 0;
id target = nil;
SEL selector = NULL;
id block = nil;
// FIXME: Check to see if function is nil or not."
// debug(@"function: %@", function);
// Determine the metadata for the function call
if ([function isKindOfClass:[MOMethod class]]) {
// ObjC method
objCCall = YES;
target = [function target];
selector = [function selector];
Class klass = [target class];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// Override for Distributed Objects
if ([klass isSubclassOfClass:[NSDistantObject class]]) {
return MOSelectorInvoke(target, selector, ctx, argumentCount, arguments, exception);
}
#pragma clang diagnostic pop
// Override for Allocators
if (selector == @selector(alloc)
|| selector == @selector(allocWithZone:))
{
// Override for -alloc
MOAllocator *allocator = [MOAllocator allocator];
allocator.objectClass = klass;
return [runtime JSValueForObject:allocator];
}
if ([target isKindOfClass:[MOAllocator class]]) {
klass = [target objectClass];
target = [[target objectClass] alloc];
}
// Make sure autorelease is ignored, since we do our own reference counting.
if (selector == NSSelectorFromString(@"autorelease")) {
[CODebugController output:@"Ignoring autorelease call on %@", target];
return [runtime JSValueForObject:target];
}
Method method = NULL;
IMP method_imp = NULL;
BOOL classMethod = (target == klass);
// Determine the method type
if (classMethod) {
method = class_getClassMethod(klass, selector);
}
else {
method = class_getInstanceMethod(klass, selector);
/* For dynamic properties from CoreData, method will be NULL, but we can still get the method_imp and the methodSignature from the object */
method_imp = [target methodForSelector: selector];
}
variadic = MOSelectorIsVariadic(klass, selector);
if (method == NULL && method_imp == NULL) {
NSException *e = [NSException exceptionWithName:MORuntimeException reason:[NSString stringWithFormat:@"Unable to locate method %@ of class %@", NSStringFromSelector(selector), klass] userInfo:nil];
if (exception != NULL) {
*exception = [runtime JSValueForObject:e];
}
return NULL;
}
const char *encoding;
if (method)
encoding = method_getTypeEncoding(method);
else
encoding = [[[target methodSignatureForSelector: selector] typeEncoding] cStringUsingEncoding: NSASCIIStringEncoding];
if (encoding)
argumentEncodings = [MOParseObjCMethodEncoding(encoding) mutableCopy];
// method_getTypeEncoding() / -methodSignatureForSelector: call above might return an incomplete/bogus
// type encoding for a C struct argument / return value for some methods: while the struct
// fields themselves are encoded correctly, the name of the struct type is replaced with a "?" symbol.
//
// This missing name in the type encoding prevents routines like -[MOFunctionArgument getValueAsJSValueInContext:]
// and -[MOFunctionArgument setValueAsJSValue:context:] from converting this struct from/to a JS value,
// because it fails to look up this struct's bridge support definition by its bogus name.
//
// As a result, it's impossible to call such methods from CocoaScript as it leads to
// the following runtime exception: "No structure encoding found for ?".
//
// Here's a few examples of such "uncallable" methods with incomplete struct type encoding
// from frameworks we load by default:
//
// -[NSProcessInfo operatingSystemVersion]'s return value type is reported as "{?=qqq}" instead of "{NSOperatingSystemVersion=qqq}"
// -[NSProcessInfo isOperatingSystemAtLeastVersion:]'s argument type is reported as "{?=qqq}" instead of "{NSOperatingSystemVersion=qqq}"
// -[NSAffineTransform transformStruct]'s return value type is reported as "{?=dddddd}" instead of "{NSAffineTransformStruct=dddddd}"
//
// The workaround is to compare the type declarations we get from method_getTypeEncoding() / -methodSignatureForSelector:
// with what's in the bridge support definitions for this method and replace bogus struct names
// with their actual names from the latter if found.
MOBridgeSupportMethod *_Nullable bridgeSupportMethod = ^MOBridgeSupportMethod *(void) {
MOBridgeSupportController *bridgeController = [MOBridgeSupportController sharedController];
MOBridgeSupportClass *_Nullable bridgeSupportClass = [bridgeController performQueryForSymbolName:NSStringFromClass(klass)
ofType:MOBridgeSupportClass.class];
return [bridgeSupportClass methodWithSelector:selector];
}();
if (bridgeSupportMethod != nil) {
[argumentEncodings enumerateObjectsUsingBlock:^(MOFunctionArgument *argument, NSUInteger idx, BOOL *stop) {
if (idx == 1 || idx == 2) {
// these are the implicit `self` and `sel` arguments; skip them
return;
}
if (argument.typeEncoding != _C_STRUCT_B) {
// this is not a C struct; skip it
return;
}
NSString *runtimeStructName = [MOFunctionArgument structureNameFromStructureTypeEncoding:argument.structureTypeEncoding];
if (![runtimeStructName isEqualToString:@"?"]) {
// not a bogus struct type name, so nothing to fix; skip it
return;
}
MOBridgeSupportArgument *_Nullable bridgeSupportArgument = ^MOBridgeSupportArgument *(void) {
if (idx == 0) {
return bridgeSupportMethod.returnValue;
}
// As bridge support files may not contain definitions for all arguments of a method,
// we rely on the `index` property here to find the one we need
NSInteger explicitArgumentIndex = idx - 3;
NSUInteger bridgeSupportArgumentIndex = [bridgeSupportMethod.arguments indexOfObjectPassingTest:^BOOL(MOBridgeSupportArgument *bridgeArgument, NSUInteger _, BOOL *__) {
return bridgeArgument.index == explicitArgumentIndex;
}];
if (bridgeSupportArgumentIndex == NSNotFound) {
// the required argument definition was not in the bridge support file
return nil;
}
return bridgeSupportMethod.arguments[bridgeSupportArgumentIndex];
}();
NSString *_Nullable bridgeSupportArgumentType = (bridgeSupportArgument.type64 ?: bridgeSupportArgument.type);
if (bridgeSupportArgument == nil || bridgeSupportArgumentType.length == 0) {
return;
}
// The code below only replaces the top-level struct name if bogus.
// It is safe to only go this far because the actual definition of the struct type
// is then fetched from a bridge support file where all the nested struct fields are
// expected to be already well-defined.
NSString *structNameFromBridgeSupport = [MOFunctionArgument structureNameFromStructureTypeEncoding:bridgeSupportArgumentType];
NSRange replacementRange = [argument.structureTypeEncoding rangeOfString:@"?"];
if (structNameFromBridgeSupport.length == 0 || replacementRange.location == NSNotFound) {
return;
}
NSString *monkeyPatchedTypeEncoding = [argument.structureTypeEncoding stringByReplacingCharactersInRange:replacementRange withString:structNameFromBridgeSupport];
[argument setStructureTypeEncoding:monkeyPatchedTypeEncoding];
}];
}
if (argumentEncodings == nil) {
NSException *e = [NSException exceptionWithName:MORuntimeException reason:[NSString stringWithFormat:@"Unable to parse method encoding for method %@ of class %@", NSStringFromSelector(selector), klass] userInfo:nil];
if (exception != NULL) {
*exception = [runtime JSValueForObject:e];
}
return NULL;
}
// Function arguments are all arguments minus return value and [instance, selector] params to objc_send
callAddressArgumentCount = [argumentEncodings count] - 3;
// Get call address
callAddress = MOInvocationGetObjCCallAddressForArguments(argumentEncodings);
if (variadic) {
if (argumentCount > 0) {
// add an argument for NULL
argumentCount++;
}
// For variadic methods, we need to get the number of fixed arguments, before the first
// variadic one since that number needs to be passed to ffi_prep_cif_var below.
fixedArgumentCount = method_getNumberOfArguments(method);
}
if ((variadic && (callAddressArgumentCount > argumentCount))
|| (!variadic && (callAddressArgumentCount != argumentCount)))
{
NSString *reason = [NSString stringWithFormat:@"ObjC method %@ requires %lu %@, but JavaScript passed %zd %@", NSStringFromSelector(selector), callAddressArgumentCount, (callAddressArgumentCount == 1 ? @"argument" : @"arguments"), argumentCount, (argumentCount == 1 ? @"argument" : @"arguments")];
NSException *e = [NSException exceptionWithName:MORuntimeException reason:reason userInfo:nil];
if (exception != NULL) {
*exception = [runtime JSValueForObject:e];
}
return NULL;
}
}
else if ([function isKindOfClass:[MOClosure class]]) {
// C block
blockCall = YES;
block = [function block];
callAddress = [function callAddress];
const char *typeEncoding = [(MOClosure *)function typeEncoding];
argumentEncodings = [MOParseObjCMethodEncoding(typeEncoding) mutableCopy];
if (argumentEncodings == nil) {
NSException *e = [NSException exceptionWithName:MORuntimeException reason:[NSString stringWithFormat:@"Unable to parse method encoding for method %@ of class %@", NSStringFromSelector(selector), [target class]] userInfo:nil];
if (exception != NULL) {
*exception = [runtime JSValueForObject:e];
}
return NULL;
}
callAddressArgumentCount = [argumentEncodings count] - 2;
if (callAddressArgumentCount != argumentCount) {
NSString *reason = [NSString stringWithFormat:@"Block requires %lu %@, but JavaScript passed %zd %@", callAddressArgumentCount, (callAddressArgumentCount == 1 ? @"argument" : @"arguments"), argumentCount, (argumentCount == 1 ? @"argument" : @"arguments")];
NSException *e = [NSException exceptionWithName:MORuntimeException reason:reason userInfo:nil];
if (exception != NULL) {
*exception = [runtime JSValueForObject:e];
}
return NULL;
}
}
else if ([function isKindOfClass:[MOBridgeSupportFunction class]]) {
// C function
NSString *functionName = [function name];
callAddress = dlsym(RTLD_DEFAULT, [functionName UTF8String]);
// If the function cannot be found, raise an exception (instead of crashing)
if (callAddress == NULL) {
if (exception != NULL) {
NSException *e = [NSException exceptionWithName:MORuntimeException reason:[NSString stringWithFormat:@"Unable to find function with name: %@", functionName] userInfo:nil];
*exception = [runtime JSValueForObject:e];
}
return NULL;
}
variadic = [function isVariadic];
NSMutableArray *args = [NSMutableArray array];
// Build return type
MOBridgeSupportArgument *returnValue = [function returnValue];
MOFunctionArgument *returnArg = nil;
if (returnValue != nil) {
NSString *returnTypeEncoding = nil;
#if __LP64__
returnTypeEncoding = [returnValue type64];
if (returnTypeEncoding == nil) {
returnTypeEncoding = [returnValue type];
}
#else
returnTypeEncoding = [returnValue type];
#endif
returnArg = MOFunctionArgumentForTypeEncoding(returnTypeEncoding);
}
else {
// void return
returnArg = [[MOFunctionArgument alloc] init];
[returnArg setTypeEncoding:_C_VOID];
}
[returnArg setReturnValue:YES];
[args addObject:returnArg];
// Build arguments
for (MOBridgeSupportArgument *argument in [function arguments]) {
NSString *typeEncoding = nil;
#if __LP64__
typeEncoding = [argument type64];
if (typeEncoding == nil) {
typeEncoding = [argument type];
}
#else
typeEncoding = [argument type];
#endif
MOFunctionArgument *arg = MOFunctionArgumentForTypeEncoding(typeEncoding);
[args addObject:arg];
}
argumentEncodings = [args mutableCopy];
// Function arguments are all arguments minus return value
callAddressArgumentCount = [args count] - 1;
// Raise if the argument counts don't match
if ((variadic && (callAddressArgumentCount > argumentCount))
|| (!variadic && (callAddressArgumentCount != argumentCount)))
{
NSString *reason = [NSString stringWithFormat:@"C function %@ requires %lu %@, but JavaScript passed %zd %@", functionName, callAddressArgumentCount, (callAddressArgumentCount == 1 ? @"argument" : @"arguments"), argumentCount, (argumentCount == 1 ? @"argument" : @"arguments")];
NSException *e = [NSException exceptionWithName:MORuntimeException reason:reason userInfo:nil];
if (exception != NULL) {
*exception = [runtime JSValueForObject:e];
}
return NULL;
}
}
// Prepare ffi
ffi_cif cif;
ffi_type** args = NULL;
void** values = NULL;
// Build the arguments
NSUInteger effectiveArgumentCount = argumentCount;
if (objCCall) {
effectiveArgumentCount += 2;
}
if (blockCall) {
effectiveArgumentCount += 1;
}
if (effectiveArgumentCount > 0) {
args = malloc(sizeof(ffi_type *) * effectiveArgumentCount);
values = malloc(sizeof(void *) * effectiveArgumentCount);
NSUInteger j = 0;
if (objCCall) {
// ObjC calls include the target and selector as the first two arguments
args[0] = &ffi_type_pointer;
args[1] = &ffi_type_pointer;
values[0] = (void *)⌖
values[1] = (void *)&selector;
j = 2;
}
else if (blockCall) {
// Block calls include the block as the first argument
args[0] = &ffi_type_pointer;
values[0] = (void *)█
j = 1;
}
for (NSUInteger i=0; i<argumentCount; i++, j++) {
JSValueRef jsValue = NULL;
MOFunctionArgument *arg = nil;
if (variadic && i >= callAddressArgumentCount) {
arg = [[MOFunctionArgument alloc] init];
[arg setTypeEncoding:_C_ID];
[argumentEncodings addObject:arg];
}
else {
arg = [argumentEncodings objectAtIndex:(j + 1)];
}
if (objCCall && variadic && i == argumentCount - 1) {
// The last variadic argument in ObjC calls is nil (the sentinel value)
jsValue = NULL;
}
else {
jsValue = arguments[i];
}
if (jsValue != NULL) {
id object = [runtime objectForJSValue:jsValue];
// Handle pointers
if ([object isKindOfClass:[MOPointer class]]) {
[arg setPointer:object];
id objValue = [(MOPointer *)object value];
JSValueRef objJSValue = [runtime JSValueForObject:objValue];
[arg setValueAsJSValue:objJSValue context:ctx dereference:YES];
}
else {
[arg setValueAsJSValue:jsValue context:ctx];
}
}
else {
[arg setValueAsJSValue:NULL context:ctx];
}
args[j] = [arg ffiType];
values[j] = [arg storage];
}
}
// Get return value holder
MOFunctionArgument *returnValue = [argumentEncodings objectAtIndex:0];
// Prep
ffi_status prep_status;
// If the method is variadic AND we could determine the number of fixed arguments, we need to
// take a special approach to prepare libffi to pass the arguments correctly.
// See https://github.com/sketch-hq/sketch/issues/35513
if (variadic && fixedArgumentCount > 0) {
if (@available(macOS 10.15, *)) {
// This is especially important on ARM Macs, since they require the variadic arguments to be
// passed on the stack, not in registers.
prep_status = ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, fixedArgumentCount, (unsigned int)effectiveArgumentCount, returnValue.ffiType, args);
} else {
// We should be safe to fall back to ffi_pref_cif here, because this only occurs on 10.14,
// which only runs on Intel, and on Intel we're using registers for variadic arguments.
prep_status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, (unsigned int)effectiveArgumentCount, [returnValue ffiType], args);
}
} else {
// If a function is not variadic, libffi will do the correct thing in any case regardless
// of architecture.
prep_status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, (unsigned int)effectiveArgumentCount, [returnValue ffiType], args);
}
// Call
if (prep_status == FFI_OK) {
void *storage = [returnValue storage];
@try {
ffi_call(&cif, callAddress, storage, values);
}
@catch (NSException *e) {
if (effectiveArgumentCount > 0) {
free(args);
free(values);
}
if (exception != NULL) {
*exception = [runtime JSValueForObject:e];
}
return NULL;
}
}
// Free the arguments
if (effectiveArgumentCount > 0) {
free(args);
free(values);
}
// Throw an exception if the prep call failed
if (prep_status != FFI_OK) {
NSException *e = [NSException exceptionWithName:MORuntimeException reason:@"ffi_prep_cif failed" userInfo:nil];
if (exception != NULL) {
*exception = [runtime JSValueForObject:e];
}
return NULL;
}
// Populate the value of pointers
for (MOFunctionArgument *arg in argumentEncodings) {
if ([arg pointer] != nil) {
MOPointer *pointer = [arg pointer];
JSValueRef contextValue = [arg getValueAsJSValueInContext:ctx dereference:YES];
id object = [runtime objectForJSValue:contextValue];
pointer.value = object;
}
}
// If the return type is void, the return value should be undefined
if ([returnValue ffiType] == &ffi_type_void) {
return JSValueMakeUndefined(ctx);
}
@try {
value = [returnValue getValueAsJSValueInContext:ctx];
}
@catch (NSException *e) {
if (exception != NULL) {
*exception = [runtime JSValueForObject:e];
}
return NULL;
}
return value;
}
JSValueRef MOSelectorInvoke(id target, SEL selector, JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef *exception) {
for (NSUInteger n = 0; n < argumentCount; ++n) {
JSValueProtect(ctx, arguments[n]);
}
JSValueRef result = _MOSelectorInvoke(target, selector, ctx, argumentCount, arguments, exception);
for (NSUInteger n = 0; n < argumentCount; ++n) {
JSValueUnprotect(ctx, arguments[n]);
}
return result;
}
JSValueRef MOFunctionInvoke(id function, JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef *exception) {
for (NSUInteger n = 0; n < argumentCount; ++n) {
JSValueProtect(ctx, arguments[n]);
}
JSValueRef result = _MOFunctionInvoke(function, ctx, argumentCount, arguments, exception);
for (NSUInteger n = 0; n < argumentCount; ++n) {
JSValueUnprotect(ctx, arguments[n]);
}
return result;
}
BOOL MOSelectorIsVariadic(Class klass, SEL selector) {
NSString *className = [NSString stringWithUTF8String:class_getName(klass)];
while (klass != Nil) {
MOBridgeSupportClass *classSymbol = [[MOBridgeSupportController sharedController] performQueryForSymbolName:className ofType:[MOBridgeSupportClass class]];
if (classSymbol == nil) {
klass = [klass superclass];
continue;
}
MOBridgeSupportMethod *methodSymbol = [classSymbol methodWithSelector:selector];
if (methodSymbol != nil) {
return [methodSymbol isVariadic];
}
klass = [klass superclass];
}
return NO;
}
MOFunctionArgument * MOFunctionArgumentForTypeEncoding(NSString *typeEncoding) {
MOFunctionArgument *argument = [[MOFunctionArgument alloc] init];
char typeEncodingChar = [typeEncoding UTF8String][0];
if (typeEncodingChar == _C_STRUCT_B) {
[argument setStructureTypeEncoding:typeEncoding];
}
else if (typeEncodingChar == _C_PTR) {
if ([typeEncoding isEqualToString:@"^{__CFString=}"]) {
[argument setTypeEncoding:_C_ID];
}
else {
[argument setPointerTypeEncoding:typeEncoding];
}
}
else {
[argument setTypeEncoding:typeEncodingChar];
}
return argument;
}
NSArray<MOFunctionArgument *> * MOParseObjCMethodEncoding(const char *typeEncoding) {
NSMutableArray *argumentEncodings = [NSMutableArray array];
char *argsParser = (char *)typeEncoding;
for(; *argsParser; argsParser++) {
// Skip ObjC argument order
if (*argsParser >= '0' && *argsParser <= '9') {
continue;
}
else {
// Skip ObjC type qualifiers - except for _C_CONST these are not defined in runtime.h
if (*argsParser == _C_CONST ||
*argsParser == 'n' ||
*argsParser == 'N' ||
*argsParser == 'o' ||
*argsParser == 'O' ||
*argsParser == 'R' ||
*argsParser == 'V') {
continue;
}
else {
if (*argsParser == _C_STRUCT_B) {
// Parse structure encoding
NSInteger count = 0;
[MOFunctionArgument typeEncodingsFromStructureTypeEncoding:[NSString stringWithUTF8String:argsParser] parsedCount:&count];
NSString *encoding = [[NSString alloc] initWithBytes:argsParser length:count encoding:NSUTF8StringEncoding];
MOFunctionArgument *argumentEncoding = [[MOFunctionArgument alloc] init];
// Set return value
if ([argumentEncodings count] == 0) {
[argumentEncoding setReturnValue:YES];
}
[argumentEncoding setStructureTypeEncoding:encoding];
[argumentEncodings addObject:argumentEncoding];
argsParser += count - 1;
}
else {
// Custom handling for pointers as they're not one char long.
char* typeStart = argsParser;
if (*argsParser == '^') {
while (*argsParser && !(*argsParser >= '0' && *argsParser <= '9')) {
argsParser++;
}
}
MOFunctionArgument *argumentEncoding = [[MOFunctionArgument alloc] init];
// Set return value
if ([argumentEncodings count] == 0) {
[argumentEncoding setReturnValue:YES];
}
// If pointer, copy pointer type (^i, ^{NSRect}) to the argumentEncoding
if (*typeStart == _C_PTR) {
NSString *encoding = [[NSString alloc] initWithBytes:typeStart length:(argsParser - typeStart) encoding:NSUTF8StringEncoding];
[argumentEncoding setPointerTypeEncoding:encoding];
}
else {
@try {
[argumentEncoding setTypeEncoding:*typeStart];
}
@catch (NSException *e) {
return nil;
}
// Blocks are '@?', skip '?'
if (typeStart[0] == _C_ID && typeStart[1] == _C_UNDEF) {
argsParser++;
}
}
[argumentEncodings addObject:argumentEncoding];
}
}
}
if (!*argsParser) {
break;
}
}
return argumentEncodings;
}
//
// From PyObjC : when to call objc_msgSend_stret, for structure return
// Depending on structure size & architecture, structures are returned as function first argument (done transparently by ffi) or via registers
//
#if defined(__ppc__)
# define SMALL_STRUCT_LIMIT 4
#elif defined(__ppc64__)
# define SMALL_STRUCT_LIMIT 8
#elif defined(__i386__)
# define SMALL_STRUCT_LIMIT 8
#elif defined(__x86_64__)
# define SMALL_STRUCT_LIMIT 16
#elif defined(__arm64)
# define SMALL_STRUCT_LIMIT 16
#elif TARGET_OS_IPHONE
// TOCHECK
# define SMALL_STRUCT_LIMIT 4
#else
# error "Unsupported MACOSX platform"
#endif
BOOL MOInvocationShouldUseStret(NSArray *arguments) {
size_t resultSize = 0;
char returnEncoding = [(MOFunctionArgument *)[arguments objectAtIndex:0] typeEncoding];
if (returnEncoding == _C_STRUCT_B) {
resultSize = [MOFunctionArgument sizeOfStructureTypeEncoding:[[arguments objectAtIndex:0] structureTypeEncoding]];
}
if (returnEncoding == _C_STRUCT_B &&
//#ifdef __ppc64__
// ffi64_stret_needs_ptr(signature_to_ffi_return_type(rettype), NULL, NULL)
//
//#else /* !__ppc64__ */
(resultSize > SMALL_STRUCT_LIMIT
#ifdef __i386__
/* darwin/x86 ABI is slightly odd ;-) */
|| (resultSize != 1
&& resultSize != 2
&& resultSize != 4
&& resultSize != 8)
#endif
#ifdef __x86_64__
/* darwin/x86-64 ABI is slightly odd ;-) */
|| (resultSize != 1
&& resultSize != 2
&& resultSize != 4
&& resultSize != 8
&& resultSize != 16
)
#endif
)
//#endif /* !__ppc64__ */
) {
// callAddress = objc_msgSend_stret;
// usingStret = YES;
return YES;
}
return NO;
}
void * MOInvocationGetObjCCallAddressForArguments(NSArray *arguments) {
#if __arm64__
void *callAddress = objc_msgSend;
#else
BOOL usingStret = MOInvocationShouldUseStret(arguments);
void *callAddress = NULL;
if (usingStret) {
callAddress = objc_msgSend_stret;
}
else {
callAddress = objc_msgSend;
}
#endif
#if __i386__