JSPatch VS Aspects

Preface

Many iOS open-source projects implement various kinds of magic by hooking the third stage of message forwarding, forwardInvocation. If a project integrates multiple libraries that do this, we may enjoy the convenience they provide, but we may also run into all kinds of traps caused by them.

iOS Message Forwarding

iOS message forwarding has been explained many times, so I will not repeat the basics. Here are the key points. Objective-C method invocation mainly follows this flow:

    1. First look in the class method cache. If found, jump to done.
    1. Search the class method cache again. If found, jump to done.
    1. Traverse the class method list. If found, add the method to the cache and jump to done.
    1. Walk through the superclass chain until NSObject, repeating steps 3 and 4 for each superclass.
    1. If the method is not found in the current class or any superclass, enter method resolution. If resolution succeeds, jump to retry.
    1. If method resolution is not implemented, runtime asks whether the receiver has another object that can handle this unknown selector through forwardingTargetForSelector:.
    1. If there is no fallback receiver, message redirection begins. Runtime wraps all details of the unknown message into an NSInvocation object and calls forwardInvocation:.

Hooking Through iOS Message Forwarding

Based on the message forwarding mechanism above, when an Objective-C object method is called, runtime searches upward along the inheritance chain until NSObject. If it still cannot find the method, the method does not exist, but an exception is not thrown immediately. Instead, the call goes through multiple forwarding stages, such as -resolveInstanceMethod:, -forwardingTargetForSelector:, -methodSignatureForSelector:, and -forwardInvocation:.

The final -forwardInvocation: receives an NSInvocation object. This object stores all information about the method call, including selector name, argument types, return value type, and most importantly all argument values.

If we want to implement a library that dynamically changes method implementations, we can hook forwardInvocation: define our own forwarding handler, redirect calls to target methods into that handler, and then dynamically control where those methods go next.

1. JSPatch Hooking

First look at how JSPatch does it. In JSPatch.mm, overrideMethod is defined as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
static void overrideMethod(Class cls, NSString *selectorName, JSValue *function, BOOL isClassMethod, const char *typeDescription)
{
SEL selector = NSSelectorFromString(selectorName);

if (!typeDescription) {
Method method = class_getInstanceMethod(cls, selector);
typeDescription = (char *)method_getTypeEncoding(method);
}

IMP originalImp = class_respondsToSelector(cls, selector) ? class_getMethodImplementation(cls, selector) : NULL;

IMP msgForwardIMP = _objc_msgForward;
#if !defined(__arm64__)
if (typeDescription[0] == '{') {
NSMethodSignature *methodSignature = [NSMethodSignature signatureWithObjCTypes:typeDescription];
if ([methodSignature.debugDescription rangeOfString:@"is special struct return? YES"].location != NSNotFound) {
msgForwardIMP = (IMP)_objc_msgForward_stret;
}
}
#endif

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
if (class_getMethodImplementation(cls, @selector(forwardInvocation:)) != (IMP)JPForwardInvocation) {
IMP originalForwardImp = class_replaceMethod(cls, @selector(forwardInvocation:), (IMP)JPForwardInvocation, "v@:@");
if (originalForwardImp) {
class_addMethod(cls, @selector(ORIGforwardInvocation:), originalForwardImp, "v@:@");
}
}
#pragma clang diagnostic pop
[cls jp_fixMethodSignature];
if (class_respondsToSelector(cls, selector)) {
NSString *originalSelectorName = [NSString stringWithFormat:@"ORIG%@", selectorName];
SEL originalSelector = NSSelectorFromString(originalSelectorName);
if(!class_respondsToSelector(cls, originalSelector)) {
class_addMethod(cls, originalSelector, originalImp, typeDescription);
}
}

NSString *JPSelectorName = [NSString stringWithFormat:@"_JP%@", selectorName];

_initJPOverideMethods(cls);
_JSOverideMethods[cls][JPSelectorName] = function;

class_replaceMethod(cls, selector, msgForwardIMP, typeDescription);
}

