FLEXRuntimeUtility.m 34 KB

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