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:
- First look in the class method cache. If found, jump to
done.
- Search the class method cache again. If found, jump to
done.
- Traverse the class method list. If found, add the method to the cache and jump to
done.
- Walk through the superclass chain until
NSObject, repeating steps 3 and 4 for each superclass.
- If the method is not found in the current class or any superclass, enter method resolution. If resolution succeeds, jump to
retry.
- If method resolution is not implemented, runtime asks whether the receiver has another object that can handle this unknown selector through
forwardingTargetForSelector:.
- If there is no fallback receiver, message redirection begins. Runtime wraps all details of the unknown message into an
NSInvocationobject and callsforwardInvocation:.
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 | static void overrideMethod(Class cls, NSString *selectorName, JSValue *function, BOOL isClassMethod, const char *typeDescription) |
JSPatch’s hook process is:
- Make
SEL(forwardInvocation)point to JSPatch’s custom forwarding implementationIMP(JPForwardInvocation). At the same time, defineSEL(ORIGforwardInvocation)to point to the originalIMP(forwardInvocation), so the original forwarding path can still be handled. For each JSPatch class, althoughoverrideMethodmay be called many times, this step runs only once.
- Make
SEL(methodName)point to_objc_msgForwardor_objc_msgForward_stret. At the same time, defineSEL(ORIGmethodName)to point to the original implementationIMP(methodName).
- Store the replacement JavaScript block as
_JSOverideMethods[cls][JPSelectorName] = function.
Now look at JPForwardInvocation:
1 | static void JPForwardInvocation(__unsafe_unretained id assignSlf, SEL selector, NSInvocation *invocation) |
JSPatch’s original forwarding logic is:
1 | static void JPExecuteORIGForwardInvocation(id slf, SEL selector, NSInvocation *invocation) |
The execution logic after JSPatch hooks a function:
- When the hooked method is executed, it is forwarded into
JPForwardInvocation. The method prepends"_JP"toselectorName, searches_JSOverideMethodsfor the JavaScript code of that method, parses arguments if found, executes the JavaScript code, and finally parses the JS return value.
- If it is not found, the method was not overridden by JSPatch, so execution jumps to
JPExecuteORIGForwardInvocationand follows the original forwarding path.
- If the current class responds to
origForwardSelector, invoke it directly.
- Otherwise, find the superclass’s
forwardInvocationmethod and invoke it.
The state after a method is hooked by JSPatch can be represented like this:
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 | static id aspect_add(id self, SEL selector, AspectOptions options, id block, NSError **error) { |
1 | static void aspect_prepareClassAndHookSelector(NSObject *self, SEL selector, NSError **error) { |
1 | static void aspect_swizzleForwardInvocation(Class klass) { |
1 | static void __ASPECTS_ARE_BEING_CALLED__(__unsafe_unretained NSObject *self, SEL selector, NSInvocation *invocation) { |
After a method is hooked by Aspects, its state can be shown as:
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 | @interface MyClass : NSObject |
1 | - (void)aspects_hook_test { |
1 | defineClass('MyClass', { |
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 Hook
After JSPatch hooks, the SEL and IMP relationships look like this:
Aspects Hook
After Aspects hooks, the SEL and IMP relationships look like this:
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:
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
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 | JPAndAspects[70095:30054488] -[MyClass ORIGtest]: unrecognized selector sent to instance 0x60400001fa30 |
The JSPatch code calls self.ORIGtest():
1 | defineClass('MyClass', { |
Why does it crash?
- According to pointer 1, calling
testenters forwarding. SinceSEL(forwardInvocation)points toIMP(JPforwardInvocation), forwarding entersJPforwardInvocation. The JS block fortestis found and executed.- The JS code calls
self.ORIGtest(). Because of replacement order,SEL(ORIGtest)no longer points toIMP(test), but toIMP(_objc_msgForward), so it is forwarded again toIMP(JPforwardInvocation).- Now the JS block for
_JPORIGtestcannot be found, so JSPatch falls back to its original forwarding path,SEL(ORIGforwardInvocation). But due to overwriting,SEL(ORIGforwardInvocation)points toIMP(__ASPECTS_ARE_BEING_CALLED__), so it enters__ASPECTS_ARE_BEING_CALLED__.- Inside
__ASPECTS_ARE_BEING_CALLED__, the block forSEL(aspects__ORIGtest)cannot be found either, so it continues to Aspects’ original forwarding path,SEL(__aspects_forwardInvocation), which points toIMP(forwardInvocation).- In this example,
IMP(forwardInvocation)is not implemented, so it crashes. Even if we implemented it, we would still not expect a selector likeSEL(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 | if (!jsFunc) { |
Output:
1 | JPAndAspects[70724:30115450] JSPatch.log: jspatch log |
Aspects Hooks the Superclass Method First, JSPatch Hooks the Same Subclass Method Later, and JSPatch Calls self.super().xxx()
1 | @interface MyClass : NSObject |
1 | - (void)aspects_hook_test { |
1 | defineClass('MySubClass', { |
If a test message is sent to an instance of
MySubClass, it crashes:
1 | JPAndAspects[73431:30359622] JSPatch.log: MySubClass jspatch log |
Look at the hooked state:
Why does it crash?
- According to pointer 6, sending
testto an instance ofMySubClassgoes into forwarding. According to pointer 9,MySubClass’sSEL(forwardInvocation)points toIMP(JPforwardInvocation), so it entersJPforwardInvocation.
- The JS block for
testis found and executes, printingMySubClass jspatch log. The JS block callsself.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 callingsuper. So whenself.super().test()is called, JSPatch addsSEL(SUPER_test)toMySubClass, pointing to the superclassMyClass’sIMP(test). Unfortunately, the superclass’sSEL(test)already points toIMP(_objc_msgForward), soSEL(_JPSUPER_test)also points toIMP(_objc_msgForward).
- According to pointer 9, forwarding enters
JPforwardInvocationagain. This time the JS block forSEL(_JPSUPER_test)cannot be found, so it follows the original forwarding path and entersJPExecuteORIGForwardInvocation.
- Since subclass
MySubClassdoes not implementforwardInvocation, it enters the superclassMyClassforwarding path. According to pointer 4, it enters__ASPECTS_ARE_BEING_CALLED__. But inside that function, no block forSEL(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 | if (!jsFunc) { |
JSPatch Hooks the Superclass Method First, Aspects Hooks the Subclass Method Later, Then [subclass superTest] Is Called
1 | @interface MyClass : NSObject |
1 | @interface MySubClass : MyClass |
1 | defineClass('MyClass', { |
1 | [MySubClass aspect_hookSelector:@selector(subTest) |
1 | JPAndAspects[76443:30659220] -[MySubClass superTest]: unrecognized selector sent to instance 0x600000016d10 |
Look at the hooked state:
Why does it crash?
- According to pointer 1, because superclass
MyClass’sSEL(superTest)points toIMP(_objc_msgForward), calling[subclass superTest]must trigger forwarding.
- Since subclass
MySubClass’sSEL(forwardInvocation)points toIMP(__ASPECTS_ARE_BEGIN_CALLED__), execution enters__ASPECTS_ARE_BEGIN_CALLED__.
- Inside the subclass’s
__ASPECTS_ARE_BEGIN_CALLED__, no block forSEL(aspects__superTest)can be found, so it is treated as not hooked and falls back to original forwarding.
- The subclass’s own
SEL(__aspects_forwardInvocation)points to an unimplementedIMP(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 | if (!respondsToAlias) { |
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.
- Crashes are definitely what we least want, so they must be analyzed, solved, and avoided.
- 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?
- A fundamental reason multiple hook libraries fail together is that each library assumes
SEL(forwardInvocation)points to the originalIMP(forwardInvocation)before it hooks. It does not know that another library may have already changedSEL(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 ofSEL(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.