Skip to content

Commit 3dc43ab

Browse files
authored
Fix undefined behaviour in View::tryCopyTo overlap (#1287)
1 parent 26a23b4 commit 3dc43ab

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

include/cpp/marshal/View.hpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@ inline bool cpp::marshal::View<T>::tryCopyTo(const View<T>& destination) const
1515
return false;
1616
}
1717

18-
std::memcpy(destination.ptr.ptr, ptr.ptr, sizeof(T) * length);
18+
if (ptr.ptr + length < destination.ptr.ptr || destination.ptr.ptr + length < ptr.ptr)
19+
std::memcpy(destination.ptr.ptr, ptr.ptr, sizeof(T) * length);
20+
else
21+
std::memmove(destination.ptr.ptr, ptr.ptr, sizeof(T) * length);
1922

2023
return true;
2124
}

test/native/tests/marshalling/view/TestView.hx

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,5 +291,13 @@ class TestView extends Test {
291291
Assert.same(buffer, biggerDst.slice(0, 10));
292292
Assert.same(buffer, matchingDst);
293293
Assert.same(buffer.slice(0, smallerDst.length), smallerDst);
294+
295+
final overlapped = buffer.copy();
296+
297+
final regionA = overlapped.asView().slice(2, 5);
298+
final regionB = overlapped.asView().slice(4, 5);
299+
300+
Assert.isTrue(regionB.tryCopyTo(regionA));
301+
Assert.same([0, 1, 4, 5, 6, 7, 8, 7, 8, 9], overlapped);
294302
}
295303
}

0 commit comments

Comments
 (0)