Hooking Objective-C Blocks with TrampolineHook on iOS

Background

Instrumentation often needs a single interception point: execution is redirected through shared logic, some work is performed before or after the original call, and control then returns to its normal path. This resembles a conventional hook, but the emphasis here is on routing many call sites through the same trampoline.

Hooking Objective-C Blocks with TrampolineHook on iOS: Background (figure 1)

Hooking an Objective-C block

Most Objective-C method dispatch eventually passes through one of the objc_msgSend variants, so method interception can be framed as hooking those entry points. Blocks are different: how can we intercept one arbitrary block invocation?

  1. Although a block is an Objective-C object, invoking it does not go through message forwarding. Its function pointer is called directly, much like a C function.
  2. Blocks can have different signatures, parameter counts, and return types. A general-purpose interception mechanism is therefore difficult to implement purely in Objective-C.

TrampolineHook provides a useful model. It redirects a function through an assembly trampoline and invokes callbacks when that function runs. Callers do not have to manage architecture-specific calling conventions or save and restore the execution context themselves. This also avoids some of the fragility that method-swizzling-based instrumentation can introduce in large codebases.

The same mechanism can be applied to blocks. Based on that idea, I built TrampolineBlockHook, a block interception framework that supports both arm64 and x86_64.

API and usage

TrampolineBlockHook exposes a small API for installing and removing a block hook.

1
2
3
extern BOOL hook_block_with_stub(void *replaced, void *replacement, void *pre, void *post);

extern BOOL unhook_block(void *replaced);

Before diving into the implementation, here is the API in action:

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
void pre(void *p1, void *p2) {
printf("before hook\n");
}

void post(void *p1, void *p2) {
printf("after hook\n");
}
- (void)testBlockWithAll {
__block BOOL didRun = NO;
Student (^Block)(id self) = ^Student (id blockself) {
didRun = YES;
printf("this is the original block\n");
Student s = {1,2,3,4,5,6};
return s;
};

Student (^ReplacedBlock)(id self) = ^Student (id blockself) {
didRun = YES;
printf("this is the replaced block\n");
Student s = {6,5,4,3,2,1};
return s;
};

hook_block_with_stub((__bridge void *)(Block), (__bridge void *)(ReplacedBlock), pre, after);
Student student = Block(self);
NSAssert(student.height == 2, @"");

unhook_block((__bridge void *)(Block));
student = Block(self);
NSAssert(student.height == 5, @"");
}

The output is shown below:

Hooking Objective-C Blocks with TrampolineHook on iOS: API and usage (figure 2)

The same block can be passed as both the first and second arguments to hook_block_with_stub. In that mode, the original implementation remains in place while two stubs, pre and post, run immediately before and after it.

vm_remap

Principle

iOS does not generally allow an application to allocate memory that is both writable and executable. vm_remap offers a different route: prepare executable code in advance, then map copies of that code into the required virtual address range.

On Darwin, vm_remap() provides support for mapping an existing code page at new address, while retaining the existing page protections; using vm_remap(), we can create multiple copies of existing, executable code, placed at arbitrary addresses.

The remapped page retains the protection attributes of the source mapping. If the source page is executable, its mapped copies are executable as well. This lets us create multiple instances of a prebuilt trampoline page at addresses selected at runtime.

As illustrated in Implementing imp_implementationWithBlock(), we can build an executable Trampoline Page ahead of time and use vm_remap to create runtime copies such as Trampoline Page Copy #1 and Trampoline Page Copy #2.

Hooking Objective-C Blocks with TrampolineHook on iOS: Principle (figure 3)

That solves only half of the problem. A Trampoline Page contains multiple Trampoline Entry slots, one for each hooked block. Every entry also needs metadata: the original block address and the addresses of its before and after stubs. We store that metadata in a corresponding Trampoline Data page.

If the Trampoline Data page is mapped next to the Trampoline Page, we can use PC-relative addressing to load the needed data from the adjacent page. As shown below, if a Trampoline Entry in Trampoline Page Copy #1 needs some information, it can load it from the corresponding position in Trampoline Data #1.

Hooking Objective-C Blocks with TrampolineHook on iOS: Principle (figure 4)

Mapping the code and data pages

Hooking Objective-C Blocks with TrampolineHook on iOS: Mapping the code and data pages (figure 5)

We first allocate two contiguous virtual memory pages with vm_allocate, release the second page with vm_deallocate, and then map trampoline_page into that address using vm_remap. The first page remains writable and stores metadata such as the block address and the pre and post stub addresses. The second page contains the executable trampoline entries. In the diagram, these are the trampoline data page and the trampoline text page, respectively.

1
2
3
4
5
6
7
8
9
10
11
12
13
// Allocate two contiguous pages.
vm_address_t data_page = 0x0;
kern_return_t kt;
kt = vm_allocate (mach_task_self(), &data_page, PAGE_SIZE*2, VM_FLAGS_ANYWHERE);

// Release the second page to make room for the trampoline table.
vm_address_t trampoline_page = data_page+PAGE_SIZE;
kt = vm_deallocate (mach_task_self(), trampoline_page, PAGE_SIZE);

// Map the executable trampoline page into the released address range.
vm_prot_t cur_prot;
vm_prot_t max_prot;
kt = vm_remap (mach_task_self(), &trampoline_page, PAGE_SIZE, 0x0, FALSE, mach_task_self(), (vm_address_t) config->template_page, FALSE, &cur_prot, &max_prot, VM_INHERIT_SHARE);

The generated page begins with tramp dispatch, followed by the first tramp entry. Because the dispatch routine determines the entry’s offset within the page, we need its exact size. We can calculate that size manually or inspect the assembled output in a tool such as Hopper.

Representing a block

To intercept blocks without knowing their parameters or return types, we need access to their runtime representation. Apple defines the relevant Block_layout structure in Block_private.h.

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
struct Block_descriptor {
/** Reserved value */
unsigned long int reserved;

/** Total size of the described block, including imported variables. */
unsigned long int size;

/** Optional block copy helper. May be NULL. */
void (*copy)(void *dst, void *src);

/** Optional block dispose helper. May be NULL. */
void (*dispose)(void *);
};

struct Block_layout {
/** Pointer to the block's Objective-C class. */
void *isa;

/** Block flags. */
int flags;

/** Reserved value. */
int reserved;

/** Block invocation function. */
void (*invoke)(void *, ...);

/** Shared block descriptor. */
struct Block_descriptor *descriptor;

// imported variables
};

Control-flow redirection

  1. Save the original block implementation address as A.
  2. Point the block’s invoke function at a dynamically mapped trampoline entry, B.
  3. When the block is invoked, execution branches to B.
  4. The trampoline retrieves the metadata associated with that entry, including the saved address A.
  5. If a pre stub is present, call it before the original implementation.
  6. Call the original implementation at A with the original execution context.
  7. When it returns, call the post stub and then resume the caller’s control flow.
Hooking Objective-C Blocks with TrampolineHook on iOS: Control-flow redirection (figure 6)

The trampoline needs the block’s pre and post stub addresses while redirecting control flow. We therefore write those addresses into the data page when installing the hook.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
extern BOOL hook_block_with_stub(void *block, void *replacement, void *pre, void *post) {
trampoline *tramp;
struct Block_layout *bl = (struct Block_layout *)block;
if (bl->flags & BLOCK_USE_STRET) {
tramp = trampoline_alloc(&STRET_TABLE_CONFIG, &STRET_TABLE);
} else {
tramp = trampoline_alloc(&blockimp_table_page_config, &blockimp_table);
}
struct Block_layout *layout = (struct Block_layout*)block;
struct Block_layout *layoutReplaced = (struct Block_layout*)replacement;
void **config = (void **)trampoline_data_ptr(tramp->trampoline);
config[0] = Block_copy(replacement);
config[1] = tramp;
config[2] = layoutReplaced->invoke;
config[3] = pre;
config[4] = post;
layout->descriptor->reserved = (unsigned long)layout->invoke;
layout->invoke = (void (*)(void *, ...))tramp->trampoline;
return YES;
}

The red area in the diagram represents one tramp data record. Its five slots store ReplacedBlock, tramp, ReplacedBlock->invoke, pre, and post, in that order.

We then point the block’s invoke function at the corresponding tramp entry, causing future invocations to enter the trampoline. Removing the hook requires the original implementation address, which this implementation stores in layout->descriptor->reserved.

With that metadata in place, removing the hook is straightforward:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
BOOL unhook_block(void *block) {
struct Block_layout *layout = (struct Block_layout*)block;
void **config = trampoline_data_ptr(layout->invoke);
struct Block_layout *bl = config[0];
trampoline *tramp = config[1];
layout->invoke = (void (*)(void *, ...))layout->descriptor->reserved;
layout->descriptor->reserved = 0;
if (bl->flags & BLOCK_USE_STRET) {
trampoline_free(&STRET_TABLE, tramp);
} else {
trampoline_free(&blockimp_table, tramp);
}
return YES;
}

