IL2CPPChainloader.cs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. using System;
  2. using System.Diagnostics;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Runtime.InteropServices;
  6. using BepInEx.Bootstrap;
  7. using BepInEx.Logging;
  8. using BepInEx.Preloader.Core;
  9. using BepInEx.Preloader.Core.Logging;
  10. using MonoMod.RuntimeDetour;
  11. using UnhollowerBaseLib.Runtime;
  12. using UnhollowerRuntimeLib;
  13. using UnityEngine;
  14. using Logger = BepInEx.Logging.Logger;
  15. namespace BepInEx.IL2CPP
  16. {
  17. public class IL2CPPChainloader : BaseChainloader<BasePlugin>
  18. {
  19. private static ManualLogSource UnityLogSource = new ManualLogSource("Unity");
  20. public static void UnityLogCallback(string logLine, string exception, LogType type)
  21. {
  22. UnityLogSource.LogInfo(logLine.Trim());
  23. }
  24. // public const CallingConvention ArchConvention =
  25. //#if X64
  26. // CallingConvention.Stdcall;
  27. //#else
  28. // CallingConvention.Cdecl;
  29. //#endif
  30. [UnmanagedFunctionPointer(CallingConvention.StdCall)]
  31. private delegate IntPtr RuntimeInvokeDetour(IntPtr method, IntPtr obj, IntPtr parameters, IntPtr exc);
  32. [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
  33. private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
  34. private static RuntimeInvokeDetour originalInvoke;
  35. private static ManualLogSource unhollowerLogSource = Logger.CreateLogSource("Unhollower");
  36. private class DetourHandler : UnhollowerRuntimeLib.ManagedDetour
  37. {
  38. public T Detour<T>(IntPtr from, T to) where T : Delegate
  39. {
  40. var detour = new NativeDetour(from, to, new NativeDetourConfig { ManualApply = true });
  41. var trampoline = detour.GenerateTrampoline<T>();
  42. detour.Apply();
  43. return trampoline;
  44. }
  45. }
  46. public override unsafe void Initialize(string gameExePath = null)
  47. {
  48. base.Initialize(gameExePath);
  49. UnityVersionHandler.Initialize(2019, 2, 17);
  50. // One or the other here for Unhollower to work correctly
  51. //ClassInjector.Detour = new DetourHandler();
  52. ClassInjector.DoHook = (ptr, patchedFunctionPtr) =>
  53. {
  54. IntPtr originalFunc = new IntPtr(*(void**)ptr);
  55. var trampolinePtr = TrampolineGenerator.Generate(unhollowerLogSource, originalFunc, patchedFunctionPtr);
  56. *(void**)ptr = (void*)trampolinePtr;
  57. };
  58. var gameAssemblyModule = Process.GetCurrentProcess().Modules.Cast<ProcessModule>().First(x => x.ModuleName.Contains("GameAssembly"));
  59. var functionPtr = GetProcAddress(gameAssemblyModule.BaseAddress, "il2cpp_runtime_invoke"); //DynDll.GetFunction(gameAssemblyModule.BaseAddress, "il2cpp_runtime_invoke");
  60. PreloaderLogger.Log.LogDebug($"Runtime invoke pointer: 0x{functionPtr.ToInt64():X}");
  61. var invokeDetour = new NativeDetour(functionPtr, Marshal.GetFunctionPointerForDelegate(new RuntimeInvokeDetour(OnInvokeMethod)), new NativeDetourConfig { ManualApply = true });
  62. originalInvoke = invokeDetour.GenerateTrampoline<RuntimeInvokeDetour>();
  63. invokeDetour.Apply();
  64. }
  65. private static bool HasSet = false;
  66. private static IntPtr OnInvokeMethod(IntPtr method, IntPtr obj, IntPtr parameters, IntPtr exc)
  67. {
  68. string methodName = Marshal.PtrToStringAnsi(UnhollowerBaseLib.IL2CPP.il2cpp_method_get_name(method));
  69. if (!HasSet && methodName == "Internal_ActiveSceneChanged")
  70. {
  71. try
  72. {
  73. UnityEngine.Application.s_LogCallbackHandler = new Action<string, string, LogType>(UnityLogCallback);
  74. UnityLogSource.LogMessage($"callback set - {methodName}");
  75. UnityEngine.Application.CallLogCallback("test from OnInvokeMethod", "", LogType.Log, true);
  76. }
  77. catch (Exception ex)
  78. {
  79. UnityLogSource.LogError(ex);
  80. }
  81. HasSet = true;
  82. }
  83. //UnityLogSource.LogDebug(methodName);
  84. return originalInvoke(method, obj, parameters, exc);
  85. }
  86. protected override void InitializeLoggers()
  87. {
  88. //Logger.Listeners.Add(new UnityLogListener());
  89. //if (ConfigUnityLogging.Value)
  90. // Logger.Sources.Add(new UnityLogSource());
  91. Logger.Sources.Add(UnityLogSource);
  92. UnhollowerBaseLib.LogSupport.InfoHandler += unhollowerLogSource.LogInfo;
  93. UnhollowerBaseLib.LogSupport.WarningHandler += unhollowerLogSource.LogWarning;
  94. UnhollowerBaseLib.LogSupport.TraceHandler += unhollowerLogSource.LogDebug;
  95. UnhollowerBaseLib.LogSupport.ErrorHandler += unhollowerLogSource.LogError;
  96. base.InitializeLoggers();
  97. //if (!ConfigDiskWriteUnityLog.Value)
  98. //{
  99. // DiskLogListener.BlacklistedSources.Add("Unity Log");
  100. //}
  101. foreach (var preloaderLogEvent in PreloaderConsoleListener.LogEvents)
  102. {
  103. PreloaderLogger.Log.Log(preloaderLogEvent.Level, preloaderLogEvent.Data);
  104. }
  105. //UnityEngine.Application.s_LogCallbackHandler = DelegateSupport.ConvertDelegate<Application.LogCallback>(new Action<string>(UnityLogCallback));
  106. //UnityEngine.Application.s_LogCallbackHandler = (Application.LogCallback)new Action<string>(UnityLogCallback);
  107. //var loggerPointer = Marshal.GetFunctionPointerForDelegate(new UnityLogCallbackDelegate(UnityLogCallback));
  108. //UnhollowerBaseLib.IL2CPP.il2cpp_register_log_callback(loggerPointer);
  109. }
  110. public override BasePlugin LoadPlugin(PluginInfo pluginInfo, Assembly pluginAssembly)
  111. {
  112. var type = pluginAssembly.GetType(pluginInfo.TypeName);
  113. var pluginInstance = (BasePlugin)Activator.CreateInstance(type);
  114. pluginInstance.Load();
  115. return pluginInstance;
  116. }
  117. }
  118. }