From 1432912ae88e750ae0aae8972d7e260538d271df Mon Sep 17 00:00:00 2001 From: Lioncash Date: Mon, 23 Jul 2018 14:52:32 -0400 Subject: [PATCH] vi: Add std::is_trivially_copyable checks to Read and Write functions It's undefined behavior to memcpy an object that isn't considered trivially copyable, so put a compile-time check in to make sure this doesn't occur. --- src/core/hle/service/vi/vi.cpp | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/core/hle/service/vi/vi.cpp b/src/core/hle/service/vi/vi.cpp index 0499575036..993f1e65a2 100644 --- a/src/core/hle/service/vi/vi.cpp +++ b/src/core/hle/service/vi/vi.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include "common/alignment.h" @@ -44,7 +45,9 @@ public: template T Read() { + static_assert(std::is_trivially_copyable_v, "T must be trivially copyable."); ASSERT(read_index + sizeof(T) <= buffer.size()); + T val; std::memcpy(&val, buffer.data() + read_index, sizeof(T)); read_index += sizeof(T); @@ -54,7 +57,9 @@ public: template T ReadUnaligned() { + static_assert(std::is_trivially_copyable_v, "T must be trivially copyable."); ASSERT(read_index + sizeof(T) <= buffer.size()); + T val; std::memcpy(&val, buffer.data() + read_index, sizeof(T)); read_index += sizeof(T); @@ -88,8 +93,12 @@ public: template void Write(const T& val) { - if (buffer.size() < write_index + sizeof(T)) + static_assert(std::is_trivially_copyable_v, "T must be trivially copyable."); + + if (buffer.size() < write_index + sizeof(T)) { buffer.resize(buffer.size() + sizeof(T) + DefaultBufferSize); + } + std::memcpy(buffer.data() + write_index, &val, sizeof(T)); write_index += sizeof(T); write_index = Common::AlignUp(write_index, 4); @@ -97,7 +106,9 @@ public: template void WriteObject(const T& val) { - u32_le size = static_cast(sizeof(val)); + static_assert(std::is_trivially_copyable_v, "T must be trivially copyable."); + + const u32_le size = static_cast(sizeof(val)); Write(size); // TODO(Subv): Support file descriptors. Write(0); // Fd count.