-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathExternMocker.cs
72 lines (60 loc) · 1.86 KB
/
ExternMocker.cs
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
namespace VSharp.CSharpUtils;
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using MonoMod.RuntimeDetour;
using MonoMod.Utils;
using System.ComponentModel;
public static class ExternMocker
{
public static readonly bool ExtMocksSupported =
!OperatingSystem.IsMacOS()
|| RuntimeInformation.OSArchitecture == Architecture.X86
|| RuntimeInformation.OSArchitecture == Architecture.X64;
public static readonly bool ShimSupported = Environment.Version.Major <= 6;
private static List<NativeDetour> _detours = new();
public static IntPtr GetExternPtr(string libName, string methodName)
{
var assembly = Assembly.GetCallingAssembly();
if (!NativeLibrary.TryLoad(libName, assembly, null, out IntPtr libRef))
{
throw new Exception("Could not open extern library");
}
return libRef.GetFunction(methodName);
}
public static void BuildAndApplyDetour(IntPtr from, IntPtr to)
{
bool manualApply = PlatformHelper.Is(Platform.MacOS);
var config = new NativeDetourConfig
{
ManualApply = manualApply
};
NativeDetour d = new NativeDetour(from, to, config);
if (manualApply) {
try {
d.Apply();
} catch (Win32Exception) {
try
{
d.Dispose();
}
finally
{
throw new Exception("Could not apply extern mock");
}
}
}
if (!d.IsApplied)
throw new Exception("Could not apply extern mock");
_detours.Add(d);
}
public static void UnPatch()
{
foreach (var d in _detours)
{
d.Undo();
}
_detours.Clear();
}
}