Skip to content

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.

fix(gameengine): survive mod data gaps, lost devices and false desyncs

Olcay Seygand27bfd61eb5e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e7c61d5c7..9f16f6d14 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -285,6 +285,7 @@ found and fixed — EA's own, not port damage.**
- A build button whose requirement names a unit the mod never made shows its tooltip with the requirement listed by name. Hovering it used to crash the game.
- A vehicle a mod gives two passenger holds no longer crashes the game. The second hold took riders in where nothing else looked, so a passenger who died stayed aboard, and the next time the vehicle seated its riders it reached for him.
- A network game or a replay on a map this machine cannot read goes back to the menu. It used to deal out the start positions as if the map had eight, while the machines that had it dealt over the map's own, and the game split from the first second.
+- A mod whose unit is switched on, held back or stripped by an upgrade the mod never defines no longer crashes the game as the map loads. The missing name is skipped and written to the log once, and the rest of the unit's upgrades work.
## One interface
@@ -1970,6 +1971,12 @@ The whole HUD is on the hardware. Four colours carry it, and they mean the same
- Stopped sounds really stop. A destroyed unit's engine loop and a turret's turning loop no longer play on, and the Idle Worker tooltip shows its key.
- A damaged map sends you back to the menu with a box naming it as damaged, instead of closing the game. A map file is whatever its maker handed you, and the reader trusted every count in it: a height map claiming four billion cells, a trigger with a negative number of points or a tile class pointing past its table either crashed the game or read on into the next part of the file, where every machine found different garbage. Each count is checked against what the file can hold now, and a map that fails is left out of the list or refused at the start, the same way on every machine in the match. For a few hours that check also refused Tournament City, Tournament Desert, Fortress Avalanche, Heartland Shield, Sand Serpent and two campaign maps, all of which save no cliff textures and were read as damaged for it. They open again; all 62 skirmish maps in the game's archives were started headless to prove it.
- A custom map's rules last for that match only. A map.ini could rewrite a weapon, a sound, a particle effect, an FX list, the water or the snow, and the next match on another map played with the change still in it, so two players who had played different maps before were running different rules. Every store a map may touch puts the game's own values back when the match ends, and a block a map has no business changing (the mouse, the multiplayer colours, the campaigns) is skipped with the rest of the file still loading. A map.ini that raised a unit's price showed it on the button and charged the old one; it charges what the button says now. Values no sane map uses, a build time of a hundred years or a snowstorm a million flakes wide, are refused one line at a time. A map that set the weather twice, in its map.ini and its solo.ini, froze the game while it loaded; it loads now.
+- A replay that cannot save a rewind point plays on. It keeps the rewind points it already made and stops making new ones; one mod unit that could not be saved used to close the game. A rewind point that will not load says so in a box instead of closing the game.
+- A network match no longer reports a desync that never happened. With a long run-ahead one frame can bring in the checks of several earlier ones, each player's newest overwrote the rest, and the game compared one player's check of one frame with another's of the next. Checks are kept by the frame they were made on now, and a frame is compared only once every connected player's check for it is in.
+- A graphics driver reset says so. The game used to vanish without a word when Windows reset the driver or the card stopped answering; now the crash report names the frame and the reason Windows gave.
+- Alt-tab no longer crashes the game while it is painting house colours onto a unit. With the screen gone the game had no picture to paint on and reached for it anyway. The unit comes out in its plain colours for that moment and gets its house colour the next time it is drawn.
+- Logging off or shutting Windows down with the game open closes it cleanly, replay saved with its length. The game used to refuse, Windows sat on its "apps are preventing shutdown" screen, killed it anyway, and the launcher reported a crash.
+- A crash that used to leave nothing in the log leaves a record now. Some access violations faulted again inside the crash report itself and the log ended on an ordinary frame; the first thing written is the fault's address and module, straight to the file, then the last second of log lines that were still waiting to be written.
## Units take corners wide, and drive round a jam instead of into it
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameMemory.h b/GeneralsMD/Code/GameEngine/Include/Common/GameMemory.h
index 3af05a4ca..5b2f24323 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GameMemory.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GameMemory.h
@@ -303,6 +303,8 @@ private:
MemoryPoolBlob *m_lastBlob; ///< tail of linked list: last blob for this pool. (needed for efficiency)
MemoryPoolBlob *m_firstBlobWithFreeBlocks; ///< first blob in this pool that has at least one unallocated block.
+ friend class MemoryPoolBlob; ///< walks m_firstBlob to find the blob holding a corrupt block header
+
private:
/// create a new blob with the given number of blocks.
MemoryPoolBlob* createBlob(Int allocationCount);
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameState.h b/GeneralsMD/Code/GameEngine/Include/Common/GameState.h
index 83a81321e..27d1a96f5 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GameState.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GameState.h
@@ -186,8 +186,9 @@ public:
/// 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.
- void saveCheckpoint( AsciiString filepath );
- void loadCheckpoint( AsciiString filepath, const std::function< void( void ) > &afterReset );
+ /// Each says FALSE when it failed: no file from a save, and from a load a match already cleared.
+ Bool saveCheckpoint( AsciiString filepath );
+ Bool loadCheckpoint( AsciiString filepath, const std::function< void( void ) > &afterReset );
SaveGameInfo *getSaveGameInfo( void ) { return &m_gameInfo; }
// snapshot interaction
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Module.h b/GeneralsMD/Code/GameEngine/Include/Common/Module.h
index cb7b0f9aa..d18d40cde 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/Module.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/Module.h
@@ -256,6 +256,9 @@ class ObjectModule : public Module
MEMORY_POOL_GLUE_ABC( ObjectModule ) ///< this abstract class needs memory pool hooks
+ // the upgrade data shared by a module's template acts on, and names, the module's object
+ friend class UpgradeMuxData;
+
public:
ObjectModule( Thing *thing, const ModuleData* moduleData );
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h b/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h
index 36c8aeeff..a2f416dc0 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h
@@ -58,6 +58,9 @@ void GetFunctionDetails(void *pointer, char*name, size_t nameSize, char*filename
// Dumps out the exception info and stack trace. Windows only: EXCEPTION_POINTERS is a structured
// exception's, and C5 owns what a crash reports elsewhere. StackDumpPosix.cpp is the other body.
void DumpExceptionInfo( unsigned int u, EXCEPTION_POINTERS* e_info );
+// The debug log's own file handle, or NULL while it is closed. DumpExceptionInfo writes a short
+// fixed record into it first, past the log's queue (Debug.cpp sets it).
+void SetCrashRecordHandle( void *handle );
#endif
#else
@@ -75,6 +78,7 @@ __inline void GetFunctionDetails(void *pointer, char*name, size_t nameSize, char
#if defined(_WIN32)
// Dumps out the exception info and stack trace.
__inline void DumpExceptionInfo( unsigned int u, EXCEPTION_POINTERS* e_info ) {};
+__inline void SetCrashRecordHandle( void *handle ) {}
#endif
#endif
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/CRCSnapshotRing.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/CRCSnapshotRing.h
index 59b658d0a..eb0da9720 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/CRCSnapshotRing.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/CRCSnapshotRing.h
@@ -67,6 +67,16 @@ struct CRCPlayerEntry
Int m_sciencePurchasePoints;
};
+/// one run of a player's commands of one type on one frame (see CRCSnapshot::m_commands)
+struct CRCCommandEntry
+{
+ UnsignedInt m_frame; ///< the logic frame the commands executed on
+ Int m_player; ///< player index
+ Int m_type; ///< GameMessage::Type
+ UnsignedInt m_count; ///< messages in the run
+ UnsignedInt m_argHash; ///< every argument of every message in the run, in order
+};
+
struct CRCSnapshot
{
UnsignedInt m_frame;
@@ -76,6 +86,11 @@ struct CRCSnapshot
std::vector<CRCObjectEntry> m_objects;
UnsignedInt m_sectionCRC[ CRC_SECTION_COUNT ]; ///< world CRC at the end of each CRCSection
std::vector<CRCPlayerEntry> m_players; ///< by player index
+ /* The network commands logic executed after the previous snapshot and before this one, the inputs
+ that made this world out of the last. Two dumps whose CRCs part on a frame with the same
+ digests ran the same orders differently (a logic split); different digests were given different
+ orders (an input split). */
+ std::vector<CRCCommandEntry> m_commands;
};
//-------------------------------------------------------------------------------------------------
@@ -95,10 +110,12 @@ public:
void setSectionCRC( CRCSection section, UnsignedInt runningCRC ); ///< record the world CRC at a section's end
void addPlayer( UnsignedInt money, Int skillPoints, Int sciencePurchasePoints ); ///< record the next player's numbers
void endSnapshot( UnsignedInt totalCRC, UnsignedInt randomSeed ); ///< close the slot being filled
+ void addCommand( UnsignedInt frame, Int player, Int type, UnsignedInt argHash ); ///< one executed command, for the next snapshot
Int getNewestSlot( void ) const; ///< -1 when no snapshot is complete
Int getNthNewestSlot( Int n ) const; ///< n==0 is the newest; -1 when out of range
Int findSlotByCRC( UnsignedInt crc ) const; ///< newest first; -1 when no slot has that CRC
+ Int findSlotByFrame( UnsignedInt frame ) const; ///< newest first; -1 when no slot is that frame
const CRCSnapshot *getSlot( Int slot ) const; ///< NULL for an out of range or unfilled slot
Int getNumSnapshots( void ) const { return m_numSnapshots; }
@@ -107,6 +124,7 @@ private:
CRCSnapshot m_snapshots[ CRC_SNAPSHOT_RING_SIZE ];
Int m_writeSlot; ///< slot beginSnapshot() last opened, -1 before the first
Int m_numSnapshots; ///< how many slots hold real data
+ std::vector<CRCCommandEntry> m_pendingCommands; ///< executed since the last beginSnapshot()
};
#endif // _CRC_SNAPSHOT_RING_H_
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h
index 1484984d2..c03a00239 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h
@@ -377,10 +377,10 @@ private:
// CRC cache system -----------------------------------------------------------------------------
UnsignedInt m_CRC; ///< Cache of previous CRC value
- std::map<Int, UnsignedInt> m_cachedCRCs; ///< CRCs we've seen this frame
+ std::map<UnsignedInt, std::map<Int, UnsignedInt> > m_cachedCRCs; ///< CRCs executed this frame, by the frame they were computed on, then by player
Bool m_shouldValidateCRCs; ///< Should we validate CRCs this frame?
CRCSnapshotRing m_crcSnapshots; ///< per object CRCs for the last few CRC frames, for mismatch diagnosis
- void writeMismatchDump( Int numPlayers ); ///< write down what the world looked like on the mismatching frame
+ void writeMismatchDump( Int numPlayers, UnsignedInt crcFrame ); ///< write down what the world looked like on the mismatching frame
//-----------------------------------------------------------------------------------------------
//Added By Sadullah Nader
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AutoHealBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AutoHealBehavior.h
index 000dd605f..78460ba6b 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AutoHealBehavior.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AutoHealBehavior.h
@@ -150,7 +150,7 @@ protected:
virtual void getUpgradeActivationMasks(UpgradeMaskType& activation, UpgradeMaskType& conflicting) const
{
- getAutoHealBehaviorModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting);
+ getAutoHealBehaviorModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting, this);
}
virtual void performUpgradeFX()
@@ -161,7 +161,7 @@ protected:
virtual void processUpgradeRemoval()
{
// I can't take it any more. Let the record show that I think the UpgradeMux multiple inheritence is CRAP.
- getAutoHealBehaviorModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(getObject());
+ getAutoHealBehaviorModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(this);
}
virtual Bool requiresAllActivationUpgrades() const
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CountermeasuresBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CountermeasuresBehavior.h
index 00280472d..ad2ca5371 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CountermeasuresBehavior.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CountermeasuresBehavior.h
@@ -160,7 +160,7 @@ protected:
virtual void getUpgradeActivationMasks(UpgradeMaskType& activation, UpgradeMaskType& conflicting) const
{
- getCountermeasuresBehaviorModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting);
+ getCountermeasuresBehaviorModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting, this);
}
virtual void performUpgradeFX()
@@ -171,7 +171,7 @@ protected:
virtual void processUpgradeRemoval()
{
// I can't take it any more. Let the record show that I think the UpgradeMux multiple inheritence is CRAP.
- getCountermeasuresBehaviorModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(getObject());
+ getCountermeasuresBehaviorModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(this);
}
virtual Bool requiresAllActivationUpgrades() const
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FXListDie.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FXListDie.h
index fe690c0f4..f8281a927 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FXListDie.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FXListDie.h
@@ -105,7 +105,7 @@ protected:
virtual void getUpgradeActivationMasks(UpgradeMaskType& activation, UpgradeMaskType& conflicting) const
{
- getFXListDieModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting);
+ getFXListDieModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting, this);
}
virtual void performUpgradeFX()
@@ -116,7 +116,7 @@ protected:
virtual void processUpgradeRemoval()
{
// I can't take it any more. Let the record show that I think the UpgradeMux multiple inheritence is CRAP.
- getFXListDieModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(getObject());
+ getFXListDieModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(this);
}
virtual Bool requiresAllActivationUpgrades() const
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireOCLAfterWeaponCooldownUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireOCLAfterWeaponCooldownUpdate.h
index 50cd85389..852083031 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireOCLAfterWeaponCooldownUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireOCLAfterWeaponCooldownUpdate.h
@@ -76,7 +76,7 @@ protected:
virtual void getUpgradeActivationMasks(UpgradeMaskType& activation, UpgradeMaskType& conflicting) const
{
- getFireOCLAfterWeaponCooldownUpdateModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting);
+ getFireOCLAfterWeaponCooldownUpdateModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting, this);
}
virtual void performUpgradeFX()
@@ -87,7 +87,7 @@ protected:
virtual void processUpgradeRemoval()
{
// I can't take it any more. Let the record show that I think the UpgradeMux multiple inheritence is CRAP.
- getFireOCLAfterWeaponCooldownUpdateModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(getObject());
+ getFireOCLAfterWeaponCooldownUpdateModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(this);
}
virtual Bool requiresAllActivationUpgrades() const
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h
index ef869f001..420763394 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h
@@ -139,7 +139,7 @@ protected:
virtual void getUpgradeActivationMasks(UpgradeMaskType& activation, UpgradeMaskType& conflicting) const
{
- getFireWeaponWhenDamagedBehaviorModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting);
+ getFireWeaponWhenDamagedBehaviorModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting, this);
}
virtual void performUpgradeFX()
@@ -150,7 +150,7 @@ protected:
virtual void processUpgradeRemoval()
{
// I can't take it any more. Let the record show that I think the UpgradeMux multiple inheritence is CRAP.
- getFireWeaponWhenDamagedBehaviorModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(getObject());
+ getFireWeaponWhenDamagedBehaviorModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(this);
}
virtual Bool requiresAllActivationUpgrades() const
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h
index 688b6dc7a..c885151a4 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h
@@ -104,7 +104,7 @@ protected:
virtual void getUpgradeActivationMasks(UpgradeMaskType& activation, UpgradeMaskType& conflicting) const
{
- getFireWeaponWhenDeadBehaviorModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting);
+ getFireWeaponWhenDeadBehaviorModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting, this);
}
virtual void performUpgradeFX()
@@ -115,7 +115,7 @@ protected:
virtual void processUpgradeRemoval()
{
// I can't take it any more. Let the record show that I think the UpgradeMux multiple inheritence is CRAP.
- getFireWeaponWhenDeadBehaviorModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(getObject());
+ getFireWeaponWhenDeadBehaviorModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(this);
}
virtual Bool requiresAllActivationUpgrades() const
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/GenerateMinefieldBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/GenerateMinefieldBehavior.h
index d6ceda2ef..fa1dda887 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/GenerateMinefieldBehavior.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/GenerateMinefieldBehavior.h
@@ -101,7 +101,7 @@ protected:
virtual void getUpgradeActivationMasks(UpgradeMaskType& activation, UpgradeMaskType& conflicting) const
{
- getGenerateMinefieldBehaviorModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting);
+ getGenerateMinefieldBehaviorModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting, this);
}
virtual void performUpgradeFX()
{
@@ -110,7 +110,7 @@ protected:
virtual void processUpgradeRemoval()
{
// I can't take it any more. Let the record show that I think the UpgradeMux multiple inheritence is CRAP.
- getGenerateMinefieldBehaviorModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(getObject());
+ getGenerateMinefieldBehaviorModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(this);
}
virtual Bool requiresAllActivationUpgrades() const
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpyVisionUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpyVisionUpdate.h
index badec77a2..a226106f4 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpyVisionUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SpyVisionUpdate.h
@@ -118,7 +118,7 @@ protected:
virtual void upgradeImplementation();
virtual void getUpgradeActivationMasks(UpgradeMaskType& activation, UpgradeMaskType& conflicting) const
{
- getSpyVisionUpdateModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting);
+ getSpyVisionUpdateModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting, this);
}
virtual void performUpgradeFX()
{
@@ -127,7 +127,7 @@ protected:
virtual void processUpgradeRemoval()
{
// I can't take it any more. Let the record show that I think the UpgradeMux multiple inheritence is CRAP.
- getSpyVisionUpdateModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(getObject());
+ getSpyVisionUpdateModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(this);
}
virtual Bool requiresAllActivationUpgrades() const
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/UpgradeModule.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/UpgradeModule.h
index ff93e4be7..b8ac236b9 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/UpgradeModule.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/UpgradeModule.h
@@ -104,9 +104,11 @@ public:
return dataFieldParse;
}
Bool requiresAllActivationUpgrades() const;
- void getUpgradeActivationMasks(UpgradeMaskType& activation, UpgradeMaskType& conflicting) const; ///< The first time someone looks at my mask, I'll figure it out.
+ /// The first time someone looks at my mask, I'll figure it out. 'module' only names the culprit
+ /// in the log when a line names an upgrade that does not exist.
+ void getUpgradeActivationMasks(UpgradeMaskType& activation, UpgradeMaskType& conflicting, const ObjectModule* module) const;
void performUpgradeFX(Object* obj) const;
- void muxDataProcessUpgradeRemoval(Object* obj) const;
+ void muxDataProcessUpgradeRemoval(ObjectModule* module) const;
Bool isTriggeredBy(const std::string &upgrade) const;
};
@@ -192,7 +194,7 @@ protected:
virtual void processUpgradeRemoval()
{
// I can't take it any more. Let the record show that I think the UpgradeMux multiple inheritence is CRAP.
- getUpgradeModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(getObject());
+ getUpgradeModuleData()->m_upgradeMuxData.muxDataProcessUpgradeRemoval(this);
}
virtual Bool requiresAllActivationUpgrades() const
@@ -202,7 +204,7 @@ protected:
virtual void getUpgradeActivationMasks(UpgradeMaskType& activation, UpgradeMaskType& conflicting) const
{
- getUpgradeModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting);
+ getUpgradeModuleData()->m_upgradeMuxData.getUpgradeActivationMasks(activation, conflicting, this);
}
virtual void performUpgradeFX()
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
index ad5118cb1..6d9e87e2e 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
@@ -1522,6 +1522,13 @@ void GameEngine::init( int argc, char *argv[] )
RELEASE_CRASH((e.mFailureMessage));
else
RELEASE_CRASH(("Uncaught Exception during initialization."));
+ }
+ catch (decltype(INI_INVALID_DATA) code)
+ {
+ // an unnamed enum, so the ErrorCode catch above does not take it
+ AsciiString why;
+ why.format("GameEngine::init failed with INI error 0x%08x: game data (a mod's INI?) names something that is not there or cannot be used.", (UnsignedInt)code);
+ RELEASE_CRASH((why.str()));
}
catch (...)
@@ -3463,6 +3470,16 @@ void GameEngine::execute( void )
{
snprintf( why, sizeof(why), "Uncaught ErrorCode 0x%08x in GameEngine::update", (UnsignedInt)ec );
}
+ // The INI_* codes are an unnamed enum, so the ErrorCode catch does not take them: a
+ // module meeting data it cannot use threw one at a mod's map load (reports 1893-1899).
+ catch (decltype(INI_INVALID_DATA) code)
+ {
+ snprintf( why, sizeof(why), "Uncaught INI error 0x%08x in GameEngine::update: game data (a mod's INI?) names something that is not there or cannot be used", (UnsignedInt)code );
+ }
+ catch (XferStatus status)
+ {
+ snprintf( why, sizeof(why), "Uncaught Xfer error %d in GameEngine::update: an object could not be saved or loaded", (Int)status );
+ }
catch (const std::exception &e)
{
snprintf( why, sizeof(why), "Uncaught std::exception in GameEngine::update: %s", e.what() );
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp
index dd6fa482f..d48f2c49a 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp
@@ -2534,8 +2534,10 @@ void Team::killTeam(void)
evacuateTeam();
- // beacons are effectively dead, so we need to destroy via a non-kill() method
- const ThingTemplate *beaconTemplate = TheThingFactory->findTemplate( getControllingPlayer()->getPlayerTemplate()->getBeaconTemplate() );
+ // beacons are effectively dead, so we need to destroy via a non-kill() method.
+ // A neutral or civilian side has no player template and so no beacon.
+ const PlayerTemplate *playerTemplate = getControllingPlayer()->getPlayerTemplate();
+ const ThingTemplate *beaconTemplate = playerTemplate ? TheThingFactory->findTemplate( playerTemplate->getBeaconTemplate() ) : NULL;
// now find objects to kill
for (DLINK_ITERATOR<Object> iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) {
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp
index 821c9e445..c5db367ed 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp
@@ -611,6 +611,11 @@ void DebugInit(int flags)
#if !defined(_WIN32)
// The crash handler writes its report into the log too, and may only use the descriptor.
setCrashLogDescriptor(theLogFile != NULL ? fileno(theLogFile) : -1);
+#else
+ // The exception dump's first record goes straight into the file, past the queue (StackDump.cpp).
+ // _get_osfhandle fails with -1 (INVALID_HANDLE_VALUE), not NULL; StackDump takes NULL for none.
+ const intptr_t logHandle = theLogFile != NULL ? _get_osfhandle(fileno(theLogFile)) : -1;
+ SetCrashRecordHandle(logHandle != -1 ? (void *)logHandle : NULL);
#endif
if (theLogFile != NULL)
{
@@ -764,6 +769,8 @@ void DebugShutdown()
stopLogWriter();
#if !defined(_WIN32)
setCrashLogDescriptor(-1);
+#else
+ SetCrashRecordHandle(NULL);
#endif
fclose(theLogFile);
}
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp
index 6f7cee32c..2678a62fe 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp
@@ -241,6 +241,15 @@ static Int roundUpMemBound(Int i)
return (i + (MEM_BOUND_ALIGNMENT-1)) & ~(MEM_BOUND_ALIGNMENT-1);
}
+//-----------------------------------------------------------------------------
+/** True for a value that cannot be a pointer this allocator stored in a block header or a blob.
+ User space sits below 2^48 on every 64-bit target here, and blocks, blobs and pools are at least
+ MEM_BOUND_ALIGNMENT aligned, so one mask catches ASCII or a stray Int written over the pointer. */
+static inline Bool isBadHeaderPointer(const void *p)
+{
+ return ((uintptr_t)p & (~(uintptr_t)0 << 48 | (MEM_BOUND_ALIGNMENT-1))) != 0;
+}
+
//-----------------------------------------------------------------------------
/* The operating system's allocator, which sysAllocateDoNotZero and sysFree below are built on.
Windows: GlobalAlloc(GMEM_FIXED), GlobalSize and GlobalFree, as this file always called them.
@@ -541,6 +550,9 @@ public:
MemoryPoolSingleBlock *allocateSingleBlock(DECLARE_LITERALSTRING_ARG1);
void freeSingleBlock(MemoryPoolSingleBlock *block);
+ Bool holdsAddress(const void *p);
+ static void crashOnCorruptBlockHeader(MemoryPoolSingleBlock *block, MemoryPool *const *pools, Int numPools);
+
MemoryPool *getOwningPool();
Int getFreeBlockCount();
Int getUsedBlockCount();
@@ -1295,6 +1307,72 @@ void MemoryPoolBlob::removeBlobFromList(MemoryPoolBlob **ppHead, MemoryPoolBlob
this->m_nextBlob->m_prevBlob = this->m_prevBlob;
}
+//-----------------------------------------------------------------------------
+/**
+ true iff p lies inside this blob's block data.
+*/
+inline Bool MemoryPoolBlob::holdsAddress(const void *p)
+{
+ uintptr_t rawBlockSize = MemoryPoolSingleBlock::calcRawBlockSize(m_owningPool->getAllocationSize());
+ return (uintptr_t)p - (uintptr_t)m_blockData < (uintptr_t)m_totalBlocksInBlob * rawBlockSize;
+}
+
+//-----------------------------------------------------------------------------
+/**
+ Crash reports 1788, 1857 and 1867: a pool block header overwritten with ASCII, which only showed
+ up later as a wild read in DynamicMemoryAllocator::freeBytes or in the free-list walk. Log the
+ pool that really holds the block and the bytes around its header, so the report names the
+ corruption and shows what was written over it, then crash. The header's own blob pointer is what
+ is in doubt, so the holder is looked up in pools[], and the dump stays inside that blob.
+*/
+void MemoryPoolBlob::crashOnCorruptBlockHeader(MemoryPoolSingleBlock *block, MemoryPool *const *pools, Int numPools)
+{
+ MemoryPoolBlob *holder = NULL;
+ for (Int i = 0; i < numPools && holder == NULL; ++i)
+ {
+ for (MemoryPoolBlob *blob = pools[i]->m_firstBlob; blob != NULL && holder == NULL; blob = blob->m_nextBlob)
+ {
+ if (blob->holdsAddress(block))
+ holder = blob;
+ }
+ }
+
+ // without a holder the bounds are unknown, so only the header itself, which was just read
+ const char *lo = (const char *)block;
+ const char *hi = lo + sizeof(MemoryPoolSingleBlock);
+ Int poolSize = -1;
+ const char *poolName = "no pool of this allocator";
+ 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);
+ 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));
+ for (const char *row = lo; row < hi; row += 16)
+ {
+ char hex[16*3 + 1];
+ char text[16 + 1];
+ Int n = 0;
+ for (; n < 16 && row + n < hi; ++n)
+ {
+ unsigned char c = (unsigned char)row[n];
+ snprintf(hex + n*3, 4, "%02x ", c);
+ text[n] = (c >= 0x20 && c < 0x7f) ? (char)c : '.';
+ }
+ hex[n*3] = 0;
+ text[n] = 0;
+ DEBUG_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);
+ RELEASE_CRASH(reason);
+}
+
//-----------------------------------------------------------------------------
/**
grab a free block from this blob, mark it as taken, and return it.
@@ -1305,7 +1383,12 @@ MemoryPoolSingleBlock *MemoryPoolBlob::allocateSingleBlock(DECLARE_LITERALSTRING
DEBUG_ASSERTCRASH(m_firstFreeBlock, ("no free blocks available in MemoryPoolBlob"));
MemoryPoolSingleBlock *block = m_firstFreeBlock;
- m_firstFreeBlock = block->getNextFreeBlock();
+ MemoryPoolSingleBlock *next = block->getNextFreeBlock();
+ // A free block's header written over turns its next pointer into the free-list head, and the
+ // allocation after this one faults on it with nothing to say why. Catch it here instead.
+ if (block->getOwningBlob() != this || (next != NULL && !holdsAddress(next)))
+ crashOnCorruptBlockHeader(block, &m_owningPool, 1);
+ m_firstFreeBlock = next;
++m_usedBlocksInBlob;
#ifdef MEMORYPOOL_INTENSE_VERIFY
@@ -1786,7 +1869,12 @@ void MemoryPool::freeBlock(void* pBlockPtr)
const char* tagString = block->debugGetLiteralTagString();
#endif
- DEBUG_ASSERTCRASH(blob && blob->getOwningPool() == this, ("block does not belong to this pool"));
+ // in Release too: a block freed here becomes the free-list head allocateSingleBlock trusts
+ if (blob == NULL || isBadHeaderPointer(blob) || blob->getOwningPool() != this)
+ {
+ MemoryPool *self = this;
+ MemoryPoolBlob::crashOnCorruptBlockHeader(block, &self, 1);
+ }
#ifdef MEMORYPOOL_CHECKPOINTING
BlockCheckpointInfo *bi = block->debugGetCheckpointInfo();
@@ -2364,8 +2452,15 @@ void DynamicMemoryAllocator::freeBytes(void* pBlockPtr)
}
#endif MEMORYPOOL_DEBUG
- if (block->getOwningBlob())
+ if (block->getOwningBlob())
{
+ // in Release too: a header written over used to fault right here as a wild read
+ MemoryPoolBlob *blob = block->getOwningBlob();
+ if (isBadHeaderPointer(blob))
+ MemoryPoolBlob::crashOnCorruptBlockHeader(block, m_pools, m_numPools);
+ MemoryPool *pool = blob->getOwningPool();
+ if (isBadHeaderPointer(pool) || pool->getOwningFactory() != m_factory)
+ MemoryPoolBlob::crashOnCorruptBlockHeader(block, m_pools, m_numPools);
#ifdef MEMORYPOOL_DEBUG
{
USE_PERF_TIMER(MemoryPoolDebugging)
@@ -2381,7 +2476,7 @@ void DynamicMemoryAllocator::freeBytes(void* pBlockPtr)
}
}
#endif MEMORYPOOL_DEBUG
- block->getOwningBlob()->getOwningPool()->freeBlock(pBlockPtr);
+ pool->freeBlock(pBlockPtr);
}
else
{
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp
index f971f3637..4051a59b8 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp
@@ -731,22 +731,35 @@ SaveCode GameState::missionSave( void )
/** A replay's rewind checkpoint. saveGame without the save list: any path, no description, and
* nothing told to the player, since one is taken every half minute of the replay. */
// ------------------------------------------------------------------------------------------------
-void GameState::saveCheckpoint( AsciiString filepath )
+Bool GameState::saveCheckpoint( AsciiString filepath )
{
getSaveGameInfo()->saveFileType = SAVE_FILE_TYPE_NORMAL;
getSaveGameInfo()->missionMapName.clear();
XferSave xferSave;
- xferSave.open( filepath );
- xferSaveData( &xferSave, SNAPSHOT_SAVELOAD );
- xferSave.close();
+ try
+ {
+ xferSave.open( filepath );
+ xferSaveData( &xferSave, SNAPSHOT_SAVELOAD );
+ xferSave.close();
+ }
+ catch( ... )
+ {
+ // the destructor throws away what was written; a mod object whose module cannot save
+ // costs the replay its rewind, not the whole game (report 1858)
+ DEBUG_LOG(( "GameState::saveCheckpoint - '%s' could not be written\n", filepath.str() ));
+ return FALSE;
+ }
+ return TRUE;
}
// ------------------------------------------------------------------------------------------------
/** loadGame for a checkpoint, with the recorder's turn between the reset and the load: the reset
- * closes the replay, and the load's new game reads the players out of it. */
+ * closes the replay, and the load's new game reads the players out of it. FALSE when the load
+ * failed part way: the half-loaded match is cleared, as a replay's end clears it, and the player
+ * is told, so a mod object whose module cannot load ends the replay rather than the game. */
// ------------------------------------------------------------------------------------------------
-void GameState::loadCheckpoint( AsciiString filepath, const std::function< void( void ) > &afterReset )
+Bool GameState::loadCheckpoint( AsciiString filepath, const std::function< void( void ) > &afterReset )
{
TheGameStateMap->clearScratchPadMaps();
@@ -764,12 +777,45 @@ void GameState::loadCheckpoint( AsciiString filepath, const std::function< void(
TheGhostObjectManager->saveLockGhostObjects( TRUE );
TheGameLogic->setLoadingWithoutScreen( TRUE );
- xferSaveData( &xferLoad, SNAPSHOT_SAVELOAD );
+ Bool error = FALSE;
+ try
+ {
+ xferSaveData( &xferLoad, SNAPSHOT_SAVELOAD );
+ }
+ catch( ... )
+ {
+ error = TRUE;
+ }
TheGameLogic->setLoadingWithoutScreen( FALSE );
xferLoad.close();
TheGhostObjectManager->saveLockGhostObjects( FALSE );
- gameStatePostProcessLoad();
+ if( !error )
+ {
+ try
+ {
+ gameStatePostProcessLoad();
+ }
+ catch( ... )
+ {
+ error = TRUE;
+ }
+ }
+
+ if( error )
+ {
+ DEBUG_LOG(( "GameState::loadCheckpoint - '%s' could not be loaded, the replay stops\n", filepath.str() ));
+ const AsciiString replayFile = TheRecorder->getCurrentReplayFilename();
+ TheGameLogic->clearGameData();
+
+ UnicodeString ufilepath;
+ ufilepath.translate( replayFile );
+ UnicodeString msg;
+ msg.format( TheGameText->fetch( "GUI:ErrorLoadingGame" ), ufilepath.str() );
+ MessageBoxOk( TheGameText->fetch( "GUI:Error" ), msg, NULL );
+ return FALSE;
+ }
+ return TRUE;
}
// ------------------------------------------------------------------------------------------------
@@ -1503,6 +1549,9 @@ void GameState::xferSaveData( Xfer *xfer, SnapshotType which )
catch( ... )
{
+ // the DEBUG_CRASH is compiled out of a release build; the module that threw logged itself
+ DEBUG_LOG(( "GameState::xferSaveData - error saving block '%s' in file '%s'\n",
+ blockName.str(), xfer->getIdentifier() ));
DEBUG_CRASH(( "Error saving block '%s' in file '%s'\n",
blockName.str(), xfer->getIdentifier() ));
throw;
@@ -1583,6 +1632,9 @@ void GameState::xferSaveData( Xfer *xfer, SnapshotType which )
catch( ... )
{
+ // the DEBUG_CRASH is compiled out of a release build; the module that threw logged itself
+ DEBUG_LOG(( "GameState::xferSaveData - error loading block '%s' in file '%s'\n",
+ blockInfo->blockName.str(), xfer->getIdentifier() ));
DEBUG_CRASH(( "Error loading block '%s' in file '%s'\n",
blockInfo->blockName.str(), xfer->getIdentifier() ));
throw;
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp
index e3d4cd7cc..917f42d33 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp
@@ -34,6 +34,7 @@
#include "Common/StackDump.h"
#include "Common/Debug.h"
+#include "Common/FileWriteQueue.h"
//*****************************************************************************
@@ -426,10 +427,76 @@ void WriteStackLine(void*address, void (*callback)(const char*))
}
+static HANDLE gsCrashRecordHandle = NULL; // the debug log's own handle, set when it opens
+
+void SetCrashRecordHandle( void *handle )
+{
+ gsCrashRecordHandle = (HANDLE)handle;
+}
+
+static char *appendText( char *out, const char *text )
+{
+ while (*text)
+ *out++ = *text++;
+ return out;
+}
+
+static char *appendHex( char *out, unsigned long long value )
+{
+ out = appendText( out, "0x" );
+ for (int shift = 60; shift >= 0; shift -= 4)
+ *out++ = "0123456789ABCDEF"[(value >> shift) & 15];
+ return out;
+}
+
+/* Written before anything that allocates, locks or formats. A second fault inside the dump below, or
+ a lock the faulting thread already held, left a log with no trace of the crash at all, its last
+ queued second included (a 0xC0000005 report whose tail was an ordinary frame). A stack buffer, no
+ CRT, and WriteFile straight into the log file past its queue; the queued lines follow it. */
+static void writeCrashRecord( EXCEPTION_POINTERS *e_info )
+{
+ if (gsCrashRecordHandle == NULL)
+ return; // no log file open
+ void *pc = e_info->ExceptionRecord->ExceptionAddress;
+ void *base = NULL;
+ RtlPcToFileHeader( pc, &base );
+
+ char record[ 256 ];
+ char *out = appendText( record, "\r\nEXCEPTION RECORD code " );
+ out = appendHex( out, e_info->ExceptionRecord->ExceptionCode );
+ out = appendText( out, " at " );
+ out = appendHex( out, (ULONG_PTR)pc );
+ out = appendText( out, " module " );
+ out = appendHex( out, (ULONG_PTR)base );
+ out = appendText( out, " + " );
+ out = appendHex( out, (ULONG_PTR)pc - (ULONG_PTR)base );
+ out = appendText( out, " thread " );
+ out = appendHex( out, GetCurrentThreadId() );
+ out = appendText( out, "\r\n" );
+ // At the end each time: the log writer may be mid-flush, and a write at the handle's own pointer
+ // would land on its bytes.
+ DWORD written;
+ SetFilePointer( gsCrashRecordHandle, 0, NULL, FILE_END );
+ WriteFile( gsCrashRecordHandle, record, (DWORD)(out - record), &written, NULL );
+
+ // The module's name second: GetModuleFileName takes the loader lock, which the faulting thread may hold.
+ char name[ MAX_PATH + 2 ];
+ const DWORD length = base != NULL ? GetModuleFileNameA( (HMODULE)base, name, MAX_PATH ) : 0;
+ if (length != 0)
+ {
+ name[ length ] = '\r';
+ name[ length + 1 ] = '\n';
+ SetFilePointer( gsCrashRecordHandle, 0, NULL, FILE_END );
+ WriteFile( gsCrashRecordHandle, name, length + 2, &written, NULL );
+ }
+}
+
//*****************************************************************************
//*****************************************************************************
void DumpExceptionInfo( unsigned int u, EXCEPTION_POINTERS* e_info )
{
+ writeCrashRecord( e_info );
+ FileWriteQueue::flushAll(); // the last second of queued lines, before the dump and its stack walk, which can fault
DEBUG_LOG(( "\n********** EXCEPTION DUMP ****************\n" ));
/*
** List of possible exceptions
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Thing/Module.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Thing/Module.cpp
index f4a13e7ae..c3f6bedcd 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/Thing/Module.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/Thing/Module.cpp
@@ -248,24 +248,41 @@ void UpgradeMuxData::performUpgradeFX(Object* obj) const
}
//-------------------------------------------------------------------------------------------------
-void UpgradeMuxData::muxDataProcessUpgradeRemoval(Object* obj) const
+/** The upgrade a TriggeredBy, ConflictsWith or RemovesUpgrades line names, or NULL when there is no
+ * such upgrade. EA threw INI_INVALID_DATA here, lazily, on the first object of the template, so a
+ * mod naming an upgrade it never defines killed the map load with nothing in the crash report
+ * (reports 1893-1899). The name is said in the log and skipped instead, and looked up again the
+ * next time: a map.ini can define the upgrade for one match, so a miss is never kept in the shared
+ * module data, or a machine that played a match without that map would go on without the upgrade
+ * that a fresh machine has. */
+//-------------------------------------------------------------------------------------------------
+static const UpgradeTemplate *findMuxUpgrade( const AsciiString &name, const char *field, const Module *module, const Object *obj )
{
- if( !m_removalUpgradeNames.empty() )
+ const UpgradeTemplate *upgrade = TheUpgradeCenter->findUpgrade( name );
+ if( !upgrade && !name.isEmpty() && !name.isNone() )
{
- std::vector<AsciiString>::const_iterator it;
- for( it = m_removalUpgradeNames.begin();
- it != m_removalUpgradeNames.end();
- it++)
- {
- const UpgradeTemplate* theTemplate = TheUpgradeCenter->findUpgrade( *it );
- if( !theTemplate && !it->isEmpty() && !it->isNone())
- {
- DEBUG_CRASH(("An upgrade module references %s, which is not an Upgrade", it->str()));
- throw INI_INVALID_DATA;
- }
-
- obj->removeUpgrade(theTemplate);
- }
+ // said once per object, module and name; the set only quiets the log and decides nothing
+ static std::set< std::string > said;
+ AsciiString key;
+ key.format( "%s %s %s %s", obj->getTemplate()->getName().str(),
+ KEYNAME( module->getModuleTagNameKey() ).str(), field, name.str() );
+ if( said.insert( key.str() ).second )
+ DEBUG_LOG(( "%s %s of %s: %s names %s, which is not an Upgrade; ignored\n",
+ KEYNAME( module->getModuleNameKey() ).str(), KEYNAME( module->getModuleTagNameKey() ).str(),
+ obj->getTemplate()->getName().str(), field, name.str() ));
+ }
+ return upgrade;
+}
+
+//-------------------------------------------------------------------------------------------------
+void UpgradeMuxData::muxDataProcessUpgradeRemoval(ObjectModule* module) const
+{
+ std::vector<AsciiString>::const_iterator it;
+ for( it = m_removalUpgradeNames.begin(); it != m_removalUpgradeNames.end(); ++it )
+ {
+ const UpgradeTemplate* theTemplate = findMuxUpgrade( *it, "RemovesUpgrades", module, module->getObject() );
+ if( theTemplate )
+ module->getObject()->removeUpgrade(theTemplate);
}
}
@@ -286,40 +303,38 @@ Bool UpgradeMuxData::isTriggeredBy(const std::string &upgrade) const
}
//-------------------------------------------------------------------------------------------------
-void UpgradeMuxData::getUpgradeActivationMasks(UpgradeMaskType& activation, UpgradeMaskType& conflicting) const
+void UpgradeMuxData::getUpgradeActivationMasks(UpgradeMaskType& activation, UpgradeMaskType& conflicting, const ObjectModule* module) const
{
// already computed.
if (!m_activationUpgradeNames.empty() || !m_conflictingUpgradeNames.empty())
{
m_activationMask.clear();
m_conflictingMask.clear();
-
+
+ // An upgrade that does not exist adds nothing to either mask. The masks are only cached once
+ // every name was found: a miss is looked up again on the next call (see findMuxUpgrade).
+ Bool allFound = TRUE;
std::vector<AsciiString>::const_iterator it;
for( it = m_activationUpgradeNames.begin();
it != m_activationUpgradeNames.end();
it++)
{
- const UpgradeTemplate* theTemplate = TheUpgradeCenter->findUpgrade( *it );
- if( !theTemplate && !it->isEmpty() && !it->isNone())
- {
- DEBUG_CRASH(("An upgrade module references %s, which is not an Upgrade", it->str()));
- throw INI_INVALID_DATA;
- }
-
- m_activationMask.set( theTemplate->getUpgradeMask() );
+ const UpgradeTemplate* theTemplate = findMuxUpgrade( *it, "TriggeredBy", module, module->getObject() );
+ if( theTemplate )
+ m_activationMask.set( theTemplate->getUpgradeMask() );
+ else if( !it->isEmpty() && !it->isNone() )
+ allFound = FALSE;
}
for( it = m_conflictingUpgradeNames.begin();
it != m_conflictingUpgradeNames.end();
it++)
{
- const UpgradeTemplate* theTemplate = TheUpgradeCenter->findUpgrade( *it );
- if( !theTemplate && !it->isEmpty() && !it->isNone())
- {
- DEBUG_CRASH(("An upgrade module references %s, which is not an Upgrade", it->str()));
- throw INI_INVALID_DATA;
- }
- m_conflictingMask.set( theTemplate->getUpgradeMask() );
+ const UpgradeTemplate* theTemplate = findMuxUpgrade( *it, "ConflictsWith", module, module->getObject() );
+ if( theTemplate )
+ m_conflictingMask.set( theTemplate->getUpgradeMask() );
+ else if( !it->isEmpty() && !it->isNone() )
+ allFound = FALSE;
}
// We set the trigger upgrade names with the activationUpgradeNames entries to be used later.
@@ -327,8 +342,11 @@ void UpgradeMuxData::getUpgradeActivationMasks(UpgradeMaskType& activation, Upgr
m_triggerUpgradeNames = m_activationUpgradeNames;
//Clear the names now that we've cached the values!
- m_activationUpgradeNames.clear();
- m_conflictingUpgradeNames.clear();
+ if( allFound )
+ {
+ m_activationUpgradeNames.clear();
+ m_conflictingUpgradeNames.clear();
+ }
}
activation = m_activationMask;
conflicting = m_conflictingMask;
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp
index 89c49deae..38d315ffd 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp
@@ -54,6 +54,7 @@
#include "Common/Radar.h"
#include "Common/RandomValue.h"
#include "Common/Science.h"
+#include "Common/StackDump.h" // g_LastErrorDump
#include "Common/ThingTemplate.h"
#include "Common/ThingFactory.h"
#include "Common/ThingSort.h"
@@ -631,6 +632,14 @@ void ThingTemplate::parseModuleName(INI* ini, void *instance, void* store, const
ini->setMissingReference(FALSE);
ModuleData* data = TheModuleFactory->newModuleDataFromINI(ini, tokenStr, type, moduleTagStr);
+ if (data == NULL)
+ {
+ // a module name this exe does not have, usually a mod written for another build
+ g_LastErrorDump.format("[LINE: %d - FILE: '%s'] Unknown module '%s' (%s) on %s\n",
+ ini->getLineNum(), ini->getFilename().str(), tokenStr.str(), moduleTagStr.str(), self->getName().str());
+ DEBUG_LOG(("%s", g_LastErrorDump.str()));
+ throw INI_UNKNOWN_TOKEN;
+ }
if (ini->hasMissingReference())
{
/* read to its End and dropped: a special power module with no template faults placing the
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
index c995cdd11..7b8e1083b 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
@@ -1875,6 +1875,8 @@ static const char *const REPLAY_CHECKPOINT_FOLDER = "ReplayRewind";
* reason as the seek frame: loading one resets the interface. */
static std::map< UnsignedInt, ReplayCheckpoint > TheReplayCheckpoints;
static AsciiString TheReplayCheckpointsOf;
+/// a checkpoint of this replay failed to save, so no more are tried: each try is a whole save
+static Bool TheReplayCheckpointsFailed = FALSE;
/** A seek back is carried out on the next client pass rather than in the click: the load resets the
* message stream, and the click is a message the stream is in the middle of handing round. */
@@ -1918,6 +1920,7 @@ static void forgetReplayCheckpoints( void )
TheLocalFileSystem->deleteFile( path.str() );
}
TheReplayCheckpoints.clear();
+ TheReplayCheckpointsFailed = FALSE;
}
static void collectPostedCRCs( GameMessageList *list, std::vector< std::pair< Int, Bool > > &crcs )
@@ -1942,7 +1945,14 @@ static void takeReplayCheckpoint( UnsignedInt frame )
// the command list first: what it holds reaches the logic ahead of what the stream still holds
collectPostedCRCs( TheCommandList, checkpoint.postedCRCs );
collectPostedCRCs( TheMessageStream, checkpoint.postedCRCs );
- TheGameState->saveCheckpoint( checkpoint.path );
+ if( !TheGameState->saveCheckpoint( checkpoint.path ) )
+ {
+ // the rewind keeps the checkpoints before this one
+ DEBUG_LOG(( "REPLAY CHECKPOINT frame %u failed, no more checkpoints for this replay\n", frame ));
+ TheReplayCheckpoints.erase( frame );
+ TheReplayCheckpointsFailed = TRUE;
+ return;
+ }
DEBUG_LOG(( "REPLAY CHECKPOINT frame %u in %u ms\n", frame, (UnsignedInt)( Clock_Milliseconds() - startMs ) ));
}
@@ -1974,8 +1984,14 @@ static void rewindReplay( UnsignedInt target )
const Int followed = TheObserverCamera.getFollowedPlayerIndex();
const Bool fog = TheObserverCamera.isFogOn();
- TheGameState->loadCheckpoint( checkpoint.path,
- [ & ]() { TheRecorder->resumePlayback( replayFile, checkpoint.cursor ); } );
+ // a failed load has cleared the match and said so; nothing is left to seek in or look at
+ if( !TheGameState->loadCheckpoint( checkpoint.path,
+ [ & ]() { TheRecorder->resumePlayback( replayFile, checkpoint.cursor ); } ) )
+ {
+ TheReplaySeekFrame = 0;
+ TheWritableGlobalData->m_TiVOFastMode = FALSE;
+ return;
+ }
SetGameLogicRandomState( checkpoint.random );
TheObserverCamera.setMode( cameraMode );
@@ -2031,7 +2047,7 @@ static void updateReplaySeek( void )
}
const UnsignedInt frame = TheGameLogic->getFrame();
- if( TheRecorder->hasPlaybackLeft() && frame > 0
+ if( TheRecorder->hasPlaybackLeft() && frame > 0 && !TheReplayCheckpointsFailed
&& ( TheReplayCheckpoints.empty() || frame >= TheReplayCheckpoints.rbegin()->first + REPLAY_CHECKPOINT_FRAMES ) )
takeReplayCheckpoint( frame );
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
index eeb14592b..7ab7683b7 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
@@ -4496,6 +4496,26 @@ void Object::crc( Xfer *xfer )
} // end crc
+//-------------------------------------------------------------------------------------------------
+/** One module's xfer, which names the module when it throws. A release build compiles the
+ * DEBUG_CRASH of GameState::xferSaveData out, so without this a save, a load or a replay
+ * checkpoint that died in a mod's module said only the last "Xfer Object" line (report 1858). */
+//-------------------------------------------------------------------------------------------------
+static void xferModule( Xfer *xfer, BehaviorModule *module, const Object *obj )
+{
+ try
+ {
+ xfer->xferSnapshot( module );
+ }
+ catch( ... )
+ {
+ DEBUG_LOG(( "Object::xfer - module %s (%s) of %s id=%d failed to xfer\n",
+ KEYNAME( module->getModuleNameKey() ).str(), KEYNAME( module->getModuleTagNameKey() ).str(),
+ obj->getTemplate()->getName().str(), obj->getID() ));
+ throw;
+ }
+}
+
//-------------------------------------------------------------------------------------------------
/** Object xfer implemtation
* Version Info:
@@ -4839,7 +4859,7 @@ void Object::xfer( Xfer *xfer )
xfer->beginBlock();
// xfer data
- xfer->xferSnapshot( module );
+ xferModule( xfer, module, this );
// end data block
xfer->endBlock();
@@ -4895,7 +4915,7 @@ void Object::xfer( Xfer *xfer )
{
// xfer the data into this module
- xfer->xferSnapshot( module );
+ xferModule( xfer, module, this );
} // end else
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp
index 751b05381..2f7493692 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp
@@ -688,7 +688,8 @@ void MissileAIUpdate::doKillState(void)
{
Coord3D aim;
Weapon::pointFromBodyOffset(getGoalObject(), m_aimOffset, aim);
- Real closeEnough = curLoco->getMaxSpeedForCondition(BODY_PRISTINE);
+ // a missile with no locomotor (an immobile hazard a mod fires as one) gets the 1.0 the idle check below uses
+ Real closeEnough = curLoco ? curLoco->getMaxSpeedForCondition(BODY_PRISTINE) : 1.0f;
const Coord3D* pos = obj->getPosition();
// over the point and on the body: the height the locomotor holds over a goal is its own
if (sqr(aim.x - pos->x) + sqr(aim.y - pos->y) < sqr(closeEnough)
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DemoTrapUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DemoTrapUpdate.cpp
index 54da24f66..22c6f6424 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DemoTrapUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DemoTrapUpdate.cpp
@@ -155,8 +155,14 @@ UpdateSleepTime DemoTrapUpdate::update()
return UPDATE_SLEEP_NONE;
}
- //Get the current weapon slot -- this determines what mode we're in.
- WeaponSlotType weaponSlot = getObject()->getCurrentWeapon()->getWeaponSlot();
+ //Get the current weapon slot -- this determines what mode we're in. A mod's trap
+ //with no weapon in its current set has no mode, so it waits for one.
+ const Weapon *currentWeapon = getObject()->getCurrentWeapon();
+ if( !currentWeapon )
+ {
+ return UPDATE_SLEEP_NONE;
+ }
+ WeaponSlotType weaponSlot = currentWeapon->getWeaponSlot();
if( weaponSlot == data->m_detonationWeaponSlot )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/CRCSnapshotRing.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/CRCSnapshotRing.cpp
index 6b9283ba3..75b6cb13d 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/CRCSnapshotRing.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/CRCSnapshotRing.cpp
@@ -41,9 +41,11 @@ void CRCSnapshotRing::clear( void )
for( Int s = 0; s < CRC_SECTION_COUNT; ++s )
m_snapshots[i].m_sectionCRC[s] = 0;
m_snapshots[i].m_players.clear();
+ m_snapshots[i].m_commands.clear();
}
m_writeSlot = -1;
m_numSnapshots = 0;
+ m_pendingCommands.clear();
}
//-------------------------------------------------------------------------------------------------
@@ -67,6 +69,9 @@ void CRCSnapshotRing::beginSnapshot( UnsignedInt frame )
for( Int s = 0; s < CRC_SECTION_COUNT; ++s )
snap.m_sectionCRC[s] = 0;
snap.m_players.clear();
+ // the commands since the last snapshot belong to this one; swap so both vectors keep their capacity
+ snap.m_commands.swap( m_pendingCommands );
+ m_pendingCommands.clear();
}
//-------------------------------------------------------------------------------------------------
@@ -123,6 +128,32 @@ void CRCSnapshotRing::endSnapshot( UnsignedInt totalCRC, UnsignedInt randomSeed
++m_numSnapshots;
}
+//-------------------------------------------------------------------------------------------------
+/** A run of one player's commands of one type on one frame folds into one entry, so a selection
+ * change and its order cost two entries, not one per message. */
+//-------------------------------------------------------------------------------------------------
+void CRCSnapshotRing::addCommand( UnsignedInt frame, Int player, Int type, UnsignedInt argHash )
+{
+ if( !m_pendingCommands.empty() )
+ {
+ CRCCommandEntry &last = m_pendingCommands.back();
+ if( last.m_frame == frame && last.m_player == player && last.m_type == type )
+ {
+ ++last.m_count;
+ last.m_argHash = last.m_argHash * 33 + argHash;
+ return;
+ }
+ }
+
+ CRCCommandEntry entry;
+ entry.m_frame = frame;
+ entry.m_player = player;
+ entry.m_type = type;
+ entry.m_count = 1;
+ entry.m_argHash = argHash;
+ m_pendingCommands.push_back( entry );
+}
+
//-------------------------------------------------------------------------------------------------
Int CRCSnapshotRing::getNewestSlot( void ) const
{
@@ -174,6 +205,22 @@ Int CRCSnapshotRing::findSlotByCRC( UnsignedInt crc ) const
return -1;
}
+//-------------------------------------------------------------------------------------------------
+/** CRC messages carry the frame they were computed for, so the frame that mismatched is known
+ * exactly and needs no lookup by value. */
+//-------------------------------------------------------------------------------------------------
+Int CRCSnapshotRing::findSlotByFrame( UnsignedInt frame ) const
+{
+ for( Int n = 0; n < m_numSnapshots; ++n )
+ {
+ Int slot = getNthNewestSlot( n );
+ if( slot >= 0 && m_snapshots[ slot ].m_frame == frame )
+ return slot;
+ }
+
+ return -1;
+}
+
//-------------------------------------------------------------------------------------------------
const CRCSnapshot *CRCSnapshotRing::getSlot( Int slot ) const
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
index a110628cb..4a9464ec6 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
@@ -2784,6 +2784,41 @@ void GameLogic::processDestroyList( void )
//in the request for a new deletion (sub-object), the new object was added to the end of this list.
}
+//-------------------------------------------------------------------------------------------------
+/** One executed network command into the digest the next CRC snapshot carries. Reads the message
+ * and nothing else, so logic state and the CRC are untouched. MSG_LOGIC_CRC is left out: it orders
+ * nothing, and its argument is the very number the digest is there to explain. */
+//-------------------------------------------------------------------------------------------------
+static void digestCommand( CRCSnapshotRing &ring, UnsignedInt frame, const GameMessage *msg )
+{
+ const GameMessage::Type type = msg->getType();
+ if( type <= GameMessage::MSG_BEGIN_NETWORK_MESSAGES || type >= GameMessage::MSG_END_NETWORK_MESSAGES
+ || type == GameMessage::MSG_LOGIC_CRC )
+ return;
+
+ // FNV-1a over each argument's own bytes, never the whole union, whose unused tail is whatever was there
+ UnsignedInt hash = 2166136261u;
+ for( Int i = 0; i < msg->getArgumentCount(); ++i )
+ {
+ const GameMessageArgumentType *arg = msg->getArgument( i );
+ size_t size = sizeof( arg->integer );
+ switch( msg->getArgumentDataType( i ) )
+ {
+ case ARGUMENTDATATYPE_BOOLEAN: size = sizeof( arg->boolean ); break;
+ case ARGUMENTDATATYPE_LOCATION: size = sizeof( arg->location ); break;
+ case ARGUMENTDATATYPE_PIXEL: size = sizeof( arg->pixel ); break;
+ case ARGUMENTDATATYPE_PIXELREGION: size = sizeof( arg->pixelRegion ); break;
+ case ARGUMENTDATATYPE_WIDECHAR: size = sizeof( arg->wChar ); break;
+ default: break;
+ }
+ const UnsignedByte *bytes = (const UnsignedByte *)arg;
+ for( size_t b = 0; b < size; ++b )
+ hash = ( hash ^ bytes[b] ) * 16777619u;
+ }
+
+ ring.addCommand( frame, msg->getPlayerIndex(), (Int)type, hash );
+}
+
//-------------------------------------------------------------------------------------------------
/** Process the command list passed to the logic from the network */
//-------------------------------------------------------------------------------------------------
@@ -2794,11 +2829,16 @@ void GameLogic::processCommandList( CommandList *list )
GameMessage* msg;
+ // the inputs beside the CRC snapshots (CRCSnapshotRing.h); only read by writeMismatchDump
+ const Bool digestCommands = TheRecorder->isMultiplayer() && getGameMode() != GAME_SHELL && getGameMode() != GAME_NONE;
+
for( msg = list->getFirstMessage(); msg; msg = msg->next() )
{
#ifdef _DEBUG
DEBUG_ASSERTCRASH(msg != NULL && msg != (GameMessage*)0xdeadbeef, ("bad msg"));
#endif
+ if( digestCommands )
+ digestCommand( m_crcSnapshots, m_frame, msg );
logicMessageDispatcher( msg, NULL );
}
@@ -2809,6 +2849,7 @@ void GameLogic::processCommandList( CommandList *list )
if (m_shouldValidateCRCs && !TheNetwork->sawCRCMismatch())
{
Bool sawCRCMismatch = FALSE;
+ UnsignedInt mismatchFrame = 0;
Int numPlayers = 0;
DEBUG_ASSERTCRASH(TheNetwork, ("No Network!"));
if (TheNetwork)
@@ -2829,48 +2870,61 @@ void GameLogic::processCommandList( CommandList *list )
EA handed the player index straight to isPlayerConnected(). A player index with no slot
behind it (no GameInfo at all, for instance) counts as present rather than as gone: the
point of this is to stop blaming people who left, not to switch the check off. */
- Bool reported[MAX_PLAYER_COUNT];
Bool connected[MAX_PLAYER_COUNT];
- UnsignedInt crcs[MAX_PLAYER_COUNT];
for (Int p = 0; p < MAX_PLAYER_COUNT; ++p)
{
- reported[p] = FALSE;
- crcs[p] = 0;
const Int slot = ThePlayerList->getSlotIndex(p);
connected[p] = (slot < 0) ? TRUE : TheNetwork->isPlayerConnected(slot);
}
- for (std::map<Int, UnsignedInt>::const_iterator crcIt = m_cachedCRCs.begin();
- crcIt != m_cachedCRCs.end(); ++crcIt)
+
+ /* Only CRCs of one logic frame are held against each other. A frame some connected player
+ sent no CRC for on this execution frame is too few, and skipped: its CRCs landed on
+ different execution frames (MSG_LOGIC_CRC in update()), and nobody disagreed. */
+ for (std::map<UnsignedInt, std::map<Int, UnsignedInt> >::const_iterator frameIt = m_cachedCRCs.begin();
+ frameIt != m_cachedCRCs.end() && !sawCRCMismatch; ++frameIt)
{
- if (crcIt->first >= 0 && crcIt->first < MAX_PLAYER_COUNT)
+ Bool reported[MAX_PLAYER_COUNT];
+ UnsignedInt crcs[MAX_PLAYER_COUNT];
+ for (Int p = 0; p < MAX_PLAYER_COUNT; ++p)
{
- reported[crcIt->first] = TRUE;
- crcs[crcIt->first] = crcIt->second;
+ reported[p] = FALSE;
+ crcs[p] = 0;
+ }
+ for (std::map<Int, UnsignedInt>::const_iterator crcIt = frameIt->second.begin();
+ crcIt != frameIt->second.end(); ++crcIt)
+ {
+ if (crcIt->first >= 0 && crcIt->first < MAX_PLAYER_COUNT)
+ {
+ reported[crcIt->first] = TRUE;
+ crcs[crcIt->first] = crcIt->second;
+ }
}
- }
- switch (crcAgreement( reported, crcs, connected, MAX_PLAYER_COUNT, numPlayers ))
- {
- case CRC_AGREEMENT_TOO_FEW:
- DEBUG_LOG(("Only %d CRCs from %d connected players on frame %d - not comparing\n",
- m_cachedCRCs.size(), numPlayers, m_frame));
- break;
+ switch (crcAgreement( reported, crcs, connected, MAX_PLAYER_COUNT, numPlayers ))
+ {
+ case CRC_AGREEMENT_TOO_FEW:
+ DEBUG_LOG(("Only %d CRCs of frame %d from %d connected players on frame %d - not comparing\n",
+ frameIt->second.size(), frameIt->first, numPlayers, m_frame));
+ break;
- case CRC_AGREEMENT_MISMATCH:
- DEBUG_CRASH(("CRC mismatch!"));
- sawCRCMismatch = TRUE;
- break;
+ case CRC_AGREEMENT_MISMATCH:
+ DEBUG_CRASH(("CRC mismatch!"));
+ sawCRCMismatch = TRUE;
+ mismatchFrame = frameIt->first;
+ break;
- case CRC_AGREEMENT_AGREE:
- break;
+ case CRC_AGREEMENT_AGREE:
+ break;
+ }
}
}
if (sawCRCMismatch)
{
#ifdef DEBUG_LOGGING
- DEBUG_LOG(("CRC Mismatch - saw %d CRCs from %d players\n", m_cachedCRCs.size(), numPlayers));
- for (std::map<Int, UnsignedInt>::const_iterator crcIt = m_cachedCRCs.begin(); crcIt != m_cachedCRCs.end(); ++crcIt)
+ const std::map<Int, UnsignedInt> &mismatched = m_cachedCRCs[mismatchFrame];
+ DEBUG_LOG(("CRC Mismatch - saw %d CRCs of frame %d from %d players\n", mismatched.size(), mismatchFrame, numPlayers));
+ for (std::map<Int, UnsignedInt>::const_iterator crcIt = mismatched.begin(); crcIt != mismatched.end(); ++crcIt)
{
Player *player = ThePlayerList->getNthPlayer(crcIt->first);
DEBUG_LOG(("CRC from player %d (%s) = %X\n", crcIt->first,
@@ -2880,7 +2934,7 @@ void GameLogic::processCommandList( CommandList *list )
TheNetwork->setSawCRCMismatch();
// write down what the world looked like on the frame that diverged, while we still have it
- writeMismatchDump( numPlayers );
+ writeMismatchDump( numPlayers, mismatchFrame );
/* Playing on is the worst of the options: two worlds that already disagree keep diverging
for the rest of the match, every order after this point lands somewhere different on
@@ -2924,23 +2978,35 @@ static AsciiString lobbyOptionsWithoutAddresses( const AsciiString &options )
return AsciiString( out.c_str() );
}
+// ------------------------------------------------------------------------------------------------
+/** One number for a snapshot's command digest, so a line per frame says whether two dumps were
+ * given the same orders on it. */
+// ------------------------------------------------------------------------------------------------
+static UnsignedInt commandDigest( const CRCSnapshot *snap )
+{
+ UnsignedInt hash = 2166136261u;
+ for( size_t i = 0; i < snap->m_commands.size(); ++i )
+ {
+ const CRCCommandEntry &c = snap->m_commands[i];
+ const UnsignedInt fields[] = { c.m_frame, (UnsignedInt)c.m_player, (UnsignedInt)c.m_type, c.m_count, c.m_argHash };
+ for( size_t f = 0; f < sizeof( fields ) / sizeof( fields[0] ); ++f )
+ hash = ( hash ^ fields[f] ) * 16777619u;
+ }
+ return hash;
+}
+
// ------------------------------------------------------------------------------------------------
/** A mismatch says the worlds diverged; it does not say where. This writes down everything we
* kept about the frame that diverged, so that two players' dumps can be diffed: the first object
* whose running CRC differs is the object whose state differs, and the fields printed next to it
* usually say how. Every machine writes its own file at the same frame. */
// ------------------------------------------------------------------------------------------------
-void GameLogic::writeMismatchDump( Int numPlayers )
+void GameLogic::writeMismatchDump( Int numPlayers, UnsignedInt crcFrame )
{
- /* The CRCs just compared were computed the run-ahead's worth of frames ago. Ours is one of
- them, so whichever retained snapshot carries one of these values names that frame exactly. */
- Int slot = -1;
- for( std::map<Int, UnsignedInt>::const_iterator crcIt = m_cachedCRCs.begin();
- crcIt != m_cachedCRCs.end() && slot < 0; ++crcIt )
- {
- slot = m_crcSnapshots.findSlotByCRC( crcIt->second );
- }
- // a run-ahead longer than the ring (a high ping at the start of a match) leaves no compared CRC in it
+ // the CRCs just compared were computed the run-ahead's worth of frames ago, on crcFrame
+ const std::map<Int, UnsignedInt> &compared = m_cachedCRCs[ crcFrame ];
+ Int slot = m_crcSnapshots.findSlotByFrame( crcFrame );
+ // a run-ahead longer than the ring (a high ping at the start of a match) leaves that frame out of it
const Bool slotFromCRC = slot >= 0;
if( slot < 0 )
slot = m_crcSnapshots.getNewestSlot();
@@ -2958,7 +3024,7 @@ void GameLogic::writeMismatchDump( Int numPlayers )
fprintf( fp, "Mismatch detected on frame %d\n", m_frame );
fprintf( fp, "Local player is slot %d of %d connected players; %d CRCs were compared\n",
- TheNetwork ? TheNetwork->getLocalPlayerID() : 0, numPlayers, m_cachedCRCs.size() );
+ TheNetwork ? TheNetwork->getLocalPlayerID() : 0, numPlayers, compared.size() );
// every player's dump carries the same two, which is how the reports from one match are paired up
fprintf( fp, "Map %s, seed %d\n", TheGameInfo->getMap().str(), TheGameInfo->getSeed() );
// what both ends agreed in the lobby and whether this machine read the map's rules file: two dumps
@@ -2980,8 +3046,9 @@ void GameLogic::writeMismatchDump( Int numPlayers )
fprintf( fp, "Simulation trig fingerprint 0x%8.8X\n\n",
SimulationMathCrc::calculateSimulationTrig() );
- for( std::map<Int, UnsignedInt>::const_iterator crcIt = m_cachedCRCs.begin();
- crcIt != m_cachedCRCs.end(); ++crcIt )
+ fprintf( fp, "CRCs of frame %d:\n", crcFrame );
+ for( std::map<Int, UnsignedInt>::const_iterator crcIt = compared.begin();
+ crcIt != compared.end(); ++crcIt )
{
Player *player = ThePlayerList->getNthPlayer( crcIt->first );
AsciiString name;
@@ -3003,7 +3070,7 @@ void GameLogic::writeMismatchDump( Int numPlayers )
fprintf( fp, "\nDiverging frame is %d (world CRC 0x%8.8X, logic random seed CRC 0x%8.8X, %d objects)\n",
snap->m_frame, snap->m_totalCRC, snap->m_randomSeed, snap->m_objects.size() );
if( !slotFromCRC )
- fprintf( fp, "No retained frame carries a compared CRC, so this is the newest one; compare it with the same frame in the other dump.\n" );
+ fprintf( fp, "Frame %d is no longer retained, so this is the newest one; compare it with the same frame in the other dump.\n", crcFrame );
// the parts getCRC folds in, in its order (CRCSection): the first line that differs between two
// dumps is the part that diverged, and when it is not the objects the table below will agree
@@ -3031,6 +3098,19 @@ void GameLogic::writeMismatchDump( Int numPlayers )
}
fprintf( fp, "\n" );
+ /* What the machine was told to do between the frame before and this one (CRCSnapshot::m_commands).
+ Same lines in both dumps and a different world: the same orders ran differently. A line that
+ differs: the machines were given different orders. */
+ fprintf( fp, "Commands executed since the frame before (digest 0x%8.8X):\n%7s %7s %6s %10s %s\n",
+ commandDigest( snap ), "frame", "player", "count", "argHash", "command" );
+ for( size_t i = 0; i < snap->m_commands.size(); ++i )
+ {
+ const CRCCommandEntry &c = snap->m_commands[i];
+ fprintf( fp, "%7u %7d %6u 0x%8.8X %s\n", c.m_frame, c.m_player, c.m_count, c.m_argHash,
+ GameMessage::getCommandTypeAsAsciiString( (GameMessage::Type)c.m_type ).str() );
+ }
+ fprintf( fp, "\n" );
+
fprintf( fp, "Diff this section against another player's file; the first differing running CRC is the object that diverged.\n\n" );
fprintf( fp, "%6s %8s %10s %12s %12s %12s %10s %s\n",
"index", "objectID", "runningCRC", "x", "y", "z", "health", "template" );
@@ -3050,8 +3130,8 @@ void GameLogic::writeMismatchDump( Int numPlayers )
const CRCSnapshot *other = m_crcSnapshots.getSlot( m_crcSnapshots.getNthNewestSlot( n ) );
if( other == NULL || other == snap )
continue;
- fprintf( fp, " frame %d: world CRC 0x%8.8X, %d objects\n",
- other->m_frame, other->m_totalCRC, other->m_objects.size() );
+ fprintf( fp, " frame %d: world CRC 0x%8.8X, %d objects, %d command runs before it, digest 0x%8.8X\n",
+ other->m_frame, other->m_totalCRC, other->m_objects.size(), other->m_commands.size(), commandDigest( other ) );
}
fclose( fp );
@@ -4950,6 +5030,13 @@ void GameLogic::update( void )
GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_LOGIC_CRC );
msg->appendIntegerArgument( m_CRC );
msg->appendBooleanArgument( (TheRecorder && TheRecorder->getMode() == RECORDERMODETYPE_PLAYBACK) ); // playback CRC
+ /* The frame this CRC is of. The message executes a run-ahead later, and the run-ahead can
+ shrink: the network never stamps an order below its last execution frame, so after the
+ opening second's run-ahead of 60 drops, every CRC from frame 61 to about 112 lands on one
+ execution frame, each machine's pile ending somewhere else. Keeping the last per player
+ then held one machine's frame 107 against another's frame 112 (report 1845). Last, so
+ the playback check's arguments 0 and 1 stay where old replays have them. */
+ msg->appendIntegerArgument( m_frame );
//DEBUG_LOG(("Appended CRC of %8.8X on frame %d\n", m_CRC, m_frame));
}
else
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
index 49cb5a40b..7ce480c9b 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
@@ -2759,11 +2759,12 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, AIGroup *orderedGroup
#endif
}
- //UnsignedInt oldCRC = m_cachedCRCs[msg->getPlayerIndex()];
UnsignedInt newCRC = msg->getArgument(0)->integer;
//DEBUG_LOG(("Recieved CRC of %8.8X from %ls on frame %d\n", newCRC,
//thisPlayer->getPlayerDisplayName().str(), m_frame));
- m_cachedCRCs[msg->getPlayerIndex()] = newCRC; // to mask problem: = (oldCRC < newCRC)?newCRC:oldCRC;
+ // by the frame it was computed on (argument 2): one execution frame can carry several (GameLogic.cpp, MSG_LOGIC_CRC)
+ const UnsignedInt crcFrame = (UnsignedInt)msg->getArgument(2)->integer;
+ m_cachedCRCs[crcFrame][msg->getPlayerIndex()] = newCRC;
}
else if (TheRecorder && TheRecorder->getMode() == RECORDERMODETYPE_PLAYBACK)
{
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp
index 8f831642f..4214b4427 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp
@@ -690,9 +690,19 @@ TextureClass * W3DAssetManager::Recolor_Texture_One_Time(TextureClass *texture,
if (!texture->Is_Initialized())
TextureLoader::Request_Foreground_Loading(texture);
- SurfaceClass::SurfaceDescription desc;
+ SurfaceClass::SurfaceDescription desc = {};
SurfaceClass *newsurf, *oldsurf;
- texture->Get_Level_Description(desc);
+
+ // A lost device (alt-tab) leaves the texture without a source level and fails
+ // CreateOffscreenPlainSurface without a word, and Copy would dereference the missing surface.
+ // The unit keeps the texture uncoloured.
+ oldsurf=texture->Get_Surface_Level();
+ if (oldsurf == NULL)
+ {
+ DEBUG_LOG(("Can't recolor texture %s: no surface, device lost?\n", name));
+ return NULL;
+ }
+ texture->Get_Level_Description(desc);
Int psize;
psize=PixelSize(desc);
@@ -703,12 +713,18 @@ TextureClass * W3DAssetManager::Recolor_Texture_One_Time(TextureClass *texture,
if (psize != 2 && psize != 4)
{
DEBUG_LOG(("Can't recolor texture %s: format %d is not 16 or 32 bit\n", name, (Int)desc.Format));
+ REF_PTR_RELEASE(oldsurf);
return NULL;
}
- oldsurf=texture->Get_Surface_Level();
-
newsurf=NEW_REF(SurfaceClass,(desc.Width,desc.Height,desc.Format));
+ if (newsurf->Peek_D3D_Surface() == NULL)
+ {
+ DEBUG_LOG(("Can't recolor texture %s: no surface, device lost?\n", name));
+ REF_PTR_RELEASE(oldsurf);
+ REF_PTR_RELEASE(newsurf);
+ return NULL;
+ }
newsurf->Copy(0,0,0,0,desc.Width,desc.Height,oldsurf);
const char *kind = Mod_Bare_Name(name) + 3; // the letter after "ZHC"
@@ -925,11 +941,17 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj(
}
#endif
- W3DPrototypeClass *w3dproto = newInstance(W3DPrototypeClass)(rendobj, newname);
- rendobj->Release_Ref();
- Add_Prototype(w3dproto);
+ // A recolour while the device is lost (alt-tab) comes back uncoloured. Cached under the
+ // team-colour name, the model would stay that way all session, so it goes back uncached and
+ // the next request recolours it again.
+ if (!(reallycolor && DX8Wrapper::Is_Device_Lost()))
+ {
+ W3DPrototypeClass *w3dproto = newInstance(W3DPrototypeClass)(rendobj, newname);
+ rendobj->Release_Ref();
+ Add_Prototype(w3dproto);
- rendobj = w3dproto->Create();
+ rendobj = w3dproto->Create();
+ }
rendobj->Set_ObjectColor(color);
#ifdef DUMP_PERF_STATS
@@ -1706,6 +1728,11 @@ TextureClass * W3DAssetManager::Recolor_Texture_One_Time(TextureClass *texture,
// if texture is monochrome and no value shifting
// return NULL
smallsurf=texture->Get_Surface_Level((TextureClass::MipCountType)texture->Get_Mip_Level_Count()-1);
+ if (smallsurf == NULL)
+ {
+ DEBUG_LOG(("Can't recolor texture %s: no surface, device lost?\n", name));
+ return NULL;
+ }
if (hsv_shift.Z==0.0f && smallsurf->Is_Monochrome())
{
REF_PTR_RELEASE(smallsurf);
@@ -1716,6 +1743,14 @@ TextureClass * W3DAssetManager::Recolor_Texture_One_Time(TextureClass *texture,
oldsurf=texture->Get_Surface_Level();
newsurf=NEW_REF(SurfaceClass,(desc.Width,desc.Height,desc.Format));
+ // Lost device: see the same check in the team-colour Recolor_Texture_One_Time.
+ if (oldsurf == NULL || newsurf->Peek_D3D_Surface() == NULL)
+ {
+ DEBUG_LOG(("Can't recolor texture %s: no surface, device lost?\n", name));
+ REF_PTR_RELEASE(oldsurf);
+ REF_PTR_RELEASE(newsurf);
+ return NULL;
+ }
newsurf->Copy(0,0,0,0,desc.Width,desc.Height,oldsurf);
newsurf->Hue_Shift(hsv_shift);
TextureClass * newtex=NEW_REF(TextureClass,(newsurf,(TextureClass::MipCountType)texture->Get_Mip_Level_Count()));
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
index 3ad39f867..985101487 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
@@ -2896,6 +2896,19 @@ AGAIN:
if( Direct3D11_Take_Present_Failure( presentResult ) )
DEBUG_LOG(("DX11 PRESENT refused at frame %d: 0x%08X, logged once\n",
TheGameLogic->getFrame(), (UnsignedInt)presentResult));
+
+ /* A removed device (a driver reset after a GPU hang, a driver update, the card gone)
+ never presents again. The game used to play on blind until the player killed it,
+ which reached us as a crash report with nothing in it. No re-creation: the crash
+ report names the reason instead. */
+ const long removedReason = Direct3D11_Device_Removed_Reason();
+ if( removedReason != 0 )
+ {
+ char reason[ 256 ];
+ snprintf( reason, ARRAY_SIZE(reason), "Graphics device removed at frame %d (DXGI reason 0x%08X): the graphics driver reset or the graphics card stopped responding",
+ TheGameLogic->getFrame(), (UnsignedInt)removedReason );
+ ReleaseCrash( reason );
+ }
}
/* End_Render is where a lost device is noticed and reset, and that reset is the most
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
index 953080e0b..5b8fa38fd 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
@@ -1067,6 +1067,14 @@ bool Direct3D11_Take_Present_Failure(long & result)
return true;
}
+long Direct3D11_Device_Removed_Reason()
+{
+ if (!Active || SUCCEEDED(Device.Last_Present_Result())) {
+ return S_OK;
+ }
+ return Device.Device_Removed_Reason();
+}
+
void Direct3D11_Mirror_Stream_Source(DX11BufferTwinClass * twin, unsigned stride, unsigned offset)
{
if (Active) {
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
index 221676cad..a09719a2b 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
@@ -260,6 +260,9 @@ bool Direct3D11_Can_Tear();
// True once, the first time a present was refused, with the HRESULT it was refused with. WW3D2
// has no logging in a shipping build, so the display asks and writes the line.
bool Direct3D11_Take_Present_Failure(long & result);
+// After a refused present, why the device went: DXGI's removed reason (a driver reset, a hung or
+// removed card), or 0 while the device is alive. A removed device never comes back.
+long Direct3D11_Device_Removed_Reason();
// Wait for the monitor on the Direct3D 11 present. DXGI takes the interval per Present, so this
// does not need a device reset the way Direct3D 9's presentation interval does.
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
index a6e7ffe1a..e9ecdfaaa 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
@@ -106,6 +106,7 @@ void Direct3D11_Present_Enable(bool) {}
bool Direct3D11_Present_Is_Enabled() { return false; }
bool Direct3D11_Can_Tear() { return false; }
bool Direct3D11_Take_Present_Failure(long &) { return false; }
+long Direct3D11_Device_Removed_Reason() { return 0; }
void Direct3D11_Set_VSync(bool) {}
// Windows answers whether it understood the chain's text. There is no post-process here to
// understand it for, so every chain is refused.
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
index f1de9e3fe..1ba8408f4 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
@@ -2373,8 +2373,13 @@ void DX8Wrapper::End_Scene(bool flip_frames)
IsDeviceLost=true;
}
- // If the device was lost we need to check for cooperative level and possibly reset the device
- if (hr==D3DERR_DEVICELOST) {
+ // If the device was lost we need to check for cooperative level and possibly reset the device.
+ // Not when the Direct3D 11 device was removed: a driver reset loses this twin too, and a fault in
+ // Reset_Device would end the process before the display reports the DXGI reason next frame.
+ if (Direct3D11_Device_Removed_Reason() != 0) {
+ // the display's ReleaseCrash names it
+ }
+ else if (hr==D3DERR_DEVICELOST) {
hr=_Get_D3D_Device()->TestCooperativeLevel();
if (hr==D3DERR_DEVICENOTRESET) {
Reset_Device();
diff --git a/GeneralsMD/Code/Main/WinMain.cpp b/GeneralsMD/Code/Main/WinMain.cpp
index 81c1d5f89..722e88b04 100644
--- a/GeneralsMD/Code/Main/WinMain.cpp
+++ b/GeneralsMD/Code/Main/WinMain.cpp
@@ -58,10 +58,12 @@
#include "Common/Monitors.h"
#include "Common/GameMemory.h"
#include "Common/INIException.h"
+#include "Common/FileWriteQueue.h"
#include "Common/SafeDisc/CdaPfn.h"
#include "Common/StackDump.h"
#include "Common/MessageStream.h"
#include "Common/PlayerList.h"
+#include "Common/Recorder.h"
#include "Common/Registry.h"
#include "Common/Team.h"
#include "GameClient/InGameUI.h"
@@ -447,14 +449,28 @@ LRESULT CALLBACK WndProc( HWND hWnd, UINT message,
break;
case WM_QUERYENDSESSION:
- {
- // guarded like the focus handlers below: these messages can arrive before the
- // engine is up and, more often, while it is tearing down - a close or end-session
- // that lands after TheMessageStream is gone used to fault right here.
- if (canPostQuitMessage())
- TheMessageStream->appendMessage(GameMessage::MSG_META_DEMO_INSTANT_QUIT);
- return 0; //don't allow Windows to shutdown while game is running.
- }
+ // Windows is logging off or shutting down. Refusing put the game on the "apps are
+ // preventing shutdown" screen, Windows killed it anyway, and the launcher read that kill
+ // as a crash. Say yes; WM_ENDSESSION below ends the process.
+ DEBUG_LOG(("Windows session ending (WM_QUERYENDSESSION 0x%llx)\n", (unsigned long long)lParam));
+ FileWriteQueue::flushAll();
+ return TRUE;
+
+ case WM_ENDSESSION:
+ // wParam FALSE: something else refused the end, so play on. TRUE: Windows ends the
+ // process soon after this returns, so no quit path; the replay closed with its end time
+ // and length the way a quit closes it, the log out, then leave with 0. The pump runs on
+ // the main thread between ticks, so the recorder is not mid-write; it is NULL before the
+ // engine is up and after it is gone.
+ if (wParam)
+ {
+ DEBUG_LOG(("Windows session ended, leaving\n"));
+ if (TheRecorder != NULL && TheRecorder->getMode() == RECORDERMODETYPE_RECORD)
+ TheRecorder->stopRecording();
+ FileWriteQueue::flushAll();
+ _exit(0);
+ }
+ return 0;
// ------------------------------------------------------------------------
case WM_CLOSE:
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 08285ad4b..0b57e75b1 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -5859,6 +5859,34 @@ TEST(crcsnapshotring_never_hands_back_a_half_written_frame)
CHECK_EQ( ring.getNumSnapshots(), 0 );
}
+TEST(crcsnapshotring_gives_each_frame_the_commands_executed_before_it)
+{
+ CRCSnapshotRing ring;
+ fillSnapshot( ring, 30, 0x30, 1 );
+
+ // a run of one player's commands of one type on one frame folds into one entry
+ ring.addCommand( 30, 1, 7, 0xA );
+ ring.addCommand( 30, 1, 7, 0xB );
+ ring.addCommand( 30, 2, 7, 0xC );
+ fillSnapshot( ring, 31, 0x31, 1 );
+ fillSnapshot( ring, 32, 0x32, 1 );
+
+ const CRCSnapshot *first = ring.getSlot( ring.findSlotByFrame( 30 ) );
+ const CRCSnapshot *second = ring.getSlot( ring.findSlotByFrame( 31 ) );
+ const CRCSnapshot *third = ring.getSlot( ring.findSlotByFrame( 32 ) );
+ CHECK( first != NULL && second != NULL && third != NULL );
+ if( first == NULL || second == NULL || third == NULL )
+ return;
+
+ CHECK_EQ( (Int)first->m_commands.size(), 0 );
+ CHECK_EQ( (Int)second->m_commands.size(), 2 );
+ CHECK_EQ( (Int)second->m_commands[0].m_count, 2 );
+ CHECK_EQ( (Int)second->m_commands[0].m_argHash, 0xA * 33 + 0xB );
+ CHECK_EQ( second->m_commands[1].m_player, 2 );
+ CHECK_EQ( (Int)third->m_commands.size(), 0 );
+ CHECK_EQ( ring.findSlotByFrame( 33 ), -1 );
+}
+
/* --------------------------------------------------------------------------------------------
A lockstep game only stays in step if both machines feed the same numbers into it, and the
join request is the last moment at which that is a refused join instead of a desynced match.
diff --git a/GeneralsMD/Code/Tests/test_gametext_csf.cpp b/GeneralsMD/Code/Tests/test_gametext_csf.cpp
index d6ffb189e..73474b22a 100644
--- a/GeneralsMD/Code/Tests/test_gametext_csf.cpp
+++ b/GeneralsMD/Code/Tests/test_gametext_csf.cpp
@@ -440,6 +440,9 @@ void getExecutableDirectory( char *buf, size_t size, Bool ) { if (size > 0) buf[
DEBUG_EXTERN_C void DebugInit( int ) {}
#endif
+// GameMemory.cpp stops on a corrupt block header; here that fails the test loudly.
+DEBUG_EXTERN_C void ReleaseCrash( const char *reason ) { fprintf( stderr, "ReleaseCrash: %s\n", reason ); abort(); }
+
#ifdef DEBUG_LOGGING
#include <stdarg.h>
DEBUG_EXTERN_C void DebugLog( const char *format, ... )
diff --git a/GeneralsMD/Code/Tests/test_global_new_alignment.cpp b/GeneralsMD/Code/Tests/test_global_new_alignment.cpp
index b01a18a6e..ac62ec36b 100644
--- a/GeneralsMD/Code/Tests/test_global_new_alignment.cpp
+++ b/GeneralsMD/Code/Tests/test_global_new_alignment.cpp
@@ -85,6 +85,7 @@ void getExecutableDirectory( char *buf, size_t size, Bool ) { if (size > 0) buf[
#ifdef ALLOW_DEBUG_UTILS
DEBUG_EXTERN_C void DebugInit( int ) {}
#endif
+DEBUG_EXTERN_C void ReleaseCrash( const char *reason ) { fprintf( stderr, "ReleaseCrash: %s\n", reason ); abort(); } // a corrupt block header
#ifdef DEBUG_LOGGING
#include <stdarg.h>
DEBUG_EXTERN_C void DebugLog( const char *format, ... )
diff --git a/GeneralsMD/Code/Tests/test_posixlocalfilesystem_stubs.cpp b/GeneralsMD/Code/Tests/test_posixlocalfilesystem_stubs.cpp
index 1b1094b5f..b311f64e7 100644
--- a/GeneralsMD/Code/Tests/test_posixlocalfilesystem_stubs.cpp
+++ b/GeneralsMD/Code/Tests/test_posixlocalfilesystem_stubs.cpp
@@ -23,6 +23,7 @@
*
* - DebugInit, DebugLog: Debug.cpp does not compile off Windows yet. DebugLog prints, so a
* DEBUG_LOG from the memory manager is not lost.
+ * - ReleaseCrash: the memory manager stops on a corrupt block header; here that aborts.
* - INI: SubsystemInterfaceList::initSubsystem loads INI files; nothing here initialises a
* subsystem through it.
* - TheFileSystem, FileSystem::openFile: RAMFile::open(const char*) opens through the whole file
@@ -49,6 +50,12 @@ extern "C" void DebugLog(const char *format, ...)
va_end(args);
}
+extern "C" void ReleaseCrash(const char *reason)
+{
+ fprintf(stderr, "test_posixlocalfilesystem: ReleaseCrash: %s\n", reason);
+ abort();
+}
+
static void unreachable(const char *what)
{
fprintf(stderr, "test_posixlocalfilesystem: %s was reached, and this test has no stand-in for it\n", what);
diff --git a/GeneralsMD/Code/Tests/test_premain_strings.cpp b/GeneralsMD/Code/Tests/test_premain_strings.cpp
index 42292cea4..51f2eabc0 100644
--- a/GeneralsMD/Code/Tests/test_premain_strings.cpp
+++ b/GeneralsMD/Code/Tests/test_premain_strings.cpp
@@ -95,6 +95,7 @@ void getExecutableDirectory( char *buf, size_t size, Bool ) { if (size > 0) buf[
#ifdef ALLOW_DEBUG_UTILS
DEBUG_EXTERN_C void DebugInit( int ) {} // the pre-main start opens the debug log; this test has none
#endif
+DEBUG_EXTERN_C void ReleaseCrash( const char *reason ) { fprintf( stderr, "ReleaseCrash: %s\n", reason ); abort(); } // a corrupt block header
#ifdef DEBUG_LOGGING
#include <stdarg.h>
DEBUG_EXTERN_C void DebugLog( const char *format, ... )
diff --git a/GeneralsMD/Code/Tools/net-check.sh b/GeneralsMD/Code/Tools/net-check.sh
index 4e58847c3..e689ab8fd 100755
--- a/GeneralsMD/Code/Tools/net-check.sh
+++ b/GeneralsMD/Code/Tools/net-check.sh
@@ -564,8 +564,9 @@ if [ "$LIVE_CRC0" != "$LIVE_CRC1" ] || [ "$LIVE_FRAME0" != "$LIVE_FRAME1" ]; the
fi
# edit_replay corrupt|strip <replay> <CRC message type> <frame>: the replay's MSG_LOGIC_CRC records
-# (Recorder.cpp writeToFile) are u32 frame, the message type, i32 player, 2 argument groups (one
-# integer, one boolean), the CRC and the boolean; the type's number is the one this build logged ("CRC
+# (Recorder.cpp writeToFile) are u32 frame, the message type, i32 player, 3 argument groups (one
+# integer, one boolean, one integer), the CRC, the boolean and the frame the CRC is of; the type's
+# number is the one this build logged ("CRC
# message is N"). corrupt changes by one bit every CRC recorded at the first CRC frame at or after
# <frame>; strip removes every record of the first CRC frame. Prints that frame, or "none".
edit_replay() {
@@ -573,8 +574,8 @@ edit_replay() {
import struct, sys
mode, path, msgtype, at = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])
b = bytearray(open(path, "rb").read())
-tag, groups, size = struct.pack("<i", msgtype), bytes([2, 0, 1, 2, 1]), 22
-records = [i for i in range(len(b) - size + 1) if b[i + 4:i + 8] == tag and b[i + 12:i + 17] == groups]
+tag, groups, size = struct.pack("<i", msgtype), bytes([3, 0, 1, 2, 1, 0, 1]), 28
+records = [i for i in range(len(b) - size + 1) if b[i + 4:i + 8] == tag and b[i + 12:i + 19] == groups]
frames = sorted({struct.unpack_from("<I", b, i)[0] for i in records if struct.unpack_from("<I", b, i)[0] >= at})
if not frames:
print("none"); sys.exit(0)
@@ -582,7 +583,7 @@ frame = frames[0]
chosen = [i for i in records if struct.unpack_from("<I", b, i)[0] == frame]
if mode == "corrupt":
for i in chosen:
- struct.pack_into("<I", b, i + 17, struct.unpack_from("<I", b, i + 17)[0] ^ 1)
+ struct.pack_into("<I", b, i + 19, struct.unpack_from("<I", b, i + 19)[0] ^ 1)
else:
for i in reversed(chosen):
del b[i:i + size]