IL2CPPChainloader.cs 4.6 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. UnhollowerBaseLib.GeneratedDatabasesUtil.DatabasesLocationOverride = Preloader.IL2CPPUnhollowedPath;
  32. PatchManager.ResolvePatcher += IL2CPPDetourMethodPatcher.TryResolve;
  33. base.Initialize(gameExePath);
  34. Instance = this;
  35. var version = //Version.Parse(Application.unityVersion);
  36. Version.Parse(Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion);
  37. UnityVersionHandler.Initialize(version.Major, version.Minor, version.Revision);
  38. // One or the other here for Unhollower to work correctly
  39. //ClassInjector.Detour = new DetourHandler();
  40. ClassInjector.DoHook = (ptr, patchedFunctionPtr) =>
  41. {
  42. IntPtr originalFunc = new IntPtr(*(void**)ptr);
  43. var detour = new FastNativeDetour(originalFunc, patchedFunctionPtr);
  44. detour.Apply();
  45. *(void**)ptr = (void*)detour.TrampolinePtr;
  46. };
  47. var gameAssemblyModule = Process.GetCurrentProcess().Modules.Cast<ProcessModule>().First(x => x.ModuleName.Contains("GameAssembly"));
  48. var functionPtr = GetProcAddress(gameAssemblyModule.BaseAddress, "il2cpp_runtime_invoke"); //DynDll.GetFunction(gameAssemblyModule.BaseAddress, "il2cpp_runtime_invoke");
  49. PreloaderLogger.Log.LogDebug($"Runtime invoke pointer: 0x{functionPtr.ToInt64():X}");
  50. RuntimeInvokeDetour = new FastNativeDetour(functionPtr,
  51. MonoExtensions.GetFunctionPointerForDelegate(new RuntimeInvokeDetourDelegate(OnInvokeMethod), CallingConvention.Cdecl));
  52. RuntimeInvokeDetour.Apply();
  53. originalInvoke = RuntimeInvokeDetour.GenerateTrampoline<RuntimeInvokeDetourDelegate>();
  54. PreloaderLogger.Log.LogDebug("Runtime invoke patched");
  55. }
  56. private static IntPtr OnInvokeMethod(IntPtr method, IntPtr obj, IntPtr parameters, IntPtr exc)
  57. {
  58. string methodName = Marshal.PtrToStringAnsi(UnhollowerBaseLib.IL2CPP.il2cpp_method_get_name(method));
  59. bool unhook = false;
  60. if (methodName == "Internal_ActiveSceneChanged")
  61. {
  62. try
  63. {
  64. if (ConfigUnityLogging.Value)
  65. {
  66. Logger.Sources.Add(new IL2CPPUnityLogSource());
  67. IL2CPPUnityEngine.Application.CallLogCallback("Test call after applying unity logging hook", "", IL2CPPUnityEngine.LogType.Assert, true);
  68. }
  69. unhook = true;
  70. Instance.Execute();
  71. }
  72. catch (Exception ex)
  73. {
  74. Logger.LogFatal("Unable to execute IL2CPP chainloader");
  75. Logger.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. base.InitializeLoggers();
  89. if (!ConfigDiskWriteUnityLog.Value)
  90. {
  91. DiskLogListener.BlacklistedSources.Add("Unity");
  92. }
  93. ChainloaderLogHelper.RewritePreloaderLogs();
  94. Logger.Sources.Add(new IL2CPPLogSource());
  95. }
  96. public override BasePlugin LoadPlugin(PluginInfo pluginInfo, Assembly pluginAssembly)
  97. {
  98. var type = pluginAssembly.GetType(pluginInfo.TypeName);
  99. var pluginInstance = (BasePlugin)Activator.CreateInstance(type);
  100. pluginInstance.Load();
  101. return pluginInstance;
  102. }
  103. private static readonly ConfigEntry<bool> ConfigUnityLogging = ConfigFile.CoreConfig.Bind(
  104. "Logging", "UnityLogListening",
  105. true,
  106. "Enables showing unity log messages in the BepInEx logging system.");
  107. private static readonly ConfigEntry<bool> ConfigDiskWriteUnityLog = ConfigFile.CoreConfig.Bind(
  108. "Logging.Disk", "WriteUnityLog",
  109. false,
  110. "Include unity log messages in log file output.");
  111. }
  112. }