-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathmain.m
More file actions
1821 lines (1699 loc) · 76.2 KB
/
Copy pathmain.m
File metadata and controls
1821 lines (1699 loc) · 76.2 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
@import Darwin;
@import QuartzCore;
@import CoreFoundation;
@import Foundation;
@import UIKit;
@import ObjectiveC;
#import "ObjCMethod.h"
#include <string.h>
typedef NS_ENUM(NSUInteger, LC32KnownStruct) {
LC32KnownStructNone,
LC32KnownStructCGAffineTransform,
LC32KnownStructCGPoint,
LC32KnownStructCGRect,
LC32KnownStructCGSize,
LC32KnownStructNSRange,
LC32KnownStructUIEdgeInsets,
};
static const char *LC32UnqualifiedEncoding(const char *encoding) {
while(encoding && *encoding && strchr("rnNoORVA", *encoding)) {
encoding++;
}
return encoding;
}
/*
* Objective-C encodings do not retain typedef names: both a CF-style opaque
* reference and an ordinary pointer to a private structure appear as
* `^{Name=...}`. Only opt known CFType families into object-proxy bridging.
* Treating every double-underscore structure as an object also catches raw
* UIKit event/GL/C++ structures (notably __GSEvent), and generated methods
* then send -host_self to arbitrary guest memory.
*/
static BOOL LC32EncodingIsOpaqueCFObjectPointer(const char *encoding) {
encoding = LC32UnqualifiedEncoding(encoding);
if(!encoding || encoding[0] != '^' || encoding[1] != '{') return NO;
/* Runtime encodings lose these exact Objective-C-compatible CF typedefs.
* Do not extend this to arbitrary CG-prefixed private structures. */
if(LC32EncodingRepresentsCGColorRef(encoding) ||
LC32EncodingRepresentsCGImageRef(encoding)) return YES;
const char *name = encoding + 2;
static const char *const prefixes[] = {
"__C3D", "__CF", "__CLClient", "__CN", "__CT", "__CV",
"__IOHID", "__IOSurface", "__SC", "__Sec",
};
for(size_t i = 0; i < sizeof(prefixes) / sizeof(prefixes[0]); i++) {
if(!strncmp(name, prefixes[i], strlen(prefixes[i]))) return YES;
}
return NO;
}
static LC32KnownStruct LC32KnownStructForEncoding(const char *encoding) {
if(!encoding) return LC32KnownStructNone;
while(*encoding && strchr("rnNoORVA", *encoding)) encoding++;
if(!strncmp(encoding, "{CGAffineTransform=", sizeof("{CGAffineTransform=") - 1)) {
return LC32KnownStructCGAffineTransform;
}
if(!strncmp(encoding, "{CGPoint=", sizeof("{CGPoint=") - 1)) {
return LC32KnownStructCGPoint;
}
if(!strncmp(encoding, "{CGRect=", sizeof("{CGRect=") - 1)) {
return LC32KnownStructCGRect;
}
if(!strncmp(encoding, "{CGSize=", sizeof("{CGSize=") - 1)) {
return LC32KnownStructCGSize;
}
if(!strncmp(encoding, "{_NSRange=", sizeof("{_NSRange=") - 1) ||
!strncmp(encoding, "{NSRange=", sizeof("{NSRange=") - 1)) {
return LC32KnownStructNSRange;
}
if(!strncmp(encoding, "{UIEdgeInsets=", sizeof("{UIEdgeInsets=") - 1)) {
return LC32KnownStructUIEdgeInsets;
}
return LC32KnownStructNone;
}
@interface MethodParameter : NSObject
@property(nonatomic, retain) NSString *name;
@property(nonatomic, retain) NSString *type;
@property(nonatomic, assign) const char *signature;
// index from 0
@property(nonatomic) int index;
// Index of the explicit element-count argument for a const id input array.
// A negative value means this is not a counted object-array parameter.
@property(nonatomic) int objectArrayCountIndex;
@end
@implementation MethodParameter
// FIXME: will need to parse header to return correctly. On 64bit, NS*Integer and CGFloat are not distinguishable from 32bit
+ (NSString *)readableTypeForSignature:(const char *)signature {
if(!signature || !*signature) return @"?";
if(LC32EncodingRepresentsCGColorRef(signature)) return @"CGColorRef";
if(LC32EncodingRepresentsCGImageRef(signature)) return @"CGImageRef";
if(LC32EncodingIsOpaqueCFObjectPointer(signature)) {
/* Runtime qualifiers can precede the pointer encoding (for example
* r^{__CF...}). Generated code only needs an address-sized token;
* the bridge still treats it as an object proxy. */
return @"void *";
}
if(LC32KnownStructForEncoding(signature) == LC32KnownStructNSRange) {
return @"NSRange";
}
// Correct some 32bit types
if(signature[0] == '^' && signature[1]) {
switch(signature[1]) {
case 'L':
return @"uint32_t *";
case 'Q':
return @"uint64_t *";
case 'c':
return @"BOOL *";
case 'd':
return @"double *";
case 'l':
return @"int32_t *";
case 'q':
return @"int64_t *";
case '{':
/* Opaque CF pointers (^{__CFRunLoop=} etc.) have no public
* struct typedef, so name them as void * in generated code.
* The guest-side proxy still round-trips through the bridge;
* the type is only used for casts and declarations. */
if(LC32EncodingIsOpaqueCFObjectPointer(signature)) {
return @"void *";
}
break;
}
}
switch(signature[0]) {
case 'C':
return @"unsigned char";
case 'L':
return @"uint32_t";
case 'Q':
return @"uint64_t";
case 'c':
return @"char";
case 'd':
return @"double";
case 'l':
return @"int32_t";
case 'q':
return @"int64_t";
default:
return LC32ReadableTypeForEncoding(signature);
}
}
+ (BOOL)isDirectCastType:(char)c {
switch(c) {
case 'B':
case 'C':
case 'I':
case 'L':
case 'Q':
case 'S':
case 'b':
case 'c':
case 'i':
case 'l':
case 'q':
case 's':
return YES;
}
return NO;
}
+ (BOOL)isFloatingType:(char)c {
return c == 'd'|| c == 'f';
}
+ (const char *)unqualifiedType:(const char *)signature {
return LC32UnqualifiedEncoding(signature);
}
- (const char *)scalarPointerSignature {
const char *pointer = [MethodParameter unqualifiedType:self.signature];
if(!pointer || pointer[0] != '^') return NULL;
const char *pointee = [MethodParameter unqualifiedType:pointer + 1];
if(!pointee || !*pointee || *pointee == 'b') return NULL;
if(![MethodParameter isDirectCastType:*pointee] &&
![MethodParameter isFloatingType:*pointee]) {
return NULL;
}
return pointer;
}
- (char)scalarPointerPointeeEncoding {
const char *pointer = self.scalarPointerSignature;
if(!pointer) return '\0';
const char *pointee = [MethodParameter unqualifiedType:pointer + 1];
return pointee ? *pointee : '\0';
}
- (NSString *)scalarPointerGuestPointeeType {
const char *pointer = self.scalarPointerSignature;
if(!pointer) return nil;
NSString *pointerType =
[MethodParameter readableTypeForSignature:pointer];
if(![pointerType hasSuffix:@" *"]) return nil;
return [pointerType substringToIndex:pointerType.length - 2];
}
- (BOOL)scalarPointerReadsGuestValue {
const char *signature = self.signature;
while(signature && *signature && strchr("rnNoORVA", *signature)) {
if(*signature == 'o') return NO;
signature++;
}
return YES;
}
- (BOOL)scalarPointerWritesGuestValue {
const char *signature = self.signature;
while(signature && *signature && strchr("rnNoORVA", *signature)) {
if(*signature == 'r' || *signature == 'n') return NO;
signature++;
}
return YES;
}
- (const char *)objectOutPointerSignature {
const char *pointer = self.signature;
// Only extend the existing one-object cell to explicit `out` pointers.
// const/in pointers can be arrays, and inout needs its incoming value.
if(pointer && *pointer == 'o') pointer++;
if(!pointer || pointer[0] != '^' ||
(pointer[1] != '@' && pointer[1] != '#')) return NULL;
return pointer;
}
- (instancetype)initWithIndex:(int)index name:(NSString *)name type:(NSString *)type signature:(const char *)signature {
self = [super init];
self.index = index;
self.name = name;
self.type = type;
self.signature = signature;
self.objectArrayCountIndex = -1;
return self;
}
- (BOOL)isCountedObjectArray {
return self.objectArrayCountIndex >= 0;
}
- (NSString *)declarationInMethod {
if ([self.type isEqualToString:@"_NSZone *"]) {
return [NSString stringWithFormat:@"%@:(struct %@)guest_arg%d", self.name, self.type, self.index];
}
return [NSString stringWithFormat:@"%@:(%@)guest_arg%d", self.name, self.type, self.index];
}
- (NSString *)declaration {
if(self.isCountedObjectArray) {
return [NSString stringWithFormat:
@"void *host_arg%1$d = LC32CreateHostObjectArray(guest_arg%1$d, (uint32_t)guest_arg%2$d, %2$d);",
self.index, self.objectArrayCountIndex];
}
if(self.objectOutPointerSignature) {
return [NSString stringWithFormat:@"uint64_t host_arg%d = 0;", self.index];
}
if(LC32EncodingIsOpaqueCFObjectPointer(self.signature)) {
return [NSString stringWithFormat:
@"uint64_t host_arg%1$d = [(__bridge id)guest_arg%1$d host_self];",
self.index];
}
/* Indirect bridge cells are always eight bytes. Match the generator's
* ordinary scalar widening: ARM32 integers use a uint64_t cell and an
* ARM32 `float` (notably CGFloat in captured iOS APIs) uses a native
* double cell. Initialize it before the call because an unqualified
* pointer may be input, output, or both. */
const char scalarPointerPointee =
self.scalarPointerPointeeEncoding;
if(scalarPointerPointee) {
const BOOL floating =
[MethodParameter isFloatingType:scalarPointerPointee];
NSString *hostType = floating ? @"double" : @"uint64_t";
NSString *zero = floating ? @"0.0" : @"0";
if(self.scalarPointerReadsGuestValue) {
return [NSString stringWithFormat:
@"%2$@ host_arg%1$d = guest_arg%1$d ? (%2$@)*guest_arg%1$d : %3$@;",
self.index, hostType, zero];
}
return [NSString stringWithFormat:
@"%2$@ host_arg%1$d = %3$@;",
self.index, hostType, zero];
}
if([MethodParameter isDirectCastType:self.signature[0]]) {
return [NSString stringWithFormat:@"uint64_t host_arg%1$d = (uint64_t)guest_arg%1$d;", self.index];
} else if([MethodParameter isFloatingType:self.signature[0]]) {
return [NSString stringWithFormat:@"double host_arg%1$d = (double)guest_arg%1$d;", self.index];
}
switch(self.signature[0]) {
case '@':
case '#':
return [NSString stringWithFormat:@"uint64_t host_arg%1$d = [guest_arg%1$d host_self];", self.index];
case ':':
return [NSString stringWithFormat:@"uint64_t host_arg%1$d = LC32GetHostSelector(guest_arg%1$d);", self.index];
case '^':
if ([self.type isEqualToString:@"_NSZone *"]) {
return [NSString stringWithFormat:@"uint64_t host_arg%d = 0;", self.index];
}
/* Known CF-style opaque pointers are represented guest-side by
* proxy objects, so pass the proxy's host mirror through. Plain
* structure pointers remain guest buffers. */
if(LC32EncodingIsOpaqueCFObjectPointer(self.signature)) {
return [NSString stringWithFormat:
@"uint64_t host_arg%1$d = [(__bridge id)guest_arg%1$d host_self];",
self.index];
}
// FIXME ???? else if([MethodParameter isFloatingType:self.signature[0]]) {
break;
case 'r': // const
switch(self.signature[1]) {
case '*':
return [NSString stringWithFormat:@"uint64_t host_arg%1$d = LC32GuestToHostCString(guest_arg%1$d, 0);", self.index];
//case 'v':
// return [NSString stringWithFormat:@"uint64_t host_arg%1$d = 0; // FIXME: LC32GuestToHostCBuffer(guest_arg%1$d, length?);", self.index]; // FIXME
}
}
const LC32KnownStruct knownStruct =
LC32KnownStructForEncoding(self.signature);
if(knownStruct == LC32KnownStructNSRange) {
return [NSString stringWithFormat:
@"LC32NSRange64 host_arg%1$d = LC32WidenNSRange(guest_arg%1$d);",
self.index];
}
if(knownStruct != LC32KnownStructNone) {
return [NSString stringWithFormat:@"%1$@_64 host_arg%2$d = LC32Host%1$@(guest_arg%2$d);", self.type, self.index];
//return [NSString stringWithFormat:@"%1$@_64 host_arg%2$d_value = LC32Host%1$@(guest_arg%2$d); uint64_t host_arg%2$d = LC32GuestToHostCString((const char *)&host_arg%2$d_value, sizeof(host_arg%2$d_value));", self.type, self.index];
}
return [NSString stringWithFormat:@"/* %s: unhandled type %@ */", sel_getName(_cmd), self.type];
}
- (NSString *)parameterToBePassed {
if(self.isCountedObjectArray) {
return [NSString stringWithFormat:
@"LC32HostObjectArrayArgument(host_arg%d)", self.index];
}
if(self.objectOutPointerSignature) {
return [NSString stringWithFormat:
@"LC32HostIndirectArgument(guest_arg%1$d ? &host_arg%1$d : NULL)",
self.index];
}
if(LC32EncodingIsOpaqueCFObjectPointer(self.signature)) {
return [NSString stringWithFormat:@"host_arg%d", self.index];
}
if(self.scalarPointerSignature) {
const char scalarPointerPointee =
self.scalarPointerPointeeEncoding;
NSString *helper =
[MethodParameter isFloatingType:scalarPointerPointee]
? @"LC32HostFloatingIndirectArgument"
: @"LC32HostIndirectArgument";
return [NSString stringWithFormat:
@"%2$@(guest_arg%1$d ? &host_arg%1$d : NULL)",
self.index, helper];
}
BOOL returnDirect = NO;
switch(self.signature[0]) {
case '@':
case '#':
case ':':
returnDirect = YES;
break;
case '^':
returnDirect |= [self.type isEqualToString:@"_NSZone *"] ||
LC32EncodingIsOpaqueCFObjectPointer(
self.signature);
break;
case 'r':
// const char *, void too?
returnDirect = self.signature[1] == '*';
break;
default:
returnDirect = [MethodParameter isDirectCastType:self.signature[0]] || [MethodParameter isFloatingType:self.signature[0]];
break;
}
if(LC32KnownStructForEncoding(self.signature) != LC32KnownStructNone) {
return [NSString stringWithFormat:
@"LC32HostAggregateArgument(&host_arg%d)", self.index];
}
if(returnDirect) {
return [NSString stringWithFormat:@"host_arg%d", self.index];
}
return [NSString stringWithFormat:@"/* %s: unhandled type %@ */", sel_getName(_cmd), self.type];
}
- (NSString *)postCall {
if(self.isCountedObjectArray) {
return [NSString stringWithFormat:
@"LC32DestroyHostObjectArray(host_arg%d);", self.index];
}
if(self.objectOutPointerSignature) {
return [NSString stringWithFormat:
@"if(guest_arg%1$d) *guest_arg%1$d = host_arg%1$d ? LC32HostToGuestObject(host_arg%1$d) : nil;",
self.index];
}
if(LC32EncodingIsOpaqueCFObjectPointer(self.signature)) {
return [NSString stringWithFormat:
@"// Opaque CF pointer guest_arg%d needs no copyback",
self.index];
}
if(self.scalarPointerSignature) {
if(!self.scalarPointerWritesGuestValue) {
return [NSString stringWithFormat:
@"// Input-only scalar pointer guest_arg%d needs no copyback",
self.index];
}
NSString *pointeeType =
self.scalarPointerGuestPointeeType;
if(pointeeType) {
return [NSString stringWithFormat:
@"if(guest_arg%1$d) *guest_arg%1$d = (%2$@)host_arg%1$d;",
self.index, pointeeType];
}
}
switch(self.signature[0]) {
case 'r':
switch(self.signature[1]) {
case '*':
// the string might have been copied, in this case invoke back to the host to free them just in case
return [NSString stringWithFormat:@"LC32GuestToHostCStringFree(host_arg%1$d);", self.index];
//default: fallthrough
}
case '*':
// Handle char *modification??
return [NSString stringWithFormat:@"/* %s: unhandled type %@ */", sel_getName(_cmd), self.type];
//case '{':
// return [NSString stringWithFormat:@"LC32GuestToHostCStringFree(host_arg%1$d);", self.index];
case '^':
// handle it below
if(LC32EncodingIsOpaqueCFObjectPointer(self.signature)) {
/* Opaque CF pointer tokens are passed by value; the guest
* proxy owns the underlying host object, so nothing to copy
* back after the call. */
return [NSString stringWithFormat:
@"// Opaque CF pointer guest_arg%d needs no copyback",
self.index];
}
if(![self.type isEqualToString:@"_NSZone *"]) {
break;
}
// NSZone: fallthough
default:
return [NSString stringWithFormat:@"// No post-process for guest_arg%d", self.index];
}
return [NSString stringWithFormat:@"/* %s: unhandled type %@ */", sel_getName(_cmd), self.type];
}
- (NSString *)description {
return self.declarationInMethod;
}
@end
static BOOL LC32SelectorIsInMethodFamily(SEL selector,
const char *family) {
const char *name = selector ? sel_getName(selector) : NULL;
if(!name || !family) return NO;
while(*name == '_') name++;
const size_t length = strlen(family);
if(strncmp(name, family, length) != 0) return NO;
const unsigned char next = (unsigned char)name[length];
return next == '\0' || next < 'a' || next > 'z';
}
static BOOL LC32MethodIsInInitFamily(LC32ObjCMethod *method) {
return method.isInstanceMethod &&
LC32SelectorIsInMethodFamily(method.selector, "init");
}
static BOOL LC32MethodReturnsOwnedResult(NSString *className,
LC32ObjCMethod *method) {
/* Runtime type encodings do not preserve objc_method_family(none).
* ABNewPersonViewController's delegate getter is the one public iOS 10
* SDK API whose family-looking selector explicitly opts out. */
if(method.isInstanceMethod &&
[className isEqualToString:@"ABNewPersonViewController"] &&
[method.selectorString isEqualToString:@"newPersonViewDelegate"]) {
return NO;
}
return LC32SelectorIsInMethodFamily(method.selector, "alloc") ||
LC32SelectorIsInMethodFamily(method.selector, "new") ||
LC32SelectorIsInMethodFamily(method.selector, "copy") ||
LC32SelectorIsInMethodFamily(method.selector, "mutableCopy");
}
static BOOL LC32MethodReturnsNotFoundIndex(NSString *className,
LC32ObjCMethod *method) {
/* NSNotFound is NSIntegerMax, not an all-ones value. Only these public
* scalar index APIs promise that sentinel; a generic integer conversion
* would corrupt counts, hashes, or unrelated methods returning -1. */
const char *encoding = method.returnType;
if(!method.isInstanceMethod || !encoding || !encoding[0] ||
!strchr("iIlL", encoding[0]) || encoding[1] != '\0') return NO;
static const char *const arraySelectors[] = {
"indexOfObject:", "indexOfObject:inRange:",
"indexOfObjectIdenticalTo:", "indexOfObjectIdenticalTo:inRange:",
"indexOfObjectPassingTest:", "indexOfObjectWithOptions:passingTest:",
"indexOfObjectAtIndexes:options:passingTest:",
"indexOfObject:inSortedRange:options:usingComparator:",
};
static const char *const orderedSetSelectors[] = {
"indexOfObject:", "indexOfObjectPassingTest:",
"indexOfObjectWithOptions:passingTest:",
"indexOfObjectAtIndexes:options:passingTest:",
"indexOfObject:inSortedRange:options:usingComparator:",
};
static const char *const indexSetSelectors[] = {
"firstIndex", "lastIndex", "indexGreaterThanIndex:",
"indexLessThanIndex:", "indexGreaterThanOrEqualToIndex:",
"indexLessThanOrEqualToIndex:", "indexPassingTest:",
"indexWithOptions:passingTest:", "indexInRange:options:passingTest:",
};
const char *const *selectors = NULL;
size_t count = 0;
if([className isEqualToString:@"NSArray"]) {
selectors = arraySelectors;
count = sizeof(arraySelectors) / sizeof(*arraySelectors);
} else if([className isEqualToString:@"NSOrderedSet"]) {
selectors = orderedSetSelectors;
count = sizeof(orderedSetSelectors) / sizeof(*orderedSetSelectors);
} else if([className isEqualToString:@"NSIndexSet"]) {
selectors = indexSetSelectors;
count = sizeof(indexSetSelectors) / sizeof(*indexSetSelectors);
}
const char *selector = sel_getName(method.selector);
for(size_t i = 0; i < count; ++i) {
if(!strcmp(selector, selectors[i])) return YES;
}
return NO;
}
@interface MethodBuilder : NSObject
@property(nonatomic, retain) LC32ObjCMethod *method;
@property(nonatomic, retain) NSString *className;
@property(nonatomic, retain) NSString *returnType;
@property(nonatomic, retain) NSMutableArray<MethodParameter *> *parameters;
@property(nonatomic, retain) NSMutableArray<NSString *> *lines;
@property(nonatomic) BOOL disabledByUnhandledType;
@end
@implementation MethodBuilder
- (instancetype)initWithMethod:(LC32ObjCMethod *)method
className:(NSString *)className {
self = [super init];
self.lines = [NSMutableArray new];
self.parameters = [NSMutableArray new];
self.method = method;
self.className = className;
const char *returnType = self.method.returnType;
self.returnType =
[MethodParameter readableTypeForSignature:returnType ? returnType : ""];
SEL selector = method.selector;
NSArray<NSString *> *selectorParameters = [@(sel_getName(selector)) componentsSeparatedByString:@":"];
for(NSUInteger i = 2; i < self.method.numberOfArguments; i++) {
const char *argType = [self.method argumentTypeAtIndex:i];
if(!argType) argType = "?";
NSString *arg = [MethodParameter readableTypeForSignature:argType];
NSUInteger selectorIndex = i - 2;
NSString *name = selectorIndex < selectorParameters.count
? selectorParameters[selectorIndex]
: [NSString stringWithFormat:@"argument%lu", (unsigned long)selectorIndex];
[self.parameters addObject:[[MethodParameter alloc]
initWithIndex:(int)selectorIndex
name:name
type:arg
signature:argType]];
}
/*
* Runtime encodings describe both a one-object out parameter and an
* object buffer as `id *`. Only opt into array staging for a const input
* pointer whose selector also names an explicit integral `count`
* argument. This covers Foundation's counted collection constructors
* and bulk mutators without changing NSError ** or getObjects: buffers.
*/
MethodParameter *countParameter = nil;
for(MethodParameter *param in self.parameters) {
if([param.name isEqualToString:@"count"] &&
(param.signature[0] == 'I' || param.signature[0] == 'L')) {
countParameter = param;
break;
}
}
if(countParameter) {
for(MethodParameter *param in self.parameters) {
const char *signature = param.signature;
if(signature && signature[0] == 'r' &&
signature[1] == '^' && signature[2] == '@') {
param.objectArrayCountIndex = countParameter.index;
}
}
}
// declare method
//[self.lines addObject:[NSString stringWithFormat:@"// %@", self.method.description]];
[self.lines addObject:[NSString stringWithFormat:@"%@ {", self.prettyName]];
// debug: log calls
[self.lines addObject:@" if(LC32ObjCTraceEnabled()) printf(\"DBG: call [%s %s]\\n\", class_getName(self.class), sel_getName(_cmd));"];
// pull host selector
[self.lines addObject:
@" static uint64_t _host_cmd __attribute__((aligned(8)));" ];
[self.lines addObject:[NSString stringWithFormat:
@" uint64_t host_cmd = LC32CachedHostSelector(&_host_cmd, _cmd, %d);",
self.method.returnType[0] == '{']];
// pull host objects
for(MethodParameter *param in self.parameters) {
[self.lines addObject:[NSString stringWithFormat:@" %@", param.declaration]];
}
// perform selector
[self.lines addObject:[NSString stringWithFormat:@" %@", self.callLine]];
// post-call: eg set NSError pointer
for(MethodParameter *param in self.parameters) {
[self.lines addObject:[NSString stringWithFormat:@" %@", param.postCall]];
}
// Return value
[self.lines addObject:[NSString stringWithFormat:@" %@", self.returnLine]];
// End
[self.lines addObject:@"}"];
if([self.description containsString:@"unhandled type"]) {
self.disabledByUnhandledType = YES;
[self.lines insertObject:@"#if 0 // FIXME: has unhandled types" atIndex:0];
[self.lines addObject:@"#endif"];
}
return self;
}
- (NSString *)prettyName {
NSString *methodTypeString = self.method.isInstanceMethod ? @"-" : @"+";
NSString *prettyName = [NSString stringWithFormat:@"%@ (%@)", methodTypeString, self.returnType];
if (self.method.numberOfArguments > 2) {
return [prettyName stringByAppendingString:[self.parameters componentsJoinedByString:@" "]];
} else {
return [prettyName stringByAppendingString:self.method.selectorString];
}
}
- (NSString *)callLine {
NSMutableString *call = [NSMutableString new];
const BOOL returnsBorrowedOpaqueObject =
LC32EncodingIsOpaqueCFObjectPointer(self.method.returnType) &&
!LC32MethodReturnsOwnedResult(self.className, self.method);
const BOOL returnsBorrowedObject =
self.method.returnType[0] == '#' ||
(self.method.returnType[0] == '@' &&
!LC32MethodIsInInitFamily(self.method) &&
!LC32MethodReturnsOwnedResult(self.className, self.method)) ||
returnsBorrowedOpaqueObject;
if(self.method.returnType[0] == 'v') {
[call appendString:@"(void)LC32InvokeHostSelector(self.host_self, host_cmd"];
} else if(self.method.returnType[0] == '{') {
if(LC32KnownStructForEncoding(self.method.returnType) ==
LC32KnownStructNSRange) {
[call appendString:
@"LC32NSRange64 host_ret; LC32InvokeHostSelector(self.host_self, host_cmd, &host_ret, sizeof(host_ret)"];
} else {
[call appendFormat:@"%@_64 host_ret; LC32InvokeHostSelector(self.host_self, host_cmd, &host_ret, sizeof(host_ret)", self.returnType];
}
} else if(returnsBorrowedObject) {
[call appendString:
@"id guest_ret = LC32InvokeHostObjectSelector(self.host_self, host_cmd"];
} else {
[call appendString:
@"uint64_t host_ret = LC32InvokeHostSelector(self.host_self, host_cmd"];
}
for(MethodParameter *param in self.parameters) {
[call appendFormat:@", %@", param.parameterToBePassed];
}
// Add a null last arg
[call appendString:@", (uint64_t)0);"];
return call;
}
- (NSString *)returnLine {
if(LC32MethodReturnsNotFoundIndex(self.className, self.method)) {
return [NSString stringWithFormat:
@"return (%@)(host_ret == INT64_MAX ? INT32_MAX : host_ret);",
self.returnType];
}
switch(self.method.returnType[0]) {
case 'v':
if([self.method.selectorString isEqualToString:@"dealloc"]) {
return @"[super dealloc];";
} else {
return @"// return void";
}
case '@':
if(LC32MethodIsInInitFamily(self.method)) {
return @"return LC32AdoptHostInitializerResult(self, host_ret);";
} else if(LC32MethodReturnsOwnedResult(
self.className, self.method)) {
return @"return LC32HostToGuestOwnedObject(host_ret);";
} else if(self.method.returnType[1] == '?') {
/* Native blocks use their copied guest block's lifetime and
* _Block_copy/_Block_release rather than NSObject custom RR. */
return @"return guest_ret;";
} else {
return @"return LC32ReturnBorrowedGuestObject(guest_ret);";
}
case '#':
return @"return (Class)guest_ret;";
case 'B':
case 'C':
case 'I':
case 'L':
case 'Q':
case 'S':
case 'b':
case 'c':
case 'i':
case 'l':
case 'q':
case 's':
return [NSString stringWithFormat:@"return (%@)host_ret;", self.returnType];
case 'd':
case 'f':
return [NSString stringWithFormat:
@"return (%@)LC32HostFloatingResult(host_ret);",
self.returnType];
}
if(LC32EncodingIsOpaqueCFObjectPointer(self.method.returnType)) {
/* Opaque CF pointers (__SecTrust *, __SecIdentity *, __CFRunLoop *
* etc.) are bridged as guest proxy objects so they can round-trip
* back into host methods as arguments. */
if(LC32MethodReturnsOwnedResult(self.className, self.method)) {
return [NSString stringWithFormat:
@"return (__bridge %@)LC32HostToGuestOwnedObject(host_ret);",
self.returnType];
}
return [NSString stringWithFormat:
@"return (__bridge %@)guest_ret;",
self.returnType];
}
const LC32KnownStruct knownStruct =
LC32KnownStructForEncoding(self.method.returnType);
if(knownStruct == LC32KnownStructNSRange) {
return @"return LC32NarrowNSRange(host_ret);";
}
if(knownStruct != LC32KnownStructNone) {
return [NSString stringWithFormat:@"return LC32Guest%@(host_ret);", self.returnType];
}
return [NSString stringWithFormat:@"/* %s: unhandled type %@ */", sel_getName(_cmd), self.returnType];
}
- (NSString *)description {
NSString *source = [self.lines componentsJoinedByString:@"\n"];
if(!LC32MethodIsInInitFamily(self.method)) return source;
/* Proxy initializers deliberately terminate at the native peer rather
* than chaining through guest self/super, so Clang's body-level
* designated-initializer diagnostic does not describe this ABI. Keep the
* class-level coverage diagnostic visible outside this local scope. */
return [NSString stringWithFormat:
@"#pragma clang diagnostic push\n"
"#pragma clang diagnostic ignored \"-Wobjc-designated-initializers\"\n"
"%@\n"
"#pragma clang diagnostic pop",
source];
}
@end
@interface ClassBuilder : NSObject
@property(nonatomic, retain) NSMutableDictionary<NSString *, id> *methods;
@property(nonatomic, retain) NSString *className;
@property(nonatomic, retain) NSString *imagePath;
@property(nonatomic) BOOL usesRuntimeSignatures;
@property(nonatomic) NSUInteger skippedIncompleteMethods;
@property(nonatomic) NSUInteger skippedFilteredMethods;
@property(nonatomic, readonly) NSUInteger disabledMethods;
- (void)validateAndAddMethod:(LC32ObjCMethod *)method;
- (void)validateAndAddRuntimeMethod:(Method)objcMethod
isInstanceMethod:(BOOL)isInstanceMethod;
@end
static BOOL LC32MethodHasManualAdapter(NSString *className,
LC32ObjCMethod *method) {
NSString *selector = method.selectorString;
if([className isEqualToString:@"NSPropertyListSerialization"] &&
!method.isInstanceMethod) {
// Preserve the CF-backed adapters, including the legacy owned
// errorDescription strings and unchanged format output on failure.
return [selector isEqualToString:@"dataWithPropertyList:format:options:error:"] ||
[selector isEqualToString:@"propertyListWithData:options:format:error:"] ||
[selector isEqualToString:@"dataFromPropertyList:format:errorDescription:"] ||
[selector isEqualToString:@"propertyListFromData:mutabilityOption:format:errorDescription:"];
}
if([className isEqualToString:@"NSArray"]) {
return (!method.isInstanceMethod &&
[selector isEqualToString:@"arrayWithObjects:"]) ||
(method.isInstanceMethod &&
[selector isEqualToString:@"initWithObjects:"]);
}
if([className isEqualToString:@"NSSet"]) {
return (!method.isInstanceMethod &&
[selector isEqualToString:@"setWithObjects:"]) ||
(method.isInstanceMethod &&
[selector isEqualToString:@"initWithObjects:"]);
}
if([className isEqualToString:@"NSOrderedSet"]) {
return (!method.isInstanceMethod &&
[selector isEqualToString:@"orderedSetWithObjects:"]) ||
(method.isInstanceMethod &&
[selector isEqualToString:@"initWithObjects:"]);
}
if([className isEqualToString:@"NSDictionary"]) {
return (!method.isInstanceMethod && [selector
isEqualToString:@"dictionaryWithObjectsAndKeys:"]) ||
(method.isInstanceMethod && [selector
isEqualToString:@"initWithObjectsAndKeys:"]);
}
if([className isEqualToString:@"NSScanner"]) {
return method.isInstanceMethod &&
[selector isEqualToString:@"scanDecimal:"];
}
if([className isEqualToString:@"NSDecimalNumber"]) {
return (!method.isInstanceMethod &&
[selector isEqualToString:@"decimalNumberWithDecimal:"]) ||
(method.isInstanceMethod &&
[selector isEqualToString:@"initWithDecimal:"]);
}
if([className isEqualToString:@"NSException"] &&
!method.isInstanceMethod) {
return [selector isEqualToString:@"raise:format:"] ||
[selector isEqualToString:@"raise:format:arguments:"];
}
if([className isEqualToString:@"NSString"]) {
if(!method.isInstanceMethod) {
return [selector isEqualToString:@"stringWithFormat:"] ||
[selector isEqualToString:@"stringWithFormat:locale:"] ||
[selector isEqualToString:@"localizedStringWithFormat:"] ||
[selector isEqualToString:
@"stringWithBytes:length:encoding:"];
}
return [selector isEqualToString:@"UTF8String"] ||
[selector isEqualToString:@"getCharacters:"] ||
[selector isEqualToString:@"getCharacters:range:"] ||
[selector isEqualToString:
@"getBytes:maxLength:filledLength:encoding:allowLossyConversion:range:remainingRange:"] ||
[selector isEqualToString:
@"getBytes:maxLength:usedLength:encoding:options:range:remainingRange:"] ||
[selector isEqualToString:
@"initWithBytes:length:encoding:"] ||
[selector isEqualToString:
@"initWithBytesNoCopy:length:encoding:freeWhenDone:"] ||
[selector isEqualToString:@"initWithFormat:"] ||
[selector isEqualToString:@"initWithFormat:arguments:"] ||
[selector isEqualToString:@"initWithFormat:locale:"] ||
[selector isEqualToString:
@"initWithFormat:locale:arguments:"] ||
[selector isEqualToString:@"rangeOfString:"] ||
[selector isEqualToString:@"rangeOfString:options:"] ||
[selector isEqualToString:
@"rangeOfString:options:range:"] ||
[selector isEqualToString:
@"rangeOfString:options:range:locale:"] ||
[selector isEqualToString:@"stringByAppendingFormat:"];
}
if([className isEqualToString:@"NSData"] && method.isInstanceMethod) {
return [selector isEqualToString:@"bytes"] ||
[selector isEqualToString:@"getBytes:"] ||
[selector isEqualToString:@"getBytes:length:"] ||
[selector isEqualToString:@"getBytes:range:"] ||
[selector isEqualToString:@"subdataWithRange:"] ||
/* r^v/^v byte buffers: native Foundation cannot dereference
* an ARM32 address, so the guest adapter copies through the
* guest-memory bridge before initializing. */
[selector isEqualToString:@"initWithBytes:length:"] ||
[selector isEqualToString:
@"initWithBytesNoCopy:length:"] ||
[selector isEqualToString:
@"initWithBytesNoCopy:length:freeWhenDone:"];
}
if([className isEqualToString:@"NSMutableData"]) {
if(!method.isInstanceMethod) {
return [selector isEqualToString:@"dataWithCapacity:"];
}
return [selector isEqualToString:@"initWithCapacity:"] ||
[selector isEqualToString:@"mutableBytes"] ||
[selector isEqualToString:@"appendData:"] ||
[selector isEqualToString:@"increaseLengthBy:"] ||
[selector isEqualToString:@"resetBytesInRange:"] ||
[selector isEqualToString:@"setData:"] ||
[selector isEqualToString:@"setLength:"];
}
if([className isEqualToString:@"NSValue"]) {
if(!method.isInstanceMethod) {
return [selector isEqualToString:
@"valueWithBytes:objCType:"] ||
[selector isEqualToString:@"value:withObjCType:"] ||
[selector isEqualToString:@"valueWithPointer:"];
}
return [selector isEqualToString:@"getValue:"] ||
[selector isEqualToString:@"objCType"] ||
[selector isEqualToString:@"pointerValue"];
}
if(method.isInstanceMethod && [selector isEqualToString:
@"countByEnumeratingWithState:objects:count:"]) {
return [className isEqualToString:@"NSArray"] ||
[className isEqualToString:@"NSDictionary"] ||
[className isEqualToString:@"NSEnumerator"] ||
[className isEqualToString:@"NSOrderedSet"] ||
[className isEqualToString:@"NSSet"];
}
if([className isEqualToString:@"UIView"] &&
!method.isInstanceMethod &&
[selector isEqualToString:@"beginAnimations:context:"]) {
return YES;
}
if([className isEqualToString:@"NSPredicate"] &&
!method.isInstanceMethod &&
[selector isEqualToString:@"predicateWithFormat:"]) {
return YES;
}
if([className isEqualToString:@"NSNotificationCenter"] &&
method.isInstanceMethod &&
[selector isEqualToString:
@"addObserverForName:object:queue:usingBlock:"]) {
/* Some legacy Apple LLVM compilers set BLOCK_HAS_SIGNATURE while
* leaving the descriptor's signature pointer null. The manual
* adapter gives this callback a modern, typed wrapper before it
* crosses the guest/host block bridge. */
return YES;
}
if([className isEqualToString:@"UIApplication"] &&
method.isInstanceMethod &&
([selector isEqualToString:
@"beginBackgroundTaskWithExpirationHandler:"] ||
[selector isEqualToString:
@"beginBackgroundTaskWithName:expirationHandler:"] ||
[selector isEqualToString:@"endBackgroundTask:"])) {
/* Legacy Apple LLVM can likewise omit the advertised signature for
* this API's void(void) expiration callback. Its manual adapter
* wraps that callback in a block whose ABI is known to LC32 and
* balances expired tasks left open by legacy clients. */
return YES;
}
if([className isEqualToString:@"NSBundle"]) {
if(!method.isInstanceMethod &&
[selector isEqualToString:@"mainBundle"]) {
return YES;
}
if(!method.isInstanceMethod &&
[selector isEqualToString:
@"preferredLocalizationsFromArray:"]) {
/* Keep Foundation's old PopCap/iOS 6 locale fallback alongside
* the manual main-bundle compatibility adapter. */
return YES;
}
if(method.isInstanceMethod &&
[selector isEqualToString:@"pathForResource:ofType:"]) {
/* iOS Foundation had a PopCap/iOS 6 compatibility path for an
* empty resource lookup which modern Foundation removed. */
return YES;
}
}
if([className isEqualToString:@"GKLocalPlayer"] &&
method.isInstanceMethod &&
([selector isEqualToString:@"setAuthenticateHandler:"] ||
[selector isEqualToString:@"isAuthenticated"] ||
[selector isEqualToString:
@"authenticateWithCompletionHandler:"] ||
[selector isEqualToString:
@"loadDefaultLeaderboardCategoryIDWithCompletionHandler:"] ||
[selector isEqualToString:
@"loadDefaultLeaderboardIdentifierWithCompletionHandler:"])) {
return YES;
}
if(method.isInstanceMethod &&
(([className isEqualToString:@"GKAchievement"] &&
[selector isEqualToString: