Skip to contentSkip to conversation

Introduce Kernel Control Flow Integrity ABI [PR107048]

RFC PATCH Superseded Kees Cook 6 participants 43 messages Aug 21, 2025 – Sep 4, 2025 3 messages not in the archive RISC-V

v1 of 17 Superseded Latest is v17 →

lore
Share & tools
lore

Kees Cook

author
#0 lore raw

cover Introduce Kernel Control Flow Integrity ABI [PR107048]

Hi!

Repeating the start of the 3rd (core kcfi) patch's commit log:

This series 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.

Just to set expectations, this is an RFC because this is my first time working on most of the affected areas in GCC, and it is likely I have missed really obvious stuff, or gone about doing things in very wrong ways. I tried to find the best way to do stuff, but I was left with many questions. :) All that said, this works for x86_64 and aarch64 Linux kernels. (I have implemented riscv64 as well, but I lack a viable test environment -- I am working on this still.)

I tried to get comments and code style into reasonable shape so as to not distract horribly from the actual implementation details, but I suspect I'm still missing some correct style in places. The commit logs are not in proper ChangeLog format either. I am planning to get that sorted once this series has gotten some review and I've actually got code in the right places.

I gave up on trying to keep the testsuite files wrapped at 80 characters. It seemed much less readable, but I will defer to whatever folks want to see there. :)

Thanks!

-Kees

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=107048
https://github.com/KSPP/linux/issues/369

Kees Cook (7):
sanitizer: Expand sanitizer flag from 32-bit to 64-bit
mangle: Introduce C typeinfo mangling API
kcfi: Add core Kernel Control Flow Integrity infrastructure
x86: Add x86_64 Kernel Control Flow Integrity implementation
aarch64: Add AArch64 Kernel Control Flow Integrity implementation
riscv: Add RISC-V Kernel Control Flow Integrity implementation
kcfi: Add regression test suite

 gcc/Makefile.in                               |   2 +
 gcc/asan.h                                    |   4 +-
 gcc/c-family/c-common.h                       |   2 +-
 gcc/config/aarch64/aarch64-protos.h           |   4 +
 gcc/config/i386/i386-protos.h                 |   4 +
 gcc/config/riscv/riscv-protos.h               |   1 +
 gcc/flag-types.h                              |  66 +-
 gcc/kcfi.h                                    |  85 ++
 gcc/mangle.h                                  |  29 +
 gcc/opts.h                                    |   8 +-
 gcc/selftest.h                                |   1 +
 gcc/tree-pass.h                               |   1 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-esr.c  |  36 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c    |  83 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c       |  83 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c |  75 ++
 .../gcc.dg/kcfi/kcfi-cold-partition.c         | 133 +++
 .../gcc.dg/kcfi/kcfi-complex-addressing.c     | 116 +++
 .../gcc.dg/kcfi/kcfi-insn-sequence.c          |  42 +
 .../gcc.dg/kcfi/kcfi-ipa-robustness.c         |  54 ++
 .../gcc.dg/kcfi/kcfi-no-sanitize-inline.c     |  96 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c  |  39 +
 .../gcc.dg/kcfi/kcfi-offset-validation.c      |  41 +
 .../gcc.dg/kcfi/kcfi-patchable-basic.c        |  54 ++
 .../gcc.dg/kcfi/kcfi-patchable-entry-only.c   |  36 +
 .../gcc.dg/kcfi/kcfi-patchable-large.c        |  47 +
 .../gcc.dg/kcfi/kcfi-patchable-medium.c       |  52 ++
 .../gcc.dg/kcfi/kcfi-patchable-none.c         |  18 +
 .../gcc.dg/kcfi/kcfi-patchable-prefix-only.c  |  48 +
 .../gcc.dg/kcfi/kcfi-pic-addressing.c         |  98 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c   | 111 +++
 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c |  56 ++
 .../gcc.dg/kcfi/kcfi-type-mangling.c          | 864 ++++++++++++++++++
 gcc/c-family/c-attribs.cc                     |  19 +-
 gcc/c/c-parser.cc                             |   4 +-
 gcc/cfgcleanup.cc                             |  20 +
 gcc/cfgexpand.cc                              |  61 ++
 gcc/combine.cc                                |   1 +
 gcc/common.opt                                |   2 +-
 gcc/config/aarch64/aarch64.cc                 | 112 +++
 gcc/config/aarch64/aarch64.md                 | 137 +++
 gcc/config/i386/i386-options.cc               |   3 +
 gcc/config/i386/i386.cc                       | 128 +++
 gcc/config/i386/i386.md                       | 144 +++
 gcc/config/riscv/riscv.cc                     | 157 ++++
 gcc/config/riscv/riscv.md                     |  49 +
 gcc/cp/typeck.cc                              |   2 +-
 gcc/d/d-attribs.cc                            |   8 +-
 gcc/doc/invoke.texi                           |  76 ++
 gcc/dwarf2asm.cc                              |   2 +-
 gcc/emit-rtl.cc                               |   1 +
 gcc/kcfi.cc                                   | 783 ++++++++++++++++
 gcc/mangle.cc                                 | 548 +++++++++++
 gcc/opts.cc                                   |  17 +-
 gcc/passes.cc                                 |   1 +
 gcc/passes.def                                |   3 +
 gcc/recog.cc                                  |   1 +
 gcc/reg-notes.def                             |   6 +
 gcc/targhooks.cc                              |  50 +-
 gcc/testsuite/gcc.dg/kcfi/kcfi.exp            |  36 +
 gcc/toplev.cc                                 |   8 +
 gcc/varasm.cc                                 |  18 +
 62 files changed, 4721 insertions(+), 65 deletions(-)
 create mode 100644 gcc/kcfi.h
 create mode 100644 gcc/mangle.h
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-esr.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.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-insn-sequence.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-ipa-robustness.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-basic.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-entry-only.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-none.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-prefix-only.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-pic-addressing.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-type-mangling.c
 create mode 100644 gcc/kcfi.cc
 create mode 100644 gcc/mangle.cc
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi.exp
Signature · 1 line
2.34.1
author
#1 lore raw

RFC PATCH 1/7 sanitizer: Expand sanitizer flag from 32-bit to 64-bit

Extend the sanitizer flags infrastructure from unsigned int (32-bit) to unsigned long long (64-bit) to support the future addition of KCFI (Kernel Control Flow Integrity) at bit position 32, which exceeds the previous 32-bit limit.

Update all sanitizer-related data structures, function signatures, and type handling across the compiler:

* common.opt: Change flag_sanitize from unsigned int to unsigned long long
* flag-types.h: Convert all SANITIZE_* enum values from 1UL << N to 1ULL << N
* opts.h: Update parse_sanitizer_options() and parse_no_sanitize_attribute() function signatures to use unsigned long long parameters
* opts.cc: Update sanitizer parsing functions and sanitizer_opts_s structure to handle 64-bit flag values, including special handling for "all" flag (~0ULL)
* asan.h: Update sanitize_flags_p() to accept and return 64-bit values
* c-family/c-common.h: Update add_no_sanitize_value() signature
* c-family/c-attribs.cc: Update no_sanitize attribute handling functions
* c-family/c-attribs.cc: Replace unsigned_type_node with long_long_unsigned_type_node for no_sanitize attribute storage
* d/d-attribs.cc: Replace d_uint_type with long_long_unsigned_type_node for consistent 64-bit attribute representation across languages
* c/c-parser.cc: Update local flag_sanitize_save variables in declaration parsing where sanitization is temporarily disabled for initializers
* cp/typeck.cc: Update flag_sanitize_save in pointer-to-member function handling
* dwarf2asm.cc: Update save_flag_sanitize for ASan-disabled indirect constants

Is using "unsigned long long" correct here, or is switching to "uint64_t" preferred?

---
 gcc/asan.h                |  4 +--
 gcc/c-family/c-common.h   |  2 +-
 gcc/flag-types.h          | 64 +++++++++++++++++++--------------------
 gcc/opts.h                |  8 ++---
 gcc/c-family/c-attribs.cc | 19 +++++++-----
 gcc/c/c-parser.cc         |  4 +--
 gcc/common.opt            |  2 +-
 gcc/cp/typeck.cc          |  2 +-
 gcc/d/d-attribs.cc        |  8 ++---
 gcc/dwarf2asm.cc          |  2 +-
 gcc/opts.cc               | 16 +++++-----
 11 files changed, 67 insertions(+), 64 deletions(-)
gcc/asan.h +2 -2
index 273d6745c58d..7434d43ac493 100644
@@ -242,9 +242,9 @@ asan_protect_stack_decl (tree decl)
    remove all flags mentioned in "no_sanitize" of DECL_ATTRIBUTES.  */
 
 inline bool
