rcvalle updated this revision to Diff 480775.
rcvalle added a comment.

Fixed comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D139395/new/

https://reviews.llvm.org/D139395

Files:
  clang/docs/ControlFlowIntegrity.rst
  clang/docs/UsersManual.rst
  clang/include/clang/AST/Mangle.h
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/MicrosoftMangle.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/cfi-icall-normalize.c

Index: clang/test/CodeGen/cfi-icall-normalize.c
===================================================================
--- /dev/null
+++ clang/test/CodeGen/cfi-icall-normalize.c
@@ -0,0 +1,59 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux -fsanitize=cfi-icall -fsanitize-trap=cfi-icall -fsanitize-cfi-icall-normalize-integers -emit-llvm -o - %s | FileCheck %s
+
+// Test that integer types are normalized for cross-language CFI support with
+// other languages that can't represent and encode C/C++ integer types.
+
+void foo(char (*fn)(char), char arg) {
+  // CHECK-LABEL: define{{.*}}foo
+  // CHECK-SAME: {{.*}}!type ![[TYPE1:[0-9]+]] !type ![[TYPE2:[0-9]+]]
+  // CHECK: call i1 @llvm.type.test(ptr {{.*}}, metadata !"_ZTSFu2i8S_E")
+  fn(arg);
+}
+
+void bar(int (*fn)(short, int), short arg1, int arg2) {
+  // CHECK-LABEL: define{{.*}}bar
+  // CHECK-SAME: {{.*}}!type ![[TYPE3:[0-9]+]] !type ![[TYPE4:[0-9]+]]
+  // CHECK: call i1 @llvm.type.test(ptr {{.*}}, metadata !"_ZTSFu3i32u3i16S_E")
+  fn(arg1, arg2);
+}
+
+void baz(__int128 (*fn)(long, long long, __int128), long arg1, long long arg2, __int128 arg3) {
+  // CHECK-LABEL: define{{.*}}baz
+  // CHECK-SAME: {{.*}}!type ![[TYPE5:[0-9]+]] !type ![[TYPE6:[0-9]+]]
+  // CHECK: call i1 @llvm.type.test(ptr {{.*}}, metadata !"_ZTSFu4i128u3i64S0_S_E")
+  fn(arg1, arg2, arg3);
+}
+
+void foo1(unsigned char (*fn)(unsigned char), unsigned char arg) {
+  // CHECK-LABEL: define{{.*}}foo1
+  // CHECK-SAME: {{.*}}!type ![[TYPE7:[0-9]+]] !type ![[TYPE8:[0-9]+]]
+  // CHECK: call i1 @llvm.type.test(ptr {{.*}}, metadata !"_ZTSFu2u8S_E")
+  fn(arg);
+}
+
+void bar1(unsigned int (*fn)(unsigned short, unsigned int), unsigned short arg1, unsigned int arg2) {
+  // CHECK-LABEL: define{{.*}}bar1
+  // CHECK-SAME: {{.*}}!type ![[TYPE9:[0-9]+]] !type ![[TYPE10:[0-9]+]]
+  // CHECK: call i1 @llvm.type.test(ptr {{.*}}, metadata !"_ZTSFu3u32u3u16S_E")
+  fn(arg1, arg2);
+}
+
+void baz1(unsigned __int128 (*fn)(unsigned long, unsigned long long, unsigned __int128), unsigned long arg1, unsigned long long arg2, unsigned __int128 arg3) {
+  // CHECK-LABEL: define{{.*}}baz1
+  // CHECK-SAME: {{.*}}!type ![[TYPE11:[0-9]+]] !type ![[TYPE12:[0-9]+]]
+  // CHECK: call i1 @llvm.type.test(ptr {{.*}}, metadata !"_ZTSFu4u128u3u64S0_S_E")
+  fn(arg1, arg2, arg3);
+}
+
+// CHECK: ![[TYPE1]] = !{i64 0, !"_ZTSFvPFu2i8S_ES_E"}
+// CHECK: ![[TYPE2]] = !{i64 0, !"_ZTSFvPvu2i8E.generalized"}
+// CHECK: ![[TYPE3]] = !{i64 0, !"_ZTSFvPFu3i32u3i16S_ES0_S_E"}
+// CHECK: ![[TYPE4]] = !{i64 0, !"_ZTSFvPvu3i16u3i32E.generalized"}
+// CHECK: ![[TYPE5]] = !{i64 0, !"_ZTSFvPFu4i128u3i64S0_S_ES0_S0_S_E"}
+// CHECK: ![[TYPE6]] = !{i64 0, !"_ZTSFvPvu3i64S0_u4i128E.generalized"}
+// CHECK: ![[TYPE7]] = !{i64 0, !"_ZTSFvPFu2u8S_ES_E"}
+// CHECK: ![[TYPE8]] = !{i64 0, !"_ZTSFvPvu2u8E.generalized"}
+// CHECK: ![[TYPE9]] = !{i64 0, !"_ZTSFvPFu3u32u3u16S_ES0_S_E"}
+// CHECK: ![[TYPE10]] = !{i64 0, !"_ZTSFvPvu3u16u3u32E.generalized"}
+// CHECK: ![[TYPE11]] = !{i64 0, !"_ZTSFvPFu4u128u3u64S0_S_ES0_S0_S_E"}
+// CHECK: ![[TYPE12]] = !{i64 0, !"_ZTSFvPvu3u64S0_u4u128E.generalized"}
Index: clang/lib/Driver/SanitizerArgs.cpp
===================================================================
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -715,6 +715,9 @@
     CfiICallGeneralizePointers =
         Args.hasArg(options::OPT_fsanitize_cfi_icall_generalize_pointers);
 
