FLEXRuntimeUtility.m 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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. // Probably an unsupported type encoding, like bitfields
  340. // or inline arrays. In the future, we could calculate
  341. // the return length on our own. For now, we abort.
  342. //
  343. // For future reference, the code here will get the true type encoding.
  344. // NSMethodSignature will convert {?=b8b4b1b1b18[8S]} to {?}
  345. // A solution might involve hooking NSGetSizeAndAlignment.
  346. //
  347. // returnType = method_getTypeEncoding(class_getInstanceMethod([object class], selector));
  348. NSMethodSignature *methodSignature = [object methodSignatureForSelector:selector];
  349. if (!methodSignature.methodReturnLength) {
  350. return nil;
  351. }
  352. // Build the invocation
  353. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
  354. [invocation setSelector:selector];
  355. [invocation setTarget:object];
  356. [invocation retainArguments];
  357. // Always self and _cmd
  358. NSUInteger numberOfArguments = [methodSignature numberOfArguments];
  359. for (NSUInteger argumentIndex = kFLEXNumberOfImplicitArgs; argumentIndex < numberOfArguments; argumentIndex++) {
  360. NSUInteger argumentsArrayIndex = argumentIndex - kFLEXNumberOfImplicitArgs;
  361. id argumentObject = arguments.count > argumentsArrayIndex ? arguments[argumentsArrayIndex] : nil;
  362. // 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.
  363. if (argumentObject && ![argumentObject isKindOfClass:[NSNull class]]) {
  364. const char *typeEncodingCString = [methodSignature getArgumentTypeAtIndex:argumentIndex];
  365. if (typeEncodingCString[0] == FLEXTypeEncodingObjcObject || typeEncodingCString[0] == FLEXTypeEncodingObjcClass || [self isTollFreeBridgedValue:argumentObject forCFType:typeEncodingCString]) {
  366. // Object
  367. [invocation setArgument:&argumentObject atIndex:argumentIndex];
  368. } else if (strcmp(typeEncodingCString, @encode(CGColorRef)) == 0 && [argumentObject isKindOfClass:[UIColor class]]) {
  369. // Bridging UIColor to CGColorRef
  370. CGColorRef colorRef = [argumentObject CGColor];
  371. [invocation setArgument:&colorRef atIndex:argumentIndex];
  372. } else if ([argumentObject isKindOfClass:[NSValue class]]) {
  373. // Primitive boxed in NSValue
  374. NSValue *argumentValue = (NSValue *)argumentObject;
  375. // Ensure that the type encoding on the NSValue matches the type encoding of the argument in the method signature
  376. if (strcmp([argumentValue objCType], typeEncodingCString) != 0) {
  377. if (error) {
  378. 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]};
  379. *error = [NSError errorWithDomain:FLEXRuntimeUtilityErrorDomain code:FLEXRuntimeUtilityErrorCodeArgumentTypeMismatch userInfo:userInfo];
  380. }
  381. return nil;
  382. }
  383. @try {
  384. NSUInteger bufferSize = 0;
  385. // NSGetSizeAndAlignment barfs on type encoding for bitfields.
  386. NSGetSizeAndAlignment(typeEncodingCString, &bufferSize, NULL);
  387. if (bufferSize > 0) {
  388. void *buffer = calloc(bufferSize, 1);
  389. [argumentValue getValue:buffer];
  390. [invocation setArgument:buffer atIndex:argumentIndex];
  391. free(buffer);
  392. }
  393. } @catch (NSException *exception) { }
  394. }
  395. }
  396. }
  397. // Try to invoke the invocation but guard against an exception being thrown.
  398. id returnObject = nil;
  399. @try {
  400. // Retrieve the return value and box if necessary.
  401. const char *returnType = methodSignature.methodReturnType;
  402. if (returnType[0] == FLEXTypeEncodingObjcObject || returnType[0] == FLEXTypeEncodingObjcClass) {
  403. // Return value is an object.
  404. __unsafe_unretained id objectReturnedFromMethod = nil;
  405. [invocation getReturnValue:&objectReturnedFromMethod];
  406. returnObject = objectReturnedFromMethod;
  407. } else if (returnType[0] != FLEXTypeEncodingVoid) {
  408. NSAssert(methodSignature.methodReturnLength, @"Memory corruption lies ahead");
  409. // Will use arbitrary buffer for return value and box it.
  410. void *returnValue = malloc(methodSignature.methodReturnLength);
  411. if (returnValue) {
  412. [invocation getReturnValue:returnValue];
  413. returnObject = [self valueForPrimitivePointer:returnValue objCType:returnType];
  414. free(returnValue);
  415. }
  416. }
  417. } @catch (NSException *exception) {
  418. // Bummer...
  419. if (error) {
  420. // "… on <class>" / "… on instance of <class>"
  421. NSString *class = NSStringFromClass([object class]);
  422. NSString *calledOn = object == [object class] ? class : [@"an instance of " stringByAppendingString:class];
  423. NSString *message = [NSString stringWithFormat:@"Exception '%@' thrown while performing selector '%@' on %@.\nReason:\n\n%@",
  424. exception.name,
  425. NSStringFromSelector(selector),
  426. calledOn,
  427. exception.reason];
  428. *error = [NSError errorWithDomain:FLEXRuntimeUtilityErrorDomain
  429. code:FLEXRuntimeUtilityErrorCodeInvocationFailed
  430. userInfo:@{ NSLocalizedDescriptionKey : message }];
  431. }
  432. }
  433. return returnObject;
  434. }
  435. + (BOOL)isTollFreeBridgedValue:(id)value forCFType:(const char *)typeEncoding
  436. {
  437. // See https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/Toll-FreeBridgin/Toll-FreeBridgin.html
  438. #define CASE(cftype, foundationClass) \
  439. if (strcmp(typeEncoding, @encode(cftype)) == 0) { \
  440. return [value isKindOfClass:[foundationClass class]]; \
  441. }
  442. CASE(CFArrayRef, NSArray);
  443. CASE(CFAttributedStringRef, NSAttributedString);
  444. CASE(CFCalendarRef, NSCalendar);
  445. CASE(CFCharacterSetRef, NSCharacterSet);
  446. CASE(CFDataRef, NSData);
  447. CASE(CFDateRef, NSDate);
  448. CASE(CFDictionaryRef, NSDictionary);
  449. CASE(CFErrorRef, NSError);
  450. CASE(CFLocaleRef, NSLocale);
  451. CASE(CFMutableArrayRef, NSMutableArray);
  452. CASE(CFMutableAttributedStringRef, NSMutableAttributedString);
  453. CASE(CFMutableCharacterSetRef, NSMutableCharacterSet);
  454. CASE(CFMutableDataRef, NSMutableData);
  455. CASE(CFMutableDictionaryRef, NSMutableDictionary);
  456. CASE(CFMutableSetRef, NSMutableSet);
  457. CASE(CFMutableStringRef, NSMutableString);
  458. CASE(CFNumberRef, NSNumber);
  459. CASE(CFReadStreamRef, NSInputStream);
  460. CASE(CFRunLoopTimerRef, NSTimer);
  461. CASE(CFSetRef, NSSet);
  462. CASE(CFStringRef, NSString);
  463. CASE(CFTimeZoneRef, NSTimeZone);
  464. CASE(CFURLRef, NSURL);
  465. CASE(CFWriteStreamRef, NSOutputStream);
  466. #undef CASE
  467. return NO;
  468. }
  469. + (NSString *)editableJSONStringForObject:(id)object
  470. {
  471. NSString *editableDescription = nil;
  472. if (object) {
  473. // This is a hack to use JSON serialization for our editable objects.
  474. // NSJSONSerialization doesn't allow writing fragments - the top level object must be an array or dictionary.
  475. // We always wrap the object inside an array and then strip the outer square braces off the final string.
  476. NSArray *wrappedObject = @[object];
  477. if ([NSJSONSerialization isValidJSONObject:wrappedObject]) {
  478. NSString *wrappedDescription = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:wrappedObject options:0 error:NULL] encoding:NSUTF8StringEncoding];
  479. editableDescription = [wrappedDescription substringWithRange:NSMakeRange(1, wrappedDescription.length - 2)];
  480. }
  481. }
  482. return editableDescription;
  483. }
  484. + (id)objectValueFromEditableJSONString:(NSString *)string
  485. {
  486. id value = nil;
  487. // nil for empty string/whitespace
  488. if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] > 0) {
  489. value = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:NULL];
  490. }
  491. return value;
  492. }
  493. + (NSValue *)valueForNumberWithObjCType:(const char *)typeEncoding fromInputString:(NSString *)inputString
  494. {
  495. NSNumberFormatter *formatter = [NSNumberFormatter new];
  496. [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
  497. NSNumber *number = [formatter numberFromString:inputString];
  498. // Make sure we box the number with the correct type encoding so it can be properly unboxed later via getValue:
  499. NSValue *value = nil;
  500. if (strcmp(typeEncoding, @encode(char)) == 0) {
  501. char primitiveValue = [number charValue];
  502. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  503. } else if (strcmp(typeEncoding, @encode(int)) == 0) {
  504. int primitiveValue = [number intValue];
  505. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  506. } else if (strcmp(typeEncoding, @encode(short)) == 0) {
  507. short primitiveValue = [number shortValue];
  508. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  509. } else if (strcmp(typeEncoding, @encode(long)) == 0) {
  510. long primitiveValue = [number longValue];
  511. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  512. } else if (strcmp(typeEncoding, @encode(long long)) == 0) {
  513. long long primitiveValue = [number longLongValue];
  514. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  515. } else if (strcmp(typeEncoding, @encode(unsigned char)) == 0) {
  516. unsigned char primitiveValue = [number unsignedCharValue];
  517. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  518. } else if (strcmp(typeEncoding, @encode(unsigned int)) == 0) {
  519. unsigned int primitiveValue = [number unsignedIntValue];
  520. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  521. } else if (strcmp(typeEncoding, @encode(unsigned short)) == 0) {
  522. unsigned short primitiveValue = [number unsignedShortValue];
  523. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  524. } else if (strcmp(typeEncoding, @encode(unsigned long)) == 0) {
  525. unsigned long primitiveValue = [number unsignedLongValue];
  526. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  527. } else if (strcmp(typeEncoding, @encode(unsigned long long)) == 0) {
  528. unsigned long long primitiveValue = [number unsignedLongValue];
  529. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  530. } else if (strcmp(typeEncoding, @encode(float)) == 0) {
  531. float primitiveValue = [number floatValue];
  532. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  533. } else if (strcmp(typeEncoding, @encode(double)) == 0) {
  534. double primitiveValue = [number doubleValue];
  535. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  536. } else if (strcmp(typeEncoding, @encode(long double)) == 0) {
  537. long double primitiveValue = [number doubleValue];
  538. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  539. }
  540. return value;
  541. }
  542. + (void)enumerateTypesInStructEncoding:(const char *)structEncoding usingBlock:(void (^)(NSString *structName, const char *fieldTypeEncoding, NSString *prettyTypeEncoding, NSUInteger fieldIndex, NSUInteger fieldOffset))typeBlock
  543. {
  544. if (structEncoding && structEncoding[0] == FLEXTypeEncodingStructBegin) {
  545. const char *equals = strchr(structEncoding, '=');
  546. if (equals) {
  547. const char *nameStart = structEncoding + 1;
  548. NSString *structName = [@(structEncoding) substringWithRange:NSMakeRange(nameStart - structEncoding, equals - nameStart)];
  549. NSUInteger fieldAlignment = 0;
  550. NSUInteger structSize = 0;
  551. @try {
  552. // NSGetSizeAndAlignment barfs on type encoding for bitfields.
  553. NSGetSizeAndAlignment(structEncoding, &structSize, &fieldAlignment);
  554. } @catch (NSException *exception) { }
  555. if (structSize > 0) {
  556. NSUInteger runningFieldIndex = 0;
  557. NSUInteger runningFieldOffset = 0;
  558. const char *typeStart = equals + 1;
  559. while (*typeStart != FLEXTypeEncodingStructEnd) {
  560. NSUInteger fieldSize = 0;
  561. // If the struct type encoding was successfully handled by NSGetSizeAndAlignment above, we *should* be ok with the field here.
  562. const char *nextTypeStart = NSGetSizeAndAlignment(typeStart, &fieldSize, NULL);
  563. NSString *typeEncoding = [@(structEncoding) substringWithRange:NSMakeRange(typeStart - structEncoding, nextTypeStart - typeStart)];
  564. // Padding to keep proper alignment. __attribute((packed)) structs will break here.
  565. // The type encoding is no different for packed structs, so it's not clear there's anything we can do for those.
  566. const NSUInteger currentSizeSum = runningFieldOffset % fieldAlignment;
  567. if (currentSizeSum != 0 && currentSizeSum + fieldSize > fieldAlignment) {
  568. runningFieldOffset += fieldAlignment - currentSizeSum;
  569. }
  570. typeBlock(structName, typeEncoding.UTF8String, [self readableTypeForEncoding:typeEncoding], runningFieldIndex, runningFieldOffset);
  571. runningFieldOffset += fieldSize;
  572. runningFieldIndex++;
  573. typeStart = nextTypeStart;
  574. }
  575. }
  576. }
  577. }
  578. }
  579. #pragma mark - Internal Helpers
  580. + (NSDictionary<NSString *, NSString *> *)attributesDictionaryForProperty:(objc_property_t)property
  581. {
  582. NSString *attributes = @(property_getAttributes(property));
  583. // Thanks to MAObjcRuntime for inspiration here.
  584. NSArray<NSString *> *attributePairs = [attributes componentsSeparatedByString:@","];
  585. NSMutableDictionary<NSString *, NSString *> *attributesDictionary = [NSMutableDictionary dictionaryWithCapacity:attributePairs.count];
  586. for (NSString *attributePair in attributePairs) {
  587. [attributesDictionary setObject:[attributePair substringFromIndex:1] forKey:[attributePair substringToIndex:1]];
  588. }
  589. return attributesDictionary;
  590. }
  591. + (NSString *)appendName:(NSString *)name toType:(NSString *)type
  592. {
  593. NSString *combined = nil;
  594. if ([type characterAtIndex:type.length - 1] == FLEXTypeEncodingCString) {
  595. combined = [type stringByAppendingString:name];
  596. } else {
  597. combined = [type stringByAppendingFormat:@" %@", name];
  598. }
  599. return combined;
  600. }
  601. + (NSString *)readableTypeForEncoding:(NSString *)encodingString
  602. {
  603. if (!encodingString) {
  604. return nil;
  605. }
  606. // See https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
  607. // class-dump has a much nicer and much more complete implementation for this task, but it is distributed under GPLv2 :/
  608. // See https://github.com/nygard/class-dump/blob/master/Source/CDType.m
  609. // Warning: this method uses multiple middle returns and macros to cut down on boilerplate.
  610. // The use of macros here was inspired by https://www.mikeash.com/pyblog/friday-qa-2013-02-08-lets-build-key-value-coding.html
  611. const char *encodingCString = encodingString.UTF8String;
  612. // Some fields have a name, such as {Size=\"width\"d\"height\"d}, we need to extract the name out and recursive
  613. const NSUInteger fieldNameOffset = [FLEXRuntimeUtility fieldNameOffsetForTypeEncoding:encodingCString];
  614. if (fieldNameOffset > 0) {
  615. // According to https://github.com/nygard/class-dump/commit/33fb5ed221810685f57c192e1ce8ab6054949a7c,
  616. // there are some consecutive quoted strings, so use `_` to concatenate the names.
  617. NSString *const fieldNamesString = [encodingString substringWithRange:NSMakeRange(0, fieldNameOffset)];
  618. NSArray<NSString *> *const fieldNames = [fieldNamesString componentsSeparatedByString:[NSString stringWithFormat:@"%c", FLEXTypeEncodingQuote]];
  619. NSMutableString *finalFieldNamesString = [NSMutableString string];
  620. for (NSString *const fieldName in fieldNames) {
  621. if (fieldName.length > 0) {
  622. if (finalFieldNamesString.length > 0) {
  623. [finalFieldNamesString appendString:@"_"];
  624. }
  625. [finalFieldNamesString appendString:fieldName];
  626. }
  627. }
  628. NSString *const recursiveType = [self readableTypeForEncoding:[encodingString substringFromIndex:fieldNameOffset]];
  629. return [NSString stringWithFormat:@"%@ %@", recursiveType, finalFieldNamesString];
  630. }
  631. // Objects
  632. if (encodingCString[0] == FLEXTypeEncodingObjcObject) {
  633. NSString *class = [encodingString substringFromIndex:1];
  634. class = [class stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%c", FLEXTypeEncodingQuote] withString:@""];
  635. if (class.length == 0 || (class.length == 1 && [class characterAtIndex:0] == FLEXTypeEncodingUnknown)) {
  636. class = @"id";
  637. } else {
  638. class = [class stringByAppendingString:@" *"];
  639. }
  640. return class;
  641. }
  642. // Qualifier Prefixes
  643. // Do this first since some of the direct translations (i.e. Method) contain a prefix.
  644. #define RECURSIVE_TRANSLATE(prefix, formatString) \
  645. if (encodingCString[0] == prefix) { \
  646. NSString *recursiveType = [self readableTypeForEncoding:[encodingString substringFromIndex:1]]; \
  647. return [NSString stringWithFormat:formatString, recursiveType]; \
  648. }
  649. // If there's a qualifier prefix on the encoding, translate it and then
  650. // recursively call this method with the rest of the encoding string.
  651. RECURSIVE_TRANSLATE('^', @"%@ *");
  652. RECURSIVE_TRANSLATE('r', @"const %@");
  653. RECURSIVE_TRANSLATE('n', @"in %@");
  654. RECURSIVE_TRANSLATE('N', @"inout %@");
  655. RECURSIVE_TRANSLATE('o', @"out %@");
  656. RECURSIVE_TRANSLATE('O', @"bycopy %@");
  657. RECURSIVE_TRANSLATE('R', @"byref %@");
  658. RECURSIVE_TRANSLATE('V', @"oneway %@");
  659. RECURSIVE_TRANSLATE('b', @"bitfield(%@)");
  660. #undef RECURSIVE_TRANSLATE
  661. // C Types
  662. #define TRANSLATE(ctype) \
  663. if (strcmp(encodingCString, @encode(ctype)) == 0) { \
  664. return (NSString *)CFSTR(#ctype); \
  665. }
  666. // Order matters here since some of the cocoa types are typedefed to c types.
  667. // We can't recover the exact mapping, but we choose to prefer the cocoa types.
  668. // This is not an exhaustive list, but it covers the most common types
  669. TRANSLATE(CGRect);
  670. TRANSLATE(CGPoint);
  671. TRANSLATE(CGSize);
  672. TRANSLATE(CGVector);
  673. TRANSLATE(UIEdgeInsets);
  674. if (@available(iOS 11.0, *)) {
  675. TRANSLATE(NSDirectionalEdgeInsets);
  676. }
  677. TRANSLATE(UIOffset);
  678. TRANSLATE(NSRange);
  679. TRANSLATE(CGAffineTransform);
  680. TRANSLATE(CATransform3D);
  681. TRANSLATE(CGColorRef);
  682. TRANSLATE(CGPathRef);
  683. TRANSLATE(CGContextRef);
  684. TRANSLATE(NSInteger);
  685. TRANSLATE(NSUInteger);
  686. TRANSLATE(CGFloat);
  687. TRANSLATE(BOOL);
  688. TRANSLATE(int);
  689. TRANSLATE(short);
  690. TRANSLATE(long);
  691. TRANSLATE(long long);
  692. TRANSLATE(unsigned char);
  693. TRANSLATE(unsigned int);
  694. TRANSLATE(unsigned short);
  695. TRANSLATE(unsigned long);
  696. TRANSLATE(unsigned long long);
  697. TRANSLATE(float);
  698. TRANSLATE(double);
  699. TRANSLATE(long double);
  700. TRANSLATE(char *);
  701. TRANSLATE(Class);
  702. TRANSLATE(objc_property_t);
  703. TRANSLATE(Ivar);
  704. TRANSLATE(Method);
  705. TRANSLATE(Category);
  706. TRANSLATE(NSZone *);
  707. TRANSLATE(SEL);
  708. TRANSLATE(void);
  709. #undef TRANSLATE
  710. // For structs, we only use the name of the structs
  711. if (encodingCString[0] == FLEXTypeEncodingStructBegin) {
  712. const char *equals = strchr(encodingCString, '=');
  713. if (equals) {
  714. const char *nameStart = encodingCString + 1;
  715. // For anonymous structs
  716. if (nameStart[0] == FLEXTypeEncodingUnknown) {
  717. return @"anonymous struct";
  718. } else {
  719. NSString *const structName = [encodingString substringWithRange:NSMakeRange(nameStart - encodingCString, equals - nameStart)];
  720. return structName;
  721. }
  722. }
  723. }
  724. // If we couldn't translate, just return the original encoding string
  725. return encodingString;
  726. }
  727. + (NSValue *)valueForPrimitivePointer:(void *)pointer objCType:(const char *)type
  728. {
  729. // Remove the field name if there is any (e.g. \"width\"d -> d)
  730. const NSUInteger fieldNameOffset = [FLEXRuntimeUtility fieldNameOffsetForTypeEncoding:type];
  731. if (fieldNameOffset > 0) {
  732. return [self valueForPrimitivePointer:pointer objCType:type + fieldNameOffset];
  733. }
  734. // CASE macro inspired by https://www.mikeash.com/pyblog/friday-qa-2013-02-08-lets-build-key-value-coding.html
  735. #define CASE(ctype, selectorpart) \
  736. if (strcmp(type, @encode(ctype)) == 0) { \
  737. return [NSNumber numberWith ## selectorpart: *(ctype *)pointer]; \
  738. }
  739. CASE(BOOL, Bool);
  740. CASE(unsigned char, UnsignedChar);
  741. CASE(short, Short);
  742. CASE(unsigned short, UnsignedShort);
  743. CASE(int, Int);
  744. CASE(unsigned int, UnsignedInt);
  745. CASE(long, Long);
  746. CASE(unsigned long, UnsignedLong);
  747. CASE(long long, LongLong);
  748. CASE(unsigned long long, UnsignedLongLong);
  749. CASE(float, Float);
  750. CASE(double, Double);
  751. CASE(long double, Double);
  752. #undef CASE
  753. NSValue *value = nil;
  754. @try {
  755. value = [NSValue valueWithBytes:pointer objCType:type];
  756. } @catch (NSException *exception) {
  757. // Certain type encodings are not supported by valueWithBytes:objCType:. Just fail silently if an exception is thrown.
  758. }
  759. return value;
  760. }
  761. @end