IL2CPPChainloader.cs 5.9 KB

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