diff --git a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml index d416d6a..c8bf062 100644 --- a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml +++ b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml @@ -2,7 +2,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="RynthCore.App.Avalonia.AccountProfileDialog" Width="520" - Height="360" + Height="310" CanResize="False" WindowStartupLocation="CenterOwner" Title="Account Profile" @@ -24,8 +24,6 @@ - - diff --git a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs index 44ed1e8..156eb9c 100644 --- a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs +++ b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs @@ -1,8 +1,5 @@ using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Text; -using System.Text.Json; using Avalonia.Controls; using RynthCore.App; @@ -30,119 +27,10 @@ internal partial class AccountProfileDialog : Window ? "No password is saved for this profile yet." : "A password is already saved for this profile. It stays hidden unless you replace or clear it."; - PopulateCharacterDropdown(profile.AccountName, GetSelectedServerName(), profile.CharacterName); - - // Re-populate characters when account name or server changes - AccountBox.TextChanged += (_, _) => - { - string currentChar = GetSelectedCharacterName(); - PopulateCharacterDropdown(AccountBox.Text?.Trim() ?? string.Empty, GetSelectedServerName(), currentChar); - }; - ServerComboBox.SelectionChanged += (_, _) => - { - PopulateCharacterDropdown(AccountBox.Text?.Trim() ?? string.Empty, GetSelectedServerName(), GetSelectedCharacterName()); - }; - SaveButton.Click += (_, _) => SaveAndClose(); CancelButton.Click += (_, _) => Close(false); } - private string GetSelectedServerName() => - ServerComboBox.SelectedIndex >= 0 && ServerComboBox.SelectedIndex < _servers.Count - ? _servers[ServerComboBox.SelectedIndex].Name - : string.Empty; - - private void PopulateCharacterDropdown(string accountName, string serverName, string selectedCharacter) - { - List chars = LoadDetectedCharacters(accountName, serverName); - - // Ensure the existing saved name appears even if the scan file is empty - if (!string.IsNullOrEmpty(selectedCharacter) - && selectedCharacter != LaunchAccountProfile.NoneOption - && !chars.Contains(selectedCharacter)) - { - chars.Insert(0, selectedCharacter); - } - - // "(None)" sentinel at the top so users can opt out of auto-login per account - chars.Insert(0, LaunchAccountProfile.NoneOption); - - CharacterBox.ItemsSource = chars; - - if (string.IsNullOrEmpty(selectedCharacter) || selectedCharacter == LaunchAccountProfile.NoneOption) - CharacterBox.SelectedItem = LaunchAccountProfile.NoneOption; - else if (chars.Contains(selectedCharacter)) - CharacterBox.SelectedItem = selectedCharacter; - } - - private string GetSelectedCharacterName() => - CharacterBox.SelectedItem as string ?? string.Empty; - - private static List LoadDetectedCharacters(string accountName, string serverName = "") - { - try - { - List cachedCharacters = CharacterCacheStore.Read(accountName, serverName); - if (cachedCharacters.Count > 0) - return cachedCharacters; - - // 3. ThwargLauncher character files - return ReadThwargCharacters(accountName, serverName); - } - catch - { - return []; - } - } - - private static List ReadThwargCharacters(string accountName, string serverName = "") - { - try - { - string charDir = Path.Combine( - System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), - "ThwargLauncher", "characters"); - - if (!Directory.Exists(charDir)) - return []; - - var results = new List(); - foreach (string file in Directory.GetFiles(charDir, "*.txt")) - { - try - { - string json = File.ReadAllText(file); - using var doc = JsonDocument.Parse(json); - foreach (var entry in doc.RootElement.EnumerateObject()) - { - bool accountMatches = string.IsNullOrWhiteSpace(accountName) || - entry.Name.EndsWith("-" + accountName, System.StringComparison.OrdinalIgnoreCase); - bool serverMatches = string.IsNullOrWhiteSpace(serverName) || - entry.Name.StartsWith(serverName + "-", System.StringComparison.OrdinalIgnoreCase); - - if (!accountMatches || !serverMatches) continue; - if (!entry.Value.TryGetProperty("CharacterList", out var list)) continue; - - foreach (var charEl in list.EnumerateArray()) - { - if (charEl.TryGetProperty("Name", out var nameEl)) - { - string name = nameEl.GetString() ?? string.Empty; - if (!string.IsNullOrEmpty(name) && !results.Contains(name)) - results.Add(name); - } - } - } - } - catch { } - } - return results; - } - catch - { - return []; - } - } private void SaveAndClose() { if (string.IsNullOrWhiteSpace(AccountBox.Text)) @@ -164,7 +52,6 @@ internal partial class AccountProfileDialog : Window _profile.Password = PasswordBox.Text; } - _profile.CharacterName = GetSelectedCharacterName(); _profile.Alias = AliasBox.Text?.Trim() ?? string.Empty; Close(true); diff --git a/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs b/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs index 41b8235..f07a5a6 100644 --- a/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs @@ -61,6 +61,14 @@ internal static class CharacterCaptureHooks private static int _autoLoginScheduled; + // Latches once auto-login has fired in this process. The character-list packet + // (0xF658) arrives every time the client sees char-select — including the + // logout-to-char-select transition — and without this latch we'd re-trigger + // auto-login the moment the user manually logs out. One-shot per process: if + // the user wants to swap characters, they can pick from char-select manually, + // or relaunch. + private static int _autoLoginEverFired; + public static void ProcessPotentialCharacterMessage(IntPtr blob, bool isGameEvent = false) { if (blob == IntPtr.Zero) @@ -269,6 +277,15 @@ internal static class CharacterCaptureHooks if (string.IsNullOrWhiteSpace(targetCharacter)) 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. + if (Interlocked.CompareExchange(ref _autoLoginEverFired, 1, 0) != 0) + { + RynthLog.Verbose($"CharacterCapture: Auto-login already fired this session — skipping for '{targetCharacter}'."); + return; + } + if (Interlocked.Exchange(ref _autoLoginScheduled, 1) != 0) return; diff --git a/src/RynthCore.Engine/Compatibility/ChatHooks.cs b/src/RynthCore.Engine/Compatibility/ChatHooks.cs index a1a569e..cc08e52 100644 --- a/src/RynthCore.Engine/Compatibility/ChatHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ChatHooks.cs @@ -117,6 +117,17 @@ internal static class ChatHooks /// 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; @@ -142,4 +153,16 @@ internal static class ChatHooks _isHiddenAsserted = false; } } + + /// + /// Drops the cached gmMainChatUI singleton pointer. Called from the + /// logout pipeline so we don't reuse a freed pointer after the next login — + /// re-captures the fresh instance on the next + /// chat-UI message dispatch. + /// + public static void ResetCachedInstance() + { + _gmMainChatInstance = IntPtr.Zero; + _isHiddenAsserted = false; + } } diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs index 346da27..d918b15 100644 --- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs @@ -561,14 +561,29 @@ internal static class ClientObjectHooks return false; training = unchecked((int)skill.AdvancementClass); - buffed = unchecked((int)(skill.InitialLevel + skill.LevelFromPracticePoints)); + + // Use CACQualities::InqSkill(stype, retval, raw=0) for the FULL buffed + // skill — that includes attribute contribution, augmentations, and + // spell-buff enchantments. The raw struct fields (InitialLevel + + // LevelFromPracticePoints) only give the base trained level and miss + // everything else, which is why this used to return ~208 for a + // character whose true buffed Creature Enchantment was 360+. + int rawBase = unchecked((int)(skill.InitialLevel + skill.LevelFromPracticePoints)); + int trulyBuffed = rawBase; + if (_inqSkillLevel != null) + { + int retval = 0; + if (_inqSkillLevel(qualitiesPtr, skillStype, &retval, 0) != 0) + trulyBuffed = retval; + } + buffed = trulyBuffed; if (_skillProbeLogCount < 6) { _skillProbeLogCount++; RynthLog.Verbose( $"Compat: skillTableProbe obj=0x{objectId:X8} skill={skillStype} qualities=0x{qualitiesPtr.ToInt32():X8} " + - $"table=0x{skillTablePtr.ToInt32():X8} buckets={tableSize} training={training} base={buffed}"); + $"table=0x{skillTablePtr.ToInt32():X8} buckets={tableSize} training={training} base={rawBase} buffed={buffed}"); } return true; diff --git a/src/RynthCore.Engine/Compatibility/LoginLifecycleHooks.cs b/src/RynthCore.Engine/Compatibility/LoginLifecycleHooks.cs index 81ba67c..e007172 100644 --- a/src/RynthCore.Engine/Compatibility/LoginLifecycleHooks.cs +++ b/src/RynthCore.Engine/Compatibility/LoginLifecycleHooks.cs @@ -92,6 +92,18 @@ internal static class LoginLifecycleHooks } } + /// + /// Clears the one-shot observation flag so the next SendLoginCompleteNotification + /// raises again. Called by the logout pipeline so the + /// following login (e.g. swapping characters) re-runs login-gated startup. + /// + public static void ResetObservation() + { + HasObservedLoginComplete = false; + _statusMessage = "Awaiting next SendLoginCompleteNotification."; + _waitingLogged = false; + } + public static void Poll() { if (HasObservedLoginComplete || !IsInstalled) diff --git a/src/RynthCore.Engine/Compatibility/LogoutLifecycleHooks.cs b/src/RynthCore.Engine/Compatibility/LogoutLifecycleHooks.cs new file mode 100644 index 0000000..58b1b9a --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/LogoutLifecycleHooks.cs @@ -0,0 +1,168 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.Hooking; + +namespace RynthCore.Engine.Compatibility; + +/// +/// 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. +/// +/// We hook both: +/// - CPlayerSystem::ExecuteLogOff(void) — 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 +/// gmGamePlayUI::RecvNotice_EndCharacterSession — 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.) +/// - gmGamePlayUI::RecvNotice_Logoff(void) — server-driven full logoff +/// notice. Belt-and-braces in case ExecuteLogOff is bypassed in some flow. +/// +/// Either one raises 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.) +/// +internal static class LogoutLifecycleHooks +{ + private const int ExpectedImageSize = 0x56D000; + private const int ExecuteLogOffFileOffset = 0x0015D4A0; + private const int RecvNoticeLogoffFileOffset = 0x000EBBA0; + + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void ThisCallVoidDelegate(IntPtr thisPtr); + + private static ThisCallVoidDelegate? _originalExecuteLogOff; + private static ThisCallVoidDelegate? _executeLogOffDetour; + private static IntPtr _executeLogOffAddress; + + private static ThisCallVoidDelegate? _originalRecvNoticeLogoff; + private static ThisCallVoidDelegate? _recvNoticeLogoffDetour; + private static IntPtr _logoffAddress; + + private static string _statusMessage = "Not probed yet."; + + public static bool IsInstalled { get; private set; } + public static bool HasObservedLogout { get; private set; } + public static string StatusMessage => _statusMessage; + + /// Fires once per logout cycle, after the first observed logout signal returns from its original. + public static event Action? LogoutComplete; + + public static void Initialize() + { + if (IsInstalled) + return; + + if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection)) + { + _statusMessage = "acclient.exe not available."; + 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"); + + if (anyHooked) + { + IsInstalled = true; + RynthLog.Compat($"Compat: logout lifecycle hook ready - ExecuteLogOff=0x{_executeLogOffAddress.ToInt32():X8} 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) + { + try + { + address = new IntPtr(textSection.TextBaseVa + fileOffset); + detourField = detour; + + IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(detourField); + original = Marshal.GetDelegateForFunctionPointer(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}"); + return false; + } + } + + /// Resets the observation flag so the next logout-class notice fires again. + public static void ResetObservation() + { + HasObservedLogout = false; + } + + private static void ExecuteLogOffDetour(IntPtr thisPtr) + { + if (!HasObservedLogout) + RynthLog.Compat("Compat: CPlayerSystem::ExecuteLogOff detour entered."); + + try { _originalExecuteLogOff!(thisPtr); } + catch { /* original must run */ } + + RaiseLogoutCompleteOnce("CPlayerSystem::ExecuteLogOff"); + } + + private static void RecvNoticeLogoffDetour(IntPtr thisPtr) + { + if (!HasObservedLogout) + RynthLog.Compat("Compat: RecvNotice_Logoff detour entered."); + + try { _originalRecvNoticeLogoff!(thisPtr); } + catch { /* original must run */ } + + RaiseLogoutCompleteOnce("gmGamePlayUI::RecvNotice_Logoff"); + } + + /// + /// 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 + /// runs after the next login. + /// + private static void RaiseLogoutCompleteOnce(string source) + { + if (HasObservedLogout) + return; + + HasObservedLogout = true; + _statusMessage = $"Logout observed via {source}."; + RynthLog.Compat($"Compat: 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}"); + } + } +} diff --git a/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs b/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs index 9dd2865..3af0d4c 100644 --- a/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs +++ b/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs @@ -178,9 +178,12 @@ internal static class UpdateObjectInventoryHooks } /// - /// Scan a range of object IDs, calling GetWeenieObject for each, and return - /// those whose containerID matches the target. This discovers items that were - /// created before the plugin loaded (e.g. pack contents at login). + /// Scan a range of object IDs and return those owned by the target container — + /// either as a contained child (containerID match) OR as a wielded child + /// (wielderID match). PublicWeenieDesc stores those as separate fields, so + /// matching only on containerID misses wielded items (weapons, armor, ammo). + /// Returning both keeps the plugin's container walk a single authoritative + /// list of "everything the player owns right now." /// private static int ScanByContainerId(uint containerId, Span itemIds) { @@ -190,9 +193,9 @@ internal static class UpdateObjectInventoryHooks for (uint id = 0x80000001; id <= 0x8000FFFF && written < itemIds.Length; id++) { if (id == containerId) continue; - if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint cid, out _, out _)) + if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint cid, out uint wid, out _)) continue; - if (cid == containerId) + if (cid == containerId || wid == containerId) itemIds[written++] = id; } diff --git a/src/RynthCore.Engine/CrashLogger.cs b/src/RynthCore.Engine/CrashLogger.cs index 35def58..57b925e 100644 --- a/src/RynthCore.Engine/CrashLogger.cs +++ b/src/RynthCore.Engine/CrashLogger.cs @@ -47,6 +47,9 @@ internal static class CrashLogger [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GetModuleHandleExW(uint dwFlags, IntPtr lpModuleName, out IntPtr phModule); + [DllImport("kernel32.dll")] + private static extern IntPtr VirtualQuery(IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, IntPtr dwLength); + [StructLayout(LayoutKind.Sequential)] private struct MODULEINFO { @@ -55,6 +58,34 @@ internal static class CrashLogger public IntPtr EntryPoint; } + [StructLayout(LayoutKind.Sequential)] + private struct MEMORY_BASIC_INFORMATION + { + public IntPtr BaseAddress; + public IntPtr AllocationBase; + public uint AllocationProtect; + public IntPtr RegionSize; + public uint State; + public uint Protect; + public uint Type; + } + + private const uint MEM_COMMIT = 0x00001000; + private const uint PAGE_NOACCESS = 0x00000001; + private const uint PAGE_GUARD = 0x00000100; + + // x86 CONTEXT field offsets (verified against winnt.h _CONTEXT layout). + // FloatSave occupies 112 bytes between the Dr* registers and SegGs. + private const int CTX_OFF_EDI = 156; + private const int CTX_OFF_ESI = 160; + private const int CTX_OFF_EBX = 164; + private const int CTX_OFF_EDX = 168; + private const int CTX_OFF_ECX = 172; + private const int CTX_OFF_EAX = 176; + private const int CTX_OFF_EBP = 180; + private const int CTX_OFF_EIP = 184; + private const int CTX_OFF_ESP = 196; + // GetModuleHandleEx flags private const uint GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS = 0x00000004; private const uint GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT = 0x00000002; @@ -121,7 +152,22 @@ internal static class CrashLogger RynthLog.Info( $"CRASH: code=0x{er.ExceptionCode:X8} addr=0x{er.ExceptionAddress.ToInt64():X8} " + - $"module={module} base=0x{moduleBase.ToInt64():X8} rva=0x{rva:X}"); + $"module={ShortModule(module)} base=0x{moduleBase.ToInt64():X8} rva=0x{rva:X}"); + + // Decode AV operation from ExceptionInformation[0..1] (first param = + // 0 read / 1 write / 8 DEP, second param = faulting data address). + // Only available when NumberParameters >= 2; safe to read the two + // dwords directly past the fixed EXCEPTION_RECORD header. + if (er.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && er.NumberParameters >= 2) + { + int infoOffset = Marshal.SizeOf(); + uint avKind = (uint)Marshal.ReadInt32(ep.ExceptionRecord, infoOffset); + IntPtr avAddr = (IntPtr)Marshal.ReadInt32(ep.ExceptionRecord, infoOffset + 4); + string kind = avKind switch { 0 => "read", 1 => "write", 8 => "DEP", _ => $"?{avKind}" }; + RynthLog.Info($"CRASH AV: {kind} faultAddr=0x{avAddr.ToInt64():X8}"); + } + + DumpContext(ep.ContextRecord); } catch { @@ -131,6 +177,137 @@ internal static class CrashLogger return EXCEPTION_CONTINUE_SEARCH; } + /// + /// Reads the x86 CONTEXT* and emits register dump + EBP-frame walk + ESP + /// sweep. EBP frames cover compilers that preserve frame pointers (most + /// managed/CLR/NativeAOT frames); the ESP sweep is the fallback for + /// FPO-optimized native code (cimgui, acclient) where return addresses + /// still sit on the stack but EBP is repurposed. + /// + private static void DumpContext(IntPtr ctx) + { + if (ctx == IntPtr.Zero) return; + + uint eip, eax, ebx, ecx, edx, esi, edi, ebp, esp; + try + { + eip = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EIP); + eax = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EAX); + ebx = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EBX); + ecx = (uint)Marshal.ReadInt32(ctx, CTX_OFF_ECX); + edx = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EDX); + esi = (uint)Marshal.ReadInt32(ctx, CTX_OFF_ESI); + edi = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EDI); + ebp = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EBP); + esp = (uint)Marshal.ReadInt32(ctx, CTX_OFF_ESP); + } + catch + { + return; + } + + RynthLog.Info( + $"CRASH regs: eip=0x{eip:X8} eax=0x{eax:X8} ebx=0x{ebx:X8} ecx=0x{ecx:X8} " + + $"edx=0x{edx:X8} esi=0x{esi:X8} edi=0x{edi:X8}"); + RynthLog.Info($"CRASH regs: ebp=0x{ebp:X8} esp=0x{esp:X8}"); + + WalkEbpFrames((IntPtr)ebp); + SweepStack((IntPtr)esp); + } + + private static void WalkEbpFrames(IntPtr startEbp) + { + try + { + IntPtr cur = startEbp; + for (int frame = 0; frame < 16; frame++) + { + if (!IsReadable(cur, 8)) break; + IntPtr nextEbp = (IntPtr)Marshal.ReadInt32(cur); + IntPtr ret = (IntPtr)Marshal.ReadInt32(cur, 4); + if (ret == IntPtr.Zero) break; + + string mod = ResolveModule(ret, out IntPtr modBase); + if (modBase != IntPtr.Zero) + { + long fr = ret.ToInt64() - modBase.ToInt64(); + RynthLog.Info($" ebp[{frame:D2}] ret=0x{ret.ToInt64():X8} {ShortModule(mod)}+0x{fr:X}"); + } + else + { + RynthLog.Info($" ebp[{frame:D2}] ret=0x{ret.ToInt64():X8} "); + } + + // Stop if next frame pointer doesn't look like a higher stack address. + long delta = nextEbp.ToInt64() - cur.ToInt64(); + if (delta <= 0 || delta > 0x100000) break; + cur = nextEbp; + } + } + catch + { + } + } + + /// + /// Reads up to 96 dwords from ESP and logs each value that lands inside a + /// loaded module. For an indirect-call AV, [esp] is the return address into + /// the caller — usually the first hit identifies the bad call site. + /// + private static void SweepStack(IntPtr startEsp) + { + const int sweepDwords = 96; + try + { + int hits = 0; + for (int i = 0; i < sweepDwords; i++) + { + IntPtr addr = (IntPtr)(startEsp.ToInt64() + i * 4); + if (!IsReadable(addr, 4)) break; + IntPtr v = (IntPtr)Marshal.ReadInt32(addr); + if (v == IntPtr.Zero) continue; + + string mod = ResolveModule(v, out IntPtr modBase); + if (modBase == IntPtr.Zero) continue; + + long fr = v.ToInt64() - modBase.ToInt64(); + RynthLog.Info($" esp+0x{i*4:X3}: 0x{v.ToInt64():X8} {ShortModule(mod)}+0x{fr:X}"); + + if (++hits >= 24) break; // cap to keep log readable + } + } + catch + { + } + } + + private static bool IsReadable(IntPtr addr, int bytes) + { + try + { + if (VirtualQuery(addr, out MEMORY_BASIC_INFORMATION mbi, (IntPtr)Marshal.SizeOf()) == IntPtr.Zero) + return false; + if (mbi.State != MEM_COMMIT) return false; + if ((mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0) return false; + + // Make sure the requested range doesn't cross out of the committed region. + long endRequested = addr.ToInt64() + bytes; + long endRegion = mbi.BaseAddress.ToInt64() + mbi.RegionSize.ToInt64(); + return endRequested <= endRegion; + } + catch + { + return false; + } + } + + private static string ShortModule(string fullPath) + { + if (string.IsNullOrEmpty(fullPath)) return ""; + int slash = fullPath.LastIndexOfAny(new[] { '\\', '/' }); + return slash >= 0 ? fullPath.Substring(slash + 1) : fullPath; + } + private static string ResolveModule(IntPtr address, out IntPtr moduleBase) { moduleBase = IntPtr.Zero; diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 70bfd64..08c3bc9 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -266,6 +266,7 @@ public static class EntryPoint RunInitStep("RynthAi action hooks", ClientActionHooks.Initialize); RunInitStep("client helper hooks", () => ClientHelperHooks.Probe()); RunInitStep("login lifecycle hooks", LoginLifecycleHooks.Initialize); + RunInitStep("logout lifecycle hooks", LogoutLifecycleHooks.Initialize); RunInitStep("session state registry", SessionStateRegistry.Initialize); RunInitStep("UI lifecycle hooks", UiLifecycleHooks.Initialize); RunInitStep("logo bypass", LogoBypassHooks.Start); diff --git a/src/RynthCore.Engine/ImGui/RynthCoreShell.cs b/src/RynthCore.Engine/ImGui/RynthCoreShell.cs index 0413038..153029f 100644 --- a/src/RynthCore.Engine/ImGui/RynthCoreShell.cs +++ b/src/RynthCore.Engine/ImGui/RynthCoreShell.cs @@ -76,6 +76,16 @@ internal static class RynthCoreShell public static void Render(int frameCount) { ApplyTheme(); + + // Hide the entire shell while we are NOT in-world. Between RecvNotice_Logoff + // and the next SendLoginCompleteNotification the AC client tears down its + // world / UI state; rendering the bar (and the plugin shortcuts it hosts) + // during that window has been observed to crash D3D9 because plugin + // controls reach into half-released game data. + bool inWorld = LoginLifecycleHooks.HasObservedLoginComplete; + if (!inWorld) + return; + RenderControlBar(frameCount); if (_showDemoWindow) diff --git a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs index 499b65e..e2c8a57 100644 --- a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs +++ b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs @@ -23,6 +23,7 @@ internal sealed class LoadedPlugin public PluginNameDelegate? GetName { get; set; } public PluginVersionDelegate? GetVersion { get; set; } public PluginOnLoginCompleteDelegate? OnLoginComplete { get; set; } + public PluginOnLogoutDelegate? OnLogout { get; set; } public PluginOnUIInitializedDelegate? OnUIInitialized { get; set; } public PluginOnBusyCountIncrementedDelegate? OnBusyCountIncremented { get; set; } public PluginOnBusyCountDecrementedDelegate? OnBusyCountDecremented { get; set; } diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 8c2f364..53d337c 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -510,7 +510,7 @@ internal struct RynthCoreAPI /// Current API version. Bump when adding fields to RynthCoreAPI. internal static class PluginContractVersion { - public const uint Current = 56; + public const uint Current = 57; } internal static class ClientActionHookFlags @@ -551,6 +551,9 @@ internal delegate IntPtr PluginVersionDelegate(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void PluginOnLoginCompleteDelegate(); +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate void PluginOnLogoutDelegate(); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void PluginOnUIInitializedDelegate(); diff --git a/src/RynthCore.Engine/Plugins/PluginLoader.cs b/src/RynthCore.Engine/Plugins/PluginLoader.cs index 50fa296..8a23547 100644 --- a/src/RynthCore.Engine/Plugins/PluginLoader.cs +++ b/src/RynthCore.Engine/Plugins/PluginLoader.cs @@ -171,6 +171,10 @@ internal static class PluginLoader if (onLoginCompletePtr != IntPtr.Zero) plugin.OnLoginComplete = Marshal.GetDelegateForFunctionPointer(onLoginCompletePtr); + IntPtr onLogoutPtr = GetProcAddress(handle, "RynthPluginOnLogout"); + if (onLogoutPtr != IntPtr.Zero) + plugin.OnLogout = Marshal.GetDelegateForFunctionPointer(onLogoutPtr); + IntPtr onUiInitializedPtr = GetProcAddress(handle, "RynthPluginOnUIInitialized"); if (onUiInitializedPtr != IntPtr.Zero) plugin.OnUIInitialized = Marshal.GetDelegateForFunctionPointer(onUiInitializedPtr); @@ -358,6 +362,7 @@ internal static class PluginLoader { var parts = new List(4) { "init", "shutdown" }; if (p.OnLoginComplete != null) parts.Add("login"); + if (p.OnLogout != null) parts.Add("logout"); if (p.OnUIInitialized != null) parts.Add("ui"); if (p.OnBusyCountIncremented != null) parts.Add("busy+"); if (p.OnBusyCountDecremented != null) parts.Add("busy-"); diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index b7dfe5a..31d0a63 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -96,6 +96,7 @@ internal static class PluginManager private static bool _uiDispatchPending; private static bool _loginCompleteObserved; private static bool _loginDispatchPending; + private static bool _logoutDispatchPending; private static long _nextUpdateObjectDispatchTick; private static int _loadGeneration; private static RynthCoreAPI _api; @@ -225,6 +226,9 @@ internal static class PluginManager _loginCompleteObserved = LoginLifecycleHooks.HasObservedLoginComplete; _loginDispatchPending = _loginCompleteObserved; + LogoutLifecycleHooks.LogoutComplete -= OnLogoutObserved; + LogoutLifecycleHooks.LogoutComplete += OnLogoutObserved; + string normalizedEngineDir = Path.GetFullPath(engineDir); bool engineDirIsRuntime = string.Equals( Path.GetFileName(normalizedEngineDir.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)), @@ -293,6 +297,11 @@ internal static class PluginManager UiLifecycleHooks.Poll(); LoginLifecycleHooks.Poll(); SessionStateRegistry.Poll(); + + // Drain logout BEFORE any per-frame plugin activity so plugin teardown + // happens this frame and Tick/Render skip stale state. + if (_logoutDispatchPending && _initialized) + DispatchPendingLogout(); DispatchQueuedBusyCountDecremented(); DispatchQueuedBusyCountIncremented(); DispatchQueuedCombatModeChange(); @@ -694,6 +703,13 @@ internal static class PluginManager public static void RenderAll() { + // Suppress plugin rendering while we are not in-world. The window between + // RecvNotice_Logoff and the next SendLoginCompleteNotification is the + // crash zone: plugin draw paths reach into world data the AC client is + // simultaneously tearing down. + if (!_loginCompleteObserved) + return; + for (int i = 0; i < _plugins.Count; i++) { var plugin = _plugins[i]; @@ -717,6 +733,7 @@ internal static class PluginManager RynthLog.Plugin($"PluginManager: Shutting down {_plugins.Count} plugin(s)..."); UiLifecycleHooks.UiInitialized -= OnUIInitializedObserved; LoginLifecycleHooks.LoginComplete -= OnLoginCompleteObserved; + LogoutLifecycleHooks.LogoutComplete -= OnLogoutObserved; UnloadAllPlugins(); PluginLoader.CleanupShadowCopies(_shadowRootDir); _initialized = false; @@ -726,6 +743,7 @@ internal static class PluginManager _uiInitializedObserved = false; _loginDispatchPending = false; _loginCompleteObserved = false; + _logoutDispatchPending = false; _pluginsDir = ""; _shadowRootDir = ""; @@ -791,6 +809,75 @@ internal static class PluginManager RynthLog.Plugin("PluginManager: OnLoginComplete observed - queued login lifecycle callbacks."); } + /// + /// Hooked to . Runs on AC's UI + /// thread INSIDE gmGamePlayUI::RecvNotice_Logoff, so it must do as little + /// work as possible — anything heavier than flipping a flag will stall AC during + /// a critical state transition. The actual plugin teardown happens on the next + /// EndScene tick via . + /// + private static void OnLogoutObserved() + { + if (_logoutDispatchPending) + return; + + _logoutDispatchPending = true; + RynthLog.Plugin("PluginManager: OnLogout observed - queued for next EndScene frame."); + } + + /// + /// Drained from on the EndScene thread. + /// + private static void DispatchPendingLogout() + { + if (!_logoutDispatchPending) + return; + + _logoutDispatchPending = false; + + RynthLog.Plugin("PluginManager: dispatching OnLogout to plugins."); + DispatchLogoutToLoadedPlugins(); + + // Drop pointers to AC objects that the engine has cached and that AC + // frees during the world-to-charselect transition. ChatHooks caches + // gmMainChatUI for per-frame visibility assertion; using that pointer + // after AC has freed the widget AVs inside UIElement::IsVisible. The + // instance gets re-captured on the next ListenToElementMessage call + // after the next login completes. + Compatibility.ChatHooks.ResetCachedInstance(); + + // Reset login observation so the next SendLoginCompleteNotification kicks + // off a fresh login-complete cycle. + for (int i = 0; i < _plugins.Count; i++) + _plugins[i].LoginCompleteDispatched = false; + + _loginCompleteObserved = false; + _loginDispatchPending = false; + LoginLifecycleHooks.ResetObservation(); + LogoutLifecycleHooks.ResetObservation(); + } + + private static void DispatchLogoutToLoadedPlugins() + { + for (int i = 0; i < _plugins.Count; i++) + { + var plugin = _plugins[i]; + if (!plugin.Initialized || plugin.Failed || plugin.OnLogout == null) + continue; + + try + { + plugin.OnLogout(); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} received OnLogout."); + } + catch (Exception ex) + { + plugin.Failed = true; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnLogout threw {ex.GetType().Name}: {ex.Message}"); + } + } + } + private static void RescanPlugins(IntPtr imguiContext, IntPtr d3dDevice, IntPtr gameHwnd) { if (string.IsNullOrWhiteSpace(_pluginsDir)) diff --git a/src/RynthCore.PluginCore/RynthPluginBase.cs b/src/RynthCore.PluginCore/RynthPluginBase.cs index ff466a7..79fac48 100644 --- a/src/RynthCore.PluginCore/RynthPluginBase.cs +++ b/src/RynthCore.PluginCore/RynthPluginBase.cs @@ -37,6 +37,7 @@ public abstract class RynthPluginBase public virtual void OnTick() { } public virtual void OnUIInitialized() { } public virtual void OnLoginComplete() { } + public virtual void OnLogout() { } public virtual void OnBarAction() { } public virtual void OnRender() { } public virtual void OnChatWindowText(string? text, int chatType, ref int eat) { } diff --git a/src/RynthCore.PluginCore/RynthPluginRuntime.cs b/src/RynthCore.PluginCore/RynthPluginRuntime.cs index b7647df..f6c79eb 100644 --- a/src/RynthCore.PluginCore/RynthPluginRuntime.cs +++ b/src/RynthCore.PluginCore/RynthPluginRuntime.cs @@ -68,6 +68,12 @@ public unsafe sealed class RynthPluginRuntime _plugin!.OnLoginComplete(); } + public void OnLogout() + { + if (IsInitialized) + _plugin!.OnLogout(); + } + public void OnBarAction() { if (IsInitialized)