Skip to content

Commit

Permalink
std::memcmp/memset/memcmp -> MemCopy/MemFill/MemCompare with size check
Browse files Browse the repository at this point in the history
  • Loading branch information
cvet committed Jan 16, 2025
1 parent 543ffbf commit df4ea76
Show file tree
Hide file tree
Showing 27 changed files with 214 additions and 210 deletions.
18 changes: 9 additions & 9 deletions Source/Client/3dStuff.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -504,10 +504,10 @@ auto ModelInstance::SetAnimation(CritterStateAnim state_anim, CritterActionAnim
// Check animation changes
int new_layers[MODEL_LAYERS_COUNT];
if (layers != nullptr) {
std::memcpy(new_layers, layers, sizeof(int) * MODEL_LAYERS_COUNT);
MemCopy(new_layers, layers, sizeof(int) * MODEL_LAYERS_COUNT);
}
else {
std::memcpy(new_layers, _currentLayers, sizeof(int) * MODEL_LAYERS_COUNT);
MemCopy(new_layers, _currentLayers, sizeof(int) * MODEL_LAYERS_COUNT);
}

// Animation layers
Expand All @@ -533,7 +533,7 @@ auto ModelInstance::SetAnimation(CritterStateAnim state_anim, CritterActionAnim
return false;
}

std::memcpy(_currentLayers, new_layers, sizeof(int) * MODEL_LAYERS_COUNT);
MemCopy(_currentLayers, new_layers, sizeof(int) * MODEL_LAYERS_COUNT);
_currentLayers[MODEL_LAYERS_COUNT] = static_cast<int>(anim_pair);

auto mesh_changed = false;
Expand Down Expand Up @@ -1984,7 +1984,7 @@ void ModelInstance::DrawCombinedMesh(const CombinedMesh* combined_mesh, bool sha
auto* effect = combined_mesh->DrawEffect != nullptr ? combined_mesh->DrawEffect : _modelMngr._effectMngr.Effects.SkinnedModel;

auto&& proj_buf = effect->ProjBuf = RenderEffect::ProjBuffer();
std::memcpy(proj_buf->ProjMatrix, _frameProjColMaj[0], 16 * sizeof(float));
MemCopy(proj_buf->ProjMatrix, _frameProjColMaj[0], 16 * sizeof(float));

effect->MainTex = combined_mesh->Textures[0] != nullptr ? combined_mesh->Textures[0]->MainTex : nullptr;

Expand All @@ -1995,24 +1995,24 @@ void ModelInstance::DrawCombinedMesh(const CombinedMesh* combined_mesh, bool sha
for (size_t i = 0; i < combined_mesh->CurBoneMatrix; i++) {
auto m = combined_mesh->SkinBones[i]->CombinedTransformationMatrix * combined_mesh->SkinBoneOffsets[i];
m.Transpose(); // Convert to column major order
std::memcpy(wm, m[0], 16 * sizeof(float));
MemCopy(wm, m[0], 16 * sizeof(float));
wm += 16;
}
effect->MatrixCount = combined_mesh->CurBoneMatrix;

std::memcpy(model_buf->GroundPosition, &_groundPos, 3 * sizeof(float));
MemCopy(model_buf->GroundPosition, &_groundPos, 3 * sizeof(float));
model_buf->GroundPosition[3] = 0.0f;

std::memcpy(model_buf->LightColor, &_modelMngr._lightColor, 4 * sizeof(float));
MemCopy(model_buf->LightColor, &_modelMngr._lightColor, 4 * sizeof(float));

if (effect->NeedModelTexBuf) {
auto&& custom_tex_buf = effect->ModelTexBuf = RenderEffect::ModelTexBuffer();

for (size_t i = 0; i < MODEL_MAX_TEXTURES; i++) {
if (combined_mesh->Textures[i] != nullptr) {
effect->ModelTex[i] = combined_mesh->Textures[i]->MainTex;
std::memcpy(&custom_tex_buf->TexAtlasOffset[i * 4 * sizeof(float)], combined_mesh->Textures[i]->AtlasOffsetData, 4 * sizeof(float));
std::memcpy(&custom_tex_buf->TexSize[i * 4 * sizeof(float)], combined_mesh->Textures[i]->MainTex->SizeData, 4 * sizeof(float));
MemCopy(&custom_tex_buf->TexAtlasOffset[i * 4 * sizeof(float)], combined_mesh->Textures[i]->AtlasOffsetData, 4 * sizeof(float));
MemCopy(&custom_tex_buf->TexSize[i * 4 * sizeof(float)], combined_mesh->Textures[i]->MainTex->SizeData, 4 * sizeof(float));
}
else {
effect->ModelTex[i] = nullptr;
Expand Down
6 changes: 3 additions & 3 deletions Source/Client/MapView.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2498,7 +2498,7 @@ void MapView::Resize(msize size)
_mapSize = size;

_hexTrack.resize(_mapSize.GetSquare());
std::memset(_hexTrack.data(), 0, _hexTrack.size());
MemFill(_hexTrack.data(), 0, _hexTrack.size());
_hexLight.resize(static_cast<size_t>(_mapSize.GetSquare()) * 3);
_hexField->Resize(_mapSize);

Expand Down Expand Up @@ -2526,7 +2526,7 @@ void MapView::ClearHexTrack()

RUNTIME_ASSERT(_mapperMode);

std::memset(_hexTrack.data(), 0, _hexTrack.size() * sizeof(char));
MemFill(_hexTrack.data(), 0, _hexTrack.size() * sizeof(char));
}

void MapView::SwitchShowTrack()
Expand Down Expand Up @@ -3937,7 +3937,7 @@ auto MapView::FindPath(CritterHexView* cr, mpos start_hex, mpos& target_hex, int

const auto max_path_find_len = _engine->Settings.MaxPathFindLength;
_findPathGrid.resize((static_cast<size_t>(max_path_find_len) * 2 + 2) * (max_path_find_len * 2 + 2));
std::memset(_findPathGrid.data(), 0, _findPathGrid.size() * sizeof(int16));
MemFill(_findPathGrid.data(), 0, _findPathGrid.size() * sizeof(int16));

const auto grid_offset = start_hex;
const auto grid_at = [&](mpos hex) -> short& { return _findPathGrid[((max_path_find_len + 1) + (hex.y) - grid_offset.y) * (max_path_find_len * 2 + 2) + ((max_path_find_len + 1) + (hex.x) - grid_offset.x)]; };
Expand Down
2 changes: 1 addition & 1 deletion Source/Client/ServerConnection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -822,7 +822,7 @@ void ServerConnection::Impl::FillSockAddr(sockaddr_in& saddr, string_view host,
throw ServerConnectionException("Can't resolve remote host", host, GetLastSocketError());
}

std::memcpy(&saddr.sin_addr, h->h_addr, sizeof(in_addr));
MemCopy(&saddr.sin_addr, h->h_addr, sizeof(in_addr));
}
}

Expand Down
12 changes: 6 additions & 6 deletions Source/Client/SoundManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ auto SoundManager::ProcessSound(Sound* sound, uint8* output) -> bool
if (whole > sound->ConvertedBuf.size() - sound->ConvertedBufCur) {
// Flush last part of buffer
auto offset = sound->ConvertedBuf.size() - sound->ConvertedBufCur;
std::memcpy(output, &sound->ConvertedBuf[sound->ConvertedBufCur], offset);
MemCopy(output, &sound->ConvertedBuf[sound->ConvertedBufCur], offset);
sound->ConvertedBufCur += offset;

// Stream new parts
Expand All @@ -144,19 +144,19 @@ auto SoundManager::ProcessSound(Sound* sound, uint8* output) -> bool
write = whole - offset;
}

std::memcpy(output + offset, &sound->ConvertedBuf[sound->ConvertedBufCur], write);
MemCopy(output + offset, &sound->ConvertedBuf[sound->ConvertedBufCur], write);
sound->ConvertedBufCur += write;
offset += write;
}

// Cut off end
if (offset < whole) {
std::memset(output + offset, App->Audio.GetSilence(), whole - offset);
MemFill(output + offset, App->Audio.GetSilence(), whole - offset);
}
}
else {
// Copy
std::memcpy(output, &sound->ConvertedBuf[sound->ConvertedBufCur], whole);
MemCopy(output, &sound->ConvertedBuf[sound->ConvertedBufCur], whole);
sound->ConvertedBufCur += whole;
}

Expand Down Expand Up @@ -190,12 +190,12 @@ auto SoundManager::ProcessSound(Sound* sound, uint8* output) -> bool
}

// Give silent
std::memset(output, App->Audio.GetSilence(), whole);
MemFill(output, App->Audio.GetSilence(), whole);
return true;
}

