IL2CPPChainloader.cs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. extern alias il2cpp;
  2. using System;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Runtime.InteropServices;
  7. using BepInEx.Bootstrap;
  8. using BepInEx.Configuration;
  9. using BepInEx.IL2CPP.Hook;
  10. using BepInEx.IL2CPP.Logging;
  11. using BepInEx.Logging;
  12. using BepInEx.Preloader.Core;
  13. using BepInEx.Preloader.Core.Logging;
  14. using HarmonyLib.Public.Patching;
  15. using UnhollowerBaseLib.Runtime;
  16. using UnhollowerRuntimeLib;
  17. using IL2CPPUnityEngine = il2cpp::UnityEngine;
  18. namespace BepInEx.IL2CPP
  19. {
  20. public class IL2CPPChainloader : BaseChainloader<BasePlugin>
  21. {
  22. [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  23. private delegate IntPtr RuntimeInvokeDetourDelegate(IntPtr method, IntPtr obj, IntPtr parameters, IntPtr exc);
  24. [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
  25. private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
  26. private static RuntimeInvokeDetourDelegate originalInvoke;
  27. private static FastNativeDetour RuntimeInvokeDetour { get; set; }
  28. private static IL2CPPChainloader Instance { get; set; }
  29. public override unsafe void Initialize(string gameExePath = null)
  30. {
  31. PatchManager.ResolvePatcher += IL2CPPDetourMethodPatcher.TryResolve;
  32. base.Initialize(gameExePath);
  33. Instance = this;
  34. var version = //Version.Parse(Application.unityVersion);
  35. Version.Parse(Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion);
  36. UnityVersionHandler.Initialize(version.Major, version.Minor, version.Revision);
  37. // One or the other here for Unhollower to work correctly
  38. //ClassInjector.Detour = new DetourHandler();
  39. ClassInjector.DoHook = (ptr, patchedFunctionPtr) =>
  40. {
  41. IntPtr originalFunc = new IntPtr(*(void**)ptr);
  42. var detour = new FastNativeDetour(originalFunc, patchedFunctionPtr);
  43. detour.Apply();
  44. *(void**)ptr = (void*)detour.TrampolinePtr;
  45. };
  46. var gameAssemblyModule = Process.GetCurrentProcess().Modules.Cast<ProcessModule>().First(x => x.ModuleName.Contains("GameAssembly"));
  47. var functionPtr = GetProcAddress(gameAssemblyModule.BaseAddress, "il2cpp_runtime_invoke"); //DynDll.GetFunction(gameAssemblyModule.BaseAddress, "il2cpp_runtime_invoke");
  48. PreloaderLogger.Log.LogDebug($"Runtime invoke pointer: 0x{functionPtr.ToInt64():X}");
  49. RuntimeInvokeDetour = new FastNativeDetour(functionPtr,
  50. MonoExtensions.GetFunctionPointerForDelegate(new RuntimeInvokeDetourDelegate(OnInvokeMethod), CallingConvention.Cdecl));
  51. RuntimeInvokeDetour.Apply();
  52. originalInvoke = RuntimeInvokeDetour.GenerateTrampoline<RuntimeInvokeDetourDelegate>();
  53. PreloaderLogger.Log.LogDebug("Runtime invoke patched");
  54. }
  55. private static IntPtr OnInvokeMethod(IntPtr method, IntPtr obj, IntPtr parameters, IntPtr exc)
  56. {
  57. string methodName = Marshal.PtrToStringAnsi(UnhollowerBaseLib.IL2CPP.il2cpp_method_get_name(method));
  58. bool unhook = false;
  59. if (methodName == "Internal_ActiveSceneChanged")
  60. {
  61. try
  62. {
  63. if (ConfigUnityLogging.Value)
  64. {
  65. Logger.Sources.Add(new IL2CPPUnityLogSource());
  66. IL2CPPUnityEngine.Application.CallLogCallback("Test call after applying unity logging hook", "", IL2CPPUnityEngine.LogType.Assert, true);
  67. }
  68. unhook = true;
  69. Instance.Execute();
  70. }
  71. catch (Exception ex)
  72. {
  73. Logger.LogFatal("Unable to execute IL2CPP chainloader");
  74. Logger.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. base.InitializeLoggers();
  88. if (!ConfigDiskWriteUnityLog.Value)
  89. {
  90. DiskLogListener.BlacklistedSources.Add("Unity");
  91. }
  92. ChainloaderLogHelper.RewritePreloaderLogs();
  93. Logger.Sources.Add(new IL2CPPLogSource());
  94. }
  95. public override BasePlugin LoadPlugin(PluginInfo pluginInfo, Assembly pluginAssembly)
  96. {
  97. var type = pluginAssembly.GetType(pluginInfo.TypeName);
  98. var pluginInstance = (BasePlugin)Activator.CreateInstance(type);
  99. pluginInstance.Load();
  100. return pluginInstance;
  101. }
  102. private static readonly ConfigEntry<bool> ConfigUnityLogging = ConfigFile.CoreConfig.Bind(
  103. "Logging", "UnityLogListening",
  104. true,
  105. "Enables showing unity log messages in the BepInEx logging system.");
  106. private static readonly ConfigEntry<bool> ConfigDiskWriteUnityLog = ConfigFile.CoreConfig.Bind(
  107. "Logging.Disk", "WriteUnityLog",
  108. false,
  109. "Include unity log messages in log file output.");
  110. }
  111. }