滥用 hook 的坑

我相信很多iOS 人员都有过 AOP思想,做过 hook 操作,这个比较方便,搞一个库,hook 控制器的生命周期,这样对于项目代码浸入就少了,也好维护的,绝大部分部分 hook 都是以下这样写法

+(void)load{
    //虽然load只执行一次,但是为了保险起见,我们还是给加个dispatch_once吧,良好的编程习惯,从这里开始
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        
        SEL orginSel = @selector(viewWillAppear:);
        SEL overrideSel = @selector(overrideViewWillAppear:);
        
        Method originMethod = class_getInstanceMethod([self class], orginSel);
        Method overrideMethod = class_getInstanceMethod([self class], overrideSel);
        
        //原来的类没有实现指定的方法,那么我们就得先做判断,把方法添加进去,然后进行替换
        if (class_addMethod([self class], orginSel, method_getImplementation(overrideMethod) , method_getTypeEncoding(originMethod))) {
            class_replaceMethod([self class],
                                overrideSel,
                                method_getImplementation(originMethod),
                                method_getTypeEncoding(originMethod));
            
        }else{
            //交换实现
            method_exchangeImplementations(originMethod, overrideMethod);
        }
    });
}

这个是就 hook 代码常用写法,也写的么有任何毛病,写进我们代码就也确实没有任何问题.但是!!!如果有多个插件 hook 项目里同一个方法,这种需求有很多的,包括我们引用的第三方,也包括我们自己 hook 的代码,这样就会出现一种问题,你就会发现 hook 只有一种会生效,其他 hook 好像是不成功的,
单单从代码分析过来看的,上面代码也貌似能够解决的
跟你们分析一下


image.png

image.png

从上面分析来看,最后面的 hook 是将之前 hook 的的逻辑和自己 hook 逻辑和系统方法都生效了,但是实际 demo 是没有的生效的,新建一个 HOOKTest项目,一个是在控制器 分类 hook(UIViewController+YJAOP),一个是在封装的framework库里MSAPM 里,为了测试简便性,我只留一个控制器 ViewController


image.png

说明一下,framework 里 hook 的方法里打印 log,NSLog(@"swizzledSelector--viewWillAppear");
而控制器里分类是打印 log NSLog(@"swizzled_viewWillAppear");
而 viewController 里打印void)viewWillAppear:(BOOL)animated 方法 NSLog(@"viewWillAppear");
看他们有没有调用就看有没有日志打印出来
我们先看一下ViewController里没有重写- (void)viewWillAppear:(BOOL)animated 方法
看一下结果如下


image.png

现在把(void)viewWillAppear:(BOOL)animated 方法注释打开
结果是三个都生效了


image.png

