FLEXRuntimeUtility.m 34 KB

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