DoorstopEntrypoint.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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. public static void PreloaderPreMain()
  11. {
  12. string bepinPath = Utility.ParentDirectory(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH), 2);
  13. Paths.SetExecutablePath(EnvVars.DOORSTOP_MANAGED_FOLDER_DIR, bepinPath);
  14. AppDomain.CurrentDomain.AssemblyResolve += LocalResolve;
  15. // Remove temporary resolver early so it won't override local resolver
  16. AppDomain.CurrentDomain.AssemblyResolve -= DoorstopEntrypoint.ResolveCurrentDirectory;
  17. PreloaderMain();
  18. }
  19. private static void PreloaderMain()
  20. {
  21. if (UnityPreloader.ConfigApplyRuntimePatches.Value)
  22. {
  23. XTermFix.Apply();
  24. ConsoleSetOutFix.Apply();
  25. }
  26. UnityPreloader.Run(EnvVars.DOORSTOP_MANAGED_FOLDER_DIR);
  27. }
  28. private static Assembly LocalResolve(object sender, ResolveEventArgs args)
  29. {
  30. if (!Utility.TryParseAssemblyName(args.Name, out var assemblyName))
  31. return null;
  32. // Use parse assembly name on managed side because native GetName() can fail on some locales
  33. // if the game path has "exotic" characters
  34. var validAssemblies = AppDomain.CurrentDomain
  35. .GetAssemblies()
  36. .Select(a => new { assembly = a, name = Utility.TryParseAssemblyName(a.FullName, out var name) ? name : null })
  37. .Where(a => a.name != null && a.name.Name == assemblyName.Name)
  38. .OrderByDescending(a => a.name.Version)
  39. .ToList();
  40. // First try to match by version, then just pick the best match (generally highest)
  41. // This should mainly affect cases where the game itself loads some assembly (like Mono.Cecil)
  42. var foundMatch = validAssemblies.FirstOrDefault(a => a.name.Version == assemblyName.Version) ?? validAssemblies.FirstOrDefault();
  43. var foundAssembly = foundMatch?.assembly;
  44. if (foundAssembly != null)
  45. return foundAssembly;
  46. if (Utility.TryResolveDllAssembly(assemblyName, Paths.BepInExAssemblyDirectory, out foundAssembly)
  47. || Utility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, out foundAssembly)
  48. || Utility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, out foundAssembly))
  49. return foundAssembly;
  50. return null;
  51. }
  52. }
  53. internal static class DoorstopEntrypoint
  54. {
  55. private static string preloaderPath;
  56. /// <summary>
  57. /// The main entrypoint of BepInEx, called from Doorstop.
  58. /// </summary>
  59. public static void Main()
  60. {
  61. // We set it to the current directory first as a fallback, but try to use the same location as the .exe file.
  62. string silentExceptionLog = $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log";
  63. try
  64. {
  65. EnvVars.LoadVars();
  66. string gamePath = Path.GetDirectoryName(EnvVars.DOORSTOP_PROCESS_PATH) ?? ".";
  67. silentExceptionLog = Path.Combine(gamePath, silentExceptionLog);
  68. // 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
  69. preloaderPath = Path.GetDirectoryName(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH));
  70. AppDomain.CurrentDomain.AssemblyResolve += ResolveCurrentDirectory;
  71. // In some versions of Unity 4, Mono tries to resolve BepInEx.dll prematurely because of the call to Paths.SetExecutablePath
  72. // 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
  73. typeof(DoorstopEntrypoint).Assembly.GetType($"BepInEx.Preloader.Unity.{nameof(UnityPreloaderRunner)}")
  74. ?.GetMethod(nameof(UnityPreloaderRunner.PreloaderPreMain))
  75. ?.Invoke(null, null);
  76. }
  77. catch (Exception ex)
  78. {
  79. File.WriteAllText(silentExceptionLog, ex.ToString());
  80. }
  81. finally
  82. {
  83. AppDomain.CurrentDomain.AssemblyResolve -= ResolveCurrentDirectory;
  84. }
  85. }
  86. internal static Assembly ResolveCurrentDirectory(object sender, ResolveEventArgs args)
  87. {
  88. // Can't use Utils here because it's not yet resolved
  89. var name = new AssemblyName(args.Name);
  90. try
  91. {
  92. return Assembly.LoadFile(Path.Combine(preloaderPath, $"{name.Name}.dll"));
  93. }
  94. catch (Exception)
  95. {
  96. return null;
  97. }
  98. }
  99. }
  100. }