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): close the string overflows that can actually happen
Olcay Seygan2593675d95d7
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h b/GeneralsMD/Code/GameEngine/Include/Common/StackDump.hindex 3644e524c..3cacccca4 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h@@ -46,7 +46,7 @@ void FillStackAddresses(void**addresses, unsigned int count, unsigned int skip =// Do full stack dump using an address arrayvoid StackDumpFromAddresses(void**addresses, unsigned int count, void (*callback)(const char*));-void GetFunctionDetails(void *pointer, char*name, char*filename, unsigned int* linenumber, unsigned int* address);+void GetFunctionDetails(void *pointer, char*name, size_t nameSize, char*filename, size_t filenameSize, unsigned int* linenumber, unsigned int* address);// Dumps out the exception info and stack trace.void DumpExceptionInfo( unsigned int u, EXCEPTION_POINTERS* e_info );@@ -61,7 +61,7 @@ __inline void FillStackAddresses(void**addresses, unsigned int count, unsigned i// Do full stack dump using an address array__inline void StackDumpFromAddresses(void**addresses, unsigned int count, void (*callback)(const char*)) {}-__inline void GetFunctionDetails(void *pointer, char*name, char*filename, unsigned int* linenumber, unsigned int* address) {}+__inline void GetFunctionDetails(void *pointer, char*name, size_t nameSize, char*filename, size_t filenameSize, unsigned int* linenumber, unsigned int* address) {}// Dumps out the exception info and stack trace.__inline void DumpExceptionInfo( unsigned int u, EXCEPTION_POINTERS* e_info ) {};diff --git a/GeneralsMD/Code/GameEngine/Include/Precompiled/PreRTS.h b/GeneralsMD/Code/GameEngine/Include/Precompiled/PreRTS.hindex 5b9ad9fe8..d6233ec87 100644--- a/GeneralsMD/Code/GameEngine/Include/Precompiled/PreRTS.h+++ b/GeneralsMD/Code/GameEngine/Include/Precompiled/PreRTS.h@@ -135,4 +135,8 @@ class STLSpecialAlloc;#include "Common/Thing.h"#include "Common/UnicodeString.h"+// The bounded string calls are meant to be the default vocabulary, so they are reachable from every+// engine translation unit rather than included one file at a time as each one gets swept.+#include "stringex.h"+#endif /* __PRERTS_H__ */diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cppindex 1cc71e0b4..b9d487e77 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp@@ -32,6 +32,7 @@#define DEFINE_DEATH_NAMES#include "Common/INI.h"+#include "stringex.h"#include "Common/INIException.h"#include "Common/DamageFX.h"@@ -397,7 +398,7 @@ void INI::load( AsciiString filename, INILoadType loadType, Xfer *pXfer )thing it read is usually the answer. Without it a report of this reads "one ofthese nine fields", and the only way on is to guess. */char buff[1024];- sprintf(buff, "Error parsing INI file '%s' (Line: '%s', reached line %d: '%s')\n",+ snprintf(buff, ARRAY_SIZE(buff), "Error parsing INI file '%s' (Line: '%s', reached line %d: '%s')\n",m_filename.str(), currentLine.str(), m_lineNum, m_buffer);throw INIException(buff);@@ -759,8 +760,8 @@ AsciiString INI::getNextQuotedAsciiString()if (strlen(token) > 1 && token[1] != '\t'){- strcat(buff, " ");- strcat(buff, token);+ strlcat(buff, " ", ARRAY_SIZE(buff));+ strlcat(buff, token, ARRAY_SIZE(buff));}else{ Int buflen=strlen(buff);@@ -794,16 +795,16 @@ AsciiString INI::getNextAsciiString()buff[0] = 0;if (strlen(token) > 1){- strcpy(buff, &token[1]);- }+ strlcpy(buff, &token[1], ARRAY_SIZE(buff));+ }token = getNextTokenOrNull(getSepsQuote());if (token) {if (strlen(token) > 1 && token[1] != '\t'){- strcat(buff, " ");+ strlcat(buff, " ", ARRAY_SIZE(buff));}- strcat(buff, token);+ strlcat(buff, token, ARRAY_SIZE(buff));result.set(buff);} else {Int len = strlen(buff);@@ -1536,7 +1537,7 @@ void INI::initFromINIMulti( void *what, const MultiIniFieldParse& parseTableListchar buff[1024];- sprintf(buff, "[LINE: %d - FILE: '%s'] Error reading field '%s'\n", INI::getLineNum(), INI::getFilename().str(), field);+ snprintf(buff, ARRAY_SIZE(buff), "[LINE: %d - FILE: '%s'] Error reading field '%s'\n", INI::getLineNum(), INI::getFilename().str(), field);throw INIException(buff);}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp b/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cppindex ba2ab397c..20f464182 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp@@ -485,8 +485,8 @@ static UnsignedInt s_framesAccumulated = 0;strcpy(s_buf, fname);char tmp[256];- strcpy(tmp, s_buf);- strcat(tmp, ".csv");+ strlcpy(tmp, s_buf, ARRAY_SIZE(tmp));+ strlcat(tmp, ".csv", ARRAY_SIZE(tmp));s_perfStatsFile = fopen(tmp, "w");s_perfDumpOptions = options;diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cppindex 799c9dcc0..4feced6b7 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp@@ -53,6 +53,7 @@#endif#include "Common/Debug.h"#include "Common/EarlyCommandLine.h"+#include "stringex.h"#include "Common/SystemInfo.h"#include "Common/UnicodeString.h"#include "GameClient/GameText.h"@@ -117,7 +118,7 @@ char* TheCurrentIgnoreCrashPtr = NULL;// ----------------------------------------------------------------------------static const char *getCurrentTimeString(void);static const char *getCurrentTickString(void);-static const char *prepBuffer(const char* format, char *buffer);+static const char *prepBuffer(const char* format, char *buffer, size_t bufferSize);#ifdef DEBUG_LOGGINGstatic void doLogOutput(const char *buffer);#endif@@ -200,7 +201,7 @@ static const char *getCurrentTimeString(void)static const char *getCurrentTickString(void){static char TheTickString[32];- sprintf(TheTickString, "(T=%08lx)",::GetTickCount());+ snprintf(TheTickString, ARRAY_SIZE(TheTickString), "(T=%08lx)",::GetTickCount());return TheTickString;}@@ -212,14 +213,14 @@ static const char *getCurrentTickString(void)Empty the buffer passed in, then optionally prepend the current TickCountvalue in string form, depending on the setting of theDebugFlags.*/-static const char *prepBuffer(const char* format, char *buffer)+static const char *prepBuffer(const char* format, char *buffer, size_t bufferSize){buffer[0] = 0;#ifdef ALLOW_DEBUG_UTILSif (theDebugFlags & DEBUG_FLAG_PREPEND_TIME){- strcpy(buffer, getCurrentTickString());- strcat(buffer, " ");+ strlcpy(buffer, getCurrentTickString(), bufferSize);+ strlcat(buffer, " ", bufferSize);}#endifreturn format;@@ -383,14 +384,14 @@ void DebugInit(int flags)if (!findEarlyCommandLineValue( L"-logPrefix", logPrefix, sizeof( logPrefix ) ))logPrefix[0] = 0;- strcpy(prevbuf, dirbuf);- strcat(prevbuf, gAppPrefix);- strcat(prevbuf, logPrefix);- strcat(prevbuf, DEBUG_FILE_NAME_PREV);- strcpy(curbuf, dirbuf);- strcat(curbuf, gAppPrefix);- strcat(curbuf, logPrefix);- strcat(curbuf, DEBUG_FILE_NAME);+ strlcpy(prevbuf, dirbuf, ARRAY_SIZE(prevbuf));+ strlcat(prevbuf, gAppPrefix, ARRAY_SIZE(prevbuf));+ strlcat(prevbuf, logPrefix, ARRAY_SIZE(prevbuf));+ strlcat(prevbuf, DEBUG_FILE_NAME_PREV, ARRAY_SIZE(prevbuf));+ strlcpy(curbuf, dirbuf, ARRAY_SIZE(curbuf));+ strlcat(curbuf, gAppPrefix, ARRAY_SIZE(curbuf));+ strlcat(curbuf, logPrefix, ARRAY_SIZE(curbuf));+ strlcat(curbuf, DEBUG_FILE_NAME, ARRAY_SIZE(curbuf));remove(prevbuf);// A failed rotate is not fatal - the log still opens - but it means the ".prev" file holds@@ -434,7 +435,7 @@ void DebugLog(const char *format, ...)if (theDebugFlags == 0)MessageBoxWrapper("DebugLog - Debug not inited properly", "", MB_OK|MB_TASKMODAL);- format = prepBuffer(format, theBuffer);+ format = prepBuffer(format, theBuffer, ARRAY_SIZE(theBuffer));va_list arg;va_start(arg, format);@@ -476,15 +477,19 @@ void DebugCrash(const char *format, ...)MessageBoxWrapper("DebugCrash - Debug not inited properly", "", MB_OK|MB_TASKMODAL);}- format = prepBuffer(format, theCrashBuffer);- strcat(theCrashBuffer, "ASSERTION FAILURE: ");+ format = prepBuffer(format, theCrashBuffer, ARRAY_SIZE(theCrashBuffer));+ strlcat(theCrashBuffer, "ASSERTION FAILURE: ", ARRAY_SIZE(theCrashBuffer));+ // The overflow test below used to sit after a vsprintf with no bound, so by the time it could+ // measure the length the stack was already written past. vsnprintf stops at the wall instead.+ const size_t used = strlen(theCrashBuffer);va_list arg;va_start(arg, format);- vsprintf(theCrashBuffer + strlen(theCrashBuffer), format, arg);+ const int wanted = _vsnprintf(theCrashBuffer + used, ARRAY_SIZE(theCrashBuffer) - used, format, arg);va_end(arg);+ theCrashBuffer[ ARRAY_SIZE(theCrashBuffer) - 1 ] = 0;- if (strlen(theCrashBuffer) >= sizeof(theCrashBuffer))+ if (wanted < 0 || (size_t)wanted >= ARRAY_SIZE(theCrashBuffer) - used){if (!DX8Wrapper_IsWindowed) {if (ApplicationHWnd) {@@ -509,7 +514,7 @@ void DebugCrash(const char *format, ...)}#endif- strcat(theCrashBuffer, "\n\nAbort->exception; Retry->debugger; Ignore->continue\n");+ strlcat(theCrashBuffer, "\n\nAbort->exception; Retry->debugger; Ignore->continue\n", ARRAY_SIZE(theCrashBuffer));int result = doCrashBox(theCrashBuffer, true);@@ -715,10 +720,10 @@ void ReleaseCrash(const char *reason)return; // We are shutting down, and TheGlobalData has been freed. jba. [4/15/2003]}- strcpy(prevbuf, TheGlobalData->getPath_UserData().str());- strcat(prevbuf, RELEASECRASH_FILE_NAME_PREV);- strcpy(curbuf, TheGlobalData->getPath_UserData().str());- strcat(curbuf, RELEASECRASH_FILE_NAME);+ strlcpy(prevbuf, TheGlobalData->getPath_UserData().str(), ARRAY_SIZE(prevbuf));+ strlcat(prevbuf, RELEASECRASH_FILE_NAME_PREV, ARRAY_SIZE(prevbuf));+ strlcpy(curbuf, TheGlobalData->getPath_UserData().str(), ARRAY_SIZE(curbuf));+ strlcat(curbuf, RELEASECRASH_FILE_NAME, ARRAY_SIZE(curbuf));remove(prevbuf);FILE *existingCrashLog = fopen(curbuf, "r");@@ -824,10 +829,10 @@ void ReleaseCrashLocalized(const AsciiString& p, const AsciiString& m)char prevbuf[ _MAX_PATH ];char curbuf[ _MAX_PATH ];- strcpy(prevbuf, TheGlobalData->getPath_UserData().str());- strcat(prevbuf, RELEASECRASH_FILE_NAME_PREV);- strcpy(curbuf, TheGlobalData->getPath_UserData().str());- strcat(curbuf, RELEASECRASH_FILE_NAME);+ strlcpy(prevbuf, TheGlobalData->getPath_UserData().str(), ARRAY_SIZE(prevbuf));+ strlcat(prevbuf, RELEASECRASH_FILE_NAME_PREV, ARRAY_SIZE(prevbuf));+ strlcpy(curbuf, TheGlobalData->getPath_UserData().str(), ARRAY_SIZE(curbuf));+ strlcat(curbuf, RELEASECRASH_FILE_NAME, ARRAY_SIZE(curbuf));remove(prevbuf);FILE *existingCrashLog = fopen(curbuf, "r");diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cppindex 7b6ba7122..a09023a5d 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp@@ -2994,8 +2994,8 @@ void MemoryPoolFactory::memoryPoolUsageReport( const char* filename, FILE *appenif( !appendToFileInstead ){char tmp[256];- strcpy(tmp,filename);- strcat(tmp,".csv");+ strlcpy(tmp, filename, ARRAY_SIZE(tmp));+ strlcat(tmp, ".csv", ARRAY_SIZE(tmp));perfStatsFile = fopen(tmp, "w");}else@@ -3218,11 +3218,11 @@ void MemoryPoolFactory::debugMemoryReport(Int flags, Int startCheckpoint, Int enDEBUG_LOG(("Begin Block Report for %s\n", nm));DEBUG_LOG(("------------------------------------------\n"));char buf[256] = "";- if (flags & _REPORT_CP_ALLOCATED_BEFORE) strcat(buf, "AllocBefore ");- if (flags & _REPORT_CP_ALLOCATED_BETWEEN) strcat(buf, "AllocBetween ");- if (flags & _REPORT_CP_FREED_BEFORE) strcat(buf, "FreedBefore ");- if (flags & _REPORT_CP_FREED_BETWEEN) strcat(buf, "FreedBetween ");- if (flags & _REPORT_CP_FREED_NEVER) strcat(buf, "StillExisting ");+ if (flags & _REPORT_CP_ALLOCATED_BEFORE) strlcat(buf, "AllocBefore ", ARRAY_SIZE(buf));+ if (flags & _REPORT_CP_ALLOCATED_BETWEEN) strlcat(buf, "AllocBetween ", ARRAY_SIZE(buf));+ if (flags & _REPORT_CP_FREED_BEFORE) strlcat(buf, "FreedBefore ", ARRAY_SIZE(buf));+ if (flags & _REPORT_CP_FREED_BETWEEN) strlcat(buf, "FreedBetween ", ARRAY_SIZE(buf));+ if (flags & _REPORT_CP_FREED_NEVER) strlcat(buf, "StillExisting ", ARRAY_SIZE(buf));DEBUG_LOG(("Options: Between checkpoints %d and %d, report on (%s)\n",startCheckpoint,endCheckpoint,buf));DEBUG_LOG(("------------------------------------------\n"));diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cppindex 27f04f347..acc720cd4 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cpp@@ -772,7 +772,7 @@ void userMemoryManagerInitPools()}--pEnd;}- strcat(buf, "\\Data\\INI\\MemoryPools.ini");+ strlcat(buf, "\\Data\\INI\\MemoryPools.ini", ARRAY_SIZE(buf));FILE* fp = fopen(buf, "r");if (fp)diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cppindex d43b29c37..ddbd6d3b9 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp@@ -40,7 +40,7 @@BOOL InitSymbolInfo(void);void UninitSymbolInfo(void);void MakeStackTrace(DWORD myeip,DWORD myesp,DWORD myebp, int skipFrames, void (*callback)(const char*));-void GetFunctionDetails(void *pointer, char*name, char*filename, unsigned int* linenumber, unsigned int* address);+void GetFunctionDetails(void *pointer, char*name, size_t nameSize, char*filename, size_t filenameSize, unsigned int* linenumber, unsigned int* address);void WriteStackLine(void*address, void (*callback)(const char*));//*****************************************************************************@@ -236,16 +236,19 @@ stack_frame.AddrFrame.Offset = myebp;//*****************************************************************************//*****************************************************************************-void GetFunctionDetails(void *pointer, char*name, char*filename, unsigned int* linenumber, unsigned int* address)+// The symbol name can be up to 512 characters and the source path up to MAX_PATH, and both used to+// be written with unbounded calls into buffers of exactly those sizes - a long symbol plus "();"+// walked off the end while the process was already reporting a crash.+void GetFunctionDetails(void *pointer, char*name, size_t nameSize, char*filename, size_t filenameSize, unsigned int* linenumber, unsigned int* address){InitSymbolInfo();if (name){- strcpy(name, "<Unknown>");+ strlcpy(name, "<Unknown>", nameSize);}if (filename){- strcpy(filename, "<Unknown>");+ strlcpy(filename, "<Unknown>", filenameSize);}if (linenumber){@@ -271,8 +274,8 @@ void GetFunctionDetails(void *pointer, char*name, char*filename, unsigned int* l{if (name){- strcpy(name, psymbol->Name);- strcat(name, "();");+ strlcpy(name, psymbol->Name, nameSize);+ strlcat(name, "();", nameSize);}// Get line now@@ -289,7 +292,7 @@ void GetFunctionDetails(void *pointer, char*name, char*filename, unsigned int* l{if (filename){- strcpy(filename, line.FileName);+ strlcpy(filename, line.FileName, filenameSize);}if (linenumber){@@ -320,7 +323,7 @@ void GetFunctionDetails(void *pointer, char*name, char*filename, unsigned int* l{const char *leaf = strrchr( modulePath, '\\' );leaf = leaf ? leaf + 1 : modulePath;- sprintf( name, "%s+0x%X;", leaf, (unsigned int)((char *)pointer - (char *)module) );+ snprintf( name, nameSize, "%s+0x%X;", leaf, (unsigned int)((char *)pointer - (char *)module) );}}}@@ -370,14 +373,18 @@ AsciiString g_LastErrorDump;//*****************************************************************************void WriteStackLine(void*address, void (*callback)(const char*)){- static char line[MAX_PATH];+ // Big enough for the longest thing that can be formatted into it: a path, a symbol, and the+ // punctuation between them. It used to be MAX_PATH and could not hold its own contents.+ static char line[MAX_PATH + 512 + 64];static char function_name[512];static char filename[MAX_PATH];unsigned int linenumber;unsigned int addr;- GetFunctionDetails(address, function_name, filename, &linenumber, &addr);- sprintf(line, " %s(%d) : %s 0x%08p", filename, linenumber, function_name, address);+ GetFunctionDetails(address, function_name, ARRAY_SIZE(function_name), filename, ARRAY_SIZE(filename), &linenumber, &addr);+ // A path of MAX_PATH plus a symbol of 512 does not fit in MAX_PATH, so this line always could+ // overrun; it just needed a deep enough source tree and a long enough C++ name to do it.+ snprintf(line, ARRAY_SIZE(line), " %s(%d) : %s 0x%08p", filename, linenumber, function_name, address);if (g_LastErrorDump.isNotEmpty()) {g_LastErrorDump.concat(line);g_LastErrorDump.concat("\n");@@ -545,13 +552,13 @@ void DumpExceptionInfo( unsigned int u, EXCEPTION_POINTERS* e_info )}else{- sprintf (bytestr, "%02X ", *eip_ptr);- strcat (scrap, bytestr);+ snprintf (bytestr, ARRAY_SIZE(bytestr), "%02X ", *eip_ptr);+ strlcat (scrap, bytestr, ARRAY_SIZE(scrap));}eip_ptr++;}- strcat (scrap, "\n");+ strlcat (scrap, "\n", ARRAY_SIZE(scrap));DOUBLE_DEBUG ( ( (scrap)));/*diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBridgeBuffer.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBridgeBuffer.cppindex 30cd03a40..5316840f7 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBridgeBuffer.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBridgeBuffer.cpp@@ -49,6 +49,7 @@#include <stdio.h>#include <string.h>+#include "stringex.h"#include "W3DDevice/GameClient/W3DAssetManager.h"#include <texture.h>#include "common/GlobalData.h"@@ -241,12 +242,13 @@ Bool W3DBridge::load(enum BodyDamageType curDamageState)char section[_MAX_PATH];char right[_MAX_PATH];- strcpy(left, modelName);- strcat(left, ".BRIDGE_LEFT");- strcpy(section, modelName);- strcat(section, ".BRIDGE_SPAN");- strcpy(right, modelName);- strcat(right, ".BRIDGE_RIGHT");+ // modelName comes out of the map, so its length is not ours to assume.+ strlcpy(left, modelName, ARRAY_SIZE(left));+ strlcat(left, ".BRIDGE_LEFT", ARRAY_SIZE(left));+ strlcpy(section, modelName, ARRAY_SIZE(section));+ strlcat(section, ".BRIDGE_SPAN", ARRAY_SIZE(section));+ strlcpy(right, modelName, ARRAY_SIZE(right));+ strlcat(right, ".BRIDGE_RIGHT", ARRAY_SIZE(right));m_bridgeTexture = pMgr->Get_Texture(textureFile, MIP_LEVELS_3);m_leftMtx.Make_Identity();diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cppindex cb4481e6b..e0b0e891e 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp@@ -38,6 +38,7 @@ static void drawFramerateBar(void);#include <windows.h>#include <io.h>#include <time.h>+#include "stringex.h"// USER INCLUDES //////////////////////////////////////////////////////////////#include "Common/ThingFactory.h"@@ -3455,12 +3456,12 @@ static void saveScreenShot(void)Bool done = false;while (!done) {#ifdef CAPTURE_TO_TARGA- sprintf( leafname, "%s%.3d.tga", "sshot", frame_number++);+ snprintf( leafname, ARRAY_SIZE(leafname), "%s%.3d.tga", "sshot", frame_number++);#else- sprintf( leafname, "%s%.3d.bmp", "sshot", frame_number++);+ snprintf( leafname, ARRAY_SIZE(leafname), "%s%.3d.bmp", "sshot", frame_number++);#endif- strcpy(pathname, TheGlobalData->getPath_UserData().str());- strcat(pathname, leafname);+ strlcpy(pathname, TheGlobalData->getPath_UserData().str(), ARRAY_SIZE(pathname));+ strlcat(pathname, leafname, ARRAY_SIZE(pathname));if (_access( pathname, 0 ) == -1)done = true;}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DFileSystem.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DFileSystem.cppindex beda6b3e6..aa01b17da 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DFileSystem.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DFileSystem.cpp@@ -42,6 +42,7 @@#include "Common/Debug.h"#include "Common/File.h"+#include "stringex.h"#include "Common/FileSystem.h"#include "Common/GlobalData.h"#include "Common/MapObject.h"@@ -188,8 +189,8 @@ char const * GameFileClass::Set_Name( char const *filename )if( fileType == FILE_TYPE_W3D ){static const char *localizedPathFormat = "Data/%s/Art/W3D/";- sprintf(m_filePath,localizedPathFormat, GetRegistryLanguage().str());- strcat( m_filePath, filename );+ snprintf(m_filePath, ARRAY_SIZE(m_filePath), localizedPathFormat, GetRegistryLanguage().str());+ strlcat( m_filePath, filename, ARRAY_SIZE(m_filePath) );} // end if@@ -197,8 +198,8 @@ char const * GameFileClass::Set_Name( char const *filename )if( isImageFileType(fileType) ){static const char *localizedPathFormat = "Data/%s/Art/Textures/";- sprintf(m_filePath,localizedPathFormat, GetRegistryLanguage().str());- strcat( m_filePath, filename );+ snprintf(m_filePath, ARRAY_SIZE(m_filePath), localizedPathFormat, GetRegistryLanguage().str());+ strlcat( m_filePath, filename, ARRAY_SIZE(m_filePath) );} // end else if@@ -214,19 +215,19 @@ char const * GameFileClass::Set_Name( char const *filename )if( fileType == FILE_TYPE_W3D ){- strcpy( m_filePath, W3D_DIR_PATH );- strcat( m_filePath, filename );-+ strlcpy( m_filePath, W3D_DIR_PATH, ARRAY_SIZE(m_filePath) );+ strlcat( m_filePath, filename, ARRAY_SIZE(m_filePath) );+} // end ifelse if( isImageFileType(fileType) ){-- strcpy( m_filePath, TGA_DIR_PATH );- strcat( m_filePath, filename );-++ strlcpy( m_filePath, TGA_DIR_PATH, ARRAY_SIZE(m_filePath) );+ strlcat( m_filePath, filename, ARRAY_SIZE(m_filePath) );+} // end else ifelse- strcpy( m_filePath, filename );+ strlcpy( m_filePath, filename, ARRAY_SIZE(m_filePath) );// see if the file existsm_fileExists = TheFileSystem->doesFileExist( m_filePath );@@ -242,15 +243,15 @@ char const * GameFileClass::Set_Name( char const *filename )if( fileType == FILE_TYPE_W3D ){- strcpy( m_filePath, LEGACY_W3D_DIR_PATH );- strcat( m_filePath, filename );+ strlcpy( m_filePath, LEGACY_W3D_DIR_PATH, ARRAY_SIZE(m_filePath) );+ strlcat( m_filePath, filename, ARRAY_SIZE(m_filePath) );} // end ifelse if( isImageFileType(fileType) ){- strcpy( m_filePath, LEGACY_TGA_DIR_PATH );- strcat( m_filePath, filename );+ strlcpy( m_filePath, LEGACY_TGA_DIR_PATH, ARRAY_SIZE(m_filePath) );+ strlcat( m_filePath, filename, ARRAY_SIZE(m_filePath) );} // end else ifdiff --git a/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h b/GeneralsMD/Code/Libraries/Include/Lib/BaseType.hindex 1df598fec..10ed6be46 100644--- a/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h+++ b/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h@@ -301,6 +301,16 @@ __forceinline float fast_float_ceil(float f)#define FAST_REAL_CEIL(x) fast_float_ceil(x)#define FAST_REAL_FLOOR(x) fast_float_floor(x)+//+// Element count of a real array. Four files each defined their own copy of this, and the bounded+// string calls need it at every site, so it lives here now. It is deliberately the array form+// only: hand it a pointer and the division is silently wrong, so never use it on a parameter that+// has decayed.+//+#ifndef ARRAY_SIZE+#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))+#endif+//--------------------------------------------------------------------// Derived type definitions//--------------------------------------------------------------------diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hcanim.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hcanim.cppindex dc0eecf81..4edd0d7f3 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hcanim.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hcanim.cpp@@ -50,6 +50,7 @@#include "hcanim.h"+#include "stringex.h"#include "assetmgr.h"#include "htree.h"#include "motchan.h"@@ -257,9 +258,11 @@ int HCompressedAnimClass::Load_W3D(ChunkLoadClass & cload)cload.Close_Chunk();- strcpy(Name,aheader.HierarchyName);- strcat(Name,".");- strcat(Name,aheader.Name);+ // The two halves come straight out of the .w3d header, where nothing guarantees a terminator+ // inside the fixed field, so the joined name could run past the end of this one.+ strlcpy(Name,aheader.HierarchyName,ARRAY_SIZE(Name));+ strlcat(Name,".",ARRAY_SIZE(Name));+ strlcat(Name,aheader.Name,ARRAY_SIZE(Name));// TSS chasing crash bug 05/26/99WWASSERT(HierarchyName != NULL);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.cppindex 1da747695..49a16beb3 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.cpp@@ -37,6 +37,7 @@#include "hmdldef.h"+#include "stringex.h"#include <assert.h>#include <string.h>#include "w3d_file.h"@@ -237,9 +238,9 @@ bool HModelDefClass::read_connection(ChunkLoadClass & cload,HmdlNodeDefStruct *return false;}- strcpy(node->RenderObjName,ModelName);- strcat(node->RenderObjName,".");- strcat(node->RenderObjName,con.RenderObjName);+ strlcpy(node->RenderObjName,ModelName,ARRAY_SIZE(node->RenderObjName));+ strlcat(node->RenderObjName,".",ARRAY_SIZE(node->RenderObjName));+ strlcat(node->RenderObjName,con.RenderObjName,ARRAY_SIZE(node->RenderObjName));if (pre30) {if (con.PivotIdx == 65535) {diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cppindex ffce69d4e..78213e884 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp@@ -37,6 +37,7 @@* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */#include "hmorphanim.h"+#include "stringex.h"#include "w3d_file.h"#include "chunkio.h"#include "assetmgr.h"@@ -559,9 +560,9 @@ int HMorphAnimClass::Load_W3D(ChunkLoadClass & cload)strncpy(AnimName,header.Name,sizeof(AnimName));strncpy(HierarchyName,header.HierarchyName,sizeof(HierarchyName));- strcpy(Name,HierarchyName);- strcat(Name,".");- strcat(Name,AnimName);+ strlcpy(Name,HierarchyName,ARRAY_SIZE(Name));+ strlcat(Name,".",ARRAY_SIZE(Name));+ strlcat(Name,AnimName,ARRAY_SIZE(Name));HTreeClass * base_pose = WW3DAssetManager::Get_Instance()->Get_HTree(HierarchyName);if (base_pose == NULL) {diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hrawanim.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hrawanim.cppindex 281a9f4cb..191bac588 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hrawanim.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hrawanim.cpp@@ -51,6 +51,7 @@* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */#include "hrawanim.h"+#include "stringex.h"#include "motchan.h"#include "chunkio.h"#include "assetmgr.h"@@ -229,9 +230,9 @@ int HRawAnimClass::Load_W3D(ChunkLoadClass & cload)pre30 = true;}- strcpy(Name,aheader.HierarchyName);- strcat(Name,".");- strcat(Name,aheader.Name);+ strlcpy(Name,aheader.HierarchyName,ARRAY_SIZE(Name));+ strlcat(Name,".",ARRAY_SIZE(Name));+ strlcat(Name,aheader.Name,ARRAY_SIZE(Name));// TSS chasing crash bug 05/26/99WWASSERT(HierarchyName != NULL);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshgeometry.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshgeometry.cppindex 834e9ceac..64312a025 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshgeometry.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshgeometry.cpp@@ -86,6 +86,7 @@#include "meshgeometry.h"+#include "stringex.h"#include "aabtree.h"#include "chunkio.h"#include "aabox.h"@@ -1614,10 +1615,10 @@ WW3DErrorType MeshGeometryClass::Load_W3D(ChunkLoadClass & cload)memset(tmpname,0,namelen);if (strlen(header.ContainerName) > 0) {- strcpy(tmpname,header.ContainerName);- strcat(tmpname,".");+ strlcpy(tmpname,header.ContainerName,namelen);+ strlcat(tmpname,".",namelen);}- strcat(tmpname,header.MeshName);+ strlcat(tmpname,header.MeshName,namelen);Set_Name(tmpname);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdlio.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdlio.cppindex 305858e42..6613fc401 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdlio.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdlio.cpp@@ -76,6 +76,7 @@* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */#include "meshmdl.h"+#include "stringex.h"#include "aabtree.h"#include "matinfo.h"#include "vertmaterial.h"@@ -274,10 +275,10 @@ WW3DErrorType MeshModelClass::Load_W3D(ChunkLoadClass & cload)memset(tmpname,0,namelen);if (strlen(context->Header.ContainerName) > 0) {- strcpy(tmpname,context->Header.ContainerName);- strcat(tmpname,".");+ strlcpy(tmpname,context->Header.ContainerName,namelen);+ strlcat(tmpname,".",namelen);}- strcat(tmpname,context->Header.MeshName);+ strlcat(tmpname,context->Header.MeshName,namelen);Set_Name(tmpname);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_dep.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_dep.cppindex 49279e03c..564d394e1 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_dep.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_dep.cpp@@ -60,6 +60,7 @@ public:#include "w3d_dep.h"+#include "stringex.h"#include "w3d_file.h"#include <assert.h>#include <chunkio.h>@@ -565,11 +566,11 @@ static const char * Make_W3D_Filename (const char *w3d_name)buffer[0] = 0;return buffer;}- strcpy(buffer, w3d_name);+ strlcpy(buffer, w3d_name, ARRAY_SIZE(buffer));char *dot = strchr(buffer, '.');if (dot)*dot = 0;strlwr(buffer);- strcat(buffer, ".w3d");+ strlcat(buffer, ".w3d", ARRAY_SIZE(buffer));return buffer;}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/Except.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/Except.cppindex 8ed9269dd..76081ccac 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/Except.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/Except.cpp@@ -52,6 +52,7 @@#include "always.h"#include <windows.h>#include "assert.h"+#include "stringex.h"#include "cpudetect.h"#include "except.h"//#include "debug.h"@@ -231,9 +232,8 @@ char const * Last_Error_Text(void)*=============================================================================================*/static void Add_Txt (char const *txt){- if (strlen(ExceptionText) + strlen(txt) < 65535) {- strcat(ExceptionText, txt);- }+ // The guard was right, but it carried the buffer's size as a literal beside the buffer.+ strlcat(ExceptionText, txt, ARRAY_SIZE(ExceptionText));#if (0)/*** Log to debug output too.@@ -651,22 +651,25 @@ void Dump_Exception_Info(EXCEPTION_POINTERS *e_info)** Dump the bytes at EIP. This will make it easier to match the crash address with later versions of the game.*/DebugString("EIP bytes dump...\n");- sprintf(scrap, "\r\nBytes at CS:EIP (%08X) : ", context->Eip);+ // This whole block writes into a 256 byte buffer with no bound, in the handler that is trying to+ // report a crash. Thirty-two bytes at three characters each plus the header is close enough to+ // 256 that a symbol name on the stack pass below pushed it over.+ snprintf(scrap, ARRAY_SIZE(scrap), "\r\nBytes at CS:EIP (%08X) : ", context->Eip);unsigned char *eip_ptr = (unsigned char *) (context->Eip);char bytestr[32];for (int c = 0 ; c < 32 ; c++) {if (IsBadReadPtr(eip_ptr, 1)) {- strcat(scrap, "?? ");+ strlcat(scrap, "?? ", ARRAY_SIZE(scrap));} else {- sprintf(bytestr, "%02X ", *eip_ptr);- strcat(scrap, bytestr);+ snprintf(bytestr, ARRAY_SIZE(bytestr), "%02X ", *eip_ptr);+ strlcat(scrap, bytestr, ARRAY_SIZE(scrap));}eip_ptr++;}- strcat(scrap, "\r\n\r\n");+ strlcat(scrap, "\r\n\r\n", ARRAY_SIZE(scrap));Add_Txt(scrap);/*@@ -681,17 +684,17 @@ void Dump_Exception_Info(EXCEPTION_POINTERS *e_info)/*** The stack contents cannot be read so just print up question marks.*/- sprintf(scrap, "%08X: ", stackptr);- strcat(scrap, "????????\r\n");+ snprintf(scrap, ARRAY_SIZE(scrap), "%08X: ", stackptr);+ strlcat(scrap, "????????\r\n", ARRAY_SIZE(scrap));} else {/*** If this stack address is in our memory space then try to match it with a code symbol.*/if (IsBadCodePtr((FARPROC)*stackptr)) {- sprintf(scrap, "%08X: %08X ", stackptr, *stackptr);- strcat(scrap, "DATA_PTR\r\n");+ snprintf(scrap, ARRAY_SIZE(scrap), "%08X: %08X ", stackptr, *stackptr);+ strlcat(scrap, "DATA_PTR\r\n", ARRAY_SIZE(scrap));} else {- sprintf(scrap, "%08X: %08X", stackptr, *stackptr);+ snprintf(scrap, ARRAY_SIZE(scrap), "%08X: %08X", stackptr, *stackptr);if (symbols_available) {symptr->SizeOfStruct = sizeof(symbol);@@ -701,13 +704,13 @@ void Dump_Exception_Info(EXCEPTION_POINTERS *e_info)if (_SymGetSymFromAddr != NULL && _SymGetSymFromAddr (GetCurrentProcess(), *stackptr, &displacement, symptr)) {char symbuf[256];- sprintf(symbuf, " - %s + %08X", symptr->Name, displacement);- strcat(scrap, symbuf);+ snprintf(symbuf, ARRAY_SIZE(symbuf), " - %s + %08X", symptr->Name, displacement);+ strlcat(scrap, symbuf, ARRAY_SIZE(scrap));}} else {- strcat (scrap, " *");+ strlcat (scrap, " *", ARRAY_SIZE(scrap));}- strcat (scrap, "\r\n");+ strlcat (scrap, "\r\n", ARRAY_SIZE(scrap));}}Add_Txt(scrap);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/registry.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/registry.cppindex 5619b26f1..8f28a19e1 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/registry.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/registry.cpp@@ -34,6 +34,7 @@* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */#include "registry.h"+#include "stringex.h"#include "rawfile.h"#include "ini.h"#include "inisup.h"@@ -385,8 +386,9 @@ void RegistryClass::Save_Registry_Values(HKEY key, char *path, INIClass *ini)** Handle dword values.*/case REG_DWORD:- strcpy(save_name, "DWORD_");- strcat(save_name, value_name);+ // value_name comes back from the registry, so its length is whatever is in there.+ strlcpy(save_name, "DWORD_", ARRAY_SIZE(save_name));+ strlcat(save_name, value_name, ARRAY_SIZE(save_name));ini->Put_Int(path, save_name, *((unsigned long*)data));break;@@ -394,8 +396,8 @@ void RegistryClass::Save_Registry_Values(HKEY key, char *path, INIClass *ini)** Handle string values.*/case REG_SZ:- strcpy(save_name, "STRING_");- strcat(save_name, value_name);+ strlcpy(save_name, "STRING_", ARRAY_SIZE(save_name));+ strlcat(save_name, value_name, ARRAY_SIZE(save_name));ini->Put_String(path, save_name, (char*)data);break;@@ -403,8 +405,8 @@ void RegistryClass::Save_Registry_Values(HKEY key, char *path, INIClass *ini)** Handle binary values.*/case REG_BINARY:- strcpy(save_name, "BIN_");- strcat(save_name, value_name);+ strlcpy(save_name, "BIN_", ARRAY_SIZE(save_name));+ strlcat(save_name, value_name, ARRAY_SIZE(save_name));ini->Put_UUBlock(path, save_name, (char*)data, data_size);break;@@ -470,9 +472,9 @@ void RegistryClass::Save_Registry_Tree(char *path, INIClass *ini)** See if there are sub keys.*/char new_key_path[512];- strcpy(new_key_path, path);- strcat(new_key_path, "\\");- strcat(new_key_path, name);+ strlcpy(new_key_path, path, ARRAY_SIZE(new_key_path));+ strlcat(new_key_path, "\\", ARRAY_SIZE(new_key_path));+ strlcat(new_key_path, name, ARRAY_SIZE(new_key_path));unsigned long num_subs = 0;unsigned long num_values = 0;@@ -564,10 +566,10 @@ void RegistryClass::Load_Registry(const char *filename, char *old_path, char *ne** Build the new path to use in the registry.*/char *section_name = section->Section;- strcpy(path, new_path);+ strlcpy(path, new_path, ARRAY_SIZE(path));char *cut = strstr(section_name, old_path);if (cut) {- strcat(path, cut + old_path_len);+ strlcat(path, cut + old_path_len, ARRAY_SIZE(path));}/*@@ -693,9 +695,9 @@ void RegistryClass::Delete_Registry_Tree(char *path)** See if there are sub keys.*/char new_key_path[512];- strcpy(new_key_path, path);- strcat(new_key_path, "\\");- strcat(new_key_path, name);+ strlcpy(new_key_path, path, ARRAY_SIZE(new_key_path));+ strlcat(new_key_path, "\\", ARRAY_SIZE(new_key_path));+ strlcat(new_key_path, name, ARRAY_SIZE(new_key_path));unsigned long num_subs = 0;unsigned long num_values = 0;diff --git a/GeneralsMD/Code/Main/WinMain.cpp b/GeneralsMD/Code/Main/WinMain.cppindex 8a1137117..5abd26a09 100644--- a/GeneralsMD/Code/Main/WinMain.cpp+++ b/GeneralsMD/Code/Main/WinMain.cpp@@ -42,6 +42,7 @@// USER INCLUDES //////////////////////////////////////////////////////////////#include "WinMain.h"#include "Lib/BaseType.h"+#include "stringex.h"#include "Common/CopyProtection.h"#include "Common/CriticalSection.h"#include "Common/GlobalData.h"@@ -1090,7 +1091,7 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,char name[_MAX_PATH], file[_MAX_PATH];unsigned int line;unsigned int addr;- GetFunctionDetails((void*)pc, name, file, &line, &addr);+ GetFunctionDetails((void*)pc, name, ARRAY_SIZE(name), file, ARRAY_SIZE(file), &line, &addr);DEBUG_LOG(("0x%x - %s, %s, line %d address 0x%x\n", pc, name, file, line, addr));}DEBUG_LOG(("\n--- END OF DX STACK DUMP\n"));@@ -1119,8 +1120,8 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,char filePath[_MAX_PATH];char *fileName = "Install_Final.bmp";static const char *localizedPathFormat = "Data/%s/";- sprintf(filePath,localizedPathFormat, GetRegistryLanguage().str());- strcat( filePath, fileName );+ snprintf(filePath, ARRAY_SIZE(filePath), localizedPathFormat, GetRegistryLanguage().str());+ strlcat( filePath, fileName, ARRAY_SIZE(filePath) );FILE *fileImage = fopen(filePath, "r");if (fileImage) {fclose(fileImage);