[RFC] Universal CFI

Summary

We (Google) are working to make CFI something that can be deployed significantly more easily and at a larger scale than it has been until now. This includes:

  • Building on the kCFI model of hash-based enforcement
  • Expanding it to virtual functions and vtables in C++
  • Adding source annotations (or other techniques) to narrow the sets of valid CFI targets
  • Exploring ways to use the same techniques for backward-edge CFI when we don’t have hardware support available (PAC or CET)
  • Improving the code generation of the hash checks for non-kernel use cases
  • Improving the optimization passes throughout LLVM to handle checks more effectively
  • Fixing correctness issues that we uncover with significantly wider deployment

This is a (very) urgent project for us, and you may have already seen several PRs for small fixes and improvements. This RFC aims to both provide the context for where these are going and to propose the larger changes. Some of the larger changes may end up as their own, focused RFC with more details.

Background and motivation

Vulnerabilities in C/C++ software are a growing problem:

We need as many and as strong of defenses as possible, and ones we can deploy rapidly to existing software systems.

CFI provides a particularly compelling option as its security model does not depend on secrets that can be leaked and is not a fundamentally probabilistic mitigation. However, it has historically struggled with deployment complexity, overhead, and precision gaps. We think we have tools to address these challenges and make it viable for the vast majority of software.

There are two existing CFI implementations in Clang and LLVM – what has been called “full” CFI and kCFI added for the Linux Kernel.

Goals and non-goals

Our goal is to make forward-edge CFI practical to enable by default across C and C++ software, including builds without LTO and binaries that link against uninstrumented shared libraries or hand-written assembly with minimal restrictions and source workarounds.

We also want to re-use the techniques for forward-edge CFI to provide a back-stop backward-edge CFI implementation on hardware that can’t enforce this directly. Direct hardware support is always preferable for backward-edge CFI.

This RFC does not aim to replace full LTO CFI, change existing Linux kernel kCFI invariants, or cover general memory safety.

Proposal: uCFI

We are proposing to build a general purpose and easily deployed CFI mode (tentatively called “uCFI” and enabled with -fsanitize=ucfi as a group covering these checks similar to -fsanitize=cfi, but happy to have a better name), based heavily on kCFI which has proven both less expensive and easier to scale up for deployment. We think it is worth having a distinct name however as the current kCFI has important Linux Kernel specifics that need to be preserved. Making this more readily deployable requires several distinct components of work that we break down in this RFC.

Existing kCFI enforces forward-edge CFI locally in each translation unit, without LTO or jump tables. Clang hashes each function’s canonicalized type signature into a 32-bit integer and attaches it to functions and indirect call sites in IR. The backend places that hash immediately before each function’s entry point. Combined with W^X, this ensures that either the hash is not writable or the target of the branch is not executable. Before an indirect call, generated code loads the word preceding the target address, compares it with the expected hash, and traps on mismatch. On x86-64, call sites compare against the negated hash so valid hash values do not appear in executable call-site code.

We propose that uCFI keeps this local, LTO-free model and adapts it for general C and C++ userspace. The main changes are extending coverage to C++ and exception handling, adding linker trampolines for uninstrumented external code, moving traps out of line by default, and relaxing kernel-only prefix constraints so prefixes can carry richer metadata.

Note: the majority of work we suggest here we expect to be generally applicable across kCFI and uCFI and all of that should be shared, likely making kCFI increasingly available for C++ kernels as well. We expect the distinction between kCFI and uCFI to be (Linux) Kernel-specific ABI considerations such as an exact x86 function preamble to align with -fpatchable-function-entry, a fixed inline trap layout that can be rewritten by FineIBT, etc.

Virtual function calls

