Skip to contentSkip to conversation

Introduce Kernel Control Flow Integrity ABI [PR107048]

PATCH In review Kees Cook 2 participants 16 messages Oct 5 – Oct 25 RISC-V

lore
Share & tools
lore

Kees Cook

author
#0 lore raw

v17 cover Introduce Kernel Control Flow Integrity ABI [PR107048]

Hi,

This series implements[1][2] the Linux Kernel Control Flow Integrity ABI, which provides a function prototype based forward edge control flow integrity protection by instrumenting every indirect call to check for a hash value before the target function address. If the hash at the call site and the hash at the target do not match, execution will trap.

Regarding the recent AI policy[3], I appear to be compliant, though the use of the Assisted-by tag doesn't distinguish between the human code and the AI-assisted work in a single patch. I used LLMs to help me research the GCC codebase, debug crashes, minimize PoCs, generate test cases, construct and run my multiple architecture build and test orchestration, and perform code reviews. Based on the feedback from Cauldron[4], I've included the tag on every patch that carries tests.

As before, I'd really like to be in a position where more people can test with GCC snapshots, etc, and there can be some follow-up patches if(when) people find issues. It sounded like Andrea and Jeff were going to hopefully get this landed in the next month? *cross fingers*

Thanks!

-Kees

Changes since v16[5]:

