RynthCore as of 2026-09-05 (internal f9abab9)

A snapshot of the working tree for aelrynth.com/git/: the code, build files
and public docs. Internal review notes and agent instructions are left out.
MIT licensed; see LICENSE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-09-25 21:22:59 -04:00
commit 68c301dac8
277 changed files with 86286 additions and 0 deletions

View file

@ -0,0 +1,331 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
namespace RynthCore.Engine.Plugins;
internal static class EngineSettings
{
private static readonly string SettingsPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"engine.json");
private static List<string> _pluginPaths = new();
private static bool _enableImGuiShell = true;
private static bool _enablePlugins = true;
private static bool _enableDatShareHook = true;
private static bool _enableAvaloniaOverlay = true;
private static bool _enableD3D9Hook = true;
private static bool _enableEngine = true;
private static int _engineHookCount = int.MaxValue;
private static bool _enableImGuiBackend = true;
private static bool _enableHangMinidump = true;
private static bool _drawCustomVitalBars = true;
private static bool _loaded;
public static IReadOnlyList<string> PluginPaths
{
get
{
EnsureLoaded();
return _pluginPaths;
}
}
/// <summary>Force-disabled in code: RynthCore's in-AC UI is the Avalonia overlay, so the
/// ImGui shell (RynthCoreShell bar + plugin ImGui windows) never renders. engine.json and
/// the launcher Plugins tab can no longer toggle this; the persisted field is now a no-op.
/// A developer can opt back in for debugging by setting env var RYNTHCORE_FORCE_IMGUI=1
/// before launching AC — normal users never set this.</summary>
public static bool EnableImGuiShell
=> string.Equals(
System.Environment.GetEnvironmentVariable("RYNTHCORE_FORCE_IMGUI"),
"1", System.StringComparison.Ordinal);
/// <summary>When false, PluginManager.LoadPlugins is skipped so no plugin DLLs load,
/// init, tick, or render. Decal-coexistence plugin pump is also skipped. Default true.</summary>
public static bool EnablePlugins
{
get
{
EnsureLoaded();
return _enablePlugins;
}
}
/// <summary>When false, DatFileShareHooks.Initialize is skipped so kernel32!CreateFileA/W
/// are NOT detoured and no DAT-extension access/share rewriting happens. Multi-client DAT
/// coexistence with Decal-injected clients sharing the same install will fall back to the
/// stricter share semantics those clients negotiated. Default true. Use to isolate the
/// hook for crash diagnostics.</summary>
public static bool EnableDatShareHook
{
get
{
EnsureLoaded();
return _enableDatShareHook;
}
}
/// <summary>When false, AvaloniaOverlay.Start() is skipped so the Avalonia STA thread,
/// the offscreen overlay window, and all OverlayHost-registered panels never instantiate.
/// Eliminates the entire Avalonia/Skia surface from the process. Compatibility hooks and
/// (when enabled) plugins still load. Default true. Use to confirm whether the engine
/// runs cleanly without Avalonia.</summary>
public static bool EnableAvaloniaOverlay
{
get
{
EnsureLoaded();
return _enableAvaloniaOverlay;
}
}
/// <summary>When false, D3D9Bootstrapper.Start() is skipped at LoginComplete so neither
/// Direct3DCreate9/CreateDevice nor IDirect3DDevice9::EndScene get hooked. Eliminates the
/// entire D3D9 detour path, ImGui per-frame work, and the in-AC overlay bar. Compatibility
/// hooks and Avalonia (when enabled) still run. Default true. Use to confirm whether the
/// engine runs cleanly without the EndScene detour.</summary>
public static bool EnableD3D9Hook
{
get
{
EnsureLoaded();
return _enableD3D9Hook;
}
}
/// <summary>When false, InitWorker installs no Compatibility/* hooks, no
/// LoginLifecycleHooks subscriber chain, no OverlayHost panels, no Avalonia,
/// no D3D9. Only the early items (CrashLogger, ProcessExitHooks,
/// MultiClientHooks, DatFileShareHooks, HeartbeatLogger) that fire before
/// InitWorker stay active. Use to confirm whether the recursive AV is in
/// the engine's main hook path or in something earlier (loader, NativeAOT
/// runtime, MultiClientHooks/DatFileShareHooks).</summary>
public static bool EnableEngine
{
get
{
EnsureLoaded();
return _enableEngine;
}
}
/// <summary>Cap on how many of InitWorker's RunInitStep calls actually fire.
/// Default = int.MaxValue (= install all 36). Set to 18 to install only the
/// first half, 9 for the first quarter, etc — use for binary-search
/// bisection of which Compatibility hook is causing the recursive AV.
/// Has no effect if EnableEngine is false.</summary>
public static int EngineHookCount
{
get
{
EnsureLoaded();
return _engineHookCount;
}
}
/// <summary>When false, EngineFrameController.OnEndScene skips its
/// ImGui-specific block (Win32Backend.NewFrame, DX9Backend.NewFrame,
/// ImGui.NewFrame/EndFrame/Render, RynthCoreShell + plugin RenderAll,
/// DX9Backend.RenderDrawData, viewport pump). The always-on engine work
/// (GameMatrixCapture, Nav3DRenderInjector, PluginManager init/tick/
/// pending-action drains, DX9Backend.RenderNav3D fallback) still runs
/// every frame. Diagnostic for whether the per-frame ImGui path is the
/// recurser.</summary>
public static bool EnableImGuiBackend
{
get
{
EnsureLoaded();
return _enableImGuiBackend;
}
}
/// <summary>When true, MainThreadHangWatchdog writes a minidump to
/// Logs\dumps\ the first time AC's main thread is confirmed permanently
/// wedged — a targeted post-mortem to replace always-on procdump (which
/// dumped on every clean exit too). Default true.</summary>
public static bool EnableHangMinidump
{
get
{
EnsureLoaded();
return _enableHangMinidump;
}
}
/// <summary>When true, the engine draws the custom D3D9 Health/Stamina/Mana HUD
/// (<see cref="D3D9.VitalHud"/>) in EndScene. Toggleable live via "/rc vitals";
/// the setter persists to engine.json so it survives relaunch. Default true.
/// Only takes visible effect on a clean (no-Decal) client where the
/// D3D9/EndScene path runs.</summary>
public static bool DrawCustomVitalBars
{
get
{
EnsureLoaded();
return _drawCustomVitalBars;
}
set
{
EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file
if (_drawCustomVitalBars == value) return;
_drawCustomVitalBars = value;
Save();
}
}
public static void AddPluginPath(string path)
{
EnsureLoaded();
string full = Path.GetFullPath(path);
for (int i = 0; i < _pluginPaths.Count; i++)
{
if (string.Equals(_pluginPaths[i], full, StringComparison.OrdinalIgnoreCase))
return;
}
_pluginPaths.Add(full);
Save();
}
public static void RemovePluginPath(int index)
{
EnsureLoaded();
if (index >= 0 && index < _pluginPaths.Count)
{
_pluginPaths.RemoveAt(index);
Save();
}
}
private static void EnsureLoaded()
{
if (_loaded) return;
_loaded = true;
try
{
if (!File.Exists(SettingsPath)) return;
// ReadAllText detects + strips the UTF-8/UTF-16 BOM that some editors
// (PowerShell 5.1 Set-Content -Encoding utf8, Notepad) silently prepend.
// ReadAllBytes + JsonDocument.Parse trips on a leading BOM with
// "'0xEF' is an invalid start of a value", which then sends every
// EngineSettings flag back to its default — silently re-enables
// EnableImGuiBackend etc. with no surfaced error.
using var doc = JsonDocument.Parse(File.ReadAllText(SettingsPath));
if (doc.RootElement.TryGetProperty("PluginPaths", out var arr) &&
arr.ValueKind == JsonValueKind.Array)
{
foreach (var el in arr.EnumerateArray())
{
string? val = el.GetString();
if (!string.IsNullOrWhiteSpace(val))
_pluginPaths.Add(val);
}
}
if (doc.RootElement.TryGetProperty("EnableImGuiShell", out var shellEl) &&
(shellEl.ValueKind == JsonValueKind.True || shellEl.ValueKind == JsonValueKind.False))
{
_enableImGuiShell = shellEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnablePlugins", out var pluginsEl) &&
(pluginsEl.ValueKind == JsonValueKind.True || pluginsEl.ValueKind == JsonValueKind.False))
{
_enablePlugins = pluginsEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableDatShareHook", out var datEl) &&
(datEl.ValueKind == JsonValueKind.True || datEl.ValueKind == JsonValueKind.False))
{
_enableDatShareHook = datEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableAvaloniaOverlay", out var avEl) &&
(avEl.ValueKind == JsonValueKind.True || avEl.ValueKind == JsonValueKind.False))
{
_enableAvaloniaOverlay = avEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableD3D9Hook", out var d3dEl) &&
(d3dEl.ValueKind == JsonValueKind.True || d3dEl.ValueKind == JsonValueKind.False))
{
_enableD3D9Hook = d3dEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableEngine", out var engEl) &&
(engEl.ValueKind == JsonValueKind.True || engEl.ValueKind == JsonValueKind.False))
{
_enableEngine = engEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EngineHookCount", out var ehcEl) &&
ehcEl.ValueKind == JsonValueKind.Number &&
ehcEl.TryGetInt32(out int ehc))
{
_engineHookCount = ehc;
}
if (doc.RootElement.TryGetProperty("EnableImGuiBackend", out var ibEl) &&
(ibEl.ValueKind == JsonValueKind.True || ibEl.ValueKind == JsonValueKind.False))
{
_enableImGuiBackend = ibEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableHangMinidump", out var hmEl) &&
(hmEl.ValueKind == JsonValueKind.True || hmEl.ValueKind == JsonValueKind.False))
{
_enableHangMinidump = hmEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("DrawCustomVitalBars", out var cvbEl) &&
(cvbEl.ValueKind == JsonValueKind.True || cvbEl.ValueKind == JsonValueKind.False))
{
_drawCustomVitalBars = cvbEl.GetBoolean();
}
}
catch (Exception ex)
{
RynthLog.Plugin($"EngineSettings: Failed to load {SettingsPath}: {ex.Message}");
}
}
private static void Save()
{
try
{
string? dir = Path.GetDirectoryName(SettingsPath);
if (dir != null) Directory.CreateDirectory(dir);
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteStartArray("PluginPaths");
foreach (string p in _pluginPaths)
w.WriteStringValue(p);
w.WriteEndArray();
w.WriteBoolean("EnableImGuiShell", _enableImGuiShell);
w.WriteBoolean("EnablePlugins", _enablePlugins);
w.WriteBoolean("EnableDatShareHook", _enableDatShareHook);
w.WriteBoolean("EnableAvaloniaOverlay", _enableAvaloniaOverlay);
w.WriteBoolean("EnableD3D9Hook", _enableD3D9Hook);
w.WriteBoolean("EnableEngine", _enableEngine);
w.WriteNumber("EngineHookCount", _engineHookCount);
w.WriteBoolean("EnableImGuiBackend", _enableImGuiBackend);
w.WriteBoolean("EnableHangMinidump", _enableHangMinidump);
w.WriteBoolean("DrawCustomVitalBars", _drawCustomVitalBars);
w.WriteEndObject();
}
File.WriteAllBytes(SettingsPath, ms.ToArray());
}
catch (Exception ex)
{
RynthLog.Plugin($"EngineSettings: Failed to save: {ex.Message}");
}
}
}

