| 1 |
using System; |
| 2 |
using System.Collections.Generic; |
| 3 |
using System.IO; |
| 4 |
using System.Reflection; |
| 5 |
using System.Runtime.Loader; |
| 6 |
|
| 7 |
namespace GodotPlugins |
| 8 |
{ |
| 9 |
public class PluginLoadContext : AssemblyLoadContext |
| 10 |
{ |
| 11 |
private readonly AssemblyDependencyResolver _resolver; |
| 12 |
private readonly ICollection<string> _sharedAssemblies; |
| 13 |
private readonly AssemblyLoadContext _mainLoadContext; |
| 14 |
|
| 15 |
public string? AssemblyLoadedPath { get; private set; } |
| 16 |
|
| 17 |
public PluginLoadContext(string pluginPath, ICollection<string> sharedAssemblies, |
| 18 |
AssemblyLoadContext mainLoadContext, bool isCollectible) |
| 19 |
: base(isCollectible) |
| 20 |
{ |
| 21 |
_resolver = new AssemblyDependencyResolver(pluginPath); |
| 22 |
_sharedAssemblies = sharedAssemblies; |
| 23 |
_mainLoadContext = mainLoadContext; |
| 24 |
|
| 25 |
if (string.IsNullOrEmpty(AppContext.BaseDirectory)) |
| 26 |
{ |
| 27 |
|
| 28 |
|
| 29 |
string? baseDirectory = Path.GetDirectoryName(pluginPath); |
| 30 |
if (baseDirectory != null) |
| 31 |
{ |
| 32 |
if (!Path.EndsInDirectorySeparator(baseDirectory)) |
| 33 |
baseDirectory += Path.DirectorySeparatorChar; |
| 34 |
|
| 35 |
|
| 36 |
AppDomain.CurrentDomain.SetData("APP_CONTEXT_BASE_DIRECTORY", baseDirectory); |
| 37 |
} |
| 38 |
else |
| 39 |
{ |
| 40 |
|
| 41 |
Console.Error.WriteLine("Failed to set AppContext.BaseDirectory. Dynamic loading of libraries may fail."); |
| 42 |
} |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
protected override Assembly? Load(AssemblyName assemblyName) |
| 47 |
{ |
| 48 |
if (assemblyName.Name == null) |
| 49 |
return null; |
| 50 |
|
| 51 |
if (_sharedAssemblies.Contains(assemblyName.Name)) |
| 52 |
return _mainLoadContext.LoadFromAssemblyName(assemblyName); |
| 53 |
|
| 54 |
string? assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName); |
| 55 |
if (assemblyPath != null) |
| 56 |
{ |
| 57 |
AssemblyLoadedPath = assemblyPath; |
| 58 |
|
| 59 |
|
| 60 |
using var assemblyFile = File.Open(assemblyPath, FileMode.Open, FileAccess.Read, FileShare.Read); |
| 61 |
string pdbPath = Path.ChangeExtension(assemblyPath, ".pdb"); |
| 62 |
|
| 63 |
if (File.Exists(pdbPath)) |
| 64 |
{ |
| 65 |
using var pdbFile = File.Open(pdbPath, FileMode.Open, FileAccess.Read, FileShare.Read); |
| 66 |
return LoadFromStream(assemblyFile, pdbFile); |
| 67 |
} |
| 68 |
|
| 69 |
return LoadFromStream(assemblyFile); |
| 70 |
} |
| 71 |
|
| 72 |
return null; |
| 73 |
} |
| 74 |
|
| 75 |
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) |
| 76 |
{ |
| 77 |
string? libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName); |
| 78 |
if (libraryPath != null) |
| 79 |
return LoadUnmanagedDllFromPath(libraryPath); |
| 80 |
|
| 81 |
return IntPtr.Zero; |
| 82 |
} |
| 83 |
} |
| 84 |
} |