Preloader.cs 6.5 KB

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