Entrypoint.cs 2.5 KB

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