Skip to contentSkip to conversation

Introduce Kernel Control Flow Integrity ABI [PR107048]

PATCH Superseded Kees Cook 7 participants 32 messages Sep 5, 2025 – Oct 1, 2025 RISC-V

v2 of 17 Superseded Latest is v17 →

lore
Share & tools
lore

Kees Cook

author
#0 lore raw

v2 cover Introduce Kernel Control Flow Integrity ABI [PR107048]

Hi!

Here is v2, which is substantially changed compared to the RFC[1].

This series implements[2][3] 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.

The major change here is getting (what seems to be) proper KCFI RTL working on the back end so that expansion Just Works. This meant all the strange hacks I had for handling corner cases mostly went away, and I was left with an optimizer that actually wanted to help me. :)

I revamped the mangler to do the hashing directly, and incorporated design details into kcfi.cc (rather than putting it all in the commit log). I'm using proper target hooks.

I've tested all 4 architectures now, and everything is working for me.

I'm still unsure about the arm32 and riscv RTL expansion: it seems strange that I have to extract the CALL from PARALLEL patterns, but everything I tried to match an PARALLEL kept failling.

For the commits, I ended up hand-building the ChangeLog trailers... I assume there is a better way to do this, but I think I was just too dense to find it. :P

Thanks!

-Kees

[1] https://lore.kernel.org/linux-hardening/[email protected]/
[2] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=107048
[3] https://github.com/KSPP/linux/issues/369

Kees Cook (7):
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
arm: Add ARM 32-bit Kernel Control Flow Integrity implementation
riscv: Add RISC-V Kernel Control Flow Integrity implementation
kcfi: Add regression test suite

 gcc/kcfi.h                                    |   47 +
 gcc/kcfi.cc                                   |  764 ++++++++++++
 gcc/Makefile.in                               |    2 +
 gcc/config/aarch64/aarch64-protos.h           |    5 +
 gcc/config/arm/arm-protos.h                   |    4 +
 gcc/config/i386/i386-protos.h                 |    1 +
 gcc/config/i386/i386.h                        |    3 +-
 gcc/config/riscv/riscv-protos.h               |    3 +
 gcc/flag-types.h                              |    2 +
 gcc/gimple.h                                  |   21 +
 gcc/mangle.h                                  |   32 +
 gcc/tree-pass.h                               |    3 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c    |   73 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c       |  101 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c |   85 ++
 .../gcc.dg/kcfi/kcfi-cold-partition.c         |  137 +++
 .../gcc.dg/kcfi/kcfi-complex-addressing.c     |  125 ++
 .../gcc.dg/kcfi/kcfi-ipa-robustness.c         |   55 +
 .../gcc.dg/kcfi/kcfi-move-preservation.c      |   56 +
 .../gcc.dg/kcfi/kcfi-no-sanitize-inline.c     |  101 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c  |   41 +
 .../gcc.dg/kcfi/kcfi-offset-validation.c      |   50 +
 .../gcc.dg/kcfi/kcfi-patchable-basic.c        |   71 ++
 .../gcc.dg/kcfi/kcfi-patchable-entry-only.c   |   64 +
 .../gcc.dg/kcfi/kcfi-patchable-large.c        |   52 +
 .../gcc.dg/kcfi/kcfi-patchable-medium.c       |   61 +
 .../gcc.dg/kcfi/kcfi-patchable-prefix-only.c  |   61 +
 .../gcc.dg/kcfi/kcfi-pic-addressing.c         |  105 ++
 .../gcc.dg/kcfi/kcfi-retpoline-r11.c          |   51 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c   |  143 +++
 .../gcc.dg/kcfi/kcfi-trap-encoding.c          |   56 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c |   43 +
 .../gcc.dg/kcfi/kcfi-type-mangling.c          | 1064 +++++++++++++++++
 gcc/c-family/c-attribs.cc                     |   12 +
 gcc/config/aarch64/aarch64.cc                 |  115 ++
 gcc/config/aarch64/aarch64.md                 |   64 +-
 gcc/config/arm/arm.cc                         |  144 +++
 gcc/config/arm/arm.md                         |   62 +
 gcc/config/i386/i386-expand.cc                |   21 +-
 gcc/config/i386/i386.cc                       |  118 ++
 gcc/config/i386/i386.md                       |   62 +-
 gcc/config/riscv/riscv.cc                     |  147 +++
 gcc/config/riscv/riscv.md                     |   74 +-
 gcc/df-scan.cc                                |    6 +
 gcc/doc/invoke.texi                           |  102 ++
 gcc/doc/tm.texi                               |   31 +
 gcc/doc/tm.texi.in                            |   12 +
 gcc/final.cc                                  |    3 +
 gcc/mangle.cc                                 |  512 ++++++++
 gcc/opts.cc                                   |    1 +
 gcc/passes.cc                                 |    1 +
 gcc/passes.def                                |    3 +
 gcc/rtl.def                                   |    6 +
 gcc/rtlanal.cc                                |    5 +
 gcc/target.def                                |   38 +
 gcc/testsuite/gcc.dg/kcfi/kcfi.exp            |   36 +
 gcc/toplev.cc                                 |   11 +
 gcc/tree-inline.cc                            |   10 +
 gcc/varasm.cc                                 |   46 +-
 59 files changed, 5092 insertions(+), 32 deletions(-)
 create mode 100644 gcc/kcfi.h
 create mode 100644 gcc/kcfi.cc
 create mode 100644 gcc/mangle.h
 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-ipa-robustness.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-move-preservation.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize-inline.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-offset-validation.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-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-prefix-only.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-pic-addressing.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-retpoline-r11.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-encoding.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/mangle.cc
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi.exp
Signature · 1 line
2.34.1
author
#1 lore raw

PATCH v2 1/7 mangle: Introduce C typeinfo mangling API

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, but then do hashing, which is needed by KCFI to get a 32-bit hash value for a given function prototype. Optionally report the mangled string to the dumpfile.

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/ChangeLog:

* Makefile.in: Add mangle.o to build.
* mangle.cc: New file. Implement C typeinfo mangling for KCFI.
* mangle.h: New file. Export hash_function_type function.

---
 gcc/Makefile.in |   1 +
 gcc/mangle.h    |  32 +++
 gcc/mangle.cc   | 512 ++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 545 insertions(+)
 create mode 100644 gcc/mangle.h
 create mode 100644 gcc/mangle.cc
gcc/Makefile.in +1 -0
index d2744db843d7..4c12ac68d979 100644
@@ -1617,6 +1617,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 +32 -0
new file mode 100644
index 000000000000..fe7916dd68e0
@@ -0,0 +1,32 @@
+/* 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"
+#include <string>
+
+/* Function type hashing following Itanium C++ ABI conventions.
+   Returns the FNV-1a hash of the mangled type string.
+   Builds the actual string only if dump is active for debugging.
+   Optional fndecl parameter provides function context for error reporting.  */
+extern uint32_t hash_function_type (tree fntype, tree fndecl = NULL_TREE);
+
+#endif /* GCC_MANGLE_H */
gcc/mangle.cc new file +512 -0

512 lines not on this page · raw message

Signature · 1 line
2.34.1
#2 lore raw

Re: [PATCH v2 1/7] mangle: Introduce C typeinfo mangling API

Quoted 260 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, but then do hashing, which is needed by KCFI to get a 32-bit hash value for a given function prototype. Optionally report the mangled string to the dumpfile.

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/ChangeLog:

* Makefile.in: Add mangle.o to build.
* mangle.cc: New file. Implement C typeinfo mangling for KCFI.
* mangle.h: New file. Export hash_function_type function.

---
 gcc/Makefile.in |   1 +
 gcc/mangle.h    |  32 +++
 gcc/mangle.cc   | 512 ++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 545 insertions(+)
 create mode 100644 gcc/mangle.h
 create mode 100644 gcc/mangle.cc
gcc/Makefile.in +1 -0
index d2744db843d7..4c12ac68d979 100644
@@ -1617,6 +1617,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 +32 -0
new file mode 100644
index 000000000000..fe7916dd68e0
@@ -0,0 +1,32 @@
+/* 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"
+#include <string>
+
+/* Function type hashing following Itanium C++ ABI conventions.
+   Returns the FNV-1a hash of the mangled type string.
+   Builds the actual string only if dump is active for debugging.
+   Optional fndecl parameter provides function context for error reporting.  */
+extern uint32_t hash_function_type (tree fntype, tree fndecl = NULL_TREE);
+
+#endif /* GCC_MANGLE_H */
gcc/mangle.cc new file +157 -0
new file mode 100644
index 000000000000..8f177a415e15
@@ -0,0 +1,512 @@
+/* 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"
+#include "dumpfile.h"
+#include "print-tree.h"
+
+/* Current function context for better error reporting.  */
+static tree current_function_context = NULL_TREE;
+
+/* Helper to update FNV-1a hash with a single character.  */
+static inline void
+fnv1a_hash_char (uint32_t *hash_state, unsigned char c)
+{
+  *hash_state ^= c;
+  *hash_state *= 16777619U; /* FNV-1a 32-bit prime.  */
+}
+
+/* Helper to append character to optional string and update hash using FNV-1a.  */
+static void
+append_char (char c, std::string *out_str, uint32_t *hash_state)
+{
+  if (out_str)
+    *out_str += c;
+  fnv1a_hash_char (hash_state, (unsigned char) c);
+}
+
+/* Helper to append string to optional string and update hash using FNV-1a.  */
+static void
+append_string (const char *str, std::string *out_str, uint32_t *hash_state)
+{
+  if (out_str)
+    *out_str += str;
+  for (const char *p = str; *p; p++)
+    fnv1a_hash_char (hash_state, (unsigned char) *p);
+}
+
+/* Forward declaration for recursive type mangling.  */
+static void mangle_type (tree type, std::string *out_str, uint32_t *hash_state);
+
+/* Mangle a builtin type following Itanium C++ ABI for C types.  */
+static void
+mangle_builtin_type (tree type, std::string *out_str, uint32_t *hash_state)
+{
+  gcc_assert (type != NULL_TREE);
+
+  switch (TREE_CODE (type))
+    {
+    case VOID_TYPE:
+      append_char ('v', out_str, hash_state);
+      return;
+
+    case BOOLEAN_TYPE:
+      append_char ('b', out_str, hash_state);
+      return;
+
+    case INTEGER_TYPE:
+      /* Handle standard integer types using Itanium ABI codes.  */
+      if (type == char_type_node)
+       append_char ('c', out_str, hash_state);
+      else if (type == signed_char_type_node)
+       append_char ('a', out_str, hash_state);
+      else if (type == unsigned_char_type_node)
+       append_char ('h', out_str, hash_state);
+      else if (type == short_integer_type_node)
+       append_char ('s', out_str, hash_state);
+      else if (type == short_unsigned_type_node)
+       append_char ('t', out_str, hash_state);
+      else if (type == integer_type_node)
+       append_char ('i', out_str, hash_state);
+      else if (type == unsigned_type_node)
+       append_char ('j', out_str, hash_state);
+      else if (type == long_integer_type_node)
+       append_char ('l', out_str, hash_state);
+      else if (type == long_unsigned_type_node)
+       append_char ('m', out_str, hash_state);
+      else if (type == long_long_integer_type_node)
+       append_char ('x', out_str, hash_state);
+      else if (type == long_long_unsigned_type_node)
+       append_char ('y', out_str, hash_state);
+      else
+       {
+         /* Fallback for other integer types - use precision-based encoding.  */
+         append_char ('i', out_str, hash_state);
+         append_string (std::to_string (TYPE_PRECISION (type)).c_str (), out_str, hash_state);
+       }
+      return;
+
+    case REAL_TYPE:
+      if (type == float_type_node)
+       append_char ('f', out_str, hash_state);
+      else if (type == double_type_node)
+       append_char ('d', out_str, hash_state);
+      else if (type == long_double_type_node)
+       append_char ('e', out_str, hash_state);
+      else
+       {
+         /* Fallback for other real types.  */
+         append_char ('f', out_str, hash_state);
+         append_string (std::to_string (TYPE_PRECISION (type)).c_str (), out_str, hash_state);
+       }
+      return;
+
+    case VECTOR_TYPE:
+      {
+       /* Handle vector types following Itanium C++ ABI:
+          Dv<num-elements>_<element-type-encoding>
+          Example: uint8x16_t → Dv16_h (vector of 16 unsigned char)  */
+       tree vector_size = TYPE_SIZE_UNIT (type);
+       tree element_type = TREE_TYPE (type);
+       tree element_size = TYPE_SIZE_UNIT (element_type);
+
+       if (vector_size && element_size &&
+           TREE_CODE (vector_size) == INTEGER_CST &&
+           TREE_CODE (element_size) == INTEGER_CST)
+         {
+           append_char ('D', out_str, hash_state);
+           append_char ('v', out_str, hash_state);
+
+           unsigned HOST_WIDE_INT vec_bytes = tree_to_uhwi (vector_size);
+           unsigned HOST_WIDE_INT elem_bytes = tree_to_uhwi (element_size);
+           unsigned HOST_WIDE_INT num_elements = vec_bytes / elem_bytes;
+
+           /* Append number of elements.  */
+           append_string (std::to_string (num_elements).c_str (), out_str, hash_state);
+           append_char ('_', out_str, hash_state);
+
+           /* Recursively mangle the element type.  */
+           mangle_type (element_type, out_str, hash_state);
+           return;
+         }
+       /* Fail for vectors with unknown size.  */
+      }

gcc/mangle.cc line 167

Quoted 10 lines
gcc/mangle.cc new file +10 -0
+      break;
+
+    default:
+      break;
+    }
+
+  /* Unknown builtin type - this should never happen in a well-formed C program.  */
+  debug_tree (type);
+  internal_error ("mangle: Unknown builtin type in function %qD - please report this as a bug",
+                  current_function_context);

This should NOT be internal_error but rather sorry.

Quoted 207 lines
gcc/mangle.cc new file +207 -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 (tree type, std::string *out_str, uint32_t *hash_state)
+{
+  gcc_assert (type != NULL_TREE);
+
+  /* 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.  */
+       append_char ('P', out_str, hash_state);
+
+       /* 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)
+             append_char ('r', out_str, hash_state);
+           if (TYPE_QUALS (pointed_to_type) & TYPE_QUAL_VOLATILE)
+             append_char ('V', out_str, hash_state);
+           if (TYPE_QUALS (pointed_to_type) & TYPE_QUAL_CONST)
+             append_char ('K', out_str, hash_state);
+         }
+
+       /* 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 (target_type, out_str, hash_state);
+       break;
+      }
+
+    case ARRAY_TYPE:
+      /* Array type: 'A' + size + '_' + element type (simplified).  */
+      append_char ('A', out_str, hash_state);
+      if (TYPE_DOMAIN (type) && TYPE_MAX_VALUE (TYPE_DOMAIN (type)))
+       {
+         tree max_val = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
+         /* Check if array size is a compile-time constant to handle VLAs safely.  */
+         if (TREE_CODE (max_val) == INTEGER_CST && tree_fits_shwi_p (max_val))
+           {
+             HOST_WIDE_INT size = tree_to_shwi (max_val) + 1;
+             append_string (std::to_string ((long) size).c_str (), out_str, hash_state);
+           }
+         /* For VLAs or non-constant dimensions, emit empty size (A_).  */
+         append_char ('_', out_str, hash_state);
+       }
+      else
+       {
+         /* No domain or no max value - emit A_.  */
+         append_char ('_', out_str, hash_state);
+       }
+      mangle_type (TREE_TYPE (type), out_str, hash_state);
+      break;
+
+    case REFERENCE_TYPE:
+      /* Reference type: 'R' + referenced type.
+         Note: We must handle references to builtin types including compiler
+         builtins like __builtin_va_list used in functions like va_start. */
+      append_char ('R', out_str, hash_state);
+      mangle_type (TREE_TYPE (type), out_str, hash_state);
+      break;
+
+    case FUNCTION_TYPE:
+      {
+       /* Function type: 'F' + return type + parameter types + 'E' */
+       append_char ('F', out_str, hash_state);
+       mangle_type (TREE_TYPE (type), out_str, hash_state);
+
+       /* Add parameter types.  */
+       tree param_types = TYPE_ARG_TYPES (type);
+
+       if (param_types == NULL_TREE)
+         {
+           /* func() - no parameter list (could be variadic). */
+         }
+       else
+         {
+           bool found_real_params = false;
+           for (tree param = param_types; param; 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 (void_type_node, out_str, hash_state);
+                     }
+                   /* 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 (canonical_param_type, out_str, hash_state);
+             }
+         }
+
+       /* Check if this is a variadic function and add 'z' marker.  */
+       if (stdarg_p (type))
+         {
+           append_char ('z', out_str, hash_state);
+         }
+
+       append_char ('E', out_str, hash_state);
+       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)

gcc/mangle.cc line 384

Quoted 10 lines
gcc/mangle.cc new file +10 -0
+             {
+               /* 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];

I am not a fan of a static variable here. Why not just a stack variable?

Quoted 69 lines
gcc/mangle.cc new file +69 -0
+
+           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;
+         }
+

gcc/mangle.cc line 463

Quoted 10 lines
gcc/mangle.cc new file +10 -0
+       if (name)
+         {
+           append_string (std::to_string (strlen (name)).c_str (), out_str, hash_state);
+           append_string (name, out_str, hash_state);
+         }
+       else
+         {
+           /* Always show diagnostic information for missing struct names.  */
+           debug_tree (type);
+           internal_error ("mangle: Missing case in struct name extraction - please report this as a bug");

Again sorry rather than internal_error.

I still think it would be better if the hashing and mangling be one step rather than 2 separate steps.
Especially since this is only used for the hashing and will most likely only used there ever.

Thanks,
Andrew Pinski

Quoted 52 lines
gcc/mangle.cc new file +49 -1
+         }
+       break;
+      }
+
+    default:
+      /* Handle builtin types.  */
+      mangle_builtin_type (type, out_str, hash_state);
+      break;
+    }
+}
+
+/* Compute canonical function type hash using Itanium C++ ABI mangling.  */
+uint32_t
+hash_function_type (tree fntype, tree fndecl)
+{
+  gcc_assert (fntype);
+  gcc_assert (TREE_CODE (fntype) == FUNCTION_TYPE);
+
+  std::string result;
+  std::string *out_str = nullptr;
+  uint32_t hash_state = 2166136261U; /* FNV-1a 32-bit offset basis.  */
+
+  /* Only build string if dump is active.  */
+  if (dump_file && (dump_flags & TDF_DETAILS))
+    {
+      result.reserve (32);
+      out_str = &result;
+    }
+
+  /* Store function context for error reporting.  */
+  current_function_context = fndecl;
+
+  /* Typeinfo for a function prototype.  */
+  append_string ("_ZTS", out_str, &hash_state);
+
+  mangle_type (fntype, out_str, &hash_state);
+
+  /* Clear function context.  */
+  current_function_context = NULL_TREE;
+
+  /* Output to dump file if enabled.  */
+  if (dump_file && (dump_flags & TDF_DETAILS))
+    {
+      fprintf (dump_file, "KCFI type ID: mangled='%s' typeid=0x%08x\n",
+              result.c_str (), hash_state);
+    }
+
+  return hash_state;
+}
--

2.34.1

author
#3 lore raw

Re: [PATCH v2 1/7] mangle: Introduce C typeinfo mangling API

Quoted 8 lines · Andrew Pinski

gcc/mangle.cc line 167

Quoted 5 lines · Kees Cook
gcc/mangle.cc new file +5 -0
+
+  /* Unknown builtin type - this should never happen in a well-formed C program.  */
+  debug_tree (type);
+  internal_error ("mangle: Unknown builtin type in function %qD - please report this as a bug",
+                  current_function_context);

This should NOT be internal_error but rather sorry.

Ah, heh. I switched to internal_error because you'd suggested it in the last version. Maybe I misunderstood where I should be using sorry vs internal_error.

Quoted 5 lines

gcc/mangle.cc line 384

Quoted 3 lines
gcc/mangle.cc new file +3 -0
+       if (!name && !TYPE_NAME (type))
+         {
+           static char anon_name[128];

I am not a fan of a static variable here. Why not just a stack variable?

Oh, whoops. I will fix that.

Quoted 11 lines

gcc/mangle.cc line 463

Quoted 4 lines
gcc/mangle.cc new file +4 -0
+         {
+           /* Always show diagnostic information for missing struct names.  */
+           debug_tree (type);
+           internal_error ("mangle: Missing case in struct name extraction - please report this as a bug");

Again sorry rather than internal_error.

I still think it would be better if the hashing and mangling be one step rather than 2 separate steps.
Especially since this is only used for the hashing and will most likely only used there ever.

In this version the hashing happens immediately. No full string is built unless the dumpfile is enabled.

-Kees

Signature · 1 line
Kees Cook
author
#4 lore raw

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

In reply to Kees Cook

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

See the start of kcfi.cc for design details.

gcc/ChangeLog:

* kcfi.h: New file with KCFI public interface declarations.
* kcfi.cc: New file implementing Kernel Control Flow Integrity infrastructure.
* Makefile.in (OBJS): Add kcfi.o.
* flag-types.h (enum sanitize_code): Add SANITIZE_KCFI.
* gimple.h (enum gf_mask): Add GF_CALL_INLINED_FROM_KCFI_NOSANTIZE. (gimple_call_set_inlined_from_kcfi_nosantize): New function. (gimple_call_inlined_from_kcfi_nosantize_p): New function.
* tree-pass.h Add kcfi passes.
* c-family/c-attribs.cc: Include asan.h. (handle_patchable_function_entry_attribute): Add error for using patchable_function_entry attribute with -fsanitize=kcfi.
* df-scan.cc (df_uses_record): Add KCFI case to handle KCFI RTL patterns and process wrapped RTL.
* doc/invoke.texi (fsanitize=kcfi): Add documentation for KCFI sanitizer option.
* doc/tm.texi.in: Add Kernel Control Flow Integrity section with TARGET_KCFI_SUPPORTED, TARGET_KCFI_MASK_TYPE_ID, TARGET_KCFI_EMIT_TYPE_ID hooks.
* doc/tm.texi: Regenerate.
* final.cc (call_from_call_insn): Add KCFI case to handle KCFI-wrapped calls.
* opts.cc (sanitizer_opts): Add kcfi entry.
* passes.cc: Include kcfi.h.
* passes.def: Add KCFI passes (GIMPLE and IPA).
* rtl.def (KCFI): Add new RTL code for KCFI instrumentation.
* rtlanal.cc (rtx_cost): Add KCFI case.
* target.def: Add KCFI target hooks.
* toplev.cc (process_options): Add KCFI option processing.
* tree-inline.cc: Include kcfi.h and asan.h.
(copy_bb): Handle KCFI no_sanitize attribute propagation during inlining.
* varasm.cc (assemble_start_function): Emit KCFI preambles. (assemble_external_real): Emit KCFI typeid symbols. (default_elf_asm_named_section): Handle .kcfi_traps using SECTION_LINK_ORDER flag.

---
 gcc/kcfi.h                |  47 +++
 gcc/kcfi.cc               | 764 ++++++++++++++++++++++++++++++++++++++
 gcc/Makefile.in           |   1 +
 gcc/flag-types.h          |   2 +
 gcc/gimple.h              |  21 ++
 gcc/tree-pass.h           |   3 +
 gcc/c-family/c-attribs.cc |  12 +
 gcc/df-scan.cc            |   6 +
 gcc/doc/invoke.texi       |  35 ++
 gcc/doc/tm.texi           |  31 ++
 gcc/doc/tm.texi.in        |  12 +
 gcc/final.cc              |   3 +
 gcc/opts.cc               |   1 +
 gcc/passes.cc             |   1 +
 gcc/passes.def            |   3 +
 gcc/rtl.def               |   6 +
 gcc/rtlanal.cc            |   5 +
 gcc/target.def            |  38 ++
 gcc/toplev.cc             |  11 +
 gcc/tree-inline.cc        |  10 +
 gcc/varasm.cc             |  46 ++-
 21 files changed, 1048 insertions(+), 10 deletions(-)
 create mode 100644 gcc/kcfi.h
 create mode 100644 gcc/kcfi.cc
gcc/kcfi.h new file +47 -0
new file mode 100644
index 000000000000..17ec59a1a3b8
@@ -0,0 +1,47 @@
+/* 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"
+
+/* Common helper for RTL patterns to emit .kcfi_traps section entry.
+   Call after emitting trap label and instruction with the trap symbol
+   reference.  */
+extern void kcfi_emit_traps_section (FILE *file, rtx trap_label_sym);
+
+/* Extract KCFI type ID from current GIMPLE statement.  */
+extern rtx kcfi_get_call_type_id (void);
+
+/* Emit KCFI type ID symbol for address-taken functions.  */
+extern void emit_kcfi_typeid_symbol (FILE *asm_file, tree decl,
+				     const char *name);
+
+/* Emit KCFI preamble.  */
+extern void kcfi_emit_preamble (FILE *file, tree decl,
+				const char *actual_fname);
+
+/* For calculating callsite offset.  */
+extern HOST_WIDE_INT kcfi_patchable_entry_prefix_nops;
+
+#endif /* GCC_KCFI_H */
gcc/kcfi.cc new file +764 -0

764 lines not on this page · raw message

gcc/Makefile.in +1 -0
index 4c12ac68d979..84bbc4223734 100644
@@ -1591,6 +1591,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 bf681c3e8153..c3c0bc61ee3e 100644
@@ -337,6 +337,8 @@ enum sanitize_code {
   SANITIZE_KERNEL_HWADDRESS = 1UL << 30,
   /* Shadow Call Stack.  */
   SANITIZE_SHADOW_CALL_STACK = 1UL << 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/gimple.h +21 -0
index da32651ea017..cef915b9164f 100644
@@ -142,6 +142,7 @@ enum gf_mask {
     GF_CALL_ALLOCA_FOR_VAR	= 1 << 5,
     GF_CALL_INTERNAL		= 1 << 6,
     GF_CALL_CTRL_ALTERING       = 1 << 7,
+    GF_CALL_INLINED_FROM_KCFI_NOSANTIZE = 1 << 8,
     GF_CALL_MUST_TAIL_CALL	= 1 << 9,
     GF_CALL_BY_DESCRIPTOR	= 1 << 10,
     GF_CALL_NOCF_CHECK		= 1 << 11,
@@ -3487,6 +3488,26 @@ gimple_call_from_thunk_p (gcall *s)
   return (s->subcode & GF_CALL_FROM_THUNK) != 0;
 }
 
+/* If INLINED_FROM_KCFI_NOSANTIZE_P is true, mark GIMPLE_CALL S as being
+   inlined from a function with no_sanitize("kcfi").  */
+
+inline void
+gimple_call_set_inlined_from_kcfi_nosantize (gcall *s, bool inlined_from_kcfi_nosantize_p)
+{
+  if (inlined_from_kcfi_nosantize_p)
+    s->subcode |= GF_CALL_INLINED_FROM_KCFI_NOSANTIZE;
+  else
+    s->subcode &= ~GF_CALL_INLINED_FROM_KCFI_NOSANTIZE;
+}
+
+/* Return true if GIMPLE_CALL S was inlined from a function with
+   no_sanitize("kcfi").  */
+
+inline bool
+gimple_call_inlined_from_kcfi_nosantize_p (const gcall *s)
+{
+  return (s->subcode & GF_CALL_INLINED_FROM_KCFI_NOSANTIZE) != 0;
+}
 
 /* If FROM_NEW_OR_DELETE_P is true, mark GIMPLE_CALL S as being a call
    to operator new or delete created from a new or delete expression.  */
gcc/tree-pass.h +3 -0
index 1c68a69350df..fbf235adada3 100644
@@ -357,6 +357,8 @@ extern gimple_opt_pass *make_pass_tsan (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_tsan_O0 (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_sancov (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_sancov_O0 (gcc::context *ctxt);
+extern gimple_opt_pass *make_pass_kcfi (gcc::context *ctxt);
+extern gimple_opt_pass *make_pass_kcfi_O0 (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_lower_cf (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_refactor_eh (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_lower_eh (gcc::context *ctxt);
@@ -544,6 +546,7 @@ extern ipa_opt_pass_d *make_pass_ipa_odr (gcc::context *ctxt);
 extern ipa_opt_pass_d *make_pass_ipa_reference (gcc::context *ctxt);
 extern ipa_opt_pass_d *make_pass_ipa_pure_const (gcc::context *ctxt);
 extern simple_ipa_opt_pass *make_pass_ipa_pta (gcc::context *ctxt);
+extern simple_ipa_opt_pass *make_pass_ipa_kcfi (gcc::context *ctxt);
 extern simple_ipa_opt_pass *make_pass_ipa_tm (gcc::context *ctxt);
 extern simple_ipa_opt_pass *make_pass_target_clone (gcc::context *ctxt);
 extern simple_ipa_opt_pass *make_pass_dispatcher_calls (gcc::context *ctxt);
gcc/c-family/c-attribs.cc +12 -0
index 1e3a94ed9493..a12cfe48772a 100644
@@ -48,6 +48,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "gimplify.h"
 #include "tree-pretty-print.h"
 #include "gcc-rich-location.h"
+#include "asan.h"
 #include "gcc-urlifier.h"
 
 static tree handle_packed_attribute (tree *, tree, tree, int, bool *);
@@ -6508,6 +6509,17 @@ static tree
 handle_patchable_function_entry_attribute (tree *, tree name, tree args,
 					   int, bool *no_add_attrs)
 {
+  /* Function-specific patchable_function_entry attribute is incompatible
+     with KCFI because KCFI callsites cannot know about function-specific
+     patchable entry settings on a preamble in a different translation
+     unit.  */
+  if (sanitize_flags_p (SANITIZE_KCFI))
+    {
+      error ("%qE attribute cannot be used with %<-fsanitize=kcfi%>", name);
+      *no_add_attrs = true;
+      return NULL_TREE;
+    }
+
   for (; args; args = TREE_CHAIN (args))
     {
       tree val = TREE_VALUE (args);
gcc/df-scan.cc +6 -0
index 1e4c6a2a4fb5..0e9c75df48dd 100644
@@ -2851,6 +2851,12 @@ df_uses_record (class df_collection_rec *collection_rec,
       /* If we're clobbering a REG then we have a def so ignore.  */
       return;
 
+    case KCFI:
+      /* KCFI wraps other RTL - process the wrapped RTL.  */
+      df_uses_record (collection_rec, &XEXP (x, 0), ref_type, bb, insn_info, flags);
+      /* The type ID operand (XEXP (x, 1)) doesn't contain register uses.  */
+      return;
+
     case MEM:
       df_uses_record (collection_rec,
 		      &XEXP (x, 0), DF_REF_REG_MEM_LOAD,
gcc/doc/invoke.texi +35 -0
index 56c4fa86e346..cd70e6351a4e 100644
@@ -18382,6 +18382,41 @@ 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.
+
+Note that KCFI is incompatible with function-specific
+@code{patchable_function_entry} attributes because KCFI call sites
+cannot know about function-specific patchable entry settings in different
+translation units.  Only the global @option{-fpatchable-function-entry}
+command-line option is supported with KCFI.
+
+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/doc/tm.texi +31 -0
index 37642680f423..69603fdad090 100644
@@ -3166,6 +3166,7 @@ This describes the stack layout and calling conventions.
 * Tail Calls::
 * Shrink-wrapping separate components::
 * Stack Smashing Protection::
+* Kernel Control Flow Integrity::
 * Miscellaneous Register Hooks::
 @end menu
 
@@ -5432,6 +5433,36 @@ should be allocated from heap memory and consumers should release them.
 The result will be pruned to cases with PREFIX if not NULL.
 @end deftypefn
 
+@node Kernel Control Flow Integrity
+@subsection Kernel Control Flow Integrity
+@cindex kernel control flow integrity
+@cindex KCFI
+
+@deftypefn {Target Hook} bool TARGET_KCFI_SUPPORTED (void)
+Return true if the target supports Kernel Control Flow Integrity (KCFI).
+This hook indicates whether the target has implemented the necessary RTL
+patterns and infrastructure to support KCFI instrumentation.  The default
+implementation returns false.
+@end deftypefn
+
+@deftypefn {Target Hook} uint32_t TARGET_KCFI_MASK_TYPE_ID (uint32_t @var{type_id})
+Apply architecture-specific masking to KCFI type ID.  This hook allows
+targets to apply bit masks or other transformations to the computed KCFI
+type identifier to match the target's specific requirements.  The default
+implementation returns the type ID unchanged.
+@end deftypefn
+
+@deftypefn {Target Hook} int TARGET_KCFI_EMIT_TYPE_ID (FILE *@var{file}, uint32_t @var{type_id})
+Emit architecture-specific type ID instruction for KCFI preambles
+and return the size of the instruction in bytes.
+@var{file} is the assembly output stream and @var{type_id} is the KCFI
+type identifier to emit.  If @var{file} is NULL, skip emission and only
+return the size.  If not overridden, the default fallback emits a
+@code{.word} directive with the type ID and returns 4 bytes.  Targets can
+override this to emit different instruction sequences and return their
+corresponding sizes.
+@end deftypefn
+
 @node Miscellaneous Register Hooks
 @subsection Miscellaneous register hooks
 @cindex miscellaneous register hooks
gcc/doc/tm.texi.in +12 -0
index c3ed9a9fd7c2..b2856886194c 100644
@@ -2433,6 +2433,7 @@ This describes the stack layout and calling conventions.
 * Tail Calls::
 * Shrink-wrapping separate components::
 * Stack Smashing Protection::
+* Kernel Control Flow Integrity::
 * Miscellaneous Register Hooks::
 @end menu
 
@@ -3807,6 +3808,17 @@ generic code.
 
 @hook TARGET_GET_VALID_OPTION_VALUES
 
+@node Kernel Control Flow Integrity
+@subsection Kernel Control Flow Integrity
+@cindex kernel control flow integrity
+@cindex KCFI
+
+@hook TARGET_KCFI_SUPPORTED
+
+@hook TARGET_KCFI_MASK_TYPE_ID
+
+@hook TARGET_KCFI_EMIT_TYPE_ID
+
 @node Miscellaneous Register Hooks
 @subsection Miscellaneous register hooks
 @cindex miscellaneous register hooks
gcc/final.cc +3 -0
index afcb0bb9efbc..7f6aa9f9e480 100644
@@ -2094,6 +2094,9 @@ call_from_call_insn (const rtx_call_insn *insn)
 	case SET:
 	  x = XEXP (x, 1);
 	  break;
+	case KCFI:
+	  x = XEXP (x, 0);
+	  break;
 	}
     }
   return x;
gcc/opts.cc +1 -0
index 3ab993aea573..0ee37e01d24a 100644
@@ -2170,6 +2170,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, ~sanitize_code_type (0), true, true),
 #undef SANITIZER_OPT
   { NULL, sanitize_code_type (0), 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 68ce53baa0f1..fd1bb0846801 100644
@@ -52,6 +52,7 @@ along with GCC; see the file COPYING3.  If not see
   NEXT_PASS (pass_ipa_auto_profile_offline);
   NEXT_PASS (pass_ipa_free_lang_data);
   NEXT_PASS (pass_ipa_function_and_variable_visibility);
+  NEXT_PASS (pass_ipa_kcfi);
   NEXT_PASS (pass_ipa_strub_mode);
   NEXT_PASS (pass_build_ssa_passes);
   PUSH_INSERT_PASSES_WITHIN (pass_build_ssa_passes)
@@ -275,6 +276,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 +445,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);
gcc/rtl.def +6 -0
index 15ae7d10fcc1..af643d187b95 100644
@@ -318,6 +318,12 @@ DEF_RTL_EXPR(CLOBBER, "clobber", "e", RTX_EXTRA)
 
 DEF_RTL_EXPR(CALL, "call", "ee", RTX_EXTRA)
 
+/* KCFI wrapper for call expressions.
+   Operand 0 is the call expression.
+   Operand 1 is the KCFI type ID (const_int).  */
+
+DEF_RTL_EXPR(KCFI, "kcfi", "ee", RTX_EXTRA)
+
 /* Return from a subroutine.  */
 
 DEF_RTL_EXPR(RETURN, "return", "", RTX_EXTRA)
gcc/rtlanal.cc +5 -0
index 63a1d08c46cf..4baa820b176e 100644
@@ -1177,6 +1177,11 @@ reg_referenced_p (const_rtx x, const_rtx body)
     case IF_THEN_ELSE:
       return reg_overlap_mentioned_p (x, body);
 
+    case KCFI:
+      /* For KCFI wrapper, check both the wrapped call and the type ID */
+      return (reg_overlap_mentioned_p (x, XEXP (body, 0))
+              || reg_overlap_mentioned_p (x, XEXP (body, 1)));
+
     case TRAP_IF:
       return reg_overlap_mentioned_p (x, TRAP_CONDITION (body));
 
gcc/target.def +38 -0
index 8e491d838642..47a11c60809a 100644
@@ -7589,6 +7589,44 @@ DEFHOOKPOD
 The default value is NULL.",
  const char *, NULL)
 
+/* Kernel Control Flow Integrity (KCFI) hooks.  */
+#undef HOOK_PREFIX
+#define HOOK_PREFIX "TARGET_KCFI_"
+HOOK_VECTOR (TARGET_KCFI, kcfi)
+
+DEFHOOK
+(supported,
+ "Return true if the target supports Kernel Control Flow Integrity (KCFI).\n\
+This hook indicates whether the target has implemented the necessary RTL\n\
+patterns and infrastructure to support KCFI instrumentation.  The default\n\
+implementation returns false.",
+ bool, (void),
+ hook_bool_void_false)
+
+DEFHOOK
+(mask_type_id,
+ "Apply architecture-specific masking to KCFI type ID.  This hook allows\n\
+targets to apply bit masks or other transformations to the computed KCFI\n\
+type identifier to match the target's specific requirements.  The default\n\
+implementation returns the type ID unchanged.",
+ uint32_t, (uint32_t type_id),
+ NULL)
+
+DEFHOOK
+(emit_type_id,
+ "Emit architecture-specific type ID instruction for KCFI preambles\n\
+and return the size of the instruction in bytes.\n\
+@var{file} is the assembly output stream and @var{type_id} is the KCFI\n\
+type identifier to emit.  If @var{file} is NULL, skip emission and only\n\
+return the size.  If not overridden, the default fallback emits a\n\
+@code{.word} directive with the type ID and returns 4 bytes.  Targets can\n\
+override this to emit different instruction sequences and return their\n\
+corresponding sizes.",
+ int, (FILE *file, uint32_t type_id),
+ NULL)
+
+HOOK_VECTOR_END (kcfi)
+
 /* Close the 'struct gcc_target' definition.  */
 HOOK_VECTOR_END (C90_EMPTY_HACK)
 
gcc/toplev.cc +11 -0
index d26467450e37..9078bb6318a9 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"
@@ -1739,6 +1740,16 @@ process_options ()
 		  "requires %<-fno-exceptions%>");
     }
 
+  if (flag_sanitize & SANITIZE_KCFI)
+    {
+      if (!targetm.kcfi.supported ())
+	sorry ("%<-fsanitize=kcfi%> not supported by this target");
+
+      /* KCFI is supported for only C at this time.  */
+      if (!lang_GNU_C ())
+	sorry ("%<-fsanitize=kcfi%> is only supported for C");
+    }
+
   HOST_WIDE_INT patch_area_size, patch_area_start;
   parse_and_check_patch_area (flag_patchable_function_entry, false,
 			      &patch_area_size, &patch_area_start);
gcc/tree-inline.cc +10 -0
index 08e642178ba5..e674e176f7d3 100644
@@ -2104,6 +2104,16 @@ copy_bb (copy_body_data *id, basic_block bb,
 	  /* Advance iterator now before stmt is moved to seq_gsi.  */
 	  gsi_next (&stmts_gsi);
 
+	  /* If inlining from a function with no_sanitize("kcfi"), mark any
+	     call statements in the inlined body with the flag so they skip
+	     KCFI instrumentation.  */
+	  if (is_gimple_call (stmt)
+	      && !sanitize_flags_p (SANITIZE_KCFI, id->src_fn))
+	    {
+	      gcall *call = as_a <gcall *> (stmt);
+	      gimple_call_set_inlined_from_kcfi_nosantize (call, true);
+	    }
+
 	  if (gimple_nop_p (stmt))
 	      continue;
 
gcc/varasm.cc +36 -10

70 lines not on this page · raw message

Signature · 1 line
2.34.1
#5 lore raw

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

Quoted 9 lines · Kees Cook

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

gcc/kcfi.cc new file +8 -0
+  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 register
+    load -$offset(%target), %tmp    ; load the typeid hash at target
+    cmp $hash, %tmp                 ; compare expected typeid with loaded
+    je .Lcheck_passed               ; jump to the indirect call

gcc/kcfi.cc line 92

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+  .Lkcfi_trap$N:                    ; label of trap insn
+    trap                            ; trap on failure, but arranged so
+                                    ; "permissive mode" falls through
+  .Lkcfi_call$N:                    ; label of call insn
+    call *%target                   ; actual indirect call
+
+  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.

I know it is far too late to do anything here. But I've recently dug through a bunch of optimization manual and the like and that Jcc is about as bad as it gets :/

The old optimization manual states that forward jumps are assumed not-taken; while backward jumps are assumed taken.

The new wisdom is that any Jcc must be assumed not-taken; that is, the fallthrough case has the best throughput.

Here we have a forward branch which is assumed taken :-(

author
#6 lore raw

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

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

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

gcc/kcfi.cc new file +8 -0
+  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 register
+    load -$offset(%target), %tmp    ; load the typeid hash at target
+    cmp $hash, %tmp                 ; compare expected typeid with loaded
+    je .Lcheck_passed               ; jump to the indirect call

gcc/kcfi.cc line 92

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+  .Lkcfi_trap$N:                    ; label of trap insn
+    trap                            ; trap on failure, but arranged so
+                                    ; "permissive mode" falls through
+  .Lkcfi_call$N:                    ; label of call insn
+    call *%target                   ; actual indirect call
+
+  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.

I know it is far too late to do anything here. But I've recently dug through a bunch of optimization manual and the like and that Jcc is about as bad as it gets :/

Quoted 5 lines

The old optimization manual states that forward jumps are assumed not-taken; while backward jumps are assumed taken.

The new wisdom is that any Jcc must be assumed not-taken; that is, the fallthrough case has the best throughput.

I would expect the cmp to be the slowest part of this sequence, and I figured the both the trap and the call to be speculation barriers? I'm not sure, though. Is changing the sequence actually useful?

Quoted 1 line

Here we have a forward branch which is assumed taken :-(

The constraints we have are:

- Linux x86 KCFI trap handler decodes the instructions from the trap backwards, but it uses exact offsets (-12 and -6).
- Control flow following the trap must make the call (for warn-only mode)

If we change this, we'd need to make the insn decoder smarter to likey look at the insn AFTER the trap ("is it a direct jump?")

And then use this, which is ugly, but matches second constraint:

cmp $hash %tmp
jne .Ltrap
.Lcall:
call *%target
jmp .Ldone
.Ltrap:

	ud2
	jmp .Lcall

.Ldone:

+4 bytes for x86_64

Signature · 1 line
Kees Cook
#7 lore raw

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

Quoted 29 lines · Kees Cook
Quoted 28 lines · Peter Zijlstra
Quoted 9 lines · Kees Cook

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

gcc/kcfi.cc new file +8 -0
+  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 register
+    load -$offset(%target), %tmp    ; load the typeid hash at target
+    cmp $hash, %tmp                 ; compare expected typeid with loaded
+    je .Lcheck_passed               ; jump to the indirect call

gcc/kcfi.cc line 92

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+  .Lkcfi_trap$N:                    ; label of trap insn
+    trap                            ; trap on failure, but arranged so
+                                    ; "permissive mode" falls through
+  .Lkcfi_call$N:                    ; label of call insn
+    call *%target                   ; actual indirect call
+
+  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.

I know it is far too late to do anything here. But I've recently dug through a bunch of optimization manual and the like and that Jcc is about as bad as it gets :/

The old optimization manual states that forward jumps are assumed not-taken; while backward jumps are assumed taken.

Quoted 6 lines
Quoted 2 lines

The new wisdom is that any Jcc must be assumed not-taken; that is, the fallthrough case has the best throughput.

I would expect the cmp to be the slowest part of this sequence, and I figured the both the trap and the call to be speculation barriers? I'm not sure, though. Is changing the sequence actually useful?

The load can miss, in which case it is definitely the most expensive thing around.

Quoted 19 lines
Quoted 1 line

Here we have a forward branch which is assumed taken :-(

The constraints we have are:

- Linux x86 KCFI trap handler decodes the instructions from the trap backwards, but it uses exact offsets (-12 and -6).
- Control flow following the trap must make the call (for warn-only mode)

If we change this, we'd need to make the insn decoder smarter to likey look at the insn AFTER the trap ("is it a direct jump?")

And then use this, which is ugly, but matches second constraint:

cmp $hash %tmp
jne .Ltrap
.Lcall:
call *%target
jmp .Ldone
.Ltrap:

Quoted 3 lines
	ud2
	jmp .Lcall

.Ldone:

Ah, you can do something like:

	cmp $hash, %tmp
	jne +3
	nopl -42(%rax)
	call *%target

which is only 2 bytes longer. Notably, that nopl is 4 bytes and the 4th byte is 0xd6 (aka UDB). This is an effective UDcc instruction based around a forward non-taken branch.

But yeah, I don't know if it is worth changing this. Its just that I've been staring at these things far too much of late :-)

author
#8 lore raw

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

Quoted 65 lines · Peter Zijlstra
Quoted 29 lines · Kees Cook
Quoted 28 lines · Peter Zijlstra
Quoted 9 lines · Kees Cook

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

gcc/kcfi.cc new file +8 -0
+  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 register
+    load -$offset(%target), %tmp    ; load the typeid hash at target
+    cmp $hash, %tmp                 ; compare expected typeid with loaded
+    je .Lcheck_passed               ; jump to the indirect call

gcc/kcfi.cc line 92

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+  .Lkcfi_trap$N:                    ; label of trap insn
+    trap                            ; trap on failure, but arranged so
+                                    ; "permissive mode" falls through
+  .Lkcfi_call$N:                    ; label of call insn
+    call *%target                   ; actual indirect call
+
+  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.

I know it is far too late to do anything here. But I've recently dug through a bunch of optimization manual and the like and that Jcc is about as bad as it gets :/

The old optimization manual states that forward jumps are assumed not-taken; while backward jumps are assumed taken.

Quoted 6 lines
Quoted 2 lines

The new wisdom is that any Jcc must be assumed not-taken; that is, the fallthrough case has the best throughput.

I would expect the cmp to be the slowest part of this sequence, and I figured the both the trap and the call to be speculation barriers? I'm not sure, though. Is changing the sequence actually useful?

The load can miss, in which case it is definitely the most expensive thing around.

Quoted 19 lines
Quoted 1 line

Here we have a forward branch which is assumed taken :-(

The constraints we have are:

- Linux x86 KCFI trap handler decodes the instructions from the trap backwards, but it uses exact offsets (-12 and -6).
- Control flow following the trap must make the call (for warn-only mode)

If we change this, we'd need to make the insn decoder smarter to likey look at the insn AFTER the trap ("is it a direct jump?")

And then use this, which is ugly, but matches second constraint:

cmp $hash %tmp
jne .Ltrap
.Lcall:
call *%target
jmp .Ldone
.Ltrap:

Quoted 3 lines
	ud2
	jmp .Lcall

.Ldone:

Ah, you can do something like:

Quoted 8 lines
	cmp $hash, %tmp
	jne +3
	nopl -42(%rax)
	call *%target

which is only 2 bytes longer. Notably, that nopl is 4 bytes and the 4th byte is 0xd6 (aka UDB). This is an effective UDcc instruction based around a forward non-taken branch.

Oh right, I forgot about the nop encodings.

Quoted 2 lines

But yeah, I don't know if it is worth changing this. Its just that I've been staring at these things far too much of late :-)

To do this we'd need to change the Linux trap handler and Clang's implementation, so yeah, I'm inclined to just leave it as-is until we have a stronger reason to change it.

Signature · 1 line
Kees Cook
#9 lore raw

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

In reply to Kees Cook
Quoted 291 lines · Kees Cook

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

See the start of kcfi.cc for design details.

gcc/ChangeLog:

* kcfi.h: New file with KCFI public interface declarations.
* kcfi.cc: New file implementing Kernel Control Flow Integrity infrastructure.
* Makefile.in (OBJS): Add kcfi.o.
* flag-types.h (enum sanitize_code): Add SANITIZE_KCFI.
* gimple.h (enum gf_mask): Add GF_CALL_INLINED_FROM_KCFI_NOSANTIZE. (gimple_call_set_inlined_from_kcfi_nosantize): New function. (gimple_call_inlined_from_kcfi_nosantize_p): New function.
* tree-pass.h Add kcfi passes.
* c-family/c-attribs.cc: Include asan.h. (handle_patchable_function_entry_attribute): Add error for using patchable_function_entry attribute with -fsanitize=kcfi.
* df-scan.cc (df_uses_record): Add KCFI case to handle KCFI RTL patterns and process wrapped RTL.
* doc/invoke.texi (fsanitize=kcfi): Add documentation for KCFI sanitizer option.
* doc/tm.texi.in: Add Kernel Control Flow Integrity section with TARGET_KCFI_SUPPORTED, TARGET_KCFI_MASK_TYPE_ID, TARGET_KCFI_EMIT_TYPE_ID hooks.
* doc/tm.texi: Regenerate.
* final.cc (call_from_call_insn): Add KCFI case to handle KCFI-wrapped calls.
* opts.cc (sanitizer_opts): Add kcfi entry.
* passes.cc: Include kcfi.h.
* passes.def: Add KCFI passes (GIMPLE and IPA).
* rtl.def (KCFI): Add new RTL code for KCFI instrumentation.
* rtlanal.cc (rtx_cost): Add KCFI case.
* target.def: Add KCFI target hooks.
* toplev.cc (process_options): Add KCFI option processing.
* tree-inline.cc: Include kcfi.h and asan.h.
(copy_bb): Handle KCFI no_sanitize attribute propagation during inlining.
* varasm.cc (assemble_start_function): Emit KCFI preambles. (assemble_external_real): Emit KCFI typeid symbols. (default_elf_asm_named_section): Handle .kcfi_traps using SECTION_LINK_ORDER flag.

---

gcc/kcfi.h                |  47 +++
gcc/kcfi.cc               | 764 ++++++++++++++++++++++++++++++++++++++
gcc/Makefile.in           |   1 +
gcc/flag-types.h          |   2 +
gcc/gimple.h              |  21 ++
gcc/tree-pass.h           |   3 +
gcc/c-family/c-attribs.cc |  12 +
gcc/df-scan.cc            |   6 +
gcc/doc/invoke.texi       |  35 ++
gcc/doc/tm.texi           |  31 ++
gcc/doc/tm.texi.in        |  12 +
gcc/final.cc              |   3 +
gcc/opts.cc               |   1 +
gcc/passes.cc             |   1 +
gcc/passes.def            |   3 +
gcc/rtl.def               |   6 +
gcc/rtlanal.cc            |   5 +
gcc/target.def            |  38 ++
gcc/toplev.cc             |  11 +
gcc/tree-inline.cc        |  10 +
gcc/varasm.cc             |  46 ++-
21 files changed, 1048 insertions(+), 10 deletions(-)

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

gcc/kcfi.h new file +47 -0
new file mode 100644
index 000000000000..17ec59a1a3b8
@@ -0,0 +1,47 @@
+/* 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"
+
+/* Common helper for RTL patterns to emit .kcfi_traps section entry.
+   Call after emitting trap label and instruction with the trap symbol
+   reference.  */
+extern void kcfi_emit_traps_section (FILE *file, rtx trap_label_sym);
+
+/* Extract KCFI type ID from current GIMPLE statement.  */
+extern rtx kcfi_get_call_type_id (void);
+
+/* Emit KCFI type ID symbol for address-taken functions.  */
+extern void emit_kcfi_typeid_symbol (FILE *asm_file, tree decl,
+     const char *name);
+
+/* Emit KCFI preamble.  */
+extern void kcfi_emit_preamble (FILE *file, tree decl,
+ const char *actual_fname);
+
+/* For calculating callsite offset.  */
+extern HOST_WIDE_INT kcfi_patchable_entry_prefix_nops;
+
+#endif /* GCC_KCFI_H */
gcc/kcfi.cc new file +154 -0
new file mode 100644
index 000000000000..1ae0602eac7b
@@ -0,0 +1,764 @@
+/* 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/>.  */
+
+/* KCFI ABI Design:
+
+The Linux Kernel Control Flow Integrity ABI 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.
+
+The general CFI ideas are discussed here, but focuses more on a CFG
+analysis to construct valid call destinations, which tends to require LTO:
+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/
+
+KCFI has a number of specific constraints. Some are tied to the
+backend architecture, which are covered in arch-specific code.
+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 register
+    load -$offset(%target), %tmp    ; load the typeid hash at target
+    cmp $hash, %tmp                 ; compare expected typeid with loaded
+    je .Lcheck_passed               ; jump to the indirect call
+  .Lkcfi_trap$N:                    ; label of trap insn
+    trap                            ; trap on failure, but arranged so
+                                    ; "permissive mode" falls through
+  .Lkcfi_call$N:                    ; label of call insn
+    call *%target                   ; actual indirect call
+
+  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.
+
+- 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, which contains the $hash value:
+
+    __cfi_target_func:
+      .word $hash
+    target_func:
+       [regular 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 with 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...]
+
+  Architectures may need to add alignment nops prior to the hash to keep things
+  aligned for function call conventions.
+
+- 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 insn (e.g. 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:
+
+  ...
+  .Lkcfi_trap$N:
+    trap
+  .section .kcfi_traps,"ao",@progbits,.text
+    .Lkcfi_entry$N:
+        .long .Lkcfi_trap$N - .Lkcfi_entry$N
+  .text
+  .Lkcfi_call$N:
+    call *%target
+
+  For architectures that can encode immediates in their trap function
+  (e.g. aarch64 and arm32), this isn't needed: they just use immediate
+  codes that indicate a KCFI trap.
+
+- The no_sanitize("kcfi") function attribute means that the marked
+  function must not produce KCFI checking for indirect calls, and this
+  attribute must survive inlining. This is used rarely by Linux, but

gcc/kcfi.cc line 164

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+  is required to make BPF JIT trampolines work on older Linux kernel
+  versions.
+
+As a result of these constraints, there are some behavioral aspects
+that need to be preserved across the middle-end and back-end.
+
+For indirect call sites:
+
+- Keeping indirect calls from being merged (see above) by adding a
+  wrapping type so that equality was tested based on type-id.

I still think that the additional new created wrapping type and the new assignment stmt

wrapper_tmp = (wrapper_ptr_type) fn
is not necessary.

All the information can be get from function type + type-id which is attached as an attribute to the original_function_type of “fn”.
Could you explain why the wrapper type and the new temporary, new assignment is necessary?

gcc/kcfi.cc line 167

Quoted 3 lines
gcc/kcfi.cc new file +3 -0
+
+- Keeping typeid information available through to the RTL expansion
+  phase was done via a new KCFI insn that wraps CALL and the typeid.

Is the new KCFI insn the following:
wrapper_tmp = (wrapper_ptr_type) fn?

Why the type-id attached as the attribute is not enough?

gcc/kcfi.cc

Quoted 9 lines
gcc/kcfi.cc new file +9 -0
+
+- To make sure KCFI expansion is skipped for inline functions, the
+  inlining is marked during GIMPLE with a new flag which is checked
+  during expansion.
+
+For indirect call targets:
+
+- kcfi_emit_preamble() uses function_needs_kcfi_preamble(),
+  to emit the preablem,

Typo: preamble.

Quoted 34 lines

which interacts with patchable function

gcc/kcfi.cc new file +33 -0
+  entry to add any needed alignment.
+
+- gcc/varasm.cc, assemble_external_real() calls emit_kcfi_typeid_symbol()
+  to add the __kcfi_typeid symbols (see get_function_kcfi_type_id()
+  below).
+
+*/
+
+#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 "cfgrtl.h"
+#include "asan.h"
+#include "diagnostic-core.h"
+#include "memmodel.h"
+#include "print-tree.h"
+#include "emit-rtl.h"
+#include "output.h"
+#include "builtins.h"

gcc/kcfi.cc line 219

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+#include "varasm.h"
+#include "opts.h"
+#include "mangle.h"
+#include "target.h"
+#include "flags.h"
+
+HOST_WIDE_INT kcfi_patchable_entry_prefix_nops = 0;  /* For callsite offset */
+static HOST_WIDE_INT kcfi_patchable_entry_arch_alignment_nops = 0;  /* For preamble alignment */
+
+/* Common helper for RTL patterns to emit .kcfi_traps section entry.  */

there should be one empty line between the comments of the function and the start of the function. I noticed that you need such empty line for all the new functions you added. -:)

Quoted 42 lines
gcc/kcfi.cc new file +42 -0
+void
+kcfi_emit_traps_section (FILE *file, rtx trap_label_sym)
+{
+  /* Generate entry label internally and get its number.  */
+  rtx entry_label = gen_label_rtx ();
+  int entry_labelno = CODE_LABEL_NUMBER (entry_label);
+
+  /* Generate entry label name with custom prefix.  */
+  char entry_name[32];
+  ASM_GENERATE_INTERNAL_LABEL (entry_name, "Lkcfi_entry", entry_labelno);
+
+  /* Save current section to restore later.  */
+  section *saved_section = in_section;
+
+  /* Use varasm infrastructure for section handling.  */
+  section *kcfi_traps_section = get_section (".kcfi_traps",
+     SECTION_LINK_ORDER, NULL);
+  switch_to_section (kcfi_traps_section);
+
+  /* Emit entry label.  */
+  ASM_OUTPUT_LABEL (file, entry_name);
+
+  /* Generate address difference using RTL infrastructure.  */
+  rtx entry_label_sym = gen_rtx_SYMBOL_REF (Pmode, entry_name);
+  rtx addr_diff = gen_rtx_MINUS (Pmode, trap_label_sym, entry_label_sym);
+
+  /* Emit the address difference as a 4-byte value.  */
+  assemble_integer (addr_diff, 4, BITS_PER_UNIT, 1);
+
+  /* Restore the previous section.  */
+  switch_to_section (saved_section);
+}
+
+/* Compute KCFI type ID for a function declaration or function type (internal) */
+static uint32_t
+compute_kcfi_type_id (tree fntype, tree fndecl = NULL_TREE)
+{
+  gcc_assert (fntype);
+  gcc_assert (TREE_CODE (fntype) == FUNCTION_TYPE);
+
+  uint32_t type_id = hash_function_type (fntype, fndecl);
+

gcc/kcfi.cc line 271

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+  /* Apply target-specific masking if supported.  */
+  if (targetm.kcfi.mask_type_id)
+    type_id = targetm.kcfi.mask_type_id (type_id);
+
+  return 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.  */

Why no_sanitize(“kcfi”) is not considered here?

Quoted 60 lines
gcc/kcfi.cc new file +60 -0
+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;
+
+/* Set KCFI type ID for a function declaration during IPA phase.
+   Fatal error if type ID is already set.  */
+static void
+set_function_kcfi_type_id (tree fndecl)
+{
+  if (!kcfi_type_id_attr)
+    kcfi_type_id_attr = get_identifier ("kcfi_type_id");
+
+  /* Fatal error if type ID already set - nothing should set it twice.  */
+  if (lookup_attribute_by_prefix ("kcfi_type_id",
+  DECL_ATTRIBUTES (fndecl)))
+    internal_error ("KCFI type ID already set for function %qD", fndecl);
+
+  /* Compute type ID using FUNCTION_TYPE to preserve typedef information.  */
+  uint32_t type_id = compute_kcfi_type_id (TREE_TYPE (fndecl), fndecl);
+
+  tree type_id_tree = build_int_cst (unsigned_type_node, type_id);
+  tree attr_value = build_tree_list (NULL_TREE, type_id_tree);
+  tree attr = build_tree_list (kcfi_type_id_attr, attr_value);
+
+  DECL_ATTRIBUTES (fndecl) = chainon (DECL_ATTRIBUTES (fndecl), attr);
+}
+
+/* Get KCFI type ID for a function declaration during assembly output phase.
+   Fatal error if type ID was not previously set during IPA phase.  */
+static uint32_t
+get_function_kcfi_type_id (tree fndecl)
+{

gcc/kcfi.cc line 341

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+  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);

The indentation of above is off.

Quoted 35 lines
gcc/kcfi.cc new file +35 -0
+    }
+
+  internal_error ("KCFI type ID not found for function %qD - "
+  "should have been set during GIMPLE phase", fndecl);
+}
+
+/* Prepare the global KCFI alignment NOPs calculation.
+   Called once during IPA pass to set global variable.  */
+static void
+kcfi_prepare_alignment_nops (void)
+{
+  /* Only use global patchable-function-entry flag, not function attributes.
+     KCFI callsites cannot know about function-specific attributes.  */
+  if (flag_patchable_function_entry)
+    {
+      HOST_WIDE_INT total_nops, prefix_nops = 0;
+      parse_and_check_patch_area (flag_patchable_function_entry, false,
+  &total_nops, &prefix_nops);
+      /* Store value for callsite offset calculation */
+      kcfi_patchable_entry_prefix_nops = prefix_nops;
+    }
+
+  /* Calculate architecture-specific alignment NOPs.
+     KCFI preamble layout:
+     __cfi_func: [alignment_nops][typeid][prefix_nops] func: [entry_nops]
+
+     The alignment NOPs ensure __cfi_func stays at proper function alignment
+     when prefix NOPs are added.  */
+  HOST_WIDE_INT arch_alignment = 0;
+
+  /* Calculate alignment NOPs based on function alignment setting.
+     Use explicit -falign-functions if set, otherwise default to 4 bytes. */
+  int alignment_bytes = 4;
+  if (align_functions.levels[0].log > 0)
+    {

gcc/kcfi.cc line 386

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+      /* Use explicit -falign-functions setting */
+      alignment_bytes = align_functions.levels[0].get_value();
+    }
+
+  /* Get typeid instruction size from target hook, default to 4 bytes */
+  int typeid_size = targetm.kcfi.emit_type_id
+                    ? targetm.kcfi.emit_type_id (NULL, 0) : 4;
+
+  /* Calculate alignment NOPs needed */
+  arch_alignment = (alignment_bytes - ((kcfi_patchable_entry_prefix_nops + typeid_size) % alignment_bytes)) % alignment_bytes;

The above line is too long.

Quoted 84 lines
gcc/kcfi.cc new file +84 -0
+
+  /* Use the calculated alignment NOPs */
+  kcfi_patchable_entry_arch_alignment_nops = arch_alignment;
+}
+
+/* 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;
+
+  /* Everything else must be indirect calls needing KCFI.  */
+  return true;
+}
+
+/* Extract KCFI type ID from indirect call GIMPLE statement.
+   Returns RTX constant with type ID, or NULL_RTX if no KCFI needed.  */
+rtx
+kcfi_get_call_type_id (void)
+{
+  if (!sanitize_flags_p (SANITIZE_KCFI) || !currently_expanding_gimple_stmt)
+    return NULL_RTX;
+
+  if (!is_gimple_call (currently_expanding_gimple_stmt))
+    return NULL_RTX;
+
+  gcall *call_stmt = as_a <gcall *> (currently_expanding_gimple_stmt);
+
+  /* Only indirect calls need KCFI instrumentation.  */
+  if (gimple_call_fndecl (call_stmt))
+    return NULL_RTX;
+
+  tree fn_type = gimple_call_fntype (call_stmt);
+  if (!fn_type)
+    return NULL_RTX;
+
+  tree attr = lookup_attribute ("kcfi_type_id", TYPE_ATTRIBUTES (fn_type));
+  if (!attr || !TREE_VALUE (attr))
+    return NULL_RTX;
+
+  if (gimple_call_inlined_from_kcfi_nosantize_p (call_stmt))
+    return NULL_RTX;
+
+  uint32_t kcfi_type_id = (uint32_t) tree_to_uhwi (TREE_VALUE (attr));
+  return GEN_INT (kcfi_type_id);
+}
+
+/* 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);
+}
+
+void
+kcfi_emit_preamble (FILE *file, tree decl, 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));
+
+  /* Get type ID.  */
+  uint32_t type_id = get_function_kcfi_type_id (decl);
+
+  /* Create symbol name for reuse.  */
+  char cfi_symbol_name[256];

gcc/kcfi.cc line 480

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+  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);
+    }

Indentations are off in the above lines.

Quoted 48 lines
gcc/kcfi.cc new file +48 -0
+
+  /* Emit .type directive.  */
+  ASM_OUTPUT_TYPE_DIRECTIVE (file, cfi_symbol_name, "function");
+  fprintf (file, "%s:\n", cfi_symbol_name);
+
+  /* Emit architecture-specific prefix NOPs.  */
+  for (int i = 0; i < kcfi_patchable_entry_arch_alignment_nops; i++)
+    {
+      fprintf (file, "\tnop\n");
+    }
+
+  /* Emit type ID bytes.  */
+  if (targetm.kcfi.emit_type_id)
+    targetm.kcfi.emit_type_id (file, type_id);
+  else
+    fprintf (file, "\t.word\t0x%08x\n", 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);
+}
+
+/* KCFI GIMPLE pass implementation.  */
+
+static bool
+gate_kcfi (void)
+{
+  /* Always process functions when KCFI is globally enabled to set type IDs.
+     Individual function processing (call instrumentation) will check no_sanitize("kcfi").  */
+  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[32];
+  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.  */

gcc/kcfi.cc line 538

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+  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;
+}

As I asked previously, In the above routine, the “type_id" is attached as an attribute to the
“original_fn_type” already, what additional information is carried by the new “wrapper_type”?

Quoted 5 lines
gcc/kcfi.cc new file +5 -0
+
+/* Wrap indirect calls with KCFI type for anti-merging.  */
+static unsigned int
+kcfi_instrument (void)
+{

gcc/kcfi.cc line 553

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+  /* Process current function for call instrumentation only.
+     Type ID setting is handled by the separate IPA pass.  */
+
+  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))
+ {

The indentation of the above line is off.

Quoted 21 lines
gcc/kcfi.cc new file +21 -0
+  gimple *stmt = gsi_stmt (gsi);
+
+  if (!is_gimple_call (stmt))
+    continue;
+
+  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)
+    continue;
+
+  tree fn = gimple_call_fn (call_stmt);
+  if (!is_kcfi_indirect_call (fn))
+    continue;
+

gcc/kcfi.cc line 584

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+  // 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)
+    continue;
+
+  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);

Again, the new “type_id” has been attached as an attribute of “fn_type” here,

gcc/kcfi.cc line 594

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+
+  // 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);
+

Why the additional wrapper_ptr_type, wrapper_tmp and new assignment stmt Are needed here?

Quoted 654 lines
gcc/kcfi.cc new file +170 -0
+  // 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);
+}
+
+/* IPA pass for KCFI type ID setting - runs once per compilation unit.  */
+
+namespace {
+
+const pass_data pass_data_ipa_kcfi =
+{
+  SIMPLE_IPA_PASS, /* type */
+  "ipa_kcfi", /* name */
+  OPTGROUP_NONE, /* optinfo_flags */
+  TV_IPA_OPT, /* tv_id */
+  0, /* properties_required */
+  0, /* properties_provided */
+  0, /* properties_destroyed */
+  0, /* todo_flags_start */
+  0, /* todo_flags_finish */
+};
+
+/* Set KCFI type IDs for all functions in the compilation unit.  */
+static unsigned int
+ipa_kcfi_execute (void)
+{
+  struct cgraph_node *node;
+
+  /* Prepare global KCFI alignment NOPs calculation once for all functions.  */
+  kcfi_prepare_alignment_nops ();
+
+  /* Process all functions - both local and external.
+     This preserves typedef information using DECL_ARGUMENTS.  */
+  FOR_EACH_FUNCTION (node)
+    {
+      tree fndecl = node->decl;
+
+      /* Skip all non-NORMAL builtins (MD, FRONTEND) entirely.
+         For NORMAL builtins, skip those that lack an implicit
+ implementation (closest way to distinguishing DEF_LIB_BUILTIN
+ from others). E.g. we need to have typeids for memset().  */
+      if (fndecl_built_in_p (fndecl))
+        {
+          if (DECL_BUILT_IN_CLASS (fndecl) != BUILT_IN_NORMAL)
+            continue;
+          if (!builtin_decl_implicit_p (DECL_FUNCTION_CODE (fndecl)))
+            continue;
+        }
+
+      set_function_kcfi_type_id (fndecl);
+    }
+
+  return 0;
+}
+
+class pass_ipa_kcfi : public simple_ipa_opt_pass
+{
+public:
+  pass_ipa_kcfi (gcc::context *ctxt)
+    : simple_ipa_opt_pass (pass_data_ipa_kcfi, ctxt)
+  {}
+
+  /* opt_pass methods: */
+  bool gate (function *) final override
+  {
+    return sanitize_flags_p (SANITIZE_KCFI);
+  }
+
+  unsigned int execute (function *) final override
+  {
+    return ipa_kcfi_execute ();
+  }
+
+}; // class pass_ipa_kcfi
+
+} // anon namespace
+
+simple_ipa_opt_pass *
+make_pass_ipa_kcfi (gcc::context *ctxt)
+{
+  return new pass_ipa_kcfi (ctxt);
+}
gcc/Makefile.in +1 -0
index 4c12ac68d979..84bbc4223734 100644
@@ -1591,6 +1591,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 bf681c3e8153..c3c0bc61ee3e 100644
@@ -337,6 +337,8 @@ enum sanitize_code {
  SANITIZE_KERNEL_HWADDRESS = 1UL << 30,
  /* Shadow Call Stack.  */
  SANITIZE_SHADOW_CALL_STACK = 1UL << 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/gimple.h +21 -0
index da32651ea017..cef915b9164f 100644
@@ -142,6 +142,7 @@ enum gf_mask {
    GF_CALL_ALLOCA_FOR_VAR = 1 << 5,
    GF_CALL_INTERNAL = 1 << 6,
    GF_CALL_CTRL_ALTERING       = 1 << 7,
+    GF_CALL_INLINED_FROM_KCFI_NOSANTIZE = 1 << 8,
    GF_CALL_MUST_TAIL_CALL = 1 << 9,
    GF_CALL_BY_DESCRIPTOR = 1 << 10,
    GF_CALL_NOCF_CHECK = 1 << 11,
@@ -3487,6 +3488,26 @@ gimple_call_from_thunk_p (gcall *s)
  return (s->subcode & GF_CALL_FROM_THUNK) != 0;
 }
 
+/* If INLINED_FROM_KCFI_NOSANTIZE_P is true, mark GIMPLE_CALL S as being
+   inlined from a function with no_sanitize("kcfi").  */
+
+inline void
+gimple_call_set_inlined_from_kcfi_nosantize (gcall *s, bool inlined_from_kcfi_nosantize_p)
+{
+  if (inlined_from_kcfi_nosantize_p)
+    s->subcode |= GF_CALL_INLINED_FROM_KCFI_NOSANTIZE;
+  else
+    s->subcode &= ~GF_CALL_INLINED_FROM_KCFI_NOSANTIZE;
+}
+
+/* Return true if GIMPLE_CALL S was inlined from a function with
+   no_sanitize("kcfi").  */
+
+inline bool
+gimple_call_inlined_from_kcfi_nosantize_p (const gcall *s)
+{
+  return (s->subcode & GF_CALL_INLINED_FROM_KCFI_NOSANTIZE) != 0;
+}
 
 /* If FROM_NEW_OR_DELETE_P is true, mark GIMPLE_CALL S as being a call
   to operator new or delete created from a new or delete expression.  */
gcc/tree-pass.h +3 -0
index 1c68a69350df..fbf235adada3 100644
@@ -357,6 +357,8 @@ extern gimple_opt_pass *make_pass_tsan (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_tsan_O0 (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_sancov (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_sancov_O0 (gcc::context *ctxt);
+extern gimple_opt_pass *make_pass_kcfi (gcc::context *ctxt);
+extern gimple_opt_pass *make_pass_kcfi_O0 (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_lower_cf (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_refactor_eh (gcc::context *ctxt);
 extern gimple_opt_pass *make_pass_lower_eh (gcc::context *ctxt);
@@ -544,6 +546,7 @@ extern ipa_opt_pass_d *make_pass_ipa_odr (gcc::context *ctxt);
 extern ipa_opt_pass_d *make_pass_ipa_reference (gcc::context *ctxt);
 extern ipa_opt_pass_d *make_pass_ipa_pure_const (gcc::context *ctxt);
 extern simple_ipa_opt_pass *make_pass_ipa_pta (gcc::context *ctxt);
+extern simple_ipa_opt_pass *make_pass_ipa_kcfi (gcc::context *ctxt);
 extern simple_ipa_opt_pass *make_pass_ipa_tm (gcc::context *ctxt);
 extern simple_ipa_opt_pass *make_pass_target_clone (gcc::context *ctxt);
 extern simple_ipa_opt_pass *make_pass_dispatcher_calls (gcc::context *ctxt);
gcc/c-family/c-attribs.cc +12 -0
index 1e3a94ed9493..a12cfe48772a 100644
@@ -48,6 +48,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "gimplify.h"
 #include "tree-pretty-print.h"
 #include "gcc-rich-location.h"
+#include "asan.h"
 #include "gcc-urlifier.h"
 
 static tree handle_packed_attribute (tree *, tree, tree, int, bool *);
@@ -6508,6 +6509,17 @@ static tree
 handle_patchable_function_entry_attribute (tree *, tree name, tree args,
  int, bool *no_add_attrs)
 {
+  /* Function-specific patchable_function_entry attribute is incompatible
+     with KCFI because KCFI callsites cannot know about function-specific
+     patchable entry settings on a preamble in a different translation
+     unit.  */
+  if (sanitize_flags_p (SANITIZE_KCFI))
+    {
+      error ("%qE attribute cannot be used with %<-fsanitize=kcfi%>", name);
+      *no_add_attrs = true;
+      return NULL_TREE;
+    }
+
  for (; args; args = TREE_CHAIN (args))
    {
      tree val = TREE_VALUE (args);
gcc/df-scan.cc +6 -0
index 1e4c6a2a4fb5..0e9c75df48dd 100644
@@ -2851,6 +2851,12 @@ df_uses_record (class df_collection_rec *collection_rec,
      /* If we're clobbering a REG then we have a def so ignore.  */
      return;
 
+    case KCFI:
+      /* KCFI wraps other RTL - process the wrapped RTL.  */
+      df_uses_record (collection_rec, &XEXP (x, 0), ref_type, bb, insn_info, flags);
+      /* The type ID operand (XEXP (x, 1)) doesn't contain register uses.  */
+      return;
+
    case MEM:
      df_uses_record (collection_rec,
     &XEXP (x, 0), DF_REF_REG_MEM_LOAD,
gcc/doc/invoke.texi +0 -0
index 56c4fa86e346..cd70e6351a4e 100644
@@ -18382,6 +18382,41 @@ 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 +33 -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.
+
+Note that KCFI is incompatible with function-specific
+@code{patchable_function_entry} attributes because KCFI call sites
+cannot know about function-specific patchable entry settings in different
+translation units.  Only the global @option{-fpatchable-function-entry}
+command-line option is supported with KCFI.
+
+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/doc/tm.texi +1 -0
index 37642680f423..69603fdad090 100644
@@ -3166,6 +3166,7 @@ This describes the stack layout and calling conventions.
 * Tail Calls::
 * Shrink-wrapping separate components::
 * Stack Smashing Protection::
+* Kernel Control Flow Integrity::
 * Miscellaneous Register Hooks::

@end menu

gcc/doc/tm.texi +0 -0
@@ -5432,6 +5433,36 @@ should be allocated from heap memory and consumers should release them.

The result will be pruned to cases with PREFIX if not NULL. @end deftypefn

+@node Kernel Control Flow Integrity
+@subsection Kernel Control Flow Integrity
+@cindex kernel control flow integrity
+@cindex KCFI

gcc/doc/tm.texi +26 -0
+
+@deftypefn {Target Hook} bool TARGET_KCFI_SUPPORTED (void)
+Return true if the target supports Kernel Control Flow Integrity (KCFI).
+This hook indicates whether the target has implemented the necessary RTL
+patterns and infrastructure to support KCFI instrumentation.  The default
+implementation returns false.
+@end deftypefn
+
+@deftypefn {Target Hook} uint32_t TARGET_KCFI_MASK_TYPE_ID (uint32_t @var{type_id})
+Apply architecture-specific masking to KCFI type ID.  This hook allows
+targets to apply bit masks or other transformations to the computed KCFI
+type identifier to match the target's specific requirements.  The default
+implementation returns the type ID unchanged.
+@end deftypefn
+
+@deftypefn {Target Hook} int TARGET_KCFI_EMIT_TYPE_ID (FILE *@var{file}, uint32_t @var{type_id})
+Emit architecture-specific type ID instruction for KCFI preambles
+and return the size of the instruction in bytes.
+@var{file} is the assembly output stream and @var{type_id} is the KCFI
+type identifier to emit.  If @var{file} is NULL, skip emission and only
+return the size.  If not overridden, the default fallback emits a
+@code{.word} directive with the type ID and returns 4 bytes.  Targets can
+override this to emit different instruction sequences and return their
+corresponding sizes.
+@end deftypefn
+

@node Miscellaneous Register Hooks
@subsection Miscellaneous register hooks
@cindex miscellaneous register hooks

gcc/doc/tm.texi.in +1 -0
index c3ed9a9fd7c2..b2856886194c 100644
@@ -2433,6 +2433,7 @@ This describes the stack layout and calling conventions.
 * Tail Calls::
 * Shrink-wrapping separate components::
 * Stack Smashing Protection::
+* Kernel Control Flow Integrity::
 * Miscellaneous Register Hooks::

@end menu

gcc/doc/tm.texi.in +0 -0
@@ -3807,6 +3808,17 @@ generic code.
 

@hook TARGET_GET_VALID_OPTION_VALUES

+@node Kernel Control Flow Integrity
+@subsection Kernel Control Flow Integrity
+@cindex kernel control flow integrity
+@cindex KCFI

gcc/doc/tm.texi.in +7 -0
+
+@hook TARGET_KCFI_SUPPORTED
+
+@hook TARGET_KCFI_MASK_TYPE_ID
+
+@hook TARGET_KCFI_EMIT_TYPE_ID
+

@node Miscellaneous Register Hooks
@subsection Miscellaneous register hooks
@cindex miscellaneous register hooks

gcc/final.cc +0 -0
index afcb0bb9efbc..7f6aa9f9e480 100644
@@ -2094,6 +2094,9 @@ call_from_call_insn (const rtx_call_insn *insn)

case SET:
x = XEXP (x, 1);
break;
+ case KCFI:

gcc/final.cc +2 -0
+  x = XEXP (x, 0);
+  break;

}

    }

return x;

gcc/opts.cc +1 -0
index 3ab993aea573..0ee37e01d24a 100644
@@ -2170,6 +2170,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, ~sanitize_code_type (0), true, true),
 #undef SANITIZER_OPT
  { NULL, sanitize_code_type (0), 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 68ce53baa0f1..fd1bb0846801 100644
@@ -52,6 +52,7 @@ along with GCC; see the file COPYING3.  If not see
  NEXT_PASS (pass_ipa_auto_profile_offline);
  NEXT_PASS (pass_ipa_free_lang_data);
  NEXT_PASS (pass_ipa_function_and_variable_visibility);
+  NEXT_PASS (pass_ipa_kcfi);
  NEXT_PASS (pass_ipa_strub_mode);
  NEXT_PASS (pass_build_ssa_passes);
  PUSH_INSERT_PASSES_WITHIN (pass_build_ssa_passes)
@@ -275,6 +276,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 +445,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);
gcc/rtl.def +6 -0
index 15ae7d10fcc1..af643d187b95 100644
@@ -318,6 +318,12 @@ DEF_RTL_EXPR(CLOBBER, "clobber", "e", RTX_EXTRA)
 
 DEF_RTL_EXPR(CALL, "call", "ee", RTX_EXTRA)
 
+/* KCFI wrapper for call expressions.
+   Operand 0 is the call expression.
+   Operand 1 is the KCFI type ID (const_int).  */
+
+DEF_RTL_EXPR(KCFI, "kcfi", "ee", RTX_EXTRA)
+
 /* Return from a subroutine.  */
 
 DEF_RTL_EXPR(RETURN, "return", "", RTX_EXTRA)
gcc/rtlanal.cc +5 -0
index 63a1d08c46cf..4baa820b176e 100644
@@ -1177,6 +1177,11 @@ reg_referenced_p (const_rtx x, const_rtx body)
    case IF_THEN_ELSE:
      return reg_overlap_mentioned_p (x, body);
 
+    case KCFI:
+      /* For KCFI wrapper, check both the wrapped call and the type ID */
+      return (reg_overlap_mentioned_p (x, XEXP (body, 0))
+              || reg_overlap_mentioned_p (x, XEXP (body, 1)));
+
    case TRAP_IF:
      return reg_overlap_mentioned_p (x, TRAP_CONDITION (body));
 
gcc/target.def +38 -0
index 8e491d838642..47a11c60809a 100644
@@ -7589,6 +7589,44 @@ DEFHOOKPOD
 The default value is NULL.",
 const char *, NULL)
 
+/* Kernel Control Flow Integrity (KCFI) hooks.  */
+#undef HOOK_PREFIX
+#define HOOK_PREFIX "TARGET_KCFI_"
+HOOK_VECTOR (TARGET_KCFI, kcfi)
+
+DEFHOOK
+(supported,
+ "Return true if the target supports Kernel Control Flow Integrity (KCFI).\n\
+This hook indicates whether the target has implemented the necessary RTL\n\
+patterns and infrastructure to support KCFI instrumentation.  The default\n\
+implementation returns false.",
+ bool, (void),
+ hook_bool_void_false)
+
+DEFHOOK
+(mask_type_id,
+ "Apply architecture-specific masking to KCFI type ID.  This hook allows\n\
+targets to apply bit masks or other transformations to the computed KCFI\n\
+type identifier to match the target's specific requirements.  The default\n\
+implementation returns the type ID unchanged.",
+ uint32_t, (uint32_t type_id),
+ NULL)
+
+DEFHOOK
+(emit_type_id,
+ "Emit architecture-specific type ID instruction for KCFI preambles\n\
+and return the size of the instruction in bytes.\n\
+@var{file} is the assembly output stream and @var{type_id} is the KCFI\n\
+type identifier to emit.  If @var{file} is NULL, skip emission and only\n\
+return the size.  If not overridden, the default fallback emits a\n\
+@code{.word} directive with the type ID and returns 4 bytes.  Targets can\n\
+override this to emit different instruction sequences and return their\n\
+corresponding sizes.",
+ int, (FILE *file, uint32_t type_id),
+ NULL)
+
+HOOK_VECTOR_END (kcfi)
+
 /* Close the 'struct gcc_target' definition.  */
 HOOK_VECTOR_END (C90_EMPTY_HACK)
 
gcc/toplev.cc +11 -0
index d26467450e37..9078bb6318a9 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"
@@ -1739,6 +1740,16 @@ process_options ()
 "requires %<-fno-exceptions%>");
    }
 
+  if (flag_sanitize & SANITIZE_KCFI)
+    {
+      if (!targetm.kcfi.supported ())
+ sorry ("%<-fsanitize=kcfi%> not supported by this target");
+
+      /* KCFI is supported for only C at this time.  */
+      if (!lang_GNU_C ())
+ sorry ("%<-fsanitize=kcfi%> is only supported for C");
+    }
+
  HOST_WIDE_INT patch_area_size, patch_area_start;
  parse_and_check_patch_area (flag_patchable_function_entry, false,
     &patch_area_size, &patch_area_start);
gcc/tree-inline.cc +10 -0
index 08e642178ba5..e674e176f7d3 100644
@@ -2104,6 +2104,16 @@ copy_bb (copy_body_data *id, basic_block bb,
 /* Advance iterator now before stmt is moved to seq_gsi.  */
 gsi_next (&stmts_gsi);
 
+  /* If inlining from a function with no_sanitize("kcfi"), mark any
+     call statements in the inlined body with the flag so they skip
+     KCFI instrumentation.  */
+  if (is_gimple_call (stmt)
+      && !sanitize_flags_p (SANITIZE_KCFI, id->src_fn))
+    {
+      gcall *call = as_a <gcall *> (stmt);
+      gimple_call_set_inlined_from_kcfi_nosantize (call, true);
+    }
+
 if (gimple_nop_p (stmt))
     continue;
 
gcc/varasm.cc +7 -0
index 0d78f5b384fb..b897954fd0ea 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"
@@ -2199,6 +2200,9 @@ assemble_start_function (tree decl, const char *fnname)
  unsigned short patch_area_size = crtl->patch_area_size;
  unsigned short patch_area_entry = crtl->patch_area_entry;
 
+  /* Emit KCFI preamble before any patchable areas.  */
+  kcfi_emit_preamble (asm_out_file, decl, fnname);
+
  /* Emit the patching area before the entry label, if any.  */
  if (patch_area_entry > 0)
    targetm.asm_out.print_patchable_function_entry (asm_out_file,
@@ -2767,6 +2771,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;

gcc/varasm.cc assemble_external_real (tree decl) · line 2786

Quoted 10 lines
gcc/varasm.cc +10 -0
+      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);
+ }

The indentations of the above lines are off.

Thanks.

Qing

Quoted 42 lines
gcc/varasm.cc +19 -10
    }
 }
 #endif
@@ -7283,16 +7300,25 @@ default_elf_asm_named_section (const char *name, unsigned int flags,
 fprintf (asm_out_file, ",%d", flags & SECTION_ENTSIZE);
      if (flags & SECTION_LINK_ORDER)
 {
-  /* 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);
+  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);
 }
      if (HAVE_COMDAT_GROUP && (flags & SECTION_LINKONCE))
 {
Signature · 1 line
2.34.1
author
#10 lore raw

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

Quoted 9 lines · Qing Zhao

gcc/kcfi.cc line 164

Quoted 6 lines · Kees Cook
gcc/kcfi.cc new file +4 -0
+For indirect call sites:
+
+- Keeping indirect calls from being merged (see above) by adding a
+  wrapping type so that equality was tested based on type-id.

I still think that the additional new created wrapping type and the new assignment stmt

Quoted 7 lines

wrapper_tmp = (wrapper_ptr_type) fn
is not necessary.

All the information can be get from function type + type-id which is attached as an attribute to the original_function_type of “fn”.
Could you explain why the wrapper type and the new temporary, new assignment is necessary?

I couldn't find a way to stop merging just using the attributes. I need a way to directly associated indirect call sites with the typeid.

Quoted 6 lines

gcc/kcfi.cc line 167

Quoted 3 lines
gcc/kcfi.cc new file +3 -0
+
+- Keeping typeid information available through to the RTL expansion
+  phase was done via a new KCFI insn that wraps CALL and the typeid.

Is the new KCFI insn the following:
wrapper_tmp = (wrapper_ptr_type) fn?

This bullet is speaking about the backend change to support the KCFI check-call insn sequences:

+/* KCFI wrapper for call expressions.
+ Operand 0 is the call expression.
+ Operand 1 is the KCFI type ID (const_int). */
+
+DEF_RTL_EXPR(KCFI, "kcfi", "ee", RTX_EXTRA)

Quoted 1 line

Why the type-id attached as the attribute is not enough?

Doing the wrapping avoided needing to update multiple optimization passes to check for the attribute. And it still needed a way to distinguish between direct and indirect calls, so I need to wrap only the indirect calls, where as the typeid attribute is for all functions for all typeid needs, like preamble generation, etc.

Quoted 10 lines

gcc/kcfi.cc

Quoted 9 lines
gcc/kcfi.cc new file +9 -0
+
+- To make sure KCFI expansion is skipped for inline functions, the
+  inlining is marked during GIMPLE with a new flag which is checked
+  during expansion.
+
+For indirect call targets:
+
+- kcfi_emit_preamble() uses function_needs_kcfi_preamble(),
+  to emit the preablem,

Typo: preamble.

Fixed.

Quoted 7 lines

gcc/kcfi.cc line 219

Quoted 4 lines
gcc/kcfi.cc new file +4 -0
+HOST_WIDE_INT kcfi_patchable_entry_prefix_nops = 0;  /* For callsite offset */
+static HOST_WIDE_INT kcfi_patchable_entry_arch_alignment_nops = 0;  /* For preamble alignment */
+
+/* Common helper for RTL patterns to emit .kcfi_traps section entry.  */

there should be one empty line between the comments of the function and the start of the function. I noticed that you need such empty line for all the new functions you added. -:)

Oh! Wow, yeah, I totally missed this coding style requirement. Fixed.

Quoted 5 lines

gcc/kcfi.cc line 271

Quoted 3 lines
gcc/kcfi.cc new file +3 -0
+/* Check if a function needs KCFI preamble generation.
+   ALL functions get preambles when -fsanitize=kcfi is enabled, regardless
+   of no_sanitize("kcfi") attribute.  */

Why no_sanitize(“kcfi”) is not considered here?

no_sanitize(“kcfi”) is strictly about whether call-site checking is performed within the function. It is not used to mark a function as not being the target of a KCFI call.

Quoted 8 lines
Quoted 8 lines
gcc/kcfi.cc new file +8 -0
+/* Get KCFI type ID for a function declaration during assembly output phase.
+   Fatal error if type ID was not previously set during IPA phase.  */
+static uint32_t
+get_function_kcfi_type_id (tree fndecl)
+{
+  if (!kcfi_type_id_attr)
+    kcfi_type_id_attr = get_identifier ("kcfi_type_id");
+
Quoted 8 lines

gcc/kcfi.cc line 341

Quoted 7 lines
gcc/kcfi.cc new file +7 -0
+  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);

The indentation of above is off.

I understand GCC code style indentation to be "leading spans of 8 spaces should be replaced with a tab character". This is what I followed:

first line indents to column 6, so 6 spaces. Second line indents to column 8, so 1 tab:

SSSSSSif (TREE_CODE (value) == INTEGER_CST)
Treturn (uint32_t) TREE_INT_CST_LOW (value);

This seems to match everywhere else? Randomly picking line get_section() from varasm.cc, I see the same:

      if (not_existing)
	internal_error ("section already exists: %qs", name);
Quoted 3 lines

gcc/kcfi.cc line 386

Quoted 2 lines
gcc/kcfi.cc new file +2 -0
+  /* Calculate alignment NOPs needed */
+  arch_alignment = (alignment_bytes - ((kcfi_patchable_entry_prefix_nops + typeid_size) % alignment_bytes)) % alignment_bytes;

The above line is too long.

Oops, yes, thank you. Fixed.

What is the right tool for me to run to check for these kinds of code style glitches? contrib/check_GNU_style.py doesn't report anything. Oh! It takes _patches_ not _files_. The .sh version specifies "patch" in the help usage. Okay, I will get this all passing cleanly.

Quoted 38 lines
Quoted 38 lines
gcc/kcfi.cc new file +38 -0
+/* Wrap indirect calls with KCFI type for anti-merging.  */
+static unsigned int
+kcfi_instrument (void)
+{
+  /* Process current function for call instrumentation only.
+     Type ID setting is handled by the separate IPA pass.  */
+
+  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))
+    continue;
+
+  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)
+    continue;
+
+  tree fn = gimple_call_fn (call_stmt);
+  if (!is_kcfi_indirect_call (fn))
+    continue;
+
+  // Get the function type to compute KCFI type ID
+  tree fn_type = gimple_call_fntype (call_stmt);
+  gcc_assert (fn_type);
Quoted 8 lines

gcc/kcfi.cc line 584

Quoted 7 lines
gcc/kcfi.cc new file +7 -0
+  if (TREE_CODE (fn_type) != FUNCTION_TYPE)
+    continue;
+
+  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);

Again, the new “type_id” has been attached as an attribute of “fn_type” here,

The attribute is attached during IPA. This is run before that, but as I mentioned, this is the call-site handling, and the IPA pass is for globally associating a type-id to the function for all other uses (preambles, weak symbols, etc).

Quoted 4 lines
Quoted 4 lines
gcc/kcfi.cc new file +4 -0
+  // 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");
+
Quoted 8 lines

gcc/kcfi.cc line 594

Quoted 5 lines
gcc/kcfi.cc new file +5 -0
+  // 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);
+

Why the additional wrapper_ptr_type, wrapper_tmp and new assignment stmt Are needed here?

Based on my understanding of the requirements for GIMPLE here is that I needed a cast between the original and the wrapper, and an assignment for SSA. It's converting the call like:

Original: result = fn(arg1, arg2)
Becomes: result = wrapper(arg1, arg2, type_id)

I'm open to whatever alternative is needed here. I tried to capture the merging issue with gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c

My other test methodology is "does Linux boot?" ;)

