IL2CPPChainloader.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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.IL2CPP.Hook;
  8. using BepInEx.Logging;
  9. using BepInEx.Preloader.Core;
  10. using BepInEx.Preloader.Core.Logging;
  11. using HarmonyLib.Public.Patching;
  12. using UnhollowerBaseLib.Runtime;
  13. using UnhollowerRuntimeLib;
  14. using UnityEngine;
  15. using Logger = BepInEx.Logging.Logger;
  16. using BaseUnityEngine = UnityEngine;
  17. namespace BepInEx.IL2CPP
  18. {
  19. public class IL2CPPChainloader : BaseChainloader<BasePlugin>
  20. {
  21. private static ManualLogSource UnityLogSource = new ManualLogSource("Unity");
  22. public static void UnityLogCallback(string logLine, string exception, LogType type)
  23. {
  24. UnityLogSource.LogInfo(logLine.Trim());
  25. }
  26. [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  27. private delegate IntPtr RuntimeInvokeDetourDelegate(IntPtr method, IntPtr obj, IntPtr parameters, IntPtr exc);
  28. [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
  29. private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
  30. private static RuntimeInvokeDetourDelegate originalInvoke;
  31. private static readonly ManualLogSource unhollowerLogSource = Logger.CreateLogSource("Unhollower");
  32. private static FastNativeDetour RuntimeInvokeDetour { get; set; }
  33. private static IL2CPPChainloader Instance { get; set; }
  34. public override unsafe void Initialize(string gameExePath = null)
  35. {
  36. PatchManager.ResolvePatcher += IL2CPPDetourMethodPatcher.TryResolve;
  37. base.Initialize(gameExePath);
  38. Instance = this;
  39. var version = //Version.Parse(Application.unityVersion);
  40. Version.Parse(Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion);
  41. UnityVersionHandler.Initialize(version.Major, version.Minor, version.Revision);
  42. // One or the other here for Unhollower to work correctly
  43. //ClassInjector.Detour = new DetourHandler();
  44. ClassInjector.DoHook = (ptr, patchedFunctionPtr) =>
  45. {
  46. IntPtr originalFunc = new IntPtr(*(void**)ptr);
  47. var detour = new FastNativeDetour(originalFunc, patchedFunctionPtr);
  48. detour.Apply();
  49. *(void**)ptr = (void*)detour.TrampolinePtr;
  50. };
  51. var gameAssemblyModule = Process.GetCurrentProcess().Modules.Cast<ProcessModule>().First(x => x.ModuleName.Contains("GameAssembly"));
  52. var functionPtr = GetProcAddress(gameAssemblyModule.BaseAddress, "il2cpp_runtime_invoke"); //DynDll.GetFunction(gameAssemblyModule.BaseAddress, "il2cpp_runtime_invoke");
  53. PreloaderLogger.Log.LogDebug($"Runtime invoke pointer: 0x{functionPtr.ToInt64():X}");
  54. RuntimeInvokeDetour = new FastNativeDetour(functionPtr,
  55. MonoExtensions.GetFunctionPointerForDelegate(new RuntimeInvokeDetourDelegate(OnInvokeMethod), CallingConvention.Cdecl));
  56. RuntimeInvokeDetour.Apply();
  57. originalInvoke = RuntimeInvokeDetour.GenerateTrampoline<RuntimeInvokeDetourDelegate>();
  58. PreloaderLogger.Log.LogDebug("Runtime invoke patched");
  59. }
  60. private static IntPtr OnInvokeMethod(IntPtr method, IntPtr obj, IntPtr parameters, IntPtr exc)
  61. {
  62. string methodName = Marshal.PtrToStringAnsi(UnhollowerBaseLib.IL2CPP.il2cpp_method_get_name(method));
  63. bool unhook = false;
  64. if (methodName == "Internal_ActiveSceneChanged")
  65. {
  66. try
  67. {
  68. //Application.s_LogCallbackHandler = new Action<string, string, LogType>(UnityLogCallback);
  69. //Application.CallLogCallback("test from OnInvokeMethod", "", LogType.Log, true);
  70. unhook = true;
  71. Instance.Execute();
  72. }
  73. catch (Exception ex)
  74. {
  75. UnityLogSource.LogError(ex);
  76. }
  77. }
  78. var result = originalInvoke(method, obj, parameters, exc);
  79. if (unhook)
  80. {
  81. RuntimeInvokeDetour.Dispose();
  82. PreloaderLogger.Log.LogDebug("Runtime invoke unpatched");
  83. }
  84. return result;
  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. }