NSObject+Reflection.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. #pragma mark NSProxy
  85. @interface NSProxy (AnyObjectAdditions) @end
  86. @implementation NSProxy (AnyObjectAdditions)
  87. + (void)load { FLEX_EXIT_IF_TESTING()
  88. // We need to get all of the methods in this file and add them to NSProxy.
  89. // To do this we we need the class itself and it's metaclass.
  90. // Edit: also add them to Swift._SwiftObject
  91. Class NSProxyClass = [NSProxy class];
  92. Class NSProxy_meta = object_getClass(NSProxyClass);
  93. Class SwiftObjectClass = (
  94. NSClassFromString(@"SwiftObject") ?: NSClassFromString(@"Swift._SwiftObject")
  95. );
  96. // Copy all of the "flex_" methods from NSObject
  97. id filterFunc = ^BOOL(FLEXMethod *method, NSUInteger idx) {
  98. return [method.name hasPrefix:@"flex_"];
  99. };
  100. NSArray *instanceMethods = [[NSObject flex_allInstanceMethods] flex_filtered:filterFunc];
  101. NSArray *classMethods = [[NSObject flex_allClassMethods] flex_filtered:filterFunc];
  102. FLEXClassBuilder *proxy = [FLEXClassBuilder builderForClass:NSProxyClass];
  103. FLEXClassBuilder *proxyMeta = [FLEXClassBuilder builderForClass:NSProxy_meta];
  104. [proxy addMethods:instanceMethods];
  105. [proxyMeta addMethods:classMethods];
  106. if (SwiftObjectClass) {
  107. Class SwiftObject_meta = object_getClass(SwiftObjectClass);
  108. FLEXClassBuilder *swiftObject = [FLEXClassBuilder builderForClass:SwiftObjectClass];
  109. FLEXClassBuilder *swiftObjectMeta = [FLEXClassBuilder builderForClass:SwiftObject_meta];
  110. [swiftObject addMethods:instanceMethods];
  111. [swiftObjectMeta addMethods:classMethods];
  112. }
  113. }
  114. @end
  115. #pragma mark Reflection
  116. @implementation NSObject (Reflection)
  117. + (FLEXMirror *)flex_reflection {
  118. return [FLEXMirror reflect:self];
  119. }
  120. - (FLEXMirror *)flex_reflection {
  121. return [FLEXMirror reflect:self];
  122. }
  123. /// Code borrowed from MAObjCRuntime by Mike Ash
  124. + (NSArray *)flex_allSubclasses {
  125. return FLEXGetAllSubclasses(self, YES);
  126. }
  127. - (Class)flex_setClass:(Class)cls {
  128. return object_setClass(self, cls);
  129. }
  130. + (Class)flex_metaclass {
  131. return objc_getMetaClass(NSStringFromClass(self.class).UTF8String);
  132. }
  133. + (size_t)flex_instanceSize {
  134. return class_getInstanceSize(self.class);
  135. }
  136. + (Class)flex_setSuperclass:(Class)superclass {
  137. #pragma clang diagnostic push
  138. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  139. return class_setSuperclass(self, superclass);
  140. #pragma clang diagnostic pop
  141. }
  142. + (NSArray<Class> *)flex_classHierarchy {
  143. return FLEXGetClassHierarchy(self, YES);
  144. }
  145. + (NSArray<FLEXProtocol *> *)flex_protocols {
  146. return FLEXGetConformedProtocols(self);
  147. }
  148. @end
  149. #pragma mark Methods
  150. @implementation NSObject (Methods)
  151. + (NSArray<FLEXMethod *> *)flex_allMethods {
  152. NSMutableArray *instanceMethods = (id)self.flex_allInstanceMethods;
  153. [instanceMethods addObjectsFromArray:self.flex_allClassMethods];
  154. return instanceMethods;
  155. }
  156. + (NSArray<FLEXMethod *> *)flex_allInstanceMethods {
  157. unsigned int mcount;
  158. Method *objcmethods = class_copyMethodList([self class], &mcount);
  159. NSMutableArray *methods = [NSMutableArray new];
  160. for (int i = 0; i < mcount; i++) {
  161. FLEXMethod *m = [FLEXMethod method:objcmethods[i] isInstanceMethod:YES];
  162. if (m) {
  163. [methods addObject:m];
  164. }
  165. }
  166. free(objcmethods);
  167. return methods;
  168. }
  169. + (NSArray<FLEXMethod *> *)flex_allClassMethods {
  170. unsigned int mcount;
  171. Method *objcmethods = class_copyMethodList(self.flex_metaclass, &mcount);
  172. NSMutableArray *methods = [NSMutableArray new];
  173. for (int i = 0; i < mcount; i++) {
  174. FLEXMethod *m = [FLEXMethod method:objcmethods[i] isInstanceMethod:NO];
  175. if (m) {
  176. [methods addObject:m];
  177. }
  178. }
  179. free(objcmethods);
  180. return methods;
  181. }
  182. + (FLEXMethod *)flex_methodNamed:(NSString *)name {
  183. Method m = class_getInstanceMethod([self class], NSSelectorFromString(name));
  184. if (m == NULL) {
  185. return nil;
  186. }
  187. return [FLEXMethod method:m isInstanceMethod:YES];
  188. }
  189. + (FLEXMethod *)flex_classMethodNamed:(NSString *)name {
  190. Method m = class_getClassMethod([self class], NSSelectorFromString(name));
  191. if (m == NULL) {
  192. return nil;
  193. }
  194. return [FLEXMethod method:m isInstanceMethod:NO];
  195. }
  196. + (BOOL)addMethod:(SEL)selector
  197. typeEncoding:(NSString *)typeEncoding
  198. implementation:(IMP)implementaiton
  199. toInstances:(BOOL)instance {
  200. return class_addMethod(instance ? self.class : self.flex_metaclass, selector, implementaiton, typeEncoding.UTF8String);
  201. }
  202. + (IMP)replaceImplementationOfMethod:(FLEXMethodBase *)method with:(IMP)implementation useInstance:(BOOL)instance {
  203. return class_replaceMethod(instance ? self.class : self.flex_metaclass, method.selector, implementation, method.typeEncoding.UTF8String);
  204. }
  205. + (void)swizzle:(FLEXMethodBase *)original with:(FLEXMethodBase *)other onInstance:(BOOL)instance {
  206. [self swizzleBySelector:original.selector with:other.selector onInstance:instance];
  207. }
  208. + (BOOL)swizzleByName:(NSString *)original with:(NSString *)other onInstance:(BOOL)instance {
  209. SEL originalMethod = NSSelectorFromString(original);
  210. SEL newMethod = NSSelectorFromString(other);
  211. if (originalMethod == 0 || newMethod == 0) {
  212. return NO;
  213. }
  214. [self swizzleBySelector:originalMethod with:newMethod onInstance:instance];
  215. return YES;
  216. }
  217. + (void)swizzleBySelector:(SEL)original with:(SEL)other onInstance:(BOOL)instance {
  218. Class cls = instance ? self.class : self.flex_metaclass;
  219. Method originalMethod = class_getInstanceMethod(cls, original);
  220. Method newMethod = class_getInstanceMethod(cls, other);
  221. if (class_addMethod(cls, original, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
  222. class_replaceMethod(cls, other, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
  223. } else {
  224. method_exchangeImplementations(originalMethod, newMethod);
  225. }
  226. }
  227. @end
  228. #pragma mark Ivars
  229. @implementation NSObject (Ivars)
  230. + (NSArray<FLEXIvar *> *)flex_allIvars {
  231. unsigned int ivcount;
  232. Ivar *objcivars = class_copyIvarList([self class], &ivcount);
  233. NSMutableArray *ivars = [NSMutableArray new];
  234. for (int i = 0; i < ivcount; i++) {
  235. [ivars addObject:[FLEXIvar ivar:objcivars[i]]];
  236. }
  237. free(objcivars);
  238. return ivars;
  239. }
  240. + (FLEXIvar *)flex_ivarNamed:(NSString *)name {
  241. Ivar i = class_getInstanceVariable([self class], name.UTF8String);
  242. if (i == NULL) {
  243. return nil;
  244. }
  245. return [FLEXIvar ivar:i];
  246. }
  247. #pragma mark Get address
  248. - (void *)flex_getIvarAddress:(FLEXIvar *)ivar {
  249. return (uint8_t *)(__bridge void *)self + ivar.offset;
  250. }
  251. - (void *)flex_getObjcIvarAddress:(Ivar)ivar {
  252. return (uint8_t *)(__bridge void *)self + ivar_getOffset(ivar);
  253. }
  254. - (void *)flex_getIvarAddressByName:(NSString *)name {
  255. Ivar ivar = class_getInstanceVariable(self.class, name.UTF8String);
  256. if (!ivar) return 0;
  257. return (uint8_t *)(__bridge void *)self + ivar_getOffset(ivar);
  258. }
  259. #pragma mark Set ivar object
  260. - (void)flex_setIvar:(FLEXIvar *)ivar object:(id)value {
  261. object_setIvar(self, ivar.objc_ivar, value);
  262. }
  263. - (BOOL)flex_setIvarByName:(NSString *)name object:(id)value {
  264. Ivar ivar = class_getInstanceVariable(self.class, name.UTF8String);
  265. if (!ivar) return NO;
  266. object_setIvar(self, ivar, value);
  267. return YES;
  268. }
  269. - (void)flex_setObjcIvar:(Ivar)ivar object:(id)value {
  270. object_setIvar(self, ivar, value);
  271. }
  272. #pragma mark Set ivar value
  273. - (void)flex_setIvar:(FLEXIvar *)ivar value:(void *)value size:(size_t)size {
  274. void *address = [self flex_getIvarAddress:ivar];
  275. memcpy(address, value, size);
  276. }
  277. - (BOOL)flex_setIvarByName:(NSString *)name value:(void *)value size:(size_t)size {
  278. Ivar ivar = class_getInstanceVariable(self.class, name.UTF8String);
  279. if (!ivar) return NO;
  280. [self flex_setObjcIvar:ivar value:value size:size];
  281. return YES;
  282. }
  283. - (void)flex_setObjcIvar:(Ivar)ivar value:(void *)value size:(size_t)size {
  284. void *address = [self flex_getObjcIvarAddress:ivar];
  285. memcpy(address, value, size);
  286. }
  287. @end
  288. #pragma mark Properties
  289. @implementation NSObject (Properties)
  290. + (NSArray<FLEXProperty *> *)flex_allProperties {
  291. NSMutableArray *instanceProperties = (id)self.flex_allInstanceProperties;
  292. [instanceProperties addObjectsFromArray:self.flex_allClassProperties];
  293. return instanceProperties;
  294. }
  295. + (NSArray<FLEXProperty *> *)flex_allInstanceProperties {
  296. unsigned int pcount;
  297. objc_property_t *objcproperties = class_copyPropertyList(self, &pcount);
  298. NSMutableArray *properties = [NSMutableArray new];
  299. for (int i = 0; i < pcount; i++) {
  300. [properties addObject:[FLEXProperty property:objcproperties[i] onClass:self]];
  301. }
  302. free(objcproperties);
  303. return properties;
  304. }
  305. + (NSArray<FLEXProperty *> *)flex_allClassProperties {
  306. Class metaclass = self.flex_metaclass;
  307. unsigned int pcount;
  308. objc_property_t *objcproperties = class_copyPropertyList(metaclass, &pcount);
  309. NSMutableArray *properties = [NSMutableArray new];
  310. for (int i = 0; i < pcount; i++) {
  311. [properties addObject:[FLEXProperty property:objcproperties[i] onClass:metaclass]];
  312. }
  313. free(objcproperties);
  314. return properties;
  315. }
  316. + (FLEXProperty *)flex_propertyNamed:(NSString *)name {
  317. objc_property_t p = class_getProperty([self class], name.UTF8String);
  318. if (p == NULL) {
  319. return nil;
  320. }
  321. return [FLEXProperty property:p onClass:self];
  322. }
  323. + (FLEXProperty *)flex_classPropertyNamed:(NSString *)name {
  324. objc_property_t p = class_getProperty(object_getClass(self), name.UTF8String);
  325. if (p == NULL) {
  326. return nil;
  327. }
  328. return [FLEXProperty property:p onClass:object_getClass(self)];
  329. }
  330. + (void)flex_replaceProperty:(FLEXProperty *)property {
  331. [self flex_replaceProperty:property.name attributes:property.attributes];
  332. }
  333. + (void)flex_replaceProperty:(NSString *)name attributes:(FLEXPropertyAttributes *)attributes {
  334. unsigned int count;
  335. objc_property_attribute_t *objc_attributes = [attributes copyAttributesList:&count];
  336. class_replaceProperty([self class], name.UTF8String, objc_attributes, count);
  337. free(objc_attributes);
  338. }
  339. @end