From cf698991987e1f0c2c9cf35587aa93233c641415 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Mon, 12 Oct 2026 16:32:05 -0700 Subject: [PATCH] Plugin fixes: duplicate target requests, bounded name read, guarded exports Selection: a selection change asked for an appraisal and a health query for every object, and the dashboard asked for health again. The engine selects each corpse it opens and each item it moves, so one object drew 4-6 identifies. OnSelectedTargetChange now sends an identify only for a creature with no cached appraisal (HasAppraisalData, else GetLastIdTime > 0) and a health query only for creatures. The dashboard no longer queries health itself. A target cached as Unknown (type not read yet) is undecided like an uncached one: a corpse name ("Corpse of") rejects, the creature flag 0x10 accepts, a typed non-creature rejects, then ObjectIsAttackable decides, and with nothing to go on it fails open. Fellowship name read: FellowshipTracker.ReadPString read to a NUL with no bound. It now reads at most 64 characters and never past the end of the probed region. Exports: an exception escaping an UnmanagedCallersOnly export fail-fasts the client under NativeAOT. The Shutdown exports of RynthAi, RynthNav, RynthNet, RynthVision, RynthLua, RynthChat, RynthInventory, RynthOracle and RynthTracker guard each step and log the error; the Name/Version exports of RynthAi, RynthNav, RynthLua, RynthChat, RynthInventory, RynthNet, RynthOracle, RynthTracker and RynthVision (a static initializer that throws surfaces there) are wrapped. Tests (PluginFixTests) with FakeHost QueryHealth and GetLastIdTime. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../Combat/FellowshipTracker.cs | 38 ++- .../LegacyUi/LegacyDashboardRenderer.cs | 3 +- .../RynthCore.Plugin.RynthAi/PluginExports.cs | 45 +++- .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 63 ++++- .../PluginExports.cs | 18 +- .../PluginExports.cs | 18 +- .../PluginExports.cs | 18 +- .../PluginExports.cs | 27 +- .../RynthNavPlugin.cs | 3 + .../PluginExports.cs | 22 +- .../PluginExports.cs | 18 +- .../PluginExports.cs | 18 +- .../PluginExports.cs | 15 +- .../Fakes/FakeHost.cs | 17 +- Tools/RynthCore.RynthAiHostTests/Program.cs | 1 + .../Tests/PluginFixTests.cs | 246 ++++++++++++++++++ 16 files changed, 518 insertions(+), 52 deletions(-) create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/PluginFixTests.cs diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs index f4d4681..cdc6726 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/FellowshipTracker.cs @@ -348,12 +348,40 @@ public class FellowshipTracker : IDisposable int bufPtr = Marshal.ReadInt32(addr); if (bufPtr == 0) return ""; IntPtr strAddr = new IntPtr(bufPtr + 0x14); - if (!IsReadablePointer(strAddr)) return ""; - string? raw = Marshal.PtrToStringAnsi(strAddr); - if (raw == null) return ""; - if (raw.Length > 64) raw = raw[..64]; - return raw; + // Bounded read: PtrToStringAnsi scans to a NUL however far that is, past + // the probed region into unmapped memory if the buffer is mid-free or never terminated. + return ReadBoundedAnsi(strAddr, MaxNameChars, ReadableBytesFrom(strAddr)); } catch { return ""; } } + + /// A fellowship member's name is at most this long (AC names are under 20). + internal const int MaxNameChars = 64; + + /// Bytes from to the end of its committed region (the probed + /// page run); 0 when the address is not readable. + internal static int ReadableBytesFrom(IntPtr ptr) + { + if (ptr == IntPtr.Zero) return 0; + if (VirtualQuery(ptr, out var mbi, Marshal.SizeOf()) == 0) return 0; + if (mbi.State != MEM_COMMIT) return 0; + if ((mbi.Protect & PAGE_NOACCESS) != 0 || (mbi.Protect & PAGE_GUARD) != 0) return 0; + long left = (long)mbi.BaseAddress + (long)mbi.RegionSize - (long)ptr; + return left <= 0 ? 0 : (int)Math.Min(left, int.MaxValue); + } + + /// + /// Reads a NUL-terminated ANSI string of at most characters and + /// never more than bytes from . An + /// unterminated run is cut at the bound, not scanned on. Internal for the tests. + /// + internal static unsafe string ReadBoundedAnsi(IntPtr addr, int maxChars, int readableBytes) + { + int limit = Math.Min(maxChars, readableBytes); + if (addr == IntPtr.Zero || limit <= 0) return ""; + byte* p = (byte*)addr; + int n = 0; + while (n < limit && p[n] != 0) n++; + return n == 0 ? "" : Marshal.PtrToStringAnsi(addr, n) ?? ""; + } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index b701abe..85aa5fa 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -1874,7 +1874,8 @@ internal sealed class LegacyDashboardRenderer _targetMana = 0; _targetMaxMana = 0; _targetHealthDisplay = targetId == 0 ? "0" : "--"; - if (targetId != 0 && _host.HasQueryHealth) _host.QueryHealth(targetId); + // No health query here: RynthAiPlugin.OnSelectedTargetChange sends the one guarded + // query (creatures only); this ran on every corpse and item the engine selects. } public void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index 715ea87..a9f5dd3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -41,14 +41,31 @@ public static unsafe class PluginExports [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] public static void Shutdown() { - Runtime.Shutdown(); - StatusInterface.Release(); - ActivityInterface.Release(); - CombatHookInterface.Shutdown(); // the hook goes native at once (RynthLua re-claims after a reload) - // The loot editor's state can be a few hundred KB (LootSnobV4): don't leave it behind on a reload. - foreach (IntPtr p in new[] { Interlocked.Exchange(ref _lootStatePtr, IntPtr.Zero), - Interlocked.Exchange(ref _lootRulePtr, IntPtr.Zero), Interlocked.Exchange(ref _lootVocabPtr, IntPtr.Zero) }) - if (p != IntPtr.Zero) Marshal.FreeCoTaskMem(p); + // An exception escaping an UnmanagedCallersOnly export fail-fasts the whole client under + // NativeAOT. Each step is guarded on its own so one failure cannot skip the rest. + RynthAiPlugin? plugin = Runtime.Plugin; // Runtime.Shutdown drops it; the log needs its host + try { Runtime.Shutdown(); } + catch (Exception ex) { LogShutdownError(plugin, "Runtime.Shutdown", ex); } + try { StatusInterface.Release(); } + catch (Exception ex) { LogShutdownError(plugin, "StatusInterface.Release", ex); } + try { ActivityInterface.Release(); } + catch (Exception ex) { LogShutdownError(plugin, "ActivityInterface.Release", ex); } + try { CombatHookInterface.Shutdown(); } // the hook goes native at once (RynthLua re-claims after a reload) + catch (Exception ex) { LogShutdownError(plugin, "CombatHookInterface.Shutdown", ex); } + try + { + // The loot editor's state can be a few hundred KB (LootSnobV4): don't leave it behind on a reload. + foreach (IntPtr p in new[] { Interlocked.Exchange(ref _lootStatePtr, IntPtr.Zero), + Interlocked.Exchange(ref _lootRulePtr, IntPtr.Zero), Interlocked.Exchange(ref _lootVocabPtr, IntPtr.Zero) }) + if (p != IntPtr.Zero) Marshal.FreeCoTaskMem(p); + } + catch (Exception ex) { LogShutdownError(plugin, "loot buffers", ex); } + } + + private static void LogShutdownError(RynthAiPlugin? plugin, string step, Exception ex) + { + try { plugin?.LogFromExport($"[RynthAi] Shutdown: {step} failed: {ex.GetType().Name}: {ex.Message}"); } + catch { /* nothing more to do: never throw out of a native export */ } } [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUIInitialized", CallConvs = new[] { typeof(CallConvCdecl) })] @@ -64,10 +81,18 @@ public static unsafe class PluginExports public static void OnSelectedTargetChange(uint currentTargetId, uint previousTargetId) => Runtime.OnSelectedTargetChange(currentTargetId, previousTargetId); [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetName() => RynthAiPlugin.NamePointer; + public static IntPtr GetName() + { + try { return RynthAiPlugin.NamePointer; } // a static initializer that throws surfaces here (TypeInitializationException) + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetVersion() => RynthAiPlugin.VersionPointer; + public static IntPtr GetVersion() + { + try { return RynthAiPlugin.VersionPointer; } + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] public static void Tick() => Runtime.OnTick(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index cd3eadb..2559277 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -2025,23 +2025,24 @@ public sealed partial class RynthAiPlugin : RynthPluginBase private bool _lootInspectMode = true; // always on; /ra lootcheck off to disable + /// Lets PluginExports log through this plugin's host (the base Log is protected). + internal void LogFromExport(string message) => Log(message); + public override void OnSelectedTargetChange(uint currentTargetId, uint previousTargetId) { _currentTargetId = currentTargetId; _dashboard?.SetSelectedTarget(currentTargetId); - // Appraise the target so the server sends back its vitals (including MaxHealth). - // Follow up with QueryHealth to resolve the ratio → absolute HP values. - if (currentTargetId != 0) - { - if (Host.HasRequestId) Host.RequestId(currentTargetId); - if (Host.HasQueryHealth) Host.QueryHealth(currentTargetId); - } - if (currentTargetId != 0) { int sid = unchecked((int)currentTargetId); WorldObject? obj = _objectCache?[sid]; + + // Vitals (incl. MaxHealth) only matter for a creature. The engine selects every corpse + // it opens and every item it moves, and AutoId already appraises the selection, so an + // unguarded appraisal + health query here sent 4-6 identifies per corpse. + RequestTargetVitals(currentTargetId, obj); + // Item info on select replaces the loot verdict line: one line per pick, not two // (as SilentKelpie's fork does, rynth/RynthSuite PR #3). /ra lootcheck still prints it. bool itemInfo = QueueItemInfoOnSelect(currentTargetId, obj); @@ -2051,6 +2052,52 @@ public sealed partial class RynthAiPlugin : RynthPluginBase } } + /// + /// Selection of a creature: ask for its appraisal only when the client has none cached, then + /// a health query (resolves the ratio to absolute HP). Corpses, items and other non-creatures + /// get neither. The dashboard no longer queries health on its own. + /// + private void RequestTargetVitals(uint id, WorldObject? obj) + { + if (!IsCreatureTarget(id, obj)) return; + if (Host.HasRequestId && !HasCachedAppraisal(id)) Host.RequestId(id); + if (Host.HasQueryHealth) Host.QueryHealth(id); + } + + private static bool IsCreatureClass(AcObjectClass cls) => + cls is AcObjectClass.Monster or AcObjectClass.Player or AcObjectClass.Npc or AcObjectClass.CombatPet; + + private const uint ItemTypeCreatureFlag = 0x10; + + /// + /// Is the selection a creature worth an identify and a health query? A cached class other than + /// Unknown decides. Otherwise (not cached, or cached as Unknown while the item type is still + /// unread, up to ~30 s after login) the name, the engine's type flags and ObjectIsAttackable + /// decide, and a target nothing can classify fails OPEN: a missed health query costs more + /// than one extra identify. + /// + private bool IsCreatureTarget(uint id, WorldObject? obj) + { + if (obj != null && obj.ObjectClass != AcObjectClass.Unknown) + return IsCreatureClass(obj.ObjectClass); + + // Corpses keep the creature flag, so reject them by name before the flag is read. + string name = obj?.Name ?? ""; + if (name.Length == 0) Host.TryGetObjectName(id, out name); + if (name != null && name.StartsWith("Corpse of", StringComparison.Ordinal)) return false; + + if (Host.HasGetItemType && Host.TryGetItemType(id, out uint flags)) + return (flags & ItemTypeCreatureFlag) != 0; // typed: a creature, else an item, door or portal + if (Host.HasObjectIsAttackable) return Host.ObjectIsAttackable(id); + return true; // nothing to go on: fail open + } + + private bool HasCachedAppraisal(uint id) + { + if (Host.HasHasAppraisalData && Host.HasAppraisalData(id)) return true; + return Host.HasGetLastIdTime && Host.GetLastIdTime(id) > 0; + } + private static bool IsLootableClass(AcObjectClass cls) => cls is not ( AcObjectClass.Unknown or AcObjectClass.Monster or AcObjectClass.Player or AcObjectClass.Vendor or AcObjectClass.Door or AcObjectClass.Corpse or diff --git a/Plugins/RynthCore.Plugin.RynthChat/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthChat/PluginExports.cs index 42113c5..61e049a 100644 --- a/Plugins/RynthCore.Plugin.RynthChat/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthChat/PluginExports.cs @@ -15,7 +15,11 @@ public static unsafe class PluginExports private static int Init(RynthCoreApiNative* api) => Runtime.Init(api); [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void Shutdown() => Runtime.Shutdown(); + public static void Shutdown() + { + try { Runtime.Shutdown(); } // an exception out of a native export fail-fasts the client + catch { } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })] public static void OnLoginComplete() => Runtime.OnLoginComplete(); @@ -24,10 +28,18 @@ public static unsafe class PluginExports public static void OnLogout() => Runtime.OnLogout(); [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetName() => RynthChatPlugin.NamePointer; + public static IntPtr GetName() + { + try { return RynthChatPlugin.NamePointer; } + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetVersion() => RynthChatPlugin.VersionPointer; + public static IntPtr GetVersion() + { + try { return RynthChatPlugin.VersionPointer; } + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] public static void Tick() => Runtime.OnTick(); diff --git a/Plugins/RynthCore.Plugin.RynthInventory/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthInventory/PluginExports.cs index 9171b56..e830c0b 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthInventory/PluginExports.cs @@ -20,14 +20,26 @@ public static unsafe class PluginExports private static int Init(RynthCoreApiNative* api) => Runtime.Init(api); [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void Shutdown() => Runtime.Shutdown(); + public static void Shutdown() + { + try { Runtime.Shutdown(); } // an exception out of a native export fail-fasts the client + catch { } + } // UTF-8 literals live in the module's read-only data: nothing to allocate or free. [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetName() => LiteralPointer("RynthInventory"u8); + public static IntPtr GetName() + { + try { return LiteralPointer("RynthInventory"u8); } + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetVersion() => LiteralPointer("0.1.0"u8); + public static IntPtr GetVersion() + { + try { return LiteralPointer("0.1.0"u8); } + catch { return IntPtr.Zero; } + } private static IntPtr LiteralPointer(ReadOnlySpan literal) { diff --git a/Plugins/RynthCore.Plugin.RynthLua/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthLua/PluginExports.cs index c54e58c..f449068 100644 --- a/Plugins/RynthCore.Plugin.RynthLua/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthLua/PluginExports.cs @@ -16,13 +16,25 @@ public static unsafe class PluginExports private static int Init(RynthCoreApiNative* api) => Runtime.Init(api); [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void Shutdown() => Runtime.Shutdown(); + public static void Shutdown() + { + try { Runtime.Shutdown(); } // an exception out of a native export fail-fasts the client + catch { } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetName() => RynthLuaPlugin.NamePointer; + public static IntPtr GetName() + { + try { return RynthLuaPlugin.NamePointer; } // a static initializer that throws surfaces here (TypeInitializationException) + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetVersion() => RynthLuaPlugin.VersionPointer; + public static IntPtr GetVersion() + { + try { return RynthLuaPlugin.VersionPointer; } + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] public static void Tick() => Runtime.OnTick(); diff --git a/Plugins/RynthCore.Plugin.RynthNav/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthNav/PluginExports.cs index 5ad6f5c..82d7f83 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/PluginExports.cs @@ -36,15 +36,34 @@ public static unsafe class PluginExports [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] public static void Shutdown() { - Runtime.Shutdown(); - PathInterface.Release(); + // An exception escaping an UnmanagedCallersOnly export fail-fasts the client under NativeAOT. + // Guard each step so one failure cannot skip the other. + RynthNavPlugin? plugin = Runtime.Plugin; // Runtime.Shutdown drops it; the log needs its host + try { Runtime.Shutdown(); } + catch (Exception ex) { LogShutdownError(plugin, "Runtime.Shutdown", ex); } + try { PathInterface.Release(); } + catch (Exception ex) { LogShutdownError(plugin, "PathInterface.Release", ex); } + } + + private static void LogShutdownError(RynthNavPlugin? plugin, string step, Exception ex) + { + try { plugin?.LogFromExport($"[RynthNav] Shutdown: {step} failed: {ex.GetType().Name}: {ex.Message}"); } + catch { /* never throw out of a native export */ } } [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetName() => RynthNavPlugin.NamePointer; + public static IntPtr GetName() + { + try { return RynthNavPlugin.NamePointer; } // a static initializer that throws surfaces here (TypeInitializationException) + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetVersion() => RynthNavPlugin.VersionPointer; + public static IntPtr GetVersion() + { + try { return RynthNavPlugin.VersionPointer; } + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })] public static void OnLoginComplete() => Runtime.OnLoginComplete(); diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs index 95dd336..874006f 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs @@ -28,6 +28,9 @@ public sealed partial class RynthNavPlugin : RynthPluginBase internal const string PluginVersion = "0.6.6"; internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi(PluginVersion); + /// Lets PluginExports log through this plugin's host (the base Log is protected). + internal void LogFromExport(string message) => Log(message); + // Where the tiles, portals.tsv, locations.json and the player's atlas.txt/recalls.txt live. // From RYNTHNAV_NAVDATA, else "navDataDir" in %APPDATA%\RynthCore\rynthnav.json, else the // default (the folder the release zip and the launcher's tile updater fill). See NavDataConfig. diff --git a/Plugins/RynthCore.Plugin.RynthNet/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthNet/PluginExports.cs index 03498c4..7fcd491 100644 --- a/Plugins/RynthCore.Plugin.RynthNet/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthNet/PluginExports.cs @@ -17,16 +17,28 @@ public static unsafe class PluginExports [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] public static void Shutdown() { - Runtime.Shutdown(); // stops the transport: joins its thread and tasks - NetInterface.Release(); - ReleaseSnapshot(); + // Each step is guarded alone: an exception escaping a native export fail-fasts the client. + try { Runtime.Shutdown(); } // stops the transport: joins its thread and tasks + catch { } + try { NetInterface.Release(); } + catch { } + try { ReleaseSnapshot(); } + catch { } } [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetName() => RynthNetPlugin.NamePointer; + public static IntPtr GetName() + { + try { return RynthNetPlugin.NamePointer; } + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetVersion() => RynthNetPlugin.VersionPointer; + public static IntPtr GetVersion() + { + try { return RynthNetPlugin.VersionPointer; } + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] public static void Tick() => Runtime.OnTick(); diff --git a/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs index cb6f120..939ef74 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs @@ -20,14 +20,26 @@ public static unsafe class PluginExports private static int Init(RynthCoreApiNative* api) => Runtime.Init(api); [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void Shutdown() => Runtime.Shutdown(); + public static void Shutdown() + { + try { Runtime.Shutdown(); } // an exception out of a native export fail-fasts the client + catch { } + } // UTF-8 literals live in the module's read-only data: nothing to allocate or free. [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetName() => LiteralPointer("RynthOracle"u8); + public static IntPtr GetName() + { + try { return LiteralPointer("RynthOracle"u8); } + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetVersion() => LiteralPointer("0.2.0"u8); + public static IntPtr GetVersion() + { + try { return LiteralPointer("0.2.0"u8); } + catch { return IntPtr.Zero; } + } private static IntPtr LiteralPointer(ReadOnlySpan literal) { diff --git a/Plugins/RynthCore.Plugin.RynthTracker/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthTracker/PluginExports.cs index 98a8b7a..33a8c4a 100644 --- a/Plugins/RynthCore.Plugin.RynthTracker/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthTracker/PluginExports.cs @@ -15,13 +15,25 @@ public static unsafe class PluginExports private static int Init(RynthCoreApiNative* api) => Runtime.Init(api); [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void Shutdown() => Runtime.Shutdown(); + public static void Shutdown() + { + try { Runtime.Shutdown(); } // an exception out of a native export fail-fasts the client + catch { } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetName() => RynthTrackerPlugin.NamePointer; + public static IntPtr GetName() + { + try { return RynthTrackerPlugin.NamePointer; } + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetVersion() => RynthTrackerPlugin.VersionPointer; + public static IntPtr GetVersion() + { + try { return RynthTrackerPlugin.VersionPointer; } + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] public static void Tick() => Runtime.OnTick(); diff --git a/Plugins/RynthCore.Plugin.RynthVision/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthVision/PluginExports.cs index c211b45..c79d1b0 100644 --- a/Plugins/RynthCore.Plugin.RynthVision/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthVision/PluginExports.cs @@ -22,7 +22,8 @@ public static unsafe class PluginExports [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] public static void Shutdown() { - Runtime.Shutdown(); + try { Runtime.Shutdown(); } + catch { } try { // The engine copies the settings string as soon as it gets it, on @@ -46,10 +47,18 @@ public static unsafe class PluginExports // and they stay valid for as long as the module is loaded (the engine // copies them right after loading, before Init). [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetName() => LiteralPointer("RynthVision"u8); + public static IntPtr GetName() + { + try { return LiteralPointer("RynthVision"u8); } + catch { return IntPtr.Zero; } + } [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetVersion() => LiteralPointer("0.1.0"u8); + public static IntPtr GetVersion() + { + try { return LiteralPointer("0.1.0"u8); } + catch { return IntPtr.Zero; } + } private static IntPtr LiteralPointer(ReadOnlySpan literal) { diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index 38dc479..f6f871d 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -115,6 +115,10 @@ internal static unsafe class FakeHost /// Every UseObject (a wield, a use) and RequestId (an identify), in order. public static readonly List Uses = new(); public static readonly List IdRequests = new(); + /// Opt-in (set before Create): QueryHealth (counted in ) and GetLastIdTime (answering , 0 = never). + public static bool TargetCalls; + public static readonly List HealthQueries = new(); + public static readonly Dictionary IdTimes = new(); /// Every MoveItemInternal (an item into a pack), in order (opt-in with ). public static readonly List<(uint Id, uint Pack, int Amount)> Moves = new(); /// Objects the fake says have appraisal data (HasAppraisalData). @@ -218,7 +222,7 @@ internal static unsafe class FakeHost HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0; Logs.Clear(); Chat.Clear(); ChatCommands.Clear(); AfterCastSpell = null; AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; - Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1; + Uses.Clear(); IdRequests.Clear(); TargetCalls = false; HealthQueries.Clear(); IdTimes.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1; VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0; ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false; // Spell mana costs "unknown" (no reserve beyond Get Mana At, no cost gate), so a portal.dat on @@ -298,6 +302,11 @@ internal static unsafe class FakeHost api.GetCurrentCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetCurrentCombatMode; api.MoveItemInternalFn = (IntPtr)(delegate* unmanaged[Cdecl])&MoveItemInternal; } + if (TargetCalls) + { + api.QueryHealthFn = (IntPtr)(delegate* unmanaged[Cdecl])&QueryHealth; + api.GetLastIdTimeFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetLastIdTime; + } if (SalvageCalls) { api.UseObjectFn = (IntPtr)(delegate* unmanaged[Cdecl])&UseObject; @@ -734,6 +743,12 @@ internal static unsafe class FakeHost [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int RequestId(uint id) { IdRequests.Add(id); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int QueryHealth(uint id) { HealthQueries.Add(id); return 1; } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static long GetLastIdTime(uint id) => IdTimes.TryGetValue(id, out long t) ? t : 0L; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int HasAppraisalData(uint id) => Appraised.Contains(id) ? 1 : 0; diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 465c4c4..d35927e 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -105,6 +105,7 @@ internal static class Program PacerEdgeTests.Register(runner); RecoveryRetryTests.Register(runner); HpFailsafeTests.Register(runner); + PluginFixTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PluginFixTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PluginFixTests.cs new file mode 100644 index 0000000..9c52b8e --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PluginFixTests.cs @@ -0,0 +1,246 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.ItemInfo; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Plugin-only fixes: +// - a selection change sent duplicate identifies and health queries (the engine selects every +// corpse it opens and every item it moves): creatures only, and no identify when cached; +// - the fellowship name read scanned to a NUL without a bound. +// (The Shutdown exports' try/catch is an [UnmanagedCallersOnly] method: managed code cannot call +// it, so it has no test here.) +internal static class PluginFixTests +{ + private const uint Player = 0x50000F21; + private const uint Wolf = 0x80400001, Dead = 0x80400002, Peas = 0x80400003, Wolf2 = 0x80400004; + private const uint Ghost = 0x80400005, Ghost2 = 0x80400006, Ghost3 = 0x80400007, Ghost4 = 0x80400008, CorpseX = 0x80400009; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static; + + public static void Register(Runner r) + { + r.Add("selection: selecting a creature whose appraisal is cached sends no identify", CachedCreatureNoId); + r.Add("selection: selecting an uncached creature sends exactly one identify (and one health query)", UncachedCreatureOneId); + r.Add("selection: selecting a corpse or an item sends no identify and no health query", CorpseAndItemNothing); + r.Add("selection: the dashboard alone sends no health query", DashboardNoHealthQuery); + r.Add("selection: a monster cached as Unknown (type not read yet) still gets its identify and health query", UnknownMonsterStillAsked); + r.Add("selection: an Unknown that is typed as an item, or not attackable, gets nothing; a late creature flag does", UnknownNonCreatureNothing); + r.Add("selection: no cache entry - a corpse is rejected by name, a creature by its flag", NullCacheFallback); + r.Add("selection: creature classes are Monster, Player, Npc and CombatPet only", CreatureClasses); + r.Add("fellowship name read: ReadableBytesFrom ends at the page whose neighbour is PAGE_NOACCESS", ReadableBytesAtGuardPage); + r.Add("fellowship name read: it stops at 64 characters and at the end of the probed bytes", NameReadBounded); + } + + // -- Selection ------------------------------------------------------------ + + private sealed class World + { + public readonly RynthAiPlugin P = new(); + public readonly WorldObjectCache Cache; + public readonly RynthCoreHost Host; + public readonly LegacyDashboardRenderer Dash; + + public World() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; // RequestId + HasAppraisalData + FakeHost.TargetCalls = true; // QueryHealth + GetLastIdTime + FakeHost.Names[Player] = "Reader"; + FakeHost.PlayerIdValue = Player; + FakeHost.Positions[Player] = (0x1048002Au, 100f, 100f, 0f); + FakeHost.PlayerPose = (0x1048002Au, 100f, 100f, 0f); + + Landscape(Wolf, "Grievver", 0x10); + Landscape(Wolf2, "Shadow", 0x10); + Landscape(Dead, "Corpse of Grievver", 0x10); // a corpse keeps the creature flag + FakeHost.Names[Peas] = "Pyreal Pea"; + FakeHost.Containers[Peas] = Player; + FakeHost.ItemTypes[Peas] = 0x8; + + Host = FakeHost.Create(playerId: Player); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + Dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(Dash, new LegacyUiSettings()); + typeof(LegacyDashboardRenderer).GetField("_host", Any)!.SetValue(Dash, Host); + Cache = new WorldObjectCache(Host); + Cache.SetPlayerId(Player); + Set("_dashboard", Dash); + Set("_objectCache", Cache); + Set("_playerId", Player); + Set("_initialized", true); + Set("_loginComplete", true); + Set("_lootInspectMode", false); // not under test: keeps the loot-rule check out of the way + foreach (uint id in new[] { Wolf, Wolf2, Dead, Peas }) Cache.OnCreateObject(id); + Cache.Tick(); + } + + private static void Landscape(uint id, string name, uint type) + { + FakeHost.Names[id] = name; + FakeHost.Positions[id] = (0x1048002Au, 105f, 100f, 0f); + FakeHost.ItemTypes[id] = type; + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + + public void Select(uint id) => P.OnSelectedTargetChange(id, 0); + } + + private static void CachedCreatureNoId() + { + var w = new World(); + FakeHost.Appraised.Add(Wolf); + w.Select(Wolf); + Check.Eq(FakeHost.IdRequests.Count, 0, "appraisal cached: no identify"); + Check.Eq(FakeHost.HealthQueries.Count, 1, "the creature's health is still asked once"); + + FakeHost.IdTimes[Wolf2] = 1234; // an engine that only reports GetLastIdTime + w.Select(Wolf2); + Check.Eq(FakeHost.IdRequests.Count, 0, "a reply on record (GetLastIdTime > 0) counts as cached"); + } + + private static void UncachedCreatureOneId() + { + var w = new World(); + w.Select(Wolf); + Check.True(FakeHost.IdRequests.SequenceEqual(new[] { Wolf }), $"exactly one identify: [{string.Join(",", FakeHost.IdRequests.Select(i => i.ToString("X8")))}]"); + Check.True(FakeHost.HealthQueries.SequenceEqual(new[] { Wolf }), "and one health query"); + } + + private static void CorpseAndItemNothing() + { + var w = new World(); + SelfSelect.Mark(Peas); // the engine's own pick (the looter moving an item) + w.Select(Dead); + w.Select(Peas); + Check.Eq(FakeHost.IdRequests.Count, 0, "a corpse and an item: no identify"); + Check.Eq(FakeHost.HealthQueries.Count, 0, "and no health query"); + } + + private static void DashboardNoHealthQuery() + { + var w = new World(); + w.Dash.SetSelectedTarget(Wolf); + w.Dash.SetSelectedTarget(Dead); + w.Dash.SetSelectedTarget(Peas); + Check.Eq(FakeHost.HealthQueries.Count, 0, "the dashboard's own selection handler sends no health query"); + Check.Eq(FakeHost.IdRequests.Count, 0, "nor an identify"); + } + + // -- Fellowship name read ------------------------------------------------- + + private static void NameReadBounded() + { + const int Size = 256; + IntPtr buf = Marshal.AllocHGlobal(Size); + try + { + for (int i = 0; i < Size; i++) Marshal.WriteByte(buf, i, i < 200 ? (byte)'A' : (byte)0); // 200 chars, then NULs + string capped = FellowshipTracker.ReadBoundedAnsi(buf, FellowshipTracker.MaxNameChars, 200); + Check.Eq(capped.Length, 64, "a long run is cut at 64 characters"); + + string atPageEnd = FellowshipTracker.ReadBoundedAnsi(buf, FellowshipTracker.MaxNameChars, 10); + Check.Eq(atPageEnd.Length, 10, "an unterminated run is cut where the probed bytes end"); + + Marshal.WriteByte(buf, 5, 0); + Check.Eq(FellowshipTracker.ReadBoundedAnsi(buf, FellowshipTracker.MaxNameChars, 200), "AAAAA", "a terminated name reads whole"); + Check.Eq(FellowshipTracker.ReadBoundedAnsi(buf, FellowshipTracker.MaxNameChars, 0), "", "nothing readable: empty"); + Check.Eq(FellowshipTracker.ReadBoundedAnsi(IntPtr.Zero, FellowshipTracker.MaxNameChars, 64), "", "null: empty"); + } + finally { Marshal.FreeHGlobal(buf); } + } + + private static void Land(uint id, string name) + { + FakeHost.Names[id] = name; + FakeHost.Positions[id] = (0x1048002Au, 106f, 100f, 0f); + } + + private static void UnknownMonsterStillAsked() + { + var w = new World(); + Land(Ghost, "Drudge Skulker"); // no ItemTypes entry: the type is not readable yet + Check.True(w.Cache[unchecked((int)Ghost)]?.ObjectClass == AcObjectClass.Unknown, "set-up: cached as Unknown"); + w.Select(Ghost); + Check.True(FakeHost.IdRequests.SequenceEqual(new[] { Ghost }), "identify sent for the Unknown"); + Check.True(FakeHost.HealthQueries.SequenceEqual(new[] { Ghost }), "health asked for the Unknown"); + } + + private static void UnknownNonCreatureNothing() + { + var w = new World(); + Land(Ghost2, "Marble Statue"); + Land(Ghost3, "Mute Thing"); + Land(Ghost4, "Late Wolf"); + foreach (uint g in new[] { Ghost2, Ghost3, Ghost4 }) + Check.True(w.Cache[unchecked((int)g)]?.ObjectClass == AcObjectClass.Unknown, $"set-up: {g:X8} cached as Unknown"); + FakeHost.ItemTypes[Ghost2] = 0x8; // the type arrives: an item + FakeHost.NotAttackable.Add(Ghost2); + FakeHost.NotAttackable.Add(Ghost3); // never typed, but the engine says not attackable + FakeHost.ItemTypes[Ghost4] = 0x10; // the type arrives: a creature + w.Select(Ghost2); + w.Select(Ghost3); + Check.Eq(FakeHost.IdRequests.Count, 0, "typed item / not attackable: no identify"); + Check.Eq(FakeHost.HealthQueries.Count, 0, "and no health query"); + w.Select(Ghost4); + Check.True(FakeHost.IdRequests.SequenceEqual(new[] { Ghost4 }) && FakeHost.HealthQueries.SequenceEqual(new[] { Ghost4 }), "the late creature flag is honoured"); + } + + private static void NullCacheFallback() + { + var w = new World(); + w.Set("_objectCache", null); + Land(CorpseX, "Corpse of Grievver"); + FakeHost.ItemTypes[CorpseX] = 0x10; // a corpse keeps the creature flag + w.Select(CorpseX); + Check.Eq(FakeHost.IdRequests.Count + FakeHost.HealthQueries.Count, 0, "an uncached corpse is rejected by name"); + w.Select(Wolf); + Check.True(FakeHost.IdRequests.SequenceEqual(new[] { Wolf }) && FakeHost.HealthQueries.SequenceEqual(new[] { Wolf }), + "positive control: an uncached creature (flag 0x10) is asked"); + } + + private static void CreatureClasses() + { + var m = typeof(RynthAiPlugin).GetMethod("IsCreatureClass", Any)!; + bool Is(AcObjectClass c) => (bool)m.Invoke(null, new object[] { c })!; + foreach (var c in new[] { AcObjectClass.Monster, AcObjectClass.Player, AcObjectClass.Npc, AcObjectClass.CombatPet }) + Check.True(Is(c), $"{c} is a creature"); + foreach (var c in new[] { AcObjectClass.Corpse, AcObjectClass.Unknown, AcObjectClass.Vendor, AcObjectClass.Door, AcObjectClass.Portal }) + Check.False(Is(c), $"{c} is not"); + } + + // -- ReadableBytesFrom at a guard page ------------------------------------ + + [DllImport("kernel32.dll")] private static extern IntPtr VirtualAlloc(IntPtr addr, UIntPtr size, uint type, uint protect); + [DllImport("kernel32.dll")] private static extern bool VirtualProtect(IntPtr addr, UIntPtr size, uint protect, out uint old); + [DllImport("kernel32.dll")] private static extern bool VirtualFree(IntPtr addr, UIntPtr size, uint type); + + private static void ReadableBytesAtGuardPage() + { + const uint CommitReserve = 0x3000, ReadWrite = 0x04, NoAccess = 0x01, Release = 0x8000; + IntPtr p = VirtualAlloc(IntPtr.Zero, (UIntPtr)8192u, CommitReserve, ReadWrite); + Check.True(p != IntPtr.Zero, "set-up: two pages allocated"); + if (p == IntPtr.Zero) return; + try + { + Check.True(VirtualProtect(p + 4096, (UIntPtr)4096u, NoAccess, out _), "set-up: second page PAGE_NOACCESS"); + for (int i = 0; i < 4096; i++) Marshal.WriteByte(p, i, (byte)'A'); // no NUL before the guard page + IntPtr s = p + 4090; + Check.Eq(FellowshipTracker.ReadableBytesFrom(s), 6, "six readable bytes left before the guard page"); + Check.Eq(FellowshipTracker.ReadableBytesFrom(p + 4096), 0, "the guard page itself: none"); + Check.Eq(FellowshipTracker.ReadBoundedAnsi(s, FellowshipTracker.MaxNameChars, FellowshipTracker.ReadableBytesFrom(s)), "AAAAAA", + "an unterminated name at the page end stops there, without touching the guard page"); + } + finally { VirtualFree(p, UIntPtr.Zero, Release); } + }}