JSPatch 能夠任意替換和新增方法,甚至能夠用來開發新模塊。可是若是純粹用來修復線上bug的話,咱們並不須要如此強大的功能。熱修復只須要具有如下幾點功能足以:html
JPAspect 一款輕量級、無侵入和無審覈風險的 iOS 熱修復框架。JPAspect 經過下發指定規則的 json 便可輕鬆實現線上 Bug 修復。JPAspect 已實現上述全部功能,具體實現請參考代碼。git
1. SEL
2. IMP
3. Method
4. NSMethodSignature
5. NSInvocation
6. void _objc_msgForward(void /* id receiver, SEL sel, ... */ )
7. id _Nullable objc_msgSend(id _Nullable self, SEL _Nonnull op, ...)
8. Objective-C type encodings
複製代碼
// 1
NSClassFromString(@"NSObject");
// 2
objc_getClass("NSObject");
複製代碼
// 1
@selector(init);
// 2
sel_registerName("init");
// 3
NSSelectorFromString(@"init");
複製代碼
static void cc_forwardInvocation(id slf, SEL sel, NSInvocation *invocation)
{
// do what you want to do
}
class_replaceMethod(klass, @selector(forwardInvocation:), (IMP)cc_forwardInvocation, "v@:@");
複製代碼
Class tClass = NSClassFromString(@"UIViewController");
SEL selector = NSSelectorFromString(@"viewDidLoad");
Method targetMethod = class_getInstanceMethod(tClass, selector);
IMP targetMethodIMP = method_getImplementation(targetMethod);
const char *typeEncoding = method_getTypeEncoding(targetMethod);
SEL aliasSelector = NSSelectorFromString([@"cc" stringByAppendingFormat:@"_%@", NSStringFromSelector(selector)]);
class_addMethod(klass, aliasSelector, method_getImplementation(targetMethod), typeEncoding);
複製代碼
Class cls = objc_allocateClassPair([NSObject class], 「CCObject」, 0);
objc_registerClassPair(cls);
複製代碼
// 1. 正常轉發
+ (BOOL)resolveClassMethod:(SEL)sel
+ (BOOL)resolveInstanceMethod:(SEL)sel
- (id)forwardingTargetForSelector:(SEL)aSelector
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
- (void)forwardInvocation:(NSInvocation *)anInvocation
// 2. 自定義轉發
void _objc_msgForward(void /* id receiver, SEL sel, ... */ )
複製代碼
@interface People : NSObject
- (void)helloWorld;
@end
複製代碼
// 常規調用
People *people = [[People alloc] init];
[people helloWorld];
// 反射調用
Class cls = NSClassFromString(@"People");
id obj = [[cls alloc] init];
[obj performSelector:NSSelectorFromString(@"helloWorld")];
// objc_msgSend
((void(*)(id, SEL))objc_msgSend)(people, sel_registerName("helloWorld"));
// C 函數調用
Method initMethod = class_getInstanceMethod([People class], @selector(helloWorld));
IMP imp = method_getImplementation(initMethod);
((void (*) (id, SEL))imp)(people, @selector(helloWorld));
// NSInvocation 調用
NSMethodSignature *sig = [[People class] instanceMethodSignatureForSelector:sel_registerName("helloWorld")];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
invocation.target = people;
invocation.selector = sel_registerName("helloWorld");
[invocation invoke];
複製代碼
新版熱修復是基於 Aspects 框架開發的,無審覈風險,已上線。Aspects 和 JSPatch 的都是基於消息轉發實現的。github
aspects_
前綴的方法,新方法(aliasSelector)實現跟目標方法相同_objc_msgForward
// 將目標類 **forwardInvocation:** 方法替換爲自定義方法
IMP originalImplementation = class_replaceMethod(klass, @selector(forwardInvocation:), (IMP)__ASPECTS_ARE_BEING_CALLED__, "v@:@");
if (originalImplementation) {
class_addMethod(klass, NSSelectorFromString(AspectsForwardInvocationSelectorName), originalImplementation, "v@:@");
}
// 目標類新增一個帶有` aspects_`前綴的方法,新方法(aliasSelector)實現跟目標方法相同
Method targetMethod = class_getInstanceMethod(klass, selector);
IMP targetMethodIMP = method_getImplementation(targetMethod);
const char *typeEncoding = method_getTypeEncoding(targetMethod);
SEL aliasSelector = NSSelectorFromString([AspectsMessagePrefix stringByAppendingFormat:@"_%@", NSStringFromSelector(selector)]);
class_addMethod(klass, aliasSelector, method_getImplementation(targetMethod), typeEncoding);
// 將目標方法實現替換爲 `_objc_msgForward`
class_replaceMethod(klass, selector, aspect_getMsgForwardIMP(self, selector), typeEncoding);
複製代碼
__ASPECTS_ARE_BEING_CALLED__
方法pthread_mutex_lock
代替便可struct
判斷邏輯不夠全面,例如:NSRange, NSPoint等 在 32 位架構下有問題,須要自行兼容#if defined(__LP64__) && __LP64__
if (valueSize == 16) {
methodReturnsStructValue = NO;
}
#endif
複製代碼
Meta class
元類方式進行解決object_getClass(targetCls)
複製代碼
swizzledClasse
key, 解決以下:static Class aspect_swizzleClassInPlace(Class klass) {
NSCParameterAssert(klass);
NSString *className = [NSString stringWithFormat:@"%@_%p", NSStringFromClass(klass), klass];
_aspect_modifySwizzledClasses(^(NSMutableSet *swizzledClasses) {
if (![swizzledClasses containsObject:className]) {
aspect_swizzleForwardInvocation(klass);
[swizzledClasses addObject:className];
}
});
return klass;
}
static void aspect_undoSwizzleClassInPlace(Class klass) {
NSCParameterAssert(klass);
NSString *className = [NSString stringWithFormat:@"%@_%p", NSStringFromClass(klass), klass];
_aspect_modifySwizzledClasses(^(NSMutableSet *swizzledClasses) {
if ([swizzledClasses containsObject:className]) {
aspect_undoSwizzleForwardInvocation(klass);
[swizzledClasses removeObject:className];
}
});
}
複製代碼
從 -forwardInvocation:
裏的 NSInvocation
對象取參數值時,若參數值是id類型,通常會這樣取:json
id value = nil;
[invocation getArgument:&value atIndex:2];
複製代碼
可是這種寫法存在 crash 風險。例如 Hook NSMutableArray 的 insertObject:atIndex: 方法.你會發如今有些系統調用會出現 EXC_BAD_INSTRUCTION
崩潰數組
[NSClassFromString(@"__NSArrayM") aspect_hookSelector:@selector(insertObject:atIndex:) withOptions:AspectPositionInstead usingBlock:^(id<AspectInfo> info){
NSLog(@"insertObject:atIndex: hook");
id value = nil;
[info.originalInvocation getArgument:&value atIndex:2];
if (value) {
[info.originalInvocation invoke];
}
} error:NULL];
複製代碼
開啓 Zombie objects 下的異常打印架構
-[UITraitCollection retain]: message sent to deallocated instance 0x6000007cde00
複製代碼
崩潰緣由分析:app
解決辦法:框架
一、將 value 變成 __unsafe_unretained
或 __weak
,讓 ARC 在它退出做用域時不插入 release 語句ide
__unsafe_unretained id value = nil;
複製代碼
二、經過 __bridge
轉換讓 value 持有返回對象,顯示賦值函數
id value = nil;
void *result;
[invocation getArgument:&result atIndex:2];
value = (__bridge id)result;
複製代碼
背景:
由於要支持參數替換,因此要從 -forwardInvocation:
裏的 NSInvocation
對象取返回值,而後替換爲自定義的參數。通常生成一個對象都會調用 alloc 方法,而後再初始化
內存泄漏緣由分析:
一、根據內存管理規則可知,當調用 alloc / new / copy / mutableCopy 方法的返回對象的 retainCount = 1。
二、若是方法有返回值的話,ARC會在 return 後自動插入 autorelease,因此通常的常規返回是沒有問題的。
三、ARC 對隱式賦值不會自動插入 autorelease,因此少了一次 release,從而致使內存泄漏。
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation.target = [NSObject class];
invocation.selector = sel_registerName([@"alloc" UTF8String]);
[invocation invoke];
id returnValue = nil;
[invocation getReturnValue:&returnValue];
return returnValue;
複製代碼
解決辦法:
id target = [NSObject class];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation.target = target;
invocation.selector = sel_registerName([@"alloc" UTF8String]);
[invocation invoke];
id resultObj = nil,
void *result;
[invocation getReturnValue:&result];
// 方法1
if ([selName isEqualToString:@"alloc"] ||
[selName isEqualToString:@"new"] ||
[selName isEqualToString:@"copy"] ||
[selName isEqualToString:@"mutableCopy"]) {
resultObj = (__bridge_transfer id)result;
} else {
resultObj = (__bridge id)result;
}
// 方法2
if ([selName isEqualToString:@"alloc"]) {
resultObj = [[target class] alloc];
} else if ([selName isEqualToString:@"new"]) {
resultObj = [[target class] new];
} else if ([selName isEqualToString:@"copy"]) {
resultObj = [target copy];
} else if ([selName isEqualToString:@"mutableCopy"]) {
resultObj = [target mutableCopy];
} else {
expectObj = (__bridge id)result;
}
複製代碼
這個功能其實很容易實現,直接替換便可
[NSClassFromString(@"UIViewController") aspect_hookSelector:@selector(viewDidLoad:) withOptions:AspectPositionInstead usingBlock:^(id<AspectInfo> info){
// 空實現
} error:NULL];
複製代碼
核心點就是經過 Aspect 獲取目標方法 Invocation ,而後對 Invocation 的參數進行對比,若是符合指望值則繼續以前原方法,例如插入的對象是否爲 nil,若是爲 nil 則放棄調用原方法,至關於執行了一個空方法。這個能夠擴展爲基礎變量判斷,例如數組越界判斷。
[NSClassFromString(@"__NSArrayM") aspect_hookSelector:@selector(insertObject:atIndex:) withOptions:AspectPositionInstead usingBlock:^(id<AspectInfo> info){
// 當 value = nil,結束當前方法調用
__unsafe_unretained id value = nil;
[info.originalInvocation getArgument:&value atIndex:2];
if (value) {
[info.originalInvocation invoke];
}
} error:NULL];
複製代碼
這個也是經過 Invocation 去修改方法裏面的參數,而後再調用,具體實現以下
[NSClassFromString(@"__NSArrayM") aspect_hookSelector:@selector(insertObject:atIndex:) withOptions:AspectPositionInstead usingBlock:^(id<AspectInfo> info){
// 無論外面怎麼調用,每次 atIndex = 0
NSUInteger value = 0;
[info.originalInvocation setArgument:& value atIndex:3];
[info.originalInvocation invoke];
} error:NULL];
複製代碼
[NSClassFromString(@"__NSArrayM") aspect_hookSelector:@selector(objectAtIndex:) withOptions:AspectPositionInstead usingBlock:^(id<AspectInfo> info){
// 無論外面怎麼調用,每次都返回 nil
[info.originalInvocation invoke];
id expectValue = nil;
[info.originalInvocation setReturnValue:&expectValue];
} error:NULL];
複製代碼
這個實現的起來稍微複雜一點,由於要實現方法先後插入方法,因此你必需要構建消息發送對象和方法參數。例如在 UIViewController
的 viewDidLoad
方法前設置其背景顏色爲紅色。首先須要獲取 viewDidLoad
方法的 Invocation
,而後經過 Invocation.target
獲取到控制器對象 self
,獲取到 self
以後調用 objc_msgSend
方法獲取 view,到這裏咱們已經獲取到消息發送對象,而後咱們用 sel_registerName
獲取 setBackgroundColor:
方法的 SEL。經過 SEL 獲取到函數簽名 NSMethodSignature
,同過函數簽名去獲取 setBackgroundColor:
的 Invocation,最後經過設置 Invocation 的參數爲紅色,而後調用 Invocation 的 invoke
方法就將背景色改成 redColor
。到此相信已經瞭解其核心原理了,咱們只須要在此基礎上再擴展,那麼足以應付線上的 90% 以上的問題了。下面是具體實現代碼。
[NSClassFromString(@"UIViewController") aspect_hookSelector:@selector(viewDidLoad) withOptions:AspectPositionInstead usingBlock:^(id<AspectInfo> aspectInfo){
// viewDidLoad 執行前插入 self.view.backgroundColor = [UIColor redColor];
target = ((id (*)(id, SEL))objc_msgSend)(aspectInfo.originalInvocation.target, NSClassFromString(@"view"));
SEL selector = sel_registerName([@"setBackgroundColor:" UTF8String]);
NSMethodSignature *signature = [[target class] instanceMethodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation.target = target;
invocation.selector = selector;
id value = ((id(*)(id, SEL))objc_msgSend)([UIColor class], sel_registerName("redColor"));
[invocation setArgument:&value atIndex:2];
[invocation invoke];
[info.originalInvocation invoke];
} error:NULL];
複製代碼