Skip to content

Commit

Permalink
Fix crash when loading very long localization lines
Browse files Browse the repository at this point in the history
The client previously crashed when loading a localization file with a replacement line (plus zero terminator) longer than the size of a `CHeap` chunk (65600 bytes) due to the line data being written outside the heap chunk.

This is fixed by allowing `CHeap` to allocate chunks as large as necessary to contain at least one item.

As an alternative the `CHeap` functions could be changed to return `nullptr` if the wanted allocation is too large, which would have to be handled explicitly when loading localization files.
  • Loading branch information
Robyt3 committed Jan 13, 2025
1 parent d3442aa commit 9706000
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
13 changes: 8 additions & 5 deletions src/engine/shared/memheap.cpp
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include "memheap.h"

#include <base/math.h>
#include <base/system.h>

#include <cstdint>
#include <cstdlib>

// allocates a new chunk to be used
void CHeap::NewChunk()
void CHeap::NewChunk(size_t ChunkSize)
{
// the chunk structure is located in the beginning of the chunk
// init it and return the chunk
CChunk *pChunk = static_cast<CChunk *>(malloc(sizeof(CChunk) + CHUNK_SIZE));
CChunk *pChunk = static_cast<CChunk *>(malloc(sizeof(CChunk) + ChunkSize));
if(!pChunk)
return;
pChunk->m_pMemory = static_cast<char *>(static_cast<void *>(pChunk + 1));
pChunk->m_pCurrent = pChunk->m_pMemory;
pChunk->m_pEnd = pChunk->m_pMemory + CHUNK_SIZE;
pChunk->m_pEnd = pChunk->m_pMemory + ChunkSize;
pChunk->m_pNext = nullptr;

pChunk->m_pNext = m_pCurrent;
Expand Down Expand Up @@ -54,7 +57,7 @@ CHeap::~CHeap()
void CHeap::Reset()
{
Clear();
NewChunk();
NewChunk(CHUNK_SIZE);
}

// destroys the heap
Expand All @@ -76,7 +79,7 @@ void *CHeap::Allocate(unsigned Size, unsigned Alignment)
if(!pMem)
{
// allocate new chunk and add it to the heap
NewChunk();
NewChunk(maximum<size_t>(CHUNK_SIZE, Size + Alignment));

// try to allocate again
pMem = AllocateFromChunk(Size, Alignment);
Expand Down
2 changes: 1 addition & 1 deletion src/engine/shared/memheap.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class CHeap
CChunk *m_pCurrent;

void Clear();
void NewChunk();
void NewChunk(size_t ChunkSize);
void *AllocateFromChunk(unsigned int Size, unsigned Alignment);

public:
Expand Down

0 comments on commit 9706000

Please sign in to comment.