NSObject+Reflection.m 12 KB

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