现在就纳闷了,为什么
我接下有断点调试,并把地址打印出来
先看一下没有重写的(void)viewWillAppear:(BOOL)animated方法测试
为了让你们跟直观,我现在公布一下 hook 的实现方式
framework库实现的方式
+ (void)toHookViewWillAppear:(Class)class {
    SEL originalSelector = @selector(viewWillAppear:);
    SEL swizzledSelector = [self swizzledSelectorForSelector:originalSelector];
    void (^swizzleBlock)(UIViewController *vc,BOOL animated) = ^(UIViewController *viewController, BOOL animated) {
        ((void(*)(id, SEL, BOOL))objc_msgSend)(viewController, swizzledSelector, animated);
         NSLog(@"swizzledSelector--viewWillAppear");
    };
    [self replaceImplementationOfKnownSelector:originalSelector onClass:class withBlock:swizzleBlock swizzledSelector:swizzledSelector];
}
+ (BOOL)replaceImplementationOfKnownSelector:(SEL)originalSelector onClass:(Class)class withBlock:(id)block swizzledSelector:(SEL)swizzledSelector {
    //返回一个指定的特定类的实例方法。
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    if (!originalMethod) {
        return NO;
    }
#ifdef __IPHONE_6_0
    //创建一个指向函数的指针,调用方法被调用时指定的块。
    IMP implementation = imp_implementationWithBlock((id)block);
#else
    IMP implementation = imp_implementationWithBlock((__bridge void *)block);
#endif
    //方法交换应该保证唯一性和原子性,唯一性:应该尽可能在+load方法中实现,这样可以保证方法一定会调用且不会出现异常。
   // 原子性:使用dispatch_once来执行方法交换,这样可以保证只运行一次。
    //给类添加一个方法  向具有给定名称和实现的类添加新方法。
    //swizzledSelector 指定要添加的方法的名称的选择器。
    //implementation 一个函数,它是新方法的实现。该函数必须包含至少两个参数- self和_cmd。
    //描述方法参数类型的字符数组
    class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalMethod));
    //class_getInstanceMethod     得到类的实例方法,
    //class_getClassMethod          得到类的类方法 
    //获取类的实例方法
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    /*
     class_addMethod:动态给类添加一个方法
     cls:被添加方法的类
     name:可以理解为方法名,这个貌似随便起名,比如我们这里叫sayHello2
     imp:实现这个方法的函数
     types:一个定义该函数返回值类型和参数类型的字符串,这个具体会在后面讲
     
     //获取通过SEL获取一个方法class_getInstanceMethod
     
     //获取一个方法的实现 method_getImplementation
     //获取一个OC实现的编码类型method_getTypeEncoding
     //給方法添加实现class_addMethod
     //用一个方法的实现替换另一个方法的实现class_replaceMethod
     //交换两个方法的实现 method_exchangeImplementations
     
     class_addMethod:如果发现方法已经存在,会失败返回,也可以用来做检查用,我们这里是为了避免源方法没有实现的情况;如果方法没有存在,我们则先尝试添加被替换的方法的实现
     1.如果返回成功:则说明被替换方法没有存在.也就是被替换的方法没有被实现,我们需要先把这个方法实现,然后再执行我们想要的效果,用我们自定义的方法去替换被替换的方法. 这里使用到的是class_replaceMethod这个方法. class_replaceMethod本身会尝试调用class_addMethod和method_setImplementation,所以直接调用class_replaceMethod就可以了)
     
     2.如果返回失败:则说明被替换方法已经存在.直接将两个方法的实现交换即

     */
    //先尝试給源方法添加实现,这里是为了避免源方法没有实现的情况
    IMP swizzledMethodIMP = method_getImplementation(swizzledMethod);
    IMP originalMethodIMP = method_getImplementation(originalMethod);
    BOOL didAddMethod = class_addMethod(class,
                                        originalSelector,
                                        swizzledMethodIMP,
                                        method_getTypeEncoding(swizzledMethod));
    IMP originalIMP = NULL;
    if (didAddMethod) {//添加成功:将源方法的实现替换到交换方法的实现,  函数  originalMethod 用swizzledSelector  替换
        
        originalIMP = class_replaceMethod(class,
                            swizzledSelector,
                            originalMethodIMP,
                            method_getTypeEncoding(originalMethod));
    }
    else {
        //添加失败:说明源方法已经有实现,直接将两个方法的实现交换即可
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
    return YES;
}

+ (SEL)swizzledSelectorForSelector:(SEL)selector {
    // 保证 selector 为唯一的,不然会死循环
    return NSSelectorFromString([NSString stringWithFormat:@"MA_Swizzle_%x_%llu_%@", arc4random(), [self currentTime], NSStringFromSelector(selector)]);
}

而是UIViewController+YJAOP,hook代码就是上面第一张图的代码
这是 frameworkhook 的结果(也是第一次 hook)


image.png

这是分类 hook 的结果 (第二次 hook)


image.png

这是分析的导图
image.png

将ViewController的- (void)viewWillAppear:(BOOL)animated方法注释打开
image.png

image.png

分析导图


image.png
image.png

