[clang] 4dde52d - [clang][bytecode] Check for overlapping memcpy regions (#119535)

via cfe-commits cfe-commits at lists.llvm.org
Wed Dec 11 03:07:00 PST 2024


Author: Timm Baeder
Date: 2024-12-11T12:06:56+01:00
New Revision: 4dde52d76b5342fd7e0b51094580818f3934ae2f

URL: https://github.com/llvm/llvm-project/commit/4dde52d76b5342fd7e0b51094580818f3934ae2f
DIFF: https://github.com/llvm/llvm-project/commit/4dde52d76b5342fd7e0b51094580818f3934ae2f.diff

LOG: [clang][bytecode] Check for overlapping memcpy regions (#119535)

Added: 
    

Modified: 
    clang/lib/AST/ByteCode/InterpBuiltin.cpp
    clang/test/AST/ByteCode/builtin-functions.cpp

Removed: 
    


################################################################################
diff  --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index a0de193ec32a2f..4fe17ec01906e9 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1875,6 +1875,20 @@ static bool interp__builtin_memcpy(InterpState &S, CodePtr OpPC,
     return false;
   }
 
+  // Check for overlapping memory regions.
+  if (!Move && SrcPtr.block() == DestPtr.block()) {
+    unsigned SrcIndex = SrcPtr.getIndex() * SrcPtr.elemSize();
+    unsigned DstIndex = DestPtr.getIndex() * DestPtr.elemSize();
+    unsigned N = Size.getZExtValue();
+
+    if ((SrcIndex <= DstIndex && (SrcIndex + N) > DstIndex) ||
+        (DstIndex <= SrcIndex && (DstIndex + N) > SrcIndex)) {
+      S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_memcpy_overlap)
+          << /*IsWChar=*/false;
+      return false;
+    }
+  }
+
   // As a last resort, reject dummy pointers.
   if (DestPtr.isDummy() || SrcPtr.isDummy())
     return false;

diff  --git a/clang/test/AST/ByteCode/builtin-functions.cpp b/clang/test/AST/ByteCode/builtin-functions.cpp
index 7dd08cb5fa1c35..ef6faae030a8f2 100644
--- a/clang/test/AST/ByteCode/builtin-functions.cpp
+++ b/clang/test/AST/ByteCode/builtin-functions.cpp
@@ -1207,4 +1207,19 @@ namespace BuiltinMemcpy {
   }
   static_assert(memcpyTypeRem() == 12); // both-error {{not an integral constant expression}} \
                                         // both-note {{in call to}}
+
+  template<typename T>
+  constexpr T result(T (&arr)[4]) {
+    return arr[0] * 1000 + arr[1] * 100 + arr[2] * 10 + arr[3];
+  }
+
+  constexpr int test_memcpy(int a, int b, int n) {
+    int arr[4] = {1, 2, 3, 4};
+    __builtin_memcpy(arr + a, arr + b, n); // both-note {{overlapping memory regions}}
+    return result(arr);
+  }
+
+  static_assert(test_memcpy(1, 2, sizeof(int)) == 1334);
+  static_assert(test_memcpy(0, 1, sizeof(int) * 2) == 2334); // both-error {{not an integral constant expression}} \
+                                                             // both-note {{in call}}
 }


        


More information about the cfe-commits mailing list