From baa51ffea1bf25f4900bbe4b85ea8efbc6f103a6 Mon Sep 17 00:00:00 2001 From: ManlyMarco <39247311+ManlyMarco@users.noreply.github.com> Date: Tue, 23 Jan 2024 11:46:45 +0100 Subject: [PATCH] Add HarmonyOptional attribute --- Harmony/Public/Attributes.cs | 27 +++++++++++++++++++ Harmony/Public/HarmonyMethod.cs | 4 +++ Harmony/Public/PatchClassProcessor.cs | 28 ++++++++++++++++++- HarmonyTests/Patching/Assets/Specials.cs | 34 ++++++++++++++++++++++++ HarmonyTests/Patching/Specials.cs | 13 ++++++++- 5 files changed, 104 insertions(+), 2 deletions(-) diff --git a/Harmony/Public/Attributes.cs b/Harmony/Public/Attributes.cs index 80eb0103..ac37b59d 100644 --- a/Harmony/Public/Attributes.cs +++ b/Harmony/Public/Attributes.cs @@ -777,4 +777,31 @@ public HarmonyArgument(int index, string name) NewName = name; } } + + /// Flags used for optionally patching members that might not exist. + /// + [Flags] + public enum OptionalFlags + { + /// Default behavior (throw and abort patching if there are no matches). + /// + None = 0, + + /// Do not throw an exception and abort the patching process if no matches are found (a warning is logged instead). + /// + AllowNoMatches = 1 << 1, + } + + /// Attribute used for optionally patching members that might not exist. + /// + [AttributeUsage(AttributeTargets.Method)] + public class HarmonyOptional : HarmonyAttribute + { + /// Default constructor + /// + public HarmonyOptional(OptionalFlags flags = OptionalFlags.AllowNoMatches) + { + info.optionalFlags = flags; + } + } } diff --git a/Harmony/Public/HarmonyMethod.cs b/Harmony/Public/HarmonyMethod.cs index dd741713..c72c9a55 100644 --- a/Harmony/Public/HarmonyMethod.cs +++ b/Harmony/Public/HarmonyMethod.cs @@ -66,6 +66,10 @@ public class HarmonyMethod /// Whether to wrap the patch itself into a try/catch. /// public bool? wrapTryCatch; + + /// Flags used for optionally patching members that might not exist. + /// + public OptionalFlags? optionalFlags; /// Default constructor /// diff --git a/Harmony/Public/PatchClassProcessor.cs b/Harmony/Public/PatchClassProcessor.cs index e5817b11..5460b67a 100644 --- a/Harmony/Public/PatchClassProcessor.cs +++ b/Harmony/Public/PatchClassProcessor.cs @@ -5,6 +5,7 @@ using System.Text; using HarmonyLib.Public.Patching; using HarmonyLib.Tools; +using MonoMod.Utils; namespace HarmonyLib { @@ -59,7 +60,7 @@ public PatchClassProcessor(Harmony instance, Type type, bool allowUnannotatedTyp containerAttributes = HarmonyMethod.Merge(harmonyAttributes); if (containerAttributes.methodType is null) // MethodType default is Normal containerAttributes.methodType = MethodType.Normal; - + this.Category = containerAttributes.category; auxilaryMethods = new Dictionary(); @@ -128,8 +129,18 @@ void ReversePatch(ref MethodBase lastOriginal) var annotatedOriginal = patchMethod.info.GetOriginalMethod(); if (annotatedOriginal is object) lastOriginal = annotatedOriginal; + if (lastOriginal is null) + { + if (IsPatchOptional(patchMethod)) + { + Logger.Log(Logger.LogChannel.Warn, () => $"Skipping optional reverse patch {patchMethod.info.method.FullDescription()} - target method not found"); + continue; + } + throw new ArgumentException($"Undefined target method for reverse patch method {patchMethod.info.method.FullDescription()}"); + } + var reversePatcher = instance.CreateReversePatcher(lastOriginal, patchMethod.info); lock (PatchProcessor.locker) _ = reversePatcher.Patch(); @@ -173,7 +184,15 @@ List PatchWithAttributes(ref MethodBase lastOriginal) { lastOriginal = patchMethod.info.GetOriginalMethod(); if (lastOriginal is null) + { + if (IsPatchOptional(patchMethod)) + { + Logger.Log(Logger.LogChannel.Warn, () => $"Skipping optional patch {patchMethod.info.method.FullDescription()} - target method not found"); + continue; + } + throw new ArgumentException($"Undefined target method for patch method {patchMethod.info.method.FullDescription()}"); + } var job = jobs.GetJob(lastOriginal); job.AddPatch(patchMethod); @@ -186,6 +205,13 @@ List PatchWithAttributes(ref MethodBase lastOriginal) return jobs.GetReplacements(); } + static bool IsPatchOptional(AttributePatch patchMethod) + { + var optionalFlags = patchMethod.info.optionalFlags; + var isOptional = optionalFlags != null && optionalFlags.Value.Has(OptionalFlags.AllowNoMatches); + return isOptional; + } + void ProcessPatchJob(PatchJobs.Job job) { MethodInfo replacement = default; diff --git a/HarmonyTests/Patching/Assets/Specials.cs b/HarmonyTests/Patching/Assets/Specials.cs index e8e821f2..4eb1a0a6 100644 --- a/HarmonyTests/Patching/Assets/Specials.cs +++ b/HarmonyTests/Patching/Assets/Specials.cs @@ -127,6 +127,40 @@ public static void ReplaceGetValue(ref bool __result) } } + public class OptionalPatch + { + [HarmonyPrefix, HarmonyOptional, HarmonyPatch(typeof(OptionalPatch), "missing_method")] + public static void Test0() => throw new InvalidOperationException(); + + [HarmonyReversePatch, HarmonyOptional, HarmonyPatch(typeof(OptionalPatch), "missing_method")] + public static void Test1() => throw new InvalidOperationException(); + + [HarmonyPostfix, HarmonyOptional, HarmonyPatch(typeof(OptionalPatch), MethodType.Constructor, typeof(string))] + public static void Test2() => throw new InvalidOperationException(); + + [HarmonyTranspiler, HarmonyOptional, HarmonyPatch(typeof(OptionalPatch), "missing_method", MethodType.Getter)] + public static void Test3() => throw new InvalidOperationException(); + + [HarmonyPostfix, HarmonyOptional, HarmonyPatch(typeof(OptionalPatch), nameof(NotEnumerator), MethodType.Enumerator)] + public static void Test4() => throw new InvalidOperationException(); + + [HarmonyPostfix, HarmonyOptional, HarmonyPatch(typeof(OptionalPatch), nameof(NotEnumerator), MethodType.Async)] + public static void Test5() => throw new InvalidOperationException(); + + private void NotEnumerator() => throw new InvalidOperationException(); + } + + public static class OptionalPatchNone + { + [HarmonyPrefix] + [HarmonyOptional(OptionalFlags.None)] + [HarmonyPatch(typeof(OptionalPatch), "missing_method")] + public static void Prefix() + { + throw new InvalidOperationException(); + } + } + public static class SafeWrapPatch { public static bool called = false; diff --git a/HarmonyTests/Patching/Specials.cs b/HarmonyTests/Patching/Specials.cs index 7800c3ad..917657d5 100644 --- a/HarmonyTests/Patching/Specials.cs +++ b/HarmonyTests/Patching/Specials.cs @@ -42,6 +42,17 @@ public void Test_HttpWebRequestGetResponse() } */ + [Test] + public void Test_Optional_Patch() + { + var instance = new Harmony("special-case-optional-patch"); + Assert.NotNull(instance); + + Assert.DoesNotThrow(() => instance.PatchAll(typeof(OptionalPatch))); + + Assert.Throws(() => instance.PatchAll(typeof(OptionalPatchNone))); + } + [Test] public void Test_Wrap_Patch() { @@ -185,7 +196,7 @@ public void Test_Enumerator_Patch() Assert.AreEqual("MoveNext", EnumeratorPatch.patchTarget.Name); var testObject = new EnumeratorCode(); - Assert.AreEqual(new []{ 1, 2, 3, 4, 5 }, testObject.NumberEnumerator().ToArray()); + Assert.AreEqual(new[] { 1, 2, 3, 4, 5 }, testObject.NumberEnumerator().ToArray()); Assert.AreEqual(6, EnumeratorPatch.runTimes); }