DoorstopEntrypoint.cs 5.4 KB

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