Preloader.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 BepInEx.Common;
  8. using Mono.Cecil;
  9. using Mono.Cecil.Cil;
  10. using MethodAttributes = Mono.Cecil.MethodAttributes;
  11. namespace BepInEx.Bootstrap
  12. {
  13. public static class Preloader
  14. {
  15. #region Path Properties
  16. public static string ExecutablePath { get; private set; }
  17. public static string CurrentExecutingAssemblyPath => Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", "").Replace('/', '\\');
  18. public static string CurrentExecutingAssemblyDirectoryPath => Path.GetDirectoryName(CurrentExecutingAssemblyPath);
  19. public static string GameName => Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().ProcessName);
  20. public static string GameRootPath => Path.GetDirectoryName(ExecutablePath);
  21. public static string ManagedPath => Utility.CombinePaths(GameRootPath, $"{GameName}_Data", "Managed");
  22. public static string PluginPath => Utility.CombinePaths(GameRootPath, "BepInEx");
  23. public static string PatcherPluginPath => Utility.CombinePaths(GameRootPath, "BepInEx", "patchers");
  24. #endregion
  25. public static Dictionary<string, IList<AssemblyPatcherDelegate>> PatcherDictionary = new Dictionary<string, IList<AssemblyPatcherDelegate>>(StringComparer.OrdinalIgnoreCase);
  26. public static void AddPatcher(string dllName, AssemblyPatcherDelegate patcher)
  27. {
  28. if (PatcherDictionary.TryGetValue(dllName, out IList<AssemblyPatcherDelegate> patcherList))
  29. patcherList.Add(patcher);
  30. else
  31. {
  32. patcherList = new List<AssemblyPatcherDelegate>();
  33. patcherList.Add(patcher);
  34. PatcherDictionary[dllName] = patcherList;
  35. }
  36. }
  37. public static void Main(string[] args)
  38. {
  39. ExecutablePath = args[0];
  40. AppDomain.CurrentDomain.AssemblyResolve += LocalResolve;
  41. try
  42. {
  43. AddPatcher("UnityEngine.dll", PatchEntrypoint);
  44. if (Directory.Exists(PatcherPluginPath))
  45. foreach (string assemblyPath in Directory.GetFiles(PatcherPluginPath, "*.dll"))
  46. {
  47. try
  48. {
  49. var assembly = Assembly.LoadFrom(assemblyPath);
  50. foreach (var kv in GetPatcherMethods(assembly))
  51. foreach (var patcher in kv.Value)
  52. AddPatcher(kv.Key, patcher);
  53. }
  54. catch (BadImageFormatException) { } //unmanaged DLL
  55. catch (ReflectionTypeLoadException) { } //invalid references
  56. }
  57. AssemblyPatcher.PatchAll(ManagedPath, PatcherDictionary);
  58. }
  59. catch (Exception ex)
  60. {
  61. //TODO: some proper exception handling
  62. }
  63. }
  64. internal static IDictionary<string, IList<AssemblyPatcherDelegate>> GetPatcherMethods(Assembly assembly)
  65. {
  66. var patcherMethods = new Dictionary<string, IList<AssemblyPatcherDelegate>>(StringComparer.OrdinalIgnoreCase);
  67. foreach (var type in assembly.GetExportedTypes())
  68. {
  69. try
  70. {
  71. if (type.IsInterface)
  72. continue;
  73. PropertyInfo targetsProperty = type.GetProperty(
  74. "TargetDLLs",
  75. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  76. null,
  77. typeof(IEnumerable<string>),
  78. Type.EmptyTypes,
  79. null);
  80. MethodInfo patcher = type.GetMethod(
  81. "Patch",
  82. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  83. null,
  84. CallingConventions.Any,
  85. new[] { typeof(AssemblyDefinition) },
  86. null);
  87. if (targetsProperty == null || !targetsProperty.CanRead || patcher == null)
  88. continue;
  89. AssemblyPatcherDelegate patchDelegate = (ass) => { patcher.Invoke(null, new object[] {ass}); };
  90. IEnumerable<string> targets = (IEnumerable<string>)targetsProperty.GetValue(null, null);
  91. foreach (string target in targets)
  92. {
  93. if (patcherMethods.TryGetValue(target, out IList<AssemblyPatcherDelegate> patchers))
  94. patchers.Add(patchDelegate);
  95. else
  96. {
  97. patchers = new List<AssemblyPatcherDelegate>{ patchDelegate };
  98. patcherMethods[target] = patchers;
  99. }
  100. }
  101. }
  102. catch (Exception ex)
  103. {
  104. //TODO: add logging of exceptions
  105. }
  106. }
  107. return patcherMethods;
  108. }
  109. internal static void PatchEntrypoint(AssemblyDefinition assembly)
  110. {
  111. if (assembly.Name.Name == "UnityEngine")
  112. {
  113. #if CECIL_10
  114. using (AssemblyDefinition injected = AssemblyDefinition.ReadAssembly(CurrentExecutingAssemblyPath))
  115. #elif CECIL_9
  116. AssemblyDefinition injected = AssemblyDefinition.ReadAssembly(CurrentExecutingAssemblyPath);
  117. #endif
  118. {
  119. var originalInjectMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader")
  120. .Methods.First(x => x.Name == "Initialize");
  121. var injectMethod = assembly.MainModule.ImportReference(originalInjectMethod);
  122. var sceneManager = assembly.MainModule.Types.First(x => x.Name == "Application");
  123. var voidType = assembly.MainModule.ImportReference(typeof(void));
  124. var cctor = new MethodDefinition(".cctor",
  125. MethodAttributes.Static
  126. | MethodAttributes.Private
  127. | MethodAttributes.HideBySig
  128. | MethodAttributes.SpecialName
  129. | MethodAttributes.RTSpecialName,
  130. voidType);
  131. var ilp = cctor.Body.GetILProcessor();
  132. ilp.Append(ilp.Create(OpCodes.Call, injectMethod));
  133. ilp.Append(ilp.Create(OpCodes.Ret));
  134. sceneManager.Methods.Add(cctor);
  135. }
  136. }
  137. }
  138. internal static Assembly LocalResolve(object sender, ResolveEventArgs args)
  139. {
  140. if (args.Name == "0Harmony, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null")
  141. return Assembly.LoadFile(Path.Combine(CurrentExecutingAssemblyDirectoryPath, "0Harmony.dll"));
  142. return null;
  143. }
  144. }
  145. }