// Give silent
std::memset(output, App->Audio.GetSilence(), whole);
MemFill(output, App->Audio.GetSilence(), whole);

return false;
}
Expand Down
2 changes: 1 addition & 1 deletion Source/Client/SparkExtension.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ namespace SPK::FO
RUNTIME_ASSERT(_effect != nullptr);
RUNTIME_ASSERT(_texture != nullptr);
_effect->ProjBuf = RenderEffect::ProjBuffer();
std::memcpy(_effect->ProjBuf->ProjMatrix, &_particleMngr->_projMatColMaj, sizeof(_effect->ProjBuf->ProjMatrix));
MemCopy(_effect->ProjBuf->ProjMatrix, &_particleMngr->_projMatColMaj, sizeof(_effect->ProjBuf->ProjMatrix));
_effect->MainTex = _texture;

buffer.Render(group.getNbParticles() << 2, _effect);
Expand Down
4 changes: 2 additions & 2 deletions Source/Client/SpriteManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1863,11 +1863,11 @@ static void StrCopy(char* to, size_t size, string_view from)
}

if (from.length() >= size) {
std::memcpy(to, from.data(), size - 1);
MemCopy(to, from.data(), size - 1);
to[size - 1] = 0;
}
else {
std::memcpy(to, from.data(), from.length());
MemCopy(to, from.data(), from.length());
to[from.length()] = 0;
}
}
Expand Down
2 changes: 1 addition & 1 deletion Source/Client/VideoClip.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ int VideoClip::DecodePacket()
}

