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(savegame): keep the old save on a failed write, refuse bad saves
Olcay Seyganb0e1e5a8cb4c
diff --git a/GeneralsMD/Code/Data/Patch.str b/GeneralsMD/Code/Data/Patch.strindex 4307e3aa3..e9f0e5840 100644--- a/GeneralsMD/Code/Data/Patch.str+++ b/GeneralsMD/Code/Data/Patch.str@@ -1153,6 +1153,10 @@ LAN:NoMod"none"END+GUI:SaveFromOlderGame+"This save was made by the original game or by an older version of Reforged, and cannot be loaded."+END+GUI:KickVoteStarted"%ls wants %ls out of the match. Type /yes or /no in chat: every other player has 30 seconds to agree."ENDdiff --git a/GeneralsMD/Code/Data/Turkish/Generals.str b/GeneralsMD/Code/Data/Turkish/Generals.strindex 4aa600b31..6ce3a816a 100644--- a/GeneralsMD/Code/Data/Turkish/Generals.str+++ b/GeneralsMD/Code/Data/Turkish/Generals.str@@ -15569,6 +15569,10 @@ CONTROLBAR:Demo_ToolTipGLAScienceRebelAmbush"Her yerde Asilerle ani bir pusu kurmanızı sağlar \n \n Seviye 1: 4 Asi \n Seviye 2: 6 Asi \n Seviye 3: 10 Asi \n \n Çağrıldığı yer: Komuta Merkezi"END+GUI:SaveFromOlderGame+"Bu kayıt orijinal oyunla ya da Reforged'ın eski bir sürümüyle yapılmış, yüklenemez."+END+GUI:KickVoteStarted"%ls, %ls oyuncusunun maçtan atılmasını istiyor. Sohbete /yes ya da /no yazın: diğer oyuncuların kabul etmek için 30 saniyesi var."ENDdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameState.h b/GeneralsMD/Code/GameEngine/Include/Common/GameState.hindex 3cd1b9758..9b7bf11c7 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GameState.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GameState.h@@ -115,6 +115,11 @@ public:SaveFileType saveFileType; // type of save file we're dealing withAsciiString missionMapName; // used for mission savesInt framesPerSecond; // game speed the match was playing at, 0 in saves older than that+ Int version; // GameState block version the file was written with, read with the header++ /// FALSE for a save written by the original game or by a build from before logic ran at 60+ /// ticks a second: none of them loads in this one.+ Bool isLoadable( void ) const;};@@ -175,6 +180,9 @@ public:SnapshotType which = SNAPSHOT_SAVELOAD ); ///< save a gameSaveCode missionSave( void ); ///< do a in between mission saveSaveCode loadGame( AvailableGameInfo gameInfo ); ///< load a save file+ /// TRUE, having told the player why, when this save cannot load here (SaveGameInfo::isLoadable).+ /// Asked before anything is torn down, so the game or menu the player is in stays.+ Bool refuseUnloadableSave( const SaveGameInfo &saveGameInfo );/// A replay's rewind checkpoint: the whole world into a file at this path, and back out of it./// Nothing on screen says so, and the load calls afterReset once the engine is empty and before/// the world goes back in, which is where the recorder picks its file up again.diff --git a/GeneralsMD/Code/GameEngine/Include/Common/XferLoad.h b/GeneralsMD/Code/GameEngine/Include/Common/XferLoad.hindex 0d68e2927..dac65b65f 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/XferLoad.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/XferLoad.h@@ -65,7 +65,12 @@ protected:virtual void xferImplementation( void *data, Int dataSize ); ///< the xfer implementation+ /// Throws XFER_READ_ERROR unless 'dataSize' bytes are left in the file: a size read from a+ /// broken or tampered save is not trusted to allocate or skip by.+ void requireBytesLeft( Int dataSize );+FILE * m_fileFP; ///< pointer to file+ long m_fileSize; ///< bytes in the file, read on open};diff --git a/GeneralsMD/Code/GameEngine/Include/Common/XferSave.h b/GeneralsMD/Code/GameEngine/Include/Common/XferSave.hindex 47ef565b5..598b1d0f4 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/XferSave.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/XferSave.h@@ -57,7 +57,11 @@ public:// Xfer methodsvirtual void open( AsciiString identifier ); ///< open file for writing- virtual void close( void ); ///< close file+ virtual void close( void ); ///< write the file and put it in place+ /// Drop what was written and leave any file already at the identifier as it was. Close writes+ /// into "<identifier>.tmp" and renames that over the identifier only once every byte is down, so+ /// a full disk or a crash mid-save never costs the save that was there.+ void discard( void );virtual Int beginBlock( void ); ///< write placeholder block sizevirtual void endBlock( void ); ///< backup to last begin block and write sizevirtual void skip( Int dataSize ); ///< skipping during a write is a no-opdiff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cppindex 1e60e305d..5e8bfd33f 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp@@ -598,9 +598,22 @@ static void startPendingSaveGame( void )}// getSaveGameInfoFromFile opens the name it is handed as-is, so give it the path (the menu's- // iterateSaveFiles callback does the same).- TheGameState->getSaveGameInfoFromFile(- TheGameState->getFilePathInSaveDirectory( thePendingSaveFile ), &gameInfo.saveGameInfo );+ // iterateSaveFiles callback does the same). A broken file throws out of the header read, which+ // the menu's callback catches too; nothing is set up yet, so it ends like a name not there.+ try+ {+ TheGameState->getSaveGameInfoFromFile(+ TheGameState->getFilePathInSaveDirectory( thePendingSaveFile ), &gameInfo.saveGameInfo );+ }+ catch( ... )+ {+ DEBUG_LOG(("-loadsave: '%s' could not be loaded, its header is broken\n", gameInfo.filename.str()));+ if (TheGlobalData->m_headless)+ TheGameEngine->setQuitting( TRUE );+ else+ TheWritableGlobalData->m_shellMapOn = TRUE;+ return;+ }TheGameLogic->prepareNewGame( GAME_SINGLE_PLAYER, DIFFICULTY_NORMAL, 0 );diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cppindex d0561c5d6..dafd5a834 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp@@ -80,6 +80,11 @@ static const Char *SAVE_GAME_EXTENSION = ".sav";static const Char *ZERO_NAME_ONLY = "00000000";static const Int MAX_SAVE_FILE_NUMBER = 99999999;+// The GameState block's version. 4 adds nothing to the block: it marks the build where logic went+// to 60 ticks a second, and a file written before that cannot load in this one. The original+// game's files are 2, as were this fork's until 3 added the game speed.+static const XferVersion GAME_STATE_VERSION = 4;+///////////////////////////////////////////////////////////////////////////////////////////////////#define GAME_STATE_BLOCK_STRING "CHUNK_GameState" // block of save game data with game info data#define CAMPAIGN_BLOCK_STRING "CHUNK_Campaign" // block of game data that has campaign info@@ -100,6 +105,7 @@ SaveGameInfo::SaveGameInfo( void )missionNumber = 0;saveFileType = SAVE_FILE_TYPE_NORMAL;framesPerSecond = 0;+ version = 0;} // end SaveGameInfo@@ -110,6 +116,16 @@ SaveGameInfo::~SaveGameInfo( void )} // end ~SaveGameInfo+// ------------------------------------------------------------------------------------------------+// ------------------------------------------------------------------------------------------------+Bool SaveGameInfo::isLoadable( void ) const+{++ // a newer one never gets this far: xferVersion refuses it while the header is read+ return version >= GAME_STATE_VERSION;++} // end isLoadable+// ------------------------------------------------------------------------------------------------/** Is this date newer than the other one passed in? */// ------------------------------------------------------------------------------------------------@@ -647,17 +663,21 @@ SaveCode GameState::saveGame( AsciiString filename, UnicodeString desc,// this is now done during startNewGame()// gameInfo->pristineMapName = TheCampaignManager->getCurrentMap();- // write the save file+ // write the save file. Close is in here too: it is where the bytes reach the disk, and where a+ // full disk shows. Either failing leaves the slot's earlier save as it was.try{// save filexferSaveData( &xferSave, which );+ xferSave.close();} // end trycatch( ... ){+ xferSave.discard();+UnicodeString ufilepath;ufilepath.translate(filepath);@@ -666,14 +686,9 @@ SaveCode GameState::saveGame( AsciiString filename, UnicodeString desc,MessageBoxOk(TheGameText->fetch("GUI:Error"), msg, NULL);- // close the file and get out of here- xferSave.close();return SC_ERROR;-- } // end catch- // close the file- xferSave.close();+ } // end catch// print message to the user for game successfully savedUnicodeString msg = TheGameText->fetch( "GUI:GameSaveComplete" );@@ -757,6 +772,10 @@ SaveCode GameState::loadGame( AvailableGameInfo gameInfo )if( doesSaveGameExist( gameInfo.filename ) == FALSE )return SC_FILE_NOT_FOUND;+ // the original game's saves and this fork's older ones read as garbage here+ if( refuseUnloadableSave( gameInfo.saveGameInfo ) )+ return SC_INVALID_DATA;+// clear game data just like loading from the debug map load screen for mission savesif( gameInfo.saveGameInfo.saveFileType == SAVE_FILE_TYPE_MISSION ){@@ -876,6 +895,21 @@ SaveCode GameState::loadGame( AvailableGameInfo gameInfo )} // end loadGame+// ------------------------------------------------------------------------------------------------+// ------------------------------------------------------------------------------------------------+Bool GameState::refuseUnloadableSave( const SaveGameInfo &saveGameInfo )+{++ if( saveGameInfo.isLoadable() )+ return FALSE;++ DEBUG_LOG(( "GameState - refused a save with GameState version %d, this build loads %d\n",+ saveGameInfo.version, GAME_STATE_VERSION ));+ MessageBoxOk( TheGameText->fetch( "GUI:Error" ), TheGameText->fetch( "GUI:SaveFromOlderGame" ), NULL );+ return TRUE;++} // end refuseUnloadableSave+//-------------------------------------------------------------------------------------------------AsciiString GameState::getSaveDirectory() const{@@ -1628,18 +1662,21 @@ void GameState::gameStatePostProcessLoad( void )/** Xfer method for the game state itself* Version Info:* 1: Initial version- * 2: Added save file type and mission map name (regular save vs automatic mission save) */+ * 2: Added save file type and mission map name (regular save vs automatic mission save)+ * 3: Added the game speed+ * 4: Nothing new in the block; see GAME_STATE_VERSION */// ------------------------------------------------------------------------------------------------void GameState::xfer( Xfer *xfer ){// version- XferVersion currentVersion = 3;+ XferVersion currentVersion = GAME_STATE_VERSION;XferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );// get structure for our current game infoSaveGameInfo *saveGameInfo = getSaveGameInfo();+ saveGameInfo->version = version;// version 3: the game speed, read back by loadGame. It goes first because the rest of this// block ends in branches.diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cppindex 490b31b81..69398695a 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cpp@@ -193,10 +193,16 @@ static void embedInUseMap( AsciiString map, Xfer *xfer )// ------------------------------------------------------------------------------------------------static void extractAndSaveMap( AsciiString mapToSave, Xfer *xfer ){- UnsignedInt dataSize;+ // read the whole map first: its size comes from the file, which XferLoad has checked holds that+ // many bytes, and a read that fails then leaves no half-written map and nothing leaked+ const Int dataSize = xfer->beginBlock();+ std::vector< char > buffer( dataSize );+ if( dataSize > 0 )+ xfer->xferUser( &buffer[ 0 ], dataSize );+ xfer->endBlock();// open handle to output file- FILE *fp = zh_fopen( mapToSave.str(), "w+b" );+ FILE *fp = zh_fopen( mapToSave.str(), "wb" );if( fp == NULL ){@@ -205,40 +211,16 @@ static void extractAndSaveMap( AsciiString mapToSave, Xfer *xfer )} // en- // read data size from file- dataSize = xfer->beginBlock();-- // allocate buffer big enough for the entire map file- char *buffer = new char[ dataSize ];- if( buffer == NULL )- {-- DEBUG_CRASH(( "extractAndSaveMap - Unable to allocate buffer for file '%s'\n", mapToSave.str() ));- throw SC_INVALID_DATA;-- } // end if-- // read map file- xfer->xferUser( buffer, dataSize );-// write contents of buffer to new file- if( fwrite( buffer, 1, dataSize, fp ) != dataSize )+ const Bool written = dataSize == 0 || fwrite( &buffer[ 0 ], dataSize, 1, fp ) == 1;+ if( fclose( fp ) != 0 || !written ){- DEBUG_CRASH(( "extractAndSaveMap - Error writing to file '%s'\n", mapToSave.str() ));+ DEBUG_LOG(( "extractAndSaveMap - Error writing to file '%s'\n", mapToSave.str() ));throw SC_INVALID_DATA;} // end if- // close the new file- fclose( fp );-- // end of data block- xfer->endBlock();-- // delete the buffer- delete [] buffer;-} // end extractAndSaveMap// ------------------------------------------------------------------------------------------------@@ -335,9 +317,15 @@ void GameStateMap::xfer( Xfer *xfer )saveGameInfo->saveGameMapName = TheGameState->portableMapPathToRealMapPath(tmp);- if (!TheGameState->isInSaveDirectory(saveGameInfo->saveGameMapName))+ // The embedded map is written out under this name, so it must be a .map straight in the save+ // directory: a broken or tampered file named "save\../x" or "save\00000001.sav" would+ // otherwise write past the directory or over another save.+ AsciiString leaf = TheGameState->getMapLeafName(saveGameInfo->saveGameMapName);+ const char *extension = strrchr(leaf.str(), '.');+ if (!TheGameState->isInSaveDirectory(saveGameInfo->saveGameMapName) ||+ strpbrk(leaf.str(), "/:") != NULL || extension == NULL || strcasecmp(extension, ".map") != 0){- DEBUG_CRASH(("GameState::xfer - The map filename read from the file '%s' is not in the SAVE directory, but should be\n",+ DEBUG_LOG(("GameStateMap::xfer - The map filename read from the file '%s' is not a .map in the SAVE directory, but should be\n",saveGameInfo->saveGameMapName.str()) );throw SC_INVALID_DATA;}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/XferLoad.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/XferLoad.cppindex dbf4fd83c..f46e77679 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/XferLoad.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/XferLoad.cpp@@ -43,6 +43,7 @@ XferLoad::XferLoad( void )m_xferMode = XFER_LOAD;m_fileFP = NULL;+ m_fileSize = 0;} // end XferLoad@@ -91,8 +92,28 @@ void XferLoad::open( AsciiString identifier )} // end if+ fseek( m_fileFP, 0, SEEK_END );+ m_fileSize = ftell( m_fileFP );+ fseek( m_fileFP, 0, SEEK_SET );+} // end open+//-------------------------------------------------------------------------------------------------+//-------------------------------------------------------------------------------------------------+void XferLoad::requireBytesLeft( Int dataSize )+{++ if( dataSize < 0 || dataSize > m_fileSize - ftell( m_fileFP ) )+ {++ DEBUG_LOG(( "XferLoad - %d bytes asked for at offset %ld of the %ld in '%s'\n",+ dataSize, ftell( m_fileFP ), m_fileSize, m_identifier.str() ));+ throw XFER_READ_ERROR;++ } // end if++} // end requireBytesLeft+//-------------------------------------------------------------------------------------------------/** Close our current file *///-------------------------------------------------------------------------------------------------@@ -129,13 +150,10 @@ Int XferLoad::beginBlock( void )// read block sizeXferBlockSize blockSize;- if( fread( &blockSize, sizeof( XferBlockSize ), 1, m_fileFP ) != 1 )- {-- DEBUG_CRASH(( "Xfer - Error reading block size for '%s'\n", m_identifier.str() ));- return 0;+ xferImplementation( &blockSize, sizeof( XferBlockSize ) );- } // end if+ // callers allocate and skip by it, so a block reaching past the end of the file is a broken save+ requireBytesLeft( blockSize );// return the block sizereturn blockSize;@@ -160,9 +178,7 @@ void XferLoad::skip( Int dataSize )DEBUG_ASSERTCRASH( m_fileFP != NULL, ("XferLoad::skip - file pointer for '%s' is NULL\n",m_identifier.str()) );- // sanity- DEBUG_ASSERTCRASH( dataSize >=0, ("XferLoad::skip - dataSize '%d' must be greater than 0\n",- dataSize) );+ requireBytesLeft( dataSize );// skip datasize in the file from the current positionif( fseek( m_fileFP, dataSize, SEEK_CUR ) != 0 )diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/XferSave.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/XferSave.cppindex 422df542d..234fc51d1 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/XferSave.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/XferSave.cpp@@ -35,6 +35,7 @@#include "Common/XferSave.h"#include "Common/Snapshot.h"#include "Common/GameMemory.h"+#include "Common/LocalFileSystem.h"// PRIVATE TYPES //////////////////////////////////////////////////////////////////////////////////class XferBlockData : public MemoryPoolObject@@ -49,6 +50,16 @@ public:};EMPTY_DTOR(XferBlockData)+// ------------------------------------------------------------------------------------------------+/** Where the file is written before it replaces 'identifier' */+// ------------------------------------------------------------------------------------------------+static AsciiString tempPathOf( const AsciiString &identifier )+{+ AsciiString temp = identifier;+ temp.concat( ".tmp" );+ return temp;+}+///////////////////////////////////////////////////////////////////////////////////////////////////// PUBLIC METHDOS ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////@@ -69,14 +80,9 @@ XferSave::XferSave( void )XferSave::~XferSave( void ){- // warn the user if a file was left open- if( m_fileFP != NULL )- {-- DEBUG_CRASH(( "Warning: Xfer file '%s' was left open\n", m_identifier.str() ));- close();-- } // end if+ // a file still open here was left by an exception part way through the save: what was written+ // is incomplete, so it never replaces the file already there+ discard();//// the block stack should be empty, if it's not that means we started blocks but never@@ -122,11 +128,11 @@ void XferSave::open( AsciiString identifier )// call base classXfer::open( identifier );- // open the file- m_fileFP = zh_fopen( identifier.str(), "w+b" );+ // open the file it is written to first; close puts it in place+ m_fileFP = zh_fopen( tempPathOf( identifier ).str(), "wb" );if( m_fileFP == NULL ){-+DEBUG_CRASH(( "File '%s' not found\n", identifier.str() ));throw XFER_FILE_NOT_FOUND;@@ -149,15 +155,20 @@ void XferSave::close( void )} // end if- // write the file and close it+ // write the file and close it; fclose flushes, so a full disk can show first thereconst size_t size = m_data.size();const Bool written = size == 0 || fwrite( &m_data[ 0 ], size, 1, m_fileFP ) == 1;- fclose( m_fileFP );+ const Bool closed = fclose( m_fileFP ) == 0;m_fileFP = NULL;m_data.clear();- if( !written )++ // only a complete file replaces the one there+ const AsciiString temp = tempPathOf( m_identifier );+ if( !written || !closed || !TheLocalFileSystem->moveFileReplacing( temp.str(), m_identifier.str() ) ){DEBUG_LOG(( "XferSave - Error writing %u bytes to file '%s'\n", (UnsignedInt)size, m_identifier.str() ));+ zh_remove( temp.str() );+ m_identifier.clear();throw XFER_WRITE_ERROR;}@@ -166,6 +177,23 @@ void XferSave::close( void )} // end close+//-------------------------------------------------------------------------------------------------+//-------------------------------------------------------------------------------------------------+void XferSave::discard( void )+{++ // closed already: by close, which cleaned up after itself if it failed+ if( m_fileFP == NULL )+ return;++ fclose( m_fileFP );+ m_fileFP = NULL;+ m_data.clear();+ zh_remove( tempPathOf( m_identifier ).str() );+ m_identifier.clear();++} // end discard+//-------------------------------------------------------------------------------------------------/** Write a placeholder at the current location in the file and store this location* internally. The next endBlock that is called will back up to the most recently storeddiff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cppindex a950a2373..a189b5b5c 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cpp@@ -492,6 +492,10 @@ static void processLoadButtonPress(GameWindow *window)if( selectedGameInfo ){+ // refused here, before the confirm and before the game or menu is torn down for the load+ if( TheGameState->refuseUnloadableSave( selectedGameInfo->saveGameInfo ) )+ return;+//// if we're in the shell we do not need a confirmation dialog that states we will// lose the current loaded game data cause we're not in a game