+    CfiICallNormalizeIntegers =
+        Args.hasArg(options::OPT_fsanitize_cfi_icall_normalize_integers);
+
     if (CfiCrossDso && CfiICallGeneralizePointers && DiagnoseErrors)
       D.Diag(diag::err_drv_argument_not_allowed_with)
           << "-fsanitize-cfi-cross-dso"
@@ -1218,6 +1221,9 @@
   if (CfiICallGeneralizePointers)
     CmdArgs.push_back("-fsanitize-cfi-icall-generalize-pointers");
 
+  if (CfiICallNormalizeIntegers)
+    CmdArgs.push_back("-fsanitize-cfi-icall-normalize-integers");
+
   if (CfiCanonicalJumpTables)
     CmdArgs.push_back("-fsanitize-cfi-canonical-jump-tables");
 
Index: clang/lib/CodeGen/CodeGenModule.cpp
===================================================================
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -6873,7 +6873,8 @@
   if (isExternallyVisible(T->getLinkage())) {
     std::string OutName;
     llvm::raw_string_ostream Out(OutName);
-    getCXXABI().getMangleContext().mangleTypeName(T, Out);
+    getCXXABI().getMangleContext().mangleTypeName(
+        T, Out, !!getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
     Out << Suffix;
 
     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
Index: clang/lib/AST/MicrosoftMangle.cpp
===================================================================
--- clang/lib/AST/MicrosoftMangle.cpp
+++ clang/lib/AST/MicrosoftMangle.cpp
@@ -179,7 +179,8 @@
                               int32_t VBPtrOffset, uint32_t VBIndex,
                               raw_ostream &Out) override;
   void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
-  void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
+  void mangleCXXRTTIName(QualType T, raw_ostream &Out,
+                         bool NormalizeIntegers) override;
   void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
                                         uint32_t NVOffset, int32_t VBPtrOffset,
                                         uint32_t VBTableOffset, uint32_t Flags,
@@ -192,7 +193,8 @@
   mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
                                      ArrayRef<const CXXRecordDecl *> BasePath,
                                      raw_ostream &Out) override;