auto* dest_buf = ogg_sync_buffer(&_impl->SyncState, read_bytes);
std::memcpy(dest_buf, _impl->RawVideoData.data() + _impl->ReadPos, read_bytes);
MemCopy(dest_buf, _impl->RawVideoData.data() + _impl->ReadPos, read_bytes);
_impl->ReadPos += read_bytes;
ogg_sync_wrote(&_impl->SyncState, read_bytes);
}
Expand Down
39 changes: 35 additions & 4 deletions Source/Common/Common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1159,7 +1159,7 @@ extern void* CRTDECL operator new[](std::size_t size, std::align_val_t align, co

#endif

extern auto MemMalloc(size_t size) -> void*
extern auto MemMalloc(size_t size) noexcept -> void*
{
NO_STACK_TRACE_ENTRY();

Expand All @@ -1175,7 +1175,7 @@ extern auto MemMalloc(size_t size) -> void*
#endif
}

extern auto MemCalloc(size_t num, size_t size) -> void*
extern auto MemCalloc(size_t num, size_t size) noexcept -> void*
{
NO_STACK_TRACE_ENTRY();

Expand All @@ -1191,7 +1191,7 @@ extern auto MemCalloc(size_t num, size_t size) -> void*
#endif
}

extern auto MemRealloc(void* ptr, size_t size) -> void*
extern auto MemRealloc(void* ptr, size_t size) noexcept -> void*
{
NO_STACK_TRACE_ENTRY();

Expand All @@ -1208,7 +1208,7 @@ extern auto MemRealloc(void* ptr, size_t size) -> void*
#endif
}

extern void MemFree(void* ptr)
extern void MemFree(void* ptr) noexcept
{
NO_STACK_TRACE_ENTRY();

Expand All @@ -1222,6 +1222,37 @@ extern void MemFree(void* ptr)
#endif
}

extern void MemCopy(void* dest, const void* src, size_t size) noexcept
{
NO_STACK_TRACE_ENTRY();

// Standard: If either dest or src is an invalid or null pointer, the behavior is undefined, even if count is zero
// So check size first
if (size != 0) {
std::memcpy(dest, src, size);
}
}

extern void MemFill(void* ptr, int value, size_t size) noexcept
{
NO_STACK_TRACE_ENTRY();

if (size != 0) {
std::memset(ptr, value, size);
}
}

extern auto MemCompare(const void* ptr1, const void* ptr2, size_t size) noexcept -> bool
{
NO_STACK_TRACE_ENTRY();

if (size != 0) {
return std::memcmp(ptr1, ptr2, size) == 0;
}

return true;
}

static constexpr size_t BACKUP_MEMORY_CHUNKS = 100;
static constexpr size_t BACKUP_MEMORY_CHUNK_SIZE = 100000; // 100 chunks x 100kb = 10mb
static unique_ptr<unique_ptr<uint8[]>[]> BackupMemoryChunks;
Expand Down
25 changes: 13 additions & 12 deletions Source/Common/Common.h
Original file line number Diff line number Diff line change
Expand Up @@ -374,11 +374,14 @@ class SafeAlloc
}
};

