Preface
As a lightweight hotfix solution, JSPatch once solved
many pain points for app hotfixes. It even became extremely popular and
looked ready to dominate the hotfix field. But because it violated
Apple’s rules, it was banned, and many companies became afraid to
continue using such indirect workarounds.
Although the ending of JSPatch is regrettable, as iOS
engineers there are still many excellent ideas inside it worth studying.
Today I mainly want to analyze JSPatch’s dealloc
problem.
What Is dealloc Sorrow?
Anyone who once integrated JSPatch has probably had this
requirement: if a released online version has resources that were not
released correctly in dealloc, or if the release logic
itself has a problem, then we need to rewrite the dealloc
method. This requirement is reasonable. However, JSPatch at the time
struggled with this problem:
- After replacing
deallocwith JavaScript, whendeallocis called,selfis wrapped as aweakObjectand passed to JS, which causes a crash.
- If the current object is not wrapped, the JS replacement for
dealloccan run successfully, but the nativedeallocis not called, so the object is not released and memory leaks.
Later, the author Bang came up with a solution:
- When
deallocis called, do not wrapselfas aweakObject; wrap it as anassignObjectand pass it to JS.
1 | if ([slf class] == slf) { |
- When calling
ORIGdealloc, becauseselectorNamehas changed, ARC does not recognize it as adeallocmethod, so ARC needs to be tricked.
1 | if (deallocFlag) { |
When I first saw this solution, I was genuinely impressed. The only
flaw is that it still did not completely solve JSPatch’s
dealloc problem. Why? Because this solution leaves one
issue behind: the JavaScript dealloc method and the
Objective-C dealloc method are both called.
1 | @implementation JPViewController |
1 | defineClass('JPViewController', { |
Output:
1 | dealloc from JS |
Imagine this: if the Objective-C dealloc method
has a bug, I only want the JS dealloc method to run after
hotfixing with JSPatch. I do not want the Objective-C
dealloc to run, while still correctly releasing object
memory. But after the current JSPatch hotfix, Objective-C
dealloc still executes. Wouldn’t the original bug in
dealloc happen again? That is why I call it the sorrow of
dealloc.
Analysis and Solution
Now let’s analyze why JSPatch’s dealloc problem is so
tricky.
Why Does weak Wrapping Crash?
The author’s initial approach was to wrap self as a
weakObject and pass it to JS when dealloc was
called. The main purpose was to avoid JS holding a strong reference to
self, which would prevent dealloc from being
called. However, this solution crashes:
1 | objc[54707]: Cannot form weak reference to instance (0x7f9d46f073d0) of class JPViewController. It is possible that this object was over-released, or is in the process of deallocation. |
Looking at the stack, it crashes inside
weak_register_no_lock:
1 | * thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGABRT |
Tracing runtime’s weak_register_no_lock, we find the
clue:
1 | BOOL (*allowsWeakReference)(objc_object *, SEL) = |
weak_register_no_lock first checks whether the object is
being deallocated. If it is, it aborts the program through
_objc_fatal, causing the crash. The crash message we saw
comes exactly from this _objc_fatal. This shows that
when an Objective-C object’s dealloc function has
already been triggered, weak references to that object are not
allowed.
We can verify this simply by weakly referencing self
inside dealloc:
1 | -(void)dealloc{ |
It also crashes:
1 | objc[56044]: Cannot form weak reference to instance (0x7f8fc750aad0) of class JPViewController. It is possible that this object was over-released, or is in the process of deallocation. |
This makes sense. What is the point of weakly referencing an object that is about to be destroyed, other than wasting resources and introducing potential danger?
Why Does assignObject Avoid the Crash, and How Can We Avoid Calling Objective-C dealloc?
assign is just a pointer reference. It does not
participate in Objective-C memory management, so it does not cause the
weak-reference crash above. But improper access can easily cause
dangling-pointer crashes, so it must be used carefully.
How can we avoid calling Objective-C dealloc? Before
solving this, first understand how Objective-C object deallocation
works. In ARC, calling [super dealloc] is not allowed. The
compiler automatically inserts [super dealloc] during
compilation.
Create a class called XXObject and trace the
dealloc call flow:
1 | @implementation XXObject |

1 | - (void)dealloc { |
1 | void _objc_rootDealloc(id obj) |
1 | inline void objc_object::rootDealloc() |
1 | id object_dispose(id obj) |
1 | void *objc_destructInstance(id obj) |
It is not hard to see that the Objective-C dealloc
function only handles the release logic we write. The real object
cleanup work is completed by runtime. In
objc_destructInstance, it:
- Executes the C++ destructor if the class has one.
- Removes and releases associated objects attached through runtime.
- Clears the object’s SideTable weak table.
Since the Objective-C dealloc logic has already
been replaced by the JS dealloc logic, the Objective-C
dealloc logic should be skipped. Previously, because we did
not understand the internals of Objective-C dealloc, we
felt the compiler might be doing mysterious work inside it and had no
way forward. But now we know that the core cleanup happens in
objc_destructInstance. Even if Objective-C
dealloc is not called, object cleanup is not absolutely
affected. We can bypass this Objective-C dealloc obstacle
in a certain way: after calling JS dealloc, skip the
current class’s Objective-C dealloc and directly call the
superclass’s dealloc. Although ARC prevents us from writing
[super dealloc], we still have runtime.
Open JSPatch.mm and modify the last few lines of
JPForwardInvocation:
1 | /// Before |
After modification, verify with:
1 | // OC |
1 | // JS |
- First, the output shows that the Objective-C
deallocis no longer called:
1 | JSPatchDemo[60463:20377984] JSPatch.log: js dealloc |
- Then use Instruments to check for memory leaks. The object is correctly released:

What Happens If Both Parent and Child dealloc Are Hooked?
1 | @implementation JPBaseViewController |
1 | defineClass('JPBaseViewController', { |
It still crashes, this time because of stack overflow:
1 | JSPatchDemo[91945:50530228] JSPatch.log: JPViewController JS dealloc |
As shown above, JPViewController JS dealloc keeps
executing repeatedly.
Analyze the reason based on the previous modification:
1 | if (deallocFlag) { |
When subclass JPViewController’s dealloc is
called, we find the IMP of the superclass’s dealloc and
call it through
originalDealloc(assignSlf, NSSelectorFromString(@"dealloc"));.
Because the superclass JPBaseViewController’s
dealloc has also been hooked, it eventually forwards into
the same code again. But after
Class instClass = object_getClass(assignSlf); executes, the
class is still JPViewController, and its superclass is
still JPBaseViewController. This forms an infinite loop and
eventually causes stack overflow.
The first solution that comes to mind is to use a while
loop and brute-force the dealloc inheritance chain. But if
one dealloc method in the middle has been hooked as a JS
block, then executing that JS block must also be handled. Clearly, this
approach requires a lot of work and many edge cases.
If we could save the dealloc execution level, we could
avoid the infinite loop. But looking at the function parameters, that
does not seem available:
1 | static void JPForwardInvocation(__unsafe_unretained id assignSlf, SEL selector, NSInvocation *invocation) |
In the end, we can only rely on assignSlf. If we can do
something with the object itself, that might work. After much thought, I
came up with one extra line:
1 | if (deallocFlag) { |
As shown above, every time the superclass is found, runtime is used
to set assignSlf’s class to its superclass
instSuperClass. This breaks the condition for the infinite
loop.
Verify the result:
1 | JSPatchDemo[93127:50640251] JSPatch.log: JPViewController JS dealloc |
Both are indeed called.
Some may wonder whether changing an object’s class this way risks crashes. In normal situations, there is definitely risk. For example, the following code crashes directly:
1 | - (void)crashTest{ |
1 | 0 CoreFoundation 0x0000000109b901ab __exceptionPreprocess + 171 |
In the code above, test exists only on
JPViewController, not on its superclass, so it crashes.
But after verification, JSPatch does not crash and can call normally:
1 | @implementation JPViewController |
1 | dealloc:function(){ |
Output:
1 | JSPatchDemo[94941:50784057] JSPatch.log: JPViewController JS dealloc |
Why?
- The Objective-C
deallocmethod itself has already been hooked into a JS block, so the Objective-Cdeallocmethod is basically impossible to execute. Remember: do not callself.ORIGdealloc()inside the JSdeallocblock, otherwise it is unnecessary and may crash.
- When the JS
deallocblock is executing, theif (deallocFlag)block has not yet run. Therefore,selfinside JSdeallocis stillJPViewController. Whenif (deallocFlag)finally executes, it is already focused on final resource release through runtime and will no longer call custom methods. Therefore, it will not crash, andobject_setClassis safe to use here.
Summary
The final solution is very simple: a small “skip” action plus changing the object’s own class. But for a long time, I had no idea how to solve this problem. Only after reading the runtime source code carefully did everything suddenly become clear.
Although JSPatch is no longer something we pay much attention to because of Apple’s policy, the core ideas inside it are still worth studying. And if other libraries, such as Aspects, use principles very close to JSPatch, could they also have similar problems?