- Rebase to latest master.
- Use the target's long double mangling (from targetm.mangle_type) in the typeinfo selftest and gcc.dg test instead of hard-coding "e". (Reported by Juergen Christ; fix suggested by Andrea Pinski and Jakub Jelinek.)
- RISC-V: use the pointer mode (:P) for the KCFI call patterns' address operands, which silences genrecog's "missing mode" warnings without hard-coding DImode. (Follow-up to Jeff Law's v2 and v12 feedback.)
- ARM: fix a scan-assembler-not in kcfi-call-sharing.c that could never match, and make it also catch a single call using the wrong type ID.
- Require the lto effective target in kcfi-lto-offset.c, so it is UNSUPPORTED rather than failing when GCC is built without LTO.
- AArch64: drop an unused kcfi_emit_trap_with_section prototype.
- AArch64: give the KCFI call patterns their real length (28 bytes, up to 36 for sibcalls with SLS hardening). They were counted as 4 bytes, so a conditional branch over many KCFI calls could be out of range.
- Use a volatile function pointer in kcfi-trap-encoding.c so its call stays indirect (and KCFI-checked) when the testsuite is run at -O2.
- Don't mangle top-level qualifiers on pointer parameters ("int *const p", "int *restrict p") or on anonymous-typedef parameters into the
type-id: they are not part of the function type, and Clang drops them. Such functions trapped when called through compatible pointer types like "void (*)(int *)". This changes their type-ids to match Clang.
- Add mangling tests for bool and for restrict below the top level (with the qualifier order), with expected strings checked against Clang.
- Fix tail merging combining indirect calls that get different KCFI
checks: calls through members of a union share one pointer value.

[1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=107048
[2] https://github.com/KSPP/linux/issues/369
[3] https://gcc.gnu.org/ai-policy.html
[4] https://outflux.net/slides/2026/cauldron/gcc-kcfi.pdf
[5] https://inbox.sourceware.org/gcc-patches/[email protected]/

Kees Cook (7):
kcfi: Introduce KCFI typeinfo mangling API
kcfi: Add core Kernel Control Flow Integrity infrastructure
kcfi: Add regression test suite
x86: Add x86_64 Kernel Control Flow Integrity implementation
aarch64: Add AArch64 Kernel Control Flow Integrity implementation
arm: Add ARM 32-bit Kernel Control Flow Integrity implementation
riscv: Add RISC-V Kernel Control Flow Integrity implementation

 gcc/kcfi.h                                    |   71 ++
 gcc/kcfi.cc                                   |  650 ++++++++++
 gcc/config/aarch64/aarch64-protos.h           |    3 +
 gcc/config/arm/arm-protos.h                   |    4 +
 gcc/config/i386/i386-protos.h                 |    2 +-
 gcc/config/i386/i386.h                        |    3 +-
 gcc/config/riscv/riscv-protos.h               |    3 +
 gcc/config/aarch64/aarch64.md                 |   66 +
 gcc/config/arm/arm.md                         |   62 +
 gcc/config/i386/i386.md                       |   63 +-
 gcc/config/riscv/riscv.md                     |   76 +-
 gcc/config/aarch64/aarch64.cc                 |  127 ++
 gcc/config/arm/arm.cc                         |  217 +++-
 gcc/config/i386/i386-expand.cc                |   28 +-
 gcc/config/i386/i386.cc                       |  210 +++-
 gcc/config/riscv/riscv.cc                     |  199 +++
 gcc/doc/extend.texi                           |  141 +++
 gcc/doc/invoke.texi                           |  141 +++
 gcc/doc/tm.texi                               |   32 +
 .../gcc.dg/kcfi-compat/kcfi-compat.exp        |   87 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi.exp            |   51 +
 gcc/testsuite/lib/target-supports.exp         |   14 +
 .../gcc.dg/builtin-typeinfo-bitint.c          |   82 ++
 gcc/testsuite/gcc.dg/builtin-typeinfo-c23.c   |   72 ++
 .../gcc.dg/builtin-typeinfo-errors.c          |   28 +
 gcc/testsuite/gcc.dg/builtin-typeinfo-fixed.c |   58 +
 gcc/testsuite/gcc.dg/builtin-typeinfo.c       |  429 +++++++
 .../gcc.dg/kcfi-compat/kcfi-indirect-1.h      |   26 +
 .../gcc.dg/kcfi-compat/kcfi-indirect-1_main.c |   22 +
 .../gcc.dg/kcfi-compat/kcfi-indirect-1_x.c    |   43 +
 .../gcc.dg/kcfi-compat/kcfi-indirect-1_y.c    |   40 +
 .../gcc.dg/kcfi/kcfi-aarch64-branch-range.c   |   29 +
 .../gcc.dg/kcfi/kcfi-aarch64-ilp32.c          |    7 +
 .../kcfi/kcfi-aarch64-insn-length-sls.c       |   32 +
 .../gcc.dg/kcfi/kcfi-aarch64-insn-length.c    |   38 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c    |  142 +++
 gcc/testsuite/gcc.dg/kcfi/kcfi-arm-fixed-ip.c |   15 +
 .../gcc.dg/kcfi/kcfi-arm-fixed-r12.c          |   15 +
 .../gcc.dg/kcfi/kcfi-arm-sibcall-r3.c         |   50 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-asm-name.c     |   16 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c       |  168 +++
 gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c |   95 ++
 .../gcc.dg/kcfi/kcfi-cold-partition.c         |  126 ++
 .../gcc.dg/kcfi/kcfi-complex-addressing.c     |  206 ++++
 .../gcc.dg/kcfi/kcfi-direct-call-shapes.c     |   36 +
 .../gcc.dg/kcfi/kcfi-ipa-robustness.c         |   54 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-lto-offset.c   |   27 +
 .../gcc.dg/kcfi/kcfi-move-preservation.c      |  138 +++
 .../gcc.dg/kcfi/kcfi-no-sanitize-inline.c     |  100 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c  |   41 +
 .../gcc.dg/kcfi/kcfi-offset-validation.c      |   40 +
 .../gcc.dg/kcfi/kcfi-patchable-entry-only.c   |   64 +
 .../gcc.dg/kcfi/kcfi-patchable-incompatible.c |    7 +
 .../gcc.dg/kcfi/kcfi-patchable-large.c        |   57 +
 .../gcc.dg/kcfi/kcfi-patchable-medium.c       |   63 +
 .../gcc.dg/kcfi/kcfi-patchable-prefix-only.c  |   64 +
 .../gcc.dg/kcfi/kcfi-qualified-params.c       |   58 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-riscv-32bit.c  |    7 +
 .../gcc.dg/kcfi/kcfi-riscv-fixed-t1.c         |    7 +
 .../gcc.dg/kcfi/kcfi-riscv-fixed-t2.c         |    7 +
 .../gcc.dg/kcfi/kcfi-riscv-fixed-t3.c         |    7 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-runtime.c      |  276 +++++
 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c   |  144 +++
 .../gcc.dg/kcfi/kcfi-tail-merge-run.c         |   54 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-merge.c   |   36 +
 .../gcc.dg/kcfi/kcfi-trap-encoding.c          |   89 ++
 .../gcc.dg/kcfi/kcfi-trap-section-per-func.c  |   23 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c |   29 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-32bit.c    |    7 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-arity.c    |   93 ++
 .../gcc.dg/kcfi/kcfi-x86-endbr-collision.c    |   55 +
 .../gcc.dg/kcfi/kcfi-x86-fixed-r10.c          |    7 +
 .../gcc.dg/kcfi/kcfi-x86-fixed-r11.c          |    7 +
 .../gcc.dg/kcfi/kcfi-x86-retpoline-r11.c      |   40 +
 gcc/testsuite/gcc.dg/pch/kcfi-1.c             |   50 +
 gcc/testsuite/gcc.dg/pch/kcfi-1.hs            |   20 +
 gcc/Makefile.in                               |    3 +
 gcc/c-family/c-common.h                       |    1 +
 gcc/flag-types.h                              |    2 +
 gcc/gimple.h                                  |   22 +
 gcc/kcfi-typeinfo.h                           |   31 +
 gcc/selftest.h                                |    1 +
 gcc/c-family/c-attribs.cc                     |   17 +-
 gcc/c-family/c-common.cc                      |    2 +
 gcc/c/c-parser.cc                             |   72 ++
 gcc/common.opt                                |    8 +
 gcc/df-scan.cc                                |    7 +
 gcc/doc/tm.texi.in                            |   12 +
 gcc/final.cc                                  |   17 +
 gcc/kcfi-typeinfo.cc                          | 1071 +++++++++++++++++
 gcc/opts.cc                                   |    5 +-
 gcc/rtl.def                                   |    6 +
 gcc/rtlanal.cc                                |    5 +
 gcc/selftest-run-tests.cc                     |    1 +
 gcc/target.def                                |   39 +
 gcc/toplev.cc                                 |   12 +
 gcc/tree-inline.cc                            |   10 +
 gcc/tree-ssa-tail-merge.cc                    |    6 +
 gcc/varasm.cc                                 |   44 +-
 99 files changed, 7034 insertions(+), 56 deletions(-)
 create mode 100644 gcc/kcfi.h
 create mode 100644 gcc/kcfi.cc
 create mode 100644 gcc/testsuite/gcc.dg/kcfi-compat/kcfi-compat.exp
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi.exp
 create mode 100644 gcc/testsuite/gcc.dg/builtin-typeinfo-bitint.c
 create mode 100644 gcc/testsuite/gcc.dg/builtin-typeinfo-c23.c
 create mode 100644 gcc/testsuite/gcc.dg/builtin-typeinfo-errors.c
 create mode 100644 gcc/testsuite/gcc.dg/builtin-typeinfo-fixed.c
 create mode 100644 gcc/testsuite/gcc.dg/builtin-typeinfo.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi-compat/kcfi-indirect-1.h
 create mode 100644 gcc/testsuite/gcc.dg/kcfi-compat/kcfi-indirect-1_main.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi-compat/kcfi-indirect-1_x.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi-compat/kcfi-indirect-1_y.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-branch-range.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-ilp32.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-insn-length-sls.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-insn-length.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-arm-fixed-ip.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-arm-fixed-r12.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-arm-sibcall-r3.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-asm-name.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-cold-partition.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-complex-addressing.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-direct-call-shapes.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-ipa-robustness.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-lto-offset.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-move-preservation.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize-inline.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-offset-validation.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-entry-only.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-incompatible.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-large.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-medium.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-prefix-only.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-qualified-params.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-riscv-32bit.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-riscv-fixed-t1.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-riscv-fixed-t2.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-riscv-fixed-t3.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-runtime.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-merge-run.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-merge.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-encoding.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section-per-func.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-32bit.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-arity.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-endbr-collision.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-fixed-r10.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-fixed-r11.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-retpoline-r11.c
 create mode 100644 gcc/testsuite/gcc.dg/pch/kcfi-1.c
 create mode 100644 gcc/testsuite/gcc.dg/pch/kcfi-1.hs
 create mode 100644 gcc/kcfi-typeinfo.h
 create mode 100644 gcc/kcfi-typeinfo.cc
Signature · 1 line
2.55.0
author
#1 lore raw

PATCH v17 1/7 kcfi: Introduce KCFI typeinfo mangling API

To support the KCFI typeid and future Linux type-based allocators, which need to convert unique types into unique 32-bit values, add a mangling system based on the Itanium C++ mangling ABI, adapted for C types. Introduce __builtin_linux_abi_kcfi_hash for the hash, and __builtin_linux_abi_kcfi_name for testing and debugging (to see the human-readable mangling form). Add tests for typeinfo validation and error handling.

This ABI needs to match what is used by LLVM Rust (which matches the Clang ABI) so that KCFI can work on mixed GCC with LLVM-Rust kernel builds. Instead of inventing a new ABI, all use the existing Itanium C++ mangling which matches KCFI's needs.

An important aspect of the C++ typeinfo behavior that is retained here is that typedefs are treated as pass-through except when the underlying type lacks a tag (i.e. anonymous struct, union, or enum). This provides a distinction between those typedefs and typedefs used to provide _aliases_ (u8, uint16_t). But regardless, this is distinct from strict ISO C type equivalency, so it remains a Linux KCFI ABI.

Assisted-by LLM [tests]

gcc/ChangeLog:

* Makefile.in: Add kcfi-typeinfo.o.
* doc/extend.texi: Document typeinfo builtins.
* kcfi-typeinfo.h: New file, typeinfo mangling API.
* kcfi-typeinfo.cc: New file, implement typeinfo mangling.
* selftest.h (kcfi_typeinfo_cc_tests): Declare.
* selftest-run-tests.cc (selftest::run_tests): Call kcfi_typeinfo_cc_tests.

gcc/c-family/ChangeLog:

* c-common.h (enum rid): Add typeinfo builtins.
* c-common.cc: Add typeinfo builtins.

gcc/c/ChangeLog:

* c-parser.cc (c_parser_get_builtin_type_arg): New function, parse type.
(c_parser_postfix_expression): Add typeinfo builtins.

gcc/testsuite/ChangeLog:

* gcc.dg/builtin-typeinfo.c: New test, typeinfo mangling.
* gcc.dg/builtin-typeinfo-bitint.c: New test, BitInt.
* gcc.dg/builtin-typeinfo-c23.c: New test, C23 types.
* gcc.dg/builtin-typeinfo-errors.c: New test, validate bad arguments are rejected.
* gcc.dg/builtin-typeinfo-fixed.c: New test, fixed point.

---
 gcc/doc/extend.texi                           |   99 ++
 .../gcc.dg/builtin-typeinfo-bitint.c          |   82 ++
 gcc/testsuite/gcc.dg/builtin-typeinfo-c23.c   |   72 ++
 .../gcc.dg/builtin-typeinfo-errors.c          |   28 +
 gcc/testsuite/gcc.dg/builtin-typeinfo-fixed.c |   58 +
 gcc/testsuite/gcc.dg/builtin-typeinfo.c       |  429 +++++++
 gcc/Makefile.in                               |    1 +
 gcc/c-family/c-common.h                       |    1 +
 gcc/kcfi-typeinfo.h                           |   31 +
 gcc/selftest.h                                |    1 +
 gcc/c-family/c-common.cc                      |    2 +
 gcc/c/c-parser.cc                             |   72 ++
 gcc/kcfi-typeinfo.cc                          | 1071 +++++++++++++++++
 gcc/selftest-run-tests.cc                     |    1 +
 14 files changed, 1948 insertions(+)
 create mode 100644 gcc/testsuite/gcc.dg/builtin-typeinfo-bitint.c
 create mode 100644 gcc/testsuite/gcc.dg/builtin-typeinfo-c23.c
 create mode 100644 gcc/testsuite/gcc.dg/builtin-typeinfo-errors.c
 create mode 100644 gcc/testsuite/gcc.dg/builtin-typeinfo-fixed.c
 create mode 100644 gcc/testsuite/gcc.dg/builtin-typeinfo.c
 create mode 100644 gcc/kcfi-typeinfo.h
 create mode 100644 gcc/kcfi-typeinfo.cc
gcc/doc/extend.texi +99 -0
index cc182b850140..6491de935eda 100644
@@ -18185,6 +18185,105 @@ which will cause a @code{NULL} pointer to be used for the unsafe case.
 
 @enddefbuiltin
 
+@defbuiltin{{unsigned int} __builtin_linux_abi_kcfi_hash (@var{type})}
+
+The built-in function @code{__builtin_linux_abi_kcfi_hash} returns a hash value
+for the given type @var{type} (which is a type, not an expression).
+The hash is computed using the FNV-1a algorithm on the type's mangled
+name representation, which follows a subset of the
+@uref{https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling,
+Itanium C++ ABI} conventions adapted for C types.  (See
+@code{__builtin_linux_abi_kcfi_name} for the string representation.)
+
+This built-in is primarily intended for kernel control flow integrity (KCFI)
+implementations and other type-aware runtime systems that need to generate
+consistent type identifiers.  The hash value is a 32-bit unsigned integer.
+
+Key characteristics of the hash:
+@itemize @bullet
+@item
+The hash is consistent for the same type across different translation units.
+@item
+Typedefs are recursively canonicalized down to integral type name or named
+struct, union, or enum tag name.
+@item
+Typedefs of anonymous structs, unions, and enums preserve the typedef name
+in the hash calculation (e.g., @code{typedef struct @{ int x; @} foo_t;}
+uses @code{foo_t} in the hash).
+@item
+Type qualifiers (@code{const}, @code{volatile}, @code{restrict}) affect
+the hash value.
+@item
+Function types include parameter types and variadic markers in the hash.
+@end itemize
+
+For example:
+@smallexample
+typedef struct @{ int x; @} mytype_t;
+unsigned int hash1 = __builtin_linux_abi_kcfi_hash (mytype_t);
+unsigned int hash2 = __builtin_linux_abi_kcfi_hash (struct @{ int x; @});
+/* hash1 != hash2 because the typedef name is preserved */
+
+void func(int x, char y);
+unsigned int hash3 = __builtin_linux_abi_kcfi_hash (typeof (func));
+/* Returns hash for function type "void(int, char)" */
+@end smallexample
+
+@emph{Note:} This construct is only available for C and Objective-C@.
+For C++, see @code{std::type_info::hash_code}.
+
+@enddefbuiltin
+
+@defbuiltin{{const char *} __builtin_linux_abi_kcfi_name (@var{type})}
+
+The built-in function @code{__builtin_linux_abi_kcfi_name} returns a string
+containing the mangled name representation of the given type @var{type}
+(which is a type, not an expression).  The string follows a subset of the
+@uref{https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling,
+Itanium C++ ABI} mangling conventions adapted for C types.  (See
+@code{__builtin_linux_abi_kcfi_hash} for the unsigned 32-bit hash
+representation.)
+
+The returned string is a compile-time constant suitable for use in
+string comparisons, debugging output, or other type introspection needs.
+The string begins with @code{_ZTS} followed by the encoded type information.
+
+Mangling examples:
+@itemize @bullet
+@item
+@code{int} becomes @code{"_ZTSi"}
+@item
+@code{char *} becomes @code{"_ZTSPc"}
+@item
+@code{const int} becomes @code{"_ZTSKi"}
+@item
+@code{int[10]} becomes @code{"_ZTSA10_i"}
+@item
+@code{void (*)(int)} becomes @code{"_ZTSPFviE"}
+@item
+@code{struct foo} becomes @code{"_ZTS3foo"}
+@item
+@code{typedef struct @{ int x; @} bar_t;} becomes @code{"_ZTS5bar_t"}
+@end itemize
+
+The mangling preserves typedef names for anonymous compound types, which
+is particularly useful for distinguishing between different typedefs of
+structurally identical anonymous types:
+
+@smallexample
+typedef struct @{ int x; @} type_a;
+typedef struct @{ int x; @} type_b;
+/* name_a is "_ZTS6type_a", name_b is "_ZTS6type_b": different despite
+   identical structure.  */
+const char *name_a = __builtin_linux_abi_kcfi_name (type_a);
+const char *name_b = __builtin_linux_abi_kcfi_name (type_b);
+@end smallexample
+
+@emph{Note:} This construct is only available for C and Objective-C@.
+For C++, see @code{std::type_info::name}.
+
+@enddefbuiltin
+
 @defbuiltin{int __builtin_types_compatible_p (@var{type1}, @var{type2})}
 
 You can use the built-in function @code{__builtin_types_compatible_p} to
gcc/testsuite/gcc.dg/builtin-typeinfo-bitint.c new file +82 -0

82 lines not on this page · raw message

gcc/testsuite/gcc.dg/builtin-typeinfo-c23.c new file +72 -0

72 lines not on this page · raw message

gcc/testsuite/gcc.dg/builtin-typeinfo-errors.c new file +28 -0
new file mode 100644
index 000000000000..5d68425c229c
@@ -0,0 +1,28 @@
+/* Test error handling for __builtin_linux_abi_kcfi_name and __builtin_linux_abi_kcfi_hash.  */
+/* { dg-do compile } */
+
+int main() {
+    /* Test missing arguments */
+    const char *result1 = __builtin_linux_abi_kcfi_name(); /* { dg-error "expected specifier-qualifier-list before '\\)'" } */
+    /* { dg-error "expected type name in '__builtin_linux_abi_kcfi_name'" "" { target *-*-* } .-1 } */
+    unsigned int result2 = __builtin_linux_abi_kcfi_hash(); /* { dg-error "expected specifier-qualifier-list before '\\)'" } */
+    /* { dg-error "expected type name in '__builtin_linux_abi_kcfi_hash'" "" { target *-*-* } .-1 } */
+
+    /* Test wrong argument types (expressions instead of type names) */
+    const char *result3 = __builtin_linux_abi_kcfi_name(42); /* { dg-error "expected specifier-qualifier-list before numeric constant" } */
+    /* { dg-error "expected type name in '__builtin_linux_abi_kcfi_name'" "" { target *-*-* } .-1 } */
+    unsigned int result4 = __builtin_linux_abi_kcfi_hash(42); /* { dg-error "expected specifier-qualifier-list before numeric constant" } */
+    /* { dg-error "expected type name in '__builtin_linux_abi_kcfi_hash'" "" { target *-*-* } .-1 } */
+
+    int x = 5;
+    const char *result5 = __builtin_linux_abi_kcfi_name(x); /* { dg-error "expected specifier-qualifier-list before" } */
+    /* { dg-error "expected type name in '__builtin_linux_abi_kcfi_name'" "" { target *-*-* } .-1 } */
+    unsigned int result6 = __builtin_linux_abi_kcfi_hash(x); /* { dg-error "expected specifier-qualifier-list before" } */
+    /* { dg-error "expected type name in '__builtin_linux_abi_kcfi_hash'" "" { target *-*-* } .-1 } */
+
+    /* Test too many arguments */
+    const char *result7 = __builtin_linux_abi_kcfi_name(int, int); /* { dg-error "expected '\\)' before ','" } */
+    unsigned int result8 = __builtin_linux_abi_kcfi_hash(int, int); /* { dg-error "expected '\\)' before ','" } */
+
+    return 0;
+}
gcc/testsuite/gcc.dg/builtin-typeinfo-fixed.c new file +58 -0

58 lines not on this page · raw message

gcc/testsuite/gcc.dg/builtin-typeinfo.c new file +429 -0

429 lines not on this page · raw message

gcc/Makefile.in +1 -0
index 83cb4884eb13..2560addbcf64 100644
@@ -1624,6 +1624,7 @@ OBJS = \
 	ira-emit.o \
 	ira-lives.o \
 	jump.o \
+	kcfi-typeinfo.o \
 	langhooks.o \
 	late-combine.o \
 	lcm.o \
gcc/c-family/c-common.h +1 -0
index 197db508c163..7dbc1b16057f 100644
@@ -113,6 +113,7 @@ enum rid
   RID_BUILTIN_HAS_ATTRIBUTE,   RID_BUILTIN_ASSOC_BARRIER,  RID_BUILTIN_STDC,
   RID_BUILTIN_COUNTED_BY_REF,  RID_BUILTIN_BSWAPG,
   RID_BUILTIN_BITREVERSEG,
+  RID_BUILTIN_LINUX_ABI_KCFI_NAME,  RID_BUILTIN_LINUX_ABI_KCFI_HASH,
   RID_DFLOAT32, RID_DFLOAT64, RID_DFLOAT128, RID_DFLOAT64X,
 
   /* TS 18661-3 keywords, in the same sequence as the TI_* values.  */
gcc/kcfi-typeinfo.h new file +31 -0
new file mode 100644
index 000000000000..092a682276af
@@ -0,0 +1,31 @@
+/* KCFI-compatible type mangling, based on Itanium C++ ABI.
+   Copyright (C) 2026 Free Software Foundation, Inc.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3.  If not see
+<http://www.gnu.org/licenses/>.  */
+
+#ifndef GCC_KCFI_TYPEINFO_H
+#define GCC_KCFI_TYPEINFO_H
+
+#include "tree.h"
+
+/* Get the typeinfo mangled name string for any C type.  */
+extern std::string kcfi_typeinfo_get_name (tree type);
+
+/* Get the typeinfo hash for any C type.  */
+extern uint32_t kcfi_typeinfo_get_hash (tree type);
+
+#endif /* GCC_KCFI_TYPEINFO_H */
gcc/selftest.h +1 -0
index acfc4a46e49b..a17a6fe1b789 100644
@@ -240,6 +240,7 @@ extern void ipa_modref_tree_cc_tests ();
 extern void json_cc_tests ();
 extern void json_parser_cc_tests ();
 extern void json_pointer_parsing_cc_tests ();
+extern void kcfi_typeinfo_cc_tests ();
 extern void opt_suggestions_cc_tests ();
 extern void optinfo_emit_json_cc_tests ();
 extern void opts_cc_tests ();
gcc/c-family/c-common.cc +2 -0
index 6380bec4515d..4836b60811d2 100644
@@ -466,6 +466,8 @@ const struct c_common_resword c_common_reswords[] =
   { "__builtin_stdc_trailing_zeros", RID_BUILTIN_STDC, D_CONLY },
   { "__builtin_tgmath", RID_BUILTIN_TGMATH, D_CONLY },
   { "__builtin_offsetof", RID_OFFSETOF, 0 },
+  { "__builtin_linux_abi_kcfi_hash", RID_BUILTIN_LINUX_ABI_KCFI_HASH, D_CONLY },
+  { "__builtin_linux_abi_kcfi_name", RID_BUILTIN_LINUX_ABI_KCFI_NAME, D_CONLY },
   { "__builtin_types_compatible_p", RID_TYPES_COMPATIBLE_P, D_CONLY },
   { "__builtin_c23_va_start", RID_C23_VA_START,	D_C23 | D_CXX26 },
   { "__builtin_va_arg",	RID_VA_ARG,	0 },
gcc/c/c-parser.cc +72 -0

90 lines not on this page · raw message

gcc/kcfi-typeinfo.cc new file +1071 -0

1,071 lines not on this page · raw message

gcc/selftest-run-tests.cc +1 -0
index 07eb984e918e..c2b85493327b 100644
@@ -92,6 +92,7 @@ selftest::run_tests ()
   input_cc_tests ();
   vec_perm_indices_cc_tests ();
   tree_cc_tests ();
+  kcfi_typeinfo_cc_tests ();
   convert_cc_tests ();
   gimple_cc_tests ();
   rtl_tests_cc_tests ();
Signature · 1 line
2.55.0
author
#2 lore raw

PATCH v17 2/7 kcfi: Add core Kernel Control Flow Integrity infrastructure

In reply to Kees Cook

Implements the Linux Kernel Control Flow Integrity ABI, which provides a function prototype based forward edge control flow integrity protection by instrumenting every indirect call to check for a hash value before the target function address. If the hash at the call site and the hash at the target do not match, execution will trap.

See the start of kcfi.cc for design details.

gcc/ChangeLog:

* kcfi.h: New file with KCFI public interface declarations.
* kcfi.cc: New file implementing Kernel Control Flow Integrity infrastructure.
* Makefile.in (OBJS): Add kcfi.o.
* flag-types.h (enum sanitize_code): Add SANITIZE_KCFI.
* gimple.h (enum gf_mask): Add GF_CALL_INLINED_FROM_KCFI_NOSANTIZE. (gimple_call_set_inlined_from_kcfi_nosantize): New function. (gimple_call_inlined_from_kcfi_nosantize_p): New function.
* df-scan.cc (df_uses_record): Add KCFI case to handle KCFI RTL patterns and process wrapped RTL.
* doc/extend.texi: Update nocf_check for kcfi.
* doc/invoke.texi (fsanitize=kcfi): Add documentation for KCFI sanitizer option.
* doc/tm.texi.in: Add Kernel Control Flow Integrity section with TARGET_KCFI_SUPPORTED, TARGET_KCFI_MASK_TYPE_ID, TARGET_KCFI_EMIT_TYPE_ID hooks.
* doc/tm.texi: Regenerate.
* final.cc (call_from_call_insn): Add KCFI case to handle KCFI-wrapped calls. Add kcfi_next_labelno().
* opts.cc (sanitizer_opts): Add kcfi entry. (parse_sanitizer_options): Exclude SANITIZE_KCFI from -fsanitize-recover=all.
* rtl.def (KCFI): Add new RTL code for KCFI instrumentation.
* rtlanal.cc (reg_referenced_p): Add KCFI case.
* target.def: Add KCFI target hooks.
* toplev.cc (process_options): Add KCFI option processing.
* tree-inline.cc (copy_bb): Handle KCFI no_sanitize attribute propagation during inlining.
* tree-ssa-tail-merge.cc: Include kcfi.h. (gimple_equal_p): Don't treat calls that get different KCFI checks as equal.
* varasm.cc (assemble_start_function): Emit KCFI preambles. (assemble_external_real): Emit KCFI typeid symbols. (default_elf_asm_named_section): Handle .kcfi_traps using SECTION_LINK_ORDER flag.

gcc/c-family/ChangeLog:

* c-attribs.cc: Include asan.h. (handle_nocf_check_attribute): Enable nocf_check under kcfi. (handle_patchable_function_entry_attribute): Add error for using patchable_function_entry attribute with -fsanitize=kcfi.

---
 gcc/kcfi.h                 |  71 ++++
 gcc/kcfi.cc                | 650 +++++++++++++++++++++++++++++++++++++
 gcc/doc/extend.texi        |  42 +++
 gcc/doc/invoke.texi        |  39 +++
 gcc/doc/tm.texi            |  32 ++
 gcc/Makefile.in            |   2 +
 gcc/flag-types.h           |   2 +
 gcc/gimple.h               |  22 ++
 gcc/c-family/c-attribs.cc  |  17 +-
 gcc/df-scan.cc             |   7 +
 gcc/doc/tm.texi.in         |  12 +
 gcc/final.cc               |  17 +
 gcc/opts.cc                |   4 +-
 gcc/rtl.def                |   6 +
 gcc/rtlanal.cc             |   5 +
 gcc/target.def             |  39 +++
 gcc/toplev.cc              |  12 +
 gcc/tree-inline.cc         |  10 +
 gcc/tree-ssa-tail-merge.cc |   6 +
 gcc/varasm.cc              |  44 ++-
 20 files changed, 1027 insertions(+), 12 deletions(-)
 create mode 100644 gcc/kcfi.h
 create mode 100644 gcc/kcfi.cc
gcc/kcfi.h new file +71 -0
new file mode 100644
index 000000000000..ab6abb4adfa8
@@ -0,0 +1,71 @@
+/* Kernel Control Flow Integrity (KCFI) support for GCC.
+   Copyright (C) 2026 Free Software Foundation, Inc.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3.  If not see
+<http://www.gnu.org/licenses/>.  */
+
+#ifndef GCC_KCFI_H
+#define GCC_KCFI_H
+
+#include "coretypes.h"
+#include "rtl.h"
+
+/* Common helper for RTL patterns to emit .kcfi_traps section entry.
+   Call after emitting trap label and instruction with the trap symbol
+   reference.  */
+extern void kcfi_emit_traps_section (FILE *file, rtx trap_label_sym,
+				      int labelno);
+
+/* Extract KCFI type ID from current GIMPLE statement.  */
+extern rtx internal_kcfi_get_type_id_for_expanding_gimple_call (void);
+
+/* Convenience wrapper to check for SANITIZE_KCFI.  */
+inline rtx
+kcfi_get_type_id_for_expanding_gimple_call (void)
+{
+  if (!(flag_sanitize & SANITIZE_KCFI))
+    return NULL_RTX;
+  return internal_kcfi_get_type_id_for_expanding_gimple_call ();
+}
+
+/* Compare the KCFI checks two call statements get.  */
+extern bool internal_kcfi_same_call_check_p (const gcall *, const gcall *);
+
+/* Return true if calls CALL1 and CALL2 get the same KCFI check (or none).  */
+inline bool
+kcfi_same_call_check_p (const gcall *call1, const gcall *call2)
+{
+  if (!(flag_sanitize & SANITIZE_KCFI))
+    return true;
+  return internal_kcfi_same_call_check_p (call1, call2);
+}
+
+/* Emit KCFI type ID symbol for external address-taken functions.  */
+extern void kcfi_emit_typeid_symbol (FILE *asm_file, tree fndecl);
+
+/* Emit KCFI preamble for potential indirect call targets.  */
+extern void kcfi_emit_preamble (FILE *asm_file, tree fndecl,
+				const char *actual_fname);
+
+/* Get next KCFI label number for trap/call/entry label numbering.  This
+   output-phase counter lives with the other unique-label counters in
+   final.cc.  */
+extern int kcfi_next_labelno (void);
+
+/* Get the KCFI typeid offset for calculating callsite typeid offset.  */
+extern HOST_WIDE_INT kcfi_get_typeid_offset (void);
+
+#endif /* GCC_KCFI_H */
gcc/kcfi.cc new file +650 -0

650 lines not on this page · raw message

gcc/doc/extend.texi +42 -0

54 lines not on this page · raw message

gcc/doc/invoke.texi +39 -0
index f89b984fd25f..f8a325b5153a 100644
@@ -17531,6 +17531,45 @@ the available options are shown at startup of the instrumented program.
 The option cannot be combined with @option{-fsanitize=thread} or
 @option{-fsanitize=address}, and is currently only available on AArch64.
 
+@opindex fsanitize=kcfi
+@item -fsanitize=kcfi
+Enable Kernel Control Flow Integrity (KCFI), a lightweight control
+flow integrity mechanism designed for operating system kernels.
+KCFI instruments indirect function calls to verify that the target
+function has the expected type signature at runtime.  Each function
+receives a unique type identifier computed from a hash of its function
+prototype (including parameter types and return type).  Before each
+indirect call, the implementation inserts a check to verify that the
+target function's type identifier matches the expected identifier
+for the call site, issuing a trap instruction if a mismatch is detected.
+This provides forward-edge control flow protection against attacks that
+attempt to redirect indirect calls to unintended targets.
+
+The implementation adds minimal runtime overhead and does not require
+runtime library support, making it suitable for kernel environments.
+The type identifier is placed before the function entry point,
+allowing runtime verification without additional metadata structures,
+and without changing the entry points of the target functions.
+
+KCFI is intended primarily for kernel code and may not be suitable
+for user-space applications that rely on techniques incompatible
+with strict type checking of indirect calls.
+
+Note that KCFI is incompatible with function-specific
+@code{patchable_function_entry} attributes because KCFI call sites
+cannot know about function-specific patchable entry settings in different
+translation units.  Only the global @option{-fpatchable-function-entry}
+command-line option is supported with KCFI.
+
+For the same reason, the location of the type identifier relative to a
+function entry point is part of a whole-program ABI: a call site computes
+that offset from its own translation unit's settings, so every translation
+unit that may be reached through an instrumented indirect call must agree on
+it.
+
+Use @option{-fdump-ipa-kcfi-details} to examine the computed type identifier
+hashes and their corresponding mangled type strings during compilation.
+
 @opindex fsanitize=kernel-hwaddress
 @item -fsanitize=kernel-hwaddress
 Enable Hardware-assisted AddressSanitizer for compilation of the Linux kernel.
gcc/doc/tm.texi +32 -0
index 97afd0175220..8bea8b01e401 100644
@@ -3221,6 +3221,7 @@ This describes the stack layout and calling conventions.
 * Tail Calls::
 * Shrink-wrapping separate components::
 * Stack Smashing Protection::
+* Kernel Control Flow Integrity::
 * Miscellaneous Register Hooks::
 @end menu
 
@@ -5498,6 +5499,37 @@ should be allocated from heap memory and consumers should release them.
 The result will be pruned to cases with PREFIX if not NULL.
 @end deftypefn
 
+@node Kernel Control Flow Integrity
+@subsection Kernel Control Flow Integrity
+@cindex kernel control flow integrity
+@cindex KCFI
+
+@deftypefn {Target Hook} bool TARGET_KCFI_SUPPORTED (void)
+Return true if the target supports Kernel Control Flow Integrity (KCFI).
+This hook indicates whether the target has implemented the necessary RTL
+patterns and infrastructure to support KCFI instrumentation.  The default
+implementation returns false.
+@end deftypefn
+
+@deftypefn {Target Hook} uint32_t TARGET_KCFI_MASK_TYPE_ID (uint32_t @var{type_id})
+Apply architecture-specific masking to KCFI type ID.  This hook allows
+targets to apply bit masks or other transformations to the computed KCFI
+type identifier to match the target's specific requirements.  The default
+implementation returns the type ID unchanged.
+@end deftypefn
+
+@deftypefn {Target Hook} int TARGET_KCFI_EMIT_TYPE_ID (FILE *@var{file}, uint32_t @var{type_id}, tree @var{fndecl})
+Emit architecture-specific type ID instruction for KCFI preambles
+and return the size of the instruction in bytes.
+@var{file} is the assembly output stream and @var{type_id} is the KCFI
+type identifier to emit.  If @var{file} is NULL, skip emission and only
+return the size.  If not overridden, the default fallback emits a
+@code{.word} directive with the type ID and returns 4 bytes.  Targets can
+override this to emit different instruction sequences and return their
+corresponding sizes.  @var{fndecl} is the function declaration, which
+targets can use to compute architecture-specific arity or other properties.
+@end deftypefn
+
 @node Miscellaneous Register Hooks
 @subsection Miscellaneous register hooks
 @cindex miscellaneous register hooks
gcc/Makefile.in +2 -0
index 2560addbcf64..63a47c30aac5 100644
@@ -1625,6 +1625,7 @@ OBJS = \
 	ira-lives.o \
 	jump.o \
 	kcfi-typeinfo.o \
+	kcfi.o \
 	langhooks.o \
 	late-combine.o \
 	lcm.o \
@@ -3186,6 +3187,7 @@ GTFILES = $(CPPLIB_H) $(srcdir)/input.h $(srcdir)/coretypes.h \
   $(srcdir)/tsan.cc \
   $(srcdir)/sanopt.cc \
   $(srcdir)/sancov.cc \
+  $(srcdir)/kcfi.cc \
   $(srcdir)/ipa-devirt.cc \
   $(srcdir)/ipa-strub.cc \
   $(srcdir)/internal-fn.h \
gcc/flag-types.h +2 -0
index c4eb8a0520a7..d35507ece51f 100644
@@ -342,6 +342,8 @@ enum sanitize_code {
   SANITIZE_MEMTAG_STACK = 1ULL << 32,
   /* Memory Tagging.  */
   SANITIZE_MEMTAG = SANITIZE_MEMTAG_STACK,
+  /* KCFI (Kernel Control Flow Integrity) */
+  SANITIZE_KCFI = 1ULL << 33,
   SANITIZE_SHIFT = SANITIZE_SHIFT_BASE | SANITIZE_SHIFT_EXPONENT,
   SANITIZE_UNDEFINED = SANITIZE_SHIFT | SANITIZE_DIVIDE | SANITIZE_UNREACHABLE
 		       | SANITIZE_VLA | SANITIZE_NULL | SANITIZE_RETURN
gcc/gimple.h +22 -0
index 82045c44bbeb..a61de841fd11 100644
@@ -145,6 +145,7 @@ enum gf_mask {
     GF_CALL_ALLOCA_FOR_VAR	= 1 << 5,
     GF_CALL_INTERNAL		= 1 << 6,
     GF_CALL_CTRL_ALTERING       = 1 << 7,
+    GF_CALL_INLINED_FROM_KCFI_NOSANTIZE = 1 << 8,
     GF_CALL_MUST_TAIL_CALL	= 1 << 9,
     GF_CALL_BY_DESCRIPTOR	= 1 << 10,
     GF_CALL_NOCF_CHECK		= 1 << 11,
@@ -3499,6 +3500,27 @@ gimple_call_from_thunk_p (gcall *s)
   return (s->subcode & GF_CALL_FROM_THUNK) != 0;
 }
 
+/* If INLINED_FROM_KCFI_NOSANTIZE_P is true, mark GIMPLE_CALL S as being
+   inlined from a function with no_sanitize("kcfi").  */
+
+inline void
+gimple_call_set_inlined_from_kcfi_nosantize (gcall *s,
+					     bool inlined_from_kcfi_nosantize_p)
+{
+  if (inlined_from_kcfi_nosantize_p)
+    s->subcode |= GF_CALL_INLINED_FROM_KCFI_NOSANTIZE;
+  else
+    s->subcode &= ~GF_CALL_INLINED_FROM_KCFI_NOSANTIZE;
+}
+
+/* Return true if GIMPLE_CALL S was inlined from a function with
+   no_sanitize("kcfi").  */
+
+inline bool
+gimple_call_inlined_from_kcfi_nosantize_p (const gcall *s)
+{
+  return (s->subcode & GF_CALL_INLINED_FROM_KCFI_NOSANTIZE) != 0;
+}
 
 /* If FROM_NEW_OR_DELETE_P is true, mark GIMPLE_CALL S as being a call
    to operator new or delete created from a new or delete expression.  */
gcc/c-family/c-attribs.cc +16 -1
index 470054f044ac..eb4c8b1a002f 100644
@@ -49,6 +49,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "gimplify.h"
 #include "tree-pretty-print.h"
 #include "gcc-rich-location.h"
+#include "asan.h"
 #include "gcc-urlifier.h"
 #include "attr-callback.h"
 
@@ -1536,8 +1537,11 @@ handle_nocf_check_attribute (tree *node, tree name,
       warning (OPT_Wattributes, "%qE attribute ignored", name);
       *no_add_attrs = true;
     }
-  else if (!(flag_cf_protection & CF_BRANCH))
+  else if (!(flag_cf_protection & CF_BRANCH)
+	   && !(flag_sanitize & SANITIZE_KCFI))
     {
+      /* Allow it with -fsanitize=kcfi, but leave this warning alone
+	 to avoid confusion over this weird corner case.  */
       warning (OPT_Wattributes, "%qE attribute ignored. Use "
 				"%<-fcf-protection%> option to enable it",
 				name);
@@ -6014,6 +6018,17 @@ static tree
 handle_patchable_function_entry_attribute (tree *, tree name, tree args,
 					   int, bool *no_add_attrs)
 {
+  /* Function-specific patchable_function_entry attribute is incompatible
+     with KCFI because KCFI callsites cannot know about function-specific
+     patchable entry settings on a preamble in a different translation
+     unit.  */
+  if (sanitize_flags_p (SANITIZE_KCFI))
+    {
+      error ("%qE attribute cannot be used with %<-fsanitize=kcfi%>", name);
+      *no_add_attrs = true;
+      return NULL_TREE;
+    }
+
   for (; args; args = TREE_CHAIN (args))
     {
       tree val = TREE_VALUE (args);
gcc/df-scan.cc +7 -0
index c6a5053ddbb6..e7ac751ca78f 100644
@@ -2851,6 +2851,13 @@ df_uses_record (class df_collection_rec *collection_rec,
       /* If we're clobbering a REG then we have a def so ignore.  */
       return;
 
+    case KCFI:
+      /* KCFI wraps other RTL - process the wrapped RTL.  */
+      df_uses_record (collection_rec, &XEXP (x, 0), ref_type, bb, insn_info,
+		      flags);
+      /* The type ID operand (XEXP (x, 1)) doesn't contain register uses.  */
+      return;
+
     case MEM:
       df_uses_record (collection_rec,
 		      &XEXP (x, 0), DF_REF_REG_MEM_LOAD,
gcc/doc/tm.texi.in +12 -0
index 2113b9c679a3..aca8e292a6c5 100644
@@ -2462,6 +2462,7 @@ This describes the stack layout and calling conventions.
 * Tail Calls::
 * Shrink-wrapping separate components::
 * Stack Smashing Protection::
+* Kernel Control Flow Integrity::
 * Miscellaneous Register Hooks::
 @end menu
 
@@ -3841,6 +3842,17 @@ generic code.
 
 @hook TARGET_GET_VALID_OPTION_VALUES
 
+@node Kernel Control Flow Integrity
+@subsection Kernel Control Flow Integrity
+@cindex kernel control flow integrity
+@cindex KCFI
+
+@hook TARGET_KCFI_SUPPORTED
+
+@hook TARGET_KCFI_MASK_TYPE_ID
+
+@hook TARGET_KCFI_EMIT_TYPE_ID
+
 @node Miscellaneous Register Hooks
 @subsection Miscellaneous register hooks
 @cindex miscellaneous register hooks
gcc/final.cc +17 -0
index b6be9be99b7f..b0330df035ec 100644
@@ -78,6 +78,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "stringpool.h"
 #include "attribs.h"
 #include "asan.h"
+#include "kcfi.h"
 #include "rtl-iter.h"
 #include "print-rtl.h"
 #include "function-abi.h"
@@ -155,6 +156,19 @@ static rtx last_ignored_compare = 0;
 
 static int insn_counter = 0;
 
+/* KCFI label counter, incremented during KCFI insn output to give each
+   indirect call site's trap/call/entry labels a unique number.  Kept here
+   with the other output-phase label counters; declared in kcfi.h for its
+   architecture back-end callers.  */
+
+static int kcfi_labelno = 0;
+
+int
+kcfi_next_labelno (void)
+{
+  return kcfi_labelno++;
+}
+
 /* Number of unmatched NOTE_INSN_BLOCK_BEG notes we have seen.  */
 
 static int block_depth;
@@ -2088,6 +2102,9 @@ call_from_call_insn (const rtx_call_insn *insn)
 	case SET:
 	  x = XEXP (x, 1);
 	  break;
+	case KCFI:
+	  x = XEXP (x, 0);
+	  break;
 	}
     }
   return x;
gcc/opts.cc +3 -1
index 21a773f8da75..ad1fd54d2792 100644
@@ -2227,6 +2227,7 @@ const struct sanitizer_opts_s sanitizer_opts[] =
   SANITIZER_OPT (builtin, SANITIZE_BUILTIN, true, true),
   SANITIZER_OPT (shadow-call-stack, SANITIZE_SHADOW_CALL_STACK, false, false),
   SANITIZER_OPT (memtag-stack, SANITIZE_MEMTAG_STACK, false, false),
+  SANITIZER_OPT (kcfi, SANITIZE_KCFI, false, true),
   SANITIZER_OPT (all, ~sanitize_code_type (0), true, true),
 #undef SANITIZER_OPT
   { NULL, sanitize_code_type (0), 0UL, false, false }
@@ -2366,7 +2367,8 @@ parse_sanitizer_options (const char *p, location_t loc, int scode,
 		  flags |= ~(SANITIZE_THREAD | SANITIZE_LEAK
 			     | SANITIZE_UNREACHABLE | SANITIZE_RETURN
 			     | SANITIZE_SHADOW_CALL_STACK
-			     | SANITIZE_MEMTAG_STACK);
+			     | SANITIZE_MEMTAG_STACK
+			     | SANITIZE_KCFI);
 		else /* if (code == OPT_fsanitize_trap_) */
 		  flags |= (SANITIZE_UNDEFINED
 			    | SANITIZE_UNDEFINED_NONDEFAULT);
gcc/rtl.def +6 -0
index cec11d832078..e01c756b562f 100644
@@ -318,6 +318,12 @@ DEF_RTL_EXPR(CLOBBER, "clobber", "e", RTX_EXTRA)
 
 DEF_RTL_EXPR(CALL, "call", "ee", RTX_EXTRA)
 
+/* KCFI wrapper for call expressions.
+   Operand 0 is the call expression.
+   Operand 1 is the KCFI type ID (const_int).  */
+
+DEF_RTL_EXPR(KCFI, "kcfi", "ee", RTX_EXTRA)
+
 /* Return from a subroutine.  */
 
 DEF_RTL_EXPR(RETURN, "return", "", RTX_EXTRA)
gcc/rtlanal.cc +5 -0
index df4a69d180ae..251f2413df59 100644
@@ -1177,6 +1177,11 @@ reg_referenced_p (const_rtx x, const_rtx body)
     case IF_THEN_ELSE:
       return reg_overlap_mentioned_p (x, body);
 
+    case KCFI:
+      /* For KCFI wrapper, only check the wrapped call.  The type ID
+	 (XEXP (body, 1)) is always a const_int.  */
+      return reg_overlap_mentioned_p (x, XEXP (body, 0));
+
     case TRAP_IF:
       return reg_overlap_mentioned_p (x, TRAP_CONDITION (body));
 
gcc/target.def +39 -0
index 11334f9d443d..30862fa649bd 100644
@@ -7737,6 +7737,45 @@ DEFHOOKPOD
 The default value is NULL.",
  const char *, NULL)
 
+/* Kernel Control Flow Integrity (KCFI) hooks.  */
+#undef HOOK_PREFIX
+#define HOOK_PREFIX "TARGET_KCFI_"
+HOOK_VECTOR (TARGET_KCFI, kcfi)
+
+DEFHOOK
+(supported,
+ "Return true if the target supports Kernel Control Flow Integrity (KCFI).\n\
+This hook indicates whether the target has implemented the necessary RTL\n\
+patterns and infrastructure to support KCFI instrumentation.  The default\n\
+implementation returns false.",
+ bool, (void),
+ hook_bool_void_false)
+
+DEFHOOK
+(mask_type_id,
+ "Apply architecture-specific masking to KCFI type ID.  This hook allows\n\
+targets to apply bit masks or other transformations to the computed KCFI\n\
+type identifier to match the target's specific requirements.  The default\n\
+implementation returns the type ID unchanged.",
+ uint32_t, (uint32_t type_id),
+ NULL)
+
+DEFHOOK
+(emit_type_id,
+ "Emit architecture-specific type ID instruction for KCFI preambles\n\
+and return the size of the instruction in bytes.\n\
+@var{file} is the assembly output stream and @var{type_id} is the KCFI\n\
+type identifier to emit.  If @var{file} is NULL, skip emission and only\n\
+return the size.  If not overridden, the default fallback emits a\n\
+@code{.word} directive with the type ID and returns 4 bytes.  Targets can\n\
+override this to emit different instruction sequences and return their\n\
+corresponding sizes.  @var{fndecl} is the function declaration, which\n\
+targets can use to compute architecture-specific arity or other properties.",
+ int, (FILE *file, uint32_t type_id, tree fndecl),
+ NULL)
+
+HOOK_VECTOR_END (kcfi)
+
 /* Close the 'struct gcc_target' definition.  */
 HOOK_VECTOR_END (C90_EMPTY_HACK)
 
gcc/toplev.cc +12 -0
index 30f5a3d00639..55ae40e9589a 100644
@@ -68,6 +68,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "attribs.h"
 #include "asan.h"
 #include "tsan.h"
+#include "kcfi.h"
 #include "plugin.h"
 #include "context.h"
 #include "pass_manager.h"
@@ -1745,6 +1746,17 @@ process_options ()
 		  "requires %<-fno-exceptions%>");
     }
 
+  if (flag_sanitize & SANITIZE_KCFI)
+    {
+      if (!targetm.kcfi.supported ())
+	sorry ("%<-fsanitize=kcfi%> not supported by this target");
+
+      /* Compiling with -flto results in frontend language of GNU GIMPLE.
+	 Allow it since the original source was C.  */
+      if (!lang_GNU_C () && !startswith (lang_hooks.name, "GNU GIMPLE"))
+	sorry ("%<-fsanitize=kcfi%> is only supported for C");
+    }
+
   HOST_WIDE_INT patch_area_size, patch_area_start;
   parse_and_check_patch_area (flag_patchable_function_entry, false,
 			      &patch_area_size, &patch_area_start);
gcc/tree-inline.cc +10 -0
index 8162b1f5051a..b451bcfdef61 100644
@@ -2110,6 +2110,16 @@ copy_bb (copy_body_data *id, basic_block bb,
 	  /* Advance iterator now before stmt is moved to seq_gsi.  */
 	  gsi_next (&stmts_gsi);
 
+	  /* If inlining from a function with no_sanitize("kcfi"), mark any
+	     call statements in the inlined body with the flag so they skip
+	     KCFI instrumentation.  */
+	  if (is_gimple_call (stmt)
+	      && !sanitize_flags_p (SANITIZE_KCFI, id->src_fn))
+	    {
+	      gcall *call = as_a <gcall *> (stmt);
+	      gimple_call_set_inlined_from_kcfi_nosantize (call, true);
+	    }
+
 	  if (gimple_nop_p (stmt))
 	      continue;
 
gcc/tree-ssa-tail-merge.cc +6 -0
index 6d81a7118b32..453cca46befd 100644
@@ -208,6 +208,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "tree-cfgcleanup.h"
 #include "tree-ssa.h"
 #include "gimple-match.h"
+#include "kcfi.h"
 
 const int ignore_edge_flags = EDGE_DFS_BACK | EDGE_EXECUTABLE;
 
@@ -1148,6 +1149,11 @@ gimple_equal_p (same_succ *same_succ, gimple *s1, gimple *s2)
       if (!gimple_call_same_target_p (s1, s2))
 	return false;
 
+      /* Calls through the same pointer value (e.g. via union members) can
+	 still get different KCFI checks.  */
+      if (!kcfi_same_call_check_p (as_a <gcall *> (s1), as_a <gcall *> (s2)))
+	return false;
+
       t1 = gimple_call_chain (s1);
       t2 = gimple_call_chain (s2);
       if (!gimple_operand_equal_value_p (t1, t2))
gcc/varasm.cc +34 -10

68 lines not on this page · raw message

Signature · 1 line
2.55.0
#3 lore raw

Re: [PATCH v17 2/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 59 lines · Kees Cook

Implements the Linux Kernel Control Flow Integrity ABI, which provides a function prototype based forward edge control flow integrity protection by instrumenting every indirect call to check for a hash value before the target function address. If the hash at the call site and the hash at the target do not match, execution will trap.

See the start of kcfi.cc for design details.

gcc/ChangeLog:

* kcfi.h: New file with KCFI public interface declarations.
* kcfi.cc: New file implementing Kernel Control Flow Integrity infrastructure.
* Makefile.in (OBJS): Add kcfi.o.
* flag-types.h (enum sanitize_code): Add SANITIZE_KCFI.
* gimple.h (enum gf_mask): Add GF_CALL_INLINED_FROM_KCFI_NOSANTIZE. (gimple_call_set_inlined_from_kcfi_nosantize): New function. (gimple_call_inlined_from_kcfi_nosantize_p): New function.
* df-scan.cc (df_uses_record): Add KCFI case to handle KCFI RTL patterns and process wrapped RTL.
* doc/extend.texi: Update nocf_check for kcfi.
* doc/invoke.texi (fsanitize=kcfi): Add documentation for KCFI sanitizer option.
* doc/tm.texi.in: Add Kernel Control Flow Integrity section with TARGET_KCFI_SUPPORTED, TARGET_KCFI_MASK_TYPE_ID, TARGET_KCFI_EMIT_TYPE_ID hooks.
* doc/tm.texi: Regenerate.
* final.cc (call_from_call_insn): Add KCFI case to handle KCFI-wrapped calls. Add kcfi_next_labelno().
* opts.cc (sanitizer_opts): Add kcfi entry. (parse_sanitizer_options): Exclude SANITIZE_KCFI from -fsanitize-recover=all.
* rtl.def (KCFI): Add new RTL code for KCFI instrumentation.
* rtlanal.cc (reg_referenced_p): Add KCFI case.
* target.def: Add KCFI target hooks.
* toplev.cc (process_options): Add KCFI option processing.
* tree-inline.cc (copy_bb): Handle KCFI no_sanitize attribute propagation during inlining.
* tree-ssa-tail-merge.cc: Include kcfi.h. (gimple_equal_p): Don't treat calls that get different KCFI checks as equal.
* varasm.cc (assemble_start_function): Emit KCFI preambles. (assemble_external_real): Emit KCFI typeid symbols. (default_elf_asm_named_section): Handle .kcfi_traps using SECTION_LINK_ORDER flag.

gcc/c-family/ChangeLog:

* c-attribs.cc: Include asan.h. (handle_nocf_check_attribute): Enable nocf_check under kcfi. (handle_patchable_function_entry_attribute): Add error for using patchable_function_entry attribute with -fsanitize=kcfi.

---

gcc/kcfi.h line 24

Quoted 3 lines
gcc/kcfi.h new file +3 -0
+
+#include "coretypes.h"
+#include "rtl.h"

In general we try to avoid having .h files include other .h files. Instead push these into the appropriate .cc files.  This make it easier to spot potential layering violations since the use point is explicit in the .cc file rather than blindly carried around in a .h file and potentially getting exposed somewhere we don't want.

gcc/kcfi.h line 33

Quoted 9 lines
gcc/kcfi.h new file +9 -0
+
+/* Common helper for RTL patterns to emit .kcfi_traps section entry.
+   Call after emitting trap label and instruction with the trap symbol
+   reference.  */
+extern void kcfi_emit_traps_section (FILE *file, rtx trap_label_sym,
+				      int labelno);
+
+/* Extract KCFI type ID from current GIMPLE statement.  */
+extern rtx internal_kcfi_get_type_id_for_expanding_gimple_call (void);

Pick one style.  You've got the parameter names in one prototype, but not the other.  The general preference within GCC is without the name.

Quoted 5 lines
gcc/kcfi.cc new file +5 -0
+
+- The check-call instruction sequence must be treated as a single unit: it
+  cannot be rearranged or split or optimized.  The pattern is that
+  indirect calls, "call *%target", get converted into:
+

gcc/kcfi.cc line 87

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+    mov $target_expression, %target ; only present if the expression was
+				    ; not already in %target register
+    load -$offset(%target), %tmp    ; load typeid hash from target preamble
+    cmp $typeid, %tmp		    ; compare expected typeid with loaded
+    je .Lkcfi_call$N		    ; success: jump to the indirect call
+  .Lkcfi_trap$N:		    ; label of trap insn
+    trap			    ; trap on failure, but arranged so
+				    ; "permissive mode" falls through
+  .Lkcfi_call$N:		    ; label of call insn
+    call *%target		    ; actual indirect call

So I sound like a broken record at this point.  I see the assertion that it has to be an atomic unit, but nothing about why.

gcc/kcfi.cc line 415

Quoted 5 lines
gcc/kcfi.cc new file +5 -0
+  /* Keep a private copy: get_insn_template can return a pointer into a target
+     output routine's static scratch buffer, and nop_insn is GC-allocated, so we
+     must not cache the raw pointer for the life of the compilation.  */
+  kcfi_nop = xstrdup (get_insn_template (code_num, nop_insn));
+  int nop_insn_bytes = get_attr_length (nop_insn);

Note that some ports do not track insn lengths, so you'll consistently get back 0 on those.   I would probably recommend asserting the size is nonzero so that if you try to use this on a target without lengths you'll get a compile-time error rather than a runtime surprise.

Also note that length computations are not guaranteed to be correct; they are guaranteed to conservatively correct for things like jump/branch relaxing to work.  So in that context conservatively correct means the reported size is no smaller than the actual size.

So you need to make sure you're safe if the port reports back a longer size than what gets encoded into the final object.

Quoted 12 lines
gcc/kcfi.cc new file +12 -0
+  int prefix_nop_bytes = prefix_nops * nop_insn_bytes;
+  kcfi_typeid_offset += prefix_nop_bytes;
+
+  /* In the case where the KCFI preamble (and potentially the prefix NOPs)
+     are being used for alternative CFI implementations via live-patching,
+     the __cfi_... label itself needs to be usable as a callable function
+     target, so alignment NOPs may need to be added between the preamble
+     label and the typeid during KCFI preamble emission:
+
+     __cfi_func:		// may need to be function entry aligned
+       [alignment padding nops] // may be needed when -falign-functions set
+       [typeid]

gcc/kcfi.cc line 452

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+       [prefix nops]
+     func:
+       [entry nops]
+       [function body]
+
+     But we only calculate alignment padding NOPs when -falign-functions
+     has been explicitly set.
+   */
+  if (align_functions.levels[0].log <= 0)
+    return;

So what happens if the port does not align functions to a useful boundary?

gcc/kcfi.cc line 593

Quoted 6 lines
gcc/kcfi.cc new file +6 -0
+
+  /* Ignore cold partition sections: cold partitions are never indirect call
+     targets.  Only skip preambles for cold partitions (has_bb_partition = true)
+     not for entire cold-attributed functions (has_bb_partition = false).  */
+  if (in_cold_section_p && crtl && crtl->has_bb_partition)
+    return;

Is that an design decision in the partitioning code or is it an implementation detail.  If it's the former, than I'm inclined to allow relying on it.  If it's the latter, then it seems we're just setting up a ticking time bomb.  It could well be either, I don't know off the top of my head.

I'm assuming that things like devirtualizing a call into a direct call are safe, including the speculative forms.

Given we can pretty easily describe the generic call setup in RTL, how painful would it be to instead do the instrumentation in a generic way rather than twiddling each backend?

In that kind of design we'd force the target to provide the two marker insns which mark the beginning and end of the atomic region. Target independent code would be used to load the typeid hash from the preamble (using the offset the target provides), compare it to the expected type id, branch around a trap-like insn, the trap-like insn itself, then finally the call.  I'm not demanding this rethink, but I do want it to be at least considered as a design question.

Jeff

author
#4 lore raw

Re: [PATCH v17 2/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 4 lines · Jeff Law

Review

Quoted 2 lines
(quoted diff) +2 -0
+#include "coretypes.h"
+#include "rtl.h"

In general we try to avoid having .h files include other .h files. Instead push these into the appropriate .cc files.  This make it easier

Ah-ha, understood! I've fixed this for v18 now.

Quoted 7 lines

gcc/kcfi.h line 33

Quoted 5 lines
gcc/kcfi.h new file +5 -0
+extern void kcfi_emit_traps_section (FILE *file, rtx trap_label_sym,
+				      int labelno);
+
+/* Extract KCFI type ID from current GIMPLE statement.  */
+extern rtx internal_kcfi_get_type_id_for_expanding_gimple_call (void);

Pick one style.  You've got the parameter names in one prototype, but not the other.  The general preference within GCC is without the name.

I've fixed this for v18. (I'm used to the opposite in Linux: everything has parameter names.)

Quoted 3 lines
Quoted 3 lines

+- The check-call instruction sequence must be treated as a single unit: it

gcc/kcfi.cc new file +2 -0
+  cannot be rearranged or split or optimized.  The pattern is that
+  indirect calls, "call *%target", get converted into:

[...]

Quoted 2 lines

So I sound like a broken record at this point.  I see the assertion that it has to be an atomic unit, but nothing about why.

Yes, sorry, and I've answered this in detail now in my reply to 7/7. In short:

1. The checked target must stay in the checked register until the call:
a spill and reload in between would let attacker-writable memory supply an unchecked target ("pop %target; call %target").
2. The trap isn't noreturn: in the kernel's permissive mode, execution continues from the trap into the call, so the trap block can't be moved out of line.
3. The kernel depends on the exact layout: its trap handlers decode the instructions around the trap, and x86 may rewrite call sites in place into FineIBT at boot.

v18 will add all of this to the design comment, so the "why" lives next to the assertion.

Quoted 7 lines

gcc/kcfi.cc line 415

Quoted 2 lines
gcc/kcfi.cc new file +2 -0
+  kcfi_nop = xstrdup (get_insn_template (code_num, nop_insn));
+  int nop_insn_bytes = get_attr_length (nop_insn);

Note that some ports do not track insn lengths, so you'll consistently get back 0 on those.   I would probably recommend asserting the size is nonzero so that if you try to use this on a target without lengths you'll get a compile-time error rather than a runtime surprise.

Quoted 7 lines

Also note that length computations are not guaranteed to be correct; they are guaranteed to conservatively correct for things like jump/branch relaxing to work.  So in that context conservatively correct means the reported size is no smaller than the actual size.

So you need to make sure you're safe if the port reports back a longer size than what gets encoded into the final object.

Yup, I was able to trigger this mismatch with RISC-V's C extension where I get a length of 4, but the assembler emits c.nop (2 bytes), so with prefix NOPs the call sites loaded the type ID from the wrong offset. (The kernel doesn't use prefix NOPs with KCFI on RISC-V, which is why I never hit this.) v18 will add a TARGET_KCFI_NOP_SIZE hook for the size the assembler actually emits; RISC-V will return 2 with C or Zca, as Clang does. Without the hook, KCFI will fall back to the length attribute and assert that it's nonzero.

Quoted 3 lines

gcc/kcfi.cc line 452

Quoted 2 lines
gcc/kcfi.cc new file +2 -0
+  if (align_functions.levels[0].log <= 0)
+    return;

So what happens if the port does not align functions to a useful boundary?

That padding is only used in Linux for x86's FineIBT live-patching, which needs the __cfi_ label itself to be callable, so the kernel asks for it with -falign-functions. But since this padding is supported by the core KCFI code, it needs to work on all backends. On RISC-V with C, and on Thumb at -Os, the type ID could end up only 2-byte aligned, making the load misaligned. Clang aligns every function that has a KCFI type ID to at least 4 bytes, on all targets; v18 will do the same now.

Quoted 10 lines

gcc/kcfi.cc line 593

Quoted 5 lines
gcc/kcfi.cc new file +5 -0
+  /* Ignore cold partition sections: cold partitions are never indirect call
+     targets.  Only skip preambles for cold partitions (has_bb_partition = true)
+     not for entire cold-attributed functions (has_bb_partition = false).  */
+  if (in_cold_section_p && crtl && crtl->has_bb_partition)
+    return;

Is that an design decision in the partitioning code or is it an implementation detail.  If it's the former, than I'm inclined to allow relying on it.  If it's the latter, then it seems we're just setting up a ticking time bomb.  It could well be either, I don't know off the top of my head.

It's a design property of partitioning: the cold part of a function is never called, only jumped to from its parent. A function's address is always its hot entry, so there's no valid entry point into the middle of a function, and we don't want KCFI to create one.

bb-reorder enforces this: sanitize_hot_paths() walks up from every hot block to the entry and moves that path into the hot partition, so when a function is split, its entry block is always hot.

And x86 IBT already depends on the same property. The ENDBR inserter (rest_of_insert_endbr_and_patchable_area() in i386-features.cc) only puts an ENDBR at the head of the function's first block, never at the start of the cold partition. An indirect branch into a cold partition would fault under IBT just as it would fail a KCFI check. For example, with -O2 -fcf-protection=full -fsanitize=kcfi:

	__cfi_work:
		...
		movl	$0xb8360626, %eax
	work:
		endbr64
		testl	%edi, %edi
		js	.L4
		...
		.section	.text.unlikely
	work.cold:
	.L4:
		subq	$24, %rsp

work gets both the ENDBR and the KCFI preamble; work.cold gets neither, and is reached only by the direct "js .L4".

Quoted 2 lines

I'm assuming that things like devirtualizing a call into a direct call are safe, including the speculative forms.

Yes. A call that becomes direct needs no check, since its target is immutable. A speculative call keeps the original indirect call as the fallback, and that is still an indirect call with its function type, so it gets checked. KCFI is C-only, so in practice the speculative form comes from indirect call profiling; v18 will add a tree-prof test (gcc.dg/tree-prof/kcfi-speculative-call.c) that checks the fallback keeps its KCFI check and that the profiled program runs without trapping.

Quoted 11 lines

Given we can pretty easily describe the generic call setup in RTL, how painful would it be to instead do the instrumentation in a generic way rather than twiddling each backend?

In that kind of design we'd force the target to provide the two marker insns which mark the beginning and end of the atomic region. Target independent code would be used to load the typeid hash from the preamble (using the offset the target provides), compare it to the expected type id, branch around a trap-like insn, the trap-like insn itself, then finally the call.  I'm not demanding this rethink, but I do want it to be at least considered as a design question.

I did consider it, and tried something like it around v2. Two things stopped me:

- The marker insns don't make the region atomic in the ways that matter (spill code between the check and the call, and the trap block being moved), as above.

- Each target's call setup is more than the generic call: the call expanders handle calling conventions, sibcalls, PLT and long-call forms, BTI and SLS mitigations, and more. KCFI wraps the call pattern each target already produces, so all of that keeps working, and the per-target part is only the check sequence itself (and the kernel's trap handlers decode a different sequence on each architecture anyway). I described this to Andrea around v5[1].

Clang made the same choice: generic code marks the indirect calls, and each target expands its own check sequence just before the call.

Thanks for looking at all this; hopefully I've covered everything. Let me know if I need to dig in further anywhere or if I've misunderstood anything. :)

-Kees

[1] https://inbox.sourceware.org/gcc-patches/202510221253.D6B51F950@keescook/

Signature · 1 line
Kees Cook
#5 lore raw

Re: [PATCH v17 2/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 4 lines · Kees Cook
Quoted 2 lines

Pick one style.  You've got the parameter names in one prototype, but not the other.  The general preference within GCC is without the name.

I've fixed this for v18. (I'm used to the opposite in Linux: everything has parameter names.)

Yea.  We're not as consistent as I'd like within the GCC tree. Hence the "just pick one" rather than forcing to one style or the other.

Quoted 9 lines
Quoted 3 lines

So I sound like a broken record at this point.  I see the assertion that it has to be an atomic unit, but nothing about why.

Yes, sorry, and I've answered this in detail now in my reply to 7/7. In short:

1. The checked target must stay in the checked register until the call:
a spill and reload in between would let attacker-writable memory supply an unchecked target ("pop %target; call %target").

Understood.  And this may in fact be the biggest reason.  I'll ponder in the context of spills.

Quoted 3 lines

2. The trap isn't noreturn: in the kernel's permissive mode, execution continues from the trap into the call, so the trap block can't be moved out of line.

Yea, but that's easily solvable.  We'd just define something with similar semantics so that the compiler doesn't think the trap halts execution.

Quoted 6 lines

3. The kernel depends on the exact layout: its trap handlers decode the instructions around the trap, and x86 may rewrite call sites in place into FineIBT at boot.

v18 will add all of this to the design comment, so the "why" lives next to the assertion.

Right, but we can handle that with the right barriers around the call to force the exact layout.  But given the concerns about spills, an atomic sequence may simply be needed here.

Quoted 10 lines
Quoted 10 lines

gcc/kcfi.cc line 593

Quoted 5 lines
gcc/kcfi.cc new file +5 -0
+  /* Ignore cold partition sections: cold partitions are never indirect call
+     targets.  Only skip preambles for cold partitions (has_bb_partition = true)
+     not for entire cold-attributed functions (has_bb_partition = false).  */
+  if (in_cold_section_p && crtl && crtl->has_bb_partition)
+    return;

Is that an design decision in the partitioning code or is it an implementation detail.  If it's the former, than I'm inclined to allow relying on it.  If it's the latter, then it seems we're just setting up a ticking time bomb.  It could well be either, I don't know off the top of my head.

Quoted 4 lines

It's a design property of partitioning: the cold part of a function is never called, only jumped to from its parent. A function's address is always its hot entry, so there's no valid entry point into the middle of a function, and we don't want KCFI to create one.

Duh.  I should have realized  this.  Crossing the partition is never a call, it's just a jump.  Presumably you're not trying to protect indirect jump targets?  I've been out of the ROP/JOP space for years now, but my recollection was that indirect jumps where just as problematical as calls.

Quoted 11 lines
Quoted 11 lines

Given we can pretty easily describe the generic call setup in RTL, how painful would it be to instead do the instrumentation in a generic way rather than twiddling each backend?

In that kind of design we'd force the target to provide the two marker insns which mark the beginning and end of the atomic region. Target independent code would be used to load the typeid hash from the preamble (using the offset the target provides), compare it to the expected type id, branch around a trap-like insn, the trap-like insn itself, then finally the call.  I'm not demanding this rethink, but I do want it to be at least considered as a design question.

Quoted 2 lines

I did consider it, and tried something like it around v2. Two things stopped me:

[ ... ]
Thanks.  I could probably argue a bit here, but it's probably academic and we've got better things to do with our time I think :-)

Still working my way through the other patch and I still want to think about atomicness of the pattern WRT spills.  I think we have similar problems in other contexts and I wonder how we manage them...

jeff

author
#6 lore raw

PATCH v17 3/7 kcfi: Add regression test suite

In reply to Kees Cook

Add test suite for KCFI (Kernel Control Flow Integrity) ABI, covering core functionality, optimization and code generation, addressing, architecture-specific KCFI sequence emission, and integration with patchable function entry.

The arch-specific patterns themselves are added with the subsequent architecture patches.

Tests can be run via:
make check-c RUNTESTFLAGS='kcfi.exp'

Assisted-by LLM [tests]

gcc/testsuite/ChangeLog:

* lib/target-supports.exp: Add check_effective_target_kcfi.
* gcc.dg/kcfi/kcfi.exp: Add kcfi tests.
* gcc.dg/kcfi/kcfi-adjacency.c: New test.
* gcc.dg/kcfi/kcfi-asm-name.c: New test.
* gcc.dg/kcfi/kcfi-basics.c: New test.
* gcc.dg/kcfi/kcfi-call-sharing.c: New test.
* gcc.dg/kcfi/kcfi-cold-partition.c: New test.
* gcc.dg/kcfi/kcfi-complex-addressing.c: New test.
* gcc.dg/kcfi/kcfi-direct-call-shapes.c: New test.
* gcc.dg/kcfi/kcfi-ipa-robustness.c: New test.
* gcc.dg/kcfi/kcfi-lto-offset.c: New test.
* gcc.dg/kcfi/kcfi-move-preservation.c: New test.
* gcc.dg/kcfi/kcfi-no-sanitize-inline.c: New test.
* gcc.dg/kcfi/kcfi-no-sanitize.c: New test.
* gcc.dg/kcfi/kcfi-offset-validation.c: New test.
* gcc.dg/kcfi/kcfi-patchable-entry-only.c: New test.
* gcc.dg/kcfi/kcfi-patchable-incompatible.c: New test.
* gcc.dg/kcfi/kcfi-patchable-large.c: New test.
* gcc.dg/kcfi/kcfi-patchable-medium.c: New test.
* gcc.dg/kcfi/kcfi-patchable-prefix-only.c: New test.
* gcc.dg/kcfi/kcfi-qualified-params.c: New test.
* gcc.dg/kcfi/kcfi-runtime.c: New test.
* gcc.dg/kcfi/kcfi-tail-calls.c: New test.
* gcc.dg/kcfi/kcfi-tail-merge-run.c: New test.
* gcc.dg/kcfi/kcfi-tail-merge.c: New test.
* gcc.dg/kcfi/kcfi-trap-section.c: New test.
* gcc.dg/kcfi-compat/kcfi-compat.exp: Add kcfi compat tests.
* gcc.dg/kcfi-compat/kcfi-indirect-1.h: New test header.
* gcc.dg/kcfi-compat/kcfi-indirect-1_main.c: New test main.
* gcc.dg/kcfi-compat/kcfi-indirect-1_x.c: New test caller half.
* gcc.dg/kcfi-compat/kcfi-indirect-1_y.c: New test target half.
* gcc.dg/pch/kcfi-1.c: New test.
* gcc.dg/pch/kcfi-1.hs: New test header.

---
 .../gcc.dg/kcfi-compat/kcfi-compat.exp        |  87 ++++++
 gcc/testsuite/gcc.dg/kcfi/kcfi.exp            |  51 ++++
 gcc/testsuite/lib/target-supports.exp         |  14 +
 .../gcc.dg/kcfi-compat/kcfi-indirect-1.h      |  26 ++
 .../gcc.dg/kcfi-compat/kcfi-indirect-1_main.c |  22 ++
 .../gcc.dg/kcfi-compat/kcfi-indirect-1_x.c    |  43 +++
 .../gcc.dg/kcfi-compat/kcfi-indirect-1_y.c    |  40 +++
 gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c    |  49 ++++
 gcc/testsuite/gcc.dg/kcfi/kcfi-asm-name.c     |  16 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c       |  74 +++++
 gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c |  61 ++++
 .../gcc.dg/kcfi/kcfi-cold-partition.c         | 126 ++++++++
 .../gcc.dg/kcfi/kcfi-complex-addressing.c     | 131 +++++++++
 .../gcc.dg/kcfi/kcfi-direct-call-shapes.c     |  28 ++
 .../gcc.dg/kcfi/kcfi-ipa-robustness.c         |  54 ++++
 gcc/testsuite/gcc.dg/kcfi/kcfi-lto-offset.c   |  27 ++
 .../gcc.dg/kcfi/kcfi-move-preservation.c      |  41 +++
 .../gcc.dg/kcfi/kcfi-no-sanitize-inline.c     |  74 +++++
 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c  |  31 ++
 .../gcc.dg/kcfi/kcfi-offset-validation.c      |  24 ++
 .../gcc.dg/kcfi/kcfi-patchable-entry-only.c   |  14 +
 .../gcc.dg/kcfi/kcfi-patchable-incompatible.c |   7 +
 .../gcc.dg/kcfi/kcfi-patchable-large.c        |  14 +
 .../gcc.dg/kcfi/kcfi-patchable-medium.c       |  14 +
 .../gcc.dg/kcfi/kcfi-patchable-prefix-only.c  |  14 +
 .../gcc.dg/kcfi/kcfi-qualified-params.c       |  58 ++++
 gcc/testsuite/gcc.dg/kcfi/kcfi-runtime.c      | 276 ++++++++++++++++++
 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c   |  60 ++++
 .../gcc.dg/kcfi/kcfi-tail-merge-run.c         |  54 ++++
 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-merge.c   |  36 +++
 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c |  17 ++
 gcc/testsuite/gcc.dg/pch/kcfi-1.c             |  50 ++++
 gcc/testsuite/gcc.dg/pch/kcfi-1.hs            |  20 ++
 33 files changed, 1653 insertions(+)
 create mode 100644 gcc/testsuite/gcc.dg/kcfi-compat/kcfi-compat.exp
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi.exp
 create mode 100644 gcc/testsuite/gcc.dg/kcfi-compat/kcfi-indirect-1.h
 create mode 100644 gcc/testsuite/gcc.dg/kcfi-compat/kcfi-indirect-1_main.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi-compat/kcfi-indirect-1_x.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi-compat/kcfi-indirect-1_y.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-asm-name.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-cold-partition.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-complex-addressing.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-direct-call-shapes.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-ipa-robustness.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-lto-offset.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-move-preservation.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize-inline.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-offset-validation.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-entry-only.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-incompatible.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-large.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-medium.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-prefix-only.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-qualified-params.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-runtime.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-merge-run.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-merge.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c
 create mode 100644 gcc/testsuite/gcc.dg/pch/kcfi-1.c
 create mode 100644 gcc/testsuite/gcc.dg/pch/kcfi-1.hs
gcc/testsuite/gcc.dg/kcfi-compat/kcfi-compat.exp new file +87 -0
new file mode 100644
index 000000000000..973a92a8ad0c
@@ -0,0 +1,87 @@
+# KCFI cross-TU / cross-compiler indirect-call ABI compatibility tests.
+#   Copyright (C) 2026 Free Software Foundation, Inc.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GCC; see the file COPYING3.  If not see
+# <http://www.gnu.org/licenses/>.
+
+# Split each test into separately-compiled halves and verify that KCFI
+# indirect-call checks pass across the object boundary (i.e. that two
+# independent compilations agree on the type-id ABI).  The _x TU is the
+# indirect caller and the _y TU holds the targets; the framework builds
+# each with the compiler under test and, when an alternate compiler is
+# configured, in every combination, so both compilers are exercised as
+# caller and as target.
+#
+# By default both halves are built with the compiler under test.  To check
+# cross-compiler agreement with clang, pass ALT_CC_UNDER_TEST as a make
+# variable (DejaGnu writes it into site.exp; remove a stale site.exp first):
+#
+#   rm gcc/site.exp
+#   make check-c RUNTESTFLAGS="kcfi-compat.exp" \
+#       ALT_CC_UNDER_TEST="/path/to/clang -Xclang -fsanitize-kcfi-hash=FNV-1a"
+
+if $tracelevel then {
+    strace $tracelevel
+}
+
+global GCC_UNDER_TEST
+global ALT_CC_UNDER_TEST
+global compat_save_gcc_under_test
+global compat_use_alt
+global compat_same_alt
+
+# c-compat.exp must be loaded before compat.exp (which guards on it).
+load_lib standard.exp
+load_lib gcc.exp
+load_lib c-compat.exp
+load_lib compat.exp
+
+gcc_init
+
+# Only run where -fsanitize=kcfi is supported (and can be linked and run).
+if { ![check_no_compiler_messages fsanitize_kcfi executable {
+    int main (void) { return 0; }
+} "-fsanitize=kcfi"] } {
+    return
+}
+
+# Save the compiler under test; each test switches it a couple of times.
+set compat_save_gcc_under_test $GCC_UNDER_TEST
+
+# Identifier for this suite, to avoid object-file name clashes.
+set sid "kcfi_compat"
+
+# Find out whether there is an alternate compiler to test.
+set compat_use_alt 0
+set compat_same_alt 0
+if [info exists ALT_CC_UNDER_TEST] then {
+    set compat_use_alt 1
+    if [string match "same" $ALT_CC_UNDER_TEST] then {
+	set compat_same_alt 1
+    }
+}
+
+# Initialize the compat framework globals (compat_save_TEST_ALWAYS_FLAGS,
+# compat_alt_*, DFP support, ...).
+compat_setup_dfp
+
+foreach src [lsort [find $srcdir/$subdir *_main.c]] {
+    if ![runtest_file_p $runtests $src] then {
+	continue
+    }
+    compat-execute $src $sid $compat_use_alt
+}
+
+# Restore the original compiler under test.
+compat-use-tst-compiler
gcc/testsuite/gcc.dg/kcfi/kcfi.exp new file +51 -0

51 lines not on this page · raw message

gcc/testsuite/lib/target-supports.exp +14 -0
index ae04b6a8daa1..6b6db81da2bb 100644
@@ -14436,6 +14436,20 @@ proc check_effective_target_no_fsanitize_address {} {
     return 0;
 }
 
+# Return 1 if this target supports KCFI (Kernel Control Flow Integrity)
+
+proc check_effective_target_kcfi {} {
+    # We don't need a full executable to test this flag
+    return [check_no_compiler_messages kcfi assembly {
+	void func(void) {}
+	int main(void) {
+	    void (*ptr)(void) = func;
+	    ptr();
+	    return 0;
+	}
+    } "-fsanitize=kcfi"]
+}
+
 # Return 1 if the target supports GNU Retain, 0 otherwise.
 # This means both SHF_GNU_RETAIN and SHT_INIT_ARRAY to simplify uses.
 
gcc/testsuite/gcc.dg/kcfi-compat/kcfi-indirect-1.h new file +26 -0
new file mode 100644
index 000000000000..1c399c9bc4e7
@@ -0,0 +1,26 @@
+/* Shared declarations for the KCFI cross-TU indirect-call compat test.
+
+   Including this in both the caller (_x) and the targets (_y) keeps their view
+   of each target's prototype (and therefore the derived KCFI type-id) in
+   sync from a single source.  */
+
+#ifndef KCFI_INDIRECT_1_H
+#define KCFI_INDIRECT_1_H
+
+typedef int (*fp1) (int);
+typedef int (*fp2) (int, int);
+typedef int (*fp3) (int *);
+
+/* Targets defined in the _y TU, called indirectly from the _x TU.  */
+extern int tgt_inc (int);
+extern int tgt_add (int, int);
+extern int tgt_neg (int);
+extern int tgt_mul (int, int);
+/* Called through fp3: the top-level const on the parameter is not part of
+   the function type, so it must not change the type-id.  */
+extern int tgt_deref (int *const);
+
+/* Entry point of the caller TU (_x), invoked from _main.  */
+extern void run_caller (void);
+
+#endif /* KCFI_INDIRECT_1_H */
gcc/testsuite/gcc.dg/kcfi-compat/kcfi-indirect-1_main.c new file +22 -0
new file mode 100644
index 000000000000..799579f977d0
@@ -0,0 +1,22 @@
+/* KCFI cross-TU / cross-compiler indirect-call ABI compatibility test.
+
+   Bootstrap TU.  main() lives here because the compat framework always builds
+   the _main TU with the compiler under test; it does nothing interesting but
+   hand control to the caller in the _x TU.
+
+   The cross-TU / cross-compiler pairing under test is _x (the indirect caller)
+   against _y (the targets): the framework builds each of those with the
+   compiler under test and, when ALT_CC_UNDER_TEST is set, an alternate
+   compiler (in every combination) so both compilers get exercised as the
+   caller and as the target.  See kcfi-compat.exp.  */
+
+/* { dg-options "-fsanitize=kcfi -O2" } */
+
+#include "kcfi-indirect-1.h"
+
+int
+main (void)
+{
+  run_caller ();
+  return 0;
+}
gcc/testsuite/gcc.dg/kcfi-compat/kcfi-indirect-1_x.c new file +43 -0

43 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi-compat/kcfi-indirect-1_y.c new file +40 -0
new file mode 100644
index 000000000000..b67635c25fee
@@ -0,0 +1,40 @@
+/* KCFI cross-TU / cross-compiler compat test: the "target" TU.
+
+   Defines the address-taken functions the caller (_x) invokes indirectly.
+   Being address-taken, each gets a __cfi_ preamble whose type-id is derived
+   from the function's own type; a call succeeds only if that matches the
+   caller's call-site type-id.  */
+
+/* { dg-options "-fsanitize=kcfi -O2" } */
+
+#include "kcfi-indirect-1.h"
+
+int
+tgt_inc (int a)
+{
+  return a + 1;
+}
+
+int
+tgt_add (int a, int b)
+{
+  return a + b;
+}
+
+int
+tgt_neg (int a)
+{
+  return -a;
+}
+
+int
+tgt_mul (int a, int b)
+{
+  return a * b;
+}
+
+int
+tgt_deref (int *const p)
+{
+  return *p;
+}
gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c new file +49 -0

49 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-asm-name.c new file +16 -0
new file mode 100644
index 000000000000..fbf34c30a591
@@ -0,0 +1,16 @@
+/* Test that the KCFI preamble strips the assembler-name encoding when
+   forming the __cfi_ label.  Functions with a custom asm() name have a
+   leading '*' in their DECL_ASSEMBLER_NAME; without stripping it the
+   preamble emits "__cfi_*name:", which the assembler rejects.  Scanning the
+   emitted label is enough to catch this, so use dg-do compile (portable to
+   targets without an assembler).  */
+/* { dg-do compile } */
+
+int realname (int x) __asm__ ("my_custom_name");
+int realname (int x) { return x + 1; }
+
+int call (int (*p) (int), int x) { return p (x); }
+
+/* The preamble label must be clean (no encoding '*').  */
+/* { dg-final { scan-assembler "__cfi_my_custom_name:" } } */
+/* { dg-final { scan-assembler-not {__cfi_\*} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c new file +74 -0

74 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c new file +61 -0

61 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-cold-partition.c new file +126 -0

126 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-complex-addressing.c new file +131 -0

131 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-direct-call-shapes.c new file +28 -0
new file mode 100644
index 000000000000..4fce0771a55d
@@ -0,0 +1,28 @@
+/* Verify that direct calls of every syntactic shape (plain, weak,
+   aliased, static) produce zero KCFI checks, and that the only KCFI
+   check generated comes from the lone indirect call.  This guards
+   against regressions where the direct-call detector would miss
+   non-SYMBOL_REF address forms (CONST, LABEL_REF) and wrongly wrap
+   a direct call.  */
+/* { dg-do compile } */
+/* { dg-additional-options "-O2" } */
+
+extern void plain_func(int);
+extern void weak_func(int) __attribute__((weak));
+void plain_func(int x) { __asm__("" : : "r"(x) : "memory"); }
+void weak_func(int x) { __asm__("" : : "r"(x) : "memory"); }
+extern void alias_func(int) __attribute__((alias("plain_func")));
+__attribute__((noinline)) static void static_func(int x) {
+    __asm__("" : : "r"(x) : "memory");
+}
+
+void caller(int sel, void (*ip)(int), int x) {
+    if (sel == 1) plain_func(x);   /* direct, plain extern */
+    if (sel == 2) weak_func(x);    /* direct, weak */
+    if (sel == 3) alias_func(x);   /* direct, alias */
+    if (sel == 4) static_func(x);  /* direct, static */
+    if (sel == 5) ip(x);           /* indirect — the only KCFI-checked call */
+}
+
+/* Per-arch dg-final patterns are added by each arch's KCFI implementation
+   commit; the invariant is "exactly one typeid load = one indirect call".  */
gcc/testsuite/gcc.dg/kcfi/kcfi-ipa-robustness.c new file +54 -0

54 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-lto-offset.c new file +27 -0
new file mode 100644
index 000000000000..029da383aca8
@@ -0,0 +1,27 @@
+/* Verify KCFI is correct under LTO.  The callsite typeid-load offset (and the
+   preamble alignment padding) must be computed in whichever process emits the
+   code.  Regression test for a bug where these were set in an IPA pass that
+   runs at WPA, so the globals were still 0 in the separate ltrans codegen
+   process: every indirect call then loaded the typeid from the wrong offset
+   and trapped at run time.  */
+
+/* { dg-do run { target native } } */
+/* { dg-require-effective-target lto } */
+/* { dg-additional-options "-O2 -flto" } */
+
+typedef int (*fp_t) (int);
+
+/* volatile keeps the call indirect (and KCFI-checked) through LTO.  */
+volatile fp_t sink;
+
+int target (int x) { return x + 1; }
+
+int do_call (int x) { return sink (x); }
+
+int
+main (void)
+{
+  sink = target;
+  /* With a wrong typeid offset this traps (SIGILL) instead of returning 42.  */
+  return do_call (41) == 42 ? 0 : 1;
+}
gcc/testsuite/gcc.dg/kcfi/kcfi-move-preservation.c new file +41 -0

41 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize-inline.c new file +74 -0

74 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c new file +31 -0
new file mode 100644
index 000000000000..124d26488635
@@ -0,0 +1,31 @@
+/* Test KCFI with no_sanitize attribute.  */
+/* { dg-do compile } */
+
+void target_function(void) {
+    /* This should get KCFI preamble.  */
+}
+
+void caller_with_checks(void) {
+    /* This function should generate KCFI checks.  */
+    void (*func_ptr)(void) = target_function;
+    func_ptr();
+}
+
+__attribute__((no_sanitize("kcfi")))
+void caller_no_checks(void) {
+    /* This function should NOT generate KCFI checks due to no_sanitize.  */
+    void (*func_ptr)(void) = target_function;
+    func_ptr();
+}
+
+int main() {
+    caller_with_checks();    /* This should generate checks inside.  */
+    caller_no_checks();      /* This should NOT generate checks inside.  */
+    return 0;
+}
+
+/* All functions should get preambles regardless of no_sanitize.  */
+/* { dg-final { scan-assembler "__cfi_target_function:" } } */
+/* { dg-final { scan-assembler "__cfi_caller_with_checks:" } } */
+/* { dg-final { scan-assembler "__cfi_caller_no_checks:" } } */
+/* { dg-final { scan-assembler "__cfi_main:" } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-offset-validation.c new file +24 -0
new file mode 100644
index 000000000000..213a1a2892a5
@@ -0,0 +1,24 @@
+/* Test KCFI call-site offset validation across architectures.  */
+/* { dg-do compile } */
+
+void target_func_a(void) { }
+void target_func_b(int x) { }
+void target_func_c(int x, int y) { }
+
+int main() {
+    void (*ptr_a)(void) = target_func_a;
+    void (*ptr_b)(int) = target_func_b;
+    void (*ptr_c)(int, int) = target_func_c;
+
+    /* Multiple indirect calls.  */
+    ptr_a();
+    ptr_b(1);
+    ptr_c(1, 2);
+
+    return 0;
+}
+
+/* Should have KCFI preambles for all functions.  */
+/* { dg-final { scan-assembler "__cfi_target_func_a:" } } */
+/* { dg-final { scan-assembler "__cfi_target_func_b:" } } */
+/* { dg-final { scan-assembler "__cfi_target_func_c:" } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-entry-only.c new file +14 -0
new file mode 100644
index 000000000000..a6a2f4816fef
@@ -0,0 +1,14 @@
+/* Test KCFI with patchable function entries - entry NOPs only.  */
+/* { dg-do compile } */
+/* { dg-additional-options "-fpatchable-function-entry=4,0" } */
+
+void test_function(void) {
+}
+
+int main() {
+    void (*func_ptr)(void) = test_function;
+    func_ptr();
+    return 0;
+}
+
+/* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-incompatible.c new file +7 -0
new file mode 100644
index 000000000000..c6cf9ab720a3
@@ -0,0 +1,7 @@
+/* The patchable_function_entry attribute is incompatible with KCFI.  */
+/* { dg-do compile } */
+
+__attribute__((patchable_function_entry(4, 2)))
+int test_function(void) { /* { dg-error "'patchable_function_entry' attribute cannot be used with '-fsanitize=kcfi'" } */
+    return 42;
+}
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-large.c new file +14 -0
new file mode 100644
index 000000000000..8c4ec30cecc5
@@ -0,0 +1,14 @@
+/* Test KCFI with large patchable function entries.  */
+/* { dg-do compile } */
+/* { dg-additional-options "-fpatchable-function-entry=11,11" } */
+
+void test_function(void) {
+}
+
+int main() {
+    void (*func_ptr)(void) = test_function;
+    func_ptr();
+    return 0;
+}
+
+/* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-medium.c new file +14 -0
new file mode 100644
index 000000000000..78a834ef2a97
@@ -0,0 +1,14 @@
+/* Test KCFI with medium patchable function entries.  */
+/* { dg-do compile } */
+/* { dg-additional-options "-fpatchable-function-entry=8,4" } */
+
+void test_function(void) {
+}
+
+int main() {
+    void (*func_ptr)(void) = test_function;
+    func_ptr();
+    return 0;
+}
+
+/* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-prefix-only.c new file +14 -0
new file mode 100644
index 000000000000..1a4d8269ed56
@@ -0,0 +1,14 @@
+/* Test KCFI with patchable function entries - prefix NOPs only.  */
+/* { dg-do compile } */
+/* { dg-additional-options "-fpatchable-function-entry=3,3" } */
+
+void test_function(void) {
+}
+
+int main() {
+    void (*func_ptr)(void) = test_function;
+    func_ptr();
+    return 0;
+}
+
+/* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-qualified-params.c new file +58 -0

58 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-runtime.c new file +276 -0

276 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c new file +60 -0

60 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-tail-merge-run.c new file +54 -0

54 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-tail-merge.c new file +36 -0
new file mode 100644
index 000000000000..5bc9307c34ff
@@ -0,0 +1,36 @@
+/* Test that tail merging does not merge indirect calls that get different
+   KCFI checks.  Calls through the members of a union share one pointer
+   value but have different function types, so each must keep its own
+   check.  Reduced from proc_vec_conv() in the Linux kernel.  */
+/* { dg-do compile } */
+/* { dg-additional-options "-O2" } */
+
+union conv
+{
+  int (*int_conv) (int *);
+  int (*uint_conv) (unsigned int *);
+  int (*ulong_conv) (unsigned long *);
+};
+
+enum which { INT, UINT, ULONG };
+
+int
+dispatch (enum which type, union conv conv, char *k)
+{
+  switch (type)
+    {
+    case INT:
+      return conv.int_conv ((int *) k);
+    case UINT:
+      return conv.uint_conv ((unsigned int *) k);
+    case ULONG:
+      return conv.ulong_conv ((unsigned long *) k);
+    }
+  return -1;
+}
+
+/* Three call-site checks; merging the calls would leave one.  */
+/* x86: { dg-final { scan-assembler-times {movl\s+\$-?[0-9]+,\s+%r10d} 3 { target i?86-*-* x86_64-*-* } } } */
+/* AArch64: { dg-final { scan-assembler-times {mov\s+w17, #[0-9]+} 3 { target aarch64*-*-* } } } */
+/* ARM 32-bit: { dg-final { scan-assembler-times {ldr\s+ip, \[(?:r[0-9]+|lr|ip), #-4\]} 3 { target arm*-*-* } } } */
+/* RISC-V: { dg-final { scan-assembler-times {lui\tt2, [0-9]+} 3 { target riscv*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c new file +17 -0
new file mode 100644
index 000000000000..6d34ad6e1a0c
@@ -0,0 +1,17 @@
+/* Test KCFI trap section generation.  */
+/* { dg-do compile } */
+
+void target_function(void) {}
+
+int main() {
+    void (*func_ptr)(void) = target_function;
+
+    /* Multiple indirect calls to generate multiple trap entries.  */
+    func_ptr();
+    func_ptr();
+
+    return 0;
+}
+
+/* Should have KCFI preamble.  */
+/* { dg-final { scan-assembler "__cfi_target_function:" } } */
gcc/testsuite/gcc.dg/pch/kcfi-1.c new file +50 -0

50 lines not on this page · raw message

gcc/testsuite/gcc.dg/pch/kcfi-1.hs new file +20 -0
new file mode 100644
index 000000000000..5a32e2bc1dc9
@@ -0,0 +1,20 @@
+/* Header precompiled for kcfi-1.c.  It supplies the function types and
+   address-taken declarations whose KCFI type-ids kcfi-1.c relies on; the point
+   of the test is that those type-ids come out identical whether the
+   FUNCTION_TYPE trees are parsed fresh or restored from the PCH.
+
+   The header is precompiled with -fsanitize=kcfi so the PCH matches the way
+   kcfi-1.c is compiled; dg-require-effective-target keeps this UNSUPPORTED
+   (not failing) on targets without KCFI.  */
+
+/* { dg-options "-fsanitize=kcfi" } */
+/* { dg-require-effective-target kcfi } */
+
+typedef int (*fp_ii) (int, int);
+typedef long (*fp_lp) (long *);
+struct s;
+typedef void (*fp_sp) (struct s *);
+
+extern int add (int, int);
+extern long deref (long *);
+extern void take (struct s *);
Signature · 1 line
2.55.0
author
#7 lore raw

PATCH v17 4/7 x86: Add x86_64 Kernel Control Flow Integrity implementation

In reply to Kees Cook

Implement x86_64-specific KCFI backend:

- Implies -mindirect-branch-register since KCFI needs call target in a register for typeid hash loading.

- Function preamble generation with type IDs positioned at -(4+prefix_nops) offset from function entry point.

- Function-aligned KCFI preambles using calculated alignment padding NOPs:
aligned(prefix_nops + 5, $func_align) to maintain ability to call the __cfi_ preamble directly in the case of Linux's FineIBT alternative CFI sequences (live patched into place).

- Type-id hash avoids generating ENDBR instruction in type IDs (0xfa1e0ff3/0xfb1e0ff3 are incremented by 1 to prevent execution).

- On-demand scratch register allocation strategy (r11 as needed), with the clobbers added when KCFI is used.

- Incompatible with -ffixed-r10 or -ffixed-r11.

- Uses the .kcfi_traps section for debugger/runtime metadata.

- Introduces -fsanitize-kcfi-arity to enable function arg count to be represented in the kcfi hash preamble for FineIBT.

Assembly Code Pattern layout required by Linux kernel:

  movl $inverse_type_id, %r10d   ; Load expected type (0 - hash)
  addl offset(%target), %r10d    ; Add stored type ID from preamble
  je .Lkcfi_call                 ; Branch if types match (sum == 0)
  .Lkcfi_trap: ud2               ; Undefined instruction trap on mismatch

.Lkcfi_call: call/jmp *%target ; Execute validated indirect transfer

Build and run tested on x86_64 Linux kernel with various CPU errata handling alternatives, with and without FineIBT patching.

Assisted-by LLM [tests]

gcc/ChangeLog:

* common.opt (fsanitize-kcfi-arity): New option.
* config/i386/i386.h: KCFI enables TARGET_INDIRECT_BRANCH_REGISTER.
* config/i386/i386-protos.h: Update ix86_output_call_insn.
* config/i386/i386-expand.cc (ix86_expand_call): Expand indirect calls into KCFI RTL.
* config/i386/i386.cc (ix86_kcfi_mask_type_id): New function. (ix86_output_call_insn): Emit KCFI assembly.
* config/i386/i386.md: Add KCFI RTL substitution patterns.
* doc/invoke.texi: Document x86 nuances.
* opts.cc (common_handle_option): Reset flag_sanitize_kcfi_arity.

gcc/testsuite/ChangeLog:

* gcc.dg/kcfi/kcfi-adjacency.c: Add x86 patterns.
* gcc.dg/kcfi/kcfi-basics.c: Add x86 patterns.
* gcc.dg/kcfi/kcfi-call-sharing.c: Add x86 patterns.
* gcc.dg/kcfi/kcfi-complex-addressing.c: Add x86 patterns.
* gcc.dg/kcfi/kcfi-direct-call-shapes.c: Add x86 patterns.
* gcc.dg/kcfi/kcfi-move-preservation.c: Add x86 patterns.
* gcc.dg/kcfi/kcfi-no-sanitize-inline.c: Add x86 patterns.
* gcc.dg/kcfi/kcfi-no-sanitize.c: Add x86 patterns.
* gcc.dg/kcfi/kcfi-offset-validation.c: Add x86 patterns.
* gcc.dg/kcfi/kcfi-patchable-entry-only.c: Add x86 patterns.
* gcc.dg/kcfi/kcfi-patchable-large.c: Add x86 patterns.
* gcc.dg/kcfi/kcfi-patchable-medium.c: Add x86 patterns.
* gcc.dg/kcfi/kcfi-patchable-prefix-only.c: Add x86 patterns.
* gcc.dg/kcfi/kcfi-tail-calls.c: Add x86 tail-call patterns.
* gcc.dg/kcfi/kcfi-trap-section.c: Add x86 trap patterns.
* gcc.dg/kcfi/kcfi-trap-section-per-func.c: New test.
* gcc.dg/kcfi/kcfi-x86-32bit.c: New test.
* gcc.dg/kcfi/kcfi-x86-arity.c: New test.
* gcc.dg/kcfi/kcfi-x86-endbr-collision.c: New test.
* gcc.dg/kcfi/kcfi-x86-fixed-r10.c: New test.
* gcc.dg/kcfi/kcfi-x86-fixed-r11.c: New test.
* gcc.dg/kcfi/kcfi-x86-retpoline-r11.c: New test.

---
 gcc/config/i386/i386-protos.h                 |   2 +-
 gcc/config/i386/i386.h                        |   3 +-
 gcc/config/i386/i386.md                       |  63 ++++--
 gcc/config/i386/i386-expand.cc                |  28 ++-
 gcc/config/i386/i386.cc                       | 210 +++++++++++++++++-
 gcc/doc/invoke.texi                           |  46 ++++
 gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c    |  17 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c       |  21 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c |  15 ++
 .../gcc.dg/kcfi/kcfi-complex-addressing.c     |  18 ++
 .../gcc.dg/kcfi/kcfi-direct-call-shapes.c     |   1 +
 .../gcc.dg/kcfi/kcfi-move-preservation.c      |  19 ++
 .../gcc.dg/kcfi/kcfi-no-sanitize-inline.c     |  11 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c  |   5 +
 .../gcc.dg/kcfi/kcfi-offset-validation.c      |   5 +
 .../gcc.dg/kcfi/kcfi-patchable-entry-only.c   |  24 ++
 .../gcc.dg/kcfi/kcfi-patchable-large.c        |  13 ++
 .../gcc.dg/kcfi/kcfi-patchable-medium.c       |  20 ++
 .../gcc.dg/kcfi/kcfi-patchable-prefix-only.c  |  21 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c   |  20 ++
 .../gcc.dg/kcfi/kcfi-trap-section-per-func.c  |  23 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c |   6 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-32bit.c    |   7 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-arity.c    |  93 ++++++++
 .../gcc.dg/kcfi/kcfi-x86-endbr-collision.c    |  55 +++++
 .../gcc.dg/kcfi/kcfi-x86-fixed-r10.c          |   7 +
 .../gcc.dg/kcfi/kcfi-x86-fixed-r11.c          |   7 +
 .../gcc.dg/kcfi/kcfi-x86-retpoline-r11.c      |  40 ++++
 gcc/common.opt                                |   8 +
 gcc/opts.cc                                   |   1 +
 30 files changed, 782 insertions(+), 27 deletions(-)
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section-per-func.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-32bit.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-arity.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-endbr-collision.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-fixed-r10.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-fixed-r11.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-x86-retpoline-r11.c
gcc/config/i386/i386-protos.h +1 -1
index 4e56bf70c8d5..dbf40eaa3c67 100644
@@ -376,7 +376,7 @@ extern enum attr_cpu ix86_schedule;
 #endif
 
 extern bool ix86_nopic_noplt_attribute_p (rtx call_op);
-extern const char * ix86_output_call_insn (rtx_insn *insn, rtx call_op);
+extern const char * ix86_output_call_insn (rtx_insn *insn, rtx *operands);
 extern const char * ix86_output_indirect_jmp (rtx call_op);
 extern const char * ix86_output_function_return (bool long_p);
 extern const char * ix86_output_indirect_function_return (rtx ret_op);
gcc/config/i386/i386.h +2 -1
index 47725c560906..678aff983bcb 100644
@@ -3108,7 +3108,8 @@ extern void debug_dispatch_window (int);
 
 #define TARGET_INDIRECT_BRANCH_REGISTER \
   (ix86_indirect_branch_register \
-   || cfun->machine->indirect_branch_type != indirect_branch_keep)
+   || cfun->machine->indirect_branch_type != indirect_branch_keep \
+   || (flag_sanitize & SANITIZE_KCFI))
 
 #define IX86_HLE_ACQUIRE (1 << 16)
 #define IX86_HLE_RELEASE (1 << 17)
