Repository navigation
[DO NOT MERGE] Mount behavior v2 - testing branch, destined for upstream - #2
Open
icemansparks wants to merge 10 commits into
Open
icemansparks wants to merge 10 commits into
icemansparks wants to merge 10 commits into
Conversation
Bots hold a raw Player* master that dangles when the master logs out and the Player object is destroyed between AI ticks on the map-update threads. FollowAction::isUseful then crashes on fTarget->GetGUID() (reproduced twice, cores captured; same UAF family as mod-playerbots#2474; the crashing branch was introduced in mod-playerbots#2462). SetMaster() now records the master GUID and GetMaster() re-validates it through ObjectAccessor::FindPlayer, which never dereferences the stored pointer, returning nullptr once the master is gone. HasRealPlayerMaster, HasActivePlayerMaster and the GetGroupLeader fallback go through the validated accessor, UpdateAIGroupMaster clears a stale master at entry, and GossipHelloAction handles the now-possible null master.
Reattempt of PR mod-playerbots#1760 (reverted in mod-playerbots#1855). Bots now stay mounted when the master dismounts far away, and mount up to reach a distant master, dismounting at assist range when the master is in combat. Unlike the original PR, the shared target-based mount/dismount logic is untouched and the feature is scoped entirely to the master-following branch, which battleground bots never enter. This removes the BG mounted-loop regression that caused the revert. Both helpers also require the follow strategy, so bots told to stay are unaffected.
- Gate the whole master mount-mirror block on the follow strategy: a bot told to stay is parked and no longer mounts when the master mounts - Clamp the in-combat dismount range to at least 18yd: for non-warrior melee CalculateDismountDistance() is ~3yd, which made the bot ride to the master's exact position and hover at follow distance without engaging - Reduce the out-of-combat proximity range to 5yd so the bot follows until near the master and then mirrors their mount state
A mob fighting the master resolves as the bot's dps target well before the bot itself is in combat, but the master-follow branch decided mount state only against the master. The bot rode past the fight to the master's exact position and could oscillate between assisting and re-mounting without attacking. When an assist target exists, dismount at engage range of the target (dismount distance + combat reach) and stop touching the mount state while next to it, so the dps/tank assist trigger can take over. Also drop the 18yd assist-range clamp again: dismount happens at the class combat distance.
The mirror path had no distance condition, so a bot at 15yd mounted the moment the master did. Now: mirror within 5yd, walk between 5 and the mount threshold (21+ yd, where the cast time isn't worth it), and mount to close distance beyond that. Shared proximity constant for the mirror gate and the stay-mounted dismount range.
Replaces the hardcoded proximity constant with the existing (previously unused) AiPlayerbot.TooCloseDistance option, default 5.
GetMaster() validated the master GUID via ObjectAccessor::FindConnectedPlayer but then returned the cached raw pointer, which is exactly the stale pointer the validation was meant to guard against: after a same-GUID relog the lookup finds the new Player object yet the old (freed) pointer was handed back. Return the resolved object instead - a logged-out master yields nullptr, a relogged one yields the fresh Player.
…ting Execute() already computes distToMaster once per tick; StayMountedToCloseDistance and ShouldMountToCloseDistance each recomputed the same GetDistance2d, so a mounted bot near a dismounted master ran the distance calc three times per tick. Thread the value through - no behaviour change.
UpdateAIGroupMaster only cleared the raw master pointer when the master resolved to nullptr. A same-GUID relog yields a fresh Player object, so GetMaster() returns the new one while the cached raw pointer still points at the destroyed one, and every raw master dereference further down the function is a use-after-free until PlayerbotMgr happens to call SetMaster again. Compare against the re-resolved master instead.
…ot only when near The near-only mirror gate left a dead band between TooCloseDistance and CalculateMountDistance() where neither the mirror branch nor the mount-to-close branch fires: 5-21 yd for melee, and 5-38.5 yd for casters, since CalculateMountDistance() is max(21, SpellDistance + 10) and SpellDistance defaults to 28.5. CalculateMountDistance() is the break-even for closing a FIXED gap, so it is the wrong test against a master who is actively opening one. And a ground mount matches the master's speed rather than beating it, so a bot that waits for the gap to cross the threshold does not claw it back - it holds that distance for the rest of the ride. A caster trailing 38 yd behind is the visible symptom. Mirror when near or when the master is moving. ShouldFollowMasterMountState already requires the master mounted, the bot unmounted, no attackers and the bot out of combat, so the added clause only fires for a safe bot on foot behind a moving mounted master. A stationary master keeps the deliberate near-only rule.
icemansparks
pushed a commit
that referenced
this pull request
Oct 12, 2026
…rbots#2811) ## Pull Request Description An `Item*` is only good until the next inventory call for that player, and six places in the module read one afterwards. One of them crashes. AzerothCore frees an item synchronously. `Item::SetState(ITEM_REMOVED, player)` runs `delete this` on the spot whenever the item is still `ITEM_NEW`, meaning it was created since the owner's last inventory save: ```cpp // Item.cpp:717 if (uState == ITEM_NEW && state == ITEM_REMOVED) { ... delete this; return; } ``` `Player::DestroyItem` ends in that call (PlayerStorage.cpp:3221), and so does the stack merge branch of `Player::_StoreItem` (PlayerStorage.cpp:2804), which covers `StoreItem`, `BankItem`, `MoveItemToInventory`, the autostore opcode, and `HandleUseItemOpcode` when a spell spends the last charge of an expendable item. The core says so itself at PlayerStorage.cpp:3112: "pItem can be deleted already". Nothing clears `ITEM_NEW` early for grey or white junk, so the window lasts until the periodic save. `~Object` then sets `m_uint32Values` to 0 but leaves `m_valuesCount` alone (Object.cpp:114), so the next `GetEntry()` passes the assert in `Object::GetUInt32Value` and reads address `3 * 4 = 0xc`. That makes it a clean null read rather than random corruption, which is why it reproduces the same way every time. ### The site that crashes `SmartDestroyItemAction::Execute` takes a list of items for one usage and, for each entry, destroys every stack sharing that entry's id: ```cpp for (auto& item : items) { FindItemByIdVisitor visitor(item->GetTemplate()->ItemId); DestroyItem(&visitor); ... } ``` Those stacks include entries still waiting later in the same list. One unsaved stack behind a saved stack of the same id is enough, and the loop keeps going while `bag space` is still 90 or more. I have two cores from my own realm, both faulting at `si_addr=0xc` in the same frame: ``` #0 Object::GetUInt32Value(index=3) Object.cpp:301 #2 Item::GetTemplate Item.cpp:547 mod-playerbots#3 SmartDestroyItemAction::Execute DestroyItemAction.cpp:95 mod-playerbots#9 PlayerbotsPlayerScript::OnPlayerAfterUpdate ``` The first is a level 27 hunter that had just been topped up to 6000 rounds of ammo at login, six fresh 1000 stacks, none of them saved yet, with bags at 92%. Entry 0 destroyed all six and entry 1 was read. The second is a warlock with four Soul Shards made at login, crashing on entry 2 at 91% bags. Nothing about it is class specific. It repeated because the crash lands before the first autosave, so the same bots log back in with the same inventory and do it again: 43 crashes in about 59 hours, roughly 30 of them inside one 2.5 hour window. That build is a fork, so treat the line number as corroboration rather than proof, but the code shape at master:95 is the same today. Worth being straight about the blast radius: `smart destroy item` comes from the `maintenance` strategy, and the two `addStrategy("maintenance")` calls in AiFactory.cpp are commented out. So this needs an admin who put `maintenance` in `AiPlayerbot.NonCombatStrategies`, or a player who typed `co +maintenance`. It also needs a bot with no real player master, bags at 90% or more, and two items sharing one id where at least one is unsaved. Stock defaults don't reach it. Any realm that turns the strategy on inherits the loop. ### The same shape elsewhere Ranked by how easy they are to reach: - `DestroyItemAction.cpp:59`, the grey branch. Same loop over a `std::set<Item*>`, but it needs a selfbot master in a real guild. - `BankAction.cpp:107` and `:87`. Deposit and withdraw read `pItem` after `BankItem` or `StoreItem` merged it into a stack that was already there. The deposit one is the easiest of all six to hit on purpose. Fixing `:87` alone would expose `:47`, which loops over bank stack pointers while every withdrawal frees one. - `GiveItemAction.cpp:46`. The receiver merges the handed over stack into one it already holds. Conjured water between two bots is the natural case. - `UnequipAction.cpp:80`. `ue [link]` with nothing matching equipped falls back to `*items.begin()`, which can be a stackable item in a bag that the autostore merges away. - `GenericSpellActions.cpp:650`. I'll call this one hardening rather than a demonstrated bug. Only five equippable items in the world DB are expendable with charges, and the trinket would have to be equipped, unsaved, and on its last charge. I couldn't build a plausible sequence for it. ### The fix No `Item*` is read after a call that may have freed it. The two loops turn their list into distinct item ids first, in the same order, and destroy by id. That's what `DistinctItemIds` and `DestroyUntilBagSpace` are for. Deduplicating costs nothing: `DestroyItem` already destroys every stack of an id on the first visit, so a later entry with an id already destroyed matched nothing on master. It only existed to be dereferenced. The single item sites build their message, or read the entry, before the call that can free the item. The fix has to live in the callers. The core's lifetime rule is deliberate and isn't ours to change, and `DestroyItemAction::DestroyItem` can't reach pointers its caller is holding. Its header now states the rule so the next caller knows. The helper's own loop is safe: it only destroys what it has already read, and a single item id never matches both a container and its contents. ### Two behaviour changes worth naming The grey branch used to iterate a `std::set<Item*>`, so it ran in heap address order. It now runs in bag order. Because the loop stops as soon as bag space drops below 90, that can leave a different grey item behind. The new order is the better one, being deterministic, but it isn't the old one. The three moved messages now report the count that was actually moved. When `CanStoreItem` splits a stack across a partial merge and a free slot, `StoreItem` clones for every destination but the last and calls `SetCount` on the last fragment, so the old code printed the fragment's count. "got 20 Linen Cloth from bank" where it used to say 15 is the corrected number, not a regression, but it is visible. ## Feature Evaluation **Minimum logic**: read the id before the call that can free the item, then use the id. For the two loops that means one pass over a list that already exists to collect ids, and a linear duplicate check on a list that is at most a handful of entries. **Processing cost across many bots**: none on any per tick path. `smart destroy item` runs from the `maintenance` strategy's `random` trigger, and only when bag space is at 90% or more. The deduplication is O(n squared) on a list the visitor caps at 5 for the grey branch, and it replaces a `std::set<Item*>` that was doing O(n log n) with an allocation per node. The single item sites just move an existing `ostringstream` a few lines up. ## How to Test the Changes Reproducing the crash on master needs the near full bags, which is the part that's easy to get wrong. If the first destroy drops bag space below 90 the loop returns before it reads the second entry and nothing happens. 1. Set `AiPlayerbot.NonCombatStrategies = "+maintenance"`, or `co +maintenance` on an altbot. 2. Take a bot with no real player master and fill its bags to about 95% of counted container slots. 3. Put two separate stacks of one grey or SellPrice 0 entry in there. `.additem` is enough to make them `ITEM_NEW`, and they stay that way until the periodic inventory save, so do the test inside that window. 4. Master segfaults in `Object::GetUInt32Value` with `si_addr = 0xc`. This branch destroys that id once, skips the duplicate, and carries on. For the bank sites: have a bot loot a stack, don't let it save, walk it to a bank that already holds a partial stack of that item, and deposit. The merge frees the item and master reads it on the next line. The withdraw mirror needs two bank stacks of one id. `GenericSpellActions.cpp:650` isn't practically testable by hand. Review it by inspection. There's no string literal to grep for, but the binary is unstripped, so `DestroyUntilBagSpace` and `DistinctItemIds` serve as markers for which build is actually running. ## Impact Assessment - Does this change increase per-bot/per-tick processing or risk scaling poorly with thousands of bots? - - [X] No, not at all - - [ ] Minimal impact (**explain below**) - - [ ] Moderate impact (**explain below**) Nothing here is on a per tick path. `SmartDestroyItemAction` only runs from the `maintenance` strategy's `random` trigger and returns early unless bag space is at 90% or more; the other five sites need a chat command. - Does this change modify default bot behavior? - - [ ] No - - [X] Yes (**explain why**) Two changes, both described above: the grey branch destroys ids in bag order rather than heap address order, which can leave a different grey item behind once the bag space early exit fires; and the three moved chat messages report the count that was moved rather than what remained in the source item after a partial merge. Neither is reachable on stock defaults, since `maintenance` is not in any default engine and the bank, give and unequip sites need a command. - Does this change add new decision branches or increase maintenance complexity? - - [X] No - - [ ] Yes (**explain below**) It removes one. The duplicate ids the old loops walked over were already no-ops, so the new code has fewer iterations and one fewer container type. ## AI Assistance Was AI assistance used while working on this change? - - [ ] No - - [X] Yes (**explain below**) Claude Code with Opus 5, used throughout: reading the core's item lifetime, working out the two cores, writing the patch, and writing this description. I ran a separate adversarial review of the diff before submitting, which is where the two behaviour changes above came from and which cut a hunk in `GenericSpellActions.cpp` that turned out to be churn rather than part of the fix. I've read the result and I own it. ## Code Provenance / Attribution Was any code in this PR copied or adapted from a sister / upstream project? - - [X] No, all code in this PR is original - - [ ] Yes (**name the project and the original author(s) below**) ## Final Checklist - - [X] Changes are understood and tested for server stability and performance impact. - - [X] Any new bot dialogue lines are translated. - - [X] New source files use the GPLv2 header. - - [X] Documentation updated if needed (Code comments, Conf comments, WiKi commands). - - [X] New and modified files do not introduce new compiler warnings. No new dialogue lines and no new source files, so those two are vacuous. All five changed translation units build clean at `-Wall -Wextra -Werror`, `apps/codestyle/codestyle-cpp.py` passes, and cppcheck with the repo's suppressions produces an empty report. ## Notes for Reviewers Two pre-existing bugs I walked past on purpose, both on lines this diff touches, so you'll probably spot them: `BankAction::ExecuteBank` seeds `bool result = false` and then only ever does `result &= ...`, so it returns false no matter what happened and the engine is told the bank action failed. Fixing it changes the action's return value, which has nothing to do with item lifetimes, so I'd rather it be its own change. Say the word and I'll do it either here or separately. `ItemUsageValue::QueryItemUsageForAmmo` starts with `if (class != HUNTER || class != ROGUE || class != WARRIOR) return ITEM_USAGE_NONE;`, which no class can fail, so ammo never gets an ammo usage and falls through to the price check. 27 of the 74 projectile templates in the world DB have SellPrice 0, which lands them in the first list `SmartDestroyItemAction` destroys. That's why my hunter had ammo to lose. It matters for honesty here: with this patch a hunter on `maintenance` at 90% bags destroys its own ammo at the moment it used to crash. mod-playerbots#2789 changes that `||` to `&&` as part of a larger change, and doesn't touch the SellPrice 0 case for soul shards and anything else priced at zero. --------- Co-authored-by: Keleborn <22352763+Celandriel@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Not for merge here. This branch carries the mount behavior v2 work, rebased onto a current base so it builds again, and is kept as a staging branch until it is proposed upstream.
What is in here
Master pointer validation. Bots hold a raw
Player* masterthat dangles when the master logs out and the Player object is destroyed between AI ticks on the map-update threads.SetMaster()now records the master GUID andGetMaster()re-resolves it throughObjectAccessor::FindConnectedPlayer, returning the freshly resolved object or nullptr. Callers that dereferenced the raw member go through the validated accessor, andUpdateAIGroupMasterre-syncs the cached pointer on any change rather than only on loss, so a same-GUID relog cannot leave a stale pointer behind.Mount behavior. Bots stay mounted while closing distance to a dismounted master, mount up when riding actually beats running, and dismount to engage an assist target instead of riding past the fight to the master's position. Mount handling only applies while the bot is following; a bot told to stay keeps its current mount state.
The mirror rule fires when the bot is within
TooCloseDistanceof the master or whenever the master is actually riding. Distance alone left a band betweenTooCloseDistanceandCalculateMountDistance()where neither the mirror nor the mount-to-close branch fired: 5 to 21 yd for melee and 5 to 38.5 yd for casters, sinceCalculateMountDistance()ismax(21, SpellDistance + 10)andSpellDistancedefaults to 28.5.CalculateMountDistance()is the break-even for closing a fixed gap, which is the wrong test against a master who is opening one, and a ground mount matches the master's speed rather than beating it, so a bot that waited for the gap to cross the threshold held that distance for the rest of the ride.Rebase notes
Upstream replaced
HasRealPlayerMaster,HasActivePlayerMasterandIsAltwithHasGameClientMasterandIsAltBot. Resolved by keeping the upstream shape and routingHasGameClientMasterthrough the validated accessor:Both helpers are null-safe, and the
master == botshort circuit inGetMaster()keeps selfbots out of a recursion throughIsSelfBot.feature/mount-behavior-v2-upstreamis the same commits rebased onto current upstream master, for the eventual upstream proposal. Its only conflicts were the east-const conversion touching the line above the two new declarations inCheckMountStateAction.h;apps/codestyle/codestyle-cpp.pypasses all checks on it.Status
Builds clean on both bases. Behaviour still needs review and hands-on testing before this is proposed upstream.