Signature · 1 line
Kees Cook
#11 lore raw

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

Quoted 9 lines · Kees Cook
Quoted 5 lines

gcc/kcfi.cc line 271

Quoted 3 lines
gcc/kcfi.cc new file +3 -0
+/* Check if a function needs KCFI preamble generation.
+   ALL functions get preambles when -fsanitize=kcfi is enabled, regardless
+   of no_sanitize("kcfi") attribute.  */

Why no_sanitize(“kcfi”) is not considered here?

no_sanitize(“kcfi”) is strictly about whether call-site checking is performed within the function. It is not used to mark a function as not being the target of a KCFI call.

I'll once again argue that __attribute__((nocf_check)) (aka. __noendbr) should have that effect.

If there is no ENDBR, then no amount of kCFI preamble will make the function (indirectly) callable.

author
#12 lore raw

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

Quoted 12 lines · Peter Zijlstra
Quoted 9 lines · Kees Cook
Quoted 5 lines

gcc/kcfi.cc line 271

Quoted 3 lines
gcc/kcfi.cc new file +3 -0
+/* Check if a function needs KCFI preamble generation.
+   ALL functions get preambles when -fsanitize=kcfi is enabled, regardless
+   of no_sanitize("kcfi") attribute.  */

Why no_sanitize(“kcfi”) is not considered here?