arm64 assembly implementation

The critical part of the implementation is preserving the calling context while assembly redirects control flow through the trampoline.

Registers

The following register roles are relevant to the trampoline:

1
2
3
4
5
6
7
8
9
- x0 - x7: used to pass subroutine arguments and results. They do not need to be preserved by the callee. Extra arguments are passed on the stack. Return values go in x0.
- x8: used to store a subroutine return address.
- x9 - x15: temporary registers.
- x16 - x17: intra-procedure-call temporary registers.
- x18: platform register. Its use is platform-specific.
- x19 - x28: temporary registers.
- x29: frame pointer register fp, used to link stack frames.
- x30: link register lr, stores the subroutine return address.
- x31: stack pointer register sp.

Assembly code

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#if defined(__arm64__)

# Save caller-saved registers.
.macro save_register
stp q0, q1, [sp, #-32]!
stp q2, q3, [sp, #-32]!
stp q4, q5, [sp, #-32]!
stp q6, q7, [sp, #-32]!
stp lr, x10, [sp, #-16]!
stp x0, x1, [sp, #-16]!
stp x2, x3, [sp, #-16]!
stp x4, x5, [sp, #-16]!
stp x6, x7, [sp, #-16]!
stp x8, x12, [sp, #-16]!
.endm

# Restore caller-saved registers.
.macro load_register
ldp x8, x12, [sp], #16
ldp x6, x7, [sp], #16
ldp x4, x5, [sp], #16
ldp x2, x3, [sp], #16
ldp x0, x1, [sp], #16
ldp lr, x10, [sp], #16
ldp q6, q7, [sp], #32
ldp q4, q5, [sp], #32
ldp q2, q3, [sp], #32
ldp q0, q1, [sp], #32
.endm

.text
.align 14
.globl _blockimp_table_page
_blockimp_table_page:

_block_tramp_dispatch:

# lr points eight bytes past the start of the trampoline entry.
sub x12, lr, #0x8
sub x12, x12, #0x4000

# Save the block's trampoline data address.
str x12, [sp, #-16]!

# Save the original return address currently held in x13.
str x13, [sp, #-16]!

# Load the pre-stub address.
ldr x13, [x12, #0x18]
cbz x13, block

# Execute the pre stub.
pre:
save_register
blr x13
load_register

# Execute the original block implementation.
block:
ldr x13, [x12, #0x10]
blr x13

# Execute the post stub.
ldr x12, [sp], #16
ldr x13, [x12, #0x20]
cbz x13, end

post:
save_register
blr x13
load_register

# Restore the original return address.
end:
ldr x13, [sp], #0x10
br x13


.rept 404
# Preserve the return address in x13.
mov x13, lr
# Branch to the shared trampoline dispatcher.
bl _block_tramp_dispatch;
.rept 8
nop
.endr
.endr

#endif

On arm64, one page is 0x4000, or 16 KB, so .align 14 is used. On arm64, every instruction is 4 bytes regardless of length.

The dispatch sequence works as follows:

  1. Because the block’s invoke function points at a tramp entry, calling the block branches directly to that entry. The entries are generated by a .rept block repeated 404 times. A page contains 16 KB = 16384 B; after subtracting the 224 B dispatch area, the remaining space holds (16384 - 224) / 40 = 404 entries of 40 B each.

  2. Each tramp entry occupies 40 bytes. At entry, lr contains the return address following the block call, so we preserve it in x13 before branching to _block_tramp_dispatch. The eight nop instructions pad the entry to 40 bytes, matching the size and offset of its tramp data record. Since every arm64 instruction is 4 bytes, each entry contains ten instructions in total.

1
2
3
4
5
6
7
8
9
10
mov x13, lr
bl _block_tramp_dispatch;
nop
nop
nop
nop
nop
nop
nop
nop
  1. Because execution jumped from the entry, lr holds the address of the instruction after the branch. lr - 8 gives the start address of the entry, and subtracting one page size #0x4000 gives the corresponding tramp data address.
1
2
sub x12, lr, #0x8
sub x12, x12, #0x4000
  1. Store the computed tramp data address on the stack.
1
str x12, [sp, #-16]!
  1. x13 currently stores the address after the Block, so store it on the stack as well.
1
str x13, [sp, #-16]!
  1. x12 stores tramp data. Offset 24 bytes from that address to get the pre stub. If it is null, jump directly to the block label. Why 24 bytes? During redirection, pre is stored at config[3]; config[0] through config[2] each take 8 bytes, so the offset is 24 bytes.
1
2
ldr x13, [x12, #0x18]
cbz x13, block
  1. x13 now holds the pre address, which blr calls directly. Because this is a nested function call, caller-saved registers must be preserved around it.
1
2
3
4
pre:
save_register
blr x13
load_register
  1. The original block implementation is stored 16 bytes into the tramp data record. Load it into x13 and branch to it. Caller-saved registers are deliberately left untouched here so that the original block receives the same execution context it would have received without the hook. Its return value must likewise pass through unchanged.
1
2
3
block:
ldr x13, [x12, #0x10]
blr x13
  1. Reload the tramp data address from the stack into x12, then offset 32 bytes to get the post address. The subsequent call is similar to pre. We reload tramp data because the previous block call did not preserve caller-save registers and may have destroyed x12.
1
2
3
4
5
6
7
8
ldr x12, [sp], #16
ldr x13, [x12, #0x20]
cbz x13, end

post:
save_register
blr x13
load_register
  1. Load the address after the Block from the stack into x13, then jump to it.
1
2
3
end:
ldr x13, [sp], #0x10
br x13

Hopper diagram

Hooking Objective-C Blocks with TrampolineHook on iOS: Hopper diagram (figure 7) Hooking Objective-C Blocks with TrampolineHook on iOS: Hopper diagram (figure 8)

In the left diagram, _block_tramp_dispatch begins at the page boundary 0x0000000000008000. In the right diagram, the first tramp entry begins at 0x00000000000080e0. The resulting 0xE0 offset is the 224-byte dispatch area described above.

x86_64 assembly implementation

Registers

Hooking Objective-C Blocks with TrampolineHook on iOS: Registers (figure 9)
Hooking Objective-C Blocks with TrampolineHook on iOS: Registers (figure 10)

Assembly code

On x86_64, one page is 0x1000, or 4 KB, so .align 12 is used. On x86_64, instruction size is not fixed.

The x86_64 implementation follows the same overall flow as the arm64 version, so I will not repeat every step.

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
.macro save_register
push %rdi
push %rsi
push %rdx
push %rcx
push %r8
push %r9
push %r10
push %r11
push %rax
push %rax # Padding for 16-byte stack alignment.
.endm

.macro load_register
pop %rax
pop %rax
pop %r11
pop %r10
pop %r9
pop %r8
pop %rcx
pop %rdx
pop %rsi
pop %rdi
.endm

.text
.align 12
.globl _blockimp_table_page
_blockimp_table_page:

_block_tramp_dispatch:
# Save the return address in r11.
movq (%rsp), %r11

subq $0x20, %rsp

# Calculate the block's trampoline data address.
sub $0x5, %r11
sub $0x1000, %r11

# Store the trampoline data address on the stack.
movq %r11, 0x8(%rsp)

# Load the pre-stub address.
mov 0x18(%r11), %r10
cmp $0x0, %r10
je block

# Execute the pre stub.
pre:
save_register
call *%r10
load_register

# Execute the original block implementation.
block:
call *0x10(%r11)

movq 0x8(%rsp), %r11
movq 0x20(%r11), %r10
cmpq $0x0, %r10
je end

# Execute the post stub.
after:
save_register
call *%r10
load_register

end:
addq $0x20, %rsp
ret
.align 4

# Generate the trampoline entries.
.rept 256
call _block_tramp_dispatch # 5 bytes
.rept 34
nop
.endr
ret
.endr

Hopper diagram

Hooking Objective-C Blocks with TrampolineHook on iOS: Hopper diagram (figure 11) Hooking Objective-C Blocks with TrampolineHook on iOS: Hopper diagram (figure 12)

Stack alignment pitfall

During debugging, the x86_64 implementation repeatedly crashed on SSE instructions such as movaps.

Hooking Objective-C Blocks with TrampolineHook on iOS: Stack alignment pitfall (figure 13)

The root cause was stack alignment. The System V AMD64 ABI specifies:

The end of the input argument area shall be aligned on a 16 (32 or 64, if __m256 or __m512 is passed on stack) byte boundary. In other words, the value (%rsp + 8) is always a multiple of 16 (32 or 64) when control is transferred to the function entry point. The stack pointer, %rsp, always points to the end of the latest allocated stack frame.

Hooking Objective-C Blocks with TrampolineHook on iOS: Stack alignment pitfall (figure 14)

The System V AMD64 calling convention requires 16-byte stack alignment at a function-call boundary. Immediately before call, %rsp must be a multiple of 16. Some SIMD instructions, including aligned moves such as movaps, rely on correctly aligned memory operands.

At the crash site, the rbp value used by movaps was 0x7ff7bac48f98, which was not 16-byte aligned; applying the -0x30 offset did not restore alignment. The trampoline had pushed an odd number of caller-saved registers, shifting the stack away from the required boundary.

1
2
3
4
5
6
7
8
9
10
11
.macro save_register
push %rdi
push %rsi
push %rdx
push %rcx
push %r8
push %r9
push %r10
push %r11
push %rax
.endm

The fix is to push one additional register, as shown by the repeated instruction on line 10.

1
2
3
4
5
6
7
8
9
10
11
12
.macro save_register
push %rdi
push %rsi
push %rdx
push %rcx
push %r8
push %r9
push %r10
push %r11
push %rax
push %rax
.endm

Why not save and restore xmm0-xmm7?

Hooking Objective-C Blocks with TrampolineHook on iOS: Why not save and restore xmm0-xmm7 ? (figure 15)

The x86_64 implementation does not currently preserve the floating-point registers. Xcode’s assembler rejected the syntax I tried, and I have not yet found a satisfactory solution. This remains a known limitation.

Thoughts

Trampoline-based interception appears in several runtime techniques:

  1. Apple’s own imp_implementationWithBlock is implemented based on this technique.
  2. Apple’s famous MainThreadChecker also uses a similar technique.

TrampolineBlockHook effectively inserts two function stubs around a block: pre and post. Those interception points enable several useful forms of instrumentation that I plan to explore:

  1. measuring block execution time,
  2. adding logs to blocks,
  3. analytics and event tracking.

TrampolineBlockHook still needs more work, particularly around thread safety and validation in large production codebases.

Summary

Although the examples in this article use different low-level mechanisms, they share the same core idea: route control flow through a trampoline while preserving the original calling context. Building TrampolineBlockHook made the ABI details concrete, especially on x86_64, where stack alignment caused failures that were initially difficult to diagnose. This article records both the resulting design and the debugging path that led to it.

References

  1. x86_64 architecture function calls and stack frames
  2. x86_64 assembly 4: function calls and calling conventions
  3. Differences between GCC assembly syntax and Intel assembly syntax
  4. Function calls and stack frames on x86-64
  5. Simple implementation of static interception for iOS object method calls
  6. A brief discussion of ARM64 assembly
  7. A bridge-based full method hook solution (2)
  8. A bridge-based full method hook solution (3) - TrampolineHook
  9. Why assembly can hook objectivec_msgSend, part 1
  10. Why assembly can hook objc_msgSend, part 2
  11. Byte alignment of the x86_64 Linux runtime stack
  12. https://github.com/g0dA/linuxStack/
  13. https://github.com/bang590/JSPatch/wiki/
  14. http://seanchense.github.io/2019/12/04/block-flags/
  15. https://clang.llvm.org/docs/Block-ABI-Apple.html
  16. Guide to x86-64
  17. https://juejin.cn/post/6844904098580398087
  18. https://blog.csdn.net/Desgard_Duan/article/details/107829106
  19. https://nickdesaulniers.github.io/blog/2014/04/18/lets-write-some-x86-64/
  20. https://evian-zhang.github.io/index.html
  21. https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI
  22. https://juejin.cn/post/6988867705637961742
  23. https://satanwoo.github.io/2017/04/23/ARM64IndirectReturn/
  24. https://landonf.org/code/objc/imp_implementationWithBlock.20110413.html
  25. https://opensource.apple.com/source/libclosure/
  26. https://docs.oracle.com/cd/E19120-01/open.solaris/817-5477/eojde/index.html
-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:Hooking Objective-C Blocks with TrampolineHook on iOS

Author:lingyun

Published:2023-05-08 23:40

Updated:2026-10-07 14:27

Original link:https://tsuijunxi.github.io/en/2023/05/08/center-redirection-in-ios/

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