FLEXRuntimeUtility.m 34 KB

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