FLEXRuntimeUtility.m 34 KB

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