feat: port aelrynth 2026.9.27.2 snapshot onto GitHub history

Overlay upstream/main (9b5e276) onto BlankenshipG main without rewriting
history. Keep origin-only Decal/plugin/docs trees. Re-apply aelrynth.com
and sibling-fork URL fixes that aelrynth git still has as tombohar links.

Co-authored-by: BlankenshipG <BlankenshipG@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-10-04 15:43:50 +00:00
commit 4ddbb52eb2
No known key found for this signature in database
244 changed files with 59710 additions and 3067 deletions

View file

@ -0,0 +1,79 @@
// ============================================================================
// AcActionTrace.cs — Temporary diagnostic for Class B AVs (AC UIElement::
// GetAttribute_* AVs that fire with NO RynthCore frame on the faulting stack).
//
// Lock-free 256-entry ring buffer that records every RynthCore-issued AC-
// mutating call (SelectItem / UseObject / ChangeCombatMode / Cast / attacks)
// with a timestamp. Dumped to the log by ProcessExitHooks.LogTermination on
// any process-exit path so post-crash analysis shows the literal sequence of
// switches RynthCore made in the milliseconds before death — tests the
// "too many switches" hypothesis without behavioural change.
//
// Zero per-call allocation: struct array preallocated at startup, lock-free
// via Interlocked.Increment. Concurrent overwrites of the same slot are
// tolerated (rare at depth 256; we only need the rough recent sequence).
//
// REMOVE once Class B is diagnosed and fixed.
// ============================================================================
using System;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static class AcActionTrace
{
private struct Entry
{
public long Ticks; // DateTime.UtcNow.Ticks
public string Name; // string literal at call site → no per-call alloc
public uint A; // primary arg (typically objectId)
public uint B; // secondary arg (e.g. spellId, mode, attackHeight)
}
private const int Capacity = 256; // power of 2 for cheap mask
private const int Mask = Capacity - 1;
private static readonly Entry[] _slots = new Entry[Capacity];
private static int _next; // Interlocked-incremented counter
/// <summary>
/// Record an AC-mutating action at the engine callback entry. Safe from
/// any thread; per call cost = one Interlocked.Increment + 4 struct field
/// writes. Name MUST be a string literal (no per-call allocation).
/// </summary>
public static void Record(string name, uint a = 0, uint b = 0)
{
int slot = (Interlocked.Increment(ref _next) - 1) & Mask;
_slots[slot].Ticks = DateTime.UtcNow.Ticks;
_slots[slot].Name = name;
_slots[slot].A = a;
_slots[slot].B = b;
}
/// <summary>
/// Dump the buffer to the log. Called by ProcessExitHooks.LogTermination
/// on every termination path so the action history is preserved across
/// AV / fail-fast / clean exit.
/// </summary>
public static void DumpToLog()
{
try
{
int total = Volatile.Read(ref _next);
int count = Math.Min(total, Capacity);
int start = total - count;
RynthLog.Info($"[AcActionTrace] dumping last {count} actions (total counter={total}):");
for (int i = start; i < total; i++)
{
Entry e = _slots[i & Mask];
if (e.Name == null) continue;
DateTime dt = new DateTime(e.Ticks, DateTimeKind.Utc).ToLocalTime();
RynthLog.Info($"[AcActionTrace] {dt:HH:mm:ss.fff} {e.Name}(0x{e.A:X8}, 0x{e.B:X8})");
}
}
catch (Exception ex)
{
RynthLog.Info($"[AcActionTrace] dump exception: {ex.Message}");
}
}
}

View file

@ -0,0 +1,620 @@
using System;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
// Marshals off-thread bot ACTIONS onto AC's main (game) thread.
//
// AC is single-threaded and non-reentrant. The plugin pump (and chat-command /
// UI threads) run OFF AC's main thread; when they invoke AC state-mutating
// functions directly — combat-mode flips, melee/missile attacks, movement,
// object use — they race AC's own per-tick bookkeeping and corrupt its
// object / range lists. AC then access-violates LATER on its own thread during
// routine teardown / range recompute: the dump-verified object-teardown class
// 0x0055FA24 (List<ObjectRangeInfo>::remove via CPlayerSystem::CalculateObjectRangeChecks)
// and 0x00416C86 (DBOCache::DestroyObj). The per-callsite SEH trampoline only
// CONTAINS an AV that fires inside OUR call — it cannot stop AC tripping over
// corruption we left behind. The only real fix is to not mutate off-thread:
// enqueue here, execute on the main thread.
//
// Drained from the always-on EngineFrameController.OnEndScene tick (AC's main
// thread; ~22-33 Hz; fires regardless of EnableImGuiBackend / idle / combat).
//
// Multi-producer-safe: Enqueue takes a short lock (it runs on engine-owned
// threads, never inside an AC detour, so a lock is fine). Drain is the single
// consumer (the main thread) and is lock-free + zero-alloc, so it never blocks
// inside the reverse-P/Invoke detour and never reintroduces the GC-in-detour
// fail-fast class.
//
// The drain re-invokes the EXISTING public action methods. Each of those
// methods self-gates on MainThreadGuard.IsOnMainThread(): off-thread it
// enqueues here; on the main thread (i.e. when called from Drain, or from any
// legitimately main-thread caller) it executes the AC call directly. So there
// is no separate "Direct" body to keep in sync, and no risk of an enqueue loop.
//
// CASTS: routed via the separate cast slot below (EnqueueCast / DrainCasts),
// drained from AC's GAME-LOGIC tick (Client::UseTime, via GameTickHooks) — NOT
// EndScene. EndScene is the render phase and does not drive AC's cast state machine
// to completion (proven dead-end, reverted 2026-05-19); UseTime is where AC processes
// player actions, so the cast completes there. SelectItem is paired inside
// CombatActionHooks.CastSpell's main-thread path, so it stays ordered with the cast.
internal static class AcMainThreadQueue
{
internal enum ActionKind : byte
{
ChangeCombatMode,
MeleeAttack,
MissileAttack,
DoMovement,
StopMovement,
Jump,
UseObject,
// Item mutators marshalled 2026-06-05 (off-thread UseObjectOn/MoveItem/stack ops
// raced AC's per-tick object graph -> null-deref AVs in Client::UseTime, e.g.
// acclient+0xF24E0; same off-thread class as the P1 UseObject fix).
UseObjectOn,
UseEquippedItem,
MoveItemExternal,
MoveItemInternal,
SplitStackInternal,
MergeStackInternal,
GiveObjectTo,
// CommandInterpreter movement marshalled 2026-06-12: SetAutoRun /
// TurnToHeading / StopCompletely were the last direct off-thread AC
// mutators (dump-proven: a SetAutoRun executed 15s after a main thread
// had wedged) — they rewrite the locomotion channels of the SAME
// CommandInterpreter/motion graph the CSequence-AV class corrupts.
SetAutoRun,
TurnToHeading,
StopCompletely,
SetMotion,
// SetSelectedObject marshalled 2026-06-13: the host-API SelectItem /
// SetSelectedObjectId (looting/targeting) was the LAST AC-mutating helper
// still calling AC directly off the pump thread. AC's SetSelectedObject
// (0x0058D110) updates the selection/targeting UIElement subtree; run off
// the main thread it raced AC's own UI walk -> deterministic corruption AV
// at acclient+0x60D1D (UIElement smart-ptr refcount writeback into
// read-only .text, 5 captures in native-crash.log, two threads at once).
SetSelectedObject,
// NativeAttack marshalled 2026-09-01 (deep-audit finding #15): the
// ClientCombatSystem StartAttackRequest/EndAttackRequest pair (plus the
// height-change notify) had no MainThreadGuard gate, unlike the sibling
// MeleeAttack/MissileAttack/ChangeCombatMode. UseNativeAttack defaults
// true, so CombatManager.FireAttack ran this un-marshalled every fight
// right after a correctly-marshalled SelectItem on the same pump thread.
// Carried as one entry (not split) so the whole ordered sequence executes
// atomically after the paired selection, per the audit's fix note.
NativeAttack,
// Jump trio marshalled 2026-09-02 (deep-audit finding #2): CommenceJump/
// DoJump/TapJump call native CommandInterpreter members through
// _boundCmdInterp with zero MainThreadGuard gate — unlike every sibling
// (SetAutoRun/SetMotion/StopCompletely/TurnToHeading), which all marshal
// via this queue. Live-exercised off-thread today via Jumper.cs's
// Decal-coexistence pump-thread tick. CommenceJump and the later
// DoJump/LaunchJumpWithMotion release land in separate queue entries
// (separate ticks, ~msToHoldDown apart) — that's fine, the ordering
// just needs to stay FIFO within this single-consumer queue, which it does.
CommenceJump,
TapJump,
DoJumpAutonomous,
// LaunchJumpWithMotion (PlayerPhysicsHooks.cs) is the more dangerous of
// the two release paths: it Marshal.WriteInt32's directly into
// CMotionInterp's forward/strafe/turn fields with NO thread gate at
// all (not even the thiscall-through-delegate try/catch the
// CommandInterpreter trio has) before calling DoJump. A torn write here
// racing AC's own motion-graph tick is exactly the CSequence corruption
// class. Carries the 5 hold-flags packed into A (bit0=shift, bit1=W,
// bit2=X, bit3=Z, bit4=C).
LaunchJumpWithMotion,
}
// Four payload slots cover every routed action (the 4th was added for
// MoveItemInternal/SplitStackInternal: id, container, slot, amount). Floats are
// carried as their IEEE bit pattern in a uint slot (BitConverter round-trip).
private readonly struct Entry(AcMainThreadQueue.ActionKind kind, uint a, uint b, uint c, uint d)
{
public readonly ActionKind Kind = kind;
public readonly uint A = a;
public readonly uint B = b;
public readonly uint C = c;
public readonly uint D = d;
}
private const int Capacity = 256; // power of two
private const int Mask = Capacity - 1;
private static readonly Entry[] _slots = new Entry[Capacity];
private static readonly object _producerLock = new();
// Monotonic counters. Producers advance _tail under _producerLock; the sole
// consumer (main thread) advances _head.
private static int _head;
private static int _tail;
private static long _dropped;
public static long DroppedCount => Interlocked.Read(ref _dropped);
private static bool Enqueue(ActionKind kind, uint a, uint b, uint c, uint d = 0)
{
lock (_producerLock)
{
int tail = _tail;
int head = Volatile.Read(ref _head);
if (tail - head >= Capacity)
{
// Full. Drop rather than block or fall back to an off-thread AC
// mutation — a dropped movement/attack tick self-corrects on the
// next bot tick; an off-thread mutation can crash the client.
Interlocked.Increment(ref _dropped);
return false;
}
_slots[tail & Mask] = new Entry(kind, a, b, c, d);
Volatile.Write(ref _tail, tail + 1);
return true;
}
}
// ── Typed enqueue helpers (called by the public action methods when they
// detect they're running off AC's main thread) ───────────────────────
public static bool EnqueueChangeCombatMode(int mode) =>
Enqueue(ActionKind.ChangeCombatMode, unchecked((uint)mode), 0, 0);
public static bool EnqueueMeleeAttack(uint targetId, int attackHeight, float powerLevel) =>
Enqueue(ActionKind.MeleeAttack, targetId, unchecked((uint)attackHeight),
BitConverter.SingleToUInt32Bits(powerLevel));
public static bool EnqueueMissileAttack(uint targetId, int attackHeight, float accuracyLevel) =>
Enqueue(ActionKind.MissileAttack, targetId, unchecked((uint)attackHeight),
BitConverter.SingleToUInt32Bits(accuracyLevel));
public static bool EnqueueDoMovement(uint motion, float speed, int holdKey) =>
Enqueue(ActionKind.DoMovement, motion, unchecked((uint)holdKey),
BitConverter.SingleToUInt32Bits(speed));
public static bool EnqueueStopMovement(uint motion, int holdKey) =>
Enqueue(ActionKind.StopMovement, motion, unchecked((uint)holdKey), 0);
public static bool EnqueueSetAutoRun(bool enabled) =>
Enqueue(ActionKind.SetAutoRun, enabled ? 1u : 0u, 0, 0);
public static bool EnqueueTurnToHeading(float headingDegrees) =>
Enqueue(ActionKind.TurnToHeading, BitConverter.SingleToUInt32Bits(headingDegrees), 0, 0);
public static bool EnqueueStopCompletely() =>
Enqueue(ActionKind.StopCompletely, 0, 0, 0);
public static bool EnqueueSetMotion(uint motion, bool enabled) =>
Enqueue(ActionKind.SetMotion, motion, enabled ? 1u : 0u, 0);
public static bool EnqueueJump(float extent) =>
Enqueue(ActionKind.Jump, BitConverter.SingleToUInt32Bits(extent), 0, 0);
public static bool EnqueueUseObject(uint objectId) =>
Enqueue(ActionKind.UseObject, objectId, 0, 0);
public static bool EnqueueUseObjectOn(uint sourceObjectId, uint targetObjectId) =>
Enqueue(ActionKind.UseObjectOn, sourceObjectId, targetObjectId, 0);
public static bool EnqueueUseEquippedItem(uint sourceObjectId, uint targetObjectId) =>
Enqueue(ActionKind.UseEquippedItem, sourceObjectId, targetObjectId, 0);
public static bool EnqueueMoveItemExternal(uint objectId, uint targetContainerId, int amount) =>
Enqueue(ActionKind.MoveItemExternal, objectId, targetContainerId, unchecked((uint)amount));
public static bool EnqueueMoveItemInternal(uint objectId, uint targetContainerId, int slot, int amount) =>
Enqueue(ActionKind.MoveItemInternal, objectId, targetContainerId, unchecked((uint)slot), unchecked((uint)amount));
public static bool EnqueueSplitStackInternal(uint objectId, uint targetContainerId, int slot, int amount) =>
Enqueue(ActionKind.SplitStackInternal, objectId, targetContainerId, unchecked((uint)slot), unchecked((uint)amount));
public static bool EnqueueMergeStackInternal(uint sourceObjectId, uint targetObjectId) =>
Enqueue(ActionKind.MergeStackInternal, sourceObjectId, targetObjectId, 0);
public static bool EnqueueGiveObjectTo(uint objectId, uint targetId, int amount) =>
Enqueue(ActionKind.GiveObjectTo, objectId, targetId, unchecked((uint)amount));
public static bool EnqueueSetSelectedObject(uint objectId) =>
Enqueue(ActionKind.SetSelectedObject, objectId, 0, 0);
public static bool EnqueueNativeAttack(int attackHeight, float power) =>
Enqueue(ActionKind.NativeAttack, unchecked((uint)attackHeight),
BitConverter.SingleToUInt32Bits(power), 0);
public static bool EnqueueCommenceJump() => Enqueue(ActionKind.CommenceJump, 0, 0, 0);
public static bool EnqueueTapJump() => Enqueue(ActionKind.TapJump, 0, 0, 0);
public static bool EnqueueDoJumpAutonomous(bool autonomous) =>
Enqueue(ActionKind.DoJumpAutonomous, autonomous ? 1u : 0u, 0, 0);
public static bool EnqueueLaunchJumpWithMotion(bool shift, bool holdW, bool holdX, bool holdZ, bool holdC)
{
uint flags = (shift ? 1u : 0u) | (holdW ? 2u : 0u) | (holdX ? 4u : 0u) | (holdZ ? 8u : 0u) | (holdC ? 16u : 0u);
return Enqueue(ActionKind.LaunchJumpWithMotion, flags, 0, 0);
}
// Latched by EngineLifecycle.Shutdown: once teardown begins, queued plugin
// actions must NOT keep executing on AC's main thread — the detours stay
// live until MH_DisableHook(ALL), so without this latch a marshalled
// mutation (SetAutoRun etc.) can run mid-teardown against state that
// plugin Shutdowns are concurrently freeing (observed live at
// 2026-06-11 07:44:03: "Move: SetAutoRun(False)" fired between plugin
// shutdown steps). Abandoned entries are benign.
private static volatile bool _disarmed;
/// <summary>Stop executing queued actions/casts permanently (engine teardown).</summary>
public static void Disarm() => _disarmed = true;
// Single-consumer drain on AC's main thread (EngineFrameController.OnEndScene).
// Re-invokes the public action methods; on the main thread they execute the
// real AC call directly (their IsOnMainThread gate is satisfied here).
// Gesture-phase defer state for the action ring (mirrors the cast slot's
// 56e6946 guard; see DrainDeferTickCap note below for why we PROCEED
// rather than drop after the cap).
private static int _drainDeferTicks;
private const int DrainDeferTickCap = 250;
public static void Drain()
{
if (_disarmed) return;
// Deep-audit finding #22 (2026-06-18): these three queues are
// documented as deliberately separate from the gesture-gated action
// ring below specifically so appraisals/chat "can never get
// gesture-deferred" — but the gesture-defer early-return further
// down used to run BEFORE these calls, so a non-empty action ring
// sitting behind an in-flight gesture silently stalled chat output
// and 0xC8 appraisal sends too, contradicting that invariant. Each
// drains only while ITS OWN queue is non-empty, so moving them here
// costs nothing when they're empty (the common case).
DrainChat();
DrainChatCommands();
DrainRequestIds();
// Vendor buy/sell: a packet send through the client's own SendShopEvent, not a
// motion, so it sits with the non-gesture queues above. Also polls whether the
// vendor window is still open. Idle fast path when no vendor is open.
try { VendorTrade.MainThreadTick(); } catch { }
int head = _head; // only the main thread writes _head
int tail = Volatile.Read(ref _tail);
// ── Gesture-phase serialization (extends the 56e6946 anim-walk guard
// to the whole ring) ─────────────────────────────────────────────────
// Every ring action perturbs AC's action/motion state to some degree:
// UseObject starts a reach gesture, ChangeCombatMode rebuilds the
// motion graph, movement rewrites locomotion channels. Retail AC
// serializes these against the IN-FLIGHT gesture via its action queue;
// we previously serialized thread + tick-phase but not gesture-phase.
// Defer the drain while the pending-motion list [CMI+0x80] is
// non-empty — bounded, then PROCEED (unlike the cast slot we never
// drop: dropping arbitrary item/movement actions desyncs the bot far
// worse than a late injection, and the pre-2026-06-12 behavior was
// "always inject" anyway, so proceeding past the cap is never worse).
if (head != tail)
{
if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight
&& ++_drainDeferTicks <= DrainDeferTickCap)
return;
_drainDeferTicks = 0;
}
while (head != tail)
{
Entry e = _slots[head & Mask];
Volatile.Write(ref _head, ++head);
try
{
switch (e.Kind)
{
case ActionKind.ChangeCombatMode:
CombatActionHooks.ChangeCombatMode(unchecked((int)e.A));
break;
case ActionKind.MeleeAttack:
CombatActionHooks.MeleeAttack(e.A, unchecked((int)e.B),
BitConverter.UInt32BitsToSingle(e.C));
break;
case ActionKind.MissileAttack:
CombatActionHooks.MissileAttack(e.A, unchecked((int)e.B),
BitConverter.UInt32BitsToSingle(e.C));
break;
case ActionKind.DoMovement:
MovementActionHooks.DoMovement(e.A,
BitConverter.UInt32BitsToSingle(e.C), unchecked((int)e.B));
break;
case ActionKind.StopMovement:
MovementActionHooks.StopMovement(e.A, unchecked((int)e.B));
break;
case ActionKind.Jump:
MovementActionHooks.JumpNonAutonomous(BitConverter.UInt32BitsToSingle(e.A));
break;
case ActionKind.UseObject:
ClientHelperHooks.UseObject(e.A);
break;
case ActionKind.UseObjectOn:
ClientHelperHooks.UseObjectOn(e.A, e.B);
break;
case ActionKind.UseEquippedItem:
ClientHelperHooks.UseEquippedItem(e.A, e.B);
break;
case ActionKind.MoveItemExternal:
ClientHelperHooks.MoveItemExternal(e.A, e.B, unchecked((int)e.C));
break;
case ActionKind.MoveItemInternal:
ClientHelperHooks.MoveItemInternal(e.A, e.B, unchecked((int)e.C), unchecked((int)e.D));
break;
case ActionKind.SplitStackInternal:
ClientHelperHooks.SplitStackInternal(e.A, e.B, unchecked((int)e.C), unchecked((int)e.D));
break;
case ActionKind.MergeStackInternal:
ClientHelperHooks.MergeStackInternal(e.A, e.B);
break;
case ActionKind.GiveObjectTo:
ClientHelperHooks.GiveObjectTo(e.A, e.B, unchecked((int)e.C));
break;
case ActionKind.SetSelectedObject:
// On the main thread now -> SetSelectedObjectId's gate is
// satisfied and it calls AC's SetSelectedObject directly.
ClientHelperHooks.SetSelectedObjectId(e.A);
break;
case ActionKind.NativeAttack:
// On the main thread now -> NativeAttack's gate is
// satisfied and it fires the real StartAttackRequest/
// EndAttackRequest pair directly.
ClientCombatHooks.NativeAttack(unchecked((int)e.A),
BitConverter.UInt32BitsToSingle(e.B));
break;
case ActionKind.CommenceJump:
CommandInterpreterHooks.CommenceJump();
break;
case ActionKind.TapJump:
CommandInterpreterHooks.TapJump();
break;
case ActionKind.DoJumpAutonomous:
CommandInterpreterHooks.DoJump(e.A != 0);
break;
case ActionKind.LaunchJumpWithMotion:
PlayerPhysicsHooks.LaunchJumpWithMotion(
(e.A & 1u) != 0, (e.A & 2u) != 0, (e.A & 4u) != 0,
(e.A & 8u) != 0, (e.A & 16u) != 0);
break;
case ActionKind.SetAutoRun:
CommandInterpreterHooks.SetAutoRun(e.A != 0);
break;
case ActionKind.TurnToHeading:
CommandInterpreterHooks.TurnToHeading(BitConverter.UInt32BitsToSingle(e.A));
break;
case ActionKind.StopCompletely:
CommandInterpreterHooks.StopCompletely();
break;
case ActionKind.SetMotion:
CommandInterpreterHooks.SetMotion(e.A, e.B != 0);
break;
}
}
catch
{
// One action must never break the drain loop. (AC-side AVs are
// not managed exceptions and won't be caught here — but these
// now run on the correct thread, which is the whole point.)
}
tail = Volatile.Read(ref _tail);
}
}
// ── RequestId slot (0xC8 appraisal sends from AutoIdService) ──────────────────
// AutoIdService runs on a Timer thread; sending 0xC8 directly there does AC heap
// allocation + a non-atomic shared UI-counter increment off AC's main thread (the
// off-thread-send class flagged for RequestId). Marshal onto the main thread here.
// Kept in its OWN queue — NOT the gesture-deferred action ring above — so a backlog
// of appraisals can never crowd out combat/movement actions or get gesture-deferred:
// an appraisal is just a packet send and doesn't perturb AC's motion/UI state.
private static readonly System.Collections.Generic.Queue<uint> _requestIdQueue = new();
private static readonly object _requestIdLock = new();
private const int MaxRequestIdQueue = 256;
// Pump/Timer-thread enqueue. Drops (returns false) if the queue is full.
public static bool EnqueueRequestId(uint objectId)
{
if (objectId == 0) return false;
lock (_requestIdLock)
{
if (_requestIdQueue.Count >= MaxRequestIdQueue)
{
Interlocked.Increment(ref _dropped);
return false;
}
_requestIdQueue.Enqueue(objectId);
return true;
}
}
// Single-consumer drain on AC's main thread (from Drain()). On the main thread
// CombatActionHooks.RequestId sends the 0xC8 directly.
private static void DrainRequestIds()
{
while (true)
{
uint id;
lock (_requestIdLock)
{
if (_requestIdQueue.Count == 0) return;
id = _requestIdQueue.Dequeue();
}
try { CombatActionHooks.RequestId(id); } catch { }
}
}
// ── Chat slot (WriteToChat strings) ──────────────────────────────────────────
// WriteToChat carries a string, which can't ride the uint Entry queue. Off-thread
// AddTextToScroll races AC's chat-scroll buffer and corrupts it (the recurring
// 0x00460D1D write-AV that killed a 5h+ session 2026-06-05). Chat writes marshal
// here and drain on the main thread from Drain(), alongside the item/movement
// actions. WriteToChat's 100 ms rate-limit runs BEFORE the enqueue, so a bot retry
// burst is dropped on the pump thread and this queue never fills with spam.
private static readonly System.Collections.Generic.Queue<(string Text, int ChatType)> _chatQueue = new();
private static readonly object _chatLock = new();
private const int MaxChatQueue = 64;
// Pump-thread enqueue. Drops (returns false) if the queue is full.
public static bool EnqueueWriteToChat(string text, int chatType)
{
lock (_chatLock)
{
if (_chatQueue.Count >= MaxChatQueue)
{
Interlocked.Increment(ref _dropped);
return false;
}
_chatQueue.Enqueue((text, chatType));
return true;
}
}
// Single-consumer drain on AC's main thread. Re-invokes WriteToChat, whose
// IsOnMainThread gate is satisfied here so it runs AddTextToScroll directly.
private static void DrainChat()
{
while (true)
{
(string Text, int ChatType) item;
lock (_chatLock)
{
if (_chatQueue.Count == 0) return;
item = _chatQueue.Dequeue();
}
try { ClientHelperHooks.WriteToChat(item.Text, item.ChatType); }
catch { }
}
}
// ── Chat COMMAND slot (full ChatCommandDispatcher.Dispatch lines) ────────────
// Deep-audit finding #4 (2026-06-18): ChatCommandDispatcher.Dispatch is not
// network-only — it runs arbitrary plugin OnChatBarEnter handlers,
// constructs/destructs AC's native PStringBase<char> (alloc/free in AC's
// heap), and calls Event_Talk/Event_Emote/etc. directly against AC's live
// chat-manager, all of which assumed (incorrectly) "safe from any thread".
// Off-thread callers exist today: OnLoginCommandRunner (ThreadPool via
// Task.Run), ChatFileDispatcher (FileSystemWatcher thread), and
// Host.InvokeChatParser (plugin export, any thread). Gating inside
// Dispatch() itself (rather than at each caller) covers all three at once.
// A full command line can't ride the uint Entry ring, so it gets its own
// string queue, same shape as the WriteToChat slot above.
private static readonly System.Collections.Generic.Queue<string> _chatCommandQueue = new();
private static readonly object _chatCommandLock = new();
private const int MaxChatCommandQueue = 64;
// Off-thread enqueue. Drops (returns false) if the queue is full.
public static bool EnqueueChatCommand(string text)
{
lock (_chatCommandLock)
{
if (_chatCommandQueue.Count >= MaxChatCommandQueue)
{
Interlocked.Increment(ref _dropped);
return false;
}
_chatCommandQueue.Enqueue(text);
return true;
}
}
// Single-consumer drain on AC's main thread. Re-invokes Dispatch, whose
// IsOnMainThread gate is satisfied here so it runs the full body directly
// instead of re-enqueuing.
private static void DrainChatCommands()
{
while (true)
{
string text;
lock (_chatCommandLock)
{
if (_chatCommandQueue.Count == 0) return;
text = _chatCommandQueue.Dequeue();
}
try { ChatCommandDispatcher.Dispatch(text); }
catch { }
}
}
// ── Cast slot (SelectItem + CastSpell pair) ─────────────────────────────────
// Drained at AC's GAME-LOGIC tick (Client::UseTime via GameTickHooks), NOT the
// EndScene render tick. Single-outstanding: EnqueueCast returns false while a cast
// is pending so the off-thread caller (BuffManager / CombatManager) retries next
// tick — they already handle a false return without wedging. At ~frame-rate drain
// the slot clears within ~1 frame. This is the LAST off-thread AC mutator to be
// marshalled, closing the off-thread object-graph corruption class at its source.
private static int _castPending;
private static uint _castTargetId;
private static uint _castSpellId;
private static readonly object _castLock = new();
// Ticks DrainCasts has deferred the pending cast because a motion gesture was
// still in flight. Bounded so a stuck gesture (the documented wand-wield wedge
// variant) can't park a cast forever: past the cap the cast is DROPPED — the
// plugin's no-chat-resolve machinery already retries casts that produce no
// chat, so a drop degrades to one retry cycle, never a wedge.
private static int _castDeferTicks;
private static long _castDeferDrops;
private const int CastDeferTickCap = 250; // ~4-8 s at the 30-63 Hz UseTime rate
/// <summary>Casts dropped after deferring CastDeferTickCap ticks (stuck gesture).</summary>
public static long CastDeferDropCount => Interlocked.Read(ref _castDeferDrops);
// Pump-thread enqueue. Returns false (caller retries next tick) if a cast is
// already pending.
public static bool EnqueueCast(uint targetId, uint spellId)
{
lock (_castLock)
{
if (_castPending != 0) return false;
_castTargetId = targetId;
_castSpellId = spellId;
_castPending = 1;
return true;
}
}
// Drained on AC's MAIN thread from the Client::UseTime detour (game-logic tick).
// Re-invokes CombatActionHooks.CastSpell, which on the main thread executes the
// cast directly (SelectItem + ClientMagicSystem::CastSpell via the SEH trampoline).
public static void DrainCasts()
{
if (_disarmed) return; // engine teardown in progress
if (Volatile.Read(ref _castPending) == 0) return; // alloc-free fast path
// ── Anim-walk race guard (dump-proven 2026-06-12) ────────────────────
// DrainCasts runs PRE-tick (selection timing), but a cast initiates a
// wind-up gesture that REPLACES the player's pending CSequence motions —
// and the SAME UseTime call then walks that sequence. If a gesture is
// already mid-flight when we inject, the walker can hit a freed/null
// node: AV at acclient 0x00526840 AnimSequenceNode::get_part_frame
// [null+0xC], full stack in CrashDumps\acclient_anim_av_4716.dmp
// (7.6 h overnight soak, crash INSIDE _originalUseTime, our detour on
// the stack below it). Same mechanism the post-tick reorder fixed for
// UseObject/movement — casts were exempted and carried the residue.
// Defer while the pending-motion list is non-empty (the exact structure
// the tick walks); main-thread read, alloc-free, fail-open: if the read
// itself fails we cast (pre-fix behavior) rather than park.
if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight)
{
if (++_castDeferTicks <= CastDeferTickCap)
return; // retry next tick
// Gesture stuck past the cap — drop the cast instead of injecting
// into a wedged motion graph; the plugin retries via no-chat-resolve.
lock (_castLock) { _castPending = 0; }
_castDeferTicks = 0;
Interlocked.Increment(ref _castDeferDrops);
return;
}
_castDeferTicks = 0;
uint target, spell;
lock (_castLock)
{
if (_castPending == 0) return;
target = _castTargetId;
spell = _castSpellId;
_castPending = 0;
}
CombatActionHooks.CastSpell(target, unchecked((int)spell));
}
}

View file

@ -27,10 +27,20 @@ internal static class AccountHooks
{
private const int ReferenceClientGetInstance = 0x004114C0;
private const int ReferenceClientGetAccountName = 0x00401D90;
private const int SendNoticeWorldNameVa = 0x00693A60;
private const int SendNoticeWorldNameFallbackVa = 0x00693A60;
private const int PStringBufferLenOffset = 8;
private const int PStringBufferDataOffset = 20;
// ECM_Login::SendNotice_WorldName(AC1Legacy::PStringBase<char> const&) — bool (cdecl)
// Distinctive: vftable-call via push 0x186A2 (UI message ID for world-name notice).
private static readonly byte?[] SendNoticeWorldNamePattern =
[
0xE8, null, null, null, null, // call rel32
0x8B, 0x10, 0x68, 0xA2, 0x86, 0x01, 0x00, // mov edx,[eax]; push 0x186A2
0x8B, 0xC8, 0xFF, 0x52, 0x10, // mov ecx,eax; call [edx+0x10]
0x85, 0xC0, 0x74, 0x22, 0x56, 0x8B, 0x70, 0x04
];
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr ClientGetInstanceDelegate();
@ -94,43 +104,34 @@ internal static class AccountHooks
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
RynthLog.Compat("Compat: world-name hook skipped - acclient.exe not available.");
RynthLog.Compat("AccountHooks: world-name hook skipped - acclient.exe not available.");
return;
}
int funcOff = SendNoticeWorldNameVa - textSection.TextBaseVa;
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
{
RynthLog.Compat($"Compat: world-name hook failed - VA 0x{SendNoticeWorldNameVa:X8} out of text section range.");
var resolved = HookResolver.Resolve(textSection, "AccountHooks.SendNotice_WorldName",
SendNoticeWorldNamePattern, SendNoticeWorldNameFallbackVa);
if (!resolved.Success)
return;
}
byte firstByte = textSection.Bytes[funcOff];
if (firstByte is 0x00 or 0xCC or 0xC3)
{
RynthLog.Compat($"Compat: world-name hook failed - invalid opcode 0x{firstByte:X2} @ 0x{SendNoticeWorldNameVa:X8}.");
return;
}
IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_sendNoticeWorldNameDetour = SendNoticeWorldNameDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_sendNoticeWorldNameDetour);
_originalSendNoticeWorldName = Marshal.GetDelegateForFunctionPointer<SendNoticeWorldNameDelegate>(
MinHook.HookCreate(targetAddress, detourPtr));
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(targetAddress);
MinHook.Enable(resolved.Address);
WorldHookInstalled = true;
RynthLog.Verbose($"Compat: world-name hook ready - ECM_Login::SendNotice_WorldName @ 0x{targetAddress.ToInt32():X8}.");
RynthLog.Compat($"AccountHooks: world-name hook ready @ 0x{resolved.Address.ToInt32():X8}.");
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: world-name hook failed - {ex.Message}");
RynthLog.Compat($"AccountHooks: world-name hook install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static byte SendNoticeWorldNameDetour(IntPtr pstringPtr)
{
RecursionGuard.Tick("AccountHooks.SendNoticeWorldName");
byte result = 0;
try { result = _originalSendNoticeWorldName!(pstringPtr); } catch { }
@ -143,7 +144,10 @@ internal static class AccountHooks
if (bufferPtr != IntPtr.Zero && IsReadable(bufferPtr + PStringBufferDataOffset))
{
int len = Marshal.ReadInt32(bufferPtr + PStringBufferLenOffset);
if (len > 1)
// Clamp + length-aware check (finding #29): len comes from
// AC's own heap, only floor-checked before — a corrupt/torn
// value could otherwise drive a copy past the committed page.
if (len > 1 && len <= 256 && IsReadable(bufferPtr + PStringBufferDataOffset, len - 1))
{
string? name = Marshal.PtrToStringAnsi(bufferPtr + PStringBufferDataOffset, len - 1);
if (!string.IsNullOrEmpty(name))
@ -192,7 +196,9 @@ internal static class AccountHooks
return false;
int len = Marshal.ReadInt32(bufferPtr + PStringBufferLenOffset);
if (len <= 1)
// Clamp + length-aware check (finding #29): same rationale as
// SendNoticeWorldNameDetour above.
if (len <= 1 || len > 256 || !IsReadable(bufferPtr + PStringBufferDataOffset, len - 1))
return false;
string? str = Marshal.PtrToStringAnsi(bufferPtr + PStringBufferDataOffset, len - 1);
@ -268,4 +274,23 @@ internal static class AccountHooks
if ((mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0) return false;
return true;
}
// Deep-audit finding #29 (2026-06-18): the single-arg IsReadable above
// only validates the START page. All three PtrToStringAnsi call sites in
// this file then do a len-driven copy (len from AC's own heap, only
// floor-checked at >1) that can cross into an uncommitted page if len is
// corrupt or torn — a length-aware check (mirroring CrashLogger's
// IsReadable(addr, bytes), which isn't accessible from here) is needed
// for the actual byte span being copied, not just its first byte.
private static bool IsReadable(IntPtr ptr, int bytes)
{
if (ptr == IntPtr.Zero || bytes <= 0) return false;
if (VirtualQuery(ptr, out var mbi, Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0) return false;
if (mbi.State != MEM_COMMIT) return false;
if ((mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0) return false;
long endRequested = ptr.ToInt64() + bytes;
long endRegion = mbi.BaseAddress.ToInt64() + mbi.RegionSize.ToInt64();
return endRequested <= endRegion;
}
}

View file

@ -79,6 +79,32 @@ internal static class AppraisalHooks
return _appraisedGuids.Contains(guid);
}
/// <summary>
/// Deep-audit finding #33 (2026-06-18): these seven session-scoped
/// collections were populated per appraised guid and never cleared or
/// bounded — no ClearSession() existed, and this class was conspicuously
/// absent from DispatchPendingLogout's reset pipeline (contrast the peer
/// ObjectQualityCache, which has both MaxEntries and a logout
/// ClearSession()). Guids don't survive a session, so a daily
/// multi-boxer accumulates entries indefinitely across relogs — worth
/// closing given this stack's documented 32-bit VA-exhaustion
/// sensitivity even though growth itself is slow. Call from
/// DispatchPendingLogout alongside the other ResetSession() calls.
/// </summary>
public static void ClearSession()
{
lock (_cacheLock)
{
_appraisedGuids.Clear();
_lastIdTime.Clear();
_intCache.Clear();
_boolCache.Clear();
_stringCache.Clear();
_spellIdCache.Clear();
_failedRollLogged.Clear();
}
}
/// <summary>
/// Returns the Unix timestamp (seconds) of when appraisal data was last received for this guid, or 0 if never.
/// </summary>
@ -228,37 +254,61 @@ internal static class AppraisalHooks
try { RynthLog.Compat($"Compat: appraisal spell cache error guid=0x{guid:X8} - {ex.GetType().Name}: {ex.Message}"); } catch { }
}
try
{
CacheCreatureVitals(guid, profilePtr);
}
catch (Exception ex)
{
try { RynthLog.Compat($"Compat: appraisal creature-vitals error guid=0x{guid:X8} - {ex.GetType().Name}: {ex.Message}"); } catch { }
}
return result;
}
private static void CacheIntProps(uint guid, IntPtr profilePtr)
{
if (profilePtr == IntPtr.Zero)
if (profilePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(profilePtr))
return;
// AppraisalProfile._intStatsTable* is at offset +0x18
IntPtr intTablePtr = Marshal.ReadIntPtr(profilePtr + 0x18);
if (intTablePtr == IntPtr.Zero)
IntPtr intTableFieldAddr = profilePtr + 0x18;
if (!ClientObjectHooks.IsReadablePointer(intTableFieldAddr))
return;
IntPtr intTablePtr = Marshal.ReadIntPtr(intTableFieldAddr);
if (intTablePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(intTablePtr))
return;
// PackableHashTable<uint,int>: bucket_array at +0x8, bucket_count at +0xC
IntPtr bucketArray = Marshal.ReadIntPtr(intTablePtr + 0x08);
int bucketCount = Marshal.ReadInt32(intTablePtr + 0x0C);
IntPtr bucketArrayFieldAddr = intTablePtr + 0x08;
IntPtr bucketCountFieldAddr = intTablePtr + 0x0C;
if (!ClientObjectHooks.IsReadablePointer(bucketArrayFieldAddr) || !ClientObjectHooks.IsReadablePointer(bucketCountFieldAddr))
return;
IntPtr bucketArray = Marshal.ReadIntPtr(bucketArrayFieldAddr);
int bucketCount = Marshal.ReadInt32(bucketCountFieldAddr);
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536)
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536 || !ClientObjectHooks.IsReadablePointer(bucketArray))
return;
var props = new Dictionary<uint, int>(8);
int totalGuard = 0;
for (int i = 0; i < bucketCount; i++)
{
IntPtr node = Marshal.ReadIntPtr(bucketArray + i * 4);
while (node != IntPtr.Zero)
IntPtr bucketSlotAddr = bucketArray + i * 4;
if (!ClientObjectHooks.IsReadablePointer(bucketSlotAddr)) continue;
IntPtr node = Marshal.ReadIntPtr(bucketSlotAddr);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < 4096 && totalGuard++ < 65536)
{
if (!ClientObjectHooks.IsReadablePointer(node)) break;
uint key = (uint)Marshal.ReadInt32(node);
int val = Marshal.ReadInt32(node + 4);
props[key] = val;
node = Marshal.ReadIntPtr(node + 8);
IntPtr nextAddr = node + 8;
if (!ClientObjectHooks.IsReadablePointer(nextAddr)) break;
node = Marshal.ReadIntPtr(nextAddr);
}
}
@ -275,32 +325,47 @@ internal static class AppraisalHooks
private static void CacheBoolProps(uint guid, IntPtr profilePtr)
{
if (profilePtr == IntPtr.Zero)
if (profilePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(profilePtr))
return;
// AppraisalProfile._boolStatsTable* is at offset +0x20
IntPtr boolTablePtr = Marshal.ReadIntPtr(profilePtr + 0x20);
if (boolTablePtr == IntPtr.Zero)
IntPtr boolTableFieldAddr = profilePtr + 0x20;
if (!ClientObjectHooks.IsReadablePointer(boolTableFieldAddr))
return;
IntPtr boolTablePtr = Marshal.ReadIntPtr(boolTableFieldAddr);
if (boolTablePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(boolTablePtr))
return;
// PackableHashTable: bucket_array at +0x8, bucket_count at +0xC
IntPtr bucketArray = Marshal.ReadIntPtr(boolTablePtr + 0x08);
int bucketCount = Marshal.ReadInt32(boolTablePtr + 0x0C);
IntPtr bucketArrayFieldAddr = boolTablePtr + 0x08;
IntPtr bucketCountFieldAddr = boolTablePtr + 0x0C;
if (!ClientObjectHooks.IsReadablePointer(bucketArrayFieldAddr) || !ClientObjectHooks.IsReadablePointer(bucketCountFieldAddr))
return;
IntPtr bucketArray = Marshal.ReadIntPtr(bucketArrayFieldAddr);
int bucketCount = Marshal.ReadInt32(bucketCountFieldAddr);
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536)
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536 || !ClientObjectHooks.IsReadablePointer(bucketArray))
return;
var props = new Dictionary<uint, bool>(4);
int totalGuard = 0;
for (int i = 0; i < bucketCount; i++)
{
IntPtr node = Marshal.ReadIntPtr(bucketArray + i * 4);
while (node != IntPtr.Zero)
IntPtr bucketSlotAddr = bucketArray + i * 4;
if (!ClientObjectHooks.IsReadablePointer(bucketSlotAddr)) continue;
IntPtr node = Marshal.ReadIntPtr(bucketSlotAddr);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < 4096 && totalGuard++ < 65536)
{
if (!ClientObjectHooks.IsReadablePointer(node)) break;
uint key = (uint)Marshal.ReadInt32(node);
int val = Marshal.ReadInt32(node + 4);
props[key] = val != 0;
node = Marshal.ReadIntPtr(node + 8);
IntPtr nextAddr = node + 8;
if (!ClientObjectHooks.IsReadablePointer(nextAddr)) break;
node = Marshal.ReadIntPtr(nextAddr);
}
}
@ -317,45 +382,65 @@ internal static class AppraisalHooks
private static void CacheStringProps(uint guid, IntPtr profilePtr)
{
if (profilePtr == IntPtr.Zero)
if (profilePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(profilePtr))
return;
// AppraisalProfile._strStatsTable* is at offset +0x28
IntPtr strTablePtr = Marshal.ReadIntPtr(profilePtr + 0x28);
if (strTablePtr == IntPtr.Zero)
IntPtr strTableFieldAddr = profilePtr + 0x28;
if (!ClientObjectHooks.IsReadablePointer(strTableFieldAddr))
return;
IntPtr strTablePtr = Marshal.ReadIntPtr(strTableFieldAddr);
if (strTablePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(strTablePtr))
return;
// PackableHashTable<uint, PStringBase<char>>: bucket_array at +0x8, bucket_count at +0xC
IntPtr bucketArray = Marshal.ReadIntPtr(strTablePtr + 0x08);
int bucketCount = Marshal.ReadInt32(strTablePtr + 0x0C);
IntPtr bucketArrayFieldAddr = strTablePtr + 0x08;
IntPtr bucketCountFieldAddr = strTablePtr + 0x0C;
if (!ClientObjectHooks.IsReadablePointer(bucketArrayFieldAddr) || !ClientObjectHooks.IsReadablePointer(bucketCountFieldAddr))
return;
IntPtr bucketArray = Marshal.ReadIntPtr(bucketArrayFieldAddr);
int bucketCount = Marshal.ReadInt32(bucketCountFieldAddr);
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536)
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536 || !ClientObjectHooks.IsReadablePointer(bucketArray))
return;
var props = new Dictionary<uint, string>(4);
int totalGuard = 0;
for (int i = 0; i < bucketCount; i++)
{
IntPtr node = Marshal.ReadIntPtr(bucketArray + i * 4);
while (node != IntPtr.Zero)
IntPtr bucketSlotAddr = bucketArray + i * 4;
if (!ClientObjectHooks.IsReadablePointer(bucketSlotAddr)) continue;
IntPtr node = Marshal.ReadIntPtr(bucketSlotAddr);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < 4096 && totalGuard++ < 65536)
{
if (!ClientObjectHooks.IsReadablePointer(node)) break;
uint key = (uint)Marshal.ReadInt32(node);
// Node value at +4: PStringBase<char>.m_buffer (PSRefBuffer<char>*)
// PSRefBuffer<char> layout: vtable(4) + m_cRef(4) + m_len(4) + m_size(4) + m_hash(4) + m_data[]
IntPtr bufferPtr = Marshal.ReadIntPtr(node + 4);
if (bufferPtr != IntPtr.Zero)
if (bufferPtr != IntPtr.Zero && ClientObjectHooks.IsReadablePointer(bufferPtr))
{
int len = Marshal.ReadInt32(bufferPtr + 8);
if (len > 1)
IntPtr lenFieldAddr = bufferPtr + 8;
if (ClientObjectHooks.IsReadablePointer(lenFieldAddr))
{
string? str = Marshal.PtrToStringAnsi(bufferPtr + 20, len - 1);
if (!string.IsNullOrEmpty(str))
props[key] = str;
int len = Marshal.ReadInt32(lenFieldAddr);
IntPtr strDataAddr = bufferPtr + 20;
if (len > 1 && len < 4096 && ClientObjectHooks.IsReadablePointer(strDataAddr))
{
string? str = Marshal.PtrToStringAnsi(strDataAddr, len - 1);
if (!string.IsNullOrEmpty(str))
props[key] = str;
}
}
}
node = Marshal.ReadIntPtr(node + 8);
IntPtr nextAddr = node + 8;
if (!ClientObjectHooks.IsReadablePointer(nextAddr)) break;
node = Marshal.ReadIntPtr(nextAddr);
}
}
@ -405,6 +490,86 @@ internal static class AppraisalHooks
RynthLog.Verbose($"Compat: cached {mNum} spell ID(s) for guid=0x{guid:X8}");
}
// Rate-limit counter for the creature-vitals diagnostic log line.
private static int _creatureVitalsLogCount;
// Guids already logged with a [FAILED-ROLL] line (dedupe; guarded by _cacheLock).
private static readonly HashSet<uint> _failedRollLogged = new();
/// <summary>
/// Reads the creature sub-profile (AppraisalProfile+0x08 → CreatureAppraisalProfile) for
/// absolute Health/MaxHealth/Stamina/Mana and publishes them to ObjectQualityCache (polled
/// via RynthCoreHost.TryGetTargetVitals) and to plugins (OnUpdateHealth push, e.g. RynthAi's
/// CreatureProfileStore / RynthJuice numbers).
///
/// This is the ONLY opcode that carries a monster's *absolute* max HP — the 0xC9 appraisal
/// CreatureProfile. The 0x01C0 combat stream is ratio-only (ACE divides Current/MaxValue
/// server-side). This hook (CM_Examine::SendNotice_SetAppraiseInfo @ 0x006B05B0) is the live
/// appraisal seam on ACE; the older wire-parse in CombatActionHooks.TryParseIdentifyResponse
/// is dead (its InnerDispatcher caller is disabled and the SmartBox caller was removed).
///
/// Offsets verified from CreatureAppraisalProfile::InqAttribute2nd (decompile 0x005B6ED0):
/// MaxHealth=+0x28 Health=+0x1C MaxStamina=+0x2C Stamina=+0x20 MaxMana=+0x30 Mana=+0x24.
/// The +0x08 pointer is non-null only when the appraisal carried a CreatureProfile (creatures
/// that are not NPCLooksLikeObject); items/hooks leave it 0 (AppraisalProfile::Clear layout).
/// It is the engine's own live struct for this dispatch frame, so the read is safe under the
/// same try/catch the sibling Cache* helpers use — no native call, no AC mutation.
///
/// Crucially this captures max even on a FAILED assess roll: ACE assigns Health/HealthMax
/// before the success gate (CreatureProfile.cs), so no AssessCreature skill is required.
/// </summary>
private static void CacheCreatureVitals(uint guid, IntPtr profilePtr)
{
if (profilePtr == IntPtr.Zero)
return;
// AppraisalProfile._creatureProfile* is at offset +0x08.
IntPtr creaturePtr = Marshal.ReadIntPtr(profilePtr + 0x08);
if (creaturePtr == IntPtr.Zero)
return; // non-creature appraisal (item / hook) — no vitals present
uint maxHealth = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x28));
if (maxHealth == 0 || maxHealth >= 1_000_000)
return; // unset / implausible — don't poison the cache
uint health = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x1C));
uint stamina = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x20));
uint maxStamina = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x2C));
uint mana = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x24));
uint maxMana = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x30));
if (health > maxHealth)
health = maxHealth; // clamp a transient over-read
ObjectQualityCache.SetCreatureVitals(guid,
new CreatureVitals(health, maxHealth, stamina, maxStamina, mana, maxMana));
float ratio = (float)health / maxHealth;
Plugins.PluginManager.QueueUpdateHealth(guid, ratio, health, maxHealth);
// ShowAttributes (wire flag 0x8) is CLEAR on a FAILED assess roll; CreatureAppraisalProfile::UnPack
// (decompile 0x005B7240, lines 31-42) then EXPLICITLY zeroes stamina/mana/attributes — so
// (maxStamina==0 && maxMana==0) is a reliable failed-roll signal, while Health/MaxHealth are written
// unconditionally. A failed-roll line therefore PROVES the un-gated capture (max obtained with no
// attributes). Failed rolls are rare (most mobs have Deception==0 → success forced) and are the whole
// point of this hook, so log them ALWAYS (greppable [FAILED-ROLL] tag); rate-limit the common success case.
if (maxStamina == 0 && maxMana == 0)
{
// Failed roll. Dedupe per guid — the combat target gets re-appraised ~1/0.75s, which would
// otherwise spam the log (and bloat it over a grind). Log the first capture per mob only.
bool firstForGuid;
lock (_cacheLock)
firstForGuid = _failedRollLogged.Add(guid);
if (firstForGuid)
RynthLog.Compat($"Compat: appraisal creature vitals [FAILED-ROLL] guid=0x{guid:X8} hp={health}/{maxHealth} (stam/mana withheld — max captured anyway)");
}
else
{
int log = Interlocked.Increment(ref _creatureVitalsLogCount);
if (log <= 50)
RynthLog.Compat($"Compat: appraisal creature vitals guid=0x{guid:X8} hp={health}/{maxHealth} stam={stamina}/{maxStamina} mana={mana}/{maxMana}");
}
}
/// <summary>
/// Fills <paramref name="output"/> with spell IDs from the last appraisal spell book.
/// Returns the total number of spell IDs (may exceed <paramref name="maxCount"/>), or -1 if no data.

View file

@ -41,6 +41,20 @@ internal static class AutoIdService
RynthLog.Verbose("Compat: AutoIdService started.");
}
/// <summary>
/// Dispose the drain timer at engine shutdown so it doesn't keep firing in
/// the old generation's (intentionally still-mapped) module across hot-reloads.
/// </summary>
public static void Stop()
{
if (!_started)
return;
_started = false;
_drainTimer?.Dispose();
_drainTimer = null;
RynthLog.Verbose("Compat: AutoIdService stopped.");
}
/// <summary>
/// Enqueue an object for automatic appraisal. Called from CreateObjectHooks detour.
/// </summary>
@ -69,6 +83,9 @@ internal static class AutoIdService
_sent.TryRemove(objectId, out _);
}
// Last target we issued a priority appraisal for (fires once per target change).
private static uint _lastPriorityTarget;
private static void DrainTick(object? state)
{
try
@ -77,13 +94,30 @@ internal static class AutoIdService
return;
int sent = 0;
// Combat-target priority: when the selected target CHANGES, appraise it
// immediately — enqueued ahead of the create-order backlog so a fast kill
// still gets its max-HP appraisal out first instead of waiting behind the
// whole spawn. Fires once per change (guarded), so no per-tick re-appraisal.
uint target = SelectedTargetHooks.ReadCurrentSelectedId();
if (target != 0 && target != _lastPriorityTarget)
{
_lastPriorityTarget = target;
uint playerId = ClientHelperHooks.GetPlayerId();
if (target != playerId && AcMainThreadQueue.EnqueueRequestId(target))
sent++;
}
while (sent < MaxPerTick && _queue.TryDequeue(out uint objectId))
{
// Object may have been destroyed between enqueue and drain
if (objectId == 0)
continue;
ClientActionHooks.RequestId(objectId);
// Marshal onto AC's main thread (EndScene drain) — the Timer thread must
// not call the native 0xC8 send directly (off-thread heap alloc + non-atomic
// UI-counter increment). EnqueueRequestId is the marshalled path.
AcMainThreadQueue.EnqueueRequestId(objectId);
sent++;
}
}

View file

@ -8,15 +8,44 @@ namespace RynthCore.Engine.Compatibility;
internal static class BusyCountHooks
{
private const int IncrementBusyCountVa = 0x00565610;
private const int DecrementBusyCountVa = 0x00565630;
// ClientUISystem::UpdateCursorState — per-frame cursor evaluation
private const int UpdateCursorStateVa = 0x005653D0;
// Fallback VAs (4,841,472-byte client). Pattern-scan is now the source of truth.
private const int IncrementBusyCountFallbackVa = 0x00565610;
private const int DecrementBusyCountFallbackVa = 0x00565630;
private const int UpdateCursorStateFallbackVa = 0x005653D0;
// ClientUISystem struct field offset for m_cBusy (confirmed via runtime dump)
private const int OffsetMCBusy = 0x14;
// ClientUISystem::IncrementBusyCount — entire function is short:
// mov edx,[ecx+14]; inc edx; mov eax,edx; cmp eax,1; mov [ecx+14],edx;
// jne +5; jmp UpdateCursorState; ret
private static readonly byte?[] IncrementBusyCountPattern =
[
0x8B, 0x51, 0x14, 0x42, 0x8B, 0xC2, 0x83, 0xF8,
0x01, 0x89, 0x51, 0x14, 0x75, 0x05,
0xE9, null, null, null, null, // jmp rel32 -> UpdateCursorState
0xC3
];
// ClientUISystem::DecrementBusyCount — also short:
// dec [ecx+14]; jne +5; jmp UpdateCursorState; ret
private static readonly byte?[] DecrementBusyCountPattern =
[
0xFF, 0x49, 0x14, 0x75, 0x05,
0xE9, null, null, null, null, // jmp rel32 -> UpdateCursorState
0xC3
];
// ClientUISystem::UpdateCursorState — large prologue with cmp/setcc pair.
private static readonly byte?[] UpdateCursorStatePattern =
[
0x83, 0xEC, 0x08, 0x53, 0x55, 0x56, 0x57, 0x89,
0x4C, 0x24, 0x10,
0xE8, null, null, null, null, // call rel32
0x85, 0xC0, 0x0F, 0x95, 0xC3, 0x33, 0xC0, 0x84,
0xDB
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void BusyCountDelegate(IntPtr thisPtr);
@ -29,6 +58,7 @@ internal static class BusyCountHooks
private static BusyCountDelegate? _decrementBusyCountDetour;
private static IntPtr _incrementTargetAddress;
private static IntPtr _decrementTargetAddress;
private static IntPtr _updateCursorStateAddress;
private static string _statusMessage = "Not probed yet.";
private static int _incrementDispatchCount;
private static int _decrementDispatchCount;
@ -41,18 +71,67 @@ internal static class BusyCountHooks
/// <summary>Returns 0 if the character is idle, positive if a UI action is in progress.</summary>
public static int GetBusyState() => Math.Max(0, _netBusyCount);
/// <summary>Force-reset the client's busy count to zero and re-evaluate the cursor.
/// Directly writes m_cBusy=0 then calls UpdateCursorState so the game
/// switches from hourglass back to the default arrow.</summary>
public static void ForceResetBusyCount()
/// <summary>
/// Force-reset the client's busy count to zero and re-evaluate the cursor.
/// <paramref name="clearMotion"/> additionally flushes the command
/// interpreter (ClearAllCommands/TakeControlFromServer/PlayerTeleported) —
/// ⚠ DANGEROUS and OFF by default: AC only runs that triplet inside full
/// teleport flows that also reset the physics sequence. Fired standalone
/// around a live gesture it can leave the player's CSequence with a null
/// current anim node → AC's next animation tick AVs at acclient 0x5264A9
/// reading null+0xC (CSequence::update_internal). Diagnosed live
/// 2026-06-11: the loot busy-watchdog called this every ~2s for an hour
/// (every corpse open leaks +1 m_cBusy) and one clear landed in the
/// gesture window. The busy UNSTICK itself only needs the decrement loop +
/// cursor refresh below. Even when requested, the motion flush is skipped
/// while a cast/action gesture is animating.
/// </summary>
// Session counters surfaced in the heartbeat so a soak shows the busy-fix
// machinery working: fcl = force-clears performed, rec = cast/item-action
// reconciles performed. A healthy post-fix soak should see rec climb during
// combat/looting and fcl stay near-flat (force-clear is now just a backstop).
private static long _forceClearCount;
private static long _reconcileCount;
public static long ForceClearCount => Interlocked.Read(ref _forceClearCount);
public static long ReconcileCount => Interlocked.Read(ref _reconcileCount);
// Off-thread force-reset requests latch here and are consumed by
// CheckWatchdog on the main thread (post-tick). ≤1 tick latency —
// irrelevant for a 2-5s watchdog; coalesces bursts for free.
private static int _forceResetRequested;
public static void ForceResetBusyCount(bool clearMotion = false)
{
// ⚠ MAIN THREAD ONLY (2026-06-12 cross-incident forensics, top-ranked
// corruption writer): the plugin host API called this raw from the
// pump thread 284-471×/session — up to 20 native DecrementBusyCount
// calls (each falling through into UpdateCursorState's UI/object-graph
// walk) plus a raw m_cBusy write, concurrent with AC's main thread.
// Leading suspect for the LFH heap detonation (ntdll+0x87D99, free()
// during object teardown, last off-thread clear ≤1s before the AV).
// Off-thread callers latch a request consumed post-tick instead.
if (!MainThreadGuard.IsOnMainThread())
{
Interlocked.Exchange(ref _forceResetRequested, 1);
return;
}
if (!IsInstalled || _lastThisPtr == IntPtr.Zero)
return;
Interlocked.Increment(ref _forceClearCount);
// Never mutate through a stale pointer: after logout/close AC frees the
// ClientUISystem singleton, and the decrement/cursor calls below would
// run native code against freed memory (uncatchable under NativeAOT).
if (!ClientObjectHooks.IsReadablePointer(_lastThisPtr + OffsetMCBusy))
{
RynthLog.Compat("BusyCountHooks: ForceResetBusyCount skipped — cached ClientUISystem pointer is no longer readable.");
_lastThisPtr = IntPtr.Zero;
return;
}
int was = _netBusyCount;
// Call the original decrement a few times to let the client run
// its own cleanup path (cursor reset, etc) for any non-zero count.
if (_originalDecrementBusyCount != null)
{
int calls = Math.Max(was, 3);
@ -62,24 +141,35 @@ internal static class BusyCountHooks
Interlocked.Exchange(ref _netBusyCount, 0);
// Directly zero m_cBusy — DecrementBusyCount guards with if(m_cBusy>0)
// so it's a no-op when our tracked count drifts from the real value.
try { Marshal.WriteInt32(_lastThisPtr + OffsetMCBusy, 0); }
catch { /* non-fatal */ }
// Clear pending commands and restore client control
CommandInterpreterHooks.ClearAllCommands();
CommandInterpreterHooks.TakeControlFromServer();
CommandInterpreterHooks.PlayerTeleported();
// Force the game's own cursor evaluation with the cleared state
try
if (clearMotion)
{
var updateCursor = Marshal.GetDelegateForFunctionPointer<UpdateCursorStateDelegate>(
new IntPtr(UpdateCursorStateVa));
updateCursor(_lastThisPtr);
bool gesture = false;
try { if (!PlayerPhysicsHooks.TryGetCastGestureInProgress(out gesture)) gesture = false; }
catch { gesture = false; }
if (gesture)
{
RynthLog.Compat("BusyCountHooks: motion flush SKIPPED — a gesture is animating (the CSequence-corruption window).");
}
else
{
CommandInterpreterHooks.ClearAllCommands();
CommandInterpreterHooks.TakeControlFromServer();
CommandInterpreterHooks.PlayerTeleported();
}
}
if (_updateCursorStateAddress != IntPtr.Zero)
{
try
{
var updateCursor = Marshal.GetDelegateForFunctionPointer<UpdateCursorStateDelegate>(_updateCursorStateAddress);
updateCursor(_lastThisPtr);
}
catch { /* non-fatal */ }
}
catch { /* non-fatal */ }
RynthLog.Verbose($"Compat: force-reset busy count (was {was})");
}
@ -95,75 +185,318 @@ internal static class BusyCountHooks
return;
}
int incrementOff = IncrementBusyCountVa - textSection.TextBaseVa;
int decrementOff = DecrementBusyCountVa - textSection.TextBaseVa;
if (!LooksHookable(textSection.Bytes, incrementOff, out byte incrementByte))
{
_statusMessage = $"ClientUISystem::IncrementBusyCount looks invalid @ 0x{IncrementBusyCountVa:X8}.";
RynthLog.Compat($"Compat: busy-count hook failed - {_statusMessage}");
return;
}
var inc = HookResolver.Resolve(textSection, "BusyCountHooks.IncrementBusyCount",
IncrementBusyCountPattern, IncrementBusyCountFallbackVa);
var dec = HookResolver.Resolve(textSection, "BusyCountHooks.DecrementBusyCount",
DecrementBusyCountPattern, DecrementBusyCountFallbackVa);
var cursor = HookResolver.Resolve(textSection, "BusyCountHooks.UpdateCursorState",
UpdateCursorStatePattern, UpdateCursorStateFallbackVa);
if (!LooksHookable(textSection.Bytes, decrementOff, out byte decrementByte))
if (cursor.Success) _updateCursorStateAddress = cursor.Address;
if (!inc.Success || !dec.Success)
{
_statusMessage = $"ClientUISystem::DecrementBusyCount looks invalid @ 0x{DecrementBusyCountVa:X8}.";
RynthLog.Compat($"Compat: busy-count hook failed - {_statusMessage}");
_statusMessage = $"Resolve failed — increment={inc.Detail}, decrement={dec.Detail}.";
RynthLog.Compat($"BusyCountHooks: {_statusMessage}");
return;
}
try
{
_incrementTargetAddress = new IntPtr(textSection.TextBaseVa + incrementOff);
_incrementTargetAddress = inc.Address;
_incrementBusyCountDetour = IncrementBusyCountDetour;
IntPtr incrementDetourPtr = Marshal.GetFunctionPointerForDelegate(_incrementBusyCountDetour);
_originalIncrementBusyCount = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(MinHook.HookCreate(_incrementTargetAddress, incrementDetourPtr));
_originalIncrementBusyCount = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(
MinHook.HookCreate(_incrementTargetAddress, incrementDetourPtr));
_decrementTargetAddress = new IntPtr(textSection.TextBaseVa + decrementOff);
_decrementTargetAddress = dec.Address;
_decrementBusyCountDetour = DecrementBusyCountDetour;
IntPtr decrementDetourPtr = Marshal.GetFunctionPointerForDelegate(_decrementBusyCountDetour);
_originalDecrementBusyCount = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(MinHook.HookCreate(_decrementTargetAddress, decrementDetourPtr));
_originalDecrementBusyCount = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(
MinHook.HookCreate(_decrementTargetAddress, decrementDetourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_incrementTargetAddress);
MinHook.Enable(_decrementTargetAddress);
IsInstalled = true;
_statusMessage = $"Hooked busy-count seams @ 0x{_incrementTargetAddress.ToInt32():X8}/0x{_decrementTargetAddress.ToInt32():X8}.";
RynthLog.Verbose($"Compat: busy-count hooks installed");
_statusMessage = $"Hooked busy-count seams (inc=0x{_incrementTargetAddress.ToInt32():X8}, dec=0x{_decrementTargetAddress.ToInt32():X8}).";
RynthLog.Compat($"BusyCountHooks: hooks installed.");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: busy-count hook failed - {ex.Message}");
RynthLog.Compat($"BusyCountHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static int _incFires, _decFires;
// ── Auto-watchdog: force-clear busy if it stays >0 too long ──────────
// Engine-side safety net so the bot self-heals when its busy tracking
// desyncs from AC's m_cBusy (e.g., a hook miss, RDP-eaten chat input
// preventing the user from running /ra clearbusy manually, or AC's
// own busy state going stuck after a server-rejected action).
//
// Trigger: any of our main-thread detours can call CheckWatchdog().
// SmartBoxHooks.DispatchGameEventDetour wires this in — it fires
// frequently on AC's main thread while in-world, so the watchdog
// gets a tick at least every server event.
//
// Heuristic: if busy has been positive for > BusyWatchdogTimeoutMs
// with no transitions back to zero, fire ForceResetBusyCount. We
// do this regardless of why it got stuck — combat-urgent or not —
// because the alternative is an inert bot.
private static long _busyBecamePositiveTickMs;
private static long _lastWatchdogFireTickMs;
private const long BusyWatchdogTimeoutMs = 5_000;
private const long BusyWatchdogCooldownMs = 2_000;
// Real-field watchdog. The shadow counter (_netBusyCount) DESYNCS from AC's
// real m_cBusy whenever AC mutates the field through a path we don't hook (or
// a detour is missed): the counter drifts to ~0 while the real field stays
// pinned > 0. A pinned real m_cBusy makes AC LOCALLY refuse combat-mode
// changes (its SetCombatMode never even fires) and casts ("You're too
// busy!") — wedging the bot in NonCombat (can't re-enter Magic to buff/fight)
// with NEITHER counter-based watchdog firing, because the counter says idle.
// So the watchdog must also trust the REAL field, read straight from
// [ClientUISystem + OffsetMCBusy]. (Diagnosed 2026-06-09: SetCombatMode
// stopped firing for 30+ min while ChangeCombatMode was re-sent and 191
// "too busy" refusals piled up, yet zero force-clears — classic desync.)
private static long _realBusyPositiveTickMs;
private const long RealBusyWatchdogTimeoutMs = 4_000;
private static int ReadRealBusy()
{
IntPtr p = _lastThisPtr;
if (p == IntPtr.Zero) return -1;
// The try/catch below cannot catch a non-null-page AV under NativeAOT
// (only null-page faults map to NullReferenceException). If AC freed
// the ClientUISystem singleton (logout/close teardown) a stale pointer
// read is fail-fast — probe the page first. TOCTOU-narrow but this is
// a watchdog: skipping one beat is free.
if (!ClientObjectHooks.IsReadablePointer(p + OffsetMCBusy)) return -1;
try { return Marshal.ReadInt32(p + OffsetMCBusy); }
catch { return -1; }
}
/// <summary>
/// Drop the cached ClientUISystem pointer at logout / client-close so the
/// watchdog and ForceResetBusyCount can't touch a freed singleton (the
/// 0x0056547B close-AV class). The increment/decrement detours re-capture
/// it on the next legit AC call.
/// </summary>
public static void ResetSession()
{
_lastThisPtr = IntPtr.Zero;
Volatile.Write(ref _realBusyPositiveTickMs, 0);
_pendingCastBusyDelta = 0;
_pendingCastGestureSeen = false;
}
// ── Direct-action busy reconciliation (source fix for the per-action leak) ──
// The engine's direct AC calls — casts (FreeHandsAndCastSpell / CastSpell)
// AND item actions (UseObject corpse-open / equip / item-use, UseObjectOn) —
// make AC increment m_cBusy synchronously, but they never register the queued
// action whose completion handler performs the matching decrements (that
// lives in the player-initiated flow we bypass). Result: EVERY such call
// leaked busy, caught only downstream by watchdogs (casts: 4322 plugin-side
// clears in one 10h soak; corpse opens: a force-clear every ~2s during loot
// grinds). Source fix: measure the real m_cBusy delta synchronously around
// the call (both run on AC's main thread, nothing interleaves, so the delta
// is exactly ours), then once the action GESTURE has completed
// ([CMI+0x80] empties — a use-reach is a sequenced motion just like a cast
// wind-up) — or after a timeout if it never starts (server refusal) — invoke
// the REAL DecrementBusyCount exactly delta times through the HOOKED entry,
// so the shadow counter and plugin busy events stay in sync. Deterministic,
// no ClearAllCommands side effects, never touches counts owned by others.
// A single accumulator serves both casts and item actions (all are
// engine-issued busy that should clear at the next gesture-end).
private static int _pendingCastBusyDelta;
private static long _pendingCastIssuedAtMs;
private static bool _pendingCastGestureSeen;
private static int _reconcileLogCount;
private const long CastBusyReconcileTimeoutMs = 4_000;
/// <summary>Snapshot the real m_cBusy immediately before a direct cast/item-action call (-1 = unreadable).</summary>
public static int CaptureRealBusyForCast() => ReadRealBusy();
/// <summary>
/// Arm reconciliation right after a direct cast/item-action call, given the
/// pre-call snapshot. Main thread only (these calls already run there).
/// </summary>
public static void NoteDirectCastIssued(int busyBefore)
{
if (busyBefore < 0) return;
int after = ReadRealBusy();
if (after < 0) return;
int delta = after - busyBefore;
if (delta <= 0) return;
_pendingCastBusyDelta += delta;
_pendingCastIssuedAtMs = Environment.TickCount64;
_pendingCastGestureSeen = false;
}
private static void ReconcileCastBusy(long now)
{
int pending = _pendingCastBusyDelta;
if (pending <= 0) return;
bool gesture = false;
try { if (!PlayerPhysicsHooks.TryGetCastGestureInProgress(out gesture)) gesture = false; }
catch { gesture = false; }
if (gesture)
{
// Cast animation running — completion is the decrement point.
_pendingCastGestureSeen = true;
return;
}
// Decrement once the observed gesture has ENDED, or after the timeout
// when no gesture was ever seen (refused cast / instant failure). The
// timeout matches the real-field watchdog window, so worst case this
// path is no slower than the old crutch.
if (!_pendingCastGestureSeen && now - _pendingCastIssuedAtMs <= CastBusyReconcileTimeoutMs)
return;
_pendingCastBusyDelta = 0;
_pendingCastGestureSeen = false;
IntPtr p = _lastThisPtr;
if (p == IntPtr.Zero || _decrementTargetAddress == IntPtr.Zero) return;
if (!ClientObjectHooks.IsReadablePointer(p + OffsetMCBusy)) return;
// Clamp to the live field — if AC (or a watchdog) already cleared part
// of it, never push m_cBusy negative.
int real = ReadRealBusy();
int n = Math.Min(pending, real);
if (n <= 0) return;
try
{
// Call the HOOKED decrement entry (not the trampoline): our detour
// fires, so _netBusyCount and the plugin busy-decremented events
// stay consistent for free.
var dec = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(_decrementTargetAddress);
for (int i = 0; i < n; i++) dec(p);
Interlocked.Increment(ref _reconcileCount);
if (_reconcileLogCount < 50 || _reconcileLogCount % 100 == 0)
RynthLog.Compat($"BusyCountHooks: direct-action busy reconciled — decremented {n} (real now {ReadRealBusy()}, total reconciles {_reconcileLogCount + 1}).");
_reconcileLogCount++;
}
catch { }
}
/// <summary>
/// Auto-clear busy state if it has been positive for too long.
/// Safe to call from any thread; only performs work on AC's main
/// thread (via MainThreadGuard) since ForceResetBusyCount writes
/// AC memory and calls AC functions that aren't thread-safe.
/// </summary>
public static void CheckWatchdog()
{
long now = Environment.TickCount64;
// ── Real-field watchdog (catches counter desync) ─────────────────────
// Trust AC's REAL m_cBusy over our shadow counter: when they diverge a
// pinned real field is what actually wedges the client (mode-change /
// cast refusal) while _netBusyCount reads ~0 and the counter watchdog
// below never fires. A legit action returns the field to 0 within ~2-3s
// (resetting the timer); only a genuinely stuck field reaches the 4s
// timeout. Field read is harmless off-thread, but ForceResetBusyCount
// mutates AC, so only clear on the main thread.
if (MainThreadGuard.IsOnMainThread())
{
// Reconcile our own cast increments FIRST — a clean deterministic
// decrement here means the stuck-field watchdog below (and the
// plugin-side clears) have nothing left to catch.
ReconcileCastBusy(now);
// Consume any off-thread force-reset request (plugin watchdogs):
// the actual clear runs HERE, on the main thread.
if (Interlocked.Exchange(ref _forceResetRequested, 0) == 1)
ForceResetBusyCount();
int realBusy = ReadRealBusy();
if (realBusy > 0)
{
long sinceR = Volatile.Read(ref _realBusyPositiveTickMs);
if (sinceR == 0)
{
Volatile.Write(ref _realBusyPositiveTickMs, now);
}
else if (now - sinceR > RealBusyWatchdogTimeoutMs
&& now - Volatile.Read(ref _lastWatchdogFireTickMs) > BusyWatchdogCooldownMs)
{
Volatile.Write(ref _lastWatchdogFireTickMs, now);
RynthLog.Compat($"BusyCountHooks: REAL m_cBusy stuck at {realBusy} for {now - sinceR}ms (counter={_netBusyCount}) — force-clearing desync.");
ForceResetBusyCount();
Volatile.Write(ref _realBusyPositiveTickMs, 0);
Volatile.Write(ref _busyBecamePositiveTickMs, 0);
return;
}
}
else
{
// 0 = idle; -1 = unreadable (no pointer / freed page). Either
// way disarm the timer — leaving it armed across an unreadable
// stretch caused an instant force-clear when reads resumed
// (e.g. first beat after the next login).
Volatile.Write(ref _realBusyPositiveTickMs, 0);
}
}
// ── Counter-based watchdog (original) ────────────────────────────────
long stuckSince = Volatile.Read(ref _busyBecamePositiveTickMs);
if (stuckSince == 0)
return;
long elapsed = now - stuckSince;
if (elapsed < BusyWatchdogTimeoutMs)
return;
if (!MainThreadGuard.IsOnMainThread())
return;
long lastFire = Volatile.Read(ref _lastWatchdogFireTickMs);
if (now - lastFire < BusyWatchdogCooldownMs)
return;
Volatile.Write(ref _lastWatchdogFireTickMs, now);
RynthLog.Compat($"BusyCountHooks: watchdog auto-resetting — busy stuck at {_netBusyCount} for {elapsed}ms.");
ForceResetBusyCount();
Volatile.Write(ref _busyBecamePositiveTickMs, 0);
}
private static void IncrementBusyCountDetour(IntPtr thisPtr)
{
RecursionGuard.Tick("BusyCountHooks.Increment");
_lastThisPtr = thisPtr;
_originalIncrementBusyCount!(thisPtr);
if (++_incFires <= 3)
RynthLog.Compat($"BusyCountHooks: Increment fired #{_incFires} this=0x{thisPtr.ToInt32():X8}");
try { _originalIncrementBusyCount!(thisPtr); }
catch (Exception ex) { try { RynthLog.Compat($"BusyCountHooks: Increment original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
Interlocked.Increment(ref _incrementDispatchCount);
Interlocked.Increment(ref _netBusyCount);
int after = Interlocked.Increment(ref _netBusyCount);
if (after == 1)
Volatile.Write(ref _busyBecamePositiveTickMs, Environment.TickCount64);
PluginManager.QueueBusyCountIncremented();
}
private static void DecrementBusyCountDetour(IntPtr thisPtr)
{
RecursionGuard.Tick("BusyCountHooks.Decrement");
if (_lastThisPtr == IntPtr.Zero)
_lastThisPtr = thisPtr;
_originalDecrementBusyCount!(thisPtr);
if (++_decFires <= 3)
RynthLog.Compat($"BusyCountHooks: Decrement fired #{_decFires} this=0x{thisPtr.ToInt32():X8}");
try { _originalDecrementBusyCount!(thisPtr); }
catch (Exception ex) { try { RynthLog.Compat($"BusyCountHooks: Decrement original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
Interlocked.Increment(ref _decrementDispatchCount);
Interlocked.Decrement(ref _netBusyCount);
int after = Interlocked.Decrement(ref _netBusyCount);
if (after <= 0)
Volatile.Write(ref _busyBecamePositiveTickMs, 0);
PluginManager.QueueBusyCountDecremented();
}
private static bool LooksHookable(byte[] textBytes, int offset, out byte firstByte)
{
firstByte = 0;
if (offset < 0 || offset >= textBytes.Length)
return false;
firstByte = textBytes[offset];
return firstByte is not (0x00 or 0xCC or 0xC3);
}
}

View file

@ -0,0 +1,220 @@
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Enumerates AC's authoritative world-object table via CObjectMaint.
///
/// Primary use: seed PluginManager._liveObjects on hot-reload, since the new
/// engine module's static state starts empty after a reload. Walking the
/// maintainer gives an immediate snapshot of every weenie the client knows
/// about so we can replay create-object events to a freshly loaded plugin
/// without waiting for new spawn/visibility events.
///
/// Secondary use: reconciliation / drift detection — even on cold start, if
/// any CreateObject hook fires miss the live-object set the maintainer is
/// authoritative and catches the omission.
///
/// Singleton: CObjectMaint::s_pcInstance @ 0x00842ADC (CObjectMaint**)
///
/// CObjectMaint layout (from Chorizite acclient.map + struct defs):
/// +0x00 Interface a0 (vtable*, 4)
/// +0x04 NoticeHandler a1 (vtable*, 4)
/// +0x08 Turbine_RefCount (vtable + m_cRef, 8)
/// +0x10 is_active (Int32, 4)
/// +0x14 lost_cell_table (IntrusiveHashTable, 112)
/// +0x84 object_table (LongHash&lt;CPhysicsObj&gt;, 24)
/// +0x9C null_object_table (LongHash&lt;CPhysicsObj&gt;, 24)
/// +0xB4 weenie_object_table (LongHash&lt;CWeenieObject&gt;, 24)
///
/// HashBase&lt;UInt32&gt; layout (LongHash wraps this):
/// +0 vfptr
/// +4 table_mask
/// +8 key_shift
/// +12 buckets (HashBaseData&lt;UInt32&gt;**)
/// +16 table_size
/// +20 fPlacementNew_
///
/// HashBaseData&lt;UInt32&gt; layout:
/// +0 vfptr
/// +4 hash_next
/// +8 id (UInt32)
/// </summary>
internal static class CObjectMaintHooks
{
private const int S_PC_INSTANCE_VA = 0x00842ADC;
private const int WEENIE_OBJECT_TABLE_OFFSET = 0xB4;
// DIAGNOSTIC (temporary): the CPhysicsObj table — superset of physics
// objects, including ones whose weenie isn't registered in
// weenie_object_table yet (the suspected missing-monster set).
private const int OBJECT_TABLE_OFFSET = 0x84;
private const int HASHBASE_BUCKETS_OFFSET = 12;
private const int HASHBASE_TABLE_SIZE_OFFSET = 16;
private const int HASHBASEDATA_HASH_NEXT_OFFSET = 4;
private const int HASHBASEDATA_ID_OFFSET = 8;
// Sanity bounds — table_size larger than this almost certainly means
// we're reading garbage (real AC tables are typically 1k-8k buckets).
private const int MaxBuckets = 65536;
private const int MaxChainPerBucket = 1024;
/// <summary>
/// Walks CObjectMaint::weenie_object_table and invokes <paramref name="visit"/> for each
/// known object id. Returns the number of ids visited, or -1 if the maintainer or
/// table layout couldn't be read safely.
/// </summary>
public static int EnumerateLiveWeenieObjectIds(Action<uint> visit)
{
if (visit == null) return -1;
IntPtr maintainer = ReadMaintainer();
if (maintainer == IntPtr.Zero)
return -1;
IntPtr tablePtr = maintainer + WEENIE_OBJECT_TABLE_OFFSET;
if (!SmartBoxLocator.IsMemoryReadable(tablePtr + HASHBASE_BUCKETS_OFFSET, 4))
return -1;
IntPtr buckets = Marshal.ReadIntPtr(tablePtr + HASHBASE_BUCKETS_OFFSET);
if (buckets == IntPtr.Zero)
return -1;
if (!SmartBoxLocator.IsMemoryReadable(tablePtr + HASHBASE_TABLE_SIZE_OFFSET, 4))
return -1;
uint tableSize = (uint)Marshal.ReadInt32(tablePtr + HASHBASE_TABLE_SIZE_OFFSET);
if (tableSize == 0 || tableSize > MaxBuckets)
return -1;
int count = 0;
try
{
for (uint i = 0; i < tableSize; i++)
{
IntPtr bucketSlot = buckets + (int)(i * 4);
if (!SmartBoxLocator.IsMemoryReadable(bucketSlot, 4))
break;
IntPtr node = Marshal.ReadIntPtr(bucketSlot);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket)
{
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4))
break;
uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET);
if (id != 0)
{
visit(id);
count++;
}
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4))
break;
node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET);
}
}
}
catch (Exception ex)
{
RynthLog.Compat($"CObjectMaint enumerate threw {ex.GetType().Name}: {ex.Message}");
return count > 0 ? count : -1;
}
return count;
}
// DIAGNOSTIC (temporary): same walk as EnumerateLiveWeenieObjectIds but over
// an arbitrary CObjectMaint table (object_table +0x84 / null_object_table
// +0x9C / weenie_object_table +0xB4). Duplicated rather than refactoring the
// tested enumerator. Remove with the diagnostic.
public static int EnumerateTableIds(int tableOffset, Action<uint> visit)
{
if (visit == null) return -1;
IntPtr maintainer = ReadMaintainer();
if (maintainer == IntPtr.Zero)
return -1;
IntPtr tablePtr = maintainer + tableOffset;
if (!SmartBoxLocator.IsMemoryReadable(tablePtr + HASHBASE_BUCKETS_OFFSET, 4))
return -1;
IntPtr buckets = Marshal.ReadIntPtr(tablePtr + HASHBASE_BUCKETS_OFFSET);
if (buckets == IntPtr.Zero)
return -1;
if (!SmartBoxLocator.IsMemoryReadable(tablePtr + HASHBASE_TABLE_SIZE_OFFSET, 4))
return -1;
uint tableSize = (uint)Marshal.ReadInt32(tablePtr + HASHBASE_TABLE_SIZE_OFFSET);
if (tableSize == 0 || tableSize > MaxBuckets)
return -1;
int count = 0;
try
{
for (uint i = 0; i < tableSize; i++)
{
IntPtr bucketSlot = buckets + (int)(i * 4);
if (!SmartBoxLocator.IsMemoryReadable(bucketSlot, 4))
break;
IntPtr node = Marshal.ReadIntPtr(bucketSlot);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket)
{
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4))
break;
uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET);
if (id != 0)
{
visit(id);
count++;
}
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4))
break;
node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET);
}
}
}
catch (Exception ex)
{
RynthLog.Compat($"CObjectMaint object-table enumerate threw {ex.GetType().Name}: {ex.Message}");
return count > 0 ? count : -1;
}
return count;
}
// Phase B: resolve s_pcInstance's address by code-xref ("mov ecx,[s_pcInstance]" =
// 8B 0D <addr>), operand at offset 2; the VA stays as fallback. Resolved lazily once.
private static readonly byte?[] PatXrefInstancePP = [ 0x8B, 0x0D, null, null, null, null, 0x55, 0xE8 ];
private static int _instancePPAddr;
private static int InstancePPAddr()
{
if (_instancePPAddr == 0)
{
_instancePPAddr = S_PC_INSTANCE_VA;
if (AcClientModule.TryReadTextSection(out AcClientTextSection text))
_instancePPAddr = HookResolver.ResolveData(text, "CObjectMaint.s_pcInstance", PatXrefInstancePP, 2, S_PC_INSTANCE_VA).Address.ToInt32();
}
return _instancePPAddr;
}
private static IntPtr ReadMaintainer()
{
IntPtr instancePP = new IntPtr(InstancePPAddr());
if (!SmartBoxLocator.IsMemoryReadable(instancePP, 4))
return IntPtr.Zero;
IntPtr maintainer = Marshal.ReadIntPtr(instancePP);
if (maintainer == IntPtr.Zero)
return IntPtr.Zero;
if (!SmartBoxLocator.IsMemoryReadable(maintainer, 4))
return IntPtr.Zero;
IntPtr vtable = Marshal.ReadIntPtr(maintainer);
if (!SmartBoxLocator.IsPointerInModule(vtable))
return IntPtr.Zero;
return maintainer;
}
}

View file

@ -0,0 +1,89 @@
using System;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// The real spell-cast gate for RynthAi buff/combat recasts.
///
/// Problem: AC refuses a cast issued while the player is mid cast-gesture
/// animation with a server-driven "You're too busy!" text notice. A tight
/// clear-and-recast retry loop on that refusal re-enters AC's AddTextToScroll
/// and produces the visible 0x00460D1D write-AV after long uptime.
///
/// AC's ClientUISystem busy-count (<see cref="BusyCountHooks"/>) is the
/// hourglass/cursor state, NOT the cast gate — it reads 0 while AC still says
/// "too busy". The true LOCAL gate is the cast GESTURE: CMotionInterp's
/// sequenced/one-shot motion queue is non-empty while the wind-up/release
/// animates and empties when it completes (offline RE of acclient.exe; see
/// <see cref="PlayerPhysicsHooks.TryGetCastGestureInProgress"/>).
///
/// This is a SAMPLED gate — no acclient.exe hook is installed. <see cref="Sample"/>
/// runs on the existing 30 Hz NormalPluginPump heartbeat (PluginManager.TickAll)
/// and reads a single CMotionInterp scalar through the already-proven
/// PlayerPhysicsHooks accessor. No new detour, no pattern-scan-and-call (the
/// ACE crash class), no list walk (UAF-safe). The consumer polls the gate at
/// the same tick rate, so the busy→idle edge is observed without any new
/// engine→plugin callback (avoids the NativeAOT reverse-P/Invoke crash class).
/// </summary>
internal static class CastGate
{
private static int _castBusy; // 0 = clear to cast, 1 = gesture in progress
private static int _reachable; // 1 once CMotionInterp has ever been read
private static long _gestureCount;
private static string _statusMessage = "Not sampled yet.";
public static bool IsInitialized => Volatile.Read(ref _reachable) == 1;
public static string StatusMessage => _statusMessage;
/// <summary>Number of cast/action gestures observed completing this session.</summary>
public static long GestureCount => Interlocked.Read(ref _gestureCount);
/// <summary>
/// 0 = clear to cast, 1 = a cast/action gesture is in progress. Mirrors
/// <see cref="BusyCountHooks.GetBusyState"/> for the host-API pull path.
/// </summary>
public static int GetCastBusyState() => Volatile.Read(ref _castBusy);
/// <summary>
/// Sampled from the 30 Hz plugin pump (PluginManager.TickAll). Cheap, fully
/// guarded, never throws. If CMotionInterp isn't reachable (pre-login /
/// between worlds) the gate reports "clear to cast" so the consumer falls
/// back to its own throttle/park, which is the hard anti-spam guarantee.
/// </summary>
public static void Sample()
{
try
{
if (!PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool inProgress))
{
Volatile.Write(ref _castBusy, 0);
return;
}
Volatile.Write(ref _reachable, 1);
int was = Volatile.Read(ref _castBusy);
int now = inProgress ? 1 : 0;
if (now == was)
return;
Volatile.Write(ref _castBusy, now);
if (now == 1)
{
_statusMessage = "Cast gesture in progress.";
}
else
{
Interlocked.Increment(ref _gestureCount);
_statusMessage = "Ready (gate open).";
}
}
catch
{
// The gate must never destabilise the pump. Default to clear-to-cast;
// the consumer's throttle still bounds retries.
Volatile.Write(ref _castBusy, 0);
}
}
}

View file

@ -28,14 +28,46 @@ internal static class CharacterCaptureHooks
private const int XCharList = 121;
private const int YTopOfBox = 209;
private const int YBottomOfBox = 532;
private const int AutoLoginDelayMs = 800;
private const int AutoLoginDelayMs = 2000;
private const int AutoLoginWindowWaitMs = 10000;
private const int AutoLoginWindowPollMs = 250;
private const int AutoLoginAttempts = 3;
private const int AutoLoginAttempts = 15;
private const int AutoLoginAttemptDelayMs = 600;
private const int AutoLoginDoubleClickGapMs = 100;
private const int DirectAutoLoginAttempts = 40;
private const int DirectAutoLoginAttemptDelayMs = 250;
private const int CharacterManagementUIMode = 0x1000000A;
private const int GamePlayUIMode = 0x10000008;
// Poll-driven auto-login. The packet-driven path (ScheduleAutoLoginIfRequested,
// fed by InnerDispatcherDetour) is dead on this client: InnerDispatcherHook was
// disabled 2026-05-14 because its pattern walk-back stalls ACE in "Entering
// World", and SmartBox does not carry the pre-login 0xF658 char-list packet.
// Result: zero CharacterCapture activity, auto-login never fired. This poll
// drives login off the native CharacterSet directly (CharacterManagementHooks),
// which needs no packet — it just watches the UIFlow mode and retries until
// login completes. Replaces the dead trigger; the packet path is left intact
// (harmless, never invoked) in case InnerDispatcher is ever re-enabled.
private const int AutoLoginPollIntervalMs = 600;
private const int AutoLoginPollHardTimeoutMs = 120_000;
private const int AutoLoginDirectFailsBeforeClick = 4;
private static int _autoLoginPollStarted;
// Native character-list capture. The 0xF658 packet path is dead (see above),
// so ParseAndSaveCharacterList never runs and the launcher's cache
// (characters_<server>_<account>.json) was only written by SessionStateRegistry's
// login upsert, which records just the launch context's TargetCharacter. An
// account launched with no character picked therefore never got a cache file
// and its launcher dropdown stayed empty. This poll reads the list straight
// from AC's native CharacterSet while char-select is up, whether or not
// auto-login is armed. In the world it only checks a managed flag; the native
// set is read only in CharacterManagementUI. Logout back to char-select
// (LoginLifecycleHooks.ResetObservation) re-arms it, so a new or deleted
// character is picked up too. The file is rewritten only when the list changes.
private const int CharacterListCapturePollIntervalMs = 500;
private static int _characterListCapturePollStarted;
private static readonly object CharacterListCaptureLock = new();
private static string _lastCharacterListCaptureKey = string.Empty;
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
@ -69,6 +101,258 @@ internal static class CharacterCaptureHooks
// or relaunch.
private static int _autoLoginEverFired;
/// <summary>
/// Starts the character-list capture poll (always) and the poll-driven
/// auto-login worker. Call once from InitWorker. Auto-login no-ops if no
/// TargetCharacter is configured in the launch context, or if the worker is
/// already running. Safe to call before the client window or char-select UI
/// exists — both workers wait for them.
/// </summary>
public static void Initialize()
{
StartCharacterListCapturePoll();
(_, _, string targetCharacter) = ReadLaunchContext();
if (string.IsNullOrWhiteSpace(targetCharacter))
{
RynthLog.Verbose("CharacterCapture: Initialize - no TargetCharacter in launch context; auto-login disabled.");
return;
}
if (Interlocked.Exchange(ref _autoLoginPollStarted, 1) != 0)
return;
var thread = new Thread(AutoLoginPollLoop)
{
Name = "RynthCore.AutoLoginPoll",
IsBackground = true
};
thread.Start();
RynthLog.Info($"CharacterCapture: Poll-driven auto-login armed for '{targetCharacter}'.");
}
/// <summary>
/// Watches the native UIFlow mode and drives LogOnCharacter directly off
/// AC's native CharacterSet. Retries every tick while char-select is up,
/// so a too-early attempt or a missed click just gets re-tried — until
/// login completes, the client enters the world, or the hard timeout hits.
/// Hard-stops the instant mode==GamePlayUI or LoginComplete is observed:
/// poking LogOn pointers while in-game has been correlated with AC self-
/// exiting (see ScheduleAutoLoginIfRequested's notes).
/// </summary>
private static void AutoLoginPollLoop()
{
(_, _, string targetCharacter) = ReadLaunchContext();
if (string.IsNullOrWhiteSpace(targetCharacter))
return;
long charSelectFirstSeenTick = 0;
int directFailCount = 0;
bool issuedDirect = false;
try
{
while (true)
{
Thread.Sleep(AutoLoginPollIntervalMs);
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
RynthLog.Info($"CharacterCapture: Auto-login complete for '{targetCharacter}' (LoginComplete observed).");
Interlocked.Exchange(ref _autoLoginEverFired, 1);
return;
}
// One-shot: if the (currently dead) packet path ever fires and
// latches, stand down so we don't double-drive.
if (Volatile.Read(ref _autoLoginEverFired) != 0)
{
RynthLog.Verbose($"CharacterCapture: Poll standing down for '{targetCharacter}' - auto-login already fired elsewhere.");
return;
}
if (!CharacterManagementHooks.TryGetCurrentMode(out int mode))
continue; // UIFlow not ready yet — keep waiting.
if (mode == GamePlayUIMode)
{
RynthLog.Compat($"CharacterCapture: Poll stopping for '{targetCharacter}' - client already in GamePlayUI.");
Interlocked.Exchange(ref _autoLoginEverFired, 1);
return;
}
if (mode != CharacterManagementUIMode)
{
// Still in connect/logo/transition — don't start the timeout
// clock until char-select has actually appeared.
continue;
}
if (charSelectFirstSeenTick == 0)
{
charSelectFirstSeenTick = Environment.TickCount64;
RynthLog.Info($"CharacterCapture: Char-select up — driving direct auto-login for '{targetCharacter}'.");
}
// Save the account's character list before logging on, so the
// launcher cache is written even when auto-login is quick.
TryCaptureNativeCharacterList();
// Direct path: read AC's native CharacterSet and call LogOnCharacter.
// No packet required. Retries every tick if it didn't take.
if (CharacterManagementHooks.TryLogOnCharacter(
targetCharacter, out string matched, out uint avatarId, out int slotIndex, out string status))
{
if (!issuedDirect)
{
issuedDirect = true;
RynthLog.Info($"CharacterCapture: Issued LogOnCharacter for '{matched}' (target '{targetCharacter}', avatar 0x{avatarId:X8}). Awaiting world entry.");
}
directFailCount = 0;
// Keep looping — watch for LoginComplete/GamePlayUI. If the
// issue didn't take, next ticks will re-issue.
}
else
{
directFailCount++;
RynthLog.Verbose($"CharacterCapture: Direct auto-login attempt {directFailCount} for '{targetCharacter}' - {status}");
// Direct keeps failing (native set not readable / name not
// matched yet). Fall back to a char-list double-click, but
// only when we know the slot — slotIndex is set when the
// name matched in the native set; otherwise use the packet-
// cached index is unavailable here so skip until known.
if (directFailCount >= AutoLoginDirectFailsBeforeClick && slotIndex >= 0)
{
int slotCount = CharacterManagementHooks.GetNativeCharacterSetSlotCount();
if (slotCount > 0)
TryClickCharacterSlot(targetCharacter, slotIndex, slotCount);
directFailCount = 0;
}
}
if (charSelectFirstSeenTick != 0 &&
Environment.TickCount64 - charSelectFirstSeenTick > AutoLoginPollHardTimeoutMs)
{
RynthLog.Compat($"CharacterCapture: Auto-login for '{targetCharacter}' gave up after {AutoLoginPollHardTimeoutMs / 1000}s at char-select. Last status: {status}");
return;
}
}
}
catch (Exception ex)
{
RynthLog.Compat($"CharacterCapture: Auto-login poll loop crashed - {ex.Message}");
}
finally
{
Interlocked.Exchange(ref _autoLoginPollStarted, 0);
}
}
private static void StartCharacterListCapturePoll()
{
if (Interlocked.Exchange(ref _characterListCapturePollStarted, 1) != 0)
return;
var thread = new Thread(CharacterListCapturePollLoop)
{
Name = "RynthCore.CharacterListCapture",
IsBackground = true
};
thread.Start();
}
private static void CharacterListCapturePollLoop()
{
try
{
while (!EngineLifecycle.IsShuttingDown)
{
Thread.Sleep(CharacterListCapturePollIntervalMs);
// In the world: no native reads at all.
if (LoginLifecycleHooks.HasObservedLoginComplete)
continue;
if (!CharacterManagementHooks.TryGetCurrentMode(out int mode) || mode != CharacterManagementUIMode)
continue;
TryCaptureNativeCharacterList();
}
}
catch (Exception ex)
{
RynthLog.Compat($"CharacterCapture: Character-list capture poll crashed - {ex.Message}");
}
finally
{
Interlocked.Exchange(ref _characterListCapturePollStarted, 0);
}
}
/// <summary>
/// Reads the character list from AC's native CharacterSet (char-select only)
/// and saves it to the launcher's character cache for this client's
/// account/server. Writes only when the list differs from the last one seen
/// in this process. Safe to call from any poll thread.
/// </summary>
private static void TryCaptureNativeCharacterList()
{
try
{
if (!CharacterManagementHooks.TryReadCharacterNames(out List<string> characters))
return;
lock (CharacterListCaptureLock)
{
string key = string.Join("\n", characters);
if (string.Equals(key, _lastCharacterListCaptureKey, StringComparison.Ordinal))
return;
_lastCharacterListCaptureKey = key;
RynthLog.Info($"CharacterCapture: Native character set has {characters.Count} chars: {string.Join(", ", characters)}");
(string accountName, string serverName, _) = ReadLaunchContext();
SaveCharacterList(characters, accountName, serverName);
}
}
catch (Exception ex)
{
RynthLog.Compat($"CharacterCapture: Native character-list capture failed - {ex.Message}");
}
}
/// <summary>
/// Single char-list double-click at the slot for <paramref name="slotIndex"/>.
/// Fallback for when the direct native LogOnCharacter path isn't taking.
/// </summary>
private static void TryClickCharacterSlot(string targetCharacter, int slotIndex, int slotCount)
{
try
{
if (CharacterManagementHooks.TryGetCurrentMode(out int m) && m == GamePlayUIMode)
return;
IntPtr hwnd = WaitForGameWindow();
if (hwnd == IntPtr.Zero)
return;
SetForegroundWindow(hwnd);
float nameSize = (YBottomOfBox - YTopOfBox) / (float)slotCount;
int yOffset = (int)(YTopOfBox + (nameSize / 2.0f) + (nameSize * slotIndex));
RynthLog.Verbose($"CharacterCapture: Click fallback for '{targetCharacter}' at slot {slotIndex}/{slotCount} ({XCharList},{yOffset}).");
PostMouseClick(hwnd, XCharList, yOffset);
Thread.Sleep(AutoLoginDoubleClickGapMs);
PostMouseClick(hwnd, XCharList, yOffset);
}
catch (Exception ex)
{
RynthLog.Compat($"CharacterCapture: Click fallback threw - {ex.Message}");
}
}
public static void ProcessPotentialCharacterMessage(IntPtr blob, bool isGameEvent = false)
{
if (blob == IntPtr.Zero)
@ -159,14 +443,26 @@ internal static class CharacterCaptureHooks
}
characters = new List<string>(characterCount);
// Deep-audit finding #28 (2026-06-18): this loop advanced offset
// (GUID, nameLen, name bytes, padding, timeout) and never compared
// it against blobSize — only nameLen itself was range-checked
// (1..127). A short/malformed blob (this server's own login
// response, so not adversarial, but still worth bounding) would
// walk past the buffer into whatever heap memory follows it.
// Bound every read against blobSize; break (not continue) on any
// overrun since offset is no longer trustworthy past that point.
for (int i = 0; i < characterCount; i++)
{
if (offset + 4 > blobSize) break; // GUID
offset += 4; // Skip Character GUID
if (offset + 2 > blobSize) break; // nameLen
short nameLen = Marshal.ReadInt16(IntPtr.Add(payloadPtr, offset));
offset += 2;
if (nameLen > 0 && nameLen < 128)
{
if (offset + nameLen > blobSize) break; // name bytes
byte[] nameBytes = new byte[nameLen];
Marshal.Copy(IntPtr.Add(payloadPtr, offset), nameBytes, 0, nameLen);
string name = Encoding.Default.GetString(nameBytes);
@ -177,6 +473,12 @@ internal static class CharacterCaptureHooks
if (offset % 4 != 0)
offset += 4 - (offset % 4);
offset += 4; // Skip Delete Timeout
if (offset > blobSize)
{
offset = (int)blobSize; // cap so the slotCount read below can't overrun either
break;
}
}
characters.Sort(StringComparer.OrdinalIgnoreCase);
@ -185,7 +487,7 @@ internal static class CharacterCaptureHooks
? Marshal.ReadInt32(IntPtr.Add(payloadPtr, offset))
: characters.Count;
RynthLog.Verbose($"CharacterCapture: Parsed {characters.Count} chars ({slotCount} slots): {string.Join(", ", characters)}");
RynthLog.Info($"CharacterCapture: Parsed {characters.Count} chars ({slotCount} slots): {string.Join(", ", characters)}");
if (characters.Count > 0)
{
@ -255,7 +557,7 @@ internal static class CharacterCaptureHooks
if (!string.IsNullOrWhiteSpace(accountName))
{
CharacterCacheStore.Write(accountName, serverName, characters);
RynthLog.Verbose(
RynthLog.Info(
!string.IsNullOrWhiteSpace(serverName)
? $"CharacterCapture: Saved {characters.Count} chars for '{accountName}' on '{serverName}'."
: $"CharacterCapture: Saved {characters.Count} chars for '{accountName}' (no server name in context).");
@ -277,6 +579,26 @@ internal static class CharacterCaptureHooks
if (string.IsNullOrWhiteSpace(targetCharacter))
return;
// If the client is already past character-select, do NOT schedule any
// auto-login work. The 0xF658 character-list packet can arrive in
// transitional states (logout-to-char-select, hot-reload replay, etc.),
// and starting a 10-second polling loop that pokes at native LogOn
// pointers while the player is in-game has been correlated with AC
// self-exiting via MSVCR70 a few seconds later.
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
RynthLog.Verbose($"CharacterCapture: Skipping auto-login schedule for '{targetCharacter}' - login already complete.");
Interlocked.Exchange(ref _autoLoginEverFired, 1);
return;
}
if (CharacterManagementHooks.TryGetCurrentMode(out int currentMode) && currentMode == 0x10000008 /* GamePlayUI */)
{
RynthLog.Compat($"CharacterCapture: Skipping auto-login schedule for '{targetCharacter}' - client is already in GamePlayUI.");
Interlocked.Exchange(ref _autoLoginEverFired, 1);
return;
}
// One-shot per process: if auto-login already fired (and the user has
// since logged back out), don't re-trigger. This keeps a manual logout
// from instantly re-logging the same character.
@ -293,7 +615,7 @@ internal static class CharacterCaptureHooks
? new List<string>(characters)
: [];
int finalSlots = slotCount > 0 ? slotCount : fallbackCharacters.Count;
int fallbackIndex = fallbackCharacters.FindIndex(c => string.Equals(c, targetCharacter, StringComparison.OrdinalIgnoreCase));
int fallbackIndex = fallbackCharacters.FindIndex(c => CharacterManagementHooks.CharacterNamesMatch(c, targetCharacter));
int logoDelayMs = LogoBypassHooks.GetRecommendedAutoLoginDelayMs();
int scheduledDelayMs = Math.Max(AutoLoginDelayMs, logoDelayMs);
@ -332,6 +654,17 @@ internal static class CharacterCaptureHooks
return;
}
// Hard early-out: if the client has already entered GamePlayUI, the player
// is in the world. Continuing to poll TryLogOnCharacter (which keeps
// dereferencing UIFlow + PlayerSystem pointers) has been correlated with
// AC self-exiting via MSVCR70 ~20s later. Treat this as "done", not a
// failure to be retried.
if (CharacterManagementHooks.TryGetCurrentMode(out int gpMode) && gpMode == 0x10000008 /* GamePlayUI */)
{
RynthLog.Compat($"CharacterCapture: Auto-login for '{targetCharacter}' aborted on attempt {attempt}/{DirectAutoLoginAttempts} - client is already in GamePlayUI. Last direct status: {lastDirectStatus}");
return;
}
if (CharacterManagementHooks.TryLogOnCharacter(targetCharacter, out string matchedCharacter, out uint avatarId, out string directStatus))
{
RynthLog.Verbose(
@ -340,19 +673,39 @@ internal static class CharacterCaptureHooks
}
lastDirectStatus = directStatus;
// Belt-and-braces: TryLogOnCharacter itself reports "Client is already in
// GamePlayUI" when mode==GamePlayUI. If we somehow raced past the
// pre-call mode check above, still bail on the status.
if (directStatus.IndexOf("already in GamePlayUI", StringComparison.OrdinalIgnoreCase) >= 0)
{
RynthLog.Compat($"CharacterCapture: Auto-login for '{targetCharacter}' aborted on attempt {attempt}/{DirectAutoLoginAttempts} - {directStatus}");
return;
}
if (attempt < DirectAutoLoginAttempts)
Thread.Sleep(DirectAutoLoginAttemptDelayMs);
}
RynthLog.Compat($"CharacterCapture: Direct auto-login did not succeed for '{targetCharacter}' - {lastDirectStatus}");
int index = fallbackCharacters.FindIndex(c => string.Equals(c, targetCharacter, StringComparison.OrdinalIgnoreCase));
int index = fallbackCharacters.FindIndex(c => CharacterManagementHooks.CharacterNamesMatch(c, targetCharacter));
if (index < 0 || slotCount <= 0)
{
RynthLog.Compat($"CharacterCapture: No click fallback is available for '{targetCharacter}' after direct login failure.");
return;
}
// Final guard: the click fallback drives a foreground window via PostMessage.
// If, by the time we reach the fallback, the client is in GamePlayUI (eg the
// user clicked through during the retry window), do NOT spam clicks at the
// game viewport.
if (CharacterManagementHooks.TryGetCurrentMode(out int fbMode) && fbMode == 0x10000008 /* GamePlayUI */)
{
RynthLog.Compat($"CharacterCapture: Skipping click fallback for '{targetCharacter}' - client is already in GamePlayUI.");
return;
}
IntPtr hwnd = WaitForGameWindow();
if (hwnd == IntPtr.Zero)
{
@ -367,6 +720,30 @@ internal static class CharacterCaptureHooks
for (int attempt = 1; attempt <= AutoLoginAttempts; attempt++)
{
// Login made it through (either by our earlier click or by the user) — stop clicking.
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
RynthLog.Verbose($"CharacterCapture: Click fallback for '{targetCharacter}' aborted on attempt {attempt}/{AutoLoginAttempts} - login complete.");
return;
}
if (CharacterManagementHooks.TryGetCurrentMode(out int clickMode) && clickMode == GamePlayUIMode)
{
RynthLog.Compat($"CharacterCapture: Click fallback for '{targetCharacter}' aborted on attempt {attempt}/{AutoLoginAttempts} - client is already in GamePlayUI.");
return;
}
// Only click while char-select is actually visible. The 0xF658 packet can arrive
// before the UI has transitioned (logos still dismissing, etc.) — wasting clicks
// outside char-select is what made earlier runs "give up too soon."
bool charSelectReady = CharacterManagementHooks.TryGetCurrentMode(out int curMode) && curMode == CharacterManagementUIMode;
if (!charSelectReady)
{
RynthLog.Verbose($"CharacterCapture: Click fallback waiting for char-select UI on attempt {attempt}/{AutoLoginAttempts} (mode=0x{curMode:X8}).");
Thread.Sleep(AutoLoginAttemptDelayMs);
continue;
}
RynthLog.Verbose($"CharacterCapture: Auto-login attempt {attempt}/{AutoLoginAttempts} for '{targetCharacter}' at ({XCharList}, {yOffset}).");
PostMouseClick(hwnd, XCharList, yOffset);

View file

@ -8,6 +8,12 @@ internal static class CharacterManagementHooks
{
private const int UIFlowInstanceVa = 0x0083E72C;
private const int PlayerSystemVa = 0x0087119C;
// Phase B: resolve the two data globals by code-xref (operand at offset 2); VAs stay fallback.
private static readonly byte?[] PatXrefUIFlow = [ 0x51, 0xA1, null, null, null, null, 0x8B, 0x4C ];
private static readonly byte?[] PatXrefCPlayerSystem = [ 0xC7, 0x05, null, null, null, null, 0x00, 0x00, 0x00, 0x00, 0x83, 0xC6 ];
private static int _uiFlowAddr = UIFlowInstanceVa;
private static int _playerSystemAddr = PlayerSystemVa;
private const int UIFlowCurModeOffset = 0x8C;
private const int UIFlowDataOffset = 0x98;
private const int UIPersistantDataCharacterSetOffset = 0x04;
@ -51,6 +57,24 @@ internal static class CharacterManagementHooks
private static CharacterSetGetNameDelegate? _characterSetGetName;
private static CharacterSetGetGidDelegate? _characterSetGetGid;
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
// The *Va consts above are FALLBACKs; these signatures (verified unique + landing exactly
// at the VA offline via tools/pe_pattern.py) are the source of truth, surviving AC-patch /
// ACE-rebuild drift. GetName/GetGid are sibling accessors differing only in a trailing
// field offset (0x08 vs 0x04) — pinned literally to stay unique.
private static readonly byte?[] PatUIFlowGetPersistantData = [ 0x8B, 0x81, 0x98, 0x00, 0x00, 0x00, 0xC3, 0x90 ];
private static readonly byte?[] PatGetPlayerSystem = [ 0xA1, 0x9C, 0x11, 0x87, 0x00, 0xC3, 0x90, 0x90 ];
private static readonly byte?[] PatLogOnCharacter = [ 0x56, 0x8B, 0xF1, 0x8A, 0x86, 0x10, 0x02, 0x00 ];
private static readonly byte?[] PatCharacterSetGetIdentity = [ 0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x14, 0x73, 0x0F ];
private static readonly byte?[] PatCharacterSetGetName = [ 0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x14, 0x73, 0x13, 0x8B, 0x49, 0x0C, 0xC1, 0xE0, 0x04, 0x03, 0xC1, 0x8B, 0x48, 0x04, 0x85, 0xC9, 0x74, 0x04, 0x85, 0xC0, 0x75, 0x05, 0x33, 0xC0, 0xC2, 0x04, 0x00, 0x8B, 0x40, 0x08 ];
private static readonly byte?[] PatCharacterSetGetGid = [ 0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x14, 0x73, 0x13, 0x8B, 0x49, 0x0C, 0xC1, 0xE0, 0x04, 0x03, 0xC1, 0x8B, 0x48, 0x04, 0x85, 0xC9, 0x74, 0x04, 0x85, 0xC0, 0x75, 0x05, 0x33, 0xC0, 0xC2, 0x04, 0x00, 0x8B, 0x40, 0x04 ];
private static T? Bind<T>(AcClientTextSection text, string name, byte?[] pattern, int fallbackVa) where T : Delegate
{
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
return r.Success ? Marshal.GetDelegateForFunctionPointer<T>(r.Address) : null;
}
public static string StatusMessage => _statusMessage;
public static bool TryGetCurrentMode(out int mode)
@ -65,9 +89,19 @@ internal static class CharacterManagementHooks
}
public static bool TryLogOnCharacter(string targetCharacter, out string matchedCharacter, out uint avatarId, out string status)
=> TryLogOnCharacter(targetCharacter, out matchedCharacter, out avatarId, out _, out status);
/// <summary>
/// Same as the 4-arg overload, but also reports the matched character's
/// slot index in AC's native CharacterSet (-1 when no match was found).
/// The slot index is what the click fallback in CharacterCaptureHooks
/// needs to compute the y-offset for the character-list double-click.
/// </summary>
public static bool TryLogOnCharacter(string targetCharacter, out string matchedCharacter, out uint avatarId, out int slotIndex, out string status)
{
matchedCharacter = string.Empty;
avatarId = 0;
slotIndex = -1;
if (string.IsNullOrWhiteSpace(targetCharacter))
{
@ -113,9 +147,15 @@ internal static class CharacterManagementHooks
continue;
availableCharacters.Add(candidateName);
if (!string.Equals(candidateName, targetCharacter, StringComparison.OrdinalIgnoreCase))
// Admin/staff character names render with a leading '+' in the AC
// client UI but the cached/launcher-side name often lacks it (or the
// server packet does). Match prefix-tolerantly so 'Buffi' matches
// '+Buffi' and vice versa.
if (!CharacterNamesMatch(candidateName, targetCharacter))
continue;
slotIndex = index;
IntPtr playerSystemPtr = GetPlayerSystemPointer();
if (playerSystemPtr == IntPtr.Zero)
{
@ -144,6 +184,84 @@ internal static class CharacterManagementHooks
return false;
}
/// <summary>
/// Reads the character names in AC's native CharacterSet, in slot order
/// (the order char-select lists them). Read-only: never calls
/// LogOnCharacter. Only reads while CharacterManagementUI is the current
/// mode, so the native set is never touched in the world. Returns false
/// (empty list) when unbound, not at char-select, or the set isn't filled yet.
/// </summary>
public static bool TryReadCharacterNames(out List<string> names)
{
names = new List<string>();
if (!EnsureBound())
return false;
if (!TryGetCurrentMode(out int mode) || mode != CharacterManagementUI)
return false;
IntPtr charSetPtr = GetCharacterSetPointer();
if (charSetPtr == IntPtr.Zero)
return false;
for (int index = 0; index < MaxCharacterSlots; index++)
{
IntPtr identityPtr = _characterSetGetIdentity!(charSetPtr, index);
if (identityPtr == IntPtr.Zero)
continue;
string? name = ReadAnsiString(_characterSetGetName!(charSetPtr, index));
uint avatarId = _characterSetGetGid!(charSetPtr, index);
if (string.IsNullOrWhiteSpace(name) || avatarId == 0)
continue;
names.Add(name.Trim());
}
return names.Count > 0;
}
/// <summary>
/// Returns the count of populated character slots in AC's native
/// CharacterSet (slots where GetIdentity returns non-null). Used by the
/// click fallback in CharacterCaptureHooks when the 0xF658 packet parser
/// produced an empty list — typical on ACE where the packet shape differs
/// from retail.
/// </summary>
public static int GetNativeCharacterSetSlotCount()
{
if (!EnsureBound())
return 0;
IntPtr charSetPtr = GetCharacterSetPointer();
if (charSetPtr == IntPtr.Zero)
return 0;
int count = 0;
for (int index = 0; index < MaxCharacterSlots; index++)
{
IntPtr identityPtr;
try { identityPtr = _characterSetGetIdentity!(charSetPtr, index); }
catch { return count; }
if (identityPtr != IntPtr.Zero)
count++;
}
return count;
}
/// <summary>
/// Compares two AC character names tolerantly of the leading '+' that the
/// client adds to admin/staff names. e.g. 'Buffi' matches '+Buffi'.
/// </summary>
internal static bool CharacterNamesMatch(string? a, string? b)
{
string lhs = (a ?? string.Empty).Trim().TrimStart('+');
string rhs = (b ?? string.Empty).Trim().TrimStart('+');
return lhs.Length > 0 && string.Equals(lhs, rhs, StringComparison.OrdinalIgnoreCase);
}
private static bool EnsureBound()
{
lock (BindLock)
@ -154,15 +272,30 @@ internal static class CharacterManagementHooks
_bindAttempted = true;
try
{
_uiFlowGetPersistantData = Marshal.GetDelegateForFunctionPointer<UIFlowGetPersistantDataDelegate>(new IntPtr(UIFlowGetPersistantDataVa));
_getPlayerSystem = Marshal.GetDelegateForFunctionPointer<GetPlayerSystemDelegate>(new IntPtr(GetPlayerSystemVa));
_logOnCharacter = Marshal.GetDelegateForFunctionPointer<LogOnCharacterDelegate>(new IntPtr(LogOnCharacterVa));
_characterSetGetIdentity = Marshal.GetDelegateForFunctionPointer<CharacterSetGetIdentityDelegate>(new IntPtr(CharacterSetGetIdentityVa));
_characterSetGetName = Marshal.GetDelegateForFunctionPointer<CharacterSetGetNameDelegate>(new IntPtr(CharacterSetGetNameVa));
_characterSetGetGid = Marshal.GetDelegateForFunctionPointer<CharacterSetGetGidDelegate>(new IntPtr(CharacterSetGetGidVa));
_bound = true;
_statusMessage = "Bound.";
RynthLog.Verbose("CharacterManagement: Bound UIFlow and direct LogOnCharacter entry points.");
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
_bound = false;
_statusMessage = "acclient .text not readable for pattern resolve.";
RynthLog.Compat($"CharacterManagement: bind failed - {_statusMessage}");
return _bound;
}
_uiFlowGetPersistantData = Bind<UIFlowGetPersistantDataDelegate>(text, "CharMgmt.UIFlowGetPersistantData", PatUIFlowGetPersistantData, UIFlowGetPersistantDataVa);
_getPlayerSystem = Bind<GetPlayerSystemDelegate>(text, "CharMgmt.GetPlayerSystem", PatGetPlayerSystem, GetPlayerSystemVa);
_logOnCharacter = Bind<LogOnCharacterDelegate>(text, "CharMgmt.LogOnCharacter", PatLogOnCharacter, LogOnCharacterVa);
_characterSetGetIdentity = Bind<CharacterSetGetIdentityDelegate>(text, "CharMgmt.CharacterSetGetIdentity", PatCharacterSetGetIdentity, CharacterSetGetIdentityVa);
_characterSetGetName = Bind<CharacterSetGetNameDelegate>(text, "CharMgmt.CharacterSetGetName", PatCharacterSetGetName, CharacterSetGetNameVa);
_characterSetGetGid = Bind<CharacterSetGetGidDelegate>(text, "CharMgmt.CharacterSetGetGid", PatCharacterSetGetGid, CharacterSetGetGidVa);
_uiFlowAddr = HookResolver.ResolveData(text, "CharMgmt.UIFlow", PatXrefUIFlow, 2, UIFlowInstanceVa).Address.ToInt32();
_playerSystemAddr = HookResolver.ResolveData(text, "CharMgmt.CPlayerSystem", PatXrefCPlayerSystem, 2, PlayerSystemVa).Address.ToInt32();
_bound = _uiFlowGetPersistantData != null && _getPlayerSystem != null && _logOnCharacter != null
&& _characterSetGetIdentity != null && _characterSetGetName != null && _characterSetGetGid != null;
_statusMessage = _bound ? "Bound." : "One or more character-management addresses failed to resolve.";
if (_bound)
RynthLog.Verbose("CharacterManagement: Bound UIFlow and direct LogOnCharacter entry points.");
else
RynthLog.Compat($"CharacterManagement: bind incomplete - {_statusMessage}");
}
catch (Exception ex)
{
@ -179,7 +312,7 @@ internal static class CharacterManagementHooks
{
try
{
return Marshal.ReadIntPtr(new IntPtr(UIFlowInstanceVa));
return Marshal.ReadIntPtr(new IntPtr(_uiFlowAddr));
}
catch
{
@ -235,7 +368,7 @@ internal static class CharacterManagementHooks
try
{
return Marshal.ReadIntPtr(new IntPtr(PlayerSystemVa));
return Marshal.ReadIntPtr(new IntPtr(_playerSystemAddr));
}
catch
{

View file

@ -25,20 +25,17 @@ internal static class ChatCallbackHooks
private const bool EnableOutgoingHook = true;
private static IncomingChatMode CurrentIncomingMode => IncomingChatMode.AddTextToScrollHostEat;
private static readonly byte[] IncomingChatAddTextToScrollSignature =
// Verified unique + lands at 0x005649F0 offline (tools/pe_pattern.py).
private static readonly byte?[] IncomingChatAddTextToScrollPattern =
[
0x81, 0xEC, 0x48, 0x09, 0x00, 0x00, 0x8A, 0x84,
0x24, 0x54, 0x09, 0x00, 0x00, 0x53, 0x55, 0x56,
0x33, 0xF6, 0x84, 0xC0, 0x57, 0x8B, 0xBC, 0x24,
0x5C, 0x09, 0x00, 0x00, 0x89, 0x4C, 0x24, 0x24
0x81, 0xEC, 0x48, 0x09, 0x00, 0x00, 0x8A, 0x84
];
private static readonly byte[] IncomingChatWrapperSignature =
// Verified unique + lands at 0x0058A000 offline (tools/pe_pattern.py).
private static readonly byte?[] IncomingChatWrapperPattern =
[
0xA1, 0xE4, 0x0B, 0x87, 0x00, 0x85, 0xC0, 0x75,
0x06, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xC3, 0x56,
0x8B, 0x74, 0x24, 0x10, 0x83, 0xFE, 0x01, 0x74,
0x0F
0x06, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xC3, 0x56
];
private static readonly byte?[] OutgoingChatPattern =
@ -73,6 +70,15 @@ internal static class ChatCallbackHooks
private static int _incomingChatSuppressionEnabled;
private static int _incomingCallCount;
// Captured live from the outgoing-chat detour so we can re-invoke AC's outgoing
// chat function DIRECTLY (deterministic) instead of simulating keystrokes into
// the native chat bar. Keystroke simulation depends on the bar's open/closed
// state, which the first simulated send corrupts — so the second send silently
// fails to submit ("works once, then stops"). Calling the function directly has
// no chat-bar state and is fully repeatable.
private static IntPtr _lastOutgoingThis;
private static uint _lastOutgoingSource = 8;
public static bool IncomingInstalled { get; private set; }
public static bool OutgoingInstalled { get; private set; }
public static bool IsInstalled => (!EnableIncomingHook || IncomingInstalled) && (!EnableOutgoingHook || OutgoingInstalled);
@ -189,17 +195,17 @@ internal static class ChatCallbackHooks
private static bool TryInstallIncomingWrapperHook(AcClientTextSection textSection, out string incomingStatus)
{
int incomingOff = IncomingChatWrapperVa - textSection.TextBaseVa;
if (!PatternScanner.VerifyBytes(textSection.Bytes, incomingOff, IncomingChatWrapperSignature))
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "ChatCallback.IncomingChatWrapper", IncomingChatWrapperPattern, IncomingChatWrapperVa);
if (!resolved.Success)
{
incomingStatus = $"signature mismatch @ 0x{IncomingChatWrapperVa:X8}";
incomingStatus = $"unresolved (VA 0x{IncomingChatWrapperVa:X8})";
RynthLog.Compat($"Compat: incoming chat hook unavailable - {incomingStatus}");
return false;
}
try
{
_incomingAddress = new IntPtr(textSection.TextBaseVa + incomingOff);
_incomingAddress = resolved.Address;
_incomingChatWrapperDetour = IncomingChatWrapperDetour;
IntPtr incomingPtr = Marshal.GetFunctionPointerForDelegate(_incomingChatWrapperDetour);
_originalIncomingChatWrapper = Marshal.GetDelegateForFunctionPointer<IncomingChatWrapperDelegate>(MinHook.HookCreate(_incomingAddress, incomingPtr));
@ -218,10 +224,10 @@ internal static class ChatCallbackHooks
private static bool TryInstallIncomingAddTextHook(AcClientTextSection textSection, out string incomingStatus)
{
int incomingOff = IncomingChatAddTextToScrollVa - textSection.TextBaseVa;
if (!PatternScanner.VerifyBytes(textSection.Bytes, incomingOff, IncomingChatAddTextToScrollSignature))
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "ChatCallback.IncomingChatAddTextToScroll", IncomingChatAddTextToScrollPattern, IncomingChatAddTextToScrollVa);
if (!resolved.Success)
{
incomingStatus = $"signature mismatch @ 0x{IncomingChatAddTextToScrollVa:X8}";
incomingStatus = $"unresolved (VA 0x{IncomingChatAddTextToScrollVa:X8})";
RynthLog.Compat($"Compat: incoming chat hook unavailable - {incomingStatus}");
return false;
}
@ -230,7 +236,7 @@ internal static class ChatCallbackHooks
{
unsafe
{
_incomingAddress = new IntPtr(textSection.TextBaseVa + incomingOff);
_incomingAddress = resolved.Address;
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int> pDetour = &IncomingChatAddTextDetour;
MinHook.Hook(_incomingAddress, (IntPtr)pDetour, out _originalIncomingChatAddTextPtr);
}
@ -247,6 +253,7 @@ internal static class ChatCallbackHooks
private static int IncomingChatWrapperDetour(int flags, IntPtr text, int chatChannel)
{
RecursionGuard.Tick("ChatCallbackHooks.IncomingChatWrapper");
try
{
return CurrentIncomingMode switch
@ -269,6 +276,7 @@ internal static class ChatCallbackHooks
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static unsafe int IncomingChatAddTextDetour(IntPtr thisPtr, IntPtr text, uint chatType, uint unknown, IntPtr stringInfo)
{
RecursionGuard.Tick("ChatCallbackHooks.IncomingChatAddText");
// 1. Read string BEFORE original — buffer may be freed after
string? line = (text != IntPtr.Zero) ? ReadIncomingChatLine(text, chatType) : null;
@ -326,9 +334,25 @@ internal static class ChatCallbackHooks
private static int OutgoingChatDetour(IntPtr thisPtr, IntPtr text, uint commandSource)
{
RecursionGuard.Tick("ChatCallbackHooks.OutgoingChat");
try
{
string? line = ReadWidePString(text);
LogoffOriginProbe.RecordChat($"AC OutgoingChat src={commandSource}", line);
// Capture the chat-manager 'this' + command source from the live submit
// so ChatCommandDispatcher can re-invoke this function directly later.
if (thisPtr != IntPtr.Zero)
{
_lastOutgoingThis = thisPtr;
_lastOutgoingSource = commandSource;
}
// RynthCore engine commands (/rc ...) — consume before plugins or
// AC see the line so the user never broadcasts "/rc resetbar" and
// a hidden overlay bar stays recoverable.
if (RynthCoreChatCommands.TryHandle(line))
return 1;
if (PluginManager.DispatchChatBarEnter(line))
return 1;
@ -514,4 +538,114 @@ internal static class ChatCallbackHooks
{
return opcode is 0xE9 or 0xE8 or 0xEB or 0x68 or 0xFF;
}
/// <summary>True once a chat-manager 'this' has been captured from a live submit.</summary>
public static bool CanDispatchDirect =>
OutgoingInstalled && _originalOutgoingChat != null && _lastOutgoingThis != IntPtr.Zero;
/// <summary>
/// Dispatches a chat line by calling AC's outgoing-chat function directly — the
/// same path AC takes when you press Enter on the native chat bar, but with no
/// keystroke simulation and no chat-bar state, so it is repeatable. Uses the
/// 'this' + command source captured by <see cref="OutgoingChatDetour"/> from a
/// prior real submit. Returns false if the hook isn't installed or no 'this' has
/// been captured yet — the caller then falls back to keystroke simulation, whose
/// first successful send seeds the capture for all subsequent calls.
/// Plugin pre-dispatch / engine-command handling is the caller's responsibility
/// (already done in ChatCommandDispatcher.Dispatch), so this goes straight to AC.
/// </summary>
public static unsafe bool TryDispatchDirect(string? text)
{
if (!OutgoingInstalled || _originalOutgoingChat == null)
return false;
IntPtr self = _lastOutgoingThis;
if (self == IntPtr.Zero || string.IsNullOrWhiteSpace(text))
return false;
string line = text!.TrimEnd('\r', '\n');
if (line.Length == 0)
return false;
foreach (char c in line)
if (c < 0x20 && c != '\t')
return false; // never feed AC control chars
LogoffOriginProbe.RecordChat("OutgoingChat direct", line);
try
{
ushort[] chars = new ushort[line.Length + 1]; // +1 null terminator (wcslen)
for (int i = 0; i < line.Length; i++)
chars[i] = line[i];
var wide = OutgoingWidePString.Create(chars);
try
{
// 'wide' is a stack local (unmanaged struct) — its address is stable
// for the synchronous call, so no 'fixed' pin is needed (or allowed).
_originalOutgoingChat(self, (IntPtr)(&wide), _lastOutgoingSource);
return true;
}
finally { wide.Dispose(); }
}
catch (Exception ex)
{
RynthLog.Compat($"OutgoingChat direct failed: {ex.GetType().Name}: {ex.Message}");
return false;
}
}
/// <summary>
/// Clears the cached chat-manager 'this'. Called on logout: AC frees the object
/// during the world→charselect transition, so the stale pointer must not be
/// reused. It is re-captured from the next real submit after the next login.
/// </summary>
public static void ResetOutgoingTarget()
{
_lastOutgoingThis = IntPtr.Zero;
}
// Minimal duplicate of ClientHelperHooks.WidePString (AC1Legacy::PStringBase<wchar_t>).
// Duplicated deliberately so the actively-used WriteToChat path stays untouched.
// Phase B / 1a-dup: resolve the PStringBase<wchar_t> ctor/dtor (fn VAs) by pattern and the
// s_NullBuffer (data VA) by code-xref. These were duplicate raw VAs left by 1a's per-file pass.
private static readonly byte?[] PatWidePStringCtor = [ 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x0C, 0x85, 0xFF, 0x8B, 0xF1, 0x74, 0x2C ];
private static readonly byte?[] PatWidePStringDtor = [ 0x56, 0x8B, 0x31, 0x83, 0xEE, 0x14, 0x8D, 0x46 ];
private static readonly byte?[] PatXrefWideNullBuffer = [ 0x3B, 0x05, null, null, null, null, 0x74, 0xE7 ];
private static unsafe void* ResolveFnVa(string name, byte?[] pattern, int fallbackVa)
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) return (void*)fallbackVa;
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
return (void*)(r.Success ? r.Address : new IntPtr(fallbackVa));
}
private static IntPtr ResolveDataVa(string name, byte?[] pattern, int operandOffset, int fallbackVa)
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) return new IntPtr(fallbackVa);
return HookResolver.ResolveData(text, name, pattern, operandOffset, fallbackVa).Address;
}
[StructLayout(LayoutKind.Sequential)]
private unsafe struct OutgoingWidePString
{
private static readonly IntPtr NullWideBufferVa = ResolveDataVa("ChatCallback.PStringW_NullBuffer", PatXrefWideNullBuffer, 2, 0x00818340);
private static readonly delegate* unmanaged[Thiscall]<OutgoingWidePString*, ushort*, void> Ctor =
(delegate* unmanaged[Thiscall]<OutgoingWidePString*, ushort*, void>)ResolveFnVa("ChatCallback.PStringW_ctor", PatWidePStringCtor, 0x00402730);
private static readonly delegate* unmanaged[Thiscall]<OutgoingWidePString*, void> Dtor =
(delegate* unmanaged[Thiscall]<OutgoingWidePString*, void>)ResolveFnVa("ChatCallback.PStringW_dtor", PatWidePStringDtor, 0x004011B0);
public IntPtr CharBuffer;
public static OutgoingWidePString Create(ushort[] chars)
{
var value = new OutgoingWidePString { CharBuffer = Marshal.ReadIntPtr(NullWideBufferVa) };
fixed (ushort* pChars = chars)
Ctor(&value, pChars);
return value;
}
public void Dispose()
{
fixed (OutgoingWidePString* ptr = &this)
Dtor(ptr);
}
}
}

View file

@ -1,5 +1,7 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
@ -10,17 +12,46 @@ namespace RynthCore.Engine.Compatibility;
/// </summary>
internal static unsafe class ChatCommandDispatcher
{
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
// The Event_*/PStringBase VAs below are now FALLBACKs; these signatures (verified unique
// + landing exactly at the VA offline via tools/pe_pattern.py) are the source of truth.
// Declared BEFORE the fn-ptr fields so the static field initializers see them. The Event_*
// senders are near-identical templates, so the patterns run long to reach the distinct tail.
private static readonly byte?[] PatEventTalk = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x1C, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x54, 0x24, 0x10, 0x52, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x44, 0x24, 0x0C, 0xC7, 0x00, 0x15 ];
private static readonly byte?[] PatEventEmote = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x1C, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x54, 0x24, 0x10, 0x52, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x44, 0x24, 0x0C, 0xC7, 0x00, 0xDF ];
private static readonly byte?[] PatEventSoulEmote = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x1C, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x54, 0x24, 0x10, 0x52, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x44, 0x24, 0x0C, 0xC7, 0x00, 0xE1 ];
private static readonly byte?[] PatEventTalkDirectByName = [ 0x83, 0xEC, 0x0C, 0x53, 0x55, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x20, 0x89, 0x44, 0x24, 0x18, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x14, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x1C, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x18, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0x6C, 0x24, 0x24, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x14, 0x51, 0x8B, 0xCD, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x54, 0x24, 0x14, 0x52, 0x8D, 0x4C, 0x24, 0x1C, 0x03, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x89, 0x44, 0x24, 0x10, 0x8B, 0xF8, 0x56, 0x8D, 0x44, 0x24, 0x14, 0x50, 0x8D, 0x4C, 0x24, 0x1C, 0xE8, null, null, null, null, 0x8B, 0x4C, 0x24, 0x10, 0xC7, 0x01, 0x5D ];
private static readonly byte?[] PatEventChannelBroadcast = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x20, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x08, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x54, 0x24, 0x10, 0x52, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x44, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x00, 0x47 ];
private static readonly byte?[] PatPStringBaseCtor = [ 0x56, 0x8B, 0x74, 0x24, 0x08, 0x85, 0xF6, 0x57, 0x8B, 0xF9, 0x74, 0x35, 0x80, 0x3E, 0x00, 0x74, 0x30, 0x8B, 0xC6, 0x8D, 0x50, 0x01, 0x8A, 0x08, 0x40, 0x84, 0xC9, 0x75, 0xF9, 0x2B, 0xC2, 0x50, 0x8B, 0xCF, 0xE8, null, null, null, null, 0x8B, 0x07 ];
private static readonly byte?[] PatPStringBaseClear = [ 0xA1, 0x1C, 0xF1, 0x8E, 0x00, 0x56, 0x57, 0x8B, 0xF9, 0x8B, 0x37, 0x3B, 0xF0, 0x74, 0x2D, 0x8D, 0x46, 0x04, 0x50, 0xFF, 0x15, 0xF8, 0x31, 0x79, 0x00, 0x85, 0xC0, 0x75, 0x0C, 0x85, 0xF6, 0x74, 0x08, 0x8B, 0x16, 0x6A, 0x01, 0x8B, 0xCE, 0xFF, 0x12, 0xA1, 0x1C, 0xF1, 0x8E, 0x00, 0x8B, 0xC8, 0x83, 0xC1, 0x04, 0x51, 0x89, 0x07, 0xFF, 0x15, 0xFC, 0x31, 0x79, 0x00, 0x5F ];
private static void* ResolveVa(string name, byte?[] pattern, int fallbackVa)
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
return (void*)fallbackVa;
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
return (void*)(r.Success ? r.Address : new IntPtr(fallbackVa));
}
// Phase B: PStringBase<char>::s_NullBuffer (0x008EF11C) via code-xref (3B 3D <addr>), offset 2.
private static readonly byte?[] PatXrefPStringNullBuffer = [ 0x3B, 0x3D, null, null, null, null, 0x74, 0xF1 ];
private static IntPtr ResolveDataVa(string name, byte?[] pattern, int operandOffset, int fallbackVa)
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
return new IntPtr(fallbackVa);
return HookResolver.ResolveData(text, name, pattern, operandOffset, fallbackVa).Address;
}
// CM_Communication::Event_* — all cdecl, all using AC1Legacy::PStringBase<char>
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, byte> FnEventTalk =
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)0x006A53E0;
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)ResolveVa("ChatCmd.Event_Talk", PatEventTalk, 0x006A53E0);
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, byte> FnEventEmote =
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)0x006A4F40;
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)ResolveVa("ChatCmd.Event_Emote", PatEventEmote, 0x006A4F40);
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, byte> FnEventSoulEmote =
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)0x006A5320;
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)ResolveVa("ChatCmd.Event_SoulEmote", PatEventSoulEmote, 0x006A5320);
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, LegacyPString*, byte> FnEventTalkDirectByName =
(delegate* unmanaged[Cdecl]<LegacyPString*, LegacyPString*, byte>)0x006A55A0;
(delegate* unmanaged[Cdecl]<LegacyPString*, LegacyPString*, byte>)ResolveVa("ChatCmd.Event_TalkDirectByName", PatEventTalkDirectByName, 0x006A55A0);
private static readonly delegate* unmanaged[Cdecl]<uint, LegacyPString*, byte> FnEventChannelBroadcast =
(delegate* unmanaged[Cdecl]<uint, LegacyPString*, byte>)0x006A4E50;
(delegate* unmanaged[Cdecl]<uint, LegacyPString*, byte>)ResolveVa("ChatCmd.Event_ChannelBroadcast", PatEventChannelBroadcast, 0x006A4E50);
private const uint WM_KEYDOWN = 0x0100;
private const uint WM_KEYUP = 0x0101;
@ -33,6 +64,16 @@ internal static unsafe class ChatCommandDispatcher
/// </summary>
public static bool UseDirectChatInput { get; set; }
/// <summary>
/// Recursion guard for the plugin pre-dispatch step. A plugin's
/// OnChatBarEnter handler may chain by calling Host.InvokeChatParser →
/// PluginManager.InvokeChatParser → ClientHelperHooks.InvokeParser →
/// ChatCommandDispatcher.Dispatch. Without this guard the plugin would
/// re-enter its own OnChatBarEnter on the chained line and could loop.
/// </summary>
[ThreadStatic]
private static bool _inPluginPreDispatch;
/// <summary>
/// AC1Legacy::PStringBase&lt;char&gt; for Event_* functions.
/// </summary>
@ -41,11 +82,11 @@ internal static unsafe class ChatCommandDispatcher
{
public IntPtr Buffer;
private static readonly IntPtr NullBufferVa = new(0x008EF11C);
private static readonly IntPtr NullBufferVa = ResolveDataVa("ChatCmd.PStringChar_NullBuffer", PatXrefPStringNullBuffer, 2, 0x008EF11C);
private static readonly delegate* unmanaged[Thiscall]<LegacyPString*, byte*, void> Ctor =
(delegate* unmanaged[Thiscall]<LegacyPString*, byte*, void>)0x0048C3E0;
(delegate* unmanaged[Thiscall]<LegacyPString*, byte*, void>)ResolveVa("ChatCmd.PStringBaseC_ctor", PatPStringBaseCtor, 0x0048C3E0);
private static readonly delegate* unmanaged[Thiscall]<LegacyPString*, void> ClearFn =
(delegate* unmanaged[Thiscall]<LegacyPString*, void>)0x004AB990;
(delegate* unmanaged[Thiscall]<LegacyPString*, void>)ResolveVa("ChatCmd.PStringBaseC_Clear", PatPStringBaseClear, 0x004AB990);
public static LegacyPString Create(string text)
{
@ -70,14 +111,64 @@ internal static unsafe class ChatCommandDispatcher
if (string.IsNullOrWhiteSpace(text))
return false;
// Deep-audit finding #4 (2026-06-18): this whole function is not
// network-only — it runs arbitrary plugin OnChatBarEnter handlers,
// constructs/destructs AC's native PStringBase<char> in AC's heap,
// and calls Event_Talk/Event_Emote/etc. directly against AC's live
// chat-manager. The old inline comment claiming this was "thread-safe"
// was an inherited Decal/VTank assumption that contradicts the
// engine's own AcMainThreadQueue design (see the documented
// 0x00460D1D chat-buffer write-AV class). Gating here (rather than at
// each call site) covers every off-thread caller at once:
// OnLoginCommandRunner (ThreadPool), ChatFileDispatcher
// (FileSystemWatcher thread), and Host.InvokeChatParser (plugin
// export, any thread). The queued call re-invokes this same method
// from the drain, where IsOnMainThread is satisfied and the body
// below runs directly — so there's only one code path to keep in sync.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueChatCommand(text);
try
{
string trimmed = text.Trim();
if (trimmed.Length == 0) return false;
LogoffOriginProbe.RecordChat("ChatCommandDispatcher", trimmed);
// RynthCore engine commands (/rc ...) are handled before plugin
// pre-dispatch and before any AC chat routing so they work even
// when the overlay is hidden and no plugin can eat the line.
if (RynthCoreChatCommands.TryHandle(trimmed))
return true;
// Expand shorthand: /s → /say, /t → /tell, /e → /emote
trimmed = ExpandShorthand(trimmed);
// Plugin pre-dispatch: matches AC's natural OutgoingChatDetour
// behavior — when a user types in the chat bar, plugins
// (RynthAi /ra, VTank /vt, UBService /ub, MagTools /mt, etc.) get
// first dibs via OnChatBarEnter and can eat the line. We mirror
// that here so callers like OnLoginCommandRunner and
// Host.InvokeChatParser produce identical-to-typed semantics.
//
// Skipped when:
// - Already inside a plugin pre-dispatch on this thread
// (avoids infinite loops on chained Host.InvokeChatParser calls)
// - UseDirectChatInput is on (raw simulate mode bypasses this)
if (!UseDirectChatInput && !_inPluginPreDispatch)
{
_inPluginPreDispatch = true;
try
{
if (PluginManager.DispatchChatBarEnter(trimmed))
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"ChatDispatch: plugin pre-dispatch threw on '{trimmed}' - {ex.GetType().Name}: {ex.Message}");
}
finally { _inPluginPreDispatch = false; }
}
// Direct Chat Input mode — everything goes through keyboard sim
if (UseDirectChatInput)
return SimulateChatInput(trimmed);
@ -102,16 +193,16 @@ internal static unsafe class ChatCommandDispatcher
if (StartsWithCmd(trimmed, "/a "))
return DispatchChannelBroadcast(1, trimmed.Substring(3));
// /f message (fellowship — use keyboard sim, no direct Event_*)
// /f message (fellowship — no direct Event_*; use the raw chat path)
if (StartsWithCmd(trimmed, "/f "))
return SimulateChatInput(trimmed);
return DispatchRaw(trimmed);
// Bare text → say
if (!trimmed.StartsWith("/", StringComparison.Ordinal))
return DispatchSay(trimmed);
// Everything else → keyboard simulation fallback
return SimulateChatInput(trimmed);
// Everything else (arbitrary slash commands like /smite) → raw chat path
return DispatchRaw(trimmed);
}
catch (Exception ex)
{
@ -169,7 +260,7 @@ internal static unsafe class ChatCommandDispatcher
int commaIdx = args.IndexOf(',');
if (commaIdx < 1)
{
return SimulateChatInput("/tell " + args);
return DispatchRaw("/tell " + args);
}
string targetName = args.Substring(0, commaIdx).Trim();
@ -210,29 +301,59 @@ internal static unsafe class ChatCommandDispatcher
finally { ps.Dispose(); }
}
/// <summary>
/// Dispatches an arbitrary chat line. Prefers calling AC's outgoing-chat
/// function directly (deterministic and repeatable — no native chat-bar state to
/// corrupt); falls back to keystroke simulation only until the chat 'this' has
/// been captured (typically the very first send of a session, whose successful
/// submit seeds the capture for every send after it).
/// </summary>
private static bool DispatchRaw(string command)
{
if (ChatCallbackHooks.TryDispatchDirect(command))
return true;
return SimulateChatInput(command);
}
/// <summary>
/// Simulates keyboard input to type and submit a chat command.
/// Used as fallback for commands without a direct Event_* function.
/// </summary>
private static bool SimulateChatInput(string command)
{
// Enter → opens chat input
IntPtr enterDown = MakeKeyLParam(0x1C, false);
IntPtr enterUp = MakeKeyLParam(0x1C, true);
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYDOWN, new IntPtr(VK_RETURN), enterDown);
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr('\r'), enterDown);
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYUP, new IntPtr(VK_RETURN), enterUp);
LogoffOriginProbe.RecordChat("SimulateChatInput", command);
// Deep-audit finding #18 (2026-06-18): SendToGameWndProc drives
// CallWindowProcA directly into AC's WndProc — calling that off the
// window-owning thread is a cross-thread WndProc re-entry. Dispatch()
// gating (finding #4) already closes the two known off-thread paths
// into this method, but wrap here too per the fix note ("protect
// future callers"): RunOnGameThread inlines with zero overhead when
// already on the game thread (the common case, post-#4) and marshals
// synchronously otherwise.
return ImGuiBackend.Win32Backend.RunOnGameThread(() =>
{
// Enter → opens chat input. The WM_CHAR '\r' is required here to complete
// AC's chat-bar open transition.
IntPtr enterDown = MakeKeyLParam(0x1C, false);
IntPtr enterUp = MakeKeyLParam(0x1C, true);
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYDOWN, new IntPtr(VK_RETURN), enterDown);
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr('\r'), enterDown);
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYUP, new IntPtr(VK_RETURN), enterUp);
// Type each character
foreach (char c in command)
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr(c), IntPtr.Zero);
// Type each character
foreach (char c in command)
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr(c), IntPtr.Zero);
// Enter → submit
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYDOWN, new IntPtr(VK_RETURN), enterDown);
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr('\r'), enterDown);
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYUP, new IntPtr(VK_RETURN), enterUp);
// Enter → submit. NO trailing WM_CHAR '\r' here: the WM_KEYDOWN submits and
// closes the bar; a '\r' arriving on the now-closed bar re-opens it (the
// "lone '\r'" behavior the chat-capture path also guards against), leaving the
// bar open so the NEXT command's open-Enter submits an empty bar instead and
// the command is lost — the "works once then stops" symptom.
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYDOWN, new IntPtr(VK_RETURN), enterDown);
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYUP, new IntPtr(VK_RETURN), enterUp);
return true;
return true;
});
}
private static IntPtr MakeKeyLParam(byte scanCode, bool keyUp)

View file

@ -0,0 +1,188 @@
using System;
using System.IO;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// File-driven chat command dispatcher.
///
/// Watches <c>%APPDATA%\RynthCore\dispatch.txt</c>. Any change to that file
/// is interpreted as a slash command for AC's chat — the file's content
/// (last non-blank line) is sent through <see cref="ChatCommandDispatcher.Dispatch"/>,
/// which routes through any RynthCore-style plugins (RynthAi, VTank, etc.)
/// just like a user-typed command would.
///
/// Use cases:
/// - User is on Remote Desktop and AC's chat input is unresponsive after a
/// hot reload or focus event. Open the dispatch.txt file in Notepad,
/// change the contents, save — command fires.
/// - Scripted automation outside the AC client.
/// - Backup chat path when ImGui/Avalonia keyboard capture is eating input.
///
/// Format: the file is plain text. The dispatcher reads the LAST non-blank
/// non-comment line (lines starting with '#' are ignored). Saving the file
/// triggers a debounced dispatch (~200ms after the last save event, so
/// half-completed edits don't fire).
///
/// Safety:
/// - Empty file or only comments → no dispatch.
/// - Dispatcher does not delete the file. Repeated saves of the same
/// content re-fire the command — by design, so the user can save again
/// to retry. If you want fire-once, write a sentinel line.
/// </summary>
internal static class ChatFileDispatcher
{
private static FileSystemWatcher? _watcher;
private static readonly object SyncRoot = new();
private static long _pendingFireTickMs;
private static Timer? _debounceTimer;
private static string _lastDispatchedContent = string.Empty;
private const int DebounceMs = 200;
public static string FilePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"dispatch.txt");
public static void Start()
{
if (_watcher != null) return;
try
{
string dir = Path.GetDirectoryName(FilePath) ?? "";
string name = Path.GetFileName(FilePath);
if (string.IsNullOrEmpty(dir) || string.IsNullOrEmpty(name))
{
RynthLog.Compat($"ChatFileDispatcher: invalid FilePath '{FilePath}', not starting.");
return;
}
Directory.CreateDirectory(dir);
if (!File.Exists(FilePath))
{
File.WriteAllText(FilePath,
"# RynthCore chat-command dispatch file.\n" +
"# Save this file with a slash command on the last line to dispatch it.\n" +
"# Example: /ra clearbusy\n" +
"# Comments (lines starting with #) and blank lines are ignored.\n" +
"# Plugin pre-dispatch (RynthAi /ra, etc.) is honored.\n");
}
_watcher = new FileSystemWatcher(dir, name)
{
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.CreationTime,
EnableRaisingEvents = true,
};
_watcher.Changed += OnChanged;
_watcher.Created += OnChanged;
_watcher.Renamed += OnRenamed;
_debounceTimer = new Timer(DispatchOnce, null, Timeout.Infinite, Timeout.Infinite);
RynthLog.Compat($"ChatFileDispatcher: watching '{FilePath}'.");
}
catch (Exception ex)
{
RynthLog.Compat($"ChatFileDispatcher: start failed — {ex.GetType().Name}: {ex.Message}");
}
}
public static void Stop()
{
try
{
if (_watcher != null)
{
_watcher.EnableRaisingEvents = false;
_watcher.Dispose();
_watcher = null;
}
_debounceTimer?.Dispose();
_debounceTimer = null;
}
catch { /* shutdown — non-fatal */ }
}
private static void OnChanged(object _, FileSystemEventArgs e) => ScheduleDispatch();
private static void OnRenamed(object _, RenamedEventArgs e) => ScheduleDispatch();
private static void ScheduleDispatch()
{
lock (SyncRoot)
{
_pendingFireTickMs = Environment.TickCount64 + DebounceMs;
try { _debounceTimer?.Change(DebounceMs, Timeout.Infinite); }
catch { /* timer disposed during shutdown */ }
}
}
private static void DispatchOnce(object? _)
{
string? line = null;
try
{
// ReadAllText with a brief retry: the editor may still hold the
// file briefly after save, FileSystemWatcher fires before the
// handle is released. Try a few times.
string? text = null;
for (int attempt = 0; attempt < 5; attempt++)
{
try { text = File.ReadAllText(FilePath); break; }
catch (IOException) { Thread.Sleep(40); }
}
if (text == null) return;
// Find the LAST non-blank non-comment line.
string[] rawLines = text.Replace("\r\n", "\n").Split('\n');
for (int i = rawLines.Length - 1; i >= 0; i--)
{
string trimmed = rawLines[i].Trim();
if (trimmed.Length == 0) continue;
if (trimmed.StartsWith('#')) continue;
line = trimmed;
break;
}
if (string.IsNullOrWhiteSpace(line))
return;
// Dedup adjacent identical content silently. Saving the file
// re-fires only if content actually differs from last dispatch
// OR the line is prefixed with "force:" (force-fire even if
// same content). User can also clear+resave to fire again.
bool force = line.StartsWith("force:", StringComparison.OrdinalIgnoreCase);
if (force) line = line.Substring("force:".Length).TrimStart();
if (!force && line == _lastDispatchedContent)
{
RynthLog.Verbose($"ChatFileDispatcher: skipped re-dispatch of unchanged line '{line}'.");
return;
}
_lastDispatchedContent = line;
// Strip leading slash if present — Dispatch handles both forms.
string toDispatch = line.StartsWith('/') ? line.Substring(1) : line;
string forDispatch = '/' + toDispatch;
RynthLog.Compat($"ChatFileDispatcher: dispatching '{forDispatch}'.");
try
{
bool ok = ChatCommandDispatcher.Dispatch(forDispatch);
RynthLog.Compat($"ChatFileDispatcher: dispatched ok={ok}.");
}
catch (Exception ex)
{
RynthLog.Compat($"ChatFileDispatcher: Dispatch threw — {ex.GetType().Name}: {ex.Message}");
}
}
catch (Exception ex)
{
RynthLog.Compat($"ChatFileDispatcher: read/parse failed — {ex.GetType().Name}: {ex.Message}");
}
}
}

View file

@ -3,15 +3,11 @@
//
// Hooks gmMainChatUI::ListenToElementMessage purely to capture the widget's
// 'this' pointer on first UI dispatch. Per-frame visibility assertion is
// driven from EndSceneHook (ChatHooks.TickHide), which avoids the unsafe
// UseTime trampoline that was crashing with 0xC000001D — UseTime's prologue
// contains a relative jump MinHook on x86 mis-relocated. ListenToElementMessage
// is a large function with a standard MSVC prologue, safe to hook.
// driven from EndSceneHook (ChatHooks.TickHide) and calls UIElement::SetVisible
// directly on the captured singleton.
//
// VA derivation (map offset + 0x00401000 = live VA):
// 000CD6F0 gmMainChatUI::ListenToElementMessage(UIElementMessageInfo const &)
// → 0x004CE6F0
// 00061390 UIElement::SetVisible(bool) → 0x00462390
// Both addresses (the listen hook and the SetVisible call target) are now
// resolved via HookResolver — pattern-scan first, fallback VA second.
// ============================================================================
using System;
@ -23,30 +19,60 @@ namespace RynthCore.Engine.Compatibility;
internal static class ChatHooks
{
private const int GmMainChatUIListenMsgVa = 0x004CE6F0;
private const int UIElementSetVisibleVa = 0x00462390;
// Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth.
private const int GmMainChatUIListenMsgFallbackVa = 0x004CE6F0;
private const int UIElementSetVisibleFallbackVa = 0x00462390;
// gmMainChatUI::ListenToElementMessage(UIElementMessageInfo const&)
// Reads the message kind from [esi+8], decrements, switches on it (0x3C, 0x3E, ...).
private static readonly byte?[] ListenToElementMessagePattern =
[
0x56, 0x8B, 0x74, 0x24, 0x08, 0x8B, 0x46, 0x08,
0x48, 0x57, 0x8B, 0xF9, 0x74, 0x72, 0x83, 0xE8,
0x06, 0x75, 0x7D, 0x8B, 0x4E, 0x04, 0x8B, 0x01,
0x6A, 0x06, 0xFF, 0x90, 0x94, 0x00, 0x00, 0x00
];
// UIElement::SetVisible(bool) — duplicated against RadarHooks deliberately;
// each consumer resolves independently so a partial failure isolates per-file.
private static readonly byte?[] UIElementSetVisiblePattern =
[
0x51, 0x53, 0x56, 0x57,
0x8B, 0x3D, null, null, null, null, // mov edi, ds:[imm32]
0x8B, 0xF1,
0xE8, null, null, null, null, // call rel32
0x8B, 0x9E, 0xA4, 0x00, 0x00, 0x00,
0x88, 0x44, 0x24, 0x0F
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void ListenToElementMessageDelegate(IntPtr thisPtr, IntPtr msgInfo);
private static ListenToElementMessageDelegate? _originalListen;
private static ListenToElementMessageDelegate? _listenDetour; // held alive to prevent GC
private static ListenToElementMessageDelegate? _listenDetour;
private static IntPtr _gmMainChatInstance;
private static IntPtr _uiElementSetVisibleAddress;
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
/// <summary>
/// When true, TickHide() calls UIElement::SetVisible(false) on the captured
/// chat widget each frame, hiding the retail chatbox. Re-asserted every frame.
/// </summary>
public static bool SuppressOriginalChat;
public static bool SuppressOriginalChat; // the user's "Hide retail chat" option
/// <summary>RynthChat's panel is on screen (set by RynthChatPanel).</summary>
public static volatile bool ChatPanelShown;
/// <summary>
/// RynthChat is standing in for the retail chat: in the world, its panel is open AND
/// "Hide retail chat" is on. Only then is the retail chatbox hidden and Enter routed to
/// RynthChat — whichever chat is visible gets Enter. Outside the world Enter is AC's:
/// at character select it enters the game.
/// </summary>
public static bool RynthChatOwnsChat =>
SuppressOriginalChat && ChatPanelShown && LoginLifecycleHooks.HasObservedLoginComplete;
/// <summary>The captured gmMainChatUI singleton. Zero until the user interacts
/// with the chat at least once (hover, click, message dispatch).</summary>
public static IntPtr GmMainChatInstance => _gmMainChatInstance;
public static void Initialize()
@ -60,109 +86,91 @@ internal static class ChatHooks
return;
}
int funcOff = GmMainChatUIListenMsgVa - textSection.TextBaseVa;
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
{
_statusMessage = $"ListenToElementMessage VA out of range @ 0x{GmMainChatUIListenMsgVa:X8}.";
RynthLog.Compat($"Compat: chat hook failed - {_statusMessage}");
return;
}
var setVisible = HookResolver.Resolve(textSection, "ChatHooks.UIElement::SetVisible",
UIElementSetVisiblePattern, UIElementSetVisibleFallbackVa);
if (setVisible.Success) _uiElementSetVisibleAddress = setVisible.Address;
byte firstByte = textSection.Bytes[funcOff];
if (firstByte is 0x00 or 0xCC or 0xC3)
var listen = HookResolver.Resolve(textSection, "ChatHooks.ListenToElementMessage",
ListenToElementMessagePattern, GmMainChatUIListenMsgFallbackVa);
if (!listen.Success)
{
_statusMessage = $"ListenToElementMessage looks invalid @ 0x{GmMainChatUIListenMsgVa:X8} (opcode 0x{firstByte:X2}).";
RynthLog.Compat($"Compat: chat hook failed - {_statusMessage}");
_statusMessage = $"ListenToElementMessage resolve failed ({listen.Detail}).";
return;
}
try
{
IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_listenDetour = ListenDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_listenDetour);
_originalListen = Marshal.GetDelegateForFunctionPointer<ListenToElementMessageDelegate>(
MinHook.HookCreate(targetAddress, detourPtr));
MinHook.HookCreate(listen.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(targetAddress);
MinHook.Enable(listen.Address);
_hookInstalled = true;
_statusMessage = $"Hooked gmMainChatUI::ListenToElementMessage @ 0x{targetAddress.ToInt32():X8}.";
RynthLog.Verbose($"Compat: chat hook ready @ 0x{targetAddress.ToInt32():X8}, firstByte=0x{firstByte:X2}");
_statusMessage = $"Hooked gmMainChatUI::ListenToElementMessage @ 0x{listen.Address.ToInt32():X8}.";
RynthLog.Compat($"ChatHooks: install ok.");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: chat hook failed - {ex.Message}");
RynthLog.Compat($"ChatHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static int _listenFires;
private static void ListenDetour(IntPtr thisPtr, IntPtr msgInfo)
{
RecursionGuard.Tick("ChatHooks.Listen");
if (thisPtr != IntPtr.Zero)
_gmMainChatInstance = thisPtr;
_originalListen!(thisPtr, msgInfo);
if (++_listenFires <= 3)
RynthLog.Compat($"ChatHooks: Listen fired #{_listenFires} this=0x{thisPtr.ToInt32():X8}");
try { _originalListen!(thisPtr, msgInfo); }
catch (Exception ex) { try { RynthLog.Compat($"ChatHooks: Listen original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
}
/// <summary>True once we've issued SetVisible(false) — used so we know to
/// restore visibility one frame after the suppress flag flips off.</summary>
private static bool _isHiddenAsserted;
// Starts true so the first tick asserts the setting either way: after an engine reload
// the previous generation may have left the chatbox hidden, and a fresh "false" here
// would never show it again even with "Hide retail chat" off. SetVisible(true) on a
// visible chatbox is a no-op.
private static bool _isHiddenAsserted = true;
/// <summary>
/// Per-frame visibility assertion — called from EndSceneHook every frame.
/// While suppression is on, calls SetVisible(false) every frame so the game
/// can't sneak the chat back on. When suppression flips off, calls
/// SetVisible(true) one time to restore the retail chatbox.
/// </summary>
public static unsafe void TickHide()
{
// CRITICAL: do not call SetVisible while AC is between in-world sessions.
// _gmMainChatInstance points at AC's gmMainChatUI singleton, which AC
// frees during the logout-to-charselect transition. Calling SetVisible
// on the freed pointer dereferences a stale vtable (filled with reused
// float/zero data) and AVs inside UIElement::IsVisible. We resume the
// assertion only after the next SendLoginCompleteNotification, by which
// time AC has rebuilt gmMainChatUI and ListenDetour has re-captured the
// fresh pointer.
if (!LoginLifecycleHooks.HasObservedLoginComplete)
return;
IntPtr inst = _gmMainChatInstance;
if (inst == IntPtr.Zero) return;
if (_uiElementSetVisibleAddress == IntPtr.Zero) return;
if (SuppressOriginalChat)
if (RynthChatOwnsChat)
{
try
{
((delegate* unmanaged[Thiscall]<IntPtr, int, void>)UIElementSetVisibleVa)(inst, 0);
((delegate* unmanaged[Thiscall]<IntPtr, int, void>)_uiElementSetVisibleAddress)(inst, 0);
}
catch { /* best-effort */ }
_isHiddenAsserted = true;
return;
}
// Suppression is off — if we previously hid it, show it again now.
if (_isHiddenAsserted)
{
try
{
((delegate* unmanaged[Thiscall]<IntPtr, int, void>)UIElementSetVisibleVa)(inst, 1);
((delegate* unmanaged[Thiscall]<IntPtr, int, void>)_uiElementSetVisibleAddress)(inst, 1);
}
catch { /* best-effort */ }
_isHiddenAsserted = false;
}
}
/// <summary>
/// Drops the cached <c>gmMainChatUI</c> singleton pointer. Called from the
/// logout pipeline so we don't reuse a freed pointer after the next login —
/// <see cref="ListenDetour"/> re-captures the fresh instance on the next
/// chat-UI message dispatch.
/// </summary>
public static void ResetCachedInstance()
{
_gmMainChatInstance = IntPtr.Zero;
_isHiddenAsserted = false;
_isHiddenAsserted = true; // re-assert on the next instance, as at start-up
}
}

View file

@ -62,6 +62,30 @@ internal static class ClientCombatHooks
private static AutoTargetDelegate? _autoTarget;
private static SendAttackHeightChangedDelegate? _sendAttackHeightChanged;
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
// The *Va consts above are now FALLBACKs. These signatures (verified unique + landing
// exactly at the VA offline against this client via tools/pe_pattern.py) are the source
// of truth, so binding survives AC-patch / ACE-rebuild drift. null = wildcard (rel32).
private static readonly byte?[] PatGetCombatSystem = [ 0xA1, 0x6C, 0x16, 0x87, 0x00, 0xC3, 0x90, 0x90 ];
private static readonly byte?[] PatSetRequestedAttackHeight = [ 0x8B, 0x51, 0x24, 0x8B, 0x44, 0x24, 0x04, 0x3B ];
private static readonly byte?[] PatStartAttackRequest = [ 0x51, 0x56, 0x8B, 0xF1, 0xE8, null, null, null, null, 0x8A ];
private static readonly byte?[] PatEndAttackRequest = [ 0x51, 0x56, 0x8B, 0xF1, 0x8A, 0x46, 0x3E, 0x84, 0xC0, 0x0F ];
private static readonly byte?[] PatPlayerInReadyPosition = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x83, 0xEC, 0x18 ];
private static readonly byte?[] PatAutoTarget = [ 0x83, 0xEC, 0x18, 0x53, 0x56, 0x57, 0x8D, 0x44, 0x24, 0x10 ];
private static readonly byte?[] PatSendAttackHeightChanged = [ 0xE8, null, null, null, null, 0x8B, 0x10, 0x68, 0xFC ];
// Phase B (1a-data): s_pCombatSystem global (0x0087166C) resolved by code-xref — the unique
// "mov [s_pCombatSystem],esi" site (89 35 <addr>); read the address from the operand at
// offset 2. The VA stays as the logged fallback.
private static readonly byte?[] PatXrefCombatSystemPtr = [ 0x89, 0x35, null, null, null, null, 0x8B, 0x06 ];
private static IntPtr _combatSystemPtrAddr = new(CombatSystemPtrVa);
private static T? Bind<T>(AcClientTextSection text, string name, byte?[] pattern, int fallbackVa) where T : Delegate
{
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
return r.Success ? Marshal.GetDelegateForFunctionPointer<T>(r.Address) : null;
}
private static bool _initialized;
private static string _statusMessage = "Not probed yet.";
@ -75,17 +99,26 @@ internal static class ClientCombatHooks
{
try
{
_getCombatSystem = Marshal.GetDelegateForFunctionPointer<GetCombatSystemDelegate>(new IntPtr(GetCombatSystemVa));
_setAttackHeight = Marshal.GetDelegateForFunctionPointer<SetRequestedAttackHeightDelegate>(new IntPtr(SetRequestedAttackHeightVa));
_startAttackRequest = Marshal.GetDelegateForFunctionPointer<StartAttackRequestDelegate>(new IntPtr(StartAttackRequestVa));
_endAttackRequest = Marshal.GetDelegateForFunctionPointer<EndAttackRequestDelegate>(new IntPtr(EndAttackRequestVa));
_playerInReadyPosition = Marshal.GetDelegateForFunctionPointer<PlayerInReadyPositionDelegate>(new IntPtr(PlayerInReadyPositionVa));
_autoTarget = Marshal.GetDelegateForFunctionPointer<AutoTargetDelegate>(new IntPtr(AutoTargetVa));
_sendAttackHeightChanged = Marshal.GetDelegateForFunctionPointer<SendAttackHeightChangedDelegate>(new IntPtr(SendAttackHeightChangedVa));
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
_statusMessage = "acclient .text not readable for pattern resolve.";
RynthLog.Compat($"Compat: ClientCombat probe failed - {_statusMessage}");
return false;
}
_combatSystemPtrAddr = HookResolver.ResolveData(text, "ClientCombat.s_pCombatSystem", PatXrefCombatSystemPtr, 2, CombatSystemPtrVa).Address;
_getCombatSystem = Bind<GetCombatSystemDelegate>(text, "ClientCombat.GetCombatSystem", PatGetCombatSystem, GetCombatSystemVa);
_setAttackHeight = Bind<SetRequestedAttackHeightDelegate>(text, "ClientCombat.SetRequestedAttackHeight", PatSetRequestedAttackHeight, SetRequestedAttackHeightVa);
_startAttackRequest = Bind<StartAttackRequestDelegate>(text, "ClientCombat.StartAttackRequest", PatStartAttackRequest, StartAttackRequestVa);
_endAttackRequest = Bind<EndAttackRequestDelegate>(text, "ClientCombat.EndAttackRequest", PatEndAttackRequest, EndAttackRequestVa);
_playerInReadyPosition = Bind<PlayerInReadyPositionDelegate>(text, "ClientCombat.PlayerInReadyPosition", PatPlayerInReadyPosition, PlayerInReadyPositionVa);
_autoTarget = Bind<AutoTargetDelegate>(text, "ClientCombat.AutoTarget", PatAutoTarget, AutoTargetVa);
_sendAttackHeightChanged = Bind<SendAttackHeightChangedDelegate>(text, "ClientCombat.SendAttackHeightChanged", PatSendAttackHeightChanged, SendAttackHeightChangedVa);
// Verify the combat system singleton is accessible
IntPtr cs = _getCombatSystem();
IntPtr globalPtr = Marshal.ReadIntPtr(new IntPtr(CombatSystemPtrVa));
IntPtr cs = _getCombatSystem?.Invoke() ?? IntPtr.Zero;
IntPtr globalPtr = Marshal.ReadIntPtr(_combatSystemPtrAddr);
RynthLog.Verbose($"Compat: ClientCombat GetCombatSystem()=0x{cs:X8}, global=0x{globalPtr:X8}");
if (cs == IntPtr.Zero && globalPtr == IntPtr.Zero)
{
@ -135,15 +168,27 @@ internal static class ClientCombatHooks
return false;
}
// Deep-audit finding #15 (2026-06-18): this fires 4 AC combat-state
// mutators (height notify, SetRequestedAttackHeight, StartAttackRequest,
// EndAttackRequest) that must land in the SAME order as the paired
// SelectItem that precedes it. Reachable off-thread via the host API,
// and UseNativeAttack defaults true — so unlike this file's sibling
// MeleeAttack/MissileAttack, this ran un-marshalled every fight. Marshal
// as ONE queue entry (not split into four) so the sequence stays atomic
// relative to the drain loop's other actions.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueNativeAttack(attackHeight, power);
try
{
IntPtr cs = _getCombatSystem();
if (cs == IntPtr.Zero)
{
IntPtr globalPtr = Marshal.ReadIntPtr(new IntPtr(CombatSystemPtrVa));
IntPtr globalPtr = Marshal.ReadIntPtr(_combatSystemPtrAddr);
if (globalPtr == IntPtr.Zero) return false;
cs = globalPtr;
}
if (!ClientObjectHooks.IsReadablePointer(cs)) return false;
// Notify client of height change via CM_Combat (same path as keyboard Del/End/PgDn)
_sendAttackHeightChanged?.Invoke(attackHeight);
@ -184,10 +229,18 @@ internal static class ClientCombatHooks
if (_autoTarget == null || _getCombatSystem == null)
return false;
// Same mutator class as NativeAttack (audit finding #15). Not currently
// exposed through the plugin SDK, so there's no live off-thread caller
// today — fail closed rather than queue, since queuing an unreachable
// path is dead-weight; revisit with an ActionKind if this is exposed.
if (!MainThreadGuard.IsOnMainThread())
return false;
try
{
IntPtr cs = _getCombatSystem();
if (cs == IntPtr.Zero) return false;
if (!ClientObjectHooks.IsReadablePointer(cs)) return false;
_autoTarget(cs);
return true;
}

View file

@ -62,6 +62,15 @@ internal static class ClientHelperHooks
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte EventStackableMergeDelegate(uint mergeFromId, uint mergeToId, int amount);
// CM_Inventory::Event_GiveObjectRequest — the public give-item-to-NPC API.
// Byte-identical sibling of Event_StackableMerge (differs only in the action
// opcode immediate: give writes 0xCD, merge 0x54). Cdecl, returns bool.
// Chorizite map: 002ACA60 -> live VA 0x006ACA60. Sends the F7B1 give
// GameAction. amount = stack count to give (0 = whole object).
// Args (live-disasm + call-site UIAttemptGive confirmed): item, targetNpc, amount.
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte EventGiveObjectRequestDelegate(uint objectId, uint targetId, int amount);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void UseObjectDelegate(IntPtr clientUiSystem, uint objectId);
@ -94,6 +103,8 @@ internal static class ClientHelperHooks
private const int TotalStackVa = 0x0081D7F0; // total_stack
// CM_Inventory::Event_StackableMerge — public merge-stack API (from Chorizite map).
private const int EventStackableMergeVa = 0x006ACDD0;
// CM_Inventory::Event_GiveObjectRequest — public give-to-NPC API (FALLBACK only; pattern-scanned).
private const int EventGiveObjectRequestVa = 0x006ACA60;
private const int UseObjectVa = 0x00565750;
private const int PlayerSystemVa = 0x0087119C;
private const int InqPlayerCoordsVa = 0x00560E00;
@ -114,6 +125,7 @@ internal static class ClientHelperHooks
private static MoveItemExternalDelegate? _moveItemExternal;
private static MoveItemInternalDelegate? _moveItemInternal;
private static EventStackableMergeDelegate? _eventStackableMerge;
private static EventGiveObjectRequestDelegate? _eventGiveObjectRequest;
private static InqPlayerCoordsDelegate? _inqPlayerCoords;
private static GetPlayerIdDelegate? _getPlayerId;
private static AddTextToScrollDelegate? _addTextToScroll;
@ -138,6 +150,7 @@ internal static class ClientHelperHooks
public static bool HasMoveItemInternal => _moveItemInternal != null;
public static bool HasSplitStackInternal => _moveItemInternal != null;
public static bool HasMergeStackInternal => _eventStackableMerge != null;
public static bool HasGiveObjectTo => _eventGiveObjectRequest != null;
public static bool HasGetCurCoords => _inqPlayerCoords != null;
public static bool HasGetPlayerId => _getPlayerId != null;
public static bool HasGetGroundContainerId => true;
@ -146,25 +159,99 @@ internal static class ClientHelperHooks
public static bool HasSalvagePanel => _sendNoticeOpenSalvagePanel != null && _gmSalvageUIAddNewItem != null && _gmSalvageUISalvage != null;
private static int _currentGroundContainerId;
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
// The *Va consts above are FALLBACKs; these signatures (verified unique + landing exactly
// at the VA offline via tools/pe_pattern.py) are the source of truth, surviving AC-patch /
// ACE-rebuild drift. UseObjectOn/UseEquippedItem are sibling templates differing only in a
// trailing immediate (0x00 vs 0x01) — both run long to stay unique. null = wildcard (rel32).
private static readonly byte?[] PatSetSelectedObject = [ 0x8B, 0x4C, 0x24, 0x08, 0x85, 0xC9, 0xA1, 0x54 ];
private static readonly byte?[] PatUseObject = [ 0x8B, 0x44, 0x24, 0x04, 0x85, 0xC0, 0x56, 0x8B, 0xF1, 0x74, 0x11 ];
private static readonly byte?[] PatGetAcPlugin = [ 0xA1, 0x54, 0x10, 0x87, 0x00, 0x85, 0xC0, 0x74, 0x03 ];
private static readonly byte?[] PatUseObjectOn = [ 0x51, 0x56, 0x8B, 0x74, 0x24, 0x0C, 0x8B, 0x06, 0x8D, 0x4C, 0x24, 0x04, 0x51, 0x56, 0xC7, 0x44, 0x24, 0x0C, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x50, 0x20, 0x8B, 0x44, 0x24, 0x14, 0x8B, 0x16, 0x50, 0x56, 0xFF, 0x52, 0x18, 0x8B, 0x4C, 0x24, 0x10, 0x6A, 0x00 ];
private static readonly byte?[] PatUseEquippedItem = [ 0x51, 0x56, 0x8B, 0x74, 0x24, 0x0C, 0x8B, 0x06, 0x8D, 0x4C, 0x24, 0x04, 0x51, 0x56, 0xC7, 0x44, 0x24, 0x0C, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x50, 0x20, 0x8B, 0x44, 0x24, 0x14, 0x8B, 0x16, 0x50, 0x56, 0xFF, 0x52, 0x18, 0x8B, 0x4C, 0x24, 0x10, 0x6A, 0x01 ];
private static readonly byte?[] PatMoveItemExternal = [ 0x8B, 0x44, 0x24, 0x10, 0x8B, 0x4C, 0x24, 0x0C, 0x8B, 0x54, 0x24, 0x08, 0x50, 0x51, 0x52, 0xE8 ];
private static readonly byte?[] PatMoveItemInternal = [ 0x8B, 0x44, 0x24, 0x10, 0x8B, 0x4C, 0x24, 0x14, 0x8B, 0x54, 0x24, 0x0C ];
private static readonly byte?[] PatEventStackableMerge = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x10, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x54 ];
// CM_Inventory::Event_GiveObjectRequest @0x006ACA60. Identical to the merge
// pattern except the trailing action-opcode write (give 0xCD vs merge 0x54) —
// that last byte is the uniqueness discriminator vs the merge/usewith siblings,
// so do NOT trim it. Generated + verified unique (1 match @0x006ACA60) via
// pe_pattern.py GEN against both acclient copies.
private static readonly byte?[] PatEventGiveObjectRequest = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x10, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0xCD ];
private static readonly byte?[] PatInqPlayerCoords = [ 0x83, 0xEC, 0x10, 0x53, 0x8B, 0x5C, 0x24, 0x1C, 0x55, 0x56 ];
private static readonly byte?[] PatGetPlayerId = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x85, 0xC0, 0x74, 0x07 ];
private static readonly byte?[] PatAddTextToScroll = [ 0x81, 0xEC, 0x48, 0x09, 0x00, 0x00, 0x8A, 0x84 ];
private static readonly byte?[] PatUseWithTargetEvent = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x35 ];
private static readonly byte?[] PatSendNoticeOpenSalvagePanel = [ 0xE8, null, null, null, null, 0x8B, 0x10, 0x68, 0x22 ];
private static readonly byte?[] PatGmSalvageUIAddNewItem = [ 0x8B, 0x44, 0x24, 0x04, 0x56, 0x57, 0x50, 0x8B, 0xF9 ];
private static readonly byte?[] PatGmSalvageUISalvage = [ 0x83, 0xEC, 0x14, 0x53, 0x56, 0x8B, 0xF1, 0x8B, 0x8E ];
private static T? Bind<T>(AcClientTextSection text, string name, byte?[] pattern, int fallbackVa) where T : Delegate
{
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
return r.Success ? Marshal.GetDelegateForFunctionPointer<T>(r.Address) : null;
}
// Phase B: data globals resolved by code-xref (operand at offset 2); the VA consts above
// stay as fallbacks. The 7 read/write globals resolve in Probe (cached int); the WidePString
// null-buffer resolves at struct static-init via ResolveDataVa.
private static readonly byte?[] PatXrefSelectedId = [ 0xC3, 0xA1, null, null, null, null, 0x89, 0x87 ];
private static readonly byte?[] PatXrefPrevSelectedId = [ 0x89, 0x3D, null, null, null, null, 0x74, 0x06 ];
private static readonly byte?[] PatXrefUiSystem = [ 0x8B, 0x0D, null, null, null, null, 0x53, 0x6A ];
private static readonly byte?[] PatXrefSplitAmount = [ 0x00, 0xA1, null, null, null, null, 0x57, 0x50 ];
private static readonly byte?[] PatXrefTotalStack = [ 0x10, 0xA1, null, null, null, null, 0x3B, 0xD8 ];
private static readonly byte?[] PatXrefPlayerSystem = [ 0xC7, 0x05, null, null, null, null, 0x00, 0x00, 0x00, 0x00, 0x83, 0xC6 ];
private static readonly byte?[] PatXrefCommunicationSystem = [ 0x08, 0xA1, null, null, null, null, 0x56, 0xBE ];
private static readonly byte?[] PatXrefWideNullBuffer = [ 0x3B, 0x05, null, null, null, null, 0x74, 0xE7 ];
private static int _selectedIdAddr = SelectedIdVa;
private static int _prevSelectedIdAddr = PreviousSelectedIdVa;
private static int _uiSystemAddr = UiSystemVa;
private static int _splitAmountAddr = SplitAmountVa;
private static int _totalStackAddr = TotalStackVa;
private static int _playerSystemAddr = PlayerSystemVa;
private static int _commSystemAddr = CommunicationSystemVa;
private static IntPtr ResolveDataVa(string name, byte?[] pattern, int operandOffset, int fallbackVa)
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
return new IntPtr(fallbackVa);
return HookResolver.ResolveData(text, name, pattern, operandOffset, fallbackVa).Address;
}
public static bool Probe()
{
try
{
_setSelectedObject = Marshal.GetDelegateForFunctionPointer<SetSelectedObjectDelegate>(new IntPtr(SetSelectedObjectVa));
_useObject = Marshal.GetDelegateForFunctionPointer<UseObjectDelegate>(new IntPtr(UseObjectVa));
_getAcPlugin = Marshal.GetDelegateForFunctionPointer<GetAcPluginDelegate>(new IntPtr(GetAcPluginVa));
_useObjectOn = Marshal.GetDelegateForFunctionPointer<UseObjectOnDelegate>(new IntPtr(UseObjectOnVa));
_useEquippedItem = Marshal.GetDelegateForFunctionPointer<UseEquippedItemDelegate>(new IntPtr(UseEquippedItemVa));
_moveItemExternal = Marshal.GetDelegateForFunctionPointer<MoveItemExternalDelegate>(new IntPtr(MoveItemExternalVa));
_moveItemInternal = Marshal.GetDelegateForFunctionPointer<MoveItemInternalDelegate>(new IntPtr(MoveItemInternalVa));
_eventStackableMerge = Marshal.GetDelegateForFunctionPointer<EventStackableMergeDelegate>(new IntPtr(EventStackableMergeVa));
_inqPlayerCoords = Marshal.GetDelegateForFunctionPointer<InqPlayerCoordsDelegate>(new IntPtr(InqPlayerCoordsVa));
_getPlayerId = Marshal.GetDelegateForFunctionPointer<GetPlayerIdDelegate>(new IntPtr(GetPlayerIdVa));
_addTextToScroll = Marshal.GetDelegateForFunctionPointer<AddTextToScrollDelegate>(new IntPtr(AddTextToScrollVa));
_useWithTargetEvent = Marshal.GetDelegateForFunctionPointer<UseWithTargetEventDelegate>(new IntPtr(UseWithTargetEventVa));
_sendNoticeOpenSalvagePanel = Marshal.GetDelegateForFunctionPointer<SendNoticeOpenSalvagePanelDelegate>(new IntPtr(SendNoticeOpenSalvagePanelVa));
_gmSalvageUIAddNewItem = Marshal.GetDelegateForFunctionPointer<GmSalvageUIAddNewItemDelegate>(new IntPtr(GmSalvageUIAddNewItemVa));
_gmSalvageUISalvage = Marshal.GetDelegateForFunctionPointer<GmSalvageUISalvageDelegate>(new IntPtr(GmSalvageUISalvageVa));
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
_statusMessage = "acclient .text not readable for pattern resolve.";
RynthLog.Compat($"Compat: helper hooks failed - {_statusMessage}");
return false;
}
_setSelectedObject = Bind<SetSelectedObjectDelegate>(text, "ClientHelper.SetSelectedObject", PatSetSelectedObject, SetSelectedObjectVa);
_useObject = Bind<UseObjectDelegate>(text, "ClientHelper.UseObject", PatUseObject, UseObjectVa);
_getAcPlugin = Bind<GetAcPluginDelegate>(text, "ClientHelper.GetAcPlugin", PatGetAcPlugin, GetAcPluginVa);
_useObjectOn = Bind<UseObjectOnDelegate>(text, "ClientHelper.UseObjectOn", PatUseObjectOn, UseObjectOnVa);
_useEquippedItem = Bind<UseEquippedItemDelegate>(text, "ClientHelper.UseEquippedItem", PatUseEquippedItem, UseEquippedItemVa);
_moveItemExternal = Bind<MoveItemExternalDelegate>(text, "ClientHelper.MoveItemExternal", PatMoveItemExternal, MoveItemExternalVa);
_moveItemInternal = Bind<MoveItemInternalDelegate>(text, "ClientHelper.MoveItemInternal", PatMoveItemInternal, MoveItemInternalVa);
_eventStackableMerge = Bind<EventStackableMergeDelegate>(text, "ClientHelper.Event_StackableMerge", PatEventStackableMerge, EventStackableMergeVa);
_eventGiveObjectRequest = Bind<EventGiveObjectRequestDelegate>(text, "ClientHelper.Event_GiveObjectRequest", PatEventGiveObjectRequest, EventGiveObjectRequestVa);
_inqPlayerCoords = Bind<InqPlayerCoordsDelegate>(text, "ClientHelper.InqPlayerCoords", PatInqPlayerCoords, InqPlayerCoordsVa);
_getPlayerId = Bind<GetPlayerIdDelegate>(text, "ClientHelper.GetPlayerId", PatGetPlayerId, GetPlayerIdVa);
_addTextToScroll = Bind<AddTextToScrollDelegate>(text, "ClientHelper.AddTextToScroll", PatAddTextToScroll, AddTextToScrollVa);
_useWithTargetEvent = Bind<UseWithTargetEventDelegate>(text, "ClientHelper.UseWithTargetEvent", PatUseWithTargetEvent, UseWithTargetEventVa);
_sendNoticeOpenSalvagePanel = Bind<SendNoticeOpenSalvagePanelDelegate>(text, "ClientHelper.SendNotice_OpenSalvagePanel", PatSendNoticeOpenSalvagePanel, SendNoticeOpenSalvagePanelVa);
_gmSalvageUIAddNewItem = Bind<GmSalvageUIAddNewItemDelegate>(text, "ClientHelper.gmSalvageUI_AddNewItem", PatGmSalvageUIAddNewItem, GmSalvageUIAddNewItemVa);
_gmSalvageUISalvage = Bind<GmSalvageUISalvageDelegate>(text, "ClientHelper.gmSalvageUI_Salvage", PatGmSalvageUISalvage, GmSalvageUISalvageVa);
_selectedIdAddr = HookResolver.ResolveData(text, "ClientHelper.s_selected_id", PatXrefSelectedId, 2, SelectedIdVa).Address.ToInt32();
_prevSelectedIdAddr = HookResolver.ResolveData(text, "ClientHelper.s_previous_selected_id", PatXrefPrevSelectedId, 2, PreviousSelectedIdVa).Address.ToInt32();
_uiSystemAddr = HookResolver.ResolveData(text, "ClientHelper.ClientUISystem", PatXrefUiSystem, 2, UiSystemVa).Address.ToInt32();
_splitAmountAddr = HookResolver.ResolveData(text, "ClientHelper.split_amount", PatXrefSplitAmount, 2, SplitAmountVa).Address.ToInt32();
_totalStackAddr = HookResolver.ResolveData(text, "ClientHelper.total_stack", PatXrefTotalStack, 2, TotalStackVa).Address.ToInt32();
_playerSystemAddr = HookResolver.ResolveData(text, "ClientHelper.CPlayerSystem", PatXrefPlayerSystem, 2, PlayerSystemVa).Address.ToInt32();
_commSystemAddr = HookResolver.ResolveData(text, "ClientHelper.CommunicationSystem", PatXrefCommunicationSystem, 2, CommunicationSystemVa).Address.ToInt32();
_initialized = true;
_statusMessage = "Ready.";
RynthLog.Verbose("Compat: helper hooks ready - validated select/state/chat helpers plus mapped interaction and inventory helpers.");
@ -186,6 +273,19 @@ internal static class ClientHelperHooks
public static bool SetSelectedObjectId(uint objectId)
{
// Marshal onto AC's main thread. AC's SetSelectedObject (0x0058D110)
// rewrites the selection/targeting UIElement subtree; off the pump thread
// it raced AC's own main-thread UI walk and corrupted a UIElement ->
// the deterministic write-AV at acclient+0x60D1D (UIElement smart-ptr
// refcount writeback into read-only .text; native-crash.log captured it
// on TWO threads at once during corpse-loot target selection, 2026-06-13).
// This was the last AC-mutating helper still calling AC directly off-thread
// (every UseObject/MoveItem/cast sibling already marshals). Drain re-invokes
// this on the main thread, where the gate is satisfied and it runs directly.
// SelectItem() funnels through here, so this one gate covers both.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueSetSelectedObject(objectId);
if (_setSelectedObject == null)
return false;
@ -202,26 +302,40 @@ internal static class ClientHelperHooks
public static uint GetSelectedItemId()
{
return ReadUInt32(SelectedIdVa);
return ReadUInt32(_selectedIdAddr);
}
public static uint GetPreviousSelectedItemId()
{
return ReadUInt32(PreviousSelectedIdVa);
return ReadUInt32(_prevSelectedIdAddr);
}
public static bool UseObject(uint objectId)
{
// P1 marshalling: looting's open-corpse / pick-up use-action runs on AC's
// main thread (via the OnEndScene drain), not off the pump thread. Off-thread
// UseObject mutated AC's animation sequence (CSequence) and corrupted it ->
// the CSequence::update_internal AV captured after looting was enabled.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueUseObject(objectId);
if (_useObject == null || !IsValidObjectId(objectId))
return false;
try
{
IntPtr uiSystem = ReadPointer(UiSystemVa);
IntPtr uiSystem = ReadPointer(_uiSystemAddr);
if (uiSystem == IntPtr.Zero)
return false;
// Reconcile the busy this open/use leaks (same source-fix as casts):
// UseObject bumps m_cBusy but no retail completion handler runs to
// decrement it, so corpse-open grinds left the plugin force-clearing
// every ~2s. Snapshot the delta; BusyCountHooks decrements it once
// the use-reach gesture completes. Both run on AC's main thread here.
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
_useObject(uiSystem, objectId);
BusyCountHooks.NoteDirectCastIssued(busyBefore);
return true;
}
catch
@ -232,12 +346,23 @@ internal static class ClientHelperHooks
public static bool UseObjectOn(uint sourceObjectId, uint targetObjectId)
{
// Marshal onto AC's main thread (off-thread use-on-target mutates AC's
// object/animation graph and corrupts it — see UseObject). Drain re-invokes
// this on the main thread, where the gate is satisfied and it runs directly.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueUseObjectOn(sourceObjectId, targetObjectId);
if (_useWithTargetEvent == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
return false;
try
{
// Reconcile leaked busy (same source-fix as casts / UseObject) — a
// use-on-target (e.g. PetManager essence refill) bumps m_cBusy with
// no retail completion decrement.
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
_useWithTargetEvent(sourceObjectId, targetObjectId);
BusyCountHooks.NoteDirectCastIssued(busyBefore);
LogInteraction($"UseObjectOn invoked via Event_UseWithTargetEvent source=0x{sourceObjectId:X8} target=0x{targetObjectId:X8}");
return true;
}
@ -250,6 +375,9 @@ internal static class ClientHelperHooks
public static bool UseEquippedItem(uint sourceObjectId, uint targetObjectId)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueUseEquippedItem(sourceObjectId, targetObjectId);
if (_useEquippedItem == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
return false;
@ -270,9 +398,23 @@ internal static class ClientHelperHooks
public static bool MoveItemExternal(uint objectId, uint targetContainerId, int amount)
{
// Marshal onto AC's main thread — off-thread item moves race AC's per-tick
// object/container bookkeeping (the looting null-deref AV class).
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueMoveItemExternal(objectId, targetContainerId, amount);
if (_moveItemExternal == null || !IsValidObjectId(objectId) || !IsValidContainerId(targetContainerId) || amount < 0)
return false;
// P0 (2026-06-24): if the target is one of THIS player's OWN containers and it
// is full, the native PutItemInContainer slot-table walk (FUN_00588f70) AVs
// instead of failing. Fail CLOSED here. Non-owned targets (trade/give to
// another player, NPCs, world containers) are NOT gated — they pass through.
// Runs on the main thread (marshalled above) so the ownership/capacity/count
// reads are authoritative. See AutoCram crash deep-dive.
if (IsFullOwnedContainer(targetContainerId))
return false;
try
{
// Stub ignores `this` — pass IntPtr.Zero to avoid depending on the
@ -288,14 +430,32 @@ internal static class ClientHelperHooks
public static bool MoveItemInternal(uint objectId, uint targetContainerId, int slot, int amount)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueMoveItemInternal(objectId, targetContainerId, slot, amount);
if (_moveItemInternal == null) return false;
if (!IsValidObjectId(objectId)) return false;
if (!IsValidContainerId(targetContainerId)) return false;
if (slot < 0) return false;
if (amount <= 0) return false;
// P0 (2026-06-24): fail CLOSED if the target is one of THIS player's OWN
// containers and it is full — the native slot-table walk (FUN_00588f70) AVs
// on a full owned pack rather than failing. Non-owned targets pass through.
if (IsFullOwnedContainer(targetContainerId))
return false;
try
{
// P0 (2026-06-24): defensively restore the whole-move split globals to
// their default 1/1 state before the send, so a leaked split state from a
// prior SplitStackInternal can never force the 0x55 specific-slot path
// (which honors `slot` and can target a populated slot). 1/1 == opcode 0x19
// (PutItemInContainer, first-empty-slot), which is what MoveItemInternal
// callers expect.
Marshal.WriteInt32(new IntPtr(_splitAmountAddr), 1);
Marshal.WriteInt32(new IntPtr(_totalStackAddr), 1);
// Stub ignores `this` — pass IntPtr.Zero to avoid depending on the
// uninitialized Decal plugin pointer at DAT_00871054.
//
@ -327,6 +487,9 @@ internal static class ClientHelperHooks
/// </summary>
public static bool SplitStackInternal(uint objectId, uint targetContainerId, int slot, int amount)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueSplitStackInternal(objectId, targetContainerId, slot, amount);
if (_moveItemInternal == null) return false;
if (!IsValidObjectId(objectId)) return false;
if (!IsValidContainerId(targetContainerId)) return false;
@ -338,8 +501,8 @@ internal static class ClientHelperHooks
// Force split_amount < total_stack so FUN_00588f70 takes the split
// path. The actual values aren't sent on the wire — FUN_00588f70
// only uses them to pick which sub-function to dispatch to.
Marshal.WriteInt32(new IntPtr(SplitAmountVa), amount);
Marshal.WriteInt32(new IntPtr(TotalStackVa), amount + 1);
Marshal.WriteInt32(new IntPtr(_splitAmountAddr), amount);
Marshal.WriteInt32(new IntPtr(_totalStackAddr), amount + 1);
_moveItemInternal(IntPtr.Zero, objectId, targetContainerId, slot, amount);
return true;
@ -348,6 +511,17 @@ internal static class ClientHelperHooks
{
return false;
}
finally
{
// P0 (2026-06-24): restore the split globals to their default whole-move
// state (1/1). They were previously written above and never restored,
// leaving a leaked state that could push a later plain MoveItemInternal
// onto the 0x55 specific-slot path. DORMANT today (AutoStack uses
// MergeStackInternal) but fixed defensively. Writes are individually
// try/caught so a failed restore can't escape the finally.
try { Marshal.WriteInt32(new IntPtr(_splitAmountAddr), 1); } catch { }
try { Marshal.WriteInt32(new IntPtr(_totalStackAddr), 1); } catch { }
}
}
/// <summary>
@ -365,6 +539,9 @@ internal static class ClientHelperHooks
/// </summary>
public static bool MergeStackInternal(uint sourceObjectId, uint targetObjectId)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId);
if (_eventStackableMerge == null) return false;
if (!IsValidObjectId(sourceObjectId)) return false;
if (!IsValidObjectId(targetObjectId)) return false;
@ -411,6 +588,39 @@ internal static class ClientHelperHooks
}
}
/// <summary>
/// Give an item to an NPC (or another player) via the canonical public API
/// CM_Inventory::Event_GiveObjectRequest (cdecl) at 0x006ACA60 — the F7B1 give
/// GameAction, the same path the drag-onto-NPC UI uses. This is the CORRECT
/// give-to-NPC primitive; MoveItemExternal is move-to-container and does not
/// give. amount=0 gives the whole object; positive = partial stack.
/// </summary>
public static bool GiveObjectTo(uint objectId, uint targetId, int amount = 0)
{
// Marshal onto AC's main thread — off-thread F7B1 inventory sends race AC's
// per-tick object/container bookkeeping (the looting null-deref AV class),
// exactly like MoveItemExternal / MergeStackInternal.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueGiveObjectTo(objectId, targetId, amount);
if (_eventGiveObjectRequest == null) return false;
if (!IsValidObjectId(objectId)) return false;
if (!IsValidObjectId(targetId)) return false;
if (amount < 0) return false;
try
{
byte rv = _eventGiveObjectRequest(objectId, targetId, amount);
RynthLog.Verbose($"Compat: Event_GiveObjectRequest item=0x{objectId:X8} -> target=0x{targetId:X8} amount={amount} rv={rv}");
return rv != 0;
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: Event_GiveObjectRequest threw - {ex.Message}");
return false;
}
}
public static bool TryGetCurCoords(out double northSouth, out double eastWest)
{
northSouth = 0;
@ -421,7 +631,7 @@ internal static class ClientHelperHooks
try
{
IntPtr playerSystem = ReadPointer(PlayerSystemVa);
IntPtr playerSystem = ReadPointer(_playerSystemAddr);
if (playerSystem == IntPtr.Zero)
return false;
@ -491,14 +701,106 @@ internal static class ClientHelperHooks
return containerId != 0;
}
// P0 (2026-06-24): shared owned-container full-check used by MoveItemInternal AND
// MoveItemExternal. Returns true ONLY when `target` is a container owned by the
// local player (the main pack, or a sub-pack/foci that roots at the player) AND it
// is full / its capacity-or-count can't be resolved (fail CLOSED).
//
// For ANY non-owned target — another player (trade/give), an NPC, a corpse, a
// world/landscape container, or an un-resolvable object — this returns FALSE so the
// caller passes the move through UNCHANGED. Trade/give is therefore never blocked.
// The crash this guards (native PutItemInContainer slot-table walk FUN_00588f70
// AVing on a full pack) only ever happens on the player's OWN pack.
//
// MUST be called only after the caller has marshalled onto AC's main thread (both
// MoveItemInternal/External early-return-enqueue off-thread), so the PWD ownership
// read, ITEMS_CAPACITY read, and GetNumContainedItems walk are all authoritative
// and the off-thread read-AV class does not apply.
private static bool IsFullOwnedContainer(uint target)
{
uint player = GetPlayerId();
if (player == 0)
return false; // can't resolve self -> treat as NOT owned -> pass through (never block trade)
bool isMainPack = target == player;
bool owned = isMainPack;
if (!owned)
{
// One-hop ownership: AC inventory is two levels deep — the player holds
// loose items and sub-packs directly, so an owned sub-pack/foci has
// _containerID == player (or _wielderID == player for a wielded
// container). Read straight from the target's PublicWeenieDesc on the main
// thread (page-probed + try/caught: returns false, never AVs).
if (!ClientObjectHooks.TryGetObjectOwnershipInfo(target, out uint containerID, out uint wielderID, out _))
return false; // can't resolve target ownership -> NOT provably owned -> pass through
owned = containerID == player || wielderID == player;
}
if (!owned)
return false; // non-owned target (trade/give/NPC/world) -> NEVER gate
// Owned target: compute free = capacity - count, all on the main thread.
if (!ClientObjectHooks.TryGetObjectIntProperty(target, 6 /* ITEMS_CAPACITY */, out int capacity))
capacity = 0;
if (isMainPack && capacity <= 0)
capacity = 102; // main-pack PWD capacity may not reflect the 102 item-slot
// cap; mirror the proven plugin constant so a cold/unresolved
// read does NOT fail-close every main-pack move.
if (capacity <= 0)
return true; // sub-pack capacity unresolved -> fail CLOSED (don't risk the walk)
int count = ClientObjectHooks.GetNumContainedItems(target); // AC's own walk; -1 if unavailable
if (count < 0)
return true; // count unresolved -> fail CLOSED
// GetNumContainedItems can only ever OVER-count (if it includes nested packs)
// -> free UNDER-stated -> conservative/safe. It never under-counts its own
// container, so a genuinely full owned pack can never slip through.
return (capacity - count) < 1;
}
// Rate-limit + reentry guard for WriteToChat. AC's AddTextToScroll
// (0x005649F0) consistently AVs at 0x00460D1D after sustained re-entry
// from inside its own chat-add path (observed when RynthAi's buff retry
// loop spammed the same "Casting: X" message dozens of times). Plus we
// also hook the same function in ChatCallbackHooks.IncomingChatAddTextDetour,
// which fires when AC processes our own WriteToChat output — guard
// against unbounded recursion into ourselves.
private const int WriteToChatMinIntervalMs = 100;
[System.Runtime.CompilerServices.ModuleInitializer]
internal static void EnsureChatRateLimiterReady() { /* triggers static init */ }
private static long _lastWriteToChatTick;
[ThreadStatic] private static int _writeToChatDepth;
public static bool WriteToChat(string? text, int chatType)
{
if (_addTextToScroll == null || string.IsNullOrWhiteSpace(text))
return false;
// Off AC's main thread: rate-limit the spam, then marshal. Running
// AddTextToScroll off-thread races AC's chat-scroll buffer and corrupts it ->
// the recurring 0x00460D1D write-AV (killed a 5h+ session 2026-06-05). The
// rate-limit lives HERE (not on the drain path) so bot retry bursts are
// dropped before they queue, and drained messages are never re-dropped.
if (!MainThreadGuard.IsOnMainThread())
{
long now = Environment.TickCount64;
long last = System.Threading.Interlocked.Read(ref _lastWriteToChatTick);
if (last != 0 && now - last < WriteToChatMinIntervalMs)
return false;
System.Threading.Interlocked.Exchange(ref _lastWriteToChatTick, now);
return AcMainThreadQueue.EnqueueWriteToChat(text!, chatType);
}
// On AC's main thread (drain, or a legit main-thread caller): execute directly.
// Re-entry guard: AC's AddTextToScroll calls back into our hook chain, which
// may re-enter WriteToChat. One level is fine; deeper risks the crash pattern.
if (_writeToChatDepth > 0)
return false;
try
{
IntPtr communicationSystem = ReadPointer(CommunicationSystemVa);
IntPtr communicationSystem = ReadPointer(_commSystemAddr);
if (communicationSystem == IntPtr.Zero)
return false;
@ -506,11 +808,21 @@ internal static class ClientHelperHooks
if (line.Length == 0)
return false;
// Strip any control chars that might confuse AC's chat tokenizer.
// The previous WriteToChat crashes correlated with bursts of
// bot retries that may have left malformed text in flight.
foreach (char c in line)
{
if (c < 0x20 && c != '\t')
return false; // bail rather than feed AC bad input.
}
ushort[] chars = new ushort[line.Length + 1]; // +1 for null terminator (wcslen requirement)
for (int i = 0; i < line.Length; i++)
chars[i] = line[i];
var wide = WidePString.Create(chars);
_writeToChatDepth++;
try
{
return _addTextToScroll(
@ -522,6 +834,7 @@ internal static class ClientHelperHooks
}
finally
{
_writeToChatDepth--;
wide.Dispose();
}
}
@ -623,6 +936,7 @@ internal static class ClientHelperHooks
return false;
RynthLog.Verbose($"Compat: InvokeParser text='{line}'");
LogoffOriginProbe.RecordChat("InvokeChatParser", line);
return ChatCommandDispatcher.Dispatch(line);
}
catch (Exception ex)
@ -642,6 +956,7 @@ internal static class ClientHelperHooks
_moveItemExternal = null;
_moveItemInternal = null;
_eventStackableMerge = null;
_eventGiveObjectRequest = null;
_inqPlayerCoords = null;
_getPlayerId = null;
_addTextToScroll = null;
@ -686,12 +1001,26 @@ internal static class ClientHelperHooks
return Marshal.ReadIntPtr(new IntPtr(address));
}
// WidePString (AC1Legacy::PStringBase<ushort>) helper fns — pattern-resolved (1a, 2026-06-05).
private static readonly byte?[] PatWidePStringCtor = [ 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x0C, 0x85, 0xFF, 0x8B, 0xF1, 0x74, 0x2C ];
private static readonly byte?[] PatWidePStringDtor = [ 0x56, 0x8B, 0x31, 0x83, 0xEE, 0x14, 0x8D, 0x46 ];
// Resolve a fn-ptr for static-init field use; returns the fallback VA (never null) on a
// total miss so the WidePString call sites keep their non-null assumption (old behavior).
private static unsafe void* ResolveFnPtr(string name, byte?[] pattern, int fallbackVa)
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
return (void*)fallbackVa;
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
return (void*)(r.Success ? r.Address : new IntPtr(fallbackVa));
}
[StructLayout(LayoutKind.Sequential)]
private unsafe struct WidePString
{
private static readonly IntPtr NullWideBufferVa = new(0x00818340);
private static readonly delegate* unmanaged[Thiscall]<WidePString*, ushort*, void> Ctor = (delegate* unmanaged[Thiscall]<WidePString*, ushort*, void>)0x00402730;
private static readonly delegate* unmanaged[Thiscall]<WidePString*, void> Dtor = (delegate* unmanaged[Thiscall]<WidePString*, void>)0x004011B0;
private static readonly IntPtr NullWideBufferVa = ResolveDataVa("ClientHelper.PStringWide_NullBuffer", PatXrefWideNullBuffer, 2, 0x00818340);
private static readonly delegate* unmanaged[Thiscall]<WidePString*, ushort*, void> Ctor = (delegate* unmanaged[Thiscall]<WidePString*, ushort*, void>)ResolveFnPtr("ClientHelper.PStringBaseW_ctor", PatWidePStringCtor, 0x00402730);
private static readonly delegate* unmanaged[Thiscall]<WidePString*, void> Dtor = (delegate* unmanaged[Thiscall]<WidePString*, void>)ResolveFnPtr("ClientHelper.PStringBaseW_dtor", PatWidePStringDtor, 0x004011B0);
public IntPtr CharBuffer;

File diff suppressed because it is too large Load diff

View file

@ -11,6 +11,17 @@ internal static class CombatActionHooks
{
private const int QueryHealthResponseVa = 0x006AA900;
// ── Pattern-resolved binding (1a hardening, 2026-06-06) ─────────────
// The cast/tick VAs were previously bound by raw VA + in-module/warn-only-prologue checks.
// These signatures (verified unique + landing exactly at the VA offline via
// tools/pe_pattern.py) are now the source of truth; the VA stays as logged fallback.
// GetMagicSystem/FreeHandsAndCastSpell are invoked via the SEH trampoline on AC's main
// thread — resolving by pattern changes only how the address is found, not the call path.
private static readonly byte?[] QueryHealthResponsePattern = [ 0x8B, 0x44, 0x24, 0x04, 0x85, 0xC0, 0x74, 0x18, 0x8B, 0x48, 0x50 ];
private static readonly byte?[] CastSpellClientPattern = [ 0x81, 0xEC, 0x48, 0x01, 0x00, 0x00, 0x53, 0x56 ];
private static readonly byte?[] GetMagicSystemPattern = [ 0xA1, 0x4C, 0x14, 0x87, 0x00, 0xC3, 0x90, 0x90 ];
private static readonly byte?[] FreeHandsAndCastSpellPattern = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x8B, 0x88, 0xB8, 0x00, 0x00, 0x00, 0x8B, 0x11, 0xFF, 0x92, 0xC0, 0x00, 0x00, 0x00, 0x8B, 0x44 ];
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool TargetedMeleeAttackDelegate(uint targetId, int attackHeight, float powerLevel);
@ -61,6 +72,18 @@ internal static class CombatActionHooks
private static RequestIdDelegate? _requestId;
private static CastSpellDelegate? _castSpell;
private static CastSpellClientDelegate? _castSpellClient;
private static IntPtr _castSpellClientPtr;
// RC2-proven explicit-target cast (no SelectItem / global selection). VAs verified
// against acclient.map. GetMagicSystem returns the ClientMagicSystem singleton ('this');
// FreeHandsAndCastSpell(this, spellId, targetId) takes the target as an EXPLICIT arg, so
// it never reads AC's selected-object global ([singleton+0xF4]) the way CastSpell(...,1)
// @ 0x00568DE0 does — which is why it survives being marshalled onto AC's game tick.
private const int GetMagicSystemVa = 0x00567C00; // void* __cdecl GetMagicSystem()
private const int FreeHandsAndCastSpellVa = 0x00567C90; // void __thiscall FreeHandsAndCastSpell(this, uint spellId, uint targetId)
private static IntPtr _getMagicSystemPtr;
private static IntPtr _freeHandsCastPtr;
private static int _sehAvLogCount;
private static QueryHealthResponseDelegate? _queryHealthResponseDetour;
private static QueryHealthResponseDelegate? _originalQueryHealthResponse;
private static QueryHealthResponseDelegate? _identifyObjectDetour;
@ -206,7 +229,7 @@ internal static class CombatActionHooks
{
int requestIdVa = textSection.TextBaseVa + requestIdFuncOff;
_requestId = Marshal.GetDelegateForFunctionPointer<RequestIdDelegate>(new IntPtr(requestIdVa));
RynthLog.Verbose($"Compat: RequestId (IdentifyObject 0xC8) found at 0x{requestIdVa:X8}");
RynthLog.Compat($"Compat: RequestId (IdentifyObject 0xC8) found at 0x{requestIdVa:X8}");
}
else
{
@ -217,34 +240,84 @@ internal static class CombatActionHooks
{
int castSpellVa = textSection.TextBaseVa + castSpellFuncOff;
_castSpell = Marshal.GetDelegateForFunctionPointer<CastSpellDelegate>(new IntPtr(castSpellVa));
RynthLog.Verbose($"Compat: CastSpell (0x4A) found at 0x{castSpellVa:X8}");
RynthLog.Compat($"Compat: CastSpell (0x4A) found at 0x{castSpellVa:X8}");
}
else
{
RynthLog.Compat("Compat: CastSpell (0x4A) not found — magic combat unavailable.");
}
// ClientMagicSystem::CastSpell — direct VA from Chorizite.
// Static Cdecl: void CastSpell(uint spellId, byte targetIsSelected)
// ClientMagicSystem::CastSpell — static Cdecl:
// void CastSpell(uint spellId, byte targetIsSelected)
// Uses the currently selected target (from SelectItem).
if (SmartBoxLocator.IsPointerInModule(new IntPtr(ClientMagicSystemCastSpellVa)))
//
// The in-module check uses `textSection` (already read above), NOT
// SmartBoxLocator.IsPointerInModule. SmartBoxLocator's bounds are
// populated only by its own Probe(), which runs lazily at the first
// TryGetSmartBox (around login) — long AFTER this early init step
// (ClientActionHooks.Initialize). IsPointerInModule therefore always
// saw _moduleBase==0 here and fail-closed for EVERY pointer, so this
// correct VA was rejected on essentially every launch and casting
// was forced onto the mis-bound _castSpell pattern fallback — the
// root cause of the AC-side near-null write AV (0x00568DE0 logged
// "outside module"; AC crashed at 0x00416C86 [null+0x28] /
// 0x0055FA24 [null+0x40]). acclient.exe is byte-identical to retail
// (only PE-header metadata differs) so this retail VA is valid here;
// it is validated live below per the no-blind-decompile-RVA rule.
HookResolver.ResolveResult csRes = HookResolver.Resolve(textSection, "CombatAction.CastSpellClient", CastSpellClientPattern, ClientMagicSystemCastSpellVa);
if (csRes.Success)
{
_castSpellClient = Marshal.GetDelegateForFunctionPointer<CastSpellClientDelegate>(
new IntPtr(ClientMagicSystemCastSpellVa));
RynthLog.Verbose($"Compat: ClientMagicSystem::CastSpell bound at 0x{ClientMagicSystemCastSpellVa:X8}");
_castSpellClient = Marshal.GetDelegateForFunctionPointer<CastSpellClientDelegate>(csRes.Address);
_castSpellClientPtr = csRes.Address;
RynthLog.Compat($"Compat: ClientMagicSystem::CastSpell bound at 0x{csRes.Address.ToInt32():X8} ({csRes.Detail})");
}
else
{
RynthLog.Compat("Compat: ClientMagicSystem::CastSpell VA outside module — unavailable.");
RynthLog.Compat($"Compat: ClientMagicSystem::CastSpell VA 0x{ClientMagicSystemCastSpellVa:X8} unresolved — unavailable.");
}
// Explicit-target cast pair (RC2-proven): GetMagicSystem + FreeHandsAndCastSpell,
// invoked via the SEH trampoline on AC's main thread. Replaces the SelectItem +
// CastSpell(targetIsSelected=1) two-step for TARGETED casts (the global-selection
// read that didn't survive being marshalled onto the tick).
HookResolver.ResolveResult gmsRes = HookResolver.Resolve(textSection, "CombatAction.GetMagicSystem", GetMagicSystemPattern, GetMagicSystemVa);
HookResolver.ResolveResult fhcRes = HookResolver.Resolve(textSection, "CombatAction.FreeHandsAndCastSpell", FreeHandsAndCastSpellPattern, FreeHandsAndCastSpellVa);
if (gmsRes.Success && fhcRes.Success)
{
_getMagicSystemPtr = gmsRes.Address;
_freeHandsCastPtr = fhcRes.Address;
RynthLog.Compat(
$"Compat: explicit-target cast bound — GetMagicSystem=0x{gmsRes.Address.ToInt32():X8} ({gmsRes.Detail}), " +
$"FreeHandsAndCastSpell=0x{fhcRes.Address.ToInt32():X8} ({fhcRes.Detail}).");
}
else
{
RynthLog.Compat(
$"Compat: explicit-target cast VAs unresolved (gms={gmsRes.Success}, fhc={fhcRes.Success}) — " +
"targeted casts fail closed.");
}
InstallQueryHealthResponseHook();
InstallInnerDispatcherHook();
// InstallInnerDispatcherHook intentionally disabled 2026-05-14.
// Its anchor-then-scan-backward heuristic (find CALL to
// QueryHealthResponseVa, then walk back ≤0x1000 bytes looking for
// `SUB ESP, 0x1C0`) lands on a function that — on this ACE
// build at least — AC traverses during world-entry, and the
// MinHook trampoline at that entry point hangs the load (player
// stuck on "Entering World", no SendLoginCompleteNotification).
// The 0xF658 character-list and 0xC9 IdentifyObject packets we
// were collecting here are redundantly captured by SmartBoxHooks'
// DispatchSmartBoxEvent / DispatchGameEvent hooks (see
// SmartBoxHooks.DispatchSmartBoxEventDetour → ProcessPotentialCharacterMessage
// at line ~117). Re-enabling requires a tighter pattern that
// *uniquely* identifies the intended inner dispatcher, plus a
// verification that AC's world-load path is unaffected.
// InstallInnerDispatcherHook();
IsInitialized = true;
_statusMessage = "Ready.";
RynthLog.Verbose($"Compat: combat hooks ready - cancel=0x{cancelVa:X8}, mode=0x{changeModeVa:X8}, health=0x{queryHealthVa:X8}, melee=0x{meleeVa:X8}, missile=0x{missileVa:X8}");
RynthLog.Compat($"Compat: combat hooks ready - cancel=0x{cancelVa:X8}, mode=0x{changeModeVa:X8}, health=0x{queryHealthVa:X8}, melee=0x{meleeVa:X8}, missile=0x{missileVa:X8}");
return true;
}
catch (Exception ex)
@ -258,6 +331,9 @@ internal static class CombatActionHooks
public static bool MeleeAttack(uint targetId, int attackHeight, float powerLevel)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueMeleeAttack(targetId, attackHeight, powerLevel);
if (_meleeAttack == null)
return false;
@ -273,6 +349,9 @@ internal static class CombatActionHooks
public static bool MissileAttack(uint targetId, int attackHeight, float accuracyLevel)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueMissileAttack(targetId, attackHeight, accuracyLevel);
if (_missileAttack == null)
return false;
@ -288,6 +367,28 @@ internal static class CombatActionHooks
public static bool ChangeCombatMode(int combatMode)
{
// P1 marshalling: off-thread mutators run on AC's main thread (via the
// OnEndScene drain) so AC mutates its single-threaded object/animation
// (CSequence) state on the thread that updates it — eliminating the
// off-thread-mutation corruption class (e.g. the CSequence::update_internal
// AV). On the main thread (incl. the drain) this executes directly.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueChangeCombatMode(combatMode);
// Prefer the CLIENT-level entry point. _changeCombatMode is bound by
// scanning for the function that writes network opcode 0x53
// (CM_Combat::Event_ChangeCombatMode) — that is the packet sender and
// nothing more. It tells the server and leaves the client's own UI
// untouched, so the stance widgets never learn and the toolbar icon sits
// on Peace while the character is in Magic and casting.
//
// ClientCombatSystem::SetCombatMode is the layer above: it sets the mode
// field, sends the same 0x53, AND notifies the UI. Calling it is what a
// toolbar click does. Falls through to the raw sender when the hook isn't
// installed, so behaviour is unchanged if the pattern ever fails to resolve.
if (CombatModeHooks.RequestCombatMode(combatMode))
return true;
if (_changeCombatMode == null)
return false;
@ -349,36 +450,146 @@ internal static class CombatActionHooks
public static bool CastSpell(uint targetId, int spellId)
{
if (spellId <= 0) return false;
if (_castSpellClient == null) return false;
// Prefer ClientMagicSystem::CastSpell — initiates the full client-side
// cast sequence (animation, state, network). The target must already be
// selected via SelectItem before calling this.
// P2 cast marshalling — drain-BEFORE-tick variant (2026-06-03, attempt 2).
// Off the main thread, enqueue the cast; GameTickHooks drains it on AC's
// game-logic tick (Client::UseTime) BEFORE _originalUseTime runs, so AC's SAME
// tick processes the freshly-set selection + cast (mimics AC's natural
// input -> UseTime flow). Attempt 1 (drain AFTER the tick) landed self-buffs but
// NOT targeted casts: SelectItem + cast initiated at the END of tick N weren't
// processed until tick N+1, by which point the selection was clobbered (target
// held hp=50/50, zero damage).
//
// Off-thread casting is NOT a safe fallback: it races AC's cast/UI state and
// AVs UNCAUGHT (0xC0000005 WRITE in UIElement::GetAttribute_Bool, off the main
// thread, tid != main) — it killed a 37-min P1 soak. So the cast MUST run on the
// main thread; the only open question is landing a targeted cast from the tick,
// which the drain-before order is intended to fix. On the main thread (the
// UseTime drain, or any main-thread caller) this falls through to the direct
// cast below.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueCast(targetId, (uint)spellId);
// Call ClientMagicSystem::CastSpell directly off the plugin pump thread.
// This is the proven-working casting path (buffs + combat resolve in
// chat). The earlier EndScene-marshalled variant (AcMainThreadQueue,
// drained from OnEndScene) was REVERTED 2026-05-19: EndScene fires AC's
// IncrementBusyCount but is not the context that drives the cast state
// machine to completion, so combat casts never produced a projectile /
// damage / "You cast" chat — busy leaked, AC's single cast slot jammed
// "Casting <spell>" client-wide, and even manual casting died. Do NOT
// re-introduce queue/EndScene marshalling for casts.
// The documented object-teardown AV (0x0055FA24 [null+0x40] /
// 0x00416C86 [null+0x28]) is contained per-callsite by the SEH
// trampoline below (__try/__except in RynthCore.SehTrampoline.dll),
// which is the correct fix for that AV. AC's CastSpell reads its
// "currently selected target" when targetIsSelected=1; SelectItem
// first so AC's selection matches the caller's intent.
if (_castSpellClient != null)
{
try
{
byte targetIsSelected = targetId != 0 ? (byte)1 : (byte)0;
_castSpellClient((uint)spellId, targetIsSelected);
// TARGETED cast (targetId != 0): explicit-target path — RC2-proven, NO
// SelectItem. GetMagicSystem() -> FreeHandsAndCastSpell(mgr, spellId, targetId).
// The old SelectItem + CastSpell(targetIsSelected=1) two-step relied on AC's
// global selection ([magicSysSingleton+0xF4], read inside 0x00568DE0) surviving
// the marshal onto AC's tick — it didn't (targets held hp=50/50, zero damage).
// FreeHandsAndCastSpell takes the target as an explicit arg and auto-readies the
// wand, so there is nothing to clobber.
if (targetId != 0)
{
if (SehTrampoline.IsAvailable && _freeHandsCastPtr != IntPtr.Zero && _getMagicSystemPtr != IntPtr.Zero)
{
IntPtr mgr = SehTrampoline.CdeclPtrVoid(_getMagicSystemPtr, out bool avMgr);
if (avMgr || mgr == IntPtr.Zero)
{
if (System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
RynthLog.Compat($"[SEH] GetMagicSystem null/AV — targeted cast skipped spell={spellId} target=0x{targetId:X8}");
return false;
}
// Measure the real m_cBusy delta around the call: the direct cast
// increments it (wand-ready + cast, often +2) but never registers
// the queued action whose completion would decrement — the per-cast
// busy leak. BusyCountHooks reconciles the delta once the cast
// gesture completes.
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
bool okCast = SehTrampoline.FreeHandsCast(_freeHandsCastPtr, mgr, (uint)spellId, targetId);
BusyCountHooks.NoteDirectCastIssued(busyBefore);
if (!okCast && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
RynthLog.Compat($"[SEH] AV in FreeHandsAndCastSpell spell={spellId} target=0x{targetId:X8} — caught");
return okCast;
}
return false; // trampoline / VAs unavailable — fail closed (never the off-thread SelectItem two-step)
}
// SELF cast (targetId == 0): the proven CastSpell(spellId, targetIsSelected=0)
// path — no selection dependency; lands buffs reliably.
if (SehTrampoline.IsAvailable && _castSpellClientPtr != IntPtr.Zero)
{
// Same per-cast busy-leak reconciliation as the targeted path —
// buff self-casts were the dominant leak source (4322 plugin
// clears / 10h soak, nearly all on buffs).
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
bool ok = SehTrampoline.CdeclVoidUintByte(_castSpellClientPtr, (uint)spellId, 0);
BusyCountHooks.NoteDirectCastIssued(busyBefore);
if (!ok && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
RynthLog.Compat($"[SEH] AV in self-CastSpell spell={spellId} — caught");
return ok;
}
{
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
_castSpellClient((uint)spellId, 0);
BusyCountHooks.NoteDirectCastIssued(busyBefore);
}
return true;
}
catch
{
// Fall through to game action method
// Fall through to "refuse" rather than the pattern-scanned
// _castSpell — see the comment block on that fallback.
}
}
// Fallback: direct game action 0x4A (network message only)
if (_castSpell == null || targetId == 0)
return false;
// No safe fallback — fail closed. The pattern-scanned game-action-0x4A
// wrapper (_castSpell) resolves to the WRONG function on this
// acclient.exe: CombatPrologue (83 EC 0C 53 56 57 E8) is shared by many
// AC functions and FindPrologueBefore takes the FIRST match, which is
// not the cast wrapper, so calling it would crash AC. The 2026-05-14
// "binaries are byte-identical so the pattern is fine" reasoning was
// wrong: identity makes the pattern consistently wrong on BOTH retail
// and ACE, not correct.
// ⚠ 2026-05-18, DUMP-VERIFIED: the AVs at 0x00416C86 [null+0x28] and
// 0x0055FA24 [null+0x40] that older notes/comments blamed on this
// fallback are NOT cast-related. Resolved via acclient.map they are
// DBOCache::DestroyObj and CPlayerSystem::CalculateObjectRangeChecks →
// List<ObjectRangeInfo>::remove — AC OBJECT-TEARDOWN code tripping over
// a corrupted object/range list (async lifecycle corruption class, not
// spellcasting). Do NOT chase CastSpell for these. See
// rynthcore_castspell_fallback_pitfall.md / rynthcore_crash_investigation.md.
// _castSpellClient (the verified ClientMagicSystem::CastSpell VA bound
// in Probe) is the only safe path; if it is unavailable we refuse the
// cast. BuffManager.CastSpellInner and CombatManager both handle a
// false / no-op return without wedging (skip the spell, retry next
// cycle), so refusing is strictly safer than crashing the client.
return false;
}
try
// Called by AcMainThreadQueue.Drain on AC's main thread (EndScene path).
// The preceding queued SelectItem entry already set AC's selection, so
// cast with targetIsSelected=1. Defensive: never throw into the drain loop.
internal static void ExecuteQueuedCast(uint spellId)
{
if (_castSpellClient == null) return;
if (SehTrampoline.IsAvailable && _castSpellClientPtr != IntPtr.Zero)
{
return _castSpell(targetId, spellId);
}
catch
{
return false;
bool ok = SehTrampoline.CdeclVoidUintByte(_castSpellClientPtr, spellId, 1);
if (!ok && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
RynthLog.Compat($"[SEH] AV in CastSpell spell={spellId} — caught, cast skipped");
return;
}
try { _castSpellClient.Invoke(spellId, 1); } catch { }
}
public static int MapAttackHeight(int uiHeight)
@ -401,6 +612,9 @@ internal static class CombatActionHooks
_requestId = null;
_castSpell = null;
_castSpellClient = null;
_castSpellClientPtr = IntPtr.Zero;
_getMagicSystemPtr = IntPtr.Zero;
_freeHandsCastPtr = IntPtr.Zero;
_queryHealthResponseDetour = null;
_originalQueryHealthResponse = null;
_identifyObjectDetour = null;
@ -505,21 +719,37 @@ internal static class CombatActionHooks
return pOriginal(thisPtr, buffer, size);
}
private static int _identifyWireLogCount;
private static int _mobHpReadLogCount;
/// <summary>
/// Parses the IdentifyObject response (game event 0xC9) to extract health/maxHealth
/// from the CreatureProfile section.
/// Layout: [eventType(4)][objectId(4)][flags(4)][success(4)][sections based on flags...]
/// Wire serialization order (matches ACE, NOT flag-bit order):
/// 0x0001 IntStatsTable, 0x1000 Int64StatsTable, 0x0002 BoolStatsTable,
/// 0x0004 FloatStatsTable, 0x0008 StringStatsTable, 0x0010 SpellBook,
/// 0x0020 ArmorProfile, 0x0040 CreatureProfile, 0x0080 WeaponProfile,
/// 0x0100 HookProfile, ...
/// Parses the IdentifyObject response (game event 0xC9) to extract
/// health/maxHealth from the CreatureProfile section. Wire format is
/// authoritative per ACE AppraiseInfoExtensions.Write / CreatureProfile:
///
/// header: [_(4)][objectId(4)][Flags(4)][Success(4)] (parser base+0..+15)
/// then sections, in ACE *write* order (NOT flag-bit order):
/// 0x0001 IntStatsTable hashtbl, entry 8 (u32 key + i32)
/// 0x2000 Int64StatsTable hashtbl, entry 12 (u32 key + i64)
/// 0x0002 BoolStatsTable hashtbl, entry 8 (u32 key + u32)
/// 0x0004 FloatStatsTable hashtbl, entry 12 (u32 key + f64)
/// 0x0008 StringStatsTable hashtbl, string entries (u32 key + str16L)
/// 0x1000 DidStatsTable hashtbl, entry 8 (u32 key + u32)
/// 0x0010 SpellBook list: i32 count + count*u32
/// 0x0080 ArmorProfile fixed 32 bytes (8 floats)
/// 0x0100 CreatureProfile &lt;-- target
/// hashtbl header = ushort count + ushort numBuckets (4 bytes).
///
/// CreatureProfile: cpFlags(4), Health(4), HealthMax(4),
/// if cpFlags&amp;0x8: Str,End,Quick,Coord,Focus,Self,
/// Stamina,Mana,StaminaMax,ManaMax (10*4),
/// if cpFlags&amp;0x1: AttrHighlights(2)+AttrColors(2).
/// </summary>
private static void TryParseIdentifyResponse(IntPtr buffer, uint size)
internal static void TryParseIdentifyResponse(IntPtr buffer, uint size)
{
try
{
// Header: eventType(4) + objectId(4) + flags(4) + success(4) = 16 bytes
// Header: _(4) + objectId(4) + flags(4) + success(4) = 16 bytes
uint objectId = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, 4)));
uint flags = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, 8)));
uint success = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, 12)));
@ -527,71 +757,66 @@ internal static class CombatActionHooks
if (success == 0 || objectId == 0)
return;
// CreatureProfile = flag 0x1000 in the retail client
if ((flags & 0x1000) == 0)
const uint CreatureProfile = 0x0100;
if ((flags & CreatureProfile) == 0)
return;
int offset = 16; // Past the header
int iSize = (int)size;
// Skip sections in wire order before CreatureProfile (0x1000):
// 0x0001 - IntStatsTable: PHashTable<uint,int> = header(4) + count*8
// Skip sections written before CreatureProfile, in ACE write order.
if ((flags & 0x0001) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))
return;
// 0x0002 - BoolStatsTable: PHashTable<uint,int> = header(4) + count*8
return; // IntStatsTable
if ((flags & 0x2000) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 12))
return; // Int64StatsTable
if ((flags & 0x0002) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))
return;
// 0x0004 - FloatStatsTable: PHashTable<uint,double> = header(4) + count*12
return; // BoolStatsTable
if ((flags & 0x0004) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 12))
return;
// 0x0008 - StringStatsTable: PHashTable<uint,string> — variable
return; // FloatStatsTable
if ((flags & 0x0008) != 0 && !SkipStringHashTable(buffer, iSize, ref offset))
return;
// 0x0010 - SpellBook: header(4) + count*4
if ((flags & 0x0010) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 4))
return;
// 0x0020, 0x0040, 0x0080 — unknown fixed sections; bail if present
if ((flags & 0x00E0) != 0)
return;
// 0x0100 - Int64StatsTable: PHashTable<uint,int32> = header(4) + count*8
// (retail client serialises "Int64" properties as 32-bit values)
if ((flags & 0x0100) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))
return;
// 0x0200, 0x0400, 0x0800 — unknown sections; bail if present
if ((flags & 0x0E00) != 0)
return; // StringStatsTable
if ((flags & 0x1000) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))
return; // DidStatsTable
if ((flags & 0x0010) != 0 && !SkipPackableListUInt(buffer, iSize, ref offset))
return; // SpellBook
if ((flags & 0x0080) != 0)
{
offset += 32; // ArmorProfile = 8 floats, fixed
if (offset > iSize)
return;
}
// CreatureProfile: cpFlags(4), Health(4), HealthMax(4), ...
if (offset + 12 > iSize)
return;
// 0x1000 - CreatureProfile layout:
// flags(4), health(4), maxHealth(4),
// strength(4), endurance(4), quickness(4), coordination(4), focus(4), self(4),
// stamina(4), maxStamina(4), mana(4), maxMana(4)
// Total: 4 + 12*4 = 52 bytes
if (offset + 52 > iSize)
return;
uint cpFlags = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset)));
uint health = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 4)));
uint maxHealth = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 8)));
// Skip the 4-byte CreatureProfile header/flags
offset += 4;
uint health = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset)));
uint maxHealth = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 4)));
// Skip 6 primary attributes (str, end, quick, coord, focus, self) = 24 bytes
// Layout: stamina(4), mana(4), maxStamina(4), maxMana(4)
uint stamina = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 32)));
uint mana = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 36)));
uint maxStamina = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 40)));
uint maxMana = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 44)));
uint stamina = 0, maxStamina = 0, mana = 0, maxMana = 0;
if ((cpFlags & 0x8) != 0 && offset + 52 <= iSize)
{
// Str(+12) End(+16) Quick(+20) Coord(+24) Focus(+28) Self(+32)
// Stamina(+36) Mana(+40) StaminaMax(+44) ManaMax(+48)
stamina = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 36)));
mana = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 40)));
maxStamina = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 44)));
maxMana = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 48)));
}
if (maxHealth > 0 && maxHealth < 1_000_000 && objectId != 0)
int log = Interlocked.Increment(ref _identifyWireLogCount);
if (log <= 20)
RynthLog.Compat($"Compat: identify-wire obj=0x{objectId:X8} flags=0x{flags:X4} cp=0x{cpFlags:X} hp={health}/{maxHealth}");
if (maxHealth > 0 && maxHealth < 1_000_000)
{
var vitals = new CreatureVitals(health, maxHealth, stamina, maxStamina, mana, maxMana);
ObjectQualityCache.SetCreatureVitals(objectId, vitals);
if (ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out IntPtr pWeenie) && pWeenie != IntPtr.Zero)
ObjectQualityCache.SetMaxHealth(pWeenie, maxHealth);
float ratio = maxHealth > 0 ? (float)health / maxHealth : 0f;
float ratio = (float)health / maxHealth;
PluginManager.QueueUpdateHealth(objectId, ratio, health, maxHealth);
// If this is the player, seed exact max vitals
uint playerId = ClientHelperHooks.GetPlayerId();
if (playerId != 0 && objectId == playerId)
PlayerVitalsHooks.SeedMaxVitalsFromIdentify(maxHealth, maxStamina, maxMana);
@ -635,6 +860,17 @@ internal static class CombatActionHooks
return offset <= size;
}
/// <summary>Skips a PackableList&lt;uint&gt;: int32 count + count*uint32.</summary>
private static bool SkipPackableListUInt(IntPtr buffer, int size, ref int offset)
{
if (offset + 4 > size) return false;
int count = Marshal.ReadInt32(IntPtr.Add(buffer, offset));
offset += 4;
if (count < 0 || count > 100_000) return false;
offset += count * 4;
return offset <= size;
}
private static void InstallQueryHealthResponseHook()
{
if (_originalQueryHealthResponse != null)
@ -643,15 +879,13 @@ internal static class CombatActionHooks
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
return;
IntPtr responsePtr = new(QueryHealthResponseVa);
int textStart = textSection.TextBaseVa;
int textEnd = textStart + textSection.Bytes.Length;
int responseVa = responsePtr.ToInt32();
if (responseVa < textStart || responseVa >= textEnd)
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "CombatAction.QueryHealthResponse", QueryHealthResponsePattern, QueryHealthResponseVa);
if (!resolved.Success)
{
RynthLog.Compat($"Compat: query-health-response hook skipped - invalid address 0x{QueryHealthResponseVa:X8}");
RynthLog.Compat($"Compat: query-health-response hook skipped - unresolved 0x{QueryHealthResponseVa:X8}");
return;
}
IntPtr responsePtr = resolved.Address;
_queryHealthResponseDetour = QueryHealthResponseDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_queryHealthResponseDetour);
@ -678,25 +912,44 @@ internal static class CombatActionHooks
// thread so the direct read is safe.
uint maxHealth = 0;
uint currentHealth = 0;
if (ClientObjectHooks.TryGetWeenieObjectPtr(targetId, out IntPtr pWeenie))
{
if (ObjectQualityCache.TryGetMaxHealth(pWeenie, out uint cached))
{
maxHealth = cached;
}
else if (PlayerVitalsHooks.TryReadObjectMaxHealth(pWeenie, out uint queried) && queried > 0)
{
maxHealth = queried;
ObjectQualityCache.SetMaxHealth(pWeenie, queried);
}
uint playerId = ClientHelperHooks.GetPlayerId();
if (maxHealth > 0)
// Appraisal-only (see SmartBoxHooks.TryQueueHealthUpdate):
// emit absolute ONLY from a real appraisal's wire-parsed
// CreatureProfile; otherwise max=0 → UI shows %. ACE creature
// Inq / pointer-cache maxes are unreliable.
if (ObjectQualityCache.TryGetCreatureVitals(targetId, out CreatureVitals exact) && exact.MaxHealth > 0)
{
maxHealth = exact.MaxHealth;
currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(healthRatio, 0f, 1f));
}
else if (targetId != 0 && targetId != playerId)
{
// No appraisal yet: read the mob's real MaxHealth straight from its
// CACQualities (InqAttribute2nd on the qualities sub-object, SEH-
// guarded). This is what fills in true HP (e.g. Olthoi Swarm
// Harvester = 175) BEFORE the player's appraise skill is high enough
// to produce a CreatureProfile. The earlier bug passed the weenie
// ptr as `this`; InqAttribute2nd derefs this+0x60 for the attribute
// cache, so it MUST get the CACQualities sub-object (resolved inside
// TryReadCreatureMaxHealth). Gated to the main thread inside
// TryGetQualitiesPtr — this detour runs on AC's game thread.
if (ClientObjectHooks.TryReadCreatureMaxHealth(targetId, out uint mobMax)
&& mobMax > 0 && mobMax < 1_000_000)
{
maxHealth = mobMax;
currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(healthRatio, 0f, 1f));
ObjectQualityCache.SetCreatureVitals(targetId,
new CreatureVitals(currentHealth, maxHealth, 0, 0, 0, 0));
int hlog = Interlocked.Increment(ref _mobHpReadLogCount);
if (hlog <= 20)
RynthLog.Compat($"Compat: mob-hp qualities-read id=0x{targetId:X8} maxHp={maxHealth} ratio={healthRatio:F3}");
}
}
// If this response is for the player, derive true MaxHealth from the ratio.
// e.g. health=92541, ratio=0.925 → trueMax ≈ 99999
uint playerId = ClientHelperHooks.GetPlayerId();
if (playerId != 0 && targetId == playerId && healthRatio > 0f && healthRatio <= 1f)
PlayerVitalsHooks.UpdateMaxFromHealthRatio(healthRatio);

View file

@ -8,7 +8,18 @@ namespace RynthCore.Engine.Compatibility;
internal static class CombatModeHooks
{
private const int SetCombatModeVa = 0x0056CB80;
private const int SetCombatModeFallbackVa = 0x0056CB80;
// ClientCombatSystem::SetCombatMode(int newMode, int playerRequested)
// Loads current mode from [esi+0x1C], compares with new arg from [esp+0x14],
// jumps if equal. Distinctive 0x0F 0x84 EA 01 00 00 (je rel32 +0x1EA).
private static readonly byte?[] SetCombatModePattern =
[
0x51, 0x53, 0x56, 0x8B, 0xF1, 0x8B, 0x46, 0x1C,
0x57, 0x8B, 0x7C, 0x24, 0x14, 0x3B, 0xF8, 0x8B,
0xD8, 0x0F, 0x84, 0xEA, 0x01, 0x00, 0x00, 0x8A,
0x44, 0x24, 0x18, 0x84, 0xC0
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void SetCombatModeDelegate(IntPtr thisPtr, int newCombatMode, int playerRequested);
@ -17,38 +28,185 @@ internal static class CombatModeHooks
private static SetCombatModeDelegate? _setCombatModeDetour;
private static IntPtr _targetAddress;
private static string _statusMessage = "Not probed yet.";
private static int _lastObservedCombatMode;
// Defaults to NonCombat (not 0) so an off-thread reader that arrives before
// the first SetCombatMode detour fire still gets a sane value instead of an
// unnormalized 0.
private static int _lastObservedCombatMode = CombatActionHooks.CombatModeNonCombat;
// ClientCombatSystem::s_pCombatSystem — pointer to the singleton in .data
// ClientCombatSystem::s_pCombatSystem — pointer to the singleton in .data.
// This is a DATA address (not code), so it can't be pattern-scanned in .text;
// it's left as a fallback constant. If the binary's .data layout shifted, the
// first dereference would AV and CrashLogger would log it as
// ACCESS_VIOLATION inside the engine's thiscall thunk.
private const uint CombatSystemPtrVa = 0x0087166C;
// Offset of combatMode (COMBAT_MODE) within ClientCombatSystem:
// ClientSystem(8) + IInputActionCallback(4) + QualityChangeHandler(4)
// + Turbine_RefCount(8) + jump_pending(1) + m_bTrackingTarget(1) + pad(2) = 28
private const int CombatModeOffset = 28;
// Phase B: resolve s_pCombatSystem's address by code-xref ("mov [s_pCombatSystem],esi" =
// 89 35 <addr>), operand at offset 2; the VA stays as fallback. Resolved in Initialize.
private static readonly byte?[] PatXrefCombatSystemPtr = [ 0x89, 0x35, null, null, null, null, 0x8B, 0x06 ];
private static uint _combatSystemPtrAddr = CombatSystemPtrVa;
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
/// <summary>
/// Reads the current combat mode directly from ClientCombatSystem::combatMode.
/// Returns NonCombat if the pointer is null or unreadable.
/// </summary>
// Deep-audit finding #4 (2026-06-18): this used to raw-dereference the
// ClientCombatSystem singleton unconditionally, including off AC's main
// thread — a teardown-window read (relog/portal, singleton being torn
// down) can land on a freed/mid-reassignment pointer, an uncatchable AV
// under NativeAOT. SetCombatModeDetour already runs ON the main thread
// (it's the inbound-echo hook) and maintains _lastObservedCombatMode as a
// main-thread-verified cache — off-thread callers get that instead of
// touching AC memory at all.
public static unsafe int ReadCurrentCombatMode()
{
if (!MainThreadGuard.IsOnMainThread())
return Volatile.Read(ref _lastObservedCombatMode);
try
{
IntPtr combatSystem = *(IntPtr*)CombatSystemPtrVa;
if (combatSystem == IntPtr.Zero)
IntPtr combatSystemPtrAddr = (IntPtr)_combatSystemPtrAddr;
if (!ClientObjectHooks.IsReadablePointer(combatSystemPtrAddr))
return Volatile.Read(ref _lastObservedCombatMode);
IntPtr combatSystem = *(IntPtr*)_combatSystemPtrAddr;
if (combatSystem == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(combatSystem + CombatModeOffset))
return CombatActionHooks.CombatModeNonCombat;
int raw = *(int*)(combatSystem + CombatModeOffset);
return NormalizeCombatMode(raw);
int raw = NormalizeCombatMode(*(int*)(combatSystem + CombatModeOffset));
// Heal the off-thread cache from this live main-thread read.
//
// _lastObservedCombatMode is only advanced by the detour, which fires
// on a mode CHANGE. After a hot reload or a fresh client it starts at
// its NonCombat default, so if the character is already in Magic and
// stays there, no change ever occurs, the detour never fires, and the
// cache stays wrong forever. Off-thread callers then read NonCombat
// and request Magic in a loop that cannot succeed — nothing needs
// changing — until EnsureMagicMode's deadlock recovery re-equips the
// wand and forces a real transition. That is the 8s stance stall seen
// at 01:49 (after a client restart) and 10:36 (after a reload) on
// 2026-09-03, both visible as an unnecessary unwield/re-wield.
//
// Safe for the change-detection above: the detour compares against
// this value, so healing it to the truth only suppresses events that
// would have reported a change that did not happen.
Volatile.Write(ref _lastObservedCombatMode, raw);
return raw;
}
catch
{
return CombatActionHooks.CombatModeNonCombat;
return Volatile.Read(ref _lastObservedCombatMode);
}
}
/// <summary>
/// Request a combat-mode change the way the CLIENT does it, by calling
/// ClientCombatSystem::SetCombatMode(newMode, playerRequested: 1).
///
/// Why this exists: CombatActionHooks.ChangeCombatMode binds the function that
/// writes network opcode 0x53 (CM_Combat::Event_ChangeCombatMode) and calls it
/// directly. That is the bottom of the stack — it tells the SERVER, and nothing
/// else. SetCombatMode is the layer above it, and it does three things:
/// * sets the client's own mode field,
/// * calls CM_Combat::Event_ChangeCombatMode → sends 0x53 to the server,
/// * calls CM_Combat::SendNotice_SetCombatMode → notifies the UI widgets
/// (gmCombatUI / gmToolbarUI / gmSpellcastingUI each have a
/// RecvNotice_SetCombatMode handler).
/// Going in below it meant the stance widgets were never told, so the toolbar
/// icon kept showing Peace while the character was genuinely in Magic and
/// casting — reported from live play 2026-09-02.
///
/// playerRequested: 1 marks this as player-initiated, which is the path the
/// toolbar button itself takes. The inbound server echo arrives as 0, and the
/// UI-refresh branch is skipped there because a real click has already updated
/// the widget optimistically — which is exactly why the echo alone never fixed
/// the icon for us.
///
/// Calls the trampoline, so our own detour does not re-enter. _lastObservedCombatMode
/// is deliberately NOT updated here: it must keep meaning "what the server
/// decided", or a server that refuses the stance (the documented wand-stance
/// wedge) would look like it had accepted it. The echo updates it.
///
/// Main thread only — the caller marshals. Returns false if the hook isn't
/// installed or the singleton isn't readable, so the caller can fall back.
/// </summary>
public static unsafe bool RequestCombatMode(int combatMode)
{
if (!IsInstalled || _originalSetCombatMode == null)
{ LogRequestPath(combatMode, -1, "FALLBACK: hook not installed"); return false; }
if (!MainThreadGuard.IsOnMainThread())
{ LogRequestPath(combatMode, -1, "FALLBACK: off main thread"); return false; }
try
{
IntPtr combatSystemPtrAddr = (IntPtr)_combatSystemPtrAddr;
if (!ClientObjectHooks.IsReadablePointer(combatSystemPtrAddr))
{ LogRequestPath(combatMode, -1, "FALLBACK: s_pCombatSystem address unreadable"); return false; }
IntPtr combatSystem = *(IntPtr*)_combatSystemPtrAddr;
if (combatSystem == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(combatSystem + CombatModeOffset))
{ LogRequestPath(combatMode, -1, "FALLBACK: combat system singleton unreadable"); return false; }
// Read the field SetCombatMode itself compares against ([esi+0x1C]).
// Its prologue jumps past the whole body when the request equals the
// current mode — so if these are equal, the call sends NO packet and
// notifies nothing, and the stance silently will not change. That is
// the leading suspect for the 8s stance stall seen on force rebuff
// (2026-09-03 01:49), so record it explicitly rather than guess.
int cur = *(int*)(combatSystem + CombatModeOffset);
// Same healing as ReadCurrentCombatMode: this is a live main-thread
// read, so it is strictly better than a stale cached default.
Volatile.Write(ref _lastObservedCombatMode, NormalizeCombatMode(cur));
// The client already believes it is in this mode, so SetCombatMode
// would jump straight past its body: no 0x53 to the server and no UI
// notice. But the SERVER can disagree with the client's field — that
// is exactly the case worth sending — so decline here and let the
// caller fall through to the raw opcode-0x53 sender, which is what
// this code did unconditionally before the client-level path existed.
// Confirmed live 2026-09-03 01:57: req=8 against clientField=8
// swallowed every retry for ~8s until EnsureMagicMode's deadlock
// recovery re-equipped the wand and forced a real transition.
//
// Nothing is lost on the UI side by taking the raw path here: the
// widgets read the same field, and it already holds the requested
// mode, so there is no stale icon to correct.
if (cur == combatMode)
{
LogRequestPath(combatMode, cur, "declining — client field already equals request (SetCombatMode would no-op); using raw 0x53 sender so the server is still told");
return false;
}
_originalSetCombatMode(combatSystem, combatMode, 1);
LogRequestPath(combatMode, cur, "sent via ClientCombatSystem::SetCombatMode(playerRequested=1)");
return true;
}
catch (Exception ex)
{
try { RynthLog.Compat($"CombatModeHooks: RequestCombatMode({combatMode}) threw {ex.GetType().Name}: {ex.Message}"); } catch { }
return false;
}
}
private static string _lastRequestLog = "";
private static long _lastRequestLogTicks;
/// <summary>One line per combat-mode request telling us which path ran.
/// Stance flips are rare, but a retry loop would repeat, so identical
/// messages are throttled to 1/s.</summary>
private static void LogRequestPath(int requested, int current, string outcome)
{
try
{
string msg = $"CombatModeHooks: RequestCombatMode(req={requested}, clientField={current}) — {outcome}";
long now = Environment.TickCount64;
if (msg == _lastRequestLog && (now - _lastRequestLogTicks) < 1000) return;
_lastRequestLog = msg;
_lastRequestLogTicks = now;
RynthLog.Compat(msg);
}
catch { }
}
public static void Initialize()
{
if (IsInstalled)
@ -60,51 +218,71 @@ internal static class CombatModeHooks
return;
}
int funcOff = SetCombatModeVa - textSection.TextBaseVa;
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
var resolved = HookResolver.Resolve(textSection, "CombatModeHooks.SetCombatMode",
SetCombatModePattern, SetCombatModeFallbackVa);
if (!resolved.Success)
{
_statusMessage = $"ClientCombatSystem::SetCombatMode VA out of range @ 0x{SetCombatModeVa:X8}.";
RynthLog.Compat($"Compat: combat-mode hook failed - {_statusMessage}");
_statusMessage = $"Resolve failed ({resolved.Detail}).";
return;
}
byte firstByte = textSection.Bytes[funcOff];
if (firstByte is 0x00 or 0xCC or 0xC3)
{
_statusMessage = $"ClientCombatSystem::SetCombatMode looks invalid @ 0x{SetCombatModeVa:X8} (opcode 0x{firstByte:X2}).";
RynthLog.Compat($"Compat: combat-mode hook failed - {_statusMessage}");
return;
}
_combatSystemPtrAddr = (uint)HookResolver.ResolveData(textSection, "CombatMode.s_pCombatSystem", PatXrefCombatSystemPtr, 2, (int)CombatSystemPtrVa).Address.ToInt32();
try
{
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_targetAddress = resolved.Address;
_setCombatModeDetour = SetCombatModeDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_setCombatModeDetour);
_originalSetCombatMode = Marshal.GetDelegateForFunctionPointer<SetCombatModeDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
_originalSetCombatMode = Marshal.GetDelegateForFunctionPointer<SetCombatModeDelegate>(
MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
IsInstalled = true;
_statusMessage = $"Hooked ClientCombatSystem::SetCombatMode @ 0x{_targetAddress.ToInt32():X8}.";
RynthLog.Verbose($"Compat: combat-mode hook ready - SetCombatMode=0x{_targetAddress.ToInt32():X8}, firstByte=0x{firstByte:X2}");
RynthLog.Compat($"CombatModeHooks: install ok.");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: combat-mode hook failed - {ex.Message}");
RynthLog.Compat($"CombatModeHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static int _fires;
private static int _lastLoggedMode = int.MinValue;
private static long _lastLogTicks;
private static void SetCombatModeDetour(IntPtr thisPtr, int newCombatMode, int playerRequested)
{
// First detour to fire latches AC's main thread ID so background
// threads (DecalCoexistence plugin-tick, panel snapshot, etc.) can
// refuse to call into AC's non-thread-safe internals.
MainThreadGuard.RecordIfFirst();
RecursionGuard.Tick("CombatModeHooks.SetCombatMode");
// This detour fires on the INBOUND server echo (RecvNotice_SetCombatMode ->
// ClientCombatSystem::SetCombatMode), so it reflects what the SERVER decided,
// not what the plugin requested. The old `_fires <= 3` lifetime cap went dark
// hours before any wedge, hiding the diagnosis. Log every distinct mode plus
// repeats throttled to 1/s, so a wand-stance wedge (server re-echoing
// NonCombat=1 against repeated Magic requests) is visible instead of silent.
// See rynthai_combat_busy_wedge ADDENDUM 5.
long nowTicks = Environment.TickCount64;
if (++_fires <= 3 || newCombatMode != _lastLoggedMode || (nowTicks - _lastLogTicks) >= 1000)
{
_lastLoggedMode = newCombatMode;
_lastLogTicks = nowTicks;
RynthLog.Compat($"CombatModeHooks: SetCombatMode fired #{_fires} mode={newCombatMode} requested={playerRequested} (main TID = {MainThreadGuard.MainThreadId})");
}
try
{
_originalSetCombatMode!(thisPtr, newCombatMode, playerRequested);
}
catch (Exception ex)
{
try { RynthLog.Compat($"Compat: combat-mode detour error - {ex.GetType().Name}: {ex.Message}"); } catch { }
try { RynthLog.Compat($"CombatModeHooks: original threw {ex.GetType().Name}: {ex.Message}"); } catch { }
throw;
}
@ -127,16 +305,4 @@ internal static class CombatModeHooks
_ => combatMode
};
}
private static string FormatCombatMode(int combatMode)
{
return combatMode switch
{
CombatActionHooks.CombatModeNonCombat => "noncombat(1)",
CombatActionHooks.CombatModeMelee => "melee(2)",
CombatActionHooks.CombatModeMissile => "missile(4)",
CombatActionHooks.CombatModeMagic => "magic(8)",
_ => combatMode.ToString()
};
}
}

View file

@ -25,6 +25,15 @@ internal static class CommandInterpreterHooks
private const int TakeControlOffsetFromSetAutoRun = ReferenceCommandInterpreterTakeControlFromServer - ReferenceCommandInterpreterSetAutoRun;
private const int ClearAllCommandsOffsetFromSetAutoRun = ReferenceCommandInterpreterClearAllCommands - ReferenceCommandInterpreterSetAutoRun;
// Verified unique + lands at the Reference VA offline (tools/pe_pattern.py).
// Primary resolution; the *Offset deltas below remain as fallback only.
private static readonly byte?[] SetMotionPattern = [ 0x8B, 0x41, 0x08, 0x81, 0xEC, 0x0C, 0x01, 0x00 ];
private static readonly byte?[] StopCompletelyPattern = [ 0x56, 0x8B, 0xF1, 0x8B, 0x46, 0x04, 0x85, 0xC0, 0x74, 0x32 ];
private static readonly byte?[] TurnToHeadingPattern = [ 0x83, 0xEC, 0x2C, 0x56, 0x8B, 0xF1, 0x8B, 0x06 ];
private static readonly byte?[] PlayerTeleportedPattern = [ 0x56, 0x8B, 0xF1, 0x8B, 0x06, 0x6A, 0x01, 0x6A ];
private static readonly byte?[] TakeControlFromServerPattern = [ 0x56, 0x8B, 0xF1, 0x8B, 0x46, 0x34, 0x85, 0xC0, 0x74 ];
private static readonly byte?[] ClearAllCommandsPattern = [ 0x56, 0x8B, 0xF1, 0x8D, 0x4E, 0x0C, 0xE8, null, null, null, null, 0x8D, 0x4E, 0x18, 0xE8, null, null, null, null, 0x8D, 0x4E, 0x24, 0x5E ];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void CommenceJumpDelegate(IntPtr thisPtr);
@ -54,6 +63,8 @@ internal static class CommandInterpreterHooks
private static IntPtr _smartboxStaticAddr;
private static IntPtr _boundCmdInterp;
private static bool _absResolved;
private static IntPtr _setMotionAbs, _stopCompletelyAbs, _turnToHeadingAbs, _playerTeleportedAbs, _takeControlAbs, _clearAllCommandsAbs;
private static CommenceJumpDelegate? _commenceJump;
private static DoJumpDelegate? _doJump;
private static SetAutoRunDelegate? _setAutoRun;
@ -113,24 +124,51 @@ internal static class CommandInterpreterHooks
}
}
// Rate-limited diag counters — see why patrol "creates a route but stands
// still" by surfacing the actual movement API calls in RynthCore.log.
private static int _setAutoRunCalls;
private static int _turnToHeadingCalls;
private static int _setMotionCalls;
private static bool ShouldLogMove(int n) => n <= 3 || (n & 0x7) == 0;
public static bool SetAutoRun(bool enabled)
{
// ⚠ Main thread only (2026-06-12 cross-incident forensics): these
// CommandInterpreter calls were the last direct off-thread AC mutators
// — dump-proven executing 15s after a main thread had wedged. They
// rewrite the locomotion channels of the same CommandInterpreter /
// motion graph the CSequence-AV corruption class kills. Off-thread
// callers marshal through the action ring (drained post-tick,
// gesture-gated) like every other mutator.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueSetAutoRun(enabled);
int n = System.Threading.Interlocked.Increment(ref _setAutoRunCalls);
if (!TryBindDelegates())
{
if (ShouldLogMove(n))
RynthLog.Compat($"Move: SetAutoRun({enabled}) #{n} — TryBindDelegates failed: {_statusMessage}");
return false;
}
try
{
_setAutoRun!(_boundCmdInterp, enabled ? 1 : 0, 1);
if (ShouldLogMove(n))
RynthLog.Compat($"Move: SetAutoRun({enabled}) #{n} -> ok (cmdInterp=0x{_boundCmdInterp.ToInt32():X8})");
return true;
}
catch
catch (Exception ex)
{
if (ShouldLogMove(n))
RynthLog.Compat($"Move: SetAutoRun({enabled}) #{n} threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
public static bool SetMotion(uint motion, bool enabled)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueSetMotion(motion, enabled); // same off-thread class as SetAutoRun
if (!TryBindDelegates() || _setMotion == null)
return false;
@ -147,6 +185,8 @@ internal static class CommandInterpreterHooks
public static bool StopCompletely()
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueStopCompletely(); // same off-thread class as SetAutoRun
if (!TryBindDelegates() || _stopCompletely == null)
return false;
@ -163,22 +203,41 @@ internal static class CommandInterpreterHooks
public static bool TurnToHeading(float headingDegrees)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueTurnToHeading(headingDegrees); // same off-thread class as SetAutoRun
int n = System.Threading.Interlocked.Increment(ref _turnToHeadingCalls);
if (!TryBindDelegates() || _turnToHeading == null)
{
if (ShouldLogMove(n))
RynthLog.Compat($"Move: TurnToHeading({headingDegrees:0.0}) #{n} — bind={(_turnToHeading != null)} status='{_statusMessage}'");
return false;
}
try
{
_turnToHeading(_boundCmdInterp, headingDegrees);
if (ShouldLogMove(n))
RynthLog.Compat($"Move: TurnToHeading({headingDegrees:0.0}) #{n} -> ok");
return true;
}
catch
catch (Exception ex)
{
if (ShouldLogMove(n))
RynthLog.Compat($"Move: TurnToHeading({headingDegrees:0.0}) #{n} threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
// Recovery triplet: unguarded like the jump trio, but only latent today
// (reached solely from the main-thread-gated ForceResetBusyCount) — public
// API surface though, so gate defensively rather than add queue plumbing
// for a currently-unreached off-thread path (revisit with an ActionKind if
// one of these is ever exposed to off-thread callers).
public static bool PlayerTeleported()
{
if (!MainThreadGuard.IsOnMainThread())
return false;
if (!TryBindDelegates() || _playerTeleported == null)
return false;
@ -195,6 +254,8 @@ internal static class CommandInterpreterHooks
public static bool TakeControlFromServer()
{
if (!MainThreadGuard.IsOnMainThread())
return false;
if (!TryBindDelegates() || _takeControlFromServer == null)
return false;
@ -211,6 +272,8 @@ internal static class CommandInterpreterHooks
public static bool ClearAllCommands()
{
if (!MainThreadGuard.IsOnMainThread())
return false;
if (!TryBindDelegates() || _clearAllCommands == null)
return false;
@ -225,8 +288,16 @@ internal static class CommandInterpreterHooks
}
}
// Jump trio marshalled 2026-09-02 (deep-audit finding #2): these called the
// native CommandInterpreter through _boundCmdInterp with zero
// MainThreadGuard gate, unlike every sibling (SetAutoRun/SetMotion/
// StopCompletely/TurnToHeading above), live-exercised off-thread via
// Jumper.cs's Decal-coexistence pump-thread tick.
public static bool TapJump()
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueTapJump();
if (!TryBindDelegates())
return false;
@ -246,6 +317,8 @@ internal static class CommandInterpreterHooks
public static bool CommenceJump()
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueCommenceJump();
if (!TryBindDelegates())
return false;
@ -262,6 +335,8 @@ internal static class CommandInterpreterHooks
public static bool DoJump(bool autonomous)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueDoJumpAutonomous(autonomous);
if (!TryBindDelegates())
return false;
@ -276,6 +351,29 @@ internal static class CommandInterpreterHooks
}
}
// Resolve the six non-vtable-slot member functions by unique .text signature (primary),
// once and cached — they are static code addresses. On a miss they stay Zero and
// TryBindDelegates falls back to the live-anchor + hardcoded-delta computation (old behavior).
private static void EnsureAbsoluteResolved()
{
if (_absResolved) return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) return; // retry next call
HookResolver.ResolveResult r;
r = HookResolver.Resolve(text, "CmdInterp.SetMotion", SetMotionPattern, ReferenceAccCmdInterpSetMotion);
_setMotionAbs = r.Success ? r.Address : IntPtr.Zero;
r = HookResolver.Resolve(text, "CmdInterp.StopCompletely", StopCompletelyPattern, ReferenceCommandInterpreterStopCompletely);
_stopCompletelyAbs = r.Success ? r.Address : IntPtr.Zero;
r = HookResolver.Resolve(text, "CmdInterp.TurnToHeading", TurnToHeadingPattern, ReferenceCommandInterpreterTurnToHeading);
_turnToHeadingAbs = r.Success ? r.Address : IntPtr.Zero;
r = HookResolver.Resolve(text, "CmdInterp.PlayerTeleported", PlayerTeleportedPattern, ReferenceCommandInterpreterPlayerTeleported);
_playerTeleportedAbs = r.Success ? r.Address : IntPtr.Zero;
r = HookResolver.Resolve(text, "CmdInterp.TakeControlFromServer", TakeControlFromServerPattern, ReferenceCommandInterpreterTakeControlFromServer);
_takeControlAbs = r.Success ? r.Address : IntPtr.Zero;
r = HookResolver.Resolve(text, "CmdInterp.ClearAllCommands", ClearAllCommandsPattern, ReferenceCommandInterpreterClearAllCommands);
_clearAllCommandsAbs = r.Success ? r.Address : IntPtr.Zero;
_absResolved = true;
}
private static bool TryBindDelegates()
{
IntPtr selectedStaticAddr = IntPtr.Zero;
@ -331,12 +429,13 @@ internal static class CommandInterpreterHooks
IntPtr commenceJumpPtr = Marshal.ReadIntPtr(vtable, VtblCommenceJumpIndex * IntPtr.Size);
IntPtr doJumpPtr = Marshal.ReadIntPtr(vtable, VtblDoJumpIndex * IntPtr.Size);
IntPtr setAutoRunPtr = Marshal.ReadIntPtr(vtable, VtblSetAutoRunIndex * IntPtr.Size);
IntPtr setMotionPtr = ResolveSetMotionPointer(commenceJumpPtr, doJumpPtr);
IntPtr stopCompletelyPtr = AddOffset(setAutoRunPtr, StopCompletelyOffsetFromSetAutoRun);
IntPtr turnToHeadingPtr = AddOffset(setAutoRunPtr, TurnToHeadingOffsetFromSetAutoRun);
IntPtr playerTeleportedPtr = AddOffset(setAutoRunPtr, PlayerTeleportedOffsetFromSetAutoRun);
IntPtr takeControlPtr = AddOffset(setAutoRunPtr, TakeControlOffsetFromSetAutoRun);
IntPtr clearAllCommandsPtr = AddOffset(setAutoRunPtr, ClearAllCommandsOffsetFromSetAutoRun);
EnsureAbsoluteResolved();
IntPtr setMotionPtr = _setMotionAbs != IntPtr.Zero ? _setMotionAbs : ResolveSetMotionPointer(commenceJumpPtr, doJumpPtr);
IntPtr stopCompletelyPtr = _stopCompletelyAbs != IntPtr.Zero ? _stopCompletelyAbs : AddOffset(setAutoRunPtr, StopCompletelyOffsetFromSetAutoRun);
IntPtr turnToHeadingPtr = _turnToHeadingAbs != IntPtr.Zero ? _turnToHeadingAbs : AddOffset(setAutoRunPtr, TurnToHeadingOffsetFromSetAutoRun);
IntPtr playerTeleportedPtr = _playerTeleportedAbs != IntPtr.Zero ? _playerTeleportedAbs : AddOffset(setAutoRunPtr, PlayerTeleportedOffsetFromSetAutoRun);
IntPtr takeControlPtr = _takeControlAbs != IntPtr.Zero ? _takeControlAbs : AddOffset(setAutoRunPtr, TakeControlOffsetFromSetAutoRun);
IntPtr clearAllCommandsPtr = _clearAllCommandsAbs != IntPtr.Zero ? _clearAllCommandsAbs : AddOffset(setAutoRunPtr, ClearAllCommandsOffsetFromSetAutoRun);
if (!SmartBoxLocator.IsPointerInModule(commenceJumpPtr) ||
!SmartBoxLocator.IsPointerInModule(doJumpPtr) ||
@ -386,6 +485,8 @@ internal static class CommandInterpreterHooks
{
_smartboxStaticAddr = IntPtr.Zero;
_boundCmdInterp = IntPtr.Zero;
_absResolved = false;
_setMotionAbs = _stopCompletelyAbs = _turnToHeadingAbs = _playerTeleportedAbs = _takeControlAbs = _clearAllCommandsAbs = IntPtr.Zero;
_commenceJump = null;
_doJump = null;
_setAutoRun = null;

View file

@ -9,12 +9,10 @@ namespace RynthCore.Engine.Compatibility;
internal static class CreateObjectHooks
{
private const int CreateObjectVa = 0x005594B0;
private static readonly byte[] CreateObjectSignature =
// Verified unique + lands at 0x005594B0 offline (tools/pe_pattern.py).
private static readonly byte?[] CreateObjectPattern =
[
0x55, 0x8B, 0x6C, 0x24, 0x08, 0x56, 0x8B, 0xF1,
0x8B, 0x8E, 0x8C, 0x00, 0x00, 0x00, 0x8B, 0x96,
0x88, 0x00, 0x00, 0x00, 0x8B, 0xC5, 0xD3, 0xE8,
0x8B, 0x8E, 0x90, 0x00, 0x00, 0x00, 0x33, 0xC5
0x55, 0x8B, 0x6C, 0x24, 0x08, 0x56, 0x8B, 0xF1, 0x8B, 0x8E
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
@ -28,6 +26,7 @@ internal static class CreateObjectHooks
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
public static int DispatchCount => _dispatchCount;
public static void Initialize()
{
@ -40,17 +39,17 @@ internal static class CreateObjectHooks
return;
}
int funcOff = CreateObjectVa - textSection.TextBaseVa;
if (!PatternScanner.VerifyBytes(textSection.Bytes, funcOff, CreateObjectSignature))
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "CreateObject.CreateObject", CreateObjectPattern, CreateObjectVa);
if (!resolved.Success)
{
_statusMessage = $"ACCObjectMaint::CreateObject signature mismatch @ 0x{CreateObjectVa:X8}.";
_statusMessage = $"ACCObjectMaint::CreateObject unresolved (VA 0x{CreateObjectVa:X8}).";
RynthLog.Compat($"Compat: create-object hook failed - {_statusMessage}");
return;
}
try
{
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_targetAddress = resolved.Address;
_createObjectDetour = CreateObjectDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_createObjectDetour);
_originalCreateObject = Marshal.GetDelegateForFunctionPointer<CreateObjectDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
@ -70,6 +69,7 @@ internal static class CreateObjectHooks
private static IntPtr CreateObjectDetour(IntPtr thisPtr, uint objectId, IntPtr visualDesc, IntPtr physicsDesc, IntPtr weenieDesc)
{
RecursionGuard.Tick("CreateObjectHooks.CreateObject");
if (objectId != 0 && visualDesc != IntPtr.Zero)
PaletteCache.ReadFromObjDesc(objectId, visualDesc);

View file

@ -0,0 +1,495 @@
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// IAT-hooks acclient.exe's <c>kernel32!CreateFileW</c> and <c>CreateFileA</c>
/// imports to force maximally-permissive share semantics on AC's data files.
///
/// Why this exists:
/// <see cref="MultiClientHooks"/> patches AC's <c>OpenDataFile</c> high-level
/// <c>openFlags</c> bit 0x2, which selects AC's "shared" branch — but that
/// branch still translates to a CreateFile call whose <c>dwShareMode</c> may
/// not be wide enough to coexist with handles already held by Decal-injected
/// clients launched by other launchers (Thwargle etc.). Windows file-sharing
/// compatibility is decided by the kernel at CreateFile time, not by AC's
/// internal flag.
///
/// This hook intercepts CreateFile right before the kernel sees it, and for
/// the known DAT paths rewrites:
/// dwDesiredAccess = GENERIC_READ (drop WRITE — DATs are read-only after patch)
/// dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
/// Other paths pass through untouched.
///
/// Why IAT-hook instead of MinHook on the kernel32 export:
/// Decal coexistence. Decal almost certainly already detours kernel32!CreateFile
/// (that's how Decal-injected Thwargle clients can multibox without a
/// second AC install). IAT-hooking acclient.exe's import slot intercepts only
/// acclient.exe's own calls; our detour's call into the saved IAT pointer
/// still routes through any Decal MinHook trampoline on the kernel32 export.
/// No collision; both hooks fire in order.
/// </summary>
internal static class DatFileShareHooks
{
// We force-share by file *extension* (.dat) rather than an explicit name
// list. Stock retail AC ships portal.dat / cell.dat / client_*.dat, but
// private servers commonly add split client-cell DATs (client_cell_1.dat,
// client_cell_2.dat, ...) and other variants we can't enumerate up front.
// Filtering on extension catches them all without per-server tuning.
// AC only opens .dat files via CreateFile for game data; non-DAT writes
// (logs, prefs, screenshots) pass through unmodified.
private const string DatExtension = ".dat";
private const uint GENERIC_READ = 0x80000000;
private const uint FILE_SHARE_READ = 0x00000001;
private const uint FILE_SHARE_WRITE = 0x00000002;
private const uint FILE_SHARE_DELETE = 0x00000004;
private const uint FILE_SHARE_ALL = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
private const uint PAGE_READWRITE = 0x04;
private const uint PAGE_EXECUTE_READWRITE = 0x40;
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)]
private delegate IntPtr CreateFileWDelegate(
IntPtr lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi, SetLastError = true)]
private delegate IntPtr CreateFileADelegate(
IntPtr lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
// Pinned via static field — Marshal.GetFunctionPointerForDelegate keeps a
// weak handle, so the delegate must be reachable for the process lifetime.
private static CreateFileWDelegate? _wDetour;
private static CreateFileADelegate? _aDetour;
// The IAT slot pointer (the address inside the IAT array, NOT the original
// function address) — needed for the unhook path.
private static IntPtr _wIatSlot;
private static IntPtr _aIatSlot;
// What was in the IAT slot when we patched it. Could be the real
// kernel32!CreateFile, or another hooker's detour if they got there first.
private static IntPtr _wOriginalPtr;
private static IntPtr _aOriginalPtr;
private static CreateFileWDelegate? _wOriginal;
private static CreateFileADelegate? _aOriginal;
private static string _statusMessage = "Not probed yet.";
public static bool IsEnabled { get; private set; }
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
if (IsInstalled)
return;
// Diagnostic kill-switch. Set "EnableDatShareHook": false in
// %APPDATA%\RynthCore\engine.json to skip detouring CreateFileA/W
// entirely. Used to isolate this hook as a crash suspect.
if (!Plugins.EngineSettings.EnableDatShareHook)
{
_statusMessage = "DAT share hook disabled via engine.json (EnableDatShareHook=false).";
RynthLog.Info($"Compat: {_statusMessage}");
return;
}
// Gate behind AllowMultipleClients. If the user has multi-client off,
// they're not multiboxing, so we have no reason to widen DAT sharing.
if (!LauncherSettings.AllowMultipleClientsEnabled)
{
_statusMessage = "Multi-client disabled — DAT share hook skipped.";
RynthLog.Verbose($"Compat: {_statusMessage}");
return;
}
IsEnabled = true;
try
{
IntPtr moduleBase = AcClientGetModuleBase();
if (moduleBase == IntPtr.Zero)
{
_statusMessage = "acclient.exe module base not found.";
RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}");
return;
}
// Hook the kernel32 exports directly with MinHook so we catch ALL
// callers in the process — acclient.exe itself, the CRT layer
// (msvcrt.dll, which is how AC's fopen-style DAT loads route), and
// any plugin or runtime DLL. IAT-hooking acclient.exe alone misses
// CRT-mediated calls because they go through msvcrt's own IAT slot.
IntPtr hKernel32 = GetModuleHandleW("kernel32.dll");
if (hKernel32 == IntPtr.Zero)
{
_statusMessage = "kernel32.dll module handle not found.";
RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}");
return;
}
// Two-phase install. Phase 1: create both hooks (inactive),
// assign typed trampolines into _aOriginal/_wOriginal. Phase 2:
// memory barrier then Enable. Critical ordering: the detour can
// fire from ANY caller in the process the moment Enable returns,
// and the detour calls _aOriginal/_wOriginal — those fields MUST
// be set first or the first invocation null-derefs and kills the
// engine init thread.
IntPtr aTarget = GetProcAddress(hKernel32, "CreateFileA");
IntPtr wTarget = GetProcAddress(hKernel32, "CreateFileW");
int patched = 0;
if (aTarget != IntPtr.Zero)
{
_aDetour = CreateFileADetour;
IntPtr aDetourPtr = Marshal.GetFunctionPointerForDelegate(_aDetour);
_aOriginalPtr = MinHook.HookCreate(aTarget, aDetourPtr);
_aOriginal = Marshal.GetDelegateForFunctionPointer<CreateFileADelegate>(_aOriginalPtr);
patched++;
}
if (wTarget != IntPtr.Zero)
{
_wDetour = CreateFileWDetour;
IntPtr wDetourPtr = Marshal.GetFunctionPointerForDelegate(_wDetour);
_wOriginalPtr = MinHook.HookCreate(wTarget, wDetourPtr);
_wOriginal = Marshal.GetDelegateForFunctionPointer<CreateFileWDelegate>(_wOriginalPtr);
patched++;
}
// Publish trampolines to other cores before enabling.
Thread.MemoryBarrier();
if (aTarget != IntPtr.Zero)
{
MinHook.Enable(aTarget);
RynthLog.Info($"Compat: DAT share - hooked kernel32!CreateFileA @ 0x{aTarget.ToInt32():X8} (trampoline 0x{_aOriginalPtr.ToInt32():X8}).");
}
else
{
RynthLog.Compat("Compat: DAT share - kernel32!CreateFileA export not found.");
}
if (wTarget != IntPtr.Zero)
{
MinHook.Enable(wTarget);
RynthLog.Info($"Compat: DAT share - hooked kernel32!CreateFileW @ 0x{wTarget.ToInt32():X8} (trampoline 0x{_wOriginalPtr.ToInt32():X8}).");
}
else
{
RynthLog.Compat("Compat: DAT share - kernel32!CreateFileW export not found.");
}
if (patched == 0)
{
_statusMessage = "MinHook on kernel32 CreateFile exports failed.";
RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}");
return;
}
IsInstalled = true;
_statusMessage = $"DAT share hook installed ({patched} kernel32 export(s) detoured).";
RynthLog.Info($"Compat: {_statusMessage}");
}
catch (Exception ex)
{
_statusMessage = $"DAT share hook exception: {ex.Message}";
RynthLog.Compat($"Compat: DAT share hook failed - {ex.Message}");
}
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
/// <summary>
/// Diagnostic — log every kernel32 import name we find that looks file- or
/// memory-mapping-related. Useful when the standard CreateFileW/A hook
/// doesn't catch DAT opens, because it tells us what API AC actually uses.
/// </summary>
private static unsafe void EnumerateKernel32FileImports(IntPtr moduleBase)
{
try
{
byte* basePtr = (byte*)moduleBase;
int peOffset = *(int*)(basePtr + 0x3C);
byte* optHeader = basePtr + peOffset + 24;
uint importDirRva = *(uint*)(optHeader + 96 + 8 * 1);
if (importDirRva == 0)
return;
byte* descriptor = basePtr + importDirRva;
for (; ; descriptor += 20)
{
uint nameRva = *(uint*)(descriptor + 12);
uint firstThunk = *(uint*)(descriptor + 16);
if (nameRva == 0 && firstThunk == 0) break;
string? dllName = Marshal.PtrToStringAnsi((IntPtr)(basePtr + nameRva));
if (!string.Equals(dllName, "kernel32.dll", StringComparison.OrdinalIgnoreCase))
continue;
uint origFirstThunk = *(uint*)(descriptor + 0);
uint nameTableRva = origFirstThunk != 0 ? origFirstThunk : firstThunk;
uint* names = (uint*)(basePtr + nameTableRva);
int i = 0;
var hits = new System.Text.StringBuilder("Compat: DAT share - kernel32 file/mmap imports in acclient.exe IAT:");
int hitCount = 0;
while (names[i] != 0)
{
uint thunk = names[i];
if ((thunk & 0x80000000u) == 0)
{
string? candidate = Marshal.PtrToStringAnsi((IntPtr)(basePtr + thunk + 2));
if (candidate != null &&
(candidate.Contains("File", StringComparison.Ordinal) ||
candidate.Contains("Mapping", StringComparison.Ordinal) ||
candidate.Contains("MapView", StringComparison.Ordinal) ||
candidate.StartsWith("_l", StringComparison.Ordinal) ||
candidate.StartsWith("_open", StringComparison.Ordinal)))
{
hits.Append(' ').Append(candidate);
hitCount++;
}
}
i++;
}
RynthLog.Info(hitCount > 0 ? hits.ToString() : "Compat: DAT share - no file-related kernel32 imports found in acclient.exe IAT.");
return;
}
RynthLog.Info("Compat: DAT share - kernel32.dll import descriptor not found in acclient.exe.");
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: DAT share - import enumeration failed: {ex.Message}");
}
}
private static IntPtr AcClientGetModuleBase()
{
IntPtr moduleBase = GetModuleHandleW("acclient.exe");
if (moduleBase == IntPtr.Zero)
moduleBase = GetModuleHandleW(null);
return moduleBase;
}
/// <summary>
/// Walks the import directory of <paramref name="moduleBase"/> looking for
/// kernel32.dll's import descriptor, then locates the named import
/// <paramref name="importName"/>'s IAT slot. Returns the slot's absolute
/// address (not the function pointer it contains) plus the current
/// pointer value.
/// </summary>
private static unsafe bool TryPatchIatSlot(IntPtr moduleBase, string importName, out IntPtr iatSlot, out IntPtr currentPtr)
{
iatSlot = IntPtr.Zero;
currentPtr = IntPtr.Zero;
byte* basePtr = (byte*)moduleBase;
int peOffset = *(int*)(basePtr + 0x3C);
if (peOffset <= 0 || *(uint*)(basePtr + peOffset) != 0x00004550) // "PE\0\0"
return false;
// OPTIONAL_HEADER starts at peOffset + 24 (4-byte sig + 20-byte FILE_HEADER).
// PE32 magic is 0x010B; DataDirectory starts at OptionalHeader+96.
byte* optHeader = basePtr + peOffset + 24;
if (*(ushort*)optHeader != 0x010B)
return false;
uint importDirRva = *(uint*)(optHeader + 96 + 8 * 1); // DataDirectory[1] = IMPORT
if (importDirRva == 0)
return false;
byte* descriptor = basePtr + importDirRva;
// Each IMAGE_IMPORT_DESCRIPTOR is 20 bytes; terminated by all zeros.
for (; ; descriptor += 20)
{
uint nameRva = *(uint*)(descriptor + 12);
uint firstThunk = *(uint*)(descriptor + 16);
if (nameRva == 0 && firstThunk == 0)
break; // End of descriptor list.
string? dllName = Marshal.PtrToStringAnsi((IntPtr)(basePtr + nameRva));
if (!string.Equals(dllName, "kernel32.dll", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(dllName, "KERNEL32.dll", StringComparison.OrdinalIgnoreCase))
{
continue;
}
uint origFirstThunk = *(uint*)(descriptor + 0);
// INT (Import Name Table) — prefer OriginalFirstThunk if present;
// some bound imports may have it zeroed, in which case the IAT
// itself is still a valid name table pre-binding. Both arrays are
// parallel, 4-byte entries on PE32.
uint nameTableRva = origFirstThunk != 0 ? origFirstThunk : firstThunk;
uint* names = (uint*)(basePtr + nameTableRva);
int i = 0;
while (names[i] != 0)
{
uint thunk = names[i];
// High bit set = import by ordinal — no name to match.
if ((thunk & 0x80000000u) == 0)
{
// IMAGE_IMPORT_BY_NAME = { WORD Hint; CHAR Name[]; }
string? candidate = Marshal.PtrToStringAnsi((IntPtr)(basePtr + thunk + 2));
if (string.Equals(candidate, importName, StringComparison.Ordinal))
{
iatSlot = (IntPtr)(basePtr + firstThunk + 4 * i);
currentPtr = Marshal.ReadIntPtr(iatSlot);
return currentPtr != IntPtr.Zero;
}
}
i++;
}
}
return false;
}
private static bool WriteIatPointer(IntPtr iatSlot, IntPtr newValue)
{
// IAT lives in .rdata which is read-only after the loader binds it.
// Flip protection, write, restore. Use the original-protection value
// from VirtualProtect so we put the page back exactly the way we
// found it (some loaders mark IAT pages as PAGE_READWRITE post-binding,
// some PAGE_READONLY).
if (!VirtualProtect(iatSlot, sizeof(int), PAGE_READWRITE, out uint oldProtect))
{
RynthLog.Compat($"Compat: DAT share - VirtualProtect(RW) on IAT slot 0x{iatSlot.ToInt32():X8} failed (error {Marshal.GetLastWin32Error()}).");
return false;
}
try
{
Marshal.WriteIntPtr(iatSlot, newValue);
}
finally
{
VirtualProtect(iatSlot, sizeof(int), oldProtect, out _);
}
return true;
}
private static bool IsDatPath(string? path)
{
return !string.IsNullOrEmpty(path)
&& path.EndsWith(DatExtension, StringComparison.OrdinalIgnoreCase);
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint GetLastError();
private static IntPtr CreateFileWDetour(
IntPtr lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile)
{
string? path = null;
bool isDat = false;
bool isAnyDatExt = false;
uint origAccess = dwDesiredAccess;
uint origShare = dwShareMode;
try
{
path = Marshal.PtrToStringUni(lpFileName);
isDat = IsDatPath(path);
isAnyDatExt = path != null && path.EndsWith(".dat", StringComparison.OrdinalIgnoreCase);
if (isDat)
{
dwDesiredAccess = GENERIC_READ;
dwShareMode = FILE_SHARE_ALL;
}
}
catch
{
}
IntPtr result = _wOriginal!(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
if (isAnyDatExt)
{
uint err = result == new IntPtr(-1) ? GetLastError() : 0;
string fname = Path.GetFileName(path!);
string note = isDat ? "filtered" : "passthrough";
RynthLog.Info($"Compat: DAT share - W [{note}]: {fname} access=0x{origAccess:X8}->0x{dwDesiredAccess:X8} share=0x{origShare:X}->0x{dwShareMode:X} result=0x{result.ToInt32():X8}{(err != 0 ? $" GetLastError={err}" : "")}");
}
return result;
}
private static IntPtr CreateFileADetour(
IntPtr lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile)
{
string? path = null;
bool isDat = false;
bool isAnyDatExt = false;
uint origAccess = dwDesiredAccess;
uint origShare = dwShareMode;
try
{
path = Marshal.PtrToStringAnsi(lpFileName);
isDat = IsDatPath(path);
isAnyDatExt = path != null && path.EndsWith(".dat", StringComparison.OrdinalIgnoreCase);
if (isDat)
{
dwDesiredAccess = GENERIC_READ;
dwShareMode = FILE_SHARE_ALL;
}
}
catch
{
}
IntPtr result = _aOriginal!(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
if (isAnyDatExt)
{
uint err = result == new IntPtr(-1) ? GetLastError() : 0;
string fname = Path.GetFileName(path!);
string note = isDat ? "filtered" : "passthrough";
RynthLog.Info($"Compat: DAT share - A [{note}]: {fname} access=0x{origAccess:X8}->0x{dwDesiredAccess:X8} share=0x{origShare:X}->0x{dwShareMode:X} result=0x{result.ToInt32():X8}{(err != 0 ? $" GetLastError={err}" : "")}");
}
return result;
}
}

View file

@ -0,0 +1,131 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Hooks AC's DAT object-cache teardown <c>DBCache::DestroyObjectCaches</c>
/// (acclient.map 0x00014040 + 0x401000 = 0x00415040; ImageBase 0x00400000, ASLR off)
/// to QUIESCE off-thread enchantment-registry reads WHILE AC frees its DB objects.
///
/// Crash this addresses: the recurring <c>0x00416C86</c> (DBOCache::DestroyObj + 0x06,
/// read [null+0x28]) AV. Root cause (MainThreadGuard.cs 2026-05-14 note): the
/// off-thread plugin pump walks AC's CACQualities -> CEnchantmentRegistry linked lists
/// (EnchantmentHooks.ReadEnchantmentsFromQualities / WalkEnchantList) while AC frees
/// those nodes during a cache teardown; the pump reads a half-freed node and AC AVs in
/// DestroyObj. Decal never hits this because it drives AC only on AC's own thread.
///
/// ⚠ CRITICAL (verified 2026-06-02 from the live log): DestroyObjectCaches is NOT
/// close-only — AC calls it during world-load / zone-entry too (it fired ~5s after
/// login). So this is a SCOPED guard: raise a depth latch on entry, lower it when the
/// call returns. It must NOT stop the plugin pump or shut down the engine — an earlier
/// destructive version (RequestTickPumpStop + EngineLifecycle.Shutdown in this detour)
/// tore the engine down ~5-30s after EVERY login ("most things don't work"). The
/// engine's real teardown stays on the ExitProcess / WM_CLOSE path. While the latch is
/// set, EnchantmentHooks bails its registry walk, so the off-thread read never races
/// AC's free — at world-load, zone change, logout, AND final close alike.
///
/// Ported (and corrected for v1's in-process threading) from RynthCore2's
/// DestroyObjectCaches guard (RynthSuite2 f8a291e).
/// </summary>
internal static class DbCacheTeardownHooks
{
// DBCache::DestroyObjectCaches. Fallback VA; pattern-scan is the source of truth.
private const int DestroyObjectCachesFallbackVa = 0x00415040;
// 8B 01 / 83 EC 0C / 53 56 57 / 6A 01 / FF 50 38 / 8D 4C 24 .. — unique in .text,
// lands exactly at 0x00415040 (byte-verified against this client).
private static readonly byte?[] DestroyObjectCachesPattern =
[
0x8B, 0x01, 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57,
0x6A, 0x01, 0xFF, 0x50, 0x38, 0x8D, 0x4C, 0x24,
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void ThisCallVoidDelegate(IntPtr thisPtr);
private static ThisCallVoidDelegate? _originalDestroyObjectCaches;
private static ThisCallVoidDelegate? _destroyObjectCachesDetour;
private static IntPtr _targetAddress;
private static int _teardownDepth;
private static int _installed;
private static int _enterLogCount;
public static bool IsInstalled => Volatile.Read(ref _installed) != 0;
/// <summary>
/// True only WHILE AC is inside DBCache::DestroyObjectCaches (freeing/rebuilding its
/// DB object caches — world-load, zone change, logout, or final close). Off-thread
/// AC object/registry walkers (the plugin-pump enchantment reader) must bail while
/// this is set so they never deref a node AC is concurrently freeing. SCOPED —
/// cleared when the call returns; NOT a one-way latch.
/// </summary>
public static bool TeardownActive => Volatile.Read(ref _teardownDepth) > 0;
public static void Initialize()
{
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
Volatile.Write(ref _installed, 0);
RynthLog.Compat("DbCacheTeardownHooks: acclient.exe not available.");
return;
}
var resolved = HookResolver.Resolve(
textSection, "DbCacheTeardown.DestroyObjectCaches",
DestroyObjectCachesPattern, DestroyObjectCachesFallbackVa);
if (!resolved.Success)
{
Volatile.Write(ref _installed, 0);
return;
}
try
{
_targetAddress = resolved.Address;
_destroyObjectCachesDetour = DestroyObjectCachesDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_destroyObjectCachesDetour);
_originalDestroyObjectCaches = Marshal.GetDelegateForFunctionPointer<ThisCallVoidDelegate>(
MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
RynthLog.Compat($"DbCacheTeardownHooks: ready (DestroyObjectCaches=0x{_targetAddress.ToInt32():X8}).");
}
catch (Exception ex)
{
Volatile.Write(ref _installed, 0);
RynthLog.Compat($"DbCacheTeardownHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static void DestroyObjectCachesDetour(IntPtr thisPtr)
{
// SCOPED read-quiesce. Raise the latch BEFORE AC frees anything; lower it when
// AC's teardown loop returns. While raised, EnchantmentHooks (the off-thread
// registry walker) bails, so the pump can't read a node AC is concurrently
// freeing -> kills the 0x00416C86 (DBOCache::DestroyObj) AV. NO pump-stop / NO
// engine shutdown here: DestroyObjectCaches ALSO fires at world-load/zone, and
// destructive work tore the engine down mid-play (2026-06-02).
Interlocked.Increment(ref _teardownDepth);
try
{
if (Interlocked.Increment(ref _enterLogCount) <= 3)
RynthLog.Compat("DbCacheTeardownHooks: DestroyObjectCaches entry — off-thread registry reads quiesced for this teardown.");
_originalDestroyObjectCaches!(thisPtr);
}
catch (Exception ex)
{
try { RynthLog.Compat($"DbCacheTeardownHooks: original threw {ex.GetType().Name}: {ex.Message}"); } catch { }
}
finally
{
Interlocked.Decrement(ref _teardownDepth);
}
}
}

View file

@ -0,0 +1,71 @@
using System;
using System.Diagnostics;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Detects whether a Decal-style coexistence stack is loaded inside this
/// acclient.exe process. When true, the engine skips its D3D9 hooks and
/// in-game overlays so Decal's own EndScene rendering isn't disrupted —
/// only Avalonia floating panels (LayeredWindow / GDI) remain available.
///
/// Result is cached on first call: a Decal stack appearing later in the
/// session would still take effect on a hot-reload, but during a single
/// run the snapshot at engine init is what gates the D3D9 path.
/// </summary>
internal static class DecalDetection
{
private static readonly string[] DecalModuleNames =
{
"decal.dll",
"UBLoader.dll",
"Decal.Adapter.dll",
"phatacd.dll",
};
private static readonly object Sync = new();
private static bool _evaluated;
private static string? _detectedModule;
public static bool IsDecalLoaded => DetectedModule != null;
public static string? DetectedModule
{
get
{
lock (Sync)
{
if (_evaluated)
return _detectedModule;
_evaluated = true;
_detectedModule = ProbeOnce();
return _detectedModule;
}
}
}
private static string? ProbeOnce()
{
try
{
using Process self = Process.GetCurrentProcess();
foreach (ProcessModule module in self.Modules)
{
string name = module.ModuleName;
for (int i = 0; i < DecalModuleNames.Length; i++)
{
if (string.Equals(name, DecalModuleNames[i], StringComparison.OrdinalIgnoreCase))
return DecalModuleNames[i];
}
}
}
catch
{
// Failed to enumerate modules — treat as no Decal so we don't
// disable our own rendering on a transient probe error.
}
return null;
}
}

View file

@ -9,12 +9,10 @@ namespace RynthCore.Engine.Compatibility;
internal static class DeleteObjectHooks
{
private const int DeleteObjectVa = 0x00558330;
private static readonly byte[] DeleteObjectSignature =
// Verified unique + lands at 0x00558330 offline (tools/pe_pattern.py).
private static readonly byte?[] DeleteObjectPattern =
[
0x56, 0x57, 0x8B, 0xF9, 0xE8, 0x67, 0x2D, 0x00,
0x00, 0x85, 0xC0, 0x8B, 0x74, 0x24, 0x0C, 0x74,
0x0C, 0xE8, 0xFA, 0x23, 0x00, 0x00, 0x8B, 0x08,
0x56, 0x50, 0xFF, 0x51, 0x24, 0x56, 0xE8
0x56, 0x57, 0x8B, 0xF9, 0xE8, null, null, null, null, 0x85, 0xC0, 0x8B, 0x74, 0x24, 0x0C
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
@ -39,17 +37,17 @@ internal static class DeleteObjectHooks
return;
}
int funcOff = DeleteObjectVa - textSection.TextBaseVa;
if (!PatternScanner.VerifyBytes(textSection.Bytes, funcOff, DeleteObjectSignature))
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "DeleteObject.DeleteObject", DeleteObjectPattern, DeleteObjectVa);
if (!resolved.Success)
{
_statusMessage = $"ACCObjectMaint::DeleteObject signature mismatch @ 0x{DeleteObjectVa:X8}.";
_statusMessage = $"ACCObjectMaint::DeleteObject unresolved (VA 0x{DeleteObjectVa:X8}).";
RynthLog.Compat($"Compat: delete-object hook failed - {_statusMessage}");
return;
}
try
{
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_targetAddress = resolved.Address;
_deleteObjectDetour = DeleteObjectDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_deleteObjectDetour);
_originalDeleteObject = Marshal.GetDelegateForFunctionPointer<DeleteObjectDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
@ -69,6 +67,7 @@ internal static class DeleteObjectHooks
private static int DeleteObjectDetour(IntPtr thisPtr, uint objectId)
{
RecursionGuard.Tick("DeleteObjectHooks.DeleteObject");
if (objectId != 0)
{
PaletteCache.Remove(objectId);

View file

@ -5,9 +5,6 @@
// Used by wobjectgetisdooropen[] to detect runtime door open/close state,
// since STypeBool.OPEN in CBaseQualities reflects the default/creation state
// and is NOT updated when a door is animated open or closed at runtime.
//
// VA derivation (map_offset + 0x00401000 = live VA):
// 0010FAF0 CPhysicsObj::DoMotion → 0x00510AF0
// ============================================================================
using System;
@ -20,31 +17,34 @@ namespace RynthCore.Engine.Compatibility;
internal static class DoMotionHooks
{
// CPhysicsObj::DoMotion(uint motion, MovementParameters* params, int sendEvent) — thiscall
// Map: 0010FAF0 → live VA: 0x00510AF0
private const int DoMotionVa = 0x00510AF0;
private const int DoMotionFallbackVa = 0x00510AF0;
// CPhysicsObj::DoMotion(uint motion, MovementParameters* params, int sendEvent)
// Distinctive 0x83 0xEC 0x64 (sub esp, 0x64) and the +0xC4 / +0xCC field
// accesses; the 'mov dword ptr [esi+0xCC],1' is unique to this function's prologue.
private static readonly byte?[] DoMotionPattern =
[
0x83, 0xEC, 0x64, 0x56, 0x8B, 0xF1, 0x8B, 0x8E,
0xC4, 0x00, 0x00, 0x00, 0x33, 0xC0, 0x3B, 0xC8,
0xC7, 0x86, 0xCC, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x75, 0x0C
];
// Door motion commands (AC1Legacy Command enum)
private const uint MotionOn = 0x4000000B; // door opens
private const uint MotionOff = 0x4000000C; // door closes
private const uint MotionOn = 0x4000000B;
private const uint MotionOff = 0x4000000C;
// CPhysicsObj::weenie_obj pointer at +0x128
// Calculated from CPhysicsObj struct layout (confirmed against PhysicsPositionOffset = 0x48).
private const int WeenieObjOffset = 0x128;
// Object ID inside ACCWeenieObject (HashBaseData<UInt32>): vfptr(4) + hash_next*(4) + id(4) = offset 8
private const int WeenieIdOffset = 8;
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate uint DoMotionDelegate(IntPtr thisPtr, uint motion, IntPtr paramsPtr, int sendEvent);
private static DoMotionDelegate? _originalDoMotion;
private static DoMotionDelegate? _doMotionDetour; // held alive to prevent GC
private static DoMotionDelegate? _doMotionDetour;
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
// Per-object motion state: true = On (open/activated), false = Off (closed/deactivated).
// Only populated for objects that have had an On or Off motion applied since injection.
private static readonly ConcurrentDictionary<uint, bool> _objectOnState = new();
public static bool IsInstalled => _hookInstalled;
@ -61,54 +61,47 @@ internal static class DoMotionHooks
return;
}
int funcOff = DoMotionVa - textSection.TextBaseVa;
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
var resolved = HookResolver.Resolve(textSection, "DoMotionHooks.DoMotion",
DoMotionPattern, DoMotionFallbackVa);
if (!resolved.Success)
{
_statusMessage = $"CPhysicsObj::DoMotion VA out of range @ 0x{DoMotionVa:X8}.";
RynthLog.Compat($"Compat: do-motion hook failed - {_statusMessage}");
return;
}
byte firstByte = textSection.Bytes[funcOff];
if (firstByte is 0x00 or 0xCC or 0xC3)
{
_statusMessage = $"CPhysicsObj::DoMotion looks invalid @ 0x{DoMotionVa:X8} (opcode 0x{firstByte:X2}).";
RynthLog.Compat($"Compat: do-motion hook failed - {_statusMessage}");
_statusMessage = $"Resolve failed ({resolved.Detail}).";
return;
}
try
{
IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_doMotionDetour = DoMotionDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_doMotionDetour);
_originalDoMotion = Marshal.GetDelegateForFunctionPointer<DoMotionDelegate>(
MinHook.HookCreate(targetAddress, detourPtr));
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(targetAddress);
MinHook.Enable(resolved.Address);
_hookInstalled = true;
_statusMessage = $"Hooked CPhysicsObj::DoMotion @ 0x{targetAddress.ToInt32():X8}.";
RynthLog.Verbose($"Compat: do-motion hook ready @ 0x{targetAddress.ToInt32():X8}, firstByte=0x{firstByte:X2}");
_statusMessage = $"Hooked CPhysicsObj::DoMotion @ 0x{resolved.Address.ToInt32():X8}.";
RynthLog.Compat($"DoMotionHooks: install ok.");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: do-motion hook failed - {ex.Message}");
RynthLog.Compat($"DoMotionHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
/// <summary>
/// Returns the last observed On/Off motion state for the given object ID.
/// Returns false (not found) if this object has never had an On or Off motion since injection.
/// </summary>
public static bool TryGetObjectMotionOn(uint objectId, out bool isOn)
{
return _objectOnState.TryGetValue(objectId, out isOn);
}
private static int _fires;
private static uint DoMotionDetour(IntPtr thisPtr, uint motion, IntPtr paramsPtr, int sendEvent)
{
RecursionGuard.Tick("DoMotionHooks.DoMotion");
if (Interlocked.Increment(ref _fires) <= 3)
RynthLog.Compat($"DoMotionHooks: fired #{_fires} this=0x{thisPtr.ToInt32():X8} motion=0x{motion:X8}");
try
{
if (thisPtr != IntPtr.Zero && (motion == MotionOn || motion == MotionOff))
@ -120,7 +113,8 @@ internal static class DoMotionHooks
}
catch { }
return _originalDoMotion!(thisPtr, motion, paramsPtr, sendEvent);
try { return _originalDoMotion!(thisPtr, motion, paramsPtr, sendEvent); }
catch (Exception ex) { try { RynthLog.Compat($"DoMotionHooks: original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
}
private static uint ReadWeenieId(IntPtr physObjPtr)

View file

@ -82,14 +82,15 @@ internal static class EnchantmentHooks
int count = ReadEnchantmentsFromQualities(qualPtr, spellIds, expiryTimes, maxCount);
if (!_loggedFirstRead && count > 0)
if (_enchReadLogCount < 8)
{
_loggedFirstRead = true;
RynthLog.Verbose($"[EnchRead] first player read: {count} enchantments");
System.Threading.Interlocked.Increment(ref _enchReadLogCount);
RynthLog.Info($"[EnchRead] player read #{_enchReadLogCount}: {count} enchantments (qualPtr=0x{qualPtr.ToInt64():X8})");
}
return count;
}
private static int _enchReadLogCount;
/// <summary>
/// Reads active enchantments from any game object's CEnchantmentRegistry.
@ -142,6 +143,29 @@ internal static class EnchantmentHooks
/// </summary>
private static unsafe int ReadEnchantmentsFromQualities(IntPtr qualPtr, uint* spellIds, double* expiryTimes, int maxCount)
{
// While AC is inside a DB object-cache teardown (DbCacheTeardownHooks sets this
// on AC's main thread for the duration of DestroyObjectCaches — which fires at
// world-load, zone change, logout, AND final close), refuse to walk the
// CEnchantmentRegistry linked lists: AC is concurrently freeing those nodes, and
// an off-thread (plugin-pump) walk over a half-freed node is the recurring
// 0x00416C86 (DBOCache::DestroyObj, [null+0x28]) AV.
if (DbCacheTeardownHooks.TeardownActive)
return -1;
// Deep-audit finding #23 (2026-06-18): ReadObjectEnchantments (the
// other caller of this method) validates the qualities pointer's own
// vtable-in-module before ever reaching here; the player path used to
// skip straight to walking the registry off a cached pointer with no
// such check. KnownPlayerQualitiesPtr is zeroed on logout and
// TeardownActive covers the dominant relog race, but a
// committed-but-stale pointer surviving both (mainly a
// Decal-coexistence exposure) would otherwise be walked as if it
// were still a real CACQualities object — a use-after-free read.
// Reuses the same canonical-vtable check the skill-read path already
// relies on instead of a fresh page-probe-only check.
if (!SmartBoxLocator.IsMemoryReadable(qualPtr, 4) || !ClientObjectHooks.IsCacQualitiesObject(qualPtr))
return -1;
IntPtr regAddr = qualPtr + QualitiesRegistryOffset;
if (!SmartBoxLocator.IsMemoryReadable(regAddr, 4))
return -1;
@ -149,6 +173,42 @@ internal static class EnchantmentHooks
if (registryPtr == IntPtr.Zero) return 0;
// Validate the registry's own vtable too, mirroring ReadObjectEnchantments.
if (!SmartBoxLocator.IsMemoryReadable(registryPtr, 4))
return -1;
IntPtr registryVtable = Marshal.ReadIntPtr(registryPtr);
if (!SmartBoxLocator.IsPointerInModule(registryVtable))
return -1;
// Stability check (2026-09-02 "infinite buffing loop" bug): AC's own
// main thread mutates these linked lists as buffs land/expire, and in
// Decal-coexistence mode this reader runs off-thread on the 30Hz
// plugin pump (no EndScene-driven main-thread tick exists there) — a
// walk here can race that mutation. A torn/truncated walk silently
// under-reports the active buff set; BuffManager.RefreshFromLiveMemory
// treats a short read as "buffs expired" and clears its timers,
// making a just-completed rebuff pass look like nothing landed and
// instantly restarting it. Walk twice and only trust an exact match;
// on a mismatch, skip this tick (return -1, already a safe no-op for
// every caller) rather than report a truncated set.
int countA = WalkAllLists(registryPtr, spellIds, expiryTimes, maxCount);
uint* idsB = stackalloc uint[maxCount];
double* expB = stackalloc double[maxCount];
int countB = WalkAllLists(registryPtr, idsB, expB, maxCount);
if (countA != countB)
return -1;
for (int i = 0; i < countA; i++)
{
if (spellIds[i] != idsB[i] || expiryTimes[i] != expB[i])
return -1;
}
return countA;
}
private static unsafe int WalkAllLists(IntPtr registryPtr, uint* spellIds, double* expiryTimes, int maxCount)
{
int count = 0;
count = WalkEnchantList(registryPtr + RegistryMultListOffset, spellIds, expiryTimes, maxCount, count);
count = WalkEnchantList(registryPtr + RegistryAddListOffset, spellIds, expiryTimes, maxCount, count);

View file

@ -0,0 +1,161 @@
// ============================================================================
// RynthCore.Engine - EngineStatusMetrics.cs
//
// A benign, generic "here are my own metrics" accessor. Each heartbeat tick
// caches the engine's live metrics (UpdateMetrics); BuildEngineStatusJson
// composes them — plus the main-thread-cached player stats and session
// identity — into a small JSON object that a plugin can pull via the
// GetEngineStatusJson host bridge. The engine NEVER writes a file, opens a
// socket, or networks; it only hands a plugin its own numbers on request.
//
// (The per-client status file and phone command drain now live entirely in the
// private RynthCore.Plugin.RynthRemote plugin, so the public engine carries no
// remote or networking code — just this benign metrics accessor.)
// ============================================================================
using System;
using System.IO;
using System.Text.Json;
namespace RynthCore.Engine.Compatibility;
internal static class EngineStatusMetrics
{
// Latest heartbeat metrics, cached so the parameterless BuildEngineStatusJson
// accessor (backing the GetEngineStatusJson host bridge) can compose without
// the heartbeat thread's locals. Updated every heartbeat tick; ~1s staleness
// is fine for a status pull.
private static long _mUptimeSec, _mWorkingSetMb, _mQueueDropped, _mReconciles, _mForceClears;
private static int _mFps, _mPluginTicksPerSec;
private static bool _mInWorld;
/// <summary>
/// Cache this tick's engine metrics. Called once/second from the heartbeat
/// thread with values it already computed — a few field writes, no I/O.
/// </summary>
internal static void UpdateMetrics(
long uptimeSeconds, int fps, int pluginTicksPerSec, long workingSetMb,
bool inWorld, long queueDropped, long reconciles, long forceClears)
{
_mUptimeSec = uptimeSeconds; _mFps = fps; _mPluginTicksPerSec = pluginTicksPerSec;
_mWorkingSetMb = workingSetMb; _mInWorld = inWorld; _mQueueDropped = queueDropped;
_mReconciles = reconciles; _mForceClears = forceClears;
}
// Per-process session baselines for the per-hour rates. Each client is its own
// process, so these naturally reset per launch; we also reset on an XP drop
// (relog / char swap).
private static long _xpBaseline = -1;
private static long _lumBaseline = -1;
private static int _deathsBaseline = -1;
private static DateTime _statsSessionStartUtc = DateTime.UtcNow;
/// <summary>
/// Compose the engine-side status fields as a JSON object string, from the
/// latest cached heartbeat metrics. Backs the GetEngineStatusJson host bridge.
/// Never throws; returns "{}" on failure. Safe off the main thread — player
/// stats come from a main-thread-cached source.
/// </summary>
internal static string BuildEngineStatusJson()
{
try
{
using var ms = new MemoryStream(1024);
using (var w = new Utf8JsonWriter(ms))
{
w.WriteStartObject();
WriteEngineFields(w, _mUptimeSec, _mFps, _mPluginTicksPerSec, _mWorkingSetMb,
_mInWorld, _mQueueDropped, _mReconciles, _mForceClears);
w.WriteEndObject();
}
return System.Text.Encoding.UTF8.GetString(ms.ToArray());
}
catch
{
return "{}";
}
}
// Writes the engine status fields into an already-open JSON object. The per-hour
// baselines below have a single writer (the GetEngineStatusJson accessor path).
private static void WriteEngineFields(
Utf8JsonWriter w,
long uptimeSeconds, int fps, int pluginTicksPerSec, long workingSetMb,
bool inWorld, long queueDropped, long reconciles, long forceClears)
{
w.WriteString("schema", "rynthcore.client-status/1");
w.WriteString("ts", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'"));
w.WriteString("host", SafeMachineName());
w.WriteNumber("pid", Environment.ProcessId);
w.WriteString("account", SessionStateRegistry.LastAccountName ?? string.Empty);
w.WriteString("character", SessionStateRegistry.LastCharacterName ?? string.Empty);
w.WriteString("server", SessionStateRegistry.LastServerName ?? string.Empty);
w.WriteNumber("uptimeSec", uptimeSeconds);
w.WriteNumber("fps", fps);
w.WriteNumber("pluginTicksPerSec", pluginTicksPerSec);
w.WriteNumber("workingSetMB", workingSetMb);
w.WriteBoolean("inWorld", inWorld);
w.WriteNumber("queueDropped", queueDropped);
w.WriteNumber("reconciles", reconciles);
w.WriteNumber("forceClears", forceClears);
// Player stats, read on the main thread by PrefetchPlayerStats and served here off-thread
// (the plugin pump can't read these live). deaths all-time; rates/session = whole-session.
ClientObjectHooks.TryGetPlayerStats(out long xp, out long lum, out int deaths, out float vitae,
out int encVal, out int encCap, out uint landcell,
out float px, out float py, out float pz);
double vitaePct = Math.Clamp((1.0 - vitae) * 100.0, 0.0, 100.0);
// Lazy baselines; reset on an XP drop (relog / char change).
if (xp > 0 && (_xpBaseline < 0 || xp < _xpBaseline))
{
_xpBaseline = xp; _deathsBaseline = deaths; _statsSessionStartUtc = DateTime.UtcNow;
}
if (_deathsBaseline < 0 && xp > 0) _deathsBaseline = deaths;
if (lum > 0 && (_lumBaseline < 0 || lum < _lumBaseline)) _lumBaseline = lum;
double hours = (DateTime.UtcNow - _statsSessionStartUtc).TotalHours;
double xpPerHour = (hours > 1.0 / 3600.0 && _xpBaseline >= 0 && xp >= _xpBaseline) ? (xp - _xpBaseline) / hours : 0;
double lumPerHour = (hours > 1.0 / 3600.0 && _lumBaseline >= 0 && lum >= _lumBaseline) ? (lum - _lumBaseline) / hours : 0;
long xpSession = (_xpBaseline >= 0 && xp >= _xpBaseline) ? xp - _xpBaseline : 0;
int deathsSession = (_deathsBaseline >= 0 && deaths >= _deathsBaseline) ? deaths - _deathsBaseline : 0;
double burdenPct = encCap > 0 ? Math.Round((double)encVal / encCap * 100.0) : 0;
w.WriteNumber("deaths", deaths);
w.WriteNumber("deathsSession", deathsSession);
w.WriteNumber("vitaePct", Math.Round(vitaePct, 1));
w.WriteNumber("xpPerHour", Math.Round(xpPerHour));
w.WriteNumber("luminancePerHour", Math.Round(lumPerHour));
w.WriteNumber("xpSession", xpSession);
w.WriteNumber("burdenPct", burdenPct);
w.WriteString("area", landcell != 0 ? (landcell >> 16).ToString("X4") : "");
// [status-export] live map-dot position. wx/wy are ABSOLUTE world coords (cell-local origin + the
// landblock grid offset) because the baked dungeon map's bounds are absolute (DungeonLOS adds the
// same gx/gy per vertex). The app maps these straight to map pixels.
uint lb = landcell != 0 ? (landcell >> 16) : 0u;
bool indoor = lb != 0 && (landcell & 0xFFFF) >= 0x0100; // indoor EnvCells are 0x0100+; outdoor = 0
w.WriteString("landblock", lb != 0 ? lb.ToString("X8") : ""); // matches the .bin filename {lb:X8}
w.WriteBoolean("indoor", indoor);
if (indoor)
{
double wx = px + ((lb >> 8) & 0xFF) * 192.0;
double wy = py + (lb & 0xFF) * 192.0;
w.WriteNumber("wx", Math.Round(wx, 2));
w.WriteNumber("wy", Math.Round(wy, 2));
w.WriteNumber("pz", Math.Round(pz, 2)); // raw local Z — floor-label / fallback hint
}
// Last engine warning/error (truncated) + age, for remote diagnosis of a stuck box.
string? li = RynthLog.LastIssue;
if (!string.IsNullOrEmpty(li))
{
w.WriteString("lastIssue", li.Length > 140 ? li.Substring(0, 140) : li);
w.WriteNumber("lastIssueAgeSec", (long)Math.Max(0, (DateTime.UtcNow - RynthLog.LastIssueUtc).TotalSeconds));
}
else { w.WriteNull("lastIssue"); w.WriteNumber("lastIssueAgeSec", -1); }
}
private static string SafeMachineName()
{
try { return Environment.MachineName; }
catch { return string.Empty; }
}
}

View file

@ -0,0 +1,186 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Hooks AC's top-level per-frame game-logic tick, <c>Client::UseTime</c>
/// (acclient.map 0x00010FA0 + 0x401000 = 0x00411FA0; ImageBase 0x00400000, ASLR
/// off), to drain the marshalled CAST queue on AC's MAIN thread IN THE GAME-LOGIC
/// PHASE.
///
/// Why this tick (not EndScene): a cast must run where AC processes player actions
/// and advances its cast state machine. EndScene is the RENDER phase — marshalling
/// the cast there fired IncrementBusyCount but never completed the cast (proven
/// dead-end, reverted 2026-05-19: no projectile/damage, busy leaked, cast slot
/// jammed). Client::UseTime IS the game-logic phase, so the cast completes there.
///
/// Why marshal casts at all: CastSpell is the LAST off-thread AC mutator. Run off
/// the pump thread it mutates AC's single-threaded object/animation/enchant graph
/// and corrupts it; AC then AVs LATER in its own per-tick code — CSequence::
/// update_internal (animation, captured 2026-06-03), 0x67E779 (classify), 0x0055FA24
/// (range-list). Running the cast here, on AC's own game thread, removes that race
/// at the source — the root fix for the off-thread object-graph corruption class.
///
/// Thiscall detour, same proven pattern as DbCacheTeardownHooks / LogoutLifecycleHooks.
/// DrainCasts early-returns when no cast is pending, so the detour is alloc-free in
/// the common per-frame case — the same safe profile as the existing EndScene detour.
/// </summary>
internal static class GameTickHooks
{
private const int UseTimeVa = 0x00411FA0; // Client::UseTime — thiscall, returns bool in AL
// Client::UseTime returns a bool (AL): AC's main loop drives it as
// do { } while ( UseTime() != 0 );
// so the return value MUST be propagated. A void delegate discards AC's AL
// and the loop then reads whatever the managed epilogue left in EAX — when
// that is nonzero the loop never exits and the client hard-freezes (main
// thread spins in UseTime pumping messages but never rendering; bot threads
// keep running). Dump-confirmed root cause, 2026-06-05.
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate int ThisCallBoolDelegate(IntPtr thisPtr);
private static ThisCallBoolDelegate? _originalUseTime;
private static ThisCallBoolDelegate? _useTimeDetour;
private static IntPtr _targetAddress;
private static int _installed;
private static int _exitLatch;
// Verified unique + lands exactly at UseTimeVa offline (tools/pe_pattern.py).
// Replaces the prior warn-only prologue check; null = wildcard (rel32 call operand).
private static readonly byte?[] UseTimePattern = [ 0x56, 0x8B, 0xF1, 0xE8, null, null, null, null, 0xE8, null, null, null, null, 0x84, 0xC0, 0x74 ];
public static bool IsInstalled => Volatile.Read(ref _installed) != 0;
public static void Initialize()
{
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
Volatile.Write(ref _installed, 0);
RynthLog.Compat("GameTickHooks: acclient.exe not available.");
return;
}
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "GameTick.UseTime", UseTimePattern, UseTimeVa);
if (!resolved.Success)
{
Volatile.Write(ref _installed, 0);
RynthLog.Compat($"GameTickHooks: Client::UseTime unresolved (VA 0x{UseTimeVa:X8}) — cast marshalling NOT installed.");
return;
}
try
{
_targetAddress = resolved.Address;
_useTimeDetour = UseTimeDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_useTimeDetour);
_originalUseTime = Marshal.GetDelegateForFunctionPointer<ThisCallBoolDelegate>(
MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
Volatile.Write(ref _installed, 1);
RynthLog.Compat($"GameTickHooks: Client::UseTime hooked @ 0x{_targetAddress.ToInt32():X8} ({resolved.Detail}) — cast drain on game-logic tick.");
}
catch (Exception ex)
{
Volatile.Write(ref _installed, 0);
RynthLog.Compat($"GameTickHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static int UseTimeDetour(IntPtr thisPtr)
{
// Hang-watchdog beat from the game-logic tick (no frame count): the
// EndScene beat alone left the watchdog blind to a main thread that
// wedges before the new generation's EndScene hook installs.
try { MainThreadHangWatchdog.MainThreadBeatNoFrame(); }
catch { }
// Diag (diag/logoff-origin): 1 Hz sample of the client's own input-idle clock.
try { LogoffOriginProbe.SampleIdleOnGameThread(); }
catch { }
// Drain any queued cast BEFORE AC's game-logic tick: SelectItem sets AC's
// selection and the cast initiates, then THIS SAME UseTime call processes it to
// completion — mimicking AC's natural input -> UseTime flow. (Draining AFTER the
// tick landed self-buffs but not targeted casts: the selection set at the end of
// tick N was clobbered before tick N+1 read it.) Alloc-free when no cast is
// pending. Must never throw into AC's native frame.
try { AcMainThreadQueue.DrainCasts(); }
catch { }
// Refresh TeleportStateHooks' main-thread cache every real game tick. This
// detour (unlike EndScene) fires on AC's true main thread in EVERY mode
// including Decal-coexistence (no D3D9 hook there) — without this,
// off-thread callers of IsPortaling in coexistence mode would see a
// perpetually stale cache since nothing else ever reads it on-thread.
// The getter itself does the guarded read + cache write; discard the value.
try { _ = TeleportStateHooks.IsPortaling; }
catch { }
// Run AC's own game-logic + physics + animation pass.
int result;
try { result = _originalUseTime!(thisPtr); }
catch { result = 0; }
// ── Game loop is exiting — quiesce BEFORE AC's teardown ──────────────
// AC's main loop is `do { } while (UseTime() != 0)`; a 0 return means
// this was the LAST tick and AC tears its world down next (DBCache::
// DestroyObjectCaches frees every DBObj). This is the only close signal
// that covers ALL exit paths: the in-game exit / logout-quit flow never
// delivers WM_CLOSE, so the Win32Backend/AvaloniaOverlay WM_CLOSE
// quiesce never ran and the ~63 Hz pump kept firing Move/SetAutoRun/
// object reads into freed objects -> the on-close AV at acclient
// 0x00416C86 (DBOCache::DestroyObj reading [null+0x28]). We are still
// INSIDE the final UseTime call here — AC objects are all valid — so
// the pump's in-flight frame finishes safely during the bounded join.
if (result == 0 && Interlocked.Exchange(ref _exitLatch, 1) == 0)
{
try { RynthLog.Compat("GameTickHooks: Client::UseTime returned 0 — game loop exiting; quiescing plugin pump + late input before AC teardown."); }
catch { }
// Drop the busy watchdog's cached ClientUISystem ptr (freed next).
try { BusyCountHooks.ResetSession(); }
catch { }
// Arm the late mouse/cursor swallow in BOTH game-window subclasses
// (the 0x0056547B UpdateCursorState close-AV trigger) — WM_CLOSE
// never fired on this path, so neither latch is set yet.
try { ImGuiBackend.Win32Backend.MarkCloseInFlight(); }
catch { }
try { UI.RynthOverlayWindow.MarkCloseInFlight(); }
catch { }
try { EntryPoint.StopTickPumpAndJoin(); }
catch { }
// Skip the post-tick drains/watchdog below — no engine-issued
// mutation may run once the loop has decided to exit.
return 0;
}
// Drain the marshalled-action ring AFTER AC's tick, NOT before.
// ⚠ Issuing a UseObject (corpse open) / movement / stance change starts
// or REPLACES the player's CSequence motion — and AC's animation update
// (CPhysicsObj::update_object -> CSequence::update_internal ->
// AnimSequenceNode::get_high_frame) runs inside _originalUseTime above.
// Draining BEFORE that call meant the SAME tick walked the sequence we
// had just perturbed, hitting a freed/null anim node -> hard AV at
// acclient 0x5263xx/0x5264xx (null+0xC). Live-diagnosed 2026-06-11
// during a rapid corpse-open grind (AC-only crash stack, no engine
// frames). Draining after lets AC install the new gesture's node and
// walk it cleanly on its NEXT tick. The EndScene drain (the other call
// site) is already post-physics in the frame, so it was never the
// trigger. (Casts stay PRE-tick above — their selection-timing
// requirement, and they go through the separate cast slot.)
try { AcMainThreadQueue.Drain(); }
catch { }
// Busy watchdog: also post-tick now. Its decrement / cursor-refresh
// touch m_cBusy, not the motion sequence, so order is immaterial here;
// keeping all engine-issued mutations after AC's pass is the invariant.
try { BusyCountHooks.CheckWatchdog(); }
catch { }
// MUST return Client::UseTime's own bool — AC loops do/while on it.
return result;
}
}

View file

@ -0,0 +1,143 @@
using System;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Writes one short "hb #N" line to the unified log every second from a
/// background thread. Purpose: when AC dies and no termination hook fires,
/// the heartbeat gives a hard upper-bound timestamp for when the process
/// went silent — so external traces (Procmon, Application Event Log,
/// network captures) can be correlated to the second.
///
/// Cheap (one log line / second). Background thread, won't keep the
/// process alive on its own. One-shot start; safe to call from
/// pre-resume early-init.
/// </summary>
internal static class HeartbeatLogger
{
private const int IntervalMs = 1000;
private static int _started;
private static int _stopRequested;
private static int _exited;
private static Thread? _thread;
public static void Start()
{
if (Interlocked.CompareExchange(ref _started, 1, 0) != 0)
return;
_thread = new Thread(Run)
{
Name = "RynthCore.Heartbeat",
IsBackground = true,
Priority = ThreadPriority.BelowNormal
};
_thread.Start();
RynthLog.Info("HeartbeatLogger: started (1s cadence).");
}
/// <summary>
/// Signals the heartbeat thread to exit and waits up to <paramref name="timeoutMs"/>
/// for it to do so. Called from EngineLifecycle.Shutdown — without this, the
/// thread keeps running past loader FreeLibrary of the engine, executing code
/// pages that have been unmapped → CLR exception / FAIL_FAST during hot reload.
/// </summary>
public static bool StopAndJoin(int timeoutMs = 1500)
{
if (_thread == null) return true;
Interlocked.Exchange(ref _stopRequested, 1);
long deadline = Environment.TickCount64 + timeoutMs;
while (Volatile.Read(ref _exited) == 0 && Environment.TickCount64 < deadline)
Thread.Sleep(10);
bool exited = Volatile.Read(ref _exited) != 0;
if (!exited)
RynthLog.Info($"HeartbeatLogger: did NOT exit within {timeoutMs}ms.");
return exited;
}
private static void Run()
{
long tick = 0;
int lastFrames = 0;
int lastPlugTicks = 0;
long lastMs = Environment.TickCount64;
long startMs = lastMs;
try
{
while (Volatile.Read(ref _stopRequested) == 0)
{
tick++;
// Rich beat: a silent-death log tail now shows WHAT the client
// was doing — render rate (0 fps = render dead, process alive),
// plugin pump rate (0 = wedged pump), memory trend, and in-world
// state — not just "alive at T". All cheap, engine-side reads.
try
{
long nowMs = Environment.TickCount64;
long dtMs = nowMs - lastMs; if (dtMs <= 0) dtMs = 1;
int frames = MainThreadHangWatchdog.FrameCount;
int plug = Plugins.PluginManager.TickCount;
int fps = (int)((frames - lastFrames) * 1000L / dtMs);
int pps = (int)((plug - lastPlugTicks) * 1000L / dtMs);
lastFrames = frames; lastPlugTicks = plug; lastMs = nowMs;
long wsMb = 0;
try { wsMb = Environment.WorkingSet / (1024 * 1024); } catch { }
int login = 0;
try { login = LoginLifecycleHooks.HasObservedLoginComplete ? 1 : 0; } catch { }
// qd = marshalled actions silently dropped (ring full). A
// climbing qd with healthy fps means the consumer phase is
// dead — exactly the silent blackhole class the review found.
long dropped = 0;
try { dropped = AcMainThreadQueue.DroppedCount; } catch { }
// rec = busy reconciles (cast/item-action), fcl = force-clears.
// Soak health: rec climbs during combat/loot; fcl stays flat.
long rec = 0, fcl = 0;
try { rec = BusyCountHooks.ReconcileCount; fcl = BusyCountHooks.ForceClearCount; } catch { }
// idle = the client's own input-idle clock (diag/logoff-origin); the retail
// client logs itself off past InactiveTimeBeforeLogout. Omitted when unknown.
int idle = -1;
try { idle = LogoffOriginProbe.IdleSecondsForHeartbeat; } catch { }
string idleField = idle >= 0 ? $" idle={idle}s" : "";
RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} plug={pps}/s ws={wsMb}MB login={login} qd={dropped} rec={rec} fcl={fcl}{idleField}");
// Cache this client's live metrics so the GetEngineStatusJson host bridge can serve
// them to a plugin (the RynthRemote status export). No file write, no networking.
EngineStatusMetrics.UpdateMetrics((nowMs - startMs) / 1000, fps, pps, wsMb,
login == 1, dropped, rec, fcl);
}
catch { /* never let the heartbeat itself bring anything down */ }
// Self-healing: clear a stuck floating-panel click-through
// (DockedPanelPointerCaptureActive whose disarm was lost ->
// every floating panel left WS_EX_TRANSPARENT). Runs here on
// purpose: independent of the input path that strands it.
try { RynthCore.Engine.UI.AvaloniaOverlay.WatchdogClearStuckClickThrough(); }
catch { /* never let the heartbeat itself bring anything down */ }
// Mid-session log rotation (~once/minute): without it a long
// soak grows RynthCore.<pid>.log without bound (startup-only
// rotation never fires mid-session and is skipped on reload).
if (tick % 60 == 0)
{
try { LogPaths.RotateIfOversized(); }
catch { /* never let the heartbeat itself bring anything down */ }
}
// Sleep in short slices so a stop signal is observed within <100ms,
// not up to a full IntervalMs after request.
int slept = 0;
while (slept < IntervalMs && Volatile.Read(ref _stopRequested) == 0)
{
try { Thread.Sleep(50); } catch { return; }
slept += 50;
}
}
}
finally
{
Interlocked.Exchange(ref _exited, 1);
}
}
}

View file

@ -0,0 +1,190 @@
// ============================================================================
// RynthCore.Engine - Compatibility/HookResolver.cs
//
// Shared helper that resolves an acclient.exe function address by:
// 1. Pattern scanning the .text section for a unique byte signature.
// 2. Falling back to a hardcoded VA only if the pattern misses, with loud
// logging so we know the next time the binary diverges.
// 3. Reporting failure with full diagnostics so the failing hook can be
// identified from the log alone.
//
// Every site that previously hardcoded `int funcOff = TargetVa - text.TextBaseVa`
// should funnel through Resolve() so the install log line tells us exactly
// how the address was found — pattern (good), fallback (suspect), or
// unavailable (definitely the wrong build).
// ============================================================================
using System;
namespace RynthCore.Engine.Compatibility;
internal static class HookResolver
{
public enum ResolveSource { Failed, PatternScan, FallbackVa }
public readonly struct ResolveResult
{
public ResolveResult(IntPtr address, ResolveSource source, string detail)
{
Address = address;
Source = source;
Detail = detail;
}
public IntPtr Address { get; }
public ResolveSource Source { get; }
public string Detail { get; }
public bool Success => Source != ResolveSource.Failed;
}
/// <summary>
/// Locate <paramref name="functionName"/> in the loaded acclient.exe text
/// section. Pattern is the source of truth; <paramref name="fallbackVa"/>
/// is a last-resort safety net if pattern matching fails (e.g. a tiny
/// build delta we haven't anticipated).
///
/// Logs at every outcome so the install-time log line names which hook
/// resolved how — when a crash happens, the *previous* successful resolve
/// log entry tells you which hook was the most recent thing patched.
/// </summary>
public static ResolveResult Resolve(
AcClientTextSection text,
string functionName,
byte?[] pattern,
int fallbackVa)
{
try
{
int firstMatch = PatternScanner.FindPattern(text.Bytes, pattern);
if (firstMatch >= 0)
{
// Deep-audit finding #30 (2026-06-18): this used to find only
// the first and the immediately-next match, so a 3rd+
// occurrence was never considered and the multimatch log
// claimed to have examined only 2 of N. Not reachable on the
// current shipped binary (all patterns verified unique) —
// this is a defensive fallback for future binary drift, but
// "examined 2 of N and picked wrong" is exactly the failure
// mode a defensive fallback shouldn't have. Enumerate every
// match and keep the global-nearest to the fallback VA.
int fallbackOff = fallbackVa - text.TextBaseVa;
int chosen = firstMatch;
int bestDist = Math.Abs(firstMatch - fallbackOff);
int matchCount = 1;
string detail;
if (bestDist != 0) // exact-VA short-circuit — no other match can beat this
{
int searchFrom = firstMatch + 1;
while (true)
{
int next = PatternScanner.FindPatternInRegion(text.Bytes, pattern, searchFrom, text.Bytes.Length);
if (next < 0) break;
matchCount++;
int dist = Math.Abs(next - fallbackOff);
if (dist < bestDist) { bestDist = dist; chosen = next; }
if (bestDist == 0) break;
searchFrom = next + 1;
}
}
if (matchCount == 1)
{
detail = "pattern-unique";
}
else
{
detail = $"pattern-multimatch(near-fallback {chosen:X}, {matchCount} matches)";
RynthLog.Compat(
$"HookResolver[{functionName}]: pattern matched {matchCount} locations — " +
$"chose 0x{text.TextBaseVa + chosen:X8} as nearest to fallback 0x{fallbackVa:X8}.");
}
IntPtr addr = new IntPtr(text.TextBaseVa + chosen);
RynthLog.Info(
$"HookResolver[{functionName}]: RESOLVED via {detail} @ 0x{addr.ToInt32():X8} " +
$"(fallbackVa=0x{fallbackVa:X8}, delta={(addr.ToInt32() - fallbackVa):+#;-#;0}).");
return new ResolveResult(addr, ResolveSource.PatternScan, detail);
}
// Pattern miss — try the hardcoded VA, but only if the bytes there
// look plausible (not padding / interrupt fill / a bare ret).
int vaOff = fallbackVa - text.TextBaseVa;
if (vaOff >= 0 && vaOff < text.Bytes.Length)
{
byte firstByte = text.Bytes[vaOff];
bool prologueLooksValid = firstByte is not (0x00 or 0xCC or 0xC3);
if (prologueLooksValid)
{
IntPtr addr = new IntPtr(fallbackVa);
RynthLog.Compat(
$"HookResolver[{functionName}]: PATTERN MISS — falling back to hardcoded VA 0x{fallbackVa:X8} " +
$"(prologue byte=0x{firstByte:X2}). The binary may have shifted; install proceeds but is RISKY.");
return new ResolveResult(addr, ResolveSource.FallbackVa, $"fallback-va(prologue=0x{firstByte:X2})");
}
RynthLog.Compat(
$"HookResolver[{functionName}]: UNAVAILABLE — pattern not found AND fallback VA 0x{fallbackVa:X8} " +
$"prologue is invalid (byte=0x{firstByte:X2}).");
}
else
{
RynthLog.Compat(
$"HookResolver[{functionName}]: UNAVAILABLE — pattern not found AND fallback VA 0x{fallbackVa:X8} " +
$"is outside the readable .text window.");
}
return new ResolveResult(IntPtr.Zero, ResolveSource.Failed, "unavailable");
}
catch (Exception ex)
{
RynthLog.Compat($"HookResolver[{functionName}]: UNAVAILABLE — exception during resolve: {ex.GetType().Name}: {ex.Message}");
return new ResolveResult(IntPtr.Zero, ResolveSource.Failed, $"exception:{ex.GetType().Name}");
}
}
/// <summary>
/// Resolve a DATA/global address (.data/.rdata — singleton ptr, selection id, string
/// null-buffer, fn-ptr slot, …) by CODE-XREF: pattern-scan .text for a unique instruction
/// that references the address as an absolute operand (the 4 operand bytes wildcarded in
/// <paramref name="codePattern"/>), then read the address back from that operand at
/// <paramref name="operandOffset"/>. Robust if the global relocates across builds.
///
/// Unlike function resolution this does NOT fail closed: the data VA is read/written by the
/// caller, which assumes it always has one, so a miss falls back to the hardcoded VA (== old
/// behavior) with a loud log rather than returning Zero.
/// </summary>
public static ResolveResult ResolveData(
AcClientTextSection text, string name, byte?[] codePattern, int operandOffset, int fallbackVa)
{
try
{
int first = PatternScanner.FindPattern(text.Bytes, codePattern);
if (first >= 0 && first + operandOffset + 4 <= text.Bytes.Length)
{
int next = PatternScanner.FindPatternInRegion(text.Bytes, codePattern, first + 1, text.Bytes.Length);
if (next < 0)
{
int operand = BitConverter.ToInt32(text.Bytes, first + operandOffset);
RynthLog.Info(
$"HookResolver[{name}]: RESOLVED via data-xref @ 0x{operand:X8} " +
$"(fallbackVa=0x{fallbackVa:X8}, delta={(operand - fallbackVa):+#;-#;0}).");
return new ResolveResult(new IntPtr(operand), ResolveSource.PatternScan, "data-xref");
}
RynthLog.Compat(
$"HookResolver[{name}]: data-xref matched MULTIPLE .text sites — falling back to hardcoded VA 0x{fallbackVa:X8} (RISKY).");
}
else
{
RynthLog.Compat(
$"HookResolver[{name}]: data-xref pattern not found — falling back to hardcoded VA 0x{fallbackVa:X8} (RISKY).");
}
return new ResolveResult(new IntPtr(fallbackVa), ResolveSource.FallbackVa, "data-fallback");
}
catch (Exception ex)
{
RynthLog.Compat($"HookResolver[{name}]: data-xref exception {ex.GetType().Name}: {ex.Message} — fallback VA 0x{fallbackVa:X8}.");
return new ResolveResult(new IntPtr(fallbackVa), ResolveSource.FallbackVa, "data-fallback-exc");
}
}
}

View file

@ -82,8 +82,8 @@ internal static class LoginLifecycleHooks
IsInstalled = true;
_statusMessage = $"Hooked SendLoginCompleteNotification @ 0x{_targetAddress.ToInt32():X8}.";
_nextStatusLogTick = Environment.TickCount64 + 3000;
RynthLog.Verbose(
$"Compat: login lifecycle hook ready - SendLoginCompleteNotification=0x{_targetAddress.ToInt32():X8}, callSite=0x{textSection.TextBaseVa + callSiteOff:X8}");
RynthLog.Info(
$"LoginLifecycleHooks: target=0x{_targetAddress.ToInt32():X8} (funcOff=0x{funcOff:X8}, callSite=0x{textSection.TextBaseVa + callSiteOff:X8}, prologueDistance={(textSection.TextBaseVa + callSiteOff) - _targetAddress.ToInt32()} bytes).");
}
catch (Exception ex)
{
@ -123,6 +123,7 @@ internal static class LoginLifecycleHooks
private static void SendLoginCompleteNotificationDetour(IntPtr thisPtr)
{
RecursionGuard.Tick("LoginLifecycleHooks.SendLoginCompleteNotification");
_originalSendLoginCompleteNotification!(thisPtr);
SignalLoginComplete("CPlayerSystem::SendLoginCompleteNotification");
}
@ -137,4 +138,17 @@ internal static class LoginLifecycleHooks
RynthLog.Verbose($"Compat: login complete observed via {source}.");
LoginComplete?.Invoke();
}
/// <summary>
/// Mark login as already complete and fire the <see cref="LoginComplete"/>
/// event without waiting for the AC client's
/// <c>SendLoginCompleteNotification</c>. Used by the hot-reload path: the
/// new engine instance starts after the game is already in-world, so the
/// notification will never fire again — we synthesize it so subscribers
/// (PluginManager, D3D9 bootstrapper) reach their post-login state.
/// </summary>
public static void MarkAlreadyComplete(string source)
{
SignalLoginComplete(source);
}
}

View file

@ -25,6 +25,16 @@ internal static class LogoBypassHooks
private const int DismissClickX = 350;
private const int DismissClickY = 100;
// Early-burst dismiss: covers the pre-connect splash/EULA/Turbine logo
// screens. Those screens appear before AC contacts the server, so the
// packet-driven NotifyPostConnect / NotifyCharacterList triggers can never
// catch them. As soon as we find a window of our PID, fire a series of
// clicks at the splash hotspot to dismiss whatever shows up. Decal sidesteps
// this by directly patching AC's splash code; we don't have that path, so
// we brute-force it with PostMessage spam.
private const int EarlyBurstClicks = 12;
private const int EarlyBurstIntervalMs = 400;
private const uint WM_MOUSEMOVE = 0x0200;
private const uint WM_LBUTTONDOWN = 0x0201;
private const uint WM_LBUTTONUP = 0x0202;
@ -68,7 +78,7 @@ internal static class LogoBypassHooks
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
RynthLog.Verbose("LogoBypass: Login already complete at start - skipping.");
RynthLog.Compat("LogoBypass: Login already complete at start - skipping.");
return;
}
@ -87,7 +97,7 @@ internal static class LogoBypassHooks
};
thread.Start();
RynthLog.Verbose("LogoBypass: Started - waiting for post-connect or character-list signal before dismiss clicks.");
RynthLog.Compat("LogoBypass: Started - waiting for post-connect or character-list signal before dismiss clicks.");
}
public static void NotifyCharacterListObserved()
@ -121,10 +131,30 @@ internal static class LogoBypassHooks
return;
}
RynthLog.Verbose($"LogoBypass: Found game HWND 0x{hwnd:X8} - awaiting post-connect or character-list signal.");
RynthLog.Compat($"LogoBypass: Found game HWND 0x{hwnd:X8} - firing {EarlyBurstClicks} early dismiss clicks before awaiting packet signals.");
EarlyBurstDismiss(hwnd);
BypassLoop(hwnd);
}
/// <summary>
/// Fires a burst of dismiss clicks immediately, covering the pre-connect
/// splash/EULA screens that the packet-driven triggers can't catch.
/// Stops early if the client transitions out of the pre-login state
/// (LoginComplete or auto-login-already-fired). Cheap to call into a
/// post-splash window: the clicks just become spurious viewport clicks
/// that AC's pre-connect UI ignores.
/// </summary>
private static void EarlyBurstDismiss(IntPtr hwnd)
{
for (int i = 0; i < EarlyBurstClicks; i++)
{
if (LoginLifecycleHooks.HasObservedLoginComplete)
return;
SendDismissInput(hwnd);
Thread.Sleep(EarlyBurstIntervalMs);
}
}
private static void ScheduleDismissClicks(string triggerName, int startDelayMs)
{
if (!_started)
@ -147,7 +177,7 @@ internal static class LogoBypassHooks
if (scheduled)
{
RynthLog.Verbose(
RynthLog.Compat(
$"LogoBypass: {triggerName} observed - scheduling {ScheduledDismissClicks} dismiss click(s) at ({DismissClickX}, {DismissClickY}) with {startDelayMs}ms start delay.");
}
}
@ -225,7 +255,7 @@ internal static class LogoBypassHooks
PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam);
PostMessage(hwnd, WM_LBUTTONDOWN, (IntPtr)0x0001, lParam);
PostMessage(hwnd, WM_LBUTTONUP, IntPtr.Zero, lParam);
RynthLog.Verbose($"LogoBypass: Sent dismiss click at ({DismissClickX}, {DismissClickY}).");
RynthLog.Compat($"LogoBypass: Sent dismiss click at ({DismissClickX}, {DismissClickY}) to hwnd=0x{hwnd.ToInt64():X8}.");
}
private static IntPtr MakeLParam(int x, int y) =>
@ -233,31 +263,58 @@ internal static class LogoBypassHooks
private static bool ReadSkipLogosFromContext()
{
string rootDir = "(unresolved)";
try
{
string rootDir = Path.Combine(
rootDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore");
string processPath = Path.Combine(rootDir, "launch_contexts", $"launch_context_{Environment.ProcessId}.json");
bool? processValue = ReadSkipLogosFromFile(processPath);
RynthLog.Compat($"LogoBypass: ReadSkipLogosFromContext processId={Environment.ProcessId} processPath='{processPath}'");
bool? processValue = ReadSkipLogosFromFile(processPath, "process");
if (processValue.HasValue)
{
RynthLog.Compat($"LogoBypass: process-scoped context resolved SkipLoginLogos={processValue.Value}.");
return processValue.Value;
}
return ReadSkipLogosFromFile(Path.Combine(rootDir, "launch_context.json")) ?? false;
string rootPath = Path.Combine(rootDir, "launch_context.json");
RynthLog.Compat($"LogoBypass: process file did not yield value, falling back to rootPath='{rootPath}'");
bool? rootValue = ReadSkipLogosFromFile(rootPath, "root");
bool resolved = rootValue ?? false;
RynthLog.Compat($"LogoBypass: root context resolved SkipLoginLogos={(rootValue.HasValue ? rootValue.Value.ToString() : "MISSING")} (effective={resolved}).");
return resolved;
}
catch
catch (Exception ex)
{
RynthLog.Compat($"LogoBypass: ReadSkipLogosFromContext threw {ex.GetType().Name}: {ex.Message} (rootDir='{rootDir}'). Treating as SkipLoginLogos=false.");
return false;
}
}
private static bool? ReadSkipLogosFromFile(string path)
private static bool? ReadSkipLogosFromFile(string path, string label)
{
if (!File.Exists(path))
{
RynthLog.Compat($"LogoBypass: {label} context file missing at '{path}'.");
return null;
}
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path));
return doc.RootElement.TryGetProperty("SkipLoginLogos", out JsonElement el) ? el.GetBoolean() : null;
try
{
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path));
if (!doc.RootElement.TryGetProperty("SkipLoginLogos", out JsonElement el))
{
RynthLog.Compat($"LogoBypass: {label} context at '{path}' has no SkipLoginLogos property.");
return null;
}
return el.GetBoolean();
}
catch (Exception ex)
{
RynthLog.Compat($"LogoBypass: {label} context at '{path}' read/parse failed: {ex.GetType().Name}: {ex.Message}.");
return null;
}
}
}

View file

@ -0,0 +1,802 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// DIAGNOSTIC (branch diag/logoff-origin, 2026-09-27): pins down which client code path
/// asks the server to log the character off. Lucy logged off by herself mid-fight at
/// 14:28:20, 15:36:52 and 16:43:30; the ExecuteLogOff caller was the server's
/// CharacterLogOff (0xF653) handler, and ACE only sends that in reply to a logoff the
/// client requested. This probe watches the request side. It changes no behaviour.
///
/// Hooks (all log caller frames via <see cref="LogoutLifecycleHooks.LogCaller"/>):
/// - CPlayerSystem::LogOffCharacter(bool immediate) every client logoff entry point
/// - CPlayerSystem::RequestLogOff() prints "Logging off...", sends
/// - Proto_UI::LogOffCharacter(uint gid) builds + sends the 0xF653 request
/// - CPlayerSystem::SetLogOffStarted() ~3 s after the request (timeline)
/// - ClientNet::LogOffServer() transport-level disconnect
///
/// Context, dumped once when a logoff is requested (or when one completes with no request):
/// - client input idle time vs InactiveTimeBeforeLogout (the retail client logs itself
/// off from ClientUISystem::UseTime when Timer::cur_time minus CInputManager's
/// last-input time exceeds it; 1200 s on the reference client)
/// - game-window foreground/focus state and when it last changed
/// - ring buffers: the last window messages the WndProc subclass saw (keys, clicks,
/// focus, close, syscommand) and the last chat lines through the engine's chat paths
/// - an acclient-only stack sweep (return addresses above the detour; may be stale)
///
/// Idle milestones are also logged as the idle time climbs toward the threshold, and the
/// heartbeat line carries idle=Ns.
///
/// CommandInterpreter::HandleLogOff (0x006B4270) is NOT hooked: it is a two-instruction
/// thunk to CommandInterpreter::Disable (vtable +0x84) that runs as a consequence of a
/// logoff, not a requester.
/// </summary>
internal static unsafe class LogoffOriginProbe
{
// Fallback VAs on the reference retail client (4,841,472 bytes, SizeOfImage 0x56D000).
// The patterns below are the source of truth (cut + verified with tools/pe_pattern.py).
private const int ProbeLogOffCharacterVa = 0x005642C0; // CPlayerSystem::LogOffCharacter(bool)
private const int ProbeRequestLogOffVa = 0x00563B70; // CPlayerSystem::RequestLogOff()
private const int ProbeProtoLogOffVa = 0x005475E0; // Proto_UI::LogOffCharacter(uint gid), cdecl
private const int ProbeSetLogOffStartedVa = 0x0055E4F0; // CPlayerSystem::SetLogOffStarted()
private const int ProbeLogOffServerVa = 0x00544AB0; // ClientNet::LogOffServer()
private const int ProbeTimerCurTimeVa = 0x008379A8; // Timer::cur_time (double, seconds)
private const int ProbeInputManagerVa = 0x00837FF4; // ICIDM::s_cidm (CInputManager*)
private const int ProbeIdleLimitVa = 0x007CEB70; // InactiveTimeBeforeLogout (double, 1200.0)
private const int ReferenceImageSize = 0x0056D000;
// push esi; mov esi,ecx; push 0; lea ecx,[esi+0x30]; call; mov al,[esp+8]; test al,al
private static readonly byte?[] LogOffCharacterPattern = [ 0x56, 0x8B, 0xF1, 0x6A, 0x00, 0x8D, 0x4E, 0x30, 0xE8, null, null, null, null, 0x8A, 0x44, 0x24, 0x08, 0x84, 0xC0 ];
// push ecx; push esi; push edi; push "Logging off...\n"; mov esi,ecx; push 0; lea ecx,[esp+0x10]; call
private static readonly byte?[] RequestLogOffPattern = [ 0x51, 0x56, 0x57, 0x68, null, null, null, null, 0x8B, 0xF1, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0xE8 ];
// push 8; call alloc; mov ecx,[esp+8]; push 8; mov dword ptr [eax],0xF653
private static readonly byte?[] ProtoLogOffPattern = [ 0x6A, 0x08, 0xE8, null, null, null, null, 0x8B, 0x4C, 0x24, 0x08, 0x6A, 0x08, 0xC7, 0x00, 0x53, 0xF6, 0x00, 0x00 ];
// mov byte ptr [ecx+0x221],0; ret
private static readonly byte?[] SetLogOffStartedPattern = [ 0xC6, 0x81, 0x21, 0x02, 0x00, 0x00, 0x00, 0xC3 ];
// push ebp; push esi; push edi; mov ebp,ecx; mov esi,[ebp+0x8820]; push 0x1C; call
private static readonly byte?[] LogOffServerPattern = [ 0x55, 0x56, 0x57, 0x8B, 0xE9, 0x8B, 0xB5, 0x20, 0x88, 0x00, 0x00, 0x6A, 0x1C, 0xE8 ];
// Data globals by code-xref (operand at offset 2).
private static readonly byte?[] CurTimeXrefPattern = [ 0xDD, 0x05, null, null, null, null, 0x56, 0xDD ];
// ClientUISystem::UseTime: mov ebp,[ICIDM::s_cidm]; push esi; push edi; lea eax,[esp+0x10]
private static readonly byte?[] InputManagerXrefPattern = [ 0x8B, 0x2D, null, null, null, null, 0x56, 0x57, 0x8D, 0x44, 0x24, 0x10 ];
// ClientUISystem::UseTime: fcomp qword ptr [InactiveTimeBeforeLogout]; fnstsw ax; test ah,0x41; jne; cmp
private static readonly byte?[] IdleLimitXrefPattern = [ 0xDC, 0x1D, null, null, null, null, 0xDF, 0xE0, 0xF6, 0xC4, 0x41, 0x75, 0x22, 0x3B ];
private static IntPtr _origLogOffCharacter;
private static IntPtr _origRequestLogOff;
private static IntPtr _origProtoLogOff;
private static IntPtr _origSetLogOffStarted;
private static IntPtr _origLogOffServer;
private static IntPtr _curTimeVa;
private static IntPtr _inputMgrSlotVa;
private static IntPtr _idleLimitVa;
private static int _lastInputOffset = -1;
private static bool _inputOffsetProbed;
private static long _acBase;
private static long _acImageSize;
private static long _acTextLo;
private static long _acTextHi;
private static bool _labelsValid;
private static bool _initialized;
public static void Initialize()
{
if (_initialized)
return;
_initialized = true;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
RynthLog.Compat("LogoffProbe: acclient.exe not available - probe not installed.");
return;
}
_acBase = text.ModuleBase.ToInt64();
_acImageSize = text.ImageSize;
_acTextLo = text.TextBaseVa;
_acTextHi = text.TextBaseVa + (long)text.Bytes.Length;
_labelsValid = text.ImageSize == ReferenceImageSize;
_curTimeVa = HookResolver.ResolveData(text, "LogoffProbe.Timer_cur_time", CurTimeXrefPattern, 2, ProbeTimerCurTimeVa).Address;
_inputMgrSlotVa = HookResolver.ResolveData(text, "LogoffProbe.ICIDM_s_cidm", InputManagerXrefPattern, 2, ProbeInputManagerVa).Address;
_idleLimitVa = HookResolver.ResolveData(text, "LogoffProbe.InactiveTimeBeforeLogout", IdleLimitXrefPattern, 2, ProbeIdleLimitVa).Address;
try
{
double limit = _idleLimitVa != IntPtr.Zero ? *(double*)_idleLimitVa : double.NaN;
RynthLog.Compat($"LogoffProbe: client idle auto-logoff threshold (InactiveTimeBeforeLogout @ 0x{_idleLimitVa.ToInt32():X8}) = {limit:0.#} s. ClientUISystem::UseTime calls LogOffCharacter(0) once Timer::cur_time - last input exceeds it.");
}
catch { }
int hooked = 0;
HookResolver.ResolveResult r;
r = HookResolver.Resolve(text, "LogoffProbe.LogOffCharacter", LogOffCharacterPattern, ProbeLogOffCharacterVa);
delegate* unmanaged[Thiscall]<IntPtr, byte, void> dLogOffCharacter = &LogOffCharacterDetour;
if (TryHook(r, "CPlayerSystem::LogOffCharacter", (IntPtr)dLogOffCharacter, out _origLogOffCharacter)) hooked++;
r = HookResolver.Resolve(text, "LogoffProbe.RequestLogOff", RequestLogOffPattern, ProbeRequestLogOffVa);
delegate* unmanaged[Thiscall]<IntPtr, void> dRequestLogOff = &RequestLogOffDetour;
if (TryHook(r, "CPlayerSystem::RequestLogOff", (IntPtr)dRequestLogOff, out _origRequestLogOff)) hooked++;
r = HookResolver.Resolve(text, "LogoffProbe.Proto_UI_LogOffCharacter", ProtoLogOffPattern, ProbeProtoLogOffVa);
delegate* unmanaged[Cdecl]<uint, int> dProtoLogOff = &ProtoLogOffDetour;
if (TryHook(r, "Proto_UI::LogOffCharacter", (IntPtr)dProtoLogOff, out _origProtoLogOff)) hooked++;
r = HookResolver.Resolve(text, "LogoffProbe.SetLogOffStarted", SetLogOffStartedPattern, ProbeSetLogOffStartedVa);
delegate* unmanaged[Thiscall]<IntPtr, void> dSetLogOffStarted = &SetLogOffStartedDetour;
if (TryHook(r, "CPlayerSystem::SetLogOffStarted", (IntPtr)dSetLogOffStarted, out _origSetLogOffStarted)) hooked++;
r = HookResolver.Resolve(text, "LogoffProbe.ClientNet_LogOffServer", LogOffServerPattern, ProbeLogOffServerVa);
delegate* unmanaged[Thiscall]<IntPtr, void> dLogOffServer = &LogOffServerDetour;
if (TryHook(r, "ClientNet::LogOffServer", (IntPtr)dLogOffServer, out _origLogOffServer)) hooked++;
RynthLog.Compat($"LogoffProbe: {hooked}/5 logoff-origin hooks installed (labels {(_labelsValid ? "on" : "off - not the reference client")}).");
}
private static bool TryHook(HookResolver.ResolveResult r, string name, IntPtr detour, out IntPtr original)
{
original = IntPtr.Zero;
if (!r.Success)
{
RynthLog.Compat($"LogoffProbe: {name} unresolved - not hooked.");
return false;
}
try
{
MinHook.Hook(r.Address, detour, out original);
RynthLog.Compat($"LogoffProbe: {name} hooked @ 0x{r.Address.ToInt32():X8} ({r.Detail}).");
return true;
}
catch (Exception ex)
{
original = IntPtr.Zero;
RynthLog.Compat($"LogoffProbe: {name} hook failed: {ex.GetType().Name}: {ex.Message}");
return false;
}
}
// ── Detours (game thread; must never throw into AC) ──────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static void LogOffCharacterDetour(IntPtr thisPtr, byte immediate)
{
try { OnRequest("CPlayerSystem::LogOffCharacter", $"immediate={immediate}"); }
catch { }
((delegate* unmanaged[Thiscall]<IntPtr, byte, void>)_origLogOffCharacter)(thisPtr, immediate);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static void RequestLogOffDetour(IntPtr thisPtr)
{
try { OnRequest("CPlayerSystem::RequestLogOff", ""); }
catch { }
((delegate* unmanaged[Thiscall]<IntPtr, void>)_origRequestLogOff)(thisPtr);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ProtoLogOffDetour(uint gid)
{
try
{
Volatile.Write(ref _lastProtoSendMs, Environment.TickCount64);
OnRequest("Proto_UI::LogOffCharacter", $"gid=0x{gid:X8} (sends 0xF653 to the server)");
}
catch { }
return ((delegate* unmanaged[Cdecl]<uint, int>)_origProtoLogOff)(gid);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static void SetLogOffStartedDetour(IntPtr thisPtr)
{
try
{
string since = _lastRequestMs != 0 ? $" {(Environment.TickCount64 - _lastRequestMs) / 1000.0:0.00}s after the request" : " (no request seen)";
RynthLog.Info($"LogoffProbe: CPlayerSystem::SetLogOffStarted{since}.");
LogoutLifecycleHooks.LogCaller("SetLogOffStarted", "LogoffProbe");
}
catch { }
((delegate* unmanaged[Thiscall]<IntPtr, void>)_origSetLogOffStarted)(thisPtr);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static void LogOffServerDetour(IntPtr thisPtr)
{
try
{
RynthLog.Info("LogoffProbe: ClientNet::LogOffServer (transport disconnect) entered.");
LogoutLifecycleHooks.LogCaller("ClientNet::LogOffServer", "LogoffProbe");
}
catch { }
((delegate* unmanaged[Thiscall]<IntPtr, void>)_origLogOffServer)(thisPtr);
}
// ── Request / completion tracking ────────────────────────────────────────
private static long _lastRequestMs;
private static string? _lastRequestDesc;
private static long _lastProtoSendMs;
private static long _lastDumpMs;
private static void OnRequest(string fn, string args)
{
long now = Environment.TickCount64;
IntPtr caller = LogoutLifecycleHooks.LogCaller(fn, "LogoffProbe");
string callerText = DescribeAcclientAddress(caller);
string idleText = "idle=?";
bool idleOver = false;
if (TryReadIdle(out double idle, out double limit, out _, out _))
{
idleOver = idle > limit;
idleText = $"idle={idle:0.0}s/{limit:0.#}s{(idleOver ? " (OVER threshold: matches the client idle auto-logoff)" : "")}";
}
string argText = args.Length > 0 ? $"({args})" : "()";
RynthLog.Warn($"LogoffProbe: logoff requested - {fn}{argText} caller={callerText} {idleText} {DescribeFocus()}");
// The first request of a cycle names the path; later ones (RequestLogOff, the send)
// are the same logoff continuing, so keep the original description.
if (_lastRequestMs == 0 || now - _lastRequestMs > 30_000)
{
_lastRequestMs = now;
_lastRequestDesc = $"{fn}{argText} from {callerText}";
}
if (now - _lastDumpMs > 30_000)
{
_lastDumpMs = now;
DumpContext($"request via {fn}");
}
}
/// <summary>
/// Called once per logout cycle from the ExecuteLogOff / RecvNotice_Logoff detours.
/// Says whether the client asked for this logoff, and if not, dumps the context.
/// </summary>
internal static void OnLogoffCompleted(string via)
{
try
{
long now = Environment.TickCount64;
long req = _lastRequestMs;
if (req != 0 && now - req < 120_000)
{
long send = Volatile.Read(ref _lastProtoSendMs);
string sendText = send != 0 && now - send < 120_000 ? $"{(now - send) / 1000.0:0.00}s after the 0xF653 send" : "no 0xF653 send seen";
RynthLog.Info($"LogoffProbe: logoff completed via {via} {(now - req) / 1000.0:0.00}s after the client request ({sendText}). Request: {_lastRequestDesc}.");
}
else
{
RynthLog.Warn($"LogoffProbe: logoff completed via {via} with NO client logoff request in the last 120 s - server-initiated, or a path this probe does not hook.");
if (now - _lastDumpMs > 30_000)
{
_lastDumpMs = now;
DumpContext($"completion via {via} without a request");
}
}
_lastRequestMs = 0;
_lastRequestDesc = null;
}
catch { }
}
// ── Idle time (client's own idle-logoff clock) ───────────────────────────
private static long _lastIdleSampleMs;
private static int _idleSecondsForHb = -1;
private static double _prevIdle;
private static int _idleMilestoneIdx;
private static bool _idleOverLogged;
private static bool _idleDisabledLogged;
// Seconds before the threshold at which a milestone line is logged.
private static readonly int[] IdleMilestonesBefore = [900, 600, 300, 120, 60, 30, 10];
/// <summary>Client input idle seconds for the heartbeat line, or -1 when unknown.</summary>
internal static int IdleSecondsForHeartbeat => Volatile.Read(ref _idleSecondsForHb);
/// <summary>
/// Called from the Client::UseTime detour (AC's game thread). Samples once a second.
/// </summary>
internal static void SampleIdleOnGameThread()
{
long now = Environment.TickCount64;
if (now - _lastIdleSampleMs < 1000)
return;
_lastIdleSampleMs = now;
try
{
if (!TryReadIdle(out double idle, out double limit, out _, out _))
{
Volatile.Write(ref _idleSecondsForHb, -1);
return;
}
Volatile.Write(ref _idleSecondsForHb, idle < 0 ? 0 : (int)Math.Min(idle, int.MaxValue));
// Input arrived since the last sample: the client reset its idle clock.
if (idle + 1.5 < _prevIdle)
{
if (_idleMilestoneIdx > 0 || _idleOverLogged)
RynthLog.Info($"LogoffProbe: client input idle clock reset after {_prevIdle:0}s (input received). {DescribeFocus()}");
_idleMilestoneIdx = 0;
_idleOverLogged = false;
}
_prevIdle = idle;
// ClientUISystem::UseTime only logs off an in-world player; skip the
// milestone lines at character select.
bool inWorld = false;
try { inWorld = LoginLifecycleHooks.HasObservedLoginComplete; } catch { }
if (!inWorld)
return;
if (double.IsNaN(limit) || double.IsInfinity(limit) || limit <= 60)
{
if (!_idleDisabledLogged)
{
_idleDisabledLogged = true;
RynthLog.Info($"LogoffProbe: idle auto-logoff threshold is {limit} - milestones off.");
}
return;
}
// The client counts only real keyboard/mouse input, so a character a bot is
// playing idles out after InactiveTimeBeforeLogout (1200 s) and logs itself off
// mid-fight - Lucy, three times on 2026-09-27, each 1206 s after the window lost
// focus. Keep the idle clock fresh while in the world (PreventIdleLogoff).
if (Plugins.EngineSettings.PreventIdleLogoff && idle > IdleRefreshAfterSec && TryRefreshLastInput())
{
long nowMs = Environment.TickCount64;
if (nowMs - _lastIdleRefreshLogMs > 600_000)
{
_lastIdleRefreshLogMs = nowMs;
RynthLog.Info($"LogoffProbe: reset the client's idle clock at {idle:0}s idle so the {limit:0.#}s idle auto-logoff can't fire (PreventIdleLogoff; logged at most every 10 min). {DescribeFocus()}");
}
_prevIdle = 0;
return;
}
while (_idleMilestoneIdx < IdleMilestonesBefore.Length && idle >= limit - IdleMilestonesBefore[_idleMilestoneIdx])
{
RynthLog.Info($"LogoffProbe: client input idle {idle:0}s - the client auto-logs-off at {limit:0.#}s ({limit - idle:0}s left). {DescribeFocus()}");
_idleMilestoneIdx++;
}
if (!_idleOverLogged && idle > limit)
{
_idleOverLogged = true;
RynthLog.Warn($"LogoffProbe: client input idle {idle:0.0}s is over the {limit:0.#}s threshold - ClientUISystem::UseTime should call LogOffCharacter(0) now. {DescribeFocus()}");
}
}
catch { }
}
private const double IdleRefreshAfterSec = 120;
private static long _lastIdleRefreshLogMs = -600_000;
/// <summary>Sets the input manager's last-input time to Timer::cur_time, as real input
/// would. Game thread only (called from SampleIdleOnGameThread).</summary>
private static bool TryRefreshLastInput()
{
if (_curTimeVa == IntPtr.Zero || _inputMgrSlotVa == IntPtr.Zero)
return false;
IntPtr mgr = *(IntPtr*)_inputMgrSlotVa;
if (mgr == IntPtr.Zero)
return false;
int off = ResolveLastInputOffset(mgr);
if (off < 0)
return false;
*(double*)((byte*)mgr + off) = *(double*)_curTimeVa;
return true;
}
/// <summary>Reads the same values ClientUISystem::UseTime compares. Game thread only.</summary>
private static bool TryReadIdle(out double idle, out double limit, out double curTime, out double lastInput)
{
idle = 0; limit = double.NaN; curTime = 0; lastInput = 0;
if (_curTimeVa == IntPtr.Zero || _inputMgrSlotVa == IntPtr.Zero)
return false;
IntPtr mgr = *(IntPtr*)_inputMgrSlotVa;
if (mgr == IntPtr.Zero)
return false;
int off = ResolveLastInputOffset(mgr);
if (off < 0)
return false;
curTime = *(double*)_curTimeVa;
lastInput = *(double*)((byte*)mgr + off);
if (_idleLimitVa != IntPtr.Zero)
limit = *(double*)_idleLimitVa;
idle = curTime - lastInput;
return true;
}
/// <summary>
/// ClientUISystem::UseTime gets the last-input time from vtable slot 5 of the input
/// manager, CInputManager::GetLastInputTimestamp, which is "fld qword [ecx+off]; ret".
/// Read the field offset out of that body so the probe never guesses a layout.
/// </summary>
private static int ResolveLastInputOffset(IntPtr mgr)
{
if (_inputOffsetProbed)
return _lastInputOffset;
_inputOffsetProbed = true;
long vtbl = (*(IntPtr*)mgr).ToInt64();
if (vtbl < _acBase || vtbl + 0x18 > _acBase + _acImageSize)
{
RynthLog.Compat($"LogoffProbe: input manager vtable 0x{vtbl:X8} is outside acclient - idle probe off.");
return -1;
}
long fn = (*(IntPtr*)(vtbl + 0x14)).ToInt64();
if (fn < _acTextLo || fn + 4 > _acTextHi)
{
RynthLog.Compat($"LogoffProbe: GetLastInputTimestamp 0x{fn:X8} is outside acclient .text - idle probe off.");
return -1;
}
byte* p = (byte*)fn;
if (p[0] == 0xDD && p[1] == 0x41 && p[3] == 0xC3)
{
_lastInputOffset = p[2];
RynthLog.Compat($"LogoffProbe: CInputManager last-input time at +0x{_lastInputOffset:X2} (GetLastInputTimestamp @ 0x{fn:X8}).");
}
else
{
RynthLog.Compat($"LogoffProbe: GetLastInputTimestamp @ 0x{fn:X8} has unexpected bytes {p[0]:X2} {p[1]:X2} {p[2]:X2} {p[3]:X2} - idle probe off.");
}
return _lastInputOffset;
}
// ── Ring buffers ─────────────────────────────────────────────────────────
private const uint WM_DESTROY = 0x0002;
private const uint WM_ACTIVATE = 0x0006;
private const uint WM_SETFOCUS = 0x0007;
private const uint WM_KILLFOCUS = 0x0008;
private const uint WM_CLOSE = 0x0010;
private const uint WM_QUERYENDSESSION = 0x0011;
private const uint WM_ENDSESSION = 0x0016;
private const uint WM_ACTIVATEAPP = 0x001C;
private const uint WM_KEYDOWN = 0x0100;
private const uint WM_KEYUP = 0x0101;
private const uint WM_SYSKEYDOWN = 0x0104;
private const uint WM_SYSKEYUP = 0x0105;
private const uint WM_SYSCOMMAND = 0x0112;
private const uint WM_MOUSEMOVE = 0x0200;
private const uint WM_LBUTTONDOWN = 0x0201;
private const uint WM_RBUTTONDOWN = 0x0204;
private const uint WM_MBUTTONDOWN = 0x0207;
private const uint WM_XBUTTONDOWN = 0x020B;
private struct MsgEntry
{
public long Ms;
public uint Msg;
public int WParam;
public int LParam;
public bool Synthetic;
}
private struct ChatEntry
{
public long Ms;
public string Source;
public string Text;
}
private const int MsgRingSize = 24;
private const int ChatRingSize = 16;
private static readonly MsgEntry[] _msgRing = new MsgEntry[MsgRingSize];
private static readonly ChatEntry[] _chatRing = new ChatEntry[ChatRingSize];
private static int _msgCount;
private static int _chatCount;
private static readonly object _ringLock = new();
private static long _lastMouseMoveMs;
private static long _lastRealKeyMs;
private static long _lastRealClickMs;
private static long _lastKillFocusMs;
private static long _lastSetFocusMs;
/// <summary>
/// Records an input/focus/close message seen by the game WndProc subclass
/// (<paramref name="synthetic"/> = false) or sent by the engine through
/// Win32Backend.SendToGameWndProc (true). Cheap filter first; never throws.
/// </summary>
internal static void RecordWndMsg(uint msg, IntPtr wParam, IntPtr lParam, bool synthetic)
{
try
{
long now;
switch (msg)
{
case WM_MOUSEMOVE:
if (!synthetic) Volatile.Write(ref _lastMouseMoveMs, Environment.TickCount64);
return;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
// Skip auto-repeat (bit 30 = key was already down) so a held key can't flood the ring.
if (((long)lParam & 0x40000000) != 0) return;
now = Environment.TickCount64;
if (!synthetic) Volatile.Write(ref _lastRealKeyMs, now);
break;
case WM_KEYUP:
case WM_SYSKEYUP:
now = Environment.TickCount64;
if (!synthetic) Volatile.Write(ref _lastRealKeyMs, now);
break;
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_XBUTTONDOWN:
now = Environment.TickCount64;
if (!synthetic) Volatile.Write(ref _lastRealClickMs, now);
break;
case WM_SETFOCUS:
now = Environment.TickCount64;
Volatile.Write(ref _lastSetFocusMs, now);
break;
case WM_KILLFOCUS:
now = Environment.TickCount64;
Volatile.Write(ref _lastKillFocusMs, now);
break;
case WM_DESTROY:
case WM_ACTIVATE:
case WM_CLOSE:
case WM_QUERYENDSESSION:
case WM_ENDSESSION:
case WM_ACTIVATEAPP:
case WM_SYSCOMMAND:
now = Environment.TickCount64;
break;
default:
return;
}
lock (_ringLock)
{
ref MsgEntry e = ref _msgRing[_msgCount % MsgRingSize];
e.Ms = now;
e.Msg = msg;
e.WParam = (int)(long)wParam;
e.LParam = (int)(long)lParam;
e.Synthetic = synthetic;
_msgCount++;
}
}
catch { }
}
/// <summary>Records a chat line passing through one of the engine's chat paths.</summary>
internal static void RecordChat(string source, string? text)
{
try
{
if (text == null) return;
string t = text.Length > 120 ? text.Substring(0, 120) + "..." : text;
lock (_ringLock)
{
ref ChatEntry e = ref _chatRing[_chatCount % ChatRingSize];
e.Ms = Environment.TickCount64;
e.Source = source;
e.Text = t;
_chatCount++;
}
}
catch { }
}
// ── Context dump ─────────────────────────────────────────────────────────
[DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] private static extern IntPtr GetFocus();
[DllImport("user32.dll")] private static extern IntPtr GetActiveWindow();
[DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd);
[DllImport("kernel32.dll")] private static extern void GetCurrentThreadStackLimits(out IntPtr lowLimit, out IntPtr highLimit);
private static string Ago(long ms, long now)
=> ms == 0 ? "never" : $"{(now - ms) / 1000.0:0.0}s ago";
private static string DescribeFocus()
{
try
{
IntPtr game = ImGuiBackend.Win32Backend.GameHwnd;
long now = Environment.TickCount64;
IntPtr fg = GetForegroundWindow();
int fgGame = game != IntPtr.Zero && fg == game ? 1 : 0;
int focusGame = game != IntPtr.Zero && GetFocus() == game ? 1 : 0;
int iconic = game != IntPtr.Zero && IsIconic(game) ? 1 : 0;
return $"fg={fgGame} focus={focusGame} min={iconic} killfocus={Ago(Volatile.Read(ref _lastKillFocusMs), now)} setfocus={Ago(Volatile.Read(ref _lastSetFocusMs), now)}";
}
catch { return "fg=?"; }
}
private static void DumpContext(string trigger)
{
try
{
long now = Environment.TickCount64;
DateTime wallNow = DateTime.Now;
var sb = new StringBuilder();
sb.Append($"LogoffProbe: ---- context dump ({trigger}) ----");
if (TryReadIdle(out double idle, out double limit, out double cur, out double last))
sb.Append($"\n idle: Timer::cur_time={cur:0.000} lastInput={last:0.000} idle={idle:0.0}s threshold={limit:0.#}s");
else
sb.Append("\n idle: unavailable");
IntPtr game = ImGuiBackend.Win32Backend.GameHwnd;
IntPtr fg = GetForegroundWindow();
sb.Append($"\n window: game=0x{game.ToInt64():X} foreground=0x{fg.ToInt64():X} active=0x{GetActiveWindow().ToInt64():X} focus=0x{GetFocus().ToInt64():X} minimized={(game != IntPtr.Zero && IsIconic(game) ? 1 : 0)}");
sb.Append($"\n engine-seen input: key={Ago(Volatile.Read(ref _lastRealKeyMs), now)} click={Ago(Volatile.Read(ref _lastRealClickMs), now)} mousemove={Ago(Volatile.Read(ref _lastMouseMoveMs), now)} killfocus={Ago(Volatile.Read(ref _lastKillFocusMs), now)} setfocus={Ago(Volatile.Read(ref _lastSetFocusMs), now)}");
sb.Append("\n acclient stack sweep (may include stale frames):");
AppendStackSweep(sb);
MsgEntry[] msgs;
ChatEntry[] chats;
int msgCount, chatCount;
lock (_ringLock)
{
msgs = (MsgEntry[])_msgRing.Clone();
chats = (ChatEntry[])_chatRing.Clone();
msgCount = _msgCount;
chatCount = _chatCount;
}
int mn = Math.Min(msgCount, MsgRingSize);
sb.Append($"\n last {mn} window messages (of {msgCount}):");
for (int i = msgCount - mn; i < msgCount; i++)
{
MsgEntry e = msgs[i % MsgRingSize];
sb.Append($"\n {Clock(wallNow, now, e.Ms)} {(e.Synthetic ? "synth " : "")}{DescribeMsg(e)}");
}
int cn = Math.Min(chatCount, ChatRingSize);
sb.Append($"\n last {cn} engine chat lines (of {chatCount}):");
for (int i = chatCount - cn; i < chatCount; i++)
{
ChatEntry e = chats[i % ChatRingSize];
sb.Append($"\n {Clock(wallNow, now, e.Ms)} [{e.Source}] '{e.Text}'");
}
sb.Append("\nLogoffProbe: ---- end context dump ----");
RynthLog.Info(sb.ToString());
}
catch (Exception ex)
{
try { RynthLog.Info($"LogoffProbe: context dump failed: {ex.GetType().Name}: {ex.Message}"); } catch { }
}
}
private static string Clock(DateTime wallNow, long now, long ms)
=> $"{wallNow.AddMilliseconds(-(now - ms)):HH:mm:ss.fff} ({(ms - now) / 1000.0:0.0}s)";
private static string DescribeMsg(MsgEntry e)
{
switch (e.Msg)
{
case WM_KEYDOWN: return $"WM_KEYDOWN vk=0x{e.WParam & 0xFF:X2}{(IsExtended(e.LParam) ? " ext" : "")}";
case WM_KEYUP: return $"WM_KEYUP vk=0x{e.WParam & 0xFF:X2}{(IsExtended(e.LParam) ? " ext" : "")}";
case WM_SYSKEYDOWN: return $"WM_SYSKEYDOWN vk=0x{e.WParam & 0xFF:X2} alt={((e.LParam >> 29) & 1)}";
case WM_SYSKEYUP: return $"WM_SYSKEYUP vk=0x{e.WParam & 0xFF:X2} alt={((e.LParam >> 29) & 1)}";
case WM_LBUTTONDOWN: return $"WM_LBUTTONDOWN ({(short)(e.LParam & 0xFFFF)},{(short)((e.LParam >> 16) & 0xFFFF)})";
case WM_RBUTTONDOWN: return $"WM_RBUTTONDOWN ({(short)(e.LParam & 0xFFFF)},{(short)((e.LParam >> 16) & 0xFFFF)})";
case WM_MBUTTONDOWN: return "WM_MBUTTONDOWN";
case WM_XBUTTONDOWN: return "WM_XBUTTONDOWN";
case WM_SETFOCUS: return $"WM_SETFOCUS from=0x{e.WParam:X}";
case WM_KILLFOCUS: return $"WM_KILLFOCUS to=0x{e.WParam:X}";
case WM_ACTIVATE: return $"WM_ACTIVATE state={e.WParam & 0xFFFF} other=0x{e.LParam:X}";
case WM_ACTIVATEAPP: return $"WM_ACTIVATEAPP active={e.WParam} tid={e.LParam}";
case WM_CLOSE: return "WM_CLOSE";
case WM_DESTROY: return "WM_DESTROY";
case WM_QUERYENDSESSION: return "WM_QUERYENDSESSION";
case WM_ENDSESSION: return $"WM_ENDSESSION ending={e.WParam}";
case WM_SYSCOMMAND: return $"WM_SYSCOMMAND cmd=0x{e.WParam & 0xFFF0:X4}{((e.WParam & 0xFFF0) == 0xF060 ? " (SC_CLOSE)" : "")}";
default: return $"msg=0x{e.Msg:X4} w=0x{e.WParam:X} l=0x{e.LParam:X}";
}
}
private static bool IsExtended(int lParam) => ((lParam >> 24) & 1) != 0;
/// <summary>
/// Scans this thread's stack above the current frame for values that are return
/// addresses into acclient .text (preceded by a call instruction). AC is built with
/// frame-pointer omission, so the EBP walk in LogCaller stops at the first AC frame;
/// this recovers the AC callers above it. Stale values from earlier calls can appear.
/// </summary>
private static void AppendStackSweep(StringBuilder sb)
{
int local = 0;
long start = (long)(nint)(&local);
GetCurrentThreadStackLimits(out IntPtr lowLimit, out IntPtr highLimit);
long high = highLimit.ToInt64();
if (start < lowLimit.ToInt64() || start >= high)
{
sb.Append(" <stack limits unavailable>");
return;
}
long end = Math.Min(high, start + 0x3000);
int hits = 0;
for (long a = (start + 3) & ~3L; a + 4 <= end && hits < 16; a += 4)
{
long v = *(uint*)a;
if (v < _acTextLo + 8 || v >= _acTextHi)
continue;
if (!LooksLikeReturnAddress((byte*)v))
continue;
hits++;
sb.Append($" {DescribeAcclientAddress((IntPtr)v)}");
}
if (hits == 0)
sb.Append(" <none>");
}
private static bool LooksLikeReturnAddress(byte* ret)
{
if (ret[-5] == 0xE8) return true; // call rel32
if (ret[-2] == 0xFF && ((ret[-1] >> 3) & 7) == 2 && (ret[-1] >> 6) == 3) return true; // call reg
if (ret[-3] == 0xFF && ((ret[-2] >> 3) & 7) == 2 && (ret[-2] >> 6) == 1) return true; // call [reg+disp8]
if (ret[-2] == 0xFF && ((ret[-1] >> 3) & 7) == 2 && (ret[-1] >> 6) == 0) return true; // call [reg]
if (ret[-6] == 0xFF && ((ret[-5] >> 3) & 7) == 2 && ((ret[-5] >> 6) == 2 || (ret[-5] & 0xC7) == 0x05)) return true; // call [reg+disp32] / [abs]
return false;
}
private static string DescribeAcclientAddress(IntPtr addr)
{
if (addr == IntPtr.Zero)
return "<no acclient frame>";
int rva = (int)(addr.ToInt64() - _acBase);
string label = LabelForAcclientRva(rva);
return label.Length > 0 ? $"acclient.exe+0x{rva:X}{{{label}}}" : $"acclient.exe+0x{rva:X}";
}
/// <summary>
/// Names the known logoff-related call sites by return-address RVA. Reference client
/// only (labels are off on any other build); the raw module+RVA is always logged.
/// </summary>
internal static string LabelForAcclientRva(int rva)
{
if (!_labelsValid)
return "";
return rva switch
{
// callers of CPlayerSystem::LogOffCharacter
0x166056 => "ClientUISystem::UseTime: idle auto-logoff",
0x0EB0E9 => "gmGamePlayUI::UseTime: logout confirmed in the UI",
0x0EAEC8 => "gmGamePlayUI::EndSession",
0x0EA80F => "gmEpilogueUI ctor",
0x15AD39 => "APIManager::EndCharacterSession: plugin API",
// callers of CPlayerSystem::RequestLogOff
0x1642EE => "CPlayerSystem::LogOffCharacter",
0x163FC6 => "CPlayerSystem::UseTime: deferred request",
// caller of Proto_UI::LogOffCharacter
0x163BC4 => "CPlayerSystem::RequestLogOff",
// callers of CPlayerSystem::ExecuteLogOff
0x15D676 => "server CharacterLogOff 0xF653 handler",
0x1642DC => "CPlayerSystem::LogOffCharacter(immediate)",
// caller of CPlayerSystem::SetLogOffStarted
0x0D7AF8 => "gmSmartBoxUI::UseTime",
// callers of ClientNet::LogOffServer
0x01160C => "Client::Disconnect",
0x012077 => "Client::CleanupNet",
0x145E79 => "ClientNet::ProcessOptionalHeader: server disconnect",
0x145FEC => "ClientNet::RemoveConnection",
_ => "",
};
}
}

View file

@ -6,33 +6,47 @@ using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Hooks the moments when the AC client commits to ending the in-world session, so the
/// engine can close its UI gate before AC starts rebuilding its UIElement tree —
/// touching world data while AC is mid-teardown crashes the client.
/// Hooks the moments when the AC client commits to ending the in-world session.
///
/// We hook both:
/// - <c>CPlayerSystem::ExecuteLogOff(void)</c> — fires when the player has confirmed
/// the logoff prompt and the actual logoff begins. This is the earliest reliable
/// "we're committed to leaving the world" signal. (NOT
/// <c>gmGamePlayUI::RecvNotice_EndCharacterSession</c> — that fires when the user
/// clicks the Exit-to-Character-Selection menu item, BEFORE the confirmation
/// prompt; if we close the UI there and the user clicks "No" on the prompt, the
/// overlay is hidden while gameplay continues.)
/// - <c>gmGamePlayUI::RecvNotice_Logoff(void)</c> — server-driven full logoff
/// notice. Belt-and-braces in case ExecuteLogOff is bypassed in some flow.
/// the logoff prompt and the actual logoff begins.
/// - <c>gmGamePlayUI::RecvNotice_Logoff(void)</c> — server-driven full logoff notice.
///
/// Either one raises <see cref="LogoutComplete"/> once per logout cycle.
///
/// Public symbol addresses taken from Chorizite's acclient.map:
/// - CPlayerSystem::ExecuteLogOff: file offset 0x0015D4A0, VA 0x0055E4A0
/// - RecvNotice_Logoff: file offset 0x000EBBA0, VA 0x004ECBA0
/// (Standard 0x56D000 acclient.exe build.)
/// Both addresses are now resolved via HookResolver — pattern-scan first,
/// fallback VA second, UNAVAILABLE if neither works.
/// </summary>
internal static class LogoutLifecycleHooks
{
private const int ExpectedImageSize = 0x56D000;
private const int ExecuteLogOffFileOffset = 0x0015D4A0;
private const int RecvNoticeLogoffFileOffset = 0x000EBBA0;
// Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth.
private const int ExecuteLogOffFallbackVa = 0x0055E4A0;
private const int RecvNoticeLogoffFallbackVa = 0x004ECBA0;
// CPlayerSystem::ExecuteLogOff(void)
// Two consecutive 'mov byte ptr [esi+0x213],bl' / 'mov byte ptr [esi+0x221],bl'
// — those CPlayerSystem flags clears are unique anchor.
private static readonly byte?[] ExecuteLogOffPattern =
[
0x53, 0x56, 0x8B, 0xF1, 0x33, 0xDB, 0x88, 0x9E,
0x13, 0x02, 0x00, 0x00, 0x88, 0x9E, 0x21, 0x02,
0x00, 0x00,
0x8B, 0x0D, null, null, null, null, // mov ecx, ds:[imm32]
0xA1, null, null, null, null, // mov eax, ds:[imm32]
0x89, 0x86, 0x00, 0x02, 0x00, 0x00
];
// gmGamePlayUI::RecvNotice_Logoff(void)
// 0x90 stack frame, sets two booleans at +0x2D / +0x2E, then E8 to a helper.
private static readonly byte?[] RecvNoticeLogoffPattern =
[
0x81, 0xEC, 0x90, 0x00, 0x00, 0x00, 0x56, 0x8B,
0xF1, 0xB0, 0x01, 0x8D, 0x4C, 0x24, 0x04, 0x88,
0x46, 0x2D, 0x88, 0x46, 0x2E,
0xE8, null, null, null, null, // call rel32
0xA1, null, null, null, null, // mov eax, ds:[imm32]
0x68, 0x01, 0x00, 0x00, 0x10
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void ThisCallVoidDelegate(IntPtr thisPtr);
@ -51,7 +65,6 @@ internal static class LogoutLifecycleHooks
public static bool HasObservedLogout { get; private set; }
public static string StatusMessage => _statusMessage;
/// <summary>Fires once per logout cycle, after the first observed logout signal returns from its original.</summary>
public static event Action? LogoutComplete;
public static void Initialize()
@ -65,55 +78,52 @@ internal static class LogoutLifecycleHooks
return;
}
int imageSize = textSection.ImageSize;
if (imageSize != ExpectedImageSize)
RynthLog.Compat($"Compat: logout lifecycle hook using unverified acclient image size 0x{imageSize:X} (expected 0x{ExpectedImageSize:X}).");
bool anyHooked = false;
anyHooked |= TryInstallHook(textSection, ExecuteLogOffFileOffset, ExecuteLogOffDetour,
out _executeLogOffAddress, out _executeLogOffDetour, out _originalExecuteLogOff,
"CPlayerSystem::ExecuteLogOff");
anyHooked |= TryInstallHook(textSection, RecvNoticeLogoffFileOffset, RecvNoticeLogoffDetour,
out _logoffAddress, out _recvNoticeLogoffDetour, out _originalRecvNoticeLogoff,
"gmGamePlayUI::RecvNotice_Logoff");
anyHooked |= TryInstall(textSection, "LogoutLifecycle.ExecuteLogOff",
ExecuteLogOffPattern, ExecuteLogOffFallbackVa, ExecuteLogOffDetour,
out _executeLogOffAddress, out _executeLogOffDetour, out _originalExecuteLogOff);
anyHooked |= TryInstall(textSection, "LogoutLifecycle.RecvNotice_Logoff",
RecvNoticeLogoffPattern, RecvNoticeLogoffFallbackVa, RecvNoticeLogoffDetour,
out _logoffAddress, out _recvNoticeLogoffDetour, out _originalRecvNoticeLogoff);
if (anyHooked)
{
IsInstalled = true;
RynthLog.Compat($"Compat: logout lifecycle hook ready - ExecuteLogOff=0x{_executeLogOffAddress.ToInt32():X8} Logoff=0x{_logoffAddress.ToInt32():X8}");
RynthLog.Compat($"LogoutLifecycleHooks: ready (ExecuteLogOff=0x{_executeLogOffAddress.ToInt32():X8}, RecvNotice_Logoff=0x{_logoffAddress.ToInt32():X8}).");
}
}
private static bool TryInstallHook(
AcClientTextSection textSection, int fileOffset, ThisCallVoidDelegate detour,
out IntPtr address, out ThisCallVoidDelegate detourField, out ThisCallVoidDelegate? original,
string name)
private static bool TryInstall(
AcClientTextSection textSection, string name,
byte?[] pattern, int fallbackVa, ThisCallVoidDelegate detour,
out IntPtr address, out ThisCallVoidDelegate detourField, out ThisCallVoidDelegate? original)
{
address = IntPtr.Zero;
detourField = detour;
original = null;
var resolved = HookResolver.Resolve(textSection, name, pattern, fallbackVa);
if (!resolved.Success)
return false;
try
{
address = new IntPtr(textSection.TextBaseVa + fileOffset);
detourField = detour;
address = resolved.Address;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(detourField);
original = Marshal.GetDelegateForFunctionPointer<ThisCallVoidDelegate>(MinHook.HookCreate(address, detourPtr));
original = Marshal.GetDelegateForFunctionPointer<ThisCallVoidDelegate>(
MinHook.HookCreate(address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(address);
_statusMessage = $"Hooked {name} @ 0x{address.ToInt32():X8}.";
return true;
}
catch (Exception ex)
{
address = IntPtr.Zero;
detourField = detour;
original = null;
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: {name} hook failed - {ex.Message}");
RynthLog.Compat($"LogoutLifecycleHooks: {name} install threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
/// <summary>Resets the observation flag so the next logout-class notice fires <see cref="LogoutComplete"/> again.</summary>
public static void ResetObservation()
{
HasObservedLogout = false;
@ -121,32 +131,79 @@ internal static class LogoutLifecycleHooks
private static void ExecuteLogOffDetour(IntPtr thisPtr)
{
RecursionGuard.Tick("LogoutLifecycleHooks.ExecuteLogOff");
if (!HasObservedLogout)
RynthLog.Compat("Compat: CPlayerSystem::ExecuteLogOff detour entered.");
{
RynthLog.Compat("LogoutLifecycleHooks: ExecuteLogOff detour entered.");
LogCaller("ExecuteLogOff");
LogoffOriginProbe.OnLogoffCompleted("CPlayerSystem::ExecuteLogOff");
}
try { _originalExecuteLogOff!(thisPtr); }
catch { /* original must run */ }
catch (Exception ex) { try { RynthLog.Compat($"LogoutLifecycleHooks: ExecuteLogOff original threw {ex.GetType().Name}: {ex.Message}"); } catch { } }
RaiseLogoutCompleteOnce("CPlayerSystem::ExecuteLogOff");
}
private static void RecvNoticeLogoffDetour(IntPtr thisPtr)
{
RecursionGuard.Tick("LogoutLifecycleHooks.RecvNoticeLogoff");
if (!HasObservedLogout)
RynthLog.Compat("Compat: RecvNotice_Logoff detour entered.");
{
RynthLog.Compat("LogoutLifecycleHooks: RecvNotice_Logoff detour entered.");
LogCaller("RecvNotice_Logoff");
LogoffOriginProbe.OnLogoffCompleted("gmGamePlayUI::RecvNotice_Logoff");
}
try { _originalRecvNoticeLogoff!(thisPtr); }
catch { /* original must run */ }
catch (Exception ex) { try { RynthLog.Compat($"LogoutLifecycleHooks: RecvNotice_Logoff original threw {ex.GetType().Name}: {ex.Message}"); } catch { } }
RaiseLogoutCompleteOnce("gmGamePlayUI::RecvNotice_Logoff");
}
[DllImport("kernel32.dll")]
private static extern ushort RtlCaptureStackBackTrace(
uint FramesToSkip, uint FramesToCapture, IntPtr[] BackTrace, out uint BackTraceHash);
/// <summary>
/// Either notice may fire first (a session may receive both — ExecuteLogOff at
/// commit, RecvNotice_Logoff later from the server). Only the first one in a
/// logout cycle should drive the dispatch — subsequent ones are no-ops until
/// <see cref="ResetObservation"/> runs after the next login.
/// Logs who in the client called the logoff, as module+RVA frames. Characters were
/// logging off by themselves (2026-09-27, Lucy, twice mid-route) with no meta, no
/// command and nothing from the server, so the next one needs to say which client
/// code path confirmed it (UI button, chat /logout, something else). x86 EBP walk:
/// deep frames can be unreliable, the first acclient frames are the useful ones.
/// Known logoff call sites get a {label} (LogoffOriginProbe). Returns the first
/// acclient.exe frame (the immediate AC caller), or Zero if none was captured.
/// </summary>
internal static IntPtr LogCaller(string hook, string prefix = "LogoutLifecycleHooks")
{
IntPtr firstAcclient = IntPtr.Zero;
try
{
var frames = new IntPtr[24];
ushort captured = RtlCaptureStackBackTrace(1, (uint)frames.Length, frames, out _);
var sb = new System.Text.StringBuilder($"{prefix}: {hook} caller frames:");
for (int i = 0; i < captured && frames[i] != IntPtr.Zero; i++)
{
string module = ProcessExitHooks.ResolveModule(frames[i], out int rva);
sb.Append($" [{i}] {module}+0x{rva:X}");
if (string.Equals(module, "acclient.exe", StringComparison.OrdinalIgnoreCase))
{
if (firstAcclient == IntPtr.Zero)
firstAcclient = frames[i];
string label = LogoffOriginProbe.LabelForAcclientRva(rva);
if (label.Length > 0)
sb.Append($"{{{label}}}");
}
}
RynthLog.Compat(sb.ToString());
}
catch (Exception ex)
{
try { RynthLog.Compat($"{prefix}: {hook} caller capture failed: {ex.GetType().Name}"); } catch { }
}
return firstAcclient;
}
private static void RaiseLogoutCompleteOnce(string source)
{
if (HasObservedLogout)
@ -154,15 +211,12 @@ internal static class LogoutLifecycleHooks
HasObservedLogout = true;
_statusMessage = $"Logout observed via {source}.";
RynthLog.Compat($"Compat: logout observed via {source} — raising LogoutComplete.");
RynthLog.Compat($"LogoutLifecycleHooks: logout observed via {source} — raising LogoutComplete.");
// Subscribers MUST keep their handler short — this fires on AC's UI thread.
// Long work (plugin teardown, disposing world data, etc.) must be deferred to
// the EndScene queue.
try { LogoutComplete?.Invoke(); }
catch (Exception ex)
{
RynthLog.Compat($"Compat: LogoutComplete handler threw {ex.GetType().Name}: {ex.Message}");
RynthLog.Compat($"LogoutLifecycleHooks: handler threw {ex.GetType().Name}: {ex.Message}");
}
}
}

View file

@ -0,0 +1,62 @@
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Tracks which OS thread is AC's main thread, so RynthCore code that's about
/// to call into AC's internals (CACQualities accessors, etc.) can refuse the
/// call from any other thread.
///
/// AC's client is not thread-safe: its internal data structures (qualities
/// hash tables, enchantment lists, object tables) are mutated by the main
/// thread without locking. Reading them from another thread can observe a
/// sub-pointer in the middle of being reassigned, which appears as null and
/// AVs three frames deep inside AC (consistent crash at 0x00416C86 reading
/// [null+0x28] from the DecalCoexistence plugin-tick thread, 2026-05-14).
///
/// Capture: any of our [UnmanagedCallersOnly] detours runs on the thread that
/// called the detoured function. AC's main thread is what invokes
/// SetCombatMode, BusyCount updates, SmartBox/GameEvent dispatch, etc. The
/// first detour to fire after install latches that thread ID; everything
/// after compares against it.
/// </summary>
internal static class MainThreadGuard
{
private static uint _acMainNativeTid;
[DllImport("kernel32.dll")]
private static extern uint GetCurrentThreadId();
/// <summary>
/// Latch the current native thread ID as AC's main thread. Idempotent;
/// only the first caller wins. Safe to call from any [UnmanagedCallersOnly]
/// detour body — those run on whichever thread invoked the detoured AC
/// function, which is AC's main thread for the detours we install.
/// </summary>
public static void RecordIfFirst()
{
if (_acMainNativeTid != 0) return;
uint tid = GetCurrentThreadId();
Interlocked.CompareExchange(ref _acMainNativeTid, tid, 0);
}
/// <summary>
/// True if AC's main thread has been observed AND the calling thread is
/// that thread. Returns false before the main thread is known, so any
/// cross-thread caller fails closed (refuses to enter AC) during early
/// init too.
/// </summary>
public static bool IsOnMainThread()
{
uint mainTid = _acMainNativeTid;
if (mainTid == 0) return false;
return GetCurrentThreadId() == mainTid;
}
/// <summary>
/// Diagnostic accessor — for logging the captured thread ID at startup
/// or in crash reports. Zero if not yet captured.
/// </summary>
public static uint MainThreadId => _acMainNativeTid;
}

View file

@ -139,38 +139,77 @@ internal static class MovementActionHooks
}
}
// Light counters so we can see in the log that the bot's movement
// commands are actually reaching AC and what AC says about each call.
// Logged at Compat every 8th call after the first 3, so a busy patrol
// loop doesn't flood the log but a one-shot test still shows up.
private static int _doMovementCalls;
private static int _stopMovementCalls;
private static int _jumpCalls;
private static int _autonomyCalls;
private static bool ShouldLog(int n) => n <= 3 || (n & 0x7) == 0;
public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = HoldKeyRun)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueDoMovement(motion, speed, holdKey);
int n = System.Threading.Interlocked.Increment(ref _doMovementCalls);
if (_doMovement == null)
{
if (ShouldLog(n))
RynthLog.Compat($"Move: DoMovement(motion=0x{motion:X8}, speed={speed:0.00}, holdKey={holdKey}) #{n} — delegate null (probe failed).");
return false;
}
try
{
return _doMovement(motion, speed, holdKey);
bool ok = _doMovement(motion, speed, holdKey);
if (ShouldLog(n))
RynthLog.Compat($"Move: DoMovement(motion=0x{motion:X8}, speed={speed:0.00}, holdKey={holdKey}) #{n} -> {ok}");
return ok;
}
catch
catch (Exception ex)
{
if (ShouldLog(n))
RynthLog.Compat($"Move: DoMovement(motion=0x{motion:X8}) #{n} threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
public static bool StopMovement(uint motion, int holdKey = HoldKeyRun)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueStopMovement(motion, holdKey);
int n = System.Threading.Interlocked.Increment(ref _stopMovementCalls);
if (_stopMovement == null)
{
if (ShouldLog(n))
RynthLog.Compat($"Move: StopMovement(motion=0x{motion:X8}, holdKey={holdKey}) #{n} — delegate null.");
return false;
}
try
{
return _stopMovement(motion, holdKey);
bool ok = _stopMovement(motion, holdKey);
if (ShouldLog(n))
RynthLog.Compat($"Move: StopMovement(motion=0x{motion:X8}, holdKey={holdKey}) #{n} -> {ok}");
return ok;
}
catch
catch (Exception ex)
{
if (ShouldLog(n))
RynthLog.Compat($"Move: StopMovement(motion=0x{motion:X8}) #{n} threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
public static bool JumpNonAutonomous(float extent)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueJump(extent);
if (_jumpNonAutonomous == null)
return false;

View file

@ -8,9 +8,15 @@ namespace RynthCore.Engine.Compatibility;
internal static class MultiClientHooks
{
private const int ExpectedImageSize = 0x56D000;
private const int IsAlreadyRunningVa = 0x004122A0;
private const int OpenDataFileVa = 0x00675920;
private const uint OpenDataFileSharedAccessFlag = 0x4;
private const int IsAlreadyRunningFallbackVa = 0x004122A0;
private const int OpenDataFileFallbackVa = 0x00675920;
// OpenDataFile's prologue tests bit 1 (value 0x2) of openFlags:
// and cl, 2
// cmp cl, 2
// That's the bit AC's code dispatches on for "shared access" — the prior
// value 0x4 was a misread of the byte sequence. Decal's coexisting clients
// open with bit 1 set; matching that lets us share with their handles.
private const uint OpenDataFileSharedAccessFlag = 0x2;
private static readonly byte?[] IsAlreadyRunningSignature =
[
@ -79,25 +85,6 @@ internal static class MultiClientHooks
if (textSection.ImageSize != ExpectedImageSize)
RynthLog.Verbose($"Compat: multi-client hook using unverified acclient image size 0x{textSection.ImageSize:X} (expected 0x{ExpectedImageSize:X}).");
int funcOff = IsAlreadyRunningVa - textSection.TextBaseVa;
if (funcOff < 0 || funcOff + IsAlreadyRunningSignature.Length > textSection.Bytes.Length)
{
_statusMessage = $"Client::IsAlreadyRunning VA 0x{IsAlreadyRunningVa:X8} is outside the readable text window.";
RynthLog.Compat($"Compat: multi-client hook failed - {_statusMessage}");
return;
}
for (int i = 0; i < IsAlreadyRunningSignature.Length; i++)
{
byte? expected = IsAlreadyRunningSignature[i];
if (expected.HasValue && textSection.Bytes[funcOff + i] != expected.Value)
{
_statusMessage = $"Client::IsAlreadyRunning signature mismatch at 0x{IsAlreadyRunningVa + i:X8}.";
RynthLog.Compat($"Compat: multi-client hook failed - {_statusMessage}");
return;
}
}
TryInstallIsAlreadyRunningHook(textSection);
TryInstallOpenDataFileHook(textSection);
@ -109,7 +96,7 @@ internal static class MultiClientHooks
}
if (IsInstalled)
_statusMessage = $"Hooked Client::IsAlreadyRunning @ 0x{IsAlreadyRunningVa:X8} and CLBlockAllocator::OpenDataFile @ 0x{OpenDataFileVa:X8}.";
_statusMessage = $"Hooked Client::IsAlreadyRunning @ 0x{_targetAddress.ToInt32():X8} and CLBlockAllocator::OpenDataFile @ 0x{_openDataFileAddress.ToInt32():X8} (share flag 0x2).";
else
_statusMessage = $"Partial install. alreadyRunning={IsAlreadyRunningInstalled}, dataFile={OpenDataFileInstalled}.";
}
@ -122,66 +109,60 @@ internal static class MultiClientHooks
private static void TryInstallIsAlreadyRunningHook(AcClientTextSection textSection)
{
int funcOff = IsAlreadyRunningVa - textSection.TextBaseVa;
if (funcOff < 0 || funcOff + IsAlreadyRunningSignature.Length > textSection.Bytes.Length)
{
RynthLog.Compat($"Compat: multi-client hook unavailable - Client::IsAlreadyRunning VA 0x{IsAlreadyRunningVa:X8} is outside the readable text window.");
var resolved = HookResolver.Resolve(textSection, "MultiClientHooks.Client::IsAlreadyRunning",
IsAlreadyRunningSignature, IsAlreadyRunningFallbackVa);
if (!resolved.Success)
return;
}
for (int i = 0; i < IsAlreadyRunningSignature.Length; i++)
try
{
byte? expected = IsAlreadyRunningSignature[i];
if (expected.HasValue && textSection.Bytes[funcOff + i] != expected.Value)
{
RynthLog.Compat($"Compat: multi-client hook unavailable - Client::IsAlreadyRunning signature mismatch at 0x{IsAlreadyRunningVa + i:X8}.");
return;
}
_targetAddress = resolved.Address;
_detour = IsAlreadyRunningDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_detour);
_originalIsAlreadyRunning = Marshal.GetDelegateForFunctionPointer<IsAlreadyRunningDelegate>(
MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
IsAlreadyRunningInstalled = true;
RynthLog.Compat($"MultiClientHooks: IsAlreadyRunning hook ready @ 0x{_targetAddress.ToInt32():X8}.");
}
catch (Exception ex)
{
RynthLog.Compat($"MultiClientHooks: IsAlreadyRunning install threw {ex.GetType().Name}: {ex.Message}");
}
_targetAddress = new IntPtr(IsAlreadyRunningVa);
_detour = IsAlreadyRunningDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_detour);
_originalIsAlreadyRunning = Marshal.GetDelegateForFunctionPointer<IsAlreadyRunningDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
IsAlreadyRunningInstalled = true;
RynthLog.Verbose($"Compat: multi-client hook ready - IsAlreadyRunning=0x{IsAlreadyRunningVa:X8}");
}
private static void TryInstallOpenDataFileHook(AcClientTextSection textSection)
{
int funcOff = OpenDataFileVa - textSection.TextBaseVa;
if (funcOff < 0 || funcOff + OpenDataFileSignature.Length > textSection.Bytes.Length)
{
RynthLog.Compat($"Compat: multi-client data-file hook unavailable - CLBlockAllocator::OpenDataFile VA 0x{OpenDataFileVa:X8} is outside the readable text window.");
var resolved = HookResolver.Resolve(textSection, "MultiClientHooks.CLBlockAllocator::OpenDataFile",
OpenDataFileSignature, OpenDataFileFallbackVa);
if (!resolved.Success)
return;
}
for (int i = 0; i < OpenDataFileSignature.Length; i++)
try
{
byte? expected = OpenDataFileSignature[i];
if (expected.HasValue && textSection.Bytes[funcOff + i] != expected.Value)
{
RynthLog.Compat($"Compat: multi-client data-file hook unavailable - CLBlockAllocator::OpenDataFile signature mismatch at 0x{OpenDataFileVa + i:X8}.");
return;
}
_openDataFileAddress = resolved.Address;
_openDataFileDetour = OpenDataFileDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_openDataFileDetour);
_originalOpenDataFile = Marshal.GetDelegateForFunctionPointer<OpenDataFileDelegate>(
MinHook.HookCreate(_openDataFileAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_openDataFileAddress);
OpenDataFileInstalled = true;
RynthLog.Compat($"MultiClientHooks: OpenDataFile hook ready @ 0x{_openDataFileAddress.ToInt32():X8}.");
}
catch (Exception ex)
{
RynthLog.Compat($"MultiClientHooks: OpenDataFile install threw {ex.GetType().Name}: {ex.Message}");
}
_openDataFileAddress = new IntPtr(OpenDataFileVa);
_openDataFileDetour = OpenDataFileDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_openDataFileDetour);
_originalOpenDataFile = Marshal.GetDelegateForFunctionPointer<OpenDataFileDelegate>(MinHook.HookCreate(_openDataFileAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_openDataFileAddress);
OpenDataFileInstalled = true;
RynthLog.Verbose($"Compat: multi-client data-file hook ready - CLBlockAllocator::OpenDataFile=0x{OpenDataFileVa:X8}");
}
private static byte IsAlreadyRunningDetour(IntPtr thisPtr)
{
// Skip the original entirely: it has a side-effect MessageBox path
// that surfaces the "client is already running on this machine" dialog
// even when we'd later override its return value, so calling it makes
// things worse. Returning 0 unconditionally was the original design.
return 0;
}

View file

@ -16,35 +16,35 @@ internal readonly record struct CreatureVitals(
/// </summary>
internal static class ObjectQualityCache
{
private static readonly Dictionary<IntPtr, uint> _maxHealthByPtr = new();
// NOTE: a former _maxHealthByPtr (keyed by reusable CWeenieObject heap
// pointers, populated per stat-update from an UnmanagedCallersOnly detour)
// was removed 2026-06-11: it was write-only — zero readers — pure
// allocation churn in a detour plus an unbounded pointer-keyed dictionary.
private static readonly Dictionary<uint, CreatureVitals> _vitalsByObjectId = new();
private static readonly object _lock = new();
public static void SetMaxHealth(IntPtr objectPtr, uint maxHealth)
{
if (objectPtr == IntPtr.Zero)
return;
lock (_lock)
_maxHealthByPtr[objectPtr] = maxHealth;
}
public static bool TryGetMaxHealth(IntPtr objectPtr, out uint maxHealth)
{
if (objectPtr == IntPtr.Zero)
{
maxHealth = 0;
return false;
}
lock (_lock)
return _maxHealthByPtr.TryGetValue(objectPtr, out maxHealth);
}
// Bound the cache: ids accumulate for the whole session otherwise. The
// cache is advisory (resolvers fall back to ratio-only); a rare wholesale
// clear is cheaper and safer than LRU bookkeeping inside detour paths.
private const int MaxEntries = 4096;
public static void SetCreatureVitals(uint objectId, CreatureVitals vitals)
{
if (objectId == 0)
return;
lock (_lock)
{
if (_vitalsByObjectId.Count >= MaxEntries && !_vitalsByObjectId.ContainsKey(objectId))
_vitalsByObjectId.Clear();
_vitalsByObjectId[objectId] = vitals;
}
}
/// <summary>Drop all cached vitals at logout — object ids don't survive the session.</summary>
public static void ClearSession()
{
lock (_lock)
_vitalsByObjectId.Clear();
}
public static bool TryGetCreatureVitals(uint objectId, out CreatureVitals vitals)

View file

@ -0,0 +1,154 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Reads per-character OnLogin chat commands from the launcher's
/// LaunchContextRecord (written per-PID under
/// %APPDATA%\RynthCore\launch_contexts\) and dispatches them via
/// <see cref="ChatCommandDispatcher"/> after AC's
/// <c>SendLoginCompleteNotification</c> fires.
///
/// Timing model mirrors Thwargle's:
/// 1. Wait for the engine's LoginComplete signal.
/// 2. Sleep <c>OnLoginWaitMs</c> (default 3000 ms — the Thwargle default).
/// 3. Dispatch each command in order with a small inter-command gap so AC's
/// chat parser has time to finish processing before the next arrives.
///
/// Single-shot per process: subscribes once, fires once. Logout/relogin within
/// the same client process is not handled here yet (would require
/// re-subscribing after LoginLifecycleHooks.ResetObservation).
/// </summary>
internal static class OnLoginCommandRunner
{
/// <summary>Inter-command delay. AC's chat parser is synchronous on the
/// main thread but the underlying network handlers benefit from breathing
/// room; 250 ms keeps things human-paced and avoids any chance of the
/// parser dropping a command queued behind a still-processing one.</summary>
private const int InterCommandGapMs = 250;
/// <summary>Fallback wait if the launcher provides 0 / unset value.</summary>
private const int DefaultWaitMs = 3000;
private static int _scheduled;
private static string _statusMessage = "Not initialized.";
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
// One-shot subscription. If LoginLifecycleHooks.ResetObservation gets
// called (logout pipeline), the next LoginComplete will still fire
// through this handler and we'll re-arm via Interlocked.Exchange.
LoginLifecycleHooks.LoginComplete += OnLoginComplete;
_statusMessage = "OnLogin command runner armed.";
RynthLog.Verbose($"Compat: {_statusMessage}");
}
private static void OnLoginComplete()
{
// Guard: only schedule once per LoginComplete edge. If we ever support
// mid-session relogin, ResetForRelogin should clear this flag.
if (Interlocked.Exchange(ref _scheduled, 1) != 0)
return;
try
{
(List<string> commands, int waitMs) = ReadLaunchCommands();
if (commands.Count == 0)
{
RynthLog.Verbose("OnLogin: no commands queued for this PID — skipping dispatch.");
return;
}
int effectiveWait = waitMs > 0 ? waitMs : DefaultWaitMs;
RynthLog.Info($"OnLogin: {commands.Count} command(s) scheduled, first dispatch in {effectiveWait}ms.");
// Fire-and-forget background task. ChatCommandDispatcher.Dispatch
// is safe to call from this ThreadPool thread — NOT because AC's
// chat layer tolerates off-thread calls (it doesn't; that was the
// deep-audit finding #4 bug this comment used to claim), but
// because Dispatch() now self-marshals: an off-thread call
// enqueues onto AcMainThreadQueue and the real native dispatch
// runs on AC's main thread from the EndScene drain.
_ = Task.Run(async () => await DispatchAsync(commands, effectiveWait));
}
catch (Exception ex)
{
RynthLog.Compat($"OnLogin: scheduling failed - {ex.GetType().Name}: {ex.Message}");
}
}
private static async Task DispatchAsync(List<string> commands, int waitMs)
{
try
{
await Task.Delay(waitMs);
for (int i = 0; i < commands.Count; i++)
{
string line = commands[i];
if (string.IsNullOrWhiteSpace(line))
continue;
// Plugin-first dispatch lives inside ChatCommandDispatcher
// itself — see its plugin pre-dispatch step. So we just call
// the unified entry point here.
bool ok = ChatCommandDispatcher.Dispatch(line);
RynthLog.Info($"OnLogin: [{i + 1}/{commands.Count}] '{line}' dispatched={ok}.");
if (i + 1 < commands.Count)
await Task.Delay(InterCommandGapMs);
}
}
catch (Exception ex)
{
RynthLog.Compat($"OnLogin: dispatch loop failed - {ex.GetType().Name}: {ex.Message}");
}
}
private static (List<string> commands, int waitMs) ReadLaunchCommands()
{
string path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"launch_contexts",
$"launch_context_{Environment.ProcessId}.json");
if (!File.Exists(path))
return (new List<string>(), 0);
try
{
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path));
JsonElement root = doc.RootElement;
int waitMs = 0;
if (root.TryGetProperty("OnLoginWaitMs", out JsonElement wEl) && wEl.ValueKind == JsonValueKind.Number)
waitMs = wEl.GetInt32();
var commands = new List<string>();
if (root.TryGetProperty("OnLoginCommands", out JsonElement cmdEl) && cmdEl.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement entry in cmdEl.EnumerateArray())
{
string? line = entry.GetString();
if (!string.IsNullOrWhiteSpace(line))
commands.Add(line);
}
}
return (commands, waitMs);
}
catch (Exception ex)
{
RynthLog.Compat($"OnLogin: launch context parse failed - {ex.Message}");
return (new List<string>(), 0);
}
}
}

View file

@ -21,6 +21,18 @@ internal static class PlayerPhysicsHooks
// The CMotionInterp pointer is the first field of MovementManager.
private const int MovementManagerOffset = 0xC4;
// CMotionInterp +0x80 = head of the sequenced/one-shot motion node list
// (singly-linked, head=+0x80 / tail=+0x84; nodes popped+heap-freed as each
// motion completes — confirmed via offline RE of acclient.exe: ctor 0x529810
// zeroes it, pop sites 0x528AD0/0x528B40, stop-all 0x528A50). A spell-cast
// wind-up/release gesture is queued here while it animates and the list
// empties when it finishes. Locomotion uses the +0x4C/+0x54 channels
// directly and does NOT enqueue here, so a non-empty list is a clean
// "an action gesture is in progress" signal. We read ONLY the head pointer
// value and never dereference it, so this is safe against AC freeing nodes
// on its own thread.
private const int CMotionPendingMotionsHeadOffset = 0x80;
// CMotionInterp::get_max_speed — Chorizite RVA 0x001278C0, our client is +0x1000
// from Chorizite (confirmed via set_heading/get_heading/CommenceJump addresses).
private const int ReferenceGetMaxSpeed = 0x005288C0;
@ -98,7 +110,27 @@ internal static class PlayerPhysicsHooks
try
{
// Deep-audit finding #3/#14/#15 pattern (2026-06-18): this is called
// off-thread (plugin/UI, e.g. RynthVision's InspectTerrain from the
// Avalonia UI thread) as well as from the main-thread render path, so
// a torn/freed player pointer must fail closed instead of risking an
// uncatchable NativeAOT AV. Probe every dereference with
// IsReadablePointer before reading it; try/catch alone is not enough.
IntPtr pos = player + PhysicsPositionOffset;
if (!ClientObjectHooks.IsReadablePointer(pos + PositionObjCellIdOffset) ||
!ClientObjectHooks.IsReadablePointer(pos + PositionQwOffset) ||
!ClientObjectHooks.IsReadablePointer(pos + PositionQxOffset) ||
!ClientObjectHooks.IsReadablePointer(pos + PositionQyOffset) ||
!ClientObjectHooks.IsReadablePointer(pos + PositionQzOffset) ||
!ClientObjectHooks.IsReadablePointer(pos + PositionOriginXOffset) ||
!ClientObjectHooks.IsReadablePointer(pos + PositionOriginYOffset) ||
!ClientObjectHooks.IsReadablePointer(pos + PositionOriginZOffset))
{
_statusMessage = "Player position struct not readable.";
return false;
}
objCellId = unchecked((uint)Marshal.ReadInt32(pos + PositionObjCellIdOffset));
qw = ReadFloat(pos + PositionQwOffset);
qx = ReadFloat(pos + PositionQxOffset);
@ -180,11 +212,17 @@ internal static class PlayerPhysicsHooks
/// so it's reliable whenever pose reads work. Does not depend on any
/// hardcoded function VAs.
/// </summary>
private static int _setHeadingCalls;
private static bool ShouldLogHeading(int n) => n <= 3 || (n & 0xF) == 0;
public static bool SetPlayerHeadingDirect(float decalHeadingDeg)
{
int n = System.Threading.Interlocked.Increment(ref _setHeadingCalls);
if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out _, out string failure))
{
_statusMessage = failure;
if (ShouldLogHeading(n))
RynthLog.Compat($"Move: SetPlayerHeadingDirect({decalHeadingDeg:0.0}) #{n} — no player: {failure}");
return false;
}
@ -204,11 +242,15 @@ internal static class PlayerPhysicsHooks
IsInitialized = true;
_statusMessage = "Ready.";
if (ShouldLogHeading(n))
RynthLog.Compat($"Move: SetPlayerHeadingDirect({decalHeadingDeg:0.0}) #{n} -> qw={newQw:0.000} qz={newQz:0.000} (player=0x{player.ToInt32():X8})");
return true;
}
catch (Exception ex)
{
_statusMessage = ex.Message;
if (ShouldLogHeading(n))
RynthLog.Compat($"Move: SetPlayerHeadingDirect({decalHeadingDeg:0.0}) #{n} threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
@ -226,6 +268,16 @@ internal static class PlayerPhysicsHooks
/// </summary>
public static bool LaunchJumpWithMotion(bool shift, bool holdW, bool holdX, bool holdZ, bool holdC)
{
// Deep-audit finding #2 (2026-06-18): this Marshal.WriteInt32's
// directly into CMotionInterp's forward/strafe/turn fields with NO
// thread gate at all — worse than the CommandInterpreterHooks jump
// trio (which at least goes through a thiscall try/catch), since a
// raw write racing AC's own motion-graph tick is a guaranteed torn
// write, not just an AV risk. Reachable off-thread via Jumper.cs's
// ReleaseJump on the Decal-coexistence pump thread.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueLaunchJumpWithMotion(shift, holdW, holdX, holdZ, holdC);
if (!TryGetCMotionInterp(out IntPtr cmi))
{
RynthLog.Compat("LaunchJumpWithMotion: CMotionInterp unavailable");
@ -298,6 +350,34 @@ internal static class PlayerPhysicsHooks
}
}
/// <summary>
/// AC's local cast gate. True when CMotionInterp has a sequenced/one-shot
/// motion queued — i.e. a spell-cast (or other action) gesture is currently
/// animating. Empty queue = idle/ready. Returns the read success (false when
/// the player/CMotionInterp isn't reachable yet — pre-login / between
/// worlds); callers should treat "couldn't read" as "no opinion" and fall
/// back to their own throttle. Reads only the list-head pointer value and
/// never walks it, so it cannot fault on nodes AC frees concurrently.
/// </summary>
public static bool TryGetCastGestureInProgress(out bool inProgress)
{
inProgress = false;
if (!TryGetCMotionInterp(out IntPtr cmi) || cmi == IntPtr.Zero)
return false;
try
{
IntPtr head = Marshal.ReadIntPtr(cmi + CMotionPendingMotionsHeadOffset);
inProgress = head != IntPtr.Zero;
return true;
}
catch
{
return false;
}
}
private static bool TryGetCMotionInterp(out IntPtr cmotionInterp)
{
cmotionInterp = IntPtr.Zero;
@ -327,10 +407,9 @@ internal static class PlayerPhysicsHooks
if (_getMaxSpeed == null)
{
IntPtr ptr = new(ReferenceGetMaxSpeed);
if (!SmartBoxLocator.IsPointerInModule(ptr))
_getMaxSpeed = ResolveBind<GetMaxSpeedDelegate>("PlayerPhysics.GetMaxSpeed", PatGetMaxSpeed, ReferenceGetMaxSpeed);
if (_getMaxSpeed == null)
return false;
_getMaxSpeed = Marshal.GetDelegateForFunctionPointer<GetMaxSpeedDelegate>(ptr);
}
try
@ -418,25 +497,39 @@ internal static class PlayerPhysicsHooks
return BindPhysicsDelegates();
}
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ──────────────
// *Va consts above are FALLBACKs; these signatures (verified unique + landing at the VA
// offline via tools/pe_pattern.py) are the source of truth. GetHeading is a tail-call
// thunk (add ecx,0x50; jmp impl) — 4 bytes suffice for uniqueness. null = wildcard.
private static readonly byte?[] PatGetHeading = [ 0x83, 0xC1, 0x50, 0xE9 ];
private static readonly byte?[] PatSetHeading = [ 0x83, 0xEC, 0x40, 0x56, 0x8B, 0xF1, 0x8D, 0x46 ];
private static readonly byte?[] PatGetMaxSpeed = [ 0x51, 0x56, 0x8B, 0xF1, 0x8B, 0x4E, 0x04, 0x85, 0xC9, 0xC7 ];
private static T? ResolveBind<T>(string name, byte?[] pattern, int fallbackVa) where T : Delegate
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
return null;
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
return r.Success ? Marshal.GetDelegateForFunctionPointer<T>(r.Address) : null;
}
private static bool BindPhysicsDelegates()
{
if (_getHeading != null && _setHeading != null)
return true;
IntPtr getHeadingPtr = new(ReferencePhysicsGetHeading);
IntPtr setHeadingPtr = new(ReferencePhysicsSetHeading);
if (!SmartBoxLocator.IsPointerInModule(getHeadingPtr) || !SmartBoxLocator.IsPointerInModule(setHeadingPtr))
_getHeading = ResolveBind<PhysicsGetHeadingDelegate>("PlayerPhysics.GetHeading", PatGetHeading, ReferencePhysicsGetHeading);
_setHeading = ResolveBind<PhysicsSetHeadingDelegate>("PlayerPhysics.SetHeading", PatSetHeading, ReferencePhysicsSetHeading);
if (_getHeading == null || _setHeading == null)
{
_statusMessage =
$"Physics heading pointers look invalid (get=0x{getHeadingPtr.ToInt32():X8}, set=0x{setHeadingPtr.ToInt32():X8}).";
_getHeading = null;
_setHeading = null;
_statusMessage = "Physics heading addresses failed to resolve.";
RynthLog.Compat($"Compat: player physics heading bind failed - {_statusMessage}");
return false;
}
_getHeading = Marshal.GetDelegateForFunctionPointer<PhysicsGetHeadingDelegate>(getHeadingPtr);
_setHeading = Marshal.GetDelegateForFunctionPointer<PhysicsSetHeadingDelegate>(setHeadingPtr);
RynthLog.Verbose(
$"Compat: player heading hooks ready - get=0x{getHeadingPtr.ToInt32():X8}, set=0x{setHeadingPtr.ToInt32():X8}");
RynthLog.Verbose("Compat: player heading hooks ready (pattern-resolved).");
return true;
}
}

View file

@ -32,6 +32,114 @@ internal static class PlayerVitalsHooks
KnownPlayerQualitiesPtr = ptr;
}
/// <summary>
/// Drops the cached qualities ptr on logout so the next buffed-max inq
/// call can't dereference a freed allocation. Called by PluginManager's
/// logout dispatch.
/// </summary>
internal static void ResetSession()
{
KnownPlayerQualitiesPtr = IntPtr.Zero;
// Creature health is keyed by object id — ids don't survive the
// session, and without this clear the 1024-entry cap filled over a
// long session and every NEW creature was silently never tracked.
lock (_creatureHpLock)
_creatureHp.Clear();
ObjectQualityCache.ClearSession();
}
/// <summary>
/// Re-seed the qualities ptr and the vital snapshot from the live player object
/// without waiting for SendNoticePlayerDescReceived. Used by the engine's
/// hot-reload path: after a reload the new engine's static state is fresh,
/// so KnownPlayerQualitiesPtr starts at zero and AC won't fire the
/// notification again until the player relogs. Returns true if a non-zero
/// qualities ptr was found and applied.
/// </summary>
public static bool TryReseedFromCurrentPlayer()
{
if (!ClientObjectHooks.TryGetPlayerQualitiesPtr(out IntPtr qualitiesPtr) || qualitiesPtr == IntPtr.Zero)
return false;
KnownPlayerQualitiesPtr = qualitiesPtr;
ClientObjectHooks.SetKnownPlayerQualitiesPtr(qualitiesPtr);
try
{
// Struct path first — gives us current health/stamina/mana plus
// a baseline max (treated as a floor, not the truth).
SeedSnapshotFromQualities(qualitiesPtr);
}
catch (Exception ex)
{
RynthLog.Compat($"PlayerVitalsHooks: TryReseedFromCurrentPlayer struct seed threw {ex.GetType().Name}: {ex.Message}");
}
try
{
// Buffed-uint path — what AC actually shows on the vital bars.
// This OVERRIDES the max values from the struct path.
ReseedBuffedMaxFromQualities(qualitiesPtr);
}
catch (Exception ex)
{
RynthLog.Compat($"PlayerVitalsHooks: TryReseedFromCurrentPlayer buffed-max threw {ex.GetType().Name}: {ex.Message}");
}
return true;
}
private static unsafe void ReseedBuffedMaxFromQualities(IntPtr qualitiesPtr)
{
if (qualitiesPtr == IntPtr.Zero || _inqAttribute2ndUint == null)
return;
if (!TryInqUint(qualitiesPtr, MaxHealthType, out uint maxHealth) ||
!TryInqUint(qualitiesPtr, MaxStaminaType, out uint maxStamina) ||
!TryInqUint(qualitiesPtr, MaxManaType, out uint maxMana))
{
return;
}
bool changed = false;
lock (CacheLock)
{
PlayerVitalsSnapshot current = _snapshot;
PlayerVitalsSnapshot updated = current with
{
MaxHealth = maxHealth != 0 ? maxHealth : current.MaxHealth,
MaxStamina = maxStamina != 0 ? maxStamina : current.MaxStamina,
MaxMana = maxMana != 0 ? maxMana : current.MaxMana,
};
if (!EqualityComparer<PlayerVitalsSnapshot>.Default.Equals(current, updated))
{
_snapshot = updated;
changed = true;
}
}
if (changed)
RynthLog.Compat($"Compat: player vitals buffed-max re-seed hp_max={maxHealth} st_max={maxStamina} mn_max={maxMana}");
}
private static unsafe bool TryInqUint(IntPtr qualitiesPtr, uint stype, out uint value)
{
value = 0;
try
{
uint result = 0;
// raw=0 → buffed effective (the same number AC renders on the bars).
int rc = _inqAttribute2ndUint!(qualitiesPtr, stype, &result, 0);
if (rc == 0) return false;
value = result;
return true;
}
catch
{
return false;
}
}
private const int UpdateAttribute2ndVa = 0x00559900;
private const int UpdateAttribute2ndLevelVa = 0x00559920;
private const int PrivateUpdateAttribute2ndVa = 0x00559B20;
@ -41,6 +149,26 @@ internal static class PlayerVitalsHooks
private const int SendNoticePlayerDescReceivedVa = 0x0047A200;
private const int MaxUpdateLogs = 18;
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
// *Va consts above are FALLBACKs; signatures verified unique + landing at the VA offline
// (tools/pe_pattern.py). The 4 Update*Attribute2nd thunks are near-identical templates
// differing only in their call target, so they use LITERAL patterns (trailing byte pins
// the rel32 low byte to stay unique); the rest are wildcarded (null = rel32 operand).
private static readonly byte?[] PatUpdateAttribute2nd = [ 0x8B, 0x44, 0x24, 0x10, 0x8B, 0x54, 0x24, 0x08, 0x50, 0x8B, 0x44, 0x24, 0x08, 0x52, 0x8B, 0x54, 0x24, 0x14, 0x50, 0x52, 0xE8, 0xA7 ];
private static readonly byte?[] PatUpdateAttribute2ndLevel = [ 0x8B, 0x44, 0x24, 0x10, 0x8B, 0x54, 0x24, 0x08, 0x50, 0x8B, 0x44, 0x24, 0x08, 0x52, 0x8B, 0x54, 0x24, 0x14, 0x50, 0x52, 0xE8, 0x07, 0xF1 ];
private static readonly byte?[] PatPrivateUpdateAttribute2nd = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x85, 0xC0, 0x74, 0x08, 0x8B, 0x80, 0xF4, 0x00, 0x00, 0x00, 0xEB, 0x02, 0x33, 0xC0, 0x8B, 0x54, 0x24, 0x0C, 0x52, 0x8B, 0x54, 0x24, 0x0C, 0x50, 0x8B, 0x44, 0x24, 0x0C, 0x50, 0x52, 0xE8, 0x78 ];
private static readonly byte?[] PatPrivateUpdateAttribute2ndLevel = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x85, 0xC0, 0x74, 0x08, 0x8B, 0x80, 0xF4, 0x00, 0x00, 0x00, 0xEB, 0x02, 0x33, 0xC0, 0x8B, 0x54, 0x24, 0x0C, 0x52, 0x8B, 0x54, 0x24, 0x0C, 0x50, 0x8B, 0x44, 0x24, 0x0C, 0x50, 0x52, 0xE8, 0xC8 ];
private static readonly byte?[] PatOnStatUpdatedInt = [ 0x8B, 0x44, 0x24, 0x04, 0x48, 0x3D, 0x97, 0x00 ];
private static readonly byte?[] PatInqAttribute2ndStruct = [ 0x8B, 0x49, 0x60, 0x85, 0xC9, 0x74, 0x13, 0x8B, 0x44, 0x24, 0x08, 0x8B, 0x54, 0x24, 0x04, 0x50, 0x52, 0xE8, null, null, null, null, 0x85, 0xC0, 0x75, 0x05, 0x33, 0xC0, 0xC2, 0x08, 0x00, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xC2, 0x08, 0x00, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x68 ];
private static readonly byte?[] PatSendNoticePlayerDescReceived = [ 0xE8, null, null, null, null, 0x8B, 0x10, 0x68, 0xF0 ];
private static readonly byte?[] PatInqAttribute2ndUint = [ 0x51, 0x53, 0x55, 0x57, 0x8B, 0x7C, 0x24, 0x14 ];
private static IntPtr Resolve(AcClientTextSection text, string name, byte?[] pattern, int fallbackVa)
{
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
return r.Success ? r.Address : IntPtr.Zero;
}
private const uint MaxHealthType = 1;
private const uint HealthType = 2;
private const uint MaxStaminaType = 3;
@ -60,6 +188,9 @@ internal static class PlayerVitalsHooks
private static int _seedLogCount;
private static PlayerVitalsSnapshot _snapshot;
private static InqAttribute2ndStructDelegate? _inqAttribute2ndStruct;
// Raw address of InqAttribute2nd(struct) — passed to the SEH trampoline so a
// monster's partial qualities table can be read without crashing on an AV.
private static IntPtr _inqAttribute2ndStructFnPtr;
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
@ -69,7 +200,7 @@ internal static class PlayerVitalsHooks
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out _))
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
_statusMessage = "acclient.exe not available.";
return;
@ -77,29 +208,33 @@ internal static class PlayerVitalsHooks
try
{
IntPtr updateAttributePtr = new(UpdateAttribute2ndVa);
IntPtr updatePtr = new(UpdateAttribute2ndLevelVa);
IntPtr privateUpdateAttributePtr = new(PrivateUpdateAttribute2ndVa);
IntPtr privateUpdatePtr = new(PrivateUpdateAttribute2ndLevelVa);
IntPtr onStatUpdatedIntPtr = new(OnStatUpdatedIntVa);
IntPtr inqAttribute2ndStructPtr = new(InqAttribute2ndStructVa);
IntPtr sendNoticePlayerDescReceivedPtr = new(SendNoticePlayerDescReceivedVa);
IntPtr updateAttributePtr = Resolve(text, "PlayerVitals.UpdateAttribute2nd", PatUpdateAttribute2nd, UpdateAttribute2ndVa);
IntPtr updatePtr = Resolve(text, "PlayerVitals.UpdateAttribute2ndLevel", PatUpdateAttribute2ndLevel, UpdateAttribute2ndLevelVa);
IntPtr privateUpdateAttributePtr = Resolve(text, "PlayerVitals.PrivateUpdateAttribute2nd", PatPrivateUpdateAttribute2nd, PrivateUpdateAttribute2ndVa);
IntPtr privateUpdatePtr = Resolve(text, "PlayerVitals.PrivateUpdateAttribute2ndLevel", PatPrivateUpdateAttribute2ndLevel, PrivateUpdateAttribute2ndLevelVa);
IntPtr onStatUpdatedIntPtr = Resolve(text, "PlayerVitals.OnStatUpdatedInt", PatOnStatUpdatedInt, OnStatUpdatedIntVa);
IntPtr inqAttribute2ndStructPtr = Resolve(text, "PlayerVitals.InqAttribute2nd_struct", PatInqAttribute2ndStruct, InqAttribute2ndStructVa);
IntPtr sendNoticePlayerDescReceivedPtr = Resolve(text, "PlayerVitals.SendNotice_PlayerDescReceived", PatSendNoticePlayerDescReceived, SendNoticePlayerDescReceivedVa);
if (!SmartBoxLocator.IsPointerInModule(updateAttributePtr) ||
!SmartBoxLocator.IsPointerInModule(updatePtr) ||
!SmartBoxLocator.IsPointerInModule(privateUpdateAttributePtr) ||
!SmartBoxLocator.IsPointerInModule(privateUpdatePtr) ||
!SmartBoxLocator.IsPointerInModule(onStatUpdatedIntPtr) ||
!SmartBoxLocator.IsPointerInModule(inqAttribute2ndStructPtr) ||
!SmartBoxLocator.IsPointerInModule(sendNoticePlayerDescReceivedPtr))
if (updateAttributePtr == IntPtr.Zero || updatePtr == IntPtr.Zero ||
privateUpdateAttributePtr == IntPtr.Zero || privateUpdatePtr == IntPtr.Zero ||
onStatUpdatedIntPtr == IntPtr.Zero || inqAttribute2ndStructPtr == IntPtr.Zero ||
sendNoticePlayerDescReceivedPtr == IntPtr.Zero)
{
_statusMessage =
$"Attribute2nd handlers look invalid (update=0x{updateAttributePtr.ToInt32():X8}, level=0x{updatePtr.ToInt32():X8}, private=0x{privateUpdateAttributePtr.ToInt32():X8}, privateLevel=0x{privateUpdatePtr.ToInt32():X8}, stat=0x{onStatUpdatedIntPtr.ToInt32():X8}, inq2nd=0x{inqAttribute2ndStructPtr.ToInt32():X8}, playerDesc=0x{sendNoticePlayerDescReceivedPtr.ToInt32():X8}).";
_statusMessage = "One or more Attribute2nd handlers failed to resolve (pattern + fallback VA both missed).";
RynthLog.Compat($"Compat: player vitals hooks failed - {_statusMessage}");
return;
}
_inqAttribute2ndStruct = Marshal.GetDelegateForFunctionPointer<InqAttribute2ndStructDelegate>(inqAttribute2ndStructPtr);
_inqAttribute2ndStructFnPtr = inqAttribute2ndStructPtr;
// Buffed-uint overload — used by hot-reload re-seed and any path
// that needs the same number AC's vital bars render. The struct
// overload returns base values; this one returns buffed.
IntPtr inqAttribute2ndUintPtr = Resolve(text, "PlayerVitals.InqAttribute2nd_uint", PatInqAttribute2ndUint, InqAttribute2ndUintVa);
if (inqAttribute2ndUintPtr != IntPtr.Zero)
_inqAttribute2ndUint = Marshal.GetDelegateForFunctionPointer<InqAttribute2ndUintDelegate>(inqAttribute2ndUintPtr);
unsafe
{
@ -149,6 +284,32 @@ internal static class PlayerVitalsHooks
return false;
}
/// <summary>
/// Read a creature's REAL MaxHealth from its qualities (2nd-level attribute
/// table) via InqAttribute2nd, routed through the SEH trampoline so a
/// partial/null MONSTER sub-table AVs into a safe failure instead of killing
/// the client. This is the appraisal-free path to a mob's true HP (appraisal
/// returns a 50 stub for mobs the char's Assess skill can't read). MAIN
/// THREAD ONLY — AC isn't thread-safe. Returns false if the trampoline is
/// unavailable, the read AVs, or the value is 0.
/// </summary>
public static unsafe bool TryReadCreatureMaxHealthSafe(IntPtr weeniePtr, out uint maxHealth)
{
maxHealth = 0;
if (weeniePtr == IntPtr.Zero || _inqAttribute2ndStructFnPtr == IntPtr.Zero)
return false;
if (!SehTrampoline.IsAvailable)
return false; // never call InqAttribute2nd unguarded on a non-player weenie
SecondaryAttributeNative result = default;
int rc = SehTrampoline.ThiscallIntUintPtr(
_inqAttribute2ndStructFnPtr, weeniePtr, MaxHealthType, &result, out bool avCaught);
if (avCaught || rc == 0 || result._currentLevel == 0)
return false;
maxHealth = result._currentLevel;
return true;
}
/// <summary>
/// Returns the unbuffed base maximum vitals (base training + gear + augmentations, no spell enchantments).
/// Uses _initLevel + _levelFromCp from InqAttribute2ndStruct on the current-vital stypes (2/4/6).
@ -254,6 +415,7 @@ internal static class PlayerVitalsHooks
var original = (delegate* unmanaged[Thiscall]<IntPtr, byte, uint, uint, int, uint>)_originalUpdateAttribute2ndLevelPtr;
uint result = original(thisPtr, wts, sender, stype, val);
UpdateCache(sender, stype, val, isPrivate: false);
ForwardCreatureHealth(sender, stype, val);
return result;
}
@ -281,10 +443,9 @@ internal static class PlayerVitalsHooks
var original = (delegate* unmanaged[Thiscall]<IntPtr, uint, int, void>)_originalOnStatUpdatedIntPtr;
original(thisPtr, stype, val);
// Cache MaxHealth for every object — used by CombatActionHooks to resolve the
// absolute target health from the healthRatio in QueryHealthResponse packets.
if (stype == MaxHealthType && val > 0)
ObjectQualityCache.SetMaxHealth(thisPtr, unchecked((uint)val));
// (A per-object MaxHealth-by-pointer cache write used to live here —
// removed 2026-06-11: nothing ever read it, and it allocated on
// dictionary growth inside this UnmanagedCallersOnly detour.)
if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out uint playerId, out _))
return;
@ -312,6 +473,8 @@ internal static class PlayerVitalsHooks
return;
UpdateCache(sender, stype, unchecked((int)val->_currentLevel), isPrivate);
if (!isPrivate)
ForwardCreatureHealth(sender, stype, unchecked((int)val->_currentLevel));
// For max-vital types (MaxHealth=1, MaxStamina=3, MaxMana=5), _currentLevel is the
// effective buffed maximum — that's already handled by the UpdateCache call above.
@ -321,6 +484,65 @@ internal static class PlayerVitalsHooks
// correct buffed value set by the seed or a direct MaxHealth update.
}
// Live monster (non-player) health, captured from the broadcast vital-update
// stream that UpdateCache discards. The server pushes a creature's current
// (stype=Health) and max (stype=MaxHealth) attribute levels here for combat
// mobs in awareness — NO appraisal needed (so it works on high-level mobs
// whose Assess skill we lack) and NO Inq* read (so no non-player-qualities AV).
// Pre-sized + capped so the per-creature add can't realloc inside this
// main-thread detour. Packed (current<<32 | max) to avoid per-entry alloc.
private static readonly Dictionary<uint, ulong> _creatureHp = new(1024);
private static readonly object _creatureHpLock = new();
private static int _creatureHpLogCount;
private static void ForwardCreatureHealth(uint sender, uint stype, int val)
{
if (sender == 0 || val < 0) return;
if (stype != HealthType && stype != MaxHealthType) return;
uint playerId = ClientHelperHooks.GetPlayerId();
if (playerId == 0 || sender == playerId) return; // player handled by UpdateCache
// Packed entry: bit 63 = "current seen", bit 62 = "max seen",
// bits 32-61 = current, bits 0-31 = max. Both halves must be observed
// before a ratio is forwarded — fabricating the missing half reported
// a near-dead mob as FULL (Health-only: max := cur → 1.0) or a fresh
// mob as DEAD (MaxHealth-only: cur = 0 → 0.0), corrupting plugin
// combat decisions.
const ulong SeenCur = 1UL << 63;
const ulong SeenMax = 1UL << 62;
const ulong CurMask = 0x3FFF_FFFFUL;
uint cur, max;
bool complete;
lock (_creatureHpLock)
{
// Bounded with self-healing: the old cap silently stopped tracking
// every NEW creature once 1024 distinct senders had been seen.
// Wholesale clear + reinsert is cheap and recovers within one
// server vital-burst per visible mob. (Also cleared at logout.)
if (_creatureHp.Count >= 1024 && !_creatureHp.ContainsKey(sender))
_creatureHp.Clear();
_creatureHp.TryGetValue(sender, out ulong packed);
cur = (uint)((packed >> 32) & CurMask);
max = (uint)packed;
if (stype == HealthType) { cur = (uint)val & (uint)CurMask; packed |= SeenCur; }
else { max = (uint)val; packed |= SeenMax; }
if (cur > max && (packed & SeenMax) != 0) max = cur; // server can momentarily push cur past a stale max
complete = (packed & SeenCur) != 0 && (packed & SeenMax) != 0;
_creatureHp[sender] = (packed & (SeenCur | SeenMax)) | ((ulong)cur << 32) | max;
}
if (_creatureHpLogCount < 40)
{
_creatureHpLogCount++;
RynthLog.Compat($"Compat: creature vital sender=0x{sender:X8} stype={stype} val={val} -> cur={cur} max={max} complete={complete}");
}
if (complete && max > 0)
Plugins.PluginManager.QueueUpdateHealth(sender, Math.Clamp((float)cur / max, 0f, 1f), cur, max);
}
private static void UpdateCache(uint sender, uint stype, int val, bool isPrivate)
{
uint playerId = ClientHelperHooks.GetPlayerId();
@ -371,6 +593,45 @@ internal static class PlayerVitalsHooks
string scope = isPrivate ? "private" : $"sender=0x{sender:X8}";
RynthLog.Verbose($"Compat: player vital update #{_updateLogCount} {scope} stype={stype} value={value}");
}
// Diagnostic: log every max-vital update so we can see whether the
// UpdateAttribute2nd hook is actually firing for stype 1/3/5 after a
// hot reload, vs being silenced. Cheap (only fires on max changes).
if (changed && (stype == MaxHealthType || stype == MaxStaminaType || stype == MaxManaType))
{
RynthLog.Compat($"PlayerVitals: max update stype={stype} value={value} private={isPrivate}");
}
// Refresh MaxHealth from the live buffed-uint inq. Runs from the
// detour context (game thread, AC just finished an event), so the
// nested-pointer derefs inside InqAttribute2nd are safe. Catches
// god-mode / enchantment-drop cases where the buffed effective max
// changes without a server-pushed UpdateAttribute2nd(MaxHealth) event.
TryRefreshLiveMaxVitals();
}
// Called from every UpdateCache() invocation so buff/vitae changes that don't
// generate an explicit UpdateAttribute2nd packet are still picked up promptly.
private static void TryRefreshLiveMaxVitals()
{
if (_inqAttribute2ndUint == null) return;
IntPtr qualities = KnownPlayerQualitiesPtr;
if (qualities == IntPtr.Zero) return;
if (!LoginLifecycleHooks.HasObservedLoginComplete) return;
if (!ClientObjectHooks.IsReadablePointer(qualities)) return;
TryInqUint(qualities, MaxHealthType, out uint liveHp);
TryInqUint(qualities, MaxStaminaType, out uint liveSt);
TryInqUint(qualities, MaxManaType, out uint liveMn);
lock (CacheLock)
{
PlayerVitalsSnapshot s = _snapshot;
if (liveHp != 0 && s.MaxHealth != liveHp) s = s with { MaxHealth = liveHp };
if (liveSt != 0 && s.MaxStamina != liveSt) s = s with { MaxStamina = liveSt };
if (liveMn != 0 && s.MaxMana != liveMn) s = s with { MaxMana = liveMn };
_snapshot = s;
}
}
private static unsafe void SeedSnapshotFromQualities(IntPtr playerDescPtr)
@ -490,4 +751,16 @@ internal static class PlayerVitalsHooks
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private unsafe delegate int InqAttribute2ndStructDelegate(IntPtr thisPtr, uint stype, SecondaryAttributeNative* retval);
/// <summary>
/// CACQualities::InqAttribute2nd uint overload at 0x00592D20.
/// raw=0 → returns buffed effective value (initLevel + levelFromCp +
/// endurance contribution + EnchantAttribute2nd buffs). raw=1 → unbuffed.
/// This is the function AC itself uses to render the vital bars.
/// </summary>
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private unsafe delegate int InqAttribute2ndUintDelegate(IntPtr thisPtr, uint stype, uint* retval, int raw);
private const int InqAttribute2ndUintVa = 0x00592D20;
private static InqAttribute2ndUintDelegate? _inqAttribute2ndUint;
}

View file

@ -7,10 +7,10 @@
// SetPowerbarLevel updates it, FinishPowerbar hides it. By no-opping all
// three, the bar stays invisible.
//
// VA derivation (map offset + 0x00401000 = live VA — same as RadarHooks):
// 000DA390 gmPowerbarUI::RecvNotice_BeginPowerbar(PowerBarMode) → 0x004DB390
// 000DA1B0 gmPowerbarUI::RecvNotice_SetPowerbarLevel(PowerBarMode,float)→ 0x004DB1B0
// 000DA1E0 gmPowerbarUI::RecvNotice_FinishPowerbar(PowerBarMode) → 0x004DB1E0
// All three target addresses are now resolved via HookResolver — pattern
// scan first, hardcoded VA fallback (logged as RISKY), or UNAVAILABLE.
// The recv-notice functions all share the +0x600/+0xFA08 ClientCombatSystem
// field offsets which are unique enough to anchor patterns against.
// ============================================================================
using System;
@ -22,20 +22,45 @@ namespace RynthCore.Engine.Compatibility;
internal static class PowerbarHooks
{
private const int GmPowerbarUIBeginVa = 0x004DB390;
private const int GmPowerbarUILevelVa = 0x004DB1B0;
private const int GmPowerbarUIFinishVa = 0x004DB1E0;
// Fallback VAs for the 4,841,472-byte client. Pattern-scan is now the
// source of truth; these are the safety net.
private const int GmPowerbarUIBeginFallbackVa = 0x004DB390;
private const int GmPowerbarUILevelFallbackVa = 0x004DB1B0;
private const int GmPowerbarUIFinishFallbackVa = 0x004DB1E0;
// ClientCombatSystem direct hide. Map: 0016A5F0 + 0x00401000 = 0x0056B5F0.
// Thiscall void HidePowerBar() — call on the CCS singleton via the global
// pointer that ClientCombatHooks already locates at 0x0087166C.
private const int ClientCombatSystemHidePowerBarVa = 0x0056B5F0;
private const int CombatSystemPtrVa = 0x0087166C;
// gmPowerbarUI::RecvNotice_BeginPowerbar(PowerBarMode) — uses jump-table
// dispatch on the mode argument; the lea-decrement and ja-of-3 are unique.
private static readonly byte?[] BeginPattern =
[
0x83, 0xEC, 0x10, 0x55, 0x8B, 0x6C, 0x24, 0x18,
0x56, 0x8D, 0x45, 0xFF, 0x83, 0xF8, 0x03, 0x57,
0x8B, 0xF1, 0x0F, 0x87, 0xBC, 0x00, 0x00, 0x00,
0xFF, 0x24, 0x85, null, null, null, null // jmp [imm32 + eax*4] — table
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void HidePowerBarDelegate(IntPtr thisPtr);
// gmPowerbarUI::RecvNotice_SetPowerbarLevel(PowerBarMode,float)
// Compares first arg with [ecx+4] then dispatches via push 0x10000034
// (UI element ID) — unique pair.
private static readonly byte?[] LevelPattern =
[
0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x04, 0x75,
0x23, 0x68, 0x34, 0x00, 0x00, 0x10, 0x81, 0xC1,
0x08, 0xFA, 0xFF, 0xFF,
0xE8, null, null, null, null, // call rel32
0x85, 0xC0, 0x74, 0x0F
];
private static IntPtr _gmPowerbarUIInstance;
// gmPowerbarUI::RecvNotice_FinishPowerbar(PowerBarMode)
// Same +0xFA08 anchor as Level, but with `75 33` instead of `75 23` and a
// C7 41 04 zero-write (clears m_active before re-arming with 0x10000034).
private static readonly byte?[] FinishPattern =
[
0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x04, 0x75,
0x33, 0x56, 0x8D, 0xB1, 0x08, 0xFA, 0xFF, 0xFF,
0xC7, 0x41, 0x04, 0x00, 0x00, 0x00, 0x00, 0x68,
0x34, 0x00, 0x00, 0x10, 0x8B, 0xCE,
0xE8, null, null, null, null // call rel32
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void NoticeBeginDelegate(IntPtr thisPtr, int powerBarMode);
@ -53,16 +78,38 @@ internal static class PowerbarHooks
private static NoticeFinishDelegate? _originalFinish;
private static NoticeFinishDelegate? _finishDetour;
// UIElement::SetVisible(bool) — same address as ChatHooks/RadarHooks use.
private const int UIElementSetVisibleFallbackVa = 0x00462390;
private static readonly byte?[] UIElementSetVisiblePattern =
[
0x51, 0x53, 0x56, 0x57,
0x8B, 0x3D, null, null, null, null, // mov edi, ds:[imm32]
0x8B, 0xF1,
0xE8, null, null, null, null, // call rel32
0x8B, 0x9E, 0xA4, 0x00, 0x00, 0x00,
0x88, 0x44, 0x24, 0x0F
];
private static IntPtr _gmPowerbarUIInstance;
private static IntPtr _uiElementSetVisibleAddress;
private static bool _hookInstalled;
private static bool _isHiddenAsserted;
private static string _statusMessage = "Not initialized.";
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
/// <summary>
/// When true, the detours skip the original gmPowerbarUI notices, so the
/// retail attack/magic power bar never appears. A plugin can render its
/// own equivalent (or just leave it hidden).
/// When true, <see cref="TickHide"/> calls UIElement::SetVisible(false) on
/// the captured powerbar singleton each frame, hiding the retail attack/
/// magic power bar. We do NOT skip the original Begin/Level/Finish notices
/// — that pattern leaves AC's powerbar state machine half-initialized
/// (Begin shows, but no Finish to hide it; or Finish without prior Begin),
/// destabilizes its UIElement, and the next UI traversal (e.g. PopOutPanel
/// undock) AVs on the corrupted state. Same fix the chat suppression uses.
/// NOTE: <c>_gmPowerbarUIInstance</c> is captured from the first notice the
/// powerbar dispatches, so SetVisible can only kick in after the player
/// has at least once initiated combat. After that, the suppression sticks.
/// </summary>
public static bool SuppressOriginalDraw;
@ -77,6 +124,13 @@ internal static class PowerbarHooks
return;
}
// Resolve UIElement::SetVisible (used by TickHide). Direct call site,
// not a hook, but treat through HookResolver so we get pattern-scan
// resilience same as the other hooked addresses.
var setVisible = HookResolver.Resolve(textSection, "PowerbarHooks.UIElement::SetVisible",
UIElementSetVisiblePattern, UIElementSetVisibleFallbackVa);
if (setVisible.Success) _uiElementSetVisibleAddress = setVisible.Address;
bool beginOk = TryInstallBeginHook(textSection);
bool levelOk = TryInstallLevelHook(textSection);
bool finishOk = TryInstallFinishHook(textSection);
@ -85,140 +139,142 @@ internal static class PowerbarHooks
{
_hookInstalled = true;
_statusMessage = "Hooked gmPowerbarUI::RecvNotice_(Begin/Level/Finish).";
RynthLog.Compat($"Compat: powerbar hooks ready (Begin=0x{GmPowerbarUIBeginVa:X8}, Level=0x{GmPowerbarUILevelVa:X8}, Finish=0x{GmPowerbarUIFinishVa:X8}).");
RynthLog.Compat($"PowerbarHooks: all three notices hooked.");
}
else
{
_statusMessage = $"Partial install — Begin={beginOk}, Level={levelOk}, Finish={finishOk}.";
RynthLog.Compat($"Compat: powerbar hook {_statusMessage}");
RynthLog.Compat($"PowerbarHooks: {_statusMessage}");
}
}
private static bool TryInstallBeginHook(AcClientTextSection textSection)
{
int funcOff = GmPowerbarUIBeginVa - textSection.TextBaseVa;
if (!IsValidPrologue(textSection, funcOff, "Begin", GmPowerbarUIBeginVa))
return false;
var resolved = HookResolver.Resolve(textSection, "PowerbarHooks.Begin",
BeginPattern, GmPowerbarUIBeginFallbackVa);
if (!resolved.Success) return false;
try
{
IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_beginDetour = BeginDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_beginDetour);
_originalBegin = Marshal.GetDelegateForFunctionPointer<NoticeBeginDelegate>(
MinHook.HookCreate(targetAddress, detourPtr));
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(targetAddress);
MinHook.Enable(resolved.Address);
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: Powerbar Begin hook failed - {ex.Message}");
RynthLog.Compat($"PowerbarHooks: Begin hook install threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static bool TryInstallLevelHook(AcClientTextSection textSection)
{
int funcOff = GmPowerbarUILevelVa - textSection.TextBaseVa;
if (!IsValidPrologue(textSection, funcOff, "Level", GmPowerbarUILevelVa))
return false;
var resolved = HookResolver.Resolve(textSection, "PowerbarHooks.Level",
LevelPattern, GmPowerbarUILevelFallbackVa);
if (!resolved.Success) return false;
try
{
IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_levelDetour = LevelDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_levelDetour);
_originalLevel = Marshal.GetDelegateForFunctionPointer<NoticeLevelDelegate>(
MinHook.HookCreate(targetAddress, detourPtr));
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(targetAddress);
MinHook.Enable(resolved.Address);
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: Powerbar Level hook failed - {ex.Message}");
RynthLog.Compat($"PowerbarHooks: Level hook install threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static bool TryInstallFinishHook(AcClientTextSection textSection)
{
int funcOff = GmPowerbarUIFinishVa - textSection.TextBaseVa;
if (!IsValidPrologue(textSection, funcOff, "Finish", GmPowerbarUIFinishVa))
return false;
var resolved = HookResolver.Resolve(textSection, "PowerbarHooks.Finish",
FinishPattern, GmPowerbarUIFinishFallbackVa);
if (!resolved.Success) return false;
try
{
IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_finishDetour = FinishDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_finishDetour);
_originalFinish = Marshal.GetDelegateForFunctionPointer<NoticeFinishDelegate>(
MinHook.HookCreate(targetAddress, detourPtr));
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(targetAddress);
MinHook.Enable(resolved.Address);
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: Powerbar Finish hook failed - {ex.Message}");
RynthLog.Compat($"PowerbarHooks: Finish hook install threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static bool IsValidPrologue(AcClientTextSection textSection, int funcOff, string label, int va)
{
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
{
RynthLog.Compat($"Compat: Powerbar {label} VA out of range @ 0x{va:X8}.");
return false;
}
byte firstByte = textSection.Bytes[funcOff];
if (firstByte is 0x00 or 0xCC or 0xC3)
{
RynthLog.Compat($"Compat: Powerbar {label} looks invalid @ 0x{va:X8} (opcode 0x{firstByte:X2}).");
return false;
}
return true;
}
// Per-call diagnostic — emits the first ~5 fires of each detour so we
// can confirm the hook is actually reached when the user expects the bar.
private static int _beginFires, _levelFires, _finishFires;
private static void BeginDetour(IntPtr thisPtr, int powerBarMode)
{
RecursionGuard.Tick("PowerbarHooks.Begin");
if (thisPtr != IntPtr.Zero) _gmPowerbarUIInstance = thisPtr;
if (++_beginFires <= 5)
RynthLog.Compat($"Powerbar Begin fired #{_beginFires} (mode={powerBarMode}, suppress={SuppressOriginalDraw})");
if (SuppressOriginalDraw)
return;
_originalBegin!(thisPtr, powerBarMode);
if (++_beginFires <= 3)
RynthLog.Compat($"PowerbarHooks: Begin fired #{_beginFires} mode={powerBarMode} suppress={SuppressOriginalDraw}");
// Always call original — see SuppressOriginalDraw comment. TickHide
// hides via SetVisible(false) per frame.
try { _originalBegin!(thisPtr, powerBarMode); }
catch (Exception ex) { try { RynthLog.Compat($"PowerbarHooks: Begin original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
}
private static void LevelDetour(IntPtr thisPtr, int powerBarMode, float level)
{
RecursionGuard.Tick("PowerbarHooks.Level");
if (thisPtr != IntPtr.Zero) _gmPowerbarUIInstance = thisPtr;
if (++_levelFires <= 5)
RynthLog.Compat($"Powerbar Level fired #{_levelFires} (mode={powerBarMode}, level={level:F2}, suppress={SuppressOriginalDraw})");
if (SuppressOriginalDraw)
return;
_originalLevel!(thisPtr, powerBarMode, level);
if (++_levelFires <= 3)
RynthLog.Compat($"PowerbarHooks: Level fired #{_levelFires} mode={powerBarMode} level={level:F2} suppress={SuppressOriginalDraw}");
try { _originalLevel!(thisPtr, powerBarMode, level); }
catch (Exception ex) { try { RynthLog.Compat($"PowerbarHooks: Level original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
}
private static void FinishDetour(IntPtr thisPtr, int powerBarMode)
{
RecursionGuard.Tick("PowerbarHooks.Finish");
if (thisPtr != IntPtr.Zero) _gmPowerbarUIInstance = thisPtr;
if (++_finishFires <= 5)
RynthLog.Compat($"Powerbar Finish fired #{_finishFires} (mode={powerBarMode}, suppress={SuppressOriginalDraw})");
if (SuppressOriginalDraw)
return;
_originalFinish!(thisPtr, powerBarMode);
if (++_finishFires <= 3)
RynthLog.Compat($"PowerbarHooks: Finish fired #{_finishFires} mode={powerBarMode} suppress={SuppressOriginalDraw}");
try { _originalFinish!(thisPtr, powerBarMode); }
catch (Exception ex) { try { RynthLog.Compat($"PowerbarHooks: Finish original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
}
// Per-frame SetVisible(false) on the captured pointer was crashing
// (0xC0000005 null-deref) — the instance grabbed from LevelDetour isn't
// safe to invoke UIElement::SetVisible on. Suppression is currently a
// no-op of the notices only; we'll need a different hide strategy later.
/// <summary>
/// Per-frame visibility assertion — currently a no-op.
///
/// Why: <c>gmPowerbarUI</c> doesn't appear to be a UIElement subclass with
/// the UIElement subobject at offset 0 (unlike gmMainChatUI and gmRadarUI).
/// Captured <c>_gmPowerbarUIInstance</c> is the gmPowerbarUI's `this`,
/// which has a different vtable layout. Passing it to UIElement::SetVisible
/// at 0x00462390 caused a NULL function-pointer dereference inside the
/// function (observed crash: "instruction at 0x00000000 referenced memory
/// at 0x00000000" on first combat engage after suppression toggled on).
///
/// Until we resolve the correct UIElement child to hide (likely a member
/// inside gmPowerbarUI at some offset), the suppression flag is wired but
/// has no visual effect. Powerbar remains visible. Detours still always
/// call AC's original notices, so AC's UI state is consistent and stable.
/// </summary>
public static void TickHide()
{
// Intentionally empty until we find the right UIElement to SetVisible on.
}
public static void ResetCachedInstance()
{
_gmPowerbarUIInstance = IntPtr.Zero;
_isHiddenAsserted = false;
}
}

View file

@ -0,0 +1,451 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// MinHook detours on <c>kernel32!ExitProcess</c> and
/// <c>kernel32!TerminateProcess</c> — the two paths every process-shutdown
/// in Windows funnels through (managed FailFast, native AC self-exit on
/// disconnect, runtime AV-induced __fastfail, etc.).
///
/// Purpose: when the AC client dies silently — no popup, no engine VEH
/// banner, no FirstChanceException — neither managed nor SEH machinery
/// catches it. The only chance to see who killed the process is to
/// intercept the kill primitive itself. We capture a native stack
/// backtrace at detour entry, identify the calling module, log it, then
/// forward to the original (process still dies, but we know why).
///
/// Logged information per call:
/// - Function (ExitProcess vs TerminateProcess)
/// - Exit code
/// - Calling thread ID
/// - Top N native return addresses, each annotated with module + RVA
/// so we can pinpoint the exact instruction that decided to kill us.
/// </summary>
internal static class ProcessExitHooks
{
private const int CapturedFrames = 12;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void ExitProcessDelegate(uint exitCode);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)]
private delegate bool TerminateProcessDelegate(IntPtr hProcess, uint exitCode);
// ntdll!RtlExitUserProcess(NTSTATUS) — the actual implementation that
// kernel32!ExitProcess wraps. Modern code (and NativeAOT runtime) can
// call this directly, bypassing kernel32.
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void RtlExitUserProcessDelegate(uint exitStatus);
// ntdll!NtTerminateProcess(HANDLE, NTSTATUS) — the syscall stub. Anything
// that wants to bypass kernel32!TerminateProcess goes through here.
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint NtTerminateProcessDelegate(IntPtr processHandle, uint exitStatus);
// kernel32!RaiseFailFastException — what __fastfail() / abort() / FailFast
// route through. Doesn't take an exit code; takes EXCEPTION_RECORD + CONTEXT.
// We don't need the params, just the call-site capture.
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void RaiseFailFastExceptionDelegate(IntPtr pExceptionRecord, IntPtr pContext, uint dwFlags);
// ntdll!RtlFailFast(NTSTATUS) — internally executes `int 0x29` (the
// __fastfail intrinsic). The kernel handles 0x29 directly and terminates
// the process WITHOUT re-entering user mode through ExitProcess /
// TerminateProcess / RaiseFailFastException. Hooking RtlFailFast itself
// is the only way to capture this path before the kernel takes over.
// Used by: stack-cookie failures (/GS), heap corruption checks, CRT
// abort paths on newer toolchains, NTDLL's own internal asserts.
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void RtlFailFastDelegate(uint code);
// ntdll!RtlFailFast2(NTSTATUS, EXCEPTION_RECORD*) — newer variant that
// also passes an exception record. Same semantics: the kernel terminates
// the process via int 0x29 without revisiting user mode.
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void RtlFailFast2Delegate(uint code, IntPtr pExceptionRecord);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern ushort RtlCaptureStackBackTrace(
uint FramesToSkip, uint FramesToCapture, IntPtr[] BackTrace, out uint BackTraceHash);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetModuleHandleExW(uint dwFlags, IntPtr lpModuleName, out IntPtr phModule);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern uint GetModuleFileNameW(IntPtr hModule, [Out] char[] lpFilename, uint nSize);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint GetCurrentThreadId();
private const uint GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS = 0x00000004;
private const uint GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT = 0x00000002;
private static readonly uint ModuleFromAddrFlags =
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT;
private static ExitProcessDelegate? _exitDetour;
private static ExitProcessDelegate? _exitOriginal;
private static TerminateProcessDelegate? _terminateDetour;
private static TerminateProcessDelegate? _terminateOriginal;
private static RtlExitUserProcessDelegate? _rtlExitDetour;
private static RtlExitUserProcessDelegate? _rtlExitOriginal;
private static NtTerminateProcessDelegate? _ntTermDetour;
private static NtTerminateProcessDelegate? _ntTermOriginal;
private static RaiseFailFastExceptionDelegate? _failFastDetour;
private static RaiseFailFastExceptionDelegate? _failFastOriginal;
private static RtlFailFastDelegate? _rtlFailFastDetour;
private static RtlFailFastDelegate? _rtlFailFastOriginal;
private static RtlFailFast2Delegate? _rtlFailFast2Detour;
private static RtlFailFast2Delegate? _rtlFailFast2Original;
private static int _installed;
private static int _logged; // ensure we log at most once even if both fire
// Re-entrancy latch for the fail-fast family (RaiseFailFastException,
// RtlFailFast, RtlFailFast2). In the NativeAOT-inside-acclient environment
// a fail-fast does NOT terminate the way it does in a normal process: the
// runtime/AC exception machinery swallows or continues the fail-fast
// exception, so kernel32!RaiseFailFastException RETURNS instead of killing
// the process. Its caller then re-invokes it, hitting our MinHook again →
// detour re-enters → calls the original again → ~190K-deep recursion that
// exhausts the 8 MB stack and AVs in ntdll (the recursing code is this
// exit logger itself, so nothing downstream can ever log it). Latch is
// process-wide and never reset — a fail-fast is terminal by contract;
// there is no "recovery", we only need to die cleanly and once.
private static int _inFailFast;
/// <summary>
/// Terminate without any possibility of re-entering a ProcessExitHooks
/// detour. Each call target is a MinHook *trampoline* (relocated original
/// prologue + jump PAST our hook), so none of them route back through our
/// detours. Used to break the fail-fast bounce.
/// </summary>
private static void HardTerminateNoReentry(uint code)
{
try { _ntTermOriginal?.Invoke(new IntPtr(-1), code); } catch { }
try { _rtlExitOriginal?.Invoke(code); } catch { }
try { _exitOriginal?.Invoke(code); } catch { }
try { Environment.Exit(unchecked((int)code)); } catch { }
}
public static void Initialize()
{
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
return;
try
{
IntPtr kernel32 = GetModuleHandleW("kernel32.dll");
if (kernel32 == IntPtr.Zero)
{
RynthLog.Compat("ProcessExitHooks: kernel32 not found.");
return;
}
HookExport(kernel32, "ExitProcess", out IntPtr exitTarget);
if (exitTarget != IntPtr.Zero)
{
_exitDetour = ExitProcessDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_exitDetour);
IntPtr trampoline = MinHook.HookCreate(exitTarget, detourPtr);
_exitOriginal = Marshal.GetDelegateForFunctionPointer<ExitProcessDelegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(exitTarget);
RynthLog.Info($"ProcessExitHooks: hooked kernel32!ExitProcess @ 0x{exitTarget.ToInt32():X8}.");
}
HookExport(kernel32, "TerminateProcess", out IntPtr terminateTarget);
if (terminateTarget != IntPtr.Zero)
{
_terminateDetour = TerminateProcessDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_terminateDetour);
IntPtr trampoline = MinHook.HookCreate(terminateTarget, detourPtr);
_terminateOriginal = Marshal.GetDelegateForFunctionPointer<TerminateProcessDelegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(terminateTarget);
RynthLog.Info($"ProcessExitHooks: hooked kernel32!TerminateProcess @ 0x{terminateTarget.ToInt32():X8}.");
}
// ── DO NOT HOOK RaiseFailFastException (proven fatal 2026-05-16) ──
// Dump analysis of the every-few-minutes silent crash showed a
// 190K-deep stack overflow whose repeating frame pair is
// <ReverseOpenStaticDelegateStub>...RaiseFailFastExceptionDelegate
// ↔ RhpReversePInvokeAttachOrTrapThread2. The NativeAOT reverse-
// P/Invoke transition that enters a managed detour for this export
// itself re-triggers RaiseFailFastException, so the detour recurses
// through the transition shim BEFORE any managed code (incl. any
// re-entrancy guard) can run. Unfixable from the managed side — the
// only correct action is to not hook it. A real fail-fast then
// terminates cleanly (as designed) instead of our hook converting
// it into the guaranteed stack-overflow crash. Same applies to
// ntdll!RtlFailFast / RtlFailFast2 below. The other exit hooks
// (ExitProcess/TerminateProcess/RtlExitUserProcess/NtTerminate) are
// safe — exiting the process does not re-enter those from within
// the transition, and they log clean interceptions.
// ntdll-level hooks — catch paths that bypass kernel32 entirely.
IntPtr ntdll = GetModuleHandleW("ntdll.dll");
if (ntdll != IntPtr.Zero)
{
HookExport(ntdll, "RtlExitUserProcess", out IntPtr rtlExitTarget);
if (rtlExitTarget != IntPtr.Zero)
{
_rtlExitDetour = RtlExitUserProcessDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_rtlExitDetour);
IntPtr trampoline = MinHook.HookCreate(rtlExitTarget, detourPtr);
_rtlExitOriginal = Marshal.GetDelegateForFunctionPointer<RtlExitUserProcessDelegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(rtlExitTarget);
RynthLog.Info($"ProcessExitHooks: hooked ntdll!RtlExitUserProcess @ 0x{rtlExitTarget.ToInt32():X8}.");
}
HookExport(ntdll, "NtTerminateProcess", out IntPtr ntTermTarget);
if (ntTermTarget != IntPtr.Zero)
{
_ntTermDetour = NtTerminateProcessDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_ntTermDetour);
IntPtr trampoline = MinHook.HookCreate(ntTermTarget, detourPtr);
_ntTermOriginal = Marshal.GetDelegateForFunctionPointer<NtTerminateProcessDelegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(ntTermTarget);
RynthLog.Info($"ProcessExitHooks: hooked ntdll!NtTerminateProcess @ 0x{ntTermTarget.ToInt32():X8}.");
}
// RtlFailFast / RtlFailFast2 — NOT HOOKED. Same NativeAOT
// reverse-P/Invoke re-entry recursion as RaiseFailFastException
// (see the block above). Hooking these with a managed detour
// is the every-few-minutes crash. Leave them alone; a genuine
// fail-fast terminates cleanly. (On this Windows build the
// GetProcAddress for these also failed historically anyway.)
if (false && ntdll != IntPtr.Zero)
{
HookExport(ntdll, "RtlFailFast", out IntPtr rtlFailFastTarget);
if (rtlFailFastTarget != IntPtr.Zero)
{
_rtlFailFastDetour = RtlFailFastDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_rtlFailFastDetour);
IntPtr trampoline = MinHook.HookCreate(rtlFailFastTarget, detourPtr);
_rtlFailFastOriginal = Marshal.GetDelegateForFunctionPointer<RtlFailFastDelegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(rtlFailFastTarget);
RynthLog.Info($"ProcessExitHooks: hooked ntdll!RtlFailFast @ 0x{rtlFailFastTarget.ToInt32():X8}.");
}
HookExport(ntdll, "RtlFailFast2", out IntPtr rtlFailFast2Target);
if (rtlFailFast2Target != IntPtr.Zero)
{
_rtlFailFast2Detour = RtlFailFast2Detour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_rtlFailFast2Detour);
IntPtr trampoline = MinHook.HookCreate(rtlFailFast2Target, detourPtr);
_rtlFailFast2Original = Marshal.GetDelegateForFunctionPointer<RtlFailFast2Delegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(rtlFailFast2Target);
RynthLog.Info($"ProcessExitHooks: hooked ntdll!RtlFailFast2 @ 0x{rtlFailFast2Target.ToInt32():X8}.");
}
}
}
}
catch (Exception ex)
{
RynthLog.Compat($"ProcessExitHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static void HookExport(IntPtr kernel32, string name, out IntPtr target)
{
target = GetProcAddress(kernel32, name);
if (target == IntPtr.Zero)
RynthLog.Compat($"ProcessExitHooks: GetProcAddress({name}) failed.");
}
private static void ExitProcessDetour(uint exitCode)
{
LogTermination("ExitProcess", IntPtr.Zero, exitCode);
// Run our orderly shutdown BEFORE AC's CRT atexit chain. Without this,
// hooks stay installed, our threads (TickPump, Avalonia STA) keep
// running, and AC's static-destructor LongHash teardown at 0x416B10
// races them on a hash chain → the popup AV at 0x00416C86.
try { EngineLifecycle.Shutdown(); }
catch (Exception ex) { RynthLog.Info($"ProcessExit: EngineLifecycle.Shutdown threw {ex.GetType().Name}: {ex.Message}"); }
try { _exitOriginal!(exitCode); }
catch { /* original never returns; swallow if it somehow does */ }
}
private static bool TerminateProcessDetour(IntPtr hProcess, uint exitCode)
{
// Only log when terminating ourselves — TerminateProcess on other
// process handles is a normal Process.Kill and not what we're hunting.
// hProcess == -1 (pseudo-handle for current process) or == GetCurrentProcess() handle.
bool selfKill = hProcess == new IntPtr(-1) || hProcess == GetCurrentProcessHandle();
if (selfKill)
LogTermination("TerminateProcess", hProcess, exitCode);
try { return _terminateOriginal!(hProcess, exitCode); }
catch { return false; }
}
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
private static IntPtr GetCurrentProcessHandle() => GetCurrentProcess();
private static void RtlExitUserProcessDetour(uint exitStatus)
{
LogTermination("RtlExitUserProcess", IntPtr.Zero, exitStatus);
try { EngineLifecycle.Shutdown(); }
catch (Exception ex) { RynthLog.Info($"ProcessExit: EngineLifecycle.Shutdown threw {ex.GetType().Name}: {ex.Message}"); }
try { _rtlExitOriginal!(exitStatus); }
catch { }
}
private static uint NtTerminateProcessDetour(IntPtr processHandle, uint exitStatus)
{
bool selfKill = processHandle == new IntPtr(-1) || processHandle == GetCurrentProcessHandle();
if (selfKill)
LogTermination("NtTerminateProcess", processHandle, exitStatus);
try { return _ntTermOriginal!(processHandle, exitStatus); }
catch { return 0xC0000001; /* STATUS_UNSUCCESSFUL */ }
}
private static void RaiseFailFastExceptionDetour(IntPtr pExceptionRecord, IntPtr pContext, uint dwFlags)
{
if (Interlocked.Exchange(ref _inFailFast, 1) != 0)
{
// Re-entered: the original bounced back through our hook instead
// of terminating. Forwarding again is the 190K-deep stack-overflow
// recursion. Break it — die now, non-recursively.
HardTerminateNoReentry(dwFlags);
return;
}
LogTermination("RaiseFailFastException", IntPtr.Zero, dwFlags);
try { _failFastOriginal!(pExceptionRecord, pContext, dwFlags); }
catch { }
// A real fail-fast never returns. In this environment it can — don't
// let the caller spin re-raising it; terminate deterministically.
HardTerminateNoReentry(dwFlags);
}
private static void RtlFailFastDetour(uint code)
{
if (Interlocked.Exchange(ref _inFailFast, 1) != 0)
{
HardTerminateNoReentry(code);
return;
}
LogTermination("RtlFailFast", IntPtr.Zero, code);
try { _rtlFailFastOriginal!(code); }
catch { /* original never returns */ }
HardTerminateNoReentry(code);
}
private static void RtlFailFast2Detour(uint code, IntPtr pExceptionRecord)
{
if (Interlocked.Exchange(ref _inFailFast, 1) != 0)
{
HardTerminateNoReentry(code);
return;
}
LogTermination("RtlFailFast2", IntPtr.Zero, code);
try { _rtlFailFast2Original!(code, pExceptionRecord); }
catch { /* original never returns */ }
HardTerminateNoReentry(code);
}
private static void LogTermination(string func, IntPtr hProcess, uint exitCode)
{
if (Interlocked.Exchange(ref _logged, 1) != 0)
return; // don't double-log if both ExitProcess + TerminateProcess fire
try
{
// Dump RynthCore->AC action trace BEFORE building the termination
// banner so the trace is in the log even if the banner build throws.
// Captures the last ~256 mutating calls — the "too many switches?"
// ring buffer for Class B AVs (AC UIElement faults, no RC stack).
AcActionTrace.DumpToLog();
var sb = new StringBuilder();
sb.AppendLine("==== PROCESS TERMINATION INTERCEPTED ====");
sb.AppendLine($" function: kernel32!{func}");
sb.AppendLine($" exit code: 0x{exitCode:X8} ({(int)exitCode})");
sb.AppendLine($" thread: {GetCurrentThreadId()} (managed name='{Thread.CurrentThread.Name ?? "<unnamed>"}', managed id={Thread.CurrentThread.ManagedThreadId})");
if (hProcess != IntPtr.Zero)
sb.AppendLine($" hProcess: 0x{hProcess.ToInt32():X8}");
var frames = new IntPtr[CapturedFrames];
// FramesToSkip=2 to step past this method + the detour wrapper.
ushort captured = RtlCaptureStackBackTrace(2, (uint)CapturedFrames, frames, out _);
sb.AppendLine($" native back-trace ({captured} frame(s)) — note: x86 EBP-walk, deep frames may be unreliable under FPO:");
for (int i = 0; i < captured; i++)
{
IntPtr addr = frames[i];
if (addr == IntPtr.Zero) break;
string module = ResolveModule(addr, out int rva);
sb.AppendLine($" [{i:00}] 0x{addr.ToInt32():X8} {module}+0x{rva:X}");
}
// Managed stack — the actually useful one. NativeAOT supports
// Environment.StackTrace; this gives us the C# call chain that
// led to ExitProcess being called from inside our engine.
sb.AppendLine(" managed stack (Environment.StackTrace):");
try
{
string mst = Environment.StackTrace ?? "<null>";
foreach (string raw in mst.Split('\n'))
{
string line = raw.TrimEnd('\r');
if (line.Length > 0) sb.AppendLine($" {line}");
}
}
catch (Exception stEx)
{
sb.AppendLine($" <stack capture failed: {stEx.GetType().Name}: {stEx.Message}>");
}
sb.Append("==========================================");
RynthLog.Info(sb.ToString());
}
catch
{
// Logging path must not throw — process is about to die anyway,
// and our detour MUST forward to the original so termination
// actually completes.
}
}
internal static string ResolveModule(IntPtr address, out int rva)
{
rva = 0;
try
{
if (!GetModuleHandleExW(ModuleFromAddrFlags, address, out IntPtr hMod) || hMod == IntPtr.Zero)
return "<unknown>";
rva = (int)(address.ToInt64() - hMod.ToInt64());
char[] buf = new char[260];
uint n = GetModuleFileNameW(hMod, buf, (uint)buf.Length);
if (n == 0)
return $"<mod 0x{hMod.ToInt32():X8}>";
string full = new string(buf, 0, (int)n);
int slash = full.LastIndexOfAny(new[] { '\\', '/' });
return slash >= 0 ? full.Substring(slash + 1) : full;
}
catch
{
return "<resolve-failed>";
}
}
}

View file

@ -9,10 +9,9 @@
// Exposes TryGetRadarRect, which asks UIElement::GetSurfaceBox for the
// radar element's current screen rect.
//
// VA derivation (map offset + 0x00401000 = live VA):
// 000D8FE0 gmRadarUI::DrawObjects(UISurface*) → 0x004D9FE0
// 000D9380 gmRadarUI::DrawChildren(Box2D&,Box2D&,SmartArray&,UISurface*) → 0x004DA380
// 00061220 UIElement::GetSurfaceBox(Box2D*) → 0x00462220
// All four target addresses are now resolved via HookResolver.Resolve:
// pattern-scan first, hardcoded VA fallback, or UNAVAILABLE — the install
// log line tells us exactly how each one resolved on the live binary.
// ============================================================================
using System;
@ -24,9 +23,55 @@ namespace RynthCore.Engine.Compatibility;
internal static class RadarHooks
{
private const int GmRadarUIDrawObjectsVa = 0x004D9FE0;
private const int GmRadarUIDrawChildrenVa = 0x004DA380;
private const int UIElementGetSurfaceBoxVa = 0x00462220;
// Fallback VAs (validated against the 4,841,472-byte client recorded in
// docs/ACCLIENT_HOOK_INVENTORY.md). Only used if pattern-scan misses.
private const int GmRadarUIDrawObjectsFallbackVa = 0x004D9FE0;
private const int GmRadarUIDrawChildrenFallbackVa = 0x004DA380;
private const int UIElementGetSurfaceBoxFallbackVa = 0x00462220;
private const int UIElementSetVisibleFallbackVa = 0x00462390;
// gmRadarUI::DrawObjects(UISurface*) — large 0xDC stack frame, fld of
// a Single field at +0x600, fmul against a global float in .data.
private static readonly byte?[] DrawObjectsPattern =
[
0x81, 0xEC, 0xDC, 0x00, 0x00, 0x00, 0x53, 0x55,
0x56, 0x8B, 0xF1, 0xD9, 0x86, 0x00, 0x06, 0x00,
0x00, 0x8B, 0x86, 0x0C, 0x06, 0x00, 0x00,
0xD8, 0x25, null, null, null, null, // fmul dword ptr [imm32] — global float
0x33, 0xDB, 0x3B, 0xC3
];
// gmRadarUI::DrawChildren(Box2D&,Box2D&,SmartArray&,UISurface*)
private static readonly byte?[] DrawChildrenPattern =
[
0x8B, 0x44, 0x24, 0x0C, 0x8B, 0x54, 0x24, 0x04,
0x53, 0x55, 0x56, 0x8B, 0x74, 0x24, 0x1C, 0x57,
0x56, 0x8B, 0xF9, 0x8B, 0x4C, 0x24, 0x1C, 0x50,
0x51, 0x52, 0x8B, 0xCF,
0xE8, null, null, null, null, // call rel32
0x56
];
// UIElement::SetVisible(bool) — entry uses [global vftable cache] + virtual call.
private static readonly byte?[] UIElementSetVisiblePattern =
[
0x51, 0x53, 0x56, 0x57,
0x8B, 0x3D, null, null, null, null, // mov edi, ds:[imm32]
0x8B, 0xF1,
0xE8, null, null, null, null, // call rel32
0x8B, 0x9E, 0xA4, 0x00, 0x00, 0x00,
0x88, 0x44, 0x24, 0x0F
];
// UIElement::GetSurfaceBox(Box2D*) — 'test byte ptr [ecx+0x556], 1' is
// the unique fingerprint (UIElement-specific flags field).
private static readonly byte?[] UIElementGetSurfaceBoxPattern =
[
0xF6, 0x81, 0x56, 0x05, 0x00, 0x00, 0x01,
0x74, 0x11, 0x56, 0x8B, 0x74, 0x24, 0x08, 0x56,
0xE8, null, null, null, null, // call rel32
0x8B, 0xC6, 0x5E, 0xC2, 0x04, 0x00
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void GmRadarUIDrawObjectsDelegate(IntPtr thisPtr, IntPtr uiSurface);
@ -40,18 +85,29 @@ internal static class RadarHooks
private static GmRadarUIDrawChildrenDelegate? _drawChildrenDetour;
private static IntPtr _gmRadarUIInstance;
private static IntPtr _uiElementSetVisibleAddress;
private static IntPtr _uiElementGetSurfaceBoxAddress;
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
/// <summary>
/// When true, the detours skip the original gmRadarUI draw calls, blanking
/// the vanilla radar so a custom renderer can own that rect. The UIElement
/// is still captured on entry, so GetSurfaceBox keeps working.
/// </summary>
public static bool SuppressOriginalDraw;
private static bool _suppressOriginalDraw;
public static bool SuppressOriginalDraw
{
get => _suppressOriginalDraw;
set
{
if (_suppressOriginalDraw == value) return;
_suppressOriginalDraw = value;
RynthLog.Info($"RadarHooks: SuppressOriginalDraw -> {value}. _gmRadarUIInstance=0x{_gmRadarUIInstance.ToInt32():X8}, drawObjectsHits={_drawObjectsHits}, drawChildrenHits={_drawChildrenHits}.");
}
}
private static int _drawObjectsHits;
private static bool _isHiddenAsserted;
private static int _drawChildrenHits;
/// <summary>
/// The captured gmRadarUI singleton. Zero until the radar has rendered at
@ -70,6 +126,18 @@ internal static class RadarHooks
return;
}
// Resolve the two helper function pointers used by TryGetRadarRect /
// any future SetVisible call. These are direct-call sites, not hooks,
// but if their VAs are wrong we'd AV inside acclient.exe just like a
// bad hook would — so resolve them through the same gate.
var setVisible = HookResolver.Resolve(textSection, "RadarHooks.UIElement::SetVisible",
UIElementSetVisiblePattern, UIElementSetVisibleFallbackVa);
if (setVisible.Success) _uiElementSetVisibleAddress = setVisible.Address;
var getSurfaceBox = HookResolver.Resolve(textSection, "RadarHooks.UIElement::GetSurfaceBox",
UIElementGetSurfaceBoxPattern, UIElementGetSurfaceBoxFallbackVa);
if (getSurfaceBox.Success) _uiElementGetSurfaceBoxAddress = getSurfaceBox.Address;
bool drawObjectsOk = TryInstallDrawObjectsHook(textSection);
bool drawChildrenOk = TryInstallDrawChildrenHook(textSection);
@ -77,103 +145,157 @@ internal static class RadarHooks
{
_hookInstalled = true;
_statusMessage = "Hooked gmRadarUI::DrawObjects + DrawChildren.";
RynthLog.Verbose("Compat: radar hooks ready (DrawObjects + DrawChildren).");
RynthLog.Info($"RadarHooks: {_statusMessage}");
}
else
{
_statusMessage = $"Partial install — DrawObjects={drawObjectsOk}, DrawChildren={drawChildrenOk}.";
RynthLog.Compat($"Compat: radar hook {_statusMessage}");
RynthLog.Compat($"RadarHooks: {_statusMessage}");
}
}
private static bool TryInstallDrawObjectsHook(AcClientTextSection textSection)
{
int funcOff = GmRadarUIDrawObjectsVa - textSection.TextBaseVa;
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
{
RynthLog.Compat($"Compat: DrawObjects VA out of range @ 0x{GmRadarUIDrawObjectsVa:X8}.");
var resolved = HookResolver.Resolve(textSection, "RadarHooks.DrawObjects",
DrawObjectsPattern, GmRadarUIDrawObjectsFallbackVa);
if (!resolved.Success)
return false;
}
byte firstByte = textSection.Bytes[funcOff];
if (firstByte is 0x00 or 0xCC or 0xC3)
{
RynthLog.Compat($"Compat: DrawObjects looks invalid @ 0x{GmRadarUIDrawObjectsVa:X8} (opcode 0x{firstByte:X2}).");
return false;
}
try
{
IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_drawObjectsDetour = DrawObjectsDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_drawObjectsDetour);
_originalDrawObjects = Marshal.GetDelegateForFunctionPointer<GmRadarUIDrawObjectsDelegate>(
MinHook.HookCreate(targetAddress, detourPtr));
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(targetAddress);
MinHook.Enable(resolved.Address);
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: DrawObjects hook failed - {ex.Message}");
RynthLog.Compat($"RadarHooks: DrawObjects hook install threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static bool TryInstallDrawChildrenHook(AcClientTextSection textSection)
{
int funcOff = GmRadarUIDrawChildrenVa - textSection.TextBaseVa;
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
{
RynthLog.Compat($"Compat: DrawChildren VA out of range @ 0x{GmRadarUIDrawChildrenVa:X8}.");
var resolved = HookResolver.Resolve(textSection, "RadarHooks.DrawChildren",
DrawChildrenPattern, GmRadarUIDrawChildrenFallbackVa);
if (!resolved.Success)
return false;
}
byte firstByte = textSection.Bytes[funcOff];
if (firstByte is 0x00 or 0xCC or 0xC3)
{
RynthLog.Compat($"Compat: DrawChildren looks invalid @ 0x{GmRadarUIDrawChildrenVa:X8} (opcode 0x{firstByte:X2}).");
return false;
}
try
{
IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_drawChildrenDetour = DrawChildrenDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_drawChildrenDetour);
_originalDrawChildren = Marshal.GetDelegateForFunctionPointer<GmRadarUIDrawChildrenDelegate>(
MinHook.HookCreate(targetAddress, detourPtr));
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(targetAddress);
MinHook.Enable(resolved.Address);
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: DrawChildren hook failed - {ex.Message}");
RynthLog.Compat($"RadarHooks: DrawChildren hook install threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static void DrawObjectsDetour(IntPtr thisPtr, IntPtr uiSurface)
{
RecursionGuard.Tick("RadarHooks.DrawObjects");
if (thisPtr != IntPtr.Zero)
_gmRadarUIInstance = thisPtr;
if (SuppressOriginalDraw)
return;
int hit = Interlocked.Increment(ref _drawObjectsHits);
if (hit <= 3)
RynthLog.Info($"RadarHooks: DrawObjects detour fired #{hit} this=0x{thisPtr.ToInt32():X8} suppress={_suppressOriginalDraw}.");
_originalDrawObjects!(thisPtr, uiSurface);
// Always call original — see SuppressOriginalDraw comment. Hiding is
// done via TickHide / SetVisible(false) per frame, NOT by skipping
// the draw. Skipping leaves AC's downstream UI state inconsistent
// (the SmartArray& boxArray output param, etc.) and crashes the
// client when the next UI traversal (e.g. PopOutPanel) walks it.
try
{
_originalDrawObjects!(thisPtr, uiSurface);
}
catch (Exception ex)
{
try { RynthLog.Compat($"RadarHooks: DrawObjects original threw {ex.GetType().Name}: {ex.Message}"); } catch { }
throw;
}
}
private static void DrawChildrenDetour(IntPtr thisPtr, IntPtr clipRect, IntPtr clipInside, IntPtr boxArray, IntPtr uiSurface)
{
RecursionGuard.Tick("RadarHooks.DrawChildren");
if (thisPtr != IntPtr.Zero)
_gmRadarUIInstance = thisPtr;
if (SuppressOriginalDraw)
int hit = Interlocked.Increment(ref _drawChildrenHits);
if (hit <= 3)
RynthLog.Info($"RadarHooks: DrawChildren detour fired #{hit} this=0x{thisPtr.ToInt32():X8} suppress={_suppressOriginalDraw}.");
try
{
_originalDrawChildren!(thisPtr, clipRect, clipInside, boxArray, uiSurface);
}
catch (Exception ex)
{
try { RynthLog.Compat($"RadarHooks: DrawChildren original threw {ex.GetType().Name}: {ex.Message}"); } catch { }
throw;
}
}
/// <summary>
/// Per-frame visibility assertion — called from EndSceneHook every frame.
/// While <see cref="SuppressOriginalDraw"/> is on, calls SetVisible(false)
/// on the captured radar singleton each frame so AC can't sneak the
/// radar back on. When the flag flips off, calls SetVisible(true) once
/// to restore. Mirrors the same pattern <see cref="ChatHooks.TickHide"/>
/// uses for the retail chatbox. Confirmed working in production.
/// </summary>
public static unsafe void TickHide()
{
// Don't touch the singleton between in-world sessions — AC frees the
// UIElement during the logout-to-charselect transition and a stale
// pointer dereference inside UIElement::IsVisible AVs the client.
if (!LoginLifecycleHooks.HasObservedLoginComplete)
return;
_originalDrawChildren!(thisPtr, clipRect, clipInside, boxArray, uiSurface);
IntPtr inst = _gmRadarUIInstance;
IntPtr setVisible = _uiElementSetVisibleAddress;
if (inst == IntPtr.Zero || setVisible == IntPtr.Zero)
return;
if (_suppressOriginalDraw)
{
try
{
((delegate* unmanaged[Thiscall]<IntPtr, int, void>)setVisible)(inst, 0);
}
catch { /* best-effort */ }
_isHiddenAsserted = true;
return;
}
if (_isHiddenAsserted)
{
try
{
((delegate* unmanaged[Thiscall]<IntPtr, int, void>)setVisible)(inst, 1);
}
catch { /* best-effort */ }
_isHiddenAsserted = false;
}
}
public static void ResetCachedInstance()
{
_gmRadarUIInstance = IntPtr.Zero;
_isHiddenAsserted = false;
}
/// <summary>
@ -188,6 +310,8 @@ internal static class RadarHooks
IntPtr inst = _gmRadarUIInstance;
if (inst == IntPtr.Zero)
return false;
if (_uiElementGetSurfaceBoxAddress == IntPtr.Zero)
return false;
// Box2D is four int32s laid out (x0, y0, x1, y1). GetSurfaceBox follows
// MSVC's "return struct by value" ABI: caller passes the output slot as
@ -197,7 +321,7 @@ internal static class RadarHooks
try
{
((delegate* unmanaged[Thiscall]<IntPtr, int*, int*>)UIElementGetSurfaceBoxVa)(inst, box);
((delegate* unmanaged[Thiscall]<IntPtr, int*, int*>)_uiElementGetSurfaceBoxAddress)(inst, box);
}
catch
{

View file

@ -29,11 +29,23 @@ internal static class RawOpcodeTracker
public static bool ShowKnown = false;
public static bool ShowUnknown = true;
// Deep-audit finding #25 (2026-06-18): Track allocates a fresh byte[] for
// every non-zero-opcode blob of every inbound packet, called from
// RecvFromDetour (a reverse-P/Invoke detour) with no gate on whether the
// Packet Sniffer panel is even open — only Frozen. Sustained per-packet
// managed allocation on a reverse-P/Invoke transition is the documented
// RhpReversePInvokeAttachOrTrapThread2 fail-fast hazard; on a busy
// multibox it's constant GC churn for a diagnostic feature nobody is
// looking at. RynthCoreShell sets this to the panel's actual visibility
// every frame (open OR closed) — Track short-circuits before any
// allocation while it's false, which is the overwhelming common case.
public static volatile bool Active;
public static bool IsKnown(ushort opcode) => KnownOpcodes.Contains(opcode);
public static unsafe void Track(ushort opcode, byte* payload, int payloadLen)
{
if (Frozen) return;
if (Frozen || !Active) return;
int sampleLen = payloadLen < 16 ? payloadLen : 16;
byte[] sample = new byte[sampleLen];

View file

@ -20,6 +20,10 @@ internal static class RawPacketHooks
{
private const int RecvFromPtrAddr = unchecked((int)0x007935AC);
// Phase B: resolve the RecvFrom fn-ptr slot's address by code-xref ("call [slot]" =
// FF 15 <addr>), operand at offset 2; the VA stays as fallback.
private static readonly byte?[] PatXrefRecvFromSlot = [ 0xFF, 0x15, null, null, null, null, 0x8B, 0xF0, 0x85, 0xF6, 0x7E, 0x67 ];
private static IntPtr _originalRecvFromPtr;
public static bool IsInstalled { get; private set; }
@ -28,12 +32,16 @@ internal static class RawPacketHooks
{
if (IsInstalled) return;
int slotAddr = RecvFromPtrAddr;
if (AcClientModule.TryReadTextSection(out AcClientTextSection text))
slotAddr = HookResolver.ResolveData(text, "RawPacket.RecvFromSlot", PatXrefRecvFromSlot, 2, RecvFromPtrAddr).Address.ToInt32();
unsafe
{
IntPtr fnPtrAddr = new IntPtr(RecvFromPtrAddr);
IntPtr fnPtrAddr = new IntPtr(slotAddr);
if (!SmartBoxLocator.IsMemoryReadable(fnPtrAddr, 4))
{
RynthLog.Compat("RawPacket: RecvFrom pointer address 0x007935AC not readable — skipping.");
RynthLog.Compat($"RawPacket: RecvFrom pointer address 0x{slotAddr:X8} not readable — skipping.");
return;
}
@ -62,6 +70,7 @@ internal static class RawPacketHooks
private static unsafe int RecvFromDetour(
IntPtr s, IntPtr buf, int len, int flags, IntPtr from, IntPtr fromlen)
{
RecursionGuard.Tick("RawPacketHooks.RecvFrom");
delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int, int, IntPtr, IntPtr, int> original =
(delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int, int, IntPtr, IntPtr, int>)_originalRecvFromPtr;

View file

@ -0,0 +1,39 @@
// ============================================================================
// RynthCore.Engine - Compatibility/RecursionGuard.cs
//
// Deep-audit finding #27 (2026-06-18): PERMANENTLY DISABLED, not
// temporarily. This used to sample Environment.StackTrace on a fraction of
// calls to detect runaway same-thread recursion across the ~24 detour call
// sites that still call Tick(name) on entry. It was switched off while
// ruling out whether the StackTrace allocation itself was contributing to a
// second recursive AV (full budget + D3D9-off + ImGui-off) — that
// investigation never re-enabled it, and the "TEMPORARILY DISABLED /
// re-enable by removing this early-return" comment it carried was
// misleading: nobody had, and the dead sampling body below it was never
// going to run again without someone reading this exact comment.
//
// Deliberately NOT re-enabled here: re-adding Environment.StackTrace
// sampling on a hot per-detour path reintroduces the exact allocation this
// was disabled to rule out, and a proper allocation-free depth counter
// needs a paired enter/exit at all ~24 call sites (Tick() today is
// entry-only) — too invasive for a diagnostic that only ever logged, never
// prevented anything (this project already triages it as P3/cosmetic).
// The sibling ThreadStackSampler.SampleAll() (cross-thread, EBP-walk based,
// no per-call allocation) is a safer design for the same goal, but it
// SuspendThreads every thread in the process on each call — wiring it to
// run unattended on a timer is a real behavioral risk (a live gaming
// client hitching, or worse, one AC thread suspended mid critical-section)
// that deserves its own deliberate decision, not a drive-by from this
// finding. Tick() stays a real, honest no-op — call sites keep compiling
// unchanged, and no allocation or new risk is introduced anywhere.
// ============================================================================
namespace RynthCore.Engine.Compatibility;
internal static class RecursionGuard
{
public static void Tick(string detourName)
{
// No-op by design — see the file-header comment above.
}
}

View file

@ -0,0 +1,84 @@
using System;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Engine-level <c>/rc ...</c> chat commands. Intercepted on every chat-entry
/// path BEFORE plugin pre-dispatch and before the line reaches AC's chat:
/// <list type="bullet">
/// <item>typed in-game — <see cref="ChatCallbackHooks"/> OutgoingChatDetour</item>
/// <item>dispatch.txt / OnLoginCommandRunner / Host.InvokeChatParser —
/// <see cref="ChatCommandDispatcher.Dispatch"/></item>
/// </list>
/// Commands:
/// <list type="bullet">
/// <item><c>/rc resetbar</c> — recover the RynthCore overlay bar when it has
/// been dragged off the visible client area (its in-overlay "Rs" reset
/// button rides the bar itself, so it's unreachable once the bar is).
/// The launcher button writes this to dispatch.txt as the out-of-band
/// recovery.</item>
/// <item><c>/rc vitals</c> (alias <c>/rc hud</c>) — toggle the custom D3D9
/// Health/Stamina/Mana HUD on/off (persisted to engine.json).</item>
/// <item><c>/rc vendor [list|info|status|buy &lt;id|sel&gt; [n]|sell &lt;id|sel&gt; [id ...]]</c>
/// — read / trade with the open vendor through the engine's vendor
/// primitives (<see cref="VendorTrade"/>); a manual test hook for the
/// plugin API. Replies go to chat from the main-thread drain and to the log.</item>
/// </list>
/// </summary>
internal static class RynthCoreChatCommands
{
private const string Prefix = "/rc ";
/// <summary>
/// True if <paramref name="line"/> was a RynthCore engine command and has
/// been handled — the caller must consume it (do NOT forward to AC chat
/// or to plugins).
/// </summary>
public static bool TryHandle(string? line)
{
if (string.IsNullOrWhiteSpace(line))
return false;
string trimmed = line.Trim();
if (!trimmed.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase))
return false;
string sub = trimmed.Substring(Prefix.Length).Trim();
// /rc vendor [list|info|status|buy <id|sel> [n]|sell <id|sel> [id ...]]
if (sub.Equals("vendor", StringComparison.OrdinalIgnoreCase)
|| sub.StartsWith("vendor ", StringComparison.OrdinalIgnoreCase))
{
try { VendorTrade.HandleChatCommand(sub.Length > 6 ? sub.Substring(7) : string.Empty); }
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc vendor failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
switch (sub.ToLowerInvariant())
{
case "resetbar":
case "barreset":
RynthLog.Compat("RynthCoreChatCommands: /rc resetbar — resetting overlay bar position.");
ImGuiBackend.RynthCoreShell.RequestExternalReset();
return true;
case "vitals":
case "hud":
{
// Toggle the custom D3D9 vital HUD. Setter persists to engine.json
// so it survives relaunch. (No AC-chat echo — the AddTextToScroll
// path has a known AV risk; the HUD appearing/vanishing confirms.)
bool now = !Plugins.EngineSettings.DrawCustomVitalBars;
Plugins.EngineSettings.DrawCustomVitalBars = now;
RynthLog.Compat($"RynthCoreChatCommands: /rc vitals — custom vital HUD {(now ? "ON" : "OFF")}.");
return true;
}
default:
// Consume anything else under the /rc namespace so a typo
// does not leak into world chat.
RynthLog.Compat($"RynthCoreChatCommands: unknown subcommand '/rc {sub}'.");
return true;
}
}
}

View file

@ -4,9 +4,6 @@
// Hooks gmSalvageUI::OpenSalvagePanel to capture the singleton 'this' pointer.
// The captured instance is used by ClientHelperHooks for SalvagePanelAddItem
// and SalvagePanelExecute, which call the thiscall instance methods directly.
//
// VA derivation (map_offset + 0x00401000 = live VA):
// 000CAF70 gmSalvageUI::OpenSalvagePanel → 0x004CBF70
// ============================================================================
using System;
@ -18,15 +15,27 @@ namespace RynthCore.Engine.Compatibility;
internal static class SalvageHooks
{
// gmSalvageUI::OpenSalvagePanel(uint toolId) — thiscall
// Map: 000CAF70 → live VA: 0x004CBF70
private const int GmSalvageUIOpenSalvagePanelVa = 0x004CBF70;
private const int OpenSalvagePanelFallbackVa = 0x004CBF70;
// gmSalvageUI::OpenSalvagePanel(uint toolId)
// Reads the salvage UI element from [esi+0x600], pushes it as 'this' to
// call the +0x608 lookup. The two `[esi+0x600]` accesses + the two E8 calls
// are very specific to this function.
private static readonly byte?[] OpenSalvagePanelPattern =
[
0x8B, 0x44, 0x24, 0x04, 0x56, 0x8B, 0xF1, 0x8B,
0x8E, 0x00, 0x06, 0x00, 0x00, 0x51, 0x8B, 0xCE,
0x89, 0x86, 0x08, 0x06, 0x00, 0x00,
0xE8, null, null, null, null, // call rel32
0x8B, 0x8E, 0x00, 0x06, 0x00, 0x00,
0xE8, null, null, null, null // call rel32
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void GmSalvageUIOpenSalvagePanelDelegate(IntPtr thisPtr, uint toolId);
private static GmSalvageUIOpenSalvagePanelDelegate? _originalOpenSalvagePanel;
private static GmSalvageUIOpenSalvagePanelDelegate? _openSalvagePanelDetour; // held alive to prevent GC
private static GmSalvageUIOpenSalvagePanelDelegate? _openSalvagePanelDetour;
private static IntPtr _gmSalvageUIInstance;
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
@ -34,10 +43,6 @@ internal static class SalvageHooks
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
/// <summary>
/// The captured gmSalvageUI singleton. Zero until the salvage panel has been
/// opened at least once (either by the player or by SalvagePanelOpen).
/// </summary>
public static IntPtr GmSalvageUIInstance => _gmSalvageUIInstance;
public static void Initialize()
@ -51,50 +56,44 @@ internal static class SalvageHooks
return;
}
int funcOff = GmSalvageUIOpenSalvagePanelVa - textSection.TextBaseVa;
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
var resolved = HookResolver.Resolve(textSection, "SalvageHooks.OpenSalvagePanel",
OpenSalvagePanelPattern, OpenSalvagePanelFallbackVa);
if (!resolved.Success)
{
_statusMessage = $"gmSalvageUI::OpenSalvagePanel VA out of range @ 0x{GmSalvageUIOpenSalvagePanelVa:X8}.";
RynthLog.Compat($"Compat: salvage hook failed - {_statusMessage}");
return;
}
byte firstByte = textSection.Bytes[funcOff];
if (firstByte is 0x00 or 0xCC or 0xC3)
{
_statusMessage = $"gmSalvageUI::OpenSalvagePanel looks invalid @ 0x{GmSalvageUIOpenSalvagePanelVa:X8} (opcode 0x{firstByte:X2}).";
RynthLog.Compat($"Compat: salvage hook failed - {_statusMessage}");
_statusMessage = $"Resolve failed ({resolved.Detail}).";
return;
}
try
{
IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_openSalvagePanelDetour = OpenSalvagePanelDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_openSalvagePanelDetour);
_originalOpenSalvagePanel = Marshal.GetDelegateForFunctionPointer<GmSalvageUIOpenSalvagePanelDelegate>(
MinHook.HookCreate(targetAddress, detourPtr));
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(targetAddress);
MinHook.Enable(resolved.Address);
_hookInstalled = true;
_statusMessage = $"Hooked gmSalvageUI::OpenSalvagePanel @ 0x{targetAddress.ToInt32():X8}.";
RynthLog.Verbose($"Compat: salvage hook ready @ 0x{targetAddress.ToInt32():X8}, firstByte=0x{firstByte:X2}");
_statusMessage = $"Hooked gmSalvageUI::OpenSalvagePanel @ 0x{resolved.Address.ToInt32():X8}.";
RynthLog.Compat($"SalvageHooks: install ok.");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: salvage hook failed - {ex.Message}");
RynthLog.Compat($"SalvageHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static int _fires;
private static void OpenSalvagePanelDetour(IntPtr thisPtr, uint toolId)
{
// Capture the gmSalvageUI singleton on every open so it stays fresh
// even across hot-reloads or UI recreation.
if (thisPtr != IntPtr.Zero)
_gmSalvageUIInstance = thisPtr;
if (++_fires <= 3)
RynthLog.Compat($"SalvageHooks: OpenSalvagePanel fired #{_fires} this=0x{thisPtr.ToInt32():X8} toolId=0x{toolId:X}");
_originalOpenSalvagePanel!(thisPtr, toolId);
try { _originalOpenSalvagePanel!(thisPtr, toolId); }
catch (Exception ex) { try { RynthLog.Compat($"SalvageHooks: original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
}
}

View file

@ -0,0 +1,194 @@
// ============================================================================
// RynthCore.Engine - SehTrampoline.cs
// Managed P/Invoke bridge to RynthCore.SehTrampoline.dll.
//
// NativeAOT managed try/catch cannot catch access violations (hardware
// exceptions / corrupted-state exceptions on .NET 5+). When AC's native
// code AVs while we call an AC API during object teardown, the managed
// catch { } is a no-op and the process dies.
//
// The trampoline DLL provides __try/__except wrappers compiled with MSVC.
// Each export wraps exactly one native call. If the call AVs, the SEH
// handler catches it, sets the out-parameter to a safe default, and
// returns 0. Return 1 means the call completed normally.
//
// This is per-callsite SEH, NOT process-wide (unlike VEH/SUEF which are
// proven fatal in NativeAOT-injected acclient — see CrashLogger.cs).
//
// Usage pattern at each call site:
// if (SehTrampoline.IsAvailable) {
// IntPtr fnPtr = Marshal.GetFunctionPointerForDelegate(_delegate!);
// T result = SehTrampoline.SomeWrapper(fnPtr, args, out bool avCaught);
// if (avCaught) { log; return safeDefault; }
// // use result normally
// } else {
// // direct delegate call (same as before this fix)
// }
// ============================================================================
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
internal static class SehTrampoline
{
private static volatile bool _available;
/// <summary>Called by EntryPoint after RynthCore.SehTrampoline.dll loads successfully.</summary>
public static void MarkAvailable() => _available = true;
/// <summary>
/// Installs the native VEH crash logger inside the trampoline DLL. PURE NATIVE —
/// no managed callback / reverse-P/Invoke transition — so unlike the removed
/// managed CrashLogger VEH it cannot itself re-trigger a NativeAOT fail-fast on an
/// AC-owned thread. Writes the faulting 32-bit context + a module-resolved stack
/// sweep to <paramref name="logPath"/> for the 0xC0000005 (AV/CSE) and 0xC0000602
/// (RaiseFailFast) classes that bypass managed handlers. Observes only.
/// </summary>
public static void InstallCrashLogger(string logPath)
{
try { _InstallCrashLogger(logPath); }
catch (Exception ex) { RynthLog.Compat($"SehTrampoline: InstallCrashLogger failed - {ex.GetType().Name}: {ex.Message}"); }
}
// ── Tag-parser guard (native detour) ───────────────────────────────────
/// <summary>Address of the native tag-parser null-guard detour (RC_TagParserGuard),
/// for the engine to pass to MinHook as the detour target.</summary>
public static IntPtr GetTagParserGuardAddress() => _GetTagParserGuardAddress();
/// <summary>Hands the native guard the MinHook trampoline (the original
/// FUN_0067D3C0). MUST be called BEFORE the hook is enabled.</summary>
public static void SetTagParserOriginal(IntPtr original) => _SetTagParserOriginal(original);
/// <summary>Count of null-context parse runs the native guard has dropped (diag).</summary>
public static uint TagParserSkipCount { get { try { return _TagParserSkipCount(); } catch { return 0; } } }
/// <summary>
/// True when the trampoline DLL is loaded. Call sites should check this
/// and fall back to direct delegate calls when false.
/// </summary>
public static bool IsAvailable => _available;
// ── P/Invoke declarations ──────────────────────────────────────────────
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_CdeclPtrUint",
CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe int _CdeclPtrUint(IntPtr fn, uint arg, void** outResult);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_CdeclPtrVoid",
CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe int _CdeclPtrVoid(IntPtr fn, void** outResult);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_CdeclVoidUintByte",
CallingConvention = CallingConvention.Cdecl)]
private static extern int _CdeclVoidUintByte(IntPtr fn, uint arg1, byte arg2);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_FreeHandsCast",
CallingConvention = CallingConvention.Cdecl)]
private static extern int _FreeHandsCast(IntPtr fn, IntPtr thisPtr, uint spellId, uint targetId);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_ThiscallByteUint",
CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe int _ThiscallByteUint(IntPtr fn, IntPtr thisPtr, uint arg, byte* outResult);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_ThiscallUintNoArg",
CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe int _ThiscallUintNoArg(IntPtr fn, IntPtr thisPtr, uint* outResult);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_ThiscallIntUintPtr",
CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe int _ThiscallIntUintPtr(IntPtr fn, IntPtr thisPtr, uint arg1, void* arg2, int* outResult);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_InstallCrashLogger",
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern void _InstallCrashLogger([MarshalAs(UnmanagedType.LPWStr)] string logPath);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_GetTagParserGuardAddress",
CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr _GetTagParserGuardAddress();
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_SetTagParserOriginal",
CallingConvention = CallingConvention.Cdecl)]
private static extern void _SetTagParserOriginal(IntPtr original);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_TagParserSkipCount",
CallingConvention = CallingConvention.Cdecl)]
private static extern uint _TagParserSkipCount();
// ── Typed call-through wrappers ────────────────────────────────────────
// Each returns the native result; sets avCaught=true if AV was intercepted.
// Callers MUST check IsAvailable before calling these.
/// <summary>void* __cdecl fn(uint) — e.g. GetWeenieObject(objectId)</summary>
public static IntPtr CdeclPtrUint(IntPtr fn, uint arg, out bool avCaught)
{
unsafe
{
void* result;
avCaught = _CdeclPtrUint(fn, arg, &result) == 0;
return (IntPtr)result;
}
}
/// <summary>void* __cdecl fn() — e.g. GetCombatSystem()</summary>
public static IntPtr CdeclPtrVoid(IntPtr fn, out bool avCaught)
{
unsafe
{
void* result;
avCaught = _CdeclPtrVoid(fn, &result) == 0;
return (IntPtr)result;
}
}
/// <summary>
/// void __cdecl fn(uint, byte) — e.g. CastSpell(spellId, targetIsSelected).
/// Returns false if AV was caught.
/// </summary>
public static bool CdeclVoidUintByte(IntPtr fn, uint arg1, byte arg2)
=> _CdeclVoidUintByte(fn, arg1, arg2) != 0;
/// <summary>
/// void __thiscall fn(this, uint spellId, uint targetId) — ClientMagicSystem::
/// FreeHandsAndCastSpell. Explicit-target cast (no global selection / UI state).
/// 'this' is the GetMagicSystem() singleton. Returns false if an AV was caught.
/// </summary>
public static bool FreeHandsCast(IntPtr fn, IntPtr thisPtr, uint spellId, uint targetId)
=> _FreeHandsCast(fn, thisPtr, spellId, targetId) != 0;
/// <summary>byte __thiscall fn(uint) — e.g. ObjectIsAttackable(objectId)</summary>
public static byte ThiscallByteUint(IntPtr fn, IntPtr thisPtr, uint arg, out bool avCaught)
{
unsafe
{
byte result;
avCaught = _ThiscallByteUint(fn, thisPtr, arg, &result) == 0;
return result;
}
}
/// <summary>uint __thiscall fn() — e.g. InqType()</summary>
public static uint ThiscallUintNoArg(IntPtr fn, IntPtr thisPtr, out bool avCaught)
{
unsafe
{
uint result;
avCaught = _ThiscallUintNoArg(fn, thisPtr, &result) == 0;
return result;
}
}
/// <summary>
/// int __thiscall fn(this, uint arg1, void* outStruct) — e.g.
/// InqAttribute2nd(stype, &SecondaryAttribute). Returns the native int result
/// (nonzero = success); avCaught=true (and result 0) if an AV was intercepted.
/// outStruct points at caller-owned memory the callee fills on success.
/// </summary>
public static unsafe int ThiscallIntUintPtr(IntPtr fn, IntPtr thisPtr, uint arg1, void* outStruct, out bool avCaught)
{
int result;
avCaught = _ThiscallIntUintPtr(fn, thisPtr, arg1, outStruct, &result) == 0;
return result;
}
}

View file

@ -10,12 +10,23 @@ internal static class SelectedTargetHooks
{
private const int SetSelectedObjectVa = 0x0058D110;
private const int SelectedIdVa = 0x00871E54;
private static readonly byte[] SetSelectedObjectSignature =
// Phase B: resolve s_selected_id's address by code-xref (ret; mov eax,[s_selected_id] =
// C3 A1 <addr>), operand at offset 2; the VA stays as fallback. Resolved in Initialize.
private static readonly byte?[] PatXrefSelectedId = [ 0xC3, 0xA1, null, null, null, null, 0x89, 0x87 ];
private static int _selectedIdAddr = SelectedIdVa;
/// <summary>
/// Reads the AC client's currently-selected target id directly from the
/// global. Used by PluginManager.DispatchLoginCompleteToLoadedPlugins to
/// re-seed plugins with the live target after a deferred init (events
/// fired before <c>_initialized=true</c> are dropped by the queue gate).
/// </summary>
public static uint ReadCurrentSelectedId() => ReadUInt32(_selectedIdAddr);
// Verified unique + lands at 0x0058D110 offline (tools/pe_pattern.py).
private static readonly byte?[] SetSelectedObjectPattern =
[
0x8B, 0x4C, 0x24, 0x08, 0x85, 0xC9, 0xA1, 0x54,
0x1E, 0x87, 0x00, 0x56, 0x8B, 0x74, 0x24, 0x08,
0x57, 0x8B, 0xF8, 0x75, 0x04, 0x3B, 0xC6, 0x74,
0x7A, 0x85, 0xC0, 0x74, 0x14, 0x50, 0xE8
0x8B, 0x4C, 0x24, 0x08, 0x85, 0xC9, 0xA1, 0x54
];
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
@ -40,17 +51,19 @@ internal static class SelectedTargetHooks
return;
}
int funcOff = SetSelectedObjectVa - textSection.TextBaseVa;
if (!PatternScanner.VerifyBytes(textSection.Bytes, funcOff, SetSelectedObjectSignature))
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "SelectedTarget.SetSelectedObject", SetSelectedObjectPattern, SetSelectedObjectVa);
if (!resolved.Success)
{
_statusMessage = $"ACCWeenieObject::SetSelectedObject signature mismatch @ 0x{SetSelectedObjectVa:X8}.";
_statusMessage = $"ACCWeenieObject::SetSelectedObject unresolved (VA 0x{SetSelectedObjectVa:X8}).";
RynthLog.Compat($"Compat: selected-target hook failed - {_statusMessage}");
return;
}
_selectedIdAddr = HookResolver.ResolveData(textSection, "SelectedTarget.s_selected_id", PatXrefSelectedId, 2, SelectedIdVa).Address.ToInt32();
try
{
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_targetAddress = resolved.Address;
_setSelectedObjectDetour = SetSelectedObjectDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_setSelectedObjectDetour);
_originalSetSelectedObject = Marshal.GetDelegateForFunctionPointer<SetSelectedObjectDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
@ -59,7 +72,7 @@ internal static class SelectedTargetHooks
IsInstalled = true;
_statusMessage = $"Hooked ACCWeenieObject::SetSelectedObject @ 0x{_targetAddress.ToInt32():X8}.";
RynthLog.Verbose(
RynthLog.Info(
$"Compat: selected-target hook ready - SetSelectedObject=0x{_targetAddress.ToInt32():X8}, selectedId=0x{SelectedIdVa:X8}");
}
catch (Exception ex)
@ -71,7 +84,7 @@ internal static class SelectedTargetHooks
private static void SetSelectedObjectDetour(uint selectedId, int reselect)
{
uint previousTargetId = ReadUInt32(SelectedIdVa);
uint previousTargetId = ReadUInt32(_selectedIdAddr);
try
{
@ -83,13 +96,17 @@ internal static class SelectedTargetHooks
throw;
}
uint currentTargetId = ReadUInt32(SelectedIdVa);
uint currentTargetId = ReadUInt32(_selectedIdAddr);
if (currentTargetId == previousTargetId)
return;
if (Interlocked.Increment(ref _detourLogCount) <= 5)
RynthLog.Compat($"Compat: selected-target detour fired (#{_detourLogCount}) - prev=0x{previousTargetId:X8} curr=0x{currentTargetId:X8} reselect={reselect}");
PluginManager.QueueSelectedTargetChange(currentTargetId, previousTargetId);
}
private static int _detourLogCount;
private static uint ReadUInt32(int address)
{
return unchecked((uint)Marshal.ReadInt32(new IntPtr(address)));

View file

@ -11,6 +11,14 @@ internal static class SessionStateRegistry
private static bool _initialized;
private static bool _loginRecorded;
// Last-recorded session identity, exposed in-memory so the GetEngineStatusJson accessor
// can label this client without re-parsing any file (re-reading
// the session record here can recurse through DatFileShareHooks — see the
// long comment in TryWriteLoginState). Empty until LoginComplete records.
internal static string LastAccountName { get; private set; } = string.Empty;
internal static string LastCharacterName { get; private set; } = string.Empty;
internal static string LastServerName { get; private set; } = string.Empty;
public static void Initialize()
{
if (_initialized)
@ -18,6 +26,12 @@ internal static class SessionStateRegistry
_initialized = true;
LoginLifecycleHooks.LoginComplete += OnLoginComplete;
// No longer subscribe to LogoutLifecycleHooks. RecvNotice_Logoff has
// been observed firing during normal play (transient state changes,
// not actual logoff), and flipping IsLoggedIn=false on a per-process
// record would let the launcher's stuck-client reaper kill a healthy
// in-game client. The launcher's _everLoggedInPids latch handles the
// post-login case from its side without needing this signal.
}
public static void Poll()
@ -33,6 +47,35 @@ internal static class SessionStateRegistry
TryWriteLoginState();
}
/// <summary>
/// Flip the persisted record to <c>IsLoggedIn=false</c> + record
/// <c>LogoutAtUtc</c>. Fires for both clean logout (CPlayerSystem::ExecuteLogOff)
/// and server-driven disconnect (gmGamePlayUI::RecvNotice_Logoff). The
/// launcher's stuck-client reaper uses LogoutAtUtc to detect a session
/// that's been sitting on the disconnect/char-select screen too long.
/// Resets <see cref="_loginRecorded"/> so a relogin within the same
/// process re-records correctly.
/// </summary>
private static void OnLogoutObserved()
{
try
{
SessionStateRecord? record = SessionStateStore.TryReadForProcess(Environment.ProcessId);
if (record == null)
return;
record.IsLoggedIn = false;
record.LogoutAtUtc = DateTime.UtcNow;
SessionStateStore.WriteForProcess(Environment.ProcessId, record);
_loginRecorded = false;
RynthLog.Verbose($"SessionState: recorded logout for PID {Environment.ProcessId}.");
}
catch (Exception ex)
{
RynthLog.Compat($"SessionState: failed to record logout - {ex.Message}");
}
}
private static void TryWriteLoginState()
{
if (_loginRecorded)
@ -40,7 +83,13 @@ internal static class SessionStateRegistry
try
{
SessionStateRecord? existingRecord = SessionStateStore.TryReadForProcess(Environment.ProcessId);
// Do not call TryReadForProcess here — JsonDocument.Parse inside
// it interacts with DatFileShareHooks.CreateFile in a way that
// causes a stack overflow (~17s after LoginComplete). All fields
// it would have contributed are either read from the launch-context
// file below or reseeded from Process.StartTime, so the result was
// always null anyway once the workaround was in place.
SessionStateRecord? existingRecord = null;
(string accountName, string serverName, string targetCharacter) = ReadLaunchContext();
accountName = Coalesce(accountName, existingRecord?.AccountName);
@ -67,8 +116,13 @@ internal static class SessionStateRegistry
if (!string.IsNullOrWhiteSpace(accountName) && !string.IsNullOrWhiteSpace(characterName))
CharacterCacheStore.UpsertCharacter(accountName, serverName, characterName);
// Cache identity in-memory for the GetEngineStatusJson accessor.
LastAccountName = accountName;
LastCharacterName = characterName;
LastServerName = serverName;
_loginRecorded = true;
RynthLog.Verbose($"SessionState: recorded login session for PID {Environment.ProcessId} account='{accountName}' character='{characterName}'.");
RynthLog.Info($"SessionState: recorded login session for PID {Environment.ProcessId} account='{accountName}' character='{characterName}' (IsLoggedIn=true).");
}
catch (Exception ex)
{
@ -78,11 +132,19 @@ internal static class SessionStateRegistry
private static string ResolveCharacterName(string fallbackCharacter)
{
// DIAGNOSTIC: live-memory lookup disabled — ClientObjectHooks.TryGetObjectName
// chain (GetWeenieObject + GetObjectName variants) was bisected as the
// recursive AV trigger at LoginComplete. Returning the launch-context
// character name only until the lookup is fixed.
return fallbackCharacter ?? string.Empty;
#pragma warning disable CS0162
uint playerId = ClientHelperHooks.GetPlayerId();
if (playerId != 0 && ClientObjectHooks.TryGetObjectName(playerId, out string actualName) && !string.IsNullOrWhiteSpace(actualName))
return actualName;
return fallbackCharacter ?? string.Empty;
#pragma warning restore CS0162
}
private static DateTime GetProcessStartTimeUtc()

View file

@ -2,7 +2,7 @@ using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
@ -16,7 +16,6 @@ internal static class SmartBoxHooks
private const uint PlayerPositionUpdateOpcode = 0x0000F74B;
private const uint VectorUpdateOpcode = 0x0000F74E;
private const uint UpdateObjectOpcode = 0x0000F7DB;
private const uint GameEventOpcode = 0x0000F7B0;
// ACSmartBox::DispatchSmartBoxEvent
// 83 EC 08 53 8B 5C 24 10 8B 53 30 83 FA 04 8B 43 2C 56 8B F1 89 44 24 14 89 54 24 08 72 ?? 8B 08
@ -28,14 +27,20 @@ internal static class SmartBoxHooks
0x89, 0x54, 0x24, 0x08, 0x72, null, 0x8B, 0x08
];
// ACGame::DispatchGameEvent
// 83 EC 08 53 8B 5C 24 10 8B 53 30 83 FA 04 8B 43 2C 56 8B F1 89 44 24 14 89 54 24 08 72 ?? 8B 08
// UIQueueManager::ProcessNetBlobData @ 0x0055BCD0 — the real inbound GameEvent
// dispatcher (switches on inner event type: 0x1B1/0x1B2 attack, 0x1AC/0x1AD
// victim/killer, 0x1C0 health, …). thiscall(this, uint* data, int end);
// the inner event type is *data and the payload follows at data+4.
// ⚠ This MUST differ from DispatchSmartBoxEventPattern — they were once an
// identical copy-paste, which deduped this hook away (it never installed, so
// combat events were never seen). Verified unique vs acclient.exe.
private static readonly byte?[] DispatchGameEventPattern =
[
0x83, 0xEC, 0x08, 0x53, 0x8B, 0x5C, 0x24, 0x10,
0x8B, 0x53, 0x30, 0x83, 0xFA, 0x04, 0x8B, 0x43,
0x2C, 0x56, 0x8B, 0xF1, 0x89, 0x44, 0x24, 0x14,
0x89, 0x54, 0x24, 0x08, 0x72, null, 0x8B, 0x08
0x81, 0xEC, 0xC0, 0x01, 0x00, 0x00, 0x53, 0x55,
0x8B, 0xAC, 0x24, 0xD0, 0x01, 0x00, 0x00, 0x56,
0x57, 0x8B, 0xF9, 0x8B, 0x8C, 0x24, 0xD4, 0x01,
0x00, 0x00, 0x8B, 0x11, 0x8B, 0xC1, 0x8D, 0x34,
0x29, 0x83, 0xC1, 0x04
];
private static IntPtr _originalDispatchSmartBoxEventPtr;
@ -86,7 +91,7 @@ internal static class SmartBoxHooks
IntPtr geAddr = new IntPtr(textSection.TextBaseVa + geOff);
if (hookedAddresses.Add(geAddr))
{
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint> pGeDetour = &DispatchGameEventDetour;
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, uint> pGeDetour = &DispatchGameEventDetour;
MinHook.Hook(geAddr, (IntPtr)pGeDetour, out _originalDispatchGameEventPtr);
RynthLog.Verbose($"Compat: game-event hook ready @ 0x{geAddr.ToInt32():X8}");
}
@ -109,58 +114,192 @@ internal static class SmartBoxHooks
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static unsafe uint DispatchSmartBoxEventDetour(IntPtr thisPtr, IntPtr blob)
{
MainThreadGuard.RecordIfFirst();
RecursionGuard.Tick("SmartBoxHooks.DispatchSmartBoxEvent");
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint>)_originalDispatchSmartBoxEventPtr;
if (!LoginLifecycleHooks.HasObservedLoginComplete)
{
CharacterCaptureHooks.ProcessPotentialCharacterMessage(blob, isGameEvent: false);
try { CharacterCaptureHooks.ProcessPotentialCharacterMessage(blob, isGameEvent: false); } catch { }
return pOriginal(thisPtr, blob);
}
SmartBoxEventInfo info = ReadSmartBoxEventInfo(blob);
DiagEvent("SB", false, blob, info);
uint status = pOriginal(thisPtr, blob);
TryQueueHealthUpdate(blob, info);
// Game events arrive as 0xF7B0 wrapper: [F7B0][playerId][seq][innerEventType][...]
// Check for IdentifyObject response (inner event 0xC9) after the original processes it.
if (info.Opcode == GameEventOpcode)
TryHandleGameEvent(blob, info);
else if (info.Opcode == 0xC9 && info.RawObjectId != 0)
TryCacheVitalsFromIdentify(info.RawObjectId);
if (info.RawObjectId != 0 &&
(info.Opcode == PositionUpdateOpcode ||
info.Opcode == PlayerPositionUpdateOpcode ||
info.Opcode == VectorUpdateOpcode ||
info.Opcode == UpdateObjectOpcode))
try
{
PluginManager.QueueUpdateObject(info.RawObjectId);
TryQueueHealthUpdate(blob, info);
TryQueueDamageEvent(blob, info);
if (info.RawObjectId != 0 &&
(info.Opcode == PositionUpdateOpcode ||
info.Opcode == PlayerPositionUpdateOpcode ||
info.Opcode == VectorUpdateOpcode ||
info.Opcode == UpdateObjectOpcode))
{
PluginManager.QueueUpdateObject(info.RawObjectId);
}
}
catch { }
return status;
}
// UIQueueManager::ProcessNetBlobData(this, uint* data, int size). thiscall:
// `this` in ECX (thisPtr), then the two stack args (data, size). The inner
// GameEvent type is *data; the event payload follows at data+4. `size` is the
// payload byte LENGTH — verified against the live binary: the hooked fn's
// prologue computes its own bound as `lea esi,[data+size]`. NOTE: this is a
// DIFFERENT function/shape than DispatchSmartBoxEvent — must keep the 2nd
// stack arg or the thiscall callee-cleanup imbalances the stack and crashes AC.
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static unsafe uint DispatchGameEventDetour(IntPtr thisPtr, IntPtr blob)
private static unsafe uint DispatchGameEventDetour(IntPtr thisPtr, IntPtr data, int size)
{
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint>)_originalDispatchGameEventPtr;
MainThreadGuard.RecordIfFirst();
// Engine-side BusyCount watchdog: fires on every inbound game event
// while in-world (AC's main thread). Self-heals busy-count desync.
try { BusyCountHooks.CheckWatchdog(); } catch { }
RecursionGuard.Tick("SmartBoxHooks.DispatchGameEvent");
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, uint>)_originalDispatchGameEventPtr;
// Log game event opcodes for discovery
SmartBoxEventInfo info = ReadSmartBoxEventInfo(blob);
TryQueueHealthUpdate(blob, info);
try
{
// Reject undersized payloads instead of clamping up: an inflated
// bound would let parsers read past the real payload (uncatchable
// NativeAOT AV on a page boundary).
if (data != IntPtr.Zero && size >= 4)
{
uint eventType = unchecked((uint)Marshal.ReadInt32(data));
int len = size > 0x4000 ? 0x4000 : size;
ParseGameEvent(eventType, data, (uint)len);
}
}
catch { }
// Always attempt capture from game events (pre-login)
CharacterCaptureHooks.ProcessPotentialCharacterMessage(blob, isGameEvent: true);
return pOriginal(thisPtr, data, size);
}
uint result = pOriginal(thisPtr, blob);
private static int _geEventLogCount;
private static int _hpReadLogCount;
// After the original handler processes 0xC9 (IdentifyObject response),
// the weenie's qualities are populated — read maxHealth and cache it.
if (info.Opcode == 0xC9 && info.RawObjectId != 0)
TryCacheVitalsFromIdentify(info.RawObjectId);
// Parse an inbound GameEvent for the events combat cares about. `data` points
// at the event blob: inner type @ +0, payload @ +4. `size` bounds reads.
private static void ParseGameEvent(uint eventType, IntPtr data, uint size)
{
// Diagnostic: surface the first handful of combat-range events so the hook
// can be verified live and any offset corrected from real bytes. Capped.
if (eventType >= 0x0180 && eventType <= 0x01E0 && _geEventLogCount < 40)
{
_geEventLogCount++;
uint d1 = size >= 8 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))) : 0;
uint d2 = size >= 12 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 8))) : 0;
uint d3 = size >= 16 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 12))) : 0;
RynthLog.Compat($"GE evt=0x{eventType:X4} len={size} p=[{d1:X8} {d2:X8} {d3:X8}]");
}
return result;
switch (eventType)
{
case 0x01C0: // UpdateHealth: [targetId u32][ratio f32]
if (size >= 12)
{
uint targetId = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4)));
float ratio = Marshal.PtrToStructure<float>(IntPtr.Add(data, 8));
uint maxHealth = 0, currentHealth = 0;
// We're on AC's main thread here, so read the creature's REAL
// MaxHealth straight from its qualities (SEH-guarded, appraisal-
// free) — fixes the bogus 50 stub for mobs the char can't assess.
// The plugin QueryHealth()s its combat target on lock, which is
// what makes this fire for the mobs it's actually fighting.
// Falls back to the wire-parsed appraisal cache if the read fails.
bool gotReal = ClientObjectHooks.TryReadCreatureMaxHealth(targetId, out uint realMax) && realMax > 0;
if (gotReal)
maxHealth = realMax;
else if (ObjectQualityCache.TryGetCreatureVitals(targetId, out CreatureVitals exact) && exact.MaxHealth > 0)
maxHealth = exact.MaxHealth;
if (maxHealth > 0)
currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(ratio, 0f, 1f));
if (_hpReadLogCount < 25)
{
_hpReadLogCount++;
RynthLog.Compat($"Creature HP id=0x{targetId:X8}: sehRead={(gotReal ? realMax.ToString() : "none")} used={maxHealth} ratio={ratio:0.00}");
}
PluginManager.QueueUpdateHealth(targetId, ratio, currentHealth, maxHealth);
}
break;
case 0x01B1: // AttackerNotification (we hit)
case 0x01B2: // DefenderNotification (we're hit)
ParseGameEventDamage(eventType, data, size);
break;
case 0x01AD: // KillerNotification — death message string (we got a kill)
{
string? msg = ReadString16Latin1(data, 4, size);
if (!string.IsNullOrEmpty(msg))
{
if (_killNotifyLogCount < 12)
{
_killNotifyLogCount++;
RynthLog.Compat($"Combat: kill notify '{msg}'");
}
PluginManager.QueueKillNotification(msg);
}
break;
}
case 0x01C7: // UseDone: [errorType u32] — server finished an action
// (cast/use) with WeenieError.None(0) = completed, or an
// error (0x1D = YoureTooBusy). Read-only observation: bump
// a monotonic counter so the plugin can pace combat casts
// on real server completion instead of a blind interval.
// This is the authoritative ACE Player.IsBusy lifecycle
// signal — it never touches client m_cBusy.
{
uint err = size >= 8 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))) : 0;
int seq = System.Threading.Interlocked.Increment(ref _useDoneSeq);
if (_useDoneLogCount < 25)
{
_useDoneLogCount++;
RynthLog.Compat($"UseDone seq={seq} err=0x{err:X}");
}
break;
}
}
}
// Monotonic count of inbound UseDone (0x1C7) events. The plugin records this
// at cast time and re-reads it to detect the server finishing the cast.
private static int _useDoneSeq;
private static int _useDoneLogCount;
public static int GetUseDoneSeq() => System.Threading.Volatile.Read(ref _useDoneSeq);
// AttackerNotification (0x01B1) / DefenderNotification (0x01B2). Payload at
// data+4: string16 name, u32 damageType, f64 percent, u32 damage,
// [u32 damageLocation (defender only),] u32 crit, …. Read-only byte math.
private static void ParseGameEventDamage(uint eventType, IntPtr data, uint size)
{
if (size < 24) return;
bool attacker = eventType == 0x01B1;
int nameLen = (ushort)Marshal.ReadInt16(IntPtr.Add(data, 4));
int strBlock = ((2 + nameLen + 3) / 4) * 4; // u16 len + chars, padded to a multiple of 4
int off = 4 + strBlock; // → damageType
int critOff = off + (attacker ? 16 : 20); // type(4)+percent(8)+damage(4)[+dmgLoc(4)]
if (critOff + 4 > size) return;
uint damageType = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, off)));
uint damage = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, off + 12)));
uint crit = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, critOff)));
if (damage == 0 || damage > 1_000_000) return;
if (_damageEventLogCount < 12)
{
_damageEventLogCount++;
RynthLog.Compat($"Combat: damage evt 0x{eventType:X3} dmg={damage} crit={crit} atk={attacker} len={size}");
}
PluginManager.QueueCombatDamage(damage, damageType, crit != 0, attacker);
}
private static SmartBoxEventInfo ReadSmartBoxEventInfo(IntPtr blob)
@ -206,13 +345,15 @@ internal static class SmartBoxHooks
uint maxHealth = 0;
uint currentHealth = 0;
if (ClientObjectHooks.TryGetWeenieObjectPtr(targetId, out IntPtr pWeenie))
// Appraisal-only: emit an absolute health pair ONLY from a real
// appraisal's wire-parsed CreatureProfile (id-keyed). With no
// appraisal, leave max=0 so the UI falls back to a % — the
// pointer-cache and creature Inq maxes are unreliable on ACE and
// fabricated wildly wrong values (e.g. 50/50 for a 190-hp mob).
if (ObjectQualityCache.TryGetCreatureVitals(targetId, out CreatureVitals exact) && exact.MaxHealth > 0)
{
if (ObjectQualityCache.TryGetMaxHealth(pWeenie, out uint cached))
{
maxHealth = cached;
currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(ratio, 0f, 1f));
}
maxHealth = exact.MaxHealth;
currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(ratio, 0f, 1f));
}
PluginManager.QueueUpdateHealth(targetId, ratio, currentHealth, maxHealth);
@ -222,13 +363,22 @@ internal static class SmartBoxHooks
}
}
private static int _identifyLogCount;
private static int _damageEventLogCount;
private static void TryHandleGameEvent(IntPtr blob, SmartBoxEventInfo info)
// AttackerNotification (0x01B1, you hit) / DefenderNotification (0x01B2, you're
// hit) carry the EXACT per-hit damage + crit — the only client-side source of
// real damage numbers (chat is flavor text; health deltas miss one-shots).
// These arrive as GameEvents whose blob envelope is
// [recipientId][sequence][eventType][payload] (eventType at +8), while
// SmartBox-dispatched events put eventType at +0. Detect the eventType at
// either offset, then parse the payload that follows:
// string16 name (u16 charCount + cp1252 1-byte chars, padded so (2+len)%4==0)
// u32 damageType, f64 percent, u32 damage, [u32 damageLocation (defender),]
// u32 crit, u64 attackConditions
// Pure read-only byte math (no allocation) to stay detour-safe.
private static void TryQueueDamageEvent(IntPtr blob, SmartBoxEventInfo info)
{
// 0xF7B0 game event layout: [0xF7B0(4)][playerId(4)][sequence(4)][innerEventType(4)][eventData...]
// Minimum size: 16 bytes for the header
if (blob == IntPtr.Zero || info.BlobSize < 16)
if (blob == IntPtr.Zero || info.BlobSize < 24)
return;
try
@ -237,43 +387,172 @@ internal static class SmartBoxHooks
if (payloadPtr == IntPtr.Zero)
return;
uint innerEvent = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, 12)));
uint et0 = unchecked((uint)Marshal.ReadInt32(payloadPtr));
uint et8 = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, 8)));
// 0xC9 = IdentifyObject response
// Layout after inner event type: [objectId(4)][flags(4)][success(4)][data...]
if (innerEvent == 0xC9 && info.BlobSize >= 20)
{
uint objectId = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, 16)));
if (objectId != 0)
TryCacheVitalsFromIdentify(objectId);
}
}
catch
{
}
}
int nameOff;
uint eventType;
if (et0 == 0x01B1 || et0 == 0x01B2) { eventType = et0; nameOff = 4; } // SmartBox-style
else if (et8 == 0x01B1 || et8 == 0x01B2) { eventType = et8; nameOff = 12; } // GameEvent envelope
else return;
private static void TryCacheVitalsFromIdentify(uint objectId)
{
try
{
if (!ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out IntPtr pWeenie) || pWeenie == IntPtr.Zero)
bool attacker = eventType == 0x01B1;
int nameLen = (ushort)Marshal.ReadInt16(IntPtr.Add(payloadPtr, nameOff));
int strBlock = ((2 + nameLen + 3) / 4) * 4; // u16 len + chars, padded to a multiple of 4
int off = nameOff + strBlock; // → damageType
int critOff = off + (attacker ? 16 : 20); // type(4)+percent(8)+damage(4)[+dmgLoc(4)]
if (critOff + 4 > info.BlobSize)
return;
// We're on the game thread (DispatchGameEvent), so InqAttribute2ndStruct is safe.
if (PlayerVitalsHooks.TryReadObjectMaxHealth(pWeenie, out uint maxHealth) && maxHealth > 0)
{
ObjectQualityCache.SetMaxHealth(pWeenie, maxHealth);
uint damageType = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, off)));
uint damage = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, off + 12)));
uint crit = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, critOff)));
if (damage == 0 || damage > 1_000_000)
return;
int count = Interlocked.Increment(ref _identifyLogCount);
if (count <= 12)
RynthLog.Verbose($"Compat: identify 0xC9 obj=0x{objectId:X8} maxHealth={maxHealth}");
if (_damageEventLogCount < 12)
{
_damageEventLogCount++;
RynthLog.Compat($"Combat: damage evt 0x{eventType:X3} nameOff={nameOff} dmg={damage} crit={crit} atk={attacker} blob={info.BlobSize}");
}
PluginManager.QueueCombatDamage(damage, damageType, crit != 0, attacker);
}
catch
{
}
}
private static int _killNotifyLogCount;
// KillerNotification (0x01AD) is sent to the player ONLY when they kill
// something, at the lethal hit — before the death animation plays out and
// the creature reclassifies to a corpse. That makes it the EARLIEST
// reliable "target dead" signal: the health=0 update and the Monster->Corpse
// flip both land at/after the corpse swap (ACE delays CreateCorpse by the
// full death-animation length), so combat that paces on those would burn a
// second full cast at an already-dead mob. Payload is a single string16 —
// the formatted death message with the victim name embedded; there is NO
// object id (GameEventKillerNotification just WriteString16L's the text).
// We forward the string so the plugin can match it against its one active
// target by name. Same envelope ambiguity as the damage events: eventType
// at +0 (SmartBox-style) or +8 (GameEvent envelope); the string16 follows
// immediately after the eventType u32.
private static void TryQueueKillNotification(IntPtr blob, SmartBoxEventInfo info)
{
if (blob == IntPtr.Zero || info.BlobSize < 6)
return;
try
{
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
if (payloadPtr == IntPtr.Zero)
return;
uint et0 = unchecked((uint)Marshal.ReadInt32(payloadPtr));
uint et8 = info.BlobSize >= 12 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, 8))) : 0;
int strOff;
if (et0 == 0x01AD) strOff = 4; // SmartBox-style: eventType at +0
else if (et8 == 0x01AD) strOff = 12; // GameEvent envelope: eventType at +8
else return;
string? deathMessage = ReadString16Latin1(payloadPtr, strOff, info.BlobSize);
if (string.IsNullOrEmpty(deathMessage))
return;
if (_killNotifyLogCount < 12)
{
_killNotifyLogCount++;
RynthLog.Compat($"Combat: kill notify strOff={strOff} blob={info.BlobSize} msg='{deathMessage}'");
}
PluginManager.QueueKillNotification(deathMessage);
}
catch
{
}
}
// Reads an AC string16 (u16 char count + that many 1-byte cp1252 chars) at
// the given payload offset, bounded by the blob size. Returns null on a
// missing/oversize length so a corrupt field can't allocate wildly inside
// this main-thread detour. High bytes are taken as Latin-1 (monster names
// are ASCII in practice). One small string alloc per kill — the same
// pattern ChatCallbackHooks already uses for inbound chat capture.
private static string? ReadString16Latin1(IntPtr payloadPtr, int off, uint blobSize)
{
if (off < 0 || off + 2 > blobSize) return null;
int len = (ushort)Marshal.ReadInt16(IntPtr.Add(payloadPtr, off));
if (len <= 0 || len > 256) return null;
if (off + 2 + len > blobSize) return null;
Span<char> chars = stackalloc char[len];
for (int i = 0; i < len; i++)
chars[i] = (char)Marshal.ReadByte(IntPtr.Add(payloadPtr, off + 2 + i));
return new string(chars);
}
// ── RE instrumentation (TEMPORARY) ───────────────────────────────────
// Diagnose why combat GameEvents (damage 0x1B1/2, kill 0x1AC/AD, health
// 0x1C0) don't reach the parsers on the user's Decal-coexistence client.
// Logs three things, all capped: (1) detour ALIVE + busyness — proves the
// hook fires and isn't on the wrong function; (2) any combat-range event's
// first dwords (COMBAT) so we see the opcode + envelope offset; (3) for the
// game-event detour, the first 30 events unfiltered (GE-ANY) so structure is
// visible even if the opcode sits at an unexpected offset. Remove once fixed.
private static int _geFire, _sbFire, _geCombat, _sbCombat, _geAny;
private static unsafe void DiagEvent(string tag, bool isGe, IntPtr blob, SmartBoxEventInfo info)
{
int fired = isGe ? ++_geFire : ++_sbFire;
if (fired == 1 || fired == 50 || fired % 500 == 0)
RynthLog.Compat($"{tag}-ALIVE fired={fired} lastOp=0x{info.Opcode:X4} blob={info.BlobSize}");
if (blob == IntPtr.Zero || info.BlobSize < 4)
return;
try
{
IntPtr p = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
if (p == IntPtr.Zero)
return;
uint sz = info.BlobSize;
uint et0 = unchecked((uint)Marshal.ReadInt32(p));
uint w1 = sz >= 8 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(p, 4))) : 0;
uint et8 = sz >= 12 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(p, 8))) : 0;
uint w3 = sz >= 16 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(p, 12))) : 0;
uint w4 = sz >= 20 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(p, 16))) : 0;
bool combat = (et0 >= 0x0180 && et0 <= 0x01E0) || (et8 >= 0x0180 && et8 <= 0x01E0);
if (combat)
{
ref int c = ref (isGe ? ref _geCombat : ref _sbCombat);
if (c < 50)
{
c++;
RynthLog.Compat($"{tag}-COMBAT sz={sz} w=[{et0:X8} {w1:X8} {et8:X8} {w3:X8} {w4:X8}]");
}
}
else if (isGe && _geAny < 30)
{
_geAny++;
RynthLog.Compat($"GE-ANY sz={sz} w=[{et0:X8} {w1:X8} {et8:X8} {w3:X8} {w4:X8}]");
}
}
catch { }
}
// WireParseIdentifyFromBlob / TryCacheVitalsFromIdentify removed 2026-05-18:
// calling CombatActionHooks.TryParseIdentifyResponse from an [UnmanagedCallersOnly]
// detour on AC's main thread triggers ObjectQualityCache dictionary growth
// (allocation) for each newly-identified mob → GC during the reverse-P/Invoke
// transition → RhpReversePInvokeAttachOrTrapThread2 STATUS_FAIL_FAST (silent
// process death, no dialog). Mob health display falls back to ratio (%) mode;
// absolute values can be restored via a pre-allocated pump-thread ring buffer.
private readonly record struct SmartBoxEventInfo(uint Opcode, uint RawObjectId, uint BlobSize);
}

View file

@ -60,9 +60,14 @@ internal static class SmartBoxLocator
if ((mbi.Protect & READABLE_MASK) == 0)
return false;
// Ensure the committed region covers the full requested range
int regionEnd = mbi.BaseAddress.ToInt32() + mbi.RegionSize.ToInt32();
int requestEnd = address.ToInt32() + size;
// Ensure the committed region covers the full requested range.
// Deep-audit finding #32 (2026-06-18): this used signed 32-bit
// arithmetic (ToInt32()) — acclient.exe is LARGE_ADDRESS_AWARE so
// addresses above 0x7FFFFFFF are reachable, and ToInt32() on those
// can wrap. Do the comparison in 64-bit (every caller passes a small
// compile-time size, so no overflow risk on that side).
long regionEnd = mbi.BaseAddress.ToInt64() + mbi.RegionSize.ToInt64();
long requestEnd = address.ToInt64() + size;
return requestEnd <= regionEnd;
}

View file

@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// On startup, reads a user-editable file at
/// <c>%APPDATA%\RynthCore\string_anchors.txt</c> and, for each non-blank /
/// non-comment line, runs <see cref="StringRefScanner.DumpStringAnchors"/>.
///
/// Workflow for figuring out which function a string anchors:
/// 1. Pick a candidate string you think might live in AC's body for a
/// function you want to hook (e.g. "ClientMagicSystem::CastSpell",
/// "Combat::CastSpell"). One per line in the file.
/// 2. Launch any RynthCore-injected acclient.exe.
/// 3. Read the resulting Compat lines in <c>RynthCore.log</c>:
/// StringRef: '...' @ 0xVA — pushed by N site(s); function entries: 0x...
/// A single function entry means that string uniquely identifies that
/// function — wire it into the relevant hook as the anchor.
/// 4. Iterate the file until each function you care about has a unique
/// string anchor.
///
/// File format: one literal per line, blank lines and lines starting with
/// '#' are ignored. No quoting; everything between BOM-stripped start of
/// line and the trailing newline is the literal.
/// </summary>
internal static class StringAnchorDiagnostic
{
private static readonly byte[] CombatPrologue =
[0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8];
private static readonly byte[] GenericPrologue =
[0x55, 0x8B, 0xEC]; // push ebp; mov ebp, esp — wider net than CombatPrologue
public static string FilePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"string_anchors.txt");
public static void RunIfConfigured()
{
try
{
string path = FilePath;
if (!File.Exists(path))
return; // No file → no diagnostic; quiet.
string[] rawLines = File.ReadAllLines(path);
var literals = new List<string>(rawLines.Length);
foreach (string raw in rawLines)
{
string line = raw.Trim();
if (line.Length == 0) continue;
if (line.StartsWith('#')) continue;
literals.Add(line);
}
if (literals.Count == 0)
{
RynthLog.Compat($"StringAnchorDiagnostic: '{path}' has no candidate strings (all blank/comment).");
return;
}
if (!AcClientModule.TryReadTextSection(out AcClientTextSection module))
{
RynthLog.Compat("StringAnchorDiagnostic: acclient.exe not readable, skipping.");
return;
}
// One-time per-process dump of every ASCII string ≥ 8 chars in
// the image. Lives next to engine.json so the user (or this
// engine on next launch) can grep it for real anchor candidates
// when guessing fails. Cheap (~1s) and read-only.
string dumpPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"acclient_strings.txt");
try
{
StringRefScanner.DumpAllStrings(module, dumpPath, minLength: 8);
}
catch (Exception ex)
{
RynthLog.Compat($"StringAnchorDiagnostic: string dump failed — {ex.GetType().Name}: {ex.Message}");
}
RynthLog.Compat($"StringAnchorDiagnostic: scanning {literals.Count} candidate string(s) against acclient.exe ({module.Bytes.Length:X} bytes).");
// Try the tight CombatPrologue first (matches the same prologue
// pattern the existing pattern scans use, so anchor results are
// directly comparable to what _castSpell etc. would bind to).
RynthLog.Compat("StringAnchorDiagnostic: --- pass 1: CombatPrologue (83 EC 0C 53 56 57 E8) ---");
StringRefScanner.DumpStringAnchors(module, literals, CombatPrologue);
// Then a generic push-ebp prologue. Many AC functions don't use
// the combat prologue — this widens the net.
RynthLog.Compat("StringAnchorDiagnostic: --- pass 2: generic prologue (55 8B EC push ebp; mov ebp, esp) ---");
StringRefScanner.DumpStringAnchors(module, literals, GenericPrologue);
RynthLog.Compat("StringAnchorDiagnostic: scan complete.");
}
catch (Exception ex)
{
RynthLog.Compat($"StringAnchorDiagnostic: failed — {ex.GetType().Name}: {ex.Message}");
}
}
}

View file

@ -0,0 +1,274 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Finds AC client functions by anchoring on string literals that those
/// functions push onto the stack (for printf/debug-trace/error messages).
///
/// Why this exists: the existing PatternScanner.FindPattern + FindPrologueBefore
/// approach matches on a generic 6-byte prologue (e.g. `83 EC 0C 53 56 57 E8`)
/// that dozens of functions share. On retail AC the body opcodes we anchor on
/// (`mov [edx], imm32`) happen to make the first match correct, but on ACE
/// rebuilds the same prologue matches a *different* function — leading to
/// `_castSpell` and `InstallInnerDispatcherHook` calling/hooking the wrong
/// function and AVing AC.
///
/// String references are far more discriminating: a string like
/// "Combat::CastSpell" is referenced by exactly one function (the one that
/// logs it on error), so finding the `push &string` site and walking back to
/// the function prologue gives a verifiable anchor.
///
/// Workflow:
/// 1. Identify a string that AC's target function pushes (run strings.exe
/// on acclient.exe, look for self-naming debug/error messages).
/// 2. Call FindFunctionsByStringRef("Combat::CastSpell", prologue).
/// 3. If exactly one match, that's the function. If multiple, narrow with
/// a second string or fall back to a body-pattern check.
/// 4. If zero matches, the string isn't present in this binary — the
/// caller should fall back to a pattern scan or refuse to bind.
/// </summary>
internal static class StringRefScanner
{
/// <summary>
/// Find the absolute VA of a NUL-terminated ASCII string literal inside
/// the loaded acclient.exe image window. Returns 0 if not present.
///
/// Note: <see cref="AcClientModule.TryReadTextSection"/> reads from
/// moduleBase+0x1000 to end-of-image, so the byte window covers .text
/// AND .rdata AND .data. String literals live in .rdata, which is
/// included.
/// </summary>
public static int FindStringVa(AcClientTextSection module, string literal)
{
if (string.IsNullOrEmpty(literal))
return 0;
byte[] needle = Encoding.ASCII.GetBytes(literal);
byte[] haystack = module.Bytes;
int max = haystack.Length - needle.Length - 1;
for (int i = 0; i <= max; i++)
{
// Match the literal exactly...
bool match = true;
for (int j = 0; j < needle.Length; j++)
{
if (haystack[i + j] != needle[j])
{
match = false;
break;
}
}
if (!match) continue;
// ...and require a NUL byte after it so we don't match a prefix
// of a longer string ("CastSpell" inside "CastSpellOnTarget").
if (haystack[i + needle.Length] != 0)
continue;
return module.TextBaseVa + i;
}
return 0;
}
/// <summary>
/// Find every `push imm32` instruction whose immediate equals
/// <paramref name="targetVa"/>. Opcode 0x68 + 4 little-endian bytes.
/// This is how MSVC-emitted C++ pushes a string literal address before
/// a printf-family call. Returns file offsets relative to
/// <c>module.TextBaseVa</c>.
/// </summary>
public static List<int> FindPushImm32Sites(AcClientTextSection module, int targetVa)
{
var sites = new List<int>();
byte b0 = (byte)(targetVa & 0xFF);
byte b1 = (byte)((targetVa >> 8) & 0xFF);
byte b2 = (byte)((targetVa >> 16) & 0xFF);
byte b3 = (byte)((targetVa >> 24) & 0xFF);
byte[] bytes = module.Bytes;
int max = bytes.Length - 5;
for (int i = 0; i < max; i++)
{
if (bytes[i] != 0x68) continue;
if (bytes[i + 1] != b0) continue;
if (bytes[i + 2] != b1) continue;
if (bytes[i + 3] != b2) continue;
if (bytes[i + 4] != b3) continue;
sites.Add(i);
}
return sites;
}
/// <summary>
/// Walk backward from <paramref name="siteOff"/> looking for the nearest
/// occurrence of <paramref name="prologue"/>. Returns the offset of the
/// matched prologue, or -1 if none found within <paramref name="maxBackward"/>.
///
/// Unlike PatternScanner.FindPrologueBefore which has its own search loop,
/// this version is intentionally local to a string-ref site so the
/// match window stays small and a global pattern can't accidentally
/// match a function far away.
/// </summary>
public static int FindFunctionEntryBefore(AcClientTextSection module, int siteOff, byte[] prologue, int maxBackward = 0x2000)
{
if (prologue.Length == 0)
return -1;
byte[] bytes = module.Bytes;
int floor = Math.Max(0, siteOff - maxBackward);
for (int i = siteOff; i >= floor; i--)
{
if (i + prologue.Length > bytes.Length)
continue;
bool match = true;
for (int j = 0; j < prologue.Length; j++)
{
if (bytes[i + j] != prologue[j])
{
match = false;
break;
}
}
if (match)
return i;
}
return -1;
}
/// <summary>
/// One-call helper: locate every function whose body pushes
/// <paramref name="literal"/>, by finding the string in the image,
/// finding every <c>push string_va</c> site, and walking back to the
/// nearest matching prologue.
///
/// Returns the set of absolute VAs of candidate function entries.
/// Caller should treat a single-result list as a hard match, and a
/// multi-result list as "needs more disambiguation."
/// </summary>
public static List<int> FindFunctionsByStringRef(
AcClientTextSection module,
string literal,
byte[] prologue,
int maxBackward = 0x2000)
{
var hits = new HashSet<int>();
int stringVa = FindStringVa(module, literal);
if (stringVa == 0)
return new List<int>();
foreach (int site in FindPushImm32Sites(module, stringVa))
{
int funcOff = FindFunctionEntryBefore(module, site, prologue, maxBackward);
if (funcOff >= 0)
hits.Add(module.TextBaseVa + funcOff);
}
return new List<int>(hits);
}
/// <summary>
/// Walks the loaded image and writes every printable ASCII run of at
/// least <paramref name="minLength"/> bytes (terminated by NUL or any
/// non-printable byte) to <paramref name="outputPath"/>, one per line,
/// in the form: <c>0xVA\ttext</c>.
///
/// This is the catalog the user (or a future automated anchor picker)
/// greps for real anchors. AC client release builds tend to strip
/// __FUNCTION__-style debug names but keep user-facing strings, format
/// strings, RTTI type descriptors (".?AVClassName@@"), and file paths
/// (when assertions or trace macros remained) — those are the real
/// hooks for string anchoring.
/// </summary>
public static void DumpAllStrings(AcClientTextSection module, string outputPath, int minLength = 8)
{
byte[] bytes = module.Bytes;
int baseVa = module.TextBaseVa;
using var sw = new System.IO.StreamWriter(outputPath, append: false, encoding: System.Text.Encoding.UTF8);
sw.WriteLine($"# acclient.exe ASCII string dump — base VA 0x{baseVa:X8}, size 0x{bytes.Length:X}, minLength={minLength}");
sw.WriteLine("# Each line: <hex VA><TAB><string>");
int i = 0;
int written = 0;
while (i < bytes.Length)
{
byte b = bytes[i];
if (b < 0x20 || b > 0x7E)
{
i++;
continue;
}
int start = i;
while (i < bytes.Length)
{
byte c = bytes[i];
if (c < 0x20 || c > 0x7E)
break;
i++;
}
int len = i - start;
if (len >= minLength)
{
int va = baseVa + start;
// ASCII-only payload, safe to convert via Encoding.ASCII.
string text = System.Text.Encoding.ASCII.GetString(bytes, start, len);
sw.Write("0x");
sw.Write(va.ToString("X8"));
sw.Write('\t');
sw.WriteLine(text);
written++;
}
}
RynthLog.Compat($"StringRef: dumped {written} string(s) of length>={minLength} to '{outputPath}'.");
}
/// <summary>
/// Diagnostic: log every string in <paramref name="literals"/> with the
/// VA we found it at, plus every push site for that string, plus the
/// nearest enclosing function entry. Useful for hand-calibration: run
/// this once with a list of candidate strings and read the log to see
/// which strings uniquely identify which functions.
/// </summary>
public static void DumpStringAnchors(AcClientTextSection module, IEnumerable<string> literals, byte[] prologue)
{
foreach (string literal in literals)
{
int va = FindStringVa(module, literal);
if (va == 0)
{
RynthLog.Compat($"StringRef: '{literal}' — NOT FOUND in image.");
continue;
}
List<int> sites = FindPushImm32Sites(module, va);
if (sites.Count == 0)
{
RynthLog.Compat($"StringRef: '{literal}' @ 0x{va:X8} — string exists but no `push imm32` site references it (may be loaded by `mov reg, imm32` or stored in vtable).");
continue;
}
var funcs = new HashSet<int>();
foreach (int site in sites)
{
int funcOff = FindFunctionEntryBefore(module, site, prologue);
if (funcOff >= 0)
funcs.Add(module.TextBaseVa + funcOff);
}
string fnList;
if (funcs.Count == 0)
{
fnList = "(no enclosing prologue match)";
}
else
{
var parts = new List<string>(funcs.Count);
foreach (int v in funcs) parts.Add($"0x{v:X8}");
fnList = string.Join(", ", parts);
}
RynthLog.Compat($"StringRef: '{literal}' @ 0x{va:X8} — pushed by {sites.Count} site(s); function entries: {fnList}");
}
}
}

View file

@ -18,22 +18,53 @@ internal static class TeleportStateHooks
private const int PlayerSystemPtrVa = 0x0087119C;
private const int TeleportInProgressOffset = 0x238;
// Phase B: resolve CPlayerSystem's address by code-xref (mov dword [CPlayerSystem],0 =
// C7 05 <addr> 00 00 00 00), operand at offset 2; the VA stays as fallback.
private static readonly byte?[] PatXrefPlayerSystem = [ 0xC7, 0x05, null, null, null, null, 0x00, 0x00, 0x00, 0x00, 0x83, 0xC6 ];
private static int _playerSystemPtrAddr = PlayerSystemPtrVa;
public static bool IsInstalled => true; // no hook needed — direct memory read
// Deep-audit finding #14 (2026-06-18): this raw-dereferenced CPlayerSystem
// unconditionally, including off AC's main thread — exposed to plugins via
// RynthCoreHost.IsPortaling() and polled constantly (NavigationEngine /
// RadarWallRenderer / NavMarkerRenderer / ExpressionEngine), some of which
// run on the Decal-coexistence pump thread. During relog/teleport teardown
// the singleton can be non-null but freed/mid-reassignment — an off-thread
// read of that is an uncatchable AV under NativeAOT (a null check alone
// doesn't protect against it). Gate to the main thread; off-thread callers
// get the last main-thread-observed value instead of touching AC memory.
private static volatile bool _cachedIsPortaling;
/// <summary>Returns true while the player is in the teleport/portal transit state.</summary>
public static unsafe bool IsPortaling
{
get
{
if (!MainThreadGuard.IsOnMainThread())
return _cachedIsPortaling;
try
{
IntPtr playerSystem = *(IntPtr*)PlayerSystemPtrVa;
if (playerSystem == IntPtr.Zero) return false;
return *(byte*)(playerSystem + TeleportInProgressOffset) != 0;
IntPtr playerSystemAddr = (IntPtr)_playerSystemPtrAddr;
if (!ClientObjectHooks.IsReadablePointer(playerSystemAddr))
return _cachedIsPortaling;
IntPtr playerSystem = *(IntPtr*)_playerSystemPtrAddr;
if (playerSystem == IntPtr.Zero)
{
_cachedIsPortaling = false;
return false;
}
IntPtr flagAddr = playerSystem + TeleportInProgressOffset;
if (!ClientObjectHooks.IsReadablePointer(flagAddr))
return _cachedIsPortaling;
bool result = *(byte*)flagAddr != 0;
_cachedIsPortaling = result;
return result;
}
catch
{
return false;
return _cachedIsPortaling;
}
}
}
@ -41,6 +72,8 @@ internal static class TeleportStateHooks
// Called from EntryPoint.Initialize chain — nothing to install for a direct read.
public static void Initialize()
{
RynthLog.Verbose($"Compat: teleport-state ready — direct read CPlayerSystem+0x238 @ PlayerSystemPtr=0x{PlayerSystemPtrVa:X8}");
if (AcClientModule.TryReadTextSection(out AcClientTextSection text))
_playerSystemPtrAddr = HookResolver.ResolveData(text, "Teleport.CPlayerSystem", PatXrefPlayerSystem, 2, PlayerSystemPtrVa).Address.ToInt32();
RynthLog.Verbose($"Compat: teleport-state ready — direct read CPlayerSystem+0x238 @ PlayerSystemPtr=0x{_playerSystemPtrAddr:X8}");
}
}

View file

@ -0,0 +1,124 @@
using System;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Installs a NATIVE null-guard on AC's tagged-text parser consumer
/// <c>FUN_0067D3C0</c> (live VA 0x0067D3C0) to kill the text-parser singleton
/// race AV.
///
/// Crash this fixes (captured 2026-06-03, native-crash.log):
/// <code>
/// code=0xC0000005 exAddr=acclient.exe+0x0027D3DA (live 0x0067D3DA) eax=0
/// 0067d3da MOV EDI,[EAX+0xC] ; EAX = parser context = 0 -> AV READ [null+0xC]
/// </code>
/// The parser context comes from the unsynchronized singleton DAT_008F881C.
/// When our off-thread plugin pump triggers a text-generation path while AC's
/// main thread is mid-parse on incoming chat (heavy Olthoi-hive combat chat),
/// the singleton races to null and this consumer dereferences it.
///
/// ⚠ This guard MUST be native. A MANAGED MinHook detour here was deployed
/// 2026-05-25 and crashed pid 20852 within ~7s: the consumer is called by AC's
/// main thread for EVERY parsed tag, so a managed detour incurs a NativeAOT
/// reverse-P/Invoke transition per tag and fail-fasts. The detour body now lives
/// entirely in RynthCore.SehTrampoline.dll (RC_TagParserGuard — pure native, no
/// managed transition). This class just installs the MinHook redirect to that
/// native detour and hands it the trampoline (original) BEFORE enabling. If the
/// parser context is null the native guard drops one parse run (returns 0); the
/// caller (FUN_0067E150) discards the return value, so that is safe.
/// </summary>
internal static class TextParserGuardHooks
{
// FUN_0067D3C0 in retail/ACE acclient.exe (byte-identical; verified at install).
private const int TargetVa = 0x0067D3C0;
// Prologue from the function start, including the literal data pointer 0x007FF308
// (bytes 5-9) — stable across retail/ACE — which makes this a strong validation
// signature. Verified unique + lands at 0x0067D3C0 offline (tools/pe_pattern.py).
private static readonly byte?[] FuncPattern =
[
0x83, 0xEC, 0x50, // SUB ESP, 0x50
0x53, // PUSH EBX
0x55, // PUSH EBP
0xB8, 0x08, 0xF3 // MOV EAX, 0x7FF308 (low bytes)
];
private static IntPtr _targetAddress;
private static int _installed;
private static string _statusMessage = "Not probed yet.";
public static bool IsInstalled => Volatile.Read(ref _installed) != 0;
public static string StatusMessage => _statusMessage;
/// <summary>Null-context parse runs the native guard has dropped (served from the
/// trampoline DLL; 0 if unavailable).</summary>
public static uint NullParamSkipCount => SehTrampoline.TagParserSkipCount;
public static void Initialize()
{
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
return;
// The detour body lives in the trampoline DLL; without it we cannot install a
// native guard, and we must NOT fall back to a managed detour (the 7s-crash).
if (!SehTrampoline.IsAvailable)
{
Volatile.Write(ref _installed, 0);
_statusMessage = "SEH trampoline unavailable.";
RynthLog.Compat("Compat: text-parser guard NOT installed — SEH trampoline unavailable (no managed fallback by design).");
return;
}
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
Volatile.Write(ref _installed, 0);
_statusMessage = "acclient.exe not available.";
return;
}
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "TextParserGuard.FUN_0067D3C0", FuncPattern, TargetVa);
if (!resolved.Success)
{
Volatile.Write(ref _installed, 0);
_statusMessage = $"unresolved (VA 0x{TargetVa:X8}).";
RynthLog.Compat($"Compat: text-parser guard NOT installed — {_statusMessage}");
return;
}
try
{
_targetAddress = resolved.Address;
IntPtr detour = SehTrampoline.GetTagParserGuardAddress();
if (detour == IntPtr.Zero)
{
Volatile.Write(ref _installed, 0);
_statusMessage = "native detour address was null.";
RynthLog.Compat($"Compat: text-parser guard NOT installed — {_statusMessage}");
return;
}
// Redirect FUN_0067D3C0 -> RC_TagParserGuard (native). HookCreate returns
// the trampoline (original); hand it to the native guard BEFORE enabling so
// the very first detoured call already has a valid original to call through.
IntPtr trampoline = MinHook.HookCreate(_targetAddress, detour);
SehTrampoline.SetTagParserOriginal(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
Volatile.Write(ref _installed, 1);
_statusMessage = $"Native parser guard @ 0x{_targetAddress.ToInt32():X8}.";
RynthLog.Compat(
$"Compat: text-parser guard ready (NATIVE) — target=0x{_targetAddress.ToInt32():X8}, " +
$"detour=0x{detour.ToInt32():X8}, trampoline=0x{trampoline.ToInt32():X8}.");
}
catch (Exception ex)
{
Volatile.Write(ref _installed, 0);
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: text-parser guard install threw {ex.GetType().Name}: {ex.Message}");
}
}
}

View file

@ -0,0 +1,244 @@
// ============================================================================
// RynthCore.Engine - Compatibility/ThreadStackSampler.cs
//
// Cross-thread stack sampler. Once per heartbeat tick, walks every other
// thread in the process via Win32 SuspendThread + GetThreadContext +
// EBP-chain unwinding. For each thread, records how deep its stack currently
// is (number of return addresses landing inside our engine module). If any
// thread crosses the runaway-depth threshold, dumps the full chain of
// engine-RVA return addresses to the log.
//
// This catches recursion that the per-detour RecursionGuard misses — namely,
// recursion contained entirely between two engine-internal methods that
// never re-enter any of our hook detours.
//
// We don't symbolicate inline; the dumped RVAs can be cross-referenced to
// the PDB after the fact.
// ============================================================================
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static class ThreadStackSampler
{
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenThread(uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint SuspendThread(IntPtr hThread);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int ResumeThread(IntPtr hThread);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetThreadContext(IntPtr hThread, IntPtr lpContext);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll")]
private static extern uint GetCurrentThreadId();
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetModuleHandleExW(uint dwFlags, IntPtr lpModuleName, out IntPtr phModule);
[DllImport("psapi.dll", SetLastError = true)]
private static extern bool GetModuleInformation(IntPtr hProcess, IntPtr hModule, out MODULEINFO lpmodinfo, uint cb);
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
[StructLayout(LayoutKind.Sequential)]
private struct MODULEINFO
{
public IntPtr lpBaseOfDll;
public uint SizeOfImage;
public IntPtr EntryPoint;
}
private const uint THREAD_SUSPEND_RESUME = 0x0002;
private const uint THREAD_GET_CONTEXT = 0x0008;
private const uint THREAD_QUERY_INFORMATION = 0x0040;
private const uint THREAD_QUERY_LIMITED_INFO = 0x0800;
private const uint CONTEXT_CONTROL = 0x00010001;
private const uint CONTEXT_INTEGER = 0x00010002;
// x86 CONTEXT layout: 716 bytes. Field offsets verified against winnt.h.
private const int CTX_SIZE = 716;
private const int CTX_OFF_EBP = 180;
private const int CTX_OFF_EIP = 184;
private const int CTX_OFF_ESP = 196;
private const int CTX_OFF_FLAGS = 0;
/// <summary>Engine module base + end, set once at first sample.</summary>
private static IntPtr _engineBase;
private static IntPtr _engineEnd;
/// <summary>Threshold for "this thread is deep in recursion": number of
/// distinct return addresses that land in our engine module.</summary>
private const int DepthAlarm = 50;
private static int _samplesEmittedTotal;
private const int MaxSamplesEmitted = 5;
public static void SampleAll()
{
if (_samplesEmittedTotal >= MaxSamplesEmitted) return;
if (_engineBase == IntPtr.Zero)
ResolveEngineRange();
if (_engineBase == IntPtr.Zero) return;
uint myTid = GetCurrentThreadId();
IntPtr ctxBuf = Marshal.AllocHGlobal(CTX_SIZE);
try
{
ProcessThread[] threads;
try { threads = new ProcessThread[Process.GetCurrentProcess().Threads.Count]; Process.GetCurrentProcess().Threads.CopyTo(threads, 0); }
catch { return; }
foreach (ProcessThread t in threads)
{
uint tid = (uint)t.Id;
if (tid == myTid) continue;
IntPtr h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_LIMITED_INFO, false, tid);
if (h == IntPtr.Zero) continue;
try
{
if (SuspendThread(h) == 0xFFFFFFFF) continue;
Marshal.WriteInt32(ctxBuf, CTX_OFF_FLAGS, (int)(CONTEXT_CONTROL | CONTEXT_INTEGER));
if (!GetThreadContext(h, ctxBuf)) continue;
uint eip = (uint)Marshal.ReadInt32(ctxBuf, CTX_OFF_EIP);
uint ebp = (uint)Marshal.ReadInt32(ctxBuf, CTX_OFF_EBP);
uint esp = (uint)Marshal.ReadInt32(ctxBuf, CTX_OFF_ESP);
int engineHits = WalkAndCount(ebp, esp, out string captured);
if (engineHits >= DepthAlarm)
{
if (Interlocked.Increment(ref _samplesEmittedTotal) > MaxSamplesEmitted) return;
RynthLog.Info("================================================================");
RynthLog.Info($"==== DEEP STACK in tid 0x{tid:X} ({tid}) name='{t.Id}' eip=0x{eip:X8} ebp=0x{ebp:X8} esp=0x{esp:X8} engineHits={engineHits} ====");
RynthLog.Info(captured);
RynthLog.Info("================================================================");
}
}
finally
{
ResumeThread(h);
CloseHandle(h);
}
}
}
finally
{
Marshal.FreeHGlobal(ctxBuf);
}
}
/// <summary>Walk EBP frame chain and count return addresses inside engine.
/// Builds a trace string (only filled if depth crosses alarm).</summary>
private static int WalkAndCount(uint ebp, uint esp, out string trace)
{
var sb = new System.Text.StringBuilder();
int hits = 0;
uint baseAddr = (uint)_engineBase.ToInt32();
uint endAddr = (uint)_engineEnd.ToInt32();
// 1) Walk EBP chain
uint cur = ebp;
for (int i = 0; i < 1024; i++)
{
if (cur == 0 || (cur & 3) != 0) break;
uint nextEbp, ret;
try
{
nextEbp = (uint)Marshal.ReadInt32((IntPtr)cur);
ret = (uint)Marshal.ReadInt32((IntPtr)cur, 4);
}
catch { break; }
if (ret >= baseAddr && ret < endAddr)
{
hits++;
if (hits <= 60)
sb.AppendLine($" ebp[{i:D3}] ret=0x{ret:X8} engine+0x{(ret - baseAddr):X}");
}
if (nextEbp <= cur || nextEbp - cur > 0x100000) break;
cur = nextEbp;
}
// 2) ESP scan as fallback (catches FPO frames)
if (hits < 5)
{
uint scanFrom = esp;
for (int i = 0; i < 4096; i++)
{
uint addr = scanFrom + (uint)(i * 4);
uint val;
try { val = (uint)Marshal.ReadInt32((IntPtr)addr); }
catch { break; }
if (val >= baseAddr && val < endAddr)
{
hits++;
if (hits <= 60)
sb.AppendLine($" esp+0x{i * 4:X4} ret=0x{val:X8} engine+0x{(val - baseAddr):X}");
}
}
}
trace = sb.ToString();
return hits;
}
private static void ResolveEngineRange()
{
try
{
// Resolve our own DLL by passing the address of one of our methods.
const uint GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS = 0x4;
const uint GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT = 0x2;
unsafe
{
delegate*<void> anchor = &Anchor;
if (!GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(IntPtr)anchor,
out IntPtr hModule) || hModule == IntPtr.Zero)
{
return;
}
if (!GetModuleInformation(GetCurrentProcess(), hModule, out MODULEINFO mi, (uint)Marshal.SizeOf<MODULEINFO>()))
return;
_engineBase = mi.lpBaseOfDll;
_engineEnd = (IntPtr)((long)mi.lpBaseOfDll + mi.SizeOfImage);
RynthLog.Info($"ThreadStackSampler: engine module range 0x{_engineBase.ToInt32():X8}..0x{_engineEnd.ToInt32():X8}");
}
}
catch (Exception ex)
{
RynthLog.Info($"ThreadStackSampler: ResolveEngineRange threw {ex.GetType().Name}: {ex.Message}");
}
}
private static void Anchor() { }
}

View file

@ -1,6 +1,7 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
@ -25,14 +26,36 @@ namespace RynthCore.Engine.Compatibility;
internal static class TimeSyncHooks
{
private const int HandleTimeSynchVa = 0x005448F0;
// Verified unique + lands exactly at HandleTimeSynchVa offline (tools/pe_pattern.py).
private static readonly byte?[] HandleTimeSynchPattern = [ 0x55, 0x8B, 0xEC, 0x83, 0xE4, 0xF8, 0x83, 0xEC, 0x10, 0x8B ];
private const int TimeSyncHeaderMTimeOffset = 24;
private static IntPtr _originalHandleTimeSynch;
private static bool _initialized;
// Server-time / wall-clock reference pair, updated each time sync arrives.
private static double _lastServerTime;
private static long _lastWallClockTicks;
// Deep-audit finding #19 (2026-06-18): these used to be two plain fields
// (double + long) written on the net thread and read on the pump thread
// with no atomicity — on x86 a 64-bit load/store isn't atomic, so a
// reader could observe a torn _lastWallClockTicks (worst case a
// mis-timed rebuff from a wildly wrong elapsed time). Publishing both as
// one immutable snapshot object, swapped via Volatile.Write/Read, fixes
// that AND the subtler cross-field issue a per-field Interlocked fix
// wouldn't: a reader can no longer see a NEW _lastServerTime paired with
// the OLD _lastWallClockTicks (or vice versa) — the reference swap is
// all-or-nothing.
private sealed class TimeSyncSnapshot
{
public readonly double ServerTime;
public readonly long WallClockTicks;
public TimeSyncSnapshot(double serverTime, long wallClockTicks)
{
ServerTime = serverTime;
WallClockTicks = wallClockTicks;
}
}
private static TimeSyncSnapshot? _snapshot;
public static bool IsInitialized => _initialized;
@ -42,12 +65,12 @@ internal static class TimeSyncHooks
/// </summary>
public static double GetCurrentServerTime()
{
long wallTicks = _lastWallClockTicks;
if (wallTicks == 0)
TimeSyncSnapshot? snap = Volatile.Read(ref _snapshot);
if (snap == null || snap.WallClockTicks == 0)
return 0;
double elapsed = (DateTime.UtcNow.Ticks - wallTicks) / (double)TimeSpan.TicksPerSecond;
return _lastServerTime + elapsed;
double elapsed = (DateTime.UtcNow.Ticks - snap.WallClockTicks) / (double)TimeSpan.TicksPerSecond;
return snap.ServerTime + elapsed;
}
public static void Initialize()
@ -55,10 +78,15 @@ internal static class TimeSyncHooks
if (_initialized)
return;
var ptr = new IntPtr(HandleTimeSynchVa);
if (!SmartBoxLocator.IsPointerInModule(ptr))
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
RynthLog.Compat($"Compat: time-sync hook pointer looks invalid (0x{HandleTimeSynchVa:X8})");
RynthLog.Compat("Compat: time-sync hook - acclient .text not readable.");
return;
}
HookResolver.ResolveResult resolved = HookResolver.Resolve(text, "TimeSync.HandleTimeSynch", HandleTimeSynchPattern, HandleTimeSynchVa);
if (!resolved.Success)
{
RynthLog.Compat($"Compat: time-sync hook unresolved (0x{HandleTimeSynchVa:X8})");
return;
}
@ -67,11 +95,11 @@ internal static class TimeSyncHooks
unsafe
{
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, IntPtr, void> detour = &HandleTimeSynchDetour;
MinHook.Hook(ptr, (IntPtr)detour, out _originalHandleTimeSynch);
MinHook.Hook(resolved.Address, (IntPtr)detour, out _originalHandleTimeSynch);
}
_initialized = true;
RynthLog.Verbose($"Compat: time-sync hook ready - HandleTimeSynch=0x{HandleTimeSynchVa:X8}");
RynthLog.Verbose($"Compat: time-sync hook ready - HandleTimeSynch=0x{resolved.Address.ToInt32():X8} ({resolved.Detail})");
}
catch (Exception ex)
{
@ -90,8 +118,7 @@ internal static class TimeSyncHooks
double serverTime = BitConverter.Int64BitsToDouble(bits);
if (serverTime > 0)
{
_lastServerTime = serverTime;
_lastWallClockTicks = DateTime.UtcNow.Ticks;
Volatile.Write(ref _snapshot, new TimeSyncSnapshot(serverTime, DateTime.UtcNow.Ticks));
}
}
}

View file

@ -9,12 +9,10 @@ namespace RynthCore.Engine.Compatibility;
internal static class UpdateObjectInventoryHooks
{
private const int UpdateObjectInventoryExpectedVa = 0x0055A190;
private static readonly byte[] UpdateObjectInventorySignature =
// Verified unique + lands at 0x0055A190 offline (tools/pe_pattern.py).
private static readonly byte?[] UpdateObjectInventoryPattern =
[
0x8B, 0x44, 0x24, 0x04, 0x50, 0xE8, 0x96, 0xE7,
0xFA, 0xFF, 0x8B, 0x4C, 0x24, 0x08, 0x51, 0x8D,
0x48, 0x3C, 0xE8, 0x69, 0xFF, 0xFF, 0xFF, 0xC2,
0x08, 0x00
0x8B, 0x44, 0x24, 0x04, 0x50, 0xE8, null, null, null, null, 0x8B, 0x4C
];
// Derived from UpdateObjectInventory disasm: lea ecx, [eax+0x3C]
@ -49,10 +47,10 @@ internal static class UpdateObjectInventoryHooks
try
{
int updateFuncOff = ResolveUpdateObjectInventoryOffset(textSection.Bytes, textSection.TextBaseVa, out bool updateUsedScan);
int updateFuncOff = ResolveUpdateObjectInventoryOffset(textSection, out bool updateUsedScan);
if (updateFuncOff < 0)
{
_statusMessage = "ACCObjectMaint::UpdateObjectInventory signature not found.";
_statusMessage = "ACCObjectMaint::UpdateObjectInventory unresolved.";
RynthLog.Compat($"Compat: update-object-inventory hook failed - {_statusMessage}");
return;
}
@ -78,31 +76,34 @@ internal static class UpdateObjectInventoryHooks
}
}
private static int ResolveUpdateObjectInventoryOffset(byte[] text, int textBaseVa, out bool usedPatternScan)
private static int ResolveUpdateObjectInventoryOffset(AcClientTextSection textSection, out bool usedPatternScan)
{
usedPatternScan = false;
int expectedOff = UpdateObjectInventoryExpectedVa - textBaseVa;
if (PatternScanner.VerifyBytes(text, expectedOff, UpdateObjectInventorySignature))
return expectedOff;
HookResolver.ResolveResult resolved = HookResolver.Resolve(
textSection, "UpdateInventory.UpdateObjectInventory", UpdateObjectInventoryPattern, UpdateObjectInventoryExpectedVa);
if (!resolved.Success)
return -1;
int scannedOff = PatternScanner.FindPattern(text, UpdateObjectInventorySignature);
if (scannedOff >= 0)
{
usedPatternScan = true;
return scannedOff;
}
return -1;
usedPatternScan = resolved.Source == HookResolver.ResolveSource.PatternScan;
return resolved.Address.ToInt32() - textSection.TextBaseVa;
}
private static void UpdateObjectInventoryDetour(IntPtr thisPtr, uint objectId, IntPtr newInventory)
{
_originalUpdateObjectInventory!(thisPtr, objectId, newInventory);
if (objectId == 0)
return;
PluginManager.QueueUpdateObjectInventory(objectId);
// Deep-audit finding #12 (2026-06-18): every sibling server-dispatch
// detour (UpdateObjectServerDispatchHooks, VectorUpdateServerDispatchHooks,
// SmartBoxHooks) wraps its queue call; this one didn't — an escaping
// throw here (e.g. OOM during the queue's lock+Enqueue) fail-fasts the
// client. Call-through stays outside the try, matching the fix note.
try
{
if (objectId != 0)
PluginManager.QueueUpdateObjectInventory(objectId);
}
catch { }
}
public static unsafe int GetContainerContents(uint containerId, uint* itemIds, int maxCount)
@ -187,9 +188,30 @@ internal static class UpdateObjectInventoryHooks
/// </summary>
private static int ScanByContainerId(uint containerId, Span<uint> itemIds)
{
// Check every object the client knows, from the identity snapshot. The old fixed
// range stopped at 0x8000FFFF, but a server hands out ids well past that once it
// has run a while, so newer items (and packs, with everything in them) were
// invisible to the bot: no bundles to craft from, inventory lookups finding nothing.
uint[] live = ClientObjectHooks.LiveObjectIds;
if (live.Length > 0)
{
int found = 0;
foreach (uint id in live)
{
if (found >= itemIds.Length) break;
if (id == containerId) continue;
if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint c, out uint w, out _))
continue;
if (c == containerId || w == containerId)
itemIds[found++] = id;
}
itemIds[..found].Sort(); // same ascending order the range scan gave
return found;
}
int written = 0;
// Scan dynamic object range (0x80000001 – 0x8000FFFF)
// No snapshot yet: scan the first dynamic object range (0x80000001 – 0x8000FFFF)
for (uint id = 0x80000001; id <= 0x8000FFFF && written < itemIds.Length; id++)
{
if (id == containerId) continue;

View file

@ -13,13 +13,10 @@ internal static class UpdateObjectServerDispatchHooks
private const int NetBlobBufPtrOffset = 0x2C;
private const int NetBlobBufSizeOffset = 0x30;
private const uint UpdateObjectOpcode = 0x0000F7DB;
private static readonly byte[] DispatchSbUpdateObjectSignature =
// Verified unique + lands at 0x006AD710 offline (tools/pe_pattern.py).
private static readonly byte?[] DispatchSbUpdateObjectPattern =
[
0x81, 0xEC, 0xB8, 0x01, 0x00, 0x00, 0x53, 0x8B,
0x9C, 0x24, 0xC4, 0x01, 0x00, 0x00, 0x85, 0xDB,
0x74, 0x0B, 0x8B, 0x84, 0x24, 0xC0, 0x01, 0x00,
0x00, 0x85, 0xC0, 0x75, 0x0D, 0xB8, 0x03, 0x00,
0x00, 0x00
0x81, 0xEC, 0xB8, 0x01, 0x00, 0x00, 0x53, 0x8B, 0x9C, 0x24, 0xC4, 0x01, 0x00, 0x00, 0x85, 0xDB, 0x74, 0x0B, 0x8B, 0x84, 0x24, 0xC0, 0x01, 0x00, 0x00, 0x85, 0xC0, 0x75, 0x0D, 0xB8, 0x03, 0x00, 0x00, 0x00, 0x5B, 0x81, 0xC4, 0xB8, 0x01, 0x00, 0x00, 0xC3, 0x8B, 0x43, 0x2C, 0x56, 0x8B, 0x73, 0x30, 0x89, 0x44, 0x24, 0x08, 0x8B, 0x08, 0x57, 0x8B, 0xF8, 0x83, 0xC0, 0x04, 0x81, 0xF9, 0xDB
];
private static IntPtr _originalDispatchSbUpdateObjectPtr;
@ -41,10 +38,10 @@ internal static class UpdateObjectServerDispatchHooks
return;
}
int funcOff = DispatchSbUpdateObjectVa - textSection.TextBaseVa;
if (!PatternScanner.VerifyBytes(textSection.Bytes, funcOff, DispatchSbUpdateObjectSignature))
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "UpdateObject.DispatchSbUpdateObject", DispatchSbUpdateObjectPattern, DispatchSbUpdateObjectVa);
if (!resolved.Success)
{
_statusMessage = $"CM_Physics::DispatchSB_UpdateObject signature mismatch @ 0x{DispatchSbUpdateObjectVa:X8}.";
_statusMessage = $"CM_Physics::DispatchSB_UpdateObject unresolved (VA 0x{DispatchSbUpdateObjectVa:X8}).";
RynthLog.Compat($"Compat: update-object hook failed - {_statusMessage}");
return;
}
@ -53,7 +50,7 @@ internal static class UpdateObjectServerDispatchHooks
{
unsafe
{
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_targetAddress = resolved.Address;
delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint> pDetour = &DispatchSbUpdateObjectDetour;
MinHook.Hook(_targetAddress, (IntPtr)pDetour, out _originalDispatchSbUpdateObjectPtr);
}
@ -72,6 +69,7 @@ internal static class UpdateObjectServerDispatchHooks
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static unsafe uint DispatchSbUpdateObjectDetour(IntPtr smartBoxPtr, IntPtr blob)
{
RecursionGuard.Tick("UpdateObjectServerDispatchHooks.DispatchSbUpdateObject");
var pOriginal = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint>)_originalDispatchSbUpdateObjectPtr;
uint objectId = TryReadUpdatedObjectId(blob);
@ -79,11 +77,15 @@ internal static class UpdateObjectServerDispatchHooks
if (!LoginLifecycleHooks.HasObservedLoginComplete || objectId == 0)
return status;
int count = Interlocked.Increment(ref _dispatchCount);
if (count <= 8)
RynthLog.Verbose($"Compat: update object #{count} id=0x{objectId:X8} status={status}");
try
{
int count = Interlocked.Increment(ref _dispatchCount);
if (count <= 8)
RynthLog.Verbose($"Compat: update object #{count} id=0x{objectId:X8} status={status}");
PluginManager.QueueUpdateObject(objectId);
PluginManager.QueueUpdateObject(objectId);
}
catch { }
return status;
}

View file

@ -12,12 +12,10 @@ internal static class VectorUpdateServerDispatchHooks
private const int NetBlobBufPtrOffset = 0x2C;
private const int NetBlobBufSizeOffset = 0x30;
private const uint VectorUpdateOpcode = 0x0000F74E;
private static readonly byte[] DispatchSbVectorUpdateSignature =
// Verified unique + lands at 0x006ADC80 offline (tools/pe_pattern.py).
private static readonly byte?[] DispatchSbVectorUpdatePattern =
[
0x83, 0xEC, 0x20, 0x53, 0x8B, 0x5C, 0x24, 0x2C,
0x85, 0xDB, 0x74, 0x08, 0x8B, 0x44, 0x24, 0x28,
0x85, 0xC0, 0x75, 0x0A, 0xB8, 0x03, 0x00, 0x00,
0x00, 0x5B, 0x83, 0xC4, 0x20, 0xC3
0x83, 0xEC, 0x20, 0x53, 0x8B, 0x5C, 0x24, 0x2C
];
private static IntPtr _originalDispatchSbVectorUpdatePtr;
@ -38,10 +36,10 @@ internal static class VectorUpdateServerDispatchHooks
return;
}
int funcOff = DispatchSbVectorUpdateVa - textSection.TextBaseVa;
if (!PatternScanner.VerifyBytes(textSection.Bytes, funcOff, DispatchSbVectorUpdateSignature))
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "VectorUpdate.DispatchSbVectorUpdate", DispatchSbVectorUpdatePattern, DispatchSbVectorUpdateVa);
if (!resolved.Success)
{
_statusMessage = $"CM_Physics::DispatchSB_VectorUpdate signature mismatch @ 0x{DispatchSbVectorUpdateVa:X8}.";
_statusMessage = $"CM_Physics::DispatchSB_VectorUpdate unresolved (VA 0x{DispatchSbVectorUpdateVa:X8}).";
RynthLog.Compat($"Compat: vector-update hook failed - {_statusMessage}");
return;
}
@ -50,7 +48,7 @@ internal static class VectorUpdateServerDispatchHooks
{
unsafe
{
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_targetAddress = resolved.Address;
delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint> pDetour = &DispatchSbVectorUpdateDetour;
MinHook.Hook(_targetAddress, (IntPtr)pDetour, out _originalDispatchSbVectorUpdatePtr);
}
@ -69,6 +67,7 @@ internal static class VectorUpdateServerDispatchHooks
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static unsafe uint DispatchSbVectorUpdateDetour(IntPtr smartBoxPtr, IntPtr blob)
{
RecursionGuard.Tick("VectorUpdateServerDispatchHooks.DispatchSbVectorUpdate");
var pOriginal = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint>)_originalDispatchSbVectorUpdatePtr;
VectorUpdateInfo info = ReadVectorUpdateInfo(blob);
@ -79,7 +78,7 @@ internal static class VectorUpdateServerDispatchHooks
if (info.Opcode != VectorUpdateOpcode || info.RawObjectId == 0)
return status;
PluginManager.QueueUpdateObject(info.RawObjectId);
try { PluginManager.QueueUpdateObject(info.RawObjectId); } catch { }
return status;
}

View file

@ -14,6 +14,10 @@ namespace RynthCore.Engine.Compatibility;
/// RecvNotice_CloseVendor = 0x000BFF40 + 0x00401000 = 0x004C0F40
///
/// We hook the real impl (0x004C5790, called by the thunk) and the close entry directly.
///
/// The open detour also feeds <see cref="VendorTrade"/> (the vendor snapshot plugins
/// read and trade against); the close path goes through <see cref="MarkVendorClosed"/>,
/// which VendorTrade's main-thread poll also calls when the vendor window goes away.
/// </summary>
internal static class VendorHooks
{
@ -22,14 +26,15 @@ internal static class VendorHooks
// gmVendorUI::RecvNotice_CloseVendor
private const int RecvNoticeCloseVendorVa = 0x004C0F40;
// Verified entry bytes (from Ghidra)
private static readonly byte[] OpenVendorSignature =
// Verified unique + lands at 0x004C5790 offline (tools/pe_pattern.py).
private static readonly byte?[] OpenVendorPattern =
[
0x83, 0xEC, 0x2C, 0x53, 0x55, 0x56, 0x57 // SUB ESP,2C; PUSH EBX; PUSH EBP; PUSH ESI; PUSH EDI
0x83, 0xEC, 0x2C, 0x53, 0x55, 0x56, 0x57, 0x8B, 0xF1 // SUB ESP,2C; PUSH EBX; PUSH EBP; PUSH ESI; PUSH EDI; MOV ESI,ECX
];
private static readonly byte[] CloseVendorSignature =
// Verified unique + lands at 0x004C0F40 offline (tools/pe_pattern.py).
private static readonly byte?[] CloseVendorPattern =
[
0x8A, 0x44, 0x24, 0x04, 0x84, 0xC0, 0x75 // MOV AL,[ESP+4]; TEST AL,AL; JNZ ...
0x8A, 0x44, 0x24, 0x04, 0x84, 0xC0, 0x75, 0x17 // MOV AL,[ESP+4]; TEST AL,AL; JNZ ...
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
@ -61,32 +66,31 @@ internal static class VendorHooks
return;
}
int openOff = RecvNoticeOpenVendorVa - textSection.TextBaseVa;
int closeOff = RecvNoticeCloseVendorVa - textSection.TextBaseVa;
if (!PatternScanner.VerifyBytes(textSection.Bytes, openOff, OpenVendorSignature))
HookResolver.ResolveResult resolvedOpen = HookResolver.Resolve(textSection, "Vendor.OpenVendor", OpenVendorPattern, RecvNoticeOpenVendorVa);
if (!resolvedOpen.Success)
{
_statusMessage = $"RecvNotice_OpenVendor signature mismatch @ 0x{RecvNoticeOpenVendorVa:X8}.";
_statusMessage = $"RecvNotice_OpenVendor unresolved (VA 0x{RecvNoticeOpenVendorVa:X8}).";
RynthLog.Compat($"Compat: vendor hooks failed - {_statusMessage}");
return;
}
if (!PatternScanner.VerifyBytes(textSection.Bytes, closeOff, CloseVendorSignature))
HookResolver.ResolveResult resolvedClose = HookResolver.Resolve(textSection, "Vendor.CloseVendor", CloseVendorPattern, RecvNoticeCloseVendorVa);
if (!resolvedClose.Success)
{
_statusMessage = $"RecvNotice_CloseVendor signature mismatch @ 0x{RecvNoticeCloseVendorVa:X8}.";
_statusMessage = $"RecvNotice_CloseVendor unresolved (VA 0x{RecvNoticeCloseVendorVa:X8}).";
RynthLog.Compat($"Compat: vendor hooks failed - {_statusMessage}");
return;
}
try
{
_openAddress = new IntPtr(textSection.TextBaseVa + openOff);
_openAddress = resolvedOpen.Address;
_openDetour = OpenVendorDetour;
IntPtr openPtr = Marshal.GetFunctionPointerForDelegate(_openDetour);
_originalOpen = Marshal.GetDelegateForFunctionPointer<RecvNoticeOpenVendorDelegate>(
MinHook.HookCreate(_openAddress, openPtr));
_closeAddress = new IntPtr(textSection.TextBaseVa + closeOff);
_closeAddress = resolvedClose.Address;
_closeDetour = CloseVendorDetour;
IntPtr closePtr = Marshal.GetFunctionPointerForDelegate(_closeDetour);
_originalClose = Marshal.GetDelegateForFunctionPointer<RecvNoticeCloseVendorDelegate>(
@ -104,22 +108,62 @@ internal static class VendorHooks
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: vendor hooks failed - {ex.Message}");
return;
}
// Vendor trading rides on these detours (snapshot + close tracking).
try { VendorTrade.Initialize(textSection); }
catch (Exception ex) { RynthLog.Warn($"VendorTrade: init failed - {ex.GetType().Name}: {ex.Message}"); }
}
private static void OpenVendorDetour(IntPtr thisPtr, uint vendorId, IntPtr vpRef, IntPtr itemsRef, int shopMode)
{
// Copy the vendor out of the arguments BEFORE the original runs: OpenVendor frees
// the item PWDs on its own copy as it turns them into weenie objects.
VendorSnapshot? snap = null;
if (vendorId != 0)
{
try { snap = VendorTrade.CaptureFromNotice(vendorId, vpRef, itemsRef, shopMode); }
catch { snap = null; }
}
_originalOpen!(thisPtr, vendorId, vpRef, itemsRef, shopMode);
if (vendorId == 0) return;
try { VendorTrade.OnVendorOpened(thisPtr, vendorId, snap); }
catch { }
// Switching straight to another vendor never sends a close notice; tell plugins.
uint prev = _currentVendorId;
_currentVendorId = vendorId;
if (prev != 0 && prev != vendorId)
PluginManager.QueueVendorClose(prev);
PluginManager.QueueVendorOpen(vendorId);
}
private static void CloseVendorDetour(IntPtr thisPtr, int updating)
{
_originalClose!(thisPtr, updating);
// The flag is a bool in the low byte (MOV AL,[ESP+4]; TEST AL,AL); the rest of the
// stack slot is garbage. With it set, the retail function returns without closing
// anything, so neither do we.
if ((updating & 0xFF) != 0)
return;
MarkVendorClosed("close notice");
}
/// <summary>
/// The vendor is gone: clear the trade snapshot and raise OnVendorClose once. Called
/// from the close detour and from VendorTrade's main-thread poll of gmVendorUI's
/// shopVendorID, which backs the notice up for any close path that skips it.
/// AC's main thread only.
/// </summary>
internal static void MarkVendorClosed(string reason)
{
uint vid = _currentVendorId;
_currentVendorId = 0;
try { VendorTrade.OnVendorClosed(reason); }
catch { }
if (vid != 0)
PluginManager.QueueVendorClose(vid);
}

File diff suppressed because it is too large Load diff

View file

@ -10,18 +10,17 @@ internal static class ViewObjectContentsHooks
{
private const int ViewObjectContentsVa = 0x005596B0;
private const int StopViewingObjectContentsVa = 0x00559770;
private static readonly byte[] ViewObjectContentsSignature =
// Verified unique + lands at 0x005596B0 offline (tools/pe_pattern.py).
private static readonly byte?[] ViewObjectContentsPattern =
[
0x53, 0x8B, 0x5C, 0x24, 0x08, 0x56, 0x57, 0x53,
0x8B, 0xF9, 0xE8, 0x71, 0xF2, 0xFA, 0xFF, 0x8B,
0xF0, 0x85, 0xF6, 0x75, 0x57
0x8B, 0xF9, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x85
];
private static readonly byte[] StopViewingObjectContentsSignature =
// Verified unique + lands at 0x00559770 offline (tools/pe_pattern.py).
private static readonly byte?[] StopViewingObjectContentsPattern =
[
0x56, 0x57, 0x8B, 0x7C, 0x24, 0x0C, 0x57, 0x8B,
0xF1, 0xE8, 0x62, 0xF1, 0xFA, 0xFF, 0x85, 0xC0,
0x74, 0x07, 0xC7, 0x40, 0x50, 0x00, 0x00, 0x00,
0x00
0xF1, 0xE8, null, null, null, null, 0x85, 0xC0, 0x74, 0x07
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
@ -54,30 +53,30 @@ internal static class ViewObjectContentsHooks
return;
}
int viewOff = ViewObjectContentsVa - textSection.TextBaseVa;
if (!PatternScanner.VerifyBytes(textSection.Bytes, viewOff, ViewObjectContentsSignature))
HookResolver.ResolveResult resolvedView = HookResolver.Resolve(textSection, "ViewContents.ViewObjectContents", ViewObjectContentsPattern, ViewObjectContentsVa);
if (!resolvedView.Success)
{
_statusMessage = $"ACCObjectMaint::ViewObjectContents signature mismatch @ 0x{ViewObjectContentsVa:X8}.";
_statusMessage = $"ACCObjectMaint::ViewObjectContents unresolved (VA 0x{ViewObjectContentsVa:X8}).";
RynthLog.Compat($"Compat: view-object-contents hook failed - {_statusMessage}");
return;
}
int stopOff = StopViewingObjectContentsVa - textSection.TextBaseVa;
if (!PatternScanner.VerifyBytes(textSection.Bytes, stopOff, StopViewingObjectContentsSignature))
HookResolver.ResolveResult resolvedStop = HookResolver.Resolve(textSection, "ViewContents.StopViewingObjectContents", StopViewingObjectContentsPattern, StopViewingObjectContentsVa);
if (!resolvedStop.Success)
{
_statusMessage = $"ACCObjectMaint::StopViewingObjectContents signature mismatch @ 0x{StopViewingObjectContentsVa:X8}.";
_statusMessage = $"ACCObjectMaint::StopViewingObjectContents unresolved (VA 0x{StopViewingObjectContentsVa:X8}).";
RynthLog.Compat($"Compat: view-object-contents hook failed - {_statusMessage}");
return;
}
try
{
_viewTargetAddress = new IntPtr(textSection.TextBaseVa + viewOff);
_viewTargetAddress = resolvedView.Address;
_viewObjectContentsDetour = ViewObjectContentsDetour;
IntPtr viewDetourPtr = Marshal.GetFunctionPointerForDelegate(_viewObjectContentsDetour);
_originalViewObjectContents = Marshal.GetDelegateForFunctionPointer<ViewObjectContentsDelegate>(MinHook.HookCreate(_viewTargetAddress, viewDetourPtr));
_stopTargetAddress = new IntPtr(textSection.TextBaseVa + stopOff);
_stopTargetAddress = resolvedStop.Address;
_stopViewingObjectContentsDetour = StopViewingObjectContentsDetour;
IntPtr stopDetourPtr = Marshal.GetFunctionPointerForDelegate(_stopViewingObjectContentsDetour);
_originalStopViewingObjectContents = Marshal.GetDelegateForFunctionPointer<StopViewingObjectContentsDelegate>(MinHook.HookCreate(_stopTargetAddress, stopDetourPtr));