Technique:Recognizing compiler-generated code/Control Flow Guard
Appearance
Topic page of Technique:Recognizing compiler-generated code.
How Microsoft Control Flow Guard (CFG) shows up in code: indirect calls routed through __guard_check_icall_fptr or __guard_dispatch_icall_fptr, with the target in RAX or ECX, and the tables in the PE load config.
Control Flow Guard (/guard:cf, also clang-cl -cfguard) validates the target of every indirect call against a bitmap of valid function starts. The compiler emits one of two call shapes; the loader fills in the pointer.
The two mechanisms
- Check (
__guard_check_icall_fptr): the target is first passed to a check function, then called normally. LLVM's description: the target goes in a register (ECX on x86, X15 on AArch64, R0 on ARM); the check function has no return value and raises a failure if the target is invalid. x86 example from the LLVM source:movl $_target_func, %ecx; calll *___guard_check_icall_fptr; calll *%ecx. - Dispatch (
__guard_dispatch_icall_fptr): the loader writes the address of a dispatch routine into this global; the call goes there instead, the target is in RAX on x64 (other argument registers as usual), and the routine validates and tail-calls the target. x64 example from the LLVM source:leaq target_func(%rip), %rax; callq *__guard_dispatch_icall_fptr(%rip). This is what x64 binaries normally use. - Both are defined in
llvm/lib/Transforms/CFGuard/CFGuard.cpp(names__guard_check_icall_fptr,__guard_dispatch_icall_fptr).
Reading it
- Replace
call [__guard_dispatch_icall_fptr]withcall raxmentally; the decompiler may show an unknown function pointer call with a hidden register argument. - Indirect calls through a vtable look like
mov rax, [rcx]; mov rax, [rax+X]; call [__guard_dispatch_icall_fptr]. - Unverified: the global pointers live in
.data/.00cfgsections and the dispatch pointer initially points to a stub that jumps to ntdll'sLdrpDispatchUserCallTarget(x64) or similar; confirm on a binary. - PE side: Guard flags, GuardCFCheckFunctionPointer, GuardCFDispatchFunctionPointer, the function table (sorted RVAs, count) are in the load config directory, see Format:PE (Portable Executable)/Load config directory. The function table is a free list of valid indirect-call targets (address-taken functions): useful for finding virtual functions and callbacks in a stripped binary.
Evidence & references
- llvm-project
llvm/lib/Transforms/CFGuard/CFGuard.cpp(read: doc comments of insertCFGuardCheck and insertCFGuardDispatch).