-  void mangleTypeName(QualType T, raw_ostream &) override;
+  void mangleTypeName(QualType T, raw_ostream &,
+                      bool NormalizeIntegers) override;
   void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
                                 raw_ostream &) override;
   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
@@ -3585,8 +3587,8 @@
   Mangler.getStream() << "@8";
 }
 
-void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
-                                                   raw_ostream &Out) {
+void MicrosoftMangleContextImpl::mangleCXXRTTIName(
+    QualType T, raw_ostream &Out, bool NormalizeIntegers = false) {
   MicrosoftCXXNameMangler Mangler(*this, Out);
   Mangler.getStream() << '.';
   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
@@ -3753,7 +3755,8 @@
   Mangler.mangleName(EnclosingDecl);
 }
 
-void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
+void MicrosoftMangleContextImpl::mangleTypeName(
+    QualType T, raw_ostream &Out, bool NormalizeIntegers = false) {
   // This is just a made up unique string for the purposes of tbaa.  undname
   // does *not* know how to demangle it.
   MicrosoftCXXNameMangler Mangler(*this, Out);
Index: clang/lib/AST/ItaniumMangle.cpp
===================================================================
--- clang/lib/AST/ItaniumMangle.cpp
+++ clang/lib/AST/ItaniumMangle.cpp
@@ -108,8 +108,10 @@
   void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
                            const CXXRecordDecl *Type, raw_ostream &) override;
   void mangleCXXRTTI(QualType T, raw_ostream &) override;
-  void mangleCXXRTTIName(QualType T, raw_ostream &) override;
-  void mangleTypeName(QualType T, raw_ostream &) override;
+  void mangleCXXRTTIName(QualType T, raw_ostream &,
+                         bool NormalizeIntegers) override;
+  void mangleTypeName(QualType T, raw_ostream &,
+                      bool NormalizeIntegers) override;
 
   void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
   void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
@@ -214,6 +216,10 @@
 class CXXNameMangler {
   ItaniumMangleContextImpl &Context;
   raw_ostream &Out;
+  /// Normalize integer types for cross-language CFI support with other
+  /// languages that can't represent and encode C/C++ integer types.
+  bool NormalizeIntegers = false;
+
   bool NullOut = false;
   /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
   /// This mode is used when mangler creates another mangler recursively to
@@ -412,6 +418,10 @@
       : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
         AbiTagsRoot(AbiTags) {}
 
+  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
+                 bool NormalizeIntegers_)
+      : Context(C), Out(Out_), NormalizeIntegers(NormalizeIntegers_),
+        NullOut(false), AbiTagsRoot(AbiTags) {}
   CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
       : Context(Outer.Context), Out(Out_), Structor(Outer.Structor),
         StructorType(Outer.StructorType), SeqID(Outer.SeqID),
@@ -2936,6 +2946,85 @@
   //                 ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
   //                 ::= u <source-name>    # vendor extended type
   std::string type_name;
+  // Normalize integer types as vendor extended types:
+  // u<length>i<type size>
+  // u<length>u<type size>
+  if (NormalizeIntegers && T->isInteger()) {
+    if (T->isSignedInteger()) {
+      switch (getASTContext().getTypeSize(T)) {
+      case 8:
+        // Pick a representative for each integer size in the substitution
+        // dictionary. (Its actual defined size is not relevant.)
+        if (mangleSubstitution(BuiltinType::SChar))
+          break;
+        Out << "u2i8";
+        addSubstitution(BuiltinType::SChar);
+        break;
+      case 16:
+        if (mangleSubstitution(BuiltinType::Short))
+          break;
+        Out << "u3i16";
+        addSubstitution(BuiltinType::Short);
+        break;
+      case 32:
+        if (mangleSubstitution(BuiltinType::Int))
+          break;
+        Out << "u3i32";
+        addSubstitution(BuiltinType::Int);
+        break;
+      case 64:
+        if (mangleSubstitution(BuiltinType::Long))
+          break;
+        Out << "u3i64";
+        addSubstitution(BuiltinType::Long);
+        break;
+      case 128:
+        if (mangleSubstitution(BuiltinType::Int128))
+          break;
+        Out << "u4i128";
+        addSubstitution(BuiltinType::Int128);
+        break;
+      default:
+        llvm_unreachable("Unknown integer size for normalization");
+      }
+    } else {
+      switch (getASTContext().getTypeSize(T)) {
+      case 8:
+        if (mangleSubstitution(BuiltinType::UChar))
+          break;
+        Out << "u2u8";
+        addSubstitution(BuiltinType::UChar);
+        break;
+      case 16:
+        if (mangleSubstitution(BuiltinType::UShort))
+          break;
+        Out << "u3u16";
+        addSubstitution(BuiltinType::UShort);
+        break;
+      case 32:
+        if (mangleSubstitution(BuiltinType::UInt))
+          break;
+        Out << "u3u32";
+        addSubstitution(BuiltinType::UInt);
+        break;
+      case 64:
+        if (mangleSubstitution(BuiltinType::ULong))
+          break;
+        Out << "u3u64";
+        addSubstitution(BuiltinType::ULong);
+        break;
+      case 128:
+        if (mangleSubstitution(BuiltinType::UInt128))
+          break;
+        Out << "u4u128";
+        addSubstitution(BuiltinType::UInt128);
+        break;
+      default:
+        llvm_unreachable("Unknown integer size for normalization");
+      }
+    }
+    return;
+  }
   switch (T->getKind()) {
   case BuiltinType::Void:
     Out << 'v';
@@ -6517,16 +6606,17 @@
   Mangler.mangleType(Ty);
 }
 
-void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
-                                                 raw_ostream &Out) {
+void ItaniumMangleContextImpl::mangleCXXRTTIName(
+    QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {
   // <special-name> ::= TS <type>  # typeinfo name (null terminated byte string)
-  CXXNameMangler Mangler(*this, Out);
+  CXXNameMangler Mangler(*this, Out, NormalizeIntegers);
   Mangler.getStream() << "_ZTS";
   Mangler.mangleType(Ty);
 }
 
-void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
-  mangleCXXRTTIName(Ty, Out);
+void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out,
+                                              bool NormalizeIntegers = false) {
+  mangleCXXRTTIName(Ty, Out, NormalizeIntegers);
 }
 
 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
Index: clang/include/clang/Driver/SanitizerArgs.h
===================================================================
--- clang/include/clang/Driver/SanitizerArgs.h
+++ clang/include/clang/Driver/SanitizerArgs.h
@@ -37,6 +37,7 @@
   bool MsanParamRetval = true;
   bool CfiCrossDso = false;
   bool CfiICallGeneralizePointers = false;
+  bool CfiICallNormalizeIntegers = false;
   bool CfiCanonicalJumpTables = false;
   int AsanFieldPadding = 0;
   bool SharedRuntime = false;
Index: clang/include/clang/Driver/Options.td
===================================================================
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1845,6 +1845,10 @@
                                               Group<f_clang_Group>,
                                               HelpText<"Generalize pointers in CFI indirect call type signature checks">,
                                               MarshallingInfoFlag<CodeGenOpts<"SanitizeCfiICallGeneralizePointers">>;
+def fsanitize_cfi_icall_normalize_integers : Flag<["-"], "fsanitize-cfi-icall-normalize-integers">,
+                                             Group<f_clang_Group>,
+                                             HelpText<"Normalize integers in CFI indirect call type signature checks">,
+                                             MarshallingInfoFlag<CodeGenOpts<"SanitizeCfiICallNormalizeIntegers">>;
 defm sanitize_cfi_canonical_jump_tables : BoolOption<"f", "sanitize-cfi-canonical-jump-tables",
   CodeGenOpts<"SanitizeCfiCanonicalJumpTables">, DefaultFalse,
   PosFlag<SetTrue, [], "Make">, NegFlag<SetFalse, [CoreOption, NoXarchOption], "Do not make">,
Index: clang/include/clang/Basic/CodeGenOptions.def
===================================================================
--- clang/include/clang/Basic/CodeGenOptions.def
+++ clang/include/clang/Basic/CodeGenOptions.def
@@ -258,6 +258,8 @@
                                          ///< diagnostics.
 CODEGENOPT(SanitizeCfiICallGeneralizePointers, 1, 0) ///< Generalize pointer types in
                                                      ///< CFI icall function signatures
+CODEGENOPT(SanitizeCfiICallNormalizeIntegers, 1, 0) ///< Normalize integer types in
+                                                    ///< CFI icall function signatures
 CODEGENOPT(SanitizeCfiCanonicalJumpTables, 1, 0) ///< Make jump table symbols canonical
                                                  ///< instead of creating a local jump table.
 CODEGENOPT(SanitizeCoverageType, 2, 0) ///< Type of sanitizer coverage
Index: clang/include/clang/AST/Mangle.h
===================================================================
--- clang/include/clang/AST/Mangle.h
+++ clang/include/clang/AST/Mangle.h
@@ -139,7 +139,8 @@
                                         unsigned ManglingNumber,
                                         raw_ostream &) = 0;
   virtual void mangleCXXRTTI(QualType T, raw_ostream &) = 0;
