Skip to content

Commit 4dde52d

Browse files
authored
[clang][bytecode] Check for overlapping memcpy regions (#119535)
1 parent 14dcf82 commit 4dde52d

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

clang/lib/AST/ByteCode/InterpBuiltin.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1875,6 +1875,20 @@ static bool interp__builtin_memcpy(InterpState &S, CodePtr OpPC,
18751875
return false;
18761876
}
18771877

1878+
// Check for overlapping memory regions.
1879+
if (!Move && SrcPtr.block() == DestPtr.block()) {
1880+
unsigned SrcIndex = SrcPtr.getIndex() * SrcPtr.elemSize();
1881+
unsigned DstIndex = DestPtr.getIndex() * DestPtr.elemSize();
1882+
unsigned N = Size.getZExtValue();
1883+
1884+
if ((SrcIndex <= DstIndex && (SrcIndex + N) > DstIndex) ||
1885+
(DstIndex <= SrcIndex && (DstIndex + N) > SrcIndex)) {
1886+
S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_memcpy_overlap)
1887+
<< /*IsWChar=*/false;
1888+
return false;
1889+
}
1890+
}
1891+
18781892
// As a last resort, reject dummy pointers.
18791893
if (DestPtr.isDummy() || SrcPtr.isDummy())
18801894
return false;

clang/test/AST/ByteCode/builtin-functions.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1207,4 +1207,19 @@ namespace BuiltinMemcpy {
12071207
}
12081208
static_assert(memcpyTypeRem() == 12); // both-error {{not an integral constant expression}} \
12091209
// both-note {{in call to}}
1210+
1211+
template<typename T>
1212+
constexpr T result(T (&arr)[4]) {
1213+
return arr[0] * 1000 + arr[1] * 100 + arr[2] * 10 + arr[3];
1214+
}
1215+
1216+
constexpr int test_memcpy(int a, int b, int n) {
1217+
int arr[4] = {1, 2, 3, 4};
1218+
__builtin_memcpy(arr + a, arr + b, n); // both-note {{overlapping memory regions}}
1219+
return result(arr);
1220+
}
1221+
1222+
static_assert(test_memcpy(1, 2, sizeof(int)) == 1334);
1223+
static_assert(test_memcpy(0, 1, sizeof(int) * 2) == 2334); // both-error {{not an integral constant expression}} \
1224+
// both-note {{in call}}
12101225
}

0 commit comments

Comments
 (0)