gcc/config/i386/i386.md +43 -20

167 lines not on this page · raw message

gcc/config/i386/i386-expand.cc +25 -3
index 9e112d017345..a93f81f29518 100644
@@ -94,6 +94,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "i386-builtins.h"
 #include "i386-expand.h"
 #include "asan.h"
+#include "kcfi.h"
 #include "function-abi.h"
 
 /* Split one or more double-mode RTL references into pairs of half-mode
@@ -11348,9 +11349,10 @@ ix86_expand_call (rtx retval, rtx fnaddr, rtx callarg1,
   rtx vec[3];
   rtx use = NULL, call;
   unsigned int vec_len = 0;
+  bool is_direct_call = SYMBOL_REF_P (XEXP (fnaddr, 0));
   tree fndecl;
 
-  if (SYMBOL_REF_P (XEXP (fnaddr, 0)))
+  if (is_direct_call)
     {
       fndecl = SYMBOL_REF_DECL (XEXP (fnaddr, 0));
       if (fndecl)
@@ -11374,7 +11376,7 @@ ix86_expand_call (rtx retval, rtx fnaddr, rtx callarg1,
   if (TARGET_MACHO && !TARGET_64BIT)
     {
 #if TARGET_MACHO
-      if (flag_pic && SYMBOL_REF_P (XEXP (fnaddr, 0)))
+      if (flag_pic && is_direct_call)
 	fnaddr = machopic_indirect_call_target (fnaddr);
 #endif
     }
@@ -11458,7 +11460,7 @@ ix86_expand_call (rtx retval, rtx fnaddr, rtx callarg1,
   if (ix86_cmodel == CM_LARGE_PIC
       && !TARGET_PECOFF
       && MEM_P (fnaddr)
-      && SYMBOL_REF_P (XEXP (fnaddr, 0))
+      && is_direct_call
       && !local_symbolic_operand (XEXP (fnaddr, 0), VOIDmode))
     fnaddr = gen_rtx_MEM (QImode, construct_plt_address (XEXP (fnaddr, 0)));
   /* Since x32 GOT slot is 64 bit with zero upper 32 bits, indirect
@@ -11490,6 +11492,26 @@ ix86_expand_call (rtx retval, rtx fnaddr, rtx callarg1,
 
   call = gen_rtx_CALL (VOIDmode, fnaddr, callarg1);
 
+  /* Only indirect calls need KCFI instrumentation.  After address
+     legitimization an indirect target is a REG; every symbolic form
+     (SYMBOL_REF, LABEL_REF, CONST) is a direct call.  Use a strict
+     REG_P check here rather than the broader is_direct_call (which is
+     SYMBOL_REF_P and is shared with PIC/PLT logic) so that direct calls
+     that are not SYMBOL_REF are not wrongly wrapped.  */
+  rtx kcfi_type_rtx = REG_P (XEXP (fnaddr, 0))
+    ? kcfi_get_type_id_for_expanding_gimple_call ()
+    : NULL_RTX;
+  if (kcfi_type_rtx)
+    {
+      /* Wrap call with KCFI.  */
+      call = gen_rtx_KCFI (VOIDmode, call, kcfi_type_rtx);
+
+      /* Add KCFI clobbers for the insn sequence.  */
+      clobber_reg (&use, gen_rtx_REG (DImode, R10_REG));
+      clobber_reg (&use, gen_rtx_REG (DImode, R11_REG));
+      clobber_reg (&use, gen_rtx_REG (CCmode, FLAGS_REG));
+    }
+
   if (retval)
     call = gen_rtx_SET (retval, call);
   vec[vec_len++] = call;