// Custom C allocators
extern auto MemMalloc(size_t size) -> void*;
extern auto MemCalloc(size_t num, size_t size) -> void*;
extern auto MemRealloc(void* ptr, size_t size) -> void*;
extern void MemFree(void* ptr);
// Memory low level management
extern auto MemMalloc(size_t size) noexcept -> void*;
extern auto MemCalloc(size_t num, size_t size) noexcept -> void*;
extern auto MemRealloc(void* ptr, size_t size) noexcept -> void*;
extern void MemFree(void* ptr) noexcept;
extern void MemCopy(void* dest, const void* src, size_t size) noexcept;
extern void MemFill(void* ptr, int value, size_t size) noexcept;
extern auto MemCompare(const void* ptr1, const void* ptr2, size_t size) noexcept -> bool;

// Basic types with safe allocator
using string = std::basic_string<char, std::char_traits<char>, SafeAllocator<char>>;
Expand Down Expand Up @@ -1395,7 +1398,7 @@ class DataReader
throw DataReadingException("Unexpected end of buffer");
}

std::memcpy(ptr, &_dataBuf[_readPos], sizeof(T));
MemCopy(ptr, &_dataBuf[_readPos], sizeof(T));
_readPos += sizeof(T);
}

Expand All @@ -1406,10 +1409,8 @@ class DataReader
throw DataReadingException("Unexpected end of buffer");
}

if (size != 0) {
std::memcpy(ptr, &_dataBuf[_readPos], size);
_readPos += size;
}
MemCopy(ptr, _dataBuf.data() + _readPos, size);
_readPos += size;
}

void VerifyEnd() const
Expand Down Expand Up @@ -1446,15 +1447,15 @@ class DataWriter
void WritePtr(const T* data) noexcept
{
ResizeBuf(sizeof(T));
std::memcpy(_dataBuf.data() + _dataBuf.size() - sizeof(T), data, sizeof(T));
MemCopy(_dataBuf.data() + _dataBuf.size() - sizeof(T), data, sizeof(T));
}

template<typename T>
void WritePtr(const T* data, size_t size) noexcept
{
if (size != 0) {
ResizeBuf(size);
std::memcpy(_dataBuf.data() + _dataBuf.size() - size, data, size);
MemCopy(_dataBuf.data() + _dataBuf.size() - size, data, size);
}
}

Expand Down
18 changes: 9 additions & 9 deletions Source/Common/DataSource.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,7 @@ auto FalloutDat::ReadTree() -> bool