Virtual functions are called indirectly only through vtables rather than ordinary function pointers, so virtual calls use a separate hash domain. We also can incorporate more precise information into the hash than the signature of the function:

  • Slot identity: Under the Itanium C++ ABI, we hash the virtual method that originally introduced the vtable slot rather than just its signature. Overriders and adjusting thunks inherit that hash, separating unrelated classes and distinct slots that happen to share a signature while handling covariant returns cleanly. Under the Microsoft ABI, where slot origin is not always available during thunk emission, we fall back to a generalized method signature.
  • Member function pointers: Non-virtual member pointers check signature hashes in their own domain, separate from free functions. Virtual member pointers on the Itanium ABI store a vtable offset instead of a code address, so taking the address of a virtual member function emits a small dispatch thunk that performs the checked virtual call. This is based on Clang’s existing pointer-authentication approach. Instrumented calls trap if they encounter a raw vtable-offset pointer from uninstrumented code.
  • Closing the gap with full CFI: A single root-slot hash allows sibling overriders under the same base class and does not validate the vtable pointer itself. We are exploring ideas to close this gap without LTO. Initially, our idea is to store a short chain of hashes along the inheritance path in the function prefix so calls can check at the static receiver depth. The details and specifics will be its own PR / RFC as needed once we have a prototype that is in good shape, as well as further extensions to fully close this gap.

LLD trampoline insertion

Unlike the Linux Kernel, userspace binaries routinely take the address of functions defined outside instrumented code: shared libraries, GNU IFUNCs, and hand-written assembly. Because those entry points have no hash prefix, indirect calls to them trap. We can fix this by having Clang and LLD collaborate:

  • Backend symbol emission: Clang currently emits per-declaration type-ID symbols through module-level inline assembly, which breaks under LTO and ThinLTO and misses backend hash adjustments. Moving emission into the backend after optimization ensures symbols appear only for functions whose address is actually taken, using the final codegen hash.
  • Linker trampolines: Under an opt-in LLD flag for ELF, the linker scans these type-ID symbols before ICF. It reports a link-time error if translation units disagree on a symbol’s hash or if an instrumented definition has a different hash, and leaves matching definitions untouched. For shared symbols, IFUNCs, and uninstrumented local definitions such as assembly, LLD synthesizes a prefixed trampoline that jumps to the target or its PLT entry, redirecting references only in objects that took the symbol’s address.
  • Boundaries: Linker trampolines cover statically referenced external symbols with only a direct jump on the indirect-call path. They cannot cover dynamically obtained pointers such as dlsym, vDSO entries, or pointers returned by uninstrumented libraries, nor weak shared symbols that may resolve to null. Those cases still require targeted opt-outs or wrappers.

Coverage of invoke

Because kCFI targeted the Linux kernel, which builds without C++ exceptions, indirect invoke instructions went largely untested. Under -fexceptions, however, most indirect calls inside try blocks or scopes with local destructors lower to invoke rather than call.

Both x86 instruction selection and the target-independent IR pass inspected only non-throwing call instructions, silently leaving indirect invoke calls unchecked even though AArch64, ARM, and RISC-V already handled both. We propose handling invoke across all of the passes, and also doing the work to make out-of-line traps (discussed below) work with exception handling mechanisms attached to invokes.

Checking invoke also surfaces a runtime ABI boundary: exception unwinding in libc++abi invokes a thrown object’s destructor as void (*)(void *), which mismatches a class destructor’s void (T *) hash and will need some customized handling.

Reverse CFI or backward-edge CFI

Unlike forward-edge CFI hardware implementations, backward-edge implementations like Arm’s PAC and CET’s shadow stack are strong and precise mitigations. We want to enable those whenever hardware supports it.

However, we’d like to be able to close the coverage gap on older (largely x86) hardware. There, we plan to explore (likely in its own RFC) a way to use the same hash-based checking of kCFI for protecting returns. The current plan directly leverages the forward checks left by uCFI or kCFI to implement a backward-edge check. This has significant performance cost and isn’t quite as strong of a mitigation as the hardware options, so we are only imagining this as a fallback option on older hardware.

Avoiding accidental hash collisions

