-
Notifications
You must be signed in to change notification settings - Fork 44
/
ManagedMethodPatcher.cs
72 lines (64 loc) · 1.82 KB
/
ManagedMethodPatcher.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
using HarmonyLib.Internal.Util;
using System;
using System.Reflection;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using MonoMod.Utils;
using MethodBody = Mono.Cecil.Cil.MethodBody;
namespace HarmonyLib.Public.Patching
{
/// <summary>
/// Method patcher for normal managed methods that have IL body attached to them.
/// Uses <see cref="MonoMod.RuntimeDetour.ILHook"/> in order to apply hooks in a way compatible with MonoMod's own
/// hooking system.
/// </summary>
///
public class ManagedMethodPatcher : MethodPatcher
{
private MethodBody hookBody;
private ILHook ilHook;
/// <inheritdoc />
public ManagedMethodPatcher(MethodBase original) : base(original) { }
/// <inheritdoc />
public override DynamicMethodDefinition PrepareOriginal()
{
return null;
}
/// <inheritdoc />
public override MethodBase DetourTo(MethodBase replacement)
{
ilHook ??= new ILHook(Original, Manipulator, applyByDefault: false);
try
{
ilHook.Undo();
ilHook.Apply();
}
catch (Exception e)
{
throw HarmonyException.Create(e, hookBody);
}
return ilHook.GetEndOfChain();
}
/// <inheritdoc />
public override DynamicMethodDefinition CopyOriginal()
{
return new DynamicMethodDefinition(Original);
}
private void Manipulator(ILContext ctx)
{
hookBody = ctx.Body;
HarmonyManipulator.Manipulate(Original, ctx);
}
/// <summary>
/// A handler for <see cref="PatchManager.ResolvePatcher"/> that checks if a method is a normal Managed method.
/// </summary>
/// <param name="sender">Not used</param>
/// <param name="args">Patch resolver arguments</param>
///
public static void TryResolve(object sender, PatchManager.PatcherResolverEventArgs args)
{
if (args.Original.GetMethodBody() != null)
args.MethodPatcher = new ManagedMethodPatcher(args.Original);
}
}
}