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 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?
- 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.
- 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 | extern BOOL hook_block_with_stub(void *replaced, void *replacement, void *pre, void *post); |
Before diving into the implementation, here is the API in action:
1 | void pre(void *p1, void *p2) { |
The output is shown below:
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.
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.
Mapping the code and data pages
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 | // Allocate two contiguous pages. |
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 | struct Block_descriptor { |
Control-flow redirection
- Save the original block implementation address as
A. - Point the block’s
invokefunction at a dynamically mapped trampoline entry,B. - When the block is invoked, execution branches to
B. - The trampoline retrieves the metadata associated with that entry,
including the saved address
A. - If a
prestub is present, call it before the original implementation. - Call the original implementation at
Awith the original execution context. - When it returns, call the
poststub and then resume the caller’s control flow.
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 | extern BOOL hook_block_with_stub(void *block, void *replacement, void *pre, void *post) { |
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 | BOOL unhook_block(void *block) { |
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 | - 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. |
Assembly code
1 | #if defined(__arm64__) |
On arm64, one page is
0x4000, or 16 KB, so.align 14is used. On arm64, every instruction is 4 bytes regardless of length.
The dispatch sequence works as follows:
Because the block’s
invokefunction points at atramp entry, calling the block branches directly to that entry. The entries are generated by a.reptblock repeated404times. A page contains16 KB = 16384 B; after subtracting the224 Bdispatch area, the remaining space holds(16384 - 224) / 40 = 404entries of40 Beach.Each
tramp entryoccupies40bytes. At entry,lrcontains the return address following the block call, so we preserve it inx13before branching to_block_tramp_dispatch. The eightnopinstructions pad the entry to40bytes, matching the size and offset of itstramp datarecord. Since every arm64 instruction is4bytes, each entry contains ten instructions in total.
1 | mov x13, lr |
- Because execution jumped from the entry,
lrholds the address of the instruction after the branch.lr - 8gives the start address of the entry, and subtracting one page size#0x4000gives the correspondingtramp dataaddress.
1 | sub x12, lr, #0x8 |
- Store the computed
tramp dataaddress on the stack.
1 | str x12, [sp, #-16]! |
x13currently stores the address after theBlock, so store it on the stack as well.
1 | str x13, [sp, #-16]! |
x12storestramp data. Offset24bytes from that address to get thepre stub. If it is null, jump directly to theblocklabel. Why24bytes? During redirection,preis stored atconfig[3];config[0]throughconfig[2]each take8bytes, so the offset is24bytes.
1 | ldr x13, [x12, #0x18] |
x13now holds thepreaddress, whichblrcalls directly. Because this is a nested function call, caller-saved registers must be preserved around it.
1 | pre: |
- The original block implementation is stored
16bytes into thetramp datarecord. Load it intox13and 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 | block: |
- Reload the
tramp dataaddress from the stack intox12, then offset32bytes to get thepostaddress. The subsequent call is similar topre. We reloadtramp databecause the previousblockcall did not preserve caller-save registers and may have destroyedx12.
1 | ldr x12, [sp], #16 |
- Load the address after the
Blockfrom the stack intox13, then jump to it.
1 | end: |
Hopper diagram
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
Assembly code
On x86_64, one page is
0x1000, or 4 KB, so.align 12is 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 | save_register |
Hopper diagram
Stack alignment pitfall
During debugging, the x86_64 implementation repeatedly crashed on
SSE instructions such as movaps.
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.
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 | save_register |
The fix is to push one additional register, as shown by the repeated instruction on line 10.
1 | save_register |
Why not save and restore
xmm0-xmm7?
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:
- Apple’s own
imp_implementationWithBlockis implemented based on this technique. - Apple’s famous
MainThreadCheckeralso 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:
- measuring block execution time,
- adding logs to blocks,
- 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
- x86_64 architecture function calls and stack frames
- x86_64 assembly 4: function calls and calling conventions
- Differences between GCC assembly syntax and Intel assembly syntax
- Function calls and stack frames on x86-64
- Simple implementation of static interception for iOS object method calls
- A brief discussion of ARM64 assembly
- A bridge-based full method hook solution (2)
- A bridge-based full method hook solution (3) - TrampolineHook
- Why assembly can hook objectivec_msgSend, part 1
- Why assembly can hook objc_msgSend, part 2
- Byte alignment of the x86_64 Linux runtime stack
- https://github.com/g0dA/linuxStack/
- https://github.com/bang590/JSPatch/wiki/
- http://seanchense.github.io/2019/12/04/block-flags/
- https://clang.llvm.org/docs/Block-ABI-Apple.html
- Guide to x86-64
- https://juejin.cn/post/6844904098580398087
- https://blog.csdn.net/Desgard_Duan/article/details/107829106
- https://nickdesaulniers.github.io/blog/2014/04/18/lets-write-some-x86-64/
- https://evian-zhang.github.io/index.html
- https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI
- https://juejin.cn/post/6988867705637961742
- https://satanwoo.github.io/2017/04/23/ARM64IndirectReturn/
- https://landonf.org/code/objc/imp_implementationWithBlock.20110413.html
- https://opensource.apple.com/source/libclosure/
- https://docs.oracle.com/cd/E19120-01/open.solaris/817-5477/eojde/index.html