no_sanitize(“kcfi”) is strictly about whether call-site checking is performed within the function. It is not used to mark a function as not being the target of a KCFI call.

Quoted 5 lines

I'll once again argue that __attribute__((nocf_check)) (aka. __noendbr) should have that effect.

If there is no ENDBR, then no amount of kCFI preamble will make the function (indirectly) callable.

Oh yeah, sure! I've added this for v3 now.

Signature · 1 line
Kees Cook
#13 lore raw

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

In reply to Kees Cook
Quoted 17 lines · Kees Cook
Quoted 12 lines · Qing Zhao

gcc/kcfi.cc line 164

Quoted 6 lines · Kees Cook
gcc/kcfi.cc new file +4 -0
+For indirect call sites:
+
+- Keeping indirect calls from being merged (see above) by adding a
+  wrapping type so that equality was tested based on type-id.

I still think that the additional new created wrapping type and the new assignment stmt

wrapper_tmp = (wrapper_ptr_type) fn
is not necessary.

Quoted 8 lines
Quoted 4 lines

All the information can be get from function type + type-id which is attached as an attribute to the original_function_type of “fn”.
Could you explain why the wrapper type and the new temporary, new assignment is necessary?

I couldn't find a way to stop merging just using the attributes. I need a way to directly associated indirect call sites with the typeid.