JSPatch’s hook process is:

    1. Make SEL(forwardInvocation) point to JSPatch’s custom forwarding implementation IMP(JPForwardInvocation). At the same time, define SEL(ORIGforwardInvocation) to point to the original IMP(forwardInvocation), so the original forwarding path can still be handled. For each JSPatch class, although overrideMethod may be called many times, this step runs only once.
    1. Make SEL(methodName) point to _objc_msgForward or _objc_msgForward_stret. At the same time, define SEL(ORIGmethodName) to point to the original implementation IMP(methodName).
    1. Store the replacement JavaScript block as _JSOverideMethods[cls][JPSelectorName] = function.

Now look at JPForwardInvocation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
static void JPForwardInvocation(__unsafe_unretained id assignSlf, SEL selector, NSInvocation *invocation)
{
BOOL deallocFlag = NO;
id slf = assignSlf;
NSMethodSignature *methodSignature = [invocation methodSignature];
NSInteger numberOfArguments = [methodSignature numberOfArguments];

NSString *selectorName = NSStringFromSelector(invocation.selector);

NSString *JPSelectorName = [NSString stringWithFormat:@"_JP%@", selectorName];
JSValue *jsFunc = getJSFunctionInObjectHierachy(slf, JPSelectorName);
if (!jsFunc) {
IMP invocationIMP = class_getMethodImplementation([slf class], invocation.selector);
JPExecuteORIGForwardInvocation(slf, selector, invocation);
return;
}
...

JSPatch’s original forwarding logic is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
static void JPExecuteORIGForwardInvocation(id slf, SEL selector, NSInvocation *invocation)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
SEL origForwardSelector = @selector(ORIGforwardInvocation:);
#pragma clang diagnostic pop

if ([slf respondsToSelector:origForwardSelector]) {
NSMethodSignature *methodSignature = [slf methodSignatureForSelector:origForwardSelector];
if (!methodSignature) {
_exceptionBlock([NSString stringWithFormat:@"unrecognized selector -ORIGforwardInvocation: for instance %@", slf]);
return;
}
NSInvocation *forwardInv= [NSInvocation invocationWithMethodSignature:methodSignature];
[forwardInv setTarget:slf];
[forwardInv setSelector:origForwardSelector];
[forwardInv setArgument:&invocation atIndex:2];
[forwardInv invoke];
} else {
Class superCls = [[slf class] superclass];
Method superForwardMethod = class_getInstanceMethod(superCls, @selector(forwardInvocation:));
void (*superForwardIMP)(id, SEL, NSInvocation *);
superForwardIMP = (void (*)(id, SEL, NSInvocation *))method_getImplementation(superForwardMethod);
superForwardIMP(slf, @selector(forwardInvocation:), invocation);
}
}

The execution logic after JSPatch hooks a function:

    1. When the hooked method is executed, it is forwarded into JPForwardInvocation. The method prepends "_JP" to selectorName, searches _JSOverideMethods for the JavaScript code of that method, parses arguments if found, executes the JavaScript code, and finally parses the JS return value.
    1. If it is not found, the method was not overridden by JSPatch, so execution jumps to JPExecuteORIGForwardInvocation and follows the original forwarding path.
    1. If the current class responds to origForwardSelector, invoke it directly.
    1. Otherwise, find the superclass’s forwardInvocation method and invoke it.

The state after a method is hooked by JSPatch can be represented like this:

JSPatch VS Aspects: 1. JSPatch Hooking (figure 1)

2. Aspects Hooking

Aspects supports not only class hooks, but also object hooks, offering finer granularity. For object-level hooks, Aspects does not directly swizzle the object’s forwardInvocation method. Instead, it dynamically creates a subclass of the current object, associates the object with that subclass, and replaces the subclass’s forwardInvocation. The idea is similar to KVO: the current object becomes an instance of a subclass, while external users can still treat it as the original object. All swizzling happens on the subclass, so the original class does not need to be changed. Object-level hooks in Aspects are not the topic today.