One challenge with analyzing the security of hash-based CFI protections is that the hashes might occur in other parts of the binary that are useful targets for an exploit. To combat this, we plan to explore how we can teach LLD to detect and reject binaries with byte-string collisions, improve the collision resistance of the hashes we emit to reduce the occurrence of these collisions, and if necessary provide a way for Clang and LLVM to emit code to materialize a constant without placing a colliding bit pattern into the emitted instruction sequence.

Performance optimizations

Hash-based enforcement in kCFI and uCFI scales well because it composes naturally with PGO indirect call promotion and ThinLTO whole-program devirtualization. In general, hash-based CFI enforcement avoids the need to embed some amount of full LTO into the build process, and especially into the instrumented build. Checks attach to calls as operand bundles instead of splitting IR basic blocks or introducing jump tables, and require no split LTO unit. When promotion or devirtualization turns a hot indirect call into a direct call, the hot path pays no CFI overhead while the cold fallback stays checked.

Early measurements on large PGO-optimized C++ workloads put CPU overhead around 0.4% to 0.6%, compared with about 2% without PGO or LTO. Reaching that soundly requires three sets of compiler changes:

  • Out-of-line traps: Upstream kCFI places traps inline before the call, forcing every passing check to take a branch over the trap. Moving traps into cold out-of-line blocks lets passing checks fall through, reducing latency and indirect-branch mispredictions while keeping per-call debug and unwind info. Inline traps stay available for Linux kernel kcfi, while out-of-line traps should be the default for ucfi.
  • Sound indirect call promotion: Call promotion must verify that a candidate callee’s hash matches the call site’s expected hash before promoting, preventing stale or mismatched profiles from bypassing CFI on the fast path. Carrying type hashes into ThinLTO-imported declarations lets promotion verify targets without importing function bodies, and later simplifications must preserve profile metadata when stripping checks from direct calls.
  • Devirtualization and tuning: Scoping integer normalization strictly to function types stops it from altering vtable metadata and breaking whole-program devirtualization. Higher indirect-call cost also favors more aggressive call-promotion thresholds and strict vtable-pointer optimizations to hoist repeated dispatch out of loops.

Source annotations for narrowing target sets

One of the current limitations of kCFI is that it doesn’t provide high-precision sets of indirect function call targets, only enforcing the type signature match. We can close this gap by extending and more aggressively using source annotations to refine the target sets:

  • Extend cfi_salt from C to C++ functions, methods, and virtual functions so libraries can adopt it.
  • Explore lightweight tag-type annotation schemes to further separate semantically distinct callback types that share a signature, analogous to what Rust has done: cfi_encoding - The Rust Unstable Book

Naming, flags, and compatibility with kCFI

We propose the following rough naming system, but happy to have suggestions here:

  • Preserve -fsanitize=kcfi for targeting Linux Kernel compatible CFI enforcement.
  • Add -fsanitize=ucfi which shares infrastructure with kcfi but diverges specifically in the layout and ABI:
    • Out-of-line trap code layout.
    • Relaxing the valid instruction prefix rule to expand hash bits or allow chained hashes.
  • (Optional) Rename shared infrastructure between these modes from kCFI to HashCFI or some other general purpose name.

Alternatives considered

Many groups have been working on CFI in LLVM for many years, and so there is a wide menu of options available.

However, despite concerted efforts we have not been able to scale up deployment of other approaches to CFI such as the full LTO or ThinLTO based versions (“full” CFI). Because of the increased time sensitivity of having these mitigations in place, we are planning to sharply focus on what we can deploy universally.

We have also looked carefully at exclusively leveraging hardware based forward-edge CFI, but it provides dramatically lower precision than we can achieve in software, and we can make the forward-edge software implementation fast enough to deploy universally. While we could use it in conjunction with uCFI to make it harder to have a hash collision, we think we can eliminate hash collisions in other ways and save the codesize cost. Hardware based backward-edge CFI is still essential for good performance.

Upstreaming plan and impact

We have already started sending some of the easy fixes to generalize kCFI, and are ready to actively upstream more. We have a largely working prototype of uCFI implemented for all of our main C++ codebase.