When determining whether two callsites should be merged, is it feasible to adding the different type_id from the attributes into consideration?

Quoted 10 lines
Quoted 6 lines

gcc/kcfi.cc line 167

Quoted 3 lines
gcc/kcfi.cc new file +3 -0
+
+- Keeping typeid information available through to the RTL expansion
+  phase was done via a new KCFI insn that wraps CALL and the typeid.

Is the new KCFI insn the following:
wrapper_tmp = (wrapper_ptr_type) fn?

This bullet is speaking about the backend change to support the KCFI check-call insn sequences:

gcc/rtl.def DEF_RTL_EXPR(CLOBBER, "clobber", "e", RTX_EXTRA) · line 325

Quoted 5 lines
gcc/rtl.def +5 -0
+/* KCFI wrapper for call expressions.
+   Operand 0 is the call expression.
+   Operand 1 is the KCFI type ID (const_int).  */
+
+DEF_RTL_EXPR(KCFI, "kcfi", "ee", RTX_EXTRA)

Okay, I see.

Quoted 8 lines
Quoted 2 lines

Why the type-id attached as the attribute is not enough?

Doing the wrapping avoided needing to update multiple optimization passes to check for the attribute. And it still needed a way to distinguish between direct and indirect calls, so I need to wrap only the indirect calls, where as the typeid attribute is for all functions for all typeid needs, like preamble generation, etc.

Okay, this sounds like a reasonable justification for these additional temporaries and assignment stmts.
One more question, are these additional temporaries and assignment stmts are finally eliminated by later optimizations? Any runtime overhead due to them?

Quoted 28 lines
Quoted 11 lines

gcc/kcfi.cc

Quoted 10 lines
gcc/kcfi.cc new file +9 -0
+
+- To make sure KCFI expansion is skipped for inline functions, the
+  inlining is marked during GIMPLE with a new flag which is checked
+  during expansion.
+
+For indirect call targets:
+
+- kcfi_emit_preamble() uses function_needs_kcfi_preamble(),
+  to emit the preablem,

Typo: preamble.

Fixed.

Quoted 7 lines

gcc/kcfi.cc line 219

Quoted 4 lines
gcc/kcfi.cc new file +4 -0
+HOST_WIDE_INT kcfi_patchable_entry_prefix_nops = 0;  /* For callsite offset */
+static HOST_WIDE_INT kcfi_patchable_entry_arch_alignment_nops = 0;  /* For preamble alignment */
+
+/* Common helper for RTL patterns to emit .kcfi_traps section entry.  */

there should be one empty line between the comments of the function and the start of the function. I noticed that you need such empty line for all the new functions you added. -:)

Oh! Wow, yeah, I totally missed this coding style requirement. Fixed.

Quoted 4 lines
Quoted 3 lines
gcc/kcfi.cc new file +3 -0
+/* Check if a function needs KCFI preamble generation.
+   ALL functions get preambles when -fsanitize=kcfi is enabled, regardless
+   of no_sanitize("kcfi") attribute.  */
Quoted 5 lines
Quoted 1 line

Why no_sanitize(“kcfi”) is not considered here?

no_sanitize(“kcfi”) is strictly about whether call-site checking is performed within the function. It is not used to mark a function as not being the target of a KCFI call.

Okay, is this documented somewhere?

Quoted 18 lines
Quoted 17 lines
Quoted 6 lines
gcc/kcfi.cc new file +5 -0
+/* Get KCFI type ID for a function declaration during assembly output phase.
+   Fatal error if type ID was not previously set during IPA phase.  */
+static uint32_t
+get_function_kcfi_type_id (tree fndecl)
+{

gcc/kcfi.cc line 341

Quoted 10 lines
gcc/kcfi.cc new file +10 -0
+  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);

The indentation of above is off.

Quoted 5 lines

I understand GCC code style indentation to be "leading spans of 8 spaces should be replaced with a tab character". This is what I followed:

first line indents to column 6, so 6 spaces. Second line indents to column 8, so 1 tab:

Yes, that’s right. -:)

Quoted 9 lines

SSSSSSif (TREE_CODE (value) == INTEGER_CST)
Treturn (uint32_t) TREE_INT_CST_LOW (value);

This seems to match everywhere else? Randomly picking line get_section() from varasm.cc, I see the same:

if (not_existing)
internal_error ("section already exists: %qs", name);

Okay. (I guess that the mail client has some issues….)

Quoted 11 lines
Quoted 4 lines

gcc/kcfi.cc line 386

Quoted 3 lines
gcc/kcfi.cc new file +2 -0
+  /* Calculate alignment NOPs needed */
+  arch_alignment = (alignment_bytes - ((kcfi_patchable_entry_prefix_nops + typeid_size) % alignment_bytes)) % alignment_bytes;

The above line is too long.

Oops, yes, thank you. Fixed.

What is the right tool for me to run to check for these kinds of code style glitches? contrib/check_GNU_style.py doesn't report anything. Oh! It takes _patches_ not _files_. The .sh version specifies "patch" in the help usage. Okay, I will get this all passing cleanly.

Yeah, I usually use contrib/check_GNU_style.py to cleanup the code before submitting the patch.

Quoted 48 lines
Quoted 39 lines
Quoted 39 lines
gcc/kcfi.cc new file +38 -0
+/* Wrap indirect calls with KCFI type for anti-merging.  */
+static unsigned int
+kcfi_instrument (void)
+{
+  /* Process current function for call instrumentation only.
+     Type ID setting is handled by the separate IPA pass.  */
+
+  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))
+    continue;
+
+  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)
+    continue;
+
+  tree fn = gimple_call_fn (call_stmt);
+  if (!is_kcfi_indirect_call (fn))
+    continue;
+
+  // Get the function type to compute KCFI type ID
+  tree fn_type = gimple_call_fntype (call_stmt);
+  gcc_assert (fn_type);
Quoted 8 lines

gcc/kcfi.cc line 584

Quoted 7 lines
gcc/kcfi.cc new file +7 -0
+  if (TREE_CODE (fn_type) != FUNCTION_TYPE)
+    continue;
+
+  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);

Again, the new “type_id” has been attached as an attribute of “fn_type” here,

Quoted 4 lines

The attribute is attached during IPA. This is run before that, but as I mentioned, this is the call-site handling, and the IPA pass is for globally associating a type-id to the function for all other uses (preambles, weak symbols, etc).

During IPA, the typeid is attached to the function type through “set_function_kcfi_type_id” for each function in the callgraph.

For each indirect callsite in the above, the routine “create_kcfi_wrapper_type” also attaches the typeid to the original_fn_type, and at the same time, create a new wrapper_type with a type_name embedding the typeid.

So, I feel the type_id information is carried redundantly here.

Quoted 13 lines
Quoted 4 lines
Quoted 4 lines
gcc/kcfi.cc new file +4 -0
+  // 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");
+
Quoted 8 lines

gcc/kcfi.cc line 594

Quoted 5 lines
gcc/kcfi.cc new file +5 -0
+  // 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);
+

Why the additional wrapper_ptr_type, wrapper_tmp and new assignment stmt Are needed here?

Quoted 6 lines

Based on my understanding of the requirements for GIMPLE here is that I needed a cast between the original and the wrapper, and an assignment for SSA. It's converting the call like:

Original: result = fn(arg1, arg2)
Becomes: result = wrapper(arg1, arg2, type_id)

Yeah, the gimples are correct.
The concerns I have is, whether these additional temporizes and stmts impact Optimization and also incur any runtime overhead.

Quoted 3 lines

I'm open to whatever alternative is needed here. I tried to capture the merging issue with gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c

Might need to study a little bit here to see whether better solution is possible without These additional temporizes and stmts.

Qing

Quoted 5 lines

My other test methodology is "does Linux boot?" ;)

Signature · 1 line
Kees Cook
author
#14 lore raw

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

Quoted 22 lines · Qing Zhao
Quoted 22 lines · Kees Cook
Quoted 16 lines · Qing Zhao

gcc/kcfi.cc line 164

Quoted 6 lines · Kees Cook
gcc/kcfi.cc new file +4 -0
+For indirect call sites:
+
+- Keeping indirect calls from being merged (see above) by adding a
+  wrapping type so that equality was tested based on type-id.

I still think that the additional new created wrapping type and the new assignment stmt

wrapper_tmp = (wrapper_ptr_type) fn
is not necessary.

All the information can be get from function type + type-id which is attached as an attribute to the original_function_type of “fn”.
Could you explain why the wrapper type and the new temporary, new assignment is necessary?

Quoted 5 lines
Quoted 3 lines

I couldn't find a way to stop merging just using the attributes. I need a way to directly associated indirect call sites with the typeid.

When determining whether two callsites should be merged, is it feasible to adding the different type_id from the attributes into consideration?

This is basically what was happening in the RFC, but I kept finding new corner cases in various passes, so it felt like whack-a-mole. Using the wrapper appeared to solve it across the board with no special casing.

Quoted 8 lines
Quoted 7 lines
Quoted 1 line

Why the type-id attached as the attribute is not enough?

Doing the wrapping avoided needing to update multiple optimization passes to check for the attribute. And it still needed a way to distinguish between direct and indirect calls, so I need to wrap only the indirect calls, where as the typeid attribute is for all functions for all typeid needs, like preamble generation, etc.

Quoted 4 lines

Okay, this sounds like a reasonable justification for these additional temporaries and assignment stmts.
One more question, are these additional temporaries and assignment stmts are finally eliminated by later optimizations? Any runtime overhead due to them?

Yeah, they totally vanish as far as I've been able to determine.

Quoted 11 lines
Quoted 9 lines
Quoted 5 lines

gcc/kcfi.cc line 271

Quoted 3 lines
gcc/kcfi.cc new file +3 -0
+/* Check if a function needs KCFI preamble generation.
+   ALL functions get preambles when -fsanitize=kcfi is enabled, regardless
+   of no_sanitize("kcfi") attribute.  */

Why no_sanitize(“kcfi”) is not considered here?

no_sanitize(“kcfi”) is strictly about whether call-site checking is performed within the function. It is not used to mark a function as not being the target of a KCFI call.

Okay, is this documented somewhere?

Ah, whoops, no. I have added a note to the "no_sanitize" function attribute docs for v3.

Quoted 7 lines
Quoted 4 lines

What is the right tool for me to run to check for these kinds of code style glitches? contrib/check_GNU_style.py doesn't report anything. Oh! It takes _patches_ not _files_. The .sh version specifies "patch" in the help usage. Okay, I will get this all passing cleanly.

Yeah, I usually use contrib/check_GNU_style.py to cleanup the code before submitting the patch.

Thanks!

Quoted 51 lines
Quoted 47 lines
Quoted 38 lines
Quoted 38 lines
gcc/kcfi.cc new file +38 -0
+/* Wrap indirect calls with KCFI type for anti-merging.  */
+static unsigned int
+kcfi_instrument (void)
+{
+  /* Process current function for call instrumentation only.
+     Type ID setting is handled by the separate IPA pass.  */
+
+  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))
+    continue;
+
+  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)
+    continue;
+
+  tree fn = gimple_call_fn (call_stmt);
+  if (!is_kcfi_indirect_call (fn))
+    continue;
+
+  // Get the function type to compute KCFI type ID
+  tree fn_type = gimple_call_fntype (call_stmt);
+  gcc_assert (fn_type);
Quoted 8 lines

gcc/kcfi.cc line 584

Quoted 7 lines
gcc/kcfi.cc new file +7 -0
+  if (TREE_CODE (fn_type) != FUNCTION_TYPE)
+    continue;
+
+  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);

Again, the new “type_id” has been attached as an attribute of “fn_type” here,

Quoted 4 lines

The attribute is attached during IPA. This is run before that, but as I mentioned, this is the call-site handling, and the IPA pass is for globally associating a type-id to the function for all other uses (preambles, weak symbols, etc).

Quoted 8 lines

During IPA, the typeid is attached to the function type through “set_function_kcfi_type_id” for each function in the callgraph.

For each indirect callsite in the above, the routine “create_kcfi_wrapper_type” also attaches the typeid to the original_fn_type, and at the same time, create a new wrapper_type with a type_name embedding the typeid.

So, I feel the type_id information is carried redundantly here.

Ah! Yes, sorry, I see what you mean: the tail portion of create_kcfi_wrapper_type! Yeah, this is kind of a oversight from switching to the IPA pass. I was attaching the typeid to DECLs in IPA and TYPEs in GIMPLE (create_kcfi_wrapper_type). The DECLs were used for preambles, and the TYPEs were used for RTL expansion. I will attempt to merge these; they should all be on the TYPE.

Quoted 5 lines
Quoted 2 lines

I'm open to whatever alternative is needed here. I tried to capture the merging issue with gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c

Might need to study a little bit here to see whether better solution is possible without These additional temporizes and stmts.

Thanks!

Signature · 1 line
Kees Cook
#15 lore raw

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

Quoted 30 lines · Kees Cook
Quoted 25 lines · Qing Zhao
Quoted 25 lines · Kees Cook
Quoted 9 lines · Qing Zhao

gcc/kcfi.cc line 164

Quoted 6 lines · Kees Cook
gcc/kcfi.cc new file +4 -0
+For indirect call sites:
+
+- Keeping indirect calls from being merged (see above) by adding a
+  wrapping type so that equality was tested based on type-id.

I still think that the additional new created wrapping type and the new assignment stmt

Quoted 7 lines

wrapper_tmp = (wrapper_ptr_type) fn
is not necessary.

All the information can be get from function type + type-id which is attached as an attribute to the original_function_type of “fn”.
Could you explain why the wrapper type and the new temporary, new assignment is necessary?

I couldn't find a way to stop merging just using the attributes. I need a way to directly associated indirect call sites with the typeid.

Quoted 6 lines
Quoted 2 lines

When determining whether two callsites should be merged, is it feasible to adding the different type_id from the attributes into consideration?

This is basically what was happening in the RFC, but I kept finding new corner cases in various passes, so it felt like whack-a-mole. Using the wrapper appeared to solve it across the board with no special casing.

Okay, if this is the case, I think that it’s better to explain the reason in the design doc on why you finally decide to add the wrapper function instead of directly using the type_id from the attribute for comparison. What’s the issues when directly using the type_id from the attribute, why only the new wrapper type and function works?

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 2 lines

Why the type-id attached as the attribute is not enough?

Doing the wrapping avoided needing to update multiple optimization passes to check for the attribute.

Do you remember which optimization passes need to be updated for these purpose?

Quoted 11 lines
Quoted 9 lines
Quoted 4 lines

And it still needed a way to distinguish
between direct and indirect calls, so I need to wrap only the indirect calls, where as the typeid attribute is for all functions for all typeid needs, like preamble generation, etc.

Okay, this sounds like a reasonable justification for these additional temporaries and assignment stmts.
One more question, are these additional temporaries and assignment stmts are finally eliminated by later optimizations? Any runtime overhead due to them?

Yeah, they totally vanish as far as I've been able to determine.

That’s good. Then you might add this too in the design doc as a justification of the New wrapper type, temporaries and new assignment stmt.

thanks.

Qing

Quoted 103 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 4 lines
gcc/kcfi.cc new file +3 -0
+/* Check if a function needs KCFI preamble generation.
+   ALL functions get preambles when -fsanitize=kcfi is enabled, regardless
+   of no_sanitize("kcfi") attribute.  */
Quoted 7 lines
Quoted 5 lines
Quoted 1 line

Why no_sanitize(“kcfi”) is not considered here?

no_sanitize(“kcfi”) is strictly about whether call-site checking is performed within the function. It is not used to mark a function as not being the target of a KCFI call.

Okay, is this documented somewhere?

Ah, whoops, no. I have added a note to the "no_sanitize" function attribute docs for v3.

Quoted 7 lines
Quoted 4 lines

What is the right tool for me to run to check for these kinds of code style glitches? contrib/check_GNU_style.py doesn't report anything. Oh! It takes _patches_ not _files_. The .sh version specifies "patch" in the help usage. Okay, I will get this all passing cleanly.

Yeah, I usually use contrib/check_GNU_style.py to cleanup the code before submitting the patch.

Thanks!

