Advertisement
Guest User

TSanResolveMethodDemo

a guest
Apr 27th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. @import Foundation;
  2. @import ObjectiveC.runtime;
  3.  
  4. @interface Foo: NSObject
  5.  
  6. - (instancetype)initWithTag:(NSString*)tag;
  7.  
  8. @property(nonatomic, readonly, copy) NSString* tag;
  9.  
  10. + (instancetype)foo_1;
  11. + (instancetype)foo_2;
  12. + (instancetype)foo_3;
  13.  
  14. @end
  15.  
  16. @implementation Foo
  17.  
  18. - (instancetype)initWithTag:(NSString*)tag {
  19.     if ((self = [super init])) {
  20.         _tag = [tag copy];
  21.     }
  22.     return self;
  23. }
  24.  
  25. + (BOOL)resolveClassMethod:(SEL)sel {
  26.     Foo *methodRetVal = [[self alloc] initWithTag:NSStringFromSelector(sel)];
  27.     Foo * (^block)(id blockSelf) = ^Foo *(id blockSelf) {
  28.         return methodRetVal; // <- Read happens here, when heap block is invoked and reads captured variable
  29.     };
  30.     IMP imp = imp_implementationWithBlock(block); // <- Write happens here, when captured variable is copyied from stack block to heap block
  31.     class_addMethod(object_getClass(self), sel, imp, "@@:");
  32.     return YES;
  33. }
  34.  
  35. @end
  36.  
  37.  
  38. int main(int argc, char * argv[]) {
  39.     @autoreleasepool {
  40.         for (int i = 0; i < 100; ++i) {
  41.             dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^{
  42.                 NSLog(@"%@", [Foo foo_1].tag);
  43.             });
  44.         }
  45.         return 0;
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement