Aspects是iOS上技巧性很强的一个第三方类库,主要针对于AOP编程(面向切面编程)的思想。
“面向切面编程” 顾名思义就是带有一定侵入性的编程方式,网上对AOP编程比较专业的解释就是:可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。比较常用于APP内部事件埋点的操作。
Aspects的使用:
我们捕捉viewWillAppear的这个方法,把option设为AspectPositionAfter,block就会在viewWillAppear执行之后再执行:
- (void)viewWillAppear:(BOOL)animated {
NSLog(@"viewWillAppear");
}
[self aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info){
NSLog(@"hook_viewWillAppear");
} error:nil];
执行结果:
而且不光能对对象使用,也可以直接对类使用
[ViewController aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info){
NSLog(@"hook_viewWillAppear");
} error:nil];
这样所有这个类的对象在执行viewWillAppear的时候,都会触发block。
当然,对类的hook和对对象的hook是不一样的,类应该是整体起效,而对象是独立起效。我们先看一下两种hook之后的情况,看看大概做了什么,然后就比较容易理解。
1、类的hook:
对类进行hook之后,我们打印出方法列表,发现确实动态添加了些方法,
aspects__viewWillAppear:加了aspects__前缀的方法,用来保留原的方法的实现,因为原来的方法指针指向forwardInvocation了。
forwardInvocation方法:即使没实现,也会动态添加这个方法,指针指向了真正实现功能的ASPECTS_ARE_BEING_CALLED方法。
2、对象的hook:
对对象进行hook之后,我们也打印出方法列表:
为啥并没有新增任何方法?我们猜测会不会是这个对象已经不指向原来的类了呢,那我们就利用object_getClass(self)方法来获取这个对象的类看看:
可以看到对象的类变化了,对象的hook由于不能使其他同族的对象收到影响,所以不能对原来的类直接进行改变,aspects就动态生成了一个类(类似kvo思想),我们再打印出动态类的方法列表:
如我们所料,他把整体的过程移到了动态类去实现。
Aspects的内部实现:
Aspects的实现核心还是利用iOS消息转发的机制,利用转发的第三部forwardInvocation来捕捉方法的调用时机,然后用利用method swizzling将函数指针指向自己的实现,然后在自己的实现里调用原来的方法,再根据option的时机调用block。
跳转方法,可以看到统一的方法入口是aspect_add,先是进行hook之前的准备工作。
+ (id<AspectToken>)aspect_hookSelector:(SEL)selector
withOptions:(AspectOptions)options
usingBlock:(id)block
error:(NSError **)error {
return aspect_add((id)self, selector, options, block, error);
}
static id aspect_add(id self, SEL selector, AspectOptions options, id block, NSError **error) {
NSCParameterAssert(self);
NSCParameterAssert(selector);
NSCParameterAssert(block);
__block AspectIdentifier *identifier = nil;
aspect_performLocked(^{ #为了安全加了锁
#判断方法是否能被hook
if (aspect_isSelectorAllowedAndTrack(self, selector, options, error)) {
#将被hook的对象先通过AspectsContainer对象先进行动态绑定,以供后续使用 。
AspectsContainer *aspectContainer = aspect_getContainerForObject(self, selector);
#生成block的方法签名,并将各个参数保存生成identifier对象
#MARK:(为什么要对block这么处理,后面再说)
identifier = [AspectIdentifier identifierWithSelector:selector object:self options:options block:block error:error];
if (identifier) {
#将identifier存入入aspectContainer
[aspectContainer addAspect:identifier withOptions:options];
// Modify the class to allow message interception.
aspect_prepareClassAndHookSelector(self, selector, error);
}
}
});
return identifier;
}
然后执行到aspect_prepareClassAndHookSelector方法,这个方法会对对象和实例区别处理,然后改变函数指针的指向。
static void aspect_prepareClassAndHookSelector(NSObject *self, SEL selector, NSError **error) {
NSCParameterAssert(selector);
#这里地方根据hook的对象是实例还是类的,进行区别处理,返回需要处理的类
Class klass = aspect_hookClass(self, error);
Method targetMethod = class_getInstanceMethod(klass, selector);
IMP targetMethodIMP = method_getImplementation(targetMethod);
#接下来主要就是改变指针指向,将原来方法的指针指向forwardInvocation方法。
if (!aspect_isMsgForwardIMP(targetMethodIMP)) {
// Make a method alias for the existing method implementation, it not already copied.
const char *typeEncoding = method_getTypeEncoding(targetMethod);
SEL aliasSelector = aspect_aliasForSelector(selector);
if (![klass instancesRespondToSelector:aliasSelector]) {
__unused BOOL addedAlias = class_addMethod(klass, aliasSelector, method_getImplementation(targetMethod), typeEncoding);
NSCAssert(addedAlias, @"Original implementation for %@ is already copied to %@ on %@", NSStringFromSelector(selector), NSStringFromSelector(aliasSelector), klass);
}
// We use forwardInvocation to hook in.
class_replaceMethod(klass, selector, aspect_getMsgForwardIMP(self, selector), typeEncoding);
AspectLog(@"Aspects: Installed hook for -[%@ %@].", klass, NSStringFromSelector(selector));
}
}
aspect_hookClass的实现:
static Class aspect_hookClass(NSObject *self, NSError **error) {
NSCParameterAssert(self);
#class会返回对象的类,但是如果本身是类,就会返回自身。
#object_getClass会返回ISA指针的指向,对象返回类,类则会返回元类。
Class statedClass = self.class;
Class baseClass = object_getClass(self);
NSString *className = NSStringFromClass(baseClass);
# isa已经指向动态生成的类了
// Already subclassed
if ([className hasSuffix:AspectsSubclassSuffix]) {
return baseClass;
// We swizzle a class object, not a single object.
#如果是类的话
}else if (class_isMetaClass(baseClass)) {
return aspect_swizzleClassInPlace((Class)self);
// Probably a KVO'ed class. Swizzle in place. Also swizzle meta classes in place.
#如果是KVO的对象的话。
#因为KVO也会动态生成子类,并且改变isa指针指向
}else if (statedClass != baseClass) {
return aspect_swizzleClassInPlace(baseClass);
}
#以下说明被Hook的是对象了
// Default case. Create dynamic subclass.
const char *subclassName = [className stringByAppendingString:AspectsSubclassSuffix].UTF8String;
Class subclass = objc_getClass(subclassName);
if (subclass == nil) {
#动态创建子类
subclass = objc_allocateClassPair(baseClass, subclassName, 0);
if (subclass == nil) {
NSString *errrorDesc = [NSString stringWithFormat:@"objc_allocateClassPair failed to allocate class %s.", subclassName];
AspectError(AspectErrorFailedToAllocateClassPair, errrorDesc);
return nil;
}
#交换forwardInvocation指针
aspect_swizzleForwardInvocation(subclass);
#这里做了kvo一样的事……让class方法返回还是原来的类。
#不过我们还是可以用object_getClass看到对象的类已经是XXX_Aspects_了 ㄟ( ▔, ▔ )ㄏ
aspect_hookedGetClass(subclass, statedClass);
aspect_hookedGetClass(object_getClass(subclass), statedClass);
objc_registerClassPair(subclass);
}
#将对象的isa指针指向动态生成的子类。
object_setClass(self, subclass);
return subclass;
}
我们也看一下aspect_swizzleClassInPlace这个方法的实现,这是对类的hook的处理
static Class aspect_swizzleClassInPlace(Class klass) {
NSCParameterAssert(klass);
NSString *className = NSStringFromClass(klass);
_aspect_modifySwizzledClasses(^(NSMutableSet *swizzledClasses) {
#其实主要的也还是交换了swizzleForwardInvocation的imp指针
#加了个数组判断,防止反复交换
if (![swizzledClasses containsObject:className]) {
aspect_swizzleForwardInvocation(klass);
[swizzledClasses addObject:className];
}
});
return klass;
}
交换了forwardInvocation的imp指针,指向了ASPECTS_ARE_BEING_CALLED方法:
static void aspect_swizzleForwardInvocation(Class klass) {
NSCParameterAssert(klass);
// If there is no method, replace will act like class_addMethod.
IMP originalImplementation = class_replaceMethod(klass, @selector(forwardInvocation:), (IMP)__ASPECTS_ARE_BEING_CALLED__, "v@:@");
if (originalImplementation) {
class_addMethod(klass, NSSelectorFromString(AspectsForwardInvocationSelectorName), originalImplementation, "v@:@");
}
AspectLog(@"Aspects: %@ is now aspect aware.", NSStringFromClass(klass));
}
然后当被hook的方法被调用时,就会触发以下的方法,也就是真正的执行的方法:
static void __ASPECTS_ARE_BEING_CALLED__(__unsafe_unretained NSObject *self, SEL selector, NSInvocation *invocation) {
NSCParameterAssert(self);
NSCParameterAssert(invocation);
SEL originalSelector = invocation.selector;
SEL aliasSelector = aspect_aliasForSelector(invocation.selector);
invocation.selector = aliasSelector;
AspectsContainer *objectContainer = objc_getAssociatedObject(self, aliasSelector);
AspectsContainer *classContainer = aspect_getContainerForClass(object_getClass(self), aliasSelector);
AspectInfo *info = [[AspectInfo alloc] initWithInstance:self invocation:invocation];
NSArray *aspectsToRemove = nil;
#根据option的情况,区分处理,执行block
#三种option分别由三个数组进行保存管理
// Before hooks.
aspect_invoke(classContainer.beforeAspects, info);
aspect_invoke(objectContainer.beforeAspects, info);
// Instead hooks.
BOOL respondsToAlias = YES;
if (objectContainer.insteadAspects.count || classContainer.insteadAspects.count) {
#选择instead ,原来的方法就不执行了。
aspect_invoke(classContainer.insteadAspects, info);
aspect_invoke(objectContainer.insteadAspects, info);
}else {
#这里执行原来的方法
Class klass = object_getClass(invocation.target);
do {
if ((respondsToAlias = [klass instancesRespondToSelector:aliasSelector])) {
[invocation invoke];
break;
}
}while (!respondsToAlias && (klass = class_getSuperclass(klass)));
}
// After hooks.
aspect_invoke(classContainer.afterAspects, info);
aspect_invoke(objectContainer.afterAspects, info);
// If no hooks are installed, call original implementation (usually to throw an exception)
#找不到方法的异常处理
if (!respondsToAlias) {
invocation.selector = originalSelector;
SEL originalForwardInvocationSEL = NSSelectorFromString(AspectsForwardInvocationSelectorName);
if ([self respondsToSelector:originalForwardInvocationSEL]) {
((void( *)(id, SEL, NSInvocation *))objc_msgSend)(self, originalForwardInvocationSEL, invocation);
}else {
[self doesNotRecognizeSelector:invocation.selector];
}
}
// Remove any hooks that are queued for deregistration.
#移除option为AspectOptionAutomaticRemoval的hook信息
[aspectsToRemove makeObjectsPerformSelector:@selector(remove)];
}
PS:关于Aspects的block签名问题:
Aspects里面对block进行了签名,然后又用NSInvocation去调用block。
有的人不理解,我们不是拿到block了吗,为什么不直接调用block,非要弄得这么麻烦???因为Aspects要让block能够支持动态参数。
block在用普通方式调用的时候,必须要明确参数,在不确定参数个数的情况下,我们就无法这么调用了,而要使用NSInvocation配置参数再进行调用。
尝试一下,依然以hook控制器的viewWillAppear方法为例,在block后面加入被hook方法的参数(即animated)
[self aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info,BOOL animated){
NSLog(@"hook_show animatied:%d",animated);
} error:nil];
输出结果:确实是成功传递了参数。
接下来看一下内部的实现:
- (BOOL)invokeWithInfo:(id<AspectInfo>)info {
#根据block签名生成block的invocation
NSInvocation *blockInvocation = [NSInvocation invocationWithMethodSignature:self.blockSignature];
#这个是原方法的invocation
NSInvocation *originalInvocation = info.originalInvocation;
NSUInteger numberOfArguments = self.blockSignature.numberOfArguments;
#检测两个invocation的参数必须匹配
// Be extra paranoid. We already check that on hook registration.
if (numberOfArguments > originalInvocation.methodSignature.numberOfArguments) {
AspectLogError(@"Block has too many arguments. Not calling %@", info);
return NO;
}
#把id<AspectInfo> info先作为第二个参数,第一个参数为self,block的方法没有_cmd
// The `self` of the block will be the AspectInfo. Optional.
if (numberOfArguments > 1) {
[blockInvocation setArgument:&info atIndex:1];
}
void *argBuf = NULL;
#这个地方是从2开始,因为我们平时的方法其实会有两个隐形的参数self和_cmd,这了两个参数占了0和1的位置
for (NSUInteger idx = 2; idx < numberOfArguments; idx++) {
const char *type = [originalInvocation.methodSignature getArgumentTypeAtIndex:idx];
NSUInteger argSize;
NSGetSizeAndAlignment(type, &argSize, NULL);
if (!(argBuf = reallocf(argBuf, argSize))) {
AspectLogError(@"Failed to allocate memory for block invocation.");
return NO;
}
#把原方法的参数传递给block
[originalInvocation getArgument:argBuf atIndex:idx];
[blockInvocation setArgument:argBuf atIndex:idx];
}
#执行block
#因为block的本质就是一个对象,内部保存着函数指针,
#所以它执行的target就是自己,不需要通过selector
找到方法名称。
[blockInvocation invokeWithTarget:self.block];
if (argBuf != NULL) {
free(argBuf);
}
return YES;
}
我们打印出执行之后的两个invocation看一下:
可以看到argument 2为{B} 0, 说明是bool类型,值为0。