NSObject+Reflection.m 12 KB

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