NSObject+RACSelectorSignal.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. //
  2. // NSObject+RACSelectorSignal.m
  3. // ReactiveObjC
  4. //
  5. // Created by Josh Abernathy on 3/18/13.
  6. // Copyright (c) 2013 GitHub, Inc. All rights reserved.
  7. //
  8. #import "NSObject+RACSelectorSignal.h"
  9. #import <ReactiveObjC/RACEXTRuntimeExtensions.h>
  10. #import "NSInvocation+RACTypeParsing.h"
  11. #import "NSObject+RACDeallocating.h"
  12. #import "RACCompoundDisposable.h"
  13. #import "RACDisposable.h"
  14. #import "RACSubject.h"
  15. #import "RACTuple.h"
  16. #import "NSObject+RACDescription.h"
  17. #import <objc/message.h>
  18. #import <objc/runtime.h>
  19. NSErrorDomain const RACSelectorSignalErrorDomain = @"RACSelectorSignalErrorDomain";
  20. static NSString * const RACSignalForSelectorAliasPrefix = @"rac_alias_";
  21. static NSString * const RACSubclassSuffix = @"_RACSelectorSignal";
  22. static void *RACSubclassAssociationKey = &RACSubclassAssociationKey;
  23. static NSMutableSet *swizzledClasses() {
  24. static NSMutableSet *set;
  25. static dispatch_once_t pred;
  26. dispatch_once(&pred, ^{
  27. set = [[NSMutableSet alloc] init];
  28. });
  29. return set;
  30. }
  31. @implementation NSObject (RACSelectorSignal)
  32. static BOOL RACForwardInvocation(id self, NSInvocation *invocation) {
  33. SEL aliasSelector = RACAliasForSelector(invocation.selector);
  34. RACSubject *subject = objc_getAssociatedObject(self, aliasSelector);
  35. Class class = object_getClass(invocation.target);
  36. BOOL respondsToAlias = [class instancesRespondToSelector:aliasSelector];
  37. if (respondsToAlias) {
  38. invocation.selector = aliasSelector;
  39. [invocation invoke];
  40. }
  41. if (subject == nil) return respondsToAlias;
  42. [subject sendNext:invocation.rac_argumentsTuple];
  43. return YES;
  44. }
  45. static void RACSwizzleForwardInvocation(Class class) {
  46. SEL forwardInvocationSEL = @selector(forwardInvocation:);
  47. Method forwardInvocationMethod = class_getInstanceMethod(class, forwardInvocationSEL);
  48. // Preserve any existing implementation of -forwardInvocation:.
  49. void (*originalForwardInvocation)(id, SEL, NSInvocation *) = NULL;
  50. if (forwardInvocationMethod != NULL) {
  51. originalForwardInvocation = (__typeof__(originalForwardInvocation))method_getImplementation(forwardInvocationMethod);
  52. }
  53. // Set up a new version of -forwardInvocation:.
  54. //
  55. // If the selector has been passed to -rac_signalForSelector:, invoke
  56. // the aliased method, and forward the arguments to any attached signals.
  57. //
  58. // If the selector has not been passed to -rac_signalForSelector:,
  59. // invoke any existing implementation of -forwardInvocation:. If there
  60. // was no existing implementation, throw an unrecognized selector
  61. // exception.
  62. id newForwardInvocation = ^(id self, NSInvocation *invocation) {
  63. BOOL matched = RACForwardInvocation(self, invocation);
  64. if (matched) return;
  65. if (originalForwardInvocation == NULL) {
  66. [self doesNotRecognizeSelector:invocation.selector];
  67. } else {
  68. originalForwardInvocation(self, forwardInvocationSEL, invocation);
  69. }
  70. };
  71. class_replaceMethod(class, forwardInvocationSEL, imp_implementationWithBlock(newForwardInvocation), "v@:@");
  72. }
  73. static void RACSwizzleRespondsToSelector(Class class) {
  74. SEL respondsToSelectorSEL = @selector(respondsToSelector:);
  75. // Preserve existing implementation of -respondsToSelector:.
  76. Method respondsToSelectorMethod = class_getInstanceMethod(class, respondsToSelectorSEL);
  77. BOOL (*originalRespondsToSelector)(id, SEL, SEL) = (__typeof__(originalRespondsToSelector))method_getImplementation(respondsToSelectorMethod);
  78. // Set up a new version of -respondsToSelector: that returns YES for methods
  79. // added by -rac_signalForSelector:.
  80. //
  81. // If the selector has a method defined on the receiver's actual class, and
  82. // if that method's implementation is _objc_msgForward, then returns whether
  83. // the instance has a signal for the selector.
  84. // Otherwise, call the original -respondsToSelector:.
  85. id newRespondsToSelector = ^ BOOL (id self, SEL selector) {
  86. Method method = rac_getImmediateInstanceMethod(class, selector);
  87. if (method != NULL && method_getImplementation(method) == _objc_msgForward) {
  88. SEL aliasSelector = RACAliasForSelector(selector);
  89. if (objc_getAssociatedObject(self, aliasSelector) != nil) return YES;
  90. }
  91. return originalRespondsToSelector(self, respondsToSelectorSEL, selector);
  92. };
  93. class_replaceMethod(class, respondsToSelectorSEL, imp_implementationWithBlock(newRespondsToSelector), method_getTypeEncoding(respondsToSelectorMethod));
  94. }
  95. static void RACSwizzleGetClass(Class class, Class statedClass) {
  96. SEL selector = @selector(class);
  97. Method method = class_getInstanceMethod(class, selector);
  98. IMP newIMP = imp_implementationWithBlock(^(id self) {
  99. return statedClass;
  100. });
  101. class_replaceMethod(class, selector, newIMP, method_getTypeEncoding(method));
  102. }
  103. static void RACSwizzleMethodSignatureForSelector(Class class) {
  104. IMP newIMP = imp_implementationWithBlock(^(id self, SEL selector) {
  105. // Don't send the -class message to the receiver because we've changed
  106. // that to return the original class.
  107. Class actualClass = object_getClass(self);
  108. Method method = class_getInstanceMethod(actualClass, selector);
  109. if (method == NULL) {
  110. // Messages that the original class dynamically implements fall
  111. // here.
  112. //
  113. // Call the original class' -methodSignatureForSelector:.
  114. struct objc_super target = {
  115. .super_class = class_getSuperclass(class),
  116. .receiver = self,
  117. };
  118. NSMethodSignature * (*messageSend)(struct objc_super *, SEL, SEL) = (__typeof__(messageSend))objc_msgSendSuper;
  119. return messageSend(&target, @selector(methodSignatureForSelector:), selector);
  120. }
  121. char const *encoding = method_getTypeEncoding(method);
  122. return [NSMethodSignature signatureWithObjCTypes:encoding];
  123. });
  124. SEL selector = @selector(methodSignatureForSelector:);
  125. Method methodSignatureForSelectorMethod = class_getInstanceMethod(class, selector);
  126. class_replaceMethod(class, selector, newIMP, method_getTypeEncoding(methodSignatureForSelectorMethod));
  127. }
  128. // It's hard to tell which struct return types use _objc_msgForward, and
  129. // which use _objc_msgForward_stret instead, so just exclude all struct, array,
  130. // union, complex and vector return types.
  131. static void RACCheckTypeEncoding(const char *typeEncoding) {
  132. #if !NS_BLOCK_ASSERTIONS
  133. // Some types, including vector types, are not encoded. In these cases the
  134. // signature starts with the size of the argument frame.
  135. NSCAssert(*typeEncoding < '1' || *typeEncoding > '9', @"unknown method return type not supported in type encoding: %s", typeEncoding);
  136. NSCAssert(strstr(typeEncoding, "(") != typeEncoding, @"union method return type not supported");
  137. NSCAssert(strstr(typeEncoding, "{") != typeEncoding, @"struct method return type not supported");
  138. NSCAssert(strstr(typeEncoding, "[") != typeEncoding, @"array method return type not supported");
  139. NSCAssert(strstr(typeEncoding, @encode(_Complex float)) != typeEncoding, @"complex float method return type not supported");
  140. NSCAssert(strstr(typeEncoding, @encode(_Complex double)) != typeEncoding, @"complex double method return type not supported");
  141. NSCAssert(strstr(typeEncoding, @encode(_Complex long double)) != typeEncoding, @"complex long double method return type not supported");
  142. #endif // !NS_BLOCK_ASSERTIONS
  143. }
  144. static RACSignal *NSObjectRACSignalForSelector(NSObject *self, SEL selector, Protocol *protocol) {
  145. SEL aliasSelector = RACAliasForSelector(selector);
  146. @synchronized (self) {
  147. RACSubject *subject = objc_getAssociatedObject(self, aliasSelector);
  148. if (subject != nil) return subject;
  149. Class class = RACSwizzleClass(self);
  150. NSCAssert(class != nil, @"Could not swizzle class of %@", self);
  151. subject = [[RACSubject subject] setNameWithFormat:@"%@ -rac_signalForSelector: %s", RACDescription(self), sel_getName(selector)];
  152. objc_setAssociatedObject(self, aliasSelector, subject, OBJC_ASSOCIATION_RETAIN);
  153. [self.rac_deallocDisposable addDisposable:[RACDisposable disposableWithBlock:^{
  154. [subject sendCompleted];
  155. }]];
  156. Method targetMethod = class_getInstanceMethod(class, selector);
  157. if (targetMethod == NULL) {
  158. const char *typeEncoding;
  159. if (protocol == NULL) {
  160. typeEncoding = RACSignatureForUndefinedSelector(selector);
  161. } else {
  162. // Look for the selector as an optional instance method.
  163. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  164. if (methodDescription.name == NULL) {
  165. // Then fall back to looking for a required instance
  166. // method.
  167. methodDescription = protocol_getMethodDescription(protocol, selector, YES, YES);
  168. NSCAssert(methodDescription.name != NULL, @"Selector %@ does not exist in <%s>", NSStringFromSelector(selector), protocol_getName(protocol));
  169. }
  170. typeEncoding = methodDescription.types;
  171. }
  172. RACCheckTypeEncoding(typeEncoding);
  173. // Define the selector to call -forwardInvocation:.
  174. if (!class_addMethod(class, selector, _objc_msgForward, typeEncoding)) {
  175. NSDictionary *userInfo = @{
  176. NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedString(@"A race condition occurred implementing %@ on class %@", nil), NSStringFromSelector(selector), class],
  177. NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Invoke -rac_signalForSelector: again to override the implementation.", nil)
  178. };
  179. return [RACSignal error:[NSError errorWithDomain:RACSelectorSignalErrorDomain code:RACSelectorSignalErrorMethodSwizzlingRace userInfo:userInfo]];
  180. }
  181. } else if (method_getImplementation(targetMethod) != _objc_msgForward) {
  182. // Make a method alias for the existing method implementation.
  183. const char *typeEncoding = method_getTypeEncoding(targetMethod);
  184. RACCheckTypeEncoding(typeEncoding);
  185. BOOL addedAlias __attribute__((unused)) = class_addMethod(class, aliasSelector, method_getImplementation(targetMethod), typeEncoding);
  186. NSCAssert(addedAlias, @"Original implementation for %@ is already copied to %@ on %@", NSStringFromSelector(selector), NSStringFromSelector(aliasSelector), class);
  187. // Redefine the selector to call -forwardInvocation:.
  188. class_replaceMethod(class, selector, _objc_msgForward, method_getTypeEncoding(targetMethod));
  189. }
  190. return subject;
  191. }
  192. }
  193. static SEL RACAliasForSelector(SEL originalSelector) {
  194. NSString *selectorName = NSStringFromSelector(originalSelector);
  195. return NSSelectorFromString([RACSignalForSelectorAliasPrefix stringByAppendingString:selectorName]);
  196. }
  197. static const char *RACSignatureForUndefinedSelector(SEL selector) {
  198. const char *name = sel_getName(selector);
  199. NSMutableString *signature = [NSMutableString stringWithString:@"v@:"];
  200. while ((name = strchr(name, ':')) != NULL) {
  201. [signature appendString:@"@"];
  202. name++;
  203. }
  204. return signature.UTF8String;
  205. }
  206. static Class RACSwizzleClass(NSObject *self) {
  207. Class statedClass = self.class;
  208. Class baseClass = object_getClass(self);
  209. // The "known dynamic subclass" is the subclass generated by RAC.
  210. // It's stored as an associated object on every instance that's already
  211. // been swizzled, so that even if something else swizzles the class of
  212. // this instance, we can still access the RAC generated subclass.
  213. Class knownDynamicSubclass = objc_getAssociatedObject(self, RACSubclassAssociationKey);
  214. if (knownDynamicSubclass != Nil) return knownDynamicSubclass;
  215. NSString *className = NSStringFromClass(baseClass);
  216. if (statedClass != baseClass) {
  217. // If the class is already lying about what it is, it's probably a KVO
  218. // dynamic subclass or something else that we shouldn't subclass
  219. // ourselves.
  220. //
  221. // Just swizzle -forwardInvocation: in-place. Since the object's class
  222. // was almost certainly dynamically changed, we shouldn't see another of
  223. // these classes in the hierarchy.
  224. //
  225. // Additionally, swizzle -respondsToSelector: because the default
  226. // implementation may be ignorant of methods added to this class.
  227. @synchronized (swizzledClasses()) {
  228. if (![swizzledClasses() containsObject:className]) {
  229. RACSwizzleForwardInvocation(baseClass);
  230. RACSwizzleRespondsToSelector(baseClass);
  231. RACSwizzleGetClass(baseClass, statedClass);
  232. RACSwizzleGetClass(object_getClass(baseClass), statedClass);
  233. RACSwizzleMethodSignatureForSelector(baseClass);
  234. [swizzledClasses() addObject:className];
  235. }
  236. }
  237. return baseClass;
  238. }
  239. const char *subclassName = [className stringByAppendingString:RACSubclassSuffix].UTF8String;
  240. Class subclass = objc_getClass(subclassName);
  241. if (subclass == nil) {
  242. subclass = objc_allocateClassPair(baseClass, subclassName, 0);
  243. if (subclass == nil) return nil;
  244. RACSwizzleForwardInvocation(subclass);
  245. RACSwizzleRespondsToSelector(subclass);
  246. RACSwizzleGetClass(subclass, statedClass);
  247. RACSwizzleGetClass(object_getClass(subclass), statedClass);
  248. RACSwizzleMethodSignatureForSelector(subclass);
  249. objc_registerClassPair(subclass);
  250. }
  251. object_setClass(self, subclass);
  252. objc_setAssociatedObject(self, RACSubclassAssociationKey, subclass, OBJC_ASSOCIATION_ASSIGN);
  253. return subclass;
  254. }
  255. - (RACSignal *)rac_signalForSelector:(SEL)selector {
  256. NSCParameterAssert(selector != NULL);
  257. return NSObjectRACSignalForSelector(self, selector, NULL);
  258. }
  259. - (RACSignal *)rac_signalForSelector:(SEL)selector fromProtocol:(Protocol *)protocol {
  260. NSCParameterAssert(selector != NULL);
  261. NSCParameterAssert(protocol != NULL);
  262. return NSObjectRACSignalForSelector(self, selector, protocol);
  263. }
  264. @end