Quoted 51 lines
Quoted 47 lines
Quoted 38 lines
Quoted 38 lines
gcc/kcfi.cc new file +38 -0
+/* Wrap indirect calls with KCFI type for anti-merging.  */
+static unsigned int
+kcfi_instrument (void)
+{
+  /* Process current function for call instrumentation only.
+     Type ID setting is handled by the separate IPA pass.  */
+
+  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))
+    continue;
+
+  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)
+    continue;
+
+  tree fn = gimple_call_fn (call_stmt);
+  if (!is_kcfi_indirect_call (fn))
+    continue;
+
+  // Get the function type to compute KCFI type ID
+  tree fn_type = gimple_call_fntype (call_stmt);
+  gcc_assert (fn_type);
Quoted 8 lines

gcc/kcfi.cc line 584

Quoted 7 lines
gcc/kcfi.cc new file +7 -0
+  if (TREE_CODE (fn_type) != FUNCTION_TYPE)
+    continue;
+
+  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);

Again, the new “type_id” has been attached as an attribute of “fn_type” here,

Quoted 4 lines

The attribute is attached during IPA. This is run before that, but as I mentioned, this is the call-site handling, and the IPA pass is for globally associating a type-id to the function for all other uses (preambles, weak symbols, etc).

Quoted 8 lines

During IPA, the typeid is attached to the function type through “set_function_kcfi_type_id” for each function in the callgraph.

For each indirect callsite in the above, the routine “create_kcfi_wrapper_type” also attaches the typeid to the original_fn_type, and at the same time, create a new wrapper_type with a type_name embedding the typeid.

So, I feel the type_id information is carried redundantly here.

Ah! Yes, sorry, I see what you mean: the tail portion of create_kcfi_wrapper_type! Yeah, this is kind of a oversight from switching to the IPA pass. I was attaching the typeid to DECLs in IPA and TYPEs in GIMPLE (create_kcfi_wrapper_type). The DECLs were used for preambles, and the TYPEs were used for RTL expansion. I will attempt to merge these; they should all be on the TYPE.

Quoted 5 lines
Quoted 2 lines

I'm open to whatever alternative is needed here. I tried to capture the merging issue with gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c

Might need to study a little bit here to see whether better solution is possible without These additional temporizes and stmts.

Thanks!

Signature · 1 line
Kees Cook
author
#16 lore raw

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

Quoted 8 lines · Qing Zhao
Quoted 8 lines · Kees Cook
Quoted 4 lines · Qing Zhao
Quoted 4 lines · Kees Cook
Quoted 8 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines · Qing Zhao
Quoted 2 lines

Why the type-id attached as the attribute is not enough?

Doing the wrapping avoided needing to update multiple optimization passes to check for the attribute.

Do you remember which optimization passes need to be updated for these purpose?

I had patched at least old_insns_match_p:
https://lore.kernel.org/linux-hardening/[email protected]/#Z31gcc:cfgcleanup.cc

The rest that I patched were about dealing with retaining notes, which aren't used any more now (an attribute is used, not a note).

Quoted 10 lines
Quoted 10 lines
Quoted 9 lines
Quoted 4 lines

And it still needed a way to distinguish
between direct and indirect calls, so I need to wrap only the indirect calls, where as the typeid attribute is for all functions for all typeid needs, like preamble generation, etc.

Okay, this sounds like a reasonable justification for these additional temporaries and assignment stmts.
One more question, are these additional temporaries and assignment stmts are finally eliminated by later optimizations? Any runtime overhead due to them?

Quoted 4 lines
Quoted 1 line

Yeah, they totally vanish as far as I've been able to determine.

That’s good. Then you might add this too in the design doc as a justification of the New wrapper type, temporaries and new assignment stmt.

I spent some time today experimenting with annotations and discovered that the KCFI RTL changes actually ended up solving all the issue I'd found. Combined with moving the DECL attributes to TYPE attributes, everything got MUCH simpler. I'll send v3 out soon with all of this redundancy removed. I want to test it a little more first.

Signature · 1 line
Kees Cook
author
#17 lore raw

PATCH v2 3/7 x86: Add x86_64 Kernel Control Flow Integrity implementation

In reply to Kees Cook

Implement x86_64-specific KCFI backend:

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

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

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

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

- On-demand scratch register allocation strategy (r11 as needed). The clobbers are available both early and late.

- 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 .Lkcfi_call                 ; Branch if types match (sum == 0)
  .Lkcfi_trap: ud2               ; Undefined instruction trap on mismatch

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

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

gcc/ChangeLog:

	config/i386/i386.h: KCFI enables TARGET_INDIRECT_BRANCH_REGISTER.
	config/i386/i386-protos.h: Declare ix86_output_kcfi_insn().
	config/i386/i386-expand.cc (ix86_expand_call): Expand indirect
	calls into KCFI RTL.
	config/i386/i386.cc (ix86_kcfi_mask_type_id): New function.
	(ix86_output_kcfi_insn): New function to emit KCFI assembly.
	config/i386/i386.md: Add KCFI RTL patterns.
	doc/invoke.texi: Document x86 nuances.
---
 gcc/config/i386/i386-protos.h  |   1 +
 gcc/config/i386/i386.h         |   3 +-
 gcc/config/i386/i386-expand.cc |  21 +++++-
 gcc/config/i386/i386.cc        | 118 +++++++++++++++++++++++++++++++++
 gcc/config/i386/i386.md        |  62 +++++++++++++++--
 gcc/doc/invoke.texi            |  23 +++++++
 6 files changed, 220 insertions(+), 8 deletions(-)
gcc/config/i386/i386-protos.h +1 -0
index bdb8bb963b5d..b0b3864fb53c 100644
@@ -377,6 +377,7 @@ extern enum attr_cpu ix86_schedule;
 
 extern bool ix86_nopic_noplt_attribute_p (rtx call_op);
 extern const char * ix86_output_call_insn (rtx_insn *insn, rtx call_op);
+extern const char * ix86_output_kcfi_insn (rtx_insn *insn, rtx *operands);
 extern const char * ix86_output_indirect_jmp (rtx call_op);
 extern const char * ix86_output_function_return (bool long_p);
 extern const char * ix86_output_indirect_function_return (rtx ret_op);
gcc/config/i386/i386.h +2 -1
index 2d53db683176..5c6012ac743b 100644
@@ -3038,7 +3038,8 @@ extern void debug_dispatch_window (int);
 
 #define TARGET_INDIRECT_BRANCH_REGISTER \
   (ix86_indirect_branch_register \
-   || cfun->machine->indirect_branch_type != indirect_branch_keep)
+   || cfun->machine->indirect_branch_type != indirect_branch_keep \
+   || (flag_sanitize & SANITIZE_KCFI))
 
 #define IX86_HLE_ACQUIRE (1 << 16)
 #define IX86_HLE_RELEASE (1 << 17)
gcc/config/i386/i386-expand.cc +18 -3
index ef6c12cd5697..2a7feffa7ebc 100644
@@ -94,6 +94,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "i386-builtins.h"
 #include "i386-expand.h"
 #include "asan.h"
+#include "kcfi.h"
 
 /* Split one or more double-mode RTL references into pairs of half-mode
    references.  The RTL can be REG, offsettable MEM, integer constant, or
@@ -10279,8 +10280,9 @@ ix86_expand_call (rtx retval, rtx fnaddr, rtx callarg1,
   unsigned int vec_len = 0;
   tree fndecl;
   bool call_no_callee_saved_registers = false;
+  bool is_direct_call = SYMBOL_REF_P (XEXP (fnaddr, 0));
 
-  if (SYMBOL_REF_P (XEXP (fnaddr, 0)))
+  if (is_direct_call)
     {
       fndecl = SYMBOL_REF_DECL (XEXP (fnaddr, 0));
       if (fndecl)
@@ -10317,7 +10319,7 @@ ix86_expand_call (rtx retval, rtx fnaddr, rtx callarg1,
   if (TARGET_MACHO && !TARGET_64BIT)
     {
 #if TARGET_MACHO
-      if (flag_pic && SYMBOL_REF_P (XEXP (fnaddr, 0)))
+      if (flag_pic && is_direct_call)
 	fnaddr = machopic_indirect_call_target (fnaddr);
 #endif
     }
@@ -10401,7 +10403,7 @@ ix86_expand_call (rtx retval, rtx fnaddr, rtx callarg1,
   if (ix86_cmodel == CM_LARGE_PIC
       && !TARGET_PECOFF
       && MEM_P (fnaddr)
-      && SYMBOL_REF_P (XEXP (fnaddr, 0))
+      && is_direct_call
       && !local_symbolic_operand (XEXP (fnaddr, 0), VOIDmode))
     fnaddr = gen_rtx_MEM (QImode, construct_plt_address (XEXP (fnaddr, 0)));
   /* Since x32 GOT slot is 64 bit with zero upper 32 bits, indirect
@@ -10433,6 +10435,19 @@ ix86_expand_call (rtx retval, rtx fnaddr, rtx callarg1,
 
   call = gen_rtx_CALL (VOIDmode, fnaddr, callarg1);
 
+  /* Only indirect calls need KCFI instrumentation.  */
+  rtx kcfi_type_rtx = is_direct_call ? NULL_RTX : kcfi_get_call_type_id ();
+  if (kcfi_type_rtx)
+    {
+      /* Wrap call with KCFI.  */
+      call = gen_rtx_KCFI (VOIDmode, call, kcfi_type_rtx);
+
+      /* Add KCFI clobbers for the insn sequence.  */
+      clobber_reg (&use, gen_rtx_REG (DImode, R10_REG));
+      clobber_reg (&use, gen_rtx_REG (DImode, R11_REG));
+      clobber_reg (&use, gen_rtx_REG (CCmode, FLAGS_REG));
+    }
+
   if (retval)
     call = gen_rtx_SET (retval, call);
   vec[vec_len++] = call;
gcc/config/i386/i386.cc +118 -0

136 lines not on this page · raw message

gcc/config/i386/i386.md +58 -4

104 lines not on this page · raw message

gcc/doc/invoke.texi +23 -0
index cd70e6351a4e..d44e7015facf 100644
@@ -18404,6 +18404,29 @@ 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.  KCFI automatically
+implies @option{-mindirect-branch-register}, forcing all indirect calls
+and jumps to use registers instead of memory operands.  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
author
#18 lore raw

PATCH v2 4/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 default alignment NOPs needed due to fixed 4-byte instruction size).

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

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

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

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

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

Build and run tested with Linux kernel ARCH=arm64.

gcc/ChangeLog:

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

---
 gcc/config/aarch64/aarch64-protos.h |   5 ++
 gcc/config/aarch64/aarch64.cc       | 115 ++++++++++++++++++++++++++++
 gcc/config/aarch64/aarch64.md       |  64 ++++++++++++++--
 gcc/doc/invoke.texi                 |  14 ++++
 4 files changed, 190 insertions(+), 8 deletions(-)
gcc/config/aarch64/aarch64-protos.h +5 -0
index 56efcf2c7f2c..c91fdcc80ea3 100644
@@ -1261,6 +1261,7 @@ tree aarch64_resolve_overloaded_builtin_general (location_t, tree, void *);
 
 const char *aarch64_sls_barrier (int);
 const char *aarch64_indirect_call_asm (rtx);
+const char *aarch64_indirect_branch_asm (rtx);
 extern bool aarch64_harden_sls_retbr_p (void);
 extern bool aarch64_harden_sls_blr_p (void);
 
@@ -1284,4 +1285,8 @@ extern unsigned aarch64_stack_alignment (const_tree exp, unsigned align);
 extern rtx aarch64_gen_compare_zero_and_branch (rtx_code code, rtx x,
 						rtx_code_label *label);
 
+/* KCFI support.  */
+extern void kcfi_emit_trap_with_section (FILE *file, rtx trap_label_rtx);
+extern const char *aarch64_output_kcfi_insn (rtx_insn *insn, rtx *operands);
+
 #endif /* GCC_AARCH64_PROTOS_H */
gcc/config/aarch64/aarch64.cc +115 -0

145 lines not on this page · raw message

gcc/config/aarch64/aarch64.md +56 -8

100 lines not on this page · raw message

gcc/doc/invoke.texi +14 -0
index d44e7015facf..45efc75a3b05 100644
@@ -18427,6 +18427,20 @@ 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
#19 lore raw

PATCH v2 5/7 arm: Add ARM 32-bit Kernel Control Flow Integrity implementation

In reply to Kees Cook

Implement ARM 32-bit KCFI backend supporting ARMv7+:

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

- Use movw/movt instructions for 32-bit immediate loading.

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

- Scratch register allocation using r0/r1 following ARM procedure call standard for caller-saved temporary registers, though they get stack spilled due to register pressure.

