https://github.com/tbaederr created https://github.com/llvm/llvm-project/pull/119535
None >From 03a5f354277a36d8380477bbd13a35484d701d3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timm=20B=C3=A4der?= <tbae...@redhat.com> Date: Wed, 11 Dec 2024 11:08:40 +0100 Subject: [PATCH] [clang][bytecode] Check for overlapping memcpy regions --- clang/lib/AST/ByteCode/InterpBuiltin.cpp | 14 ++++++++++++++ clang/test/AST/ByteCode/builtin-functions.cpp | 15 +++++++++++++++ 2 files changed, 29 insertions(+) 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}} } _______________________________________________ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits