Entrypoint.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. string bepinPath = Utility.ParentDirectory(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH), 2);
  51. Paths.SetExecutablePath(EnvVars.DOORSTOP_PROCESS_PATH, bepinPath, EnvVars.DOORSTOP_MANAGED_FOLDER_DIR);
  52. LoadCriticalAssemblies();
  53. InitializeAssemblyResolvers();
  54. PreloaderMain();
  55. }
  56. private static void PreloaderMain()
  57. {
  58. if (Preloader.ConfigApplyRuntimePatches.Value)
  59. {
  60. XTermFix.Apply();
  61. ConsoleSetOutFix.Apply();
  62. }
  63. Preloader.Run();
  64. }
  65. private static Assembly LocalResolve(object sender, ResolveEventArgs args)
  66. {
  67. if (!Utility.TryParseAssemblyName(args.Name, out var assemblyName))
  68. return null;
  69. // Use parse assembly name on managed side because native GetName() can fail on some locales
  70. // if the game path has "exotic" characters
  71. var validAssemblies = AppDomain.CurrentDomain
  72. .GetAssemblies()
  73. .Select(a => new { assembly = a, name = Utility.TryParseAssemblyName(a.FullName, out var name) ? name : null })
  74. .Where(a => a.name != null && a.name.Name == assemblyName.Name)
  75. .OrderByDescending(a => a.name.Version)
  76. .ToList();
  77. // First try to match by version, then just pick the best match (generally highest)
  78. // This should mainly affect cases where the game itself loads some assembly (like Mono.Cecil)
  79. var foundMatch = validAssemblies.FirstOrDefault(a => a.name.Version == assemblyName.Version) ?? validAssemblies.FirstOrDefault();
  80. var foundAssembly = foundMatch?.assembly;
  81. if (foundAssembly != null)
  82. return foundAssembly;
  83. if (Utility.TryResolveDllAssembly(assemblyName, Paths.BepInExAssemblyDirectory, out foundAssembly)
  84. || Utility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, out foundAssembly)
  85. || Utility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, out foundAssembly))
  86. return foundAssembly;
  87. return null;
  88. }
  89. }
  90. internal static class Entrypoint
  91. {
  92. private static string preloaderPath;
  93. /// <summary>
  94. /// The main entrypoint of BepInEx, called from Doorstop.
  95. /// </summary>
  96. public static void Main()
  97. {
  98. // We set it to the current directory first as a fallback, but try to use the same location as the .exe file.
  99. string silentExceptionLog = $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log";
  100. try
  101. {
  102. EnvVars.LoadVars();
  103. string gamePath = Path.GetDirectoryName(EnvVars.DOORSTOP_PROCESS_PATH) ?? ".";
  104. silentExceptionLog = Path.Combine(gamePath, silentExceptionLog);
  105. // 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
  106. preloaderPath = Path.GetDirectoryName(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH));
  107. AppDomain.CurrentDomain.AssemblyResolve += ResolveCurrentDirectory;
  108. // In some versions of Unity 4, Mono tries to resolve BepInEx.dll prematurely because of the call to Paths.SetExecutablePath
  109. // 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
  110. typeof(Entrypoint).Assembly.GetType($"BepInEx.Preloader.{nameof(PreloaderRunner)}")
  111. ?.GetMethod(nameof(PreloaderRunner.PreloaderPreMain))
  112. ?.Invoke(null, null);
  113. }
  114. catch (Exception ex)
  115. {
  116. File.WriteAllText(silentExceptionLog, ex.ToString());
  117. }
  118. finally
  119. {
  120. AppDomain.CurrentDomain.AssemblyResolve -= ResolveCurrentDirectory;
  121. }
  122. }
  123. internal static Assembly ResolveCurrentDirectory(object sender, ResolveEventArgs args)
  124. {
  125. // Can't use Utils here because it's not yet resolved
  126. var name = new AssemblyName(args.Name);
  127. try
  128. {
  129. return Assembly.LoadFile(Path.Combine(preloaderPath, $"{name.Name}.dll"));
  130. }
  131. catch (Exception)
  132. {
  133. return null;
  134. }
  135. }
  136. }
  137. }