FLEXRuntimeUtility.m 34 KB

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