-  virtual void mangleCXXRTTIName(QualType T, raw_ostream &) = 0;
+  virtual void mangleCXXRTTIName(QualType T, raw_ostream &,
+                                 bool NormalizeIntegers = false) = 0;
   virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &) = 0;
   virtual void mangleMSGuidDecl(const MSGuidDecl *GD, raw_ostream&);
 
@@ -176,7 +177,8 @@
   /// or type uniquing.
   /// TODO: Extend this to internal types by generating names that are unique
   /// across translation units so it can be used with LTO.
-  virtual void mangleTypeName(QualType T, raw_ostream &) = 0;
+  virtual void mangleTypeName(QualType T, raw_ostream &,
+                              bool NormalizeIntegers = false) = 0;
 
   /// @}
 };
Index: clang/docs/UsersManual.rst
===================================================================
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -1951,6 +1951,12 @@
    checked by Control Flow Integrity indirect call checking. See
    :doc:`ControlFlowIntegrity` for more details.
 
+.. option:: -fsanitize-cfi-icall-normalize-integers
+
+   Normalize integers in return and argument types in function type signatures
+   checked by Control Flow Integrity indirect call checking. See
+   :doc:`ControlFlowIntegrity` for more details.
+
 .. option:: -fstrict-vtable-pointers
 
    Enable optimizations based on the strict rules for overwriting polymorphic
Index: clang/docs/ControlFlowIntegrity.rst
===================================================================
--- clang/docs/ControlFlowIntegrity.rst
+++ clang/docs/ControlFlowIntegrity.rst
@@ -236,6 +236,23 @@
 ``-fsanitize-cfi-icall-generalize-pointers`` is not compatible with
 ``-fsanitize-cfi-cross-dso``.
 
+.. _cfi-icall-normalize-integers:
+
+``-fsanitize-cfi-icall-normalize-integers``
+--------------------------------------------
+
+This option enables normalizing integer types as vendor extended types for
+cross-language LLVM CFI/KCFI support with other languages that can't represent
+and encode C/C++ integer types.
+
+Specifically, integer types are encoded as their defined representations (e.g.,
+8-bit signed integer, 16-bit signed integer, 32-bit signed integer, ...) for
+compatibility with languages that define explicitly-sized integer types (e.g.,
+i8, i16, i32, ..., in Rust).
+
+``-fsanitize-cfi-icall-normalize-integers`` is compatible with
+``-fsanitize-cfi-icall-generalize-pointers``.
+
 .. _cfi-canonical-jump-tables:
 
 ``-fsanitize-cfi-canonical-jump-tables``
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to