Our focus is on generalizing kCFI first, and then we can make some tactical renaming where it makes sense to keep things well organized. Happy to have suggestions on sequencing or ordering.

Acknowledgements

All of this builds on the extensive work done to build LLVM’s CFI and kCFI infrastructure. This RFC and all the PRs related are also the work of a broad group of Clang and LLVM contributors, not just myself. =]

3 Likes

One suggestion is to move away from the current kcfi hashing function.

It does not work for many c compatibility functions. There has to have some better way of doing the hashing than using the mangled c++ like name.

That is not fully true. Pointer to member functions can call virtual functions. And in some cases pointer to member functions can just be pointing to the virtual function. Unless I am missing something in the ia64 abi there.

Oh and it looks like clang does not implement (even though it claims to be GNU C++ compatible) the GNU extension that would allow this:

Iterating on the hashing is definitely in-scope here. I think we’ll have some PRs in this space, but happy to have more ideas to tighten and harden hash-based CFI and PRs in that direction.

We specifically mention extending the cfi_salt in the RFC, and I’m guessing there is a lot more to come.

@zygoloid can maybe speak to this more directly than I can – my understanding is that in standard C++, pointer-to-virtual-member-functions can only be called as such. The RFC mentions this, and our prototype currently uses the same thunking approach as in the Arm PAC implementation for this.

However, it does break the GNU extension you reference.

Technically, it also breaks something that we’ve asked the committee to consider rejecting in standard C++ as well: taking the address of a virtual member function which has incomplete argument or return types.

Both of these seem like very reasonable tradeoffs for the protection of CFI, and we’ve been able to build all of our monolithic codebase, including all of its OSS dependencies, in this mode without issue.

I’m excited to see a drive towards use of control-flow integrity in wider set of deployed binaries!

We have also looked carefully at exclusively leveraging hardware based forward-edge CFI, but it provides dramatically lower precision than we can achieve in software, and we can make the forward-edge software implementation fast enough to deploy universally.

I wanted to make sure I understood this correctly. “lower precision”: is that because fewer hash bits may be used in the hardware based forward-edge CFI schemes compared to the kcfi scheme; or something different?

Most hw forward edge protection doesn’t use any meaningful bits AFAIK. CET doesn’t, and the default PAC behavior treats all indirect calls as equivalent. I know there are some interesting hw extensions to PAC that increase the inputs to any hash, but not aware of those being widely available or deployed (happy to be corrected if wrong tho!!)

and the default PAC behavior treats all indirect calls as equivalent

Sorry to be a pain. PAC is used by more than one protection scheme and I wanted to know which one?

There’s pac-ret which is from -mbranch-protection=standard (or pac-ret) which covers the return address only.

There’s also the arm64e (Apple) and PAuthTest (ELF) that also covers indirect calls. C function pointers do not use type discrimination by default as I believe that causes problems with some permitted C casting. C++ pointers, including vtable pointers have more options available such as type and address discrimination. It is true that PAuthTest is not widely deployed though due to its test status. I have been trying to change that [RFC][AArch64] Full support for ELF Pointer Authentication ABI (PAuthABI) but I expect bare-metal embedded to be the most likely use case as ABI is less of a problem there.

Encouraging to see a full software based solution proposed, as ease of deployability seems to be one of the most important properties that any CFI scheme needs.

To make sure I understand what the trampolines are. These would in effect be something like:

hash for fn
trampoline_for_fn:
   // bti c (aarch64) or endbr (I think for x86_64) if enabled.
   direct-branch to fn (fn@plt)

The linker would generate these for DSO local functions without a hash (presumably there’s a way it can identify the hash) and for all address taken external definitions. I guess that LD_PRELOAD stops the linker from examining any static shared-libraries to see if they already have hashes.

Thinking about function pointer equivalence across shared-object boundaries, I guess the trampoline becomes the canonical address for the function?

I expect that this trampoline insertion pass happens before finalizeAddressContent() rather than trying to extend the range extension trampoline pass.