-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHarmonyExt.cs
201 lines (185 loc) · 8.62 KB
/
HarmonyExt.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
using HarmonyLib;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Shockah.Shared;
public static class HarmonyExt
{
public static void PatchVirtual(
this Harmony self,
MethodBase? original,
ILogger logger,
LogLevel problemLogLevel = LogLevel.Error,
LogLevel successLogLevel = LogLevel.Trace,
HarmonyMethod? prefix = null,
HarmonyMethod? postfix = null,
HarmonyMethod? transpiler = null,
HarmonyMethod? finalizer = null
)
{
if (original is null)
{
logger.Log(problemLogLevel, "Could not patch method - the mod may not work correctly.\nReason: Unknown method to patch.");
return;
}
Type? declaringType = original.DeclaringType;
if (declaringType == null)
throw new ArgumentException($"{nameof(original)}.{nameof(original.DeclaringType)} is null.");
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
IEnumerable<Type> subtypes = Enumerable.Empty<Type>();
try
{
subtypes = assembly.GetTypes().Where(t => t.IsAssignableTo(declaringType));
}
catch (Exception ex)
{
logger.Log(LogLevel.Trace, "There was a problem while getting types defined in assembly {Assembly}, ignoring it. Reason:\n{Exception}", assembly.GetName().Name, ex);
}
foreach (Type subtype in subtypes)
{
var originalParameters = original.GetParameters();
var subtypeOriginal = AccessTools.Method(
subtype,
original.Name,
originalParameters.Select(p => p.ParameterType).ToArray()
);
if (subtypeOriginal is null)
continue;
if (!subtypeOriginal.IsDeclaredMember())
continue;
if (!subtypeOriginal.HasMethodBody())
continue;
static bool ContainsNonSpecialArguments(HarmonyMethod patch)
=> patch.method.GetParameters().Any(p => !(p.Name ?? "").StartsWith("__"));
if (
(prefix is not null && ContainsNonSpecialArguments(prefix)) ||
(postfix is not null && ContainsNonSpecialArguments(postfix)) ||
(finalizer is not null && ContainsNonSpecialArguments(finalizer))
)
{
var subtypeOriginalParameters = subtypeOriginal.GetParameters();
for (int i = 0; i < original.GetParameters().Length; i++)
if (originalParameters[i].Name != subtypeOriginalParameters[i].Name)
throw new InvalidOperationException($"Method {declaringType.Name}.{original.Name} cannot be automatically patched for subtype {subtype.Name}, because argument #{i} has a mismatched name: `{originalParameters[i].Name}` vs `{subtypeOriginalParameters[i].Name}`.");
}
self.Patch(subtypeOriginal, prefix, subtypeOriginal.HasMethodBody() ? postfix : null, transpiler, finalizer);
logger.Log(successLogLevel, "Patched method {Method}.", subtypeOriginal.FullDescription());
}
}
}
public static bool TryPatch(
this Harmony self,
Func<MethodBase?> original,
ILogger logger,
LogLevel problemLogLevel = LogLevel.Error,
LogLevel successLogLevel = LogLevel.Trace,
HarmonyMethod? prefix = null,
HarmonyMethod? postfix = null,
HarmonyMethod? transpiler = null,
HarmonyMethod? finalizer = null
)
{
var originalMethod = original();
if (originalMethod is null)
{
logger.Log(problemLogLevel, "Could not patch method - the mod may not work correctly.\nReason: Unknown method to patch.");
return false;
}
try
{
self.Patch(originalMethod, prefix, postfix, transpiler, finalizer);
logger.Log(successLogLevel, "Patched method {Method}.", originalMethod.FullDescription());
return true;
}
catch (Exception ex)
{
logger.Log(problemLogLevel, "Could not patch method {Method} - the mod may not work correctly.\nReason: {Exception}", originalMethod, ex);
return false;
}
}
public static (int patched, int total) TryPatchVirtual(
this Harmony self,
Func<MethodBase?> original,
ILogger logger,
LogLevel problemLogLevel = LogLevel.Error,
LogLevel successLogLevel = LogLevel.Trace,
HarmonyMethod? prefix = null,
HarmonyMethod? postfix = null,
HarmonyMethod? transpiler = null,
HarmonyMethod? finalizer = null
)
{
var originalMethod = original();
if (originalMethod is null)
{
logger.Log(problemLogLevel, "Could not patch method - the mod may not work correctly.\nReason: Unknown method to patch.");
return (0, 1);
}
try
{
int patched = 0;
int total = 0;
Type declaringType = originalMethod.DeclaringType ?? throw new ArgumentException($"{nameof(original)}.{nameof(originalMethod.DeclaringType)} is null.");
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
total++;
IEnumerable<Type> subtypes = Enumerable.Empty<Type>();
try
{
subtypes = assembly.GetTypes().Where(t => t.IsAssignableTo(declaringType));
}
catch (Exception ex)
{
logger.Log(LogLevel.Trace, "There was a problem while getting types defined in assembly {Assembly}, ignoring it. Reason:\n{Exception}", assembly.GetName().Name, ex);
}
foreach (Type subtype in subtypes)
{
try
{
var originalParameters = originalMethod.GetParameters();
var subtypeOriginal = AccessTools.Method(
subtype,
originalMethod.Name,
originalParameters.Select(p => p.ParameterType).ToArray()
);
if (subtypeOriginal is null)
continue;
if (!subtypeOriginal.IsDeclaredMember())
continue;
if (!subtypeOriginal.HasMethodBody())
continue;
static bool ContainsNonSpecialArguments(HarmonyMethod patch)
=> patch.method.GetParameters().Any(p => !(p.Name ?? "").StartsWith("__"));
if (
(prefix is not null && ContainsNonSpecialArguments(prefix)) ||
(postfix is not null && ContainsNonSpecialArguments(postfix)) ||
(finalizer is not null && ContainsNonSpecialArguments(finalizer))
)
{
var subtypeOriginalParameters = subtypeOriginal.GetParameters();
for (int i = 0; i < originalMethod.GetParameters().Length; i++)
if (originalParameters[i].Name != subtypeOriginalParameters[i].Name)
throw new InvalidOperationException($"Method {declaringType.Name}.{originalMethod.Name} cannot be automatically patched for subtype {subtype.Name}, because argument #{i} has a mismatched name: `{originalParameters[i].Name}` vs `{subtypeOriginalParameters[i].Name}`.");
}
self.Patch(subtypeOriginal, prefix, postfix, transpiler, finalizer);
logger.Log(successLogLevel, "Patched method {Method}.", subtypeOriginal.FullDescription());
patched++;
}
catch (Exception ex)
{
logger.Log(problemLogLevel, "Could not patch method - the mod may not work correctly.\nReason: {Exception}", ex);
}
}
}
return (patched, total);
}
catch (Exception ex)
{
logger.Log(problemLogLevel, "Could not patch method {Method} - the mod may not work correctly.\nReason: {Exception}", originalMethod, ex);
return (0, 1);
}
}
}