Entrypoint.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Reflection;
  5. using BepInEx.Preloader.RuntimeFixes;
  6. using HarmonyXInterop;
  7. namespace BepInEx.Preloader
  8. {
  9. internal static class PreloaderRunner
  10. {
  11. // This is a list of important assemblies in BepInEx core folder that should be force-loaded
  12. // Some games can ship these assemblies in Managed folder, in which case assembly resolving bypasses our LocalResolve
  13. // On the other hand, renaming these assemblies is not viable because 3rd party assemblies
  14. // that we don't build (e.g. MonoMod, Harmony, many plugins) depend on them
  15. // As such, we load them early so that the game uses our version instead
  16. // These assemblies should be known to be rarely edited and are known to be shipped as-is with Unity assets
  17. private static readonly string[] CriticalAssemblies =
  18. {
  19. "Mono.Cecil.dll",
  20. "Mono.Cecil.Mdb.dll",
  21. "Mono.Cecil.Pdb.dll",
  22. "Mono.Cecil.Rocks.dll",
  23. };
  24. private static void LoadCriticalAssemblies()
  25. {
  26. foreach (string criticalAssembly in CriticalAssemblies)
  27. {
  28. try
  29. {
  30. Assembly.LoadFile(Path.Combine(Paths.BepInExAssemblyDirectory, criticalAssembly));
  31. }
  32. catch (Exception)
  33. {
  34. // Suppress error for now
  35. // TODO: Should we crash here if load fails? Can't use logging at this point
  36. }
  37. }
  38. }
  39. // Do this in a separate method to not trigger cctor prematurely
  40. private static void InitializeAssemblyResolvers()
  41. {
  42. // Need to initialize interop first because it installs its own special assembly resolver
  43. HarmonyInterop.Initialize();
  44. AppDomain.CurrentDomain.AssemblyResolve += LocalResolve;
  45. // Remove temporary resolver early so it won't override local resolver
  46. AppDomain.CurrentDomain.AssemblyResolve -= Entrypoint.ResolveCurrentDirectory;
  47. }
  48. public static void PreloaderPreMain()
  49. {
  50. PlatformUtils.SetPlatform();
  51. string bepinPath = Utility.ParentDirectory(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH), 2);
  52. Paths.SetExecutablePath(EnvVars.DOORSTOP_PROCESS_PATH, bepinPath, EnvVars.DOORSTOP_MANAGED_FOLDER_DIR);
  53. LoadCriticalAssemblies();
  54. InitializeAssemblyResolvers();
  55. PreloaderMain();
  56. }
  57. private static void PreloaderMain()
  58. {
  59. if (Preloader.ConfigApplyRuntimePatches.Value)
  60. {
  61. XTermFix.Apply();
  62. ConsoleSetOutFix.Apply();
  63. }
  64. Preloader.Run();
  65. }
  66. private static Assembly LocalResolve(object sender, ResolveEventArgs args)
  67. {
  68. if (!Utility.TryParseAssemblyName(args.Name, out var assemblyName))
  69. return null;
  70. // Use parse assembly name on managed side because native GetName() can fail on some locales
  71. // if the game path has "exotic" characters
  72. var validAssemblies = AppDomain.CurrentDomain
  73. .GetAssemblies()
  74. .Select(a => new { assembly = a, name = Utility.TryParseAssemblyName(a.FullName, out var name) ? name : null })
  75. .Where(a => a.name != null && a.name.Name == assemblyName.Name)
  76. .OrderByDescending(a => a.name.Version)
  77. .ToList();
  78. // First try to match by version, then just pick the best match (generally highest)
  79. // This should mainly affect cases where the game itself loads some assembly (like Mono.Cecil)
  80. var foundMatch = validAssemblies.FirstOrDefault(a => a.name.Version == assemblyName.Version) ?? validAssemblies.FirstOrDefault();
  81. var foundAssembly = foundMatch?.assembly;
  82. if (foundAssembly != null)
  83. return foundAssembly;
  84. if (Utility.TryResolveDllAssembly(assemblyName, Paths.BepInExAssemblyDirectory, out foundAssembly)
  85. || Utility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, out foundAssembly)
  86. || Utility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, out foundAssembly))
  87. return foundAssembly;
  88. return null;
  89. }
  90. }
  91. internal static class Entrypoint
  92. {
  93. private static string preloaderPath;
  94. /// <summary>
  95. /// The main entrypoint of BepInEx, called from Doorstop.
  96. /// </summary>
  97. public static void Main()
  98. {
  99. // We set it to the current directory first as a fallback, but try to use the same location as the .exe file.
  100. string silentExceptionLog = $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log";
  101. try
  102. {
  103. EnvVars.LoadVars();
  104. string gamePath = Path.GetDirectoryName(EnvVars.DOORSTOP_PROCESS_PATH) ?? ".";
  105. silentExceptionLog = Path.Combine(gamePath, silentExceptionLog);
  106. // Get the path of this DLL via Doorstop env var because Assembly.Location mangles non-ASCII characters on some versions of Mono for unknown reasons
  107. preloaderPath = Path.GetDirectoryName(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH));
  108. AppDomain.CurrentDomain.AssemblyResolve += ResolveCurrentDirectory;
  109. // In some versions of Unity 4, Mono tries to resolve BepInEx.dll prematurely because of the call to Paths.SetExecutablePath
  110. // To prevent that, we have to use reflection and a separate startup class so that we can install required assembly resolvers before the main code
  111. typeof(Entrypoint).Assembly.GetType($"BepInEx.Preloader.{nameof(PreloaderRunner)}")
  112. ?.GetMethod(nameof(PreloaderRunner.PreloaderPreMain))
  113. ?.Invoke(null, null);
  114. }
  115. catch (Exception ex)
  116. {
  117. File.WriteAllText(silentExceptionLog, ex.ToString());
  118. }
  119. finally
  120. {
  121. AppDomain.CurrentDomain.AssemblyResolve -= ResolveCurrentDirectory;
  122. }
  123. }
  124. internal static Assembly ResolveCurrentDirectory(object sender, ResolveEventArgs args)
  125. {
  126. // Can't use Utils here because it's not yet resolved
  127. var name = new AssemblyName(args.Name);
  128. try
  129. {
  130. return Assembly.LoadFile(Path.Combine(preloaderPath, $"{name.Name}.dll"));
  131. }
  132. catch (Exception)
  133. {
  134. return null;
  135. }
  136. }
  137. }
  138. }