View file

@ -0,0 +1,65 @@
// ============================================================================
// RynthCore.Engine - Plugins/LoadedPlugin.cs
// Represents a single plugin DLL that has been loaded and had its exports
// resolved. Holds the module handle and cached delegates.
// ============================================================================
using System;
namespace RynthCore.Engine.Plugins;
internal sealed class LoadedPlugin
{
public string SourceFilePath { get; init; } = "";
public string FilePath { get; init; } = "";
public string FileName { get; init; } = "";
public IntPtr ModuleHandle { get; init; }
// ─── Required exports ────────────────────────────────────────────
public PluginInitDelegate? Init { get; set; }
public PluginShutdownDelegate? Shutdown { get; set; }
// ─── Optional exports ────────────────────────────────────────────
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; }
public PluginOnSelectedTargetChangeDelegate? OnSelectedTargetChange { get; set; }
public PluginOnCombatModeChangeDelegate? OnCombatModeChange { get; set; }
public IntPtr OnSmartBoxEventPtr { get; set; }
public PluginOnSmartBoxEventDelegate? OnSmartBoxEvent { get; set; }
public PluginOnDeleteObjectDelegate? OnDeleteObject { get; set; }
public PluginOnCreateObjectDelegate? OnCreateObject { get; set; }
public IntPtr OnUpdateObjectPtr { get; set; }
public PluginOnUpdateObjectDelegate? OnUpdateObject { get; set; }
public PluginOnUpdateObjectInventoryDelegate? OnUpdateObjectInventory { get; set; }
public PluginOnViewObjectContentsDelegate? OnViewObjectContents { get; set; }
public PluginOnStopViewingObjectContentsDelegate? OnStopViewingObjectContents { get; set; }
public PluginOnVendorOpenDelegate? OnVendorOpen { get; set; }
public PluginOnVendorCloseDelegate? OnVendorClose { get; set; }
public IntPtr OnUpdateHealthPtr { get; set; }
public PluginOnUpdateHealthDelegate? OnUpdateHealth { get; set; }
public IntPtr OnCombatDamagePtr { get; set; }
public PluginOnCombatDamageDelegate? OnCombatDamage { get; set; }
public IntPtr OnKillNotificationPtr { get; set; }
public PluginOnKillNotificationDelegate? OnKillNotification { get; set; }
public IntPtr OnChatWindowTextPtr { get; set; }
public PluginOnChatWindowTextDelegate? OnChatWindowText { get; set; }
public PluginOnChatBarEnterDelegate? OnChatBarEnter { get; set; }
public PluginBarActionDelegate? OnBarAction { get; set; }
public PluginOnEnchantmentAddedDelegate? OnEnchantmentAdded { get; set; }
public PluginOnEnchantmentRemovedDelegate? OnEnchantmentRemoved { get; set; }
public PluginTickDelegate? Tick { get; set; }
public PluginRenderDelegate? Render { get; set; }
// ─── Runtime state ───────────────────────────────────────────────
public bool Initialized { get; set; }
public bool LoginCompleteDispatched { get; set; }
public bool UIInitializedDispatched { get; set; }
public bool Failed { get; set; }
public string DisplayName { get; set; } = "";
public string VersionString { get; set; } = "";
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,601 @@
// ============================================================================
// RynthCore.Engine - Plugins/PluginLoader.cs
// Scans the Plugins directory, loads each DLL, and resolves exports.
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Plugins;
internal static class PluginLoader
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr LoadLibraryW(string lpLibFileName);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
/// <summary>
/// Scans <paramref name="pluginsDir"/> for *.dll files, loads each one,
/// and resolves the plugin contract exports.
/// Returns only plugins that have the two required exports (Init + Shutdown).
/// </summary>
public static List<LoadedPlugin> LoadAll(string pluginsDir, string shadowRootDir, int generation)
{
var plugins = new List<LoadedPlugin>();
if (!Directory.Exists(pluginsDir))
{
RynthLog.Verbose($"PluginLoader: Creating plugins directory: {pluginsDir}");
try { Directory.CreateDirectory(pluginsDir); }
catch (Exception ex)
{
RynthLog.Plugin($"PluginLoader: Failed to create directory: {ex.Message}");
return plugins;
}
return plugins;
}
string sessionShadowDir = PrepareShadowDirectory(shadowRootDir, generation);
string[] dllFiles;
try { dllFiles = Directory.GetFiles(pluginsDir, "*.dll"); }
catch (Exception ex)
{
RynthLog.Plugin($"PluginLoader: Failed to enumerate {pluginsDir}: {ex.Message}");
return plugins;
}
Array.Sort(dllFiles, StringComparer.OrdinalIgnoreCase);
if (dllFiles.Length == 0)
{
RynthLog.Verbose("PluginLoader: No plugin DLLs found.");
return plugins;
}
RynthLog.Verbose($"PluginLoader: Found {dllFiles.Length} DLL(s) in {pluginsDir}");
foreach (string dllPath in dllFiles)
{
var plugin = TryLoad(dllPath, sessionShadowDir);
if (plugin != null)
plugins.Add(plugin);
}
RynthLog.Verbose($"PluginLoader: {plugins.Count} plugin(s) loaded successfully.");
return plugins;
}
/// <summary>
/// Unloads a plugin. <b>Does NOT call FreeLibrary</b> — NativeAOT plugin DLLs
/// share the .NET runtime with the host engine, and their <c>DLL_PROCESS_DETACH</c>
/// path tears down NativeAOT runtime state in ways that race with our other
/// threads (TickPump, Avalonia STA, hooks) and produce a deterministic
/// <c>ntdll!RtlpHeap</c> AV at addr ending in <c>0xFFC</c> on hot-reload + manual
/// exit. The module handle is intentionally leaked; on next reload, a new
/// shadow copy at a different path is loaded so the new plugin code runs
/// cleanly. The OS reclaims the leaked module pages when the process exits.
/// </summary>
public static void Unload(LoadedPlugin plugin)
{
if (plugin.ModuleHandle != IntPtr.Zero)
{
RynthLog.Verbose($"PluginLoader: Skipping FreeLibrary on {plugin.FileName} (NativeAOT — module pages leaked intentionally).");
}
// Don't try to delete the .dll/.pdb either — they're still mapped.
// Old shadow copies get cleaned up on next launch via CleanupShadowCopies.
TryDeleteEmptyDirectory(Path.GetDirectoryName(plugin.FilePath));
}
public static void CleanupShadowCopies(string shadowRootDir)
{
if (!Directory.Exists(shadowRootDir))
return;
try
{
foreach (string dir in Directory.GetDirectories(shadowRootDir))
TryDeleteDirectory(dir);
}
catch (Exception ex)
{
RynthLog.Verbose($"PluginLoader: Shadow cleanup skipped ({ex.Message})");
}
}
/// <summary>
/// One-shot startup sweep over sibling per-PID shadow roots
/// (<c>&lt;baseShadowRootDir&gt;/p&lt;PID&gt;/</c>). Deletes dirs whose
/// owning PID is dead — i.e. orphans from previous client runs that
/// crashed or were killed before tearing down their shadow tree.
///
/// Mutex-serialized across processes: two clients launching concurrently
/// must not race on the same dead-PID dirs, because Directory.Delete
/// failures (already-deleted-by-other-client → DirectoryNotFoundException)
/// generate exception heap pressure, which is exactly the failure mode
/// the per-PID shadow-root design is meant to eliminate.
/// </summary>
public static void CleanupOrphanShadowRoots(string baseShadowRootDir, int currentPid)
{
RynthLog.Plugin($"PluginLoader: orphan sweep starting (root={baseShadowRootDir}, currentPid={currentPid}).");
if (!Directory.Exists(baseShadowRootDir))
{
RynthLog.Plugin("PluginLoader: orphan sweep — base dir does not exist, nothing to do.");
return;
}
RynthLog.Plugin("PluginLoader: orphan sweep DIAG-1 — base dir exists, creating mutex.");
System.Threading.Mutex? mutex = null;
bool acquired = false;
int deleted = 0;
int skippedAlive = 0;
try
{
try
{
mutex = new System.Threading.Mutex(false, "Local\\RynthCore.PluginShadow.OrphanSweep");
}
catch (Exception ex)
{
RynthLog.Plugin($"PluginLoader: orphan sweep — mutex create threw {ex.GetType().Name}: {ex.Message}. Proceeding without serialization.");
}
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-2 — mutex created (null={mutex == null}).");
if (mutex != null)
{
RynthLog.Plugin("PluginLoader: orphan sweep DIAG-3 — calling mutex.WaitOne(5s).");
try { acquired = mutex.WaitOne(TimeSpan.FromSeconds(5)); }
catch (System.Threading.AbandonedMutexException) { acquired = true; }
catch (Exception ex)
{
RynthLog.Plugin($"PluginLoader: orphan sweep — mutex wait threw {ex.GetType().Name}: {ex.Message}. Proceeding without serialization.");
}
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-4 — mutex.WaitOne returned, acquired={acquired}.");
if (!acquired)
RynthLog.Plugin("PluginLoader: orphan sweep — mutex not acquired within 5s; proceeding without serialization.");
}
RynthLog.Plugin("PluginLoader: orphan sweep DIAG-5 — calling Directory.GetDirectories.");
string[] dirs = Directory.GetDirectories(baseShadowRootDir);
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-6 — got {dirs.Length} dirs.");
for (int i = 0; i < dirs.Length; i++)
{
string dir = dirs[i];
string name = Path.GetFileName(dir);
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-7.{i} — examining '{name}'.");
if (name.Length < 2 || name[0] != 'p') continue;
if (!int.TryParse(name.AsSpan(1), out int ownerPid)) continue;
if (ownerPid == currentPid)
{
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-7.{i} — skipping {name} (own PID).");
continue;
}
// Liveness check via Win32 OpenProcess — bypasses
// System.Diagnostics.Process which was crashing this thread
// (and by extension the process) under NativeAOT in a
// heavily-hooked acclient.exe. We need this gate because
// Directory.Delete over a still-mapped DLL — which is what
// a LIVE owner's shadow dir contains — also crashes silently
// here, bypassing the managed try/catch in
// TryDeleteDirectoryReporting. So delete is unsafe without
// knowing the owner is dead.
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-7.{i} — checking IsPidAliveWin32({ownerPid}).");
bool alive = IsPidAliveWin32(ownerPid);
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-7.{i} — IsPidAliveWin32({ownerPid})={alive}.");
if (alive)
{
skippedAlive++;
RynthLog.Plugin($"PluginLoader: orphan sweep skipping {name} — PID {ownerPid} still running.");
continue;
}
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-7.{i} — calling TryDeleteDirectoryReporting('{name}').");
bool ok = TryDeleteDirectoryReporting(dir);
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-7.{i} — delete returned ok={ok}.");
if (ok) deleted++;
}
RynthLog.Plugin($"PluginLoader: orphan sweep complete (deleted={deleted}, skippedAlive={skippedAlive}).");
}
catch (Exception ex)
{
RynthLog.Plugin($"PluginLoader: orphan sweep threw {ex.GetType().Name}: {ex.Message}");
}
finally
{
RynthLog.Plugin($"PluginLoader: orphan sweep DIAG-FIN — releasing mutex (acquired={acquired}).");
if (acquired && mutex != null)
{
try { mutex.ReleaseMutex(); } catch { }
}
mutex?.Dispose();
RynthLog.Plugin("PluginLoader: orphan sweep DIAG-FIN — done.");
}
}
private static bool TryDeleteDirectoryReporting(string path)
{
try
{
Directory.Delete(path, true);
return true;
}
catch (Exception ex)
{
RynthLog.Plugin($"PluginLoader: orphan sweep delete failed for {Path.GetFileName(path)} — {ex.GetType().Name}: {ex.Message}");
return false;
}
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenProcess(uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
private const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
private const uint STILL_ACTIVE = 259;
/// <summary>
/// Win32-native liveness check. Replaces the original
/// System.Diagnostics.Process.GetProcessById path which AVs the host
/// process under NativeAOT in injected acclient.exe — see the comment in
/// CleanupOrphanShadowRoots. Trade-off vs. the original: no ProcessName
/// verification, so a recycled PID held by an unrelated process keeps the
/// orphan dir alive. The cost is a stale shadow tree, not a crash.
/// </summary>
private static bool IsPidAliveWin32(int pid)
{
if (pid <= 0) return false;
IntPtr h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
if (h == IntPtr.Zero) return false;
try
{
if (!GetExitCodeProcess(h, out uint exitCode)) return false;
return exitCode == STILL_ACTIVE;
}
finally
{
CloseHandle(h);
}
}
[Obsolete("Use IsPidAliveWin32 — Process.GetProcessById crashes under NativeAOT in injected x86 acclient.exe.")]
private static bool IsProcessAlive(int pid)
{
try
{
using var p = System.Diagnostics.Process.GetProcessById(pid);
if (p.HasExited) return false;
return string.Equals(p.ProcessName, "acclient", StringComparison.OrdinalIgnoreCase);
}
catch
{
return false;
}
}
public static LoadedPlugin? LoadSingle(string sourcePath, string shadowRootDir, int generation)
{
string sessionShadowDir = PrepareShadowDirectory(shadowRootDir, generation);
return TryLoad(sourcePath, sessionShadowDir);
}
private static LoadedPlugin? TryLoad(string sourcePath, string sessionShadowDir)
{
string fileName = Path.GetFileName(sourcePath);
RynthLog.Verbose($"PluginLoader: Loading {fileName}...");
string shadowPath;
try
{
shadowPath = CreateShadowCopy(sourcePath, sessionShadowDir);
}
catch (Exception ex)
{
RynthLog.Plugin($"PluginLoader: FAILED to stage {fileName} ({ex.Message})");
return null;
}
IntPtr handle = LoadLibraryW(shadowPath);
if (handle == IntPtr.Zero)
{
int err = Marshal.GetLastWin32Error();
RynthLog.Plugin($"PluginLoader: FAILED to load {fileName} (Win32 error {err})");
return null;
}
// Resolve required exports
IntPtr initPtr = GetProcAddress(handle, "RynthPluginInit");
IntPtr shutdownPtr = GetProcAddress(handle, "RynthPluginShutdown");
if (initPtr == IntPtr.Zero || shutdownPtr == IntPtr.Zero)
{
RynthLog.Plugin($"PluginLoader: {fileName} missing required exports (RynthPluginInit/RynthPluginShutdown) — skipping.");
FreeLibrary(handle);
return null;
}
var plugin = new LoadedPlugin
{
SourceFilePath = sourcePath,
FilePath = shadowPath,
FileName = fileName,
ModuleHandle = handle,
Init = Marshal.GetDelegateForFunctionPointer<PluginInitDelegate>(initPtr),
Shutdown = Marshal.GetDelegateForFunctionPointer<PluginShutdownDelegate>(shutdownPtr),
DisplayName = fileName
};
// Resolve optional exports
IntPtr namePtr = GetProcAddress(handle, "RynthPluginName");
if (namePtr != IntPtr.Zero)
plugin.GetName = Marshal.GetDelegateForFunctionPointer<PluginNameDelegate>(namePtr);
IntPtr versionPtr = GetProcAddress(handle, "RynthPluginVersion");
if (versionPtr != IntPtr.Zero)
plugin.GetVersion = Marshal.GetDelegateForFunctionPointer<PluginVersionDelegate>(versionPtr);
IntPtr onLoginCompletePtr = GetProcAddress(handle, "RynthPluginOnLoginComplete");
if (onLoginCompletePtr != IntPtr.Zero)
plugin.OnLoginComplete = Marshal.GetDelegateForFunctionPointer<PluginOnLoginCompleteDelegate>(onLoginCompletePtr);
IntPtr onLogoutPtr = GetProcAddress(handle, "RynthPluginOnLogout");
if (onLogoutPtr != IntPtr.Zero)
plugin.OnLogout = Marshal.GetDelegateForFunctionPointer<PluginOnLogoutDelegate>(onLogoutPtr);
IntPtr onUiInitializedPtr = GetProcAddress(handle, "RynthPluginOnUIInitialized");
if (onUiInitializedPtr != IntPtr.Zero)
plugin.OnUIInitialized = Marshal.GetDelegateForFunctionPointer<PluginOnUIInitializedDelegate>(onUiInitializedPtr);
IntPtr onBusyCountIncrementedPtr = GetProcAddress(handle, "RynthPluginOnBusyCountIncremented");
if (onBusyCountIncrementedPtr != IntPtr.Zero)
plugin.OnBusyCountIncremented = Marshal.GetDelegateForFunctionPointer<PluginOnBusyCountIncrementedDelegate>(onBusyCountIncrementedPtr);
IntPtr onBusyCountDecrementedPtr = GetProcAddress(handle, "RynthPluginOnBusyCountDecremented");
if (onBusyCountDecrementedPtr != IntPtr.Zero)
plugin.OnBusyCountDecremented = Marshal.GetDelegateForFunctionPointer<PluginOnBusyCountDecrementedDelegate>(onBusyCountDecrementedPtr);
IntPtr onSelectedTargetChangePtr = GetProcAddress(handle, "RynthPluginOnSelectedTargetChange");
if (onSelectedTargetChangePtr != IntPtr.Zero)
plugin.OnSelectedTargetChange = Marshal.GetDelegateForFunctionPointer<PluginOnSelectedTargetChangeDelegate>(onSelectedTargetChangePtr);
IntPtr onCombatModeChangePtr = GetProcAddress(handle, "RynthPluginOnCombatModeChange");
if (onCombatModeChangePtr != IntPtr.Zero)
plugin.OnCombatModeChange = Marshal.GetDelegateForFunctionPointer<PluginOnCombatModeChangeDelegate>(onCombatModeChangePtr);
IntPtr onSmartBoxEventPtr = GetProcAddress(handle, "RynthPluginOnSmartBoxEvent");
if (onSmartBoxEventPtr != IntPtr.Zero)
{
plugin.OnSmartBoxEventPtr = onSmartBoxEventPtr;
plugin.OnSmartBoxEvent = Marshal.GetDelegateForFunctionPointer<PluginOnSmartBoxEventDelegate>(onSmartBoxEventPtr);
}
IntPtr onDeleteObjectPtr = GetProcAddress(handle, "RynthPluginOnDeleteObject");
if (onDeleteObjectPtr != IntPtr.Zero)
plugin.OnDeleteObject = Marshal.GetDelegateForFunctionPointer<PluginOnDeleteObjectDelegate>(onDeleteObjectPtr);
IntPtr onCreateObjectPtr = GetProcAddress(handle, "RynthPluginOnCreateObject");
if (onCreateObjectPtr != IntPtr.Zero)
plugin.OnCreateObject = Marshal.GetDelegateForFunctionPointer<PluginOnCreateObjectDelegate>(onCreateObjectPtr);
IntPtr onUpdateObjectPtr = GetProcAddress(handle, "RynthPluginOnUpdateObject");
if (onUpdateObjectPtr != IntPtr.Zero)
{
plugin.OnUpdateObjectPtr = onUpdateObjectPtr;
plugin.OnUpdateObject = Marshal.GetDelegateForFunctionPointer<PluginOnUpdateObjectDelegate>(onUpdateObjectPtr);
}
IntPtr onUpdateObjectInventoryPtr = GetProcAddress(handle, "RynthPluginOnUpdateObjectInventory");
if (onUpdateObjectInventoryPtr != IntPtr.Zero)
plugin.OnUpdateObjectInventory = Marshal.GetDelegateForFunctionPointer<PluginOnUpdateObjectInventoryDelegate>(onUpdateObjectInventoryPtr);
IntPtr onViewObjectContentsPtr = GetProcAddress(handle, "RynthPluginOnViewObjectContents");
if (onViewObjectContentsPtr != IntPtr.Zero)
plugin.OnViewObjectContents = Marshal.GetDelegateForFunctionPointer<PluginOnViewObjectContentsDelegate>(onViewObjectContentsPtr);
IntPtr onStopViewingObjectContentsPtr = GetProcAddress(handle, "RynthPluginOnStopViewingObjectContents");
if (onStopViewingObjectContentsPtr != IntPtr.Zero)
plugin.OnStopViewingObjectContents = Marshal.GetDelegateForFunctionPointer<PluginOnStopViewingObjectContentsDelegate>(onStopViewingObjectContentsPtr);
IntPtr onVendorOpenPtr = GetProcAddress(handle, "RynthPluginOnVendorOpen");
if (onVendorOpenPtr != IntPtr.Zero)
plugin.OnVendorOpen = Marshal.GetDelegateForFunctionPointer<PluginOnVendorOpenDelegate>(onVendorOpenPtr);
IntPtr onVendorClosePtr = GetProcAddress(handle, "RynthPluginOnVendorClose");
if (onVendorClosePtr != IntPtr.Zero)
plugin.OnVendorClose = Marshal.GetDelegateForFunctionPointer<PluginOnVendorCloseDelegate>(onVendorClosePtr);
IntPtr onUpdateHealthPtr = GetProcAddress(handle, "RynthPluginOnUpdateHealth");
if (onUpdateHealthPtr != IntPtr.Zero)
{
plugin.OnUpdateHealthPtr = onUpdateHealthPtr;
plugin.OnUpdateHealth = Marshal.GetDelegateForFunctionPointer<PluginOnUpdateHealthDelegate>(onUpdateHealthPtr);
}
IntPtr onCombatDamagePtr = GetProcAddress(handle, "RynthPluginOnCombatDamage");
if (onCombatDamagePtr != IntPtr.Zero)
{
plugin.OnCombatDamagePtr = onCombatDamagePtr;
plugin.OnCombatDamage = Marshal.GetDelegateForFunctionPointer<PluginOnCombatDamageDelegate>(onCombatDamagePtr);
}
IntPtr onKillNotificationPtr = GetProcAddress(handle, "RynthPluginOnKillNotification");
if (onKillNotificationPtr != IntPtr.Zero)
{
plugin.OnKillNotificationPtr = onKillNotificationPtr;
plugin.OnKillNotification = Marshal.GetDelegateForFunctionPointer<PluginOnKillNotificationDelegate>(onKillNotificationPtr);
}
IntPtr onChatWindowTextPtr = GetProcAddress(handle, "RynthPluginOnChatWindowText");
if (onChatWindowTextPtr != IntPtr.Zero)
{
plugin.OnChatWindowTextPtr = onChatWindowTextPtr;
plugin.OnChatWindowText = Marshal.GetDelegateForFunctionPointer<PluginOnChatWindowTextDelegate>(onChatWindowTextPtr);
}
IntPtr onChatBarEnterPtr = GetProcAddress(handle, "RynthPluginOnChatBarEnter");
if (onChatBarEnterPtr != IntPtr.Zero)
plugin.OnChatBarEnter = Marshal.GetDelegateForFunctionPointer<PluginOnChatBarEnterDelegate>(onChatBarEnterPtr);
IntPtr onBarActionPtr = GetProcAddress(handle, "RynthPluginOnBarAction");
if (onBarActionPtr != IntPtr.Zero)
plugin.OnBarAction = Marshal.GetDelegateForFunctionPointer<PluginBarActionDelegate>(onBarActionPtr);
IntPtr onEnchantmentAddedPtr = GetProcAddress(handle, "RynthPluginOnEnchantmentAdded");
if (onEnchantmentAddedPtr != IntPtr.Zero)
plugin.OnEnchantmentAdded = Marshal.GetDelegateForFunctionPointer<PluginOnEnchantmentAddedDelegate>(onEnchantmentAddedPtr);
IntPtr onEnchantmentRemovedPtr = GetProcAddress(handle, "RynthPluginOnEnchantmentRemoved");
if (onEnchantmentRemovedPtr != IntPtr.Zero)
plugin.OnEnchantmentRemoved = Marshal.GetDelegateForFunctionPointer<PluginOnEnchantmentRemovedDelegate>(onEnchantmentRemovedPtr);
IntPtr tickPtr = GetProcAddress(handle, "RynthPluginTick");
if (tickPtr != IntPtr.Zero)
plugin.Tick = Marshal.GetDelegateForFunctionPointer<PluginTickDelegate>(tickPtr);
IntPtr renderPtr = GetProcAddress(handle, "RynthPluginRender");
if (renderPtr != IntPtr.Zero)
plugin.Render = Marshal.GetDelegateForFunctionPointer<PluginRenderDelegate>(renderPtr);
// Read name/version from the plugin if available
if (plugin.GetName != null)
{
IntPtr strPtr = plugin.GetName();
if (strPtr != IntPtr.Zero)
plugin.DisplayName = Marshal.PtrToStringAnsi(strPtr) ?? fileName;
}
if (plugin.GetVersion != null)
{
IntPtr strPtr = plugin.GetVersion();
if (strPtr != IntPtr.Zero)
plugin.VersionString = Marshal.PtrToStringAnsi(strPtr) ?? "";
}
string ver = string.IsNullOrEmpty(plugin.VersionString) ? "" : $" v{plugin.VersionString}";
string caps = BuildCapsList(plugin);
RynthLog.Verbose($"PluginLoader: {plugin.DisplayName}{ver} loaded ({caps})");
return plugin;
}
private static string PrepareShadowDirectory(string shadowRootDir, int generation)
{
// Include EntryPoint.InitCount so each engine instance gets its own
// shadow root. After an engine hot-reload the previous engine's
// plugin DLL stays pinned (FreeLibrary doesn't actually unmap), so
// overwriting its shadow path would fail with a sharing violation.
int engineInit = EntryPoint.InitCount;
string sessionDir = Path.Combine(
shadowRootDir,
$"session-{generation:D4}-pid{Environment.ProcessId}-eng{engineInit:D2}");
Directory.CreateDirectory(sessionDir);
return sessionDir;
}
private static string CreateShadowCopy(string sourcePath, string sessionShadowDir)
{
string fileName = Path.GetFileName(sourcePath);
string shadowPath = Path.Combine(sessionShadowDir, fileName);
File.Copy(sourcePath, shadowPath, true);
string sourcePdb = Path.ChangeExtension(sourcePath, ".pdb");
string shadowPdb = Path.ChangeExtension(shadowPath, ".pdb");
if (File.Exists(sourcePdb))
File.Copy(sourcePdb, shadowPdb, true);
return shadowPath;
}
private static void TryDeleteFile(string? path)
{
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
return;
try
{
File.Delete(path);
}
catch
{
}
}
private static void TryDeleteEmptyDirectory(string? path)
{
if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path))
return;
try
{
if (Directory.GetFileSystemEntries(path).Length == 0)
Directory.Delete(path);
}
catch
{
}
}
private static void TryDeleteDirectory(string path)
{
try
{
Directory.Delete(path, true);
}
catch
{
}
}
private static string BuildCapsList(LoadedPlugin p)
{
var parts = new List<string>(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-");
if (p.OnSelectedTargetChange != null) parts.Add("target");
if (p.OnCombatModeChange != null) parts.Add("combat-mode");
if (p.OnSmartBoxEvent != null) parts.Add("smartbox");
if (p.OnCreateObject != null) parts.Add("create");
if (p.OnDeleteObject != null) parts.Add("delete");
if (p.OnUpdateObject != null) parts.Add("update-object");
if (p.OnUpdateObjectInventory != null) parts.Add("inventory");
if (p.OnViewObjectContents != null) parts.Add("contents-open");
if (p.OnStopViewingObjectContents != null) parts.Add("contents-close");
if (p.OnVendorOpen != null) parts.Add("vendor-open");
if (p.OnVendorClose != null) parts.Add("vendor-close");
if (p.OnUpdateHealth != null || p.OnUpdateHealthPtr != IntPtr.Zero) parts.Add("health");
if (p.OnCombatDamage != null || p.OnCombatDamagePtr != IntPtr.Zero) parts.Add("combatdmg");
if (p.OnKillNotification != null || p.OnKillNotificationPtr != IntPtr.Zero) parts.Add("kill");
if (p.OnChatWindowText != null) parts.Add("chat-in");
if (p.OnChatBarEnter != null) parts.Add("chat-out");
if (p.OnBarAction != null) parts.Add("bar");
if (p.Tick != null) parts.Add("tick");
if (p.Render != null) parts.Add("render");
return string.Join(", ", parts);
}
}

File diff suppressed because it is too large Load diff