Assembly Code Pattern for ARM 32-bit:

  push {r0, r1}                ; Spill r0, r1
  ldr  r0, [target, #-4]       ; Load actual type ID from preamble
  movw r1, #type_id_low        ; Load expected type (lower 16 bits)
  movt r1, #type_id_high       ; Load upper 16 bits with top instruction
  cmp  r0, r1                  ; Compare type IDs directly
  pop [r0, r1]                 ; Reload r0, r1
  beq  .Lkcfi_call             ; Branch if typeids match
  .Lkcfi_trap: udf #udf_value  ; Undefined instruction trap with encoding
  .Lkcfi_call: blx/bx target   ; Execute validated indirect transfer

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

Build and run tested with Linux kernel ARCH=arm.

gcc/ChangeLog:

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

---
 gcc/config/arm/arm-protos.h |   4 +
 gcc/config/arm/arm.cc       | 144 ++++++++++++++++++++++++++++++++++++
 gcc/config/arm/arm.md       |  62 ++++++++++++++++
 gcc/doc/invoke.texi         |  17 +++++
 4 files changed, 227 insertions(+)
gcc/config/arm/arm-protos.h +4 -0
index ff7e7658f912..ad3dc522e2b9 100644
@@ -607,6 +607,10 @@ void arm_initialize_isa (sbitmap, const enum isa_feature *);
 
 const char * arm_gen_far_branch (rtx *, int, const char * , const char *);
 
+rtx arm_maybe_wrap_call_with_kcfi (rtx, rtx);
+rtx arm_maybe_wrap_call_value_with_kcfi (rtx, rtx);
+const char *arm_output_kcfi_insn (rtx_insn *, rtx *);
+
 bool arm_mve_immediate_check(rtx, machine_mode, bool);
 
 opt_machine_mode arm_mve_data_mode (scalar_mode, poly_uint64);
gcc/config/arm/arm.cc +144 -0

156 lines not on this page · raw message

gcc/config/arm/arm.md +62 -0

109 lines not on this page · raw message

gcc/doc/invoke.texi +17 -0
index 45efc75a3b05..25ee82c9cba7 100644
@@ -18441,6 +18441,23 @@ trap is taken, allowing the kernel to identify both the KCFI violation
 and the involved registers for detailed diagnostics (eliminating the need
 for a separate @code{.kcfi_traps} section as used on x86_64).
 
+On ARM 32-bit, KCFI type identifiers are emitted as a @code{.word ID}
+directive (a 32-bit constant) before the function entry.  ARM's
+natural 4-byte instruction alignment eliminates the need for additional
+padding NOPs.  When used with @option{-fpatchable-function-entry}, the
+type identifier is placed before any patchable NOPs.  The runtime check
+preserves argument registers @code{r0} and @code{r1} using @code{push}
+and @code{pop} instructions, then uses them as scratch registers for
+the type comparison.  The expected type is loaded using @code{movw} and
+@code{movt} instruction pairs for 32-bit immediate values.  Type mismatches
+trigger a @code{udf} instruction with an immediate value that encodes
+both the expected type register index and the target address register
+index in the format @code{0x8000 | (type_reg << 5) | addr_reg}.  This
+encoding is captured in the UDF immediate field when the trap is taken,
+allowing the kernel to identify both the KCFI violation and the involved
+registers for detailed diagnostics (eliminating the need for a separate
+@code{.kcfi_traps} section as used on x86_64).
+
 KCFI is intended primarily for kernel code and may not be suitable
 for user-space applications that rely on techniques incompatible
 with strict type checking of indirect calls.
Signature · 1 line
2.34.1
#20 lore raw

Re: [PATCH v2 5/7] arm: Add ARM 32-bit Kernel Control Flow Integrity implementation

Quoted 16 lines · Kees Cook

Implement ARM 32-bit KCFI backend supporting ARMv7+:

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

- Use movw/movt instructions for 32-bit immediate loading.

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

- Scratch register allocation using r0/r1 following ARM procedure call standard for caller-saved temporary registers, though they get stack spilled due to register pressure.

Quoted 7 lines

Assembly Code Pattern for ARM 32-bit:

  push {r0, r1}                ; Spill r0, r1
  ldr  r0, [target, #-4]       ; Load actual type ID from preamble
  movw r1, #type_id_low        ; Load expected type (lower 16 bits)
  movt r1, #type_id_high       ; Load upper 16 bits with top instruction
  cmp  r0, r1                  ; Compare type IDs directly
  pop [r0, r1]                 ; Reload r0, r1

We could avoid the MOVW/MOVT pair and the spilling by doing something along the lines of

ldr   ip, [target, #-4]
eor   ip, ip, #type_id[0]
eor   ip, ip, #type_id[1] << 8
eor   ip, ip, #type_id[2] << 16
eors  ip, ip, #type_id[3] << 24

ldrne ip, =type_id[3:0]

Note that IP (R12) should be dead before a function call. Here it is conditionally loaded with the expected target typeid, removing the need to decode the instructions to recover it when the trap occurs.

This should compile to Thumb2 as well as ARM encodings.

Quoted 30 lines
  beq  .Lkcfi_call             ; Branch if typeids match
  .Lkcfi_trap: udf #udf_value  ; Undefined instruction trap with encoding
  .Lkcfi_call: blx/bx target   ; Execute validated indirect transfer

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

Build and run tested with Linux kernel ARCH=arm.

gcc/ChangeLog:

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

---
 gcc/config/arm/arm-protos.h |   4 +
 gcc/config/arm/arm.cc       | 144 ++++++++++++++++++++++++++++++++++++
 gcc/config/arm/arm.md       |  62 ++++++++++++++++
 gcc/doc/invoke.texi         |  17 +++++
 4 files changed, 227 insertions(+)
author
#21 lore raw

Re: [PATCH v2 5/7] arm: Add ARM 32-bit Kernel Control Flow Integrity implementation

Quoted 28 lines · Ard Biesheuvel
Quoted 16 lines · Kees Cook

Implement ARM 32-bit KCFI backend supporting ARMv7+:

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

- Use movw/movt instructions for 32-bit immediate loading.

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

- Scratch register allocation using r0/r1 following ARM procedure call standard for caller-saved temporary registers, though they get stack spilled due to register pressure.

Quoted 7 lines

Assembly Code Pattern for ARM 32-bit:

  push {r0, r1}                ; Spill r0, r1
  ldr  r0, [target, #-4]       ; Load actual type ID from preamble
  movw r1, #type_id_low        ; Load expected type (lower 16 bits)
  movt r1, #type_id_high       ; Load upper 16 bits with top instruction
  cmp  r0, r1                  ; Compare type IDs directly
  pop [r0, r1]                 ; Reload r0, r1

We could avoid the MOVW/MOVT pair and the spilling by doing something along the lines of

Quoted 6 lines
ldr   ip, [target, #-4]
eor   ip, ip, #type_id[0]
eor   ip, ip, #type_id[1] << 8
eor   ip, ip, #type_id[2] << 16
eors  ip, ip, #type_id[3] << 24

ldrne ip, =type_id[3:0]

Ah-ha, nice. And it could re-load the type_id on the slow path instead of unconditionally, I guess? (So no "ne" suffix needed there.)

...
eors ip, ip, #type_id[3] << 24
beq .Lkcfi_call
.Lkcfi_trap:
ldr ip, =type_id[3:0]
udf #nnn
.Lkcfi_call:
blx target

Quoted 6 lines

Note that IP (R12) should be dead before a function call. Here it is conditionally loaded with the expected target typeid, removing the need to decode the instructions to recover it when the trap occurs.

This should compile to Thumb2 as well as ARM encodings.

Won't IP get used as the target register if r0-r3 are used for passing arguments? AAPCS implies this is how it'll go (4 arguments in registers, the rest on stack), but when I tried to force this to happen, it looked like it'd only pass 3 via registers, and would make the call with r3.

I can't see if this is safe to unconditionally use IP?

Signature · 1 line
Kees Cook
author
#22 lore raw

Re: [PATCH v2 5/7] arm: Add ARM 32-bit Kernel Control Flow Integrity implementation

Quoted 54 lines · Kees Cook
Quoted 28 lines · Ard Biesheuvel
Quoted 16 lines · Kees Cook

Implement ARM 32-bit KCFI backend supporting ARMv7+:

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

- Use movw/movt instructions for 32-bit immediate loading.

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

- Scratch register allocation using r0/r1 following ARM procedure call standard for caller-saved temporary registers, though they get stack spilled due to register pressure.

Quoted 7 lines

Assembly Code Pattern for ARM 32-bit:

  push {r0, r1}                ; Spill r0, r1
  ldr  r0, [target, #-4]       ; Load actual type ID from preamble
  movw r1, #type_id_low        ; Load expected type (lower 16 bits)
  movt r1, #type_id_high       ; Load upper 16 bits with top instruction
  cmp  r0, r1                  ; Compare type IDs directly
  pop [r0, r1]                 ; Reload r0, r1

We could avoid the MOVW/MOVT pair and the spilling by doing something along the lines of

Quoted 6 lines
ldr   ip, [target, #-4]
eor   ip, ip, #type_id[0]
eor   ip, ip, #type_id[1] << 8
eor   ip, ip, #type_id[2] << 16
eors  ip, ip, #type_id[3] << 24

ldrne ip, =type_id[3:0]

Ah-ha, nice. And it could re-load the type_id on the slow path instead of unconditionally, I guess? (So no "ne" suffix needed there.)

...
eors ip, ip, #type_id[3] << 24
beq .Lkcfi_call
.Lkcfi_trap:
ldr ip, =type_id[3:0]
udf #nnn
.Lkcfi_call:
blx target

Quoted 5 lines

Note that IP (R12) should be dead before a function call. Here it is conditionally loaded with the expected target typeid, removing the need to decode the instructions to recover it when the trap occurs.

Quoted 6 lines
Quoted 1 line

This should compile to Thumb2 as well as ARM encodings.

Won't IP get used as the target register if r0-r3 are used for passing arguments? AAPCS implies this is how it'll go (4 arguments in registers, the rest on stack), but when I tried to force this to happen, it looked like it'd only pass 3 via registers, and would make the call with r3.

Wait, I misread, my test is using r4 as the target! Still, is IP guaranteed to never be used for the target?

-Kees

Signature · 1 line
Kees Cook
#23 lore raw

Re: [PATCH v2 5/7] arm: Add ARM 32-bit Kernel Control Flow Integrity implementation

Quoted 38 lines · Kees Cook
Quoted 36 lines · Kees Cook
Quoted 34 lines · Ard Biesheuvel
Quoted 16 lines · Kees Cook

Implement ARM 32-bit KCFI backend supporting ARMv7+:

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

- Use movw/movt instructions for 32-bit immediate loading.

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

- Scratch register allocation using r0/r1 following ARM procedure call standard for caller-saved temporary registers, though they get stack spilled due to register pressure.

Quoted 7 lines

Assembly Code Pattern for ARM 32-bit:

  push {r0, r1}                ; Spill r0, r1
  ldr  r0, [target, #-4]       ; Load actual type ID from preamble
  movw r1, #type_id_low        ; Load expected type (lower 16 bits)
  movt r1, #type_id_high       ; Load upper 16 bits with top instruction
  cmp  r0, r1                  ; Compare type IDs directly
  pop [r0, r1]                 ; Reload r0, r1

We could avoid the MOVW/MOVT pair and the spilling by doing something along the lines of

ldr   ip, [target, #-4]
eor   ip, ip, #type_id[0]
eor   ip, ip, #type_id[1] << 8
eor   ip, ip, #type_id[2] << 16
eors  ip, ip, #type_id[3] << 24

ldrne ip, =type_id[3:0]

Quoted 8 lines
Quoted 8 lines

Ah-ha, nice. And it could re-load the type_id on the slow path instead of unconditionally, I guess? (So no "ne" suffix needed there.)

...
eors ip, ip, #type_id[3] << 24
beq .Lkcfi_call
.Lkcfi_trap:
ldr ip, =type_id[3:0]

Yeah better. If you use the right compiler abstraction to emit this load, it will be turned into MOVW/MOVT if the target supports it.

Quoted 12 lines
Quoted 12 lines

udf #nnn
.Lkcfi_call:
blx target

Quoted 6 lines

Note that IP (R12) should be dead before a function call. Here it is conditionally loaded with the expected target typeid, removing the need to decode the instructions to recover it when the trap occurs.

This should compile to Thumb2 as well as ARM encodings.

Quoted 8 lines
Quoted 4 lines

Won't IP get used as the target register if r0-r3 are used for passing arguments? AAPCS implies this is how it'll go (4 arguments in registers, the rest on stack), but when I tried to force this to happen, it looked like it'd only pass 3 via registers, and would make the call with r3.

Wait, I misread, my test is using r4 as the target! Still, is IP guaranteed to never be used for the target?

The target register can be any GPR. IP is guaranteed by AAPCS not to play a role in parameter passing, because it is the Inter Procedural scratch register, and may be clobbered by PLT trampolines that get inserted between a direct call and its target. These are not direct calls, of course, but the callee does not know that, and so it cannot make any assumptions about the value of IP.

That said, I'm not sure I understand why this type register has to be a fixed register. It /can/ be a fixed register, but you'd have to tell the compiler that. In that case, it can still use the link register for the target, unless it is emitting a tail call and LR needs to be preserved. The upshot of that would be that some tail calls will be converted into ordinary calls, due to the need to preserve some registers on the stack. But I'd still assume letting the compiler do this when needed is better than always pushing/popping two registers in the CFI call sequence.

author
#24 lore raw

Re: [PATCH v2 5/7] arm: Add ARM 32-bit Kernel Control Flow Integrity implementation

Quoted 72 lines · Ard Biesheuvel
Quoted 38 lines · Kees Cook
Quoted 36 lines · Kees Cook
Quoted 34 lines · Ard Biesheuvel
Quoted 16 lines · Kees Cook

Implement ARM 32-bit KCFI backend supporting ARMv7+:

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

- Use movw/movt instructions for 32-bit immediate loading.

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

- Scratch register allocation using r0/r1 following ARM procedure call standard for caller-saved temporary registers, though they get stack spilled due to register pressure.

Quoted 7 lines

Assembly Code Pattern for ARM 32-bit:

  push {r0, r1}                ; Spill r0, r1
  ldr  r0, [target, #-4]       ; Load actual type ID from preamble
  movw r1, #type_id_low        ; Load expected type (lower 16 bits)
  movt r1, #type_id_high       ; Load upper 16 bits with top instruction
  cmp  r0, r1                  ; Compare type IDs directly
  pop [r0, r1]                 ; Reload r0, r1

We could avoid the MOVW/MOVT pair and the spilling by doing something along the lines of

ldr   ip, [target, #-4]
eor   ip, ip, #type_id[0]
eor   ip, ip, #type_id[1] << 8
eor   ip, ip, #type_id[2] << 16
eors  ip, ip, #type_id[3] << 24

ldrne ip, =type_id[3:0]

Quoted 8 lines
Quoted 8 lines

Ah-ha, nice. And it could re-load the type_id on the slow path instead of unconditionally, I guess? (So no "ne" suffix needed there.)

...
eors ip, ip, #type_id[3] << 24
beq .Lkcfi_call
.Lkcfi_trap:
ldr ip, =type_id[3:0]

Yeah better. If you use the right compiler abstraction to emit this load, it will be turned into MOVW/MOVT if the target supports it.

Quoted 12 lines
Quoted 12 lines

udf #nnn
.Lkcfi_call:
blx target

Quoted 6 lines

Note that IP (R12) should be dead before a function call. Here it is conditionally loaded with the expected target typeid, removing the need to decode the instructions to recover it when the trap occurs.

This should compile to Thumb2 as well as ARM encodings.

Quoted 8 lines
Quoted 4 lines

Won't IP get used as the target register if r0-r3 are used for passing arguments? AAPCS implies this is how it'll go (4 arguments in registers, the rest on stack), but when I tried to force this to happen, it looked like it'd only pass 3 via registers, and would make the call with r3.

Wait, I misread, my test is using r4 as the target! Still, is IP guaranteed to never be used for the target?

Quoted 6 lines

The target register can be any GPR. IP is guaranteed by AAPCS not to play a role in parameter passing, because it is the Inter Procedural scratch register, and may be clobbered by PLT trampolines that get inserted between a direct call and its target. These are not direct calls, of course, but the callee does not know that, and so it cannot make any assumptions about the value of IP.

Okay, it seems like I am close to having this replaced with the eor method, but the backend really really does not like constructing the ldr for me. I may leave this as a "future improvement", and just change the Linux side of the trap handling to decode the eor insns instead of pulling the value out of IP.

Signature · 1 line
Kees Cook
author
#25 lore raw

PATCH v2 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 alignment NOPs needed due to fix 4-byte instruction size).

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

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

Assembly Code Pattern for RISC-V:

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

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

Build and run tested with Linux kernel ARCH=riscv.

gcc/ChangeLog:

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

---
 gcc/config/riscv/riscv-protos.h |   3 +
 gcc/config/riscv/riscv.cc       | 147 ++++++++++++++++++++++++++++++++
 gcc/config/riscv/riscv.md       |  74 ++++++++++++++--
 gcc/doc/invoke.texi             |  13 +++
 4 files changed, 231 insertions(+), 6 deletions(-)
gcc/config/riscv/riscv-protos.h +3 -0
index 2d60a0ad44b3..0e916fbdde13 100644
@@ -126,6 +126,9 @@ 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 rtx riscv_maybe_wrap_call_with_kcfi (rtx, rtx);
+extern rtx riscv_maybe_wrap_call_value_with_kcfi (rtx, rtx);
+extern const char *riscv_output_kcfi_insn (rtx_insn *, rtx *);
 extern void riscv_declare_function_name (FILE *, const char *, tree);
 extern void riscv_declare_function_size (FILE *, const char *, tree);
 extern void riscv_asm_output_alias (FILE *, const tree, const tree);
gcc/config/riscv/riscv.cc +147 -0

165 lines not on this page · raw message

gcc/config/riscv/riscv.md +68 -6

110 lines not on this page · raw message

gcc/doc/invoke.texi +13 -0
index 25ee82c9cba7..43e86f4bc5b4 100644
@@ -18458,6 +18458,19 @@ 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
#26 lore raw

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

Quoted 57 lines · 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 alignment NOPs needed due to fix 4-byte instruction size).

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

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

Assembly Code Pattern for RISC-V:

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

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

Build and run tested with Linux kernel ARCH=riscv.

gcc/ChangeLog:

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

---
  gcc/config/riscv/riscv-protos.h |   3 +
  gcc/config/riscv/riscv.cc       | 147 ++++++++++++++++++++++++++++++++
  gcc/config/riscv/riscv.md       |  74 ++++++++++++++--
  gcc/doc/invoke.texi             |  13 +++
  4 files changed, 231 insertions(+), 6 deletions(-)
gcc/config/riscv/riscv-protos.h +3 -0
index 2d60a0ad44b3..0e916fbdde13 100644
@@ -126,6 +126,9 @@ 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 rtx riscv_maybe_wrap_call_with_kcfi (rtx, rtx);
+extern rtx riscv_maybe_wrap_call_value_with_kcfi (rtx, rtx);
+extern const char *riscv_output_kcfi_insn (rtx_insn *, rtx *);
  extern void riscv_declare_function_name (FILE *, const char *, tree);
  extern void riscv_declare_function_size (FILE *, const char *, tree);
  extern void riscv_asm_output_alias (FILE *, const tree, const tree);

gcc/config/riscv/riscv-protos.h riscv_convert_vector_chunks (struct gcc_options *opts) · line 11352

Quoted 6 lines
gcc/config/riscv/riscv-protos.h +3 -0
@@ -11346,6 +11347,149 @@ riscv_convert_vector_chunks (struct gcc_options *opts)
      return 1;
  }
 
+/* Apply KCFI wrapping to call pattern if needed.  */
+rtx
+riscv_maybe_wrap_call_with_kcfi (rtx pat, rtx addr)

So our coding standards require a bit more for that function comment. What are PAT and ADDR and how are they used?

gcc/config/riscv/riscv-protos.h riscv_convert_vector_chunks (struct gcc_options *opts) · line 11357

Quoted 5 lines
gcc/config/riscv/riscv-protos.h +5 -0
+}
+
+/* Apply KCFI wrapping to call_value pattern if needed.  */
+rtx
+riscv_maybe_wrap_call_value_with_kcfi (rtx pat, rtx addr)

Similarly here.

gcc/config/riscv/riscv-protos.h riscv_convert_vector_chunks (struct gcc_options *opts) · line 11361

Quoted 4 lines
gcc/config/riscv/riscv-protos.h +4 -0
+
+/* Output the assembly for a KCFI checked call instruction.  */
+const char *
+riscv_output_kcfi_insn (rtx_insn *insn, rtx *operands)

And here.

gcc/config/riscv/riscv-protos.h riscv_convert_vector_chunks (struct gcc_options *opts) · line 11368

Quoted 7 lines
gcc/config/riscv/riscv-protos.h +7 -0
+{
+  /* Target register.  */
+  rtx target_reg = operands[0];
+  gcc_assert (REG_P (target_reg));
+
+  /* Get KCFI type ID.  */
+  uint32_t expected_type = (uint32_t) INTVAL (operands[3]);

Do we know operands[3] is a CONST_INT?

gcc/config/riscv/riscv-protos.h riscv_convert_vector_chunks (struct gcc_options *opts) · line 11375

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

ISTM that this will need some kidn of adjustment if someone were to compile with -ffixed-reg. Maybe all we really need is a sorry() so that if someone were to try to fix the temporary registers they'd get a loud complaint from teh compiler.

gcc/config/riscv/riscv-protos.h riscv_convert_vector_chunks (struct gcc_options *opts) · line 11382

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

Rather than using DImode for the PLUS, shouldn't it instead use Pmode so that it at least tries to work on rv32? Or is this stuff somehow defined as only working for rv64?

Quoted 8 lines
gcc/config/riscv/riscv-protos.h +8 -0
+
+  /* Execute the indirect call.  */
+  if (SIBLING_CALL_P (insn))
+    {
+      /* Tail call uses x0 (zero register) to avoid saving return address.  */
+      temp_operands[0] = gen_rtx_REG (DImode, 0);  /* x0 */
+      temp_operands[1] = target_reg;  /* target register */
+      temp_operands[2] = const0_rtx;

gcc/config/riscv/riscv-protos.h riscv_convert_vector_chunks (struct gcc_options *opts) · line 11400

Quoted 10 lines
gcc/config/riscv/riscv-protos.h +10 -0
+      output_asm_insn ("jalr\t%0, %1, %2", temp_operands);
+    }
+  else
+    {
+      /* Regular call uses x1 (return address register).  */
+      temp_operands[0] = gen_rtx_REG (DImode, RETURN_ADDR_REGNUM);  /* x1 */
+      temp_operands[1] = target_reg;  /* target register */
+      temp_operands[2] = const0_rtx;
+      output_asm_insn ("jalr\t%0, %1, %2", temp_operands);
+    }

More cases where we probably should be using Pmode.

We generally prefer to not generate assembly code like you've done, but instead prefer to generate actual RTL. Is there some reason why you decided to use output_asm_insn rather than generating RTL and letting usual mechanisms for generating assembly code kick in?

Quoted 5 lines
gcc/config/riscv/riscv-protos.h +3 -1
    rtx target = riscv_legitimize_call_address (XEXP (operands[0], 0));
-  emit_call_insn (gen_sibcall_internal (target, operands[1], operands[2]));
+  rtx pat = gen_sibcall_internal (target, operands[1], operands[2]);
+  pat = riscv_maybe_wrap_call_with_kcfi (pat, target);
+  emit_call_insn (pat);

gcc/config/riscv/riscv-protos.h riscv_convert_vector_chunks (struct gcc_options *opts)

Quoted 10 lines
gcc/config/riscv/riscv-protos.h +7 -0
    DONE;
  })
 
+;; KCFI sibling call - matches KCFI wrapper RTL
+(define_insn "*kcfi_sibcall_insn"
+  [(kcfi (call (mem:SI (match_operand:DI 0 "call_insn_operand" "l"))
+               (match_operand 1 ""))
+         (match_operand 3 "const_int_operand"))
+   (use (unspec:SI [(match_operand 2 "const_int_operand")] UNSPEC_CALLEE_CC))]
+  "SIBLING_CALL_P (insn)"

I think the DI for the memory operand should probably be :P instead so that we're not so tied to rv64.

gcc/config/riscv/riscv-protos.h

Quoted 13 lines
gcc/config/riscv/riscv-protos.h +13 -0
+;; KCFI sibling call with return value - matches KCFI wrapper RTL
+(define_insn "*kcfi_sibcall_value_insn"
+  [(set (match_operand 0 "")
+	(kcfi (call (mem:SI (match_operand:DI 1 "call_insn_operand" "l"))
+		    (match_operand 2 ""))
+	      (match_operand 4 "const_int_operand")))
+   (use (unspec:SI [(match_operand 3 "const_int_operand")] UNSPEC_CALLEE_CC))]
+  "SIBLING_CALL_P (insn)"
+{
+  return riscv_output_kcfi_insn (insn, &operands[1]);
+}
+  [(set_attr "type" "call")
+   (set_attr "length" "24")])

Similarly for this pattern.

Quoted 4 lines
gcc/config/riscv/riscv-protos.h +3 -0
+;; KCFI indirect call - matches KCFI wrapper RTL
+(define_insn "*kcfi_call_internal"
+  [(kcfi (call (mem:SI (match_operand:DI 0 "call_insn_operand" "l"))

gcc/config/riscv/riscv-protos.h

Quoted 10 lines
gcc/config/riscv/riscv-protos.h +10 -0
+               (match_operand 1 "" ""))
+         (match_operand 3 "const_int_operand"))
+   (use (unspec:SI [(match_operand 2 "const_int_operand")] UNSPEC_CALLEE_CC))
+   (clobber (reg:SI RETURN_ADDR_REGNUM))]
+  "!SIBLING_CALL_P (insn)"
+{
+  return riscv_output_kcfi_insn (insn, operands);
+}
+  [(set_attr "type" "call")
+   (set_attr "length" "24")])

And this one.

Quoted 5 lines
gcc/config/riscv/riscv-protos.h +4 -0
+;; KCFI call with return value - matches KCFI wrapper RTL
+(define_insn "*kcfi_call_value_insn"
+  [(set (match_operand 0 "" "")
+	(kcfi (call (mem:SI (match_operand:DI 1 "call_insn_operand" "l"))

gcc/config/riscv/riscv-protos.h

Quoted 10 lines
gcc/config/riscv/riscv-protos.h +10 -0
+		    (match_operand 2 "" ""))
+	      (match_operand 4 "const_int_operand")))
+   (use (unspec:SI [(match_operand 3 "const_int_operand")] UNSPEC_CALLEE_CC))
+   (clobber (reg:SI RETURN_ADDR_REGNUM))]
+  "!SIBLING_CALL_P (insn)"
+{
+  return riscv_output_kcfi_insn (insn, &operands[1]);
+}
+  [(set_attr "type" "call")
+   (set_attr "length" "24")])

THis one too.

64).

gcc/config/riscv/riscv-protos.h

Quoted 6 lines
gcc/config/riscv/riscv-protos.h +5 -0
+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. 

Note that many designs implement the "C" extension and as a result only have a 2 byte alignment for instructions.

Jeff

author
#27 lore raw

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

Quoted 59 lines · Jeff Law
Quoted 55 lines · 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 alignment NOPs needed due to fix 4-byte instruction size).

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

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

Assembly Code Pattern for RISC-V:

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

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

Build and run tested with Linux kernel ARCH=riscv.

gcc/ChangeLog:

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

---
  gcc/config/riscv/riscv-protos.h |   3 +
  gcc/config/riscv/riscv.cc       | 147 ++++++++++++++++++++++++++++++++
  gcc/config/riscv/riscv.md       |  74 ++++++++++++++--
  gcc/doc/invoke.texi             |  13 +++
  4 files changed, 231 insertions(+), 6 deletions(-)
gcc/config/riscv/riscv-protos.h +3 -0
index 2d60a0ad44b3..0e916fbdde13 100644
@@ -126,6 +126,9 @@ 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 rtx riscv_maybe_wrap_call_with_kcfi (rtx, rtx);
+extern rtx riscv_maybe_wrap_call_value_with_kcfi (rtx, rtx);
+extern const char *riscv_output_kcfi_insn (rtx_insn *, rtx *);
  extern void riscv_declare_function_name (FILE *, const char *, tree);
  extern void riscv_declare_function_size (FILE *, const char *, tree);
  extern void riscv_asm_output_alias (FILE *, const tree, const tree);
Quoted 8 lines

gcc/config/riscv/riscv-protos.h riscv_convert_vector_chunks (struct gcc_options *opts) · line 11351

Quoted 6 lines
gcc/config/riscv/riscv-protos.h +3 -0
@@ -11346,6 +11347,149 @@ riscv_convert_vector_chunks (struct gcc_options *opts)
      return 1;
  }
+/* Apply KCFI wrapping to call pattern if needed.  */
+rtx
+riscv_maybe_wrap_call_with_kcfi (rtx pat, rtx addr)

So our coding standards require a bit more for that function comment. What are PAT and ADDR and how are they used?

Sure, I can document those more fully in the next version.

Quoted 9 lines

gcc/config/riscv/riscv-protos.h riscv_convert_vector_chunks (struct gcc_options *opts) · line 11359

Quoted 8 lines
gcc/config/riscv/riscv-protos.h +8 -0
+riscv_output_kcfi_insn (rtx_insn *insn, rtx *operands)
+{
+  /* Target register.  */
+  rtx target_reg = operands[0];
+  gcc_assert (REG_P (target_reg));
+
+  /* Get KCFI type ID.  */
+  uint32_t expected_type = (uint32_t) INTVAL (operands[3]);

Do we know operands[3] is a CONST_INT?

Yes, these all come from their respective RTL's:

(match_operand 3 "const_int_operand"))

(Except for sibcalls where the RTL operand is offset by 1, but adjust for in the call to riscv_output_kcfi_insn.

Quoted 12 lines

gcc/config/riscv/riscv-protos.h riscv_convert_vector_chunks (struct gcc_options *opts) · line 11366

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

ISTM that this will need some kidn of adjustment if someone were to compile with -ffixed-reg. Maybe all we really need is a sorry() so that if someone were to try to fix the temporary registers they'd get a loud complaint from teh compiler.

Yeah, this needs more careful management of the scratch registers. I have not been able to find a sane way to provide working constraints to the RTL patterns, but I'd _much_ rather let the register allocator do all this work.

Quoted 10 lines

gcc/config/riscv/riscv-protos.h riscv_convert_vector_chunks (struct gcc_options *opts) · line 11373

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

Rather than using DImode for the PLUS, shouldn't it instead use Pmode so that it at least tries to work on rv32? Or is this stuff somehow defined as only working for rv64?

It was designed entirely for rv64. I'm not against making it work with rv32, but I just haven't tried or tested it there.

Quoted 18 lines
Quoted 8 lines
gcc/config/riscv/riscv-protos.h +8 -0
+
+  /* Execute the indirect call.  */
+  if (SIBLING_CALL_P (insn))
+    {
+      /* Tail call uses x0 (zero register) to avoid saving return address.  */
+      temp_operands[0] = gen_rtx_REG (DImode, 0);  /* x0 */
+      temp_operands[1] = target_reg;  /* target register */
+      temp_operands[2] = const0_rtx;

gcc/config/riscv/riscv-protos.h riscv_convert_vector_chunks (struct gcc_options *opts) · line 11391

Quoted 10 lines
gcc/config/riscv/riscv-protos.h +10 -0
+      output_asm_insn ("jalr\t%0, %1, %2", temp_operands);
+    }
+  else
+    {
+      /* Regular call uses x1 (return address register).  */
+      temp_operands[0] = gen_rtx_REG (DImode, RETURN_ADDR_REGNUM);  /* x1 */
+      temp_operands[1] = target_reg;  /* target register */
+      temp_operands[2] = const0_rtx;
+      output_asm_insn ("jalr\t%0, %1, %2", temp_operands);
+    }
Quoted 6 lines

More cases where we probably should be using Pmode.

We generally prefer to not generate assembly code like you've done, but instead prefer to generate actual RTL. Is there some reason why you decided to use output_asm_insn rather than generating RTL and letting usual mechanisms for generating assembly code kick in?

Yeah, I covered this a bit in patch #2 in the series which describe the design requirements. The main issue is that the typeid validation check cannot be separated from the call, and the instruction pattern needs to have very close control over the register usage so we don't introduce any new indirect call gadgets (pop %target, call %target).

So, this is a replacement of the regular CALL rtl pattern. I am totally open to any other way to do this. I have been bumbling around in here (and on the other architectures) trying to find ways to make it all work, but it still feels like a bit of a hack. :)

Quoted 7 lines

gcc/config/riscv/riscv-protos.h riscv_convert_vector_chunks (struct gcc_options *opts) · line 11396

Quoted 5 lines
gcc/config/riscv/riscv-protos.h +5 -0
+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.

Note that many designs implement the "C" extension and as a result only have a 2 byte alignment for instructions.

Okay, noted. Are there any restrictions on function pointer alignment? Regardless, I should probably rewrite this language a bit to try to better say "we don't care about alignment padding since the preamble typeid contents are a multiple of instruction size" (which would still be true for 2 byte alignemnt).

Thanks for looking this over!

-Kees

Signature · 1 line
Kees Cook
#28 lore raw

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

Quoted 7 lines · Kees Cook
Quoted 5 lines

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

Quoted 3 lines
gcc/config/riscv/riscv.cc +3 -0
+/* Apply KCFI wrapping to call pattern if needed.  */
+rtx
+riscv_maybe_wrap_call_with_kcfi (rtx pat, rtx addr)

So our coding standards require a bit more for that function comment. What are PAT and ADDR and how are they used?

Sure, I can document those more fully in the next version.

Thanks.

Quoted 11 lines
Quoted 10 lines

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

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

Do we know operands[3] is a CONST_INT?

Quoted 3 lines

Yes, these all come from their respective RTL's:

(match_operand 3 "const_int_operand"))

Perfect. Just wanted to make sure. It's a fairly common goof to try to extract an integer value from a non-integer node.

Quoted 9 lines
Quoted 4 lines

ISTM that this will need some kidn of adjustment if someone were to compile with -ffixed-reg. Maybe all we really need is a sorry() so that if someone were to try to fix the temporary registers they'd get a loud complaint from teh compiler.

Yeah, this needs more careful management of the scratch registers. I have not been able to find a sane way to provide working constraints to the RTL patterns, but I'd _much_ rather let the register allocator do all this work.

Usually you end up having to define a register class with the single register you want. Of course once you do that you also need to start defining union classes and you also have to audit all kinds of code to make sure it's doing something sensible. Yea, it's painful.

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

Rather than using DImode for the PLUS, shouldn't it instead use Pmode so that it at least tries to work on rv32? Or is this stuff somehow defined as only working for rv64?

It was designed entirely for rv64. I'm not against making it work with rv32, but I just haven't tried or tested it there.

ACK. This may never end up being used on rv32. But we should at least fix the obvious stuff since it's just the right thing to do.

Conceptually any pointer should be using Pmode. If you keep that in mind, that covers one big blob of issues. It also means that if someone where to try to light up 32 bit pointers on rv64 that your code is ready for that (and yes, we've had those kinds of requests, though to date none of that code has been ready to integrate).

Quoted 12 lines
Quoted 5 lines

We generally prefer to not generate assembly code like you've done, but instead prefer to generate actual RTL. Is there some reason why you decided to use output_asm_insn rather than generating RTL and letting usual mechanisms for generating assembly code kick in?

Yeah, I covered this a bit in patch #2 in the series which describe the design requirements. The main issue is that the typeid validation check cannot be separated from the call, and the instruction pattern needs to have very close control over the register usage so we don't introduce any new indirect call gadgets (pop %target, call %target).

Quoted 4 lines

So, this is a replacement of the regular CALL rtl pattern. I am totally open to any other way to do this. I have been bumbling around in here (and on the other architectures) trying to find ways to make it all work, but it still feels like a bit of a hack. :)

I didn't really see anything in patch#2 which would indicate we want to generate blobs of assembly code. It feels like there's something missing in both our understandings.

Quoted 6 lines

Okay, noted. Are there any restrictions on function pointer alignment? Regardless, I should probably rewrite this language a bit to try to better say "we don't care about alignment padding since the preamble typeid contents are a multiple of instruction size" (which would still be true for 2 byte alignemnt).

Nope. The architecture will require them to be 2 byte aligned if "C" is enabled or 4 byte aligned if "C" is not enabled. In both cases those alignments correspond to the minimum instruction size.

Jeff

author
#29 lore raw

PATCH v2 7/7 kcfi: Add regression test suite

In reply to Kees Cook

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

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

gcc/testsuite/ChangeLog:

gcc.dg/kcfi/kcfi-adjacency.c: New test. gcc.dg/kcfi/kcfi-basics.c: New test. gcc.dg/kcfi/kcfi-call-sharing.c: New test. gcc.dg/kcfi/kcfi-cold-partition.c: New test. gcc.dg/kcfi/kcfi-complex-addressing.c: New test. gcc.dg/kcfi/kcfi-ipa-robustness.c: New test. gcc.dg/kcfi/kcfi-move-preservation.c: New test. gcc.dg/kcfi/kcfi-no-sanitize-inline.c: New test. gcc.dg/kcfi/kcfi-no-sanitize.c: New test. gcc.dg/kcfi/kcfi-offset-validation.c: New test. gcc.dg/kcfi/kcfi-patchable-basic.c: New test. gcc.dg/kcfi/kcfi-patchable-entry-only.c: New test. gcc.dg/kcfi/kcfi-patchable-large.c: New test. gcc.dg/kcfi/kcfi-patchable-medium.c: New test. gcc.dg/kcfi/kcfi-patchable-prefix-only.c: New test. gcc.dg/kcfi/kcfi-pic-addressing.c: New test. gcc.dg/kcfi/kcfi-retpoline-r11.c: New test. gcc.dg/kcfi/kcfi-tail-calls.c: New test. gcc.dg/kcfi/kcfi-trap-encoding.c: New test. gcc.dg/kcfi/kcfi-trap-section.c: New test. gcc.dg/kcfi/kcfi-type-mangling.c: New test. gcc.dg/kcfi/kcfi.exp: New file, test infrastructure.

---
 gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c    |   73 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c       |  101 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-call-sharing.c |   85 ++
 .../gcc.dg/kcfi/kcfi-cold-partition.c         |  137 +++
 .../gcc.dg/kcfi/kcfi-complex-addressing.c     |  125 ++
 .../gcc.dg/kcfi/kcfi-ipa-robustness.c         |   55 +
 .../gcc.dg/kcfi/kcfi-move-preservation.c      |   56 +
 .../gcc.dg/kcfi/kcfi-no-sanitize-inline.c     |  101 ++
 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c  |   41 +
 .../gcc.dg/kcfi/kcfi-offset-validation.c      |   50 +
 .../gcc.dg/kcfi/kcfi-patchable-basic.c        |   71 ++
 .../gcc.dg/kcfi/kcfi-patchable-entry-only.c   |   64 +
 .../gcc.dg/kcfi/kcfi-patchable-large.c        |   52 +
 .../gcc.dg/kcfi/kcfi-patchable-medium.c       |   61 +
 .../gcc.dg/kcfi/kcfi-patchable-prefix-only.c  |   61 +
 .../gcc.dg/kcfi/kcfi-pic-addressing.c         |  105 ++
 .../gcc.dg/kcfi/kcfi-retpoline-r11.c          |   51 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c   |  143 +++
 .../gcc.dg/kcfi/kcfi-trap-encoding.c          |   56 +
 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c |   43 +
 .../gcc.dg/kcfi/kcfi-type-mangling.c          | 1064 +++++++++++++++++
 gcc/testsuite/gcc.dg/kcfi/kcfi.exp            |   36 +
 22 files changed, 2631 insertions(+)
 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-ipa-robustness.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-move-preservation.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize-inline.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-no-sanitize.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-offset-validation.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-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-prefix-only.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-pic-addressing.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-retpoline-r11.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-tail-calls.c
 create mode 100644 gcc/testsuite/gcc.dg/kcfi/kcfi-trap-encoding.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-adjacency.c new file +73 -0
new file mode 100644
index 000000000000..3c52e01c9558
@@ -0,0 +1,73 @@
+/* Test KCFI check/transfer adjacency - regression test for instruction
+   insertion.  */
+/* { dg-do compile } */
+/* { dg-options "-fsanitize=kcfi -O2" } */
+/* { dg-options "-fsanitize=kcfi -O2 -march=armv7-a -mfloat-abi=soft" { target arm32 } } */
+
+/* This test ensures that KCFI security checks remain immediately adjacent
+   to their corresponding indirect calls/jumps, with no executable instructions
+   between the type ID check and the control flow transfer. */
+
+/* External function pointers to prevent optimization.  */
+extern void (*complex_func_ptr)(int, int, int, int);
+extern int (*return_func_ptr)(int, int);
+
+/* Function with complex argument preparation that could tempt
+   the optimizer to insert instructions between KCFI check and call.  */
+__attribute__((noinline)) void test_complex_args(int a, int b, int c, int d) {
+    /* Complex argument expressions that might cause instruction scheduling.  */
+    complex_func_ptr(a * 2, b + c, d - a, (a << 1) | b);
+}
+
+/* Function with return value handling.  */
+__attribute__((noinline)) int test_return_value(int x, int y) {
+    /* Return value handling that shouldn't interfere with adjacency.  */
+    int result = return_func_ptr(x + 1, y * 2);
+    return result + 1;
+}
+
+/* Test struct field access that caused issues in try-catch.c.  */
+struct call_info {
+    void (*handler)(void);
+    int status;
+    int data;
+};
+
+extern struct call_info *global_call_info;
+
+__attribute__((noinline)) void test_struct_field_call(void) {
+    /* This pattern caused adjacency issues before the fix.  */
+    global_call_info->handler();
+}
+
+/* Test conditional indirect call.  */
+__attribute__((noinline)) void test_conditional_call(int flag) {
+    if (flag) {
+        global_call_info->handler();
+    }
+}
+
+/* Should have KCFI instrumentation for all indirect calls.  */
+
+/* x86_64: Complete KCFI check sequence should be present.  */
+/* { dg-final { scan-assembler {movl\t\$-?[0-9]+, %r1[01]d\n\taddl\t[^,]+, %r1[01]d\n\tje\t\.Lkcfi_call[0-9]+\n\.Lkcfi_trap[0-9]+:\n\tud2} { target x86_64-*-* } } } */
+
+/* AArch64: Complete KCFI check sequence should be present.  */
+/* { dg-final { scan-assembler {ldur\tw16, \[x[0-9]+, #-[0-9]+\]\n\tmov\tw17, #[0-9]+\n\tmovk\tw17, #[0-9]+, lsl #16\n\tcmp\tw16, w17\n\tb\.eq\t(\.Lkcfi_call[0-9]+)\n\.Lkcfi_trap[0-9]+:\n\tbrk\t#[0-9]+\n\1:\n\tblr\tx[0-9]+} { target aarch64*-*-* } } } */
+
+/* ARM 32-bit: Complete KCFI check sequence should be present with stack
+   spilling.  */
+/* { dg-final { scan-assembler {push\t\{r0, r1\}\n\tldr\tr0, \[r[0-9]+, #-[0-9]+\]\n\tmovw\tr1, #[0-9]+\n\tmovt\tr1, #[0-9]+\n\tcmp\tr0, r1\n\tpop\t\{r0, r1\}\n\tbeq\t\.Lkcfi_call[0-9]+\n\.Lkcfi_trap[0-9]+:\n\tudf\t#[0-9]+\n\.Lkcfi_call[0-9]+:\n\tblx\tr[0-9]+} { target arm32 } } } */
+
+/* RISC-V: Complete KCFI check sequence should be present.  */
+/* { dg-final { scan-assembler {lw\tt1, -4\([a-z0-9]+\)\n\tlui\tt2, [0-9]+\n\taddiw\tt2, t2, -?[0-9]+\n\tbeq\tt1, t2, \.Lkcfi_call[0-9]+\n\.Lkcfi_trap[0-9]+:\n\tebreak} { target riscv*-*-* } } } */
+
+/* Should have trap section with entries.  */
+/* { dg-final { scan-assembler {\.kcfi_traps} { target x86_64-*-* } } } */
+/* { dg-final { scan-assembler {\.kcfi_traps} { target riscv*-*-* } } } */
+
+/* AArch64 should NOT have trap section (uses brk immediate instead) */
+/* { dg-final { scan-assembler-not {\.kcfi_traps} { target aarch64*-*-* } } } */
+
+/* ARM 32-bit should NOT have trap section (uses udf immediate instead) */
+/* { dg-final { scan-assembler-not {\.kcfi_traps} { target arm32 } } } */
gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c new file +101 -0

101 lines not on this page · raw message

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

85 lines not on this page · raw message

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

137 lines not on this page · raw message

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

125 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-ipa-robustness.c new file +55 -0

55 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-move-preservation.c new file +56 -0

56 lines not on this page · raw message

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

101 lines not on this page · raw message

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

41 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-offset-validation.c new file +50 -0

50 lines not on this page · raw message

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

71 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-entry-only.c new file +64 -0

64 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-large.c new file +52 -0

52 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-medium.c new file +61 -0

61 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-patchable-prefix-only.c new file +61 -0

61 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-pic-addressing.c new file +105 -0

105 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-retpoline-r11.c new file +51 -0

51 lines not on this page · raw message

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

143 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-trap-encoding.c new file +56 -0

56 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-trap-section.c new file +43 -0

43 lines not on this page · raw message

gcc/testsuite/gcc.dg/kcfi/kcfi-type-mangling.c new file +1064 -0

1,064 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
#30 lore raw

Re: [PATCH v2 7/7] kcfi: Add regression test suite

gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c line 5

Quoted 8 lines · Kees Cook
gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c new file +5 -0
@@ -0,0 +1,73 @@
+/* Test KCFI check/transfer adjacency - regression test for instruction
+   insertion.  */
+/* { dg-do compile } */
+/* { dg-options "-fsanitize=kcfi -O2" } */
+/* { dg-options "-fsanitize=kcfi -O2 -march=armv7-a -mfloat-abi=soft" { target arm32 } } */

For stuff like this you should be using dg-additional-options.
/* { dg-options "-fsanitize=kcfi -O2" } */
/* { dg-additional-options "-march=armv7-a -mfloat-abi=soft" { target arm32 } } */ (in various other tests too).

gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c line 53

Quoted 4 lines
gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c new file +4 -0
+/* Should have KCFI instrumentation for all indirect calls.  */
+
+/* x86_64: Complete KCFI check sequence should be present.  */
+/* { dg-final { scan-assembler {movl\t\$-?[0-9]+, %r1[01]d\n\taddl\t[^,]+, %r1[01]d\n\tje\t\.Lkcfi_call[0-9]+\n\.Lkcfi_trap[0-9]+:\n\tud2} { target x86_64-*-* } } } */

This at least needs
/* { dg-additional-options "-masm=att" { target x86_64-*-* } } */ because Intel syntax wouldn't match. Does this match with all possible -march/-mtune settings?
Peope very often do test
make check RUNTESTFLAGS='--target_board=unix/-march=skylake-avx512' etc. so if the test depends on a particular ISA or tuning, better add it explicitly to dg-options.
Also, we try not to use triplets like x86_64-*-* but instead { i?86-*-* x86_64-*-* } && lp64
or
{ i?86-*-* x86_64-*-* } && { ! ia32 }
depending on whether it is only for -m64, or for both -m64 and -mx32, because on some targets the multilib compiler is i?86-*-* defaulting to -m32, on most obviously x86_64-*-* defaulting to -m64.

gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c line 5

Quoted 8 lines
gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c new file +5 -0
@@ -0,0 +1,101 @@
+/* Test basic KCFI functionality - preamble generation.  */
+/* { dg-do compile } */
+/* { dg-options "-fsanitize=kcfi" } */
+/* { dg-options "-fsanitize=kcfi -falign-functions=16" { target x86_64-*-* } } */
+/* { dg-options "-fsanitize=kcfi -march=armv7-a -mfloat-abi=soft" { target arm32 } } */

Again (and in many others).

gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c line 9

Quoted 4 lines
gcc/testsuite/gcc.dg/kcfi/kcfi-basics.c new file +4 -0
+/* x86_64: Should have 0 entry NOPs - function starts immediately with
+   pushq.  */
+/* { dg-final { scan-assembler {test_function:\n\.LFB[0-9]+:\n\t*\.cfi_startproc\n\t*pushq\t*%rbp} { target x86_64-*-* } } } */
+/* { dg-final { scan-assembler-not {\t*\.weak\t*__kcfi_typeid_test_function\n} { target x86_64-*-* } } } */

.weak is ELF specific, not all targets have it, are the tests restricted to targets that do support it and in this syntax? We have
/* { dg-require-weak "" } */
but that doesn't imply a particular function.

Also, not all configurations will support .cfi_* directives, that depends both on command line parameters and on whether assembler supports those. If you expect them in all tests, perhaps you should test for those in kcfi.exp and not run the tests at all if the directives aren't supported (or if weak isn't supported etc.).
Also, there are targets with different line endings, so usually one scans for [\n\r]* instead of just \n. No idea why you're using \t*, the compiler emits just one tab.

Jakub

author
#31 lore raw

Re: [PATCH v2 7/7] kcfi: Add regression test suite

Quoted 14 lines · Jakub Jelinek

gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c line 5

Quoted 8 lines · Kees Cook
gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c new file +5 -0
@@ -0,0 +1,73 @@
+/* Test KCFI check/transfer adjacency - regression test for instruction
+   insertion.  */
+/* { dg-do compile } */
+/* { dg-options "-fsanitize=kcfi -O2" } */
+/* { dg-options "-fsanitize=kcfi -O2 -march=armv7-a -mfloat-abi=soft" { target arm32 } } */

For stuff like this you should be using dg-additional-options.
/* { dg-options "-fsanitize=kcfi -O2" } */
/* { dg-additional-options "-march=armv7-a -mfloat-abi=soft" { target arm32 } } */ (in various other tests too).

Ah, perfect; thanks!

Quoted 8 lines

gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c line 53

Quoted 4 lines
gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c new file +4 -0
+/* Should have KCFI instrumentation for all indirect calls.  */
+
+/* x86_64: Complete KCFI check sequence should be present.  */
+/* { dg-final { scan-assembler {movl\t\$-?[0-9]+, %r1[01]d\n\taddl\t[^,]+, %r1[01]d\n\tje\t\.Lkcfi_call[0-9]+\n\.Lkcfi_trap[0-9]+:\n\tud2} { target x86_64-*-* } } } */

This at least needs
/* { dg-additional-options "-masm=att" { target x86_64-*-* } } */ because Intel syntax wouldn't match.

Ah, okay. Is the test suite ever run with -masm != att?

Quoted 1 line

Does this match with all possible -march/-mtune settings?

I was just running this with "default" state. I didn't think there was value is testing all the combinations -- all the sequence tests are basically validating that nothing surprising happened during emission, etc. What's the best practice for this? Should I add specific -march/-mtune options for each arch?

Quoted 4 lines

Peope very often do test
make check RUNTESTFLAGS='--target_board=unix/-march=skylake-avx512' etc. so if the test depends on a particular ISA or tuning, better add it explicitly to dg-options.

How does that end up meshing? i.e. if I have -mtune=generic in dg-options, but someone runs with a different -mtune, what happens?

Quoted 7 lines

Also, we try not to use triplets like x86_64-*-* but instead { i?86-*-* x86_64-*-* } && lp64
or
{ i?86-*-* x86_64-*-* } && { ! ia32 }
depending on whether it is only for -m64, or for both -m64 and -mx32, because on some targets the multilib compiler is i?86-*-* defaulting to -m32, on most obviously x86_64-*-* defaulting to -m64.

Okay, sounds good. I'll update all of these (for this we only care about 64-bit x86). Out of curiosity what triple matches i?86-*-* and lp64? I thought x86_64 was sufficient here.

(Though I suddenly realize I think I have nothing in the KCFI patches can that rejects working under -m32 ... I only do careful target checks under arm.)

Quoted 9 lines

gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c line 13

Quoted 4 lines
gcc/testsuite/gcc.dg/kcfi/kcfi-adjacency.c new file +4 -0
+/* x86_64: Should have 0 entry NOPs - function starts immediately with
+   pushq.  */
+/* { dg-final { scan-assembler {test_function:\n\.LFB[0-9]+:\n\t*\.cfi_startproc\n\t*pushq\t*%rbp} { target x86_64-*-* } } } */
+/* { dg-final { scan-assembler-not {\t*\.weak\t*__kcfi_typeid_test_function\n} { target x86_64-*-* } } } */

.weak is ELF specific, not all targets have it, are the tests restricted to targets that do support it and in this syntax? We have
/* { dg-require-weak "" } */
but that doesn't imply a particular function.

Oh, er, this is just for ELF targets. Is there a way to globally restrict all of these tests to just the 4 arch combos? I'm suspecting now that these tests will all universally fail for the archs that don't support -fsanitize=kcfi. I thought dg-options was handling filtering this, but maybe I've misunderstood?

I'm guessing I need to declare an alias like "lp64" or what I think I saw asan doing for this feature?

Quoted 5 lines

Also, not all configurations will support .cfi_* directives, that depends both on command line parameters and on whether assembler supports those. If you expect them in all tests, perhaps you should test for those in kcfi.exp and not run the tests at all if the directives aren't supported (or if weak isn't supported etc.).

Yeah, this sounds like the place I need to limit the tests from? Everything I know about dg I've learned in the last month. :P

Studying this some more, it looks like some .exp files use "istarget". I found, e.g.:

if { [istarget nvptx-*-*] } {
return
}

So maybe I need that as a top-level filter in kcfi.exp:

if { ![istarget arm*-*-*] && ![istarget x86_64-*-*] && ... } {
unsupported "KCFI tests not supported on this target" return
}

?

I will build some 5th target and see what happens when I run these tests. :P

Quoted 2 lines

Also, there are targets with different line endings, so usually one scans for [\n\r]* instead of just \n.

Okay -- I'm expecting this will go away once I limit to just the 4 targets I want, or do you want me to universally update the \n patterns to [\n\r]*?

Quoted 1 line

No idea why you're using \t*, the compiler emits just one tab.

Ah, I'm not sure where that came from (I will fix it). There has been a lot of automation on my end to get all these patterns converted from .s output into dg patterns.

Thanks for looking this over!

-Kees

Signature · 1 line
Kees Cook