gcc/config/i386/i386.cc +208 -2

237 lines not on this page · raw message

gcc/doc/invoke.texi +46 -0

52 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c +17 -0
index 7c1cff986c01..7c59921e630c 100644
@@ -46,4 +46,21 @@ __attribute__((noinline)) void test_conditional_call(int flag) {
     }
 }
 
+/*
+** test_complex_args: { target x86_64-*-* }
+** ...
+** movl	\$-?[0-9]+, %r10d
+** addl	-4\((%r[a-z0-9]+)\), %r10d
+** je	.Lkcfi_call([0-9]+)
+** .Lkcfi_trap([0-9]+):
+** ud2
+** .section	.kcfi_traps,"ao",@progbits,.text
+** .Lkcfi_entry([0-9]+):
+** .long	.Lkcfi_trap\3-.Lkcfi_entry\4
+** .text
+** .Lkcfi_call\2:
+** jmp	\*\1
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.L.*|\.section|\.text} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c +21 -0
index ca833fed2971..fe0a21d26df9 100644
@@ -1,5 +1,6 @@
 /* Test basic KCFI functionality - preamble generation.  */
 /* { dg-do compile } */
+/* { dg-additional-options "-falign-functions=16" { target x86_64-*-* } } */
 
 /* Extern function declarations - should NOT get KCFI preambles.  */
 extern void external_func(void);
