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): five lifetime and state bugs found reading the client

Olcay Seygan9349fd5d97aa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 09ac90ecd..15414816c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -60,6 +60,7 @@ found and fixed — EA's own, not port damage.**
- It now weighs distance, whether the target is crippled - an opportunity, not a distraction - and how much of what it can see that player is worth. Only a genuinely finished enemy is skipped.
- It still refuses to gang up with another computer opponent on one victim, and still gently prefers whoever is already shooting at it.
- An aggressive computer team is supposed to fight its way to where it is sent rather than walk there. It never did. The order to fight was being reissued every frame, and each reissue pushed the moment that unit next looks for a target one step further into the future, so the look never came at all and the team crossed the map through the enemy without firing. Over four and a half minutes of one test match that order was restarted 2,240 times. It is restarted 15 times now.
+- And when that switch does happen, the old order stops there. It used to finish its own turn afterwards, steering one last time toward the place the unit was going before the order changed, which is a visible flinch at the head of a column.
## The computer knows when to quit
- Its teams fought to the last man. The word "retreat" appeared nowhere in the opponent's code - the single most visible thing that made it look stupid.
@@ -373,6 +374,9 @@ found and fixed — EA's own, not port damage.**
- A supply centre could stop accepting trucks permanently.
- Selling a building mid-research gave no refund and left the upgrade in limbo.
- On-screen messages now hold for two and a half seconds and fade in one.
+- Closing a dialog while another one sits on top of it no longer leaves the game holding a pointer to the window it just freed. Every click, every keypress and the tab order all read that list, so what it caused was a crash with no pattern to it.
+- Ordering a group to use a special power that can kill the units casting it, the GLA rebel ambush over water being the one that does it every time, no longer walks a list of units that the ambush is deleting underneath.
+- A replay that never recorded which seat was yours plays instead of crashing before the map loads.
- Double-tapping 0 jumps the camera to that group.
- The mouse wheel no longer cancels a camera move already in progress.
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/GameWindow.h b/GeneralsMD/Code/GameEngine/Include/GameClient/GameWindow.h
index fb212c0aa..d750045ec 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/GameWindow.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/GameWindow.h
@@ -438,6 +438,9 @@ public:
};
EMPTY_DTOR(ModalWindow)
+///< drop every entry for this window from a modal stack and return the new head (GameWindowManager.cpp)
+extern ModalWindow *ModalStack_removeWindow( ModalWindow *head, const GameWindow *window );
+
// Errors returned by window functions
enum
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp
index aa7e301a5..97761b6c2 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp
@@ -108,8 +108,7 @@ void GameWindowManager::processDestroyList( void )
if( m_keyboardFocus == doDestroy )
winSetFocus( NULL );
- if( (m_modalHead != NULL) && (doDestroy == m_modalHead->window) )
- winUnsetModal( m_modalHead->window );
+ m_modalHead = ModalStack_removeWindow( m_modalHead, doDestroy );
if( m_currMouseRgn == doDestroy )
m_currMouseRgn = NULL;
@@ -1487,8 +1486,7 @@ Int GameWindowManager::winDestroy( GameWindow *window )
if( m_keyboardFocus == window )
winSetFocus( NULL );
- if( (m_modalHead != NULL) && (window == m_modalHead->window) )
- winUnsetModal( m_modalHead->window );
+ m_modalHead = ModalStack_removeWindow( m_modalHead, window );
if( m_currMouseRgn == window )
m_currMouseRgn = NULL;
@@ -1558,6 +1556,39 @@ Int GameWindowManager::winDestroyAll( void )
//-------------------------------------------------------------------------------------------------
/** Sets selected window into a modal state. This window will get
* put at the top of a modal stack */
+//-------------------------------------------------------------------------------------------------
+/**
+ * Drop every entry for this window from a modal stack, wherever in it they sit, and return the new
+ * head. Removed entries are freed.
+ *
+ * With no GameWindowManager involved so test_gameengine can link straight to it, and because the
+ * window pointer is only ever compared here - it belongs to a window that is being destroyed and
+ * must not be dereferenced.
+ *
+ * winUnsetModal only ever pops the top of the stack, so a window destroyed while another modal
+ * window sat above it left its entry behind pointing at freed memory. Everything that walks the
+ * stack afterwards - the mouse hit test in winPointInAnyChild, the tab list, the modal check on
+ * every input message - reads that pointer.
+ */
+ModalWindow *ModalStack_removeWindow( ModalWindow *head, const GameWindow *window )
+{
+ ModalWindow **link = &head;
+ while( *link )
+ {
+ ModalWindow *entry = *link;
+ if( entry->window == window )
+ {
+ *link = entry->next;
+ entry->deleteInstance();
+ }
+ else
+ {
+ link = &entry->next;
+ }
+ }
+ return head;
+}
+
//-------------------------------------------------------------------------------------------------
Int GameWindowManager::winSetModal( GameWindow *window )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp
index c5cedb9ba..89b31ca8a 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp
@@ -3591,13 +3591,16 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage
}
break;
}
- case GameMessage::MSG_CHEAT_ADD_CASH:
+ case GameMessage::MSG_CHEAT_ADD_CASH:
{
if ( !TheGameLogic->isInMultiplayerGame() )
{
Player *localPlayer = ThePlayerList->getLocalPlayer();
Money *money = localPlayer->getMoney();
money->deposit( 10000 );
+ // consumed here, like every cheat around it. Without this the message went on down
+ // the translator chain and onto the command list, where nothing acts on it.
+ disp = DESTROY_MESSAGE;
}
break;
}
@@ -4744,6 +4747,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage
Player *localPlayer = ThePlayerList->getLocalPlayer();
Money *money = localPlayer->getMoney();
money->deposit( 10000 );
+ disp = DESTROY_MESSAGE; // same omission as the cheat message above
}
break;
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
index ccb234ef7..c64adf2f2 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
@@ -3053,13 +3053,23 @@ void AIGroup::groupCreateFormation( CommandSourceType cmdSource ) ///< Create
*/
void AIGroup::groupDoSpecialPower( UnsignedInt specialPowerID, UnsignedInt commandOptions )
{
- //This is the no target, no position version.
- std::list<Object *>::iterator i;
- for( i = m_memberList.begin(); i != m_memberList.end(); ++i )
+ //
+ // This is the no target, no position version.
+ //
+ // Firing a special power can destroy the group it was ordered from. The rebel ambush over water
+ // drowns every rebel; their slow death calls deselect(), which empties this list to keep the
+ // selection and the group in step. Walking m_memberList while that happens walks freed nodes.
+ // So take the members by id first and drive the copy - each one looked up again, because by the
+ // time its turn comes an earlier member's power may have killed it.
+ //
+ const VecObjectID members = getAllIDs();
+ for( VecObjectID::const_iterator i = members.begin(); i != members.end(); ++i )
{
//Special powers do a lot of different things, but the top level stuff doesn't use
//ai interface code. It finds the special power module and calls it directly for each object.
- Object *object = (*i);
+ Object *object = TheGameLogic->findObjectByID( *i );
+ if( object == NULL || object->isEffectivelyDead() )
+ continue;
const SpecialPowerTemplate *spTemplate = TheSpecialPowerStore->findSpecialPowerTemplateByID( specialPowerID );
if( spTemplate )
{
@@ -3093,21 +3103,25 @@ void AIGroup::groupDoSpecialPowerAtLocation( UnsignedInt specialPowerID, const C
{
- //This one requires a position
- std::list<Object *>::iterator i;
- for( i = m_memberList.begin(); i != m_memberList.end(); )
+ //
+ // This one requires a position.
+ //
+ // The rebel ambush over the ocean drowns every rebel, and their slow death calls deselect(),
+ // which destroys this list to keep the selection in step with the group - M Lorenzen noted that
+ // in 2003 and stepped the iterator forward before firing to cope with it. That covers the member
+ // that just went away and nothing else: a list emptied outright leaves the iterator on a freed
+ // node. Take the members by id instead - see groupDoSpecialPower above.
+ //
+ const VecObjectID members = getAllIDs();
+ for( VecObjectID::const_iterator i = members.begin(); i != members.end(); ++i )
{
//Special powers do a lot of different things, but the top level stuff doesn't use
//ai interface code. It finds the special power module and calls it directly for each object.
- Object *object = (*i);
+ Object *object = TheGameLogic->findObjectByID( *i );
+ if( object == NULL || object->isEffectivelyDead() )
+ continue;
- ++i; // just in case the act of specialpowering changes this list,
- // like when the rebelambush happens over the ocean, and all the rebels drown
- // and, of course, their slowdeath behavior calls deselect(), which naturally
- // destroys the AIGroup list, in order to keep the selection sync'ed with the group.
- // M Lorenzen... 8/23/03
-
const SpecialPowerTemplate *spTemplate = TheSpecialPowerStore->findSpecialPowerTemplateByID( specialPowerID );
if( spTemplate )
{
@@ -3140,14 +3154,16 @@ void AIGroup::groupDoSpecialPowerAtLocation( UnsignedInt specialPowerID, const C
*/
void AIGroup::groupDoSpecialPowerAtObject( UnsignedInt specialPowerID, Object *target, UnsignedInt commandOptions )
{
- //This one requires a target
- std::list<Object *>::iterator i;
- for( i = m_memberList.begin(); i != m_memberList.end(); ++i )
+ //This one requires a target; by id for the same reason - see groupDoSpecialPower above.
+ const VecObjectID members = getAllIDs();
+ for( VecObjectID::const_iterator i = members.begin(); i != members.end(); ++i )
{
//Special powers do a lot of different things, but the top level stuff doesn't use
//ai interface code. It finds the special power module and calls it directly for each object.
- Object *object = (*i);
+ Object *object = TheGameLogic->findObjectByID( *i );
+ if( object == NULL || object->isEffectivelyDead() )
+ continue;
const SpecialPowerTemplate *spTemplate = TheSpecialPowerStore->findSpecialPowerTemplateByID( specialPowerID );
if( spTemplate )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
index c2f8a14b0..df2f21280 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
@@ -2100,7 +2100,14 @@ StateReturnType AIMoveToState::update()
UnsignedInt adjustment = ai->getMoodMatrixActionAdjustment(MM_Action_Move);
if (m_isMoveTo && (adjustment & MAA_Action_To_AttackMove)
&& getMachine()->getCurrentStateID() == AI_MOVE_TO)
+ {
ai->aiAttackMoveToPosition(&m_goalPosition, NO_MAX_SHOTS_LIMIT, CMD_FROM_AI);
+ // We are no longer the current state and the one that replaced us has already had its
+ // onEnter, which computed its own goal and its own path. Running the rest of this update
+ // drives the locomotor from the goal *this* state was holding, one frame after the order
+ // that replaced it - so the new state's first frame steers to the old destination.
+ return STATE_CONTINUE;
+ }
// if we have a goal object, move to it, as it may have moved
Object* goalObj = getMachineGoalObject();
@@ -4623,6 +4630,9 @@ StateReturnType AIFollowWaypointPathState::update()
} else {
ai->aiAttackFollowWaypointPath(m_currentWaypoint, NO_MAX_SHOTS_LIMIT, CMD_FROM_AI);
}
+ // The attack-follow state that replaced us owns the waypoint walk now; the rest of this
+ // update would advance our own copy of it - see AIMoveToState::update above.
+ return STATE_CONTINUE;
}
if (m_appendGoalPosition) {
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
index 86c1d5cfe..9fa8d9769 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
@@ -1411,7 +1411,16 @@ void GameLogic::startNewGame( Bool loadingSaveGame )
d.setInt(TheKey_multiplayerStartIndex, slot->getStartPos());
// d.setBool(TheKey_multiplayerIsLocal, slot->isLocalPlayer());
// d.setBool(TheKey_multiplayerIsLocal, slot->getIP() == game->getLocalIP());
- d.setBool(TheKey_multiplayerIsLocal, slot->isHuman() && (slot->getName().compare(game->getSlot(game->getLocalSlotNum())->getName().str()) == 0));
+ //
+ // getLocalSlotNum() returns -1 when no slot belongs to us, and getSlot(-1) returns NULL.
+ // A replay is the ordinary way to get here with no local slot at all: the header carries
+ // -1 when the recording side never identified its own seat, and the reply to that used to
+ // be a null dereference before the map had even loaded. Nobody's slot is the local one in
+ // that case, which is also the truthful answer.
+ //
+ GameSlot *localGameSlot = game->getSlot(game->getLocalSlotNum());
+ d.setBool(TheKey_multiplayerIsLocal, localGameSlot != NULL && slot->isHuman()
+ && (slot->getName().compare(localGameSlot->getName().str()) == 0));
/*
if (slot->getIP() == game->getLocalIP())
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 288f32ba0..c7fd35603 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -1126,6 +1126,60 @@ TEST(attack_move_turns_on_whoever_is_shooting_it)
CHECK( !AIAttackMove_shouldRetaliate( 0xffffffff, 0xfffffff0, WINDOW, false, true ) );
}
+/* GameWindowManager.cpp: destroying a modal window that is not the top of the modal stack
+ used to leave its entry behind, holding a pointer to freed memory. */
+#include "GameClient/GameWindow.h"
+
+TEST(destroying_a_modal_window_takes_it_out_of_the_stack_wherever_it_sits)
+{
+ /* the window pointers are never dereferenced, only compared - which is the whole point:
+ by the time the stack is cleaned up the window is being freed. */
+ GameWindow *bottom = (GameWindow *)0x1000;
+ GameWindow *middle = (GameWindow *)0x2000;
+ GameWindow *top = (GameWindow *)0x3000;
+
+ ModalWindow *head = NULL;
+ GameWindow *order[3] = { bottom, middle, top };
+ for( Int i = 0; i < 3; i++ )
+ {
+ ModalWindow *entry = newInstance(ModalWindow);
+ entry->window = order[i];
+ entry->next = head;
+ head = entry; /* pushed like winSetModal does: top of the stack is 'top' */
+ }
+
+ /* the middle one goes away while another modal window still sits above it. */
+ head = ModalStack_removeWindow( head, middle );
+ CHECK( head != NULL );
+ CHECK_EQ( head->window, top );
+ CHECK( head->next != NULL );
+ CHECK_EQ( head->next->window, bottom );
+ CHECK( head->next->next == NULL );
+
+ /* a window that is not in the stack at all leaves it alone. */
+ head = ModalStack_removeWindow( head, (GameWindow *)0x4000 );
+ CHECK_EQ( head->window, top );
+ CHECK_EQ( head->next->window, bottom );
+
+ /* the same window set modal twice loses both entries, not one. */
+ for( Int j = 0; j < 2; j++ )
+ {
+ ModalWindow *dup = newInstance(ModalWindow);
+ dup->window = bottom;
+ dup->next = head;
+ head = dup;
+ }
+ head = ModalStack_removeWindow( head, bottom );
+ CHECK( head != NULL );
+ CHECK_EQ( head->window, top );
+ CHECK( head->next == NULL );
+
+ /* emptying it gives a null head back, not a stale one. */
+ head = ModalStack_removeWindow( head, top );
+ CHECK( head == NULL );
+ CHECK( ModalStack_removeWindow( NULL, top ) == NULL );
+}
+
/* AIStates.cpp: a dud fight and a broken leash suspend the approach, never the shooting -
a unit on attack move drove past whatever stood next to it during those windows. */
extern Bool AIAttackMove_mayTakeTarget( Bool targetIsInRangeNow, Bool targetIsTheLastDud,