IL2CPPChainloader.cs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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 FastNativeDetour RuntimeInvokeDetour { get; set; }
  32. private static IL2CPPChainloader Instance { get; set; }
  33. public override unsafe void Initialize(string gameExePath = null)
  34. {
  35. PatchManager.ResolvePatcher += IL2CPPDetourMethodPatcher.TryResolve;
  36. base.Initialize(gameExePath);
  37. Instance = this;
  38. var version = //Version.Parse(Application.unityVersion);
  39. Version.Parse(Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion);
  40. UnityVersionHandler.Initialize(version.Major, version.Minor, version.Revision);
  41. // One or the other here for Unhollower to work correctly
  42. //ClassInjector.Detour = new DetourHandler();
  43. ClassInjector.DoHook = (ptr, patchedFunctionPtr) =>
  44. {
  45. IntPtr originalFunc = new IntPtr(*(void**)ptr);
  46. var detour = new FastNativeDetour(originalFunc, patchedFunctionPtr);
  47. detour.Apply();
  48. *(void**)ptr = (void*)detour.TrampolinePtr;
  49. };
  50. var gameAssemblyModule = Process.GetCurrentProcess().Modules.Cast<ProcessModule>().First(x => x.ModuleName.Contains("GameAssembly"));
  51. var functionPtr = GetProcAddress(gameAssemblyModule.BaseAddress, "il2cpp_runtime_invoke"); //DynDll.GetFunction(gameAssemblyModule.BaseAddress, "il2cpp_runtime_invoke");
  52. PreloaderLogger.Log.LogDebug($"Runtime invoke pointer: 0x{functionPtr.ToInt64():X}");
  53. RuntimeInvokeDetour = new FastNativeDetour(functionPtr,
  54. MonoExtensions.GetFunctionPointerForDelegate(new RuntimeInvokeDetourDelegate(OnInvokeMethod), CallingConvention.Cdecl));
  55. RuntimeInvokeDetour.Apply();
  56. originalInvoke = RuntimeInvokeDetour.GenerateTrampoline<RuntimeInvokeDetourDelegate>();
  57. PreloaderLogger.Log.LogDebug("Runtime invoke patched");
  58. }
  59. private static IntPtr OnInvokeMethod(IntPtr method, IntPtr obj, IntPtr parameters, IntPtr exc)
  60. {
  61. string methodName = Marshal.PtrToStringAnsi(UnhollowerBaseLib.IL2CPP.il2cpp_method_get_name(method));
  62. bool unhook = false;
  63. if (methodName == "Internal_ActiveSceneChanged")
  64. {
  65. try
  66. {
  67. //Application.s_LogCallbackHandler = new Action<string, string, LogType>(UnityLogCallback);
  68. //Application.CallLogCallback("test from OnInvokeMethod", "", LogType.Log, true);
  69. unhook = true;
  70. Instance.Execute();
  71. }
  72. catch (Exception ex)
  73. {
  74. UnityLogSource.LogError(ex);
  75. }
  76. }
  77. var result = originalInvoke(method, obj, parameters, exc);
  78. if (unhook)
  79. {
  80. RuntimeInvokeDetour.Dispose();
  81. PreloaderLogger.Log.LogDebug("Runtime invoke unpatched");
  82. }
  83. return result;
  84. }
  85. protected override void InitializeLoggers()
  86. {
  87. //Logger.Listeners.Add(new UnityLogListener());
  88. //if (ConfigUnityLogging.Value)
  89. // Logger.Sources.Add(new UnityLogSource());
  90. Logger.Sources.Add(UnityLogSource);
  91. base.InitializeLoggers();
  92. //if (!ConfigDiskWriteUnityLog.Value)
  93. //{
  94. // DiskLogListener.BlacklistedSources.Add("Unity Log");
  95. //}
  96. // Temporarily disable the console log listener as we replay the preloader logs
  97. var logListener = Logger.Listeners.FirstOrDefault(logger => logger is ConsoleLogListener);
  98. if (logListener != null)
  99. Logger.Listeners.Remove(logListener);
  100. foreach (var preloaderLogEvent in PreloaderConsoleListener.LogEvents)
  101. {
  102. PreloaderLogger.Log.Log(preloaderLogEvent.Level, preloaderLogEvent.Data);
  103. }
  104. if (logListener != null)
  105. Logger.Listeners.Add(logListener);
  106. //UnityEngine.Application.s_LogCallbackHandler = DelegateSupport.ConvertDelegate<Application.LogCallback>(new Action<string>(UnityLogCallback));
  107. //UnityEngine.Application.s_LogCallbackHandler = (Application.LogCallback)new Action<string>(UnityLogCallback);
  108. //var loggerPointer = Marshal.GetFunctionPointerForDelegate(new UnityLogCallbackDelegate(UnityLogCallback));
  109. //UnhollowerBaseLib.IL2CPP.il2cpp_register_log_callback(loggerPointer);
  110. }
  111. public override BasePlugin LoadPlugin(PluginInfo pluginInfo, Assembly pluginAssembly)
  112. {
  113. var type = pluginAssembly.GetType(pluginInfo.TypeName);
  114. var pluginInstance = (BasePlugin)Activator.CreateInstance(type);
  115. pluginInstance.Load();
  116. return pluginInstance;
  117. }
  118. }
  119. }