@import Darwin; @import QuartzCore; @import CoreFoundation; @import Foundation; @import UIKit; @import ObjectiveC; #import "ObjCMethod.h" #include typedef NS_ENUM(NSUInteger, LC32KnownStruct) { LC32KnownStructNone, LC32KnownStructCMTime, LC32KnownStructCMTimeRange, 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; // CoreMedia's opaque CF types do not use the __CF naming convention. // Keep this explicit: other opaque structures may be raw guest memory. if(!strcmp(encoding, "^{opaqueCMSampleBuffer=}") || !strcmp(encoding, "^{opaqueCMFormatDescription=}")) 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++; // Old SDKs encode these typedefs anonymously. All fields have fixed // widths, so the 24/48-byte layouts are identical on ARM32 and ARM64. if(!strcmp(encoding, "{?=qiIq}") || !strcmp(encoding, "{CMTime=qiIq}")) return LC32KnownStructCMTime; if(!strcmp(encoding, "{?={?=qiIq}{?=qiIq}}") || !strcmp(encoding, "{CMTimeRange={CMTime=qiIq}{CMTime=qiIq}}")) return LC32KnownStructCMTimeRange; 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; } static BOOL LC32KnownStructHasFixedLayout(LC32KnownStruct type) { return type == LC32KnownStructCMTime || type == LC32KnownStructCMTimeRange; } @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 @"?"; const LC32KnownStruct knownStruct = LC32KnownStructForEncoding(signature); if(knownStruct == LC32KnownStructCMTime) return @"CMTime"; if(knownStruct == LC32KnownStructCMTimeRange) return @"CMTimeRange"; 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(LC32KnownStructHasFixedLayout(knownStruct)) { return [NSString stringWithFormat:@"%1$@ host_arg%2$d = guest_arg%2$d;", self.type, self.index]; } 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 *parameters; @property(nonatomic, retain) NSMutableArray *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 *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(LC32KnownStructHasFixedLayout( LC32KnownStructForEncoding(self.method.returnType))) { [call appendFormat:@"%@ host_ret = {0}; LC32InvokeHostSelector(self.host_self, host_cmd, &host_ret, sizeof(host_ret)", self.returnType]; } else 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(LC32KnownStructHasFixedLayout(knownStruct)) return @"return host_ret;"; 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 *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:@"AVAssetImageGenerator"] && method.isInstanceMethod && [selector isEqualToString:@"copyCGImageAtTime:actualTime:error:"]) { // The CMTime pointer is one synchronous output, not an arbitrary // struct array. Its manual adapter supplies bounded native storage. return YES; } 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: @"reportAchievementWithCompletionHandler:"]) || ([className isEqualToString:@"GKMatchmaker"] && [selector isEqualToString:@"setInviteHandler:"]) || ([className isEqualToString:@"GKVoiceChat"] && [selector isEqualToString: @"setPlayerStateUpdateHandler:"]))) { /* A few GameKit callbacks in early games use the same null-signature * block descriptor as their notification observers. Their public * APIs define the missing callback ABI, so manual adapters can wrap * them in current-compiler blocks before native GameKit sees them. */ return YES; } if(method.isInstanceMethod && (([className isEqualToString:@"UIImage"] && [selector isEqualToString:@"CGImage"]) || ([className isEqualToString:@"UIScreen"] && ([selector isEqualToString:@"bounds"] || [selector isEqualToString:@"applicationFrame"] || [selector isEqualToString:@"scale"])) || ([className isEqualToString:@"UIWebView"] && [selector isEqualToString:@"loadRequest:"]) || ([className isEqualToString:@"UIWindow"] && ([selector isEqualToString:@"rootViewController"] || [selector isEqualToString:@"setRootViewController:"])) || ([className isEqualToString:@"UIDevice"] && [selector isEqualToString:@"userInterfaceIdiom"]))) { return YES; } if([className isEqualToString:@"UIImage"] && !method.isInstanceMethod && ([selector isEqualToString:@"imageNamed:"] || [selector isEqualToString:@"imageWithCGImage:"] || [selector isEqualToString:@"imageWithCGImage:scale:orientation:"])) { return YES; } /* Every captured status-bar orientation setter has a manual guest adapter * that records the intent for the host scene compatibility layer before * preserving the native call. Do not also emit a generated implementation * that can bypass it. Native selector availability is unchanged. */ if([className isEqualToString:@"UIApplication"] && method.isInstanceMethod && ([selector isEqualToString:@"setStatusBarOrientation:"] || [selector isEqualToString: @"setStatusBarOrientation:animated:"] || [selector isEqualToString: @"setStatusBarOrientation:animation:duration:"] || [selector isEqualToString: @"setStatusBarOrientation:animationParameters:"] || [selector isEqualToString: @"setStatusBarOrientation:animationParameters:notifySpringBoardAndFence:"] || [selector isEqualToString: @"setStatusBarOrientation:animationParameters:notifySpringBoardAndFence:updateBlock:"])) { return YES; } /* UIDevice uniqueIdentifier was removed from the host SDK (iOS 7), so * forwarding to the host UIDevice raises NSInvalidArgumentException. * The guest adapter fabricates a stable legacy identifier instead. */ if([className isEqualToString:@"UIDevice"] && method.isInstanceMethod && [selector isEqualToString:@"uniqueIdentifier"]) { return YES; } return [className isEqualToString:@"NSMutableString"] && method.isInstanceMethod && ([selector isEqualToString:@"appendFormat:"] || [selector isEqualToString:@"deleteCharactersInRange:"] || [selector isEqualToString: @"replaceCharactersInRange:withString:"] || [selector isEqualToString: @"replaceOccurrencesOfString:withString:options:range:"]); } static BOOL LC32MethodHasIndirectObjectBuffer(NSString *className, LC32ObjCMethod *method) { NSString *selector = method.selectorString; if(method.isInstanceMethod && ([selector hasPrefix:@"getObjects:"] || [selector hasPrefix:@"getKeys:"])) { return [className isEqualToString:@"NSArray"] || [className isEqualToString:@"NSCountedSet"] || [className isEqualToString:@"NSDictionary"] || [className isEqualToString:@"NSOrderedSet"] || [className isEqualToString:@"NSSet"]; } return !method.isInstanceMethod && [className isEqualToString:@"NSManagedObject"] && [selector isEqualToString:@"allocBatch:withEntity:count:"]; } @implementation ClassBuilder - (NSUInteger)disabledMethods { NSUInteger count = 0; for(id method in self.methods.allValues) { if([method isKindOfClass:MethodBuilder.class] && [(MethodBuilder *)method disabledByUnhandledType]) count++; } return count; } - (instancetype)initWithClass:(Class)cls imagePath:(NSString *)imagePath { self = [super init]; if(!self || !cls) return nil; self.className = NSStringFromClass(cls); self.imagePath = imagePath; self.usesRuntimeSignatures = YES; self.methods = [NSMutableDictionary new]; unsigned int mc = 0; Method *mlist; mlist = class_copyMethodList(object_getClass(cls), &mc); for(unsigned int m = 0; m < mc; m++) { [self validateAndAddRuntimeMethod:mlist[m] isInstanceMethod:NO]; } free(mlist); mlist = class_copyMethodList(cls, &mc); for(unsigned int m = 0; m < mc; m++) { [self validateAndAddRuntimeMethod:mlist[m] isInstanceMethod:YES]; } free(mlist); return self; } - (instancetype)initWithClassName:(NSString *)className imagePath:(NSString *)imagePath methodSignatures:(NSDictionary *)dict { self = [super init]; if(!self) return nil; self.className = className; self.imagePath = imagePath; if([imagePath.lastPathComponent isEqualToString:@"OpenGLES"]) { self.imagePath = @"GLKit"; } self.methods = [NSMutableDictionary new]; for(NSString *kind in @[@"+", @"-"]) { NSDictionary *methods = dict[kind]; BOOL isInstanceMethod = [kind isEqualToString:@"-"]; for(NSString *selectorName in [methods.allKeys sortedArrayUsingSelector:@selector(compare:)]) { NSString *typeEncoding = methods[selectorName]; LC32ObjCMethod *method = [LC32ObjCMethod methodWithSelector:NSSelectorFromString(selectorName) typeEncoding:typeEncoding.UTF8String isInstanceMethod:isInstanceMethod]; [self validateAndAddMethod:method]; } } return self; } - (void)validateAndAddRuntimeMethod:(Method)objcMethod isInstanceMethod:(BOOL)isInstanceMethod { [self validateAndAddMethod:[LC32ObjCMethod method:objcMethod isInstanceMethod:isInstanceMethod]]; } - (void)validateAndAddMethod:(LC32ObjCMethod *)method { if(!method) { self.skippedIncompleteMethods++; return; } const char *selectorName = sel_getName(method.selector); if(LC32MethodHasManualAdapter(self.className, method)) { // These methods need ABI-aware hand-written adapters (for example an // ARMv7 va_list, guest-owned buffer, or opaque pointer token). self.skippedFilteredMethods++; return; } else if(LC32MethodHasIndirectObjectBuffer(self.className, method)) { // Runtime type encodings only say `id *`; they do not distinguish a // one-object out parameter from a caller-provided object array. The // generic indirect bridge owns one native pointer cell, so buffer // APIs need a manual adapter with an explicit element count. self.skippedFilteredMethods++; return; } else if(strchr(selectorName, '_') != NULL) { // this is a private API, skip self.skippedFilteredMethods++; return; } else if(!strcmp(selectorName, "allocWithZone:")) { // skip alloc self.skippedFilteredMethods++; return; } else if(!method.isInstanceMethod && !strcmp(selectorName, "load")) { /* * The native dyld invokes +load while loading the host framework. * Forwarding it from the guest is both redundant and unsafe: guest * libobjc may call +load before this image's C constructors have had * a chance to load an optional native framework. */ self.skippedFilteredMethods++; return; } else if(!strcmp(selectorName, "dealloc") || !strcmp(selectorName, "autorelease") || !strcmp(selectorName, "release") || !strcmp(selectorName, "retain") || !strcmp(selectorName, "retainCount")) { // skip ARC methods self.skippedFilteredMethods++; return; } if(!method.hasCompleteTypeEncoding) { fprintf(stderr, "Skipping incomplete encoding: %s %s\n", self.className.UTF8String, selectorName); self.skippedIncompleteMethods++; return; } NSString *methodKey = [NSString stringWithFormat:@"%@%s", method.isInstanceMethod ? @"-" : @"+", selectorName]; if(!method.isInstanceMethod && sel_isEqual(method.selector, @selector(initialize))) { // For +(void)initialize, we must first obtain the host class pointer NSMutableString *string = [NSMutableString new]; [string appendFormat:@"%@ {\n", method.description]; //[string appendString:@" self.host_self = LC32GetHostClass(class_getName(self.class));\n"]; [string appendFormat:@"}"]; self.methods[methodKey] = string; return; } self.methods[methodKey] = [[MethodBuilder alloc] initWithMethod:method className:self.className]; } - (NSString *)description { NSMutableString *string = [NSMutableString new]; [string appendString:@"// Generated file\n"]; if(self.usesRuntimeSignatures) { [string appendString:@"// WARNING: types came from the current 64-bit host runtime; audit width-dependent types before using this shim.\n"]; } [string appendFormat:@"#if __has_include(<%1$@/%1$@+LC32.h>)\n", self.imagePath.lastPathComponent]; [string appendFormat:@"#import <%1$@/%1$@+LC32.h>\n", self.imagePath.lastPathComponent]; [string appendFormat:@"#else\n"]; [string appendFormat:@"#import <%1$@/%1$@.h>\n", self.imagePath.lastPathComponent]; [string appendFormat:@"#endif\n"]; [string appendFormat:@"#import \n"]; [string appendString:@"#import \n"]; [string appendFormat:@"#import \n"]; [string appendFormat:@"#import \n"]; [string appendString: @"// Proxy methods intentionally forward across an ABI boundary; " "source-level noescape and guest self/super checks do not apply.\n" "#pragma clang diagnostic push\n" "#pragma clang diagnostic ignored \"-Wmissing-noescape\"\n" "#pragma clang diagnostic ignored \"-Wobjc-missing-super-calls\"\n"]; if(!self.usesRuntimeSignatures) { /* Captured ARM32 encodings are authoritative, but do not retain every * typedef, object specialization, or block spelling from the SDK. * Runtime-derived UIKit extras stay unsuppressed because their * width-dependent mismatches require an ABI audit. */ [string appendString: @"#pragma clang diagnostic ignored \"-Wmismatched-parameter-types\"\n" "#pragma clang diagnostic ignored \"-Wmismatched-return-types\"\n"]; } [string appendFormat:@"@implementation %@\n", self.className]; if([self.className isEqualToString:@"NSData"]) { // NSData.h declares bytes as a property. Once its generated method is // filtered for the manual guest-copy adapter, Clang would otherwise // synthesize a zero-filled guest ivar and a competing -bytes getter. [string appendString:@"@dynamic bytes;\n"]; } if([self.className isEqualToString:@"NSValue"]) { // The raw-value adapter supplies an ABI-aware getter. Suppress the // property-backed guest getter/ivar that would otherwise compete // with the manual category implementation. [string appendString:@"@dynamic objCType;\n"]; } /* Filtering a manual property adapter's accessor is not enough: Clang * otherwise synthesizes a guest ivar and replacement accessor in the * primary class. Declare those SDK properties dynamic so the category is * the sole implementation. */ if([self.className isEqualToString:@"NSMutableData"]) { [string appendString:@"@dynamic mutableBytes;\n"]; } if([self.className isEqualToString:@"GKLocalPlayer"]) { [string appendString:@"@dynamic authenticateHandler, authenticated;\n"]; } if([self.className isEqualToString:@"UIImage"]) { [string appendString:@"@dynamic CGImage;\n"]; } if([self.className isEqualToString:@"UIScreen"]) { [string appendString:@"@dynamic bounds, applicationFrame, scale;\n"]; } if([self.className isEqualToString:@"UIWindow"]) { [string appendString:@"@dynamic rootViewController;\n"]; } if([self.className isEqualToString:@"UIDevice"]) { [string appendString:@"@dynamic userInterfaceIdiom;\n"]; } NSArray *methodKeys = [self.methods.allKeys sortedArrayUsingSelector:@selector(compare:)]; NSMutableArray *methodSources = [NSMutableArray arrayWithCapacity:methodKeys.count]; for(NSString *methodKey in methodKeys) { [methodSources addObject:[self.methods[methodKey] description]]; } [string appendString:[methodSources componentsJoinedByString:@"\n\n"]]; [string appendString:@"\n"]; [string appendString:@"@end\n"]; [string appendString:@"#pragma clang diagnostic pop"]; return string; } @end static BOOL LC32CreateEmptyOutputDirectory(NSString *outputPath, NSError **error) { NSFileManager *fileManager = NSFileManager.defaultManager; BOOL isDirectory = NO; if([fileManager fileExistsAtPath:outputPath isDirectory:&isDirectory]) { if(!isDirectory) { if(error) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteFileExistsError userInfo:@{ NSLocalizedDescriptionKey: @"Output path exists and is not a directory" }]; } return NO; } NSArray *contents = [fileManager contentsOfDirectoryAtPath:outputPath error:error]; if(!contents) return NO; if(contents.count != 0) { if(error) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteFileExistsError userInfo:@{ NSLocalizedDescriptionKey: @"Output directory must be empty" }]; } return NO; } return YES; } return [fileManager createDirectoryAtPath:outputPath withIntermediateDirectories:YES attributes:nil error:error]; } static BOOL LC32IsSafePathComponent(NSString *component) { if(![component isKindOfClass:NSString.class] || component.length == 0) { return NO; } if([component isEqualToString:@"."] || [component isEqualToString:@".."]) { return NO; } return [component rangeOfString:@"/"].location == NSNotFound; } static BOOL LC32SetValidationError(NSError **error, NSString *description) { if(error) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadCorruptFileError userInfo:@{ NSLocalizedDescriptionKey: description }]; } return NO; } static BOOL LC32ValidateSignaturesPlist(NSDictionary *frameworks, NSError **error) { for(id frameworkName in frameworks) { if(!LC32IsSafePathComponent(frameworkName)) { return LC32SetValidationError(error, [NSString stringWithFormat: @"Invalid framework path component: %@", frameworkName]); } id classes = frameworks[frameworkName]; if(![classes isKindOfClass:NSDictionary.class]) { return LC32SetValidationError(error, [NSString stringWithFormat: @"Framework %@ is not a dictionary", frameworkName]); } for(id className in classes) { if(!LC32IsSafePathComponent(className)) { return LC32SetValidationError(error, [NSString stringWithFormat: @"Invalid class path component: %@/%@", frameworkName, className]); } id methodKinds = classes[className]; if(![methodKinds isKindOfClass:NSDictionary.class]) { return LC32SetValidationError(error, [NSString stringWithFormat: @"Class %@/%@ is not a dictionary", frameworkName, className]); } for(id kind in methodKinds) { if(![kind isKindOfClass:NSString.class] || (![(NSString *)kind isEqualToString:@"+"] && ![(NSString *)kind isEqualToString:@"-"])) { return LC32SetValidationError(error, [NSString stringWithFormat: @"Invalid method kind for %@/%@: %@", frameworkName, className, kind]); } id methods = methodKinds[kind]; if(![methods isKindOfClass:NSDictionary.class]) { return LC32SetValidationError(error, [NSString stringWithFormat: @"Method kind %@ for %@/%@ is not a dictionary", kind, frameworkName, className]); } for(id selectorName in methods) { id typeEncoding = methods[selectorName]; if(![selectorName isKindOfClass:NSString.class] || [(NSString *)selectorName length] == 0 || ![typeEncoding isKindOfClass:NSString.class] || [(NSString *)typeEncoding length] == 0) { return LC32SetValidationError(error, [NSString stringWithFormat: @"Invalid method entry for %@/%@: %@", frameworkName, className, selectorName]); } } } } } return YES; } static BOOL LC32ValidateFrameworkMap(NSDictionary *frameworkMap, NSDictionary *frameworks, NSError **error) { for(id sourceKey in frameworkMap) { id destinationFramework = frameworkMap[sourceKey]; if(![sourceKey isKindOfClass:NSString.class] || ![destinationFramework isKindOfClass:NSString.class]) { return LC32SetValidationError(error, @"Framework map keys and values must be strings"); } NSArray *sourceComponents = [(NSString *)sourceKey componentsSeparatedByString:@"/"]; if(sourceComponents.count != 2 || !LC32IsSafePathComponent(sourceComponents[0]) || !LC32IsSafePathComponent(sourceComponents[1])) { return LC32SetValidationError(error, [NSString stringWithFormat: @"Invalid framework map source: %@", sourceKey]); } NSString *sourceFramework = sourceComponents[0]; NSString *sourceClass = sourceComponents[1]; NSDictionary *classes = frameworks[sourceFramework]; if(![classes isKindOfClass:NSDictionary.class] || !classes[sourceClass]) { return LC32SetValidationError(error, [NSString stringWithFormat: @"Framework map source is not in the signatures plist: %@", sourceKey]); } if(![(NSString *)destinationFramework isEqualToString:@"-"] && !LC32IsSafePathComponent(destinationFramework)) { return LC32SetValidationError(error, [NSString stringWithFormat: @"Invalid destination framework for %@: %@", sourceKey, destinationFramework]); } } // Resolve every class before creating the output directory so a routing // collision fails without leaving a partially generated source tree. NSMutableDictionary *outputOwners = [NSMutableDictionary new]; for(NSString *sourceFramework in frameworks) { NSDictionary *classes = frameworks[sourceFramework]; for(NSString *sourceClass in classes) { NSString *sourceKey = [NSString stringWithFormat:@"%@/%@", sourceFramework, sourceClass]; NSString *destinationFramework = frameworkMap[sourceKey]; if([destinationFramework isEqualToString:@"-"]) continue; if(!destinationFramework) destinationFramework = sourceFramework; NSString *outputKey = [NSString stringWithFormat:@"%@/%@", destinationFramework, sourceClass]; NSString *existingOwner = outputOwners[outputKey]; if(existingOwner) { return LC32SetValidationError(error, [NSString stringWithFormat: @"Framework map collision at %@ between %@ and %@", outputKey, existingOwner, sourceKey]); } outputOwners[outputKey] = sourceKey; } } return YES; } static BOOL LC32WriteClass(ClassBuilder *classBuilder, NSString *outputPath, NSError **error) { NSString *fileName = [classBuilder.className stringByAppendingPathExtension:@"m"]; NSString *filePath = [outputPath stringByAppendingPathComponent:fileName]; return [classBuilder.description writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:error]; } typedef struct { NSUInteger generated; NSUInteger unavailable; NSUInteger failures; NSUInteger disabledMethods; } LC32RuntimeGenerationResult; static LC32RuntimeGenerationResult LC32GenerateRuntimeUIKitExtras(NSString *outputRoot, NSDictionary *frameworks) { LC32RuntimeGenerationResult result = {0}; NSString *uikitPath = @"/System/Library/Frameworks/UIKit.framework/UIKit"; NSArray *classes = @[ @"_UIAppearance", @"UIDynamicSystemColor", @"UIDynamicColor", @"UILayoutContainerView", @"UICachedDeviceWhiteColor", @"UIDeviceWhiteColor", @"UIDeviceRGBColor", @"UITableViewCellLayoutManager", @"_UIMoreListTableView", @"UIMoreListCellLayoutManager", @"UIMoreListController", @"UIMoreNavigationController", @"UINibDecoder" ]; NSString *outputPath = [outputRoot stringByAppendingPathComponent:@"UIKit"]; NSError *error = nil; if(![NSFileManager.defaultManager createDirectoryAtPath:outputPath withIntermediateDirectories:YES attributes:nil error:&error]) { fprintf(stderr, "Could not create %s: %s\n", outputPath.UTF8String, error.localizedDescription.UTF8String); result.failures++; return result; } for(NSString *className in classes) { NSString *fileName = [className stringByAppendingPathExtension:@"m"]; NSString *filePath = [outputPath stringByAppendingPathComponent:fileName]; if([NSFileManager.defaultManager fileExistsAtPath:filePath]) { fprintf(stderr, "Keeping captured UIKit class instead of runtime class: %s\n", className.UTF8String); continue; } Class cls = NSClassFromString(className); if(!cls) { fprintf(stderr, "Runtime UIKit class not found: %s\n", className.UTF8String); result.unavailable++; continue; } ClassBuilder *classBuilder = [[ClassBuilder alloc] initWithClass:cls imagePath:uikitPath]; if([className isEqualToString:@"_UIAppearance"]) { /* * The iOS 10 guest runtime has no Foundation message-forward * handler installed, so merely mirroring _UIAppearance's * -methodSignatureForSelector:/-forwardInvocation: pair cannot * receive an otherwise unknown appearance selector. Install * the typed public declarations used by legacy navigation-bar * appearance proxies directly on the private guest mirror. Use * the captured iOS 10 signatures rather than current host UIKit * metadata: UIBarMetrics and UIControlState are 32-bit in the * ARMv7 ABI but NSInteger/NSUInteger are 64-bit on the host. */ NSDictionary *appearanceMethods = @{ @"setBackgroundImage:forBarMetrics:": @"UINavigationBar", @"setBackButtonBackgroundImage:forState:barMetrics:": @"UIBarButtonItem", @"setBackgroundImage:forState:barMetrics:": @"UIBarButtonItem", }; for(NSString *selectorName in [appearanceMethods.allKeys sortedArrayUsingSelector:@selector(compare:)]) { NSString *declaringClass = appearanceMethods[selectorName]; NSString *typeEncoding = frameworks[@"UIKit"][declaringClass][@"-"][selectorName]; if(![typeEncoding isKindOfClass:NSString.class] || typeEncoding.length == 0) { fprintf(stderr, "Captured UIKit appearance method not found: %s/%s\n", declaringClass.UTF8String, selectorName.UTF8String); result.failures++; continue; } LC32ObjCMethod *method = [LC32ObjCMethod methodWithSelector:NSSelectorFromString(selectorName) typeEncoding:typeEncoding.UTF8String isInstanceMethod:YES]; [classBuilder validateAndAddMethod:method]; } } error = nil; if(!LC32WriteClass(classBuilder, outputPath, &error)) { fprintf(stderr, "Could not write runtime class %s: %s\n", className.UTF8String, error.localizedDescription.UTF8String); result.failures++; continue; } result.generated++; result.disabledMethods += classBuilder.disabledMethods; } return result; } int main(int argc, char **argv) { @autoreleasepool { BOOL includeRuntimeUIKit = NO; NSString *frameworkMapPath = nil; BOOL invalidArguments = argc < 3; for(int argumentIndex = 3; !invalidArguments && argumentIndex < argc; argumentIndex++) { if(strcmp(argv[argumentIndex], "--runtime-uikit") == 0) { if(includeRuntimeUIKit) { invalidArguments = YES; } else { includeRuntimeUIKit = YES; } } else if(strcmp(argv[argumentIndex], "--framework-map") == 0) { if(frameworkMapPath || argumentIndex + 1 >= argc) { invalidArguments = YES; } else { frameworkMapPath = [@(argv[++argumentIndex]) stringByStandardizingPath]; } } else { invalidArguments = YES; } } if(invalidArguments) { fprintf(stderr, "Usage: %s INPUT_PLIST EMPTY_OUTPUT_DIRECTORY " "[--framework-map PATH] [--runtime-uikit]\n", argv[0]); return 2; } NSString *inputPath = [@(argv[1]) stringByStandardizingPath]; NSString *outputRoot = [@(argv[2]) stringByStandardizingPath]; NSDictionary *frameworks = [NSDictionary dictionaryWithContentsOfFile:inputPath]; if(![frameworks isKindOfClass:NSDictionary.class]) { fprintf(stderr, "Could not read signatures plist: %s\n", inputPath.UTF8String); return 1; } NSError *error = nil; if(!LC32ValidateSignaturesPlist(frameworks, &error)) { fprintf(stderr, "Invalid signatures plist %s: %s\n", inputPath.UTF8String, error.localizedDescription.UTF8String); return 1; } NSDictionary *frameworkMap = @{}; if(frameworkMapPath) { frameworkMap = [NSDictionary dictionaryWithContentsOfFile:frameworkMapPath]; if(![frameworkMap isKindOfClass:NSDictionary.class]) { fprintf(stderr, "Could not read framework map plist: %s\n", frameworkMapPath.UTF8String); return 1; } } if(!LC32ValidateFrameworkMap(frameworkMap, frameworks, &error)) { fprintf(stderr, "Invalid framework map%s%s: %s\n", frameworkMapPath ? " " : "", frameworkMapPath ? frameworkMapPath.UTF8String : "", error.localizedDescription.UTF8String); return 1; } if(!LC32CreateEmptyOutputDirectory(outputRoot, &error)) { fprintf(stderr, "Could not use output directory %s: %s\n", outputRoot.UTF8String, error.localizedDescription.UTF8String); return 1; } NSUInteger frameworkCount = 0; NSUInteger classCount = 0; NSUInteger methodCount = 0; NSUInteger skippedIncompleteMethods = 0; NSUInteger skippedFilteredMethods = 0; NSUInteger disabledMethods = 0; NSUInteger writeFailureCount = 0; NSMutableSet *createdFrameworks = [NSMutableSet new]; NSArray *frameworkNames = [frameworks.allKeys sortedArrayUsingSelector:@selector(compare:)]; for(NSString *frameworkName in frameworkNames) { NSDictionary *classes = frameworks[frameworkName]; if(![classes isKindOfClass:NSDictionary.class]) { fprintf(stderr, "Invalid framework entry: %s\n", frameworkName.UTF8String); writeFailureCount++; continue; } NSArray *classNames = [classes.allKeys sortedArrayUsingSelector:@selector(compare:)]; for(NSString *className in classNames) { @autoreleasepool { NSString *sourceKey = [NSString stringWithFormat:@"%@/%@", frameworkName, className]; NSString *destinationFramework = frameworkMap[sourceKey]; if([destinationFramework isEqualToString:@"-"]) continue; if(!destinationFramework) { destinationFramework = frameworkName; } NSString *outputPath = [outputRoot stringByAppendingPathComponent:destinationFramework]; if(![createdFrameworks containsObject:destinationFramework]) { error = nil; if(![NSFileManager.defaultManager createDirectoryAtPath:outputPath withIntermediateDirectories:YES attributes:nil error:&error]) { fprintf(stderr, "Could not create framework directory " "%s: %s\n", outputPath.UTF8String, error.localizedDescription.UTF8String); writeFailureCount++; continue; } [createdFrameworks addObject:destinationFramework]; frameworkCount++; } NSDictionary *methodSignatures = classes[className]; if(![methodSignatures isKindOfClass:NSDictionary.class]) { fprintf(stderr, "Invalid class entry: %s/%s\n", frameworkName.UTF8String, className.UTF8String); writeFailureCount++; continue; } ClassBuilder *classBuilder = [[ClassBuilder alloc] initWithClassName:className imagePath:frameworkName methodSignatures:methodSignatures]; methodCount += classBuilder.methods.count; skippedIncompleteMethods += classBuilder.skippedIncompleteMethods; skippedFilteredMethods += classBuilder.skippedFilteredMethods; error = nil; if(!LC32WriteClass(classBuilder, outputPath, &error)) { fprintf(stderr, "Could not write %s/%s to %s: %s\n", frameworkName.UTF8String, className.UTF8String, destinationFramework.UTF8String, error.localizedDescription.UTF8String); writeFailureCount++; continue; } classCount++; disabledMethods += classBuilder.disabledMethods; } } } LC32RuntimeGenerationResult runtimeResult = {0}; if(includeRuntimeUIKit) { runtimeResult = LC32GenerateRuntimeUIKitExtras(outputRoot, frameworks); } printf("Generated %lu methods in %lu classes from %lu frameworks; " "skipped %lu incomplete and %lu filtered methods", (unsigned long)methodCount, (unsigned long)classCount, (unsigned long)frameworkCount, (unsigned long)skippedIncompleteMethods, (unsigned long)skippedFilteredMethods); if(includeRuntimeUIKit) { printf("; added %lu runtime UIKit classes, %lu unavailable", (unsigned long)runtimeResult.generated, (unsigned long)runtimeResult.unavailable); } printf(".\n"); // These methods have complete encodings but no emitted bridge body; // keep them visible separately from incomplete/filtered signatures. printf("Disabled %lu methods with unhandled types (wrapped in #if 0).\n", (unsigned long)(disabledMethods + runtimeResult.disabledMethods)); return writeFailureCount == 0 && runtimeResult.failures == 0 && runtimeResult.unavailable == 0 ? 0 : 1; } }