diff --git a/BepInEx.IL2CPP/Hook/INativeDetour.cs b/BepInEx.IL2CPP/Hook/INativeDetour.cs index fc3e636..4e12fe1 100644 --- a/BepInEx.IL2CPP/Hook/INativeDetour.cs +++ b/BepInEx.IL2CPP/Hook/INativeDetour.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Reflection; using System.Runtime.InteropServices; using BepInEx.Configuration; using BepInEx.IL2CPP.Hook.Dobby; @@ -38,9 +40,57 @@ public interface INativeDetour : IDetour var detour = Create(from, toPtr); original = detour.GenerateTrampoline(); detour.Apply(); + + // TODO check if this is still needed and remove if not + // if (!ReflectionHelper.IsMono) + // { + // return new CacheDetourWrapper(detour, original, to); + // } + return detour; } + // Workaround for CoreCLR collecting all delegates + private class CacheDetourWrapper : INativeDetour where T : Delegate + { + private readonly INativeDetour _wrapped; + + private List _cache = new(); + + public CacheDetourWrapper(INativeDetour wrapped, T original, T to) + { + _wrapped = wrapped; + _cache.Add(original); + _cache.Add(to); + } + + public void Dispose() + { + _wrapped.Dispose(); + _cache.Clear(); + } + + public void Apply() => _wrapped.Apply(); + + public void Undo() => _wrapped.Undo(); + + public void Free() => _wrapped.Free(); + + public MethodBase GenerateTrampoline(MethodBase signature = null) => _wrapped.GenerateTrampoline(signature); + + public T GenerateTrampoline() where T : Delegate => _wrapped.GenerateTrampoline(); + + public bool IsValid => _wrapped.IsValid; + + public bool IsApplied => _wrapped.IsApplied; + + public nint OriginalMethodPtr => _wrapped.OriginalMethodPtr; + + public nint DetourMethodPtr => _wrapped.DetourMethodPtr; + + public nint TrampolinePtr => _wrapped.TrampolinePtr; + } + internal enum DetourProvider { Default, diff --git a/BepInEx.IL2CPP/IL2CPPChainloader.cs b/BepInEx.IL2CPP/IL2CPPChainloader.cs index 01358ee..2af317e 100644 --- a/BepInEx.IL2CPP/IL2CPPChainloader.cs +++ b/BepInEx.IL2CPP/IL2CPPChainloader.cs @@ -33,7 +33,6 @@ public class IL2CPPChainloader : BaseChainloader false, "Include unity log messages in log file output."); - private static List DetourCache = new(); private static INativeDetour RuntimeInvokeDetour { get; set; } @@ -75,8 +74,6 @@ public class IL2CPPChainloader : BaseChainloader RuntimeInvokeDetour = INativeDetour.CreateAndApply(runtimeInvokePtr, invokeMethodDetour, out originalInvoke); - DetourCache.Add(invokeMethodDetour); - DetourCache.Add(originalInvoke); PreloaderLogger.Log.Log(LogLevel.Debug, "Runtime invoke patched"); } @@ -113,8 +110,6 @@ public class IL2CPPChainloader : BaseChainloader { RuntimeInvokeDetour.Dispose(); - DetourCache.Clear(); - PreloaderLogger.Log.Log(LogLevel.Debug, "Runtime invoke unpatched"); }