JSPatch's dealloc Sorrow

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:

    1. After replacing dealloc with JavaScript, when dealloc is called, self is wrapped as a weakObject and passed to JS, which causes a crash.
    1. If the current object is not wrapped, the JS replacement for dealloc can run successfully, but the native dealloc is not called, so the object is not released and memory leaks.

Later, the author Bang came up with a solution:

    1. When dealloc is called, do not wrap self as a weakObject; wrap it as an assignObject and pass it to JS.
1
2
3
4
5
6
7
8
9
if ([slf class] == slf) {
[argList addObject:[JSValue valueWithObject:@{@"__clsName": NSStringFromClass([slf class])}
inContext:_context]];
} else if ([selectorName isEqualToString:@"dealloc"]) {
[argList addObject:[JPBoxing boxAssignObj:slf]];
deallocFlag = YES;
} else {
[argList addObject:[JPBoxing boxWeakObj:slf]];
}
    1. When calling ORIGdealloc, because selectorName has changed, ARC does not recognize it as a dealloc method, so ARC needs to be tricked.
1
2
3
4
5
6
7
if (deallocFlag) {
slf = nil;
Class instClass = object_getClass(assignSlf);
Method deallocMethod = class_getInstanceMethod(instClass, NSSelectorFromString(@"ORIGdealloc"));
void (*originalDealloc)(__unsafe_unretained id, SEL) = (__typeof__(originalDealloc))method_getImplementation(deallocMethod);
originalDealloc(assignSlf, NSSelectorFromString(@"dealloc"));
}

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
2
3
4
5
@implementation JPViewController
- (void)dealloc {
NSLog(@"dealloc from OC");
}
@end
1
2
3
4
5
defineClass('JPViewController', {
dealloc: function() {
console.log('dealloc from JS');
}
}

Output:

1
2
dealloc from JS
dealloc from OC

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
2
3
4
5
6
* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
frame #5: 0x00000001094738fd libobjc.A.dylib`weak_register_no_lock + 291
frame #6: 0x0000000109473eca libobjc.A.dylib`objc_storeWeak + 480
frame #7: 0x0000000107fceb7e JSPatchDemo`-[JPBoxing setWeakObj:]
frame #8: 0x0000000107fce73f JSPatchDemo`+[JPBoxing boxWeakObj:]
frame #9: 0x0000000107fdd1c4 JSPatchDemo`JPForwardInvocation

Tracing runtime’s weak_register_no_lock, we find the clue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
BOOL (*allowsWeakReference)(objc_object *, SEL) =
(BOOL(*)(objc_object *, SEL))
object_getMethodImplementation((id)referent,
SEL_allowsWeakReference);
if ((IMP)allowsWeakReference == _objc_msgForward) {
return nil;
}

deallocating = ! (*allowsWeakReference)(referent, SEL_allowsWeakReference);
...

if (deallocating) {
if (crashIfDeallocating) {
_objc_fatal("Cannot form weak reference to instance (%p) of "
"class %s. It is possible that this object was "
"over-released, or is in the process of deallocation.",
(void*)referent, object_getClassName((id)referent));
} else {
return nil;
}
}

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
2
3
4
-(void)dealloc{
__weak __typeof(self) weakSelf = self;
NSLog(@"%@",weakSelf);
}

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
2
3
4
5
@implementation XXObject
-(void)dealloc{
NSLog(@"XXObject dealloc");
}
@end

OC dealloc

1
2
3
- (void)dealloc {
_objc_rootDealloc(self);
}
1
2
3
4
5
void _objc_rootDealloc(id obj)
{
assert(obj);
obj->rootDealloc();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
inline void objc_object::rootDealloc()
{
if (isTaggedPointer()) return;

if (fastpath(isa.nonpointer &&
!isa.weakly_referenced &&
!isa.has_assoc &&
!isa.has_cxx_dtor &&
!isa.has_sidetable_rc))
{
assert(!sidetable_present());
free(this);
}
else {
object_dispose((id)this);
}
}
1
2
3
4
5
6
7
id object_dispose(id obj)
{
if (!obj) return nil;
objc_destructInstance(obj);
free(obj);
return nil;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void *objc_destructInstance(id obj) 
{
if (obj) {
bool cxx = obj->hasCxxDtor();
bool assoc = obj->hasAssociatedObjects();

if (cxx) object_cxxDestruct(obj);

if (assoc) _object_remove_assocations(obj);

obj->clearDeallocating();
}

return 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/// Before
if (deallocFlag) {
slf = nil;
Class instClass = object_getClass(assignSlf);
Method deallocMethod = class_getInstanceMethod(instClass, NSSelectorFromString(@"ORIGdealloc"));
void (*originalDealloc)(__unsafe_unretained id, SEL) = (__typeof__(originalDealloc))method_getImplementation(deallocMethod);
originalDealloc(assignSlf, NSSelectorFromString(@"dealloc"));
}

/// After
if (deallocFlag) {
slf = nil;
Class instClass = object_getClass(assignSlf);
Class instSuperClass = [instClass superclass];
Method deallocMethod = class_getInstanceMethod(instSuperClass, NSSelectorFromString(@"dealloc"));
void (*originalDealloc)(__unsafe_unretained id, SEL) = (__typeof__(originalDealloc))method_getImplementation(deallocMethod);
originalDealloc(assignSlf, NSSelectorFromString(@"dealloc"));
}

After modification, verify with:

1
2
3
4
// OC 
-(void)dealloc{
NSLog(@"oc dealloc");
}
1
2
3
4
// JS
dealloc:function(){
console.log("js dealloc");
}
    1. First, the output shows that the Objective-C dealloc is no longer called:
1
JSPatchDemo[60463:20377984] JSPatch.log: js dealloc
    1. Then use Instruments to check for memory leaks. The object is correctly released:

Memory leak check

What Happens If Both Parent and Child dealloc Are Hooked?

1
2
3
4
5
6
7
8
9
10
11
12
13
@implementation JPBaseViewController
- (void)dealloc{
NSLog(@"JPBaseViewController OC dealloc");
}
@end

@interface JPViewController : JPBaseViewController
@end
@implementation JPViewController
- (void)dealloc{
NSLog(@"JPViewController OC dealloc");
}
@end
1
2
3
4
5
6
7
8
9
10
11
defineClass('JPBaseViewController', {            
dealloc:function(){
console.log("JPBaseViewController JS dealloc");
},
})

defineClass('JPViewController', {
dealloc:function(){
console.log("JPViewController JS dealloc");
},
})

It still crashes, this time because of stack overflow:

JSPatch's dealloc Sorrow: What Happens If Both Parent and Child dealloc Are Hooked? (figure 3)
1
2
3
4
JSPatchDemo[91945:50530228] JSPatch.log: JPViewController JS dealloc
JSPatchDemo[91945:50530228] JSPatch.log: JPViewController JS dealloc
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
2
3
4
5
6
7
8
if (deallocFlag) {
slf = nil;
Class instClass = object_getClass(assignSlf);
Class instSuperClass = [instClass superclass];
Method deallocMethod = class_getInstanceMethod(instSuperClass, NSSelectorFromString(@"dealloc"));
void (*originalDealloc)(__unsafe_unretained id, SEL) = (__typeof__(originalDealloc))method_getImplementation(deallocMethod);
originalDealloc(assignSlf, NSSelectorFromString(@"dealloc"));
}

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
2
3
4
5
6
7
8
9
10
11
12
if (deallocFlag) {
slf = nil;
Class instClass = object_getClass(assignSlf);
Class instSuperClass = [instClass superclass];

// Every time the superclass is found, use runtime to set assignSlf's class to instSuperClass.
object_setClass(assignSlf, instSuperClass);

Method deallocMethod = class_getInstanceMethod(instSuperClass, NSSelectorFromString(@"dealloc"));
void (*originalDealloc)(__unsafe_unretained id, SEL) = (__typeof__(originalDealloc))method_getImplementation(deallocMethod);
originalDealloc(assignSlf, NSSelectorFromString(@"dealloc"));
}

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
2
JSPatchDemo[93127:50640251] JSPatch.log: JPViewController JS dealloc
JSPatchDemo[93127:50640251] JSPatch.log: JPBaseViewController 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
2
3
4
5
6
7
- (void)crashTest{
JPViewController* JPVC = [[JPViewController alloc]init];
Class instClass = object_getClass(JPVC);
Class instSuperClass = [instClass superclass];
object_setClass(JPVC, instSuperClass);
[JPVC test];
}
1
2
3
0   CoreFoundation                      0x0000000109b901ab __exceptionPreprocess + 171
1 libobjc.A.dylib 0x0000000109225f41 objc_exception_throw + 48
2 CoreFoundation 0x0000000109c10a34 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132

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
2
3
4
5
6
7
8
9
@implementation JPViewController
- (void)dealloc{
NSLog(@"JPViewController OC dealloc");
}

-(void)test{
NSLog(@"JPViewController test");
}
@end
1
2
3
4
dealloc:function(){
console.log("JPViewController JS dealloc");
self.test();
},

Output:

1
2
3
JSPatchDemo[94941:50784057] JSPatch.log: JPViewController JS dealloc
JSPatchDemo[94941:50784057] JPViewController test
JSPatchDemo[94941:50784057] JSPatch.log: JPBaseViewController JS dealloc

Why?

    1. The Objective-C dealloc method itself has already been hooked into a JS block, so the Objective-C dealloc method is basically impossible to execute. Remember: do not call self.ORIGdealloc() inside the JS dealloc block, otherwise it is unnecessary and may crash.
    1. When the JS dealloc block is executing, the if (deallocFlag) block has not yet run. Therefore, self inside JS dealloc is still JPViewController. When if (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, and object_setClass is 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?

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

Title:JSPatch's dealloc Sorrow

Author:lingyun

Published:2018-01-21 21:42

Updated:2026-09-23 00:37

Original link:https://tsuijunxi.github.io/en/2018/01/21/jspatch-dealloc-sorrow/

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