tree_size -= 28 + 4; // Subtract information block and files total
_memTree = SafeAlloc::MakeUniqueArr<uint8>(tree_size);
std::memset(_memTree.get(), 0, tree_size);
MemFill(_memTree.get(), 0, tree_size);

if (!_datFile.Read(_memTree.get(), tree_size)) {
return false;
Expand All @@ -550,9 +550,9 @@ auto FalloutDat::ReadTree() -> bool

while (ptr < end_ptr) {
uint fnsz = 0;
std::memcpy(&fnsz, ptr, sizeof(fnsz));
MemCopy(&fnsz, ptr, sizeof(fnsz));
uint type = 0;
std::memcpy(&type, ptr + 4 + fnsz + 4, sizeof(type));
MemCopy(&type, ptr + 4 + fnsz + 4, sizeof(type));

if (fnsz != 0 && type != 0x400) { // Not folder
string name = strex(string(reinterpret_cast<const char*>(ptr) + 4, fnsz)).normalizePathSlashes();
Expand Down Expand Up @@ -629,7 +629,7 @@ auto FalloutDat::ReadTree() -> bool

while (ptr < end_ptr) {
uint name_len = 0;
std::memcpy(&name_len, ptr, 4);
MemCopy(&name_len, ptr, 4);

if (ptr + 4 + name_len > end_ptr) {
return false;
Expand Down Expand Up @@ -665,7 +665,7 @@ auto FalloutDat::IsFilePresent(string_view path, size_t& size, uint64& write_tim
}

uint real_size = 0;
std::memcpy(&real_size, it->second + 1, sizeof(real_size));
MemCopy(&real_size, it->second + 1, sizeof(real_size));

size = real_size;
write_time = _writeTime;
Expand All @@ -684,13 +684,13 @@ auto FalloutDat::OpenFile(string_view path, size_t& size, uint64& write_time) co

const auto* ptr = it->second;
uint8 type = 0;
std::memcpy(&type, ptr, sizeof(type));
MemCopy(&type, ptr, sizeof(type));
uint real_size = 0;
std::memcpy(&real_size, ptr + 1, sizeof(real_size));
MemCopy(&real_size, ptr + 1, sizeof(real_size));
uint packed_size = 0;
std::memcpy(&packed_size, ptr + 5, sizeof(packed_size));
MemCopy(&packed_size, ptr + 5, sizeof(packed_size));
int offset = 0;
std::memcpy(&offset, ptr + 9, sizeof(offset));
MemCopy(&offset, ptr + 9, sizeof(offset));

if (!_datFile.SetReadPos(offset, DiskFileSeek::Set)) {
throw DataSourceException("Can't read file from fallout dat (1)", path);
Expand Down
6 changes: 3 additions & 3 deletions Source/Common/FileSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ File::File(string_view name, string_view path, uint64 write_time, DataSource* ds

if (make_copy) {
auto buf_copy = SafeAlloc::MakeUniqueArr<uint8>(buf.size());
std::memcpy(buf_copy.get(), buf.data(), buf.size());
MemCopy(buf_copy.get(), buf.data(), buf.size());
_fileBuf = {buf_copy.release(), [](const auto* p) { delete[] p; }};
}
else {
Expand All @@ -157,7 +157,7 @@ auto File::GetData() const -> vector<uint8>

vector<uint8> result;
result.resize(_fileSize);
std::memcpy(result.data(), _fileBuf.get(), _fileSize);
MemCopy(result.data(), _fileBuf.get(), _fileSize);
return result;
}

Expand Down Expand Up @@ -268,7 +268,7 @@ void File::CopyData(void* ptr, size_t size)
throw FileSystemExeption("Read file error", _fileName);
}

std::memcpy(ptr, _fileBuf.get() + _curPos, size);
MemCopy(ptr, _fileBuf.get() + _curPos, size);
_curPos += size;
}

Expand Down
Loading

0 comments on commit df4ea76

Please sign in to comment.