Entrypoint.cs 4.2 KB

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