现在我们使用 RSSwizzle 来hook 方法,相信很多 iOS 都不陌生的,我也试过了,确实是可以解决问题,但是我们要搞清楚其原理,不然以后出现问题都心理没底的
里面核心的代码是 方法static void swizzle(Class classToSwizzle, SEL selector, RSSwizzleImpFactoryBlock factoryBlock)
我里面做了好多注释

static void swizzle(Class classToSwizzle,
                    SEL selector,
                    RSSwizzleImpFactoryBlock factoryBlock)
{
    //返回一个指定的特定类的实例方法。
    Method method = class_getInstanceMethod(classToSwizzle, selector);
    
    NSCAssert(NULL != method,
              @"Selector %@ not found in %@ methods of class %@.",
              NSStringFromSelector(selector),
              class_isMetaClass(classToSwizzle) ? @"class" : @"instance",
              classToSwizzle);
    
    NSCAssert(blockIsAnImpFactoryBlock(factoryBlock),
             @"Wrong type of implementation factory block.");
    
    //惯例是解锁为零,锁定为非零。
    __block OSSpinLock lock = OS_SPINLOCK_INIT;
    // To keep things thread-safe, we fill in the originalIMP later,
    // with the result of the class_replaceMethod call below.为了保证线程安全,我们稍后再填写originalIMP,
    //下面是class_replaceMethod调用的结果。
    __block IMP originalIMP = NULL;

    // This block will be called by the client to get original implementation and call it.客户端将调用此块以获得原始实现并调用它。
    RSSWizzleImpProvider originalImpProvider = ^IMP{
        // It's possible that another thread can call the method between the call to
        // class_replaceMethod and its return value being set.
        // So to be sure originalIMP has the right value, we need a lock.
        OSSpinLockLock(&lock);
        IMP imp = originalIMP;
        OSSpinLockUnlock(&lock);
        
        if (NULL == imp){
            // If the class does not implement the method
            // we need to find an implementation in one of the superclasses.如果类没有实现该方法
            //我们需要在其中一个超类中找到一个实现。
            Class superclass = class_getSuperclass(classToSwizzle);
            //获取父类s/获取类的实例方方法
            //根据Method获取IMP  imp 就是方法实现的地址
            imp = method_getImplementation(class_getInstanceMethod(superclass,selector));
        }
        return imp;
    };
    
    RSSwizzleInfo *swizzleInfo = [RSSwizzleInfo new];
    swizzleInfo.selector = selector;
    //方法 imp 的实现
    swizzleInfo.impProviderBlock = originalImpProvider;
    
    // We ask the client for the new implementation block.
    // We pass swizzleInfo as an argument to factory block, so the client can
    // call original implementation from the new implementation.我们要求客户端提供新的实现块。
    //我们将swizzleInfo作为参数传递给工厂块,这样客户端就可以
    //从新实现调用原始实现。
    /*
     ^void (__unsafe_unretained id self,BOOL animated)
     {
     ((__typeof(originalImplementation_))[swizzleInfo
     getOriginalImplementation])(self, selector_, animated);
     NSLog(@"view will appear");
     }
     */
    //返回 newIMPBlock 就是RSSWReplacement里面部分
    id newIMPBlock = factoryBlock(swizzleInfo);
    
    const char *methodType = method_getTypeEncoding(method);
    //从工厂返回的块与方法类型不兼容。blockIsCompatibleWithMethodType()函数中就是判断block的签名是否与selector的签名匹配
    NSCAssert(blockIsCompatibleWithMethodType(newIMPBlock,methodType),
             @"Block returned from factory is not compatible with method type.");
    //根据代码块获取IMP,其实就是代码块与IMP关联
    IMP newIMP = imp_implementationWithBlock(newIMPBlock);
    
    // Atomically replace the original method with our new implementation.
    // This will ensure that if someone else's code on another thread is messing
    // with the class' method list too, we always have a valid method at all times.
    //
    // If the class does not implement the method itself then
    // class_replaceMethod returns NULL and superclasses's implementation will be used.
    //
    // We need a lock to be sure that originalIMP has the right value in the
    // originalImpProvider block above.原子地用我们的新实现替换原来的方法。
    //这将确保如果另一个线程上的其他人的代码混乱
    //对于类的方法列表,我们总是在任何时候都有一个有效的方法。
    //
    //如果类本身没有实现方法
    // class_replaceMethod返回NULL,将使用超类的实现。
    //
    //我们需要一个锁来确保originalIMP在
    //上面的originalImpProvider块。
    OSSpinLockLock(&lock);
    //替代方法的实现
    //将原始selector的IMP替换成这个block的IMP,如果该类中没有实现这个Selector方法,则返回值为nil;否则返回原始的IMP
    //函数  newIMP 用selector  替换
    /*
     替换给定类的方法的实现。
     class_replaceMethod(Class _Nullable cls, SEL _Nonnull name, IMP _Nonnull imp,
     const char * _Nullable types)
     @param cls 要修改的类。
     SEL _Nonnull name  一个选择器,它标识要替换其实现的方法。
     IMP _Nonnull imp 为cls标识的类的名称标识的方法提供新的实现。  
     types 描述方法参数类型的字符数组。
     *因为函数必须包含至少两个参数- self和_cmd,第二个和第三个字符
     *必须是“@:”(第一个字符是返回类型)。
     返回 之前的类方法的实现
     
     这个函数有两种不同的行为方式:
     * -如果\e name标识的方法还不存在,则添加它,就像调用了\c class_addMethod一样。
     * \e类型指定的类型编码如下所示。
     * -如果由\e名称标识的方法确实存在,则将其\c IMP替换为调用\c method_setImplementation。
     *忽略\e类型指定的类型编码。
     */
    //替换成新实现方法,返回以前实现的方法,
    originalIMP = class_replaceMethod(classToSwizzle, selector, newIMP, methodType);
    OSSpinLockUnlock(&lock);
}

