Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
fix(gameengine): a pool block freed twice crashes at the second free
Olcay Seygan4775fd9c9748
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cppindex c5db367ed..9109222ee 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp@@ -277,13 +277,19 @@ inline HWND getThreadHWND()#endif/* Before a message box in full screen the game's window is hidden, so that the box can be seen. The- window is Windows' ApplicationHWnd; off Windows there is none until C2 creates one. */+ window is Windows' ApplicationHWnd; off Windows there is none until C2 creates one.+ ShowWindow on another thread's window waits until that thread pumps. A crash on the logic thread+ can hold the memory pool locks here, and the main thread stops pumping at its next allocation, so+ the wait never ended and no crash file got written. Off the main thread, ask and carry on. */static void hideFullScreenWindowForMessage( void ){#if defined(_WIN32)if (!DX8Wrapper_IsWindowed) {if (ApplicationHWnd) {- ShowWindow(ApplicationHWnd, SW_HIDE);+ if (getThreadHWND() != NULL)+ ShowWindow(ApplicationHWnd, SW_HIDE);+ else+ ShowWindowAsync(ApplicationHWnd, SW_HIDE);}}#endif@@ -956,7 +962,8 @@ void ReleaseCrash(const char *reason)FileWriteQueue::flushAll();#ifdef DEBUG_LOGGING// From here to _exit the file is this thread's alone, so the writer cannot cut into the report- // with other threads' lines. Never released; what is queued meanwhile goes out before each _exit.+ // with other threads' lines. Released only on the shutdown return below; what is queued meanwhile+ // goes out before each _exit.if (theLogQueue != NULL)theLogQueue->fileLock.lock();#endif@@ -978,6 +985,11 @@ void ReleaseCrash(const char *reason)char curbuf[ _MAX_PATH ];if (TheGlobalData==NULL) {+#ifdef DEBUG_LOGGING+ // the process goes on, and stopping the log writer waits for this lock+ if (theLogQueue != NULL)+ theLogQueue->fileLock.unlock();+#endifreturn; // We are shutting down, and TheGlobalData has been freed. jba. [4/15/2003]}@@ -1136,7 +1148,11 @@ void ReleaseCrashLocalized(const AsciiString& p, const AsciiString& m)#endifif (!TheGameText) {ReleaseCrash(m.str());- // This won't ever return+ // Back here only when TheGlobalData is gone; the lock taken above goes as ReleaseCrash's did.+#ifdef DEBUG_LOGGING+ if (theLogQueue != NULL)+ theLogQueue->fileLock.unlock();+#endifreturn;}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cppindex 2678a62fe..7db68bbaa 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp@@ -94,6 +94,7 @@ DECLARE_PERF_TIMER(MemoryPoolInitFilling)define MPSB_DLINK to add a backlink to MemoryPoolSingleBlock; this makes itfaster to free raw DMA blocks.@todo verify this speedup is enough to be worth the extra space+ A blob block has no use for the backlink, so there it holds the free mark instead (isOnFreeList).*/#define MPSB_DLINK@@ -462,7 +463,7 @@ private:MemoryPoolBlob *m_owningBlob; ///< will be NULL if the single block was allocated via sysAllocate()MemoryPoolSingleBlock *m_nextBlock; ///< if m_owningBlob is nonnull, this points to next free (unallocated) block in the blob; if m_owningBlob is null, this points to the next used (allocated) raw block in the pool.#ifdef MPSB_DLINK- MemoryPoolSingleBlock *m_prevBlock; ///< if m_owningBlob is nonnull, this points to prev free (unallocated) block in the blob; if m_owningBlob is null, this points to the prev used (allocated) raw block in the pool.+ MemoryPoolSingleBlock *m_prevBlock; ///< if m_owningBlob is nonnull, this points to itself while the block is free and is null while allocated; if m_owningBlob is null, this points to the prev used (allocated) raw block in the pool.#endif#ifdef MEMORYPOOL_CHECKPOINTINGBlockCheckpointInfo *m_checkpointInfo; ///< ptr to the checkpointinfo for this block@@ -501,6 +502,8 @@ public:MemoryPoolSingleBlock *getNextFreeBlock();void setNextFreeBlock(MemoryPoolSingleBlock *b);+ Bool isOnFreeList();+ void setOnFreeList(Bool onFreeList);MemoryPoolSingleBlock *getNextRawBlock();void setNextRawBlock(MemoryPoolSingleBlock *b);@@ -656,13 +659,22 @@ inline void MemoryPoolSingleBlock::setNextFreeBlock(MemoryPoolSingleBlock *b){//DEBUG_ASSERTCRASH(m_owningBlob != NULL && b->m_owningBlob != NULL, ("must be called on blob block"));// don't check the 'b' block -- we need to call this before 'b' is fully initialized.- DEBUG_ASSERTCRASH(m_owningBlob != NULL, ("must be called on blob block"));+ DEBUG_ASSERTCRASH(m_owningBlob != NULL, ("must be called on blob block"));this->m_nextBlock = b;-#ifdef MPSB_DLINK- if (b) {- b->m_prevBlock = this;- }-#endif+}++/**+ true while this blob block sits on its blob's free list. A list walk would answer the same at a+ cost this path cannot pay; the mark is one load from a line freeSingleBlock writes anyway.+*/+inline Bool MemoryPoolSingleBlock::isOnFreeList()+{+ return m_prevBlock == this;+}++inline void MemoryPoolSingleBlock::setOnFreeList(Bool onFreeList)+{+ m_prevBlock = onFreeList ? this : NULL;}/**@@ -1260,6 +1272,7 @@ void MemoryPoolBlob::initBlob(MemoryPool *owningPool, Int allocationCount)block->initBlock(m_owningPool->getAllocationSize(), this, owningPool->getOwningFactory());#endifblock->setNextFreeBlock((i > 0) ? next : NULL);+ block->setOnFreeList(TRUE);#ifdef MEMORYPOOL_DEBUGblock->debugMarkBlockAsFree();#endif@@ -1324,6 +1337,10 @@ inline Bool MemoryPoolBlob::holdsAddress(const void *p)pool that really holds the block and the bytes around its header, so the report names thecorruption and shows what was written over it, then crash. The header's own blob pointer is whatis in doubt, so the holder is looked up in pools[], and the dump stays inside that blob.++ Crash report 2655 came through here with nothing overwritten: the freed pointer was 8 bytes past a+ block's user data, so the "header" was the real one read 8 bytes late, its next link taken for the+ blob. A pointer that is not on a block boundary says so instead.*/void MemoryPoolBlob::crashOnCorruptBlockHeader(MemoryPoolSingleBlock *block, MemoryPool *const *pools, Int numPools){@@ -1342,16 +1359,22 @@ void MemoryPoolBlob::crashOnCorruptBlockHeader(MemoryPoolSingleBlock *block, Memconst char *hi = lo + sizeof(MemoryPoolSingleBlock);Int poolSize = -1;const char *poolName = "no pool of this allocator";+ Int pastBoundary = 0;if (holder != NULL){poolSize = holder->m_owningPool->getAllocationSize();poolName = holder->m_owningPool->getPoolName();- const char *blobEnd = holder->m_blockData + (uintptr_t)holder->m_totalBlocksInBlob * MemoryPoolSingleBlock::calcRawBlockSize(poolSize);+ const uintptr_t rawBlockSize = MemoryPoolSingleBlock::calcRawBlockSize(poolSize);+ pastBoundary = (Int)((uintptr_t)(lo - holder->m_blockData) % rawBlockSize);+ const char *blobEnd = holder->m_blockData + (uintptr_t)holder->m_totalBlocksInBlob * rawBlockSize;lo = (lo - holder->m_blockData > 64) ? lo - 64 : holder->m_blockData;hi = (blobEnd - hi > 32) ? hi + 32 : blobEnd;}- DEBUG_LOG(("Memory pool block header at %p overwritten, in '%s' (%d bytes); offsets from the header:\n", block, poolName, poolSize));+ if (pastBoundary != 0)+ DEBUG_LOG(("Memory pool pointer %d bytes past a block boundary at %p, in '%s' (%d bytes); offsets from that pointer's supposed header:\n", pastBoundary, block, poolName, poolSize));+ else+ DEBUG_LOG(("Memory pool block header at %p overwritten, in '%s' (%d bytes); offsets from the header:\n", block, poolName, poolSize));for (const char *row = lo; row < hi; row += 16){char hex[16*3 + 1];@@ -1368,8 +1391,11 @@ void MemoryPoolBlob::crashOnCorruptBlockHeader(MemoryPoolSingleBlock *block, MemDEBUG_LOG(("%+5d %-48s %s\n", (Int)(row - (const char *)block), hex, text));}- char reason[96];- snprintf(reason, sizeof(reason), "memory pool block header overwritten (pool %d bytes)", poolSize);+ char reason[128];+ if (pastBoundary != 0)+ snprintf(reason, sizeof(reason), "memory pool pointer %d bytes past a block boundary (pool %d bytes)", pastBoundary, poolSize);+ else+ snprintf(reason, sizeof(reason), "memory pool block header overwritten (pool %d bytes)", poolSize);RELEASE_CRASH(reason);}@@ -1389,6 +1415,7 @@ MemoryPoolSingleBlock *MemoryPoolBlob::allocateSingleBlock(DECLARE_LITERALSTRINGif (block->getOwningBlob() != this || (next != NULL && !holdsAddress(next)))crashOnCorruptBlockHeader(block, &m_owningPool, 1);m_firstFreeBlock = next;+ block->setOnFreeList(FALSE);++m_usedBlocksInBlob;#ifdef MEMORYPOOL_INTENSE_VERIFY@@ -1418,6 +1445,7 @@ void MemoryPoolBlob::freeSingleBlock(MemoryPoolSingleBlock *block)DEBUG_ASSERTCRASH(block->getOwningBlob() == this, ("block does not belong to this blob"));block->setNextFreeBlock(m_firstFreeBlock);+ block->setOnFreeList(TRUE);m_firstFreeBlock = block;--m_usedBlocksInBlob;@@ -1852,6 +1880,20 @@ void* MemoryPool::allocateBlockImplementation(DECLARE_LITERALSTRING_ARG1)return p;}+//-----------------------------------------------------------------------------+/**+ Crash report 2655: a block freed while it headed the free list linked to itself, and every later+ allocation of that size got that one block, so the crash came minutes later from whichever two+ owners collided. Crash at the second free, whose stack is the one worth having. Its own function,+ so the buffer costs freeBlock nothing on the way past.+*/+static void crashOnDoubleFree(MemoryPool *pool)+{+ char reason[128];+ snprintf(reason, sizeof(reason), "memory pool block freed twice (pool '%s', %d bytes)", pool->getPoolName(), pool->getAllocationSize());+ RELEASE_CRASH(reason);+}+//-----------------------------------------------------------------------------/**free a block allocated by this pool. it's ok to pass null.@@ -1876,6 +1918,14 @@ void MemoryPool::freeBlock(void* pBlockPtr)MemoryPoolBlob::crashOnCorruptBlockHeader(block, &self, 1);}+ // in Release too. ReleaseCrash comes back only at shutdown, when TheGlobalData is gone, and the+ // block is already free, so nothing is left to do for it.+ if (block->isOnFreeList())+ {+ crashOnDoubleFree(this);+ return;+ }+#ifdef MEMORYPOOL_CHECKPOINTINGBlockCheckpointInfo *bi = block->debugGetCheckpointInfo();DEBUG_ASSERTCRASH(bi, ("hmm, no checkpoint info"));diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 21d7cd306..f19380cd4 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -15792,6 +15792,57 @@ TEST(an_allocation_inside_a_job_is_counted)JobSystem::shutdown();}+/* Crash report 2655: a block freed twice linked to itself and every later allocation of that size got+ that one block. ReleaseCrash ends the process unless TheGlobalData is gone, as at shutdown, so with+ it gone the real path runs and comes back, and what the free list hands out next says whether the+ second free got through. Freed twice in a row, the old code gives the same block forever; with one+ free between, a check against the list's head alone hands it out again. */+TEST(a_pool_block_freed_twice_never_goes_back_on_the_free_list)+{+ CHECK( bootOnce() );+ GlobalData *saved = TheWritableGlobalData;+ TheWritableGlobalData = NULL;++ MemoryPool *pool = TheMemoryPoolFactory->createMemoryPool( "testDoubleFree", 64, 8, 8 );++ // healthy order first: the mark must not change which block comes next+ void *a = pool->allocateBlock( "testDoubleFree" );+ void *b = pool->allocateBlock( "testDoubleFree" );+ pool->freeBlock( a );+ pool->freeBlock( b );+ void *again = pool->allocateBlock( "testDoubleFree" );+ CHECK( again == b );+ again = pool->allocateBlock( "testDoubleFree" );+ CHECK( again == a );++ pool->freeBlock( a );+ pool->freeBlock( a );+ void *first = pool->allocateBlock( "testDoubleFree" );+ void *second = pool->allocateBlock( "testDoubleFree" );+ CHECK( first == a );+ CHECK( second != a );+ pool->freeBlock( second );+ pool->freeBlock( first );++ void *c = pool->allocateBlock( "testDoubleFree" );+ pool->freeBlock( c );+ pool->freeBlock( b );+ pool->freeBlock( c );+ void *third = pool->allocateBlock( "testDoubleFree" );+ void *fourth = pool->allocateBlock( "testDoubleFree" );+ void *fifth = pool->allocateBlock( "testDoubleFree" );+ CHECK( third == b );+ CHECK( fourth == c );+ CHECK( fifth != b && fifth != c );+ pool->freeBlock( third );+ pool->freeBlock( fourth );+ pool->freeBlock( fifth );++ CHECK_EQ( 0, pool->getUsedBlockCount() );+ TheMemoryPoolFactory->destroyMemoryPool( pool );+ TheWritableGlobalData = saved;+}+/* A fork made the moment the last one returned finds some workers still on their way back to thewait; a fork made after a pause finds them all asleep. A wake lost in either case hangs this test,and a wake left over from one fork and taken by the next returns before its workers are done,