-sanitize_flags_p (unsigned int flag, const_tree fn = current_function_decl)
+sanitize_flags_p (unsigned long long flag, const_tree fn = current_function_decl)
 {
-  unsigned int result_flags = flag_sanitize & flag;
+  unsigned long long result_flags = flag_sanitize & flag;
   if (result_flags == 0)
     return false;
 
gcc/c-family/c-common.h +1 -1
index 7c7e21d2d0eb..e7940cc079f6 100644
@@ -1713,7 +1713,7 @@ extern enum flt_eval_method
 excess_precision_mode_join (enum flt_eval_method, enum flt_eval_method);
 
 extern int c_flt_eval_method (bool ts18661_p);
-extern void add_no_sanitize_value (tree node, unsigned int flags);
+extern void add_no_sanitize_value (tree node, unsigned long long flags);
 
 extern void maybe_add_include_fixit (rich_location *, const char *, bool);
 extern void maybe_suggest_missing_token_insertion (rich_location *richloc,
gcc/flag-types.h +32 -32

74 lines not on this page · raw message

gcc/opts.h +4 -4
index ea92c4922a3b..65b8a1079f34 100644
@@ -432,10 +432,10 @@ extern char *write_langs (unsigned int mask);
 extern void print_ignored_options (void);
 extern void handle_common_deferred_options (void);
 extern void handle_deferred_dump_options (void);
-unsigned int parse_sanitizer_options (const char *, location_t, int,
-				      unsigned int, int, bool);
+unsigned long long parse_sanitizer_options (const char *, location_t, int,
+					    unsigned long long, int, bool);
 
-unsigned int parse_no_sanitize_attribute (char *value);
+unsigned long long parse_no_sanitize_attribute (char *value);
 extern bool common_handle_option (struct gcc_options *opts,
 				  struct gcc_options *opts_set,
 				  const struct cl_decoded_option *decoded,
@@ -477,7 +477,7 @@ extern bool opt_enum_arg_to_value (size_t opt_index, const char *arg,
 extern const struct sanitizer_opts_s
 {
   const char *const name;
-  unsigned int flag;
+  unsigned long long flag;
   size_t len;
   bool can_recover;
   bool can_trap;
gcc/c-family/c-attribs.cc +11 -8
index 1f4a0df12051..eed384818433 100644
@@ -1409,24 +1409,27 @@ handle_cold_attribute (tree *node, tree name, tree ARG_UNUSED (args),
 /* Add FLAGS for a function NODE to no_sanitize_flags in DECL_ATTRIBUTES.  */
 
 void
-add_no_sanitize_value (tree node, unsigned int flags)
+add_no_sanitize_value (tree node, unsigned long long flags)
 {
+
   tree attr = lookup_attribute ("no_sanitize", DECL_ATTRIBUTES (node));
   if (attr)
     {
-      unsigned int old_value = tree_to_uhwi (TREE_VALUE (attr));
+      unsigned long long old_value = tree_to_uhwi (TREE_VALUE (attr));
       flags |= old_value;
 
       if (flags == old_value)
 	return;
 
-      TREE_VALUE (attr) = build_int_cst (unsigned_type_node, flags);
+      TREE_VALUE (attr) = build_int_cst (long_long_unsigned_type_node, flags);
     }
   else
-    DECL_ATTRIBUTES (node)
-      = tree_cons (get_identifier ("no_sanitize"),
-		   build_int_cst (unsigned_type_node, flags),
-		   DECL_ATTRIBUTES (node));
+    {
+      DECL_ATTRIBUTES (node)
+	= tree_cons (get_identifier ("no_sanitize"),
+		     build_int_cst (long_long_unsigned_type_node, flags),
+		     DECL_ATTRIBUTES (node));
+    }
 }
 
 /* Handle a "no_sanitize" attribute; arguments as in
@@ -1436,7 +1439,7 @@ static tree
 handle_no_sanitize_attribute (tree *node, tree name, tree args, int,
 			      bool *no_add_attrs)
 {
-  unsigned int flags = 0;
+  unsigned long long flags = 0;
   *no_add_attrs = true;
   if (TREE_CODE (*node) != FUNCTION_DECL)
     {
gcc/c/c-parser.cc +2 -2
index 4a13fc0d3842..7a0e1d6de6f3 100644
@@ -2822,7 +2822,7 @@ c_parser_declaration_or_fndef (c_parser *parser, bool fndef_ok,
 			      specs->constexpr_p, &richloc);
 		  /* A parameter is initialized, which is invalid.  Don't
 		     attempt to instrument the initializer.  */
-		  int flag_sanitize_save = flag_sanitize;
+		  unsigned long long flag_sanitize_save = flag_sanitize;
 		  if (nested && !empty_ok)
 		    flag_sanitize = 0;
 		  init = c_parser_expr_no_commas (parser, NULL);
@@ -2911,7 +2911,7 @@ c_parser_declaration_or_fndef (c_parser *parser, bool fndef_ok,
 			      specs->constexpr_p, &richloc);
 		  /* A parameter is initialized, which is invalid.  Don't
 		     attempt to instrument the initializer.  */
-		  int flag_sanitize_save = flag_sanitize;
+		  unsigned long long flag_sanitize_save = flag_sanitize;
 		  if (TREE_CODE (d) == PARM_DECL)
 		    flag_sanitize = 0;
 		  init = c_parser_initializer (parser, d);
gcc/common.opt +1 -1
index 70659fabebd5..f82f2b3f1b11 100644
@@ -205,7 +205,7 @@ bool flag_opts_finished
 
 ; What the sanitizer should instrument
 Variable
-unsigned int flag_sanitize
+unsigned long long flag_sanitize
 
 ; What sanitizers should recover from errors
 Variable
gcc/cp/typeck.cc +1 -1
index f592894e01ab..c26b2fb8939b 100644
@@ -4287,7 +4287,7 @@ get_member_function_from_ptrfunc (tree *instance_ptrptr, tree function,
       idx = build1 (NOP_EXPR, vtable_index_type, e3);
       switch (TARGET_PTRMEMFUNC_VBIT_LOCATION)
 	{
-	  int flag_sanitize_save;
+	  unsigned long long flag_sanitize_save;
 	case ptrmemfunc_vbit_in_pfn:
 	  e1 = cp_build_binary_op (input_location,
 				   BIT_AND_EXPR, idx, integer_one_node,
gcc/d/d-attribs.cc +4 -4
index 77315dc5d58d..a1712f996bdc 100644
@@ -1406,7 +1406,7 @@ d_handle_no_sanitize_attribute (tree *node, tree name, tree args, int,
       return NULL_TREE;
     }
 
-  unsigned int flags = 0;
+  unsigned long long flags = 0;
   for (; args; args = TREE_CHAIN (args))
     {
       tree id = TREE_VALUE (args);
@@ -1424,16 +1424,16 @@ d_handle_no_sanitize_attribute (tree *node, tree name, tree args, int,
      merge existing flags if no_sanitize was previously handled.  */
   if (tree attr = lookup_attribute ("no_sanitize", DECL_ATTRIBUTES (*node)))
     {
-      unsigned int old_value = tree_to_uhwi (TREE_VALUE (attr));
+      unsigned long long old_value = tree_to_uhwi (TREE_VALUE (attr));
       flags |= old_value;
 
       if (flags != old_value)
-	TREE_VALUE (attr) = build_int_cst (d_uint_type, flags);
+	TREE_VALUE (attr) = build_int_cst (long_long_unsigned_type_node, flags);
     }
   else
     {
       DECL_ATTRIBUTES (*node) = tree_cons (get_identifier ("no_sanitize"),
-					   build_int_cst (d_uint_type, flags),
+					   build_int_cst (long_long_unsigned_type_node, flags),
 					   DECL_ATTRIBUTES (*node));
     }
 
gcc/dwarf2asm.cc +1 -1
index ec5c684da479..6f193a68bf9d 100644
@@ -1041,7 +1041,7 @@ dw2_output_indirect_constant_1 (const char *sym, tree id)
   sym_ref = gen_rtx_SYMBOL_REF (Pmode, sym);
   /* Disable ASan for decl because redzones cause ABI breakage between GCC and
      libstdc++ for `.LDFCM*' variables.  See PR 78651 for details.  */
-  unsigned int save_flag_sanitize = flag_sanitize;
+  unsigned long long save_flag_sanitize = flag_sanitize;
   flag_sanitize &= ~(SANITIZE_ADDRESS | SANITIZE_USER_ADDRESS
 		     | SANITIZE_KERNEL_ADDRESS);
   /* And also temporarily disable -fsection-anchors.  These indirect constants
gcc/opts.cc +8 -8
index c21e66ba9171..5fd86aa89adb 100644
@@ -2168,9 +2168,9 @@ const struct sanitizer_opts_s sanitizer_opts[] =
   SANITIZER_OPT (pointer-overflow, SANITIZE_POINTER_OVERFLOW, true, true),
   SANITIZER_OPT (builtin, SANITIZE_BUILTIN, true, true),
   SANITIZER_OPT (shadow-call-stack, SANITIZE_SHADOW_CALL_STACK, false, false),
-  SANITIZER_OPT (all, ~0U, true, true),
+  SANITIZER_OPT (all, ~0ULL, true, true),
 #undef SANITIZER_OPT
-  { NULL, 0U, 0UL, false, false }
+  { NULL, 0ULL, 0UL, false, false }
 };
 
 /* -fzero-call-used-regs= suboptions.  */
@@ -2241,7 +2241,7 @@ get_closest_sanitizer_option (const string_fragment &arg,
     {
       /* -fsanitize=all is not valid, so don't offer it.  */
       if (code == OPT_fsanitize_
-	  && opts[i].flag == ~0U
+	  && opts[i].flag == ~0ULL
 	  && value)
 	continue;
 
@@ -2268,9 +2268,9 @@ get_closest_sanitizer_option (const string_fragment &arg,
    adjust previous FLAGS and return new ones.  If COMPLAIN is false,
    don't issue diagnostics.  */
 
-unsigned int
+unsigned long long
 parse_sanitizer_options (const char *p, location_t loc, int scode,
-			 unsigned int flags, int value, bool complain)
+			 unsigned long long flags, int value, bool complain)
 {
   enum opt_code code = (enum opt_code) scode;
 
@@ -2296,7 +2296,7 @@ parse_sanitizer_options (const char *p, location_t loc, int scode,
 	    && memcmp (p, sanitizer_opts[i].name, len) == 0)
 	  {
 	    /* Handle both -fsanitize and -fno-sanitize cases.  */
-	    if (value && sanitizer_opts[i].flag == ~0U)
+	    if (value && sanitizer_opts[i].flag == ~0ULL)
 	      {
 		if (code == OPT_fsanitize_)
 		  {
@@ -2377,10 +2377,10 @@ parse_sanitizer_options (const char *p, location_t loc, int scode,
 /* Parse string values of no_sanitize attribute passed in VALUE.
    Values are separated with comma.  */
 
-unsigned int
+unsigned long long
 parse_no_sanitize_attribute (char *value)
 {
-  unsigned int flags = 0;
+  unsigned long long flags = 0;
   unsigned int i;
   char *q = strtok (value, ",");
 
Signature · 1 line
2.34.1
author
#2 lore raw

RFC PATCH 2/7 mangle: Introduce C typeinfo mangling API

In reply to Kees Cook

To support the KCFI type-id which needs to convert unique function prototypes into unique 32-bit values, add a subset of the Itanium C++ mangling ABI for C typeinfo of function prototypes. This gets us to the first step: a string representation of the function prototype.

Trying to extract only the C portions of the gcc/cp/mangle.cc code seemed infeasible after a few attempts. So this is the minimal subset of the mangling ABI needed to generate unique KCFI type ids.

I could not find a way to build a sensible selftest infrastructure for this code. I wanted to do something like this:

#ifdef CHECKING_P
const char code[] = "

	typedef struct { int x, y } xy_t;
	extern int func(xy_t *p);

";

  ASSERT_MANGLE (code, "_ZTSPFiP4xy_tE");
  ...
  #endif

But I could not find any way to build a localized parser that could parse the "code" string from which I could extract the "func" fndecl. It would have been so much nicer to build the selftest directly into mangle.cc here, but I couldn't figure it out. Instead, later patches create a "kcfi" dump file, and the large kcfi testsuite validates expected mangle strings as part of the type-id validation.

---
 gcc/Makefile.in |   1 +
 gcc/mangle.h    |  29 +++
 gcc/selftest.h  |   1 +
 gcc/mangle.cc   | 548 ++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 579 insertions(+)
 create mode 100644 gcc/mangle.h
 create mode 100644 gcc/mangle.cc
gcc/Makefile.in +1 -0
index d7d5cbe72770..86f62611c1d4 100644
@@ -1619,6 +1619,7 @@ OBJS = \
 	lto-section-out.o \
 	lto-opts.o \
 	lto-compress.o \
+	mangle.o \
 	mcf.o \
 	mode-switching.o \
 	modulo-sched.o \
gcc/mangle.h new file +29 -0
new file mode 100644
index 000000000000..94521e1e7e5c
@@ -0,0 +1,29 @@
+/* Itanium C++ ABI type mangling for GCC.
+   Copyright (C) 2025 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_MANGLE_H
+#define GCC_MANGLE_H
+
+#include "tree.h"
+
+/* Function type mangling following Itanium C++ ABI conventions.
+   Returns a static buffer containing the mangled type string.  */
+extern const char *mangle_function_type (tree fntype_or_fndecl);
+
+#endif /* GCC_MANGLE_H */
gcc/mangle.cc new file +548 -0

548 lines not on this page · raw message

Signature · 1 line
2.34.1

A message that is not in the archive (sent off-list or not yet received): CALvbMcAPV1eB6nocPAS=qR8SCiQyU43v911R8S7Ah_=G7yK-+g@mail.gmail.com

#4 lore raw

Re: [RFC PATCH 2/7] mangle: Introduce C typeinfo mangling API

Quoted 11 lines · Andrew Pinski
Quoted 5 lines · Kees Cook

To support the KCFI type-id which needs to convert unique function prototypes into unique 32-bit values, add a subset of the Itanium C++ mangling ABI for C typeinfo of function prototypes. This gets us to the first step: a string representation of the function prototype.

Can you explain why this is needed? Also it seems like the code is very sensitive to buffer overflows. Especially the way it is currently written. The C++ front-end version uses obstack_grow to overcome the buffer overflow issue.

So looking at where this is only used; You should calculate the hash directly instead.
So basically places where you do *(p++) = 'x'; replace it with doing the hash calculation.
Add a few functions like:
hash add_hash (hash, char);
hash add_hash (hash, char*);
hash add_hash_int (hash, int);

Etc.

Thanks,
Andrew

Quoted 682 lines
Quoted 133 lines

Trying to extract only the C portions of the gcc/cp/mangle.cc code seemed infeasible after a few attempts. So this is the minimal subset of the mangling ABI needed to generate unique KCFI type ids.

I could not find a way to build a sensible selftest infrastructure for this code. I wanted to do something like this:

  #ifdef CHECKING_P
  const char code[] = "
        typedef struct { int x, y } xy_t;
        extern int func(xy_t *p);
  ";

  ASSERT_MANGLE (code, "_ZTSPFiP4xy_tE");
  ...
  #endif

But I could not find any way to build a localized parser that could parse the "code" string from which I could extract the "func" fndecl. It would have been so much nicer to build the selftest directly into mangle.cc here, but I couldn't figure it out. Instead, later patches create a "kcfi" dump file, and the large kcfi testsuite validates expected mangle strings as part of the type-id validation.

---
 gcc/Makefile.in |   1 +
 gcc/mangle.h    |  29 +++
 gcc/selftest.h  |   1 +
 gcc/mangle.cc   | 548 ++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 579 insertions(+)
 create mode 100644 gcc/mangle.h
 create mode 100644 gcc/mangle.cc
gcc/Makefile.in +1 -0
index d7d5cbe72770..86f62611c1d4 100644
@@ -1619,6 +1619,7 @@ OBJS = \
        lto-section-out.o \
        lto-opts.o \
        lto-compress.o \
+       mangle.o \
        mcf.o \
        mode-switching.o \
        modulo-sched.o \
gcc/mangle.h new file +29 -0
new file mode 100644
index 000000000000..94521e1e7e5c
@@ -0,0 +1,29 @@
+/* Itanium C++ ABI type mangling for GCC.
+   Copyright (C) 2025 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_MANGLE_H
+#define GCC_MANGLE_H
+
+#include "tree.h"
+
+/* Function type mangling following Itanium C++ ABI conventions.
+   Returns a static buffer containing the mangled type string.  */
+extern const char *mangle_function_type (tree fntype_or_fndecl);
+
+#endif /* GCC_MANGLE_H */
gcc/mangle.cc new file +43 -0
new file mode 100644
index 000000000000..830985251c81
@@ -0,0 +1,548 @@
+/* Itanium C++ ABI type mangling for GCC.
+   Copyright (C) 2025 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/>.  */
+
+#include "config.h"
+#include "system.h"
+#include "coretypes.h"
+#include "tree.h"
+#include "diagnostic-core.h"
+#include "stringpool.h"
+#include "stor-layout.h"
+#include "mangle.h"
+#include "selftest.h"
+
+/* Forward declaration for recursive type mangling.  */
+static void mangle_type_to_buffer (tree type, char **p, char *end);
+
+/* Mangle a builtin type following Itanium C++ ABI for C types.  */
+static void
+mangle_builtin_type_to_buffer (tree type, char **p, char *end)
+{
+  gcc_assert (type != NULL_TREE);
+  gcc_assert (p != NULL && *p != NULL && end != NULL);
+  gcc_assert (*p < end);
+
+  if (*p >= end)
+    return;
+

gcc/mangle.cc line 53

Quoted 10 lines
gcc/mangle.cc new file +10 -0
+  switch (TREE_CODE (type))
+    {
+    case VOID_TYPE:
+      **p = 'v';
+      (*p)++;
+      break;
+
+    case BOOLEAN_TYPE:
+      **p = 'b';
+      (*p)++;

I am not 100% sure this is always correct. because there could be a boolean type with a precision non 1.

Quoted 79 lines
gcc/mangle.cc new file +78 -0
+      break;
+
+    case INTEGER_TYPE:
+      /* Handle standard integer types using Itanium ABI codes.  */
+      if (type == char_type_node)
+       {
+         **p = 'c';
+         (*p)++;
+       }
+      else if (type == signed_char_type_node)
+       {
+         **p = 'a';
+         (*p)++;
+       }
+      else if (type == unsigned_char_type_node)
+       {
+         **p = 'h';
+         (*p)++;
+       }
+      else if (type == short_integer_type_node)
+       {
+         **p = 's';
+         (*p)++;
+       }
+      else if (type == short_unsigned_type_node)
+       {
+         **p = 't';
+         (*p)++;
+       }
+      else if (type == integer_type_node)
+       {
+         **p = 'i';
+         (*p)++;
+       }
+      else if (type == unsigned_type_node)
+       {
+         **p = 'j';
+         (*p)++;
+       }
+      else if (type == long_integer_type_node)
+       {
+         **p = 'l';
+         (*p)++;
+       }
+      else if (type == long_unsigned_type_node)
+       {
+         **p = 'm';
+         (*p)++;
+       }
+      else if (type == long_long_integer_type_node)
+       {
+         **p = 'x';
+         (*p)++;
+       }
+      else if (type == long_long_unsigned_type_node)
+       {
+         **p = 'y';
+         (*p)++;
+       }
+      else
+       {
+         /* Fallback for other integer types - use precision-based encoding.  */
+         *p += snprintf (*p, end - *p, "i%d", TYPE_PRECISION (type));
+       }
+      break;
+
+    case REAL_TYPE:
+      if (type == float_type_node)
+       {
+         **p = 'f';
+         (*p)++;
+       }
+      else if (type == double_type_node)
+       {
+         **p = 'd';
+         (*p)++;
+       }
+      else if (type == long_double_type_node)

gcc/mangle.cc line 141

Quoted 10 lines
gcc/mangle.cc new file +10 -0
+       {
+         **p = 'e';
+         (*p)++;
+       }
+      else
+       {
+         /* Fallback for other real types.  */
+         *p += snprintf (*p, end - *p, "f%d", TYPE_PRECISION (type));
+       }
+      break;

You definitely miss NULLPTR_TYPE.

gcc/mangle.cc line 148

Quoted 8 lines
gcc/mangle.cc new file +7 -0
+
+    default:
+      /* Unknown builtin type - this should never happen in a well-formed C program.  */
+      error ("mangle: Unknown builtin type with %<TREE_CODE%> %d", TREE_CODE (type));
+      error ("mangle: %<TYPE_MODE%> = %d, %<TYPE_PRECISION%> = %d", TYPE_MODE (type), TYPE_PRECISION (type));
+      error ("mangle: Please report this as a bug with the above diagnostic information");
+      gcc_unreachable ();

This is wrong way of doing this.
It should be a sorry or a fatal_error instead. Maybe with an inform beforehand.
You might also want to use get_tree_code_name, GET_MODE_NAME instead of printing out a number because the number tells nothing. Maybe even use print_tree or print_generic_expr to print out the tree instead of manually printing it.

Quoted 112 lines
gcc/mangle.cc new file +111 -0
+    }
+}
+
+/* Canonicalize typedef types to their underlying named struct/union types.  */
+static tree
+canonicalize_typedef_type (tree type)
+{
+  /* Handle typedef types - canonicalize to named structs when possible.  */
+  if (TYPE_NAME (type) && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL)
+    {
+      tree type_decl = TYPE_NAME (type);
+
+      /* Check if this is a typedef (not the original struct declaration) */
+      if (DECL_ORIGINAL_TYPE (type_decl))
+       {
+         tree original_type = DECL_ORIGINAL_TYPE (type_decl);
+
+         /* If the original type is a named struct/union/enum, use that instead.  */
+         if ((TREE_CODE (original_type) == RECORD_TYPE
+              || TREE_CODE (original_type) == UNION_TYPE
+              || TREE_CODE (original_type) == ENUMERAL_TYPE)
+             && TYPE_NAME (original_type)
+             && ((TREE_CODE (TYPE_NAME (original_type)) == TYPE_DECL
+                  && DECL_NAME (TYPE_NAME (original_type)))
+                 || TREE_CODE (TYPE_NAME (original_type)) == IDENTIFIER_NODE))
+           {
+             /* Recursively canonicalize in case the original type is also a typedef.  */
+             return canonicalize_typedef_type (original_type);
+           }
+
+         /* For basic type typedefs (e.g., u8 -> unsigned char), canonicalize to original type.  */
+         if (TREE_CODE (original_type) == INTEGER_TYPE
+             || TREE_CODE (original_type) == REAL_TYPE
+             || TREE_CODE (original_type) == POINTER_TYPE
+             || TREE_CODE (original_type) == ARRAY_TYPE
+             || TREE_CODE (original_type) == FUNCTION_TYPE
+             || TREE_CODE (original_type) == METHOD_TYPE
+             || TREE_CODE (original_type) == BOOLEAN_TYPE
+             || TREE_CODE (original_type) == COMPLEX_TYPE
+             || TREE_CODE (original_type) == VECTOR_TYPE)
+           {
+             /* Recursively canonicalize in case the original type is also a typedef.  */
+             return canonicalize_typedef_type (original_type);
+           }
+       }
+    }
+
+  return type;
+}
+
+/* Recursively mangle a type following Itanium C++ ABI conventions.  */
+static void
+mangle_type_to_buffer (tree type, char **p, char *end)
+{
+  gcc_assert (type != NULL_TREE);
+  gcc_assert (p != NULL && *p != NULL && end != NULL);
+  gcc_assert (*p < end);
+
+  if (*p >= end)
+    return;
+
+  /* Canonicalize typedef types to their underlying named struct types.  */
+  type = canonicalize_typedef_type (type);
+
+  switch (TREE_CODE (type))
+    {
+    case POINTER_TYPE:
+      {
+       /* Pointer type: 'P' + qualifiers + pointed-to type.  */
+       **p = 'P';
+       (*p)++;
+
+       /* Add qualifiers to the pointed-to type following Itanium C++ ABI ordering.  */
+       tree pointed_to_type = TREE_TYPE (type);
+       if (TYPE_QUALS (pointed_to_type) != TYPE_UNQUALIFIED)
+         {
+           /* Emit qualifiers in Itanium ABI order: restrict, volatile, const.  */
+           if (TYPE_QUALS (pointed_to_type) & TYPE_QUAL_RESTRICT)
+             {
+               **p = 'r';
+               (*p)++;
+             }
+           if (TYPE_QUALS (pointed_to_type) & TYPE_QUAL_VOLATILE)
+             {
+               **p = 'V';
+               (*p)++;
+             }
+           if (TYPE_QUALS (pointed_to_type) & TYPE_QUAL_CONST)
+             {
+               **p = 'K';
+               (*p)++;
+             }
+           /* Note: _Atomic is not typically used in kernel code.  */
+         }
+
+       /* For KCFI's hybrid type system: preserve typedef names for compound types,
+          but use canonical forms for primitive types.  */
+       tree target_type;
+       if (TREE_CODE (pointed_to_type) == RECORD_TYPE
+           || TREE_CODE (pointed_to_type) == UNION_TYPE
+           || TREE_CODE (pointed_to_type) == ENUMERAL_TYPE)
+         {
+           /* Compound type: preserve typedef information by using original type.  */
+           target_type = pointed_to_type;
+         }
+       else
+         {
+           /* Primitive type: use canonical form to ensure structural typing.  */
+           target_type = TYPE_MAIN_VARIANT (pointed_to_type);
+         }
+       mangle_type_to_buffer (target_type, p, end);

gcc/mangle.cc line 269

Quoted 10 lines
gcc/mangle.cc new file +10 -0
+       break;
+      }
+
+    case ARRAY_TYPE:
+      /* Array type: 'A' + size + '_' + element type (simplified).  */
+      **p = 'A';
+      (*p)++;
+      if (TYPE_DOMAIN (type) && TYPE_MAX_VALUE (TYPE_DOMAIN (type)))
+       {
+         HOST_WIDE_INT size = tree_to_shwi (TYPE_MAX_VALUE (TYPE_DOMAIN (type))) + 1;

No check to make sure array type is not a VLA. So this will ICE.

Quoted 189 lines
gcc/mangle.cc new file +188 -0
+         *p += snprintf (*p, end - *p, "%ld_", (long) size);
+       }
+      else
+       {
+         **p = '_';
+         (*p)++;
+       }
+      mangle_type_to_buffer (TREE_TYPE (type), p, end);
+      break;
+
+    case FUNCTION_TYPE:
+      {
+       /* Function type: 'F' + return type + parameter types + 'E' */
+       **p = 'F';
+       (*p)++;
+       mangle_type_to_buffer (TREE_TYPE (type), p, end);
+
+       /* Add parameter types.  */
+       tree param_types = TYPE_ARG_TYPES (type);
+
+       if (param_types == NULL_TREE)
+         {
+           /* func() - variadic function, no parameter list.
+              Don't mangle any parameters. */
+         }
+       else
+         {
+           bool found_real_params = false;
+           for (tree param = param_types; param && *p < end; param = TREE_CHAIN (param))
+             {
+               tree param_type = TREE_VALUE (param);
+               if (param_type == void_type_node)
+                 {
+                   /* Check if this is the first parameter (explicit void) or a sentinel */
+                   if (!found_real_params)
+                     {
+                       /* func(void) - explicit empty parameter list.
+                          Mangle void to distinguish from variadic func(). */
+                       mangle_type_to_buffer (void_type_node, p, end);
+                     }
+                   /* If we found real params before this void, it's a sentinel - stop */
+                   break;
+                 }
+
+               found_real_params = true;
+
+               /* For value parameters, ignore const/volatile qualifiers as they
+                  don't affect the calling convention.  const int and int are
+                  passed identically by value.  */
+               tree canonical_param_type = param_type;
+               if (TREE_CODE (param_type) != POINTER_TYPE
+                   && TREE_CODE (param_type) != REFERENCE_TYPE
+                   && TREE_CODE (param_type) != ARRAY_TYPE)
+                 {
+                   /* Strip qualifiers for non-pointer/reference value parameters.  */
+                   canonical_param_type = TYPE_MAIN_VARIANT (param_type);
+                 }
+
+               mangle_type_to_buffer (canonical_param_type, p, end);
+             }
+         }
+
+       **p = 'E';
+       (*p)++;
+       break;
+      }
+
+    case RECORD_TYPE:
+    case UNION_TYPE:
+    case ENUMERAL_TYPE:
+      {
+       /* Struct/union/enum: use simplified representation for C types.  */
+       const char *name = NULL;
+
+       if (TYPE_NAME (type))
+         {
+           if (TREE_CODE (TYPE_NAME (type)) == TYPE_DECL)
+             {
+               /* TYPE_DECL case: both named structs and typedef structs.  */
+               tree decl_name = DECL_NAME (TYPE_NAME (type));
+               if (decl_name && TREE_CODE (decl_name) == IDENTIFIER_NODE)
+                 {
+                   name = IDENTIFIER_POINTER (decl_name);
+                 }
+             }
+           else if (TREE_CODE (TYPE_NAME (type)) == IDENTIFIER_NODE)
+             {
+               /* Direct identifier case.  */
+               name = IDENTIFIER_POINTER (TYPE_NAME (type));
+             }
+         }
+
+       /* If no name found through normal extraction, handle anonymous types following Itanium C++ ABI.  */
+       if (!name && !TYPE_NAME (type))
+         {
+           static char anon_name[128];
+
+           if (TREE_CODE (type) == UNION_TYPE)
+             {
+               /* For anonymous unions, try to find first named field (Itanium ABI approach).  */
+               tree field = TYPE_FIELDS (type);
+               while (field && !DECL_NAME (field))
+                 field = DECL_CHAIN (field);
+
+               if (field && DECL_NAME (field))
+                 {
+                   const char *field_name = IDENTIFIER_POINTER (DECL_NAME (field));
+                   snprintf (anon_name, sizeof(anon_name), "anon_union_by_%s", field_name);
+                 }
+               else
+                 {
+                   /* No named fields - use Itanium-style Ut encoding.  */
+                   snprintf (anon_name, sizeof(anon_name), "Ut_unnamed_union");
+                 }
+             }
+           else
+             {
+               /* For anonymous structs/enums, use Itanium-style Ut encoding with layout info for discrimination.  */
+               const char *type_prefix = "";
+               if (TREE_CODE (type) == RECORD_TYPE)
+                 type_prefix = "struct";
+               else if (TREE_CODE (type) == ENUMERAL_TYPE)
+                 type_prefix = "enum";
+
+               /* Include size and field layout for better discrimination.  */
+               HOST_WIDE_INT size = 0;
+               if (TYPE_SIZE (type) && tree_fits_shwi_p (TYPE_SIZE (type)))
+                 size = tree_to_shwi (TYPE_SIZE (type));
+
+               /* Generate a hash based on field layout to distinguish same-sized anonymous types.  */
+               unsigned layout_hash = 0;
+               if (TREE_CODE (type) == RECORD_TYPE)
+                 {
+                   for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
+                     {
+                       if (TREE_CODE (field) == FIELD_DECL)
+                         {
+                           /* Hash field offset and type.  */
+                           if (DECL_FIELD_OFFSET (field))
+                             {
+                               HOST_WIDE_INT offset = tree_to_shwi (DECL_FIELD_OFFSET (field));
+                               layout_hash = layout_hash * 31 + (unsigned)offset;
+                             }
+
+                           /* Hash field type.  */
+                           tree field_type = TREE_TYPE (field);
+                           if (field_type && TYPE_MODE (field_type) != VOIDmode)
+                             layout_hash = layout_hash * 37 + (unsigned)TYPE_MODE (field_type);
+                         }
+                     }
+                 }
+
+               if (layout_hash != 0)
+                 snprintf (anon_name, sizeof(anon_name), "Ut_%s_%ld_%x", type_prefix, (long)size, layout_hash);
+               else
+                 snprintf (anon_name, sizeof(anon_name), "Ut_%s_%ld", type_prefix, (long)size);
+             }
+
+           name = anon_name;
+         }
+
+       if (name)
+         {
+           *p += snprintf (*p, end - *p, "%zu%s", strlen (name), name);
+         }
+       else
+         {
+           /* Always show diagnostic information for missing struct names.  */
+           error ("mangle: No struct/union/enum name found for type code %d (%qs)",
+                  TREE_CODE (type), get_tree_code_name (TREE_CODE (type)));
+           if (TYPE_NAME (type))
+             {
+               error ("mangle: %<TYPE_NAME%> exists but extraction failed");
+               error ("mangle: %<TYPE_NAME%> tree code = %d", TREE_CODE (TYPE_NAME (type)));
+               if (TREE_CODE (TYPE_NAME (type)) == TYPE_DECL)
+                 {
+                   tree decl_name = DECL_NAME (TYPE_NAME (type));
+                   error ("mangle: %<TYPE_DECL%> %<DECL_NAME%> = %p", (void*)decl_name);
+                   if (decl_name && TREE_CODE (decl_name) == IDENTIFIER_NODE)
+                     error ("mangle: %<IDENTIFIER_NODE%> name = '%s'", IDENTIFIER_POINTER (decl_name));
+                 }
+               else if (TREE_CODE (TYPE_NAME (type)) == IDENTIFIER_NODE)
+                 {
+                   error ("mangle: %<IDENTIFIER_NODE%> name = '%s'", IDENTIFIER_POINTER (TYPE_NAME (type)));
+                 }
+               else
+                 {
+                   error ("mangle: Unknown %<TYPE_NAME%> tree code = %d", TREE_CODE (TYPE_NAME (type)));

gcc/mangle.cc line 467

Quoted 10 lines
gcc/mangle.cc new file +10 -0
+                 }
+             }
+           else
+             {
+               error ("mangle: %<TYPE_NAME%> is NULL - anonymous struct/union/enum detected");
+             }
+
+           /* This indicates a missing case in our struct name extraction.  */
+           error ("mangle: Please report this as a bug with the above diagnostic information");
+           gcc_unreachable ();

See above about sorry/fatal_error.

Quoted 24 lines
gcc/mangle.cc new file +23 -0
+         }
+       break;
+      }
+
+    default:
+      /* Handle builtin types.  */
+      mangle_builtin_type_to_buffer (type, p, end);
+      break;
+    }
+}
+
+/* Compute canonical type name using Itanium C++ ABI mangling.
+   Accepts either FUNCTION_DECL (preferred for typedef preservation) or FUNCTION_TYPE.  */
+const char *
+mangle_function_type (tree fntype_or_fndecl)
+{
+  gcc_assert (fntype_or_fndecl);
+
+  tree fntype = NULL;
+
+  /* Determine input type and extract function type.  */
+  if (TREE_CODE (fntype_or_fndecl) == FUNCTION_TYPE)
+    {

gcc/mangle.cc line 500

Quoted 10 lines
gcc/mangle.cc new file +10 -0
+      /* Already FUNCTION_TYPE.  */
+      fntype = fntype_or_fndecl;
+    }
+  else if (TREE_CODE (fntype_or_fndecl) == FUNCTION_DECL)
+    {
+      tree fndecl = fntype_or_fndecl;
+      tree base_fntype = TREE_TYPE (fndecl);
+
+      /* For FUNCTION_DECL, build a synthetic function type using DECL_ARGUMENTS
+        if available to preserve typedef information.  */

Why do the building? Seems like you could just do that work here. Also doesn't FUNCTION_DECL's type have exactly what you need?

Quoted 25 lines
gcc/mangle.cc new file +24 -0
+      tree parm = DECL_ARGUMENTS (fndecl);
+      if (parm)
+       {
+         /* Build parameter type list from DECL_ARGUMENTS.  */
+         tree param_list = NULL_TREE;
+         tree *param_tail = &param_list;
+
+         for (; parm; parm = DECL_CHAIN (parm))
+           {
+             tree parm_type = TREE_TYPE (parm);
+             *param_tail = tree_cons (NULL_TREE, parm_type, NULL_TREE);
+             param_tail = &TREE_CHAIN (*param_tail);
+           }
+
+         /* Add void_type_node sentinel if the function takes no parameters.  */
+         if (!param_list)
+           param_list = tree_cons (NULL_TREE, void_type_node, NULL_TREE);
+
+         /* Build synthetic function type with preserved parameter types.  */
+         fntype = build_function_type (TREE_TYPE (base_fntype), param_list);
+       }
+      else
+       {
+         /* No DECL_ARGUMENTS - use the standard function type.  */

gcc/mangle.cc line 534

Quoted 10 lines
gcc/mangle.cc new file +10 -0
+         fntype = base_fntype;
+       }
+    }
+  else
+    {
+      /* Must only be called with FUNCTION_DECL or FUNCTION_TYPE.  */
+      gcc_unreachable ();
+    }
+
+  static char name_buf[512];

Why use a fixed size buffer on the stack? Why not use obstack or something to that extent. OR even std::string with a pre-allocated estimate.

Thanks,
Andrew

Quoted 18 lines
gcc/mangle.cc new file +14 -1
+  char *p = name_buf;
+  char *end = name_buf + sizeof (name_buf) - 1;
+
+  /* Typeinfo for a function prototype.  */
+  p += sprintf(name_buf, "_ZTSP");
+
+  /* Use mangle_type_to_buffer for all cases.  */
+  mangle_type_to_buffer (fntype, &p, end);
+
+  /* Ensure we didn't overflow the buffer.  */
+  gcc_assert (p <= end);
+  *p = '\0';
+  return name_buf;
+}
--

2.34.1

author
#5 lore raw

Re: [RFC PATCH 2/7] mangle: Introduce C typeinfo mangling API

In reply to a message not in the archive
Quoted 9 lines · Andrew Pinski
Quoted 5 lines · Kees Cook

To support the KCFI type-id which needs to convert unique function prototypes into unique 32-bit values, add a subset of the Itanium C++ mangling ABI for C typeinfo of function prototypes. This gets us to the first step: a string representation of the function prototype.

Can you explain why this is needed? Also it seems like the code is very

As you suggest later, this could just twiddle hash bits instead of building up a string, but I left this as a C mangler in case it might be useful in the future, and for debugging. Trying to figure out why certain prototypes got mismatched was super frustrating, and looking at a hash value was pretty meaningless. :)

Quoted 3 lines

sensitive to buffer overflows. Especially the way it is currently written. The C++ front-end version uses obstack_grow to overcome the buffer overflow issue.

Oh nice, yes, obstack looks perfect for this. (Or as you suggest below, std::string).

If keeping the mangling string output is unwanted, maybe I could use obstack when the dumpfile is active and report the string+hash at the end of mangling, but make the actual output be the hash value?

Quoted 7 lines

gcc/mangle.cc line 53

Quoted 4 lines
gcc/mangle.cc new file +3 -0
+    case BOOLEAN_TYPE:
+      **p = 'b';
+      (*p)++;

I am not 100% sure this is always correct. because there could be a boolean type with a precision non 1.

AIUI, the non-1 case isn't possible on the C end of things and since this is strictly for C type representation, it's good as-is. But maybe I'm missing something?

Quoted 9 lines

gcc/mangle.cc line 141

Quoted 7 lines
gcc/mangle.cc new file +6 -0
+      else
+       {
+         /* Fallback for other real types.  */
+         *p += snprintf (*p, end - *p, "f%d", TYPE_PRECISION (type));
+       }
+      break;

You definitely miss NULLPTR_TYPE.

Isn't nullptr C++-only? I don't think I can create a C type that ends up getting internally mapped to NULLPTR_TYPE.

Quoted 13 lines
Quoted 12 lines
gcc/mangle.cc new file +3 -0
+
+    default:
+      /* Unknown builtin type - this should never happen in a well-formed

C program. */
+ error ("mangle: Unknown builtin type with %<TREE_CODE%> %d",
TREE_CODE (type));
+ error ("mangle: %<TYPE_MODE%> = %d, %<TYPE_PRECISION%> = %d",
TYPE_MODE (type), TYPE_PRECISION (type));
+ error ("mangle: Please report this as a bug with the above
diagnostic information");
+ gcc_unreachable ();

Quoted 7 lines

This is wrong way of doing this.
It should be a sorry or a fatal_error instead. Maybe with an inform beforehand.
You might also want to use get_tree_code_name, GET_MODE_NAME instead of printing out a number because the number tells nothing. Maybe even use print_tree or print_generic_expr to print out the tree instead of manually printing it.

Ah, perfect; thanks!

Quoted 11 lines
Quoted 9 lines
gcc/mangle.cc new file +7 -0
+    case ARRAY_TYPE:
+      /* Array type: 'A' + size + '_' + element type (simplified).  */
+      **p = 'A';
+      (*p)++;
+      if (TYPE_DOMAIN (type) && TYPE_MAX_VALUE (TYPE_DOMAIN (type)))
+       {
+         HOST_WIDE_INT size = tree_to_shwi (TYPE_MAX_VALUE (TYPE_DOMAIN

(type))) + 1;

No check to make sure array type is not a VLA. So this will ICE.

Oops, yes. Thanks!

Quoted 10 lines
Quoted 9 lines
gcc/mangle.cc new file +6 -0
+  else if (TREE_CODE (fntype_or_fndecl) == FUNCTION_DECL)
+    {
+      tree fndecl = fntype_or_fndecl;
+      tree base_fntype = TREE_TYPE (fndecl);
+
+      /* For FUNCTION_DECL, build a synthetic function type using

DECL_ARGUMENTS
+ if available to preserve typedef information. */

Quoted 2 lines

Why do the building? Seems like you could just do that work here. Also doesn't FUNCTION_DECL's type have exactly what you need?

I need the function prototype in three places:

- address-taken extern functions
- function preambles
- indirect call sites

At indirect call sites (during the early GIMPLE pass), I had a FUNCTION_TYPE available that still had the full typedef information, and I could use it fine. For the other two, it's later on and the TREE_TYPE(fndecl)'s FUNCTION_TYPE had lost the typedef information (which I need to be able to examine in cases where the typedef name was needed for the mangling vs looking at the underlying types).

Quoted 27 lines
Quoted 27 lines
gcc/mangle.cc new file +15 -0
+      tree parm = DECL_ARGUMENTS (fndecl);
+      if (parm)
+       {
+         /* Build parameter type list from DECL_ARGUMENTS.  */
+         tree param_list = NULL_TREE;
+         tree *param_tail = &param_list;
+
+         for (; parm; parm = DECL_CHAIN (parm))
+           {
+             tree parm_type = TREE_TYPE (parm);
+             *param_tail = tree_cons (NULL_TREE, parm_type, NULL_TREE);
+             param_tail = &TREE_CHAIN (*param_tail);
+           }
+
+         /* Add void_type_node sentinel if the function takes no

parameters. */

gcc/mangle.cc new file +4 -0
+         if (!param_list)
+           param_list = tree_cons (NULL_TREE, void_type_node, NULL_TREE);
+
+         /* Build synthetic function type with preserved parameter

types. */
+ fntype = build_function_type (TREE_TYPE (base_fntype),
param_list);

gcc/mangle.cc new file +4 -0
+       }
+      else
+       {
+         /* No DECL_ARGUMENTS - use the standard function type.  */
Quoted 8 lines

gcc/mangle.cc line 532

Quoted 8 lines
gcc/mangle.cc new file +8 -0
+         fntype = base_fntype;
+       }
+    }
+  else
+    {
+      /* Must only be called with FUNCTION_DECL or FUNCTION_TYPE.  */
+      gcc_unreachable ();
+    }

Thanks for looking through all this!

-Kees

Signature · 1 line
Kees Cook
#6 lore raw

Re: [RFC PATCH 2/7] mangle: Introduce C typeinfo mangling API

Quoted 49 lines · Kees Cook
Quoted 9 lines · Andrew Pinski
Quoted 5 lines · Kees Cook

To support the KCFI type-id which needs to convert unique function prototypes into unique 32-bit values, add a subset of the Itanium C++ mangling ABI for C typeinfo of function prototypes. This gets us to the first step: a string representation of the function prototype.

Can you explain why this is needed? Also it seems like the code is very

As you suggest later, this could just twiddle hash bits instead of building up a string, but I left this as a C mangler in case it might be useful in the future, and for debugging. Trying to figure out why certain prototypes got mismatched was super frustrating, and looking at a hash value was pretty meaningless. :)

Quoted 3 lines

sensitive to buffer overflows. Especially the way it is currently written. The C++ front-end version uses obstack_grow to overcome the buffer overflow issue.

Oh nice, yes, obstack looks perfect for this. (Or as you suggest below, std::string).

If keeping the mangling string output is unwanted, maybe I could use obstack when the dumpfile is active and report the string+hash at the end of mangling, but make the actual output be the hash value?

Quoted 7 lines

gcc/mangle.cc line 53

Quoted 4 lines
gcc/mangle.cc new file +3 -0
+    case BOOLEAN_TYPE:
+      **p = 'b';
+      (*p)++;

I am not 100% sure this is always correct. because there could be a boolean type with a precision non 1.

AIUI, the non-1 case isn't possible on the C end of things and since this is strictly for C type representation, it's good as-is. But maybe I'm missing something?

Quoted 8 lines
Quoted 7 lines
gcc/mangle.cc new file +6 -0
+      else
+       {
+         /* Fallback for other real types.  */
+         *p += snprintf (*p, end - *p, "f%d", TYPE_PRECISION (type));
+       }
+      break;
Quoted 4 lines
Quoted 1 line

You definitely miss NULLPTR_TYPE.

Isn't nullptr C++-only? I don't think I can create a C type that ends up getting internally mapped to NULLPTR_TYPE.

NO, it is part of C23.
typeof(nullptr) in C23 program will have a NULLPTR_TYPE. I just posted some fixes for the C front-end in the area of NULLPTR_TYPE which is why I know it exists.

Quoted 57 lines
Quoted 14 lines
Quoted 4 lines
gcc/mangle.cc new file +3 -0
+
+    default:
+      /* Unknown builtin type - this should never happen in a well-formed
Quoted 9 lines

C program. */
+ error ("mangle: Unknown builtin type with %<TREE_CODE%> %d",
TREE_CODE (type));
+ error ("mangle: %<TYPE_MODE%> = %d, %<TYPE_PRECISION%> = %d",
TYPE_MODE (type), TYPE_PRECISION (type));
+ error ("mangle: Please report this as a bug with the above
diagnostic information");
+ gcc_unreachable ();

Quoted 7 lines

This is wrong way of doing this.
It should be a sorry or a fatal_error instead. Maybe with an inform beforehand.
You might also want to use get_tree_code_name, GET_MODE_NAME instead of printing out a number because the number tells nothing. Maybe even use print_tree or print_generic_expr to print out the tree instead of manually printing it.

Ah, perfect; thanks!

Quoted 11 lines
Quoted 9 lines
gcc/mangle.cc new file +7 -0
+    case ARRAY_TYPE:
+      /* Array type: 'A' + size + '_' + element type (simplified).  */
+      **p = 'A';
+      (*p)++;
+      if (TYPE_DOMAIN (type) && TYPE_MAX_VALUE (TYPE_DOMAIN (type)))
+       {
+         HOST_WIDE_INT size = tree_to_shwi (TYPE_MAX_VALUE (TYPE_DOMAIN

(type))) + 1;

No check to make sure array type is not a VLA. So this will ICE.

Oops, yes. Thanks!

Quoted 10 lines
Quoted 9 lines
gcc/mangle.cc new file +6 -0
+  else if (TREE_CODE (fntype_or_fndecl) == FUNCTION_DECL)
+    {
+      tree fndecl = fntype_or_fndecl;
+      tree base_fntype = TREE_TYPE (fndecl);
+
+      /* For FUNCTION_DECL, build a synthetic function type using

DECL_ARGUMENTS
+ if available to preserve typedef information. */

Quoted 2 lines

Why do the building? Seems like you could just do that work here. Also doesn't FUNCTION_DECL's type have exactly what you need?

I need the function prototype in three places:

- address-taken extern functions
- function preambles
- indirect call sites

Quoted 6 lines

At indirect call sites (during the early GIMPLE pass), I had a FUNCTION_TYPE available that still had the full typedef information, and I could use it fine. For the other two, it's later on and the TREE_TYPE(fndecl)'s FUNCTION_TYPE had lost the typedef information (which I need to be able to examine in cases where the typedef name was needed for the mangling vs looking at the underlying types).

What typedef information do you need that is missing? struct names? or something different?

So from the looks of it there is a big issue with attack vector where you have 2 different structs with the same name. Seems like the hash should have included the fields of the struct instead of just a mangled name of the struct. Can we break the hash for GCC's KFCI from clang to include this extra hashing info? and maybe even fix up clang later on?

Thanks,
Andrew Pinski

Quoted 43 lines
Quoted 28 lines
Quoted 28 lines
gcc/mangle.cc new file +15 -0
+      tree parm = DECL_ARGUMENTS (fndecl);
+      if (parm)
+       {
+         /* Build parameter type list from DECL_ARGUMENTS.  */
+         tree param_list = NULL_TREE;
+         tree *param_tail = &param_list;
+
+         for (; parm; parm = DECL_CHAIN (parm))
+           {
+             tree parm_type = TREE_TYPE (parm);
+             *param_tail = tree_cons (NULL_TREE, parm_type, NULL_TREE);
+             param_tail = &TREE_CHAIN (*param_tail);
+           }
+
+         /* Add void_type_node sentinel if the function takes no

parameters. */

gcc/mangle.cc new file +4 -0
+         if (!param_list)
+           param_list = tree_cons (NULL_TREE, void_type_node, NULL_TREE);
+
+         /* Build synthetic function type with preserved parameter

types. */
+ fntype = build_function_type (TREE_TYPE (base_fntype),
param_list);

gcc/mangle.cc new file +4 -0
+       }
+      else
+       {
+         /* No DECL_ARGUMENTS - use the standard function type.  */
Quoted 8 lines

gcc/mangle.cc line 532

Quoted 8 lines
gcc/mangle.cc new file +8 -0
+         fntype = base_fntype;
+       }
+    }
+  else
+    {
+      /* Must only be called with FUNCTION_DECL or FUNCTION_TYPE.  */
+      gcc_unreachable ();
+    }

Thanks for looking through all this!

-Kees

--
Kees Cook

#7 lore raw

Re: [RFC PATCH 2/7] mangle: Introduce C typeinfo mangling API

In reply to Kees Cook
Quoted 15 lines · Kees Cook
Quoted 12 lines
Quoted 11 lines
gcc/mangle.cc new file +6 -0
+  else if (TREE_CODE (fntype_or_fndecl) == FUNCTION_DECL)
+    {
+      tree fndecl = fntype_or_fndecl;
+      tree base_fntype = TREE_TYPE (fndecl);
+
+      /* For FUNCTION_DECL, build a synthetic function type using

DECL_ARGUMENTS
+ if available to preserve typedef information. */

Quoted 9 lines
Quoted 2 lines

Why do the building? Seems like you could just do that work here. Also doesn't FUNCTION_DECL's type have exactly what you need?

I need the function prototype in three places:

- address-taken extern functions
- function preambles
- indirect call sites

A little confused with the above:

From my understanding,

1. At each indirect call sites, we should generate the checking code to A. load the hashed precomputed typeid from the callee’s preamble B. compare it with the precomputed typeid for this call site

So, we need the function prototype of the indirect call site to compute the typeid for this call site.

2. For every “address-taken” function, we should generate the function preamble, in which the precomputed typeid for this function is stored.

So, we need the function prototype of this function to compute the typeid for this function.

The above 2 should cover all the KCFI ABIs.

What I was confused is, why “address-taken external function” and “function preambles” are separated items? For the function preambles, shall we generate for all the functions? Or only for address-taken functions in the compilation?

Quoted 8 lines

At indirect call sites (during the early GIMPLE pass), I had a FUNCTION_TYPE available that still had the full typedef information, and I could use it fine.

For the other two, it's later on and the
TREE_TYPE(fndecl)'s FUNCTION_TYPE had lost the typedef information (which I need to be able to examine in cases where the typedef name was needed for the mangling vs looking at the underlying types).

Then why not also compute the typeid for the function preamble during early GIMPLE phase the same as the indirect call sites when all the typedef information is available?

Qing

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

+ tree parm = DECL_ARGUMENTS (fndecl);

author
#8 lore raw

Re: [RFC PATCH 2/7] mangle: Introduce C typeinfo mangling API

Quoted 27 lines · Qing Zhao
Quoted 15 lines · Kees Cook
Quoted 12 lines
Quoted 11 lines
gcc/mangle.cc new file +6 -0
+  else if (TREE_CODE (fntype_or_fndecl) == FUNCTION_DECL)
+    {
+      tree fndecl = fntype_or_fndecl;
+      tree base_fntype = TREE_TYPE (fndecl);
+
+      /* For FUNCTION_DECL, build a synthetic function type using

DECL_ARGUMENTS
+ if available to preserve typedef information. */

Quoted 9 lines
Quoted 2 lines

Why do the building? Seems like you could just do that work here. Also doesn't FUNCTION_DECL's type have exactly what you need?

I need the function prototype in three places:

- address-taken extern functions
- function preambles
- indirect call sites

A little confused with the above:

Quoted 7 lines

From my understanding,

1. At each indirect call sites, we should generate the checking code to A. load the hashed precomputed typeid from the callee’s preamble B. compare it with the precomputed typeid for this call site

So, we need the function prototype of the indirect call site to compute the typeid for this call site.

Correct.

Quoted 6 lines

2. For every “address-taken” function, we should generate the function preamble, in which the precomputed typeid for this function is stored.

So, we need the function prototype of this function to compute the typeid for this function.

The above 2 should cover all the KCFI ABIs.

For non-static functions, we cannot know if other compilation units may make indirect calls to a given function, so those functions must always have their kcfi preamble added. For static functions, if they are address-taken by the current compilation unit, then they must get a kcfi preamble added.

Quoted 3 lines

What I was confused is, why “address-taken external function” and “function preambles” are separated items? For the function preambles, shall we generate for all the functions? Or only for address-taken functions in the compilation?

The other case is emitting the __ckfi_typeid_FUNC weak symbols, which is used for link-time resolution with non-C code (i.e. raw .S assembly) which doesn't have access to the C type system to calculate the hashes on its own, and needs to have a way to build its own kcfi preambles. This is how Linux constructs its assembly function entry points:

#ifndef __CFI_TYPE

#define __CFI_TYPE(name)                                \
        .4byte __kcfi_typeid_##name

#endif

#define SYM_TYPED_ENTRY(name, linkage, align...)        \
        linkage(name) ASM_NL                            \
        align ASM_NL                                    \
        __CFI_TYPE(name) ASM_NL                         \

name:

That way all the asm functions can be be indirect call targets without knowing the hash value (which will be filled in at link time).

Quoted 11 lines
Quoted 8 lines

At indirect call sites (during the early GIMPLE pass), I had a FUNCTION_TYPE available that still had the full typedef information, and I could use it fine.

For the other two, it's later on and the
TREE_TYPE(fndecl)'s FUNCTION_TYPE had lost the typedef information (which I need to be able to examine in cases where the typedef name was needed for the mangling vs looking at the underlying types).

Then why not also compute the typeid for the function preamble during early GIMPLE phase the same as the indirect call sites when all the typedef information is available?

I assume I just didn't see how yet. :) I wasn't able to identify nor store the typeid for function definitions that ultimately end up getting .s file output. For example, down in ix86_asm_output_function_label(), I have the decl (but it's way late):

ix86_asm_output_function_label (FILE *out_file, const char *fname,
tree decl)

I couldn't figure out how to find these during the GIMPLE pass. Oh, perhaps I can do this with an IPA pass? That should let me walk all functions including externs. I'll give it a try...

Signature · 1 line
Kees Cook
#9 lore raw

Re: [RFC PATCH 2/7] mangle: Introduce C typeinfo mangling API

Quoted 47 lines · Kees Cook
Quoted 27 lines · Qing Zhao
Quoted 15 lines · Kees Cook
Quoted 12 lines
Quoted 11 lines
gcc/mangle.cc new file +6 -0
+  else if (TREE_CODE (fntype_or_fndecl) == FUNCTION_DECL)
+    {
+      tree fndecl = fntype_or_fndecl;
+      tree base_fntype = TREE_TYPE (fndecl);
+
+      /* For FUNCTION_DECL, build a synthetic function type using

DECL_ARGUMENTS
+ if available to preserve typedef information. */

Quoted 9 lines
Quoted 2 lines

Why do the building? Seems like you could just do that work here. Also doesn't FUNCTION_DECL's type have exactly what you need?

I need the function prototype in three places:

- address-taken extern functions
- function preambles
- indirect call sites

A little confused with the above:

Quoted 7 lines

From my understanding,

1. At each indirect call sites, we should generate the checking code to A. load the hashed precomputed typeid from the callee’s preamble B. compare it with the precomputed typeid for this call site

So, we need the function prototype of the indirect call site to compute the typeid for this call site.

Correct.

Quoted 5 lines

2. For every “address-taken” function, we should generate the function preamble, in which the precomputed typeid for this function is stored.

So, we need the function prototype of this function to compute the typeid for this function.

Quoted 7 lines
Quoted 1 line

The above 2 should cover all the KCFI ABIs.

For non-static functions, we cannot know if other compilation units may make indirect calls to a given function, so those functions must always have their kcfi preamble added. For static functions, if they are address-taken by the current compilation unit, then they must get a kcfi preamble added.

Oh, yeah, I see. without lto or whole-program-mode, we cannot determine whether a extern function is address taken or not. Therefore, we have to treat ALL extern functions conservatively as address taken.

So, from my understanding, the complete list that need to compute the typeid from the function prototype is:

- At indirect call sites
- all indirect call sites; (At the call site)
- At function preambles
- all address-taken static functions (At the function definition)
- all extern functions (At function declaration or function definition?? Please see my question below)

Quoted 9 lines
Quoted 4 lines

What I was confused is, why “address-taken external function” and “function preambles” are separated items? For the function preambles, shall we generate for all the functions? Or only for address-taken functions in the compilation?

The other case is emitting the __ckfi_typeid_FUNC weak symbols, which is used for link-time resolution with non-C code (i.e. raw .S assembly) which doesn't have access to the C type system to calculate the hashes on its own, and needs to have a way to build its own kcfi preambles.

So, for such functions, there should be an extern function declaration in the C code. But the definition of such function is not available in the C code we are compiling. Therefore the weak __ckfi_typeid_FUNC symbol is emitted at the function declaration point for such function when we compile the C code?

And the typeid (the hash value) for such routine is computed at the function declaration point too.

Is the above understanding correct?

Then for the other extern function whose definition is in the C code of other modules that might be compiled later, should the typeid is computed at the declaration or the definition?

Quoted 8 lines

This
is how Linux constructs its assembly function entry points:

#ifndef __CFI_TYPE

#define __CFI_TYPE(name)                                \
       .4byte __kcfi_typeid_##name

#endif

Quoted 8 lines
#define SYM_TYPED_ENTRY(name, linkage, align...)        \
       linkage(name) ASM_NL                            \
       align ASM_NL                                    \
       __CFI_TYPE(name) ASM_NL                         \
       name:

That way all the asm functions can be be indirect call targets without knowing the hash value (which will be filled in at link time).

Okay. I see. This is the case for the extern function whose definition is in the assembly file. (Not available in the C code)

Quoted 10 lines
Quoted 10 lines
Quoted 9 lines

At indirect call sites (during the early GIMPLE pass), I had a FUNCTION_TYPE available that still had the full typedef information, and I could use it fine.

For the other two, it's later on and the
TREE_TYPE(fndecl)'s FUNCTION_TYPE had lost the typedef information (which I need to be able to examine in cases where the typedef name was needed for the mangling vs looking at the underlying types).

Quoted 6 lines
Quoted 2 lines

Then why not also compute the typeid for the function preamble during early GIMPLE phase the same as the indirect call sites when all the typedef information is available?

I assume I just didn't see how yet. :) I wasn't able to identify nor store the typeid for function definitions that ultimately end up getting .s file output.

So, the problem only exists for the external functions whose definition is NOT in the C code?

Qing

Quoted 12 lines

For example, down in ix86_asm_output_function_label(), I have the decl (but it's way late):

ix86_asm_output_function_label (FILE *out_file, const char *fname,
tree decl)

I couldn't figure out how to find these during the GIMPLE pass. Oh, perhaps I can do this with an IPA pass? That should let me walk all functions including externs. I'll give it a try...

Signature · 1 line
Kees Cook
author
#10 lore raw

Re: [RFC PATCH 2/7] mangle: Introduce C typeinfo mangling API

Quoted 11 lines · Qing Zhao
Quoted 6 lines · Kees Cook

For non-static functions, we cannot know if other compilation units may make indirect calls to a given function, so those functions must always have their kcfi preamble added. For static functions, if they are address-taken by the current compilation unit, then they must get a kcfi preamble added.

Oh, yeah, I see. without lto or whole-program-mode, we cannot determine whether a extern function is address taken or not. Therefore, we have to treat ALL extern functions conservatively as address taken.

Quoted 7 lines

So, from my understanding, the complete list that need to compute the typeid from the function prototype is:

- At indirect call sites
- all indirect call sites; (At the call site)
- At function preambles
- all address-taken static functions (At the function definition)
- all extern functions (At function declaration or function definition?? Please see my question below)

For "extern functions", the logic is split as:
- "all extern function definitions get preamble"
- "all extern function declarations without a definition that are address-taken get __kcfi_typeid_ symbol"

Quoted 10 lines
Quoted 4 lines

The other case is emitting the __ckfi_typeid_FUNC weak symbols, which is used for link-time resolution with non-C code (i.e. raw .S assembly) which doesn't have access to the C type system to calculate the hashes on its own, and needs to have a way to build its own kcfi preambles.

So, for such functions, there should be an extern function declaration in the C code. But the definition of such function is not available in the C code we are compiling. Therefore the weak __ckfi_typeid_FUNC symbol is emitted at the function declaration point for such function when we compile the C code?

Quoted 4 lines

And the typeid (the hash value) for such routine is computed at the function declaration point too.

Is the above understanding correct?

Correct, the kcfi_typeid symbol and value are emitted at function declaration point, but only if such function is address-taken.

Quoted 2 lines

Then for the other extern function whose definition is in the C code of other modules that might be compiled later, should the typeid is computed at the declaration or the definition?

It is computed and emitted just for externs that are address-taken.

Quoted 14 lines
Quoted 14 lines

This
is how Linux constructs its assembly function entry points:

#ifndef __CFI_TYPE

#define __CFI_TYPE(name)                                \
       .4byte __kcfi_typeid_##name

#endif

#define SYM_TYPED_ENTRY(name, linkage, align...)        \
       linkage(name) ASM_NL                            \
       align ASM_NL                                    \
       __CFI_TYPE(name) ASM_NL                         \
       name:
Quoted 5 lines
Quoted 2 lines

That way all the asm functions can be be indirect call targets without knowing the hash value (which will be filled in at link time).

Okay. I see. This is the case for the extern function whose definition is in the assembly file. (Not available in the C code)

Right, and sometimes we have to explicitly perform a no-op address-taking to make sure a symbol gets generated:

/*
* Force the compiler to emit 'sym' as a symbol, so that we can reference
* it from inline assembler. Necessary in case 'sym' could be inlined
* otherwise, or eliminated entirely due to lack of references that are
* visible to the compiler.
*/

#define ___ADDRESSABLE(sym, __attrs)                                            \
        static void * __used __attrs                                            \
        __UNIQUE_ID(__PASTE(__addressable_,sym)) = (void *)(uintptr_t)&sym;
#define __ADDRESSABLE(sym) \
        ___ADDRESSABLE(sym, __section(".discard.addressable"))
$ git grep KCFI_REFERENCE
include/linux/compiler.h:#define KCFI_REFERENCE(sym) __ADDRESSABLE(sym)
arch/x86/include/asm/page_64.h:KCFI_REFERENCE(copy_page);
arch/x86/include/asm/string_64.h:KCFI_REFERENCE(__memset);
arch/x86/include/asm/string_64.h:KCFI_REFERENCE(__memmove);
arch/x86/kernel/alternative.c:KCFI_REFERENCE(__bpf_prog_runX);
arch/x86/kernel/alternative.c:KCFI_REFERENCE(__bpf_callback_fn);
Quoted 4 lines
Quoted 3 lines

I assume I just didn't see how yet. :) I wasn't able to identify nor store the typeid for function definitions that ultimately end up getting .s file output.

So, the problem only exists for the external functions whose definition is NOT in the C code?

Yup!

Quoted 3 lines
Quoted 3 lines

I couldn't figure out how to find these during the GIMPLE pass. Oh, perhaps I can do this with an IPA pass? That should let me walk all functions including externs. I'll give it a try...

Adding the IPA pass to find all functions worked perfectly. I was able to remove all the weird DECL reconstruction and just use the original FUNCTION_TYPE info for the typeids.

-Kees

Signature · 1 line
Kees Cook
#11 lore raw

Re: [RFC PATCH 2/7] mangle: Introduce C typeinfo mangling API

Quoted 24 lines · Kees Cook
Quoted 11 lines · Qing Zhao
Quoted 6 lines · Kees Cook

For non-static functions, we cannot know if other compilation units may make indirect calls to a given function, so those functions must always have their kcfi preamble added. For static functions, if they are address-taken by the current compilation unit, then they must get a kcfi preamble added.

Oh, yeah, I see. without lto or whole-program-mode, we cannot determine whether a extern function is address taken or not. Therefore, we have to treat ALL extern functions conservatively as address taken.

Quoted 7 lines

So, from my understanding, the complete list that need to compute the typeid from the function prototype is:

- At indirect call sites
- all indirect call sites; (At the call site)
- At function preambles
- all address-taken static functions (At the function definition)
- all extern functions (At function declaration or function definition?? Please see my question below)

Quoted 4 lines

For "extern functions", the logic is split as:
- "all extern function definitions get preamble"
- "all extern function declarations without a definition that are address-taken get __kcfi_typeid_ symbol"

Okay.

Quoted 16 lines
Quoted 11 lines
Quoted 5 lines

The other case is emitting the __ckfi_typeid_FUNC weak symbols, which is used for link-time resolution with non-C code (i.e. raw .S assembly) which doesn't have access to the C type system to calculate the hashes on its own, and needs to have a way to build its own kcfi preambles.

So, for such functions, there should be an extern function declaration in the C code. But the definition of such function is not available in the C code we are compiling. Therefore the weak __ckfi_typeid_FUNC symbol is emitted at the function declaration point for such function when we compile the C code?

Quoted 4 lines

And the typeid (the hash value) for such routine is computed at the function declaration point too.

Is the above understanding correct?

Quoted 7 lines

Correct, the kcfi_typeid symbol and value are emitted at function declaration point, but only if such function is address-taken.

Quoted 2 lines

Then for the other extern function whose definition is in the C code of other modules that might be compiled later, should the typeid is computed at the declaration or the definition?

It is computed and emitted just for externs that are address-taken.

Okay.

Quoted 37 lines
Quoted 15 lines
Quoted 15 lines

This
is how Linux constructs its assembly function entry points:

#ifndef __CFI_TYPE

#define __CFI_TYPE(name)                                \
      .4byte __kcfi_typeid_##name

#endif

#define SYM_TYPED_ENTRY(name, linkage, align...)        \
      linkage(name) ASM_NL                            \
      align ASM_NL                                    \
      __CFI_TYPE(name) ASM_NL                         \
      name:
Quoted 5 lines
Quoted 2 lines

That way all the asm functions can be be indirect call targets without knowing the hash value (which will be filled in at link time).

Okay. I see. This is the case for the extern function whose definition is in the assembly file. (Not available in the C code)

Right, and sometimes we have to explicitly perform a no-op address-taking to make sure a symbol gets generated:

/*
* Force the compiler to emit 'sym' as a symbol, so that we can reference
* it from inline assembler. Necessary in case 'sym' could be inlined
* otherwise, or eliminated entirely due to lack of references that are
* visible to the compiler.
*/

#define ___ADDRESSABLE(sym, __attrs)                                            \
       static void * __used __attrs                                            \
       __UNIQUE_ID(__PASTE(__addressable_,sym)) = (void *)(uintptr_t)&sym;
#define __ADDRESSABLE(sym) \
       ___ADDRESSABLE(sym, __section(".discard.addressable"))
Quoted 7 lines
$ git grep KCFI_REFERENCE
include/linux/compiler.h:#define KCFI_REFERENCE(sym) __ADDRESSABLE(sym)
arch/x86/include/asm/page_64.h:KCFI_REFERENCE(copy_page);
arch/x86/include/asm/string_64.h:KCFI_REFERENCE(__memset);
arch/x86/include/asm/string_64.h:KCFI_REFERENCE(__memmove);
arch/x86/kernel/alternative.c:KCFI_REFERENCE(__bpf_prog_runX);
arch/x86/kernel/alternative.c:KCFI_REFERENCE(__bpf_callback_fn);

I am curious on why the compiler eliminates an external routine completely in the file if it's address-taken in that file. Why an additional no-op address-taken is needed here.

Quoted 9 lines
Quoted 6 lines
Quoted 5 lines

I assume I just didn't see how yet. :) I wasn't able to identify nor store the typeid for function definitions that ultimately end up getting .s file output.

So, the problem only exists for the external functions whose definition is NOT in the C code?

Yup!

Quoted 7 lines
Quoted 3 lines
Quoted 3 lines

I couldn't figure out how to find these during the GIMPLE pass. Oh, perhaps I can do this with an IPA pass? That should let me walk all functions including externs. I'll give it a try...

Adding the IPA pass to find all functions worked perfectly. I was able to remove all the weird DECL reconstruction and just use the original FUNCTION_TYPE info for the typeids.

Nice. So this new IPA pass is invoked even when O0?

Qing

Quoted 5 lines

-Kees

Signature · 1 line
Kees Cook
author
#12 lore raw

Re: [RFC PATCH 2/7] mangle: Introduce C typeinfo mangling API

Quoted 25 lines · Qing Zhao
Quoted 17 lines · Kees Cook

Right, and sometimes we have to explicitly perform a no-op address-taking to make sure a symbol gets generated:

/*
* Force the compiler to emit 'sym' as a symbol, so that we can reference
* it from inline assembler. Necessary in case 'sym' could be inlined
* otherwise, or eliminated entirely due to lack of references that are
* visible to the compiler.
*/

#define ___ADDRESSABLE(sym, __attrs)                                            \
       static void * __used __attrs                                            \
       __UNIQUE_ID(__PASTE(__addressable_,sym)) = (void *)(uintptr_t)&sym;
#define __ADDRESSABLE(sym) \
       ___ADDRESSABLE(sym, __section(".discard.addressable"))
Quoted 7 lines
$ git grep KCFI_REFERENCE
include/linux/compiler.h:#define KCFI_REFERENCE(sym) __ADDRESSABLE(sym)
arch/x86/include/asm/page_64.h:KCFI_REFERENCE(copy_page);
arch/x86/include/asm/string_64.h:KCFI_REFERENCE(__memset);
arch/x86/include/asm/string_64.h:KCFI_REFERENCE(__memmove);
arch/x86/kernel/alternative.c:KCFI_REFERENCE(__bpf_prog_runX);
arch/x86/kernel/alternative.c:KCFI_REFERENCE(__bpf_callback_fn);
Quoted 2 lines

I am curious on why the compiler eliminates an external routine completely in the file if it's address-taken in that file. Why an additional no-op address-taken is needed here.

If I am remembering correctly this is needed for rare cases where a function built without a C definition is being used in Linux's self-patching "alternatives" code swaps in one function for another, and is being used indirectly. These cases end up not being visible to compiler (so no address-taken), but the indirect call site is still being instrumented. And the above list is the _entire_ list of such corner cases: all really low-level things.

Peter may remember this better than me...

Quoted 5 lines
Quoted 3 lines

Adding the IPA pass to find all functions worked perfectly. I was able to remove all the weird DECL reconstruction and just use the original FUNCTION_TYPE info for the typeids.

Nice. So this new IPA pass is invoked even when O0?

It seems like it works at any optimization level, yes.

Signature · 1 line
Kees Cook
#13 lore raw

Re: [RFC PATCH 2/7] mangle: Introduce C typeinfo mangling API

Quoted 37 lines · Kees Cook
Quoted 25 lines · Qing Zhao
Quoted 17 lines · Kees Cook

Right, and sometimes we have to explicitly perform a no-op address-taking to make sure a symbol gets generated:

/*
* Force the compiler to emit 'sym' as a symbol, so that we can reference
* it from inline assembler. Necessary in case 'sym' could be inlined
* otherwise, or eliminated entirely due to lack of references that are
* visible to the compiler.
*/

#define ___ADDRESSABLE(sym, __attrs)                                            \
       static void * __used __attrs                                            \
       __UNIQUE_ID(__PASTE(__addressable_,sym)) = (void *)(uintptr_t)&sym;
#define __ADDRESSABLE(sym) \
       ___ADDRESSABLE(sym, __section(".discard.addressable"))
Quoted 7 lines
$ git grep KCFI_REFERENCE
include/linux/compiler.h:#define KCFI_REFERENCE(sym) __ADDRESSABLE(sym)
arch/x86/include/asm/page_64.h:KCFI_REFERENCE(copy_page);
arch/x86/include/asm/string_64.h:KCFI_REFERENCE(__memset);
arch/x86/include/asm/string_64.h:KCFI_REFERENCE(__memmove);
arch/x86/kernel/alternative.c:KCFI_REFERENCE(__bpf_prog_runX);
arch/x86/kernel/alternative.c:KCFI_REFERENCE(__bpf_callback_fn);
Quoted 2 lines

I am curious on why the compiler eliminates an external routine completely in the file if it's address-taken in that file. Why an additional no-op address-taken is needed here.

If I am remembering correctly this is needed for rare cases where a function built without a C definition is being used in Linux's self-patching "alternatives" code swaps in one function for another, and is being used indirectly. These cases end up not being visible to compiler (so no address-taken), but the indirect call site is still being instrumented. And the above list is the _entire_ list of such corner cases: all really low-level things.

Quoted 1 line

Peter may remember this better than me...

The above are all functions from assembly and JITs, the C compiler simply never sees the function definition, only the declaration. The above is used to force emit the __typeid symbol, such that assembly can reference it and it all links correctly.

#14 lore raw

Re: [RFC PATCH 2/7] mangle: Introduce C typeinfo mangling API

Quoted 42 lines · Peter Zijlstra
Quoted 37 lines · Kees Cook
Quoted 25 lines · Qing Zhao
Quoted 17 lines · Kees Cook

Right, and sometimes we have to explicitly perform a no-op address-taking to make sure a symbol gets generated:

/*
* Force the compiler to emit 'sym' as a symbol, so that we can reference
* it from inline assembler. Necessary in case 'sym' could be inlined
* otherwise, or eliminated entirely due to lack of references that are
* visible to the compiler.
*/

#define ___ADDRESSABLE(sym, __attrs)                                            \
      static void * __used __attrs                                            \
      __UNIQUE_ID(__PASTE(__addressable_,sym)) = (void *)(uintptr_t)&sym;
#define __ADDRESSABLE(sym) \
      ___ADDRESSABLE(sym, __section(".discard.addressable"))
Quoted 7 lines
$ git grep KCFI_REFERENCE
include/linux/compiler.h:#define KCFI_REFERENCE(sym) __ADDRESSABLE(sym)
arch/x86/include/asm/page_64.h:KCFI_REFERENCE(copy_page);
arch/x86/include/asm/string_64.h:KCFI_REFERENCE(__memset);
arch/x86/include/asm/string_64.h:KCFI_REFERENCE(__memmove);
arch/x86/kernel/alternative.c:KCFI_REFERENCE(__bpf_prog_runX);
arch/x86/kernel/alternative.c:KCFI_REFERENCE(__bpf_callback_fn);
Quoted 2 lines

I am curious on why the compiler eliminates an external routine completely in the file if it's address-taken in that file. Why an additional no-op address-taken is needed here.

If I am remembering correctly this is needed for rare cases where a function built without a C definition is being used in Linux's self-patching "alternatives" code swaps in one function for another, and is being used indirectly. These cases end up not being visible to compiler (so no address-taken), but the indirect call site is still being instrumented. And the above list is the _entire_ list of such corner cases: all really low-level things.

Quoted 6 lines
Quoted 1 line

Peter may remember this better than me...

The above are all functions from assembly and JITs, the C compiler simply never sees the function definition, only the declaration. The above is used to force emit the __typeid symbol, such that assembly can reference it and it all links correctly.

Okay, I see. Thanks for the information.

Qing

author
#15 lore raw

RFC PATCH 3/7 kcfi: Add core Kernel Control Flow Integrity infrastructure

In reply to Kees Cook

This series 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.

Just to set expectations, this is an RFC because this is my first time working on most of the affected areas in GCC, and it is likely I have missed really obvious stuff, or gone about doing things in very wrong ways. I tried to find the best way to do stuff, but I was left with many questions. :) All that said, this works for x86_64 and aarch64 Linux kernels. (I have implemented riscv64 as well, but I lack a viable test environment -- I am working on this still.)

KCFI has a number of specific constraints. Some are tied to the backend architecture, which I'll cover in more detail in later patches. The constraints are:

- The KCFI scheme generates a unique 32-bit hash for each unique function prototype, allowing for indirect call sites to verify that they are calling into a matching _type_ of function pointer. This changes the semantics of some optimization logic because now indirect calls to different types cannot be merged. For example:

    if (p->func_type_1)
	return p->func_type_1();
    if (p->func_type_2)
	return p->func_type_2();

In final asm, the optimizer may collapse the second indirect call into a jump to the first indirect call once it has loaded the function pointer. KCFI must block cross-type merging otherwise there will be a single KCFI check happening for only 1 type but being used by 2 target types. The distinguishing characteristic for call merging becomes the type, not the address/register usage.

- The check-call instruction sequence must be treated a single unit: it cannot be rearranged or split or optimized. The pattern is that indirect calls, "call *$target", get converted into:

mov $target_expression, %target (only present if the expression was
not already %target)
load -$offset(%target), %tmp
cmp $hash, %tmp
je .Lcheck_passed
.Ltrap$N:
trap
.Lcheck_passed$N:
call *%target

This pattern of call immediately after trap provides for the "permissive" checking mode automatically: the trap gets handled, a warning emitted, and then execution continues after the trap to the call.

(x86_64 uses "mov -$hash, %tmp; addl -$offset(%target), %tmp; je" to zero out the register before making the call. Also Linux needs exactly these insns because it is both disassembling them during trap handling and potentially live patching them at boot time to be converted into a different series of instrutions, a scheme know as FineIBT, making the insn sequence ABI.)

- KCFI check-call instrumentation must survive tail call optimization. If an indirect call is turned into an indirect jump, KCFI checking must still happen (but will still use the jmp).

- Functions that may be called indirectly have a preamble added, __cfi_$original_func_name, that contains the $hash value:

__cfi_target_func:
.word $hash
target_func:
[regular function entry...]

(x86_64 uses a movl instruction to hold the hash and prefixed aligned NOPs to maintain cache line alignment in the face of patchable function entry...)

- The preamble needs to interact with patchable function entry so that the hash appears further away from the actual start of the function (leaving the prefix NOPs of the patchable function entry unchanged). This means only _globally defined_ patchable function entry is supported with KCFI (indrect call sites must know in advance what the offset is, which may not be possible extern functions). For example, a "4,4" patchable function entry would end up like:

__cfi_target_func:
.data $hash
nop nop nop nop
target_func:
[regular function entry...]

(Linux x86_64 uses an 11 byte prefix nop area resulting in 16 bytes total including the movl. This region may be live patched at boot time for FineIBT so the behavior here is also ABI.)

- External functions that are address-taken have a weak __kcfi_typeid_$funcname symbol added with the hash value available so that the hash can be referenced from assembly linkages, etc, where the hash values cannot be calculated (i.e where C type information is missing):

.weak __kcfi_typeid_$func
.set __kcfi_typeid_$func, $hash

- On architectures that do not have a good way to encode additional details in their trap (x86_64 and riscv64), the trap location is identified as a KCFI trap via a relative address offset entry emitted into the .kcfi_traps section for each indirect call site's trap instruction. The previous check-call example's insn sequence has a section push/pop inserted between the trap and call:

...
.Ltrap$N:
trap
.pushsection .kcfi_traps,"ao",@progbits,.text
.Lentry$N:
.long .Ltrap$N - .Lentry$N
.popsection
.Lcheck_passed$N:
call %target

(aarch64 encodes the register numbers that hold the expected hash and the target address in the trap ESR and thereby does not need a .kcfi_traps section at all.)

- The no_sanitize("kcfi") function attribute means that the marked function must not produce KCFI checking for indirect calls, and that this attribute must survive inlining. This is used rarely by Linux, but is required to make BPF JIT trampolines work on older Linux kernel versions. (The preamble code is very recently finally being generated at JIT time on the last remaining Linux KCFI arch where this was
missing: aarch64.)

As a result of these constraints, there are some behavioral aspects that need to be preserved across the middle-end and back-end, as I understand them.

For indirect call sites:

- Keeping indirect calls from being merged (see above). I did this by adding a wrapping type so that equality was tested based on type-id. This is done in create_kcfi_wrapper_type(), via kcfi_instrument(), via an early GIMPLE pass (pass_kcfi and pass_kcfi0). The wrapper type is checked in gcc/cfgcleanup.cc, old_insns_match_p().

- Keeping typeid information available through to the RTL expansion phase was done via a typeid note (REG_CALL_KCFI_TYPE) attached also in create_kcfi_wrapper_type() in the same GIMPLE pass.

- REG_CALL_KCFI_TYPE notes needed to survive optimization passes so RTL expansion could find them again. These are retained in gcc/emit-rtl.cc, try_split(), and gcc/combine.cc, distribute_notes().

- The expansion to RTL is handled in gcc/cfgexpand.cc, expand_call_stmt(). This lets the call expansion logic run, but then marks the resulting call RTL with REG_CALL_KCFI_TYPE so the last RTL instrumentation pass can find it. To me, this logic feels the most weird. It seems like there should be a better place to do this, but I do see that similar behavioral needs are also here, like nocf_check, so perhaps it's not far off.

- The same expand_call_stmt() logic also adds the clobbers that will be present in the final KCFI check-call insn sequences, which need to be added now so that register allocation is aware of them while working through optimization passes. Without this, the clobbered registers may get used in the RTL before we have replaced the call instructions that actually have the clobbers associated with them. This is the "have cake and eat it too" case where we have to do the check-call RTL replacement very late, but need to make sure the clobbers are known very early. Again, this seems like there should be a better way...

- To emit the exact KCFI check-call instruction sequences, a very late RTL pass is used (pass_kcfi_final_instrumentation). In order to handle sibling calls (tail calls), this pass chooses between either a check-call insn sequence or a check-jump insn sequence (provided by the per-arch back-end).

- To make sure instrumentation was skipped for inline functions, the RTL pass walks the basic blocks to identify their function origins, looking for the no_sanitize("kcfi") attribute, and skipping instrumentation if found.

For indirect call targets:

- kcfi_emit_preamble_if_needed() uses function_needs_kcfi_preamble(), and counter helpers, to emit the preablem, with patchable function entry NOPs. This gets used both in default_print_patchable_function_entry() and the per-arch path. I could not find a simpler way to deal with patchable function entry besides splitting it up like this. I feel like there should be a better way.

- gcc/varasm.cc, assemble_external_real() calls emit_kcfi_typeid_symbol() to add the __kcfi_typeid symbols (see get_function_kcfi_type_id() below).

To support the per-arch back-ends, there are some common helpers:

- A callback framework is added via struct kcfi_target_hooks for backends to fill out.

- kcfi_emit_trap_with_section() handles the push/pop section and generating the relative offset section entries.

- get_function_kcfi_type_id() generates the 32-bit hash value, using compute_kcfi_type_id() and kcfi_hash_string() to hook to the mangling API. The hash is FNV-1a right now: it doesn't need secrecy. It could be replaced with any hash, though the hash will need to be coordinated with Rust, which implements the KCFI ABI as well.

---
 gcc/Makefile.in     |   1 +
 gcc/flag-types.h    |   2 +
 gcc/kcfi.h          |  85 +++++
 gcc/tree-pass.h     |   1 +
 gcc/cfgcleanup.cc   |  20 ++
 gcc/cfgexpand.cc    |  61 ++++
 gcc/combine.cc      |   1 +
 gcc/doc/invoke.texi |  29 ++
 gcc/emit-rtl.cc     |   1 +
 gcc/kcfi.cc         | 783 ++++++++++++++++++++++++++++++++++++++++++++
 gcc/opts.cc         |   1 +
 gcc/passes.cc       |   1 +
 gcc/passes.def      |   3 +
 gcc/recog.cc        |   1 +
 gcc/reg-notes.def   |   6 +
 gcc/targhooks.cc    |  50 ++-
 gcc/toplev.cc       |   8 +
 gcc/varasm.cc       |  18 +
 18 files changed, 1071 insertions(+), 1 deletion(-)
 create mode 100644 gcc/kcfi.h
 create mode 100644 gcc/kcfi.cc
gcc/Makefile.in +1 -0
index 86f62611c1d4..01cccd88fde0 100644
@@ -1593,6 +1593,7 @@ OBJS = \
 	ira-emit.o \
 	ira-lives.o \
 	jump.o \
+	kcfi.o \
 	langhooks.o \
 	late-combine.o \
 	lcm.o \
gcc/flag-types.h +2 -0
index 33c88a15ecbb..7ed6dab1bd4b 100644
@@ -337,6 +337,8 @@ enum sanitize_code {
   SANITIZE_KERNEL_HWADDRESS = 1ULL << 30,
   /* Shadow Call Stack.  */
   SANITIZE_SHADOW_CALL_STACK = 1ULL << 31,
+  /* KCFI (Kernel Control Flow Integrity) */
+  SANITIZE_KCFI = 1ULL << 32,
   SANITIZE_SHIFT = SANITIZE_SHIFT_BASE | SANITIZE_SHIFT_EXPONENT,
   SANITIZE_UNDEFINED = SANITIZE_SHIFT | SANITIZE_DIVIDE | SANITIZE_UNREACHABLE
 		       | SANITIZE_VLA | SANITIZE_NULL | SANITIZE_RETURN
gcc/kcfi.h new file +85 -0

85 lines not on this page · raw message

gcc/tree-pass.h +1 -0
index 1c68a69350df..2affea230213 100644
@@ -561,6 +561,7 @@ extern gimple_opt_pass *make_pass_fixup_cfg (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_backprop (gcc::context *ctxt);
 
 extern rtl_opt_pass *make_pass_expand (gcc::context *ctxt);
+extern rtl_opt_pass *make_pass_kcfi_final_instrumentation (gcc::context *ctxt);
 extern rtl_opt_pass *make_pass_instantiate_virtual_regs (gcc::context *ctxt);
 extern rtl_opt_pass *make_pass_rtl_fwprop (gcc::context *ctxt);
 extern rtl_opt_pass *make_pass_rtl_fwprop_addr (gcc::context *ctxt);
gcc/cfgcleanup.cc +20 -0
index d28d23231911..9707b7e22222 100644
@@ -1238,6 +1238,26 @@ old_insns_match_p (int mode ATTRIBUTE_UNUSED, rtx_insn *i1, rtx_insn *i2)
   if (RTX_FRAME_RELATED_P (i1) && !insns_have_identical_cfa_notes (i1, i2))
     return dir_none;
 
+  /* KCFI (Kernel Control Flow Integrity): Do not cross-jump between different
+     KCFI check patterns.  Each bundled KCFI call has a unique type ID that must
+     be preserved to prevent type confusion attacks.  */
+  if (CALL_P (i1) && CALL_P (i2))
+    {
+      rtx kcfi_note1 = find_reg_note (i1, REG_CALL_KCFI_TYPE, NULL_RTX);
+      rtx kcfi_note2 = find_reg_note (i2, REG_CALL_KCFI_TYPE, NULL_RTX);
+
+      if (kcfi_note1 || kcfi_note2)
+	{
+	  /* If only one has KCFI note, they're different.  */
+	  if (!kcfi_note1 || !kcfi_note2)
+	    return dir_none;
+
+	  /* If both have KCFI notes, compare the type IDs.  */
+	  if (!rtx_equal_p (XEXP (kcfi_note1, 0), XEXP (kcfi_note2, 0)))
+	    return dir_none;
+	}
+    }
+
 #ifdef STACK_REGS
   /* If cross_jump_death_matters is not 0, the insn's mode
      indicates whether or not the insn contains any stack-like
gcc/cfgexpand.cc +61 -0

73 lines not on this page · raw message

gcc/combine.cc +1 -0
index 4dbc1f6a4a4e..efaeb426d254 100644
@@ -14525,6 +14525,7 @@ distribute_notes (rtx notes, rtx_insn *from_insn, rtx_insn *i3, rtx_insn *i2,
 	case REG_CALL_DECL:
 	case REG_UNTYPED_CALL:
 	case REG_CALL_NOCF_CHECK:
+	case REG_CALL_KCFI_TYPE:
 	  /* These notes must remain with the call.  It should not be
 	     possible for both I2 and I3 to be a call.  */
 	  if (CALL_P (i3))
gcc/doc/invoke.texi +29 -0
index c1e708beacf3..c66f47336826 100644
@@ -18294,6 +18294,35 @@ possible by specifying the command-line options
 @option{--param hwasan-instrument-allocas=1} respectively. Using a random frame
 tag is not implemented for kernel instrumentation.
 
+@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, terminating the program 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. Only
+functions that have referenced by their address receive the KCFI preamble
+instrumentation.
+
+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.
+
+Use @option{-fdump-tree-kcfi} to examine the computed type identifiers
+and their corresponding mangled type strings during compilation.
+
 @opindex fsanitize=pointer-compare
 @item -fsanitize=pointer-compare
 Instrument comparison operation (<, <=, >, >=) with pointer operands.
gcc/emit-rtl.cc +1 -0
index f4fc92bb37a1..aa56112bc250 100644
@@ -4056,6 +4056,7 @@ try_split (rtx pat, rtx_insn *trial, int last)
 	case REG_SETJMP:
 	case REG_TM:
 	case REG_CALL_NOCF_CHECK:
+	case REG_CALL_KCFI_TYPE:
 	case REG_CALL_ARG_LOCATION:
 	  for (insn = insn_last; insn != NULL_RTX; insn = PREV_INSN (insn))
 	    {
gcc/kcfi.cc new file +783 -0

783 lines not on this page · raw message

gcc/opts.cc +1 -0
index 5fd86aa89adb..ab74414b9c5b 100644
@@ -2168,6 +2168,7 @@ const struct sanitizer_opts_s sanitizer_opts[] =
   SANITIZER_OPT (pointer-overflow, SANITIZE_POINTER_OVERFLOW, true, true),
   SANITIZER_OPT (builtin, SANITIZE_BUILTIN, true, true),
   SANITIZER_OPT (shadow-call-stack, SANITIZE_SHADOW_CALL_STACK, false, false),
+  SANITIZER_OPT (kcfi, SANITIZE_KCFI, false, true),
   SANITIZER_OPT (all, ~0ULL, true, true),
 #undef SANITIZER_OPT
   { NULL, 0ULL, 0UL, false, false }
gcc/passes.cc +1 -0
index a33c8d924a52..4c6ceac740ff 100644
@@ -63,6 +63,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "diagnostic-core.h" /* for fnotice */
 #include "stringpool.h"
 #include "attribs.h"
+#include "kcfi.h"
 
 /* Reserved TODOs */
 #define TODO_verify_il			(1u << 31)
gcc/passes.def +3 -0
index d528a0477d9a..d4c84ca7064d 100644
@@ -275,6 +275,7 @@ along with GCC; see the file COPYING3.  If not see
       NEXT_PASS (pass_sink_code, false /* unsplit edges */);
       NEXT_PASS (pass_sancov);
       NEXT_PASS (pass_asan);
+      NEXT_PASS (pass_kcfi);
       NEXT_PASS (pass_tsan);
       NEXT_PASS (pass_dse, true /* use DR analysis */);
       NEXT_PASS (pass_dce, false /* update_address_taken_p */, false /* remove_unused_locals */);
@@ -443,6 +444,7 @@ along with GCC; see the file COPYING3.  If not see
   NEXT_PASS (pass_sancov_O0);
   NEXT_PASS (pass_lower_switch_O0);
   NEXT_PASS (pass_asan_O0);
+  NEXT_PASS (pass_kcfi_O0);
   NEXT_PASS (pass_tsan_O0);
   NEXT_PASS (pass_musttail);
   NEXT_PASS (pass_sanopt);
@@ -563,6 +565,7 @@ along with GCC; see the file COPYING3.  If not see
 	  NEXT_PASS (pass_delay_slots);
 	  NEXT_PASS (pass_split_for_shorten_branches);
 	  NEXT_PASS (pass_convert_to_eh_region_ranges);
+	  NEXT_PASS (pass_kcfi_final_instrumentation);
 	  NEXT_PASS (pass_shorten_branches);
 	  NEXT_PASS (pass_set_nothrow_function_flags);
 	  NEXT_PASS (pass_dwarf2_frame);
gcc/recog.cc +1 -0
index 67d7fa630692..127524cfb4e2 100644
@@ -4026,6 +4026,7 @@ peep2_attempt (basic_block bb, rtx_insn *insn, int match_len, rtx_insn *attempt)
 	  case REG_SETJMP:
 	  case REG_TM:
 	  case REG_CALL_NOCF_CHECK:
+	  case REG_CALL_KCFI_TYPE:
 	    add_reg_note (new_insn, REG_NOTE_KIND (note),
 			  XEXP (note, 0));
 	    break;
gcc/reg-notes.def +6 -0
index 68e137ceccaa..27924ee8afda 100644
@@ -251,5 +251,11 @@ REG_NOTE (UNTYPED_CALL)
    compiler when the option -fcf-protection=branch is specified.  */
 REG_NOTE (CALL_NOCF_CHECK)
 
+/* Contains the expected KCFI type ID for an indirect call instruction.
+   This note carries the 32-bit type identifier that should match the
+   type ID stored in the function preamble.  Used by KCFI (Kernel Control
+   Flow Integrity) to validate indirect call targets at runtime.  */
+REG_NOTE (CALL_KCFI_TYPE)
+
 /* The values passed to callee, for debuginfo purposes.  */
 REG_NOTE (CALL_ARG_LOCATION)
gcc/targhooks.cc +49 -1

77 lines not on this page · raw message

gcc/toplev.cc +8 -0
index 70dbb3e717f6..04331947b9da 100644
@@ -67,6 +67,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"
@@ -524,6 +525,7 @@ compile_file (void)
       insn_locations_init ();
       targetm.asm_out.code_end ();
 
+
       /* Do dbx symbols.  */
       timevar_push (TV_SYMOUT);
 
@@ -1733,6 +1735,12 @@ process_options ()
 		  "requires %<-fno-exceptions%>");
     }
 
+  if (flag_sanitize & SANITIZE_KCFI)
+    {
+      if (!kcfi_target.gen_kcfi_checked_call)
+	sorry ("%<-fsanitize=kcfi%> not supported by this target");
+    }
+
   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/varasm.cc +18 -0
index 000ad9e26f6f..9c4e3c223159 100644
@@ -57,6 +57,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "attribs.h"
 #include "asan.h"
 #include "rtl-iter.h"
+#include "kcfi.h"
 #include "file-prefix-map.h" /* remap_debug_filename()  */
 #include "alloc-pool.h"
 #include "toplev.h"
@@ -2210,6 +2211,10 @@ assemble_start_function (tree decl, const char *fnname)
   ASM_OUTPUT_FUNCTION_LABEL (asm_out_file, fnname, current_function_decl);
 #endif /* ASM_DECLARE_FUNCTION_NAME */
 
+  /* KCFI type ID symbols are only emitted for external function declarations,
+     handled by assemble_external_real().  Function definitions do not emit
+     __kcfi_typeid symbols.  */
+
   /* And the area after the label.  Record it if we haven't done so yet.  */
   if (patch_area_size > patch_area_entry)
     targetm.asm_out.print_patchable_function_entry (asm_out_file,
@@ -2752,6 +2757,19 @@ assemble_external_real (tree decl)
       /* Some systems do require some output.  */
       SYMBOL_REF_USED (XEXP (rtl, 0)) = 1;
       ASM_OUTPUT_EXTERNAL (asm_out_file, decl, XSTR (XEXP (rtl, 0), 0));
+
+      /* Emit KCFI type ID symbol for external function declarations that are address-taken.  */
+      struct cgraph_node *node = (TREE_CODE (decl) == FUNCTION_DECL) ? cgraph_node::get (decl) : NULL;
+      if (flag_sanitize & SANITIZE_KCFI
+	  && TREE_CODE (decl) == FUNCTION_DECL
+	  && !DECL_INITIAL (decl)  /* Only for external declarations (no function body) */
+	  && node && node->address_taken)  /* Use direct cgraph analysis for address-taken check.  */
+	{
+	  const char *name = XSTR (XEXP (rtl, 0), 0);
+	  /* Strip any encoding prefixes like '*' from symbol name.  */
+	  name = targetm.strip_name_encoding (name);
+	  emit_kcfi_typeid_symbol (asm_out_file, decl, name);
+	}
     }
 }
 #endif
Signature · 1 line
2.34.1

A message that is not in the archive (sent off-list or not yet received): CALvbMcA+8iHo+zCCvs4UdAg9PVQVtgOno-rtMS4i5YajrjkyGw@mail.gmail.com

#17 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 8 lines · Andrew Pinski
Quoted 8 lines

+/* Compute KCFI type ID for a function declaration or function type (internal) */

gcc/kcfi.cc new file +6 -0
+static uint32_t
+compute_kcfi_type_id (tree fntype_or_fndecl)
+{
+  if (!fntype_or_fndecl)
+    return 0;
+
Quoted 8 lines

gcc/kcfi.cc line 97

Quoted 3 lines
gcc/kcfi.cc new file +2 -0
+  const char *canonical_name = mangle_function_type (fntype_or_fndecl);
+  uint32_t base_type_id = kcfi_hash_string (canonical_name);

Now I am curious why this needs to be a mangled function name? Since the function in C the symbol is just its name.
Is there documentation that says the hash needs to be based on all of the function arguments types?

The whole point of kCFI is to limit the targets of indirect calls to functions of the same signature. The actual function name is immaterial.

#18 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 19 lines · Peter Zijlstra
Quoted 8 lines · Andrew Pinski
Quoted 8 lines

+/* Compute KCFI type ID for a function declaration or function type (internal) */

gcc/kcfi.cc new file +6 -0
+static uint32_t
+compute_kcfi_type_id (tree fntype_or_fndecl)
+{
+  if (!fntype_or_fndecl)
+    return 0;
+
Quoted 8 lines

gcc/kcfi.cc line 97

Quoted 3 lines
gcc/kcfi.cc new file +2 -0
+  const char *canonical_name = mangle_function_type (fntype_or_fndecl);
+  uint32_t base_type_id = kcfi_hash_string (canonical_name);

Now I am curious why this needs to be a mangled function name? Since the function in C the symbol is just its name.
Is there documentation that says the hash needs to be based on all of the function arguments types?

Quoted 2 lines

The whole point of kCFI is to limit the targets of indirect calls to functions of the same signature. The actual function name is immaterial.

What's the attack vector and how does kCFI achieve mitigating it?

Richard.

#19 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 21 lines · Richard Biener
Quoted 19 lines · Peter Zijlstra
Quoted 16 lines · Andrew Pinski

gcc/kcfi.cc line 97

Quoted 11 lines

+/* Compute KCFI type ID for a function declaration or function type (internal) */

gcc/kcfi.cc new file +8 -0
+static uint32_t
+compute_kcfi_type_id (tree fntype_or_fndecl)
+{
+  if (!fntype_or_fndecl)
+    return 0;
+
+  const char *canonical_name = mangle_function_type (fntype_or_fndecl);
+  uint32_t base_type_id = kcfi_hash_string (canonical_name);

Now I am curious why this needs to be a mangled function name? Since the function in C the symbol is just its name.
Is there documentation that says the hash needs to be based on all of the function arguments types?

Quoted 4 lines
Quoted 2 lines

The whole point of kCFI is to limit the targets of indirect calls to functions of the same signature. The actual function name is immaterial.

What's the attack vector and how does kCFI achieve mitigating it?

Any of the attacks that can result in scribbling a function pointer. Typically a buffer overflow I suppose.

The way kCFI works is by changing the indirect call ABI. Traditionally the indirect call is simply:

load-pointer-into-reg
call *%reg

kCFI changes every function to have a preamble like (with IBT and retpolines and all the modern crap on):

__cfi_\func:
movl $0x12345678, %eax
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
\func:
endbr64
...

And every indirect call site to:

load-pointer-into-r11
movl $(-0x12345678), %r10d
addl $-15(%r11), %r10d
je 2f
1:ud2
.pushsection .kcfi_traps
.long 1b - .
.popsection
2:cs call __x86_indirect_thunk_r11

Where 0x12345678 is the appropriate signature hash.

So if the loaded pointer is scribbled somehow, the hash embedded at the callsite no longer matches the hash in the function preamble and #UD.

The kernel is also going to rewrite this if the hardware supports IBT, into a FineIBT sequence (with too many variants :-/), but I'll spare you those details.

Those people interested can find it here:

https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/x86/kernel/alternative.c#n1298

#20 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 35 lines · Peter Zijlstra
Quoted 21 lines · Richard Biener
Quoted 19 lines · Peter Zijlstra
Quoted 16 lines · Andrew Pinski

gcc/kcfi.cc line 97

Quoted 11 lines

+/* Compute KCFI type ID for a function declaration or function type (internal) */

gcc/kcfi.cc new file +8 -0
+static uint32_t
+compute_kcfi_type_id (tree fntype_or_fndecl)
+{
+  if (!fntype_or_fndecl)
+    return 0;
+
+  const char *canonical_name = mangle_function_type (fntype_or_fndecl);
+  uint32_t base_type_id = kcfi_hash_string (canonical_name);

Now I am curious why this needs to be a mangled function name? Since the function in C the symbol is just its name.
Is there documentation that says the hash needs to be based on all of the function arguments types?

Quoted 4 lines
Quoted 2 lines

The whole point of kCFI is to limit the targets of indirect calls to functions of the same signature. The actual function name is immaterial.

What's the attack vector and how does kCFI achieve mitigating it?

Any of the attacks that can result in scribbling a function pointer. Typically a buffer overflow I suppose.

Quoted 8 lines

The way kCFI works is by changing the indirect call ABI. Traditionally the indirect call is simply:

load-pointer-into-reg
call *%reg

kCFI changes every function to have a preamble like (with IBT and retpolines and all the modern crap on):

Does “every function” mean all the function in the compilation? Not only the function whose address is taken?

Qing

Quoted 46 lines

__cfi_\func:
movl $0x12345678, %eax
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
\func:
endbr64
...

And every indirect call site to:

load-pointer-into-r11
movl $(-0x12345678), %r10d
addl $-15(%r11), %r10d
je 2f
1:ud2
.pushsection .kcfi_traps
.long 1b - .
.popsection
2:cs call __x86_indirect_thunk_r11

Where 0x12345678 is the appropriate signature hash.

So if the loaded pointer is scribbled somehow, the hash embedded at the callsite no longer matches the hash in the function preamble and #UD.

The kernel is also going to rewrite this if the hardware supports IBT, into a FineIBT sequence (with too many variants :-/), but I'll spare you those details.

Those people interested can find it here:

https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/x86/kernel/alternative.c#n1298

author
#21 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 36 lines · Qing Zhao
Quoted 36 lines · Peter Zijlstra
Quoted 21 lines · Richard Biener
Quoted 19 lines · Peter Zijlstra
Quoted 16 lines · Andrew Pinski

gcc/kcfi.cc line 97

Quoted 11 lines

+/* Compute KCFI type ID for a function declaration or function type (internal) */

gcc/kcfi.cc new file +8 -0
+static uint32_t
+compute_kcfi_type_id (tree fntype_or_fndecl)
+{
+  if (!fntype_or_fndecl)
+    return 0;
+
+  const char *canonical_name = mangle_function_type (fntype_or_fndecl);
+  uint32_t base_type_id = kcfi_hash_string (canonical_name);

Now I am curious why this needs to be a mangled function name? Since the function in C the symbol is just its name.
Is there documentation that says the hash needs to be based on all of the function arguments types?

Quoted 4 lines
Quoted 2 lines

The whole point of kCFI is to limit the targets of indirect calls to functions of the same signature. The actual function name is immaterial.

What's the attack vector and how does kCFI achieve mitigating it?

Any of the attacks that can result in scribbling a function pointer. Typically a buffer overflow I suppose.

The way kCFI works is by changing the indirect call ABI. Traditionally the indirect call is simply:

Quoted 7 lines
Quoted 5 lines

load-pointer-into-reg
call *%reg

kCFI changes every function to have a preamble like (with IBT and retpolines and all the modern crap on):

Does “every function” mean all the function in the compilation? Not only the function whose address is taken?

I tried to explain the specific logic on how the set of functions getting preambles is chosen in this other reply:
https://lore.kernel.org/linux-hardening/202508211258.8DEE293@keescook/

If that didn't answer your question, let me know and I'll try again. :)

-Kees

Signature · 1 line
Kees Cook
#22 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 6 lines · Kees Cook
Quoted 5 lines · Qing Zhao
Quoted 4 lines · Peter Zijlstra

kCFI changes every function to have a preamble like (with IBT and retpolines and all the modern crap on):

Quoted 7 lines
Quoted 1 line

Does “every function” mean all the function in the compilation? Not only the function whose address is taken?

I tried to explain the specific logic on how the set of functions getting preambles is chosen in this other reply:
https://lore.kernel.org/linux-hardening/202508211258.8DEE293@keescook/

If that didn't answer your question, let me know and I'll try again. :)

One detail that might be interesting is that ENDBR and the __cfi_\func preamble should be the same condition. The way these features are exposed doesn't make this obvious.

And in fact, marking an address taken function with __noendbr will result in a function that has a __cfi_\func preamble, but no ENDBR (clang-20).

And while there is both a __noendbr and __nocfi attribute, they are *VERY* different from one another. Where __noendbr inhibits the emission of ENDBR and basically marks the function as impossible to reach with an indirect call, the __nocfi attribute inhibits the CALL modification.

Notably, there is no function attribute to inhibit the __cfi_\func preamble (and I'm arguing __noendbr should have that effect).

OTOH a function without __cfi_\func preamble but with ENDBR is 'unsafe', but usable with a __nocfi call (typically reserved for calling external code, like firmware). Anyway, we don't currently have means of expressing this to the compiler (also, I don't care much in this case -- I think we should taint the kernel on EFI calls :-).

author
#23 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

In reply to Richard Biener
Quoted 21 lines · Richard Biener
Quoted 19 lines · Peter Zijlstra
Quoted 16 lines · Andrew Pinski

gcc/kcfi.cc line 97

Quoted 11 lines

+/* Compute KCFI type ID for a function declaration or function type (internal) */

gcc/kcfi.cc new file +8 -0
+static uint32_t
+compute_kcfi_type_id (tree fntype_or_fndecl)
+{
+  if (!fntype_or_fndecl)
+    return 0;
+
+  const char *canonical_name = mangle_function_type (fntype_or_fndecl);
+  uint32_t base_type_id = kcfi_hash_string (canonical_name);

Now I am curious why this needs to be a mangled function name? Since the function in C the symbol is just its name.
Is there documentation that says the hash needs to be based on all of the function arguments types?

Quoted 4 lines
Quoted 2 lines

The whole point of kCFI is to limit the targets of indirect calls to functions of the same signature. The actual function name is immaterial.

What's the attack vector and how does kCFI achieve mitigating it?

To add some more detail to Peter's answer, the attack vector is dealing with stored function pointers (generally on the heap, but potentially also the stack), that can be changed by attacker-controlled writes (via buffer overflows or use-after-free writes). The idea being that instead of being able to call anywhere through an indirect call site that uses a manipulated pointer, now the attacker is limited to a subset of "matching" destinations. (KCFI depends on a system already enforcing W^X memory in the sense that if an attacker can construct an executable region, they could write whatever hash they want into in addition to whatever code.)

The general CFI ideas for this are discussed here, but focuses more on a CFG analysis to construct valid call destinations, which tends to require LTO, etc:
https://users.soe.ucsc.edu/~abadi/Papers/cfi-tissec-revised.pdf

Later refinement for using jump tables (constructed via CFG analysis during LTO) was proposed here:
https://www.usenix.org/system/files/conference/usenixsecurity14/sec14-paper-tice.pdf
Linux used the above implementation from 2018 to 2022:
https://android-developers.googleblog.com/2018/10/control-flow-integrity-in-android-kernel.html
but the corner cases for target addresses not being the actual functions (i.e. pointing into the jump table) was a continual source of problems, and generating the jump tables required full LTO, which had its own set of problems.

Looking at function prototypes as the source of call validity was presented here, though still relied on LTO:
https://www.blackhat.com/docs/asia-17/materials/asia-17-Moreira-Drop-The-Rop-Fine-Grained-Control-Flow-Integrity-For-The-Linux-Kernel-wp.pdf

The KCFI approach built on the function-prototype idea, but avoided needing LTO, and could be further updated to deal with CPU errata (retpolines, etc):
https://lpc.events/event/16/contributions/1315/
This has been working very well now for 3 years, but has been limited to only Linux built with Clang (e.g. Linux kernel CFI, first LLVM-CFI and now KCFI, has been deployed on all Android phones and all Chrome OS devices since 2018.)

I have been trying to find someone to work on KCFI in GCC since 2018, (see my annual arm-waving at the Linux Plumbers conference Toolchain track) and other than Dan Li who took a stab at it for aarch64 in 2023, no one has stepped up to do it, so I thought I'd finally try tackling it. :)

-Kees

Signature · 1 line
Kees Cook
#24 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 65 lines · Kees Cook
Quoted 21 lines · Richard Biener
Quoted 19 lines · Peter Zijlstra
Quoted 16 lines · Andrew Pinski

gcc/kcfi.cc line 97

Quoted 11 lines

+/* Compute KCFI type ID for a function declaration or function type (internal) */

gcc/kcfi.cc new file +8 -0
+static uint32_t
+compute_kcfi_type_id (tree fntype_or_fndecl)
+{
+  if (!fntype_or_fndecl)
+    return 0;
+
+  const char *canonical_name = mangle_function_type (fntype_or_fndecl);
+  uint32_t base_type_id = kcfi_hash_string (canonical_name);

Now I am curious why this needs to be a mangled function name? Since the function in C the symbol is just its name.
Is there documentation that says the hash needs to be based on all of the function arguments types?

Quoted 4 lines
Quoted 2 lines

The whole point of kCFI is to limit the targets of indirect calls to functions of the same signature. The actual function name is immaterial.

What's the attack vector and how does kCFI achieve mitigating it?

To add some more detail to Peter's answer, the attack vector is dealing with stored function pointers (generally on the heap, but potentially also the stack), that can be changed by attacker-controlled writes (via buffer overflows or use-after-free writes). The idea being that instead of being able to call anywhere through an indirect call site that uses a manipulated pointer, now the attacker is limited to a subset of "matching" destinations. (KCFI depends on a system already enforcing W^X memory in the sense that if an attacker can construct an executable region, they could write whatever hash they want into in addition to whatever code.)

The general CFI ideas for this are discussed here, but focuses more on a CFG analysis to construct valid call destinations, which tends to require LTO, etc:
https://users.soe.ucsc.edu/~abadi/Papers/cfi-tissec-revised.pdf

Later refinement for using jump tables (constructed via CFG analysis during LTO) was proposed here:
https://www.usenix.org/system/files/conference/usenixsecurity14/sec14-paper-tice.pdf
Linux used the above implementation from 2018 to 2022:
https://android-developers.googleblog.com/2018/10/control-flow-integrity-in-android-kernel.html
but the corner cases for target addresses not being the actual functions (i.e. pointing into the jump table) was a continual source of problems, and generating the jump tables required full LTO, which had its own set of problems.

Looking at function prototypes as the source of call validity was presented here, though still relied on LTO:
https://www.blackhat.com/docs/asia-17/materials/asia-17-Moreira-Drop-The-Rop-Fine-Grained-Control-Flow-Integrity-For-The-Linux-Kernel-wp.pdf

The KCFI approach built on the function-prototype idea, but avoided needing LTO, and could be further updated to deal with CPU errata (retpolines, etc):
https://lpc.events/event/16/contributions/1315/
This has been working very well now for 3 years, but has been limited to only Linux built with Clang (e.g. Linux kernel CFI, first LLVM-CFI and now KCFI, has been deployed on all Android phones and all Chrome OS devices since 2018.)

Quoted 5 lines

I have been trying to find someone to work on KCFI in GCC since 2018, (see my annual arm-waving at the Linux Plumbers conference Toolchain track) and other than Dan Li who took a stab at it for aarch64 in 2023, no one has stepped up to do it, so I thought I'd finally try tackling it. :)

Thanks for the write-up. So I wonder whether a more general solution would be to detach "hash value" computation and assignment and leave that to external tooling that could do better than non-LTO can and the compiler working with attributed function types instead? Say

void __attribute__((cfi_hash("voidvoidbutonlykind1"))) foo (void);

that decouples the way to arrive at the hashes from the instrumentation. You could then of course have compiler assisted auto-attribution based on function types. So implementation-wise I'd try to separate both? Oh, and somehow it reminds me of vtable verification?

That said, how's the collision rate on the kernel side?

What's the usual exploitation of overwriting a call function pointer? That is, what's a good useful function to target? I'd guess a hypothetical setuid (int)? Somehow it feels like a more academic thing, with other attack vectors being much more accessible?

Richard.

author
#25 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 6 lines · Richard Biener

Thanks for the write-up. So I wonder whether a more general solution would be to detach "hash value" computation and assignment and leave that to external tooling that could do better than non-LTO can and the compiler working with attributed function types instead? Say

void __attribute__((cfi_hash("voidvoidbutonlykind1"))) foo (void);

Yeah, having a way to choose different hashes was part of Joao's thesis. Additionally, using a function attribute to salt a given function's hash had been on the KCFI TODO list for a few years and just got implemented in Clang last week:
https://clang.llvm.org/docs/AttributeReference.html#cfi-salt

I intend to get that implemented too, but I wanted to get the core KCFI landed first.

Quoted 6 lines

that decouples the way to arrive at the hashes from the instrumentation. You could then of course have compiler assisted auto-attribution based on function types. So implementation-wise I'd try to separate both? Oh, and somehow it reminds me of vtable verification?

That said, how's the collision rate on the kernel side?

The salting (and Joao's work) are designed specifically for dealing with collisions; you can see the frequency graph in here:
https://security.googleblog.com/2018/10/posted-by-sami-tolvanen-staff-software.html
In the Android Linux kernel, indirect calls:
- 55% have <= 5 targets
- 7% have > 100 targets

Breaking up that long 7% tail has been the goal with either LTO analysis to split up the groups or manual annotation (i.e. hash salt).

Quoted 4 lines

What's the usual exploitation of overwriting a call function pointer? That is, what's a good useful function to target? I'd guess a hypothetical setuid (int)? Somehow it feels like a more academic thing, with other attack vectors being much more accessible?

For forward edge, it's usually calling a series of useful targets. Calling into functions to disable SMAP/SMEP, turn off SELinux, setuid, etc. Each of these specific cases have been hardened over the years (no non-inline MSR manipulation, SELinux permissive knob removed, credential creation doesn't take a default arg, etc).

What we've seen after the addition of CFI (and other hardening) in Linux was a greater push by attackers toward the less "low-hanging fruit" of "data only" attacks (e.g. write to the page tables, etc). Jann Horn has a particularly sobering write-up about this via memory allocators:
https://googleprojectzero.blogspot.com/2021/10/how-simple-linux-kernel-memory.html

-Kees

Signature · 1 line
Kees Cook

A message that is not in the archive (sent off-list or not yet received): CA+=Sn1koTTQaXDnAVWtVU6ACWwhD08NR5nDJO236Pmcoi2X9qA@mail.gmail.com

#27 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 22 lines · Andrew Pinski
Quoted 20 lines · Peter Zijlstra
Quoted 9 lines · Andrew Pinski

gcc/kcfi.cc

Quoted 9 lines

+/* Compute KCFI type ID for a function declaration or function type (internal) */

gcc/kcfi.cc new file +7 -0
+static uint32_t
+compute_kcfi_type_id (tree fntype_or_fndecl)
+{
+  if (!fntype_or_fndecl)
+    return 0;
+
+  const char *canonical_name = mangle_function_type

(fntype_or_fndecl);

Quoted 7 lines
Quoted 2 lines

+ uint32_t base_type_id = kcfi_hash_string (canonical_name);

Now I am curious why this needs to be a mangled function name? Since the function in C the symbol is just its name.
Is there documentation that says the hash needs to be based on all of the function arguments types?

Quoted 7 lines
Quoted 3 lines

The whole point of kCFI is to limit the targets of indirect calls to functions of the same signature. The actual function name is immaterial.

So then just hash the function argument types. It only needs to be consistent for the objects that are compiled together right?

Function argument and return; but yes that could be done. Ideally the kCFI implementation would be compatible between compilers. Specifically rust is based on llvm and therefore generates kCFI that is compatible with clang. Being able to mix GCC and rust code (as the kernel does) would be nice.

#28 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 28 lines · Peter Zijlstra
Quoted 27 lines · Andrew Pinski
Quoted 23 lines · Peter Zijlstra
Quoted 9 lines · Andrew Pinski

gcc/kcfi.cc

Quoted 9 lines

+/* Compute KCFI type ID for a function declaration or function type (internal) */

gcc/kcfi.cc new file +7 -0
+static uint32_t
+compute_kcfi_type_id (tree fntype_or_fndecl)
+{
+  if (!fntype_or_fndecl)
+    return 0;
+
+  const char *canonical_name = mangle_function_type

(fntype_or_fndecl);

Quoted 7 lines
Quoted 2 lines

+ uint32_t base_type_id = kcfi_hash_string (canonical_name);

Now I am curious why this needs to be a mangled function name? Since the function in C the symbol is just its name.
Is there documentation that says the hash needs to be based on all of the function arguments types?

The whole point of kCFI is to limit the targets of indirect calls to functions of the same signature. The actual function name is immaterial.

Quoted 8 lines
Quoted 2 lines

So then just hash the function argument types. It only needs to be consistent for the objects that are compiled together right?

Function argument and return; but yes that could be done. Ideally the kCFI implementation would be compatible between compilers. Specifically rust is based on llvm and therefore generates kCFI that is compatible with clang. Being able to mix GCC and rust code (as the kernel does) would be nice.

FWIW, Kees, for this to actually work, we need this CFI_ICALL_NORMALIZE_INTEGERS thing supported. Rust gets really upset about LP64's whole 'long' vs 'long long' trainwreck :/

That is the -fsanitize-cfi-icall-experimental-normalize-integers argument for clang (omg so long).

author
#29 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 38 lines · Peter Zijlstra
Quoted 28 lines · Peter Zijlstra
Quoted 27 lines · Andrew Pinski
Quoted 23 lines · Peter Zijlstra
Quoted 9 lines · Andrew Pinski

gcc/kcfi.cc

Quoted 9 lines

+/* Compute KCFI type ID for a function declaration or function type (internal) */

gcc/kcfi.cc new file +7 -0
+static uint32_t
+compute_kcfi_type_id (tree fntype_or_fndecl)
+{
+  if (!fntype_or_fndecl)
+    return 0;
+
+  const char *canonical_name = mangle_function_type

(fntype_or_fndecl);

Quoted 7 lines
Quoted 2 lines

+ uint32_t base_type_id = kcfi_hash_string (canonical_name);

Now I am curious why this needs to be a mangled function name? Since the function in C the symbol is just its name.
Is there documentation that says the hash needs to be based on all of the function arguments types?

The whole point of kCFI is to limit the targets of indirect calls to functions of the same signature. The actual function name is immaterial.

Quoted 8 lines
Quoted 2 lines

So then just hash the function argument types. It only needs to be consistent for the objects that are compiled together right?

Function argument and return; but yes that could be done. Ideally the kCFI implementation would be compatible between compilers. Specifically rust is based on llvm and therefore generates kCFI that is compatible with clang. Being able to mix GCC and rust code (as the kernel does) would be nice.

Quoted 6 lines

FWIW, Kees, for this to actually work, we need this CFI_ICALL_NORMALIZE_INTEGERS thing supported. Rust gets really upset about LP64's whole 'long' vs 'long long' trainwreck :/

That is the -fsanitize-cfi-icall-experimental-normalize-integers argument for clang (omg so long).

Yup! I forgot to include my "TODO" list in the RFC. It is:

* -fsanitize-cfi-icall-experimental-normalize-integers (but this option needs a better name if it's going to be supported in GCC too for Rust compat)

* -fsanitize-kcfi-arity
https://clang.llvm.org/docs/ControlFlowIntegrity.html#fsanitize-kcfi-arity

* cfi_salt function attribute
https://clang.llvm.org/docs/AttributeReference.html#cfi-salt
https://github.com/llvm/llvm-project/commit/aa4805a09052c1b6298718eeb6d30c33dd0d695f

-Kees

Signature · 1 line
Kees Cook
author
#30 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

In reply to a message not in the archive
Quoted 20 lines · Andrew Pinski
Quoted 19 lines · Kees Cook
gcc/kcfi.h new file +5 -0
+struct kcfi_target_hooks {
+  /* Apply architecture-specific masking to type ID.  */
+  uint32_t (*mask_type_id) (uint32_t type_id);
+
+  /* Generate bundled KCFI checked call (atomic check + call to prevent

optimizer separation) */
+ rtx (*gen_kcfi_checked_call) (rtx call_insn, rtx target_reg, uint32_t expected_type, HOST_WIDE_INT prefix_nops);

gcc/kcfi.h new file +5 -0
+
+  /* Add architecture-specific register clobbers for KCFI calls.  */
+  void (*add_kcfi_clobbers) (rtx_insn *call_insn);
+
+  /* Calculate architecture-specific prefix NOPs count (optional, returns

prefix_nops unchanged if NULL) */

gcc/kcfi.h new file +3 -0
+  int (*calculate_prefix_nops) (HOST_WIDE_INT prefix_nops);
+
+  /* Emit architecture-specific type ID instruction (required for common

preamble helper) */
+ void (*emit_type_id_instruction) (FILE *file, uint32_t type_id);

Quoted 8 lines
Quoted 2 lines

+};

This should really be part of target.def so you also have the internals documentation done for these hooks.
And then you could just use targetm.kcfi.xyz below.
And for the hooks you would have TARGET_KCFI_XYZ being defined like the others one.

Ah-ha! Thank you. The macros to build that eluded me. I've updated to this now.

Quoted 7 lines

gcc/kcfi.h line 79

Quoted 5 lines
gcc/kcfi.h new file +4 -0
+/* Pass creation functions.  */
+class gimple_opt_pass;
+class rtl_opt_pass;
+namespace gcc { class context; }

This above is definitely bad form.

Ah yeah, sorry; this was a leftover. (And below.)

Quoted 8 lines
Quoted 6 lines
gcc/kcfi.h new file +4 -0
+
+extern gimple_opt_pass *make_pass_kcfi (gcc::context *ctxt);
+extern gimple_opt_pass *make_pass_kcfi_O0 (gcc::context *ctxt);
+extern rtl_opt_pass *make_pass_kcfi_final_instrumentation (gcc::context

*ctxt);

these 3 lines should just be in tree-pass.h with the other make_pass_*.

Yup, totally. I've moved these now.

Quoted 18 lines
Quoted 18 lines
gcc/cfgexpand.cc +1 -0
index 8950294abb60..432ccc7f864a 100644
@@ -76,6 +76,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "opts.h"
 #include "gimple-range.h"
 #include "rtl-iter.h"
+#include "kcfi.h"
 
 /* Some systems use __main in a way incompatible with its use in gcc, in

these
cases use the macros NAME__MAIN to give a quoted symbol and
SYMBOL__MAIN to

gcc/cfgexpand.cc +0 -0
@@ -3203,6 +3204,66 @@ expand_call_stmt (gcall *stmt)
   else
     expand_expr (exp, const0_rtx, VOIDmode, EXPAND_NORMAL);
 
Quoted 7 lines
Quoted 4 lines
gcc/cfgexpand.cc +1 -0
+  /* Add KCFI annotations if this is an indirect call with KCFI wrapper

type. */
+ if (sanitize_flags_p (SANITIZE_KCFI) && !gimple_call_fndecl (stmt))

Internal function calls with also have a null fndecl can you double check that you don't have an internal function call here?

I think I need this explained in more detail. This logic mostly matches the nocf_check below:

if (gimple_call_nocf_check_p (stmt)

      && !gimple_call_fndecl (stmt))

Or do you mean the fn_type below?

Quoted 5 lines

gcc/cfgexpand.cc expand_call_stmt (gcall *stmt) · line 3211

Quoted 5 lines
gcc/cfgexpand.cc +3 -0
+    {
+      tree fn_type = gimple_call_fntype (stmt);
+      gcc_assert (fn_type);

... here? I haven't encountered this assert, if that's a useful signal. :)

Quoted 10 lines
Quoted 9 lines

+ tree attr = lookup_attribute ("kcfi_type_id", TYPE_ATTRIBUTES
(fn_type));

gcc/cfgexpand.cc +3 -0
+      if (attr && TREE_VALUE (attr))
+       {
+         /* Check if this call site originated from a no_sanitize("kcfi")

function
+ during inlining. If so, skip KCFI instrumentation in RTL
phase too. */

Quoted 3 lines

Why not add a bit to gimple_call and add while inlining instead of looking it up afterwards?
I am not 100% sure the BLOCK will always be correct.

Ah, I think I see how: add a new GF_CALL_* flag? I'll go find where inlining happens...

Quoted 30 lines
Quoted 30 lines
gcc/cfgexpand.cc +11 -0
+         bool should_skip_kcfi = false;
+         location_t call_location = gimple_location (stmt);
+         gcc_assert (call_location != UNKNOWN_LOCATION);
+
+         tree block = gimple_block (stmt);
+         while (block && TREE_CODE (block) == BLOCK)
+           {
+             tree fn_decl = BLOCK_ABSTRACT_ORIGIN (block);
+             if (fn_decl && TREE_CODE (fn_decl) == FUNCTION_DECL)
+               {
+                 /* Found an inlined function - check if it has

no_sanitize("kcfi"). */

gcc/cfgexpand.cc +8 -0
+                 if (!sanitize_flags_p (SANITIZE_KCFI, fn_decl))
+                   {
+                     should_skip_kcfi = true;
+                     break;
+                   }
+                 break;
+               }
+             /* Move up the block chain to find parent inlined

functions. */

gcc/cfgexpand.cc +6 -0
+             block = BLOCK_SUPERCONTEXT (block);
+           }
+
+         if (!should_skip_kcfi)
+           {
+             uint32_t kcfi_type_id = (uint32_t) tree_to_uhwi (TREE_VALUE

(attr));

gcc/cfgexpand.cc +2 -0
+
+             /* Find the call that has been created.  */
Quoted 8 lines
Quoted 5 lines
gcc/cfgexpand.cc +2 -0
+             rtx_insn *call_insn = get_last_insn ();
+             while (call_insn && call_insn != before_call && !CALL_P

(call_insn))
+ call_insn = PREV_INSN (call_insn);

This seems very fragile why not do this inside expand_call in calls.cc instead of expand_call_stmt ?

In expand_call, I couldn't find a way to have access to both the GIMPLE (for the typeid) and the just-created RTL to attach the clobbers and typeid. Initially I tried to just insert my own RTL in expand_call, but there are some very complicated things going on in the default expansion, so I needed to just let those run before I could try to tag the actually produced call insn.

After looking through expand_call_stmt, I found the pattern used by nocf_check, which seems to be doing very nearly the same thing KCFI needed, so I repeated it (with great success). :)

I am, of course, happy to try moving it somewhere else!

Quoted 13 lines
Quoted 13 lines
gcc/cfgexpand.cc +2 -0
+
+             if (call_insn && call_insn != before_call && CALL_P

(call_insn))

gcc/cfgexpand.cc +5 -0
+               {
+                 /* Add KCFI type ID note for anti-merging protection.  */
+                 add_kcfi_type_note (call_insn, kcfi_type_id);
+
+                 /* Add architecture-specific clobbers so register

allocator knows

gcc/cfgexpand.cc +4 -0
+                    they'll be used.  */
+                 if (kcfi_target.add_kcfi_clobbers)
+                   kcfi_target.add_kcfi_clobbers (call_insn);
+               }
Quoted 8 lines
Quoted 6 lines
gcc/cfgexpand.cc +3 -0
+             else
+               {
+                 error ("KCFI: Could not find call instruction for

wrapper type");
+ gcc_unreachable ();

internal_error instead of error/gcc_unreachable.

Okay, I will fix these. And I see fatal_error as well; is that just for user fixable issues? (i.e. I probably just need to use internal_error exclusively for these kind of sanity checking pieces.)

Quoted 9 lines
Quoted 9 lines
gcc/cfgexpand.cc +5 -0
+kcfi_emit_trap_with_section (FILE *file, rtx trap_label_rtx)
+{
+  /* Convert trap label to string using standard GCC helper.  */
+  char trap_name[64];
+  ASM_GENERATE_INTERNAL_LABEL (trap_name, "L", CODE_LABEL_NUMBER

(trap_label_rtx));

gcc/cfgexpand.cc +3 -0
+
+  /* Generate entry label name from trap label number.  */
+  char entry_name[64];
Quoted 8 lines

gcc/cfgexpand.cc

Quoted 6 lines

+ ASM_GENERATE_INTERNAL_LABEL (entry_name, "Lentry", CODE_LABEL_NUMBER (trap_label_rtx));

gcc/cfgexpand.cc +3 -0
+
+  /* Emit .kcfi_traps section entry using the converted labels.  */
+  fprintf (file, "\t.pushsection\t.kcfi_traps,\"ao\",@progbits,.text\n");

This is totally wrong. instead look at varasm and use a section.

I've spent some more time looking through here and I *think* I see how it's expected to be done with get_section. The trouble seems to be with SECTION_LINK_ORDER which appears to need explicit special-casing with a strcmp? (There's an exception for __patchable_function_entries already.) It feels very weird. :P

My new change to default_elf_asm_named_section replaces:

         /* For now, only section "__patchable_function_entries"
            adopts flag SECTION_LINK_ORDER, internal label LPFE*
            was emitted in default_print_patchable_function_entry,
            just place it here for linked_to section.  */
         gcc_assert (!strcmp (name, "__patchable_function_entries"));
         fprintf (asm_out_file, ",");
         char buf[256];
         ASM_GENERATE_INTERNAL_LABEL (buf, "LPFE",
                                      current_function_funcdef_no);
         assemble_name_raw (asm_out_file, buf);

with:

         if (!strcmp (name, "__patchable_function_entries"))
           {
             /* For patchable function entries, internal label LPFE*
                was emitted in default_print_patchable_function_entry,
                just place it here for linked_to section.  */
             fprintf (asm_out_file, ",");
             char buf[256];
             ASM_GENERATE_INTERNAL_LABEL (buf, "LPFE",
                                          current_function_funcdef_no);
             assemble_name_raw (asm_out_file, buf);
           }
         else if (!strcmp (name, ".kcfi_traps"))
           {
             /* KCFI traps section links to .text section.  */
             fprintf (asm_out_file, ",.text");
           }
         else
           internal_error ("unexpected use of SECTION_LINK_ORDER by section %qs",
                           name);

These strcmps seem odd. Do __patchable_function_entries and .kcfi_traps need dedicated global sections like done for others (e.g. exception_section)? I really can't tell what the right approach should be here.

Quoted 10 lines

+ assemble_name (file, entry_name);

gcc/cfgexpand.cc

Quoted 7 lines
gcc/cfgexpand.cc +6 -0
+  fprintf (file, ":\n");
+  fprintf (file, "\t.long\t");
+  assemble_name (file, trap_name);
+  fprintf (file, " - ");
+  assemble_name (file, entry_name);
+  fprintf (file, "\n");

There are better ways of generating this subtraction.

I couldn't find an obvious helper for this. I looked for stuff doing subtraction, relative offsets, etc. The closest I could find was dw2_asm_output_delta, but it's quite specialized. Were you thinking that using get_rtx* was the better way on this (like dw2_asm_output_delta does)? I now currently have:

  section *saved_section = in_section;

section *kcfi_traps_section = get_section (".kcfi_traps",

                                             SECTION_LINK_ORDER, NULL);

switch_to_section (kcfi_traps_section);

  ASM_OUTPUT_LABEL (file, entry_name);

  rtx trap_symbol = gen_rtx_SYMBOL_REF (Pmode, trap_name);
  rtx entry_symbol = gen_rtx_SYMBOL_REF (Pmode, entry_name);
  rtx addr_diff = gen_rtx_MINUS (Pmode, trap_symbol, entry_symbol);

/* Emit the address difference as a 4-byte value. */ assemble_integer (addr_diff, 4, BITS_PER_UNIT, 1);

  switch_to_section (saved_section);
Quoted 29 lines
Quoted 20 lines
gcc/cfgexpand.cc +18 -0
+  fprintf (file, "\t.popsection\n");
+}
+
+/* Hash function for KCFI type ID computation.
+   This implements a simple hash similar to FNV-1a.  */
+static uint32_t
+kcfi_hash_string (const char *str)
+{
+  uint32_t hash = 2166136261U; /* FNV-1a 32-bit offset basis.  */
+  for (const char *p = str; *p; p++)
+    {
+      hash ^= (unsigned char) *p;
+      hash *= 16777619U; /* FNV-1a 32-bit prime.  */
+    }
+  return hash;
+}
+
+/* Compute KCFI type ID for a function declaration or function type

(internal) */

gcc/cfgexpand.cc

Quoted 8 lines
gcc/cfgexpand.cc +8 -0
+static uint32_t
+compute_kcfi_type_id (tree fntype_or_fndecl)
+{
+  if (!fntype_or_fndecl)
+    return 0;
+
+  const char *canonical_name = mangle_function_type (fntype_or_fndecl);
+  uint32_t base_type_id = kcfi_hash_string (canonical_name);
Quoted 8 lines

Now I am curious why this needs to be a mangled function name? Since the function in C the symbol is just its name.
Is there documentation that says the hash needs to be based on all of the function arguments types?
Also since you are producing a mangled name just to produce a hash and throwing away the mangled name (except writing it to a dump file which is just human readable), instead if better just to produce the hash from the function type instead of doing it in 2 steps?

I think this has been answered in other replies, but: yes, hash is based on entire function prototype (and not function name). The mangling is there to be human readable (it was an existing ABI so seemed a stable intermediate). But yes, we could just go directly to the hash and build the string only for the dumpfile, if no one wants to reuse this mangler?

Thanks for the review!

-Kees

Signature · 1 line
Kees Cook
#31 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 81 lines · Kees Cook
Quoted 20 lines · Andrew Pinski
Quoted 19 lines · Kees Cook
gcc/kcfi.h new file +5 -0
+struct kcfi_target_hooks {
+  /* Apply architecture-specific masking to type ID.  */
+  uint32_t (*mask_type_id) (uint32_t type_id);
+
+  /* Generate bundled KCFI checked call (atomic check + call to prevent

optimizer separation) */
+ rtx (*gen_kcfi_checked_call) (rtx call_insn, rtx target_reg, uint32_t expected_type, HOST_WIDE_INT prefix_nops);

gcc/kcfi.h new file +5 -0
+
+  /* Add architecture-specific register clobbers for KCFI calls.  */
+  void (*add_kcfi_clobbers) (rtx_insn *call_insn);
+
+  /* Calculate architecture-specific prefix NOPs count (optional, returns

prefix_nops unchanged if NULL) */

gcc/kcfi.h new file +3 -0
+  int (*calculate_prefix_nops) (HOST_WIDE_INT prefix_nops);
+
+  /* Emit architecture-specific type ID instruction (required for common

preamble helper) */
+ void (*emit_type_id_instruction) (FILE *file, uint32_t type_id);

Quoted 8 lines
Quoted 2 lines

+};

This should really be part of target.def so you also have the internals documentation done for these hooks.
And then you could just use targetm.kcfi.xyz below.
And for the hooks you would have TARGET_KCFI_XYZ being defined like the others one.

Ah-ha! Thank you. The macros to build that eluded me. I've updated to this now.

Quoted 7 lines

gcc/kcfi.h line 79

Quoted 5 lines
gcc/kcfi.h new file +4 -0
+/* Pass creation functions.  */
+class gimple_opt_pass;
+class rtl_opt_pass;
+namespace gcc { class context; }

This above is definitely bad form.

Ah yeah, sorry; this was a leftover. (And below.)

Quoted 8 lines
Quoted 6 lines
gcc/kcfi.h new file +4 -0
+
+extern gimple_opt_pass *make_pass_kcfi (gcc::context *ctxt);
+extern gimple_opt_pass *make_pass_kcfi_O0 (gcc::context *ctxt);
+extern rtl_opt_pass *make_pass_kcfi_final_instrumentation (gcc::context

*ctxt);

these 3 lines should just be in tree-pass.h with the other make_pass_*.

Yup, totally. I've moved these now.

Quoted 18 lines
Quoted 18 lines
gcc/cfgexpand.cc +1 -0
index 8950294abb60..432ccc7f864a 100644
@@ -76,6 +76,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "opts.h"
 #include "gimple-range.h"
 #include "rtl-iter.h"
+#include "kcfi.h"
 
 /* Some systems use __main in a way incompatible with its use in gcc, in

these
cases use the macros NAME__MAIN to give a quoted symbol and
SYMBOL__MAIN to

gcc/cfgexpand.cc +0 -0
@@ -3203,6 +3204,66 @@ expand_call_stmt (gcall *stmt)
   else
     expand_expr (exp, const0_rtx, VOIDmode, EXPAND_NORMAL);
 
Quoted 7 lines
Quoted 4 lines
gcc/cfgexpand.cc +1 -0
+  /* Add KCFI annotations if this is an indirect call with KCFI wrapper

type. */
+ if (sanitize_flags_p (SANITIZE_KCFI) && !gimple_call_fndecl (stmt))

Internal function calls with also have a null fndecl can you double check that you don't have an internal function call here?

Quoted 7 lines

I think I need this explained in more detail. This logic mostly matches the nocf_check below:

if (gimple_call_nocf_check_p (stmt)

      && !gimple_call_fndecl (stmt))

Or do you mean the fn_type below?

So nocf check is on the GIMPLE_CALL first unlike your code. The nocf is set only from the original function type so it will NOT be on calls to internal function. You just need to check gimple_call_internal_p first.
But then I missed that expand_call_stmt does a check for call internal very first. So just add a comment/assert that you will not have an internal call here.

Thanks,
Andrew

Quoted 250 lines
Quoted 5 lines

gcc/cfgexpand.cc expand_call_stmt (gcall *stmt) · line 3211

Quoted 5 lines
gcc/cfgexpand.cc +3 -0
+    {
+      tree fn_type = gimple_call_fntype (stmt);
+      gcc_assert (fn_type);

... here? I haven't encountered this assert, if that's a useful signal. :)

Quoted 10 lines
Quoted 9 lines

+ tree attr = lookup_attribute ("kcfi_type_id", TYPE_ATTRIBUTES
(fn_type));

gcc/cfgexpand.cc +3 -0
+      if (attr && TREE_VALUE (attr))
+       {
+         /* Check if this call site originated from a no_sanitize("kcfi")

function
+ during inlining. If so, skip KCFI instrumentation in RTL
phase too. */

Quoted 3 lines

Why not add a bit to gimple_call and add while inlining instead of looking it up afterwards?
I am not 100% sure the BLOCK will always be correct.

Ah, I think I see how: add a new GF_CALL_* flag? I'll go find where inlining happens...

Quoted 30 lines
Quoted 30 lines
gcc/cfgexpand.cc +11 -0
+         bool should_skip_kcfi = false;
+         location_t call_location = gimple_location (stmt);
+         gcc_assert (call_location != UNKNOWN_LOCATION);
+
+         tree block = gimple_block (stmt);
+         while (block && TREE_CODE (block) == BLOCK)
+           {
+             tree fn_decl = BLOCK_ABSTRACT_ORIGIN (block);
+             if (fn_decl && TREE_CODE (fn_decl) == FUNCTION_DECL)
+               {
+                 /* Found an inlined function - check if it has

no_sanitize("kcfi"). */

gcc/cfgexpand.cc +8 -0
+                 if (!sanitize_flags_p (SANITIZE_KCFI, fn_decl))
+                   {
+                     should_skip_kcfi = true;
+                     break;
+                   }
+                 break;
+               }
+             /* Move up the block chain to find parent inlined

functions. */

gcc/cfgexpand.cc +6 -0
+             block = BLOCK_SUPERCONTEXT (block);
+           }
+
+         if (!should_skip_kcfi)
+           {
+             uint32_t kcfi_type_id = (uint32_t) tree_to_uhwi (TREE_VALUE

(attr));

gcc/cfgexpand.cc +2 -0
+
+             /* Find the call that has been created.  */
Quoted 8 lines
Quoted 5 lines
gcc/cfgexpand.cc +2 -0
+             rtx_insn *call_insn = get_last_insn ();
+             while (call_insn && call_insn != before_call && !CALL_P

(call_insn))
+ call_insn = PREV_INSN (call_insn);

This seems very fragile why not do this inside expand_call in calls.cc instead of expand_call_stmt ?

In expand_call, I couldn't find a way to have access to both the GIMPLE (for the typeid) and the just-created RTL to attach the clobbers and typeid. Initially I tried to just insert my own RTL in expand_call, but there are some very complicated things going on in the default expansion, so I needed to just let those run before I could try to tag the actually produced call insn.

After looking through expand_call_stmt, I found the pattern used by nocf_check, which seems to be doing very nearly the same thing KCFI needed, so I repeated it (with great success). :)

I am, of course, happy to try moving it somewhere else!

Quoted 13 lines
Quoted 13 lines
gcc/cfgexpand.cc +2 -0
+
+             if (call_insn && call_insn != before_call && CALL_P

(call_insn))

gcc/cfgexpand.cc +5 -0
+               {
+                 /* Add KCFI type ID note for anti-merging protection.  */
+                 add_kcfi_type_note (call_insn, kcfi_type_id);
+
+                 /* Add architecture-specific clobbers so register

allocator knows

gcc/cfgexpand.cc +4 -0
+                    they'll be used.  */
+                 if (kcfi_target.add_kcfi_clobbers)
+                   kcfi_target.add_kcfi_clobbers (call_insn);
+               }
Quoted 8 lines
Quoted 6 lines
gcc/cfgexpand.cc +3 -0
+             else
+               {
+                 error ("KCFI: Could not find call instruction for

wrapper type");
+ gcc_unreachable ();

internal_error instead of error/gcc_unreachable.

Okay, I will fix these. And I see fatal_error as well; is that just for user fixable issues? (i.e. I probably just need to use internal_error exclusively for these kind of sanity checking pieces.)

Quoted 9 lines
Quoted 9 lines
gcc/cfgexpand.cc +5 -0
+kcfi_emit_trap_with_section (FILE *file, rtx trap_label_rtx)
+{
+  /* Convert trap label to string using standard GCC helper.  */
+  char trap_name[64];
+  ASM_GENERATE_INTERNAL_LABEL (trap_name, "L", CODE_LABEL_NUMBER

(trap_label_rtx));

gcc/cfgexpand.cc +3 -0
+
+  /* Generate entry label name from trap label number.  */
+  char entry_name[64];
Quoted 8 lines

gcc/cfgexpand.cc

Quoted 6 lines

+ ASM_GENERATE_INTERNAL_LABEL (entry_name, "Lentry", CODE_LABEL_NUMBER (trap_label_rtx));

gcc/cfgexpand.cc +3 -0
+
+  /* Emit .kcfi_traps section entry using the converted labels.  */
+  fprintf (file, "\t.pushsection\t.kcfi_traps,\"ao\",@progbits,.text\n");

This is totally wrong. instead look at varasm and use a section.

I've spent some more time looking through here and I *think* I see how it's expected to be done with get_section. The trouble seems to be with SECTION_LINK_ORDER which appears to need explicit special-casing with a strcmp? (There's an exception for __patchable_function_entries already.) It feels very weird. :P

My new change to default_elf_asm_named_section replaces:

         /* For now, only section "__patchable_function_entries"
            adopts flag SECTION_LINK_ORDER, internal label LPFE*
            was emitted in default_print_patchable_function_entry,
            just place it here for linked_to section.  */
         gcc_assert (!strcmp (name, "__patchable_function_entries"));
         fprintf (asm_out_file, ",");
         char buf[256];
         ASM_GENERATE_INTERNAL_LABEL (buf, "LPFE",
                                      current_function_funcdef_no);
         assemble_name_raw (asm_out_file, buf);

with:

         if (!strcmp (name, "__patchable_function_entries"))
           {
             /* For patchable function entries, internal label LPFE*
                was emitted in default_print_patchable_function_entry,
                just place it here for linked_to section.  */
             fprintf (asm_out_file, ",");
             char buf[256];
             ASM_GENERATE_INTERNAL_LABEL (buf, "LPFE",
                                          current_function_funcdef_no);
             assemble_name_raw (asm_out_file, buf);
           }
         else if (!strcmp (name, ".kcfi_traps"))
           {
             /* KCFI traps section links to .text section.  */
             fprintf (asm_out_file, ",.text");
           }
         else
           internal_error ("unexpected use of SECTION_LINK_ORDER by section %qs",
                           name);

These strcmps seem odd. Do __patchable_function_entries and .kcfi_traps need dedicated global sections like done for others (e.g. exception_section)? I really can't tell what the right approach should be here.

Quoted 10 lines

+ assemble_name (file, entry_name);

gcc/cfgexpand.cc

Quoted 7 lines
gcc/cfgexpand.cc +6 -0
+  fprintf (file, ":\n");
+  fprintf (file, "\t.long\t");
+  assemble_name (file, trap_name);
+  fprintf (file, " - ");
+  assemble_name (file, entry_name);
+  fprintf (file, "\n");

There are better ways of generating this subtraction.

I couldn't find an obvious helper for this. I looked for stuff doing subtraction, relative offsets, etc. The closest I could find was dw2_asm_output_delta, but it's quite specialized. Were you thinking that using get_rtx* was the better way on this (like dw2_asm_output_delta does)? I now currently have:

  section *saved_section = in_section;

section *kcfi_traps_section = get_section (".kcfi_traps",

                                             SECTION_LINK_ORDER, NULL);

switch_to_section (kcfi_traps_section);

  ASM_OUTPUT_LABEL (file, entry_name);

  rtx trap_symbol = gen_rtx_SYMBOL_REF (Pmode, trap_name);
  rtx entry_symbol = gen_rtx_SYMBOL_REF (Pmode, entry_name);
  rtx addr_diff = gen_rtx_MINUS (Pmode, trap_symbol, entry_symbol);

/* Emit the address difference as a 4-byte value. */ assemble_integer (addr_diff, 4, BITS_PER_UNIT, 1);

  switch_to_section (saved_section);
Quoted 29 lines
Quoted 20 lines
gcc/cfgexpand.cc +18 -0
+  fprintf (file, "\t.popsection\n");
+}
+
+/* Hash function for KCFI type ID computation.
+   This implements a simple hash similar to FNV-1a.  */
+static uint32_t
+kcfi_hash_string (const char *str)
+{
+  uint32_t hash = 2166136261U; /* FNV-1a 32-bit offset basis.  */
+  for (const char *p = str; *p; p++)
+    {
+      hash ^= (unsigned char) *p;
+      hash *= 16777619U; /* FNV-1a 32-bit prime.  */
+    }
+  return hash;
+}
+
+/* Compute KCFI type ID for a function declaration or function type

(internal) */

gcc/cfgexpand.cc

Quoted 8 lines
gcc/cfgexpand.cc +8 -0
+static uint32_t
+compute_kcfi_type_id (tree fntype_or_fndecl)
+{
+  if (!fntype_or_fndecl)
+    return 0;
+
+  const char *canonical_name = mangle_function_type (fntype_or_fndecl);
+  uint32_t base_type_id = kcfi_hash_string (canonical_name);
Quoted 8 lines

Now I am curious why this needs to be a mangled function name? Since the function in C the symbol is just its name.
Is there documentation that says the hash needs to be based on all of the function arguments types?
Also since you are producing a mangled name just to produce a hash and throwing away the mangled name (except writing it to a dump file which is just human readable), instead if better just to produce the hash from the function type instead of doing it in 2 steps?

I think this has been answered in other replies, but: yes, hash is based on entire function prototype (and not function name). The mangling is there to be human readable (it was an existing ABI so seemed a stable intermediate). But yes, we could just go directly to the hash and build the string only for the dumpfile, if no one wants to reuse this mangler?

Thanks for the review!

-Kees

--
Kees Cook

#32 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

In reply to Kees Cook

Hi, Kees,

I have several suggestions and questions first for this patch:

1. Is -fsanitize=kcfi a C only feature? If so, you might need to mention this in the documentation and also reject its usage in other languages.
2. There is no overall description of the design of this kcfi implementation
in the source code, I think it might be very helpful to provide such description In the new module kcfi.cc <http://kcfi.cc/>. such documentation will be helpful for current review and future maintenance of this feature.

Quoted 139 lines · Kees Cook

This series 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.

Just to set expectations, this is an RFC because this is my first time working on most of the affected areas in GCC, and it is likely I have missed really obvious stuff, or gone about doing things in very wrong ways. I tried to find the best way to do stuff, but I was left with many questions. :) All that said, this works for x86_64 and aarch64 Linux kernels. (I have implemented riscv64 as well, but I lack a viable test environment -- I am working on this still.)

KCFI has a number of specific constraints. Some are tied to the backend architecture, which I'll cover in more detail in later patches. The constraints are:

- The KCFI scheme generates a unique 32-bit hash for each unique function prototype, allowing for indirect call sites to verify that they are calling into a matching _type_ of function pointer. This changes the semantics of some optimization logic because now indirect calls to different types cannot be merged. For example:

   if (p->func_type_1)
return p->func_type_1();
   if (p->func_type_2)

return p->func_type_2();

In final asm, the optimizer may collapse the second indirect call into a jump to the first indirect call once it has loaded the function pointer. KCFI must block cross-type merging otherwise there will be a single KCFI check happening for only 1 type but being used by 2 target types. The distinguishing characteristic for call merging becomes the type, not the address/register usage.

- The check-call instruction sequence must be treated a single unit: it cannot be rearranged or split or optimized. The pattern is that indirect calls, "call *$target", get converted into:

mov $target_expression, %target (only present if the expression was
not already %target)
load -$offset(%target), %tmp
cmp $hash, %tmp
je .Lcheck_passed
.Ltrap$N:
trap
.Lcheck_passed$N:
call *%target

This pattern of call immediately after trap provides for the "permissive" checking mode automatically: the trap gets handled, a warning emitted, and then execution continues after the trap to the call.

(x86_64 uses "mov -$hash, %tmp; addl -$offset(%target), %tmp; je" to zero out the register before making the call. Also Linux needs exactly these insns because it is both disassembling them during trap handling and potentially live patching them at boot time to be converted into a different series of instrutions, a scheme know as FineIBT, making the insn sequence ABI.)

- KCFI check-call instrumentation must survive tail call optimization. If an indirect call is turned into an indirect jump, KCFI checking must still happen (but will still use the jmp).

- Functions that may be called indirectly have a preamble added, __cfi_$original_func_name, that contains the $hash value:

__cfi_target_func:
.word $hash
target_func:
[regular function entry...]

(x86_64 uses a movl instruction to hold the hash and prefixed aligned NOPs to maintain cache line alignment in the face of patchable function entry...)

- The preamble needs to interact with patchable function entry so that the hash appears further away from the actual start of the function (leaving the prefix NOPs of the patchable function entry unchanged). This means only _globally defined_ patchable function entry is supported with KCFI (indrect call sites must know in advance what the offset is, which may not be possible extern functions). For example, a "4,4" patchable function entry would end up like:

__cfi_target_func:
.data $hash
nop nop nop nop
target_func:
[regular function entry...]

(Linux x86_64 uses an 11 byte prefix nop area resulting in 16 bytes total including the movl. This region may be live patched at boot time for FineIBT so the behavior here is also ABI.)

- External functions that are address-taken have a weak __kcfi_typeid_$funcname symbol added with the hash value available so that the hash can be referenced from assembly linkages, etc, where the hash values cannot be calculated (i.e where C type information is missing):

.weak __kcfi_typeid_$func
.set __kcfi_typeid_$func, $hash

- On architectures that do not have a good way to encode additional details in their trap (x86_64 and riscv64), the trap location is identified as a KCFI trap via a relative address offset entry emitted into the .kcfi_traps section for each indirect call site's trap instruction. The previous check-call example's insn sequence has a section push/pop inserted between the trap and call:

...
.Ltrap$N:
trap
.pushsection .kcfi_traps,"ao",@progbits,.text
.Lentry$N:
.long .Ltrap$N - .Lentry$N
.popsection
.Lcheck_passed$N:
call %target

(aarch64 encodes the register numbers that hold the expected hash and the target address in the trap ESR and thereby does not need a .kcfi_traps section at all.)

- The no_sanitize("kcfi") function attribute means that the marked function must not produce KCFI checking for indirect calls, and that this attribute must survive inlining. This is used rarely by Linux, but is required to make BPF JIT trampolines work on older Linux kernel versions. (The preamble code is very recently finally being generated at JIT time on the last remaining Linux KCFI arch where this was
missing: aarch64.)

As a result of these constraints, there are some behavioral aspects that need to be preserved across the middle-end and back-end, as I understand them.

Quoted 7 lines

For indirect call sites:

- Keeping indirect calls from being merged (see above). I did this by adding a wrapping type so that equality was tested based on type-id. This is done in create_kcfi_wrapper_type(), via kcfi_instrument(), via an early GIMPLE pass (pass_kcfi and pass_kcfi0). The wrapper type is checked in gcc/cfgcleanup.cc, old_insns_match_p().

First, Looks like that the routine “old_insns_match_p” checks the type-ids that were embedded in the REG_NOTE ( REG_CALL_KCFI_TYPE) of the RTL. -:)

My understanding is: the computed type-id is recorded into to a “kcfi_type_id” attribute, and then this “kcfi_type_id” attribute is attached to the original function type. At the same time, A wrapper type is created for the original function type, whose typename is “__kcfi_wrapper_type_id”.

I am confused:

1. Why the additional wrapper type is needed? why the original function type + “kcfi_type_id” not enough?
2. Why attaching the type-id as a “kcfi_type_id” attribute to the original function type?
Is there other way to attach the type-id to the original function type? Or to the original indirect call site?

Is it possible that we might provide a user level “kcfi_type_id” attribute to function type in the future? then That will be conflict with the current “kcfi_type_id” attribute?

Quoted 4 lines

- Keeping typeid information available through to the RTL expansion phase was done via a typeid note (REG_CALL_KCFI_TYPE) attached also in create_kcfi_wrapper_type() in the same GIMPLE pass.

This is done in the routine “expand_call_stmt” through call to “add_kcfi_type_note”. The “type_id” is attached as a “kcfi_type_id” attribute to the original function type in the routine “create_kcfi_wrapper_type”.

Please see my above question 2.

Quoted 3 lines

- REG_CALL_KCFI_TYPE notes needed to survive optimization passes so RTL expansion could find them again. These are retained in gcc/emit-rtl.cc, try_split(), and gcc/combine.cc, distribute_notes().

Okay.

Quoted 8 lines

- The expansion to RTL is handled in gcc/cfgexpand.cc, expand_call_stmt(). This lets the call expansion logic run, but then marks the resulting call RTL with REG_CALL_KCFI_TYPE so the last RTL instrumentation pass can find it. To me, this logic feels the most weird. It seems like there should be a better place to do this, but I do see that similar behavioral needs are also here, like nocf_check, so perhaps it's not far off.

I think this should be okay.

Quoted 17 lines

- The same expand_call_stmt() logic also adds the clobbers that will be present in the final KCFI check-call insn sequences, which need to be added now so that register allocation is aware of them while working through optimization passes. Without this, the clobbered registers may get used in the RTL before we have replaced the call instructions that actually have the clobbers associated with them. This is the "have cake and eat it too" case where we have to do the check-call RTL replacement very late, but need to make sure the clobbers are known very early. Again, this seems like there should be a better way...

- To emit the exact KCFI check-call instruction sequences, a very late RTL pass is used (pass_kcfi_final_instrumentation). In order to handle sibling calls (tail calls), this pass chooses between either a check-call insn sequence or a check-jump insn sequence (provided by the per-arch back-end).

Quoted 4 lines

- To make sure instrumentation was skipped for inline functions, the RTL pass walks the basic blocks to identify their function origins, looking for the no_sanitize("kcfi") attribute, and skipping instrumentation if found.

I think this was done inefficiently. It’s better to do this during inlining transformation to propagate the no_sanitize information from the caller to the callee body and attach the no_sanitize information to the indirect callsite.

Quoted 7 lines

For indirect call targets:

- kcfi_emit_preamble_if_needed() uses function_needs_kcfi_preamble(), and counter helpers, to emit the preablem, with patchable function entry NOPs. This gets used both in default_print_patchable_function_entry() and the per-arch path.

I saw that “kcfi_emit_preamble_if_needed” is called by “default_print_patchable_function_entry”, But I didn’t see where it is called when the function is not patchable?

Quoted 13 lines

I could not find a simpler way to deal with
patchable function entry besides splitting it up like this. I feel like there should be a better way.

- gcc/varasm.cc, assemble_external_real() calls emit_kcfi_typeid_symbol() to add the __kcfi_typeid symbols (see get_function_kcfi_type_id() below).

To support the per-arch back-ends, there are some common helpers:

- A callback framework is added via struct kcfi_target_hooks for backends to fill out.

Quoted 8 lines

- kcfi_emit_trap_with_section() handles the push/pop section and generating the relative offset section entries.

- get_function_kcfi_type_id() generates the 32-bit hash value, using compute_kcfi_type_id() and kcfi_hash_string() to hook to the mangling API. The hash is FNV-1a right now: it doesn't need secrecy. It could be replaced with any hash, though the hash will need to be coordinated with Rust, which implements the KCFI ABI as well.

One question here, the final type_id will be computed by the following 2 steps:

1. Itanium C++ mangling based on return type + parameter types of the function.
2. FNV-1a hash on the mangled string

If the hacker knows these, it should be quite easy for them to come up with a matched typeid, is it?

Thanks.

Qing

Quoted 1,360 lines

---

gcc/Makefile.in     |   1 +
gcc/flag-types.h    |   2 +
gcc/kcfi.h          |  85 +++++
gcc/tree-pass.h     |   1 +
gcc/cfgcleanup.cc   |  20 ++
gcc/cfgexpand.cc    |  61 ++++
gcc/combine.cc      |   1 +
gcc/doc/invoke.texi |  29 ++
gcc/emit-rtl.cc     |   1 +
gcc/kcfi.cc         | 783 ++++++++++++++++++++++++++++++++++++++++++++
gcc/opts.cc         |   1 +
gcc/passes.cc       |   1 +
gcc/passes.def      |   3 +
gcc/recog.cc        |   1 +
gcc/reg-notes.def   |   6 +
gcc/targhooks.cc    |  50 ++-
gcc/toplev.cc       |   8 +
gcc/varasm.cc       |  18 +
18 files changed, 1071 insertions(+), 1 deletion(-)

create mode 100644 gcc/kcfi.h
create mode 100644 gcc/kcfi.cc

gcc/Makefile.in +1 -0
index 86f62611c1d4..01cccd88fde0 100644
@@ -1593,6 +1593,7 @@ OBJS = \
 ira-emit.o \
 ira-lives.o \
 jump.o \
+ kcfi.o \
 langhooks.o \
 late-combine.o \
 lcm.o \
gcc/flag-types.h +2 -0
index 33c88a15ecbb..7ed6dab1bd4b 100644
@@ -337,6 +337,8 @@ enum sanitize_code {
  SANITIZE_KERNEL_HWADDRESS = 1ULL << 30,
  /* Shadow Call Stack.  */
  SANITIZE_SHADOW_CALL_STACK = 1ULL << 31,
+  /* KCFI (Kernel Control Flow Integrity) */
+  SANITIZE_KCFI = 1ULL << 32,
  SANITIZE_SHIFT = SANITIZE_SHIFT_BASE | SANITIZE_SHIFT_EXPONENT,
  SANITIZE_UNDEFINED = SANITIZE_SHIFT | SANITIZE_DIVIDE | SANITIZE_UNREACHABLE
      | SANITIZE_VLA | SANITIZE_NULL | SANITIZE_RETURN
gcc/kcfi.h new file +85 -0
new file mode 100644
index 000000000000..23d679b73ba4
@@ -0,0 +1,85 @@
+/* Kernel Control Flow Integrity (KCFI) support for GCC.
+   Copyright (C) 2025 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 "config.h"
+#include "system.h"
+#include "coretypes.h"
+#include "rtl.h"
+
+/* Get KCFI type ID for a function declaration.  */
+extern uint32_t get_function_kcfi_type_id (tree fndecl);
+
+/* KCFI target hooks for architecture-specific functionality.  */
+
+struct kcfi_target_hooks {
+  /* Apply architecture-specific masking to type ID.  */
+  uint32_t (*mask_type_id) (uint32_t type_id);
+
+  /* Generate bundled KCFI checked call (atomic check + call to prevent optimizer separation) */
+  rtx (*gen_kcfi_checked_call) (rtx call_insn, rtx target_reg, uint32_t expected_type, HOST_WIDE_INT prefix_nops);
+
+  /* Add architecture-specific register clobbers for KCFI calls.  */
+  void (*add_kcfi_clobbers) (rtx_insn *call_insn);
+
+  /* Calculate architecture-specific prefix NOPs count (optional, returns prefix_nops unchanged if NULL) */
+  int (*calculate_prefix_nops) (HOST_WIDE_INT prefix_nops);
+
+  /* Emit architecture-specific type ID instruction (required for common preamble helper) */
+  void (*emit_type_id_instruction) (FILE *file, uint32_t type_id);
+};
+
+/* Global KCFI target hooks.  */
+extern struct kcfi_target_hooks kcfi_target;
+
+/* Common helper for RTL patterns to emit .kcfi_traps section entry.
+   Call AFTER emitting trap label and instruction with the RTX label operand.  */
+extern void kcfi_emit_trap_with_section (FILE *file, rtx trap_label_rtx);
+
+/* RTL note management for KCFI.  */
+
+/* Add KCFI type ID note to call instruction.  */
+extern void add_kcfi_type_note (rtx_insn *call_insn, uint32_t type_id);
+
+/* Emit KCFI type ID symbol for address-taken functions.  */
+extern void emit_kcfi_typeid_symbol (FILE *asm_file, tree decl, const char *name);
+
+/* KCFI preamble emission coordination.  */
+
+/* Mark that KCFI preamble has been emitted to prevent duplication.  */
+extern void mark_kcfi_preamble_emitted (void);
+
+/* Central manager for all KCFI preamble generation decisions.  */
+extern void kcfi_emit_preamble_if_needed (FILE *file, tree decl,
+  bool is_patchable_context,
+  HOST_WIDE_INT prefix_nops,
+  const char *actual_fname);
+
+/* Pass creation functions.  */
+class gimple_opt_pass;
+class rtl_opt_pass;
+namespace gcc { class context; }
+
+extern gimple_opt_pass *make_pass_kcfi (gcc::context *ctxt);
+extern gimple_opt_pass *make_pass_kcfi_O0 (gcc::context *ctxt);
+extern rtl_opt_pass *make_pass_kcfi_final_instrumentation (gcc::context *ctxt);
+
+#endif /* GCC_KCFI_H */
gcc/tree-pass.h +1 -0
index 1c68a69350df..2affea230213 100644
@@ -561,6 +561,7 @@ extern gimple_opt_pass *make_pass_fixup_cfg (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_backprop (gcc::context *ctxt);
 
 extern rtl_opt_pass *make_pass_expand (gcc::context *ctxt);
+extern rtl_opt_pass *make_pass_kcfi_final_instrumentation (gcc::context *ctxt);
 extern rtl_opt_pass *make_pass_instantiate_virtual_regs (gcc::context *ctxt);
 extern rtl_opt_pass *make_pass_rtl_fwprop (gcc::context *ctxt);
 extern rtl_opt_pass *make_pass_rtl_fwprop_addr (gcc::context *ctxt);
gcc/cfgcleanup.cc +20 -0
index d28d23231911..9707b7e22222 100644
@@ -1238,6 +1238,26 @@ old_insns_match_p (int mode ATTRIBUTE_UNUSED, rtx_insn *i1, rtx_insn *i2)
  if (RTX_FRAME_RELATED_P (i1) && !insns_have_identical_cfa_notes (i1, i2))
    return dir_none;
 
+  /* KCFI (Kernel Control Flow Integrity): Do not cross-jump between different
+     KCFI check patterns.  Each bundled KCFI call has a unique type ID that must
+     be preserved to prevent type confusion attacks.  */
+  if (CALL_P (i1) && CALL_P (i2))
+    {
+      rtx kcfi_note1 = find_reg_note (i1, REG_CALL_KCFI_TYPE, NULL_RTX);
+      rtx kcfi_note2 = find_reg_note (i2, REG_CALL_KCFI_TYPE, NULL_RTX);
+
+      if (kcfi_note1 || kcfi_note2)
+ {
+  /* If only one has KCFI note, they're different.  */
+  if (!kcfi_note1 || !kcfi_note2)
+    return dir_none;
+
+  /* If both have KCFI notes, compare the type IDs.  */
+  if (!rtx_equal_p (XEXP (kcfi_note1, 0), XEXP (kcfi_note2, 0)))
+    return dir_none;
+ }
+    }
+
 #ifdef STACK_REGS
  /* If cross_jump_death_matters is not 0, the insn's mode
     indicates whether or not the insn contains any stack-like
gcc/cfgexpand.cc +61 -0
index 8950294abb60..432ccc7f864a 100644
@@ -76,6 +76,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "opts.h"
 #include "gimple-range.h"
 #include "rtl-iter.h"
+#include "kcfi.h"
 
 /* Some systems use __main in a way incompatible with its use in gcc, in these
   cases use the macros NAME__MAIN to give a quoted symbol and SYMBOL__MAIN to
@@ -3203,6 +3204,66 @@ expand_call_stmt (gcall *stmt)
  else
    expand_expr (exp, const0_rtx, VOIDmode, EXPAND_NORMAL);
 
+  /* Add KCFI annotations if this is an indirect call with KCFI wrapper type.  */
+  if (sanitize_flags_p (SANITIZE_KCFI) && !gimple_call_fndecl (stmt))
+    {
+      tree fn_type = gimple_call_fntype (stmt);
+      gcc_assert (fn_type);
+      tree attr = lookup_attribute ("kcfi_type_id", TYPE_ATTRIBUTES (fn_type));
+      if (attr && TREE_VALUE (attr))
+ {
+  /* Check if this call site originated from a no_sanitize("kcfi") function
+     during inlining. If so, skip KCFI instrumentation in RTL phase too.  */
+  bool should_skip_kcfi = false;
+  location_t call_location = gimple_location (stmt);
+  gcc_assert (call_location != UNKNOWN_LOCATION);
+
+  tree block = gimple_block (stmt);
+  while (block && TREE_CODE (block) == BLOCK)
+    {
+      tree fn_decl = BLOCK_ABSTRACT_ORIGIN (block);
+      if (fn_decl && TREE_CODE (fn_decl) == FUNCTION_DECL)
+ {
+  /* Found an inlined function - check if it has no_sanitize("kcfi").  */
+  if (!sanitize_flags_p (SANITIZE_KCFI, fn_decl))
+    {
+      should_skip_kcfi = true;
+      break;
+    }
+  break;
+ }
+      /* Move up the block chain to find parent inlined functions.  */
+      block = BLOCK_SUPERCONTEXT (block);
+    }
+
+  if (!should_skip_kcfi)
+    {
+      uint32_t kcfi_type_id = (uint32_t) tree_to_uhwi (TREE_VALUE (attr));
+
+      /* Find the call that has been created.  */
+      rtx_insn *call_insn = get_last_insn ();
+      while (call_insn && call_insn != before_call && !CALL_P (call_insn))
+ call_insn = PREV_INSN (call_insn);
+
+      if (call_insn && call_insn != before_call && CALL_P (call_insn))
+ {
+  /* Add KCFI type ID note for anti-merging protection.  */
+  add_kcfi_type_note (call_insn, kcfi_type_id);
+
+  /* Add architecture-specific clobbers so register allocator knows
+     they'll be used.  */
+  if (kcfi_target.add_kcfi_clobbers)
+    kcfi_target.add_kcfi_clobbers (call_insn);
+ }
+      else
+ {
+  error ("KCFI: Could not find call instruction for wrapper type");
+  gcc_unreachable ();
+ }
+    }
+ }
+    }
+
  /* If the gimple call is an indirect call and has 'nocf_check'
     attribute find a generated CALL insn to mark it as no
     control-flow verification is needed.  */
gcc/combine.cc +0 -0
index 4dbc1f6a4a4e..efaeb426d254 100644
@@ -14525,6 +14525,7 @@ distribute_notes (rtx notes, rtx_insn *from_insn, rtx_insn *i3, rtx_insn *i2,

case REG_CALL_DECL:
case REG_UNTYPED_CALL:
case REG_CALL_NOCF_CHECK:
+ case REG_CALL_KCFI_TYPE:
/* These notes must remain with the call. It should not be
possible for both I2 and I3 to be a call. */
if (CALL_P (i3))

gcc/doc/invoke.texi +0 -0
index c1e708beacf3..c66f47336826 100644
@@ -18294,6 +18294,35 @@ possible by specifying the command-line options

@option{--param hwasan-instrument-allocas=1} respectively. Using a random frame tag is not implemented for kernel instrumentation.

+@opindex fsanitize=kcfi
+@item -fsanitize=kcfi

gcc/doc/invoke.texi +27 -0
+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, terminating the program 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. Only
+functions that have referenced by their address receive the KCFI preamble
+instrumentation.
+
+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.
+
+Use @option{-fdump-tree-kcfi} to examine the computed type identifiers
+and their corresponding mangled type strings during compilation.
+

@opindex fsanitize=pointer-compare
@item -fsanitize=pointer-compare
Instrument comparison operation (<, <=, >, >=) with pointer operands.

gcc/emit-rtl.cc +0 -0
index f4fc92bb37a1..aa56112bc250 100644
@@ -4056,6 +4056,7 @@ try_split (rtx pat, rtx_insn *trial, int last)

case REG_SETJMP:
case REG_TM:
case REG_CALL_NOCF_CHECK:
+ case REG_CALL_KCFI_TYPE:
case REG_CALL_ARG_LOCATION:
for (insn = insn_last; insn != NULL_RTX; insn = PREV_INSN (insn))
{

gcc/kcfi.cc new file +783 -0
new file mode 100644
index 000000000000..522bb97bf503
@@ -0,0 +1,783 @@
+/* Kernel Control Flow Integrity (KCFI) support for GCC.
+   Copyright (C) 2025 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/>.  */
+
+#include "config.h"
+#include "system.h"
+#include "coretypes.h"
+#include "target.h"
+#include "function.h"
+#include "tree.h"
+#include "tree-pass.h"
+#include "dumpfile.h"
+#include "basic-block.h"
+#include "gimple.h"
+#include "gimple-iterator.h"
+#include "cgraph.h"
+#include "kcfi.h"
+#include "stringpool.h"
+#include "attribs.h"
+#include "rtl.h"
+#include "cfg.h"
+#include "asan.h"
+#include "diagnostic-core.h"
+#include "memmodel.h"
+#include "emit-rtl.h"
+#include "output.h"
+#include "varasm.h"
+#include "opts.h"
+#include "mangle.h"
+
+/* Global KCFI target hooks structure - zero-initialized for safe defaults.  */
+struct kcfi_target_hooks kcfi_target = { };
+
+/* Common KCFI utilities.  */
+
+/* Common helper for RTL patterns to emit .kcfi_traps section entry.  */
+void
+kcfi_emit_trap_with_section (FILE *file, rtx trap_label_rtx)
+{
+  /* Convert trap label to string using standard GCC helper.  */
+  char trap_name[64];
+  ASM_GENERATE_INTERNAL_LABEL (trap_name, "L", CODE_LABEL_NUMBER (trap_label_rtx));
+
+  /* Generate entry label name from trap label number.  */
+  char entry_name[64];
+  ASM_GENERATE_INTERNAL_LABEL (entry_name, "Lentry", CODE_LABEL_NUMBER (trap_label_rtx));
+
+  /* Emit .kcfi_traps section entry using the converted labels.  */
+  fprintf (file, "\t.pushsection\t.kcfi_traps,\"ao\",@progbits,.text\n");
+  assemble_name (file, entry_name);
+  fprintf (file, ":\n");
+  fprintf (file, "\t.long\t");
+  assemble_name (file, trap_name);
+  fprintf (file, " - ");
+  assemble_name (file, entry_name);
+  fprintf (file, "\n");
+  fprintf (file, "\t.popsection\n");
+}
+
+/* Hash function for KCFI type ID computation.
+   This implements a simple hash similar to FNV-1a.  */
+static uint32_t
+kcfi_hash_string (const char *str)
+{
+  uint32_t hash = 2166136261U; /* FNV-1a 32-bit offset basis.  */
+  for (const char *p = str; *p; p++)
+    {
+      hash ^= (unsigned char) *p;
+      hash *= 16777619U; /* FNV-1a 32-bit prime.  */
+    }
+  return hash;
+}
+
+/* Compute KCFI type ID for a function declaration or function type (internal) */
+static uint32_t
+compute_kcfi_type_id (tree fntype_or_fndecl)
+{
+  if (!fntype_or_fndecl)
+    return 0;
+
+  const char *canonical_name = mangle_function_type (fntype_or_fndecl);
+  uint32_t base_type_id = kcfi_hash_string (canonical_name);
+
+  /* Apply target-specific masking if supported.  */
+  if (kcfi_target.mask_type_id)
+    base_type_id = kcfi_target.mask_type_id (base_type_id);
+
+  /* Output to dump file if enabled */
+  if (dump_file && (dump_flags & TDF_DETAILS))
+    {
+      const char *name = NULL;
+      if (TREE_CODE (fntype_or_fndecl) == FUNCTION_DECL)
+        {
+          if (DECL_NAME (fntype_or_fndecl))
+            name = IDENTIFIER_POINTER (DECL_NAME (fntype_or_fndecl));
+        }
+
+      if (name)
+        fprintf (dump_file, "KCFI type ID for function '%s': mangled='%s' typeid=0x%08x\n",
+                 name, canonical_name, base_type_id);
+      else
+        fprintf (dump_file, "KCFI type ID: mangled='%s' typeid=0x%08x\n",
+                 canonical_name, base_type_id);
+    }
+
+  return base_type_id;
+}
+
+/* Check if a function needs KCFI preamble generation.
+   ALL functions get preambles when -fsanitize=kcfi is enabled, regardless
+   of no_sanitize("kcfi") attribute.  */
+static bool
+function_needs_kcfi_preamble (tree fndecl)
+{
+  /* Only instrument if KCFI is globally enabled.  */
+  if (!(flag_sanitize & SANITIZE_KCFI))
+    return false;
+
+  struct cgraph_node *node = cgraph_node::get (fndecl);
+
+  /* Ignore cold partition functions: not reached via indirect call.  */
+  if (node && node->split_part)
+    return false;
+
+  /* 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 false;
+
+  /* Check if function is truly address-taken using cgraph node analysis.  */
+  bool addr_taken = (node && node->address_taken);
+
+  /* Only instrument functions that can be targets of indirect calls:
+     - Public functions (can be called externally)
+     - External declarations (from other modules)
+     - Functions with true address-taken status from cgraph analysis.  */
+  return TREE_PUBLIC (fndecl) || DECL_EXTERNAL (fndecl) || addr_taken;
+}
+
+/* Function attribute to store KCFI type ID.  */
+static tree kcfi_type_id_attr = NULL_TREE;
+
+/* Get KCFI type ID for a function declaration.  */
+uint32_t
+get_function_kcfi_type_id (tree fndecl)
+{
+  if (!kcfi_type_id_attr)
+    kcfi_type_id_attr = get_identifier ("kcfi_type_id");
+
+  tree attr = lookup_attribute_by_prefix ("kcfi_type_id", DECL_ATTRIBUTES (fndecl));
+  if (attr && TREE_VALUE (attr) && TREE_VALUE (TREE_VALUE (attr)))
+    {
+      tree value = TREE_VALUE (TREE_VALUE (attr));
+      if (TREE_CODE (value) == INTEGER_CST)
+ return (uint32_t) TREE_INT_CST_LOW (value);
+    }
+
+  /* Compute and cache type ID using original parameter declarations.  */
+  uint32_t type_id = compute_kcfi_type_id (fndecl);
+
+  tree type_id_tree = build_int_cst (unsigned_type_node, type_id);
+  tree attr_value = build_tree_list (NULL_TREE, type_id_tree);
+  attr = build_tree_list (kcfi_type_id_attr, attr_value);
+
+  DECL_ATTRIBUTES (fndecl) = chainon (DECL_ATTRIBUTES (fndecl), attr);
+
+  return type_id;
+}
+
+/* Get the number of patchable prefix NOPs for the current function.  */
+static HOST_WIDE_INT
+get_current_function_patchable_prefix_nops (void)
+{
+  HOST_WIDE_INT prefix_nops = 0;
+
+  /* Check for function-specific patchable_function_entry attribute.  */
+  tree patchable_attr = lookup_attribute ("patchable_function_entry",
+ DECL_ATTRIBUTES (current_function_decl));
+  if (patchable_attr)
+    {
+      tree pp_val = TREE_VALUE (patchable_attr);
+      /* total_nops = tree_to_uhwi (TREE_VALUE (pp_val)); */
+      if (TREE_CHAIN (pp_val))
+ prefix_nops = tree_to_uhwi (TREE_VALUE (TREE_CHAIN (pp_val)));
+    }
+  else
+    {
+      /* Use global configuration if no function-specific attribute.  */
+      HOST_WIDE_INT total_nops, patch_area_entry;
+      parse_and_check_patch_area (flag_patchable_function_entry, false,
+  &total_nops, &patch_area_entry);
+      prefix_nops = patch_area_entry;
+    }
+
+  return prefix_nops;
+}
+
+/* Check if this is an indirect call that needs KCFI instrumentation.  */
+static bool
+is_kcfi_indirect_call (tree fn)
+{
+  if (!fn)
+    return false;
+
+  /* Only functions WITHOUT no_sanitize("kcfi") should generate KCFI checks at
+     indirect call sites.  */
+  if (!sanitize_flags_p (SANITIZE_KCFI, current_function_decl))
+    return false;
+
+  /* Direct function calls via ADDR_EXPR don't need KCFI checks.  */
+  if (TREE_CODE (fn) == ADDR_EXPR)
+    return false;
+
+  /* Function pointers, variables, and other indirect calls need KCFI.  */
+  return true;
+}
+
+/* Extract target from call instruction RTL pattern.
+   Handles the RTL pattern matching needed to find the rtx containing
+   the function pointer for indirect calls.  */
+static rtx
+kcfi_find_call_target (rtx_insn *call_insn)
+{
+  if (!call_insn || (!CALL_P (call_insn) && !JUMP_P (call_insn)))
+    return NULL_RTX;
+
+  rtx call_pattern = PATTERN (call_insn);
+  rtx target_reg = NULL_RTX;
+
+  if (CALL_P (call_insn) && GET_CODE (call_pattern) == PARALLEL)
+    {
+      /* Handle PARALLEL patterns (need to extract CALL) */
+      rtx call_part = XVECEXP (call_pattern, 0, 0);
+      call_pattern = call_part;
+    }
+
+  if (CALL_P (call_insn) && GET_CODE (call_pattern) == CALL)
+    {
+      /* Handle CALL patterns.  */
+      rtx mem = XEXP (call_pattern, 0);
+      if (GET_CODE (mem) == MEM)
+ {
+  target_reg = XEXP (mem, 0);
+ }
+    }
+  else if (CALL_P (call_insn) && GET_CODE (call_pattern) == SET)
+    {
+      /* Handle SET patterns (function calls with return values) */
+      rtx src = XEXP (call_pattern, 1);
+      if (GET_CODE (src) == CALL)
+ {
+  rtx mem = XEXP (src, 0);
+  if (GET_CODE (mem) == MEM)
+    {
+      target_reg = XEXP (mem, 0);
+    }
+ }
+    }
+  else if (JUMP_P (call_insn) && GET_CODE (call_pattern) == SET)
+    {
+      /* Handle jump patterns.  */
+      rtx src = SET_SRC (call_pattern);
+      if (GET_CODE (src) == MEM)  /* Direct indirect jump.  */
+ {
+  target_reg = XEXP (src, 0);
+ }
+    }
+
+  return target_reg;
+}
+
+/* Add KCFI type ID note to call instruction.  */
+void
+add_kcfi_type_note (rtx_insn *call_insn, uint32_t type_id)
+{
+  if (!call_insn || !CALL_P (call_insn))
+    return;
+
+  /* Create integer constant for type ID.  */
+  rtx type_id_rtx = gen_int_mode (type_id, SImode);
+
+  /* Add note to call instruction.  */
+  add_reg_note (call_insn, REG_CALL_KCFI_TYPE, type_id_rtx);
+}
+
+/* Global flag to coordinate KCFI preamble emission.  */
+static bool kcfi_preamble_emitted = false;
+
+/* Mark that KCFI preamble has been emitted to prevent duplication.  */
+void
+mark_kcfi_preamble_emitted (void)
+{
+  kcfi_preamble_emitted = true;
+}
+
+/* Emit KCFI type ID symbol for an address-taken function.
+   Centralized emission point to avoid duplication between
+   assemble_external_real() and assemble_start_function(). */
+void
+emit_kcfi_typeid_symbol (FILE *asm_file, tree decl, const char *name)
+{
+  uint32_t type_id = get_function_kcfi_type_id (decl);
+  fprintf (asm_file, "\t.weak\t__kcfi_typeid_%s\n", name);
+  fprintf (asm_file, "\t.set\t__kcfi_typeid_%s, 0x%08x\n", name, type_id);
+}
+
+/* Parse patchable function entry configuration from global flags.  */
+static bool
+parse_patchable_function_entry_config (void)
+{
+  HOST_WIDE_INT total_nops, prefix_nops;
+
+  if (!flag_patchable_function_entry)
+    return false;
+
+  parse_and_check_patch_area (flag_patchable_function_entry, false, &total_nops, &prefix_nops);
+  return (total_nops > 0);
+}
+
+/* Common KCFI preamble helper that handles shared logic across architectures.  */
+static void
+kcfi_emit_cfi_preamble (FILE *file, tree decl, HOST_WIDE_INT prefix_nops, const char *fname)
+{
+  /* Get type ID.  */
+  uint32_t type_id = get_function_kcfi_type_id (decl);
+
+  /* Create symbol name for reuse.  */
+  char cfi_symbol_name[256];
+  snprintf (cfi_symbol_name, sizeof(cfi_symbol_name), "__cfi_%s", fname);
+
+  /* Emit __cfi_ symbol with proper visibility.  */
+  if (TREE_PUBLIC (decl))
+    {
+      if (DECL_WEAK (decl))
+ ASM_WEAKEN_LABEL (file, cfi_symbol_name);
+      else
+ targetm.asm_out.globalize_label (file, cfi_symbol_name);
+    }
+
+  /* Emit .type directive.  */
+  ASM_OUTPUT_TYPE_DIRECTIVE (file, cfi_symbol_name, "function");
+  fprintf (file, "%s:\n", cfi_symbol_name);
+
+  /* Calculate architecture-specific prefix NOPs if hook provided.  */
+  int final_nops = prefix_nops;
+  if (kcfi_target.calculate_prefix_nops)
+    final_nops = kcfi_target.calculate_prefix_nops (prefix_nops);
+
+  /* Emit architecture-specific prefix NOPs.  */
+  for (int i = 0; i < final_nops; i++)
+    {
+      fprintf (file, "\tnop\n");
+    }
+
+  /* Emit architecture-specific type ID instruction.  */
+  if (kcfi_target.emit_type_id_instruction)
+    kcfi_target.emit_type_id_instruction (file, type_id);
+
+  /* Mark end of __cfi_ symbol and emit size directive.  */
+  char cfi_end_label[256];
+  snprintf (cfi_end_label, sizeof(cfi_end_label), ".Lcfi_func_end_%s", fname);
+  ASM_OUTPUT_LABEL (file, cfi_end_label);
+
+  ASM_OUTPUT_MEASURED_SIZE (file, cfi_symbol_name);
+}
+
+void
+kcfi_emit_preamble_if_needed (FILE *file, tree decl,
+      bool is_patchable_context,
+      HOST_WIDE_INT prefix_nops,
+      const char *actual_fname)
+{
+  /* Check if KCFI is enabled and function needs preamble.  */
+  if (!function_needs_kcfi_preamble (decl))
+    return;
+
+  /* Use actual function name if provided, otherwise fall back to DECL_ASSEMBLER_NAME.  */
+  const char *fname = actual_fname ? actual_fname : IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
+
+  /* Determine if we should emit here based on context.  */
+  bool has_patchable_entries = parse_patchable_function_entry_config ();
+
+  if (is_patchable_context && has_patchable_entries)
+    {
+      /* Use the provided prefix_nops parameter.  */
+    }
+  else if (!is_patchable_context && !has_patchable_entries)
+    {
+      /* Emit for standard non-patchable functions.  */
+      prefix_nops = 0;
+    }
+  else
+    {
+      /* Skip to avoid duplication:
+ - Patchable context but no global patchable config
+ - Non-patchable context but has global patchable config.  */
+      return;
+    }
+
+  kcfi_emit_cfi_preamble (file, decl, prefix_nops, fname);
+}
+
+/* KCFI Final Instrumentation Pass - Post-Optimization Implementation
+
+   This pass runs after all optimizations to insert KCFI checks immediately
+   before indirect calls/jumps, solving the fundamental problem where
+   optimization would insert code between KCFI checks and their protected
+   indirect transfers.  */
+
+namespace {
+
+const pass_data pass_data_kcfi_final_instrumentation =
+{
+  RTL_PASS,                    /* type */
+  "kcfi_final_instrumentation", /* name */
+  OPTGROUP_NONE,              /* optinfo_flags */
+  TV_NONE,                    /* tv_id */
+  0,                          /* properties_required */
+  0,                          /* properties_provided */
+  0,                          /* properties_destroyed */
+  0,                          /* todo_flags_start */
+  0,                          /* todo_flags_finish */
+};
+
+class pass_kcfi_final_instrumentation : public rtl_opt_pass
+{
+public:
+  pass_kcfi_final_instrumentation (gcc::context *ctxt)
+    : rtl_opt_pass (pass_data_kcfi_final_instrumentation, ctxt)
+  {}
+
+  /* opt_pass methods: */
+  bool gate (function *) final override
+  {
+    /* Note: Target KCFI support is validated in toplev.cc during option processing.
+       If the target doesn't provide gen_kcfi_checked_call, compilation stops with
+       a "sorry" message before any passes run.  */
+    return sanitize_flags_p (SANITIZE_KCFI);
+  }
+
+  unsigned int execute (function *) final override;
+};
+
+/* Check if an RTL instruction is an indirect call/jump marked for KCFI.  */
+static bool
+is_marked_indirect_transfer (rtx_insn *insn, uint32_t *type_id)
+{
+  if (!insn || (!CALL_P (insn) && !JUMP_P (insn)))
+    return false;
+
+  /* Check for KCFI type ID note.  */
+  rtx note = find_reg_note (insn, REG_CALL_KCFI_TYPE, NULL_RTX);
+  if (!note)
+    return false;
+
+  rtx type_rtx = XEXP (note, 0);
+  if (!CONST_INT_P (type_rtx))
+    return false;
+
+  *type_id = (uint32_t) INTVAL (type_rtx);
+
+  /* Verify it's actually an indirect transfer.  */
+  rtx pattern = PATTERN (insn);
+
+  if (CALL_P (insn))
+    {
+      /* Handle call patterns.  */
+      if (GET_CODE (pattern) == CALL)
+ {
+  rtx target = XEXP (pattern, 0);
+  return GET_CODE (target) == MEM;
+ }
+      else if (GET_CODE (pattern) == SET)
+ {
+  rtx src = SET_SRC (pattern);
+  if (GET_CODE (src) == CALL)
+    {
+      rtx target = XEXP (src, 0);
+      return GET_CODE (target) == MEM;
+    }
+ }
+      else if (GET_CODE (pattern) == PARALLEL)
+ {
+  for (int i = 0; i < XVECLEN (pattern, 0); i++)
+    {
+      rtx elem = XVECEXP (pattern, 0, i);
+      if (GET_CODE (elem) == CALL
+  || (GET_CODE (elem) == SET && GET_CODE (SET_SRC (elem)) == CALL))
+ {
+  rtx call_rtx = (GET_CODE (elem) == SET) ? SET_SRC (elem) : elem;
+  rtx target = XEXP (call_rtx, 0);
+  return GET_CODE (target) == MEM;
+ }
+    }
+ }
+    }
+  else if (JUMP_P (insn))
+    {
+      /* Handle jump patterns.  */
+      if (GET_CODE (pattern) == SET)
+ {
+  rtx src = SET_SRC (pattern);
+  if (GET_CODE (src) == MEM)  /* Direct indirect jump.  */
+    return true;
+  /* Could also handle other indirect jump patterns here.  */
+ }
+    }
+
+  return false;
+}
+
+/* Replace marked indirect transfer with KCFI-protected version.  */
+unsigned int
+pass_kcfi_final_instrumentation::execute (function *fun)
+{
+  basic_block bb;
+
+  /* Scan all basic blocks for marked indirect transfers.  */
+  FOR_EACH_BB_FN (bb, fun)
+    {
+      rtx_insn *insn, *next_insn;
+
+      /* Use safe iteration since we'll be modifying the instruction stream.  */
+      for (insn = BB_HEAD (bb); insn && insn != NEXT_INSN (BB_END (bb)); insn = next_insn)
+ {
+  next_insn = NEXT_INSN (insn);
+
+  uint32_t type_id;
+  if (is_marked_indirect_transfer (insn, &type_id))
+    {
+      /* Extract target address from the call instruction.  */
+      rtx target_addr = kcfi_find_call_target (insn);
+      if (!target_addr)
+ {
+  error ("KCFI: cannot find target for indirect call");
+  gcc_unreachable ();
+ }
+
+      HOST_WIDE_INT prefix_nops = get_current_function_patchable_prefix_nops ();
+
+      /* Generate bundled KCFI checked call.  */
+      start_sequence ();
+
+      /* Pass the target as-is to the RTL pattern, which will handle
+ moving non-register targets to a register internally if needed.  */
+      rtx bundled_call = kcfi_target.gen_kcfi_checked_call (insn, target_addr, type_id, prefix_nops);
+      if (!bundled_call)
+ {
+  error ("KCFI: instruction sequence creation failed");
+  gcc_unreachable ();
+ }
+
+      /* Emit as call_insn, not generic insn.  */
+      emit_call_insn (bundled_call);
+      rtx replacement_seq = get_insns ();
+      if (!replacement_seq)
+ {
+  error ("KCFI: instruction sequence insertion failed");
+  gcc_unreachable ();
+ }
+
+      end_sequence ();
+
+      /* Check if original was a sibling call and preserve that flag.  */
+      bool was_sibcall = CALL_P (insn) && SIBLING_CALL_P (insn);
+
+      /* Replace the original call entirely with bundled version.  */
+      rtx_insn *new_insn = emit_insn_before (replacement_seq, insn);
+
+      /* If original was a sibling call, mark the new instruction as such.  */
+      if (was_sibcall && new_insn && CALL_P (new_insn))
+ SIBLING_CALL_P (new_insn) = 1;
+
+      set_insn_deleted (insn);  /* Mark original call as deleted.  */
+    }
+ }
+    }
+
+  return 0;
+}
+
+} // anon namespace
+
+rtl_opt_pass *
+make_pass_kcfi_final_instrumentation (gcc::context *ctxt)
+{
+  return new pass_kcfi_final_instrumentation (ctxt);
+}
+
+/* KCFI GIMPLE pass implementation.  */
+
+static bool
+gate_kcfi (void)
+{
+  return sanitize_flags_p (SANITIZE_KCFI);
+}
+
+/* Create a KCFI wrapper function type that embeds the type ID.  */
+static tree
+create_kcfi_wrapper_type (tree original_fn_type, uint32_t type_id)
+{
+  /* Create a unique type name incorporating the type ID.  */
+  char wrapper_name[64];
+  snprintf (wrapper_name, sizeof (wrapper_name), "__kcfi_wrapper_%x", type_id);
+
+  /* Build a new function type that's structurally identical but nominally different.  */
+  tree wrapper_type = build_function_type (TREE_TYPE (original_fn_type),
+   TYPE_ARG_TYPES (original_fn_type));
+
+  /* Set the type name to make it distinct.  */
+  TYPE_NAME (wrapper_type) = get_identifier (wrapper_name);
+
+  /* Attach kcfi_type_id attribute to the original function type for cfgexpand.cc */
+  tree attr_name = get_identifier ("kcfi_type_id");
+  tree attr_value = build_int_cst (unsigned_type_node, type_id);
+  tree attr = build_tree_list (attr_name, attr_value);
+  TYPE_ATTRIBUTES (original_fn_type) = chainon (TYPE_ATTRIBUTES (original_fn_type), attr);
+
+  return wrapper_type;
+}
+
+/* Replace indirect calls with KCFI wrapper types for anti-merging and clobber tracking.  */
+static unsigned int
+kcfi_instrument (void)
+{
+  basic_block bb;
+
+  FOR_EACH_BB_FN (bb, cfun)
+    {
+      gimple_stmt_iterator gsi;
+      for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
+ {
+  gimple *stmt = gsi_stmt (gsi);
+
+  if (is_gimple_call (stmt))
+    {
+      gcall *call_stmt = as_a <gcall *> (stmt);
+
+      // Skip internal calls - we only instrument indirect calls
+      if (gimple_call_internal_p (call_stmt))
+ {
+  continue;
+ }
+
+      tree fndecl = gimple_call_fndecl (call_stmt);
+
+      // Only process indirect calls (no fndecl)
+      if (!fndecl)
+ {
+  tree fn = gimple_call_fn (call_stmt);
+  if (fn && is_kcfi_indirect_call (fn))
+    {
+      // Get the function type to compute KCFI type ID
+      tree fn_type = gimple_call_fntype (call_stmt);
+      gcc_assert (fn_type);
+      if (TREE_CODE (fn_type) == FUNCTION_TYPE)
+ {
+  uint32_t type_id = compute_kcfi_type_id (fn_type);
+
+  // Create KCFI wrapper type for this call
+  tree wrapper_type = create_kcfi_wrapper_type (fn_type, type_id);
+
+  // Create a temporary variable for the wrapped function pointer
+  tree wrapper_ptr_type = build_pointer_type (wrapper_type);
+  tree wrapper_tmp = create_tmp_var (wrapper_ptr_type, "kcfi_wrapper");
+
+  // Create assignment: wrapper_tmp = (wrapper_ptr_type) fn
+  tree cast_expr = build1 (NOP_EXPR, wrapper_ptr_type, fn);
+  gimple *cast_stmt = gimple_build_assign (wrapper_tmp, cast_expr);
+  gsi_insert_before (&gsi, cast_stmt, GSI_SAME_STMT);
+
+  // Update the call to use the wrapped function pointer
+  gimple_call_set_fn (call_stmt, wrapper_tmp);
+ }
+    }
+ }
+    }
+ }
+    }
+
+  return 0;
+}
+
+namespace {
+
+const pass_data pass_data_kcfi =
+{
+  GIMPLE_PASS, /* type */
+  "kcfi", /* name */
+  OPTGROUP_NONE, /* optinfo_flags */
+  TV_NONE, /* tv_id */
+  ( PROP_ssa | PROP_cfg | PROP_gimple_leh ), /* properties_required */
+  0, /* properties_provided */
+  0, /* properties_destroyed */
+  0, /* todo_flags_start */
+  TODO_update_ssa, /* todo_flags_finish */
+};
+
+class pass_kcfi : public gimple_opt_pass
+{
+public:
+  pass_kcfi (gcc::context *ctxt)
+    : gimple_opt_pass (pass_data_kcfi, ctxt)
+  {}
+
+  /* opt_pass methods: */
+  opt_pass * clone () final override { return new pass_kcfi (m_ctxt); }
+  bool gate (function *) final override
+  {
+    return gate_kcfi ();
+  }
+  unsigned int execute (function *) final override
+  {
+    return kcfi_instrument ();
+  }
+
+}; // class pass_kcfi
+
+} // anon namespace
+
+gimple_opt_pass *
+make_pass_kcfi (gcc::context *ctxt)
+{
+  return new pass_kcfi (ctxt);
+}
+
+namespace {
+
+const pass_data pass_data_kcfi_O0 =
+{
+  GIMPLE_PASS, /* type */
+  "kcfi0", /* name */
+  OPTGROUP_NONE, /* optinfo_flags */
+  TV_NONE, /* tv_id */
+  ( PROP_ssa | PROP_cfg | PROP_gimple_leh ), /* properties_required */
+  0, /* properties_provided */
+  0, /* properties_destroyed */
+  0, /* todo_flags_start */
+  TODO_update_ssa, /* todo_flags_finish */
+};
+
+class pass_kcfi_O0 : public gimple_opt_pass
+{
+public:
+  pass_kcfi_O0 (gcc::context *ctxt)
+    : gimple_opt_pass (pass_data_kcfi_O0, ctxt)
+  {}
+
+  /* opt_pass methods: */
+  bool gate (function *) final override
+    {
+      return !optimize && gate_kcfi ();
+    }
+  unsigned int execute (function *) final override
+  {
+    return kcfi_instrument ();
+  }
+
+}; // class pass_kcfi_O0
+
+} // anon namespace
+
+gimple_opt_pass *
+make_pass_kcfi_O0 (gcc::context *ctxt)
+{
+  return new pass_kcfi_O0 (ctxt);
+}
gcc/opts.cc +1 -0
index 5fd86aa89adb..ab74414b9c5b 100644
@@ -2168,6 +2168,7 @@ const struct sanitizer_opts_s sanitizer_opts[] =
  SANITIZER_OPT (pointer-overflow, SANITIZE_POINTER_OVERFLOW, true, true),
  SANITIZER_OPT (builtin, SANITIZE_BUILTIN, true, true),
  SANITIZER_OPT (shadow-call-stack, SANITIZE_SHADOW_CALL_STACK, false, false),
+  SANITIZER_OPT (kcfi, SANITIZE_KCFI, false, true),
  SANITIZER_OPT (all, ~0ULL, true, true),
 #undef SANITIZER_OPT
  { NULL, 0ULL, 0UL, false, false }
gcc/passes.cc +1 -0
index a33c8d924a52..4c6ceac740ff 100644
@@ -63,6 +63,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "diagnostic-core.h" /* for fnotice */
 #include "stringpool.h"
 #include "attribs.h"
+#include "kcfi.h"
 
 /* Reserved TODOs */
 #define TODO_verify_il (1u << 31)
gcc/passes.def +3 -0
index d528a0477d9a..d4c84ca7064d 100644
@@ -275,6 +275,7 @@ along with GCC; see the file COPYING3.  If not see
      NEXT_PASS (pass_sink_code, false /* unsplit edges */);
      NEXT_PASS (pass_sancov);
      NEXT_PASS (pass_asan);
+      NEXT_PASS (pass_kcfi);
      NEXT_PASS (pass_tsan);
      NEXT_PASS (pass_dse, true /* use DR analysis */);
      NEXT_PASS (pass_dce, false /* update_address_taken_p */, false /* remove_unused_locals */);
@@ -443,6 +444,7 @@ along with GCC; see the file COPYING3.  If not see
  NEXT_PASS (pass_sancov_O0);
  NEXT_PASS (pass_lower_switch_O0);
  NEXT_PASS (pass_asan_O0);
+  NEXT_PASS (pass_kcfi_O0);
  NEXT_PASS (pass_tsan_O0);
  NEXT_PASS (pass_musttail);
  NEXT_PASS (pass_sanopt);
@@ -563,6 +565,7 @@ along with GCC; see the file COPYING3.  If not see
 NEXT_PASS (pass_delay_slots);
 NEXT_PASS (pass_split_for_shorten_branches);
 NEXT_PASS (pass_convert_to_eh_region_ranges);
+  NEXT_PASS (pass_kcfi_final_instrumentation);
 NEXT_PASS (pass_shorten_branches);
 NEXT_PASS (pass_set_nothrow_function_flags);
 NEXT_PASS (pass_dwarf2_frame);
gcc/recog.cc +1 -0
index 67d7fa630692..127524cfb4e2 100644
@@ -4026,6 +4026,7 @@ peep2_attempt (basic_block bb, rtx_insn *insn, int match_len, rtx_insn *attempt)
 case REG_SETJMP:
 case REG_TM:
 case REG_CALL_NOCF_CHECK:
+  case REG_CALL_KCFI_TYPE:
   add_reg_note (new_insn, REG_NOTE_KIND (note),
 XEXP (note, 0));
   break;
gcc/reg-notes.def +6 -0
index 68e137ceccaa..27924ee8afda 100644
@@ -251,5 +251,11 @@ REG_NOTE (UNTYPED_CALL)
   compiler when the option -fcf-protection=branch is specified.  */
 REG_NOTE (CALL_NOCF_CHECK)
 
+/* Contains the expected KCFI type ID for an indirect call instruction.
+   This note carries the 32-bit type identifier that should match the
+   type ID stored in the function preamble.  Used by KCFI (Kernel Control
+   Flow Integrity) to validate indirect call targets at runtime.  */
+REG_NOTE (CALL_KCFI_TYPE)
+
 /* The values passed to callee, for debuginfo purposes.  */
 REG_NOTE (CALL_ARG_LOCATION)
gcc/targhooks.cc +6 -1
index e723bbbc4df6..7edd3d8619af 100644
@@ -77,6 +77,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "calls.h"
 #include "expr.h"
 #include "output.h"
+#include "kcfi.h"
 #include "common/common-target.h"
 #include "reload.h"
 #include "intl.h"
@@ -2203,7 +2204,11 @@ default_compare_by_pieces_branch_ratio (machine_mode)
   the location of the NOPs will be recorded in a special object section
   called "__patchable_function_entries".  This routine may be called
   twice per function to put NOPs before and after the function
-   entry.  */
+   entry.
+
+   KCFI Integration: When KCFI is enabled and this is prefix emission (record_p = true),
+   this function will emit the KCFI preamble (symbols, NOPs, movl) before the prefix NOPs
+   to ensure correct memory layout per KCFI specification.  */
 

void
default_print_patchable_function_entry (FILE *file,

gcc/targhooks.cc +43 -0
@@ -2219,6 +2224,42 @@ default_print_patchable_function_entry (FILE *file,
  code_num = recog_memoized (my_nop);
  nop_templ = get_insn_template (code_num, my_nop);
 
+  /* KCFI Integration for prefix emission.  */
+  bool kcfi_handled = false;
+  if (record_p && current_function_decl)
+    {
+      /* Parse patchable function entry configuration to get prefix NOPs.  */
+      HOST_WIDE_INT total_nops = patch_area_size;
+      HOST_WIDE_INT prefix_nops = 0;
+
+      /* Check for function-specific patchable_function_entry attribute.  */
+      tree patchable_attr = lookup_attribute ("patchable_function_entry",
+     DECL_ATTRIBUTES (current_function_decl));
+      if (patchable_attr)
+ {
+  tree pp_val = TREE_VALUE (patchable_attr);
+  total_nops = tree_to_uhwi (TREE_VALUE (pp_val));
+  if (TREE_CHAIN (pp_val))
+    prefix_nops = tree_to_uhwi (TREE_VALUE (TREE_CHAIN (pp_val)));
+ }
+      else
+ {
+  /* Use global configuration if no function-specific attribute.  */
+  HOST_WIDE_INT patch_area_entry;
+  parse_and_check_patch_area (flag_patchable_function_entry, false,
+      &total_nops, &patch_area_entry);
+  prefix_nops = patch_area_entry;
+ }
+
+      /* Use centralized KCFI manager for patchable context.  */
+      if (prefix_nops > 0 && patch_area_size == (unsigned HOST_WIDE_INT)prefix_nops)
+ {
+  kcfi_emit_preamble_if_needed (file, current_function_decl, true, prefix_nops, NULL);
+  kcfi_handled = true;
+ }
+    }
+
+  /* Standard patchable function entry handling.  */
  if (record_p && targetm_common.have_named_sections)
    {
      char buf[256];
@@ -2249,9 +2290,16 @@ default_print_patchable_function_entry (FILE *file,
      ASM_OUTPUT_LABEL (file, buf);
    }
 
+  /* Emit the patchable NOPs.  */
  unsigned i;
  for (i = 0; i < patch_area_size; ++i)
    output_asm_insn (nop_templ, NULL);
+
+  /* Mark that KCFI preamble was handled to prevent duplication in ix86_asm_output_function_label.  */
+  if (kcfi_handled)
+    {
+      mark_kcfi_preamble_emitted ();
+    }
 }
 

bool

gcc/toplev.cc +8 -0
index 70dbb3e717f6..04331947b9da 100644
@@ -67,6 +67,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"
@@ -524,6 +525,7 @@ compile_file (void)
      insn_locations_init ();
      targetm.asm_out.code_end ();
 
+
      /* Do dbx symbols.  */
      timevar_push (TV_SYMOUT);
 
@@ -1733,6 +1735,12 @@ process_options ()
 "requires %<-fno-exceptions%>");
    }
 
+  if (flag_sanitize & SANITIZE_KCFI)
+    {
+      if (!kcfi_target.gen_kcfi_checked_call)
+ sorry ("%<-fsanitize=kcfi%> not supported by this target");
+    }
+
  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/varasm.cc +18 -0
index 000ad9e26f6f..9c4e3c223159 100644
@@ -57,6 +57,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "attribs.h"
 #include "asan.h"
 #include "rtl-iter.h"
+#include "kcfi.h"
 #include "file-prefix-map.h" /* remap_debug_filename()  */
 #include "alloc-pool.h"
 #include "toplev.h"
@@ -2210,6 +2211,10 @@ assemble_start_function (tree decl, const char *fnname)
  ASM_OUTPUT_FUNCTION_LABEL (asm_out_file, fnname, current_function_decl);
 #endif /* ASM_DECLARE_FUNCTION_NAME */
 
+  /* KCFI type ID symbols are only emitted for external function declarations,
+     handled by assemble_external_real().  Function definitions do not emit
+     __kcfi_typeid symbols.  */
+
  /* And the area after the label.  Record it if we haven't done so yet.  */
  if (patch_area_size > patch_area_entry)
    targetm.asm_out.print_patchable_function_entry (asm_out_file,
@@ -2752,6 +2757,19 @@ assemble_external_real (tree decl)
      /* Some systems do require some output.  */
      SYMBOL_REF_USED (XEXP (rtl, 0)) = 1;
      ASM_OUTPUT_EXTERNAL (asm_out_file, decl, XSTR (XEXP (rtl, 0), 0));
+
+      /* Emit KCFI type ID symbol for external function declarations that are address-taken.  */
+      struct cgraph_node *node = (TREE_CODE (decl) == FUNCTION_DECL) ? cgraph_node::get (decl) : NULL;
+      if (flag_sanitize & SANITIZE_KCFI
+  && TREE_CODE (decl) == FUNCTION_DECL
+  && !DECL_INITIAL (decl)  /* Only for external declarations (no function body) */
+  && node && node->address_taken)  /* Use direct cgraph analysis for address-taken check.  */
+ {
+  const char *name = XSTR (XEXP (rtl, 0), 0);
+  /* Strip any encoding prefixes like '*' from symbol name.  */
+  name = targetm.strip_name_encoding (name);
+  emit_kcfi_typeid_symbol (asm_out_file, decl, name);
+ }
    }
 }
 #endif
Signature · 1 line
2.34.1
author
#33 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 6 lines · Qing Zhao

Hi, Kees,

I have several suggestions and questions first for this patch:

1. Is -fsanitize=kcfi a C only feature? If so, you might need to mention this in the documentation and also reject its usage in other languages.

Yes, it's C only. I will note it and add a check for that. Thanks for the reminder!

Quoted 4 lines

2. There is no overall description of the design of this kcfi implementation
in the source code, I think it might be very helpful to provide such description In the new module kcfi.cc <http://kcfi.cc/>. such documentation will be helpful for current review and future maintenance of this feature.

Ah yeah, good idea. I will adapt the commit log.

Quoted 142 lines
Quoted 142 lines · Kees Cook

This series 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.

Just to set expectations, this is an RFC because this is my first time working on most of the affected areas in GCC, and it is likely I have missed really obvious stuff, or gone about doing things in very wrong ways. I tried to find the best way to do stuff, but I was left with many questions. :) All that said, this works for x86_64 and aarch64 Linux kernels. (I have implemented riscv64 as well, but I lack a viable test environment -- I am working on this still.)

KCFI has a number of specific constraints. Some are tied to the backend architecture, which I'll cover in more detail in later patches. The constraints are:

- The KCFI scheme generates a unique 32-bit hash for each unique function prototype, allowing for indirect call sites to verify that they are calling into a matching _type_ of function pointer. This changes the semantics of some optimization logic because now indirect calls to different types cannot be merged. For example:

   if (p->func_type_1)
return p->func_type_1();
   if (p->func_type_2)

return p->func_type_2();

In final asm, the optimizer may collapse the second indirect call into a jump to the first indirect call once it has loaded the function pointer. KCFI must block cross-type merging otherwise there will be a single KCFI check happening for only 1 type but being used by 2 target types. The distinguishing characteristic for call merging becomes the type, not the address/register usage.

- The check-call instruction sequence must be treated a single unit: it cannot be rearranged or split or optimized. The pattern is that indirect calls, "call *$target", get converted into:

mov $target_expression, %target (only present if the expression was
not already %target)
load -$offset(%target), %tmp
cmp $hash, %tmp
je .Lcheck_passed
.Ltrap$N:
trap
.Lcheck_passed$N:
call *%target

This pattern of call immediately after trap provides for the "permissive" checking mode automatically: the trap gets handled, a warning emitted, and then execution continues after the trap to the call.

(x86_64 uses "mov -$hash, %tmp; addl -$offset(%target), %tmp; je" to zero out the register before making the call. Also Linux needs exactly these insns because it is both disassembling them during trap handling and potentially live patching them at boot time to be converted into a different series of instrutions, a scheme know as FineIBT, making the insn sequence ABI.)

- KCFI check-call instrumentation must survive tail call optimization. If an indirect call is turned into an indirect jump, KCFI checking must still happen (but will still use the jmp).

- Functions that may be called indirectly have a preamble added, __cfi_$original_func_name, that contains the $hash value:

__cfi_target_func:
.word $hash
target_func:
[regular function entry...]

(x86_64 uses a movl instruction to hold the hash and prefixed aligned NOPs to maintain cache line alignment in the face of patchable function entry...)

- The preamble needs to interact with patchable function entry so that the hash appears further away from the actual start of the function (leaving the prefix NOPs of the patchable function entry unchanged). This means only _globally defined_ patchable function entry is supported with KCFI (indrect call sites must know in advance what the offset is, which may not be possible extern functions). For example, a "4,4" patchable function entry would end up like:

__cfi_target_func:
.data $hash
nop nop nop nop
target_func:
[regular function entry...]

(Linux x86_64 uses an 11 byte prefix nop area resulting in 16 bytes total including the movl. This region may be live patched at boot time for FineIBT so the behavior here is also ABI.)

- External functions that are address-taken have a weak __kcfi_typeid_$funcname symbol added with the hash value available so that the hash can be referenced from assembly linkages, etc, where the hash values cannot be calculated (i.e where C type information is missing):

.weak __kcfi_typeid_$func
.set __kcfi_typeid_$func, $hash

- On architectures that do not have a good way to encode additional details in their trap (x86_64 and riscv64), the trap location is identified as a KCFI trap via a relative address offset entry emitted into the .kcfi_traps section for each indirect call site's trap instruction. The previous check-call example's insn sequence has a section push/pop inserted between the trap and call:

...
.Ltrap$N:
trap
.pushsection .kcfi_traps,"ao",@progbits,.text
.Lentry$N:
.long .Ltrap$N - .Lentry$N
.popsection
.Lcheck_passed$N:
call %target

(aarch64 encodes the register numbers that hold the expected hash and the target address in the trap ESR and thereby does not need a .kcfi_traps section at all.)

- The no_sanitize("kcfi") function attribute means that the marked function must not produce KCFI checking for indirect calls, and that this attribute must survive inlining. This is used rarely by Linux, but is required to make BPF JIT trampolines work on older Linux kernel versions. (The preamble code is very recently finally being generated at JIT time on the last remaining Linux KCFI arch where this was
missing: aarch64.)

As a result of these constraints, there are some behavioral aspects that need to be preserved across the middle-end and back-end, as I understand them.

For indirect call sites:

Quoted 8 lines
Quoted 5 lines

- Keeping indirect calls from being merged (see above). I did this by adding a wrapping type so that equality was tested based on type-id. This is done in create_kcfi_wrapper_type(), via kcfi_instrument(), via an early GIMPLE pass (pass_kcfi and pass_kcfi0). The wrapper type is checked in gcc/cfgcleanup.cc, old_insns_match_p().

First, Looks like that the routine “old_insns_match_p” checks the type-ids that were embedded in the REG_NOTE ( REG_CALL_KCFI_TYPE) of the RTL. -:)

Once I started using the backend RTL patterns more correctly, this note and all the logic attached to it went away. I'll send my v2 shortly.

Quoted 2 lines

My understanding is: the computed type-id is recorded into to a “kcfi_type_id” attribute, and then this “kcfi_type_id” attribute is attached to the original function type.

Correct (so that we can use it when generating the preambles and RTL define_insn output).

Quoted 6 lines

At the same time, A wrapper type is created for the original function type, whose typename is “__kcfi_wrapper_type_id”.

I am confused:

1. Why the additional wrapper type is needed? why the original function type + “kcfi_type_id” not enough?

This was created to keep calls some being combined during optimization. e.g.:

if (func1) {
	func1();
	return;
}
if (func2) {
	func2();
	return;
}

this was getting constructed as:

if (func1) {
	ptr = func1;
do_call:
	call ptr;
	return;
}
if (func2) {
	ptr = func2;
	goto do_call;
}

The above is normally totally fine because only address "matters", but in the CFI world, the typeid is a part of the call. If func1 and func2 don't share the same typeid, suddenly the "goto do_call" call path will fail because the call (that checks the func1 typeid) will trigger a mismatch wne func2 tries to be called through the func1-typeid-call.

Quoted 2 lines

2. Why attaching the type-id as a “kcfi_type_id” attribute to the original function type?
Is there other way to attach the type-id to the original function type? Or to the original indirect call site?

In the v2 series I moved this to the IPA phase so I could attach everything to the original fndecl.

Quoted 2 lines

Is it possible that we might provide a user level “kcfi_type_id” attribute to function type in the future? then That will be conflict with the current “kcfi_type_id” attribute?

The closest I can imagine is the kcfi hash salt, which will just allow the user to bump the typeid hash by a deterministic amount (to separate the larger "pools" of hashes -- e.g. "void func(void)" is very common, so the salt would allow for a slight modification to separate sets of otherwise identical types).

Quoted 10 lines
Quoted 4 lines

- Keeping typeid information available through to the RTL expansion phase was done via a typeid note (REG_CALL_KCFI_TYPE) attached also in create_kcfi_wrapper_type() in the same GIMPLE pass.

This is done in the routine “expand_call_stmt” through call to “add_kcfi_type_note”. The “type_id” is attached as a “kcfi_type_id” attribute to the original function type in the routine “create_kcfi_wrapper_type”.

Please see my above question 2.

In v2 this has been pretty radically changed -- expansion just reads the kcfi_type_id directly into an RTL operand for a new KCFI insn type (i.e. separate from CALL or SET), which wraps CALL.

Quoted 8 lines
Quoted 4 lines

- To make sure instrumentation was skipped for inline functions, the RTL pass walks the basic blocks to identify their function origins, looking for the no_sanitize("kcfi") attribute, and skipping instrumentation if found.

I think this was done inefficiently. It’s better to do this during inlining transformation to propagate the no_sanitize information from the caller to the callee body and attach the no_sanitize information to the indirect callsite.

Yes, I took Andrew's suggestion and implemented a flag that is set on the insn itself and is checked at the callsite.

Quoted 11 lines
Quoted 8 lines

For indirect call targets:

- kcfi_emit_preamble_if_needed() uses function_needs_kcfi_preamble(), and counter helpers, to emit the preablem, with patchable function entry NOPs. This gets used both in default_print_patchable_function_entry() and the per-arch path.

I saw that “kcfi_emit_preamble_if_needed” is called by “default_print_patchable_function_entry”, But I didn’t see where it is called when the function is not patchable?

These were in the per-arch function label emission, but for v2 I've moved them out after refactoring how the patchable function entry integration works.

Quoted 22 lines
Quoted 13 lines

I could not find a simpler way to deal with
patchable function entry besides splitting it up like this. I feel like there should be a better way.

- gcc/varasm.cc, assemble_external_real() calls emit_kcfi_typeid_symbol() to add the __kcfi_typeid symbols (see get_function_kcfi_type_id() below).

To support the per-arch back-ends, there are some common helpers:

- A callback framework is added via struct kcfi_target_hooks for backends to fill out.

Quoted 8 lines

- kcfi_emit_trap_with_section() handles the push/pop section and generating the relative offset section entries.

- get_function_kcfi_type_id() generates the 32-bit hash value, using compute_kcfi_type_id() and kcfi_hash_string() to hook to the mangling API. The hash is FNV-1a right now: it doesn't need secrecy. It could be replaced with any hash, though the hash will need to be coordinated with Rust, which implements the KCFI ABI as well.

Quoted 7 lines

One question here, the final type_id will be computed by the following 2 steps:

1. Itanium C++ mangling based on return type + parameter types of the function.
2. FNV-1a hash on the mangled string

If the hacker knows these, it should be quite easy for them to come up with a matched typeid, is it?

The hashes aren't considered secret -- they need to be known/match between compilation units, and even across languages (Rust). The KCFI mitigation is fundamentally an "exploit surface reduction" measure in the sense that it limits an attacker's set of callable functions to only matching typeids (instead of all functions or all executable memory). I discuss this a big more here:
https://gcc.gnu.org/pipermail/gcc-patches/2025-August/693059.html

Thanks for the review! I'll have v2 up shortly -- I'm still going through the commit logs and tests to make sure they're sensible. :)

-Kees

Signature · 1 line
Kees Cook
#34 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

Quoted 10 lines · Kees Cook
Quoted 2 lines

If the hacker knows these, it should be quite easy for them to come up with a matched typeid, is it?

The hashes aren't considered secret -- they need to be known/match between compilation units, and even across languages (Rust). The KCFI mitigation is fundamentally an "exploit surface reduction" measure in the sense that it limits an attacker's set of callable functions to only matching typeids (instead of all functions or all executable memory). I discuss this a big more here:
https://gcc.gnu.org/pipermail/gcc-patches/2025-August/693059.html

Also note that the kernel with re-hash all the values at boot time once more -- further increasing the difficulty of an attack.

#35 lore raw

Re: [RFC PATCH 3/7] kcfi: Add core Kernel Control Flow Integrity infrastructure

In reply to Kees Cook
Quoted 36 lines · Kees Cook
Quoted 7 lines

At the same time, A wrapper type is created for the original function type, whose typename is “__kcfi_wrapper_type_id”.

I am confused:

1. Why the additional wrapper type is needed? why the original function type + “kcfi_type_id” not enough?

This was created to keep calls some being combined during optimization. e.g.:

if (func1) {
func1();
return;
}
if (func2) {
func2();
return;
}

this was getting constructed as:

if (func1) {
ptr = func1;
do_call:
call ptr;
return;
}
if (func2) {
ptr = func2;
goto do_call;
}

Quoted 5 lines

The above is normally totally fine because only address "matters", but in the CFI world, the typeid is a part of the call. If func1 and func2 don't share the same typeid, suddenly the "goto do_call" call path will fail because the call (that checks the func1 typeid) will trigger a mismatch wne func2 tries to be called through the func1-typeid-call.

If the new “wrapper type” is only used to avoid the above transformation, then original function type + kcfi_type_id should be enough to avoid such merging, No need to create a new wrapper type with the exactly same information embedded.

Do I still miss anything obvious?

Quoted 9 lines
Quoted 9 lines
Quoted 8 lines

For indirect call targets:

- kcfi_emit_preamble_if_needed() uses function_needs_kcfi_preamble(), and counter helpers, to emit the preablem, with patchable function entry NOPs. This gets used both in default_print_patchable_function_entry() and the per-arch path.

Quoted 7 lines
Quoted 2 lines

I saw that “kcfi_emit_preamble_if_needed” is called by “default_print_patchable_function_entry”, But I didn’t see where it is called when the function is not patchable?

These were in the per-arch function label emission, but for v2 I've moved them out after refactoring how the patchable function entry integration works.

Yeah, I saw them when I read the patches for the backends. -:)

Quoted 15 lines
Quoted 7 lines
Quoted 6 lines

- get_function_kcfi_type_id() generates the 32-bit hash value, using compute_kcfi_type_id() and kcfi_hash_string() to hook to the mangling API. The hash is FNV-1a right now: it doesn't need secrecy. It could be replaced with any hash, though the hash will need to be coordinated with Rust, which implements the KCFI ABI as well.

Quoted 7 lines

One question here, the final type_id will be computed by the following 2 steps:

1. Itanium C++ mangling based on return type + parameter types of the function.
2. FNV-1a hash on the mangled string

If the hacker knows these, it should be quite easy for them to come up with a matched typeid, is it?

Quoted 7 lines

The hashes aren't considered secret -- they need to be known/match between compilation units, and even across languages (Rust). The KCFI mitigation is fundamentally an "exploit surface reduction" measure in the sense that it limits an attacker's set of callable functions to only matching typeids (instead of all functions or all executable memory). I discuss this a big more here:
https://gcc.gnu.org/pipermail/gcc-patches/2025-August/693059.html

Thanks for the info.

Qing.

author
#36 lore raw

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

In reply to Kees Cook

Implement x86_64-specific KCFI backend:

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

- 16-byte alignment of KCFI preambles using calculated prefix NOPs:
aligned(prefix_nops + 5, 16) to maintain cache lines.

- 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). The clobbers are available both early and late.

- Atomic bundled KCFI check + call/branch sequences using UNSPECV_KCFI to prevent optimizer separation and maintain security properties.

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

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 .Lpass                     ; Branch if types match (sum == 0)
  .Ltrap: ud2                   ; Undefined instruction trap on mismatch
  .Lpass: call/jmp *%target     ; Execute validated indirect transfer

The initialization of the kcfi callbacks in ix86_option_override() seems like a hack. I couldn't find a better place to do this.

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

---
 gcc/config/i386/i386-protos.h   |   4 +
 gcc/config/i386/i386-options.cc |   3 +
 gcc/config/i386/i386.cc         | 128 ++++++++++++++++++++++++++++
 gcc/config/i386/i386.md         | 144 ++++++++++++++++++++++++++++++++
 gcc/doc/invoke.texi             |  20 +++++
 5 files changed, 299 insertions(+)
gcc/config/i386/i386-protos.h +4 -0
index 69bc0ee570dd..a5209077506c 100644
@@ -36,6 +36,10 @@ extern void ix86_maybe_emit_epilogue_vzeroupper (void);
 extern void ix86_expand_epilogue (int);
 extern void ix86_expand_split_stack_prologue (void);
 
+/* KCFI support.  */
+extern void ix86_kcfi_init (void);
+extern void kcfi_emit_trap_with_section (FILE *file, rtx trap_label_rtx);
+
 extern void ix86_output_addr_vec_elt (FILE *, int);
 extern void ix86_output_addr_diff_elt (FILE *, int, int);
 
gcc/config/i386/i386-options.cc +3 -0
index 09a35ef62980..f7726c3fdd8f 100644
@@ -3180,6 +3180,9 @@ void
 ix86_option_override (void)
 {
   ix86_option_override_internal (true, &global_options, &global_options_set);
+
+  /* Initialize KCFI target hooks for x86-64.  */
+  ix86_kcfi_init ();
 }
 
 /* Remember the last target of ix86_set_current_function.  */
gcc/config/i386/i386.cc +128 -0

152 lines not on this page · raw message

gcc/config/i386/i386.md +144 -0

156 lines not on this page · raw message

gcc/doc/invoke.texi +20 -0
index c66f47336826..f531a9f6ce33 100644
@@ -18316,6 +18316,26 @@ and without changing the entry points of the target functions. Only
 functions that have referenced by their address receive the KCFI preamble
 instrumentation.
 
+Platform-specific implementation details:
+
+On x86_64, KCFI type identifiers are emitted as a @code{movl $ID, %eax}
+instruction before the function entry.  The implementation ensures that
+type IDs never collide with ENDBR instruction encodings.  When used with
+@option{-fpatchable-function-entry}, the type identifier is placed before
+any patchable NOPs, with appropriate alignment to maintain a 16-byte
+boundary for the function entry.  The runtime check loads the type ID
+from the target function into @code{%r10d} and uses an @code{addl}
+instruction to add the negative expected type ID, effectively zeroing
+the register if the types match.  A conditional jump follows to either
+continue execution or trap on mismatch.  The check sequence uses
+@code{%r10d} and @code{%r11d} as scratch registers.  Trap locations are
+recorded in a special @code{.kcfi_traps} section that maps trap sites
+to their corresponding function entry points, enabling debuggers and
+crash handlers to identify KCFI violations.  The exact instruction
+sequences for both the KCFI preamble and the check-call bundle are
+considered ABI, as the Linux kernel may optionally rewrite these areas
+at boot time to mitigate detected CPU errata.
+
 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.
Signature · 1 line
2.34.1
#37 lore raw

Re: [RFC PATCH 4/7] x86: Add x86_64 Kernel Control Flow Integrity implementation

Quoted 26 lines · Kees Cook

Implement x86_64-specific KCFI backend:

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

- 16-byte alignment of KCFI preambles using calculated prefix NOPs:
aligned(prefix_nops + 5, 16) to maintain cache lines.

- 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). The clobbers are available both early and late.

- Atomic bundled KCFI check + call/branch sequences using UNSPECV_KCFI to prevent optimizer separation and maintain security properties.

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

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 .Lpass                     ; Branch if types match (sum == 0)
  .Ltrap: ud2                   ; Undefined instruction trap on mismatch
  .Lpass: call/jmp *%target     ; Execute validated indirect transfer
Quoted 5 lines

The initialization of the kcfi callbacks in ix86_option_override() seems like a hack. I couldn't find a better place to do this.

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

I'm a little confused, does this force r11 to be the indirect call register like clang does? The code seems to suggest it is possible it uses another register.

The current kernel FineIBT code hard assumes r11 for now.

author
#38 lore raw

Re: [RFC PATCH 4/7] x86: Add x86_64 Kernel Control Flow Integrity implementation

Quoted 30 lines · Peter Zijlstra
Quoted 29 lines · Kees Cook

Implement x86_64-specific KCFI backend:

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

- 16-byte alignment of KCFI preambles using calculated prefix NOPs:
aligned(prefix_nops + 5, 16) to maintain cache lines.

- 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). The clobbers are available both early and late.

- Atomic bundled KCFI check + call/branch sequences using UNSPECV_KCFI to prevent optimizer separation and maintain security properties.

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

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 .Lpass                     ; Branch if types match (sum == 0)
  .Ltrap: ud2                   ; Undefined instruction trap on mismatch
  .Lpass: call/jmp *%target     ; Execute validated indirect transfer

The initialization of the kcfi callbacks in ix86_option_override() seems like a hack. I couldn't find a better place to do this.

Quoted 8 lines
Quoted 2 lines

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

I'm a little confused, does this force r11 to be the indirect call register like clang does? The code seems to suggest it is possible it uses another register.

The current kernel FineIBT code hard assumes r11 for now.

Oh, it looked like it wasn't always r11. Does clang force the call register to be r11? I only do that here if the call expression isn't a register (similar to -mindirect-branch-register). Looking at the retpoline implementation, I see __x86_indirect_thunk_* being generated for all the general registers. Hm, but in looking now I see all the hard-coded r11 use in the fineibt alternatives. I wonder if my boot testing is somehow not triggering the FineIBT alternatives patching? I will investigate more...

Signature · 1 line
Kees Cook
author
#39 lore raw

Re: [RFC PATCH 4/7] x86: Add x86_64 Kernel Control Flow Integrity implementation

Quoted 4 lines · Kees Cook
Quoted 3 lines · Peter Zijlstra
Quoted 2 lines · Kees Cook

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

Turns out my configs were broken -- I only tested non-retpoline.

Quoted 7 lines
Quoted 6 lines

I'm a little confused, does this force r11 to be the indirect call register like clang does? The code seems to suggest it is possible it uses another register.

The current kernel FineIBT code hard assumes r11 for now.

Quoted 7 lines

Oh, it looked like it wasn't always r11. Does clang force the call register to be r11? I only do that here if the call expression isn't a register (similar to -mindirect-branch-register). Looking at the retpoline implementation, I see __x86_indirect_thunk_* being generated for all the general registers. Hm, but in looking now I see all the hard-coded r11 use in the fineibt alternatives. I wonder if my boot testing is somehow not triggering the FineIBT alternatives patching? I will investigate more...

I've found my Kconfig problem now. Confirmed that this RFC does _not_ work with retpoline (much less FineIBT). I will get that fixed for the next version.

Signature · 1 line
Kees Cook
#40 lore raw

Re: [RFC PATCH 4/7] x86: Add x86_64 Kernel Control Flow Integrity implementation

In reply to Kees Cook
Quoted 6 lines · Kees Cook
Quoted 1 line · Peter Zijlstra

The current kernel FineIBT code hard assumes r11 for now.

Oh, it looked like it wasn't always r11. Does clang force the call register to be r11?

Yes. I'm not sure why, but that's what it does, unconditionally r11.

(funny extra detail, when using retpolines, clang sometimes generates conditional tail-calls, it merged Jcc and JMP __x86_indirect_thunk_r11 into Jcc __x86_indirect_thunk_r11. I've never seen GCC do this).

Quoted 4 lines

I only do that here if the call expression isn't a
register (similar to -mindirect-branch-register). Looking at the retpoline implementation, I see __x86_indirect_thunk_* being generated for all the general registers.

Yeah, generating the whole set was easiest. The BPF JIT and custom asm also have retpolines in. Eg.

arch/x86/kernel/ftrace_64.S: CALL_NOSPEC r8
arch/x86/platform/efi/efi_stub_64.S: CALL_NOSPEC rdi

Quoted 3 lines

Hm, but in looking now I see all the hard-coded r11 use
in the fineibt alternatives. I wonder if my boot testing is somehow not triggering the FineIBT alternatives patching? I will investigate more...

Right, GCC typically prefers rax (with a wide margin) but pretty much every register gets used on a big enough code-base.

Random defconfig of the day gets me:

15227 __x86_indirect_thunk_rax

    417 __x86_indirect_thunk_rdx
    205 __x86_indirect_thunk_rcx
    110 __x86_indirect_thunk_r13
    108 __x86_indirect_thunk_r12
     98 __x86_indirect_thunk_r8
     97 __x86_indirect_thunk_rbp
     96 __x86_indirect_thunk_r10
     85 __x86_indirect_thunk_r14
     38 __x86_indirect_thunk_r15
     36 __x86_indirect_thunk_r9
     34 __x86_indirect_thunk_rbx
     28 __x86_indirect_thunk_r11
     16 __x86_indirect_thunk_rsi
      1 __x86_indirect_thunk_rdi

IIRC you clobber r10 for the hash usage, so you'll not generate indirect calls through that, but other than that the code seems to preserve random register if the address is already loaded in it, otherwise loads into r11.

Anyway, I might be able to deal with the indirect call not being r11, but it'll take a bit of prodding. Also it will shatter my plans to move the hash to eax to save a few bytes in instruction encoding. Let me go poke around with that UDB patch see what's possible.

author
#41 lore raw

Re: [RFC PATCH 4/7] x86: Add x86_64 Kernel Control Flow Integrity implementation

Quoted 4 lines · Peter Zijlstra

Anyway, I might be able to deal with the indirect call not being r11, but it'll take a bit of prodding. Also it will shatter my plans to move the hash to eax to save a few bytes in instruction encoding. Let me go poke around with that UDB patch see what's possible.

I think I have it mostly working to force r11 when doing kcfi and retpoline now, though I'm seeing a few glitches still. I'll keep working on it.

Signature · 1 line
Kees Cook
#42 lore raw

Re: [RFC PATCH 4/7] x86: Add x86_64 Kernel Control Flow Integrity implementation

Quoted 9 lines · Kees Cook
Quoted 4 lines · Peter Zijlstra

Anyway, I might be able to deal with the indirect call not being r11, but it'll take a bit of prodding. Also it will shatter my plans to move the hash to eax to save a few bytes in instruction encoding. Let me go poke around with that UDB patch see what's possible.

I think I have it mostly working to force r11 when doing kcfi and retpoline now, though I'm seeing a few glitches still. I'll keep working on it.

Awesome, thanks!

author
#43 lore raw

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

In reply to Kees Cook

Implement AArch64-specific KCFI backend.

- Function preamble generation using .word directives for type ID storage at offset from function entry point (no prefix NOPs needed due to 4-byte instruction alignment).

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

- Scratch register allocation using w16/w17 (x16/x17) following AArch64 procedure call standard for intra-procedure-call registers.

- Support for both regular calls (BLR) and sibling calls (BR) with appropriate register usage and jump instructions.

- Atomic bundled KCFI check + call/branch sequences using UNSPECV_KCFI_CHECK to prevent optimizer separation and maintain security properties.

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

Like x86, the callback initialization in aarch64_override_options() seem hacky. Is there a better place for this?

Build and run tested with Linux kernel ARCH=arm64.

---
 gcc/config/aarch64/aarch64-protos.h |   4 +
 gcc/config/aarch64/aarch64.cc       | 112 +++++++++++++++++++++++
 gcc/config/aarch64/aarch64.md       | 137 ++++++++++++++++++++++++++++
 gcc/doc/invoke.texi                 |  14 +++
 4 files changed, 267 insertions(+)
gcc/config/aarch64/aarch64-protos.h +4 -0
index 38c307cdc3a6..ff235305fbc1 100644
@@ -1280,4 +1280,8 @@ extern bool aarch64_gcs_enabled ();
 extern unsigned aarch64_data_alignment (const_tree exp, unsigned align);
 extern unsigned aarch64_stack_alignment (const_tree exp, unsigned align);
 
+/* KCFI support.  */
+extern void aarch64_kcfi_init (void);
+extern void kcfi_emit_trap_with_section (FILE *file, rtx trap_label_rtx);
+
 #endif /* GCC_AARCH64_PROTOS_H */
gcc/config/aarch64/aarch64.cc +112 -0

136 lines not on this page · raw message

gcc/config/aarch64/aarch64.md +137 -0

149 lines not on this page · raw message

gcc/doc/invoke.texi +14 -0
index f531a9f6ce33..161c7024f842 100644
@@ -18336,6 +18336,20 @@ sequences for both the KCFI preamble and the check-call bundle are
 considered ABI, as the Linux kernel may optionally rewrite these areas
 at boot time to mitigate detected CPU errata.
 
+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
+padding NOPs.  When used with @option{-fpatchable-function-entry}, the
+type identifier is placed before any patchable 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.
Signature · 1 line
2.34.1
author
#44 lore raw

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

In reply to Kees Cook

Implement RISC-V-specific KCFI backend.

- Function preamble generation using .word directives for type ID storage at offset from function entry point (no prefix NOPs needed due to natural 4-byte instruction alignment).

- Scratch register allocation using t1/t2 (x6/x7) following RISC-V procedure call standard for temporary registers.

- Support for both regular calls (JALR) and sibling calls (JR) with appropriate register usage and jump instructions.

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

- Atomic bundled KCFI check + call/jump sequences using UNSPECV_KCFI_CHECK to prevent optimizer separation and maintain security properties.

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, .Lpass            ; Branch if types match

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

Build tested with Linux kernel ARCH=riscv (I am still building a proper risc-v emulation setup). Run tested via userspace binaries.

---
 gcc/config/riscv/riscv-protos.h |   1 +
 gcc/config/riscv/riscv.cc       | 157 ++++++++++++++++++++++++++++++++
 gcc/config/riscv/riscv.md       |  49 ++++++++++
 gcc/doc/invoke.texi             |  13 +++
 4 files changed, 220 insertions(+)
gcc/config/riscv/riscv-protos.h +1 -0
index 539321ff95b8..1d343c529934 100644
@@ -126,6 +126,7 @@ extern bool riscv_split_64bit_move_p (rtx, rtx);
 extern void riscv_split_doubleword_move (rtx, rtx);
 extern const char *riscv_output_move (rtx, rtx);
 extern const char *riscv_output_return ();
+extern const char *riscv_output_kcfi_checked_call (uint32_t, HOST_WIDE_INT, bool);
 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.cc +157 -0

193 lines not on this page · raw message

gcc/config/riscv/riscv.md +49 -0

61 lines not on this page · raw message

gcc/doc/invoke.texi +13 -0
index 161c7024f842..f82d0464590d 100644
@@ -18350,6 +18350,19 @@ 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 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 4-byte instruction alignment eliminates the need for
+additional padding NOPs.  When used with @option{-fpatchable-function-entry},
+the type identifier is placed before any patchable 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}.  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 unlike 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.
Signature · 1 line
2.34.1
author
#45 lore raw

RFC PATCH 7/7 kcfi: Add regression test suite

In reply to Kees Cook

Adds a test suite for KCFI (Kernel Control Flow Integrity) ABI.

Core Functionality Tests:
- kcfi-basics.c: Basic KCFI preamble generation, IPA analysis, and __kcfi_typeid_ symbol emission for external address-taken functions.
- kcfi-type-mangling.c: Type ID hashing validation with Itanium C++ ABI mangling for function signatures covering basic types, pointers, const qualifiers, multiple parameters, return types, arrays, function pointers, structs/unions/enums, typedef canonicalization, and recursive type definitions.
- kcfi-no-sanitize.c: no_sanitize("kcfi") attribute support for instrumentation disabling.
- kcfi-no-sanitize-inline.c: Regression test for preserving no_sanitize("kcfi") attributes during function inlining. Tests that functions marked with both no_sanitize("kcfi") and always_inline correctly suppress KCFI checks when inlined.
- kcfi-trap-section.c: Trap section (.kcfi_traps) generation and proper trap instruction placement.

Optimization and Code Generation Tests:
- kcfi-adjacency.c: Regression test ensuring KCFI checks remain immediately adjacent to indirect calls with no intervening instructions.
- kcfi-call-sharing.c: Prevents optimizer from incorrectly sharing KCFI checks between different function pointer types.
- kcfi-tail-calls.c: KCFI protection preservation when indirect calls are converted to tail calls under optimization.
- kcfi-ipa-robustness.c: IPA pass robustness with compiler-generated constructs like static_assert.

Addressing and Environment Tests:
- kcfi-complex-addressing.c: Structure member and array element function pointers with complex addressing modes.
- kcfi-pic-addressing.c: Position-independent code with PIC addressing modes and symbol references.
- kcfi-cold-partition.c: Cold function attributes and block partitioning with -freorder-blocks-and-partition.

Architecture-Specific Verification:
- kcfi-aarch64-esr.c: AArch64 ESR encoding in BRK instructions with proper exception register values.
- kcfi-offset-validation.c: Call site offset validation across architectures.
- kcfi-insn-sequence.c: Exact instruction sequence verification for KCFI runtime checks.

Patchable Function Entry Integration:
- kcfi-patchable-none.c: Standard case without patchable entries.
- kcfi-patchable-basic.c: Basic patchable entries (5,2 configuration).
- kcfi-patchable-prefix-only.c: Equal prefix/entry split (3,3 configuration).
- kcfi-patchable-entry-only.c: Entry-only NOPs (4,0 configuration).
- kcfi-patchable-medium.c: Medium prefix NOPs (8,4 configuration).
- kcfi-patchable-large.c: Large prefix NOPs (11,11 configuration).

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

---
 gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-esr.c  |  36 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c    |  83 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c       |  83 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c |  75 ++
 .../gcc.dg/kcfi/kcfi-cold-partition.c         | 133 +++
 .../gcc.dg/kcfi/kcfi-complex-addressing.c     | 116 +++
 .../gcc.dg/kcfi/kcfi-insn-sequence.c          |  42 +
 .../gcc.dg/kcfi/kcfi-ipa-robustness.c         |  54 ++
 .../gcc.dg/kcfi/kcfi-no-sanitize-inline.c     |  96 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c  |  39 +
 .../gcc.dg/kcfi/kcfi-offset-validation.c      |  41 +
 .../gcc.dg/kcfi/kcfi-patchable-basic.c        |  54 ++
 .../gcc.dg/kcfi/kcfi-patchable-entry-only.c   |  36 +
 .../gcc.dg/kcfi/kcfi-patchable-large.c        |  47 +
 .../gcc.dg/kcfi/kcfi-patchable-medium.c       |  52 ++
 .../gcc.dg/kcfi/kcfi-patchable-none.c         |  18 +
 .../gcc.dg/kcfi/kcfi-patchable-prefix-only.c  |  48 +
 .../gcc.dg/kcfi/kcfi-pic-addressing.c         |  98 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c   | 111 +++
 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c |  56 ++
 .../gcc.dg/kcfi/kcfi-type-mangling.c          | 864 ++++++++++++++++++
 gcc/testsuite/gcc.dg/kcfi/kcfi.exp            |  36 +
 22 files changed, 2218 insertions(+)
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-esr.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.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-insn-sequence.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-ipa-robustness.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-basic.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-entry-only.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-none.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-prefix-only.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-pic-addressing.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-type-mangling.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi.exp
gcc/testsuite/gcc.dg/kcfi/kcfi-aarch64-esr.c new file +36 -0
new file mode 100644
index 000000000000..6bbbba0431b0
@@ -0,0 +1,36 @@
+/* Test AArch64 KCFI ESR encoding in BRK instructions */
+/* { dg-do compile { target aarch64*-*-* } } */
+/* { dg-options "-fsanitize=kcfi" } */
+
+void target_function(int x, char y) {
+    /* Different signature to get different type ID */
+}
+
+int main() {
+    void (*func_ptr)(int, char) = target_function;
+
+    /* This should generate BRK with ESR encoding */
+    func_ptr(42, 'a');
+
+    return 0;
+}
+
+/* Should have KCFI preamble */
+/* { dg-final { scan-assembler "__cfi_target_function:" } } */
+
+/* AArch64 specific: Should have BRK instruction with proper ESR encoding
+   ESR format: 0x8000 | ((type_reg & 31) << 5) | (addr_reg & 31)
+
+   Test the ESR encoding by checking for the expected value.
+   Since we know this test uses x2, we expect ESR = 0x8000 | (17<<5) | 2 = 33314
+
+   A truly dynamic test would need to extract the register from blr and compute
+   the corresponding ESR, but DejaGnu's regex limitations make this complex.
+   This test validates the specific case and documents the encoding.
+   */
+/* { dg-final { scan-assembler "blr\\s+x2" { target aarch64*-*-* } } } */
+/* { dg-final { scan-assembler "brk\\s+#33314" { target aarch64*-*-* } } } */
+
+/* Should have KCFI check with type comparison */
+/* { dg-final { scan-assembler {ldur\t*w16, \[x[0-9]+, #-4\]} { target aarch64*-*-* } } } */
+/* { dg-final { scan-assembler {cmp\t*w16, w17} { target aarch64*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c new file +83 -0

83 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c new file +83 -0

83 lines not on this page · raw message

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

75 lines not on this page · raw message

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

133 lines not on this page · raw message

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

116 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-insn-sequence.c new file +42 -0

42 lines not on this page · raw message

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-no-sanitize-inline.c new file +96 -0

96 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c new file +39 -0
new file mode 100644
index 000000000000..1a48fd1407f3
@@ -0,0 +1,39 @@
+/* Test KCFI with no_sanitize attribute */
+/* { dg-do compile } */
+/* { dg-options "-fsanitize=kcfi" } */
+
+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:" } } */
+
+/* caller_with_checks() should generate KCFI check (1 check) */
+/* caller_no_checks() should NOT generate KCFI check due to no_sanitize attribute */
+/* Total: 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-*-* } } } */
+/* { dg-final { scan-assembler-times {lw\tt1, -[0-9]+\(} 1 { target riscv*-*-* } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-offset-validation.c new file +41 -0

41 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-basic.c new file +54 -0

54 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-entry-only.c new file +36 -0
new file mode 100644
index 000000000000..68a42dd32995
@@ -0,0 +1,36 @@
+/* Test KCFI with patchable function entries - entry NOPs only */
+/* { dg-do compile } */
+/* { dg-options "-fsanitize=kcfi -fpatchable-function-entry=4,0" } */
+
+void test_function(void) {
+    /* All NOPs are entry NOPs, no prefix NOPs for KCFI */
+}
+
+int main() {
+    test_function();
+    return 0;
+}
+
+/* Should NOT have KCFI preamble (no prefix NOPs) */
+/* { dg-final { scan-assembler-not "__cfi_test_function:" } } */
+
+/* x86_64: All 4 NOPs are entry NOPs - should have exactly 4 entry NOPs */
+/* { dg-final { scan-assembler {\.LPFE[0-9]+:\n\t*nop\n\t*nop\n\t*nop\n\t*nop\n\t*pushq} { target x86_64-*-* } } } */
+
+/* x86_64: No prefix NOPs - function type should come immediately before function */
+/* { dg-final { scan-assembler {\.type\t*test_function, @function\n*test_function:} { target x86_64-*-* } } } */
+
+/* AArch64: All 4 NOPs are entry NOPs - should have exactly 4 entry NOPs */
+/* { dg-final { scan-assembler {\.LPFE[0-9]+:\n\t*nop\n\t*nop\n\t*nop\n\t*nop\n\t*stp} { target aarch64*-*-* } } } */
+
+/* AArch64: No prefix NOPs - function type should come immediately before function */
+/* { dg-final { scan-assembler {\.type\t*test_function, %function\n*test_function:} { target aarch64*-*-* } } } */
+
+/* RISC-V: All 4 NOPs are entry NOPs */
+/* { dg-final { scan-assembler {\.LPFE[0-9]+:\n\t*nop\n\t*nop\n\t*nop\n\t*nop\n\.LFB} { target riscv*-*-* } } } */
+
+/* RISC-V: No prefix NOPs - function type should come immediately before function */
+/* { dg-final { scan-assembler {\.type\t*test_function, @function\n*test_function:} { target riscv*-*-* } } } */
+
+/* Should have patchable function entry section */
+/* { dg-final { scan-assembler "__patchable_function_entries" } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-large.c new file +47 -0

47 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-medium.c new file +52 -0

52 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-none.c new file +18 -0
new file mode 100644
index 000000000000..01a611ca754d
@@ -0,0 +1,18 @@
+/* Test KCFI without patchable function entries - standard case */
+/* { dg-do compile } */
+/* { dg-options "-fsanitize=kcfi" } */
+
+void test_function(void) {
+    /* Standard KCFI without patchable entries */
+}
+
+int main() {
+    test_function();
+    return 0;
+}
+
+/* Should have KCFI preamble */
+/* { dg-final { scan-assembler "__cfi_test_function:" } } */
+
+/* Should NOT have patchable function entry section */
+/* { dg-final { scan-assembler-not "__patchable_function_entries" } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-prefix-only.c new file +48 -0

48 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-pic-addressing.c new file +98 -0

98 lines not on this page · raw message

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

111 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c new file +56 -0

56 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-type-mangling.c new file +864 -0

864 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi.exp new file +36 -0
new file mode 100644
index 000000000000..2aebcbe1c01b
@@ -0,0 +1,36 @@
+#   Copyright (C) 2025 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/>.
+
+# GCC testsuite for KCFI (Kernel Control Flow Integrity) tests.
+
+# Load support procs.
+load_lib gcc-dg.exp
+
+# If a testcase doesn't have special options, use these.
+global DEFAULT_CFLAGS
+if ![info exists DEFAULT_CFLAGS] then {
+    set DEFAULT_CFLAGS ""
+}
+
+# Initialize `dg'.
+dg-init
+
+# Main loop.
+dg-runtest [lsort [glob -nocomplain $srcdir/$subdir/*.c]] \
+	"" $DEFAULT_CFLAGS
+
+# All done.
+dg-finish
Signature · 1 line
2.34.1