FLEXRuntimeUtility.m 34 KB

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