Repository navigation
Expand file tree
/
Copy pathPatcherLoadContext.cs
More file actions
82 lines (67 loc) · 2.97 KB
/
Copy pathPatcherLoadContext.cs
File metadata and controls
82 lines (67 loc) · 2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using Serilog;
namespace NetcodePatcher.Tools.Common;
class PatcherLoadContext : AssemblyLoadContext
{
private static readonly HashSet<string> SpecificAssemblyNames = [ "NetcodePatcher", "Unity.Netcode.Runtime" ];
private static readonly HashSet<string> SharedDependencyAssemblyNames = [ "Serilog" ];
private readonly PatcherConfiguration _configuration;
public PatcherLoadContext(string name, PatcherConfiguration configuration) : base(name)
{
_configuration = configuration;
}
protected override Assembly? Load(AssemblyName assemblyName)
{
var loadedAssembly = Default.Assemblies
.FirstOrDefault(assembly => assembly.GetName() == assemblyName);
if (loadedAssembly is not null) return loadedAssembly;
if (assemblyName.Name is null) return null;
if (SharedDependencyAssemblyNames.Contains(assemblyName.Name))
{
string? sharedPath = ResolveAssemblyToPath(assemblyName);
if (sharedPath is null)
{
Log.Debug("Shared dependency {SharedName} not found in {CommonDir} or {SharedDir}, trying to load from system", assemblyName, _configuration.PatcherCommonAssemblyDir, _configuration.PatcherNetcodeSpecificAssemblyDir);
return Default.LoadFromAssemblyName(assemblyName);
}
Log.Debug("Shared Dependency {SharedName} loading from {Directory}", assemblyName, sharedPath);
return Default.LoadFromAssemblyPath(sharedPath);
}
string? assemblyPath = ResolveAssemblyToPath(assemblyName);
if (assemblyPath is null) return null;
return LoadFromAssemblyPath(assemblyPath);
}
private string? ResolveAssemblyToPath(AssemblyName assemblyName)
{
if (assemblyName.Name is null) return null;
if (SpecificAssemblyNames.Contains(assemblyName.Name))
{
if (TryResolveSpecificAssemblyToPath(assemblyName, out var specificPath))
return specificPath;
}
if (TryResolveCommonAssemblyToPath(assemblyName, out var commonPath))
return commonPath;
return null;
bool TryResolveCommonAssemblyToPath(AssemblyName assemblyName, [MaybeNullWhen(false)] out string path)
{
path = Path.Combine(_configuration.PatcherCommonAssemblyDir, $"{assemblyName.Name}.dll");
if (File.Exists(path))
return true;
path = null;
return false;
}
bool TryResolveSpecificAssemblyToPath(AssemblyName assemblyName, [MaybeNullWhen(false)] out string path)
{
path = Path.Combine(_configuration.PatcherNetcodeSpecificAssemblyDir, $"{assemblyName.Name}.dll");
if (File.Exists(path))
return true;
path = null;
return false;
}
}
}