Entrypoint.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Reflection;
  5. namespace BepInEx.Preloader
  6. {
  7. internal static class PreloaderRunner
  8. {
  9. public static void PreloaderMain(string[] args)
  10. {
  11. Paths.SetExecutablePath(args[0]);
  12. Paths.SetManagedPath(Environment.GetEnvironmentVariable("DOORSTOP_MANAGED_FOLDER_DIR"));
  13. AppDomain.CurrentDomain.AssemblyResolve += LocalResolve;
  14. Preloader.Run();
  15. }
  16. private static Assembly LocalResolve(object sender, ResolveEventArgs args)
  17. {
  18. var assemblyName = new AssemblyName(args.Name);
  19. var foundAssembly = AppDomain.CurrentDomain.GetAssemblies()
  20. .FirstOrDefault(x => x.GetName().Name == assemblyName.Name);
  21. if (foundAssembly != null)
  22. return foundAssembly;
  23. if (Utility.TryResolveDllAssembly(assemblyName, Paths.BepInExAssemblyDirectory, out foundAssembly)
  24. || Utility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, out foundAssembly)
  25. || Utility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, out foundAssembly))
  26. return foundAssembly;
  27. return null;
  28. }
  29. }
  30. internal static class Entrypoint
  31. {
  32. private static string preloaderPath;
  33. /// <summary>
  34. /// The main entrypoint of BepInEx, called from Doorstop.
  35. /// </summary>
  36. /// <param name="args">
  37. /// The arguments passed in from Doorstop. First argument is the path of the currently executing
  38. /// process.
  39. /// </param>
  40. public static void Main(string[] args)
  41. {
  42. // 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
  43. preloaderPath = Path.GetDirectoryName(Path.GetFullPath(Environment.GetEnvironmentVariable("DOORSTOP_INVOKE_DLL_PATH")));
  44. AppDomain.CurrentDomain.AssemblyResolve += ResolveCurrentDirectory;
  45. // We have to use reflection and a separate startup class in order to not trigger premature assembly resolving
  46. typeof(Entrypoint).Assembly.GetType($"BepInEx.Preloader.{nameof(PreloaderRunner)}")
  47. ?.GetMethod(nameof(PreloaderRunner.PreloaderMain))
  48. ?.Invoke(null, new object[] { args });
  49. AppDomain.CurrentDomain.AssemblyResolve -= ResolveCurrentDirectory;
  50. }
  51. private static Assembly ResolveCurrentDirectory(object sender, ResolveEventArgs args)
  52. {
  53. var name = new AssemblyName(args.Name);
  54. try
  55. {
  56. return Assembly.LoadFile(Path.Combine(preloaderPath, $"{name.Name}.dll"));
  57. }
  58. catch (Exception)
  59. {
  60. return null;
  61. }
  62. }
  63. }
  64. }