Dynamic Function Table RF_CALLBACK Injection
Dynamic Function Tables & the RF_CALLBACK (Type 2) Mechanism
On x64 Windows, stack unwinding for exceptions and SEH is table-driven, not frame-pointer-based. Every function that touches the stack must have a RUNTIME_FUNCTION entry (.pdata) describing its prologue/epilogue so the unwinder can walk the stack.
For statically compiled modules, RtlLookupFunctionEntry() finds these tables via the PE’s IMAGE_DIRECTORY_ENTRY_EXCEPTION. But for JIT-compiled code (CLR, Java, JavaScript engines, dynamically generated stubs), Windows exposes an API to register unwind info at runtime:
RtlAddFunctionTable()- Type 1 (static table in memory)RtlInstallFunctionTableCallback()- Type 2 (RF_CALLBACK) aka the interesting oneRtlAddGrowableFunctionTable()- Type 3
From Microslop’s own documentation:
For dynamically generated functions [JIT compilers], the runtime to support these functions must either use RtlInstallFunctionTableCallback or RtlAddFunctionTable to provide this information to the operating system. Failure to do so results in unreliable exception handling and debugging of processes.
Internally these all populate the process-global list ntdll!RtlpDynamicFunctionTable (a doubly linked list guarded by RtlpDynamicFunctionTableLock, an SRW lock).
The DYNAMIC_FUNCTION_TABLE Structure
Microsoft defines DYNAMIC_FUNCTION_TABLE as:
The
DYNAMIC_FUNCTION_TABLEstructure is an entry in a linked list which is used by a debugger to discover all of the dynamic function tables in a target process.
Each node roughly looks like (thank you ReactOS):
1 | |
For Type 2 (RF_CALLBACK), FunctionTable is NULL and instead the unwinder must call Callback(ControlPc, Context) every time it needs a RUNTIME_FUNCTION for an address in [MinimumAddress, MaximumAddress).
Looking into the definition of PGET_RUNTIME_FUNCTION_CALLBACK:
1 | |
If this callback function returns NULL it means “no unwind info here” - the callback still ran, which is the whole point.
The Registration API
1 | |
That Callback pointer is stored as a raw function pointer in the caller’s own heap-tracked list inside ntdll. It is not CFG-guarded on the way in, and it lives at a data address (not in a code section).
SUS!
Sidenote: At this point of writing this blog, my friends forced me to buy Skyrim and Cyberpunk. Is it bad that I haven’t played any of these? Anyways, moving on.
The Invocation Path - Where the Callback Fires
The interesting question for injection research is: “what makes ntdll actually call that function pointer?”
The chain is:
1 | |
Any exception raised by any thread whose PC falls in the registered range: RtlDispatchException -> RtlVirtualUnwind -> RtlLookupFunctionEntry. So the primitive is: “if I can make the process throw/unwind through an address I own, my callback runs - with the ControlPc and my Context as arguments.”
The Exception-Driven Trigger
A naive approach would call RtlLookupFunctionEntry directly from the injected stub - but that makes the injected code explicitly invoke a function-table API, which is unusual for non-JIT code and trivially detectable.
The cleaner design: don’t call RtlLookupFunctionEntry at all. Instead, trigger an exception at an address within the registered range. The OS exception dispatcher (KiUserExceptionDispatcher -> RtlDispatchException) naturally calls RtlLookupFunctionEntry during its stack walk - it’s the OS doing the lookup, not our code.
Here’s the chain:
- The APC stub registers our RF_CALLBACK via
RtlInstallFunctionTableCallback - The stub executes
ud2(invalid opcode, 2 bytes:0F 0B) - this triggers aSTATUS_ILLEGAL_INSTRUCTIONexception - The OS exception dispatcher begins a stack walk, calling
RtlLookupFunctionEntryfor the faulting PC - Since the fault PC is within our registered range, our RF_CALLBACK fires - it returns a
RUNTIME_FUNCTIONpointing to anUNWIND_INFOwith an exception handler - The dispatcher calls our exception handler, which modifies
ContextRecord->Ripto point past theud2and returnsExceptionContinueExecution NtContinueresumes execution at the modified RIP - the stub continues with cleanup and shellcode
The callback returns real unwind data - a RUNTIME_FUNCTION structure pointing to UNWIND_INFO with UNW_FLAG_EHANDLER. The exception handler is the mechanism that keeps the target alive: it catches the intentional fault and redirects execution, all through the legitimate x64 structured exception handling framework. The actual shellcode still runs later, in a completely normal context - no calling convention constraints, no unwinder expectations.
Why Not Just Manually Write the List Entry?
One of the first things I tried was skipping RtlInstallFunctionTableCallback entirely and just crafting a fake DYNAMIC_FUNCTION_TABLE structure via WriteProcessMemory, then splicing it into the doubly-linked list. Sounds reasonable, right?
It doesn’t work. And the reason is that RtlLookupFunctionEntry does not walk the linked list to find matching entries. Internally (observed via reverse engineering of ntdll), RtlpLookupDynamicFunctionEntry searches four AVL trees - two pairs, one for callback-type entries and one for function-table entries, each pair indexed by MinimumAddress and MaximumAddress respectively (RtlpDynamicCallbackTableTreeMin/Max, RtlpDynamicFunctionTableTreeMin/Max). The linked list is there for debugger enumeration (and RtlDeleteFunctionTable), but the hot lookup path goes through the AVL trees exclusively.
So writing a list node alone leaves the AVL trees completely unaware of your entry. The lookup never finds it. And correctly inserting into the AVL trees would require balancing, parent-pointer updates, and acquiring the SRW lock - basically reimplementing half of ntdll’s internals via WriteProcessMemory. Not fun. Just call the API.
Injection Design
An earlier version of this PoC used CreateRemoteThread to run the stub - but that defeats the purpose. VirtualAllocEx + WriteProcessMemory + CreateRemoteThread is the same detection surface as every other injection technique. EDRs already flag that pattern in their sleep.
Instead, we deliver the stub via QueueUserAPC. No new thread is created. The stub runs on an existing thread in the target when it enters an alertable wait. The PAPCFUNC callback takes a single ULONG_PTR parameter in RCX - same register, same position as our setup data pointer, so the stub code is identical.
The full injection flow:
sequenceDiagram
participant I as Injector
participant T as Target Process
participant N as ntdll
Note over I: Resolve ntdll API addresses
(same across processes, per-boot ASLR)
I->>T: VirtualAllocEx(RWX)
Note over T: Memory allocated at base
I->>T: WriteProcessMemory
Note over T: +0x000 APC stub (ud2 at +0x3E)
+0x100 RF_CALLBACK
+0x110 Exception handler
+0x130 RUNTIME_FUNCTION + UNWIND_INFO
+0x200 Setup data (fn ptrs)
+0x400 Shellcode (embedded)
I->>T: QueueUserAPC(base, thread, base+0x200)
Note over T: APC queued to existing thread
Note over T: Thread enters alertable wait...
activate T
T->>N: RtlInstallFunctionTableCallback(
base|3, base, allocSize,
base+0x100, base, NULL)
N-->>T: Registered
Note over T: ud2 -> STATUS_ILLEGAL_INSTRUCTION
T->>N: KiUserExceptionDispatcher
N->>N: RtlDispatchException -> stack walk
N->>T: RtlLookupFunctionEntry(fault_PC)
-> invokes RF_CALLBACK
T-->>N: Returns &RUNTIME_FUNCTION
(-> UNWIND_INFO with handler)
N->>T: Calls exception handler at +0x110
T-->>N: Sets Rip = base+0x40
Returns ExceptionContinueExecution
Note over N: NtContinue -> resumes at stub+0x40
T->>N: RtlDeleteFunctionTable(base|3)
N-->>T: Cleaned up
Note over T: call base+0x400 -> SHELLCODE RUNS
deactivate T
Note over I: Poll status byte via
ReadProcessMemory until done
A few things worth noting:
- No
CreateRemoteThread. The APC runs on an existing thread - no new thread is created in the target. This avoids one of the most heavily monitored injection indicators. - ntdll API addresses are the same in every process (per-boot ASLR randomizes the base, but all processes load the same ntdll). We only need to resolve
RtlInstallFunctionTableCallbackandRtlDeleteFunctionTablelocally and pass the addresses to the target.RtlLookupFunctionEntryis never called by our code - the OS calls it internally during exception dispatch. - The
TableIdentifiermust have the low 2 bits set (base | 0x3) - this is how ntdll distinguishes callback-based entries from pointer-based ones. - We trigger the callback via
ud2- an intentional invalid opcode exception. The OS exception dispatcher walks the stack, callingRtlLookupFunctionEntryfor the faulting PC. Since the fault is within our registered range, our RF_CALLBACK fires. It returns aRUNTIME_FUNCTIONpointing toUNWIND_INFOwithUNW_FLAG_EHANDLER, whose exception handler redirects execution past the fault. - We clean up after ourselves with
RtlDeleteFunctionTable. The dynamic function table entry is transient - it exists only between the Install and Delete calls. - APCs are queued to all threads. If multiple threads enter alertable waits, the stub runs more than once - multiple calc windows, repeated Install/Delete cycles. For a PoC this is fine; a weaponized version would target a single thread or guard with an interlocked status byte.
- Since there’s no thread handle to wait on, we poll the status byte via
ReadProcessMemoryto track progress.
Payload Memory Layout
The payload buffer we write into the target has a fixed layout:
1 | |
The status byte at +0x300 is a diagnostic breadcrumb - the APC stub writes the current stage number before each step, so if the target crashes or hangs, we can read that byte back via ReadProcessMemory and know exactly where it died. Status 0x02 means the ud2 fired but the exception handler didn’t redirect execution - a failure in the unwind data or structures.
The APC Stub
The APC stub is a small x64 shellcode that orchestrates the whole sequence. It’s delivered via QueueUserAPC and runs when the target thread enters an alertable wait. PAPCFUNC receives a single ULONG_PTR in RCX - we pass a pointer to the setup data, which is exactly the same calling convention as LPTHREAD_START_ROUTINE. The machine code is identical either way:
1 | |
The mov r8d, <allocSize> immediate gets patched at runtime with the actual allocation size - the injector knows this value only after VirtualAllocEx returns.
A nice property of the x64 calling convention: PAPCFUNC(ULONG_PTR) and LPTHREAD_START_ROUTINE(LPVOID) both pass their single argument in RCX. So this same machine code works whether delivered via QueueUserAPC or CreateRemoteThread.
The RF_CALLBACK returns real unwind data:
1 | |
And the exception handler at +0x110 redirects execution past the ud2:
1 | |
The handler gets ImageBase from the DISPATCHER_CONTEXT (which the OS passes as the 4th parameter, in r9). ImageBase is the BaseAddress we registered - our allocation base. Adding 0x40 (the offset of the resume point within the APC stub) gives the address to continue at. The handler writes this into ContextRecord->Rip (at offset 0xF8 in the x64 CONTEXT structure) and returns 0 (ExceptionContinueExecution), telling the dispatcher to resume execution at the modified RIP via NtContinue.
The PoC
Here is the full injector. It takes a target PID, builds the payload with an embedded WinExec("calc.exe") shellcode, and injects via QueueUserAPC to existing threads. No new thread is created in the target.
Build with:
1 | |
Usage:
1 | |
1 | |
Test Run
Here’s what a successful injection looks like against notepad.exe. The embedded shellcode pops calc.exe via WinExec and returns cleanly:
1 | |
Status 0xFF confirms the full exception-driven chain completed: the APC stub registered the dynamic function table, triggered an intentional ud2 exception, the OS dispatcher called RtlLookupFunctionEntry during its stack walk which invoked our RF_CALLBACK, the returned RUNTIME_FUNCTION/UNWIND_INFO directed the dispatcher to our exception handler which redirected execution past the fault, RtlDeleteFunctionTable cleaned up the entry, and the shellcode ran. Notepad stays alive, Calculator appears.
Detection Surface
Let’s talk about what this looks like from a defender’s perspective.
| Artifact | Description |
|---|---|
VirtualAllocEx |
RWX allocation in target (standard for most injection) |
WriteProcessMemory |
Payload write (standard) |
QueueUserAPC |
APC to existing thread - no new thread created |
RtlInstallFunctionTableCallback |
Unique to this technique - called inside target |
STATUS_ILLEGAL_INSTRUCTION |
Transient ud2 exception - handled internally, not visible to debugger unless first-chance |
RUNTIME_FUNCTION / UNWIND_INFO |
Crafted unwind data with exception handler in RWX memory |
| Dynamic function table entry | Transient; cleaned up by RtlDeleteFunctionTable |
| No modified existing data | No hooks, no patched pointers, no DLL loads at injection time |
The delivery avoids CreateRemoteThread entirely - one of the most heavily monitored injection indicators. QueueUserAPC to an existing thread is lower-profile: no new thread appears in the target, and the code runs in the natural context of an alertable wait.
Notably, RtlLookupFunctionEntry is never called by the injected code - it’s invoked by the OS exception dispatcher (RtlDispatchException) as part of the normal stack walk during exception handling. This makes the trigger harder to detect via API monitoring, since the lookup happens inside ntdll’s own exception dispatch path, indistinguishable from any other exception being handled.
What blue teams should watch for:
RtlInstallFunctionTableCallbackcalls from non-JIT contexts. Legitimate callers are JIT engines (CLR, V8, Chakra). An application thread registering a function table for an RWX region is very suspicious.- Dynamic function table registrations covering RWX memory. JIT engines typically use RX (execute+read) after compilation. RWX is sloppy. (Yes, our PoC is sloppy. No, I don’t care for a PoC.)
QueueUserAPCfrom a process writing to the target’s memory. Cross-referenceVirtualAllocEx+WriteProcessMemory+QueueUserAPC- this triple is less commonly flagged than the classicCreateRemoteThreadvariant but equally suspicious.- The callback entry exists only transiently - between the Install and Delete calls. Periodic snapshots of
RtlpDynamicFunctionTablemight miss it entirely. - Exception handlers in RWX memory. A
RUNTIME_FUNCTION/UNWIND_INFOchain pointing to an exception handler inside an RWX allocation is unusual - legitimate exception handlers live in mapped image sections, not dynamically allocated memory.
One thing to note is that if you can trigger a crash somehow at a PC within the registered range, you can skip the APC altogether(well, that is a topic for another time ¯_(ツ)_/¯)
References
- Exception Handling (x64) - Microsoft Learn
- RtlInstallFunctionTableCallback - Microsoft Learn
- RtlLookupFunctionEntry - Microsoft Learn
- DYNAMIC_FUNCTION_TABLE_TYPE - Microsoft Learn
- ReactOS DYNAMIC_FUNCTION_TABLE
- SRW Locks - Microsoft Learn
- klezVirus - BYOUD: Bring Your Own Unwinding Data - Related work on dynamic function table internals for call-stack spoofing via
RtlAddFunctionTable(Type 1). Presented at Black Hat Europe 2025. - NocturneLdr (xec412) - Patches dynamic function table entry type from
RF_CALLBACKtoRF_SORTEDfor detection evasion.
PS: This is the first time I have had claude/qwen help me write stuff because I wanted to get things out fast. I just wanted to be transparent about that - it’s been a busy few weeks man.