Skip to content

Commit

Permalink
Set default alignment for SysAllocator to cache-line size
Browse files Browse the repository at this point in the history
Avoids memory corruptions when the memory is cleared via DCZeroRange. Seen in BotW with AX AUX buffers.
  • Loading branch information
Exzap committed Oct 18, 2023
1 parent 9bb4093 commit b0a7fd4
Showing 1 changed file with 18 additions and 9 deletions.
27 changes: 18 additions & 9 deletions src/Common/SysAllocator.h
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#pragma once

#include <vector>

uint32 coreinit_allocFromSysArea(uint32 size, uint32 alignment);
class SysAllocatorBase;

#define SYSALLOCATOR_GUARDS 0 // if 1, create a magic constant at the top of each memory allocation which is used to check for memory corruption

class SysAllocatorContainer
{
public:
Expand All @@ -29,9 +29,7 @@ class SysAllocatorBase
virtual void Initialize() = 0;
};



template<typename T, size_t count = 1, size_t alignment = 8>
template<typename T, size_t count = 1, size_t alignment = 32>
class SysAllocator : public SysAllocatorBase
{
public:
Expand Down Expand Up @@ -68,11 +66,17 @@ class SysAllocator : public SysAllocatorBase

T* GetPtr() const
{
#if SYSALLOCATOR_GUARDS
cemu_assert(*(uint32*)((uint8*)m_sysMem.GetPtr()+(sizeof(T) * count)) == 0x112A33C4);
#endif
return m_sysMem.GetPtr();
}

uint32 GetMPTR() const
{
#if SYSALLOCATOR_GUARDS
cemu_assert(*(uint32*)((uint8*)m_sysMem.GetPtr()+(sizeof(T) * count)) == 0x112A33C4);
#endif
return m_sysMem.GetMPTR();
}

Expand Down Expand Up @@ -130,11 +134,17 @@ class SysAllocator : public SysAllocatorBase
{
if (m_sysMem.GetMPTR() != 0)
return;

// alloc mem
m_sysMem = { coreinit_allocFromSysArea(sizeof(T) * count, alignment) };
uint32 guardSize = 0;
#if SYSALLOCATOR_GUARDS
guardSize = 4;
#endif
m_sysMem = { coreinit_allocFromSysArea(sizeof(T) * count + guardSize, alignment) };
// copy temp buffer to mem and clear it
memcpy(m_sysMem.GetPtr(), m_tempData.data(), sizeof(T)*count);
#if SYSALLOCATOR_GUARDS
*(uint32*)((uint8*)m_sysMem.GetPtr()+(sizeof(T) * count)) = 0x112A33C4;
#endif
m_tempData.clear();
}

Expand Down Expand Up @@ -197,9 +207,8 @@ class SysAllocator<T, 1> : public SysAllocatorBase
{
if (m_sysMem.GetMPTR() != 0)
return;

// alloc mem
m_sysMem = { coreinit_allocFromSysArea(sizeof(T), 8) };
m_sysMem = { coreinit_allocFromSysArea(sizeof(T), 32) };
// copy temp buffer to mem and clear it
*m_sysMem = m_tempData;
}
Expand Down

0 comments on commit b0a7fd4

Please sign in to comment.