FLEXRuntimeUtility.m 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. //
  2. // FLEXRuntimeUtility.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 6/8/14.
  6. // Copyright (c) 2014 Flipboard. All rights reserved.
  7. //
  8. #import <UIKit/UIKit.h>
  9. #import "FLEXRuntimeUtility.h"
  10. #import "FLEXObjcInternal.h"
  11. // See https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html#//apple_ref/doc/uid/TP40008048-CH101-SW6
  12. NSString *const kFLEXUtilityAttributeTypeEncoding = @"T";
  13. NSString *const kFLEXUtilityAttributeBackingIvar = @"V";
  14. NSString *const kFLEXUtilityAttributeReadOnly = @"R";
  15. NSString *const kFLEXUtilityAttributeCopy = @"C";
  16. NSString *const kFLEXUtilityAttributeRetain = @"&";
  17. NSString *const kFLEXUtilityAttributeNonAtomic = @"N";
  18. NSString *const kFLEXUtilityAttributeCustomGetter = @"G";
  19. NSString *const kFLEXUtilityAttributeCustomSetter = @"S";
  20. NSString *const kFLEXUtilityAttributeDynamic = @"D";
  21. NSString *const kFLEXUtilityAttributeWeak = @"W";
  22. NSString *const kFLEXUtilityAttributeGarbageCollectable = @"P";
  23. NSString *const kFLEXUtilityAttributeOldStyleTypeEncoding = @"t";
  24. static NSString *const FLEXRuntimeUtilityErrorDomain = @"FLEXRuntimeUtilityErrorDomain";
  25. typedef NS_ENUM(NSInteger, FLEXRuntimeUtilityErrorCode) {
  26. FLEXRuntimeUtilityErrorCodeDoesNotRecognizeSelector = 0,
  27. FLEXRuntimeUtilityErrorCodeInvocationFailed = 1,
  28. FLEXRuntimeUtilityErrorCodeArgumentTypeMismatch = 2
  29. };
  30. // Arguments 0 and 1 are self and _cmd always
  31. const unsigned int kFLEXNumberOfImplicitArgs = 2;
  32. @implementation FLEXRuntimeUtility
  33. #pragma mark - General Helpers (Public)
  34. + (BOOL)pointerIsValidObjcObject:(const void *)pointer
  35. {
  36. return FLEXPointerIsValidObjcObject(pointer);
  37. }
  38. + (id)potentiallyUnwrapBoxedPointer:(id)returnedObjectOrNil type:(const FLEXTypeEncoding *)returnType
  39. {
  40. if (!returnedObjectOrNil) {
  41. return nil;
  42. }
  43. NSInteger i = 0;
  44. if (returnType[i] == FLEXTypeEncodingConst) {
  45. i++;
  46. }
  47. BOOL returnsObjectOrClass = returnType[i] == FLEXTypeEncodingObjcObject ||
  48. returnType[i] == FLEXTypeEncodingObjcClass;
  49. BOOL returnsVoidPointer = returnType[i] == FLEXTypeEncodingPointer &&
  50. returnType[i+1] == FLEXTypeEncodingVoid;
  51. BOOL returnsCString = returnType[i] == FLEXTypeEncodingCString;
  52. // If we got back an NSValue and the return type is not an object,
  53. // we check to see if the pointer is of a valid object. If not,
  54. // we just display the NSValue.
  55. if (!returnsObjectOrClass) {
  56. // Can only be NSValue since return type is not an object,
  57. // so we bail if this doesn't add up
  58. if (![returnedObjectOrNil isKindOfClass:[NSValue class]]) {
  59. return returnedObjectOrNil;
  60. }
  61. NSValue *value = (NSValue *)returnedObjectOrNil;
  62. if (returnsCString) {
  63. // Wrap char * in NSString
  64. const char *string = (const char *)value.pointerValue;
  65. returnedObjectOrNil = string ? [NSString stringWithCString:string encoding:NSUTF8StringEncoding] : NULL;
  66. } else if (returnsVoidPointer) {
  67. // Cast valid objects disguised as void * to id
  68. if ([FLEXRuntimeUtility pointerIsValidObjcObject:value.pointerValue]) {
  69. returnedObjectOrNil = (__bridge id)value.pointerValue;
  70. }
  71. }
  72. }
  73. return returnedObjectOrNil;
  74. }
  75. + (NSUInteger)fieldNameOffsetForTypeEncoding:(const FLEXTypeEncoding *)typeEncoding
  76. {
  77. NSUInteger beginIndex = 0;
  78. while (typeEncoding[beginIndex] == FLEXTypeEncodingQuote) {
  79. NSUInteger endIndex = beginIndex + 1;
  80. while (typeEncoding[endIndex] != FLEXTypeEncodingQuote) {
  81. ++endIndex;
  82. }
  83. beginIndex = endIndex + 1;
  84. }
  85. return beginIndex;
  86. }
  87. + (NSArray<Class> *)classHierarchyOfObject:(id)objectOrClass
  88. {
  89. NSMutableArray<Class> *superClasses = [NSMutableArray new];
  90. id cls = [objectOrClass class];
  91. do {
  92. [superClasses addObject:cls];
  93. } while ((cls = [cls superclass]));
  94. return superClasses;
  95. }
  96. #pragma mark - Property Helpers (Public)
  97. + (NSString *)prettyNameForProperty:(objc_property_t)property
  98. {
  99. NSString *name = @(property_getName(property));
  100. NSString *encoding = [self typeEncodingForProperty:property];
  101. NSString *readableType = [self readableTypeForEncoding:encoding];
  102. return [self appendName:name toType:readableType];
  103. }
  104. + (NSString *)typeEncodingForProperty:(objc_property_t)property
  105. {
  106. NSDictionary<NSString *, NSString *> *attributesDictionary = [self attributesDictionaryForProperty:property];
  107. return attributesDictionary[kFLEXUtilityAttributeTypeEncoding];
  108. }
  109. + (BOOL)isReadonlyProperty:(objc_property_t)property
  110. {
  111. return [[self attributesDictionaryForProperty:property] objectForKey:kFLEXUtilityAttributeReadOnly] != nil;
  112. }
  113. + (SEL)setterSelectorForProperty:(objc_property_t)property
  114. {
  115. SEL setterSelector = NULL;
  116. NSString *setterSelectorString = [[self attributesDictionaryForProperty:property] objectForKey:kFLEXUtilityAttributeCustomSetter];
  117. if (!setterSelectorString) {
  118. NSString *propertyName = @(property_getName(property));
  119. setterSelectorString = [NSString stringWithFormat:@"set%@%@:", [[propertyName substringToIndex:1] uppercaseString], [propertyName substringFromIndex:1]];
  120. }
  121. if (setterSelectorString) {
  122. setterSelector = NSSelectorFromString(setterSelectorString);
  123. }
  124. return setterSelector;
  125. }
  126. + (NSString *)fullDescriptionForProperty:(objc_property_t)property
  127. {
  128. NSDictionary<NSString *, NSString *> *attributesDictionary = [self attributesDictionaryForProperty:property];
  129. NSMutableArray<NSString *> *attributesStrings = [NSMutableArray array];
  130. // Atomicity
  131. if (attributesDictionary[kFLEXUtilityAttributeNonAtomic]) {
  132. [attributesStrings addObject:@"nonatomic"];
  133. } else {
  134. [attributesStrings addObject:@"atomic"];
  135. }
  136. // Storage
  137. if (attributesDictionary[kFLEXUtilityAttributeRetain]) {
  138. [attributesStrings addObject:@"strong"];
  139. } else if (attributesDictionary[kFLEXUtilityAttributeCopy]) {
  140. [attributesStrings addObject:@"copy"];
  141. } else if (attributesDictionary[kFLEXUtilityAttributeWeak]) {
  142. [attributesStrings addObject:@"weak"];
  143. } else {
  144. [attributesStrings addObject:@"assign"];
  145. }
  146. // Mutability
  147. if (attributesDictionary[kFLEXUtilityAttributeReadOnly]) {
  148. [attributesStrings addObject:@"readonly"];
  149. } else {
  150. [attributesStrings addObject:@"readwrite"];
  151. }
  152. // Custom getter/setter
  153. NSString *customGetter = attributesDictionary[kFLEXUtilityAttributeCustomGetter];
  154. NSString *customSetter = attributesDictionary[kFLEXUtilityAttributeCustomSetter];
  155. if (customGetter) {
  156. [attributesStrings addObject:[NSString stringWithFormat:@"getter=%@", customGetter]];
  157. }
  158. if (customSetter) {
  159. [attributesStrings addObject:[NSString stringWithFormat:@"setter=%@", customSetter]];
  160. }
  161. NSString *attributesString = [attributesStrings componentsJoinedByString:@", "];
  162. NSString *shortName = [self prettyNameForProperty:property];
  163. return [NSString stringWithFormat:@"@property (%@) %@", attributesString, shortName];
  164. }
  165. + (id)valueForProperty:(objc_property_t)property onObject:(id)object
  166. {
  167. NSString *customGetterString = nil;
  168. char *customGetterName = property_copyAttributeValue(property, kFLEXUtilityAttributeCustomGetter.UTF8String);
  169. if (customGetterName) {
  170. customGetterString = @(customGetterName);
  171. free(customGetterName);
  172. }
  173. SEL getterSelector;
  174. if (customGetterString.length > 0) {
  175. getterSelector = NSSelectorFromString(customGetterString);
  176. } else {
  177. NSString *propertyName = @(property_getName(property));
  178. getterSelector = NSSelectorFromString(propertyName);
  179. }
  180. return [self performSelector:getterSelector onObject:object withArguments:nil error:NULL];
  181. }
  182. + (NSString *)descriptionForIvarOrPropertyValue:(id)value
  183. {
  184. NSString *description = nil;
  185. // Special case BOOL for better readability.
  186. if ([value isKindOfClass:[NSValue class]]) {
  187. const char *type = [value objCType];
  188. if (strcmp(type, @encode(BOOL)) == 0) {
  189. BOOL boolValue = NO;
  190. [value getValue:&boolValue];
  191. description = boolValue ? @"YES" : @"NO";
  192. } else if (strcmp(type, @encode(SEL)) == 0) {
  193. SEL selector = NULL;
  194. [value getValue:&selector];
  195. description = NSStringFromSelector(selector);
  196. }
  197. }
  198. @try {
  199. if (!description) {
  200. // Single line display - replace newlines and tabs with spaces.
  201. description = [[value description] stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
  202. description = [description stringByReplacingOccurrencesOfString:@"\t" withString:@" "];
  203. }
  204. } @catch (NSException *e) {
  205. description = [@"Thrown: " stringByAppendingString:e.reason ?: @"(nil exception reason)"];
  206. }
  207. if (!description) {
  208. description = @"nil";
  209. }
  210. return description;
  211. }
  212. + (void)tryAddPropertyWithName:(const char *)name attributes:(NSDictionary<NSString *, NSString *> *)attributePairs toClass:(__unsafe_unretained Class)theClass
  213. {
  214. objc_property_t property = class_getProperty(theClass, name);
  215. if (!property) {
  216. unsigned int totalAttributesCount = (unsigned int)attributePairs.count;
  217. objc_property_attribute_t *attributes = malloc(sizeof(objc_property_attribute_t) * totalAttributesCount);
  218. if (attributes) {
  219. unsigned int attributeIndex = 0;
  220. for (NSString *attributeName in attributePairs.allKeys) {
  221. objc_property_attribute_t attribute;
  222. attribute.name = attributeName.UTF8String;
  223. attribute.value = attributePairs[attributeName].UTF8String;
  224. attributes[attributeIndex++] = attribute;
  225. }
  226. class_addProperty(theClass, name, attributes, totalAttributesCount);
  227. free(attributes);
  228. }
  229. }
  230. }
  231. #pragma mark - Ivar Helpers (Public)
  232. + (NSString *)prettyNameForIvar:(Ivar)ivar
  233. {
  234. const char *nameCString = ivar_getName(ivar);
  235. NSString *name = nameCString ? @(nameCString) : nil;
  236. const char *encodingCString = ivar_getTypeEncoding(ivar);
  237. NSString *encoding = encodingCString ? @(encodingCString) : nil;
  238. NSString *readableType = [self readableTypeForEncoding:encoding];
  239. return [self appendName:name toType:readableType];
  240. }
  241. + (id)valueForIvar:(Ivar)ivar onObject:(id)object
  242. {
  243. id value = nil;
  244. const char *type = ivar_getTypeEncoding(ivar);
  245. #ifdef __arm64__
  246. // See http://www.sealiesoftware.com/blog/archive/2013/09/24/objc_explain_Non-pointer_isa.html
  247. const char *name = ivar_getName(ivar);
  248. if (type[0] == FLEXTypeEncodingObjcClass && strcmp(name, "isa") == 0) {
  249. value = object_getClass(object);
  250. } else
  251. #endif
  252. if (type[0] == FLEXTypeEncodingObjcObject || type[0] == FLEXTypeEncodingObjcClass) {
  253. value = object_getIvar(object, ivar);
  254. } else {
  255. ptrdiff_t offset = ivar_getOffset(ivar);
  256. void *pointer = (__bridge void *)object + offset;
  257. value = [self valueForPrimitivePointer:pointer objCType:type];
  258. }
  259. return value;
  260. }
  261. + (void)setValue:(id)value forIvar:(Ivar)ivar onObject:(id)object
  262. {
  263. const char *typeEncodingCString = ivar_getTypeEncoding(ivar);
  264. if (typeEncodingCString[0] == FLEXTypeEncodingObjcObject) {
  265. object_setIvar(object, ivar, value);
  266. } else if ([value isKindOfClass:[NSValue class]]) {
  267. // Primitive - unbox the NSValue.
  268. NSValue *valueValue = (NSValue *)value;
  269. // Make sure that the box contained the correct type.
  270. NSAssert(strcmp([valueValue objCType], typeEncodingCString) == 0, @"Type encoding mismatch (value: %s; ivar: %s) in setting ivar named: %s on object: %@", [valueValue objCType], typeEncodingCString, ivar_getName(ivar), object);
  271. NSUInteger bufferSize = 0;
  272. @try {
  273. // NSGetSizeAndAlignment barfs on type encoding for bitfields.
  274. NSGetSizeAndAlignment(typeEncodingCString, &bufferSize, NULL);
  275. } @catch (NSException *exception) { }
  276. if (bufferSize > 0) {
  277. void *buffer = calloc(bufferSize, 1);
  278. [valueValue getValue:buffer];
  279. ptrdiff_t offset = ivar_getOffset(ivar);
  280. void *pointer = (__bridge void *)object + offset;
  281. memcpy(pointer, buffer, bufferSize);
  282. free(buffer);
  283. }
  284. }
  285. }
  286. #pragma mark - Method Helpers (Public)
  287. + (NSString *)prettyNameForMethod:(Method)method isClassMethod:(BOOL)isClassMethod
  288. {
  289. NSString *selectorName = NSStringFromSelector(method_getName(method));
  290. NSString *methodTypeString = isClassMethod ? @"+" : @"-";
  291. char *returnType = method_copyReturnType(method);
  292. NSString *readableReturnType = [self readableTypeForEncoding:@(returnType)];
  293. free(returnType);
  294. NSString *prettyName = [NSString stringWithFormat:@"%@ (%@)", methodTypeString, readableReturnType];
  295. NSArray<NSString *> *components = [self prettyArgumentComponentsForMethod:method];
  296. if (components.count > 0) {
  297. prettyName = [prettyName stringByAppendingString:[components componentsJoinedByString:@" "]];
  298. } else {
  299. prettyName = [prettyName stringByAppendingString:selectorName];
  300. }
  301. return prettyName;
  302. }
  303. + (NSArray<NSString *> *)prettyArgumentComponentsForMethod:(Method)method
  304. {
  305. NSMutableArray<NSString *> *components = [NSMutableArray array];
  306. NSString *selectorName = NSStringFromSelector(method_getName(method));
  307. NSMutableArray<NSString *> *selectorComponents = [[selectorName componentsSeparatedByString:@":"] mutableCopy];
  308. // this is a workaround cause method_getNumberOfArguments() returns wrong number for some methods
  309. if (selectorComponents.count == 1) {
  310. return @[];
  311. }
  312. if ([selectorComponents.lastObject isEqualToString:@""]) {
  313. [selectorComponents removeLastObject];
  314. }
  315. for (unsigned int argIndex = 0; argIndex < selectorComponents.count; argIndex++) {
  316. char *argType = method_copyArgumentType(method, argIndex + kFLEXNumberOfImplicitArgs);
  317. NSString *readableArgType = (argType != NULL) ? [self readableTypeForEncoding:@(argType)] : nil;
  318. free(argType);
  319. NSString *prettyComponent = [NSString stringWithFormat:@"%@:(%@) ", [selectorComponents objectAtIndex:argIndex], readableArgType];
  320. [components addObject:prettyComponent];
  321. }
  322. return components;
  323. }
  324. + (FLEXTypeEncoding *)returnTypeForMethod:(Method)method
  325. {
  326. return (FLEXTypeEncoding *)method_copyReturnType(method);
  327. }
  328. #pragma mark - Method Calling/Field Editing (Public)
  329. + (id)performSelector:(SEL)selector onObject:(id)object withArguments:(NSArray *)arguments error:(NSError * __autoreleasing *)error
  330. {
  331. // Bail if the object won't respond to this selector.
  332. if (![object respondsToSelector:selector]) {
  333. if (error) {
  334. NSDictionary<NSString *, id> *userInfo = @{ NSLocalizedDescriptionKey : [NSString stringWithFormat:@"%@ does not respond to the selector %@", object, NSStringFromSelector(selector)]};
  335. *error = [NSError errorWithDomain:FLEXRuntimeUtilityErrorDomain code:FLEXRuntimeUtilityErrorCodeDoesNotRecognizeSelector userInfo:userInfo];
  336. }
  337. return nil;
  338. }
  339. // Build the invocation
  340. NSMethodSignature *methodSignature = [object methodSignatureForSelector:selector];
  341. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
  342. [invocation setSelector:selector];
  343. [invocation setTarget:object];
  344. [invocation retainArguments];
  345. // Always self and _cmd
  346. NSUInteger numberOfArguments = [methodSignature numberOfArguments];
  347. for (NSUInteger argumentIndex = kFLEXNumberOfImplicitArgs; argumentIndex < numberOfArguments; argumentIndex++) {
  348. NSUInteger argumentsArrayIndex = argumentIndex - kFLEXNumberOfImplicitArgs;
  349. id argumentObject = arguments.count > argumentsArrayIndex ? arguments[argumentsArrayIndex] : nil;
  350. // NSNull in the arguments array can be passed as a placeholder to indicate nil. We only need to set the argument if it will be non-nil.
  351. if (argumentObject && ![argumentObject isKindOfClass:[NSNull class]]) {
  352. const char *typeEncodingCString = [methodSignature getArgumentTypeAtIndex:argumentIndex];
  353. if (typeEncodingCString[0] == FLEXTypeEncodingObjcObject || typeEncodingCString[0] == FLEXTypeEncodingObjcClass || [self isTollFreeBridgedValue:argumentObject forCFType:typeEncodingCString]) {
  354. // Object
  355. [invocation setArgument:&argumentObject atIndex:argumentIndex];
  356. } else if (strcmp(typeEncodingCString, @encode(CGColorRef)) == 0 && [argumentObject isKindOfClass:[UIColor class]]) {
  357. // Bridging UIColor to CGColorRef
  358. CGColorRef colorRef = [argumentObject CGColor];
  359. [invocation setArgument:&colorRef atIndex:argumentIndex];
  360. } else if ([argumentObject isKindOfClass:[NSValue class]]) {
  361. // Primitive boxed in NSValue
  362. NSValue *argumentValue = (NSValue *)argumentObject;
  363. // Ensure that the type encoding on the NSValue matches the type encoding of the argument in the method signature
  364. if (strcmp([argumentValue objCType], typeEncodingCString) != 0) {
  365. if (error) {
  366. NSDictionary<NSString *, id> *userInfo = @{ NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Type encoding mismatch for argument at index %lu. Value type: %s; Method argument type: %s.", (unsigned long)argumentsArrayIndex, [argumentValue objCType], typeEncodingCString]};
  367. *error = [NSError errorWithDomain:FLEXRuntimeUtilityErrorDomain code:FLEXRuntimeUtilityErrorCodeArgumentTypeMismatch userInfo:userInfo];
  368. }
  369. return nil;
  370. }
  371. @try {
  372. NSUInteger bufferSize = 0;
  373. // NSGetSizeAndAlignment barfs on type encoding for bitfields.
  374. NSGetSizeAndAlignment(typeEncodingCString, &bufferSize, NULL);
  375. if (bufferSize > 0) {
  376. void *buffer = calloc(bufferSize, 1);
  377. [argumentValue getValue:buffer];
  378. [invocation setArgument:buffer atIndex:argumentIndex];
  379. free(buffer);
  380. }
  381. } @catch (NSException *exception) { }
  382. }
  383. }
  384. }
  385. // Try to invoke the invocation but guard against an exception being thrown.
  386. id returnObject = nil;
  387. @try {
  388. // Some methods are not fit to be called...
  389. // Looking at you -[UIResponder(UITextInputAdditions) _caretRect]
  390. [invocation invoke];
  391. // Retrieve the return value and box if necessary.
  392. const char *returnType = methodSignature.methodReturnType;
  393. if (returnType[0] == FLEXTypeEncodingObjcObject || returnType[0] == FLEXTypeEncodingObjcClass) {
  394. // Return value is an object.
  395. __unsafe_unretained id objectReturnedFromMethod = nil;
  396. [invocation getReturnValue:&objectReturnedFromMethod];
  397. returnObject = objectReturnedFromMethod;
  398. } else if (returnType[0] != FLEXTypeEncodingVoid) {
  399. // Will use arbitrary buffer for return value and box it.
  400. void *returnValue = malloc(methodSignature.methodReturnLength);
  401. if (returnValue) {
  402. [invocation getReturnValue:returnValue];
  403. returnObject = [self valueForPrimitivePointer:returnValue objCType:returnType];
  404. free(returnValue);
  405. }
  406. }
  407. } @catch (NSException *exception) {
  408. // Bummer...
  409. if (error) {
  410. // "… on <class>" / "… on instance of <class>"
  411. NSString *class = NSStringFromClass([object class]);
  412. NSString *calledOn = object == [object class] ? class : [@"an instance of " stringByAppendingString:class];
  413. NSString *message = [NSString stringWithFormat:@"Exception '%@' thrown while performing selector '%@' on %@.\nReason:\n\n%@",
  414. exception.name,
  415. NSStringFromSelector(selector),
  416. calledOn,
  417. exception.reason];
  418. *error = [NSError errorWithDomain:FLEXRuntimeUtilityErrorDomain
  419. code:FLEXRuntimeUtilityErrorCodeInvocationFailed
  420. userInfo:@{ NSLocalizedDescriptionKey : message }];
  421. }
  422. }
  423. return returnObject;
  424. }
  425. + (BOOL)isTollFreeBridgedValue:(id)value forCFType:(const char *)typeEncoding
  426. {
  427. // See https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/Toll-FreeBridgin/Toll-FreeBridgin.html
  428. #define CASE(cftype, foundationClass) \
  429. if (strcmp(typeEncoding, @encode(cftype)) == 0) { \
  430. return [value isKindOfClass:[foundationClass class]]; \
  431. }
  432. CASE(CFArrayRef, NSArray);
  433. CASE(CFAttributedStringRef, NSAttributedString);
  434. CASE(CFCalendarRef, NSCalendar);
  435. CASE(CFCharacterSetRef, NSCharacterSet);
  436. CASE(CFDataRef, NSData);
  437. CASE(CFDateRef, NSDate);
  438. CASE(CFDictionaryRef, NSDictionary);
  439. CASE(CFErrorRef, NSError);
  440. CASE(CFLocaleRef, NSLocale);
  441. CASE(CFMutableArrayRef, NSMutableArray);
  442. CASE(CFMutableAttributedStringRef, NSMutableAttributedString);
  443. CASE(CFMutableCharacterSetRef, NSMutableCharacterSet);
  444. CASE(CFMutableDataRef, NSMutableData);
  445. CASE(CFMutableDictionaryRef, NSMutableDictionary);
  446. CASE(CFMutableSetRef, NSMutableSet);
  447. CASE(CFMutableStringRef, NSMutableString);
  448. CASE(CFNumberRef, NSNumber);
  449. CASE(CFReadStreamRef, NSInputStream);
  450. CASE(CFRunLoopTimerRef, NSTimer);
  451. CASE(CFSetRef, NSSet);
  452. CASE(CFStringRef, NSString);
  453. CASE(CFTimeZoneRef, NSTimeZone);
  454. CASE(CFURLRef, NSURL);
  455. CASE(CFWriteStreamRef, NSOutputStream);
  456. #undef CASE
  457. return NO;
  458. }
  459. + (NSString *)editableJSONStringForObject:(id)object
  460. {
  461. NSString *editableDescription = nil;
  462. if (object) {
  463. // This is a hack to use JSON serialization for our editable objects.
  464. // NSJSONSerialization doesn't allow writing fragments - the top level object must be an array or dictionary.
  465. // We always wrap the object inside an array and then strip the outer square braces off the final string.
  466. NSArray *wrappedObject = @[object];
  467. if ([NSJSONSerialization isValidJSONObject:wrappedObject]) {
  468. NSString *wrappedDescription = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:wrappedObject options:0 error:NULL] encoding:NSUTF8StringEncoding];
  469. editableDescription = [wrappedDescription substringWithRange:NSMakeRange(1, wrappedDescription.length - 2)];
  470. }
  471. }
  472. return editableDescription;
  473. }
  474. + (id)objectValueFromEditableJSONString:(NSString *)string
  475. {
  476. id value = nil;
  477. // nil for empty string/whitespace
  478. if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] > 0) {
  479. value = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:NULL];
  480. }
  481. return value;
  482. }
  483. + (NSValue *)valueForNumberWithObjCType:(const char *)typeEncoding fromInputString:(NSString *)inputString
  484. {
  485. NSNumberFormatter *formatter = [NSNumberFormatter new];
  486. [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
  487. NSNumber *number = [formatter numberFromString:inputString];
  488. // Make sure we box the number with the correct type encoding so it can be properly unboxed later via getValue:
  489. NSValue *value = nil;
  490. if (strcmp(typeEncoding, @encode(char)) == 0) {
  491. char primitiveValue = [number charValue];
  492. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  493. } else if (strcmp(typeEncoding, @encode(int)) == 0) {
  494. int primitiveValue = [number intValue];
  495. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  496. } else if (strcmp(typeEncoding, @encode(short)) == 0) {
  497. short primitiveValue = [number shortValue];
  498. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  499. } else if (strcmp(typeEncoding, @encode(long)) == 0) {
  500. long primitiveValue = [number longValue];
  501. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  502. } else if (strcmp(typeEncoding, @encode(long long)) == 0) {
  503. long long primitiveValue = [number longLongValue];
  504. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  505. } else if (strcmp(typeEncoding, @encode(unsigned char)) == 0) {
  506. unsigned char primitiveValue = [number unsignedCharValue];
  507. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  508. } else if (strcmp(typeEncoding, @encode(unsigned int)) == 0) {
  509. unsigned int primitiveValue = [number unsignedIntValue];
  510. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  511. } else if (strcmp(typeEncoding, @encode(unsigned short)) == 0) {
  512. unsigned short primitiveValue = [number unsignedShortValue];
  513. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  514. } else if (strcmp(typeEncoding, @encode(unsigned long)) == 0) {
  515. unsigned long primitiveValue = [number unsignedLongValue];
  516. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  517. } else if (strcmp(typeEncoding, @encode(unsigned long long)) == 0) {
  518. unsigned long long primitiveValue = [number unsignedLongValue];
  519. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  520. } else if (strcmp(typeEncoding, @encode(float)) == 0) {
  521. float primitiveValue = [number floatValue];
  522. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  523. } else if (strcmp(typeEncoding, @encode(double)) == 0) {
  524. double primitiveValue = [number doubleValue];
  525. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  526. } else if (strcmp(typeEncoding, @encode(long double)) == 0) {
  527. long double primitiveValue = [number doubleValue];
  528. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  529. }
  530. return value;
  531. }
  532. + (void)enumerateTypesInStructEncoding:(const char *)structEncoding usingBlock:(void (^)(NSString *structName, const char *fieldTypeEncoding, NSString *prettyTypeEncoding, NSUInteger fieldIndex, NSUInteger fieldOffset))typeBlock
  533. {
  534. if (structEncoding && structEncoding[0] == FLEXTypeEncodingStructBegin) {
  535. const char *equals = strchr(structEncoding, '=');
  536. if (equals) {
  537. const char *nameStart = structEncoding + 1;
  538. NSString *structName = [@(structEncoding) substringWithRange:NSMakeRange(nameStart - structEncoding, equals - nameStart)];
  539. NSUInteger fieldAlignment = 0;
  540. NSUInteger structSize = 0;
  541. @try {
  542. // NSGetSizeAndAlignment barfs on type encoding for bitfields.
  543. NSGetSizeAndAlignment(structEncoding, &structSize, &fieldAlignment);
  544. } @catch (NSException *exception) { }
  545. if (structSize > 0) {
  546. NSUInteger runningFieldIndex = 0;
  547. NSUInteger runningFieldOffset = 0;
  548. const char *typeStart = equals + 1;
  549. while (*typeStart != FLEXTypeEncodingStructEnd) {
  550. NSUInteger fieldSize = 0;
  551. // If the struct type encoding was successfully handled by NSGetSizeAndAlignment above, we *should* be ok with the field here.
  552. const char *nextTypeStart = NSGetSizeAndAlignment(typeStart, &fieldSize, NULL);
  553. NSString *typeEncoding = [@(structEncoding) substringWithRange:NSMakeRange(typeStart - structEncoding, nextTypeStart - typeStart)];
  554. // Padding to keep proper alignment. __attribute((packed)) structs will break here.
  555. // The type encoding is no different for packed structs, so it's not clear there's anything we can do for those.
  556. const NSUInteger currentSizeSum = runningFieldOffset % fieldAlignment;
  557. if (currentSizeSum != 0 && currentSizeSum + fieldSize > fieldAlignment) {
  558. runningFieldOffset += fieldAlignment - currentSizeSum;
  559. }
  560. typeBlock(structName, typeEncoding.UTF8String, [self readableTypeForEncoding:typeEncoding], runningFieldIndex, runningFieldOffset);
  561. runningFieldOffset += fieldSize;
  562. runningFieldIndex++;
  563. typeStart = nextTypeStart;
  564. }
  565. }
  566. }
  567. }
  568. }
  569. #pragma mark - Internal Helpers
  570. + (NSDictionary<NSString *, NSString *> *)attributesDictionaryForProperty:(objc_property_t)property
  571. {
  572. NSString *attributes = @(property_getAttributes(property));
  573. // Thanks to MAObjcRuntime for inspiration here.
  574. NSArray<NSString *> *attributePairs = [attributes componentsSeparatedByString:@","];
  575. NSMutableDictionary<NSString *, NSString *> *attributesDictionary = [NSMutableDictionary dictionaryWithCapacity:attributePairs.count];
  576. for (NSString *attributePair in attributePairs) {
  577. [attributesDictionary setObject:[attributePair substringFromIndex:1] forKey:[attributePair substringToIndex:1]];
  578. }
  579. return attributesDictionary;
  580. }
  581. + (NSString *)appendName:(NSString *)name toType:(NSString *)type
  582. {
  583. NSString *combined = nil;
  584. if ([type characterAtIndex:type.length - 1] == FLEXTypeEncodingCString) {
  585. combined = [type stringByAppendingString:name];
  586. } else {
  587. combined = [type stringByAppendingFormat:@" %@", name];
  588. }
  589. return combined;
  590. }
  591. + (NSString *)readableTypeForEncoding:(NSString *)encodingString
  592. {
  593. if (!encodingString) {
  594. return nil;
  595. }
  596. // See https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
  597. // class-dump has a much nicer and much more complete implementation for this task, but it is distributed under GPLv2 :/
  598. // See https://github.com/nygard/class-dump/blob/master/Source/CDType.m
  599. // Warning: this method uses multiple middle returns and macros to cut down on boilerplate.
  600. // The use of macros here was inspired by https://www.mikeash.com/pyblog/friday-qa-2013-02-08-lets-build-key-value-coding.html
  601. const char *encodingCString = encodingString.UTF8String;
  602. // Some fields have a name, such as {Size=\"width\"d\"height\"d}, we need to extract the name out and recursive
  603. const NSUInteger fieldNameOffset = [FLEXRuntimeUtility fieldNameOffsetForTypeEncoding:encodingCString];
  604. if (fieldNameOffset > 0) {
  605. // According to https://github.com/nygard/class-dump/commit/33fb5ed221810685f57c192e1ce8ab6054949a7c,
  606. // there are some consecutive quoted strings, so use `_` to concatenate the names.
  607. NSString *const fieldNamesString = [encodingString substringWithRange:NSMakeRange(0, fieldNameOffset)];
  608. NSArray<NSString *> *const fieldNames = [fieldNamesString componentsSeparatedByString:[NSString stringWithFormat:@"%c", FLEXTypeEncodingQuote]];
  609. NSMutableString *finalFieldNamesString = [NSMutableString string];
  610. for (NSString *const fieldName in fieldNames) {
  611. if (fieldName.length > 0) {
  612. if (finalFieldNamesString.length > 0) {
  613. [finalFieldNamesString appendString:@"_"];
  614. }
  615. [finalFieldNamesString appendString:fieldName];
  616. }
  617. }
  618. NSString *const recursiveType = [self readableTypeForEncoding:[encodingString substringFromIndex:fieldNameOffset]];
  619. return [NSString stringWithFormat:@"%@ %@", recursiveType, finalFieldNamesString];
  620. }
  621. // Objects
  622. if (encodingCString[0] == FLEXTypeEncodingObjcObject) {
  623. NSString *class = [encodingString substringFromIndex:1];
  624. class = [class stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%c", FLEXTypeEncodingQuote] withString:@""];
  625. if (class.length == 0 || (class.length == 1 && [class characterAtIndex:0] == FLEXTypeEncodingUnknown)) {
  626. class = @"id";
  627. } else {
  628. class = [class stringByAppendingString:@" *"];
  629. }
  630. return class;
  631. }
  632. // Qualifier Prefixes
  633. // Do this first since some of the direct translations (i.e. Method) contain a prefix.
  634. #define RECURSIVE_TRANSLATE(prefix, formatString) \
  635. if (encodingCString[0] == prefix) { \
  636. NSString *recursiveType = [self readableTypeForEncoding:[encodingString substringFromIndex:1]]; \
  637. return [NSString stringWithFormat:formatString, recursiveType]; \
  638. }
  639. // If there's a qualifier prefix on the encoding, translate it and then
  640. // recursively call this method with the rest of the encoding string.
  641. RECURSIVE_TRANSLATE('^', @"%@ *");
  642. RECURSIVE_TRANSLATE('r', @"const %@");
  643. RECURSIVE_TRANSLATE('n', @"in %@");
  644. RECURSIVE_TRANSLATE('N', @"inout %@");
  645. RECURSIVE_TRANSLATE('o', @"out %@");
  646. RECURSIVE_TRANSLATE('O', @"bycopy %@");
  647. RECURSIVE_TRANSLATE('R', @"byref %@");
  648. RECURSIVE_TRANSLATE('V', @"oneway %@");
  649. RECURSIVE_TRANSLATE('b', @"bitfield(%@)");
  650. #undef RECURSIVE_TRANSLATE
  651. // C Types
  652. #define TRANSLATE(ctype) \
  653. if (strcmp(encodingCString, @encode(ctype)) == 0) { \
  654. return (NSString *)CFSTR(#ctype); \
  655. }
  656. // Order matters here since some of the cocoa types are typedefed to c types.
  657. // We can't recover the exact mapping, but we choose to prefer the cocoa types.
  658. // This is not an exhaustive list, but it covers the most common types
  659. TRANSLATE(CGRect);
  660. TRANSLATE(CGPoint);
  661. TRANSLATE(CGSize);
  662. TRANSLATE(CGVector);
  663. TRANSLATE(UIEdgeInsets);
  664. if (@available(iOS 11.0, *)) {
  665. TRANSLATE(NSDirectionalEdgeInsets);
  666. }
  667. TRANSLATE(UIOffset);
  668. TRANSLATE(NSRange);
  669. TRANSLATE(CGAffineTransform);
  670. TRANSLATE(CATransform3D);
  671. TRANSLATE(CGColorRef);
  672. TRANSLATE(CGPathRef);
  673. TRANSLATE(CGContextRef);
  674. TRANSLATE(NSInteger);
  675. TRANSLATE(NSUInteger);
  676. TRANSLATE(CGFloat);
  677. TRANSLATE(BOOL);
  678. TRANSLATE(int);
  679. TRANSLATE(short);
  680. TRANSLATE(long);
  681. TRANSLATE(long long);
  682. TRANSLATE(unsigned char);
  683. TRANSLATE(unsigned int);
  684. TRANSLATE(unsigned short);
  685. TRANSLATE(unsigned long);
  686. TRANSLATE(unsigned long long);
  687. TRANSLATE(float);
  688. TRANSLATE(double);
  689. TRANSLATE(long double);
  690. TRANSLATE(char *);
  691. TRANSLATE(Class);
  692. TRANSLATE(objc_property_t);
  693. TRANSLATE(Ivar);
  694. TRANSLATE(Method);
  695. TRANSLATE(Category);
  696. TRANSLATE(NSZone *);
  697. TRANSLATE(SEL);
  698. TRANSLATE(void);
  699. #undef TRANSLATE
  700. // For structs, we only use the name of the structs
  701. if (encodingCString[0] == FLEXTypeEncodingStructBegin) {
  702. const char *equals = strchr(encodingCString, '=');
  703. if (equals) {
  704. const char *nameStart = encodingCString + 1;
  705. // For anonymous structs
  706. if (nameStart[0] == FLEXTypeEncodingUnknown) {
  707. return @"anonymous struct";
  708. } else {
  709. NSString *const structName = [encodingString substringWithRange:NSMakeRange(nameStart - encodingCString, equals - nameStart)];
  710. return structName;
  711. }
  712. }
  713. }
  714. // If we couldn't translate, just return the original encoding string
  715. return encodingString;
  716. }
  717. + (NSValue *)valueForPrimitivePointer:(void *)pointer objCType:(const char *)type
  718. {
  719. // Remove the field name if there is any (e.g. \"width\"d -> d)
  720. const NSUInteger fieldNameOffset = [FLEXRuntimeUtility fieldNameOffsetForTypeEncoding:type];
  721. if (fieldNameOffset > 0) {
  722. return [self valueForPrimitivePointer:pointer objCType:type + fieldNameOffset];
  723. }
  724. // CASE macro inspired by https://www.mikeash.com/pyblog/friday-qa-2013-02-08-lets-build-key-value-coding.html
  725. #define CASE(ctype, selectorpart) \
  726. if (strcmp(type, @encode(ctype)) == 0) { \
  727. return [NSNumber numberWith ## selectorpart: *(ctype *)pointer]; \
  728. }
  729. CASE(BOOL, Bool);
  730. CASE(unsigned char, UnsignedChar);
  731. CASE(short, Short);
  732. CASE(unsigned short, UnsignedShort);
  733. CASE(int, Int);
  734. CASE(unsigned int, UnsignedInt);
  735. CASE(long, Long);
  736. CASE(unsigned long, UnsignedLong);
  737. CASE(long long, LongLong);
  738. CASE(unsigned long long, UnsignedLongLong);
  739. CASE(float, Float);
  740. CASE(double, Double);
  741. CASE(long double, Double);
  742. #undef CASE
  743. NSValue *value = nil;
  744. @try {
  745. value = [NSValue valueWithBytes:pointer objCType:type];
  746. } @catch (NSException *exception) {
  747. // Certain type encodings are not supported by valueWithBytes:objCType:. Just fail silently if an exception is thrown.
  748. }
  749. return value;
  750. }
  751. @end