NSObject+Reflection.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. //
  2. // NSObject+Reflection.m
  3. // FLEX
  4. //
  5. // Derived from MirrorKit.
  6. // Created by Tanner on 6/30/15.
  7. // Copyright (c) 2015 Tanner Bennett. All rights reserved.
  8. //
  9. #import "NSObject+Reflection.h"
  10. #import "FLEXClassBuilder.h"
  11. #import "FLEXMirror.h"
  12. #import "FLEXProperty.h"
  13. #import "FLEXMethod.h"
  14. #import "FLEXIvar.h"
  15. #import "FLEXProtocol.h"
  16. #import "FLEXPropertyAttributes.h"
  17. #import "NSArray+Functional.h"
  18. #import "FLEXUtility.h"
  19. NSString * FLEXTypeEncodingString(const char *returnType, NSUInteger count, ...) {
  20. if (returnType == NULL) return nil;
  21. NSMutableString *encoding = [NSMutableString new];
  22. [encoding appendFormat:@"%s%s%s", returnType, @encode(id), @encode(SEL)];
  23. va_list args;
  24. va_start(args, count);
  25. char *type = va_arg(args, char *);
  26. for (NSUInteger i = 0; i < count; i++, type = va_arg(args, char *)) {
  27. [encoding appendFormat:@"%s", type];
  28. }
  29. va_end(args);
  30. return encoding.copy;
  31. }
  32. NSArray<Class> *FLEXGetAllSubclasses(Class cls, BOOL includeSelf) {
  33. if (!cls) {
  34. return nil;
  35. }
  36. Class *buffer = NULL;
  37. int count, size;
  38. do {
  39. count = objc_getClassList(NULL, 0);
  40. buffer = (Class *)realloc(buffer, count * sizeof(*buffer));
  41. size = objc_getClassList(buffer, count);
  42. } while (size != count);
  43. NSMutableArray *classes = [NSMutableArray new];
  44. if (includeSelf) {
  45. [classes addObject:cls];
  46. }
  47. for (int i = 0; i < count; i++) {
  48. Class candidate = buffer[i];
  49. Class superclass = candidate;
  50. while ((superclass = class_getSuperclass(superclass))) {
  51. if (superclass == cls) {
  52. [classes addObject:candidate];
  53. break;
  54. }
  55. }
  56. }
  57. free(buffer);
  58. return classes.copy;
  59. }
  60. NSArray<Class> *FLEXGetClassHierarchy(Class cls, BOOL includeSelf) {
  61. if (!cls) {
  62. return nil;
  63. }
  64. NSMutableArray *classes = [NSMutableArray new];
  65. if (includeSelf) {
  66. [classes addObject:cls];
  67. }
  68. while ((cls = [cls superclass])) {
  69. [classes addObject:cls];
  70. };
  71. return classes.copy;
  72. }
  73. NSArray<FLEXProtocol *> *FLEXGetConformedProtocols(Class cls) {
  74. if (!cls) {
  75. return nil;
  76. }
  77. unsigned int count = 0;
  78. Protocol *__unsafe_unretained *list = class_copyProtocolList(cls, &count);
  79. NSArray<Protocol *> *protocols = [NSArray arrayWithObjects:list count:count];
  80. return [protocols flex_mapped:^id(Protocol *pro, NSUInteger idx) {
  81. return [FLEXProtocol protocol:pro];
  82. }];
  83. }
  84. NSArray<FLEXIvar *> *FLEXGetAllIvars(_Nullable Class cls) {
  85. if (!cls) return nil;
  86. unsigned int ivcount;
  87. Ivar *objcivars = class_copyIvarList(cls, &ivcount);
  88. NSArray *ivars = [NSArray flex_forEachUpTo:ivcount map:^id(NSUInteger i) {
  89. return [FLEXIvar ivar:objcivars[i]];
  90. }];
  91. free(objcivars);
  92. return ivars;
  93. }
  94. NSArray<FLEXProperty *> *FLEXGetAllProperties(_Nullable Class cls) {
  95. if (!cls) return nil;
  96. unsigned int pcount;
  97. objc_property_t *objcproperties = class_copyPropertyList(cls, &pcount);
  98. NSArray *properties = [NSArray flex_forEachUpTo:pcount map:^id(NSUInteger i) {
  99. return [FLEXProperty property:objcproperties[i] onClass:cls];
  100. }];
  101. free(objcproperties);
  102. return properties;
  103. }
  104. NSArray<FLEXMethod *> *FLEXGetAllMethods(_Nullable Class cls, BOOL instance) {
  105. if (!cls) return nil;
  106. unsigned int mcount;
  107. Method *objcmethods = class_copyMethodList(cls, &mcount);
  108. NSArray *methods = [NSArray flex_forEachUpTo:mcount map:^id(NSUInteger i) {
  109. return [FLEXMethod method:objcmethods[i] isInstanceMethod:instance];
  110. }];
  111. free(objcmethods);
  112. return methods;
  113. }
  114. #pragma mark NSProxy
  115. @interface NSProxy (AnyObjectAdditions) @end
  116. @implementation NSProxy (AnyObjectAdditions)
  117. + (void)load { FLEX_EXIT_IF_TESTING()
  118. // We need to get all of the methods in this file and add them to NSProxy.
  119. // To do this we we need the class itself and it's metaclass.
  120. // Edit: also add them to Swift._SwiftObject
  121. Class NSProxyClass = [NSProxy class];
  122. Class NSProxy_meta = object_getClass(NSProxyClass);
  123. Class SwiftObjectClass = (
  124. NSClassFromString(@"SwiftObject") ?: NSClassFromString(@"Swift._SwiftObject")
  125. );
  126. // Copy all of the "flex_" methods from NSObject
  127. id filterFunc = ^BOOL(FLEXMethod *method, NSUInteger idx) {
  128. return [method.name hasPrefix:@"flex_"];
  129. };
  130. NSArray *instanceMethods = [NSObject.flex_allInstanceMethods flex_filtered:filterFunc];
  131. NSArray *classMethods = [NSObject.flex_allClassMethods flex_filtered:filterFunc];
  132. FLEXClassBuilder *proxy = [FLEXClassBuilder builderForClass:NSProxyClass];
  133. FLEXClassBuilder *proxyMeta = [FLEXClassBuilder builderForClass:NSProxy_meta];
  134. [proxy addMethods:instanceMethods];
  135. [proxyMeta addMethods:classMethods];
  136. if (SwiftObjectClass) {
  137. Class SwiftObject_meta = object_getClass(SwiftObjectClass);
  138. FLEXClassBuilder *swiftObject = [FLEXClassBuilder builderForClass:SwiftObjectClass];
  139. FLEXClassBuilder *swiftObjectMeta = [FLEXClassBuilder builderForClass:SwiftObject_meta];
  140. [swiftObject addMethods:instanceMethods];
  141. [swiftObjectMeta addMethods:classMethods];
  142. // So we can put Swift objects into dictionaries...
  143. [swiftObjectMeta addMethods:@[
  144. [NSObject flex_classMethodNamed:@"copyWithZone:"]]
  145. ];
  146. }
  147. }
  148. @end
  149. #pragma mark Reflection
  150. @implementation NSObject (Reflection)
  151. + (FLEXMirror *)flex_reflection {
  152. return [FLEXMirror reflect:self];
  153. }
  154. - (FLEXMirror *)flex_reflection {
  155. return [FLEXMirror reflect:self];
  156. }
  157. /// Code borrowed from MAObjCRuntime by Mike Ash
  158. + (NSArray *)flex_allSubclasses {
  159. return FLEXGetAllSubclasses(self, YES);
  160. }
  161. - (Class)flex_setClass:(Class)cls {
  162. return object_setClass(self, cls);
  163. }
  164. + (Class)flex_metaclass {
  165. return objc_getMetaClass(NSStringFromClass(self.class).UTF8String);
  166. }
  167. + (size_t)flex_instanceSize {
  168. return class_getInstanceSize(self.class);
  169. }
  170. + (Class)flex_setSuperclass:(Class)superclass {
  171. #pragma clang diagnostic push
  172. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  173. return class_setSuperclass(self, superclass);
  174. #pragma clang diagnostic pop
  175. }
  176. + (NSArray<Class> *)flex_classHierarchy {
  177. return FLEXGetClassHierarchy(self, YES);
  178. }
  179. + (NSArray<FLEXProtocol *> *)flex_protocols {
  180. return FLEXGetConformedProtocols(self);
  181. }
  182. @end
  183. #pragma mark Methods
  184. @implementation NSObject (Methods)
  185. + (NSArray<FLEXMethod *> *)flex_allMethods {
  186. NSMutableArray *instanceMethods = (id)self.flex_allInstanceMethods;
  187. [instanceMethods addObjectsFromArray:self.flex_allClassMethods];
  188. return instanceMethods;
  189. }
  190. + (NSArray<FLEXMethod *> *)flex_allInstanceMethods {
  191. return FLEXGetAllMethods(self, YES);
  192. }
  193. + (NSArray<FLEXMethod *> *)flex_allClassMethods {
  194. return FLEXGetAllMethods(self.flex_metaclass, NO);
  195. }
  196. + (FLEXMethod *)flex_methodNamed:(NSString *)name {
  197. Method m = class_getInstanceMethod([self class], NSSelectorFromString(name));
  198. if (m == NULL) {
  199. return nil;
  200. }
  201. return [FLEXMethod method:m isInstanceMethod:YES];
  202. }
  203. + (FLEXMethod *)flex_classMethodNamed:(NSString *)name {
  204. Method m = class_getClassMethod([self class], NSSelectorFromString(name));
  205. if (m == NULL) {
  206. return nil;
  207. }
  208. return [FLEXMethod method:m isInstanceMethod:NO];
  209. }
  210. + (BOOL)addMethod:(SEL)selector
  211. typeEncoding:(NSString *)typeEncoding
  212. implementation:(IMP)implementaiton
  213. toInstances:(BOOL)instance {
  214. return class_addMethod(instance ? self.class : self.flex_metaclass, selector, implementaiton, typeEncoding.UTF8String);
  215. }
  216. + (IMP)replaceImplementationOfMethod:(FLEXMethodBase *)method with:(IMP)implementation useInstance:(BOOL)instance {
  217. return class_replaceMethod(instance ? self.class : self.flex_metaclass, method.selector, implementation, method.typeEncoding.UTF8String);
  218. }
  219. + (void)swizzle:(FLEXMethodBase *)original with:(FLEXMethodBase *)other onInstance:(BOOL)instance {
  220. [self swizzleBySelector:original.selector with:other.selector onInstance:instance];
  221. }
  222. + (BOOL)swizzleByName:(NSString *)original with:(NSString *)other onInstance:(BOOL)instance {
  223. SEL originalMethod = NSSelectorFromString(original);
  224. SEL newMethod = NSSelectorFromString(other);
  225. if (originalMethod == 0 || newMethod == 0) {
  226. return NO;
  227. }
  228. [self swizzleBySelector:originalMethod with:newMethod onInstance:instance];
  229. return YES;
  230. }
  231. + (void)swizzleBySelector:(SEL)original with:(SEL)other onInstance:(BOOL)instance {
  232. Class cls = instance ? self.class : self.flex_metaclass;
  233. Method originalMethod = class_getInstanceMethod(cls, original);
  234. Method newMethod = class_getInstanceMethod(cls, other);
  235. if (class_addMethod(cls, original, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
  236. class_replaceMethod(cls, other, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
  237. } else {
  238. method_exchangeImplementations(originalMethod, newMethod);
  239. }
  240. }
  241. @end
  242. #pragma mark Ivars
  243. @implementation NSObject (Ivars)
  244. + (NSArray<FLEXIvar *> *)flex_allIvars {
  245. return FLEXGetAllIvars(self);
  246. }
  247. + (FLEXIvar *)flex_ivarNamed:(NSString *)name {
  248. Ivar i = class_getInstanceVariable([self class], name.UTF8String);
  249. if (i == NULL) {
  250. return nil;
  251. }
  252. return [FLEXIvar ivar:i];
  253. }
  254. #pragma mark Get address
  255. - (void *)flex_getIvarAddress:(FLEXIvar *)ivar {
  256. return (uint8_t *)(__bridge void *)self + ivar.offset;
  257. }
  258. - (void *)flex_getObjcIvarAddress:(Ivar)ivar {
  259. return (uint8_t *)(__bridge void *)self + ivar_getOffset(ivar);
  260. }
  261. - (void *)flex_getIvarAddressByName:(NSString *)name {
  262. Ivar ivar = class_getInstanceVariable(self.class, name.UTF8String);
  263. if (!ivar) return 0;
  264. return (uint8_t *)(__bridge void *)self + ivar_getOffset(ivar);
  265. }
  266. #pragma mark Set ivar object
  267. - (void)flex_setIvar:(FLEXIvar *)ivar object:(id)value {
  268. object_setIvar(self, ivar.objc_ivar, value);
  269. }
  270. - (BOOL)flex_setIvarByName:(NSString *)name object:(id)value {
  271. Ivar ivar = class_getInstanceVariable(self.class, name.UTF8String);
  272. if (!ivar) return NO;
  273. object_setIvar(self, ivar, value);
  274. return YES;
  275. }
  276. - (void)flex_setObjcIvar:(Ivar)ivar object:(id)value {
  277. object_setIvar(self, ivar, value);
  278. }
  279. #pragma mark Set ivar value
  280. - (void)flex_setIvar:(FLEXIvar *)ivar value:(void *)value size:(size_t)size {
  281. void *address = [self flex_getIvarAddress:ivar];
  282. memcpy(address, value, size);
  283. }
  284. - (BOOL)flex_setIvarByName:(NSString *)name value:(void *)value size:(size_t)size {
  285. Ivar ivar = class_getInstanceVariable(self.class, name.UTF8String);
  286. if (!ivar) return NO;
  287. [self flex_setObjcIvar:ivar value:value size:size];
  288. return YES;
  289. }
  290. - (void)flex_setObjcIvar:(Ivar)ivar value:(void *)value size:(size_t)size {
  291. void *address = [self flex_getObjcIvarAddress:ivar];
  292. memcpy(address, value, size);
  293. }
  294. @end
  295. #pragma mark Properties
  296. @implementation NSObject (Properties)
  297. + (NSArray<FLEXProperty *> *)flex_allProperties {
  298. NSMutableArray *instanceProperties = (id)self.flex_allInstanceProperties;
  299. [instanceProperties addObjectsFromArray:self.flex_allClassProperties];
  300. return instanceProperties;
  301. }
  302. + (NSArray<FLEXProperty *> *)flex_allInstanceProperties {
  303. return FLEXGetAllProperties(self);
  304. }
  305. + (NSArray<FLEXProperty *> *)flex_allClassProperties {
  306. return FLEXGetAllProperties(self.flex_metaclass);
  307. }
  308. + (FLEXProperty *)flex_propertyNamed:(NSString *)name {
  309. objc_property_t p = class_getProperty([self class], name.UTF8String);
  310. if (p == NULL) {
  311. return nil;
  312. }
  313. return [FLEXProperty property:p onClass:self];
  314. }
  315. + (FLEXProperty *)flex_classPropertyNamed:(NSString *)name {
  316. objc_property_t p = class_getProperty(object_getClass(self), name.UTF8String);
  317. if (p == NULL) {
  318. return nil;
  319. }
  320. return [FLEXProperty property:p onClass:object_getClass(self)];
  321. }
  322. + (void)flex_replaceProperty:(FLEXProperty *)property {
  323. [self flex_replaceProperty:property.name attributes:property.attributes];
  324. }
  325. + (void)flex_replaceProperty:(NSString *)name attributes:(FLEXPropertyAttributes *)attributes {
  326. unsigned int count;
  327. objc_property_attribute_t *objc_attributes = [attributes copyAttributesList:&count];
  328. class_replaceProperty([self class], name.UTF8String, objc_attributes, count);
  329. free(objc_attributes);
  330. }
  331. @end