Preloader.cs 10 KB

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