Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ConcurrentReadableArray: Use std::uninitialized_copy_n() instead of std::copy() to avoid calling destructors on uninitialized memory #40521

Merged
merged 1 commit into from
Dec 13, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions include/swift/Runtime/Concurrent.h
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ template <class ElemTy> struct ConcurrentReadableArray {
auto newCapacity = std::max((size_t)16, count * 2);
auto *newStorage = Storage::allocate(newCapacity);
if (storage) {
std::copy(storage->data(), storage->data() + count, newStorage->data());
std::uninitialized_copy_n(storage->data(), count, newStorage->data());
newStorage->Count.store(count, std::memory_order_release);
ConcurrentFreeListNode::add(&FreeList, storage);
}
Expand Down Expand Up @@ -622,10 +622,7 @@ using llvm::hash_value;
/// outstanding readers, but this won't destroy the static mutex it uses.
template <class ElemTy, class MutexTy = StaticMutex>
struct ConcurrentReadableHashMap {
// We use memcpy and don't call destructors. Make sure the elements will put
// up with this.
static_assert(std::is_trivially_copyable<ElemTy>::value,
"Elements must be trivially copyable.");
// We don't call destructors. Make sure the elements will put up with this.
static_assert(std::is_trivially_destructible<ElemTy>::value,
"Elements must not have destructors (they won't be called).");

Expand Down Expand Up @@ -884,8 +881,13 @@ struct ConcurrentReadableHashMap {
auto *newElements = ElementStorage::allocate(newCapacity);

if (elements) {
memcpy(newElements->data(), elements->data(),
elementCount * sizeof(ElemTy));
if constexpr (std::is_trivially_copyable<ElemTy>::value) {
memcpy(newElements->data(), elements->data(),
elementCount * sizeof(ElemTy));
} else {
std::uninitialized_copy_n(elements->data(), elementCount,
newElements->data());
}
ConcurrentFreeListNode::add(&FreeList, elements);
}

Expand Down