IL2CPPChainloader.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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.IL2CPP.Hook;
  9. using BepInEx.Logging;
  10. using BepInEx.Preloader.Core;
  11. using BepInEx.Preloader.Core.Logging;
  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 readonly ManualLogSource unhollowerLogSource = Logger.CreateLogSource("Unhollower");
  37. public override unsafe void Initialize(string gameExePath = null)
  38. {
  39. base.Initialize(gameExePath);
  40. UnityVersionHandler.Initialize(2019, 2, 17);
  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. var invokeDetour = new FastNativeDetour(functionPtr, Marshal.GetFunctionPointerForDelegate(new RuntimeInvokeDetour(OnInvokeMethod)));
  54. invokeDetour.Apply(unhollowerLogSource);
  55. originalInvoke = invokeDetour.GenerateTrampoline<RuntimeInvokeDetour>();
  56. }
  57. private static bool HasSet = false;
  58. private static HashSet<string> recordedNames = new HashSet<string>();
  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. IntPtr methodClass = UnhollowerBaseLib.IL2CPP.il2cpp_method_get_class(method);
  63. string methodClassName = Marshal.PtrToStringAnsi(UnhollowerBaseLib.IL2CPP.il2cpp_class_get_name(methodClass));
  64. string methodClassNamespace = Marshal.PtrToStringAnsi(UnhollowerBaseLib.IL2CPP.il2cpp_class_get_namespace(methodClass));
  65. string methodFullName = $"{methodClassNamespace}.{methodClassName}::{methodName}";
  66. if (!HasSet && methodName == "Internal_ActiveSceneChanged")
  67. {
  68. try
  69. {
  70. Application.s_LogCallbackHandler = new Action<string, string, LogType>(UnityLogCallback);
  71. UnityLogSource.LogMessage($"callback set - {methodName}");
  72. Application.CallLogCallback("test from OnInvokeMethod", "", LogType.Log, true);
  73. }
  74. catch (Exception ex)
  75. {
  76. UnityLogSource.LogError(ex);
  77. }
  78. HasSet = true;
  79. }
  80. var result = originalInvoke(method, obj, parameters, exc);
  81. //UnityLogSource.LogDebug(methodName + " => " + result.ToString("X"));
  82. if (!recordedNames.Contains(methodFullName))
  83. {
  84. UnityLogSource.LogDebug(methodFullName + " => " + result.ToString("X"));
  85. lock (recordedNames)
  86. recordedNames.Add(methodFullName);
  87. }
  88. return result;
  89. }
  90. protected override void InitializeLoggers()
  91. {
  92. //Logger.Listeners.Add(new UnityLogListener());
  93. //if (ConfigUnityLogging.Value)
  94. // Logger.Sources.Add(new UnityLogSource());
  95. Logger.Sources.Add(UnityLogSource);
  96. UnhollowerBaseLib.LogSupport.InfoHandler += unhollowerLogSource.LogInfo;
  97. UnhollowerBaseLib.LogSupport.WarningHandler += unhollowerLogSource.LogWarning;
  98. UnhollowerBaseLib.LogSupport.TraceHandler += unhollowerLogSource.LogDebug;
  99. UnhollowerBaseLib.LogSupport.ErrorHandler += unhollowerLogSource.LogError;
  100. base.InitializeLoggers();
  101. //if (!ConfigDiskWriteUnityLog.Value)
  102. //{
  103. // DiskLogListener.BlacklistedSources.Add("Unity Log");
  104. //}
  105. foreach (var preloaderLogEvent in PreloaderConsoleListener.LogEvents)
  106. {
  107. PreloaderLogger.Log.Log(preloaderLogEvent.Level, preloaderLogEvent.Data);
  108. }
  109. //UnityEngine.Application.s_LogCallbackHandler = DelegateSupport.ConvertDelegate<Application.LogCallback>(new Action<string>(UnityLogCallback));
  110. //UnityEngine.Application.s_LogCallbackHandler = (Application.LogCallback)new Action<string>(UnityLogCallback);
  111. //var loggerPointer = Marshal.GetFunctionPointerForDelegate(new UnityLogCallbackDelegate(UnityLogCallback));
  112. //UnhollowerBaseLib.IL2CPP.il2cpp_register_log_callback(loggerPointer);
  113. }
  114. public override BasePlugin LoadPlugin(PluginInfo pluginInfo, Assembly pluginAssembly)
  115. {
  116. var type = pluginAssembly.GetType(pluginInfo.TypeName);
  117. var pluginInstance = (BasePlugin)Activator.CreateInstance(type);
  118. pluginInstance.Load();
  119. return pluginInstance;
  120. }
  121. }
  122. }