iOS精选iOS

iOS使用Aspects做简单热修复原理

2018-11-16  本文已影响360人  芝麻酱的简书

用到的技术点:Method Swizzling + JavaScriptCore框架

本文Demo: https://github.com/3KK3/iOSHotFixDemo

结合Demo食用最佳 ~


案例预备:

首先假如我们项目中写有如下代码:

MightyCrash *mc = [[MightyCrash alloc] init];

[mc divideUsingDenominator: 0];

实例化一个对象,然后调用对象的一个方法,这个方法内部实现如下:

- (float)divideUsingDenominator:(NSInteger)denominator {
    return 1.f / denominator;
}

问题所在:因为调用方法时候我们传入的值为0,所以除以0会出现问题


热修复解决:

在Appdelegate实现文件中添加如下代码即可:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [Felix fixIt];
    
    NSString *fixScriptString = @" \
    fixInstanceMethodReplace('MightyCrash', 'divideUsingDenominator:', function(instance, originInvocation, originArguments){ \
        if (originArguments[0] == 0) { \
            console.log('zero goes here'); \
        } else { \
            runInvocation(originInvocation); \
        } \
    }); \
    \
    ";
    
    [Felix evalString:fixScriptString];
    
    return YES;
}

原理分析:

  1. 首先第一步的[Felix fixIt];执行结果,会生成一个全局的JSContext对象来为执行JS方法提供环境:
+ (JSContext *)context {
    static JSContext *_context;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _context = [[JSContext alloc] init];
        [_context setExceptionHandler:^(JSContext *context, JSValue *value) {
            NSLog(@"Oops: %@", value);
        }];
    });
    return _context;
}

同时,使用匿名函数的方式包装OC方法:

[self context][@"fixInstanceMethodBefore"] = ^(NSString *instanceName, NSString *selectorName, JSValue *fixImpl) {
    [self _fixWithMethod:NO aspectionOptions:AspectPositionBefore instanceName:instanceName selectorName:selectorName fixImpl:fixImpl];
};

此时的模型可以理解为:

图1.0

包装的OC方法是什么呢?我们来看实现:

+ (void)_fixWithMethod:(BOOL)isClassMethod aspectionOptions:(AspectOptions)option instanceName:(NSString *)instanceName selectorName:(NSString *)selectorName fixImpl:(JSValue *)fixImpl {
    Class klass = NSClassFromString(instanceName);
    if (isClassMethod) {
        klass = object_getClass(klass);
    }
    SEL sel = NSSelectorFromString(selectorName);
    [klass aspect_hookSelector:sel withOptions:option usingBlock:^(id<AspectInfo> aspectInfo){
        [fixImpl callWithArguments:@[aspectInfo.instance, aspectInfo.originalInvocation, aspectInfo.arguments]];
    } error:nil];
}

可以看出,该OC方法是通过Aspects框架来实现hack

  1. 然后看Appdelegate的第二步:
NSString *fixScriptString = @" \
fixInstanceMethodReplace('MightyCrash', 'divideUsingDenominator:', function(instance, originInvocation, originArguments){ \
        if (originArguments[0] == 0) { \
            console.log('zero goes here'); \
        } else { \
            runInvocation(originInvocation); \
        } \
    }); \
    \
 ";

声明一个字符串fixScriptString,该字符串其实是一个JS方法,传入3个参数

  1. 第三步[Felix evalString:fixScriptString];

执行后,会在全局的JSContent环境中, 执行下面绿色部分fixInstanceMethodReplaceJS方法, 而绿色部分其实是对OC方法的封装,所以实质是对红色部分OC方法的调用

图1.1

红色部分OC方法使用Method Swizzling黑魔法完成了目标执行函数的替换,即MightyCrash类中的- (float)divideUsingDenominator:(NSInteger)denominator;方法替换为 [fixImpl callWithArguments:@[aspectInfo.instance, aspectInfo.originalInvocation, aspectInfo.arguments]];

  1. 第四步

当执行

    MightyCrash *mc = [[MightyCrash alloc] init];
    [mc divideUsingDenominator:1];

这段代码的时候,因为第三步我们已经替换了方法实现,所以其实是调用了[fixImpl callWithArguments:@[aspectInfo.instance, aspectInfo.originalInvocation, aspectInfo.arguments]];方法,该方法会执行第二步声明的JS方法的第三个function参数,即执行:

function(instance, originInvocation, originArguments){ 
        if (originArguments[0] == 0) { 
            console.log('zero goes here'); 
        } else { 
            runInvocation(originInvocation); 
        } 

总结:

上面案例是在Appdeelgate文件中固定写死一个JS方法(字符串),在实际项目应用中,写死的JS方法可以通过从服务器请求来获取,已达到动态修复线上bug的目的。


参考文章:
https://www.jianshu.com/p/ac534f508fb0
https://limboy.me/tech/2018/03/04/ios-lightweight-hotfix.html
复杂情况修复:
https://www.jianshu.com/p/d4574a4268b3


上一篇下一篇

猜你喜欢

热点阅读