@@ -55,6 +56,26 @@ int main() {
 /* Function with nocf_check attribute should NOT have preamble.  */
 /* { dg-final { scan-assembler-not {__cfi_nocf_check_function:} } } */
 
+/* x86_64: Verify type ID in preamble (after NOPs, before function label) */
+/* { dg-final { scan-assembler {__cfi_regular_function:\n\t+nop\n.*\n\t+movl\t+\$0x[0-9a-f]+, %eax} { target x86_64-*-* } } } */
+
+/*
+** static_caller: { target x86_64-*-* }
+** ...
+** movl	\$-?[0-9]+, %r10d
+** addl	-4\((%r[a-z0-9]+)\), %r10d
+** je	.Lkcfi_call([0-9]+)
+** .Lkcfi_trap([0-9]+):
+** ud2
+** .section	.kcfi_traps,"ao",@progbits,.text
+** .Lkcfi_entry([0-9]+):
+** .long	.Lkcfi_trap\3-.Lkcfi_entry\4
+** .text
+** .Lkcfi_call\2:
+** call	\*\1
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.L.*|\.section|\.text} } } */
 
 /* Extern functions should NOT get KCFI preambles.  */
gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c +15 -0
index f72344f77124..05165f0e2851 100644
@@ -59,3 +59,18 @@ int test_kcfi_check_sharing(struct kobject *kobj, const struct attribute_group *
    Should see:
    1. KCFI check for is_visible call with is_visible type ID A.
    2. KCFI check for is_bin_visible and is_bin_visible_again call with type ID B.  */
+
+/* Verify we have TWO different KCFI check sequences.  */
+/* Each check should have different type ID constants.  */
+/* x86: { dg-final { scan-assembler-times {movl\s+\$-?[0-9]+,\s+%r10d} 2 { target i?86-*-* x86_64-*-* } } } */
+
+/* Verify the checks use DIFFERENT type IDs (not shared).
+   We should NOT see the same type ID used twice - that would indicate
+   unmerged sharing.  */
+/* x86: { dg-final { scan-assembler-not {movl\s+\$(-?[0-9]+),\s+%r10d.*movl\s+\$\1,\s+%r10d} { target i?86-*-* x86_64-*-* } } } */
+
+/* Verify expected number of traps.  */
+/* x86: { dg-final { scan-assembler-times {ud2} 2 { target i?86-*-* x86_64-*-* } } } */
+
+/* Verify 2 separate call sites.  */
+/* x86: { dg-final { scan-assembler-times {jmp\s+\*%[a-z0-9]+} 2 { target i?86-*-* x86_64-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-complex-addressing.c +18 -0
index c48b8d7ad552..ed415033c5c9 100644
@@ -128,4 +128,22 @@ int main() {
     return result;
 }
 
+/* Standard KCFI handling.  */
+/*
+** test_struct_members: { target x86_64-*-* }
+** ...
+** movl	\$-?[0-9]+, %r10d
+** addl	-4\((%r[a-z0-9]+)\), %r10d
+** je	.Lkcfi_call([0-9]+)
+** .Lkcfi_trap([0-9]+):
+** ud2
+** .section	.kcfi_traps,"ao",@progbits,.text
+** .Lkcfi_entry([0-9]+):
+** .long	.Lkcfi_trap\3-.Lkcfi_entry\4
+** .text
+** .Lkcfi_call\2:
+** call	\*\1
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.L.*|\.section|\.text} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-direct-call-shapes.c +1 -0
index 4fce0771a55d..cda9bf6c82b8 100644
@@ -26,3 +26,4 @@ void caller(int sel, void (*ip)(int), int x) {
 
 /* Per-arch dg-final patterns are added by each arch's KCFI implementation
    commit; the invariant is "exactly one typeid load = one indirect call".  */
+/* { dg-final { scan-assembler-times {addl\t-4\(%r[a-z0-9]+\), %r10d} 1 { target x86_64-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-move-preservation.c +19 -0
index 7d58fef3f920..5553ff47174b 100644
@@ -38,4 +38,23 @@ int main(void)
     return 0;
 }
 
+/*
+** indirect_call: { target x86_64-*-* }
+** ...
+** movq	%rdi, (%rax)
+** movl	\$called_count, %edi
+** movl	\$-?[0-9]+, %r10d
+** addl	-4\(\1\), %r10d
+** je	.Lkcfi_call([0-9]+)
+** .Lkcfi_trap([0-9]+):
+** ud2
+** .section	.kcfi_traps,"ao",@progbits,.text
+** .Lkcfi_entry([0-9]+):
+** .long	.Lkcfi_trap\3-.Lkcfi_entry\4
+** .text
+** .Lkcfi_call\2:
+** jmp	\*\1
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.L.*|\.section|\.text} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize-inline.c +11 -0
index 4a90390d1934..9ed7e21fe8eb 100644
@@ -72,3 +72,14 @@ int main(void)
 
     return 0;
 }
+
+/* Verify correct number of KCFI checks: exactly 2 */
+/* { dg-final { scan-assembler-times {ud2} 2 { target x86_64-*-* } } } */
+
+/* Positive controls: these should have KCFI checks.  */
+/* { dg-final { scan-assembler {normal_function:.*ud2.*\.size\s+normal_function} { target x86_64-*-* } } } */
+/* { dg-final { scan-assembler {wrap_normal_inline:.*ud2.*\.size\s+wrap_normal_inline} { target x86_64-*-* } } } */
+
+/* Negative controls: these should NOT have KCFI checks.  */
+/* { dg-final { scan-assembler-not {sensitive_non_inline_function:.*ud2.*\.size\s+sensitive_non_inline_function} { target x86_64-*-* } } } */
+/* { dg-final { scan-assembler-not {wrap_sensitive_inline:.*ud2.*\.size\s+wrap_sensitive_inline} { target x86_64-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c +5 -0
index 124d26488635..95a8e8419e00 100644
@@ -29,3 +29,8 @@ int main() {
 /* { dg-final { scan-assembler "__cfi_caller_with_checks:" } } */
 /* { dg-final { scan-assembler "__cfi_caller_no_checks:" } } */
 /* { dg-final { scan-assembler "__cfi_main:" } } */
+
+/* caller_with_checks() should generate KCFI check.
+   caller_no_checks() should NOT generate KCFI check (no_sanitize).
+   So a total of exactly 1 KCFI check in the entire program.  */
+/* { dg-final { scan-assembler-times {addl\t-4\(%r[ad]x\), %r1[01]d} 1 { target x86_64-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-offset-validation.c +5 -0
index 213a1a2892a5..97d964feebd3 100644
@@ -1,5 +1,6 @@
 /* Test KCFI call-site offset validation across architectures.  */
 /* { dg-do compile } */
+/* { dg-additional-options "-falign-functions=16" { target x86_64-*-* } } */
 
 void target_func_a(void) { }
 void target_func_b(int x) { }
@@ -22,3 +23,7 @@ int main() {
 /* { dg-final { scan-assembler "__cfi_target_func_a:" } } */
 /* { dg-final { scan-assembler "__cfi_target_func_b:" } } */
 /* { dg-final { scan-assembler "__cfi_target_func_c:" } } */
+
+/* x86_64: All call sites should use -4 offset for KCFI type ID loads, even
+   with -falign-functions=16 (we're not using patchable entries here).  */
+/* { dg-final { scan-assembler {movl\t\$-?[0-9]+, %r10d\n\taddl\t-4\(%r[a-z0-9]+\), %r10d} { target x86_64-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-entry-only.c +24 -0
index a6a2f4816fef..379356385a16 100644
@@ -1,6 +1,7 @@
 /* Test KCFI with patchable function entries - entry NOPs only.  */
 /* { dg-do compile } */
 /* { dg-additional-options "-fpatchable-function-entry=4,0" } */
+/* { dg-additional-options "-falign-functions=16" { target x86_64-*-* } } */
 
 void test_function(void) {
 }
@@ -11,4 +12,27 @@ int main() {
     return 0;
 }
 
+/*
+** __cfi_test_function: { target x86_64-*-* }
+** nop
+** nop
+** nop
+** nop
+** nop
+** nop
+** nop
+** nop
+** nop
+** nop
+** nop
+** movl	\$0x[0-9a-f]+, %eax
+*/
+
+/*
+** main: { target x86_64-*-* }
+** ...
+** addl	-4\(%r[a-z0-9]+\), %r10d
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-large.c +13 -0
index 8c4ec30cecc5..06df3495bb23 100644
@@ -1,6 +1,7 @@
 /* Test KCFI with large patchable function entries.  */
 /* { dg-do compile } */
 /* { dg-additional-options "-fpatchable-function-entry=11,11" } */
+/* { dg-additional-options "-falign-functions=16" { target x86_64-*-* } } */
 
 void test_function(void) {
 }
@@ -11,4 +12,16 @@ int main() {
     return 0;
 }
 
+/*
+** __cfi_test_function: { target x86_64-*-* }
+** movl	\$0x[0-9a-f]+, %eax
+*/
+
+/*
+** main: { target x86_64-*-* }
+** ...
+** addl	-15\(%r[a-z0-9]+\), %r10d
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-medium.c +20 -0
index 78a834ef2a97..ef87b135934b 100644
@@ -1,6 +1,7 @@
 /* Test KCFI with medium patchable function entries.  */
 /* { dg-do compile } */
 /* { dg-additional-options "-fpatchable-function-entry=8,4" } */
+/* { dg-additional-options "-falign-functions=16" { target x86_64-*-* } } */
 
 void test_function(void) {
 }
@@ -11,4 +12,23 @@ int main() {
     return 0;
 }
 
+/*
+** __cfi_test_function: { target x86_64-*-* }
+** nop
+** nop
+** nop
+** nop
+** nop
+** nop
+** nop
+** movl	\$0x[0-9a-f]+, %eax
+*/
+
+/*
+** main: { target x86_64-*-* }
+** ...
+** addl	-8\(%r[a-z0-9]+\), %r10d
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-prefix-only.c +21 -0
index 1a4d8269ed56..872814aa4171 100644
@@ -1,6 +1,7 @@
 /* Test KCFI with patchable function entries - prefix NOPs only.  */
 /* { dg-do compile } */
 /* { dg-additional-options "-fpatchable-function-entry=3,3" } */
+/* { dg-additional-options "-falign-functions=16" { target x86_64-*-* } } */
 
 void test_function(void) {
 }
@@ -11,4 +12,24 @@ int main() {
     return 0;
 }
 
+/*
+** __cfi_test_function: { target x86_64-*-* }
+** nop
+** nop
+** nop
+** nop
+** nop
+** nop
+** nop
+** nop
+** movl	\$0x[0-9a-f]+, %eax
+*/
+
+/*
+** main: { target x86_64-*-* }
+** ...
+** addl	-7\(%r[a-z0-9]+\), %r10d
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c +20 -0
index 9ddf178aa2b1..04a9eb1fd206 100644
@@ -58,3 +58,23 @@ int test_non_tail_indirect_call(func_ptr_t handler, int x) {
 /* { dg-final { scan-assembler-times "__cfi_test_param_indirect_call:" 1 } } */
 /* { dg-final { scan-assembler-times "__cfi_test_void_indirect_call:" 1 } } */
 /* { dg-final { scan-assembler-times "__cfi_test_non_tail_indirect_call:" 1 } } */
+
+/* Should have exactly 4 KCFI checks for indirect calls as
+   (load type ID + compare).  */
+/* { dg-final { scan-assembler-times {movl\t\$-?[0-9]+, %r10d} 4 { target x86_64-*-* } } } */
+/* { dg-final { scan-assembler-times {addl\t-4\(%r[a-z0-9]+\), %r10d} 4 { target x86_64-*-* } } } */
+
+/* Should have exactly 4 trap sections and 4 trap instructions.  */
+/* { dg-final { scan-assembler-times "\\.kcfi_traps" 4 { target x86_64-*-* } } } */
+/* { dg-final { scan-assembler-times "ud2" 4 { target x86_64-*-* } } } */
+
+/* Should NOT have unprotected direct jumps to vtable.  */
+/* { dg-final { scan-assembler-not {jmp\t\*vtable\(%rip\)} { target x86_64-*-* } } } */
+/* { dg-final { scan-assembler-not {jmp\t\*vtable\+8\(%rip\)} { target x86_64-*-* } } } */
+
+/* Should have exactly 3 protected tail calls (jmp through register after
+   KCFI check).  */
+/* { dg-final { scan-assembler-times {jmp\t\*%[a-z0-9]+} 3 { target x86_64-*-* } } } */
+
+/* Should have exactly 1 regular call (non-tail call case).  */
+/* { dg-final { scan-assembler-times {call\t\*%[a-z0-9]+} 1 { target x86_64-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section-per-func.c new file +23 -0
new file mode 100644
index 000000000000..448805a37808
@@ -0,0 +1,23 @@
+/* The .kcfi_traps section is SHF_LINK_ORDER and must be tied to the
+   containing function's own text section, not the generic .text.  When it
+   links to the generic .text, building with -ffunction-sections and
+   -Wl,--gc-sections silently drops the entire .kcfi_traps section (losing all
+   KCFI trap metadata, even for retained functions), because the empty generic
+   .text is garbage-collected and the link-ordered section goes with it.
+
+   Only x86_64 and RISC-V use a .kcfi_traps section; AArch64 and ARM encode the
+   trap information directly in the trap instruction's immediate.  */
+
+/* { dg-do compile { target x86_64-*-* } } */
+/* { dg-additional-options "-ffunction-sections" } */
+
+typedef int (*fn_t) (int);
+volatile fn_t ptr;
+
+int caller (int x) { return ptr (x); }
+
+/* Under -ffunction-sections the link-ordered target must be the function's
+   own text section (.text.caller), not the generic .text (which would be
+   garbage-collected, dropping the trap metadata).  */
+/* { dg-final { scan-assembler {\.kcfi_traps,"ao",@progbits,\.text\.caller\n} } } */
+/* { dg-final { scan-assembler-not {\.kcfi_traps,"ao",@progbits,\.text\n} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c +6 -0
index 6d34ad6e1a0c..55c0829ccd7b 100644
@@ -15,3 +15,9 @@ int main() {
 
 /* Should have KCFI preamble.  */
 /* { dg-final { scan-assembler "__cfi_target_function:" } } */
+
+/* Should have exactly 2 trap labels in code.  */
+/* { dg-final { scan-assembler-times {\.L[^:]+:\n\s*ud2} 2 { target x86_64-*-* } } } */
+
+/* x86_64 should exactly 2 .kcfi_traps sections.  */
+/* { dg-final { scan-assembler-times {\.section\t\.kcfi_traps,"ao",@progbits,\.text} 2 { target x86_64-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-x86-32bit.c new file +7 -0
new file mode 100644
index 000000000000..3bbceb2925c5
@@ -0,0 +1,7 @@
+/* Test that KCFI is rejected for 32-bit x86.  */
+/* { dg-do compile { target i?86-*-* x86_64-*-* } } */
+/* { dg-additional-options "-m32" } */
+/* { dg-error ".-fsanitize=kcfi. is not supported for 32-bit x86 or x32 mode" "" { target *-*-* } 0 } */
+/* { dg-message "sorry, unimplemented: .-fsanitize=kcfi. not supported" "" { target *-*-* } 0 } */
+
+void foo (void) { }
gcc/testsuite/gcc.dg/kcfi/kcfi-x86-arity.c new file +93 -0

93 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-x86-endbr-collision.c new file +55 -0

55 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-x86-fixed-r10.c new file +7 -0
new file mode 100644
index 000000000000..d0879d161599
@@ -0,0 +1,7 @@
+/* Test that KCFI is incompatible with -ffixed-r10 on x86_64.  */
+/* { dg-do compile { target x86_64-*-* } } */
+/* { dg-additional-options "-ffixed-r10" } */
+/* { dg-error ".-fsanitize=kcfi. is not compatible with .-ffixed-r10. or .-ffixed-r11. as KCFI requires these registers for type checking" "" { target *-*-* } 0 } */
+/* { dg-message "sorry, unimplemented: .-fsanitize=kcfi. not supported" "" { target *-*-* } 0 } */
+
+void foo (void) { }
gcc/testsuite/gcc.dg/kcfi/kcfi-x86-fixed-r11.c new file +7 -0
new file mode 100644
index 000000000000..465f2cad6285
@@ -0,0 +1,7 @@
+/* Test that KCFI is incompatible with -ffixed-r11 on x86_64.  */
+/* { dg-do compile { target x86_64-*-* } } */
+/* { dg-additional-options "-ffixed-r11" } */
+/* { dg-error ".-fsanitize=kcfi. is not compatible with .-ffixed-r10. or .-ffixed-r11. as KCFI requires these registers for type checking" "" { target *-*-* } 0 } */
+/* { dg-message "sorry, unimplemented: .-fsanitize=kcfi. not supported" "" { target *-*-* } 0 } */
+
+void foo (void) { }
gcc/testsuite/gcc.dg/kcfi/kcfi-x86-retpoline-r11.c new file +40 -0
new file mode 100644
index 000000000000..056068b4f197
@@ -0,0 +1,40 @@
+/* Test KCFI with retpoline thunk-extern flag forces r11 usage.  */
+/* { dg-do compile { target x86_64-*-* } } */
+/* { dg-additional-options "-O2 -mindirect-branch=thunk-extern" } */
+
+extern int external_target(void);
+
+/* Test regular call (not tail call) */
+__attribute__((noinline))
+int call_test(int (*func_ptr)(void)) {
+    /* This indirect call should use r11 when both KCFI and
+       -mindirect-branch=thunk-extern are enabled.  */
+    int result = func_ptr();  /* Function parameter prevents direct optimization.  */
+    return result + 1;  /* Prevent tail call optimization.  */
+}
+
+/* Reference external_target to generate the required symbol.  */
+int (*external_func_ptr)(void) = external_target;
+
+/* Test function for sibcalls (tail calls) */
+__attribute__((noinline))
+void sibcall_test(int (**func_ptr)(void)) {
+    /* This sibcall should use r11 when both KCFI and
+       -mindirect-branch=thunk-extern are enabled.  */
+    (*func_ptr)();  /* Tail call - should be optimized to sibcall.  */
+}
+
+/* Should have weak symbol for external function.  */
+/* { dg-final { scan-assembler "__kcfi_typeid_external_target" } } */
+
+/* When both KCFI and -mindirect-branch=thunk-extern are enabled,
+   indirect calls should always use r11 register and convert to extern thunks.  */
+/* { dg-final { scan-assembler-times {call\s+} 1 } } */
+/* { dg-final { scan-assembler-times {call\s+__x86_indirect_thunk_r11} 1 } } */
+
+/* Sibcalls should also use r11 register and convert to extern thunks.  */
+/* { dg-final { scan-assembler-times {jmp\s+} 1 } } */
+/* { dg-final { scan-assembler-times {jmp\s+__x86_indirect_thunk_r11} 1 } } */
+
+/* Should have exactly 2 KCFI traps (one per function) */
+/* { dg-final { scan-assembler-times {ud2} 2 } } */
gcc/common.opt +8 -0
index 69a55b8d40d6..1dde799a932c 100644
@@ -1165,6 +1165,14 @@ Enum(sanitize_coverage) String(trace-pc) Value(SANITIZE_COV_TRACE_PC)
 EnumValue
 Enum(sanitize_coverage) String(trace-cmp) Value(SANITIZE_COV_TRACE_CMP)
 
+fsanitize-kcfi-arity
+Common Driver Var(flag_sanitize_kcfi_arity)
+For supported targets, this feature extends kCFI by telling the compiler
+to record information about each indirect-callable function’s
+arity (i.e., the number of arguments passed in registers) into the
+binary.  Some kernel CFI techniques, such as FineIBT, may be able to use
+this information to provide enhanced security.
+
 fasan-shadow-offset=
 Common Joined RejectNegative Var(common_deferred_options) Defer
 -fasan-shadow-offset=<number>	Use custom shadow memory offset.
gcc/opts.cc +1 -0
index ad1fd54d2792..6382550110ac 100644
@@ -2853,6 +2853,7 @@ common_handle_option (struct gcc_options *opts,
 	  SET_OPTION_IF_UNSET (opts, opts_set, param_asan_stack, 0);
 	  SET_OPTION_IF_UNSET (opts, opts_set, param_asan_protect_allocas, 0);
 	  SET_OPTION_IF_UNSET (opts, opts_set, param_asan_use_after_return, 0);
+	  SET_OPTION_IF_UNSET (opts, opts_set, flag_sanitize_kcfi_arity, 0);
 	}
       if (opts->x_flag_sanitize & SANITIZE_KERNEL_HWADDRESS)
 	{
Signature · 1 line
2.55.0
author
#8 lore raw

PATCH v17 5/7 aarch64: Add AArch64 Kernel Control Flow Integrity implementation

In reply to Kees Cook

Implement AArch64-specific KCFI backend.

- Trap debugging through ESR (Exception Syndrome Register) encoding in BRK instruction immediate values.

- Scratch register allocation using w16/w17 (x16/x17) following AArch64 procedure call standard for intra-procedure-call registers, which already makes x16/x17 available through existing clobbers.

Note that BTI uses x16/x17 AT the call site, and KCFI uses w16/w17 BEFORE the call (for the type hash comparison). These don't conflict because:
- KCFI clobbers w16/w17 with hash values.
- Then the actual call happens via blr %target_reg (whatever register the target is in).
- If SLS hardening is enabled, aarch64_indirect_call_asm will create a thunk that moves target into x16 and does br x16.
- By the time the SLS thunk uses x16, KCFI is already done with it.

- Complementary with BTI (which uses a separate pass system to inject landing instructions where needed).

- Does not interfere with SME, which uses attributes not function prototypes for distinguishing functions.

Assembly Code Pattern for AArch64:
ldur w16, [target, #-4] ; Load actual type ID from preamble
mov w17, #type_id_low ; Load expected type (lower 16 bits)
movk w17, #type_id_high, lsl #16 ; Load upper 16 bits if needed

  cmp  w16, w17                 ; Compare type IDs directly
  b.eq .Lpass                   ; Branch if types match
  .Ltrap: brk #esr_value        ; Enhanced trap with register info
  .Lpass: blr/br target         ; Execute validated indirect transfer

ESR (Exception Syndrome Register) Integration:
- BRK instruction immediate encoding format:
0x8000 | ((TypeIndex & 31) << 5) | (AddrIndex & 31)
- TypeIndex indicates which W register contains expected type (W17 = 17)
- AddrIndex indicates which X register contains target address (0-30)
- Example: brk #33313 (0x8221) = expected type in W17, target address in X1

Build and run tested with Linux kernel ARCH=arm64.

Assisted-by LLM [tests]

gcc/ChangeLog:

* config/aarch64/aarch64-protos.h (aarch64_output_kcfi_insn): Declare.
* config/aarch64/aarch64.cc (aarch64_expand_call): Wrap CALLs in KCFI, with clobbers.
(aarch64_indirect_branch_asm): New function, extract common logic for branch asm, like existing call asm helper. (aarch64_output_kcfi_insn): Emit KCFI assembly.
* config/aarch64/aarch64.md: Add KCFI RTL patterns and replace open-coded branch emission with aarch64_indirect_branch_asm.
* doc/invoke.texi: Document aarch64 nuances.

gcc/testsuite/ChangeLog:

* gcc.dg/kcfi/kcfi-aarch64-branch-range.c: New test.
* gcc.dg/kcfi/kcfi-aarch64-ilp32.c: New test.
* gcc.dg/kcfi/kcfi-aarch64-insn-length-sls.c: New test.
* gcc.dg/kcfi/kcfi-aarch64-insn-length.c: New test.
* gcc.dg/kcfi/kcfi-adjacency.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-basics.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-call-sharing.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-complex-addressing.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-direct-call-shapes.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-move-preservation.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-no-sanitize-inline.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-no-sanitize.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-offset-validation.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-patchable-entry-only.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-patchable-large.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-patchable-medium.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-patchable-prefix-only.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-tail-calls.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-trap-section.c: Add aarch64 patterns.
* gcc.dg/kcfi/kcfi-trap-encoding.c: New test.

---
 gcc/config/aarch64/aarch64-protos.h           |   3 +
 gcc/config/aarch64/aarch64.md                 |  66 +++++++++
 gcc/config/aarch64/aarch64.cc                 | 127 ++++++++++++++++++
 gcc/doc/invoke.texi                           |  14 ++
 .../gcc.dg/kcfi/kcfi-aarch64-branch-range.c   |  29 ++++
 .../gcc.dg/kcfi/kcfi-aarch64-ilp32.c          |   7 +
 .../kcfi/kcfi-aarch64-insn-length-sls.c       |  32 +++++
 .../gcc.dg/kcfi/kcfi-aarch64-insn-length.c    |  38 ++++++
 gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c    |  20 +++
 gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c       |  21 +++
 gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c |   4 +
 .../gcc.dg/kcfi/kcfi-complex-addressing.c     |  16 +++
 .../gcc.dg/kcfi/kcfi-direct-call-shapes.c     |   3 +
 .../gcc.dg/kcfi/kcfi-move-preservation.c      |  20 +++
 .../gcc.dg/kcfi/kcfi-no-sanitize-inline.c     |   5 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c  |   1 +
 .../gcc.dg/kcfi/kcfi-offset-validation.c      |   3 +
 .../gcc.dg/kcfi/kcfi-patchable-entry-only.c   |  12 ++
 .../gcc.dg/kcfi/kcfi-patchable-large.c        |  12 ++
 .../gcc.dg/kcfi/kcfi-patchable-medium.c       |  12 ++
 .../gcc.dg/kcfi/kcfi-patchable-prefix-only.c  |  12 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c   |  21 +++
 .../gcc.dg/kcfi/kcfi-trap-encoding.c          |  43 ++++++
 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c |   4 +
 24 files changed, 525 insertions(+)
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-branch-range.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-ilp32.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-insn-length-sls.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-insn-length.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-encoding.c
gcc/config/aarch64/aarch64-protos.h +3 -0
index e8ae3d427949..af00040b7abe 100644
@@ -1316,4 +1316,7 @@ extern unsigned aarch64_stack_alignment (const_tree exp, unsigned align);
 extern rtx aarch64_gen_compare_zero_and_branch (rtx_code code, rtx x,
 						rtx_code_label *label);
 
+/* KCFI support.  */
+extern const char *aarch64_output_kcfi_insn (rtx_insn *insn, rtx *operands);
+
 #endif /* GCC_AARCH64_PROTOS_H */
gcc/config/aarch64/aarch64.md +66 -0

90 lines not on this page · raw message

gcc/config/aarch64/aarch64.cc +127 -0

145 lines not on this page · raw message

gcc/doc/invoke.texi +14 -0
index da258175b497..ee8b48a68517 100644
@@ -17597,6 +17597,20 @@ header MOVri instruction would become something like this:
 
 @code{movl    $199571451, %ebx	# hash of foo's type = 0xBE537FB}
 
+On AArch64, KCFI type identifiers are emitted as a @code{.word ID}
+directive (a 32-bit constant) before the function entry.  AArch64's
+natural 4-byte instruction alignment eliminates the need for additional
+alignment NOPs.  When used with @option{-fpatchable-function-entry}, the
+type identifier is placed before any prefix NOPs.  The runtime check
+uses @code{x16} and @code{x17} as scratch registers.  Type mismatches
+trigger a @code{brk} instruction with an immediate value that encodes
+both the expected type register index and the target address register
+index in the format @code{0x8000 | (type_reg << 5) | addr_reg}.  This
+encoding is captured in the ESR (Exception Syndrome Register) when the
+trap is taken, allowing the kernel to identify both the KCFI violation
+and the involved registers for detailed diagnostics (eliminating the need
+for a separate @code{.kcfi_traps} section as used on x86_64).
+
 KCFI is intended primarily for kernel code and may not be suitable
 for user-space applications that rely on techniques incompatible
 with strict type checking of indirect calls.
gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-branch-range.c new file +29 -0
new file mode 100644
index 000000000000..52a5866c59a8
@@ -0,0 +1,29 @@
+/* Test that the AArch64 KCFI call patterns account for the length of the
+   whole check sequence.  If each KCFI call is counted as one 4-byte
+   instruction, the tbz skipping the block below is assumed to be in range
+   (+-32KiB), and the assembler rejects it.  See kcfi-aarch64-insn-length*.c
+   for the sibling call patterns.  */
+/* { dg-do assemble { target aarch64*-*-* } } */
+/* { dg-additional-options "-O2" } */
+
+typedef void (*fn_t) (void);
+extern fn_t tbl[2048];
+
+#define C1(i) tbl[(i)] ();
+#define C4(i) C1(i) C1((i)+1) C1((i)+2) C1((i)+3)
+#define C16(i) C4(i) C4((i)+4) C4((i)+8) C4((i)+12)
+#define C64(i) C16(i) C16((i)+16) C16((i)+32) C16((i)+48)
+#define C256(i) C64(i) C64((i)+64) C64((i)+128) C64((i)+192)
+#define C1024(i) C256(i) C256((i)+256) C256((i)+512) C256((i)+768)
+
+/* About 1280 KCFI calls: roughly 41KiB of code, but only 10KiB if each
+   call is counted as 4 bytes.  */
+void
+calls (unsigned long x)
+{
+  if (x & 1)
+    {
+      C1024 (0)
+      C256 (1024)
+    }
+}
gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-ilp32.c new file +7 -0
new file mode 100644
index 000000000000..aff560020c7e
@@ -0,0 +1,7 @@
+/* Test that KCFI is rejected for AArch64 ILP32.  */
+/* { dg-do compile { target aarch64*-*-* } } */
+/* { dg-additional-options "-mabi=ilp32 -Wno-deprecated" } */
+/* { dg-error ".-fsanitize=kcfi. is not supported for .-mabi=ilp32." "" { target *-*-* } 0 } */
+/* { dg-message "sorry, unimplemented: .-fsanitize=kcfi. not supported" "" { target *-*-* } 0 } */
+
+void foo (void) { }
gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-insn-length-sls.c new file +32 -0
new file mode 100644
index 000000000000..4164efcb5d0e
@@ -0,0 +1,32 @@
+/* Test the AArch64 KCFI sibling call length with straight-line speculation
+   hardening, which adds a barrier after the br: sb (4 bytes) when SB is
+   available, otherwise dsb sy; isb (8 bytes).  Calls are unaffected.  */
+/* { dg-do compile { target aarch64*-*-* } } */
+/* { dg-additional-options "-O2 -dp -mharden-sls=retbr" } */
+
+typedef void (*vfn_t) (void);
+
+__attribute__ ((target ("arch=armv8-a")))
+void
+sibcall_no_sb (vfn_t f)
+{
+  f ();
+}
+
+__attribute__ ((target ("arch=armv8-a+sb")))
+void
+sibcall_sb (vfn_t f)
+{
+  f ();
+}
+
+int
+call (vfn_t f)
+{
+  f ();
+  return 0;
+}
+
+/* { dg-final { scan-assembler-times {\[c=[0-9]+ l=36\]  \*sibcall_insn\n} 1 } } */
+/* { dg-final { scan-assembler-times {\[c=[0-9]+ l=32\]  \*sibcall_insn\n} 1 } } */
+/* { dg-final { scan-assembler-times {\[c=[0-9]+ l=28\]  \*call_insn\n} 1 } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-insn-length.c new file +38 -0
new file mode 100644
index 000000000000..3a0ee389ef8a
@@ -0,0 +1,38 @@
+/* Test that the AArch64 KCFI call patterns report the length of the whole
+   check sequence (ldur, mov, movk, cmp, b.eq, brk, blr/br: 28 bytes), so
+   that branch shortening sees their true size.  */
+/* { dg-do compile { target aarch64*-*-* } } */
+/* { dg-additional-options "-O2 -dp" } */
+
+typedef void (*vfn_t) (void);
+typedef int (*ifn_t) (void);
+
+void
+call (vfn_t f)
+{
+  f ();
+  f ();
+}
+
+int
+call_value (ifn_t f)
+{
+  return f () + 1;
+}
+
+void
+sibcall (vfn_t f)
+{
+  f ();
+}
+
+int
+sibcall_value (ifn_t f)
+{
+  return f ();
+}
+
+/* { dg-final { scan-assembler-times {\[c=[0-9]+ l=28\]  \*call_insn\n} 1 } } */
+/* { dg-final { scan-assembler-times {\[c=[0-9]+ l=28\]  \*call_value_insn\n} 1 } } */
+/* { dg-final { scan-assembler-times {\[c=[0-9]+ l=28\]  \*sibcall_insn\n} 2 } } */
+/* { dg-final { scan-assembler-times {\[c=[0-9]+ l=28\]  \*sibcall_value_insn\n} 1 } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c +20 -0
index 7c59921e630c..47a33bf6393b 100644
@@ -63,4 +63,24 @@ __attribute__((noinline)) void test_conditional_call(int flag) {
 ** ...
 */
 
+/*
+** test_complex_args: { target aarch64*-*-* }
+** ...
+** ldur	w[0-9]+, \[(x[0-9]+), #-4\]
+** mov	w[0-9]+, #[0-9]+
+** movk	w[0-9]+, #[0-9]+, lsl #16
+** cmp	w[0-9]+, w[0-9]+
+** b.eq	.Lkcfi_call([0-9]+)
+** .Lkcfi_trap[0-9]+:
+** brk	#0x[0-9a-f]+
+** .Lkcfi_call\2:
+** br	\1
+** ...
+*/
+
+/* The typeid load must not clobber the call target: its destination
+   register must differ from the base (target) register.  "ldur wN, [xN,..."
+   (same register number) means the target was overwritten by the load.  */
+/* { dg-final { scan-assembler-not {ldur\tw([0-9]+), \[x\1,} { target aarch64*-*-* } } } */
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.L.*|\.section|\.text} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c +21 -0
index fe0a21d26df9..7f1c45f1fe94 100644
@@ -59,6 +59,9 @@ int main() {
 /* x86_64: Verify type ID in preamble (after NOPs, before function label) */
 /* { dg-final { scan-assembler {__cfi_regular_function:\n\t+nop\n.*\n\t+movl\t+\$0x[0-9a-f]+, %eax} { target x86_64-*-* } } } */
 
+/* AArch64: Verify type ID word in preamble.  */
+/* { dg-final { scan-assembler {__cfi_regular_function:\n\t\.word\t0x[0-9a-f]+} { target aarch64*-*-* } } } */
+
 /*
 ** static_caller: { target x86_64-*-* }
 ** ...
@@ -76,6 +79,21 @@ int main() {
 ** ...
 */
 
+/*
+** static_caller: { target aarch64*-*-* }
+** ...
+** ldur	w16, \[(x[0-9]+), #-4\]
+** mov	w17, #[0-9]+
+** movk	w17, #[0-9]+, lsl #16
+** cmp	w16, w17
+** b.eq	.Lkcfi_call([0-9]+)
+** .Lkcfi_trap[0-9]+:
+** brk	#0x[0-9a-f]+
+** .Lkcfi_call\2:
+** blr	\1
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.L.*|\.section|\.text} } } */
 
 /* Extern functions should NOT get KCFI preambles.  */
@@ -93,3 +111,6 @@ int main() {
 /* External functions that are only called directly should NOT get
    __kcfi_typeid_ symbols.  */
 /* { dg-final { scan-assembler-not {__kcfi_typeid_external_func_int} } } */
+
+/* AArch64 should NOT have trap section (use immediate instructions instead).  */
+/* { dg-final { scan-assembler-not {\.kcfi_traps} { target aarch64*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c +4 -0
index 05165f0e2851..c402a1678a73 100644
@@ -63,14 +63,18 @@ int test_kcfi_check_sharing(struct kobject *kobj, const struct attribute_group *
 /* Verify we have TWO different KCFI check sequences.  */
 /* Each check should have different type ID constants.  */
 /* x86: { dg-final { scan-assembler-times {movl\s+\$-?[0-9]+,\s+%r10d} 2 { target i?86-*-* x86_64-*-* } } } */
+/* AArch64: { dg-final { scan-assembler-times {mov\s+w17, #[0-9]+} 2 { target aarch64*-*-* } } } */
 
 /* Verify the checks use DIFFERENT type IDs (not shared).
    We should NOT see the same type ID used twice - that would indicate
    unmerged sharing.  */
 /* x86: { dg-final { scan-assembler-not {movl\s+\$(-?[0-9]+),\s+%r10d.*movl\s+\$\1,\s+%r10d} { target i?86-*-* x86_64-*-* } } } */
+/* AArch64: { dg-final { scan-assembler-not {mov\s+w17, #([0-9]+).*mov\s+w17, #\1} { target aarch64*-*-* } } } */
 
 /* Verify expected number of traps.  */
 /* x86: { dg-final { scan-assembler-times {ud2} 2 { target i?86-*-* x86_64-*-* } } } */
+/* AArch64: { dg-final { scan-assembler-times {brk\s+#0x[0-9a-f]+} 2 { target aarch64*-*-* } } } */
 
 /* Verify 2 separate call sites.  */
 /* x86: { dg-final { scan-assembler-times {jmp\s+\*%[a-z0-9]+} 2 { target i?86-*-* x86_64-*-* } } } */
+/* AArch64: { dg-final { scan-assembler-times {br\tx[0-9]+} 2 { target aarch64*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-complex-addressing.c +16 -0
index ed415033c5c9..0b23caa49ebb 100644
@@ -146,4 +146,20 @@ int main() {
 ** ...
 */
 
+/* Standard KCFI handling.  */
+/*
+** main: { target aarch64*-*-* }
+** ...
+** ldur	w16, \[(x[0-9]+), #-4\]
+** mov	w17, #[0-9]+
+** movk	w17, #[0-9]+, lsl #16
+** cmp	w16, w17
+** b.eq	.Lkcfi_call([0-9]+)
+** .Lkcfi_trap[0-9]+:
+** brk	#0x[0-9a-f]+
+** .Lkcfi_call\2:
+** blr	\1
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.L.*|\.section|\.text} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-direct-call-shapes.c +3 -0
index cda9bf6c82b8..6b4698447b7b 100644
@@ -27,3 +27,6 @@ void caller(int sel, void (*ip)(int), int x) {
 /* Per-arch dg-final patterns are added by each arch's KCFI implementation
    commit; the invariant is "exactly one typeid load = one indirect call".  */
 /* { dg-final { scan-assembler-times {addl\t-4\(%r[a-z0-9]+\), %r10d} 1 { target x86_64-*-* } } } */
+/* The typeid scratch register avoids the call target, so it is not always
+   w16 (a sibcall target lands in x16/x17, forcing the load into w9).  */
+/* { dg-final { scan-assembler-times {ldur\tw[0-9]+, \[x[0-9]+, #-4\]} 1 { target aarch64*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-move-preservation.c +20 -0
index 5553ff47174b..ad6130c9d323 100644
@@ -57,4 +57,24 @@ int main(void)
 ** ...
 */
 
+/*
+** indirect_call: { target aarch64*-*-* }
+** ...
+** mov	(x[0-9]+), x0
+** ...
+** ldur	w[0-9]+, \[\1, #-4\]
+** mov	w[0-9]+, #[0-9]+
+** movk	w[0-9]+, #[0-9]+, lsl #16
+** cmp	w[0-9]+, w[0-9]+
+** b.eq	.Lkcfi_call([0-9]+)
+** .Lkcfi_trap[0-9]+:
+** brk	#0x[0-9a-f]+
+** .Lkcfi_call\2:
+** br	\1
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.L.*|\.section|\.text} } } */
+
+/* AArch64 should NOT have trap section (use immediate instructions instead).  */
+/* { dg-final { scan-assembler-not {\.kcfi_traps} { target aarch64*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize-inline.c +5 -0
index 9ed7e21fe8eb..98591ed9b145 100644
@@ -75,11 +75,16 @@ int main(void)
 
 /* Verify correct number of KCFI checks: exactly 2 */
 /* { dg-final { scan-assembler-times {ud2} 2 { target x86_64-*-* } } } */
+/* { dg-final { scan-assembler-times {brk\s+#0x[0-9a-f]+} 2 { target aarch64*-*-* } } } */
 
 /* Positive controls: these should have KCFI checks.  */
 /* { dg-final { scan-assembler {normal_function:.*ud2.*\.size\s+normal_function} { target x86_64-*-* } } } */
 /* { dg-final { scan-assembler {wrap_normal_inline:.*ud2.*\.size\s+wrap_normal_inline} { target x86_64-*-* } } } */
+/* { dg-final { scan-assembler {normal_function:.*brk\s+#0x[0-9a-f]+.*\.size\s+normal_function} { target aarch64*-*-* } } } */
+/* { dg-final { scan-assembler {wrap_normal_inline:.*brk\s+#0x[0-9a-f]+.*\.size\s+wrap_normal_inline} { target aarch64*-*-* } } } */
 
 /* Negative controls: these should NOT have KCFI checks.  */
 /* { dg-final { scan-assembler-not {sensitive_non_inline_function:.*ud2.*\.size\s+sensitive_non_inline_function} { target x86_64-*-* } } } */
 /* { dg-final { scan-assembler-not {wrap_sensitive_inline:.*ud2.*\.size\s+wrap_sensitive_inline} { target x86_64-*-* } } } */
+/* { dg-final { scan-assembler-not {sensitive_non_inline_function:.*brk\s+#0x[0-9a-f]+.*\.size\s+sensitive_non_inline_function} { target aarch64*-*-* } } } */
+/* { dg-final { scan-assembler-not {wrap_sensitive_inline:.*brk\s+#0x[0-9a-f]+.*\.size\s+wrap_sensitive_inline} { target aarch64*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c +1 -0
index 95a8e8419e00..af6d86803576 100644
@@ -34,3 +34,4 @@ int main() {
    caller_no_checks() should NOT generate KCFI check (no_sanitize).
    So a total of exactly 1 KCFI check in the entire program.  */
 /* { dg-final { scan-assembler-times {addl\t-4\(%r[ad]x\), %r1[01]d} 1 { target x86_64-*-* } } } */
+/* { dg-final { scan-assembler-times {ldur\tw16, \[x[0-9]+, #-4\]} 1 { target aarch64-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-offset-validation.c +3 -0
index 97d964feebd3..0ced5c43ae92 100644
@@ -27,3 +27,6 @@ int main() {
 /* x86_64: All call sites should use -4 offset for KCFI type ID loads, even
    with -falign-functions=16 (we're not using patchable entries here).  */
 /* { dg-final { scan-assembler {movl\t\$-?[0-9]+, %r10d\n\taddl\t-4\(%r[a-z0-9]+\), %r10d} { target x86_64-*-* } } } */
+
+/* AArch64: All call sites should use -4 offset.  */
+/* { dg-final { scan-assembler {ldur\tw16, \[x[0-9]+, #-4\]} { target aarch64*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-entry-only.c +12 -0
index 379356385a16..7a251cbdee3b 100644
@@ -28,6 +28,11 @@ int main() {
 ** movl	\$0x[0-9a-f]+, %eax
 */
 
+/*
+** __cfi_test_function: { target aarch64*-*-* }
+** .word	0x[0-9a-f]+
+*/
+
 /*
 ** main: { target x86_64-*-* }
 ** ...
@@ -35,4 +40,11 @@ int main() {
 ** ...
 */
 
+/*
+** main: { target aarch64*-*-* }
+** ...
+** ldur	w16, \[x[0-9]+, #-4\]
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-large.c +12 -0
index 06df3495bb23..3ed5d16c8e91 100644
@@ -17,6 +17,11 @@ int main() {
 ** movl	\$0x[0-9a-f]+, %eax
 */
 
+/*
+** __cfi_test_function: { target aarch64*-*-* }
+** .word	0x[0-9a-f]+
+*/
+
 /*
 ** main: { target x86_64-*-* }
 ** ...
@@ -24,4 +29,11 @@ int main() {
 ** ...
 */
 
+/*
+** main: { target aarch64*-*-* }
+** ...
+** ldur	w16, \[x[0-9]+, #-48\]
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-medium.c +12 -0
index ef87b135934b..e354914209e9 100644
@@ -24,6 +24,11 @@ int main() {
 ** movl	\$0x[0-9a-f]+, %eax
 */
 
+/*
+** __cfi_test_function: { target aarch64*-*-* }
+** .word	0x[0-9a-f]+
+*/
+
 /*
 ** main: { target x86_64-*-* }
 ** ...
@@ -31,4 +36,11 @@ int main() {
 ** ...
 */
 
+/*
+** main: { target aarch64*-*-* }
+** ...
+** ldur	w16, \[x[0-9]+, #-20\]
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-prefix-only.c +12 -0
index 872814aa4171..7a1dc4fa0e07 100644
@@ -25,6 +25,11 @@ int main() {
 ** movl	\$0x[0-9a-f]+, %eax
 */
 
+/*
+** __cfi_test_function: { target aarch64*-*-* }
+** .word	0x[0-9a-f]+
+*/
+
 /*
 ** main: { target x86_64-*-* }
 ** ...
@@ -32,4 +37,11 @@ int main() {
 ** ...
 */
 
+/*
+** main: { target aarch64*-*-* }
+** ...
+** ldur	w16, \[x[0-9]+, #-16\]
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c +21 -0
index 04a9eb1fd206..7ac40719504b 100644
@@ -78,3 +78,24 @@ int test_non_tail_indirect_call(func_ptr_t handler, int x) {
 
 /* Should have exactly 1 regular call (non-tail call case).  */
 /* { dg-final { scan-assembler-times {call\t\*%[a-z0-9]+} 1 { target x86_64-*-* } } } */
+
+/* Should have exactly 4 KCFI checks for indirect calls (load type ID from
+   -4 offset + compare).  The actual-type scratch register avoids the call
+   target, so it is w9 for the sibcall targets (x16) and w16 otherwise; the
+   expected type is in the other of w16/w17.  */
+/* { dg-final { scan-assembler-times {ldur\tw[0-9]+, \[x[0-9]+, #-4\]} 4 { target aarch64-*-* } } } */
+/* { dg-final { scan-assembler-times {cmp\tw[0-9]+, w1[67]} 4 { target aarch64-*-* } } } */
+
+/* Should have exactly 4 trap instructions.  */
+/* { dg-final { scan-assembler-times {brk\t#0x[0-9a-f]+} 4 { target aarch64-*-* } } } */
+
+/* Should have exactly 3 protected tail calls (br through register after
+   KCFI check).  */
+/* { dg-final { scan-assembler-times {br\tx[0-9]+} 3 { target aarch64-*-* } } } */
+
+/* Should have exactly 1 regular call (non-tail call case).  */
+/* { dg-final { scan-assembler-times {blr\tx[0-9]+} 1 { target aarch64-*-* } } } */
+
+/* Type ID loading should use mov + movk pattern for 32-bit constants.  */
+/* { dg-final { scan-assembler {mov\tw17, #[0-9]+} { target aarch64-*-* } } } */
+/* { dg-final { scan-assembler {movk\tw17, #[0-9]+, lsl #16} { target aarch64-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-trap-encoding.c new file +43 -0

43 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c +4 -0
index 55c0829ccd7b..e92873e51321 100644
@@ -18,6 +18,10 @@ int main() {
 
 /* Should have exactly 2 trap labels in code.  */
 /* { dg-final { scan-assembler-times {\.L[^:]+:\n\s*ud2} 2 { target x86_64-*-* } } } */
+/* { dg-final { scan-assembler-times {\.L[^:]+:\n\s*brk} 2 { target aarch64*-*-* } } } */
 
 /* x86_64 should exactly 2 .kcfi_traps sections.  */
 /* { dg-final { scan-assembler-times {\.section\t\.kcfi_traps,"ao",@progbits,\.text} 2 { target x86_64-*-* } } } */
+
+/* AArch64 should NOT have .kcfi_traps section.  */
+/* { dg-final { scan-assembler-not {\.section\t+\.kcfi_traps} { target aarch64*-*-* } } } */
Signature · 1 line
2.55.0
author
#9 lore raw

PATCH v17 6/7 arm: Add ARM 32-bit Kernel Control Flow Integrity implementation

In reply to Kees Cook

Implement ARM 32-bit KCFI backend:

- Use eor instructions for 32-bit immediate loading.

- Trap debugging through UDF instruction immediate encoding following AArch64 BRK pattern for encoding registers with useful contents.

- Scratch register allocation uses ip by default since it is most commonly available as a caller-saved register. When, due to register pressure, ip is the call target register, use r3. Since r3 is already caller-saved, the allocator will have already arranged to reload r3 after the call if it is needed again. However, if r3 is being used as the 4th argument to the call, we must internally spill/reload it. Also uses r3 with -ffixed-ip or -ffixed-r12.

Assembly Code Pattern for ARM 32-bit:

  ldr  ip, [target, #-4]       ; Load actual type ID from preamble
  eor  ip, ip, #byte1          ; OR type id byte 1
  eor  ip, ip, #byte2 << 8     ; OR type id byte 2
  eor  ip, ip, #byte3 << 16    ; OR type id byte 3
  eors ip, ip, #byte4 << 24    ; OR type id byte 4 and set if reg is 0
  beq  .Lkcfi_call             ; Branch if typeids matched
  .Lkcfi_trap: udf #udf_value  ; Undefined instruction trap with encoding
  .Lkcfi_call: blx/bx target   ; Execute validated indirect transfer

UDF Immediate Encoding (following AArch64 ESR pattern):
- UDF instruction immediate encoding format:
0x8000 | ((ExpectedTypeReg & 31) << 5) | (TargetAddrReg & 31)
- ExpectedTypeReg indicates which register contains expected type (R12 = 12)
- TargetAddrReg indicates which register contains target address (0-15)
- Example: udf #33154 (0x817A) = expected type in R12, target address in R2

Build and run tested with Linux kernel ARCH=arm.

Assisted-by LLM [tests]

gcc/ChangeLog:

* config/arm/arm-protos.h: Declare KCFI helpers.
* config/arm/arm.cc (arm_maybe_wrap_call_with_kcfi): New function. (arm_maybe_wrap_call_value_with_kcfi): New function. (arm_output_kcfi_insn): Emit KCFI assembly.
* config/arm/arm.md: Add KCFI RTL patterns and hook expansion.
* doc/invoke.texi: Document arm32 nuances.

gcc/testsuite/ChangeLog:

* gcc.dg/kcfi/kcfi-adjacency.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-basics.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-call-sharing.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-complex-addressing.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-direct-call-shapes.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-move-preservation.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-no-sanitize-inline.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-no-sanitize.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-offset-validation.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-patchable-entry-only.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-patchable-large.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-patchable-medium.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-patchable-prefix-only.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-tail-calls.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-trap-encoding.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-trap-section.c: Add arm patterns.
* gcc.dg/kcfi/kcfi-arm-fixed-ip.c: New test.
* gcc.dg/kcfi/kcfi-arm-fixed-r12.c: New test.
* gcc.dg/kcfi/kcfi-arm-sibcall-r3.c: New test.

---
 gcc/config/arm/arm-protos.h                   |   4 +
 gcc/config/arm/arm.md                         |  62 +++++
 gcc/config/arm/arm.cc                         | 217 +++++++++++++++++-
 gcc/doc/invoke.texi                           |  27 ++-
 gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c    |  38 +++
 gcc/testsuite/gcc.dg/kcfi/kcfi-arm-fixed-ip.c |  15 ++
 .../gcc.dg/kcfi/kcfi-arm-fixed-r12.c          |  15 ++
 .../gcc.dg/kcfi/kcfi-arm-sibcall-r3.c         |  50 ++++
 gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c       |  42 +++-
 gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c |  17 +-
 .../gcc.dg/kcfi/kcfi-complex-addressing.c     |  22 ++
 .../gcc.dg/kcfi/kcfi-direct-call-shapes.c     |   3 +
 .../gcc.dg/kcfi/kcfi-move-preservation.c      |  42 +++-
 .../gcc.dg/kcfi/kcfi-no-sanitize-inline.c     |   5 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c  |   3 +
 .../gcc.dg/kcfi/kcfi-offset-validation.c      |   5 +
 .../gcc.dg/kcfi/kcfi-patchable-entry-only.c   |   9 +-
 .../gcc.dg/kcfi/kcfi-patchable-large.c        |  12 +-
 .../gcc.dg/kcfi/kcfi-patchable-medium.c       |  12 +-
 .../gcc.dg/kcfi/kcfi-patchable-prefix-only.c  |  12 +-
 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c   |  20 ++
 .../gcc.dg/kcfi/kcfi-trap-encoding.c          |  48 +++-
 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c |   5 +-
 23 files changed, 659 insertions(+), 26 deletions(-)
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-arm-fixed-ip.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-arm-fixed-r12.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-arm-sibcall-r3.c
gcc/config/arm/arm-protos.h +4 -0
index b607cdb3fcc0..295647a0efeb 100644
@@ -608,6 +608,10 @@ void arm_initialize_isa (sbitmap, const enum isa_feature *);
 
 const char * arm_gen_far_branch (rtx *, int, const char * , const char *);
 
+rtx arm_maybe_wrap_call_with_kcfi (rtx, rtx);
+rtx arm_maybe_wrap_call_value_with_kcfi (rtx, rtx);
+const char *arm_output_kcfi_insn (rtx_insn *, rtx *);
+
 bool arm_mve_immediate_check(rtx, machine_mode, bool);
 
 opt_machine_mode arm_mve_data_mode (scalar_mode, poly_uint64);
gcc/config/arm/arm.md +62 -0

109 lines not on this page · raw message

gcc/config/arm/arm.cc +208 -9

237 lines not on this page · raw message

gcc/doc/invoke.texi +26 -1
index ee8b48a68517..f0b1314d1731 100644
@@ -17611,6 +17611,26 @@ trap is taken, allowing the kernel to identify both the KCFI violation
 and the involved registers for detailed diagnostics (eliminating the need
 for a separate @code{.kcfi_traps} section as used on x86_64).
 
+On ARM 32-bit, KCFI type identifiers are emitted as a @code{.word ID}
+directive (a 32-bit constant) before the function entry.  ARM's
+natural 4-byte instruction alignment eliminates the need for additional
+alignment NOPs.  When used with @option{-fpatchable-function-entry}, the
+type identifier is placed before any prefix NOPs.  The runtime check uses
+@code{ip} (@code{r12}) as a scratch register, falling back to @code{r3} when
+@code{ip} is the call target or is a fixed register (spilling and restoring
+@code{r3} only when it carries a live argument).  In Thumb-2 mode a
+@code{bic} first clears the function-pointer Thumb bit before the type
+identifier is loaded.  The loaded type identifier is compared against the
+expected one using a sequence of four @code{eor} instructions (one per byte
+of the 32-bit value), the last of which sets the condition flags.  Type
+mismatches trigger a @code{udf} instruction with an immediate value that
+encodes both the expected type register index and the target address
+register index in the format @code{0x8000 | (type_reg << 5) | addr_reg}.  This
+encoding is captured in the UDF immediate field when the trap is taken,
+allowing the kernel to identify both the KCFI violation and the involved
+registers for detailed diagnostics (eliminating the need for a separate
+@code{.kcfi_traps} section as used on x86_64).
+
 KCFI is intended primarily for kernel code and may not be suitable
 for user-space applications that rely on techniques incompatible
 with strict type checking of indirect calls.
@@ -17625,7 +17645,12 @@ For the same reason, the location of the type identifier relative to a
 function entry point is part of a whole-program ABI: a call site computes
 that offset from its own translation unit's settings, so every translation
 unit that may be reached through an instrumented indirect call must agree on
-it.
+it.  On ARM this additionally requires a uniform instruction set state: the
+prefix-NOP size differs between ARM (4 bytes) and Thumb-2 (2 bytes), and
+Thumb function pointers carry the Thumb bit in bit 0, both of which feed the
+type-identifier location.  KCFI therefore does not support mixing ARM and
+Thumb-2 instrumented code in a single program; all such translation units
+must be built in the same mode.
 
 Use @option{-fdump-ipa-kcfi-details} to examine the computed type identifier
 hashes and their corresponding mangled type strings during compilation.
gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c +38 -0
index 47a33bf6393b..63fade749ddd 100644
@@ -83,4 +83,42 @@ __attribute__((noinline)) void test_conditional_call(int flag) {
    (same register number) means the target was overwritten by the load.  */
 /* { dg-final { scan-assembler-not {ldur\tw([0-9]+), \[x\1,} { target aarch64*-*-* } } } */
 
+/*
+** test_complex_args: { target arm_nothumb }
+** ...
+** push	\{r3\}
+** ldr	r3, \[ip, #-4\]
+** eor	r3, r3, #[0-9]+
+** eor	r3, r3, #[0-9]+
+** eor	r3, r3, #[0-9]+
+** eors	r3, r3, #[0-9]+
+** pop	\{r3\}
+** beq	.Lkcfi_call([0-9]+)
+** .Lkcfi_trap[0-9]+:
+** udf	#[0-9]+
+** .Lkcfi_call\1:
+** bx	ip
+** ...
+*/
+
+/* Thumb-2 inserts a BIC to strip the Thumb bit before the typeid load.  */
+/*
+** test_complex_args: { target arm_thumb2 }
+** ...
+** push	\{r3\}
+** bic	r3, ip, #1
+** ldr	r3, \[r3, #-4\]
+** eor	r3, r3, #[0-9]+
+** eor	r3, r3, #[0-9]+
+** eor	r3, r3, #[0-9]+
+** eors	r3, r3, #[0-9]+
+** pop	\{r3\}
+** beq	.Lkcfi_call([0-9]+)
+** .Lkcfi_trap[0-9]+:
+** udf	#[0-9]+
+** .Lkcfi_call\1:
+** bx	ip
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.L.*|\.section|\.text} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-arm-fixed-ip.c new file +15 -0
new file mode 100644
index 000000000000..bb76078aa800
@@ -0,0 +1,15 @@
+/* Test that KCFI works with -ffixed-ip on ARM by using r3 fallback.  */
+/* { dg-do compile { target arm*-*-* } } */
+/* { dg-additional-options "-ffixed-ip" } */
+
+void target_function(void) {}
+
+int main() {
+    void (*func_ptr)(void) = target_function;
+    func_ptr();
+    return 0;
+}
+
+/* Should use r3 instead of ip for scratch register when ip is fixed.  */
+/* { dg-final { scan-assembler "ldr\tr3, \\\[r\[0-9\]+, #-4\\\]" } } */
+/* { dg-final { scan-assembler "eor\tr3, r3, #\[0-9\]+" } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-arm-fixed-r12.c new file +15 -0
new file mode 100644
index 000000000000..dd3f1f001f5b
@@ -0,0 +1,15 @@
+/* Test that KCFI works with -ffixed-r12 on ARM by using r3 fallback.  */
+/* { dg-do compile { target arm*-*-* } } */
+/* { dg-additional-options "-ffixed-r12" } */
+
+void target_function(void) {}
+
+int main() {
+    void (*func_ptr)(void) = target_function;
+    func_ptr();
+    return 0;
+}
+
+/* Should use r3 instead of ip for scratch register when ip is fixed.  */
+/* { dg-final { scan-assembler "ldr\tr3, \\\[r\[0-9\]+, #-4\\\]" } } */
+/* { dg-final { scan-assembler "eor\tr3, r3, #\[0-9\]+" } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-arm-sibcall-r3.c new file +50 -0

50 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c +38 -4

57 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c +14 -3
index c402a1678a73..ce5e17134929 100644
@@ -60,21 +60,32 @@ int test_kcfi_check_sharing(struct kobject *kobj, const struct attribute_group *
    1. KCFI check for is_visible call with is_visible type ID A.
    2. KCFI check for is_bin_visible and is_bin_visible_again call with type ID B.  */
 
-/* Verify we have TWO different KCFI check sequences.  */
+/* Verify we have TWO different KCFI check sequences (except on arm, which
+   due to heavy register pressure ends up generating an unmergeable series
+   of instructions: the call target registers differ).  */
 /* Each check should have different type ID constants.  */
 /* x86: { dg-final { scan-assembler-times {movl\s+\$-?[0-9]+,\s+%r10d} 2 { target i?86-*-* x86_64-*-* } } } */
 /* AArch64: { dg-final { scan-assembler-times {mov\s+w17, #[0-9]+} 2 { target aarch64*-*-* } } } */
+/* ARM 32-bit: In Thumb-2 the load base is ip (post-Thumb-bit-strip), in ARM
+   mode it is the call target register or lr; accept any.  */
+/* { dg-final { scan-assembler-times {ldr\s+ip, \[(?:r[0-9]+|lr|ip), #-4\]} 3 { target arm*-*-* } } } */
 
-/* Verify the checks use DIFFERENT type IDs (not shared).
+/* Verify the checks use DIFFERENT type IDs (not shared, except arm: see above).
    We should NOT see the same type ID used twice - that would indicate
    unmerged sharing.  */
 /* x86: { dg-final { scan-assembler-not {movl\s+\$(-?[0-9]+),\s+%r10d.*movl\s+\$\1,\s+%r10d} { target i?86-*-* x86_64-*-* } } } */
 /* AArch64: { dg-final { scan-assembler-not {mov\s+w17, #([0-9]+).*mov\s+w17, #\1} { target aarch64*-*-* } } } */
+/* ARM 32-bit: the first check (to .Lkcfi_call0) must not have its type ID
+   reused by a later check.  Each check uses a single scratch register,
+   ip or r3.  */
+/* { dg-final { scan-assembler-not {eor\s+(ip|r3), \1, #([0-9]+)\n\teor\s+\1, \1, #([0-9]+)\n\teor\s+\1, \1, #([0-9]+)\n\teors\s+\1, \1, #([0-9]+)\n(?:\tpop\t\{r3\}\n)?\tbeq\t\.Lkcfi_call0\n.*eor\s+(?:ip|r3), (?:ip|r3), #\2\n\teor\s+(?:ip|r3), (?:ip|r3), #\3\n\teor\s+(?:ip|r3), (?:ip|r3), #\4\n\teors\s+(?:ip|r3), (?:ip|r3), #\5} { target arm*-*-* } } } */
 
 /* Verify expected number of traps.  */
 /* x86: { dg-final { scan-assembler-times {ud2} 2 { target i?86-*-* x86_64-*-* } } } */
 /* AArch64: { dg-final { scan-assembler-times {brk\s+#0x[0-9a-f]+} 2 { target aarch64*-*-* } } } */
+/* ARM 32-bit: { dg-final { scan-assembler-times {udf\s+#[0-9]+} 3 { target arm*-*-* } } } */
 
-/* Verify 2 separate call sites.  */
+/* Verify 2 separate call sites (except arm).  */
 /* x86: { dg-final { scan-assembler-times {jmp\s+\*%[a-z0-9]+} 2 { target i?86-*-* x86_64-*-* } } } */
 /* AArch64: { dg-final { scan-assembler-times {br\tx[0-9]+} 2 { target aarch64*-*-* } } } */
+/* ARM 32-bit: { dg-final { scan-assembler-times {bx\s+(?:r[0-9]+|lr)} 3 { target arm*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-complex-addressing.c +22 -0
index 0b23caa49ebb..5eec800e108d 100644
@@ -4,6 +4,9 @@
    of a simple register.  */
 /* { dg-do compile } */
 /* { dg-additional-options "-O2" } */
+/* The force_r3_spill check verifies ARM-mode register-pressure codegen,
+   which differs in Thumb mode.  Force ARM mode where supported.  */
+/* { dg-additional-options "-marm" { target arm*-*-* } } */
 
 struct function_table {
     int (*callback1)(int);
@@ -162,4 +165,23 @@ int main() {
 ** ...
 */
 
+/* Looking for r3 fall-back due to register pressure.  */
+/*
+** force_r3_spill: { target arm*-*-* }
+** ...
+** push	\{r3\}
+** ldr	r3, \[(ip), #-4\]
+** eor	r3, r3, #[0-9]+
+** eor	r3, r3, #[0-9]+
+** eor	r3, r3, #[0-9]+
+** eors	r3, r3, #[0-9]+
+** pop	\{r3\}
+** beq	.Lkcfi_call([0-9]+)
+** .Lkcfi_trap[0-9]+:
+** udf	#[0-9]+
+** .Lkcfi_call\2:
+** blx	\1
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.L.*|\.section|\.text} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-direct-call-shapes.c +3 -0
index 6b4698447b7b..2daf5aa94bcf 100644
@@ -30,3 +30,6 @@ void caller(int sel, void (*ip)(int), int x) {
 /* The typeid scratch register avoids the call target, so it is not always
    w16 (a sibcall target lands in x16/x17, forcing the load into w9).  */
 /* { dg-final { scan-assembler-times {ldur\tw[0-9]+, \[x[0-9]+, #-4\]} 1 { target aarch64*-*-* } } } */
+/* The arm load base is the call target register in ARM mode and ip in
+   Thumb-2 (after the Thumb-bit strip); accept either.  */
+/* { dg-final { scan-assembler-times {ldr\tip, \[(?:r[0-9]+|ip), #-4\]} 1 { target arm*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-move-preservation.c +40 -2

47 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize-inline.c +5 -0
index 98591ed9b145..279207a85cdc 100644
@@ -76,15 +76,20 @@ int main(void)
 /* Verify correct number of KCFI checks: exactly 2 */
 /* { dg-final { scan-assembler-times {ud2} 2 { target x86_64-*-* } } } */
 /* { dg-final { scan-assembler-times {brk\s+#0x[0-9a-f]+} 2 { target aarch64*-*-* } } } */
+/* { dg-final { scan-assembler-times {udf\s+#[0-9]+} 2 { target arm*-*-* } } } */
 
 /* Positive controls: these should have KCFI checks.  */
 /* { dg-final { scan-assembler {normal_function:.*ud2.*\.size\s+normal_function} { target x86_64-*-* } } } */
 /* { dg-final { scan-assembler {wrap_normal_inline:.*ud2.*\.size\s+wrap_normal_inline} { target x86_64-*-* } } } */
 /* { dg-final { scan-assembler {normal_function:.*brk\s+#0x[0-9a-f]+.*\.size\s+normal_function} { target aarch64*-*-* } } } */
 /* { dg-final { scan-assembler {wrap_normal_inline:.*brk\s+#0x[0-9a-f]+.*\.size\s+wrap_normal_inline} { target aarch64*-*-* } } } */
+/* { dg-final { scan-assembler {normal_function:.*udf\t#[0-9]+.*\.size\s+normal_function} { target arm*-*-* } } } */
+/* { dg-final { scan-assembler {wrap_normal_inline:.*udf\t#[0-9]+.*\.size\s+wrap_normal_inline} { target arm*-*-* } } } */
 
 /* Negative controls: these should NOT have KCFI checks.  */
 /* { dg-final { scan-assembler-not {sensitive_non_inline_function:.*ud2.*\.size\s+sensitive_non_inline_function} { target x86_64-*-* } } } */
 /* { dg-final { scan-assembler-not {wrap_sensitive_inline:.*ud2.*\.size\s+wrap_sensitive_inline} { target x86_64-*-* } } } */
 /* { dg-final { scan-assembler-not {sensitive_non_inline_function:.*brk\s+#0x[0-9a-f]+.*\.size\s+sensitive_non_inline_function} { target aarch64*-*-* } } } */
 /* { dg-final { scan-assembler-not {wrap_sensitive_inline:.*brk\s+#0x[0-9a-f]+.*\.size\s+wrap_sensitive_inline} { target aarch64*-*-* } } } */
+/* { dg-final { scan-assembler-not {sensitive_non_inline_function:[^\n]*udf\t#[0-9]+[^\n]*\.size\tsensitive_non_inline_function} { target arm*-*-* } } } */
+/* { dg-final { scan-assembler-not {wrap_sensitive_inline:[^\n]*udf\t#[0-9]+[^\n]*\.size\twrap_sensitive_inline} { target arm*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c +3 -0
index af6d86803576..9355d633301b 100644
@@ -35,3 +35,6 @@ int main() {
    So a total of exactly 1 KCFI check in the entire program.  */
 /* { dg-final { scan-assembler-times {addl\t-4\(%r[ad]x\), %r1[01]d} 1 { target x86_64-*-* } } } */
 /* { dg-final { scan-assembler-times {ldur\tw16, \[x[0-9]+, #-4\]} 1 { target aarch64-*-* } } } */
+/* In Thumb-2 the load base is ip (post-Thumb-bit-strip), in ARM mode it is
+   the call target register; accept either.  */
+/* { dg-final { scan-assembler-times {ldr\tip, \[(?:r[0-9]+|ip), #-4\]} 1 { target arm*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-offset-validation.c +5 -0
index 0ced5c43ae92..cb1eb7c7ecc6 100644
@@ -30,3 +30,8 @@ int main() {
 
 /* AArch64: All call sites should use -4 offset.  */
 /* { dg-final { scan-assembler {ldur\tw16, \[x[0-9]+, #-4\]} { target aarch64*-*-* } } } */
+
+/* ARM 32-bit: All call sites should use -4 offset with EOR sequence.
+   In Thumb-2 the load base is ip (after the Thumb-bit strip); in ARM mode it
+   is the call target register directly.  Accept either.  */
+/* { dg-final { scan-assembler {ldr\tip, \[(?:r[0-9]+|ip), #-4\]} { target arm*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-entry-only.c +8 -1
index 7a251cbdee3b..612140a0f509 100644
@@ -29,7 +29,7 @@ int main() {
 */
 
 /*
-** __cfi_test_function: { target aarch64*-*-* }
+** __cfi_test_function: { target aarch64*-*-* arm*-*-* }
 ** .word	0x[0-9a-f]+
 */
 
@@ -47,4 +47,11 @@ int main() {
 ** ...
 */
 
+/*
+** main: { target arm*-*-* }
+** ...
+** ldr	(r[0-9]+|ip), \[(r[0-9]+|ip), #-4\]
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-large.c +11 -1
index 3ed5d16c8e91..7f7ada17cc14 100644
@@ -2,6 +2,9 @@
 /* { dg-do compile } */
 /* { dg-additional-options "-fpatchable-function-entry=11,11" } */
 /* { dg-additional-options "-falign-functions=16" { target x86_64-*-* } } */
+/* The typeid offset depends on patchable NOP size (4 bytes in ARM mode,
+   2 bytes in Thumb mode).  Force ARM mode for deterministic offsets.  */
+/* { dg-additional-options "-marm" { target arm*-*-* } } */
 
 void test_function(void) {
 }
@@ -18,7 +21,7 @@ int main() {
 */
 
 /*
-** __cfi_test_function: { target aarch64*-*-* }
+** __cfi_test_function: { target aarch64*-*-* arm*-*-* }
 ** .word	0x[0-9a-f]+
 */
 
@@ -36,4 +39,11 @@ int main() {
 ** ...
 */
 
+/*
+** main: { target arm*-*-* }
+** ...
+** ldr	(r[0-9]+|ip), \[(r[0-9]+|ip), #-48\]
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-medium.c +11 -1
index e354914209e9..0a1f4e20851f 100644
@@ -2,6 +2,9 @@
 /* { dg-do compile } */
 /* { dg-additional-options "-fpatchable-function-entry=8,4" } */
 /* { dg-additional-options "-falign-functions=16" { target x86_64-*-* } } */
+/* The typeid offset depends on patchable NOP size (4 bytes in ARM mode,
+   2 bytes in Thumb mode).  Force ARM mode for deterministic offsets.  */
+/* { dg-additional-options "-marm" { target arm*-*-* } } */
 
 void test_function(void) {
 }
@@ -25,7 +28,7 @@ int main() {
 */
 
 /*
-** __cfi_test_function: { target aarch64*-*-* }
+** __cfi_test_function: { target aarch64*-*-* arm*-*-* }
 ** .word	0x[0-9a-f]+
 */
 
@@ -43,4 +46,11 @@ int main() {
 ** ...
 */
 
+/*
+** main: { target arm*-*-* }
+** ...
+** ldr	ip, \[r[0-9]+, #-20\]
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-prefix-only.c +11 -1
index 7a1dc4fa0e07..548a2f5d8b84 100644
@@ -2,6 +2,9 @@
 /* { dg-do compile } */
 /* { dg-additional-options "-fpatchable-function-entry=3,3" } */
 /* { dg-additional-options "-falign-functions=16" { target x86_64-*-* } } */
+/* The typeid offset depends on patchable NOP size (4 bytes in ARM mode,
+   2 bytes in Thumb mode).  Force ARM mode for deterministic offsets.  */
+/* { dg-additional-options "-marm" { target arm*-*-* } } */
 
 void test_function(void) {
 }
@@ -26,7 +29,7 @@ int main() {
 */
 
 /*
-** __cfi_test_function: { target aarch64*-*-* }
+** __cfi_test_function: { target aarch64*-*-* arm*-*-* }
 ** .word	0x[0-9a-f]+
 */
 
@@ -44,4 +47,11 @@ int main() {
 ** ...
 */
 
+/*
+** main: { target arm*-*-* }
+** ...
+** ldr	(r[0-9]+|ip), \[(r[0-9]+|ip), #-16\]
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c +20 -0
index 7ac40719504b..544ae7807297 100644
@@ -99,3 +99,23 @@ int test_non_tail_indirect_call(func_ptr_t handler, int x) {
 /* Type ID loading should use mov + movk pattern for 32-bit constants.  */
 /* { dg-final { scan-assembler {mov\tw17, #[0-9]+} { target aarch64-*-* } } } */
 /* { dg-final { scan-assembler {movk\tw17, #[0-9]+, lsl #16} { target aarch64-*-* } } } */
+
+/* Should have exactly 4 KCFI checks for indirect calls (load type ID from
+   -4 offset + EOR sequence).  */
+/* In Thumb-2 the load base is ip (post-Thumb-bit-strip), in ARM mode it is
+   the call target register; accept either.  */
+/* { dg-final { scan-assembler-times {ldr\tip, \[(?:r[0-9]+|ip), #-4\]} 4 { target arm*-*-* } } } */
+/* { dg-final { scan-assembler-times {eors\tip, ip, #[0-9]+} 4 { target arm*-*-* } } } */
+
+/* Should have exactly 4 trap instructions.  */
+/* { dg-final { scan-assembler-times {udf\t#[0-9]+} 4 { target arm*-*-* } } } */
+
+/* Should have exactly 3 protected tail calls (bx through register after
+   KCFI check).  */
+/* { dg-final { scan-assembler-times {bx\tr[0-9]+} 3 { target arm*-*-* } } } */
+
+/* Should have exactly 1 regular call (non-tail call case).  */
+/* { dg-final { scan-assembler-times {blx\tr[0-9]+} 1 { target arm*-*-* } } } */
+
+/* Type ID loading should use 4 EOR instructions for 32-bit constants.  */
+/* { dg-final { scan-assembler-times {eors?\tip, ip, #[0-9]+} 16 { target arm*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-trap-encoding.c +47 -1

56 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c +3 -2
index e92873e51321..e02a320f2f92 100644
@@ -19,9 +19,10 @@ int main() {
 /* Should have exactly 2 trap labels in code.  */
 /* { dg-final { scan-assembler-times {\.L[^:]+:\n\s*ud2} 2 { target x86_64-*-* } } } */
 /* { dg-final { scan-assembler-times {\.L[^:]+:\n\s*brk} 2 { target aarch64*-*-* } } } */
+/* { dg-final { scan-assembler-times {\.L[^:]+:\n\s*udf} 2 { target arm*-*-* } } } */
 
 /* x86_64 should exactly 2 .kcfi_traps sections.  */
 /* { dg-final { scan-assembler-times {\.section\t\.kcfi_traps,"ao",@progbits,\.text} 2 { target x86_64-*-* } } } */
 
-/* AArch64 should NOT have .kcfi_traps section.  */
-/* { dg-final { scan-assembler-not {\.section\t+\.kcfi_traps} { target aarch64*-*-* } } } */
+/* AArch64 and ARM 32-bit should NOT have .kcfi_traps section.  */
+/* { dg-final { scan-assembler-not {\.section\t+\.kcfi_traps} { target aarch64*-*-* arm*-*-* } } } */
Signature · 1 line
2.55.0
author
#10 lore raw

PATCH v17 7/7 riscv: Add RISC-V Kernel Control Flow Integrity implementation

In reply to Kees Cook

Implement RISC-V-specific KCFI backend. This is rv64-only: the emitted typeid construction uses addiw, which exists only on RV64/RV128. An rv32 backend would need an alternate sequence (e.g. addi); since the only current user of KCFI on riscv is the rv64 build of the Linux kernel, the support hook rejects rv32.

- Scratch register allocation using t1/t2 (x6/x7) following RISC-V procedure call standard for temporary registers (already caller-saved), and t3 (x28) when either t1 or t2 is already the call target register.

- Incompatible with -ffixed-t1, -ffixed-t2, or -ffixed-t3.

- Integration with .kcfi_traps section for debugger/runtime metadata (like x86_64).

Assembly Code Pattern for RISC-V:

  lw      t1, -4(target_reg)         ; Load actual type ID from preamble
  lui     t2, %hi(expected_type)     ; Load expected type (upper 20 bits)
  addiw   t2, t2, %lo(expected_type) ; Add lower 12 bits (sign-extended)
  beq     t1, t2, .Lkcfi_call        ; Branch if types match

.Lkcfi_trap: ebreak ; Environment break trap on mismatch
.Lkcfi_call: jalr/jr target_reg ; Execute validated indirect transfer

Build and run tested with Linux kernel ARCH=riscv.

Assisted-by LLM [tests]

gcc/ChangeLog:

* config/riscv/riscv-protos.h: Declare KCFI helpers.
* config/riscv/riscv.cc (riscv_maybe_wrap_call_with_kcfi): New function, to wrap calls. (riscv_maybe_wrap_call_value_with_kcfi): New function, to wrap calls with return values. (riscv_output_kcfi_insn): New function to emit KCFI assembly.
* config/riscv/riscv.md: Add KCFI RTL patterns and hook expansion.
* doc/invoke.texi: Document riscv nuances.

gcc/testsuite/ChangeLog:

* gcc.dg/kcfi/kcfi-adjacency.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-basics.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-call-sharing.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-complex-addressing.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-direct-call-shapes.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-move-preservation.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-no-sanitize-inline.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-no-sanitize.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-offset-validation.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-patchable-entry-only.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-patchable-large.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-patchable-medium.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-patchable-prefix-only.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-tail-calls.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-trap-section.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-trap-section-per-func.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-riscv-32bit.c: New test.
* gcc.dg/kcfi/kcfi-riscv-fixed-t1.c: New test.
* gcc.dg/kcfi/kcfi-riscv-fixed-t2.c: New test.
* gcc.dg/kcfi/kcfi-riscv-fixed-t3.c: New test.

---
 gcc/config/riscv/riscv-protos.h               |   3 +
 gcc/config/riscv/riscv.md                     |  76 ++++++-
 gcc/config/riscv/riscv.cc                     | 199 ++++++++++++++++++
 gcc/doc/invoke.texi                           |  17 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c    |  18 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c       |  22 +-
 gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c |   4 +
 .../gcc.dg/kcfi/kcfi-complex-addressing.c     |  19 ++
 .../gcc.dg/kcfi/kcfi-direct-call-shapes.c     |   1 +
 .../gcc.dg/kcfi/kcfi-move-preservation.c      |  20 ++
 .../gcc.dg/kcfi/kcfi-no-sanitize-inline.c     |   5 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c  |   1 +
 .../gcc.dg/kcfi/kcfi-offset-validation.c      |   3 +
 .../gcc.dg/kcfi/kcfi-patchable-entry-only.c   |   9 +-
 .../gcc.dg/kcfi/kcfi-patchable-large.c        |  10 +-
 .../gcc.dg/kcfi/kcfi-patchable-medium.c       |   9 +-
 .../gcc.dg/kcfi/kcfi-patchable-prefix-only.c  |   9 +-
 gcc/testsuite/gcc.dg/kcfi/kcfi-riscv-32bit.c  |   7 +
 .../gcc.dg/kcfi/kcfi-riscv-fixed-t1.c         |   7 +
 .../gcc.dg/kcfi/kcfi-riscv-fixed-t2.c         |   7 +
 .../gcc.dg/kcfi/kcfi-riscv-fixed-t3.c         |   7 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c   |  23 ++
 .../gcc.dg/kcfi/kcfi-trap-section-per-func.c  |   2 +-
 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c |   5 +-
 24 files changed, 466 insertions(+), 17 deletions(-)
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-riscv-32bit.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-riscv-fixed-t1.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-riscv-fixed-t2.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-riscv-fixed-t3.c
gcc/config/riscv/riscv-protos.h +3 -0
index c0fb28397809..44f497882ff7 100644
@@ -127,6 +127,9 @@ extern void riscv_split_doubleword_move (rtx, rtx);
 extern void riscv_split_quadword_move (rtx, rtx);
 extern const char *riscv_output_move (rtx, rtx);
 extern const char *riscv_output_return ();
+extern rtx riscv_maybe_wrap_call_with_kcfi (rtx, rtx);
+extern rtx riscv_maybe_wrap_call_value_with_kcfi (rtx, rtx);
+extern const char *riscv_output_kcfi_insn (rtx_insn *, rtx *);
 extern void riscv_declare_function_name (FILE *, const char *, tree);
 extern void riscv_declare_function_size (FILE *, const char *, tree);
 extern void riscv_asm_output_alias (FILE *, const tree, const tree);
gcc/config/riscv/riscv.md +68 -8

120 lines not on this page · raw message

gcc/config/riscv/riscv.cc +199 -0

217 lines not on this page · raw message

gcc/doc/invoke.texi +17 -0
index f0b1314d1731..b1ebae37ed89 100644
@@ -17631,6 +17631,23 @@ allowing the kernel to identify both the KCFI violation and the involved
 registers for detailed diagnostics (eliminating the need for a separate
 @code{.kcfi_traps} section as used on x86_64).
 
+On 64-bit RISC-V, KCFI type identifiers are emitted as a @code{.word ID}
+directive (a 32-bit constant) before the function entry, similar to AArch64.
+RISC-V's natural instruction alignment eliminates the need for
+additional alignment NOPs.  When used with @option{-fpatchable-function-entry},
+the type identifier is placed before any prefix NOPs.  The runtime check
+loads the actual type using @code{lw t1, OFFSET(target_reg)}, where the
+offset accounts for any prefix NOPs, constructs the expected type using
+@code{lui} and @code{addiw} instructions into @code{t2}, and compares them
+with @code{beq}.  @code{t3} is used as an alternative when @code{t1} or
+@code{t2} is the target call register.  Because of the use of these
+registers, they cannot be fixed registers, so KCFI cannot be used with any
+of @code{-ffixed-t1}, @code{-ffixed-t2}, nor @code{-ffixed-t3}. Type
+mismatches trigger an @code{ebreak} instruction.  Like x86_64, RISC-V
+uses a @code{.kcfi_traps} section to map trap locations to their
+corresponding function entry points for debugging (RISC-V lacks
+ESR-style trap encoding like used on AArch64).
+
 KCFI is intended primarily for kernel code and may not be suitable
 for user-space applications that rely on techniques incompatible
 with strict type checking of indirect calls.
gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c +18 -0
index 63fade749ddd..fad09c4f08d1 100644
@@ -121,4 +121,22 @@ __attribute__((noinline)) void test_conditional_call(int flag) {
 ** ...
 */
 
+/*
+** test_complex_args: { target riscv*-*-* }
+** ...
+** lw	t1, -4\((a[0-9]+)\)
+** lui	t2, [0-9]+
+** addiw	t2, t2, -?[0-9]+
+** beq	t1, t2, .Lkcfi_call([0-9]+)
+** .Lkcfi_trap([0-9]+):
+** ebreak
+** .section	.kcfi_traps,"ao",@progbits,.text
+** .Lkcfi_entry([0-9]+):
+** .4byte	.Lkcfi_trap\3-.Lkcfi_entry\4
+** .text
+** .Lkcfi_call\2:
+** jalr	zero, \1, 0
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.L.*|\.section|\.text} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c +20 -2
index a917e1c70089..9256d2a1a3c3 100644
@@ -59,8 +59,8 @@ int main() {
 /* x86_64: Verify type ID in preamble (after NOPs, before function label) */
 /* { dg-final { scan-assembler {__cfi_regular_function:\n\t+nop\n.*\n\t+movl\t+\$0x[0-9a-f]+, %eax} { target x86_64-*-* } } } */
 
-/* AArch64, ARM32: Verify type ID word in preamble.  */
-/* { dg-final { scan-assembler {__cfi_regular_function:\n\t\.word\t0x[0-9a-f]+} { target aarch64*-*-* arm*-*-* } } } */
+/* AArch64, ARM32, RISC-V: Verify type ID word in preamble.  */
+/* { dg-final { scan-assembler {__cfi_regular_function:\n\t\.word\t0x[0-9a-f]+} { target aarch64*-*-* arm*-*-* riscv*-*-* } } } */
 
 /*
 ** static_caller: { target x86_64-*-* }
@@ -128,6 +128,24 @@ int main() {
 ** ...
 */
 
+/*
+** static_caller: { target riscv*-*-* }
+** ...
+** lw	t1, -4\((a[0-9]+)\)
+** lui	t2, [0-9]+
+** addiw	t2, t2, -?[0-9]+
+** beq	t1, t2, .Lkcfi_call([0-9]+)
+** .Lkcfi_trap([0-9]+):
+** ebreak
+** .section	.kcfi_traps,"ao",@progbits,.text
+** .Lkcfi_entry([0-9]+):
+** .4byte	.Lkcfi_trap\3-.Lkcfi_entry\4
+** .text
+** .Lkcfi_call\2:
+** jalr	ra, \1, 0
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.L.*|\.section|\.text} } } */
 
 /* Extern functions should NOT get KCFI preambles.  */
gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c +4 -0
index ce5e17134929..f11556dd43de 100644
@@ -69,6 +69,7 @@ int test_kcfi_check_sharing(struct kobject *kobj, const struct attribute_group *
 /* ARM 32-bit: In Thumb-2 the load base is ip (post-Thumb-bit-strip), in ARM
    mode it is the call target register or lr; accept any.  */
 /* { dg-final { scan-assembler-times {ldr\s+ip, \[(?:r[0-9]+|lr|ip), #-4\]} 3 { target arm*-*-* } } } */
+/* RISC-V: { dg-final { scan-assembler-times {lui\tt2, [0-9]+} 2 { target riscv*-*-* } } } */
 
 /* Verify the checks use DIFFERENT type IDs (not shared, except arm: see above).
    We should NOT see the same type ID used twice - that would indicate
@@ -79,13 +80,16 @@ int test_kcfi_check_sharing(struct kobject *kobj, const struct attribute_group *
    reused by a later check.  Each check uses a single scratch register,
    ip or r3.  */
 /* { dg-final { scan-assembler-not {eor\s+(ip|r3), \1, #([0-9]+)\n\teor\s+\1, \1, #([0-9]+)\n\teor\s+\1, \1, #([0-9]+)\n\teors\s+\1, \1, #([0-9]+)\n(?:\tpop\t\{r3\}\n)?\tbeq\t\.Lkcfi_call0\n.*eor\s+(?:ip|r3), (?:ip|r3), #\2\n\teor\s+(?:ip|r3), (?:ip|r3), #\3\n\teor\s+(?:ip|r3), (?:ip|r3), #\4\n\teors\s+(?:ip|r3), (?:ip|r3), #\5} { target arm*-*-* } } } */
+/* RISC-V: { dg-final { scan-assembler-not {lui\s+t2, ([0-9]+)\s.*lui\s+t2, \1\s} { target riscv*-*-* } } } */
 
 /* Verify expected number of traps.  */
 /* x86: { dg-final { scan-assembler-times {ud2} 2 { target i?86-*-* x86_64-*-* } } } */
 /* AArch64: { dg-final { scan-assembler-times {brk\s+#0x[0-9a-f]+} 2 { target aarch64*-*-* } } } */
 /* ARM 32-bit: { dg-final { scan-assembler-times {udf\s+#[0-9]+} 3 { target arm*-*-* } } } */
+/* RISC-V: { dg-final { scan-assembler-times {ebreak} 2 { target riscv*-*-* } } } */
 
 /* Verify 2 separate call sites (except arm).  */
 /* x86: { dg-final { scan-assembler-times {jmp\s+\*%[a-z0-9]+} 2 { target i?86-*-* x86_64-*-* } } } */
 /* AArch64: { dg-final { scan-assembler-times {br\tx[0-9]+} 2 { target aarch64*-*-* } } } */
 /* ARM 32-bit: { dg-final { scan-assembler-times {bx\s+(?:r[0-9]+|lr)} 3 { target arm*-*-* } } } */
+/* RISC-V: { dg-final { scan-assembler-times {jalr\t[a-z0-9]+} 2 { target riscv*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-complex-addressing.c +19 -0
index 5eec800e108d..b11014c29676 100644
@@ -184,4 +184,23 @@ int main() {
 ** ...
 */
 
+/* Standard KCFI handling.  */
+/*
+** test_struct_members: { target riscv*-*-* }
+** ...
+** lw	t1, -4\((a[0-9]+)\)
+** lui	t2, [0-9]+
+** addiw	t2, t2, -?[0-9]+
+** beq	t1, t2, .Lkcfi_call([0-9]+)
+** .Lkcfi_trap([0-9]+):
+** ebreak
+** .section	.kcfi_traps,"ao",@progbits,.text
+** .Lkcfi_entry([0-9]+):
+** .4byte	.Lkcfi_trap\3-.Lkcfi_entry\4
+** .text
+** .Lkcfi_call\2:
+** jalr	ra, \1, 0
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.L.*|\.section|\.text} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-direct-call-shapes.c +1 -0
index 2daf5aa94bcf..1c72f0fc5757 100644
@@ -33,3 +33,4 @@ void caller(int sel, void (*ip)(int), int x) {
 /* The arm load base is the call target register in ARM mode and ip in
    Thumb-2 (after the Thumb-bit strip); accept either.  */
 /* { dg-final { scan-assembler-times {ldr\tip, \[(?:r[0-9]+|ip), #-4\]} 1 { target arm*-*-* } } } */
+/* { dg-final { scan-assembler-times {lw\tt1, -4\(a[0-9]+\)} 1 { target riscv*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-move-preservation.c +20 -0
index fac0e3aff0e4..b78434cbe5e6 100644
@@ -112,6 +112,26 @@ int main(void)
 ** ...
 */
 
+/*
+** indirect_call: { target riscv*-*-* }
+** ...
+** mv	(a[0-9]+),a0
+** addi	a0,a4,%lo\(called_count\)
+** lw	t1, -4\(\1\)
+** lui	t2, [0-9]+
+** addiw	t2, t2, -?[0-9]+
+** beq	t1, t2, .Lkcfi_call([0-9]+)
+** .Lkcfi_trap([0-9]+):
+** ebreak
+** .section	.kcfi_traps,"ao",@progbits,.text
+** .Lkcfi_entry([0-9]+):
+** .4byte	.Lkcfi_trap\3-.Lkcfi_entry\4
+** .text
+** .Lkcfi_call\2:
+** jalr	zero, \1, 0
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.L.*|\.section|\.text} } } */
 
 /* AArch64, ARM32 should NOT have trap section (use immediate instructions instead).  */
gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize-inline.c +5 -0
index 279207a85cdc..8bc353ed2d32 100644
@@ -77,6 +77,7 @@ int main(void)
 /* { dg-final { scan-assembler-times {ud2} 2 { target x86_64-*-* } } } */
 /* { dg-final { scan-assembler-times {brk\s+#0x[0-9a-f]+} 2 { target aarch64*-*-* } } } */
 /* { dg-final { scan-assembler-times {udf\s+#[0-9]+} 2 { target arm*-*-* } } } */
+/* { dg-final { scan-assembler-times {ebreak} 2 { target riscv*-*-* } } } */
 
 /* Positive controls: these should have KCFI checks.  */
 /* { dg-final { scan-assembler {normal_function:.*ud2.*\.size\s+normal_function} { target x86_64-*-* } } } */
@@ -85,6 +86,8 @@ int main(void)
 /* { dg-final { scan-assembler {wrap_normal_inline:.*brk\s+#0x[0-9a-f]+.*\.size\s+wrap_normal_inline} { target aarch64*-*-* } } } */
 /* { dg-final { scan-assembler {normal_function:.*udf\t#[0-9]+.*\.size\s+normal_function} { target arm*-*-* } } } */
 /* { dg-final { scan-assembler {wrap_normal_inline:.*udf\t#[0-9]+.*\.size\s+wrap_normal_inline} { target arm*-*-* } } } */
+/* { dg-final { scan-assembler {normal_function:.*ebreak.*\.size\s+normal_function} { target riscv*-*-* } } } */
+/* { dg-final { scan-assembler {wrap_normal_inline:.*ebreak.*\.size\s+wrap_normal_inline} { target riscv*-*-* } } } */
 
 /* Negative controls: these should NOT have KCFI checks.  */
 /* { dg-final { scan-assembler-not {sensitive_non_inline_function:.*ud2.*\.size\s+sensitive_non_inline_function} { target x86_64-*-* } } } */
@@ -93,3 +96,5 @@ int main(void)
 /* { dg-final { scan-assembler-not {wrap_sensitive_inline:.*brk\s+#0x[0-9a-f]+.*\.size\s+wrap_sensitive_inline} { target aarch64*-*-* } } } */
 /* { dg-final { scan-assembler-not {sensitive_non_inline_function:[^\n]*udf\t#[0-9]+[^\n]*\.size\tsensitive_non_inline_function} { target arm*-*-* } } } */
 /* { dg-final { scan-assembler-not {wrap_sensitive_inline:[^\n]*udf\t#[0-9]+[^\n]*\.size\twrap_sensitive_inline} { target arm*-*-* } } } */
+/* { dg-final { scan-assembler-not {sensitive_non_inline_function:.*ebreak.*\.size\s+sensitive_non_inline_function} { target riscv*-*-* } } } */
+/* { dg-final { scan-assembler-not {wrap_sensitive_inline:.*ebreak.*\.size\s+wrap_sensitive_inline} { target riscv*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c +1 -0
index 9355d633301b..86855eca9d86 100644
@@ -38,3 +38,4 @@ int main() {
 /* In Thumb-2 the load base is ip (post-Thumb-bit-strip), in ARM mode it is
    the call target register; accept either.  */
 /* { dg-final { scan-assembler-times {ldr\tip, \[(?:r[0-9]+|ip), #-4\]} 1 { target arm*-*-* } } } */
+/* { dg-final { scan-assembler-times {lw\tt1, -[0-9]+\(} 1 { target riscv*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-offset-validation.c +3 -0
index cb1eb7c7ecc6..8d48c5f2ef23 100644
@@ -35,3 +35,6 @@ int main() {
    In Thumb-2 the load base is ip (after the Thumb-bit strip); in ARM mode it
    is the call target register directly.  Accept either.  */
 /* { dg-final { scan-assembler {ldr\tip, \[(?:r[0-9]+|ip), #-4\]} { target arm*-*-* } } } */
+
+/* RISC-V: All call sites should use -4 offset.  */
+/* { dg-final { scan-assembler {lw\tt1, -4\(} { target riscv*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-entry-only.c +8 -1
index 612140a0f509..db2ec8a5b64f 100644
@@ -29,7 +29,7 @@ int main() {
 */
 
 /*
-** __cfi_test_function: { target aarch64*-*-* arm*-*-* }
+** __cfi_test_function: { target aarch64*-*-* arm*-*-* riscv*-*-* }
 ** .word	0x[0-9a-f]+
 */
 
@@ -54,4 +54,11 @@ int main() {
 ** ...
 */
 
+/*
+** main: { target riscv*-*-* }
+** ...
+** lw	t1, -4\(a[0-9]+\)
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-large.c +9 -1
index 7f7ada17cc14..49a684b7ee15 100644
@@ -21,7 +21,7 @@ int main() {
 */
 
 /*
-** __cfi_test_function: { target aarch64*-*-* arm*-*-* }
+** __cfi_test_function: { target aarch64*-*-* arm*-*-* riscv*-*-* }
 ** .word	0x[0-9a-f]+
 */
 
@@ -46,4 +46,12 @@ int main() {
 ** ...
 */
 
+
+/*
+** main: { target riscv*-*-* }
+** ...
+** lw	t1, -48\(a[0-9]+\)
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-medium.c +8 -1
index 0a1f4e20851f..8d53407789cf 100644
@@ -28,7 +28,7 @@ int main() {
 */
 
 /*
-** __cfi_test_function: { target aarch64*-*-* arm*-*-* }
+** __cfi_test_function: { target aarch64*-*-* arm*-*-* riscv*-*-* }
 ** .word	0x[0-9a-f]+
 */
 
@@ -53,4 +53,11 @@ int main() {
 ** ...
 */
 
+/*
+** main: { target riscv*-*-* }
+** ...
+** lw	t1, -20\(a[0-9]+\)
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-prefix-only.c +8 -1
index 548a2f5d8b84..d85f7f907ce5 100644
@@ -29,7 +29,7 @@ int main() {
 */
 
 /*
-** __cfi_test_function: { target aarch64*-*-* arm*-*-* }
+** __cfi_test_function: { target aarch64*-*-* arm*-*-* riscv*-*-* }
 ** .word	0x[0-9a-f]+
 */
 
@@ -54,4 +54,11 @@ int main() {
 ** ...
 */
 
+/*
+** main: { target riscv*-*-* }
+** ...
+** lw	t1, -16\(a[0-9]+\)
+** ...
+*/
+
 /* { dg-final { check-function-bodies "**" "" "" { target *-*-* } {\.word} } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-riscv-32bit.c new file +7 -0
new file mode 100644
index 000000000000..8b2dc926c704
@@ -0,0 +1,7 @@
+/* Test that KCFI is rejected for 32-bit RISC-V.  */
+/* { dg-do compile { target riscv*-*-* } } */
+/* { dg-additional-options "-march=rv32gc -mabi=ilp32d" } */
+/* { dg-error ".-fsanitize=kcfi. is not supported for 32-bit RISC-V" "" { target *-*-* } 0 } */
+/* { dg-message "sorry, unimplemented: .-fsanitize=kcfi. not supported" "" { target *-*-* } 0 } */
+
+void foo (void) { }
gcc/testsuite/gcc.dg/kcfi/kcfi-riscv-fixed-t1.c new file +7 -0
new file mode 100644
index 000000000000..a5ef21092d63
@@ -0,0 +1,7 @@
+/* Test that KCFI is incompatible with -ffixed-t1 on RISC-V.  */
+/* { dg-do compile { target riscv*-*-* } } */
+/* { dg-additional-options "-ffixed-t1" } */
+/* { dg-error ".-fsanitize=kcfi. is not compatible with .-ffixed-t1., .-ffixed-t2., or .-ffixed-t3. as KCFI requires these registers for type checking" "" { target *-*-* } 0 } */
+/* { dg-message "sorry, unimplemented: .-fsanitize=kcfi. not supported" "" { target *-*-* } 0 } */
+
+void foo (void) { }
gcc/testsuite/gcc.dg/kcfi/kcfi-riscv-fixed-t2.c new file +7 -0
new file mode 100644
index 000000000000..3ead648e7154
@@ -0,0 +1,7 @@
+/* Test that KCFI is incompatible with -ffixed-t2 on RISC-V.  */
+/* { dg-do compile { target riscv*-*-* } } */
+/* { dg-additional-options "-ffixed-t2" } */
+/* { dg-error ".-fsanitize=kcfi. is not compatible with .-ffixed-t1., .-ffixed-t2., or .-ffixed-t3. as KCFI requires these registers for type checking" "" { target *-*-* } 0 } */
+/* { dg-message "sorry, unimplemented: .-fsanitize=kcfi. not supported" "" { target *-*-* } 0 } */
+
+void foo (void) { }
gcc/testsuite/gcc.dg/kcfi/kcfi-riscv-fixed-t3.c new file +7 -0
new file mode 100644
index 000000000000..98b579867a48
@@ -0,0 +1,7 @@
+/* Test that KCFI is incompatible with -ffixed-t3 on RISC-V.  */
+/* { dg-do compile { target riscv*-*-* } } */
+/* { dg-additional-options "-ffixed-t3" } */
+/* { dg-error ".-fsanitize=kcfi. is not compatible with .-ffixed-t1., .-ffixed-t2., or .-ffixed-t3. as KCFI requires these registers for type checking" "" { target *-*-* } 0 } */
+/* { dg-message "sorry, unimplemented: .-fsanitize=kcfi. not supported" "" { target *-*-* } 0 } */
+
+void foo (void) { }
gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c +23 -0
index 544ae7807297..f8a76d3ac4f6 100644
@@ -67,6 +67,8 @@ int test_non_tail_indirect_call(func_ptr_t handler, int x) {
 /* Should have exactly 4 trap sections and 4 trap instructions.  */
 /* { dg-final { scan-assembler-times "\\.kcfi_traps" 4 { target x86_64-*-* } } } */
 /* { dg-final { scan-assembler-times "ud2" 4 { target x86_64-*-* } } } */
+/* { dg-final { scan-assembler-times "\\.kcfi_traps" 4 { target riscv*-*-* } } } */
+/* { dg-final { scan-assembler-times "ebreak" 4 { target riscv*-*-* } } } */
 
 /* Should NOT have unprotected direct jumps to vtable.  */
 /* { dg-final { scan-assembler-not {jmp\t\*vtable\(%rip\)} { target x86_64-*-* } } } */
@@ -79,6 +81,27 @@ int test_non_tail_indirect_call(func_ptr_t handler, int x) {
 /* Should have exactly 1 regular call (non-tail call case).  */
 /* { dg-final { scan-assembler-times {call\t\*%[a-z0-9]+} 1 { target x86_64-*-* } } } */
 
+/* RISC-V: Should have exactly 4 KCFI checks for indirect calls
+   (comparison instruction).  */
+/* { dg-final { scan-assembler-times {beq\tt1, t2, \.Lkcfi_call[0-9]+} 4 { target riscv*-*-* } } } */
+
+/* RISC-V: Should have exactly 4 KCFI checks for indirect calls as
+   (load type ID + compare).  */
+/* { dg-final { scan-assembler-times {lw\tt1, -4\([a-z0-9]+\)} 4 { target riscv*-*-* } } } */
+/* { dg-final { scan-assembler-times {lui\tt2, [0-9]+} 4 { target riscv*-*-* } } } */
+
+/* RISC-V: Should have exactly 3 protected tail calls (jr after
+   KCFI check - no return address save).  */
+/* { dg-final { scan-assembler-times {jalr\t(x0|zero), [a-z0-9]+, 0} 3 { target riscv*-*-* } } } */
+
+/* RISC-V: Should have exactly 1 regular call (non-tail call case - saves
+   return address).  */
+/* { dg-final { scan-assembler-times {jalr\t(x1|ra), [a-z0-9]+, 0} 1 { target riscv*-*-* } } } */
+
+/* Type ID loading should use lui + addiw pattern for 32-bit constants.  */
+/* { dg-final { scan-assembler {lui\tt2, [0-9]+} { target riscv*-*-* } } } */
+/* { dg-final { scan-assembler {addiw\tt2, t2, -?[0-9]+} { target riscv*-*-* } } } */
+
 /* Should have exactly 4 KCFI checks for indirect calls (load type ID from
    -4 offset + compare).  The actual-type scratch register avoids the call
    target, so it is w9 for the sibcall targets (x16) and w16 otherwise; the
gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section-per-func.c +1 -1
index 448805a37808..7faeca95cac7 100644
@@ -8,7 +8,7 @@
    Only x86_64 and RISC-V use a .kcfi_traps section; AArch64 and ARM encode the
    trap information directly in the trap instruction's immediate.  */
 
-/* { dg-do compile { target x86_64-*-* } } */
+/* { dg-do compile { target x86_64-*-* riscv*-*-* } } */
 /* { dg-additional-options "-ffunction-sections" } */
 
 typedef int (*fn_t) (int);
gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c +3 -2
index e02a320f2f92..5d1159cfb39b 100644
@@ -20,9 +20,10 @@ int main() {
 /* { dg-final { scan-assembler-times {\.L[^:]+:\n\s*ud2} 2 { target x86_64-*-* } } } */
 /* { dg-final { scan-assembler-times {\.L[^:]+:\n\s*brk} 2 { target aarch64*-*-* } } } */
 /* { dg-final { scan-assembler-times {\.L[^:]+:\n\s*udf} 2 { target arm*-*-* } } } */
+/* { dg-final { scan-assembler-times {\.L[^:]+:\n\s*ebreak} 2 { target riscv*-*-* } } } */
 
-/* x86_64 should exactly 2 .kcfi_traps sections.  */
-/* { dg-final { scan-assembler-times {\.section\t\.kcfi_traps,"ao",@progbits,\.text} 2 { target x86_64-*-* } } } */
+/* x86_64 and RISC-V should exactly 2 .kcfi_traps sections.  */
+/* { dg-final { scan-assembler-times {\.section\t\.kcfi_traps,"ao",@progbits,\.text} 2 { target x86_64-*-* riscv*-*-* } } } */
 
 /* AArch64 and ARM 32-bit should NOT have .kcfi_traps section.  */
 /* { dg-final { scan-assembler-not {\.section\t+\.kcfi_traps} { target aarch64*-*-* arm*-*-* } } } */
Signature · 1 line
2.55.0
#11 lore raw

Re: [PATCH v17 7/7] riscv: Add RISC-V Kernel Control Flow Integrity implementation

Quoted 5 lines · Kees Cook

Implement RISC-V-specific KCFI backend. This is rv64-only: the emitted typeid construction uses addiw, which exists only on RV64/RV128. An rv32 backend would need an alternate sequence (e.g. addi); since the only current user of KCFI on riscv is the rv64 build of the Linux kernel, the support hook rejects rv32.

Note that addiw explicitly sign extends the result from bit 32 out to bit 63.   That seems to match what you want with the implementation (since you do a lw do load the ID from the preamble and that's sign-extending from bit 32 to bit 63.

Quoted 11 lines

- Scratch register allocation using t1/t2 (x6/x7) following RISC-V procedure call standard for temporary registers (already caller-saved), and t3 (x28) when either t1 or t2 is already the call target register.

- Incompatible with -ffixed-t1, -ffixed-t2, or -ffixed-t3.

- Integration with .kcfi_traps section for debugger/runtime metadata (like x86_64).

Quoted 7 lines

Assembly Code Pattern for RISC-V:

   lw      t1, -4(target_reg)         ; Load actual type ID from preamble
   lui     t2, %hi(expected_type)     ; Load expected type (upper 20 bits)
   addiw   t2, t2, %lo(expected_type) ; Add lower 12 bits (sign-extended)
   beq     t1, t2, .Lkcfi_call        ; Branch if types match

.Lkcfi_trap: ebreak ; Environment break trap on mismatch
.Lkcfi_call: jalr/jr target_reg ; Execute validated indirect transfer

So what I can't recall ever seeing is an explanation of why this sequence needs to be emitted as a single assembly block.  That's something we generally try to avoid.  Now if that design decision/need is covered in the talk from the Cauldron, that's fine.  I was intercepted and couldn't get there in time, but I'll certainly make a point to watch the whole thing.

And note that if it really needs to be an atomic sequence, there's still ways to achieve that that avoid the blobs of assembly code.  See below.

Quoted 52 lines

Build and run tested with Linux kernel ARCH=riscv.

Assisted-by LLM [tests]

gcc/ChangeLog:

* config/riscv/riscv-protos.h: Declare KCFI helpers.
* config/riscv/riscv.cc (riscv_maybe_wrap_call_with_kcfi): New function, to wrap calls. (riscv_maybe_wrap_call_value_with_kcfi): New function, to wrap calls with return values. (riscv_output_kcfi_insn): New function to emit KCFI assembly.
* config/riscv/riscv.md: Add KCFI RTL patterns and hook expansion.
* doc/invoke.texi: Document riscv nuances.

gcc/testsuite/ChangeLog:

* gcc.dg/kcfi/kcfi-adjacency.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-basics.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-call-sharing.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-complex-addressing.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-direct-call-shapes.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-move-preservation.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-no-sanitize-inline.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-no-sanitize.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-offset-validation.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-patchable-entry-only.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-patchable-large.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-patchable-medium.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-patchable-prefix-only.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-tail-calls.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-trap-section.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-trap-section-per-func.c: Add riscv patterns.
* gcc.dg/kcfi/kcfi-riscv-32bit.c: New test.
* gcc.dg/kcfi/kcfi-riscv-fixed-t1.c: New test.
* gcc.dg/kcfi/kcfi-riscv-fixed-t2.c: New test.
* gcc.dg/kcfi/kcfi-riscv-fixed-t3.c: New test.

---

gcc/config/riscv/riscv.cc +6 -0
+
+/* Output the assembly for a KCFI checked call instruction.  INSN is the
+   RTL instruction being processed.  OPERANDS is the array of RTL operands
+   where operands[0] is the call target register, operands[2] is the KCFI
+   type ID constant.  Returns an empty string as all output is handled by
+   direct assembly generation.  */

gcc/config/riscv/riscv.cc riscv_convert_vector_chunks (struct gcc_options *opts) · line 12423

Quoted 10 lines
gcc/config/riscv/riscv.cc +10 -0
+
+const char *
+riscv_output_kcfi_insn (rtx_insn *insn, rtx *operands)
+{
+  /* Target register.  */
+  rtx target_reg = operands[0];
+  gcc_assert (REG_P (target_reg));
+
+  /* Get KCFI type ID.  */
+  uint32_t expected_type = UINTVAL (operands[2]);

Generally you don't want to be using types like uint32_t, uint64_t, etc.  Those are properties of the host, not the target.   Given that you're using "lw" and a sign extending "addiw", you probably want this to be a HOST_WIDE_INT (vs an unsigned HOST_WIDE_INT).  It probably doesn't matter in practice here, but  if you're pulling data out via [U]INTVAL, then destination data type should generally be a HOST_WIDE_INT or unsigned variant of the same.

gcc/config/riscv/riscv.cc riscv_convert_vector_chunks (struct gcc_options *opts) · line 12430

Quoted 7 lines
gcc/config/riscv/riscv.cc +7 -0
+
+  /* Calculate typeid offset from call target.  */
+  HOST_WIDE_INT offset = -kcfi_get_typeid_offset ();
+
+  /* Choose scratch registers that don't conflict with target.  */
+  unsigned temp1_regnum = T1_REGNUM;
+  unsigned temp2_regnum = T2_REGNUM;

Why use fixed registers?   It would seem to work better if you just generated pseudos and let the register allocator do the right thing and assign them to whatever temporary is best.  That would also remove the restrictions around -ffixed-reg.

gcc/config/riscv/riscv.cc riscv_convert_vector_chunks (struct gcc_options *opts) · line 12463

Quoted 12 lines
gcc/config/riscv/riscv.cc +12 -0
+
+  rtx temp_operands[3];
+
+  /* The check sequence (typeid load through indirect jump) must be emitted
+     as a single atomic unit: a mismatch must be caught before the jalr
+     executes, with no opportunity for the linker or assembler to interleave
+     anything.  Disable linker relaxation (which can rewrite jalr/call forms
+     and shift offsets) and the C extension (which can shrink instructions
+     and perturb sizes the length attribute reports) for the duration.  */
+  output_asm_insn (".option push", operands);
+  output_asm_insn (".option norelax", operands);
+  output_asm_insn (".option norvc", operands);

Why does this need to be an atomic sequence with restrictions around relaxing and compression avoidance?  From other comments I'm guessing you're rewriting that ebreak.  At the least you need to explain why its an atomic sequence.

gcc/config/riscv/riscv.cc riscv_convert_vector_chunks (struct gcc_options *opts) · line 12470

Quoted 7 lines
gcc/config/riscv/riscv.cc +7 -0
+
+  /* Load actual type from memory at offset.  */
+  temp_operands[0] = gen_rtx_REG (SImode, temp1_regnum);
+  temp_operands[1] = gen_rtx_MEM (SImode,
+				  gen_rtx_PLUS (DImode, target_reg,
+						GEN_INT (offset)));
+  output_asm_insn ("lw\t%0, %1", temp_operands);

So if we really don't need to generate an atomic sequence, then you've got the skeleton for generating RTL here.  You've got the register destination and memory source.  So instead of output_asm_insn, you'd do something like:

emit_move_insn (temp_operands[0], temp_operands[1]);

gcc/config/riscv/riscv.cc riscv_convert_vector_chunks (struct gcc_options *opts) · line 12480

Quoted 10 lines
gcc/config/riscv/riscv.cc +10 -0
+
+  /* Load expected type using lui + addiw for proper sign extension.  */
+  temp_operands[0] = gen_rtx_REG (SImode, temp2_regnum);
+  temp_operands[1] = GEN_INT (hi20);
+  output_asm_insn ("lui\t%0, %1", temp_operands);
+
+  temp_operands[0] = gen_rtx_REG (SImode, temp2_regnum);
+  temp_operands[1] = gen_rtx_REG (SImode, temp2_regnum);
+  temp_operands[2] = GEN_INT (lo12);
+  output_asm_insn ("addiw\t%0, %1, %2", temp_operands);

All that turns into dest = force_reg (SImode, GEN_INT (expected_type));

gcc/config/riscv/riscv.cc riscv_convert_vector_chunks (struct gcc_options *opts) · line 12486

Quoted 6 lines
gcc/config/riscv/riscv.cc +6 -0
+
+  /* Output conditional branch to call label.  */
+  fprintf (asm_out_file, "\tbeq\t%s, %s, ",
+	   reg_names[temp1_regnum], reg_names[temp2_regnum]);
+  assemble_name (asm_out_file, call_name);
+  fputc ('\n', asm_out_file);

And you'd emit a conditional branch here via emit_jump_insn after generating appropriate RTL.

gcc/config/riscv/riscv.cc riscv_convert_vector_chunks (struct gcc_options *opts) · line 12490

Quoted 4 lines
gcc/config/riscv/riscv.cc +4 -0
+
+  /* Output trap label and ebreak instruction.  */
+  ASM_OUTPUT_LABEL (asm_out_file, trap_name);
+  output_asm_insn ("ebreak", operands);

This is a "trap" insn.  So

emit_insn (gen_trap ()); or something along those lines.

gcc/config/riscv/riscv.cc riscv_convert_vector_chunks (struct gcc_options *opts) · line 12494

Quoted 4 lines
gcc/config/riscv/riscv.cc +4 -0
+
+  /* Use common helper for trap section entry.  */
+  rtx trap_label_sym = gen_rtx_SYMBOL_REF (Pmode, trap_name);
+  kcfi_emit_traps_section (asm_out_file, trap_label_sym, labelno);

So do you do something fun like rewrite the trap?  Is that why you're generating the atomic sequence?  ANd if so, we can still get you an atomic sequence without emitting blobs of assembly code via emit_barrier () at the start and end of the atomic sequence.

If you're rewriting the trap, then I'd probably do somethign like

1. Define a new insn that has the same basic properties as a barrier, but emits the .option thingies at the start of the sequence.
2. Define another new insn also with barrier semantics that emits the option pop.
3. Convert riscv_output_kcfi_insn to emit RTL instead and hook into the define_expands.  It'll need to generate the insns you created in steps #1 and #2.

Note that steps #1 and #2 would in turn allow others to simplify other parts of the RISC-V port as well.  Not the main motivation, but worth noting.

gcc/config/riscv/riscv.cc riscv_memtag_tag_bitsize () · line 17542

Quoted 13 lines
gcc/config/riscv/riscv.cc +6 -0
+
  /* 'Unpack' up the internal tuning structs and update the options
      in OPTS.  The caller must have set up selected_tune and selected_arch
      as all the other target-specific codegen decisions are
@@ -17360,6 +17535,30 @@ riscv_memtag_tag_bitsize ()
  #undef TARGET_MEMTAG_TAG_BITSIZE
  #define TARGET_MEMTAG_TAG_BITSIZE riscv_memtag_tag_bitsize
 
+/* Return true if the target supports KCFI.
+   KCFI requires 64-bit mode and the T1, T2, and T3 registers.  */
+
+static bool
+riscv_kcfi_supported_p (void)

We probably need to avoid for C++ due to thunks and Fortran due to multiple entry points.  And you may not have a good way to test for those, particularly in an LTO build.  We need to think about that problem.  There are ways to identify multiple entry points, but those assume you've got a control flow graph for the current function.  So they probably won't work here and we can't really check for what language is in use (think about LTO).

gcc/doc/invoke.texi allowing the kernel to identify both the KCFI violation and the involved · line 17637

Quoted 13 lines
gcc/doc/invoke.texi +4 -0
index f0b1314d1731..b1ebae37ed89 100644
@@ -17631,6 +17631,23 @@ allowing the kernel to identify both the KCFI violation and the involved
  registers for detailed diagnostics (eliminating the need for a separate
  @code{.kcfi_traps} section as used on x86_64).
 
+On 64-bit RISC-V, KCFI type identifiers are emitted as a @code{.word ID}
+directive (a 32-bit constant) before the function entry, similar to AArch64.
+RISC-V's natural instruction alignment eliminates the need for
+additional alignment NOPs.

Really?  Natural instruction alignment for the designs I expect to see almost everywhere is 16 bits (via the C extension which is mandatory for rva23 and used in nearly design I'm aware of).  So you've got a bit of a problem here as unaligned access isn't necessary guaranteed to work.  You could do something like force the function alignment to 4 bytes when KFCI is on.  A bit hackish, but probably sensible in practice.

gcc/doc/invoke.texi allowing the kernel to identify both the KCFI violation and the involved · line 17639

Quoted 3 lines
gcc/doc/invoke.texi +2 -0
   When used with @option{-fpatchable-function-entry},
+the type identifier is placed before any prefix NOPs.  The runtime check
+loads the actual type using @code{lw t1, OFFSET(target_reg)}, where the

Is the offset always at -4?  Just helps me understand the underlying assumptions you need to make.

Jeff

author
#12 lore raw

Re: [PATCH v17 7/7] riscv: Add RISC-V Kernel Control Flow Integrity implementation

Quoted 4 lines · Jeff Law

Note that addiw explicitly sign extends the result from bit 32 out to bit 63.   That seems to match what you want with the implementation (since you do a lw do load the ID from the preamble and that's sign-extending from bit 32 to bit 63.

Right, both sides of the beq are sign-extended the same way, so the comparison works for type IDs with bit 31 set. I was suspicious of the sign extension myself and had double-checked it at the edges just to be sure when I first worked on this. :)

Quoted 6 lines

So what I can't recall ever seeing is an explanation of why this sequence needs to be emitted as a single assembly block.  That's something we generally try to avoid.  Now if that design decision/need is covered in the talk from the Cauldron, that's fine.  I was intercepted and couldn't get there in time, but I'll certainly make a point to watch the whole thing.

You asked this back in v2, and my reply then[1] wasn't very helpful. Sorry about that! Here's hopefully more complete reasoning; v18 will also put it in the design comment at the top of kcfi.cc, since you're right that it was only asserted there.

1. The checked target must stay in the checked register until the call. If the register allocator spilled it after the check and reloaded it (or rematerialized it) before the call, memory an attacker can write would supply an unchecked target, effectively restoring the "pop %target; call %target" gadget that KCFI seeks to remove. Separate insns would give reload and the post-reload passes the freedom to create it again, which needs to be avoided.

2. The trap isn't noreturn. It is designed to be continuable: Linux has a permissive (warn-only) mode where the trap handler reports the mismatch and returns, and execution continues into the call right after it. So the trap can't be gen_trap() with a barrier after it, and the trap block must not be moved out of line by bb-reorder or hot/cold partitioning, even though it looks cold.

3. The kernel depends on the exact layout. (This is, of course, changeable, but it would require coordination with Linux and Clang.) Specifically on RISC-V, Linux's trap handler (arch/riscv/kernel/cfi.c) reads the beq just before the ebreak to find the register holding the expected type, and the jalr just after it to find the target. On x86, the kernel may rewrite every KCFI call site in place into the FineIBT sequence at boot, patching a fixed number of bytes before the call.

FWIW, Clang KCFI is built the same way: its RISC-V backend emits a KCFI_CHECK pseudo that must immediately precede the call through the same register (it asserts this), and expands it with specific scratch registers when the assembly is printed (RISCVAsmPrinter::LowerKCFI_CHECK).

Quoted 7 lines

And note that if it really needs to be an atomic sequence, there's still ways to achieve that that avoid the blobs of assembly code.  See below.

Generally you don't want to be using types like uint32_t, uint64_t, etc.  Those are properties of the host, not the target.   Given that you're using "lw" and a sign extending "addiw", you probably want this to be a HOST_WIDE_INT (vs an unsigned HOST_WIDE_INT).  It probably

Ah, yes. This is now fixed in v18: RISC-V will hold it as a HOST_WIDE_INT, sign-extended from bit 31 to match the lw and addiw, and the other three backends will hold it as an unsigned HOST_WIDE_INT. The generated code doesn't change.

I went through the rest of the series for the same problem. The type ID itself will stay a uint32_t: the ABI defines it as a 32-bit FNV-1a hash, computed on the host, so that's the arithmetic it needs. Now __builtin_linux_abi_kcfi_hash will return a 32-bit unsigned type even where int is 16 bits, and the type ID's size in the preamble will be a named constant instead of sizeof (uint32_t).

Quoted 4 lines

Why use fixed registers?   It would seem to work better if you just generated pseudos and let the register allocator do the right thing and assign them to whatever temporary is best.  That would also remove the restrictions around -ffixed-reg.

I'd love to, but the KCFI check is part of/within the call insn and LRA allows no output reloads in a CALL_INSN:

	/* CALL_INSNs are not allowed to have any output reloads.  */
	if (CALL_P (curr_insn))
	  no_output_reloads_p = true;

So under register pressure the allocator can't provide a scratch register for the call pattern, so I had to have each backend instead pick scratch registers that are dead at the call (caller-saved temporaries that aren't argument registers or the target). I went through this with Andrea for AArch64[2][3]. Moving the check out into separate insns, so that pseudos would work, runs into point 1 above.

And trying to create an entirely new mode of register allocation for use within a CALL_INSN seemed like serious over-kill, given the other narrow constraints on KCFI.

The -ffixed-reg restriction could go, though: Clang uses t1 and t2 and falls back to t3 through t6, skipping any the user reserved, so it never has to reject fixed registers. I could do the same here, but I had so much pain making the ARM backend do this that I didn't want to tackle it again. :P But I can if you'd like to see that here too.

Quoted 4 lines

Why does this need to be an atomic sequence with restrictions around relaxing and compression avoidance?  From other comments I'm guessing you're rewriting that ebreak.  At the least you need to explain why its an atomic sequence.

The atomicity is for the reasons above; the kernel doesn't rewrite the ebreak on RISC-V (x86 is where call sites get rewritten).

The directives came from your v12 review[4], where you said that if the sequence really must be atomic, it should be wrapped in directives so the assembler and linker don't expand macros or relax. However, in looking at it more closely now, neither can affect this sequence:

- Nothing in it can be relaxed: the lw is register-relative, the lui and addiw take plain constants with no relocations, the beq goes to a local label, and the jalr is through a register. The linker only relaxes symbol-based sequences marked R_RISCV_RELAX.

- None of the instructions is an assembler macro.

- Compression is harmless: the assembler may use c.lui, c.addiw, c.jalr, or c.ebreak, but the beq can never be compressed (t1 and t2 aren't in the compressed register set, and c.beqz only compares against zero), and the kernel's decoder reads the beq at epc - 4, accepts jalr or c.jalr, and steps over the ebreak by its actual length.

So v18 will drop ".option norelax" and ".option norvc", which also lets the sequence shrink with C, and matches Clang, which has none of these directives either.

Quoted 6 lines

So if we really don't need to generate an atomic sequence, then you've got the skeleton for generating RTL here.  You've got the register

This is a "trap" insn.  So

emit_insn (gen_trap ()); or something along those lines.

As in point 2, it can't be a trap with the usual noreturn semantics, since execution continues from it into the call in permissive mode.

Quoted 4 lines

So do you do something fun like rewrite the trap?  Is that why you're generating the atomic sequence?  ANd if so, we can still get you an atomic sequence without emitting blobs of assembly code via emit_barrier () at the start and end of the atomic sequence.

Marker insns at the start and end would keep the scheduler from moving things across them, but they wouldn't stop reload from inserting spill code between the check and the call (point 1), and the beq would split the sequence into basic blocks that bb-reorder and partitioning are free to rearrange (point 2). If there's a way to pin all of that down, I'm happy to try it, but it seemed to fight the compiler at every step, while emitting the sequence from the call pattern's output routine appears to be the simplest and most robust way to get the right output. (And, FWIW, Clang ended up in the same place too.)

Quoted 3 lines

We probably need to avoid for C++ due to thunks and Fortran due to multiple entry points.  And you may not have a good way to test for those, particularly in an LTO build.  We need to think about that

KCFI is C-only: process_options() rejects -fsanitize=kcfi for any other front end. And while I tried to enforce this under LTO too, I did now find a way that it fails. The check for language accepted LTO's "GNU GIMPLE", but that meant a C++ object built with -flto and linked with -fsanitize=kcfi would crash on a METHOD_TYPE. v18 will check the language of every translation unit the IL came from (TRANSLATION_UNIT_LANGUAGE survives streaming), and reject anything that isn't C, reporting the offending file:

thunk.cc:3:49: sorry, unimplemented: '-fsanitize=kcfi' is only supported for C, but 'thunk.cc' was compiled by the GNU C++20 front end

I tested this by hand (and that C-only LTO links are still instrumented), but I couldn't find a way to add a regression test for it: the case needs -fsanitize=kcfi at link time only, which means lto.exp, and lto.exp has no way to expect a link to fail; any failed link is a FAIL. If there's a way to do this that I've missed, I'd be happy to add one.

Quoted 6 lines

Really?  Natural instruction alignment for the designs I expect to see almost everywhere is 16 bits (via the C extension which is mandatory for rva23 and used in nearly design I'm aware of).  So you've got a bit of a problem here as unaligned access isn't necessary guaranteed to work. You could do something like force the function alignment to 4 bytes when KFCI is on.  A bit hackish, but probably sensible in practice.

Oops, yes, thank you for persisting on this. :P You mentioned it in v12 too, but I misunderstood it: ".option norvc" around the call sequence did nothing for the alignment of the functions it calls. With the C extension the preamble was only 2-byte aligned, so the lw could be misaligned (and so could the ldr on Thumb at -Os). Clang aligns every function that has a KCFI type ID to at least 4 bytes, on all targets, "to avoid unaligned access". v18 will do the same, and fix that paragraph of the documentation.

Quoted 2 lines

Is the offset always at -4?  Just helps me understand the underlying assumptions you need to make.

It's -4 plus the size of any prefix NOPs from -fpatchable-function-entry=N,M, since the type ID sits before them. (Call sites can't see per-function patchable_function_entry attributes, so KCFI rejects those and uses only the global option.)

But checking this turned up the bug you were predicting about NOP sizing in your 2/7 review. I had sized each prefix NOP from the nop insn's length attribute (4 bytes), but with the C extension the assembler emits c.nop (2 bytes), so with prefix NOPs the call sites loaded from the wrong offset. As you pointed out, lengths are only upper bounds. v18 will add a TARGET_KCFI_NOP_SIZE hook for the size the assembler actually emits; RISC-V will return 2 with C or Zca, matching Clang. More on this in the 2/7 reply...

Thank you for the review! :)

-Kees

[1] https://inbox.sourceware.org/gcc-patches/202509152254.8A38F96D91@keescook/
[2] https://inbox.sourceware.org/gcc-patches/202509141233.33B8C6D4@keescook/
[3] https://inbox.sourceware.org/gcc-patches/202509171251.BA32F4B@keescook/
[4] https://inbox.sourceware.org/gcc-patches/[email protected]/

Signature · 1 line
Kees Cook
#13 lore raw

Re: [PATCH v17 7/7] riscv: Add RISC-V Kernel Control Flow Integrity implementation

Quoted 29 lines · Kees Cook

You asked this back in v2, and my reply then[1] wasn't very helpful. Sorry about that! Here's hopefully more complete reasoning; v18 will also put it in the design comment at the top of kcfi.cc, since you're right that it was only asserted there.

1. The checked target must stay in the checked register until the call. If the register allocator spilled it after the check and reloaded it (or rematerialized it) before the call, memory an attacker can write would supply an unchecked target, effectively restoring the "pop %target; call %target" gadget that KCFI seeks to remove. Separate insns would give reload and the post-reload passes the freedom to create it again, which needs to be avoided.

2. The trap isn't noreturn. It is designed to be continuable: Linux has a permissive (warn-only) mode where the trap handler reports the mismatch and returns, and execution continues into the call right after it. So the trap can't be gen_trap() with a barrier after it, and the trap block must not be moved out of line by bb-reorder or hot/cold partitioning, even though it looks cold.

3. The kernel depends on the exact layout. (This is, of course, changeable, but it would require coordination with Linux and Clang.) Specifically on RISC-V, Linux's trap handler (arch/riscv/kernel/cfi.c) reads the beq just before the ebreak to find the register holding the expected type, and the jalr just after it to find the target. On x86, the kernel may rewrite every KCFI call site in place into the FineIBT sequence at boot, patching a fixed number of bytes before the call.

Quoted 4 lines

FWIW, Clang KCFI is built the same way: its RISC-V backend emits a KCFI_CHECK pseudo that must immediately precede the call through the same register (it asserts this), and expands it with specific scratch registers when the assembly is printed (RISCVAsmPrinter::LowerKCFI_CHECK).

THanks.  As noted on the other patch.  I'll ponder this, particularly #1, that may be what carries the day.

Quoted 12 lines
Quoted 5 lines

Why use fixed registers?   It would seem to work better if you just generated pseudos and let the register allocator do the right thing and assign them to whatever temporary is best.  That would also remove the restrictions around -ffixed-reg.

I'd love to, but the KCFI check is part of/within the call insn and LRA allows no output reloads in a CALL_INSN:

	/* CALL_INSNs are not allowed to have any output reloads.  */
	if (CALL_P (curr_insn))
	  no_output_reloads_p = true;
Quoted 6 lines

So under register pressure the allocator can't provide a scratch register for the call pattern, so I had to have each backend instead pick scratch registers that are dead at the call (caller-saved temporaries that aren't argument registers or the target). I went through this with Andrea for AArch64[2][3]. Moving the check out into separate insns, so that pseudos would work, runs into point 1 above.

But it'd be an input reload, not an output reload since it's reloading for the call address, not the result of the call.  Perhaps if the value were needed after the call because we made multiple indirect calls through the same pseudo register, the pseudo does not get a hard register and the indirect call insns require a call clobbered register for the call address -- *maybe*.  But off the top of my head I'd kind of expect that to be a series of input reloads rather than a series of in/out reloads.

Quoted 4 lines

And trying to create an entirely new mode of register allocation for use within a CALL_INSN seemed like serious over-kill, given the other narrow constraints on KCFI.

Certainly wouldn't suggest that.  Just seems like standard mechanisms ought to be working here at least at first glance.

Quoted 21 lines

The atomicity is for the reasons above; the kernel doesn't rewrite the ebreak on RISC-V (x86 is where call sites get rewritten).

The directives came from your v12 review[4], where you said that if the sequence really must be atomic, it should be wrapped in directives so the assembler and linker don't expand macros or relax. However, in looking at it more closely now, neither can affect this sequence:

- Nothing in it can be relaxed: the lw is register-relative, the lui and addiw take plain constants with no relocations, the beq goes to a local label, and the jalr is through a register. The linker only relaxes symbol-based sequences marked R_RISCV_RELAX.

- None of the instructions is an assembler macro.

- Compression is harmless: the assembler may use c.lui, c.addiw, c.jalr, or c.ebreak, but the beq can never be compressed (t1 and t2 aren't in the compressed register set, and c.beqz only compares against zero), and the kernel's decoder reads the beq at epc - 4, accepts jalr or c.jalr, and steps over the ebreak by its actual length.

Quoted 3 lines

So v18 will drop ".option norelax" and ".option norvc", which also lets the sequence shrink with C, and matches Clang, which has none of these directives either.

Must have been a mismatch between what I thought you needed and reality.  Sorry about the bad steer.

Jeff

author
#14 lore raw

Re: [PATCH v17 7/7] riscv: Add RISC-V Kernel Control Flow Integrity implementation

Quoted 24 lines · Jeff Law
Quoted 7 lines · Kees Cook

I'd love to, but the KCFI check is part of/within the call insn and LRA allows no output reloads in a CALL_INSN:

	/* CALL_INSNs are not allowed to have any output reloads.  */
	if (CALL_P (curr_insn))
	  no_output_reloads_p = true;
Quoted 6 lines

So under register pressure the allocator can't provide a scratch register for the call pattern, so I had to have each backend instead pick scratch registers that are dead at the call (caller-saved temporaries that aren't argument registers or the target). I went through this with Andrea for AArch64[2][3]. Moving the check out into separate insns, so that pseudos would work, runs into point 1 above.

But it'd be an input reload, not an output reload since it's reloading for the call address, not the result of the call.  Perhaps if the value were needed after the call because we made multiple indirect calls through the same pseudo register, the pseudo does not get a hard register and the indirect call insns require a call clobbered register for the call address -- *maybe*.  But off the top of my head I'd kind of expect that to be a series of input reloads rather than a series of in/out reloads.

Quoted 1 line
Quoted 5 lines
Quoted 3 lines

And trying to create an entirely new mode of register allocation for use within a CALL_INSN seemed like serious over-kill, given the other narrow constraints on KCFI.

Certainly wouldn't suggest that.  Just seems like standard mechanisms ought to be working here at least at first glance.

Is there some way to have only an input reload? I totally failed to convince LRA to do _any_ kind of register allocation for me in these sequences, and boy would I have preferred it do the work. ARM was especially gross for doing this by hand.

Signature · 1 line
Kees Cook
#15 lore raw

Re: [PATCH v17 7/7] riscv: Add RISC-V Kernel Control Flow Integrity implementation

Quoted 9 lines · Kees Cook
Quoted 5 lines
Quoted 3 lines

And trying to create an entirely new mode of register allocation for use within a CALL_INSN seemed like serious over-kill, given the other narrow constraints on KCFI.

Certainly wouldn't suggest that.  Just seems like standard mechanisms ought to be working here at least at first glance.

Is there some way to have only an input reload? I totally failed to convince LRA to do _any_ kind of register allocation for me in these sequences, and boy would I have preferred it do the work. ARM was especially gross for doing this by hand.

Reloading is based on operand predicates & constraints, it's not something we get direct control over.

Essentially the register allocator does its thing and tries to pack the infinite pseudos onto the targets register set.  In a perfect world you can map all the pseudos to a physical register and the physical register chosen matches the constraints for the operand -- but it is common for there to be too many live values at any given point or to get the wrong kind of register.

So after IRA is done, LRA examines every operand in every pattern and verifies if the operand matches its constraint.  If there is a mismatch, then LRA will reload the value so that the constraints are satisfied.  LRA will examine how the operand is used to determine the kind of reload that's needed.  You're already aware of INPUT, OUTPUT and INOUT.  But there's other cases.  For example, you might need an address reload for an output operand.  So it's an input reload, but used for the output phase.  I don't remember the name for this one, but raise it as an example of the kinds of scenarios LRA deals with.  There's an ordering and lifetime defined for each type of reload so that reload registers can potentially be shared. So if you need an address reload for both an input and output operand, you can often use the same register for the two needs.

Jeff