Preloader.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Text;
  8. using BepInEx.Common;
  9. using BepInEx.Logging;
  10. using Mono.Cecil;
  11. using Mono.Cecil.Cil;
  12. using UnityInjector.ConsoleUtil;
  13. using MethodAttributes = Mono.Cecil.MethodAttributes;
  14. namespace BepInEx.Bootstrap
  15. {
  16. public static class Preloader
  17. {
  18. #region Path Properties
  19. public static string ExecutablePath { get; private set; }
  20. public static string CurrentExecutingAssemblyPath => Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", "").Replace('/', '\\');
  21. public static string CurrentExecutingAssemblyDirectoryPath => Path.GetDirectoryName(CurrentExecutingAssemblyPath);
  22. public static string GameName => Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().ProcessName);
  23. public static string GameRootPath => Path.GetDirectoryName(ExecutablePath);
  24. public static string ManagedPath => Utility.CombinePaths(GameRootPath, $"{GameName}_Data", "Managed");
  25. public static string PluginPath => Utility.CombinePaths(GameRootPath, "BepInEx");
  26. public static string PatcherPluginPath => Utility.CombinePaths(GameRootPath, "BepInEx", "patchers");
  27. #endregion
  28. public static PreloaderLogWriter PreloaderLog { get; private set; }
  29. public static Dictionary<string, IList<AssemblyPatcherDelegate>> PatcherDictionary = new Dictionary<string, IList<AssemblyPatcherDelegate>>(StringComparer.OrdinalIgnoreCase);
  30. public static void AddPatcher(string dllName, AssemblyPatcherDelegate patcher)
  31. {
  32. if (PatcherDictionary.TryGetValue(dllName, out IList<AssemblyPatcherDelegate> patcherList))
  33. patcherList.Add(patcher);
  34. else
  35. {
  36. patcherList = new List<AssemblyPatcherDelegate>();
  37. patcherList.Add(patcher);
  38. PatcherDictionary[dllName] = patcherList;
  39. }
  40. }
  41. private static bool TryGetConfigBool(string key, string defaultValue)
  42. {
  43. try
  44. {
  45. string result = Config.GetEntry(key, defaultValue);
  46. return bool.Parse(result);
  47. }
  48. catch
  49. {
  50. return false;
  51. }
  52. }
  53. internal static void AllocateConsole()
  54. {
  55. bool console = TryGetConfigBool("console", "false");
  56. bool shiftjis = TryGetConfigBool("console-shiftjis", "false");
  57. if (console)
  58. {
  59. try
  60. {
  61. ConsoleWindow.Attach();
  62. uint encoding = (uint) Encoding.UTF8.CodePage;
  63. if (shiftjis)
  64. encoding = 932;
  65. ConsoleEncoding.ConsoleCodePage = encoding;
  66. Console.OutputEncoding = ConsoleEncoding.GetEncoding(encoding);
  67. }
  68. catch (Exception ex)
  69. {
  70. Logger.Log(LogLevel.Error, "Failed to allocate console!");
  71. Logger.Log(LogLevel.Error, ex);
  72. }
  73. }
  74. }
  75. public static void Main(string[] args)
  76. {
  77. try
  78. {
  79. AppDomain.CurrentDomain.AssemblyResolve += LocalResolve;
  80. ExecutablePath = args[0];
  81. AllocateConsole();
  82. PreloaderLog = new PreloaderLogWriter(TryGetConfigBool("preloader-logconsole", "false"));
  83. PreloaderLog.Enabled = true;
  84. string consoleTile = $"BepInEx {Assembly.GetExecutingAssembly().GetName().Version} - {Process.GetCurrentProcess().ProcessName}";
  85. ConsoleWindow.Title = consoleTile;
  86. Logger.SetLogger(PreloaderLog);
  87. PreloaderLog.WriteLine(consoleTile);
  88. Logger.Log(LogLevel.Message, "Preloader started");
  89. AddPatcher("UnityEngine.dll", PatchEntrypoint);
  90. if (Directory.Exists(PatcherPluginPath))
  91. foreach (string assemblyPath in Directory.GetFiles(PatcherPluginPath, "*.dll"))
  92. {
  93. try
  94. {
  95. var assembly = Assembly.LoadFrom(assemblyPath);
  96. foreach (var kv in GetPatcherMethods(assembly))
  97. foreach (var patcher in kv.Value)
  98. AddPatcher(kv.Key, patcher);
  99. }
  100. catch (BadImageFormatException) { } //unmanaged DLL
  101. catch (ReflectionTypeLoadException) { } //invalid references
  102. }
  103. AssemblyPatcher.PatchAll(ManagedPath, PatcherDictionary);
  104. }
  105. catch (Exception ex)
  106. {
  107. Logger.Log(LogLevel.Fatal, "Could not run preloader!");
  108. Logger.Log(LogLevel.Fatal, ex);
  109. PreloaderLog.Enabled = false;
  110. try
  111. {
  112. UnityInjector.ConsoleUtil.ConsoleWindow.Attach();
  113. Console.Write(PreloaderLog);
  114. }
  115. finally
  116. {
  117. File.WriteAllText(Path.Combine(GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
  118. PreloaderLog.ToString());
  119. PreloaderLog.Dispose();
  120. }
  121. }
  122. }
  123. internal static IDictionary<string, IList<AssemblyPatcherDelegate>> GetPatcherMethods(Assembly assembly)
  124. {
  125. var patcherMethods = new Dictionary<string, IList<AssemblyPatcherDelegate>>(StringComparer.OrdinalIgnoreCase);
  126. foreach (var type in assembly.GetExportedTypes())
  127. {
  128. try
  129. {
  130. if (type.IsInterface)
  131. continue;
  132. PropertyInfo targetsProperty = type.GetProperty(
  133. "TargetDLLs",
  134. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  135. null,
  136. typeof(IEnumerable<string>),
  137. Type.EmptyTypes,
  138. null);
  139. //first try get the ref patcher method
  140. MethodInfo patcher = type.GetMethod(
  141. "Patch",
  142. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  143. null,
  144. CallingConventions.Any,
  145. new[] {typeof(AssemblyDefinition).MakeByRefType()},
  146. null);
  147. if (patcher == null) //otherwise try getting the non-ref patcher method
  148. {
  149. patcher = type.GetMethod(
  150. "Patch",
  151. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  152. null,
  153. CallingConventions.Any,
  154. new[] {typeof(AssemblyDefinition)},
  155. null);
  156. }
  157. if (targetsProperty == null || !targetsProperty.CanRead || patcher == null)
  158. continue;
  159. AssemblyPatcherDelegate patchDelegate = (ref AssemblyDefinition ass) =>
  160. {
  161. //we do the array fuckery here to get the ref result out
  162. object[] args = { ass };
  163. patcher.Invoke(null, args);
  164. ass = (AssemblyDefinition)args[0];
  165. };
  166. IEnumerable<string> targets = (IEnumerable<string>)targetsProperty.GetValue(null, null);
  167. foreach (string target in targets)
  168. {
  169. if (patcherMethods.TryGetValue(target, out IList<AssemblyPatcherDelegate> patchers))
  170. patchers.Add(patchDelegate);
  171. else
  172. {
  173. patchers = new List<AssemblyPatcherDelegate>{ patchDelegate };
  174. patcherMethods[target] = patchers;
  175. }
  176. }
  177. }
  178. catch (Exception ex)
  179. {
  180. Logger.Log(LogLevel.Warning, $"Could not load patcher methods from {assembly.GetName().Name}");
  181. Logger.Log(LogLevel.Warning, $"{ex}");
  182. }
  183. }
  184. Logger.Log(LogLevel.Info, $"Loaded {patcherMethods.SelectMany(x => x.Value).Distinct().Count()} patcher methods from {assembly.GetName().Name}");
  185. return patcherMethods;
  186. }
  187. internal static void PatchEntrypoint(ref AssemblyDefinition assembly)
  188. {
  189. if (assembly.Name.Name == "UnityEngine")
  190. {
  191. #if CECIL_10
  192. using (AssemblyDefinition injected = AssemblyDefinition.ReadAssembly(CurrentExecutingAssemblyPath))
  193. #elif CECIL_9
  194. AssemblyDefinition injected = AssemblyDefinition.ReadAssembly(CurrentExecutingAssemblyPath);
  195. #endif
  196. {
  197. var originalInjectMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader")
  198. .Methods.First(x => x.Name == "Initialize");
  199. var injectMethod = assembly.MainModule.ImportReference(originalInjectMethod);
  200. var sceneManager = assembly.MainModule.Types.First(x => x.Name == "Application");
  201. var voidType = assembly.MainModule.ImportReference(typeof(void));
  202. var cctor = new MethodDefinition(".cctor",
  203. MethodAttributes.Static
  204. | MethodAttributes.Private
  205. | MethodAttributes.HideBySig
  206. | MethodAttributes.SpecialName
  207. | MethodAttributes.RTSpecialName,
  208. voidType);
  209. var ilp = cctor.Body.GetILProcessor();
  210. ilp.Append(ilp.Create(OpCodes.Call, injectMethod));
  211. ilp.Append(ilp.Create(OpCodes.Ret));
  212. sceneManager.Methods.Add(cctor);
  213. }
  214. }
  215. }
  216. internal static Assembly LocalResolve(object sender, ResolveEventArgs args)
  217. {
  218. AssemblyName assemblyName = new AssemblyName(args.Name);
  219. var foundAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.GetName().Name == assemblyName.Name);
  220. if (foundAssembly != null)
  221. return foundAssembly;
  222. if (Utility.TryResolveDllAssembly(assemblyName, CurrentExecutingAssemblyDirectoryPath, out foundAssembly) ||
  223. Utility.TryResolveDllAssembly(assemblyName, PatcherPluginPath, out foundAssembly) ||
  224. Utility.TryResolveDllAssembly(assemblyName, PluginPath, out foundAssembly))
  225. return foundAssembly;
  226. return null;
  227. }
  228. }
  229. }