FLEXRuntimeUtility.m 39 KB

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