里面有比较不同是 是将替换实现方法,并将上一次的实现方法赋值给originalIMP,后续originalImpProvider回调 block

 originalIMP = class_replaceMethod(classToSwizzle, selector, newIMP, methodType);
// This block will be called by the client to get original implementation and call it.客户端将调用此块以获得原始实现并调用它。
    RSSWizzleImpProvider originalImpProvider = ^IMP{
        // It's possible that another thread can call the method between the call to
        // class_replaceMethod and its return value being set.
        // So to be sure originalIMP has the right value, we need a lock.
        OSSpinLockLock(&lock);
        IMP imp = originalIMP;
        OSSpinLockUnlock(&lock);
        
        if (NULL == imp){
            // If the class does not implement the method
            // we need to find an implementation in one of the superclasses.如果类没有实现该方法
            //我们需要在其中一个超类中找到一个实现。
            Class superclass = class_getSuperclass(classToSwizzle);
            //获取父类s/获取类的实例方方法
            //根据Method获取IMP  imp 就是方法实现的地址
            imp = method_getImplementation(class_getInstanceMethod(superclass,selector));
        }
        return imp;
    };

源码分析完了 我们来有 demo 测试一下
将ViewController里- (void)viewWillAppear:(BOOL)animated 给注释掉


image.png

image.png

image.png

接下来 我们将ViewController里- (void)viewWillAppear:(BOOL)animated 给注释打开
实践分析


image.png

image.png
image.png

image.png
image.png

hook 测试 demo 地址:https://github.com/MoShenGuo/HooK.git

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,710评论 4 376
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,839评论 2 308
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,295评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,776评论 0 223
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,198评论 3 297
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,074评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,200评论 2 322
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,986评论 0 214
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,733评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,877评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,348评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,675评论 3 265
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,393评论 3 246
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,209评论 0 9
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,996评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,212评论 2 287
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 36,003评论 2 280

推荐阅读更多精彩内容