diff --git a/Harmony/Internal/PatchTools.cs b/Harmony/Internal/PatchTools.cs index 3905e29b..65355073 100644 --- a/Harmony/Internal/PatchTools.cs +++ b/Harmony/Internal/PatchTools.cs @@ -65,13 +65,13 @@ internal static MethodBase GetOriginalMethod(this HarmonyMethod attr) case MethodType.Getter: if (attr.methodName is null) - return AccessTools.DeclaredIndexer(attr.declaringType, attr.argumentTypes).GetGetMethod(true); - return AccessTools.DeclaredProperty(attr.declaringType, attr.methodName).GetGetMethod(true); + return AccessTools.DeclaredIndexer(attr.declaringType, attr.argumentTypes)?.GetGetMethod(true); + return AccessTools.DeclaredProperty(attr.declaringType, attr.methodName)?.GetGetMethod(true); case MethodType.Setter: if (attr.methodName is null) - return AccessTools.DeclaredIndexer(attr.declaringType, attr.argumentTypes).GetSetMethod(true); - return AccessTools.DeclaredProperty(attr.declaringType, attr.methodName).GetSetMethod(true); + return AccessTools.DeclaredIndexer(attr.declaringType, attr.argumentTypes)?.GetSetMethod(true); + return AccessTools.DeclaredProperty(attr.declaringType, attr.methodName)?.GetSetMethod(true); case MethodType.Constructor: return AccessTools.DeclaredConstructor(attr.GetDeclaringType(), attr.argumentTypes); diff --git a/Harmony/Public/Attributes.cs b/Harmony/Public/Attributes.cs index 80eb0103..7fe50292 100644 --- a/Harmony/Public/Attributes.cs +++ b/Harmony/Public/Attributes.cs @@ -777,4 +777,18 @@ public HarmonyArgument(int index, string name) NewName = name; } } + + /// Attribute used for optionally patching members that might not exist. + /// Harmony patches with this attribute will not throw an exception and abort the patching process if the target member is not found (a warning is logged instead). + /// + [AttributeUsage(AttributeTargets.Method)] + public class HarmonyOptional : HarmonyAttribute + { + /// Default constructor + /// + public HarmonyOptional() + { + info.optional = true; + } + } } diff --git a/Harmony/Public/HarmonyMethod.cs b/Harmony/Public/HarmonyMethod.cs index dd741713..28f8c4b2 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; + + /// Whether to not throw/abort when trying to patch members that do not exist (skip instead). + /// + public bool? optional; /// Default constructor /// diff --git a/Harmony/Public/PatchClassProcessor.cs b/Harmony/Public/PatchClassProcessor.cs index d05e55e2..6baac2c6 100644 --- a/Harmony/Public/PatchClassProcessor.cs +++ b/Harmony/Public/PatchClassProcessor.cs @@ -59,7 +59,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,6 +128,18 @@ void ReversePatch(ref MethodBase lastOriginal) var annotatedOriginal = patchMethod.info.GetOriginalMethod(); if (annotatedOriginal is object) lastOriginal = annotatedOriginal; + + if (lastOriginal is null) + { + if (patchMethod.info.optional == true) + { + 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(); @@ -171,7 +183,15 @@ List PatchWithAttributes(ref MethodBase lastOriginal) { lastOriginal = patchMethod.info.GetOriginalMethod(); if (lastOriginal is null) + { + if (patchMethod.info.optional == true) + { + 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); diff --git a/HarmonyTests/Patching/Assets/Specials.cs b/HarmonyTests/Patching/Assets/Specials.cs index e8e821f2..3947bcd2 100644 --- a/HarmonyTests/Patching/Assets/Specials.cs +++ b/HarmonyTests/Patching/Assets/Specials.cs @@ -127,6 +127,48 @@ 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(); + + [HarmonyPrefix] + [HarmonyOptional] + [HarmonyPatch(typeof(OptionalPatch), "missing_method1")] + [HarmonyPatch(typeof(OptionalPatch), nameof(Thrower), MethodType.Normal)] + [HarmonyPatch(typeof(OptionalPatch), "missing_method2")] + public static bool Test6() => false; + + private void NotEnumerator() => throw new InvalidOperationException(); + public static void Thrower() => throw new InvalidOperationException(); + } + + public static class OptionalPatchNone + { + [HarmonyPrefix] + [HarmonyPatch(typeof(OptionalPatch), "missing_method1")] + [HarmonyPatch(typeof(OptionalPatchNone), nameof(Thrower), MethodType.Normal)] + [HarmonyPatch(typeof(OptionalPatch), "missing_method2")] + public static bool Test6() => false; + + public static void Thrower() => 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..c6e09168 100644 --- a/HarmonyTests/Patching/Specials.cs +++ b/HarmonyTests/Patching/Specials.cs @@ -42,6 +42,21 @@ public void Test_HttpWebRequestGetResponse() } */ + [Test] + public void Test_Optional_Patch() + { + var instance = new Harmony("special-case-optional-patch"); + Assert.NotNull(instance); + + Assert.Throws(OptionalPatch.Thrower); + Assert.DoesNotThrow(() => instance.PatchAll(typeof(OptionalPatch))); + Assert.DoesNotThrow(OptionalPatch.Thrower); + + Assert.Throws(OptionalPatchNone.Thrower); + Assert.Throws(() => instance.PatchAll(typeof(OptionalPatchNone))); + Assert.Throws(OptionalPatchNone.Thrower); + } + [Test] public void Test_Wrap_Patch() { @@ -185,7 +200,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); }