From 463db2c82f11d5fa96da93f021a89b6d655f5858 Mon Sep 17 00:00:00 2001 From: Andreas Pardeike Date: Tue, 24 Jul 2018 21:17:59 +0200 Subject: [PATCH] Fix self patching --- Harmony/Tools/SelfPatching.cs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/Harmony/Tools/SelfPatching.cs b/Harmony/Tools/SelfPatching.cs index 250ff5ac..e992d87f 100644 --- a/Harmony/Tools/SelfPatching.cs +++ b/Harmony/Tools/SelfPatching.cs @@ -9,10 +9,15 @@ namespace Harmony.Tools { internal class SelfPatching { + static readonly string upgradeToLatestVersionFullName = typeof(UpgradeToLatestVersion).FullName; static int GetVersion(MethodInfo method) { - var attribute = method.GetCustomAttributes(false).OfType().FirstOrDefault(); - return attribute?.version ?? -1; + var attribute = method.GetCustomAttributes(false) + .Where(attr => attr.GetType().FullName == upgradeToLatestVersionFullName) + .FirstOrDefault(); + if (attribute == null) + return -1; + return Traverse.Create(attribute).Field("version").GetValue(); } static string MethodKey(MethodInfo method) @@ -42,13 +47,14 @@ static bool IsHarmonyAssembly(Assembly assembly) public static void PatchOldHarmonyMethods() { var potentialMethodsToUpgrade = new Dictionary(); - typeof(SelfPatching).Assembly.GetTypes() + var ourAssembly = typeof(SelfPatching).Assembly; + ourAssembly.GetTypes() .SelectMany(type => type.GetMethods(AccessTools.all)) .Where(method => method.GetCustomAttributes(false).Any(attr => attr is UpgradeToLatestVersion)) .Do(method => potentialMethodsToUpgrade.Add(MethodKey(method), method)); AppDomain.CurrentDomain.GetAssemblies() - .Where(assembly => IsHarmonyAssembly(assembly)) + .Where(assembly => IsHarmonyAssembly(assembly) && assembly != ourAssembly) .SelectMany(assembly => assembly.GetTypes()) .SelectMany(type => type.GetMethods(AccessTools.all)) .Select(method => @@ -56,11 +62,15 @@ public static void PatchOldHarmonyMethods() potentialMethodsToUpgrade.TryGetValue(MethodKey(method), out var newMethod); return new KeyValuePair(method, newMethod); }) - .Do(pair => + .DoIf(pair => pair.Value != null, pair => { var oldMethod = pair.Key; + var oldVersion = GetVersion(oldMethod); + var newMethod = pair.Value; - if (newMethod != null && GetVersion(oldMethod) < GetVersion(newMethod)) + var newVersion = GetVersion(newMethod); + + if (oldVersion != -1 && newVersion != -1 && oldVersion < newVersion) { if (patchedMethods.Contains(oldMethod) == false) {