NSObject+RACSelectorSignal.m 13 KB

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