DoorstopEntrypoint.cs 5.3 KB

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