Here we mainly discuss class hooks in Aspects. The principle is very similar to JSPatch. The core code is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
static id aspect_add(id self, SEL selector, AspectOptions options, id block, NSError **error) {
__block AspectIdentifier *identifier = nil;
aspect_performLocked(^{
if (aspect_isSelectorAllowedAndTrack(self, selector, options, error)) {
AspectsContainer *aspectContainer = aspect_getContainerForObject(self, selector);
identifier = [AspectIdentifier identifierWithSelector:selector object:self options:options block:block error:error];
if (identifier) {
[aspectContainer addAspect:identifier withOptions:options];
aspect_prepareClassAndHookSelector(self, selector, error);
}
}
});
return identifier;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
static void aspect_prepareClassAndHookSelector(NSObject *self, SEL selector, NSError **error) {
NSCParameterAssert(selector);
Class klass = aspect_hookClass(self, error);

Method targetMethod = class_getInstanceMethod(klass, selector);
IMP targetMethodIMP = method_getImplementation(targetMethod);
if (!aspect_isMsgForwardIMP(targetMethodIMP)) {
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);
}

class_replaceMethod(klass, selector, aspect_getMsgForwardIMP(self, selector), typeEncoding);
}
}
1
2
3
4
5
6
7
static void aspect_swizzleForwardInvocation(Class klass) {
NSCParameterAssert(klass);
IMP originalImplementation = class_replaceMethod(klass, @selector(forwardInvocation:), (IMP)__ASPECTS_ARE_BEING_CALLED__, "v@:@");
if (originalImplementation) {
class_addMethod(klass, NSSelectorFromString(AspectsForwardInvocationSelectorName), originalImplementation, "v@:@");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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;

// Before hooks.
aspect_invoke(classContainer.beforeAspects, info);
aspect_invoke(objectContainer.beforeAspects, info);

// Instead hooks.
BOOL respondsToAlias = YES;
if (objectContainer.insteadAspects.count || classContainer.insteadAspects.count) {
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 matching hooks are found, call the original forwarding path.
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.
[aspectsToRemove makeObjectsPerformSelector:@selector(remove)];
}

After a method is hooked by Aspects, its state can be shown as:

JSPatch VS Aspects: 2. Aspects Hooking (figure 2)

JSPatch and Aspects Fighting Each Other

If a project integrates multiple third-party libraries that all hook a class’s forwardInvocation, many problems can occur. Next, using Aspects and JSPatch as examples, let’s look at their collisions.

First, some context:

1
2
3
4
5
6
7
8
9
@interface MyClass : NSObject
- (void)test;
@end

@implementation MyClass
- (void)test {
NSLog(@"MyClass origin log");
}
@end
1
2
3
4
5
6
7
- (void)aspects_hook_test {
[MyClass aspect_hookSelector:@selector(test)
withOptions:AspectPositionInstead
usingBlock:^(id aspects) {
NSLog(@"aspects log");
} error:nil];
}
1
2
3
4
5
defineClass('MyClass', {
test: function() {
console.log("jspatch log");
}
});

Here is a summary of the problems:

Operation Result
JSPatch hooks first, Aspects hooks later aspects log
Aspects hooks first, JSPatch hooks later jspatch log
Aspects hooks first, JSPatch hooks later, and JSPatch calls self.ORIGxxx() crash
Aspects hooks a superclass method first, JSPatch hooks the same subclass method later, and JSPatch calls self.super().xxx() crash
JSPatch hooks a superclass method first, Aspects hooks a subclass method later, then [subclass superTest] is called crash

Now analyze them step by step.

Original State

Before any hook, each class’s SEL and IMP relationships look like this:

JSPatch VS Aspects: Original State (figure 3)

JSPatch Hook

After JSPatch hooks, the SEL and IMP relationships look like this:

JSPatch VS Aspects: JSPatch Hook (figure 4)

Aspects Hook

After Aspects hooks, the SEL and IMP relationships look like this:

JSPatch VS Aspects: Aspects Hook (figure 5)

JSPatch Hooks First, Aspects Hooks Later

JSPatch first hooks the test method, and then Aspects hooks test on top of that. The SEL and IMP relationships become:

JSPatch VS Aspects: JSPatch Hooks First, Aspects Hooks Later (figure 6)

At this point, if a message is sent to test, forwarding naturally occurs according to pointer 1. Since SEL(forwardInvocation) now points to IMP(__ASPECTS_ARE_BEING_CALLED__), forwarding enters __ASPECTS_ARE_BEING_CALLED__. Because Aspects can find the replacement block for test, it executes that block and prints aspects log. The original JSPatch JavaScript block is overwritten and will not execute.

Aspects Hooks First, JSPatch Hooks Later

JSPatch VS Aspects: Aspects Hooks First, JSPatch Hooks Later (figure 7)

If a message is sent to test, forwarding happens according to pointer 1. Since SEL(forwardInvocation) points to IMP(JPforwardInvocation), forwarding enters JPforwardInvocation. Because the JavaScript block for test can be found, it executes that block and prints jspatch log. The Aspects block is overwritten and will not execute.

Aspects Hooks First, JSPatch Hooks Later, and JSPatch Calls self.ORIGtest()

The result is a crash:

1
2
3
JPAndAspects[70095:30054488] -[MyClass ORIGtest]: unrecognized selector sent to instance 0x60400001fa30
JPAndAspects[70095:30054488] *** Terminating app due to uncaught exception 'NSInvalidArgumentException'
reason: '-[MyClass ORIGtest]: unrecognized selector sent to instance 0x60400001fa30'
JSPatch VS Aspects: Aspects Hooks First, JSPatch Hooks Later, and JSPatch Calls self.ORIGtest() (figure 8)

The JSPatch code calls self.ORIGtest():

1
2
3
4
5
6
defineClass('MyClass', {
test: function() {
console.log("jspatch log");
self.ORIGtest();
}
});

Why does it crash?

  • According to pointer 1, calling test enters forwarding. Since SEL(forwardInvocation) points to IMP(JPforwardInvocation), forwarding enters JPforwardInvocation. The JS block for test is found and executed.
  • The JS code calls self.ORIGtest(). Because of replacement order, SEL(ORIGtest) no longer points to IMP(test), but to IMP(_objc_msgForward), so it is forwarded again to IMP(JPforwardInvocation).
  • Now the JS block for _JPORIGtest cannot be found, so JSPatch falls back to its original forwarding path, SEL(ORIGforwardInvocation). But due to overwriting, SEL(ORIGforwardInvocation) points to IMP(__ASPECTS_ARE_BEING_CALLED__), so it enters __ASPECTS_ARE_BEING_CALLED__.
  • Inside __ASPECTS_ARE_BEING_CALLED__, the block for SEL(aspects__ORIGtest) cannot be found either, so it continues to Aspects’ original forwarding path, SEL(__aspects_forwardInvocation), which points to IMP(forwardInvocation).
  • In this example, IMP(forwardInvocation) is not implemented, so it crashes. Even if we implemented it, we would still not expect a selector like SEL(aspects__ORIGtest), so a crash would still be likely.

How can this be solved?

In theory, ORIGtest, as the original implementation of the function, should not enter forwarding. It should point directly to IMP(test). Once it enters JPforwardInvocation, it means the class’s test method has already been hooked by another library. We need to check whether the current ORIGtest has also been hooked. If not, follow the original flow. If it has been hooked, remove ORIG and forward again.

Modify JSPatch source code. In JPForwardInvocation, before falling back to original forwarding when the corresponding JS block is not found, add:

1
2
3
4
5
6
7
8
9
10
11
if (!jsFunc) {
IMP invocationIMP = class_getMethodImplementation([slf class], invocation.selector);
if([selectorName hasPrefix:@"ORIG"] && (invocationIMP == _objc_msgForward || invocationIMP==_objc_msgForward_stret))
{
selectorName = [selectorName stringByReplacingOccurrencesOfString:@"ORIG" withString:@""];
invocation.selector = NSSelectorFromString(selectorName);
}

JPExecuteORIGForwardInvocation(slf, selector, invocation);
return;
}

Output:

1
2
JPAndAspects[70724:30115450] JSPatch.log: jspatch log
JPAndAspects[70724:30115450] aspects log

Aspects Hooks the Superclass Method First, JSPatch Hooks the Same Subclass Method Later, and JSPatch Calls self.super().xxx()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@interface MyClass : NSObject
- (void)test;
@end
@implementation MyClass
- (void)test {
NSLog(@"MyClass origin log");
}
@end

@interface MySubClass : MyClass
@end
@implementation MySubClass
- (void)test {
NSLog(@"MySubClass origin log");
}
@end
1
2
3
4
5
6
7
- (void)aspects_hook_test {
[MyClass aspect_hookSelector:@selector(test)
withOptions:AspectPositionInstead
usingBlock:^(id aspects) {
NSLog(@"MyClass aspects log");
} error:nil];
}
1
2
3
4
5
6
defineClass('MySubClass', {
test: function() {
console.log("MySubClass jspatch log");
self.super().test();
}
});

If a test message is sent to an instance of MySubClass, it crashes:

1
2
JPAndAspects[73431:30359622] JSPatch.log: MySubClass jspatch log
JPAndAspects[73431:30359622] -[MySubClass SUPER_test]: unrecognized selector sent to instance 0x608000017220

Look at the hooked state:

JSPatch VS Aspects: Aspects Hooks the Superclass Method First, JSPatch Hooks the Same Subclass Method Later, and JSPatch Calls self.super().xxx() (figure 9)

Why does it crash?

    1. According to pointer 6, sending test to an instance of MySubClass goes into forwarding. According to pointer 9, MySubClass’s SEL(forwardInvocation) points to IMP(JPforwardInvocation), so it enters JPforwardInvocation.
    1. The JS block for test is found and executes, printing MySubClass jspatch log. The JS block calls self.super().test(). JSPatch’s super-call mechanism works by finding the IMP implementation of the superclass method and adding a new method to the current class that points to the superclass’s IMP. Calling this new method is equivalent to calling super. So when self.super().test() is called, JSPatch adds SEL(SUPER_test) to MySubClass, pointing to the superclass MyClass’s IMP(test). Unfortunately, the superclass’s SEL(test) already points to IMP(_objc_msgForward), so SEL(_JPSUPER_test) also points to IMP(_objc_msgForward).
    1. According to pointer 9, forwarding enters JPforwardInvocation again. This time the JS block for SEL(_JPSUPER_test) cannot be found, so it follows the original forwarding path and enters JPExecuteORIGForwardInvocation.
    1. Since subclass MySubClass does not implement forwardInvocation, it enters the superclass MyClass forwarding path. According to pointer 4, it enters __ASPECTS_ARE_BEING_CALLED__. But inside that function, no block for SEL(aspects__SUPER_test) can be found, so it crashes directly.

How to solve it?

This problem is similar to the ORIG issue. In theory, a super call should not enter its own forwarding path; it should point directly to the superclass implementation. But because the superclass has already been hooked by Aspects, the call to self.super().test() accidentally enters the current forwarding path again, causing everything that follows.

Following the same idea, before falling back to original forwarding when the JS block is not found, check whether selectorName has the SUPER_ prefix and whether its IMP has already been hooked to _objc_msgForward. If so, remove the SUPER_ prefix and forward again.

1
2
3
4
5
6
7
8
9
10
11
if (!jsFunc) {
IMP invocationIMP = class_getMethodImplementation([slf class], invocation.selector);

if([selectorName hasPrefix:@"SUPER_"] && (invocationIMP == _objc_msgForward || invocationIMP==_objc_msgForward_stret)){
selectorName = [selectorName stringByReplacingOccurrencesOfString:@"SUPER_" withString:@""];
invocation.selector = NSSelectorFromString(selectorName);
}

JPExecuteORIGForwardInvocation(slf, selector, invocation);
return;
}

JSPatch Hooks the Superclass Method First, Aspects Hooks the Subclass Method Later, Then [subclass superTest] Is Called

1
2
3
4
5
6
7
8
9
@interface MyClass : NSObject
- (void)superTest;
@end

@implementation MyClass
-(void)superTest{
NSLog(@"MyClass superTest");
}
@end
1
2
3
4
5
6
7
8
9
@interface MySubClass : MyClass
-(void)subTest;
@end

@implementation MySubClass
-(void)subTest{
NSLog(@"MySubClass subTest");
}
@end
1
2
3
4
5
defineClass('MyClass', {
superTest: function() {
console.log("MyClass superTest jspatch log");
}
});
1
2
3
4
5
6
[MySubClass aspect_hookSelector:@selector(subTest)
withOptions:AspectPositionInstead
usingBlock:^(id aspects) {
NSLog(@"MySubClass subTest aspects log");

} error:nil];
1
2
3
JPAndAspects[76443:30659220] -[MySubClass superTest]: unrecognized selector sent to instance 0x600000016d10
JPAndAspects[76443:30659220] *** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[MySubClass superTest]: unrecognized selector sent to instance 0x600000016d10'

Look at the hooked state:

JSPatch VS Aspects: JSPatch Hooks the Superclass Method First, Aspects Hooks the Subclass Method Later, Then [subclass superTest] Is Called (figure 10)

Why does it crash?

    1. According to pointer 1, because superclass MyClass’s SEL(superTest) points to IMP(_objc_msgForward), calling [subclass superTest] must trigger forwarding.
    1. Since subclass MySubClass’s SEL(forwardInvocation) points to IMP(__ASPECTS_ARE_BEGIN_CALLED__), execution enters __ASPECTS_ARE_BEGIN_CALLED__.
    1. Inside the subclass’s __ASPECTS_ARE_BEGIN_CALLED__, no block for SEL(aspects__superTest) can be found, so it is treated as not hooked and falls back to original forwarding.
    1. The subclass’s own SEL(__aspects_forwardInvocation) points to an unimplemented IMP(forwardInvocation), so it crashes directly.

How can this be solved?

The root cause is that the subclass cannot handle SEL(aspects__superTest), while the superclass forwardInvocation, which can really handle it, is not reached. In other words, the inheritance of forwardInvocation is broken by the hooks on the superclass and subclass. The solution is to let the inheritance hierarchy handle it.

Modify the Aspects source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
if (!respondsToAlias) {
invocation.selector = originalSelector;
SEL originalForwardInvocationSEL = NSSelectorFromString(AspectsForwardInvocationSelectorName);
SEL forwardInvocationSEL = @selector(forwardInvocation:);
Class kClass = object_getClass(self);
Method method = NULL;
do{
method = class_getInstanceMethod(kClass, originalForwardInvocationSEL) ?:
class_getInstanceMethod(kClass, forwardInvocationSEL);
FORWARD_INVOCATION_IMP imp = method ? (FORWARD_INVOCATION_IMP)method_getImplementation(method) : NULL;
if(imp && (imp != &__ASPECTS_ARE_BEING_CALLED__)){
imp(self,@selector(forwardInvocation:),invocation);
break;
}
}while((kClass = class_getSuperclass(kClass)));

if(NULL == method){
[self doesNotRecognizeSelector:invocation.selector];
}
}

The result after modification:

1
JPAndAspects[78567:30830810] JSPatch.log: MyClass superTest jspatch log

How to Keep a Correct Hooking Posture

So far, we have analyzed several problems caused by JSPatch and Aspects both hooking message forwarding through forwardInvocation, and we have proposed solutions one by one. The core of the solution is to identify the forwarding state after multiple libraries have hooked it, and then analyze the method invocation flow from that state.

Although the previous fight involved only two libraries, the complexity is already quite high. If you have read this far, you can probably feel it too. And this is only a two-library conflict. What if there are more libraries?

Each library’s hook logic often considers only itself, assuming it is the only one using this kind of runtime magic in the project. But other libraries think the same way. Since hooks must have an order, logic overwriting or strange forwarding jumps are inevitable, which can lead to crashes and logic errors.

    1. Crashes are definitely what we least want, so they must be analyzed, solved, and avoided.
    1. Logic overwriting may not necessarily crash, but if several hook libraries are used on the same class, does that product logic or technical logic already have a problem?
    1. A fundamental reason multiple hook libraries fail together is that each library assumes SEL(forwardInvocation) points to the original IMP(forwardInvocation) before it hooks. It does not know that another library may have already changed SEL(forwardInvocation) to another implementation. The original forwarding implementation is then lost to the current library, causing incorrect original forwarding and crashes. If we implement a mechanism for getting the true original forwarding implementation without relying on the pre-hook state, this problem can be improved. Even so, logical overwriting of SEL(forwardInvocation) is probably unavoidable to some extent. If the integrated library is closed source, the situation becomes even more serious.

So when implementing this kind of library, or integrating one, be extra careful with the traps it may bring.

Summary

Forwarding is risky. Hook with care.

-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:JSPatch VS Aspects

Author:lingyun

Published:2018-01-24 22:03

Updated:2026-09-23 00:37

Original link:https://tsuijunxi.github.io/en/2018/01/24/jspatch-vs-aspects/

License: Attribution-NonCommercial-NoDerivatives 4.0 International Please keep the original link and author when sharing.