From e08979acd301792435661d2c0008469a800f8dbb Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 5 May 2020 20:49:05 -0400 Subject: migrate to Harmony 2.0 (#711) --- src/SMAPI/Framework/Patching/GamePatcher.cs | 4 ++-- src/SMAPI/Framework/Patching/IHarmonyPatch.cs | 4 ++-- src/SMAPI/Framework/PerformanceMonitoring/PerformanceCounter.cs | 3 +-- src/SMAPI/Patches/DialogueErrorPatch.cs | 4 ++-- src/SMAPI/Patches/EventErrorPatch.cs | 4 ++-- src/SMAPI/Patches/LoadContextPatch.cs | 4 ++-- src/SMAPI/Patches/LoadErrorPatch.cs | 4 ++-- src/SMAPI/Patches/ObjectErrorPatch.cs | 4 ++-- src/SMAPI/Patches/ScheduleErrorPatch.cs | 4 ++-- src/SMAPI/SMAPI.csproj | 2 +- 10 files changed, 18 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/SMAPI/Framework/Patching/GamePatcher.cs b/src/SMAPI/Framework/Patching/GamePatcher.cs index f82159d0..cdb54453 100644 --- a/src/SMAPI/Framework/Patching/GamePatcher.cs +++ b/src/SMAPI/Framework/Patching/GamePatcher.cs @@ -1,5 +1,5 @@ using System; -using Harmony; +using HarmonyLib; namespace StardewModdingAPI.Framework.Patching { @@ -27,7 +27,7 @@ namespace StardewModdingAPI.Framework.Patching /// The patches to apply. public void Apply(params IHarmonyPatch[] patches) { - HarmonyInstance harmony = HarmonyInstance.Create("io.smapi"); + Harmony harmony = new Harmony("io.smapi"); foreach (IHarmonyPatch patch in patches) { try diff --git a/src/SMAPI/Framework/Patching/IHarmonyPatch.cs b/src/SMAPI/Framework/Patching/IHarmonyPatch.cs index cb42f40e..7d5eb3d4 100644 --- a/src/SMAPI/Framework/Patching/IHarmonyPatch.cs +++ b/src/SMAPI/Framework/Patching/IHarmonyPatch.cs @@ -1,4 +1,4 @@ -using Harmony; +using HarmonyLib; namespace StardewModdingAPI.Framework.Patching { @@ -10,6 +10,6 @@ namespace StardewModdingAPI.Framework.Patching /// Apply the Harmony patch. /// The Harmony instance. - void Apply(HarmonyInstance harmony); + void Apply(Harmony harmony); } } diff --git a/src/SMAPI/Framework/PerformanceMonitoring/PerformanceCounter.cs b/src/SMAPI/Framework/PerformanceMonitoring/PerformanceCounter.cs index 3cf668ee..42825999 100644 --- a/src/SMAPI/Framework/PerformanceMonitoring/PerformanceCounter.cs +++ b/src/SMAPI/Framework/PerformanceMonitoring/PerformanceCounter.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Harmony; namespace StardewModdingAPI.Framework.PerformanceMonitoring { @@ -57,7 +56,7 @@ namespace StardewModdingAPI.Framework.PerformanceMonitoring // add entry if (this.Entries.Count > this.MaxEntries) this.Entries.Pop(); - this.Entries.Add(entry); + this.Entries.Push(entry); // update metrics if (this.PeakPerformanceCounterEntry == null || entry.ElapsedMilliseconds > this.PeakPerformanceCounterEntry.Value.ElapsedMilliseconds) diff --git a/src/SMAPI/Patches/DialogueErrorPatch.cs b/src/SMAPI/Patches/DialogueErrorPatch.cs index 1e49826d..80029540 100644 --- a/src/SMAPI/Patches/DialogueErrorPatch.cs +++ b/src/SMAPI/Patches/DialogueErrorPatch.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Reflection; -using Harmony; +using HarmonyLib; using StardewModdingAPI.Framework.Patching; using StardewModdingAPI.Framework.Reflection; using StardewValley; @@ -47,7 +47,7 @@ namespace StardewModdingAPI.Patches /// Apply the Harmony patch. /// The Harmony instance. - public void Apply(HarmonyInstance harmony) + public void Apply(Harmony harmony) { harmony.Patch( original: AccessTools.Constructor(typeof(Dialogue), new[] { typeof(string), typeof(NPC) }), diff --git a/src/SMAPI/Patches/EventErrorPatch.cs b/src/SMAPI/Patches/EventErrorPatch.cs index 504d1d2e..a2b94e8b 100644 --- a/src/SMAPI/Patches/EventErrorPatch.cs +++ b/src/SMAPI/Patches/EventErrorPatch.cs @@ -1,6 +1,6 @@ using System.Diagnostics.CodeAnalysis; using System.Reflection; -using Harmony; +using HarmonyLib; using StardewModdingAPI.Framework.Patching; using StardewValley; @@ -38,7 +38,7 @@ namespace StardewModdingAPI.Patches /// Apply the Harmony patch. /// The Harmony instance. - public void Apply(HarmonyInstance harmony) + public void Apply(Harmony harmony) { harmony.Patch( original: AccessTools.Method(typeof(GameLocation), "checkEventPrecondition"), diff --git a/src/SMAPI/Patches/LoadContextPatch.cs b/src/SMAPI/Patches/LoadContextPatch.cs index 0cc8c8eb..9c707676 100644 --- a/src/SMAPI/Patches/LoadContextPatch.cs +++ b/src/SMAPI/Patches/LoadContextPatch.cs @@ -1,6 +1,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using Harmony; +using HarmonyLib; using StardewModdingAPI.Enums; using StardewModdingAPI.Framework.Patching; using StardewModdingAPI.Framework.Reflection; @@ -47,7 +47,7 @@ namespace StardewModdingAPI.Patches /// Apply the Harmony patch. /// The Harmony instance. - public void Apply(HarmonyInstance harmony) + public void Apply(Harmony harmony) { // detect CreatedBasicInfo harmony.Patch( diff --git a/src/SMAPI/Patches/LoadErrorPatch.cs b/src/SMAPI/Patches/LoadErrorPatch.cs index 77415ff2..f8ad6693 100644 --- a/src/SMAPI/Patches/LoadErrorPatch.cs +++ b/src/SMAPI/Patches/LoadErrorPatch.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; -using Harmony; +using HarmonyLib; using StardewModdingAPI.Framework.Exceptions; using StardewModdingAPI.Framework.Patching; using StardewValley; @@ -49,7 +49,7 @@ namespace StardewModdingAPI.Patches /// Apply the Harmony patch. /// The Harmony instance. - public void Apply(HarmonyInstance harmony) + public void Apply(Harmony harmony) { harmony.Patch( original: AccessTools.Method(typeof(SaveGame), nameof(SaveGame.loadDataToLocations)), diff --git a/src/SMAPI/Patches/ObjectErrorPatch.cs b/src/SMAPI/Patches/ObjectErrorPatch.cs index d3b8800a..b9655043 100644 --- a/src/SMAPI/Patches/ObjectErrorPatch.cs +++ b/src/SMAPI/Patches/ObjectErrorPatch.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Reflection; -using Harmony; +using HarmonyLib; using StardewModdingAPI.Framework.Patching; using StardewValley; using StardewValley.Menus; @@ -27,7 +27,7 @@ namespace StardewModdingAPI.Patches *********/ /// Apply the Harmony patch. /// The Harmony instance. - public void Apply(HarmonyInstance harmony) + public void Apply(Harmony harmony) { // object.getDescription harmony.Patch( diff --git a/src/SMAPI/Patches/ScheduleErrorPatch.cs b/src/SMAPI/Patches/ScheduleErrorPatch.cs index 799fcb40..386230a6 100644 --- a/src/SMAPI/Patches/ScheduleErrorPatch.cs +++ b/src/SMAPI/Patches/ScheduleErrorPatch.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Reflection; -using Harmony; +using HarmonyLib; using StardewModdingAPI.Framework.Patching; using StardewValley; @@ -39,7 +39,7 @@ namespace StardewModdingAPI.Patches /// Apply the Harmony patch. /// The Harmony instance. - public void Apply(HarmonyInstance harmony) + public void Apply(Harmony harmony) { harmony.Patch( original: AccessTools.Method(typeof(NPC), "parseMasterSchedule"), diff --git a/src/SMAPI/SMAPI.csproj b/src/SMAPI/SMAPI.csproj index 5f41387b..1755b9e7 100644 --- a/src/SMAPI/SMAPI.csproj +++ b/src/SMAPI/SMAPI.csproj @@ -16,7 +16,7 @@ - + -- cgit From 2d37fe6819dd15a6e995ea55d625179106c22cd7 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 5 May 2020 20:54:25 -0400 Subject: rename files for upcoming change (#711) --- .../Framework/ModLoading/Finders/TypeFinder.cs | 139 ------------------- .../ModLoading/Framework/BaseTypeFinder.cs | 139 +++++++++++++++++++ .../Framework/BaseTypeReferenceRewriter.cs | 151 ++++++++++++++++++++ .../ModLoading/Rewriters/TypeReferenceRewriter.cs | 152 --------------------- src/SMAPI/Metadata/InstructionMetadata.cs | 1 + 5 files changed, 291 insertions(+), 291 deletions(-) delete mode 100644 src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs create mode 100644 src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs create mode 100644 src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs delete mode 100644 src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs (limited to 'src') diff --git a/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs deleted file mode 100644 index 701b15f2..00000000 --- a/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using System.Linq; -using Mono.Cecil; -using Mono.Cecil.Cil; - -namespace StardewModdingAPI.Framework.ModLoading.Finders -{ - /// Finds incompatible CIL instructions that reference a given type. - internal class TypeFinder : IInstructionHandler - { - /********* - ** Accessors - *********/ - /// The full type name for which to find references. - private readonly string FullTypeName; - - /// The result to return for matching instructions. - private readonly InstructionHandleResult Result; - - /// A lambda which overrides a matched type. - protected readonly Func ShouldIgnore; - - - /********* - ** Accessors - *********/ - /// A brief noun phrase indicating what the instruction finder matches. - public string NounPhrase { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The full type name to match. - /// The result to return for matching instructions. - /// A lambda which overrides a matched type. - public TypeFinder(string fullTypeName, InstructionHandleResult result, Func shouldIgnore = null) - { - this.FullTypeName = fullTypeName; - this.Result = result; - this.NounPhrase = $"{fullTypeName} type"; - this.ShouldIgnore = shouldIgnore ?? (p => false); - } - - /// Perform the predefined logic for a method if applicable. - /// The assembly module containing the instruction. - /// The method definition containing the instruction. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - return this.IsMatch(method) - ? this.Result - : InstructionHandleResult.None; - } - - /// Perform the predefined logic for an instruction if applicable. - /// The assembly module containing the instruction. - /// The CIL processor. - /// The instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - return this.IsMatch(instruction) - ? this.Result - : InstructionHandleResult.None; - } - - - /********* - ** Protected methods - *********/ - /// Get whether a CIL instruction matches. - /// The method definition. - protected bool IsMatch(MethodDefinition method) - { - if (this.IsMatch(method.ReturnType)) - return true; - - foreach (VariableDefinition variable in method.Body.Variables) - { - if (this.IsMatch(variable.VariableType)) - return true; - } - - return false; - } - - /// Get whether a CIL instruction matches. - /// The IL instruction. - protected bool IsMatch(Instruction instruction) - { - // field reference - FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); - if (fieldRef != null) - { - return - this.IsMatch(fieldRef.DeclaringType) // field on target class - || this.IsMatch(fieldRef.FieldType); // field value is target class - } - - // method reference - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); - if (methodRef != null) - { - return - this.IsMatch(methodRef.DeclaringType) // method on target class - || this.IsMatch(methodRef.ReturnType) // method returns target class - || methodRef.Parameters.Any(p => this.IsMatch(p.ParameterType)); // method parameters - } - - return false; - } - - /// Get whether a type reference matches the expected type. - /// The type to check. - protected bool IsMatch(TypeReference type) - { - // root type - if (type.FullName == this.FullTypeName && !this.ShouldIgnore(type)) - return true; - - // generic arguments - if (type is GenericInstanceType genericType) - { - if (genericType.GenericArguments.Any(this.IsMatch)) - return true; - } - - // generic parameters (e.g. constraints) - if (type.GenericParameters.Any(this.IsMatch)) - return true; - - return false; - } - } -} diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs new file mode 100644 index 00000000..170bbb48 --- /dev/null +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs @@ -0,0 +1,139 @@ +using System; +using System.Linq; +using Mono.Cecil; +using Mono.Cecil.Cil; + +namespace StardewModdingAPI.Framework.ModLoading.Framework +{ + /// Finds incompatible CIL instructions that reference a given type. + internal class TypeFinder : IInstructionHandler + { + /********* + ** Accessors + *********/ + /// The full type name for which to find references. + private readonly string FullTypeName; + + /// The result to return for matching instructions. + private readonly InstructionHandleResult Result; + + /// A lambda which overrides a matched type. + protected readonly Func ShouldIgnore; + + + /********* + ** Accessors + *********/ + /// A brief noun phrase indicating what the instruction finder matches. + public string NounPhrase { get; } + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The full type name to match. + /// The result to return for matching instructions. + /// A lambda which overrides a matched type. + public TypeFinder(string fullTypeName, InstructionHandleResult result, Func shouldIgnore = null) + { + this.FullTypeName = fullTypeName; + this.Result = result; + this.NounPhrase = $"{fullTypeName} type"; + this.ShouldIgnore = shouldIgnore ?? (p => false); + } + + /// Perform the predefined logic for a method if applicable. + /// The assembly module containing the instruction. + /// The method definition containing the instruction. + /// Metadata for mapping assemblies to the current platform. + /// Whether the mod was compiled on a different platform. + public virtual InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) + { + return this.IsMatch(method) + ? this.Result + : InstructionHandleResult.None; + } + + /// Perform the predefined logic for an instruction if applicable. + /// The assembly module containing the instruction. + /// The CIL processor. + /// The instruction to handle. + /// Metadata for mapping assemblies to the current platform. + /// Whether the mod was compiled on a different platform. + public virtual InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + { + return this.IsMatch(instruction) + ? this.Result + : InstructionHandleResult.None; + } + + + /********* + ** Protected methods + *********/ + /// Get whether a CIL instruction matches. + /// The method definition. + protected bool IsMatch(MethodDefinition method) + { + if (this.IsMatch(method.ReturnType)) + return true; + + foreach (VariableDefinition variable in method.Body.Variables) + { + if (this.IsMatch(variable.VariableType)) + return true; + } + + return false; + } + + /// Get whether a CIL instruction matches. + /// The IL instruction. + protected bool IsMatch(Instruction instruction) + { + // field reference + FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + if (fieldRef != null) + { + return + this.IsMatch(fieldRef.DeclaringType) // field on target class + || this.IsMatch(fieldRef.FieldType); // field value is target class + } + + // method reference + MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + if (methodRef != null) + { + return + this.IsMatch(methodRef.DeclaringType) // method on target class + || this.IsMatch(methodRef.ReturnType) // method returns target class + || methodRef.Parameters.Any(p => this.IsMatch(p.ParameterType)); // method parameters + } + + return false; + } + + /// Get whether a type reference matches the expected type. + /// The type to check. + protected bool IsMatch(TypeReference type) + { + // root type + if (type.FullName == this.FullTypeName && !this.ShouldIgnore(type)) + return true; + + // generic arguments + if (type is GenericInstanceType genericType) + { + if (genericType.GenericArguments.Any(this.IsMatch)) + return true; + } + + // generic parameters (e.g. constraints) + if (type.GenericParameters.Any(this.IsMatch)) + return true; + + return false; + } + } +} diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs new file mode 100644 index 00000000..8c2d11c8 --- /dev/null +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs @@ -0,0 +1,151 @@ +using System; +using Mono.Cecil; +using Mono.Cecil.Cil; + +namespace StardewModdingAPI.Framework.ModLoading.Framework +{ + /// Rewrites all references to a type. + internal class TypeReferenceRewriter : TypeFinder + { + /********* + ** Fields + *********/ + /// The full type name to which to find references. + private readonly string FromTypeName; + + /// The new type to reference. + private readonly Type ToType; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The full type name to which to find references. + /// The new type to reference. + /// A lambda which overrides a matched type. + public TypeReferenceRewriter(string fromTypeFullName, Type toType, Func shouldIgnore = null) + : base(fromTypeFullName, InstructionHandleResult.None, shouldIgnore) + { + this.FromTypeName = fromTypeFullName; + this.ToType = toType; + } + + /// Perform the predefined logic for a method if applicable. + /// The assembly module containing the instruction. + /// The method definition containing the instruction. + /// Metadata for mapping assemblies to the current platform. + /// Whether the mod was compiled on a different platform. + public override InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) + { + bool rewritten = false; + + // return type + if (this.IsMatch(method.ReturnType)) + { + this.RewriteIfNeeded(module, method.ReturnType, newType => method.ReturnType = newType); + rewritten = true; + } + + // parameters + foreach (ParameterDefinition parameter in method.Parameters) + { + if (this.IsMatch(parameter.ParameterType)) + { + this.RewriteIfNeeded(module, parameter.ParameterType, newType => parameter.ParameterType = newType); + rewritten = true; + } + } + + // generic parameters + for (int i = 0; i < method.GenericParameters.Count; i++) + { + var parameter = method.GenericParameters[i]; + if (this.IsMatch(parameter)) + { + this.RewriteIfNeeded(module, parameter, newType => method.GenericParameters[i] = new GenericParameter(parameter.Name, newType)); + rewritten = true; + } + } + + // local variables + foreach (VariableDefinition variable in method.Body.Variables) + { + if (this.IsMatch(variable.VariableType)) + { + this.RewriteIfNeeded(module, variable.VariableType, newType => variable.VariableType = newType); + rewritten = true; + } + } + + return rewritten + ? InstructionHandleResult.Rewritten + : InstructionHandleResult.None; + } + + /// Perform the predefined logic for an instruction if applicable. + /// The assembly module containing the instruction. + /// The CIL processor. + /// The instruction to handle. + /// Metadata for mapping assemblies to the current platform. + /// Whether the mod was compiled on a different platform. + public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + { + if (!this.IsMatch(instruction)) + return InstructionHandleResult.None; + + // field reference + FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + if (fieldRef != null) + { + this.RewriteIfNeeded(module, fieldRef.DeclaringType, newType => fieldRef.DeclaringType = newType); + this.RewriteIfNeeded(module, fieldRef.FieldType, newType => fieldRef.FieldType = newType); + } + + // method reference + MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + if (methodRef != null) + { + this.RewriteIfNeeded(module, methodRef.DeclaringType, newType => methodRef.DeclaringType = newType); + this.RewriteIfNeeded(module, methodRef.ReturnType, newType => methodRef.ReturnType = newType); + foreach (var parameter in methodRef.Parameters) + this.RewriteIfNeeded(module, parameter.ParameterType, newType => parameter.ParameterType = newType); + } + + // type reference + if (instruction.Operand is TypeReference typeRef) + this.RewriteIfNeeded(module, typeRef, newType => cil.Replace(instruction, cil.Create(instruction.OpCode, newType))); + + return InstructionHandleResult.Rewritten; + } + + /********* + ** Private methods + *********/ + /// Change a type reference if needed. + /// The assembly module containing the instruction. + /// The type to replace if it matches. + /// Assign the new type reference. + private void RewriteIfNeeded(ModuleDefinition module, TypeReference type, Action set) + { + // current type + if (type.FullName == this.FromTypeName) + { + if (!this.ShouldIgnore(type)) + set(module.ImportReference(this.ToType)); + return; + } + + // recurse into generic arguments + if (type is GenericInstanceType genericType) + { + for (int i = 0; i < genericType.GenericArguments.Count; i++) + this.RewriteIfNeeded(module, genericType.GenericArguments[i], typeRef => genericType.GenericArguments[i] = typeRef); + } + + // recurse into generic parameters (e.g. constraints) + for (int i = 0; i < type.GenericParameters.Count; i++) + this.RewriteIfNeeded(module, type.GenericParameters[i], typeRef => type.GenericParameters[i] = new GenericParameter(typeRef)); + } + } +} diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs deleted file mode 100644 index fade082b..00000000 --- a/src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System; -using Mono.Cecil; -using Mono.Cecil.Cil; -using StardewModdingAPI.Framework.ModLoading.Finders; - -namespace StardewModdingAPI.Framework.ModLoading.Rewriters -{ - /// Rewrites all references to a type. - internal class TypeReferenceRewriter : TypeFinder - { - /********* - ** Fields - *********/ - /// The full type name to which to find references. - private readonly string FromTypeName; - - /// The new type to reference. - private readonly Type ToType; - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The full type name to which to find references. - /// The new type to reference. - /// A lambda which overrides a matched type. - public TypeReferenceRewriter(string fromTypeFullName, Type toType, Func shouldIgnore = null) - : base(fromTypeFullName, InstructionHandleResult.None, shouldIgnore) - { - this.FromTypeName = fromTypeFullName; - this.ToType = toType; - } - - /// Perform the predefined logic for a method if applicable. - /// The assembly module containing the instruction. - /// The method definition containing the instruction. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - bool rewritten = false; - - // return type - if (this.IsMatch(method.ReturnType)) - { - this.RewriteIfNeeded(module, method.ReturnType, newType => method.ReturnType = newType); - rewritten = true; - } - - // parameters - foreach (ParameterDefinition parameter in method.Parameters) - { - if (this.IsMatch(parameter.ParameterType)) - { - this.RewriteIfNeeded(module, parameter.ParameterType, newType => parameter.ParameterType = newType); - rewritten = true; - } - } - - // generic parameters - for (int i = 0; i < method.GenericParameters.Count; i++) - { - var parameter = method.GenericParameters[i]; - if (this.IsMatch(parameter)) - { - this.RewriteIfNeeded(module, parameter, newType => method.GenericParameters[i] = new GenericParameter(parameter.Name, newType)); - rewritten = true; - } - } - - // local variables - foreach (VariableDefinition variable in method.Body.Variables) - { - if (this.IsMatch(variable.VariableType)) - { - this.RewriteIfNeeded(module, variable.VariableType, newType => variable.VariableType = newType); - rewritten = true; - } - } - - return rewritten - ? InstructionHandleResult.Rewritten - : InstructionHandleResult.None; - } - - /// Perform the predefined logic for an instruction if applicable. - /// The assembly module containing the instruction. - /// The CIL processor. - /// The instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - if (!this.IsMatch(instruction)) - return InstructionHandleResult.None; - - // field reference - FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); - if (fieldRef != null) - { - this.RewriteIfNeeded(module, fieldRef.DeclaringType, newType => fieldRef.DeclaringType = newType); - this.RewriteIfNeeded(module, fieldRef.FieldType, newType => fieldRef.FieldType = newType); - } - - // method reference - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); - if (methodRef != null) - { - this.RewriteIfNeeded(module, methodRef.DeclaringType, newType => methodRef.DeclaringType = newType); - this.RewriteIfNeeded(module, methodRef.ReturnType, newType => methodRef.ReturnType = newType); - foreach (var parameter in methodRef.Parameters) - this.RewriteIfNeeded(module, parameter.ParameterType, newType => parameter.ParameterType = newType); - } - - // type reference - if (instruction.Operand is TypeReference typeRef) - this.RewriteIfNeeded(module, typeRef, newType => cil.Replace(instruction, cil.Create(instruction.OpCode, newType))); - - return InstructionHandleResult.Rewritten; - } - - /********* - ** Private methods - *********/ - /// Change a type reference if needed. - /// The assembly module containing the instruction. - /// The type to replace if it matches. - /// Assign the new type reference. - private void RewriteIfNeeded(ModuleDefinition module, TypeReference type, Action set) - { - // current type - if (type.FullName == this.FromTypeName) - { - if (!this.ShouldIgnore(type)) - set(module.ImportReference(this.ToType)); - return; - } - - // recurse into generic arguments - if (type is GenericInstanceType genericType) - { - for (int i = 0; i < genericType.GenericArguments.Count; i++) - this.RewriteIfNeeded(module, genericType.GenericArguments[i], typeRef => genericType.GenericArguments[i] = typeRef); - } - - // recurse into generic parameters (e.g. constraints) - for (int i = 0; i < type.GenericParameters.Count; i++) - this.RewriteIfNeeded(module, type.GenericParameters[i], typeRef => type.GenericParameters[i] = new GenericParameter(typeRef)); - } - } -} diff --git a/src/SMAPI/Metadata/InstructionMetadata.cs b/src/SMAPI/Metadata/InstructionMetadata.cs index eee5c235..f3d6e6db 100644 --- a/src/SMAPI/Metadata/InstructionMetadata.cs +++ b/src/SMAPI/Metadata/InstructionMetadata.cs @@ -3,6 +3,7 @@ using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Events; using StardewModdingAPI.Framework.ModLoading; using StardewModdingAPI.Framework.ModLoading.Finders; +using StardewModdingAPI.Framework.ModLoading.Framework; using StardewModdingAPI.Framework.ModLoading.Rewriters; using StardewModdingAPI.Framework.RewriteFacades; using StardewValley; -- cgit From f4192663d78c7a45418f07f0bf4acb67b11291fe Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 5 May 2020 20:53:02 -0400 Subject: add Harmony 2.0 rewriters (#711) --- .../ModLoading/Finders/TypeAssemblyFinder.cs | 25 ++++++ .../Framework/ModLoading/Finders/TypeFinder.cs | 25 ++++++ .../ModLoading/Framework/BaseTypeFinder.cs | 34 +++----- .../Framework/BaseTypeReferenceRewriter.cs | 97 ++++++++-------------- src/SMAPI/Framework/ModLoading/RewriteHelper.cs | 2 +- .../Rewriters/Harmony1AssemblyRewriter.cs | 77 +++++++++++++++++ .../ModLoading/Rewriters/MethodParentRewriter.cs | 18 ++-- .../ModLoading/Rewriters/TypeReferenceRewriter.cs | 68 +++++++++++++++ .../RewriteFacades/HarmonyInstanceMethods.cs | 33 ++++++++ src/SMAPI/Metadata/InstructionMetadata.cs | 5 +- 10 files changed, 295 insertions(+), 89 deletions(-) create mode 100644 src/SMAPI/Framework/ModLoading/Finders/TypeAssemblyFinder.cs create mode 100644 src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs create mode 100644 src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs create mode 100644 src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs create mode 100644 src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs (limited to 'src') diff --git a/src/SMAPI/Framework/ModLoading/Finders/TypeAssemblyFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/TypeAssemblyFinder.cs new file mode 100644 index 00000000..5301186b --- /dev/null +++ b/src/SMAPI/Framework/ModLoading/Finders/TypeAssemblyFinder.cs @@ -0,0 +1,25 @@ +using System; +using Mono.Cecil; +using StardewModdingAPI.Framework.ModLoading.Framework; + +namespace StardewModdingAPI.Framework.ModLoading.Finders +{ + /// Finds incompatible CIL instructions that reference types in a given assembly. + internal class TypeAssemblyFinder : BaseTypeFinder + { + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The full assembly name to which to find references. + /// The result to return for matching instructions. + /// A lambda which overrides a matched type. + public TypeAssemblyFinder(string assemblyName, InstructionHandleResult result, Func shouldIgnore = null) + : base( + isMatch: type => type.Scope.Name == assemblyName && (shouldIgnore == null || !shouldIgnore(type)), + result: result, + nounPhrase: $"{assemblyName} assembly" + ) + { } + } +} diff --git a/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs new file mode 100644 index 00000000..3adc31c7 --- /dev/null +++ b/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs @@ -0,0 +1,25 @@ +using System; +using Mono.Cecil; +using StardewModdingAPI.Framework.ModLoading.Framework; + +namespace StardewModdingAPI.Framework.ModLoading.Finders +{ + /// Finds incompatible CIL instructions that reference a given type. + internal class TypeFinder : BaseTypeFinder + { + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The full type name to match. + /// The result to return for matching instructions. + /// A lambda which overrides a matched type. + public TypeFinder(string fullTypeName, InstructionHandleResult result, Func shouldIgnore = null) + : base( + isMatch: type => type.FullName == fullTypeName && (shouldIgnore == null || !shouldIgnore(type)), + result: result, + nounPhrase: $"{fullTypeName} type" + ) + { } + } +} diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs index 170bbb48..b1547334 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs @@ -5,21 +5,18 @@ using Mono.Cecil.Cil; namespace StardewModdingAPI.Framework.ModLoading.Framework { - /// Finds incompatible CIL instructions that reference a given type. - internal class TypeFinder : IInstructionHandler + /// Finds incompatible CIL type reference instructions. + internal abstract class BaseTypeFinder : IInstructionHandler { /********* ** Accessors *********/ - /// The full type name for which to find references. - private readonly string FullTypeName; + /// Matches the type references to handle. + private readonly Func IsMatchImpl; /// The result to return for matching instructions. private readonly InstructionHandleResult Result; - /// A lambda which overrides a matched type. - protected readonly Func ShouldIgnore; - /********* ** Accessors @@ -32,15 +29,14 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework ** Public methods *********/ /// Construct an instance. - /// The full type name to match. + /// Matches the type references to handle. /// The result to return for matching instructions. - /// A lambda which overrides a matched type. - public TypeFinder(string fullTypeName, InstructionHandleResult result, Func shouldIgnore = null) + /// A brief noun phrase indicating what the instruction finder matches. + public BaseTypeFinder(Func isMatch, InstructionHandleResult result, string nounPhrase) { - this.FullTypeName = fullTypeName; + this.IsMatchImpl = isMatch; this.Result = result; - this.NounPhrase = $"{fullTypeName} type"; - this.ShouldIgnore = shouldIgnore ?? (p => false); + this.NounPhrase = nounPhrase; } /// Perform the predefined logic for a method if applicable. @@ -68,13 +64,9 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework : InstructionHandleResult.None; } - - /********* - ** Protected methods - *********/ /// Get whether a CIL instruction matches. /// The method definition. - protected bool IsMatch(MethodDefinition method) + public bool IsMatch(MethodDefinition method) { if (this.IsMatch(method.ReturnType)) return true; @@ -90,7 +82,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /// Get whether a CIL instruction matches. /// The IL instruction. - protected bool IsMatch(Instruction instruction) + public bool IsMatch(Instruction instruction) { // field reference FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); @@ -116,10 +108,10 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /// Get whether a type reference matches the expected type. /// The type to check. - protected bool IsMatch(TypeReference type) + public bool IsMatch(TypeReference type) { // root type - if (type.FullName == this.FullTypeName && !this.ShouldIgnore(type)) + if (this.IsMatchImpl(type)) return true; // generic arguments diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs index 8c2d11c8..55ce6b5a 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs @@ -5,30 +5,32 @@ using Mono.Cecil.Cil; namespace StardewModdingAPI.Framework.ModLoading.Framework { /// Rewrites all references to a type. - internal class TypeReferenceRewriter : TypeFinder + internal abstract class BaseTypeReferenceRewriter : IInstructionHandler { /********* ** Fields *********/ - /// The full type name to which to find references. - private readonly string FromTypeName; + /// The type finder which matches types to rewrite. + private readonly BaseTypeFinder Finder; - /// The new type to reference. - private readonly Type ToType; + + /********* + ** Accessors + *********/ + /// A brief noun phrase indicating what the handler matches. + public string NounPhrase { get; } /********* ** Public methods *********/ /// Construct an instance. - /// The full type name to which to find references. - /// The new type to reference. - /// A lambda which overrides a matched type. - public TypeReferenceRewriter(string fromTypeFullName, Type toType, Func shouldIgnore = null) - : base(fromTypeFullName, InstructionHandleResult.None, shouldIgnore) + /// The type finder which matches types to rewrite. + /// A brief noun phrase indicating what the instruction finder matches. + public BaseTypeReferenceRewriter(BaseTypeFinder finder, string nounPhrase) { - this.FromTypeName = fromTypeFullName; - this.ToType = toType; + this.Finder = finder; + this.NounPhrase = nounPhrase; } /// Perform the predefined logic for a method if applicable. @@ -36,46 +38,36 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /// The method definition containing the instruction. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) + public InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) { bool rewritten = false; // return type - if (this.IsMatch(method.ReturnType)) + if (this.Finder.IsMatch(method.ReturnType)) { - this.RewriteIfNeeded(module, method.ReturnType, newType => method.ReturnType = newType); - rewritten = true; + rewritten |= this.RewriteIfNeeded(module, method.ReturnType, newType => method.ReturnType = newType); } // parameters foreach (ParameterDefinition parameter in method.Parameters) { - if (this.IsMatch(parameter.ParameterType)) - { - this.RewriteIfNeeded(module, parameter.ParameterType, newType => parameter.ParameterType = newType); - rewritten = true; - } + if (this.Finder.IsMatch(parameter.ParameterType)) + rewritten |= this.RewriteIfNeeded(module, parameter.ParameterType, newType => parameter.ParameterType = newType); } // generic parameters for (int i = 0; i < method.GenericParameters.Count; i++) { var parameter = method.GenericParameters[i]; - if (this.IsMatch(parameter)) - { - this.RewriteIfNeeded(module, parameter, newType => method.GenericParameters[i] = new GenericParameter(parameter.Name, newType)); - rewritten = true; - } + if (this.Finder.IsMatch(parameter)) + rewritten |= this.RewriteIfNeeded(module, parameter, newType => method.GenericParameters[i] = new GenericParameter(parameter.Name, newType)); } // local variables foreach (VariableDefinition variable in method.Body.Variables) { - if (this.IsMatch(variable.VariableType)) - { - this.RewriteIfNeeded(module, variable.VariableType, newType => variable.VariableType = newType); - rewritten = true; - } + if (this.Finder.IsMatch(variable.VariableType)) + rewritten |= this.RewriteIfNeeded(module, variable.VariableType, newType => variable.VariableType = newType); } return rewritten @@ -89,34 +81,37 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /// The instruction to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + public InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) { - if (!this.IsMatch(instruction)) + if (!this.Finder.IsMatch(instruction)) return InstructionHandleResult.None; + bool rewritten = false; // field reference FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); if (fieldRef != null) { - this.RewriteIfNeeded(module, fieldRef.DeclaringType, newType => fieldRef.DeclaringType = newType); - this.RewriteIfNeeded(module, fieldRef.FieldType, newType => fieldRef.FieldType = newType); + rewritten |= this.RewriteIfNeeded(module, fieldRef.DeclaringType, newType => fieldRef.DeclaringType = newType); + rewritten |= this.RewriteIfNeeded(module, fieldRef.FieldType, newType => fieldRef.FieldType = newType); } // method reference MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); if (methodRef != null) { - this.RewriteIfNeeded(module, methodRef.DeclaringType, newType => methodRef.DeclaringType = newType); - this.RewriteIfNeeded(module, methodRef.ReturnType, newType => methodRef.ReturnType = newType); + rewritten |= this.RewriteIfNeeded(module, methodRef.DeclaringType, newType => methodRef.DeclaringType = newType); + rewritten |= this.RewriteIfNeeded(module, methodRef.ReturnType, newType => methodRef.ReturnType = newType); foreach (var parameter in methodRef.Parameters) - this.RewriteIfNeeded(module, parameter.ParameterType, newType => parameter.ParameterType = newType); + rewritten |= this.RewriteIfNeeded(module, parameter.ParameterType, newType => parameter.ParameterType = newType); } // type reference if (instruction.Operand is TypeReference typeRef) - this.RewriteIfNeeded(module, typeRef, newType => cil.Replace(instruction, cil.Create(instruction.OpCode, newType))); + rewritten |= this.RewriteIfNeeded(module, typeRef, newType => cil.Replace(instruction, cil.Create(instruction.OpCode, newType))); - return InstructionHandleResult.Rewritten; + return rewritten + ? InstructionHandleResult.Rewritten + : InstructionHandleResult.None; } /********* @@ -126,26 +121,6 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /// The assembly module containing the instruction. /// The type to replace if it matches. /// Assign the new type reference. - private void RewriteIfNeeded(ModuleDefinition module, TypeReference type, Action set) - { - // current type - if (type.FullName == this.FromTypeName) - { - if (!this.ShouldIgnore(type)) - set(module.ImportReference(this.ToType)); - return; - } - - // recurse into generic arguments - if (type is GenericInstanceType genericType) - { - for (int i = 0; i < genericType.GenericArguments.Count; i++) - this.RewriteIfNeeded(module, genericType.GenericArguments[i], typeRef => genericType.GenericArguments[i] = typeRef); - } - - // recurse into generic parameters (e.g. constraints) - for (int i = 0; i < type.GenericParameters.Count; i++) - this.RewriteIfNeeded(module, type.GenericParameters[i], typeRef => type.GenericParameters[i] = new GenericParameter(typeRef)); - } + protected abstract bool RewriteIfNeeded(ModuleDefinition module, TypeReference type, Action set); } } diff --git a/src/SMAPI/Framework/ModLoading/RewriteHelper.cs b/src/SMAPI/Framework/ModLoading/RewriteHelper.cs index f8f10dc4..d9a49cfa 100644 --- a/src/SMAPI/Framework/ModLoading/RewriteHelper.cs +++ b/src/SMAPI/Framework/ModLoading/RewriteHelper.cs @@ -103,7 +103,7 @@ namespace StardewModdingAPI.Framework.ModLoading public static bool HasMatchingSignature(Type type, MethodReference reference) { return type - .GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public) + .GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public) .Any(method => RewriteHelper.HasMatchingSignature(method, reference)); } } diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs new file mode 100644 index 00000000..29e44bfe --- /dev/null +++ b/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs @@ -0,0 +1,77 @@ +using System; +using Mono.Cecil; +using StardewModdingAPI.Framework.ModLoading.Finders; +using StardewModdingAPI.Framework.ModLoading.Framework; + +namespace StardewModdingAPI.Framework.ModLoading.Rewriters +{ + /// Rewrites Harmony 1.x assembly references to work with Harmony 2.x. + internal class Harmony1AssemblyRewriter : BaseTypeReferenceRewriter + { + /********* + ** Fields + *********/ + /// The full assembly name to which to find references. + private const string FromAssemblyName = "0Harmony"; + + /// The main Harmony type. + private readonly Type HarmonyType = typeof(HarmonyLib.Harmony); + + + /********* + ** Public methods + *********/ + /// Construct an instance. + public Harmony1AssemblyRewriter() + : base(new TypeAssemblyFinder(Harmony1AssemblyRewriter.FromAssemblyName, InstructionHandleResult.None), "Harmony 1.x types") + { } + + + /********* + ** Private methods + *********/ + /// Change a type reference if needed. + /// The assembly module containing the instruction. + /// The type to replace if it matches. + /// Assign the new type reference. + protected override bool RewriteIfNeeded(ModuleDefinition module, TypeReference type, Action set) + { + bool rewritten = false; + + // current type + if (type.Scope.Name == Harmony1AssemblyRewriter.FromAssemblyName && type.Scope is AssemblyNameReference assemblyScope && assemblyScope.Version.Major == 1) + { + Type targetType = this.GetMappedType(type); + set(module.ImportReference(targetType)); + return true; + } + + // recurse into generic arguments + if (type is GenericInstanceType genericType) + { + for (int i = 0; i < genericType.GenericArguments.Count; i++) + rewritten |= this.RewriteIfNeeded(module, genericType.GenericArguments[i], typeRef => genericType.GenericArguments[i] = typeRef); + } + + // recurse into generic parameters (e.g. constraints) + for (int i = 0; i < type.GenericParameters.Count; i++) + rewritten |= this.RewriteIfNeeded(module, type.GenericParameters[i], typeRef => type.GenericParameters[i] = new GenericParameter(typeRef)); + + return rewritten; + } + + /// Get an equivalent Harmony 2.x type. + /// The Harmony 1.x method. + private Type GetMappedType(TypeReference type) + { + // main Harmony object + if (type.FullName == "Harmony.HarmonyInstance") + return this.HarmonyType; + + // other objects + string fullName = type.FullName.Replace("Harmony.", "HarmonyLib."); + string targetName = this.HarmonyType.AssemblyQualifiedName.Replace(this.HarmonyType.FullName, fullName); + return Type.GetType(targetName, throwOnError: true); + } + } +} diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs index 6b8c2de1..0984dc44 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; @@ -10,8 +11,8 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /********* ** Fields *********/ - /// The type whose methods to remap. - private readonly Type FromType; + /// The full name of the type whose methods to remap. + private readonly string FromType; /// The type with methods to map to. private readonly Type ToType; @@ -34,14 +35,21 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// The type whose methods to remap. /// The type with methods to map to. /// Whether to only rewrite references if loading the assembly on a different platform than it was compiled on. - public MethodParentRewriter(Type fromType, Type toType, bool onlyIfPlatformChanged = false) + public MethodParentRewriter(string fromType, Type toType, bool onlyIfPlatformChanged = false) { this.FromType = fromType; this.ToType = toType; - this.NounPhrase = $"{fromType.Name} methods"; + this.NounPhrase = $"{fromType.Split('.').Last()} methods"; this.OnlyIfPlatformChanged = onlyIfPlatformChanged; } + /// Construct an instance. + /// The type whose methods to remap. + /// The type with methods to map to. + /// Whether to only rewrite references if loading the assembly on a different platform than it was compiled on. + public MethodParentRewriter(Type fromType, Type toType, bool onlyIfPlatformChanged = false) + : this(fromType.FullName, toType, onlyIfPlatformChanged) { } + /// Perform the predefined logic for a method if applicable. /// The assembly module containing the instruction. /// The method definition containing the instruction. @@ -81,7 +89,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters return methodRef != null && (platformChanged || !this.OnlyIfPlatformChanged) - && methodRef.DeclaringType.FullName == this.FromType.FullName + && methodRef.DeclaringType.FullName == this.FromType && RewriteHelper.HasMatchingSignature(this.ToType, methodRef); } } diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs new file mode 100644 index 00000000..d95e5ac9 --- /dev/null +++ b/src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs @@ -0,0 +1,68 @@ +using System; +using Mono.Cecil; +using StardewModdingAPI.Framework.ModLoading.Finders; +using StardewModdingAPI.Framework.ModLoading.Framework; + +namespace StardewModdingAPI.Framework.ModLoading.Rewriters +{ + /// Rewrites all references to a type. + internal class TypeReferenceRewriter : BaseTypeReferenceRewriter + { + /********* + ** Fields + *********/ + /// The full type name to which to find references. + private readonly string FromTypeName; + + /// The new type to reference. + private readonly Type ToType; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The full type name to which to find references. + /// The new type to reference. + /// A lambda which overrides a matched type. + public TypeReferenceRewriter(string fromTypeFullName, Type toType, Func shouldIgnore = null) + : base(new TypeFinder(fromTypeFullName, InstructionHandleResult.None, shouldIgnore), $"{fromTypeFullName} type") + { + this.FromTypeName = fromTypeFullName; + this.ToType = toType; + } + + + /********* + ** Protected methods + *********/ + /// Change a type reference if needed. + /// The assembly module containing the instruction. + /// The type to replace if it matches. + /// Assign the new type reference. + protected override bool RewriteIfNeeded(ModuleDefinition module, TypeReference type, Action set) + { + bool rewritten = false; + + // current type + if (type.FullName == this.FromTypeName) + { + set(module.ImportReference(this.ToType)); + return true; + } + + // recurse into generic arguments + if (type is GenericInstanceType genericType) + { + for (int i = 0; i < genericType.GenericArguments.Count; i++) + rewritten |= this.RewriteIfNeeded(module, genericType.GenericArguments[i], typeRef => genericType.GenericArguments[i] = typeRef); + } + + // recurse into generic parameters (e.g. constraints) + for (int i = 0; i < type.GenericParameters.Count; i++) + rewritten |= this.RewriteIfNeeded(module, type.GenericParameters[i], typeRef => type.GenericParameters[i] = new GenericParameter(typeRef)); + + return rewritten; + } + } +} diff --git a/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs b/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs new file mode 100644 index 00000000..0f906f51 --- /dev/null +++ b/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs @@ -0,0 +1,33 @@ +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using HarmonyLib; + +namespace StardewModdingAPI.Framework.RewriteFacades +{ + /// Maps Harmony 1.x methods to Harmony 2.x to avoid breaking older mods. + /// This is public to support SMAPI rewriting and should not be referenced directly by mods. + public class HarmonyInstanceMethods : Harmony + { + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The unique patch identifier. + public HarmonyInstanceMethods(string id) + : base(id) { } + + /// Creates a new Harmony instance. + /// A unique identifier for the instance. + public static Harmony Create(string id) + { + return new Harmony(id); + } + + public DynamicMethod Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null) + { + MethodInfo method = base.Patch(original: original, prefix: prefix, postfix: postfix, transpiler: transpiler); + return new DynamicMethod(method.Name, method.Attributes, method.CallingConvention, method.ReturnType, method.GetParameters().Select(p => p.ParameterType).ToArray(), method.Module, true); + } + } +} diff --git a/src/SMAPI/Metadata/InstructionMetadata.cs b/src/SMAPI/Metadata/InstructionMetadata.cs index f3d6e6db..fb7141e7 100644 --- a/src/SMAPI/Metadata/InstructionMetadata.cs +++ b/src/SMAPI/Metadata/InstructionMetadata.cs @@ -3,7 +3,6 @@ using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Events; using StardewModdingAPI.Framework.ModLoading; using StardewModdingAPI.Framework.ModLoading.Finders; -using StardewModdingAPI.Framework.ModLoading.Framework; using StardewModdingAPI.Framework.ModLoading.Rewriters; using StardewModdingAPI.Framework.RewriteFacades; using StardewValley; @@ -37,6 +36,10 @@ namespace StardewModdingAPI.Metadata // rewrite for Stardew Valley 1.3 yield return new StaticFieldToConstantRewriter(typeof(Game1), "tileSize", Game1.tileSize); + // rewrite for SMAPI 3.6 (Harmony 1.x => 2.0 update) + yield return new Harmony1AssemblyRewriter(); + yield return new MethodParentRewriter("HarmonyLib.Harmony", typeof(HarmonyInstanceMethods), onlyIfPlatformChanged: false); + /**** ** detect mod issues ****/ -- cgit From 499cd8ab317080096c373c6ed6649bd51fb01c7d Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 5 May 2020 21:45:53 -0400 Subject: combine Harmony 1.x rewrite logs (#711) --- .../Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs | 9 ++++++++- src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs | 5 +++-- src/SMAPI/Metadata/InstructionMetadata.cs | 2 +- 3 files changed, 12 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs index 29e44bfe..9faca235 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs @@ -18,12 +18,19 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters private readonly Type HarmonyType = typeof(HarmonyLib.Harmony); + /********* + ** Accessors + *********/ + /// A brief noun phrase indicating what the rewriter matches. + public const string DefaultNounPhrase = "Harmony 1.x"; + + /********* ** Public methods *********/ /// Construct an instance. public Harmony1AssemblyRewriter() - : base(new TypeAssemblyFinder(Harmony1AssemblyRewriter.FromAssemblyName, InstructionHandleResult.None), "Harmony 1.x types") + : base(new TypeAssemblyFinder(Harmony1AssemblyRewriter.FromAssemblyName, InstructionHandleResult.None), Harmony1AssemblyRewriter.DefaultNounPhrase) { } diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs index 0984dc44..c4c740b3 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs @@ -35,11 +35,12 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// The type whose methods to remap. /// The type with methods to map to. /// Whether to only rewrite references if loading the assembly on a different platform than it was compiled on. - public MethodParentRewriter(string fromType, Type toType, bool onlyIfPlatformChanged = false) + /// A brief noun phrase indicating what the instruction finder matches (or null to generate one). + public MethodParentRewriter(string fromType, Type toType, bool onlyIfPlatformChanged = false, string nounPhrase = null) { this.FromType = fromType; this.ToType = toType; - this.NounPhrase = $"{fromType.Split('.').Last()} methods"; + this.NounPhrase = nounPhrase ?? $"{fromType.Split('.').Last()} methods"; this.OnlyIfPlatformChanged = onlyIfPlatformChanged; } diff --git a/src/SMAPI/Metadata/InstructionMetadata.cs b/src/SMAPI/Metadata/InstructionMetadata.cs index fb7141e7..665147e4 100644 --- a/src/SMAPI/Metadata/InstructionMetadata.cs +++ b/src/SMAPI/Metadata/InstructionMetadata.cs @@ -38,7 +38,7 @@ namespace StardewModdingAPI.Metadata // rewrite for SMAPI 3.6 (Harmony 1.x => 2.0 update) yield return new Harmony1AssemblyRewriter(); - yield return new MethodParentRewriter("HarmonyLib.Harmony", typeof(HarmonyInstanceMethods), onlyIfPlatformChanged: false); + yield return new MethodParentRewriter("HarmonyLib.Harmony", typeof(HarmonyInstanceMethods), onlyIfPlatformChanged: false, nounPhrase: Harmony1AssemblyRewriter.DefaultNounPhrase); /**** ** detect mod issues -- cgit From 7a60e6d2a1fbddc60a4052ba577e4f64c35736b3 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 5 May 2020 22:15:38 -0400 Subject: migrate to Harmony 2.0 finalizers (#711) --- src/SMAPI/Framework/Patching/PatchHelper.cs | 34 ------------- src/SMAPI/Patches/DialogueErrorPatch.cs | 75 +++++++++-------------------- src/SMAPI/Patches/EventErrorPatch.cs | 31 ++++-------- src/SMAPI/Patches/ObjectErrorPatch.cs | 39 +++++---------- src/SMAPI/Patches/ScheduleErrorPatch.cs | 31 ++++-------- 5 files changed, 54 insertions(+), 156 deletions(-) delete mode 100644 src/SMAPI/Framework/Patching/PatchHelper.cs (limited to 'src') diff --git a/src/SMAPI/Framework/Patching/PatchHelper.cs b/src/SMAPI/Framework/Patching/PatchHelper.cs deleted file mode 100644 index 4cb436f0..00000000 --- a/src/SMAPI/Framework/Patching/PatchHelper.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace StardewModdingAPI.Framework.Patching -{ - /// Provides generic methods for implementing Harmony patches. - internal class PatchHelper - { - /********* - ** Fields - *********/ - /// The interception keys currently being intercepted. - private static readonly HashSet InterceptingKeys = new HashSet(StringComparer.OrdinalIgnoreCase); - - - /********* - ** Public methods - *********/ - /// Track a method that will be intercepted. - /// The intercept key. - /// Returns false if the method was already marked for interception, else true. - public static bool StartIntercept(string key) - { - return PatchHelper.InterceptingKeys.Add(key); - } - - /// Track a method as no longer being intercepted. - /// The intercept key. - public static void StopIntercept(string key) - { - PatchHelper.InterceptingKeys.Remove(key); - } - } -} diff --git a/src/SMAPI/Patches/DialogueErrorPatch.cs b/src/SMAPI/Patches/DialogueErrorPatch.cs index 80029540..cddf29d6 100644 --- a/src/SMAPI/Patches/DialogueErrorPatch.cs +++ b/src/SMAPI/Patches/DialogueErrorPatch.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Reflection; using HarmonyLib; +using StardewModdingAPI.Framework; using StardewModdingAPI.Framework.Patching; using StardewModdingAPI.Framework.Reflection; using StardewValley; @@ -51,11 +51,11 @@ namespace StardewModdingAPI.Patches { harmony.Patch( original: AccessTools.Constructor(typeof(Dialogue), new[] { typeof(string), typeof(NPC) }), - prefix: new HarmonyMethod(this.GetType(), nameof(DialogueErrorPatch.Before_Dialogue_Constructor)) + finalizer: new HarmonyMethod(this.GetType(), nameof(DialogueErrorPatch.Finalize_Dialogue_Constructor)) ); harmony.Patch( original: AccessTools.Property(typeof(NPC), nameof(NPC.CurrentDialogue)).GetMethod, - prefix: new HarmonyMethod(this.GetType(), nameof(DialogueErrorPatch.Before_NPC_CurrentDialogue)) + finalizer: new HarmonyMethod(this.GetType(), nameof(DialogueErrorPatch.Finalize_NPC_CurrentDialogue)) ); } @@ -63,71 +63,44 @@ namespace StardewModdingAPI.Patches /********* ** Private methods *********/ - /// The method to call instead of the Dialogue constructor. + /// The method to call after the Dialogue constructor. /// The instance being patched. /// The dialogue being parsed. /// The NPC for which the dialogue is being parsed. - /// Returns whether to execute the original method. - private static bool Before_Dialogue_Constructor(Dialogue __instance, string masterDialogue, NPC speaker) + /// The exception thrown by the wrapped method, if any. + /// Returns the exception to throw, if any. + private static Exception Finalize_Dialogue_Constructor(Dialogue __instance, string masterDialogue, NPC speaker, Exception __exception) { - // get private members - bool nameArraysTranslated = DialogueErrorPatch.Reflection.GetField(typeof(Dialogue), "nameArraysTranslated").GetValue(); - IReflectedMethod translateArraysOfStrings = DialogueErrorPatch.Reflection.GetMethod(typeof(Dialogue), "TranslateArraysOfStrings"); - IReflectedMethod parseDialogueString = DialogueErrorPatch.Reflection.GetMethod(__instance, "parseDialogueString"); - IReflectedMethod checkForSpecialDialogueAttributes = DialogueErrorPatch.Reflection.GetMethod(__instance, "checkForSpecialDialogueAttributes"); - IReflectedField> dialogues = DialogueErrorPatch.Reflection.GetField>(__instance, "dialogues"); - - // replicate base constructor - if (dialogues.GetValue() == null) - dialogues.SetValue(new List()); - - // duplicate code with try..catch - try - { - if (!nameArraysTranslated) - translateArraysOfStrings.Invoke(); - __instance.speaker = speaker; - parseDialogueString.Invoke(masterDialogue); - checkForSpecialDialogueAttributes.Invoke(); - } - catch (Exception baseEx) when (baseEx.InnerException is TargetInvocationException invocationEx && invocationEx.InnerException is Exception ex) + if (__exception != null) { + // log message string name = !string.IsNullOrWhiteSpace(speaker?.Name) ? speaker.Name : null; - DialogueErrorPatch.MonitorForGame.Log($"Failed parsing dialogue string{(name != null ? $" for {name}" : "")}:\n{masterDialogue}\n{ex}", LogLevel.Error); + DialogueErrorPatch.MonitorForGame.Log($"Failed parsing dialogue string{(name != null ? $" for {name}" : "")}:\n{masterDialogue}\n{__exception.GetLogSummary()}", LogLevel.Error); + // set default dialogue + IReflectedMethod parseDialogueString = DialogueErrorPatch.Reflection.GetMethod(__instance, "parseDialogueString"); + IReflectedMethod checkForSpecialDialogueAttributes = DialogueErrorPatch.Reflection.GetMethod(__instance, "checkForSpecialDialogueAttributes"); parseDialogueString.Invoke("..."); checkForSpecialDialogueAttributes.Invoke(); } - return false; + return null; } - /// The method to call instead of . + /// The method to call after . /// The instance being patched. /// The return value of the original method. - /// The method being wrapped. - /// Returns whether to execute the original method. - private static bool Before_NPC_CurrentDialogue(NPC __instance, ref Stack __result, MethodInfo __originalMethod) + /// The exception thrown by the wrapped method, if any. + /// Returns the exception to throw, if any. + private static Exception Finalize_NPC_CurrentDialogue(NPC __instance, ref Stack __result, Exception __exception) { - const string key = nameof(Before_NPC_CurrentDialogue); - if (!PatchHelper.StartIntercept(key)) - return true; + if (__exception == null) + return null; - try - { - __result = (Stack)__originalMethod.Invoke(__instance, new object[0]); - return false; - } - catch (TargetInvocationException ex) - { - DialogueErrorPatch.MonitorForGame.Log($"Failed loading current dialogue for NPC {__instance.Name}:\n{ex.InnerException ?? ex}", LogLevel.Error); - __result = new Stack(); - return false; - } - finally - { - PatchHelper.StopIntercept(key); - } + DialogueErrorPatch.MonitorForGame.Log($"Failed loading current dialogue for NPC {__instance.Name}:\n{__exception.GetLogSummary()}", LogLevel.Error); + __result = new Stack(); + + return null; } } } diff --git a/src/SMAPI/Patches/EventErrorPatch.cs b/src/SMAPI/Patches/EventErrorPatch.cs index a2b94e8b..de9dea29 100644 --- a/src/SMAPI/Patches/EventErrorPatch.cs +++ b/src/SMAPI/Patches/EventErrorPatch.cs @@ -1,5 +1,5 @@ +using System; using System.Diagnostics.CodeAnalysis; -using System.Reflection; using HarmonyLib; using StardewModdingAPI.Framework.Patching; using StardewValley; @@ -42,7 +42,7 @@ namespace StardewModdingAPI.Patches { harmony.Patch( original: AccessTools.Method(typeof(GameLocation), "checkEventPrecondition"), - prefix: new HarmonyMethod(this.GetType(), nameof(EventErrorPatch.Before_GameLocation_CheckEventPrecondition)) + finalizer: new HarmonyMethod(this.GetType(), nameof(EventErrorPatch.Finalize_GameLocation_CheckEventPrecondition)) ); } @@ -51,32 +51,19 @@ namespace StardewModdingAPI.Patches ** Private methods *********/ /// The method to call instead of the GameLocation.CheckEventPrecondition. - /// The instance being patched. /// The return value of the original method. /// The precondition to be parsed. - /// The method being wrapped. - /// Returns whether to execute the original method. - private static bool Before_GameLocation_CheckEventPrecondition(GameLocation __instance, ref int __result, string precondition, MethodInfo __originalMethod) + /// The exception thrown by the wrapped method, if any. + /// Returns the exception to throw, if any. + private static Exception Finalize_GameLocation_CheckEventPrecondition(ref int __result, string precondition, Exception __exception) { - const string key = nameof(Before_GameLocation_CheckEventPrecondition); - if (!PatchHelper.StartIntercept(key)) - return true; - - try - { - __result = (int)__originalMethod.Invoke(__instance, new object[] { precondition }); - return false; - } - catch (TargetInvocationException ex) + if (__exception != null) { __result = -1; - EventErrorPatch.MonitorForGame.Log($"Failed parsing event precondition ({precondition}):\n{ex.InnerException}", LogLevel.Error); - return false; - } - finally - { - PatchHelper.StopIntercept(key); + EventErrorPatch.MonitorForGame.Log($"Failed parsing event precondition ({precondition}):\n{__exception.InnerException}", LogLevel.Error); } + + return null; } } } diff --git a/src/SMAPI/Patches/ObjectErrorPatch.cs b/src/SMAPI/Patches/ObjectErrorPatch.cs index b9655043..189a14a0 100644 --- a/src/SMAPI/Patches/ObjectErrorPatch.cs +++ b/src/SMAPI/Patches/ObjectErrorPatch.cs @@ -1,6 +1,6 @@ +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Reflection; using HarmonyLib; using StardewModdingAPI.Framework.Patching; using StardewValley; @@ -38,7 +38,7 @@ namespace StardewModdingAPI.Patches // object.getDisplayName harmony.Patch( original: AccessTools.Method(typeof(SObject), "loadDisplayName"), - prefix: new HarmonyMethod(this.GetType(), nameof(ObjectErrorPatch.Before_Object_loadDisplayName)) + finalizer: new HarmonyMethod(this.GetType(), nameof(ObjectErrorPatch.Finalize_Object_loadDisplayName)) ); // IClickableMenu.drawToolTip @@ -68,42 +68,25 @@ namespace StardewModdingAPI.Patches return true; } - /// The method to call instead of . - /// The instance being patched. + /// The method to call after . /// The patched method's return value. - /// The method being wrapped. - /// Returns whether to execute the original method. - private static bool Before_Object_loadDisplayName(SObject __instance, ref string __result, MethodInfo __originalMethod) + /// The exception thrown by the wrapped method, if any. + /// Returns the exception to throw, if any. + private static Exception Finalize_Object_loadDisplayName(ref string __result, Exception __exception) { - const string key = nameof(Before_Object_loadDisplayName); - if (!PatchHelper.StartIntercept(key)) - return true; - - try - { - __result = (string)__originalMethod.Invoke(__instance, new object[0]); - return false; - } - catch (TargetInvocationException ex) when (ex.InnerException is KeyNotFoundException) + if (__exception is KeyNotFoundException) { __result = "???"; - return false; - } - catch - { - return true; - } - finally - { - PatchHelper.StopIntercept(key); + return null; } + + return __exception; } /// The method to call instead of . - /// The instance being patched. /// The item for which to draw a tooltip. /// Returns whether to execute the original method. - private static bool Before_IClickableMenu_DrawTooltip(IClickableMenu __instance, Item hoveredItem) + private static bool Before_IClickableMenu_DrawTooltip(Item hoveredItem) { // invalid edible item cause crash when drawing tooltips if (hoveredItem is SObject obj && obj.Edibility != -300 && !Game1.objectInformation.ContainsKey(obj.ParentSheetIndex)) diff --git a/src/SMAPI/Patches/ScheduleErrorPatch.cs b/src/SMAPI/Patches/ScheduleErrorPatch.cs index 386230a6..df6ffab3 100644 --- a/src/SMAPI/Patches/ScheduleErrorPatch.cs +++ b/src/SMAPI/Patches/ScheduleErrorPatch.cs @@ -1,7 +1,8 @@ +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Reflection; using HarmonyLib; +using StardewModdingAPI.Framework; using StardewModdingAPI.Framework.Patching; using StardewValley; @@ -43,7 +44,7 @@ namespace StardewModdingAPI.Patches { harmony.Patch( original: AccessTools.Method(typeof(NPC), "parseMasterSchedule"), - prefix: new HarmonyMethod(this.GetType(), nameof(ScheduleErrorPatch.Before_NPC_parseMasterSchedule)) + finalizer: new HarmonyMethod(this.GetType(), nameof(ScheduleErrorPatch.Finalize_NPC_parseMasterSchedule)) ); } @@ -55,29 +56,17 @@ namespace StardewModdingAPI.Patches /// The raw schedule data to parse. /// The instance being patched. /// The patched method's return value. - /// The method being wrapped. - /// Returns whether to execute the original method. - private static bool Before_NPC_parseMasterSchedule(string rawData, NPC __instance, ref Dictionary __result, MethodInfo __originalMethod) + /// The exception thrown by the wrapped method, if any. + /// Returns the exception to throw, if any. + private static Exception Finalize_NPC_parseMasterSchedule(string rawData, NPC __instance, ref Dictionary __result, Exception __exception) { - const string key = nameof(Before_NPC_parseMasterSchedule); - if (!PatchHelper.StartIntercept(key)) - return true; - - try - { - __result = (Dictionary)__originalMethod.Invoke(__instance, new object[] { rawData }); - return false; - } - catch (TargetInvocationException ex) + if (__exception != null) { - ScheduleErrorPatch.MonitorForGame.Log($"Failed parsing schedule for NPC {__instance.Name}:\n{rawData}\n{ex.InnerException ?? ex}", LogLevel.Error); + ScheduleErrorPatch.MonitorForGame.Log($"Failed parsing schedule for NPC {__instance.Name}:\n{rawData}\n{__exception.GetLogSummary()}", LogLevel.Error); __result = new Dictionary(); - return false; - } - finally - { - PatchHelper.StopIntercept(key); } + + return null; } } } -- cgit From cfc07c1ee58b113c4e2ec8d6de28a57397589068 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 5 May 2020 23:31:06 -0400 Subject: fix reference to old Harmony namespace (#711) --- src/SMAPI/Metadata/InstructionMetadata.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/SMAPI/Metadata/InstructionMetadata.cs b/src/SMAPI/Metadata/InstructionMetadata.cs index 665147e4..64216138 100644 --- a/src/SMAPI/Metadata/InstructionMetadata.cs +++ b/src/SMAPI/Metadata/InstructionMetadata.cs @@ -50,7 +50,7 @@ namespace StardewModdingAPI.Metadata /**** ** detect code which may impact game stability ****/ - yield return new TypeFinder("Harmony.HarmonyInstance", InstructionHandleResult.DetectedGamePatch); + yield return new TypeFinder(typeof(HarmonyLib.Harmony).FullName, InstructionHandleResult.DetectedGamePatch); yield return new TypeFinder("System.Runtime.CompilerServices.CallSite", InstructionHandleResult.DetectedDynamic); yield return new FieldFinder(typeof(SaveGame).FullName, nameof(SaveGame.serializer), InstructionHandleResult.DetectedSaveSerializer); yield return new FieldFinder(typeof(SaveGame).FullName, nameof(SaveGame.farmerSerializer), InstructionHandleResult.DetectedSaveSerializer); -- cgit From f16e477fc22bf76c33d8860acda090a199a0dcdb Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 6 May 2020 00:02:10 -0400 Subject: add base instruction handler (#711) --- .../Framework/ModLoading/Finders/EventFinder.cs | 26 +++-------- .../Framework/ModLoading/Finders/FieldFinder.cs | 26 +++-------- .../Framework/ModLoading/Finders/MethodFinder.cs | 26 +++-------- .../Framework/ModLoading/Finders/PropertyFinder.cs | 26 +++-------- .../ReferenceToMemberWithUnexpectedTypeFinder.cs | 25 +++-------- .../Finders/ReferenceToMissingMemberFinder.cs | 25 +++-------- .../ModLoading/Framework/BaseInstructionHandler.cs | 51 ++++++++++++++++++++++ .../ModLoading/Framework/BaseTypeFinder.cs | 43 +++++++++--------- .../Framework/BaseTypeReferenceRewriter.cs | 38 +++++++--------- .../Framework/ModLoading/IInstructionHandler.cs | 4 +- .../ModLoading/Rewriters/MethodParentRewriter.cs | 25 +++-------- 11 files changed, 124 insertions(+), 191 deletions(-) create mode 100644 src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs (limited to 'src') diff --git a/src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs index 898bafb4..1a7ae636 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs @@ -1,10 +1,11 @@ using Mono.Cecil; using Mono.Cecil.Cil; +using StardewModdingAPI.Framework.ModLoading.Framework; namespace StardewModdingAPI.Framework.ModLoading.Finders { /// Finds incompatible CIL instructions that reference a given event. - internal class EventFinder : IInstructionHandler + internal class EventFinder : BaseInstructionHandler { /********* ** Fields @@ -19,13 +20,6 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders private readonly InstructionHandleResult Result; - /********* - ** Accessors - *********/ - /// A brief noun phrase indicating what the instruction finder matches. - public string NounPhrase { get; } - - /********* ** Public methods *********/ @@ -34,30 +28,20 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The event name for which to find references. /// The result to return for matching instructions. public EventFinder(string fullTypeName, string eventName, InstructionHandleResult result) + : base(nounPhrase: $"{fullTypeName}.{eventName} event") { this.FullTypeName = fullTypeName; this.EventName = eventName; this.Result = result; - this.NounPhrase = $"{fullTypeName}.{eventName} event"; - } - - /// Perform the predefined logic for a method if applicable. - /// The assembly module containing the instruction. - /// The method definition containing the instruction. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - return InstructionHandleResult.None; } /// Perform the predefined logic for an instruction if applicable. /// The assembly module containing the instruction. /// The CIL processor. - /// The instruction to handle. + /// The CIL instruction to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) { return this.IsMatch(instruction) ? this.Result diff --git a/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs index 606ca8b7..9ae07916 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs @@ -1,10 +1,11 @@ using Mono.Cecil; using Mono.Cecil.Cil; +using StardewModdingAPI.Framework.ModLoading.Framework; namespace StardewModdingAPI.Framework.ModLoading.Finders { /// Finds incompatible CIL instructions that reference a given field. - internal class FieldFinder : IInstructionHandler + internal class FieldFinder : BaseInstructionHandler { /********* ** Fields @@ -19,13 +20,6 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders private readonly InstructionHandleResult Result; - /********* - ** Accessors - *********/ - /// A brief noun phrase indicating what the instruction finder matches. - public string NounPhrase { get; } - - /********* ** Public methods *********/ @@ -34,30 +28,20 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The field name for which to find references. /// The result to return for matching instructions. public FieldFinder(string fullTypeName, string fieldName, InstructionHandleResult result) + : base(nounPhrase: $"{fullTypeName}.{fieldName} field") { this.FullTypeName = fullTypeName; this.FieldName = fieldName; this.Result = result; - this.NounPhrase = $"{fullTypeName}.{fieldName} field"; - } - - /// Perform the predefined logic for a method if applicable. - /// The assembly module containing the instruction. - /// The method definition containing the instruction. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - return InstructionHandleResult.None; } /// Perform the predefined logic for an instruction if applicable. /// The assembly module containing the instruction. /// The CIL processor. - /// The instruction to handle. + /// The CIL instruction to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) { return this.IsMatch(instruction) ? this.Result diff --git a/src/SMAPI/Framework/ModLoading/Finders/MethodFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/MethodFinder.cs index 9ca246ff..75584f1f 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/MethodFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/MethodFinder.cs @@ -1,10 +1,11 @@ using Mono.Cecil; using Mono.Cecil.Cil; +using StardewModdingAPI.Framework.ModLoading.Framework; namespace StardewModdingAPI.Framework.ModLoading.Finders { /// Finds incompatible CIL instructions that reference a given method. - internal class MethodFinder : IInstructionHandler + internal class MethodFinder : BaseInstructionHandler { /********* ** Fields @@ -19,13 +20,6 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders private readonly InstructionHandleResult Result; - /********* - ** Accessors - *********/ - /// A brief noun phrase indicating what the instruction finder matches. - public string NounPhrase { get; } - - /********* ** Public methods *********/ @@ -34,30 +28,20 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The method name for which to find references. /// The result to return for matching instructions. public MethodFinder(string fullTypeName, string methodName, InstructionHandleResult result) + : base(nounPhrase: $"{fullTypeName}.{methodName} method") { this.FullTypeName = fullTypeName; this.MethodName = methodName; this.Result = result; - this.NounPhrase = $"{fullTypeName}.{methodName} method"; - } - - /// Perform the predefined logic for a method if applicable. - /// The assembly module containing the instruction. - /// The method definition containing the instruction. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - return InstructionHandleResult.None; } /// Perform the predefined logic for an instruction if applicable. /// The assembly module containing the instruction. /// The CIL processor. - /// The instruction to handle. + /// The CIL instruction to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. - public InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) { return this.IsMatch(instruction) ? this.Result diff --git a/src/SMAPI/Framework/ModLoading/Finders/PropertyFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/PropertyFinder.cs index 0677aa88..811420c5 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/PropertyFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/PropertyFinder.cs @@ -1,10 +1,11 @@ using Mono.Cecil; using Mono.Cecil.Cil; +using StardewModdingAPI.Framework.ModLoading.Framework; namespace StardewModdingAPI.Framework.ModLoading.Finders { /// Finds incompatible CIL instructions that reference a given property. - internal class PropertyFinder : IInstructionHandler + internal class PropertyFinder : BaseInstructionHandler { /********* ** Fields @@ -19,13 +20,6 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders private readonly InstructionHandleResult Result; - /********* - ** Accessors - *********/ - /// A brief noun phrase indicating what the instruction finder matches. - public string NounPhrase { get; } - - /********* ** Public methods *********/ @@ -34,30 +28,20 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The property name for which to find references. /// The result to return for matching instructions. public PropertyFinder(string fullTypeName, string propertyName, InstructionHandleResult result) + : base(nounPhrase: $"{fullTypeName}.{propertyName} property") { this.FullTypeName = fullTypeName; this.PropertyName = propertyName; this.Result = result; - this.NounPhrase = $"{fullTypeName}.{propertyName} property"; - } - - /// Perform the predefined logic for a method if applicable. - /// The assembly module containing the instruction. - /// The method definition containing the instruction. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - return InstructionHandleResult.None; } /// Perform the predefined logic for an instruction if applicable. /// The assembly module containing the instruction. /// The CIL processor. - /// The instruction to handle. + /// The CIL instruction to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) { return this.IsMatch(instruction) ? this.Result diff --git a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs index 459e3210..1029d350 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs @@ -2,12 +2,13 @@ using System.Collections.Generic; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; +using StardewModdingAPI.Framework.ModLoading.Framework; namespace StardewModdingAPI.Framework.ModLoading.Finders { /// Finds references to a field, property, or method which returns a different type than the code expects. /// This implementation is purely heuristic. It should never return a false positive, but won't detect all cases. - internal class ReferenceToMemberWithUnexpectedTypeFinder : IInstructionHandler + internal class ReferenceToMemberWithUnexpectedTypeFinder : BaseInstructionHandler { /********* ** Fields @@ -16,40 +17,24 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders private readonly HashSet ValidateReferencesToAssemblies; - /********* - ** Accessors - *********/ - /// A brief noun phrase indicating what the instruction finder matches. - public string NounPhrase { get; private set; } = ""; - - /********* ** Public methods *********/ /// Construct an instance. /// The assembly names to which to heuristically detect broken references. public ReferenceToMemberWithUnexpectedTypeFinder(string[] validateReferencesToAssemblies) + : base(nounPhrase: "") { this.ValidateReferencesToAssemblies = new HashSet(validateReferencesToAssemblies); } - /// Perform the predefined logic for a method if applicable. - /// The assembly module containing the instruction. - /// The method definition containing the instruction. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - return InstructionHandleResult.None; - } - /// Perform the predefined logic for an instruction if applicable. /// The assembly module containing the instruction. /// The CIL processor. - /// The instruction to handle. + /// The CIL instruction to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) { // field reference FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); diff --git a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs index 44b531a5..fefa88f4 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs @@ -2,12 +2,13 @@ using System.Collections.Generic; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; +using StardewModdingAPI.Framework.ModLoading.Framework; namespace StardewModdingAPI.Framework.ModLoading.Finders { /// Finds references to a field, property, or method which no longer exists. /// This implementation is purely heuristic. It should never return a false positive, but won't detect all cases. - internal class ReferenceToMissingMemberFinder : IInstructionHandler + internal class ReferenceToMissingMemberFinder : BaseInstructionHandler { /********* ** Fields @@ -16,40 +17,24 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders private readonly HashSet ValidateReferencesToAssemblies; - /********* - ** Accessors - *********/ - /// A brief noun phrase indicating what the instruction finder matches. - public string NounPhrase { get; private set; } = ""; - - /********* ** Public methods *********/ /// Construct an instance. /// The assembly names to which to heuristically detect broken references. public ReferenceToMissingMemberFinder(string[] validateReferencesToAssemblies) + : base(nounPhrase: "") { this.ValidateReferencesToAssemblies = new HashSet(validateReferencesToAssemblies); } - /// Perform the predefined logic for a method if applicable. - /// The assembly module containing the instruction. - /// The method definition containing the instruction. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - return InstructionHandleResult.None; - } - /// Perform the predefined logic for an instruction if applicable. /// The assembly module containing the instruction. /// The CIL processor. - /// The instruction to handle. + /// The CIL instruction to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) { // field reference FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs new file mode 100644 index 00000000..10780d07 --- /dev/null +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs @@ -0,0 +1,51 @@ +using Mono.Cecil; +using Mono.Cecil.Cil; + +namespace StardewModdingAPI.Framework.ModLoading.Framework +{ + /// The base implementation for a CIL instruction handler or rewriter. + internal abstract class BaseInstructionHandler : IInstructionHandler + { + /********* + ** Accessors + *********/ + /// A brief noun phrase indicating what the handler matches. + public string NounPhrase { get; protected set; } + + + /********* + ** Public methods + *********/ + /// Perform the predefined logic for a method if applicable. + /// The assembly module containing the instruction. + /// The method definition to handle. + /// Metadata for mapping assemblies to the current platform. + /// Whether the mod was compiled on a different platform. + public virtual InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) + { + return InstructionHandleResult.None; + } + + /// Perform the predefined logic for an instruction if applicable. + /// The assembly module containing the instruction. + /// The CIL processor. + /// The CIL instruction to handle. + /// Metadata for mapping assemblies to the current platform. + /// Whether the mod was compiled on a different platform. + public virtual InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + { + return InstructionHandleResult.None; + } + + + /********* + ** Protected methods + *********/ + /// Construct an instance. + /// A brief noun phrase indicating what the handler matches. + protected BaseInstructionHandler(string nounPhrase) + { + this.NounPhrase = nounPhrase; + } + } +} diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs index b1547334..cfd87922 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs @@ -6,7 +6,7 @@ using Mono.Cecil.Cil; namespace StardewModdingAPI.Framework.ModLoading.Framework { /// Finds incompatible CIL type reference instructions. - internal abstract class BaseTypeFinder : IInstructionHandler + internal abstract class BaseTypeFinder : BaseInstructionHandler { /********* ** Accessors @@ -18,33 +18,15 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework private readonly InstructionHandleResult Result; - /********* - ** Accessors - *********/ - /// A brief noun phrase indicating what the instruction finder matches. - public string NounPhrase { get; } - - /********* ** Public methods *********/ - /// Construct an instance. - /// Matches the type references to handle. - /// The result to return for matching instructions. - /// A brief noun phrase indicating what the instruction finder matches. - public BaseTypeFinder(Func isMatch, InstructionHandleResult result, string nounPhrase) - { - this.IsMatchImpl = isMatch; - this.Result = result; - this.NounPhrase = nounPhrase; - } - /// Perform the predefined logic for a method if applicable. /// The assembly module containing the instruction. - /// The method definition containing the instruction. + /// The method definition to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) + public override InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) { return this.IsMatch(method) ? this.Result @@ -54,10 +36,10 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /// Perform the predefined logic for an instruction if applicable. /// The assembly module containing the instruction. /// The CIL processor. - /// The instruction to handle. + /// The CIL instruction to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) { return this.IsMatch(instruction) ? this.Result @@ -127,5 +109,20 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework return false; } + + + /********* + ** Protected methods + *********/ + /// Construct an instance. + /// Matches the type references to handle. + /// The result to return for matching instructions. + /// A brief noun phrase indicating what the instruction finder matches. + protected BaseTypeFinder(Func isMatch, InstructionHandleResult result, string nounPhrase) + : base(nounPhrase) + { + this.IsMatchImpl = isMatch; + this.Result = result; + } } } diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs index 55ce6b5a..5f38a30b 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs @@ -5,7 +5,7 @@ using Mono.Cecil.Cil; namespace StardewModdingAPI.Framework.ModLoading.Framework { /// Rewrites all references to a type. - internal abstract class BaseTypeReferenceRewriter : IInstructionHandler + internal abstract class BaseTypeReferenceRewriter : BaseInstructionHandler { /********* ** Fields @@ -14,31 +14,15 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework private readonly BaseTypeFinder Finder; - /********* - ** Accessors - *********/ - /// A brief noun phrase indicating what the handler matches. - public string NounPhrase { get; } - - /********* ** Public methods *********/ - /// Construct an instance. - /// The type finder which matches types to rewrite. - /// A brief noun phrase indicating what the instruction finder matches. - public BaseTypeReferenceRewriter(BaseTypeFinder finder, string nounPhrase) - { - this.Finder = finder; - this.NounPhrase = nounPhrase; - } - /// Perform the predefined logic for a method if applicable. /// The assembly module containing the instruction. - /// The method definition containing the instruction. + /// The method definition to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. - public InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) + public override InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) { bool rewritten = false; @@ -78,10 +62,10 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /// Perform the predefined logic for an instruction if applicable. /// The assembly module containing the instruction. /// The CIL processor. - /// The instruction to handle. + /// The CIL instruction to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. - public InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) { if (!this.Finder.IsMatch(instruction)) return InstructionHandleResult.None; @@ -114,9 +98,19 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework : InstructionHandleResult.None; } + /********* - ** Private methods + ** Protected methods *********/ + /// Construct an instance. + /// The type finder which matches types to rewrite. + /// A brief noun phrase indicating what the instruction finder matches. + protected BaseTypeReferenceRewriter(BaseTypeFinder finder, string nounPhrase) + : base(nounPhrase) + { + this.Finder = finder; + } + /// Change a type reference if needed. /// The assembly module containing the instruction. /// The type to replace if it matches. diff --git a/src/SMAPI/Framework/ModLoading/IInstructionHandler.cs b/src/SMAPI/Framework/ModLoading/IInstructionHandler.cs index 8830cc74..65b45b08 100644 --- a/src/SMAPI/Framework/ModLoading/IInstructionHandler.cs +++ b/src/SMAPI/Framework/ModLoading/IInstructionHandler.cs @@ -18,7 +18,7 @@ namespace StardewModdingAPI.Framework.ModLoading *********/ /// Perform the predefined logic for a method if applicable. /// The assembly module containing the instruction. - /// The method definition containing the instruction. + /// The method definition to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged); @@ -26,7 +26,7 @@ namespace StardewModdingAPI.Framework.ModLoading /// Perform the predefined logic for an instruction if applicable. /// The assembly module containing the instruction. /// The CIL processor. - /// The instruction to handle. + /// The CIL instruction to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged); diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs index c4c740b3..c6388295 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs @@ -2,11 +2,12 @@ using System; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; +using StardewModdingAPI.Framework.ModLoading.Framework; namespace StardewModdingAPI.Framework.ModLoading.Rewriters { /// Rewrites method references from one parent type to another if the signatures match. - internal class MethodParentRewriter : IInstructionHandler + internal class MethodParentRewriter : BaseInstructionHandler { /********* ** Fields @@ -21,13 +22,6 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters private readonly bool OnlyIfPlatformChanged; - /********* - ** Accessors - *********/ - /// A brief noun phrase indicating what the instruction finder matches. - public string NounPhrase { get; } - - /********* ** Public methods *********/ @@ -37,10 +31,10 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// Whether to only rewrite references if loading the assembly on a different platform than it was compiled on. /// A brief noun phrase indicating what the instruction finder matches (or null to generate one). public MethodParentRewriter(string fromType, Type toType, bool onlyIfPlatformChanged = false, string nounPhrase = null) + : base(nounPhrase ?? $"{fromType.Split('.').Last()} methods") { this.FromType = fromType; this.ToType = toType; - this.NounPhrase = nounPhrase ?? $"{fromType.Split('.').Last()} methods"; this.OnlyIfPlatformChanged = onlyIfPlatformChanged; } @@ -51,23 +45,14 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters public MethodParentRewriter(Type fromType, Type toType, bool onlyIfPlatformChanged = false) : this(fromType.FullName, toType, onlyIfPlatformChanged) { } - /// Perform the predefined logic for a method if applicable. - /// The assembly module containing the instruction. - /// The method definition containing the instruction. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - return InstructionHandleResult.None; - } /// Perform the predefined logic for an instruction if applicable. /// The assembly module containing the instruction. /// The CIL processor. - /// The instruction to handle. + /// The CIL instruction to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. - public InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) { if (!this.IsMatch(instruction, platformChanged)) return InstructionHandleResult.None; -- cgit From 311033964924b69961c3a9f3e21e6e3ea880910e Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 9 May 2020 00:51:56 -0400 Subject: add attribute type rewriting (#711) --- docs/release-notes.md | 2 + src/SMAPI/Framework/ModLoading/AssemblyLoader.cs | 46 +++++------ .../ModLoading/Framework/BaseInstructionHandler.cs | 10 +++ .../ModLoading/Framework/BaseTypeFinder.cs | 29 +++++++ .../Framework/BaseTypeReferenceRewriter.cs | 88 +++++++++++++++++++++- .../Framework/ModLoading/IInstructionHandler.cs | 7 ++ src/SMAPI/Framework/ModLoading/RewriteHelper.cs | 67 ++++++++++++++++ 7 files changed, 224 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/docs/release-notes.md b/docs/release-notes.md index 8037c10c..91acb14e 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -4,6 +4,8 @@ ## Upcoming released * For modders: * Added `Multiplayer.PeerConnected` event. + * Migrated to Harmony 2.0 (see [_migrate to Harmony 2.0_](https://stardewvalleywiki.com/Modding:Migrate_to_Harmony_2.0) for more info). + * Harmony mods which use the `[HarmonyPatch(type)]` attribute now work crossplatform. Previously SMAPI couldn't rewrite types in custom attributes for compatibility. * Fixed asset propagation for Gil's portraits. ## 3.5 diff --git a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs index b5533335..5b5a621b 100644 --- a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs +++ b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs @@ -285,31 +285,44 @@ namespace StardewModdingAPI.Framework.ModLoading // find (and optionally rewrite) incompatible instructions bool anyRewritten = false; IInstructionHandler[] handlers = new InstructionMetadata().GetHandlers(this.ParanoidMode).ToArray(); - foreach (MethodDefinition method in this.GetMethods(module)) + foreach (TypeDefinition type in module.GetTypes()) { - // check method definition + // check type definition foreach (IInstructionHandler handler in handlers) { - InstructionHandleResult result = handler.Handle(module, method, this.AssemblyMap, platformChanged); + InstructionHandleResult result = handler.Handle(module, type, this.AssemblyMap, platformChanged); this.ProcessInstructionHandleResult(mod, handler, result, loggedMessages, logPrefix, filename); if (result == InstructionHandleResult.Rewritten) anyRewritten = true; } - // check CIL instructions - ILProcessor cil = method.Body.GetILProcessor(); - var instructions = cil.Body.Instructions; - // ReSharper disable once ForCanBeConvertedToForeach -- deliberate access by index so each handler sees replacements from previous handlers - for (int offset = 0; offset < instructions.Count; offset++) + // check methods + foreach (MethodDefinition method in type.Methods.Where(p => p.HasBody)) { + // check method definition foreach (IInstructionHandler handler in handlers) { - Instruction instruction = instructions[offset]; - InstructionHandleResult result = handler.Handle(module, cil, instruction, this.AssemblyMap, platformChanged); + InstructionHandleResult result = handler.Handle(module, method, this.AssemblyMap, platformChanged); this.ProcessInstructionHandleResult(mod, handler, result, loggedMessages, logPrefix, filename); if (result == InstructionHandleResult.Rewritten) anyRewritten = true; } + + // check CIL instructions + ILProcessor cil = method.Body.GetILProcessor(); + var instructions = cil.Body.Instructions; + // ReSharper disable once ForCanBeConvertedToForeach -- deliberate access by index so each handler sees replacements from previous handlers + for (int offset = 0; offset < instructions.Count; offset++) + { + foreach (IInstructionHandler handler in handlers) + { + Instruction instruction = instructions[offset]; + InstructionHandleResult result = handler.Handle(module, cil, instruction, this.AssemblyMap, platformChanged); + this.ProcessInstructionHandleResult(mod, handler, result, loggedMessages, logPrefix, filename); + if (result == InstructionHandleResult.Rewritten) + anyRewritten = true; + } + } } } @@ -395,18 +408,5 @@ namespace StardewModdingAPI.Framework.ModLoading AssemblyNameReference assemblyRef = this.AssemblyMap.TargetReferences[assembly]; type.Scope = assemblyRef; } - - /// Get all methods in a module. - /// The module to search. - private IEnumerable GetMethods(ModuleDefinition module) - { - return ( - from type in module.GetTypes() - where type.HasMethods - from method in type.Methods - where method.HasBody - select method - ); - } } } diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs index 10780d07..353de464 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs @@ -16,6 +16,16 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /********* ** Public methods *********/ + /// Perform the predefined logic for a method if applicable. + /// The assembly module containing the instruction. + /// The type definition to handle. + /// Metadata for mapping assemblies to the current platform. + /// Whether the mod was compiled on a different platform. + public virtual InstructionHandleResult Handle(ModuleDefinition module, TypeDefinition type, PlatformAssemblyMap assemblyMap, bool platformChanged) + { + return InstructionHandleResult.None; + } + /// Perform the predefined logic for a method if applicable. /// The assembly module containing the instruction. /// The method definition to handle. diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs index cfd87922..48165c4c 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs @@ -50,9 +50,38 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /// The method definition. public bool IsMatch(MethodDefinition method) { + // return type if (this.IsMatch(method.ReturnType)) return true; + // parameters + foreach (ParameterDefinition parameter in method.Parameters) + { + if (this.IsMatch(parameter.ParameterType)) + return true; + } + + // generic parameters + foreach (GenericParameter parameter in method.GenericParameters) + { + if (this.IsMatch(parameter)) + return true; + } + + // custom attributes + foreach (CustomAttribute attribute in method.CustomAttributes) + { + if (this.IsMatch(attribute.AttributeType)) + return true; + + foreach (var arg in attribute.ConstructorArguments) + { + if (this.IsMatch(arg.Type)) + return true; + } + } + + // local variables foreach (VariableDefinition variable in method.Body.Variables) { if (this.IsMatch(variable.VariableType)) diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs index 5f38a30b..445ac2cb 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs @@ -1,6 +1,8 @@ using System; +using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; +using Mono.Collections.Generic; namespace StardewModdingAPI.Framework.ModLoading.Framework { @@ -17,6 +19,20 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /********* ** Public methods *********/ + /// Perform the predefined logic for a method if applicable. + /// The assembly module containing the instruction. + /// The type definition to handle. + /// Metadata for mapping assemblies to the current platform. + /// Whether the mod was compiled on a different platform. + public override InstructionHandleResult Handle(ModuleDefinition module, TypeDefinition type, PlatformAssemblyMap assemblyMap, bool platformChanged) + { + bool rewritten = this.RewriteCustomAttributesIfNeeded(module, type.CustomAttributes); + + return rewritten + ? InstructionHandleResult.Rewritten + : InstructionHandleResult.None; + } + /// Perform the predefined logic for a method if applicable. /// The assembly module containing the instruction. /// The method definition to handle. @@ -28,9 +44,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework // return type if (this.Finder.IsMatch(method.ReturnType)) - { rewritten |= this.RewriteIfNeeded(module, method.ReturnType, newType => method.ReturnType = newType); - } // parameters foreach (ParameterDefinition parameter in method.Parameters) @@ -47,6 +61,9 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework rewritten |= this.RewriteIfNeeded(module, parameter, newType => method.GenericParameters[i] = new GenericParameter(parameter.Name, newType)); } + // custom attributes + rewritten |= this.RewriteCustomAttributesIfNeeded(module, method.CustomAttributes); + // local variables foreach (VariableDefinition variable in method.Body.Variables) { @@ -116,5 +133,72 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /// The type to replace if it matches. /// Assign the new type reference. protected abstract bool RewriteIfNeeded(ModuleDefinition module, TypeReference type, Action set); + + /// Rewrite custom attributes if needed. + /// The assembly module containing the attributes. + /// The custom attributes to handle. + private bool RewriteCustomAttributesIfNeeded(ModuleDefinition module, Collection attributes) + { + bool rewritten = false; + + for (int attrIndex = 0; attrIndex < attributes.Count; attrIndex++) + { + CustomAttribute attribute = attributes[attrIndex]; + bool curChanged = false; + + // attribute type + TypeReference newAttrType = null; + if (this.Finder.IsMatch(attribute.AttributeType)) + { + rewritten |= this.RewriteIfNeeded(module, attribute.AttributeType, newType => + { + newAttrType = newType; + curChanged = true; + }); + } + + // constructor arguments + TypeReference[] argTypes = new TypeReference[attribute.ConstructorArguments.Count]; + for (int i = 0; i < argTypes.Length; i++) + { + var arg = attribute.ConstructorArguments[i]; + + argTypes[i] = arg.Type; + rewritten |= this.RewriteIfNeeded(module, arg.Type, newType => + { + argTypes[i] = newType; + curChanged = true; + }); + } + + // swap attribute + if (curChanged) + { + // get constructor + MethodDefinition constructor = (newAttrType ?? attribute.AttributeType) + .Resolve() + .Methods + .Where(method => method.IsConstructor) + .FirstOrDefault(ctor => RewriteHelper.HasMatchingSignature(ctor, attribute.Constructor)); + if (constructor == null) + throw new InvalidOperationException($"Can't rewrite attribute type '{attribute.AttributeType.FullName}' to '{newAttrType?.FullName}', no equivalent constructor found."); + + // create new attribute + var newAttr = new CustomAttribute(module.ImportReference(constructor)); + for (int i = 0; i < argTypes.Length; i++) + newAttr.ConstructorArguments.Add(new CustomAttributeArgument(argTypes[i], attribute.ConstructorArguments[i].Value)); + foreach (var prop in attribute.Properties) + newAttr.Properties.Add(new CustomAttributeNamedArgument(prop.Name, prop.Argument)); + foreach (var field in attribute.Fields) + newAttr.Fields.Add(new CustomAttributeNamedArgument(field.Name, field.Argument)); + + // swap attribute + attributes[attrIndex] = newAttr; + rewritten = true; + } + } + + return rewritten; + } } } diff --git a/src/SMAPI/Framework/ModLoading/IInstructionHandler.cs b/src/SMAPI/Framework/ModLoading/IInstructionHandler.cs index 65b45b08..f9d320a6 100644 --- a/src/SMAPI/Framework/ModLoading/IInstructionHandler.cs +++ b/src/SMAPI/Framework/ModLoading/IInstructionHandler.cs @@ -16,6 +16,13 @@ namespace StardewModdingAPI.Framework.ModLoading /********* ** Methods *********/ + /// Perform the predefined logic for a method if applicable. + /// The assembly module containing the instruction. + /// The type definition to handle. + /// Metadata for mapping assemblies to the current platform. + /// Whether the mod was compiled on a different platform. + InstructionHandleResult Handle(ModuleDefinition module, TypeDefinition type, PlatformAssemblyMap assemblyMap, bool platformChanged); + /// Perform the predefined logic for a method if applicable. /// The assembly module containing the instruction. /// The method definition to handle. diff --git a/src/SMAPI/Framework/ModLoading/RewriteHelper.cs b/src/SMAPI/Framework/ModLoading/RewriteHelper.cs index d9a49cfa..553679f9 100644 --- a/src/SMAPI/Framework/ModLoading/RewriteHelper.cs +++ b/src/SMAPI/Framework/ModLoading/RewriteHelper.cs @@ -42,6 +42,10 @@ namespace StardewModdingAPI.Framework.ModLoading /// The type reference. public static bool IsSameType(Type type, TypeReference reference) { + // + // duplicated by IsSameType(TypeReference, TypeReference) below + // + // same namespace & name if (type.Namespace != reference.Namespace || type.Name != reference.Name) return false; @@ -66,6 +70,39 @@ namespace StardewModdingAPI.Framework.ModLoading return true; } + /// Get whether a type matches a type reference. + /// The defined type. + /// The type reference. + public static bool IsSameType(TypeReference type, TypeReference reference) + { + // + // duplicated by IsSameType(Type, TypeReference) above + // + + // same namespace & name + if (type.Namespace != reference.Namespace || type.Name != reference.Name) + return false; + + // same generic parameters + if (type.IsGenericInstance) + { + if (!reference.IsGenericInstance) + return false; + + TypeReference[] defGenerics = ((GenericInstanceType)type).GenericArguments.ToArray(); + TypeReference[] refGenerics = ((GenericInstanceType)reference).GenericArguments.ToArray(); + if (defGenerics.Length != refGenerics.Length) + return false; + for (int i = 0; i < defGenerics.Length; i++) + { + if (!RewriteHelper.IsSameType(defGenerics[i], refGenerics[i])) + return false; + } + } + + return true; + } + /// Determine whether two type IDs look like the same type, accounting for placeholder values such as !0. /// The type ID to compare. /// The other type ID to compare. @@ -80,6 +117,10 @@ namespace StardewModdingAPI.Framework.ModLoading /// The method reference. public static bool HasMatchingSignature(MethodInfo definition, MethodReference reference) { + // + // duplicated by HasMatchingSignature(MethodDefinition, MethodReference) below + // + // same name if (definition.Name != reference.Name) return false; @@ -97,6 +138,32 @@ namespace StardewModdingAPI.Framework.ModLoading return true; } + /// Get whether a method definition matches the signature expected by a method reference. + /// The method definition. + /// The method reference. + public static bool HasMatchingSignature(MethodDefinition definition, MethodReference reference) + { + // + // duplicated by HasMatchingSignature(MethodInfo, MethodReference) above + // + + // same name + if (definition.Name != reference.Name) + return false; + + // same arguments + ParameterDefinition[] definitionParameters = definition.Parameters.ToArray(); + ParameterDefinition[] referenceParameters = reference.Parameters.ToArray(); + if (referenceParameters.Length != definitionParameters.Length) + return false; + for (int i = 0; i < referenceParameters.Length; i++) + { + if (!RewriteHelper.IsSameType(definitionParameters[i].ParameterType, referenceParameters[i].ParameterType)) + return false; + } + return true; + } + /// Get whether a type has a method whose signature matches the one expected by a method reference. /// The type to check. /// The method reference. -- cgit From 19397a89ff6f0d216637e1272b78c7e15c85bf76 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 9 May 2020 09:23:27 -0400 Subject: log detailed error for rewritten patch failures (#711) --- .../RewriteFacades/HarmonyInstanceMethods.cs | 26 ++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs b/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs index 0f906f51..bca76981 100644 --- a/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs +++ b/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs @@ -1,3 +1,5 @@ +using System; +using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; @@ -24,10 +26,30 @@ namespace StardewModdingAPI.Framework.RewriteFacades return new Harmony(id); } + /// Apply one or more patches to a method. + /// The original method. + /// The prefix to apply. + /// The postfix to apply. + /// The transpiler to apply. public DynamicMethod Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null) { - MethodInfo method = base.Patch(original: original, prefix: prefix, postfix: postfix, transpiler: transpiler); - return new DynamicMethod(method.Name, method.Attributes, method.CallingConvention, method.ReturnType, method.GetParameters().Select(p => p.ParameterType).ToArray(), method.Module, true); + try + { + MethodInfo method = base.Patch(original: original, prefix: prefix, postfix: postfix, transpiler: transpiler); + return new DynamicMethod(method.Name, method.Attributes, method.CallingConvention, method.ReturnType, method.GetParameters().Select(p => p.ParameterType).ToArray(), method.Module, true); + } + catch (Exception ex) + { + var patchTypes = new List(); + if (prefix != null) + patchTypes.Add("prefix"); + if (postfix != null) + patchTypes.Add("postfix"); + if (transpiler != null) + patchTypes.Add("transpiler"); + + throw new Exception($"Failed applying {string.Join("/", patchTypes)} to method {original.DeclaringType?.FullName}.{original.Name}", ex); + } } } } -- cgit From 1ff09685906b03b46b23e69b7bfe95df24c8184f Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 9 May 2020 20:45:45 -0400 Subject: fixed generic types in method references not rewritten (#711) --- docs/release-notes.md | 3 +++ src/SMAPI/Framework/ModLoading/AssemblyLoader.cs | 8 +++++++- .../Framework/ModLoading/Framework/BaseTypeFinder.cs | 19 +++++++++++++++---- .../ModLoading/Framework/BaseTypeReferenceRewriter.cs | 5 +++++ 4 files changed, 30 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/docs/release-notes.md b/docs/release-notes.md index 91acb14e..de4684ec 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -6,6 +6,9 @@ * Added `Multiplayer.PeerConnected` event. * Migrated to Harmony 2.0 (see [_migrate to Harmony 2.0_](https://stardewvalleywiki.com/Modding:Migrate_to_Harmony_2.0) for more info). * Harmony mods which use the `[HarmonyPatch(type)]` attribute now work crossplatform. Previously SMAPI couldn't rewrite types in custom attributes for compatibility. + * Improved mod rewriting for compatibility: + * Fixed rewriting types in custom attributes. + * Fixed rewriting generic types to method references. * Fixed asset propagation for Gil's portraits. ## 3.5 diff --git a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs index 5b5a621b..570686fe 100644 --- a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs +++ b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs @@ -314,13 +314,19 @@ namespace StardewModdingAPI.Framework.ModLoading // ReSharper disable once ForCanBeConvertedToForeach -- deliberate access by index so each handler sees replacements from previous handlers for (int offset = 0; offset < instructions.Count; offset++) { + Instruction instruction = instructions[offset]; + if (instruction.OpCode.Code == Code.Nop) + continue; + foreach (IInstructionHandler handler in handlers) { - Instruction instruction = instructions[offset]; InstructionHandleResult result = handler.Handle(module, cil, instruction, this.AssemblyMap, platformChanged); this.ProcessInstructionHandleResult(mod, handler, result, loggedMessages, logPrefix, filename); if (result == InstructionHandleResult.Rewritten) + { + instruction = instructions[offset]; anyRewritten = true; + } } } } diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs index 48165c4c..04b2e08d 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs @@ -108,10 +108,21 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); if (methodRef != null) { - return - this.IsMatch(methodRef.DeclaringType) // method on target class - || this.IsMatch(methodRef.ReturnType) // method returns target class - || methodRef.Parameters.Any(p => this.IsMatch(p.ParameterType)); // method parameters + // method on target class + if (this.IsMatch(methodRef.DeclaringType)) + return true; + + // method returns target class + if (this.IsMatch(methodRef.ReturnType)) + return true; + + // method parameters of target class + if (methodRef.Parameters.Any(p => this.IsMatch(p.ParameterType))) + return true; + + // generic args of target class + if (methodRef is GenericInstanceMethod genericRef && genericRef.GenericArguments.Any(this.IsMatch)) + return true; } return false; diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs index 445ac2cb..3ccacf22 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs @@ -104,6 +104,11 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework rewritten |= this.RewriteIfNeeded(module, methodRef.ReturnType, newType => methodRef.ReturnType = newType); foreach (var parameter in methodRef.Parameters) rewritten |= this.RewriteIfNeeded(module, parameter.ParameterType, newType => parameter.ParameterType = newType); + if (methodRef is GenericInstanceMethod genericRef) + { + for (int i = 0; i < genericRef.GenericArguments.Count; i++) + rewritten |= this.RewriteIfNeeded(module, genericRef.GenericArguments[i], newType => genericRef.GenericArguments[i] = newType); + } } // type reference -- cgit From 10531e537fda7c4901304b295f4ef60ac1f83eea Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 10 May 2020 11:50:35 -0400 Subject: rewrite AccessTools methods which changed in Harmony 2.0 (#711) --- .../ModLoading/Rewriters/MethodParentRewriter.cs | 5 ++-- .../Framework/RewriteFacades/AccessToolsMethods.cs | 32 ++++++++++++++++++++++ .../RewriteFacades/HarmonyInstanceMethods.cs | 11 ++------ src/SMAPI/Metadata/InstructionMetadata.cs | 3 +- 4 files changed, 40 insertions(+), 11 deletions(-) create mode 100644 src/SMAPI/Framework/RewriteFacades/AccessToolsMethods.cs (limited to 'src') diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs index c6388295..d0fe8b13 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs @@ -42,8 +42,9 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// The type whose methods to remap. /// The type with methods to map to. /// Whether to only rewrite references if loading the assembly on a different platform than it was compiled on. - public MethodParentRewriter(Type fromType, Type toType, bool onlyIfPlatformChanged = false) - : this(fromType.FullName, toType, onlyIfPlatformChanged) { } + /// A brief noun phrase indicating what the instruction finder matches (or null to generate one). + public MethodParentRewriter(Type fromType, Type toType, bool onlyIfPlatformChanged = false, string nounPhrase = null) + : this(fromType.FullName, toType, onlyIfPlatformChanged, nounPhrase) { } /// Perform the predefined logic for an instruction if applicable. diff --git a/src/SMAPI/Framework/RewriteFacades/AccessToolsMethods.cs b/src/SMAPI/Framework/RewriteFacades/AccessToolsMethods.cs new file mode 100644 index 00000000..cb40bbcc --- /dev/null +++ b/src/SMAPI/Framework/RewriteFacades/AccessToolsMethods.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using HarmonyLib; + +namespace StardewModdingAPI.Framework.RewriteFacades +{ + /// Maps Harmony 1.x methods to Harmony 2.x to avoid breaking older mods. + /// This is public to support SMAPI rewriting and should not be referenced directly by mods. + [SuppressMessage("ReSharper", "CS1591", Justification = "Documentation not needed for facade classes.")] + public class AccessToolsMethods + { + /********* + ** Public methods + *********/ + public static ConstructorInfo DeclaredConstructor(Type type, Type[] parameters = null) + { + return AccessTools.DeclaredConstructor(type, parameters, searchForStatic: true); + } + + public static ConstructorInfo Constructor(Type type, Type[] parameters = null) + { + return AccessTools.Constructor(type, parameters, searchForStatic: true); + } + + public static List GetDeclaredConstructors(Type type) + { + return AccessTools.GetDeclaredConstructors(type, searchForStatic: true); + } + } +} diff --git a/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs b/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs index bca76981..aad62c9b 100644 --- a/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs +++ b/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Reflection.Emit; @@ -7,8 +8,9 @@ using HarmonyLib; namespace StardewModdingAPI.Framework.RewriteFacades { - /// Maps Harmony 1.x methods to Harmony 2.x to avoid breaking older mods. + /// Maps Harmony 1.x HarmonyInstance methods to Harmony 2.x's to avoid breaking older mods. /// This is public to support SMAPI rewriting and should not be referenced directly by mods. + [SuppressMessage("ReSharper", "CS1591", Justification = "Documentation not needed for facade classes.")] public class HarmonyInstanceMethods : Harmony { /********* @@ -19,18 +21,11 @@ namespace StardewModdingAPI.Framework.RewriteFacades public HarmonyInstanceMethods(string id) : base(id) { } - /// Creates a new Harmony instance. - /// A unique identifier for the instance. public static Harmony Create(string id) { return new Harmony(id); } - /// Apply one or more patches to a method. - /// The original method. - /// The prefix to apply. - /// The postfix to apply. - /// The transpiler to apply. public DynamicMethod Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null) { try diff --git a/src/SMAPI/Metadata/InstructionMetadata.cs b/src/SMAPI/Metadata/InstructionMetadata.cs index 64216138..40a7588e 100644 --- a/src/SMAPI/Metadata/InstructionMetadata.cs +++ b/src/SMAPI/Metadata/InstructionMetadata.cs @@ -38,7 +38,8 @@ namespace StardewModdingAPI.Metadata // rewrite for SMAPI 3.6 (Harmony 1.x => 2.0 update) yield return new Harmony1AssemblyRewriter(); - yield return new MethodParentRewriter("HarmonyLib.Harmony", typeof(HarmonyInstanceMethods), onlyIfPlatformChanged: false, nounPhrase: Harmony1AssemblyRewriter.DefaultNounPhrase); + yield return new MethodParentRewriter(typeof(HarmonyLib.Harmony), typeof(HarmonyInstanceMethods), onlyIfPlatformChanged: false, nounPhrase: Harmony1AssemblyRewriter.DefaultNounPhrase); + yield return new MethodParentRewriter(typeof(HarmonyLib.AccessTools), typeof(AccessToolsMethods), onlyIfPlatformChanged: false, nounPhrase: Harmony1AssemblyRewriter.DefaultNounPhrase); /**** ** detect mod issues -- cgit From 2b9703f98fedcf97fd5e511f1e30bcc8fd94b5cc Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 11 May 2020 01:40:46 -0400 Subject: fix Harmony issue when assembly is loaded from memory (#711) --- src/SMAPI.Installer/InteractiveInstaller.cs | 40 ++---------------------- src/SMAPI/Constants.cs | 3 ++ src/SMAPI/Framework/ModLoading/AssemblyLoader.cs | 27 ++++++++++++++-- src/SMAPI/Framework/SCore.cs | 16 +++++++++- 4 files changed, 44 insertions(+), 42 deletions(-) (limited to 'src') diff --git a/src/SMAPI.Installer/InteractiveInstaller.cs b/src/SMAPI.Installer/InteractiveInstaller.cs index 5b0c6e1f..1457848b 100644 --- a/src/SMAPI.Installer/InteractiveInstaller.cs +++ b/src/SMAPI.Installer/InteractiveInstaller.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; -using System.Threading; using Microsoft.Win32; using StardewModdingApi.Installer.Enums; using StardewModdingAPI.Installer.Framework; @@ -624,7 +623,7 @@ namespace StardewModdingApi.Installer { try { - this.ForceDelete(Directory.Exists(path) ? new DirectoryInfo(path) : (FileSystemInfo)new FileInfo(path)); + FileUtilities.ForceDelete(Directory.Exists(path) ? new DirectoryInfo(path) : (FileSystemInfo)new FileInfo(path)); break; } catch (Exception ex) @@ -665,41 +664,6 @@ namespace StardewModdingApi.Installer } } - /// Delete a file or folder regardless of file permissions, and block until deletion completes. - /// The file or folder to reset. - /// This method is mirrored from FileUtilities.ForceDelete in the toolkit. - private void ForceDelete(FileSystemInfo entry) - { - // ignore if already deleted - entry.Refresh(); - if (!entry.Exists) - return; - - // delete children - if (entry is DirectoryInfo folder) - { - foreach (FileSystemInfo child in folder.GetFileSystemInfos()) - this.ForceDelete(child); - } - - // reset permissions & delete - entry.Attributes = FileAttributes.Normal; - entry.Delete(); - - // wait for deletion to finish - for (int i = 0; i < 10; i++) - { - entry.Refresh(); - if (entry.Exists) - Thread.Sleep(500); - } - - // throw exception if deletion didn't happen before timeout - entry.Refresh(); - if (entry.Exists) - throw new IOException($"Timed out trying to delete {entry.FullName}"); - } - /// Interactively ask the user to choose a value. /// A callback which prints a message to the console. /// The message to print. @@ -707,7 +671,7 @@ namespace StardewModdingApi.Installer /// The indentation to prefix to output. private string InteractivelyChoose(string message, string[] options, string indent = "", Action print = null) { - print = print ?? this.PrintInfo; + print ??= this.PrintInfo; while (true) { diff --git a/src/SMAPI/Constants.cs b/src/SMAPI/Constants.cs index a898fccd..907a93b2 100644 --- a/src/SMAPI/Constants.cs +++ b/src/SMAPI/Constants.cs @@ -61,6 +61,9 @@ namespace StardewModdingAPI /// The absolute path to the folder containing SMAPI's internal files. internal static readonly string InternalFilesPath = Program.DllSearchPath; + /// The folder containing temporary files that are only valid for the current session. + internal static string InternalTempFilesPath => Path.Combine(Program.DllSearchPath, ".temp"); + /// The file path for the SMAPI configuration file. internal static string ApiConfigPath => Path.Combine(Constants.InternalFilesPath, "config.json"); diff --git a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs index 570686fe..78e717e9 100644 --- a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs +++ b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs @@ -36,6 +36,9 @@ namespace StardewModdingAPI.Framework.ModLoading /// The objects to dispose as part of this instance. private readonly HashSet Disposables = new HashSet(); + /// The full path to the folder in which to save rewritten assemblies. + private readonly string TempFolderPath; + /********* ** Public methods @@ -44,11 +47,15 @@ namespace StardewModdingAPI.Framework.ModLoading /// The current game platform. /// Encapsulates monitoring and logging. /// Whether to detect paranoid mode issues. - public AssemblyLoader(Platform targetPlatform, IMonitor monitor, bool paranoidMode) + /// The full path to the folder in which to save rewritten assemblies. + public AssemblyLoader(Platform targetPlatform, IMonitor monitor, bool paranoidMode, string tempFolderPath) { this.Monitor = monitor; this.ParanoidMode = paranoidMode; this.AssemblyMap = this.TrackForDisposal(Constants.GetAssemblyMap(targetPlatform)); + this.TempFolderPath = tempFolderPath; + + // init resolver this.AssemblyDefinitionResolver = this.TrackForDisposal(new AssemblyDefinitionResolver()); this.AssemblyDefinitionResolver.AddSearchDirectory(Constants.ExecutionPath); this.AssemblyDefinitionResolver.AddSearchDirectory(Constants.InternalFilesPath); @@ -124,9 +131,23 @@ namespace StardewModdingAPI.Framework.ModLoading if (changed) { if (!oneAssembly) - this.Monitor.Log($" Loading {assembly.File.Name} (rewritten in memory)...", LogLevel.Trace); - using (MemoryStream outStream = new MemoryStream()) + this.Monitor.Log($" Loading {assembly.File.Name} (rewritten)...", LogLevel.Trace); + + if (assembly.Definition.MainModule.AssemblyReferences.Any(p => p.Name == "0Harmony")) + { + // Note: the assembly must be loaded from disk for Harmony compatibility. + // Loading it from memory sets the assembly module's FullyQualifiedName to + // "", so Harmony incorrectly identifies the module in its + // Patch.PatchMethod when handling multiple patches for the same method, + // leading to "Token 0x... is not valid in the scope of module HarmonySharedState" + // errors (e.g. https://smapi.io/log/A0gAsc3M). + string tempPath = Path.Combine(this.TempFolderPath, $"{Path.GetFileNameWithoutExtension(assemblyPath)}.{Guid.NewGuid()}.dll"); + assembly.Definition.Write(tempPath); + lastAssembly = Assembly.LoadFile(tempPath); + } + else { + using MemoryStream outStream = new MemoryStream(); assembly.Definition.Write(outStream); byte[] bytes = outStream.ToArray(); lastAssembly = Assembly.Load(bytes); diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index de9c955d..12dc9c3d 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -213,6 +213,20 @@ namespace StardewModdingAPI.Framework return; } #endif + + // reset temp folder + if (Directory.Exists(Constants.InternalTempFilesPath)) + { + try + { + FileUtilities.ForceDelete(new DirectoryInfo(Constants.InternalTempFilesPath)); + } + catch (Exception ex) + { + this.Monitor.Log($"Couldn't delete temporary files at {Constants.InternalTempFilesPath}: {ex}", LogLevel.Trace); + } + } + Directory.CreateDirectory(Constants.InternalTempFilesPath); } /// Launch SMAPI. @@ -748,7 +762,7 @@ namespace StardewModdingAPI.Framework // load mods IDictionary> skippedMods = new Dictionary>(); - using (AssemblyLoader modAssemblyLoader = new AssemblyLoader(Constants.Platform, this.Monitor, this.Settings.ParanoidWarnings)) + using (AssemblyLoader modAssemblyLoader = new AssemblyLoader(Constants.Platform, this.Monitor, this.Settings.ParanoidWarnings, Constants.InternalTempFilesPath)) { // init HashSet suppressUpdateChecks = new HashSet(this.Settings.SuppressUpdateChecks, StringComparer.InvariantCultureIgnoreCase); -- cgit From e626e5817e66f1133d125ab49866b8a0475dde07 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 13 May 2020 20:52:09 -0400 Subject: tweak Harmony patch error (#711) --- src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs b/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs index aad62c9b..995a40d6 100644 --- a/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs +++ b/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs @@ -43,7 +43,7 @@ namespace StardewModdingAPI.Framework.RewriteFacades if (transpiler != null) patchTypes.Add("transpiler"); - throw new Exception($"Failed applying {string.Join("/", patchTypes)} to method {original.DeclaringType?.FullName}.{original.Name}", ex); + throw new Exception($"Harmony instance {this.Id} failed applying {string.Join("/", patchTypes)} to method {original.DeclaringType?.FullName}.{original.Name}.", ex); } } } -- cgit From b34d7470e2769a50e87a33e1cb3a8da637a2f143 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 18 May 2020 17:24:16 -0400 Subject: simplify patch facade (#711) Thanks to 0x0ade for the suggestion! --- src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs b/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs index 995a40d6..8e4ef7df 100644 --- a/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs +++ b/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Reflection; using System.Reflection.Emit; using HarmonyLib; @@ -31,7 +30,7 @@ namespace StardewModdingAPI.Framework.RewriteFacades try { MethodInfo method = base.Patch(original: original, prefix: prefix, postfix: postfix, transpiler: transpiler); - return new DynamicMethod(method.Name, method.Attributes, method.CallingConvention, method.ReturnType, method.GetParameters().Select(p => p.ParameterType).ToArray(), method.Module, true); + return (DynamicMethod)method; } catch (Exception ex) { -- cgit From 21303a4e987e4169f3bf0c55c7099d0d07536ca5 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 18 May 2020 17:26:47 -0400 Subject: remove workaround no longer needed with Harmony 2.0.2 (#711) --- src/SMAPI/Constants.cs | 3 --- src/SMAPI/Framework/ModLoading/AssemblyLoader.cs | 30 ++++-------------------- src/SMAPI/Framework/SCore.cs | 16 +------------ 3 files changed, 6 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/SMAPI/Constants.cs b/src/SMAPI/Constants.cs index 907a93b2..a898fccd 100644 --- a/src/SMAPI/Constants.cs +++ b/src/SMAPI/Constants.cs @@ -61,9 +61,6 @@ namespace StardewModdingAPI /// The absolute path to the folder containing SMAPI's internal files. internal static readonly string InternalFilesPath = Program.DllSearchPath; - /// The folder containing temporary files that are only valid for the current session. - internal static string InternalTempFilesPath => Path.Combine(Program.DllSearchPath, ".temp"); - /// The file path for the SMAPI configuration file. internal static string ApiConfigPath => Path.Combine(Constants.InternalFilesPath, "config.json"); diff --git a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs index 78e717e9..b95a45b5 100644 --- a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs +++ b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs @@ -36,9 +36,6 @@ namespace StardewModdingAPI.Framework.ModLoading /// The objects to dispose as part of this instance. private readonly HashSet Disposables = new HashSet(); - /// The full path to the folder in which to save rewritten assemblies. - private readonly string TempFolderPath; - /********* ** Public methods @@ -47,13 +44,11 @@ namespace StardewModdingAPI.Framework.ModLoading /// The current game platform. /// Encapsulates monitoring and logging. /// Whether to detect paranoid mode issues. - /// The full path to the folder in which to save rewritten assemblies. - public AssemblyLoader(Platform targetPlatform, IMonitor monitor, bool paranoidMode, string tempFolderPath) + public AssemblyLoader(Platform targetPlatform, IMonitor monitor, bool paranoidMode) { this.Monitor = monitor; this.ParanoidMode = paranoidMode; this.AssemblyMap = this.TrackForDisposal(Constants.GetAssemblyMap(targetPlatform)); - this.TempFolderPath = tempFolderPath; // init resolver this.AssemblyDefinitionResolver = this.TrackForDisposal(new AssemblyDefinitionResolver()); @@ -133,25 +128,10 @@ namespace StardewModdingAPI.Framework.ModLoading if (!oneAssembly) this.Monitor.Log($" Loading {assembly.File.Name} (rewritten)...", LogLevel.Trace); - if (assembly.Definition.MainModule.AssemblyReferences.Any(p => p.Name == "0Harmony")) - { - // Note: the assembly must be loaded from disk for Harmony compatibility. - // Loading it from memory sets the assembly module's FullyQualifiedName to - // "", so Harmony incorrectly identifies the module in its - // Patch.PatchMethod when handling multiple patches for the same method, - // leading to "Token 0x... is not valid in the scope of module HarmonySharedState" - // errors (e.g. https://smapi.io/log/A0gAsc3M). - string tempPath = Path.Combine(this.TempFolderPath, $"{Path.GetFileNameWithoutExtension(assemblyPath)}.{Guid.NewGuid()}.dll"); - assembly.Definition.Write(tempPath); - lastAssembly = Assembly.LoadFile(tempPath); - } - else - { - using MemoryStream outStream = new MemoryStream(); - assembly.Definition.Write(outStream); - byte[] bytes = outStream.ToArray(); - lastAssembly = Assembly.Load(bytes); - } + using MemoryStream outStream = new MemoryStream(); + assembly.Definition.Write(outStream); + byte[] bytes = outStream.ToArray(); + lastAssembly = Assembly.Load(bytes); } else { diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index 12dc9c3d..de9c955d 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -213,20 +213,6 @@ namespace StardewModdingAPI.Framework return; } #endif - - // reset temp folder - if (Directory.Exists(Constants.InternalTempFilesPath)) - { - try - { - FileUtilities.ForceDelete(new DirectoryInfo(Constants.InternalTempFilesPath)); - } - catch (Exception ex) - { - this.Monitor.Log($"Couldn't delete temporary files at {Constants.InternalTempFilesPath}: {ex}", LogLevel.Trace); - } - } - Directory.CreateDirectory(Constants.InternalTempFilesPath); } /// Launch SMAPI. @@ -762,7 +748,7 @@ namespace StardewModdingAPI.Framework // load mods IDictionary> skippedMods = new Dictionary>(); - using (AssemblyLoader modAssemblyLoader = new AssemblyLoader(Constants.Platform, this.Monitor, this.Settings.ParanoidWarnings, Constants.InternalTempFilesPath)) + using (AssemblyLoader modAssemblyLoader = new AssemblyLoader(Constants.Platform, this.Monitor, this.Settings.ParanoidWarnings)) { // init HashSet suppressUpdateChecks = new HashSet(this.Settings.SuppressUpdateChecks, StringComparer.InvariantCultureIgnoreCase); -- cgit From d1bf3d52352df4bb720cf0fa87dcd6a64f35446a Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 18 May 2020 22:44:06 -0400 Subject: move facade namespace (#711) --- .../RewriteFacades/AccessToolsMethods.cs | 32 ++++++++++++ .../RewriteFacades/HarmonyInstanceMethods.cs | 49 +++++++++++++++++ .../RewriteFacades/SpriteBatchMethods.cs | 61 ++++++++++++++++++++++ .../Framework/RewriteFacades/AccessToolsMethods.cs | 32 ------------ .../RewriteFacades/HarmonyInstanceMethods.cs | 49 ----------------- .../Framework/RewriteFacades/SpriteBatchMethods.cs | 61 ---------------------- src/SMAPI/Metadata/InstructionMetadata.cs | 2 +- 7 files changed, 143 insertions(+), 143 deletions(-) create mode 100644 src/SMAPI/Framework/ModLoading/RewriteFacades/AccessToolsMethods.cs create mode 100644 src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyInstanceMethods.cs create mode 100644 src/SMAPI/Framework/ModLoading/RewriteFacades/SpriteBatchMethods.cs delete mode 100644 src/SMAPI/Framework/RewriteFacades/AccessToolsMethods.cs delete mode 100644 src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs delete mode 100644 src/SMAPI/Framework/RewriteFacades/SpriteBatchMethods.cs (limited to 'src') diff --git a/src/SMAPI/Framework/ModLoading/RewriteFacades/AccessToolsMethods.cs b/src/SMAPI/Framework/ModLoading/RewriteFacades/AccessToolsMethods.cs new file mode 100644 index 00000000..ea35fec9 --- /dev/null +++ b/src/SMAPI/Framework/ModLoading/RewriteFacades/AccessToolsMethods.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using HarmonyLib; + +namespace StardewModdingAPI.Framework.ModLoading.RewriteFacades +{ + /// Maps Harmony 1.x methods to Harmony 2.x to avoid breaking older mods. + /// This is public to support SMAPI rewriting and should not be referenced directly by mods. + [SuppressMessage("ReSharper", "CS1591", Justification = "Documentation not needed for facade classes.")] + public class AccessToolsMethods + { + /********* + ** Public methods + *********/ + public static ConstructorInfo DeclaredConstructor(Type type, Type[] parameters = null) + { + return AccessTools.DeclaredConstructor(type, parameters, searchForStatic: true); + } + + public static ConstructorInfo Constructor(Type type, Type[] parameters = null) + { + return AccessTools.Constructor(type, parameters, searchForStatic: true); + } + + public static List GetDeclaredConstructors(Type type) + { + return AccessTools.GetDeclaredConstructors(type, searchForStatic: true); + } + } +} diff --git a/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyInstanceMethods.cs b/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyInstanceMethods.cs new file mode 100644 index 00000000..78cf25f8 --- /dev/null +++ b/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyInstanceMethods.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Reflection.Emit; +using HarmonyLib; + +namespace StardewModdingAPI.Framework.ModLoading.RewriteFacades +{ + /// Maps Harmony 1.x HarmonyInstance methods to Harmony 2.x's to avoid breaking older mods. + /// This is public to support SMAPI rewriting and should not be referenced directly by mods. + [SuppressMessage("ReSharper", "CS1591", Justification = "Documentation not needed for facade classes.")] + public class HarmonyInstanceMethods : Harmony + { + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The unique patch identifier. + public HarmonyInstanceMethods(string id) + : base(id) { } + + public static Harmony Create(string id) + { + return new Harmony(id); + } + + public DynamicMethod Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null) + { + try + { + MethodInfo method = base.Patch(original: original, prefix: prefix, postfix: postfix, transpiler: transpiler); + return (DynamicMethod)method; + } + catch (Exception ex) + { + var patchTypes = new List(); + if (prefix != null) + patchTypes.Add("prefix"); + if (postfix != null) + patchTypes.Add("postfix"); + if (transpiler != null) + patchTypes.Add("transpiler"); + + throw new Exception($"Harmony instance {this.Id} failed applying {string.Join("/", patchTypes)} to method {original.DeclaringType?.FullName}.{original.Name}.", ex); + } + } + } +} diff --git a/src/SMAPI/Framework/ModLoading/RewriteFacades/SpriteBatchMethods.cs b/src/SMAPI/Framework/ModLoading/RewriteFacades/SpriteBatchMethods.cs new file mode 100644 index 00000000..75bb61ef --- /dev/null +++ b/src/SMAPI/Framework/ModLoading/RewriteFacades/SpriteBatchMethods.cs @@ -0,0 +1,61 @@ +using System.Diagnostics.CodeAnalysis; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; + +#pragma warning disable 1591 // missing documentation +namespace StardewModdingAPI.Framework.ModLoading.RewriteFacades +{ + /// Provides method signatures that can be injected into mod code for compatibility between Linux/Mac or Windows. + /// This is public to support SMAPI rewriting and should not be referenced directly by mods. + public class SpriteBatchMethods : SpriteBatch + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public SpriteBatchMethods(GraphicsDevice graphicsDevice) : base(graphicsDevice) { } + + + /**** + ** MonoGame signatures + ****/ + [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Linux/Mac.")] + public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect, Matrix? matrix) + { + base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, matrix ?? Matrix.Identity); + } + + /**** + ** XNA signatures + ****/ + [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")] + public new void Begin() + { + base.Begin(); + } + + [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")] + public new void Begin(SpriteSortMode sortMode, BlendState blendState) + { + base.Begin(sortMode, blendState); + } + + [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")] + public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState) + { + base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState); + } + + [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")] + public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect) + { + base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect); + } + + [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")] + public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect, Matrix transformMatrix) + { + base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, transformMatrix); + } + } +} diff --git a/src/SMAPI/Framework/RewriteFacades/AccessToolsMethods.cs b/src/SMAPI/Framework/RewriteFacades/AccessToolsMethods.cs deleted file mode 100644 index cb40bbcc..00000000 --- a/src/SMAPI/Framework/RewriteFacades/AccessToolsMethods.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Reflection; -using HarmonyLib; - -namespace StardewModdingAPI.Framework.RewriteFacades -{ - /// Maps Harmony 1.x methods to Harmony 2.x to avoid breaking older mods. - /// This is public to support SMAPI rewriting and should not be referenced directly by mods. - [SuppressMessage("ReSharper", "CS1591", Justification = "Documentation not needed for facade classes.")] - public class AccessToolsMethods - { - /********* - ** Public methods - *********/ - public static ConstructorInfo DeclaredConstructor(Type type, Type[] parameters = null) - { - return AccessTools.DeclaredConstructor(type, parameters, searchForStatic: true); - } - - public static ConstructorInfo Constructor(Type type, Type[] parameters = null) - { - return AccessTools.Constructor(type, parameters, searchForStatic: true); - } - - public static List GetDeclaredConstructors(Type type) - { - return AccessTools.GetDeclaredConstructors(type, searchForStatic: true); - } - } -} diff --git a/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs b/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs deleted file mode 100644 index 8e4ef7df..00000000 --- a/src/SMAPI/Framework/RewriteFacades/HarmonyInstanceMethods.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Reflection; -using System.Reflection.Emit; -using HarmonyLib; - -namespace StardewModdingAPI.Framework.RewriteFacades -{ - /// Maps Harmony 1.x HarmonyInstance methods to Harmony 2.x's to avoid breaking older mods. - /// This is public to support SMAPI rewriting and should not be referenced directly by mods. - [SuppressMessage("ReSharper", "CS1591", Justification = "Documentation not needed for facade classes.")] - public class HarmonyInstanceMethods : Harmony - { - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The unique patch identifier. - public HarmonyInstanceMethods(string id) - : base(id) { } - - public static Harmony Create(string id) - { - return new Harmony(id); - } - - public DynamicMethod Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null) - { - try - { - MethodInfo method = base.Patch(original: original, prefix: prefix, postfix: postfix, transpiler: transpiler); - return (DynamicMethod)method; - } - catch (Exception ex) - { - var patchTypes = new List(); - if (prefix != null) - patchTypes.Add("prefix"); - if (postfix != null) - patchTypes.Add("postfix"); - if (transpiler != null) - patchTypes.Add("transpiler"); - - throw new Exception($"Harmony instance {this.Id} failed applying {string.Join("/", patchTypes)} to method {original.DeclaringType?.FullName}.{original.Name}.", ex); - } - } - } -} diff --git a/src/SMAPI/Framework/RewriteFacades/SpriteBatchMethods.cs b/src/SMAPI/Framework/RewriteFacades/SpriteBatchMethods.cs deleted file mode 100644 index 26b22315..00000000 --- a/src/SMAPI/Framework/RewriteFacades/SpriteBatchMethods.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; - -#pragma warning disable 1591 // missing documentation -namespace StardewModdingAPI.Framework.RewriteFacades -{ - /// Provides method signatures that can be injected into mod code for compatibility between Linux/Mac or Windows. - /// This is public to support SMAPI rewriting and should not be referenced directly by mods. - public class SpriteBatchMethods : SpriteBatch - { - /********* - ** Public methods - *********/ - /// Construct an instance. - public SpriteBatchMethods(GraphicsDevice graphicsDevice) : base(graphicsDevice) { } - - - /**** - ** MonoGame signatures - ****/ - [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Linux/Mac.")] - public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect, Matrix? matrix) - { - base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, matrix ?? Matrix.Identity); - } - - /**** - ** XNA signatures - ****/ - [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")] - public new void Begin() - { - base.Begin(); - } - - [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")] - public new void Begin(SpriteSortMode sortMode, BlendState blendState) - { - base.Begin(sortMode, blendState); - } - - [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")] - public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState) - { - base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState); - } - - [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")] - public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect) - { - base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect); - } - - [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")] - public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect, Matrix transformMatrix) - { - base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, transformMatrix); - } - } -} diff --git a/src/SMAPI/Metadata/InstructionMetadata.cs b/src/SMAPI/Metadata/InstructionMetadata.cs index 40a7588e..d80f64e2 100644 --- a/src/SMAPI/Metadata/InstructionMetadata.cs +++ b/src/SMAPI/Metadata/InstructionMetadata.cs @@ -3,8 +3,8 @@ using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Events; using StardewModdingAPI.Framework.ModLoading; using StardewModdingAPI.Framework.ModLoading.Finders; +using StardewModdingAPI.Framework.ModLoading.RewriteFacades; using StardewModdingAPI.Framework.ModLoading.Rewriters; -using StardewModdingAPI.Framework.RewriteFacades; using StardewValley; namespace StardewModdingAPI.Metadata -- cgit From f96dde00f98a913557617f716673f1af355cc6b5 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 18 May 2020 23:11:17 -0400 Subject: fix some type references not being rewritten (#711) --- src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs index 04b2e08d..8c85b6a5 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs @@ -125,6 +125,10 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework return true; } + // type reference + if (instruction.Operand is TypeReference typeRef && this.IsMatch(typeRef)) + return true; + return false; } -- cgit From 1838842bbc2db2d1049c193b8650bd101ba4858f Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 19 May 2020 20:57:50 -0400 Subject: rewrite assembly rewriting, merge Harmony rewriters (#711) This reduces duplication, decouples it from the assembly loader, and makes it more flexible to handle Harmony rewriting. --- src/SMAPI/Framework/ModLoading/AssemblyLoader.cs | 100 ++++---- .../Framework/ModLoading/Finders/EventFinder.cs | 18 +- .../Framework/ModLoading/Finders/FieldFinder.cs | 31 +-- .../Framework/ModLoading/Finders/MethodFinder.cs | 18 +- .../Framework/ModLoading/Finders/PropertyFinder.cs | 18 +- .../ReferenceToMemberWithUnexpectedTypeFinder.cs | 27 +-- .../Finders/ReferenceToMissingMemberFinder.cs | 28 ++- .../ModLoading/Finders/TypeAssemblyFinder.cs | 42 +++- .../Framework/ModLoading/Finders/TypeFinder.cs | 42 +++- .../ModLoading/Framework/BaseInstructionHandler.cs | 66 ++++-- .../ModLoading/Framework/BaseTypeFinder.cs | 172 -------------- .../Framework/BaseTypeReferenceRewriter.cs | 209 ----------------- .../ModLoading/Framework/RecursiveRewriter.cs | 260 +++++++++++++++++++++ .../ModLoading/Framework/RewriteHelper.cs | 199 ++++++++++++++++ .../Framework/ModLoading/IInstructionHandler.cs | 35 +-- src/SMAPI/Framework/ModLoading/RewriteHelper.cs | 177 -------------- .../ModLoading/Rewriters/FieldReplaceRewriter.cs | 37 +-- .../Rewriters/FieldToPropertyRewriter.cs | 42 ++-- .../Rewriters/Harmony1AssemblyRewriter.cs | 107 ++++++--- .../ModLoading/Rewriters/MethodParentRewriter.cs | 40 ++-- .../Rewriters/StaticFieldToConstantRewriter.cs | 35 ++- .../ModLoading/Rewriters/TypeReferenceRewriter.cs | 50 ++-- src/SMAPI/Metadata/InstructionMetadata.cs | 8 +- 23 files changed, 879 insertions(+), 882 deletions(-) delete mode 100644 src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs delete mode 100644 src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs create mode 100644 src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs create mode 100644 src/SMAPI/Framework/ModLoading/Framework/RewriteHelper.cs delete mode 100644 src/SMAPI/Framework/ModLoading/RewriteHelper.cs (limited to 'src') diff --git a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs index b95a45b5..d9b4af1b 100644 --- a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs +++ b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs @@ -4,8 +4,8 @@ using System.IO; using System.Linq; using System.Reflection; using Mono.Cecil; -using Mono.Cecil.Cil; using StardewModdingAPI.Framework.Exceptions; +using StardewModdingAPI.Framework.ModLoading.Framework; using StardewModdingAPI.Metadata; using StardewModdingAPI.Toolkit.Framework.ModData; using StardewModdingAPI.Toolkit.Utilities; @@ -283,54 +283,32 @@ namespace StardewModdingAPI.Framework.ModLoading this.ChangeTypeScope(type); } - // find (and optionally rewrite) incompatible instructions - bool anyRewritten = false; - IInstructionHandler[] handlers = new InstructionMetadata().GetHandlers(this.ParanoidMode).ToArray(); - foreach (TypeDefinition type in module.GetTypes()) - { - // check type definition - foreach (IInstructionHandler handler in handlers) + // find or rewrite code + IInstructionHandler[] handlers = new InstructionMetadata().GetHandlers(this.ParanoidMode, platformChanged).ToArray(); + RecursiveRewriter rewriter = new RecursiveRewriter( + module: module, + rewriteType: (type, replaceWith) => { - InstructionHandleResult result = handler.Handle(module, type, this.AssemblyMap, platformChanged); - this.ProcessInstructionHandleResult(mod, handler, result, loggedMessages, logPrefix, filename); - if (result == InstructionHandleResult.Rewritten) - anyRewritten = true; - } - - // check methods - foreach (MethodDefinition method in type.Methods.Where(p => p.HasBody)) + bool rewritten = false; + foreach (IInstructionHandler handler in handlers) + rewritten |= handler.Handle(module, type, replaceWith); + return rewritten; + }, + rewriteInstruction: (instruction, cil, replaceWith) => { - // check method definition + bool rewritten = false; foreach (IInstructionHandler handler in handlers) - { - InstructionHandleResult result = handler.Handle(module, method, this.AssemblyMap, platformChanged); - this.ProcessInstructionHandleResult(mod, handler, result, loggedMessages, logPrefix, filename); - if (result == InstructionHandleResult.Rewritten) - anyRewritten = true; - } - - // check CIL instructions - ILProcessor cil = method.Body.GetILProcessor(); - var instructions = cil.Body.Instructions; - // ReSharper disable once ForCanBeConvertedToForeach -- deliberate access by index so each handler sees replacements from previous handlers - for (int offset = 0; offset < instructions.Count; offset++) - { - Instruction instruction = instructions[offset]; - if (instruction.OpCode.Code == Code.Nop) - continue; - - foreach (IInstructionHandler handler in handlers) - { - InstructionHandleResult result = handler.Handle(module, cil, instruction, this.AssemblyMap, platformChanged); - this.ProcessInstructionHandleResult(mod, handler, result, loggedMessages, logPrefix, filename); - if (result == InstructionHandleResult.Rewritten) - { - instruction = instructions[offset]; - anyRewritten = true; - } - } - } + rewritten |= handler.Handle(module, cil, instruction, replaceWith); + return rewritten; } + ); + bool anyRewritten = rewriter.RewriteModule(); + + // handle rewrite flags + foreach (IInstructionHandler handler in handlers) + { + foreach (var flag in handler.Flags) + this.ProcessInstructionHandleResult(mod, handler, flag, loggedMessages, logPrefix, filename); } return platformChanged || anyRewritten; @@ -345,49 +323,52 @@ namespace StardewModdingAPI.Framework.ModLoading /// The assembly filename for log messages. private void ProcessInstructionHandleResult(IModMetadata mod, IInstructionHandler handler, InstructionHandleResult result, HashSet loggedMessages, string logPrefix, string filename) { + // get message template + // ($phrase is replaced with the noun phrase or messages) + string template = null; switch (result) { case InstructionHandleResult.Rewritten: - this.Monitor.LogOnce(loggedMessages, $"{logPrefix}Rewrote {filename} to fix {handler.NounPhrase}..."); + template = $"{logPrefix}Rewrote {filename} to fix $phrase..."; break; case InstructionHandleResult.NotCompatible: - this.Monitor.LogOnce(loggedMessages, $"{logPrefix}Broken code in {filename}: {handler.NounPhrase}."); + template = $"{logPrefix}Broken code in {filename}: $phrase."; mod.SetWarning(ModWarning.BrokenCodeLoaded); break; case InstructionHandleResult.DetectedGamePatch: - this.Monitor.LogOnce(loggedMessages, $"{logPrefix}Detected game patcher ({handler.NounPhrase}) in assembly {filename}."); + template = $"{logPrefix}Detected game patcher ($phrase) in assembly {filename}."; mod.SetWarning(ModWarning.PatchesGame); break; case InstructionHandleResult.DetectedSaveSerializer: - this.Monitor.LogOnce(loggedMessages, $"{logPrefix}Detected possible save serializer change ({handler.NounPhrase}) in assembly {filename}."); + template = $"{logPrefix}Detected possible save serializer change ($phrase) in assembly {filename}."; mod.SetWarning(ModWarning.ChangesSaveSerializer); break; case InstructionHandleResult.DetectedUnvalidatedUpdateTick: - this.Monitor.LogOnce(loggedMessages, $"{logPrefix}Detected reference to {handler.NounPhrase} in assembly {filename}."); + template = $"{logPrefix}Detected reference to $phrase in assembly {filename}."; mod.SetWarning(ModWarning.UsesUnvalidatedUpdateTick); break; case InstructionHandleResult.DetectedDynamic: - this.Monitor.LogOnce(loggedMessages, $"{logPrefix}Detected 'dynamic' keyword ({handler.NounPhrase}) in assembly {filename}."); + template = $"{logPrefix}Detected 'dynamic' keyword ($phrase) in assembly {filename}."; mod.SetWarning(ModWarning.UsesDynamic); break; case InstructionHandleResult.DetectedConsoleAccess: - this.Monitor.LogOnce(loggedMessages, $"{logPrefix}Detected direct console access ({handler.NounPhrase}) in assembly {filename}."); + template = $"{logPrefix}Detected direct console access ($phrase) in assembly {filename}."; mod.SetWarning(ModWarning.AccessesConsole); break; case InstructionHandleResult.DetectedFilesystemAccess: - this.Monitor.LogOnce(loggedMessages, $"{logPrefix}Detected filesystem access ({handler.NounPhrase}) in assembly {filename}."); + template = $"{logPrefix}Detected filesystem access ($phrase) in assembly {filename}."; mod.SetWarning(ModWarning.AccessesFilesystem); break; case InstructionHandleResult.DetectedShellAccess: - this.Monitor.LogOnce(loggedMessages, $"{logPrefix}Detected shell or process access ({handler.NounPhrase}) in assembly {filename}."); + template = $"{logPrefix}Detected shell or process access ($phrase) in assembly {filename}."; mod.SetWarning(ModWarning.AccessesShell); break; @@ -397,6 +378,17 @@ namespace StardewModdingAPI.Framework.ModLoading default: throw new NotSupportedException($"Unrecognized instruction handler result '{result}'."); } + if (template == null) + return; + + // format messages + if (handler.Phrases.Any()) + { + foreach (string message in handler.Phrases) + this.Monitor.LogOnce(template.Replace("$phrase", message)); + } + else + this.Monitor.LogOnce(template.Replace("$phrase", handler.DefaultPhrase ?? handler.GetType().Name)); } /// Get the correct reference to use for compatibility with the current platform. diff --git a/src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs index 1a7ae636..e1476b73 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs @@ -1,3 +1,4 @@ +using System; using Mono.Cecil; using Mono.Cecil.Cil; using StardewModdingAPI.Framework.ModLoading.Framework; @@ -28,24 +29,25 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The event name for which to find references. /// The result to return for matching instructions. public EventFinder(string fullTypeName, string eventName, InstructionHandleResult result) - : base(nounPhrase: $"{fullTypeName}.{eventName} event") + : base(defaultPhrase: $"{fullTypeName}.{eventName} event") { this.FullTypeName = fullTypeName; this.EventName = eventName; this.Result = result; } - /// Perform the predefined logic for an instruction if applicable. + /// Rewrite a CIL instruction reference if needed. /// The assembly module containing the instruction. /// The CIL processor. /// The CIL instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + /// Replaces the CIL instruction with a new one. + /// Returns whether the instruction was changed. + public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, Action replaceWith) { - return this.IsMatch(instruction) - ? this.Result - : InstructionHandleResult.None; + if (!this.Flags.Contains(this.Result) && this.IsMatch(instruction)) + this.MarkFlag(this.Result); + + return false; } diff --git a/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs index 9ae07916..c157ed9b 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs @@ -1,3 +1,4 @@ +using System; using Mono.Cecil; using Mono.Cecil.Cil; using StardewModdingAPI.Framework.ModLoading.Framework; @@ -28,39 +29,25 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The field name for which to find references. /// The result to return for matching instructions. public FieldFinder(string fullTypeName, string fieldName, InstructionHandleResult result) - : base(nounPhrase: $"{fullTypeName}.{fieldName} field") + : base(defaultPhrase: $"{fullTypeName}.{fieldName} field") { this.FullTypeName = fullTypeName; this.FieldName = fieldName; this.Result = result; } - /// Perform the predefined logic for an instruction if applicable. + /// Rewrite a CIL instruction reference if needed. /// The assembly module containing the instruction. /// The CIL processor. /// The CIL instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + /// Replaces the CIL instruction with a new one. + /// Returns whether the instruction was changed. + public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, Action replaceWith) { - return this.IsMatch(instruction) - ? this.Result - : InstructionHandleResult.None; - } - + if (!this.Flags.Contains(this.Result) && RewriteHelper.IsFieldReferenceTo(instruction, this.FullTypeName, this.FieldName)) + this.MarkFlag(this.Result); - /********* - ** Protected methods - *********/ - /// Get whether a CIL instruction matches. - /// The IL instruction. - protected bool IsMatch(Instruction instruction) - { - FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); - return - fieldRef != null - && fieldRef.DeclaringType.FullName == this.FullTypeName - && fieldRef.Name == this.FieldName; + return false; } } } diff --git a/src/SMAPI/Framework/ModLoading/Finders/MethodFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/MethodFinder.cs index 75584f1f..82c93a7c 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/MethodFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/MethodFinder.cs @@ -1,3 +1,4 @@ +using System; using Mono.Cecil; using Mono.Cecil.Cil; using StardewModdingAPI.Framework.ModLoading.Framework; @@ -28,24 +29,25 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The method name for which to find references. /// The result to return for matching instructions. public MethodFinder(string fullTypeName, string methodName, InstructionHandleResult result) - : base(nounPhrase: $"{fullTypeName}.{methodName} method") + : base(defaultPhrase: $"{fullTypeName}.{methodName} method") { this.FullTypeName = fullTypeName; this.MethodName = methodName; this.Result = result; } - /// Perform the predefined logic for an instruction if applicable. + /// Rewrite a CIL instruction reference if needed. /// The assembly module containing the instruction. /// The CIL processor. /// The CIL instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + /// Replaces the CIL instruction with a new one. + /// Returns whether the instruction was changed. + public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, Action replaceWith) { - return this.IsMatch(instruction) - ? this.Result - : InstructionHandleResult.None; + if (!this.Flags.Contains(this.Result) && this.IsMatch(instruction)) + this.MarkFlag(this.Result); + + return false; } diff --git a/src/SMAPI/Framework/ModLoading/Finders/PropertyFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/PropertyFinder.cs index 811420c5..c96d61a2 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/PropertyFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/PropertyFinder.cs @@ -1,3 +1,4 @@ +using System; using Mono.Cecil; using Mono.Cecil.Cil; using StardewModdingAPI.Framework.ModLoading.Framework; @@ -28,24 +29,25 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The property name for which to find references. /// The result to return for matching instructions. public PropertyFinder(string fullTypeName, string propertyName, InstructionHandleResult result) - : base(nounPhrase: $"{fullTypeName}.{propertyName} property") + : base(defaultPhrase: $"{fullTypeName}.{propertyName} property") { this.FullTypeName = fullTypeName; this.PropertyName = propertyName; this.Result = result; } - /// Perform the predefined logic for an instruction if applicable. + /// Rewrite a CIL instruction reference if needed. /// The assembly module containing the instruction. /// The CIL processor. /// The CIL instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + /// Replaces the CIL instruction with a new one. + /// Returns whether the instruction was changed. + public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, Action replaceWith) { - return this.IsMatch(instruction) - ? this.Result - : InstructionHandleResult.None; + if (!this.Flags.Contains(this.Result) && this.IsMatch(instruction)) + this.MarkFlag(this.Result); + + return false; } diff --git a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs index 1029d350..a67cfa4f 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using Mono.Cecil; @@ -23,18 +24,18 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// Construct an instance. /// The assembly names to which to heuristically detect broken references. public ReferenceToMemberWithUnexpectedTypeFinder(string[] validateReferencesToAssemblies) - : base(nounPhrase: "") + : base(defaultPhrase: "") { this.ValidateReferencesToAssemblies = new HashSet(validateReferencesToAssemblies); } - /// Perform the predefined logic for an instruction if applicable. + /// Rewrite a CIL instruction reference if needed. /// The assembly module containing the instruction. /// The CIL processor. /// The CIL instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + /// Replaces the CIL instruction with a new one. + /// Returns whether the instruction was changed. + public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, Action replaceWith) { // field reference FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); @@ -43,13 +44,13 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders // get target field FieldDefinition targetField = fieldRef.DeclaringType.Resolve()?.Fields.FirstOrDefault(p => p.Name == fieldRef.Name); if (targetField == null) - return InstructionHandleResult.None; + return false; // validate return type if (!RewriteHelper.LooksLikeSameType(fieldRef.FieldType, targetField.FieldType)) { - this.NounPhrase = $"reference to {fieldRef.DeclaringType.FullName}.{fieldRef.Name} (field returns {this.GetFriendlyTypeName(targetField.FieldType)}, not {this.GetFriendlyTypeName(fieldRef.FieldType)})"; - return InstructionHandleResult.NotCompatible; + this.MarkFlag(InstructionHandleResult.NotCompatible, $"reference to {fieldRef.DeclaringType.FullName}.{fieldRef.Name} (field returns {this.GetFriendlyTypeName(targetField.FieldType)}, not {this.GetFriendlyTypeName(fieldRef.FieldType)})"); + return false; } } @@ -60,21 +61,21 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders // get potential targets MethodDefinition[] candidateMethods = methodReference.DeclaringType.Resolve()?.Methods.Where(found => found.Name == methodReference.Name).ToArray(); if (candidateMethods == null || !candidateMethods.Any()) - return InstructionHandleResult.None; + return false; // compare return types MethodDefinition methodDef = methodReference.Resolve(); if (methodDef == null) - return InstructionHandleResult.None; // validated by ReferenceToMissingMemberFinder + return false; // validated by ReferenceToMissingMemberFinder if (candidateMethods.All(method => !RewriteHelper.LooksLikeSameType(method.ReturnType, methodDef.ReturnType))) { - this.NounPhrase = $"reference to {methodDef.DeclaringType.FullName}.{methodDef.Name} (no such method returns {this.GetFriendlyTypeName(methodDef.ReturnType)})"; - return InstructionHandleResult.NotCompatible; + this.MarkFlag(InstructionHandleResult.NotCompatible, $"reference to {methodDef.DeclaringType.FullName}.{methodDef.Name} (no such method returns {this.GetFriendlyTypeName(methodDef.ReturnType)})"); + return false; } } - return InstructionHandleResult.None; + return false; } diff --git a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs index fefa88f4..ebb62948 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using Mono.Cecil; @@ -23,18 +24,18 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// Construct an instance. /// The assembly names to which to heuristically detect broken references. public ReferenceToMissingMemberFinder(string[] validateReferencesToAssemblies) - : base(nounPhrase: "") + : base(defaultPhrase: "") { this.ValidateReferencesToAssemblies = new HashSet(validateReferencesToAssemblies); } - /// Perform the predefined logic for an instruction if applicable. + /// Rewrite a CIL instruction reference if needed. /// The assembly module containing the instruction. /// The CIL processor. /// The CIL instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + /// Replaces the CIL instruction with a new one. + /// Returns whether the instruction was changed. + public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, Action replaceWith) { // field reference FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); @@ -43,8 +44,8 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders FieldDefinition target = fieldRef.DeclaringType.Resolve()?.Fields.FirstOrDefault(p => p.Name == fieldRef.Name); if (target == null) { - this.NounPhrase = $"reference to {fieldRef.DeclaringType.FullName}.{fieldRef.Name} (no such field)"; - return InstructionHandleResult.NotCompatible; + this.MarkFlag(InstructionHandleResult.NotCompatible, $"reference to {fieldRef.DeclaringType.FullName}.{fieldRef.Name} (no such field)"); + return false; } } @@ -55,17 +56,20 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders MethodDefinition target = methodRef.Resolve(); if (target == null) { + string phrase = null; if (this.IsProperty(methodRef)) - this.NounPhrase = $"reference to {methodRef.DeclaringType.FullName}.{methodRef.Name.Substring(4)} (no such property)"; + phrase = $"reference to {methodRef.DeclaringType.FullName}.{methodRef.Name.Substring(4)} (no such property)"; else if (methodRef.Name == ".ctor") - this.NounPhrase = $"reference to {methodRef.DeclaringType.FullName}.{methodRef.Name} (no matching constructor)"; + phrase = $"reference to {methodRef.DeclaringType.FullName}.{methodRef.Name} (no matching constructor)"; else - this.NounPhrase = $"reference to {methodRef.DeclaringType.FullName}.{methodRef.Name} (no such method)"; - return InstructionHandleResult.NotCompatible; + phrase = $"reference to {methodRef.DeclaringType.FullName}.{methodRef.Name} (no such method)"; + + this.MarkFlag(InstructionHandleResult.NotCompatible, phrase); + return false; } } - return InstructionHandleResult.None; + return false; } diff --git a/src/SMAPI/Framework/ModLoading/Finders/TypeAssemblyFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/TypeAssemblyFinder.cs index 5301186b..a1ade536 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/TypeAssemblyFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/TypeAssemblyFinder.cs @@ -5,21 +5,47 @@ using StardewModdingAPI.Framework.ModLoading.Framework; namespace StardewModdingAPI.Framework.ModLoading.Finders { /// Finds incompatible CIL instructions that reference types in a given assembly. - internal class TypeAssemblyFinder : BaseTypeFinder + internal class TypeAssemblyFinder : BaseInstructionHandler { + /********* + ** Fields + *********/ + /// The full assembly name to which to find references. + private readonly string AssemblyName; + + /// The result to return for matching instructions. + private readonly InstructionHandleResult Result; + + /// Get whether a matched type should be ignored. + private readonly Func ShouldIgnore; + + /********* ** Public methods *********/ /// Construct an instance. /// The full assembly name to which to find references. /// The result to return for matching instructions. - /// A lambda which overrides a matched type. + /// Get whether a matched type should be ignored. public TypeAssemblyFinder(string assemblyName, InstructionHandleResult result, Func shouldIgnore = null) - : base( - isMatch: type => type.Scope.Name == assemblyName && (shouldIgnore == null || !shouldIgnore(type)), - result: result, - nounPhrase: $"{assemblyName} assembly" - ) - { } + : base(defaultPhrase: $"{assemblyName} assembly") + { + this.AssemblyName = assemblyName; + this.Result = result; + this.ShouldIgnore = shouldIgnore; + } + + /// Rewrite a type reference if needed. + /// The assembly module containing the instruction. + /// The type definition to handle. + /// Replaces the type reference with a new one. + /// Returns whether the type was changed. + public override bool Handle(ModuleDefinition module, TypeReference type, Action replaceWith) + { + if (type.Scope.Name == this.AssemblyName && this.ShouldIgnore?.Invoke(type) != true) + this.MarkFlag(this.Result); + + return false; + } } } diff --git a/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs index 3adc31c7..c285414a 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs @@ -5,21 +5,47 @@ using StardewModdingAPI.Framework.ModLoading.Framework; namespace StardewModdingAPI.Framework.ModLoading.Finders { /// Finds incompatible CIL instructions that reference a given type. - internal class TypeFinder : BaseTypeFinder + internal class TypeFinder : BaseInstructionHandler { + /********* + ** Fields + *********/ + /// The full type name to match. + private readonly string FullTypeName; + + /// The result to return for matching instructions. + private readonly InstructionHandleResult Result; + + /// Get whether a matched type should be ignored. + private readonly Func ShouldIgnore; + + /********* ** Public methods *********/ /// Construct an instance. /// The full type name to match. /// The result to return for matching instructions. - /// A lambda which overrides a matched type. + /// Get whether a matched type should be ignored. public TypeFinder(string fullTypeName, InstructionHandleResult result, Func shouldIgnore = null) - : base( - isMatch: type => type.FullName == fullTypeName && (shouldIgnore == null || !shouldIgnore(type)), - result: result, - nounPhrase: $"{fullTypeName} type" - ) - { } + : base(defaultPhrase: $"{fullTypeName} type") + { + this.FullTypeName = fullTypeName; + this.Result = result; + this.ShouldIgnore = shouldIgnore; + } + + /// Rewrite a type reference if needed. + /// The assembly module containing the instruction. + /// The type definition to handle. + /// Replaces the type reference with a new one. + /// Returns whether the type was changed. + public override bool Handle(ModuleDefinition module, TypeReference type, Action replaceWith) + { + if (type.FullName == this.FullTypeName && this.ShouldIgnore?.Invoke(type) != true) + this.MarkFlag(this.Result); + + return false; + } } } diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs index 353de464..79fb45b8 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs @@ -1,3 +1,5 @@ +using System; +using System.Collections.Generic; using Mono.Cecil; using Mono.Cecil.Cil; @@ -9,42 +11,38 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /********* ** Accessors *********/ - /// A brief noun phrase indicating what the handler matches. - public string NounPhrase { get; protected set; } + /// A brief noun phrase indicating what the handler matches, used if is empty. + public string DefaultPhrase { get; } + + /// The rewrite flags raised for the current module. + public ISet Flags { get; } = new HashSet(); + + /// The brief noun phrases indicating what the handler matched for the current module. + public ISet Phrases { get; } = new HashSet(StringComparer.InvariantCultureIgnoreCase); /********* ** Public methods *********/ - /// Perform the predefined logic for a method if applicable. + /// Rewrite a type reference if needed. /// The assembly module containing the instruction. /// The type definition to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, TypeDefinition type, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - return InstructionHandleResult.None; - } - - /// Perform the predefined logic for a method if applicable. - /// The assembly module containing the instruction. - /// The method definition to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) + /// Replaces the type reference with a new one. + /// Returns whether the type was changed. + public virtual bool Handle(ModuleDefinition module, TypeReference type, Action replaceWith) { - return InstructionHandleResult.None; + return false; } - /// Perform the predefined logic for an instruction if applicable. + /// Rewrite a CIL instruction reference if needed. /// The assembly module containing the instruction. /// The CIL processor. /// The CIL instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public virtual InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + /// Replaces the CIL instruction with a new one. + /// Returns whether the instruction was changed. + public virtual bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, Action replaceWith) { - return InstructionHandleResult.None; + return false; } @@ -52,10 +50,28 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework ** Protected methods *********/ /// Construct an instance. - /// A brief noun phrase indicating what the handler matches. - protected BaseInstructionHandler(string nounPhrase) + /// A brief noun phrase indicating what the handler matches. + protected BaseInstructionHandler(string defaultPhrase) + { + this.DefaultPhrase = defaultPhrase; + } + + /// Raise a result flag. + /// The result flag to set. + /// The result message to add. + /// Returns true for convenience. + protected bool MarkFlag(InstructionHandleResult flag, string resultMessage = null) + { + this.Flags.Add(flag); + if (resultMessage != null) + this.Phrases.Add(resultMessage); + return true; + } + + /// Raise a generic flag indicating that the code was rewritten. + public bool MarkRewritten() { - this.NounPhrase = nounPhrase; + return this.MarkFlag(InstructionHandleResult.Rewritten); } } } diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs deleted file mode 100644 index 8c85b6a5..00000000 --- a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeFinder.cs +++ /dev/null @@ -1,172 +0,0 @@ -using System; -using System.Linq; -using Mono.Cecil; -using Mono.Cecil.Cil; - -namespace StardewModdingAPI.Framework.ModLoading.Framework -{ - /// Finds incompatible CIL type reference instructions. - internal abstract class BaseTypeFinder : BaseInstructionHandler - { - /********* - ** Accessors - *********/ - /// Matches the type references to handle. - private readonly Func IsMatchImpl; - - /// The result to return for matching instructions. - private readonly InstructionHandleResult Result; - - - /********* - ** Public methods - *********/ - /// Perform the predefined logic for a method if applicable. - /// The assembly module containing the instruction. - /// The method definition to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - return this.IsMatch(method) - ? this.Result - : InstructionHandleResult.None; - } - - /// Perform the predefined logic for an instruction if applicable. - /// The assembly module containing the instruction. - /// The CIL processor. - /// The CIL instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - return this.IsMatch(instruction) - ? this.Result - : InstructionHandleResult.None; - } - - /// Get whether a CIL instruction matches. - /// The method definition. - public bool IsMatch(MethodDefinition method) - { - // return type - if (this.IsMatch(method.ReturnType)) - return true; - - // parameters - foreach (ParameterDefinition parameter in method.Parameters) - { - if (this.IsMatch(parameter.ParameterType)) - return true; - } - - // generic parameters - foreach (GenericParameter parameter in method.GenericParameters) - { - if (this.IsMatch(parameter)) - return true; - } - - // custom attributes - foreach (CustomAttribute attribute in method.CustomAttributes) - { - if (this.IsMatch(attribute.AttributeType)) - return true; - - foreach (var arg in attribute.ConstructorArguments) - { - if (this.IsMatch(arg.Type)) - return true; - } - } - - // local variables - foreach (VariableDefinition variable in method.Body.Variables) - { - if (this.IsMatch(variable.VariableType)) - return true; - } - - return false; - } - - /// Get whether a CIL instruction matches. - /// The IL instruction. - public bool IsMatch(Instruction instruction) - { - // field reference - FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); - if (fieldRef != null) - { - return - this.IsMatch(fieldRef.DeclaringType) // field on target class - || this.IsMatch(fieldRef.FieldType); // field value is target class - } - - // method reference - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); - if (methodRef != null) - { - // method on target class - if (this.IsMatch(methodRef.DeclaringType)) - return true; - - // method returns target class - if (this.IsMatch(methodRef.ReturnType)) - return true; - - // method parameters of target class - if (methodRef.Parameters.Any(p => this.IsMatch(p.ParameterType))) - return true; - - // generic args of target class - if (methodRef is GenericInstanceMethod genericRef && genericRef.GenericArguments.Any(this.IsMatch)) - return true; - } - - // type reference - if (instruction.Operand is TypeReference typeRef && this.IsMatch(typeRef)) - return true; - - return false; - } - - /// Get whether a type reference matches the expected type. - /// The type to check. - public bool IsMatch(TypeReference type) - { - // root type - if (this.IsMatchImpl(type)) - return true; - - // generic arguments - if (type is GenericInstanceType genericType) - { - if (genericType.GenericArguments.Any(this.IsMatch)) - return true; - } - - // generic parameters (e.g. constraints) - if (type.GenericParameters.Any(this.IsMatch)) - return true; - - return false; - } - - - /********* - ** Protected methods - *********/ - /// Construct an instance. - /// Matches the type references to handle. - /// The result to return for matching instructions. - /// A brief noun phrase indicating what the instruction finder matches. - protected BaseTypeFinder(Func isMatch, InstructionHandleResult result, string nounPhrase) - : base(nounPhrase) - { - this.IsMatchImpl = isMatch; - this.Result = result; - } - } -} diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs deleted file mode 100644 index 3ccacf22..00000000 --- a/src/SMAPI/Framework/ModLoading/Framework/BaseTypeReferenceRewriter.cs +++ /dev/null @@ -1,209 +0,0 @@ -using System; -using System.Linq; -using Mono.Cecil; -using Mono.Cecil.Cil; -using Mono.Collections.Generic; - -namespace StardewModdingAPI.Framework.ModLoading.Framework -{ - /// Rewrites all references to a type. - internal abstract class BaseTypeReferenceRewriter : BaseInstructionHandler - { - /********* - ** Fields - *********/ - /// The type finder which matches types to rewrite. - private readonly BaseTypeFinder Finder; - - - /********* - ** Public methods - *********/ - /// Perform the predefined logic for a method if applicable. - /// The assembly module containing the instruction. - /// The type definition to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, TypeDefinition type, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - bool rewritten = this.RewriteCustomAttributesIfNeeded(module, type.CustomAttributes); - - return rewritten - ? InstructionHandleResult.Rewritten - : InstructionHandleResult.None; - } - - /// Perform the predefined logic for a method if applicable. - /// The assembly module containing the instruction. - /// The method definition to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - bool rewritten = false; - - // return type - if (this.Finder.IsMatch(method.ReturnType)) - rewritten |= this.RewriteIfNeeded(module, method.ReturnType, newType => method.ReturnType = newType); - - // parameters - foreach (ParameterDefinition parameter in method.Parameters) - { - if (this.Finder.IsMatch(parameter.ParameterType)) - rewritten |= this.RewriteIfNeeded(module, parameter.ParameterType, newType => parameter.ParameterType = newType); - } - - // generic parameters - for (int i = 0; i < method.GenericParameters.Count; i++) - { - var parameter = method.GenericParameters[i]; - if (this.Finder.IsMatch(parameter)) - rewritten |= this.RewriteIfNeeded(module, parameter, newType => method.GenericParameters[i] = new GenericParameter(parameter.Name, newType)); - } - - // custom attributes - rewritten |= this.RewriteCustomAttributesIfNeeded(module, method.CustomAttributes); - - // local variables - foreach (VariableDefinition variable in method.Body.Variables) - { - if (this.Finder.IsMatch(variable.VariableType)) - rewritten |= this.RewriteIfNeeded(module, variable.VariableType, newType => variable.VariableType = newType); - } - - return rewritten - ? InstructionHandleResult.Rewritten - : InstructionHandleResult.None; - } - - /// Perform the predefined logic for an instruction if applicable. - /// The assembly module containing the instruction. - /// The CIL processor. - /// The CIL instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) - { - if (!this.Finder.IsMatch(instruction)) - return InstructionHandleResult.None; - bool rewritten = false; - - // field reference - FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); - if (fieldRef != null) - { - rewritten |= this.RewriteIfNeeded(module, fieldRef.DeclaringType, newType => fieldRef.DeclaringType = newType); - rewritten |= this.RewriteIfNeeded(module, fieldRef.FieldType, newType => fieldRef.FieldType = newType); - } - - // method reference - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); - if (methodRef != null) - { - rewritten |= this.RewriteIfNeeded(module, methodRef.DeclaringType, newType => methodRef.DeclaringType = newType); - rewritten |= this.RewriteIfNeeded(module, methodRef.ReturnType, newType => methodRef.ReturnType = newType); - foreach (var parameter in methodRef.Parameters) - rewritten |= this.RewriteIfNeeded(module, parameter.ParameterType, newType => parameter.ParameterType = newType); - if (methodRef is GenericInstanceMethod genericRef) - { - for (int i = 0; i < genericRef.GenericArguments.Count; i++) - rewritten |= this.RewriteIfNeeded(module, genericRef.GenericArguments[i], newType => genericRef.GenericArguments[i] = newType); - } - } - - // type reference - if (instruction.Operand is TypeReference typeRef) - rewritten |= this.RewriteIfNeeded(module, typeRef, newType => cil.Replace(instruction, cil.Create(instruction.OpCode, newType))); - - return rewritten - ? InstructionHandleResult.Rewritten - : InstructionHandleResult.None; - } - - - /********* - ** Protected methods - *********/ - /// Construct an instance. - /// The type finder which matches types to rewrite. - /// A brief noun phrase indicating what the instruction finder matches. - protected BaseTypeReferenceRewriter(BaseTypeFinder finder, string nounPhrase) - : base(nounPhrase) - { - this.Finder = finder; - } - - /// Change a type reference if needed. - /// The assembly module containing the instruction. - /// The type to replace if it matches. - /// Assign the new type reference. - protected abstract bool RewriteIfNeeded(ModuleDefinition module, TypeReference type, Action set); - - /// Rewrite custom attributes if needed. - /// The assembly module containing the attributes. - /// The custom attributes to handle. - private bool RewriteCustomAttributesIfNeeded(ModuleDefinition module, Collection attributes) - { - bool rewritten = false; - - for (int attrIndex = 0; attrIndex < attributes.Count; attrIndex++) - { - CustomAttribute attribute = attributes[attrIndex]; - bool curChanged = false; - - // attribute type - TypeReference newAttrType = null; - if (this.Finder.IsMatch(attribute.AttributeType)) - { - rewritten |= this.RewriteIfNeeded(module, attribute.AttributeType, newType => - { - newAttrType = newType; - curChanged = true; - }); - } - - // constructor arguments - TypeReference[] argTypes = new TypeReference[attribute.ConstructorArguments.Count]; - for (int i = 0; i < argTypes.Length; i++) - { - var arg = attribute.ConstructorArguments[i]; - - argTypes[i] = arg.Type; - rewritten |= this.RewriteIfNeeded(module, arg.Type, newType => - { - argTypes[i] = newType; - curChanged = true; - }); - } - - // swap attribute - if (curChanged) - { - // get constructor - MethodDefinition constructor = (newAttrType ?? attribute.AttributeType) - .Resolve() - .Methods - .Where(method => method.IsConstructor) - .FirstOrDefault(ctor => RewriteHelper.HasMatchingSignature(ctor, attribute.Constructor)); - if (constructor == null) - throw new InvalidOperationException($"Can't rewrite attribute type '{attribute.AttributeType.FullName}' to '{newAttrType?.FullName}', no equivalent constructor found."); - - // create new attribute - var newAttr = new CustomAttribute(module.ImportReference(constructor)); - for (int i = 0; i < argTypes.Length; i++) - newAttr.ConstructorArguments.Add(new CustomAttributeArgument(argTypes[i], attribute.ConstructorArguments[i].Value)); - foreach (var prop in attribute.Properties) - newAttr.Properties.Add(new CustomAttributeNamedArgument(prop.Name, prop.Argument)); - foreach (var field in attribute.Fields) - newAttr.Fields.Add(new CustomAttributeNamedArgument(field.Name, field.Argument)); - - // swap attribute - attributes[attrIndex] = newAttr; - rewritten = true; - } - } - - return rewritten; - } - } -} diff --git a/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs b/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs new file mode 100644 index 00000000..6aeb00ce --- /dev/null +++ b/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs @@ -0,0 +1,260 @@ +using System; +using System.Linq; +using Mono.Cecil; +using Mono.Cecil.Cil; +using Mono.Collections.Generic; + +namespace StardewModdingAPI.Framework.ModLoading.Framework +{ + /// Handles recursively rewriting loaded assembly code. + internal class RecursiveRewriter + { + /********* + ** Delegates + *********/ + /// Rewrite a type reference in the assembly code. + /// The current type reference. + /// Replaces the type reference with the given type. + /// Returns whether the type was changed. + public delegate bool RewriteTypeDelegate(TypeReference type, Action replaceWith); + + /// Rewrite a CIL instruction in the assembly code. + /// The current CIL instruction. + /// The CIL instruction processor. + /// Replaces the CIL instruction with the given instruction. + /// Returns whether the instruction was changed. + public delegate bool RewriteInstructionDelegate(Instruction instruction, ILProcessor cil, Action replaceWith); + + + /********* + ** Accessors + *********/ + /// The module to rewrite. + public ModuleDefinition Module { get; } + + /// Handle or rewrite a type reference if needed. + public RewriteTypeDelegate RewriteTypeImpl { get; } + + /// Handle or rewrite a CIL instruction if needed. + public RewriteInstructionDelegate RewriteInstructionImpl { get; } + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The module to rewrite. + /// Handle or rewrite a type reference if needed. + /// Handle or rewrite a CIL instruction if needed. + public RecursiveRewriter(ModuleDefinition module, RewriteTypeDelegate rewriteType, RewriteInstructionDelegate rewriteInstruction) + { + this.Module = module; + this.RewriteTypeImpl = rewriteType; + this.RewriteInstructionImpl = rewriteInstruction; + } + + /// Rewrite the loaded module code. + /// Returns whether the module was modified. + public bool RewriteModule() + { + bool anyRewritten = false; + + foreach (TypeDefinition type in this.Module.GetTypes()) + { + anyRewritten |= this.RewriteCustomAttributes(type.CustomAttributes); + anyRewritten |= this.RewriteGenericParameters(type.GenericParameters); + + foreach (MethodDefinition method in type.Methods.Where(p => p.HasBody)) + { + anyRewritten |= this.RewriteTypeReference(method.ReturnType, newType => method.ReturnType = newType); + anyRewritten |= this.RewriteGenericParameters(method.GenericParameters); + anyRewritten |= this.RewriteCustomAttributes(method.CustomAttributes); + + foreach (ParameterDefinition parameter in method.Parameters) + anyRewritten |= this.RewriteTypeReference(parameter.ParameterType, newType => parameter.ParameterType = newType); + + foreach (VariableDefinition variable in method.Body.Variables) + anyRewritten |= this.RewriteTypeReference(variable.VariableType, newType => variable.VariableType = newType); + + // check CIL instructions + ILProcessor cil = method.Body.GetILProcessor(); + Collection instructions = cil.Body.Instructions; + for (int i = 0; i < instructions.Count; i++) + { + var instruction = instructions[i]; + if (instruction.OpCode.Code == Code.Nop) + continue; + + anyRewritten |= this.RewriteInstruction(instruction, cil, newInstruction => + { + anyRewritten = true; + cil.Replace(instruction, newInstruction); + instruction = newInstruction; + }); + } + } + } + + return anyRewritten; + } + + + /********* + ** Private methods + *********/ + /// Rewrite a CIL instruction if needed. + /// The current CIL instruction. + /// The CIL instruction processor. + /// Replaces the CIL instruction with a new one. + private bool RewriteInstruction(Instruction instruction, ILProcessor cil, Action replaceWith) + { + bool rewritten = false; + + // field reference + FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + if (fieldRef != null) + { + rewritten |= this.RewriteTypeReference(fieldRef.DeclaringType, newType => fieldRef.DeclaringType = newType); + rewritten |= this.RewriteTypeReference(fieldRef.FieldType, newType => fieldRef.FieldType = newType); + } + + // method reference + MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + if (methodRef != null) + { + rewritten |= this.RewriteTypeReference(methodRef.DeclaringType, newType => methodRef.DeclaringType = newType); + rewritten |= this.RewriteTypeReference(methodRef.ReturnType, newType => methodRef.ReturnType = newType); + + foreach (var parameter in methodRef.Parameters) + rewritten |= this.RewriteTypeReference(parameter.ParameterType, newType => parameter.ParameterType = newType); + + if (methodRef is GenericInstanceMethod genericRef) + { + for (int i = 0; i < genericRef.GenericArguments.Count; i++) + rewritten |= this.RewriteTypeReference(genericRef.GenericArguments[i], newType => genericRef.GenericArguments[i] = newType); + } + } + + // type reference + if (instruction.Operand is TypeReference typeRef) + rewritten |= this.RewriteTypeReference(typeRef, newType => replaceWith(cil.Create(instruction.OpCode, newType))); + + // instruction itself + // (should be done after the above type rewrites to ensure valid types) + rewritten |= this.RewriteInstructionImpl(instruction, cil, newInstruction => + { + rewritten = true; + cil.Replace(instruction, newInstruction); + instruction = newInstruction; + }); + + return rewritten; + } + + /// Rewrite a type reference if needed. + /// The current type reference. + /// Replaces the type reference with a new one. + private bool RewriteTypeReference(TypeReference type, Action replaceWith) + { + bool rewritten = false; + + // type + rewritten |= this.RewriteTypeImpl(type, newType => + { + type = newType; + replaceWith(newType); + rewritten = true; + }); + + // generic arguments + if (type is GenericInstanceType genericType) + { + for (int i = 0; i < genericType.GenericArguments.Count; i++) + rewritten |= this.RewriteTypeReference(genericType.GenericArguments[i], typeRef => genericType.GenericArguments[i] = typeRef); + } + + // generic parameters (e.g. constraints) + rewritten |= this.RewriteGenericParameters(type.GenericParameters); + + return rewritten; + } + + /// Rewrite custom attributes if needed. + /// The current custom attributes. + private bool RewriteCustomAttributes(Collection attributes) + { + bool rewritten = false; + + for (int attrIndex = 0; attrIndex < attributes.Count; attrIndex++) + { + CustomAttribute attribute = attributes[attrIndex]; + bool curChanged = false; + + // attribute type + TypeReference newAttrType = null; + rewritten |= this.RewriteTypeReference(attribute.AttributeType, newType => + { + newAttrType = newType; + curChanged = true; + }); + + // constructor arguments + TypeReference[] argTypes = new TypeReference[attribute.ConstructorArguments.Count]; + for (int i = 0; i < argTypes.Length; i++) + { + var arg = attribute.ConstructorArguments[i]; + + argTypes[i] = arg.Type; + rewritten |= this.RewriteTypeReference(arg.Type, newType => + { + argTypes[i] = newType; + curChanged = true; + }); + } + + // swap attribute + if (curChanged) + { + // get constructor + MethodDefinition constructor = (newAttrType ?? attribute.AttributeType) + .Resolve() + .Methods + .Where(method => method.IsConstructor) + .FirstOrDefault(ctor => RewriteHelper.HasMatchingSignature(ctor, attribute.Constructor)); + if (constructor == null) + throw new InvalidOperationException($"Can't rewrite attribute type '{attribute.AttributeType.FullName}' to '{newAttrType?.FullName}', no equivalent constructor found."); + + // create new attribute + var newAttr = new CustomAttribute(this.Module.ImportReference(constructor)); + for (int i = 0; i < argTypes.Length; i++) + newAttr.ConstructorArguments.Add(new CustomAttributeArgument(argTypes[i], attribute.ConstructorArguments[i].Value)); + foreach (var prop in attribute.Properties) + newAttr.Properties.Add(new CustomAttributeNamedArgument(prop.Name, prop.Argument)); + foreach (var field in attribute.Fields) + newAttr.Fields.Add(new CustomAttributeNamedArgument(field.Name, field.Argument)); + + // swap attribute + attributes[attrIndex] = newAttr; + rewritten = true; + } + } + + return rewritten; + } + + /// Rewrites generic type parameters if needed. + /// The current generic type parameters. + private bool RewriteGenericParameters(Collection parameters) + { + bool anyChanged = false; + + for (int i = 0; i < parameters.Count; i++) + { + TypeReference parameter = parameters[i]; + anyChanged |= this.RewriteTypeReference(parameter, newType => parameters[i] = new GenericParameter(parameter.Name, newType)); + } + + return anyChanged; + } + } +} diff --git a/src/SMAPI/Framework/ModLoading/Framework/RewriteHelper.cs b/src/SMAPI/Framework/ModLoading/Framework/RewriteHelper.cs new file mode 100644 index 00000000..91c9dec3 --- /dev/null +++ b/src/SMAPI/Framework/ModLoading/Framework/RewriteHelper.cs @@ -0,0 +1,199 @@ +using System; +using System.Linq; +using System.Reflection; +using Mono.Cecil; +using Mono.Cecil.Cil; + +namespace StardewModdingAPI.Framework.ModLoading.Framework +{ + /// Provides helper methods for field rewriters. + internal static class RewriteHelper + { + /********* + ** Fields + *********/ + /// The comparer which heuristically compares type definitions. + private static readonly TypeReferenceComparer TypeDefinitionComparer = new TypeReferenceComparer(); + + + /********* + ** Public methods + *********/ + /// Get the field reference from an instruction if it matches. + /// The IL instruction. + public static FieldReference AsFieldReference(Instruction instruction) + { + return instruction.OpCode == OpCodes.Ldfld || instruction.OpCode == OpCodes.Ldsfld || instruction.OpCode == OpCodes.Stfld || instruction.OpCode == OpCodes.Stsfld + ? (FieldReference)instruction.Operand + : null; + } + + /// Get whether the field is a reference to the expected type and field. + /// The IL instruction. + /// The full type name containing the expected field. + /// The name of the expected field. + public static bool IsFieldReferenceTo(Instruction instruction, string fullTypeName, string fieldName) + { + FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + return RewriteHelper.IsFieldReferenceTo(fieldRef, fullTypeName, fieldName); + } + + /// Get whether the field is a reference to the expected type and field. + /// The field reference to check. + /// The full type name containing the expected field. + /// The name of the expected field. + public static bool IsFieldReferenceTo(FieldReference fieldRef, string fullTypeName, string fieldName) + { + return + fieldRef != null + && fieldRef.DeclaringType.FullName == fullTypeName + && fieldRef.Name == fieldName; + } + + /// Get the method reference from an instruction if it matches. + /// The IL instruction. + public static MethodReference AsMethodReference(Instruction instruction) + { + return instruction.OpCode == OpCodes.Call || instruction.OpCode == OpCodes.Callvirt || instruction.OpCode == OpCodes.Newobj + ? (MethodReference)instruction.Operand + : null; + } + + /// Get whether a type matches a type reference. + /// The defined type. + /// The type reference. + public static bool IsSameType(Type type, TypeReference reference) + { + // + // duplicated by IsSameType(TypeReference, TypeReference) below + // + + // same namespace & name + if (type.Namespace != reference.Namespace || type.Name != reference.Name) + return false; + + // same generic parameters + if (type.IsGenericType) + { + if (!reference.IsGenericInstance) + return false; + + Type[] defGenerics = type.GetGenericArguments(); + TypeReference[] refGenerics = ((GenericInstanceType)reference).GenericArguments.ToArray(); + if (defGenerics.Length != refGenerics.Length) + return false; + for (int i = 0; i < defGenerics.Length; i++) + { + if (!RewriteHelper.IsSameType(defGenerics[i], refGenerics[i])) + return false; + } + } + + return true; + } + + /// Get whether a type matches a type reference. + /// The defined type. + /// The type reference. + public static bool IsSameType(TypeReference type, TypeReference reference) + { + // + // duplicated by IsSameType(Type, TypeReference) above + // + + // same namespace & name + if (type.Namespace != reference.Namespace || type.Name != reference.Name) + return false; + + // same generic parameters + if (type.IsGenericInstance) + { + if (!reference.IsGenericInstance) + return false; + + TypeReference[] defGenerics = ((GenericInstanceType)type).GenericArguments.ToArray(); + TypeReference[] refGenerics = ((GenericInstanceType)reference).GenericArguments.ToArray(); + if (defGenerics.Length != refGenerics.Length) + return false; + for (int i = 0; i < defGenerics.Length; i++) + { + if (!RewriteHelper.IsSameType(defGenerics[i], refGenerics[i])) + return false; + } + } + + return true; + } + + /// Determine whether two type IDs look like the same type, accounting for placeholder values such as !0. + /// The type ID to compare. + /// The other type ID to compare. + /// true if the type IDs look like the same type, false if not. + public static bool LooksLikeSameType(TypeReference typeA, TypeReference typeB) + { + return RewriteHelper.TypeDefinitionComparer.Equals(typeA, typeB); + } + + /// Get whether a method definition matches the signature expected by a method reference. + /// The method definition. + /// The method reference. + public static bool HasMatchingSignature(MethodInfo definition, MethodReference reference) + { + // + // duplicated by HasMatchingSignature(MethodDefinition, MethodReference) below + // + + // same name + if (definition.Name != reference.Name) + return false; + + // same arguments + ParameterInfo[] definitionParameters = definition.GetParameters(); + ParameterDefinition[] referenceParameters = reference.Parameters.ToArray(); + if (referenceParameters.Length != definitionParameters.Length) + return false; + for (int i = 0; i < referenceParameters.Length; i++) + { + if (!RewriteHelper.IsSameType(definitionParameters[i].ParameterType, referenceParameters[i].ParameterType)) + return false; + } + return true; + } + + /// Get whether a method definition matches the signature expected by a method reference. + /// The method definition. + /// The method reference. + public static bool HasMatchingSignature(MethodDefinition definition, MethodReference reference) + { + // + // duplicated by HasMatchingSignature(MethodInfo, MethodReference) above + // + + // same name + if (definition.Name != reference.Name) + return false; + + // same arguments + ParameterDefinition[] definitionParameters = definition.Parameters.ToArray(); + ParameterDefinition[] referenceParameters = reference.Parameters.ToArray(); + if (referenceParameters.Length != definitionParameters.Length) + return false; + for (int i = 0; i < referenceParameters.Length; i++) + { + if (!RewriteHelper.IsSameType(definitionParameters[i].ParameterType, referenceParameters[i].ParameterType)) + return false; + } + return true; + } + + /// Get whether a type has a method whose signature matches the one expected by a method reference. + /// The type to check. + /// The method reference. + public static bool HasMatchingSignature(Type type, MethodReference reference) + { + return type + .GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public) + .Any(method => RewriteHelper.HasMatchingSignature(method, reference)); + } + } +} diff --git a/src/SMAPI/Framework/ModLoading/IInstructionHandler.cs b/src/SMAPI/Framework/ModLoading/IInstructionHandler.cs index f9d320a6..e6de6785 100644 --- a/src/SMAPI/Framework/ModLoading/IInstructionHandler.cs +++ b/src/SMAPI/Framework/ModLoading/IInstructionHandler.cs @@ -1,3 +1,5 @@ +using System; +using System.Collections.Generic; using Mono.Cecil; using Mono.Cecil.Cil; @@ -9,33 +11,32 @@ namespace StardewModdingAPI.Framework.ModLoading /********* ** Accessors *********/ - /// A brief noun phrase indicating what the handler matches. - string NounPhrase { get; } + /// A brief noun phrase indicating what the handler matches, used if is empty. + string DefaultPhrase { get; } + + /// The rewrite flags raised for the current module. + ISet Flags { get; } + + /// The brief noun phrases indicating what the handler matched for the current module. + ISet Phrases { get; } /********* ** Methods *********/ - /// Perform the predefined logic for a method if applicable. + /// Rewrite a type reference if needed. /// The assembly module containing the instruction. /// The type definition to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - InstructionHandleResult Handle(ModuleDefinition module, TypeDefinition type, PlatformAssemblyMap assemblyMap, bool platformChanged); - - /// Perform the predefined logic for a method if applicable. - /// The assembly module containing the instruction. - /// The method definition to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged); + /// Replaces the type reference with a new one. + /// Returns whether the type was changed. + bool Handle(ModuleDefinition module, TypeReference type, Action replaceWith); - /// Perform the predefined logic for an instruction if applicable. + /// Rewrite a CIL instruction reference if needed. /// The assembly module containing the instruction. /// The CIL processor. /// The CIL instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged); + /// Replaces the CIL instruction with a new one. + /// Returns whether the instruction was changed. + bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, Action replaceWith); } } diff --git a/src/SMAPI/Framework/ModLoading/RewriteHelper.cs b/src/SMAPI/Framework/ModLoading/RewriteHelper.cs deleted file mode 100644 index 553679f9..00000000 --- a/src/SMAPI/Framework/ModLoading/RewriteHelper.cs +++ /dev/null @@ -1,177 +0,0 @@ -using System; -using System.Linq; -using System.Reflection; -using Mono.Cecil; -using Mono.Cecil.Cil; - -namespace StardewModdingAPI.Framework.ModLoading -{ - /// Provides helper methods for field rewriters. - internal static class RewriteHelper - { - /********* - ** Fields - *********/ - /// The comparer which heuristically compares type definitions. - private static readonly TypeReferenceComparer TypeDefinitionComparer = new TypeReferenceComparer(); - - - /********* - ** Public methods - *********/ - /// Get the field reference from an instruction if it matches. - /// The IL instruction. - public static FieldReference AsFieldReference(Instruction instruction) - { - return instruction.OpCode == OpCodes.Ldfld || instruction.OpCode == OpCodes.Ldsfld || instruction.OpCode == OpCodes.Stfld || instruction.OpCode == OpCodes.Stsfld - ? (FieldReference)instruction.Operand - : null; - } - - /// Get the method reference from an instruction if it matches. - /// The IL instruction. - public static MethodReference AsMethodReference(Instruction instruction) - { - return instruction.OpCode == OpCodes.Call || instruction.OpCode == OpCodes.Callvirt || instruction.OpCode == OpCodes.Newobj - ? (MethodReference)instruction.Operand - : null; - } - - /// Get whether a type matches a type reference. - /// The defined type. - /// The type reference. - public static bool IsSameType(Type type, TypeReference reference) - { - // - // duplicated by IsSameType(TypeReference, TypeReference) below - // - - // same namespace & name - if (type.Namespace != reference.Namespace || type.Name != reference.Name) - return false; - - // same generic parameters - if (type.IsGenericType) - { - if (!reference.IsGenericInstance) - return false; - - Type[] defGenerics = type.GetGenericArguments(); - TypeReference[] refGenerics = ((GenericInstanceType)reference).GenericArguments.ToArray(); - if (defGenerics.Length != refGenerics.Length) - return false; - for (int i = 0; i < defGenerics.Length; i++) - { - if (!RewriteHelper.IsSameType(defGenerics[i], refGenerics[i])) - return false; - } - } - - return true; - } - - /// Get whether a type matches a type reference. - /// The defined type. - /// The type reference. - public static bool IsSameType(TypeReference type, TypeReference reference) - { - // - // duplicated by IsSameType(Type, TypeReference) above - // - - // same namespace & name - if (type.Namespace != reference.Namespace || type.Name != reference.Name) - return false; - - // same generic parameters - if (type.IsGenericInstance) - { - if (!reference.IsGenericInstance) - return false; - - TypeReference[] defGenerics = ((GenericInstanceType)type).GenericArguments.ToArray(); - TypeReference[] refGenerics = ((GenericInstanceType)reference).GenericArguments.ToArray(); - if (defGenerics.Length != refGenerics.Length) - return false; - for (int i = 0; i < defGenerics.Length; i++) - { - if (!RewriteHelper.IsSameType(defGenerics[i], refGenerics[i])) - return false; - } - } - - return true; - } - - /// Determine whether two type IDs look like the same type, accounting for placeholder values such as !0. - /// The type ID to compare. - /// The other type ID to compare. - /// true if the type IDs look like the same type, false if not. - public static bool LooksLikeSameType(TypeReference typeA, TypeReference typeB) - { - return RewriteHelper.TypeDefinitionComparer.Equals(typeA, typeB); - } - - /// Get whether a method definition matches the signature expected by a method reference. - /// The method definition. - /// The method reference. - public static bool HasMatchingSignature(MethodInfo definition, MethodReference reference) - { - // - // duplicated by HasMatchingSignature(MethodDefinition, MethodReference) below - // - - // same name - if (definition.Name != reference.Name) - return false; - - // same arguments - ParameterInfo[] definitionParameters = definition.GetParameters(); - ParameterDefinition[] referenceParameters = reference.Parameters.ToArray(); - if (referenceParameters.Length != definitionParameters.Length) - return false; - for (int i = 0; i < referenceParameters.Length; i++) - { - if (!RewriteHelper.IsSameType(definitionParameters[i].ParameterType, referenceParameters[i].ParameterType)) - return false; - } - return true; - } - - /// Get whether a method definition matches the signature expected by a method reference. - /// The method definition. - /// The method reference. - public static bool HasMatchingSignature(MethodDefinition definition, MethodReference reference) - { - // - // duplicated by HasMatchingSignature(MethodInfo, MethodReference) above - // - - // same name - if (definition.Name != reference.Name) - return false; - - // same arguments - ParameterDefinition[] definitionParameters = definition.Parameters.ToArray(); - ParameterDefinition[] referenceParameters = reference.Parameters.ToArray(); - if (referenceParameters.Length != definitionParameters.Length) - return false; - for (int i = 0; i < referenceParameters.Length; i++) - { - if (!RewriteHelper.IsSameType(definitionParameters[i].ParameterType, referenceParameters[i].ParameterType)) - return false; - } - return true; - } - - /// Get whether a type has a method whose signature matches the one expected by a method reference. - /// The type to check. - /// The method reference. - public static bool HasMatchingSignature(Type type, MethodReference reference) - { - return type - .GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public) - .Any(method => RewriteHelper.HasMatchingSignature(method, reference)); - } - } -} diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/FieldReplaceRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/FieldReplaceRewriter.cs index ff86c6e2..8043b13a 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/FieldReplaceRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/FieldReplaceRewriter.cs @@ -2,16 +2,22 @@ using System; using System.Reflection; using Mono.Cecil; using Mono.Cecil.Cil; -using StardewModdingAPI.Framework.ModLoading.Finders; +using StardewModdingAPI.Framework.ModLoading.Framework; namespace StardewModdingAPI.Framework.ModLoading.Rewriters { /// Rewrites references to one field with another. - internal class FieldReplaceRewriter : FieldFinder + internal class FieldReplaceRewriter : BaseInstructionHandler { /********* ** Fields *********/ + /// The type containing the field to which references should be rewritten. + private readonly Type Type; + + /// The field name to which references should be rewritten. + private readonly string FromFieldName; + /// The new field to reference. private readonly FieldInfo ToField; @@ -20,31 +26,36 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters ** Public methods *********/ /// Construct an instance. - /// The type whose field to which references should be rewritten. + /// The type whose field to rewrite. /// The field name to rewrite. /// The new field name to reference. public FieldReplaceRewriter(Type type, string fromFieldName, string toFieldName) - : base(type.FullName, fromFieldName, InstructionHandleResult.None) + : base(defaultPhrase: $"{type.FullName}.{fromFieldName} field") { + this.Type = type; + this.FromFieldName = fromFieldName; this.ToField = type.GetField(toFieldName); if (this.ToField == null) throw new InvalidOperationException($"The {type.FullName} class doesn't have a {toFieldName} field."); } - /// Perform the predefined logic for an instruction if applicable. + /// Rewrite a CIL instruction reference if needed. /// The assembly module containing the instruction. /// The CIL processor. - /// The instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + /// The CIL instruction to handle. + /// Replaces the CIL instruction with a new one. + /// Returns whether the instruction was changed. + public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, Action replaceWith) { - if (!this.IsMatch(instruction)) - return InstructionHandleResult.None; + // get field reference + FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + if (!RewriteHelper.IsFieldReferenceTo(fieldRef, this.Type.FullName, this.FromFieldName)) + return false; + // replace with new field FieldReference newRef = module.ImportReference(this.ToField); - cil.Replace(instruction, cil.Create(instruction.OpCode, newRef)); - return InstructionHandleResult.Rewritten; + replaceWith(cil.Create(instruction.OpCode, newRef)); + return this.MarkRewritten(); } } } diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/FieldToPropertyRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/FieldToPropertyRewriter.cs index a43c5e9a..c3b5854e 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/FieldToPropertyRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/FieldToPropertyRewriter.cs @@ -1,21 +1,24 @@ using System; using Mono.Cecil; using Mono.Cecil.Cil; -using StardewModdingAPI.Framework.ModLoading.Finders; +using StardewModdingAPI.Framework.ModLoading.Framework; namespace StardewModdingAPI.Framework.ModLoading.Rewriters { /// Rewrites field references into property references. - internal class FieldToPropertyRewriter : FieldFinder + internal class FieldToPropertyRewriter : BaseInstructionHandler { /********* ** Fields *********/ - /// The type whose field to which references should be rewritten. + /// The type containing the field to which references should be rewritten. private readonly Type Type; - /// The property name. - private readonly string PropertyName; + /// The field name to which references should be rewritten. + private readonly string FromFieldName; + + /// The new property name. + private readonly string ToPropertyName; /********* @@ -26,10 +29,11 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// The field name to rewrite. /// The property name (if different). public FieldToPropertyRewriter(Type type, string fieldName, string propertyName) - : base(type.FullName, fieldName, InstructionHandleResult.None) + : base(defaultPhrase: $"{type.FullName}.{fieldName} field") { this.Type = type; - this.PropertyName = propertyName; + this.FromFieldName = fieldName; + this.ToPropertyName = propertyName; } /// Construct an instance. @@ -38,22 +42,24 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters public FieldToPropertyRewriter(Type type, string fieldName) : this(type, fieldName, fieldName) { } - /// Perform the predefined logic for an instruction if applicable. + /// Rewrite a CIL instruction reference if needed. /// The assembly module containing the instruction. /// The CIL processor. - /// The instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + /// The CIL instruction to handle. + /// Replaces the CIL instruction with a new one. + /// Returns whether the instruction was changed. + public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, Action replaceWith) { - if (!this.IsMatch(instruction)) - return InstructionHandleResult.None; + // get field ref + FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + if (!RewriteHelper.IsFieldReferenceTo(fieldRef, this.Type.FullName, this.FromFieldName)) + return false; + // replace with property string methodPrefix = instruction.OpCode == OpCodes.Ldsfld || instruction.OpCode == OpCodes.Ldfld ? "get" : "set"; - MethodReference propertyRef = module.ImportReference(this.Type.GetMethod($"{methodPrefix}_{this.PropertyName}")); - cil.Replace(instruction, cil.Create(OpCodes.Call, propertyRef)); - - return InstructionHandleResult.Rewritten; + MethodReference propertyRef = module.ImportReference(this.Type.GetMethod($"{methodPrefix}_{this.ToPropertyName}")); + replaceWith(cil.Create(OpCodes.Call, propertyRef)); + return this.MarkRewritten(); } } } diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs index 9faca235..a7a0b9c3 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs @@ -1,28 +1,20 @@ using System; +using HarmonyLib; using Mono.Cecil; -using StardewModdingAPI.Framework.ModLoading.Finders; +using Mono.Cecil.Cil; using StardewModdingAPI.Framework.ModLoading.Framework; +using StardewModdingAPI.Framework.ModLoading.RewriteFacades; namespace StardewModdingAPI.Framework.ModLoading.Rewriters { /// Rewrites Harmony 1.x assembly references to work with Harmony 2.x. - internal class Harmony1AssemblyRewriter : BaseTypeReferenceRewriter + internal class Harmony1AssemblyRewriter : BaseInstructionHandler { /********* ** Fields *********/ - /// The full assembly name to which to find references. - private const string FromAssemblyName = "0Harmony"; - - /// The main Harmony type. - private readonly Type HarmonyType = typeof(HarmonyLib.Harmony); - - - /********* - ** Accessors - *********/ - /// A brief noun phrase indicating what the rewriter matches. - public const string DefaultNounPhrase = "Harmony 1.x"; + /// Whether any Harmony 1.x types were replaced. + private bool ReplacedTypes; /********* @@ -30,41 +22,80 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters *********/ /// Construct an instance. public Harmony1AssemblyRewriter() - : base(new TypeAssemblyFinder(Harmony1AssemblyRewriter.FromAssemblyName, InstructionHandleResult.None), Harmony1AssemblyRewriter.DefaultNounPhrase) - { } + : base(defaultPhrase: "Harmony 1.x") { } + + /// Rewrite a type reference if needed. + /// The assembly module containing the instruction. + /// The type definition to handle. + /// Replaces the type reference with a new one. + /// Returns whether the type was changed. + public override bool Handle(ModuleDefinition module, TypeReference type, Action replaceWith) + { + // rewrite Harmony 1.x type to Harmony 2.0 type + if (type.Scope is AssemblyNameReference scope && scope.Name == "0Harmony" && scope.Version.Major == 1) + { + Type targetType = this.GetMappedType(type); + replaceWith(module.ImportReference(targetType)); + this.MarkRewritten(); + this.ReplacedTypes = true; + return true; + } + + return false; + } + + /// Rewrite a CIL instruction reference if needed. + /// The assembly module containing the instruction. + /// The CIL processor. + /// The CIL instruction to handle. + /// Replaces the CIL instruction with a new one. + /// Returns whether the instruction was changed. + public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, Action replaceWith) + { + // rewrite Harmony 1.x methods to Harmony 2.0 + MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + if (this.TryRewriteMethodsToFacade(module, methodRef)) + return true; + + return false; + } /********* ** Private methods *********/ - /// Change a type reference if needed. - /// The assembly module containing the instruction. - /// The type to replace if it matches. - /// Assign the new type reference. - protected override bool RewriteIfNeeded(ModuleDefinition module, TypeReference type, Action set) + /// Rewrite methods to use Harmony facades if needed. + /// The assembly module containing the method reference. + /// The method reference to map. + private bool TryRewriteMethodsToFacade(ModuleDefinition module, MethodReference methodRef) { - bool rewritten = false; + if (!this.ReplacedTypes) + return false; // not Harmony (or already using Harmony 2.0) - // current type - if (type.Scope.Name == Harmony1AssemblyRewriter.FromAssemblyName && type.Scope is AssemblyNameReference assemblyScope && assemblyScope.Version.Major == 1) + // get facade type + Type toType; + switch (methodRef?.DeclaringType.FullName) { - Type targetType = this.GetMappedType(type); - set(module.ImportReference(targetType)); - return true; + case "HarmonyLib.Harmony": + toType = typeof(HarmonyInstanceMethods); + break; + + case "HarmonyLib.AccessTools": + toType = typeof(AccessToolsMethods); + break; + + default: + return false; } - // recurse into generic arguments - if (type is GenericInstanceType genericType) + // map if there's a matching method + if (RewriteHelper.HasMatchingSignature(toType, methodRef)) { - for (int i = 0; i < genericType.GenericArguments.Count; i++) - rewritten |= this.RewriteIfNeeded(module, genericType.GenericArguments[i], typeRef => genericType.GenericArguments[i] = typeRef); + methodRef.DeclaringType = module.ImportReference(toType); + return true; } - // recurse into generic parameters (e.g. constraints) - for (int i = 0; i < type.GenericParameters.Count; i++) - rewritten |= this.RewriteIfNeeded(module, type.GenericParameters[i], typeRef => type.GenericParameters[i] = new GenericParameter(typeRef)); - - return rewritten; + return false; } /// Get an equivalent Harmony 2.x type. @@ -73,11 +104,11 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters { // main Harmony object if (type.FullName == "Harmony.HarmonyInstance") - return this.HarmonyType; + return typeof(Harmony); // other objects string fullName = type.FullName.Replace("Harmony.", "HarmonyLib."); - string targetName = this.HarmonyType.AssemblyQualifiedName.Replace(this.HarmonyType.FullName, fullName); + string targetName = typeof(Harmony).AssemblyQualifiedName.Replace(typeof(Harmony).FullName, fullName); return Type.GetType(targetName, throwOnError: true); } } diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs index d0fe8b13..b8e53f40 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs @@ -18,9 +18,6 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// The type with methods to map to. private readonly Type ToType; - /// Whether to only rewrite references if loading the assembly on a different platform than it was compiled on. - private readonly bool OnlyIfPlatformChanged; - /********* ** Public methods @@ -28,54 +25,49 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// Construct an instance. /// The type whose methods to remap. /// The type with methods to map to. - /// Whether to only rewrite references if loading the assembly on a different platform than it was compiled on. /// A brief noun phrase indicating what the instruction finder matches (or null to generate one). - public MethodParentRewriter(string fromType, Type toType, bool onlyIfPlatformChanged = false, string nounPhrase = null) + public MethodParentRewriter(string fromType, Type toType, string nounPhrase = null) : base(nounPhrase ?? $"{fromType.Split('.').Last()} methods") { this.FromType = fromType; this.ToType = toType; - this.OnlyIfPlatformChanged = onlyIfPlatformChanged; } /// Construct an instance. /// The type whose methods to remap. /// The type with methods to map to. - /// Whether to only rewrite references if loading the assembly on a different platform than it was compiled on. /// A brief noun phrase indicating what the instruction finder matches (or null to generate one). - public MethodParentRewriter(Type fromType, Type toType, bool onlyIfPlatformChanged = false, string nounPhrase = null) - : this(fromType.FullName, toType, onlyIfPlatformChanged, nounPhrase) { } - + public MethodParentRewriter(Type fromType, Type toType, string nounPhrase = null) + : this(fromType.FullName, toType, nounPhrase) { } - /// Perform the predefined logic for an instruction if applicable. + /// Rewrite a CIL instruction reference if needed. /// The assembly module containing the instruction. /// The CIL processor. /// The CIL instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + /// Replaces the CIL instruction with a new one. + /// Returns whether the instruction was changed. + public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, Action replaceWith) { - if (!this.IsMatch(instruction, platformChanged)) - return InstructionHandleResult.None; + // get method ref + MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + if (!this.IsMatch(methodRef)) + return false; - MethodReference methodRef = (MethodReference)instruction.Operand; + // rewrite methodRef.DeclaringType = module.ImportReference(this.ToType); - return InstructionHandleResult.Rewritten; + return this.MarkRewritten(); } /********* - ** Protected methods + ** Private methods *********/ /// Get whether a CIL instruction matches. - /// The IL instruction. - /// Whether the mod was compiled on a different platform. - protected bool IsMatch(Instruction instruction, bool platformChanged) + /// The method reference. + private bool IsMatch(MethodReference methodRef) { - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); return methodRef != null - && (platformChanged || !this.OnlyIfPlatformChanged) && methodRef.DeclaringType.FullName == this.FromType && RewriteHelper.HasMatchingSignature(this.ToType, methodRef); } diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/StaticFieldToConstantRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/StaticFieldToConstantRewriter.cs index 7e7c0efa..6ef18b26 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/StaticFieldToConstantRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/StaticFieldToConstantRewriter.cs @@ -1,17 +1,23 @@ using System; using Mono.Cecil; using Mono.Cecil.Cil; -using StardewModdingAPI.Framework.ModLoading.Finders; +using StardewModdingAPI.Framework.ModLoading.Framework; namespace StardewModdingAPI.Framework.ModLoading.Rewriters { /// Rewrites static field references into constant values. /// The constant value type. - internal class StaticFieldToConstantRewriter : FieldFinder + internal class StaticFieldToConstantRewriter : BaseInstructionHandler { /********* ** Fields *********/ + /// The type containing the field to which references should be rewritten. + private readonly Type Type; + + /// The field name to which references should be rewritten. + private readonly string FromFieldName; + /// The constant value to replace with. private readonly TValue Value; @@ -24,24 +30,29 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// The field name to rewrite. /// The constant value to replace with. public StaticFieldToConstantRewriter(Type type, string fieldName, TValue value) - : base(type.FullName, fieldName, InstructionHandleResult.None) + : base(defaultPhrase: $"{type.FullName}.{fieldName} field") { + this.Type = type; + this.FromFieldName = fieldName; this.Value = value; } - /// Perform the predefined logic for an instruction if applicable. + /// Rewrite a CIL instruction reference if needed. /// The assembly module containing the instruction. /// The CIL processor. - /// The instruction to handle. - /// Metadata for mapping assemblies to the current platform. - /// Whether the mod was compiled on a different platform. - public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) + /// The CIL instruction to handle. + /// Replaces the CIL instruction with a new one. + /// Returns whether the instruction was changed. + public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, Action replaceWith) { - if (!this.IsMatch(instruction)) - return InstructionHandleResult.None; + // get field reference + FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + if (!RewriteHelper.IsFieldReferenceTo(fieldRef, this.Type.FullName, this.FromFieldName)) + return false; - cil.Replace(instruction, this.CreateConstantInstruction(cil, this.Value)); - return InstructionHandleResult.Rewritten; + // rewrite to constant + replaceWith(this.CreateConstantInstruction(cil, this.Value)); + return this.MarkRewritten(); } diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs index d95e5ac9..c2120444 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs @@ -1,12 +1,11 @@ using System; using Mono.Cecil; -using StardewModdingAPI.Framework.ModLoading.Finders; using StardewModdingAPI.Framework.ModLoading.Framework; namespace StardewModdingAPI.Framework.ModLoading.Rewriters { /// Rewrites all references to a type. - internal class TypeReferenceRewriter : BaseTypeReferenceRewriter + internal class TypeReferenceRewriter : BaseInstructionHandler { /********* ** Fields @@ -17,6 +16,9 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// The new type to reference. private readonly Type ToType; + /// Get whether a matched type should be ignored. + private readonly Func ShouldIgnore; + /********* ** Public methods @@ -24,45 +26,29 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// Construct an instance. /// The full type name to which to find references. /// The new type to reference. - /// A lambda which overrides a matched type. + /// Get whether a matched type should be ignored. public TypeReferenceRewriter(string fromTypeFullName, Type toType, Func shouldIgnore = null) - : base(new TypeFinder(fromTypeFullName, InstructionHandleResult.None, shouldIgnore), $"{fromTypeFullName} type") + : base($"{fromTypeFullName} type") { this.FromTypeName = fromTypeFullName; this.ToType = toType; + this.ShouldIgnore = shouldIgnore; } - - /********* - ** Protected methods - *********/ - /// Change a type reference if needed. + /// Rewrite a type reference if needed. /// The assembly module containing the instruction. - /// The type to replace if it matches. - /// Assign the new type reference. - protected override bool RewriteIfNeeded(ModuleDefinition module, TypeReference type, Action set) + /// The type definition to handle. + /// Replaces the type reference with a new one. + /// Returns whether the type was changed. + public override bool Handle(ModuleDefinition module, TypeReference type, Action replaceWith) { - bool rewritten = false; - - // current type - if (type.FullName == this.FromTypeName) - { - set(module.ImportReference(this.ToType)); - return true; - } - - // recurse into generic arguments - if (type is GenericInstanceType genericType) - { - for (int i = 0; i < genericType.GenericArguments.Count; i++) - rewritten |= this.RewriteIfNeeded(module, genericType.GenericArguments[i], typeRef => genericType.GenericArguments[i] = typeRef); - } - - // recurse into generic parameters (e.g. constraints) - for (int i = 0; i < type.GenericParameters.Count; i++) - rewritten |= this.RewriteIfNeeded(module, type.GenericParameters[i], typeRef => type.GenericParameters[i] = new GenericParameter(typeRef)); + // check type reference + if (type.FullName != this.FromTypeName || this.ShouldIgnore?.Invoke(type) == true) + return false; - return rewritten; + // rewrite to new type + replaceWith(module.ImportReference(this.ToType)); + return this.MarkRewritten(); } } } diff --git a/src/SMAPI/Metadata/InstructionMetadata.cs b/src/SMAPI/Metadata/InstructionMetadata.cs index d80f64e2..b7aad9da 100644 --- a/src/SMAPI/Metadata/InstructionMetadata.cs +++ b/src/SMAPI/Metadata/InstructionMetadata.cs @@ -25,21 +25,21 @@ namespace StardewModdingAPI.Metadata *********/ /// Get rewriters which detect or fix incompatible CIL instructions in mod assemblies. /// Whether to detect paranoid mode issues. - public IEnumerable GetHandlers(bool paranoidMode) + /// Whether the assembly was rewritten for crossplatform compatibility. + public IEnumerable GetHandlers(bool paranoidMode, bool platformChanged) { /**** ** rewrite CIL to fix incompatible code ****/ // rewrite for crossplatform compatibility - yield return new MethodParentRewriter(typeof(SpriteBatch), typeof(SpriteBatchMethods), onlyIfPlatformChanged: true); + if (platformChanged) + yield return new MethodParentRewriter(typeof(SpriteBatch), typeof(SpriteBatchMethods)); // rewrite for Stardew Valley 1.3 yield return new StaticFieldToConstantRewriter(typeof(Game1), "tileSize", Game1.tileSize); // rewrite for SMAPI 3.6 (Harmony 1.x => 2.0 update) yield return new Harmony1AssemblyRewriter(); - yield return new MethodParentRewriter(typeof(HarmonyLib.Harmony), typeof(HarmonyInstanceMethods), onlyIfPlatformChanged: false, nounPhrase: Harmony1AssemblyRewriter.DefaultNounPhrase); - yield return new MethodParentRewriter(typeof(HarmonyLib.AccessTools), typeof(AccessToolsMethods), onlyIfPlatformChanged: false, nounPhrase: Harmony1AssemblyRewriter.DefaultNounPhrase); /**** ** detect mod issues -- cgit From b54d892abf2bb5b7c05631d6f665b2a1d06529b1 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 19 May 2020 22:50:33 -0400 Subject: fix rewriting declaring type for a generic method (#711) --- src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs b/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs index 6aeb00ce..4c707248 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs @@ -122,7 +122,13 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); if (methodRef != null) { - rewritten |= this.RewriteTypeReference(methodRef.DeclaringType, newType => methodRef.DeclaringType = newType); + rewritten |= this.RewriteTypeReference(methodRef.DeclaringType, newType => + { + // note: generic methods are wrapped into a MethodSpecification which doesn't allow changing the + // declaring type directly. For our purposes we want to change all generic versions of a matched + // method anyway, so we can use GetElementMethod to get the underlying method here. + methodRef.GetElementMethod().DeclaringType = newType; + }); rewritten |= this.RewriteTypeReference(methodRef.ReturnType, newType => methodRef.ReturnType = newType); foreach (var parameter in methodRef.Parameters) -- cgit From 71a11337d6e51a1d95d3a40634f2ce319c330c33 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 20 May 2020 00:53:46 -0400 Subject: ignore special types (#711) --- src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs b/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs index 4c707248..5f7c2128 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs @@ -61,6 +61,9 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework foreach (TypeDefinition type in this.Module.GetTypes()) { + if (type.BaseType == null) + continue; // special type like + anyRewritten |= this.RewriteCustomAttributes(type.CustomAttributes); anyRewritten |= this.RewriteGenericParameters(type.GenericParameters); -- cgit From 136a548fbbb27e28ac7b8167760388eb5754bdb9 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 20 May 2020 00:54:28 -0400 Subject: rewrite methods without a body (#711) --- .../ModLoading/Framework/RecursiveRewriter.cs | 35 ++++++++++++---------- 1 file changed, 19 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs b/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs index 5f7c2128..612d0fdd 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs @@ -67,7 +67,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework anyRewritten |= this.RewriteCustomAttributes(type.CustomAttributes); anyRewritten |= this.RewriteGenericParameters(type.GenericParameters); - foreach (MethodDefinition method in type.Methods.Where(p => p.HasBody)) + foreach (MethodDefinition method in type.Methods) { anyRewritten |= this.RewriteTypeReference(method.ReturnType, newType => method.ReturnType = newType); anyRewritten |= this.RewriteGenericParameters(method.GenericParameters); @@ -76,24 +76,27 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework foreach (ParameterDefinition parameter in method.Parameters) anyRewritten |= this.RewriteTypeReference(parameter.ParameterType, newType => parameter.ParameterType = newType); - foreach (VariableDefinition variable in method.Body.Variables) - anyRewritten |= this.RewriteTypeReference(variable.VariableType, newType => variable.VariableType = newType); - - // check CIL instructions - ILProcessor cil = method.Body.GetILProcessor(); - Collection instructions = cil.Body.Instructions; - for (int i = 0; i < instructions.Count; i++) + if (method.HasBody) { - var instruction = instructions[i]; - if (instruction.OpCode.Code == Code.Nop) - continue; + foreach (VariableDefinition variable in method.Body.Variables) + anyRewritten |= this.RewriteTypeReference(variable.VariableType, newType => variable.VariableType = newType); - anyRewritten |= this.RewriteInstruction(instruction, cil, newInstruction => + // check CIL instructions + ILProcessor cil = method.Body.GetILProcessor(); + Collection instructions = cil.Body.Instructions; + for (int i = 0; i < instructions.Count; i++) { - anyRewritten = true; - cil.Replace(instruction, newInstruction); - instruction = newInstruction; - }); + var instruction = instructions[i]; + if (instruction.OpCode.Code == Code.Nop) + continue; + + anyRewritten |= this.RewriteInstruction(instruction, cil, newInstruction => + { + anyRewritten = true; + cil.Replace(instruction, newInstruction); + instruction = newInstruction; + }); + } } } } -- cgit From b38b7af05496e9a844ce8f63a05d23bd6c39430f Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 20 May 2020 00:56:28 -0400 Subject: rewrite base types & interfaces (#711) --- src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src') diff --git a/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs b/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs index 612d0fdd..3b8cda88 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs @@ -67,6 +67,12 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework anyRewritten |= this.RewriteCustomAttributes(type.CustomAttributes); anyRewritten |= this.RewriteGenericParameters(type.GenericParameters); + foreach (InterfaceImplementation @interface in type.Interfaces) + anyRewritten |= this.RewriteTypeReference(@interface.InterfaceType, newType => @interface.InterfaceType = newType); + + if (type.BaseType.FullName != "System.Object") + anyRewritten |= this.RewriteTypeReference(type.BaseType, newType => type.BaseType = newType); + foreach (MethodDefinition method in type.Methods) { anyRewritten |= this.RewriteTypeReference(method.ReturnType, newType => method.ReturnType = newType); -- cgit From 518bf7e3f13f10d2ef6ea4f064ecd8d58bf07c49 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 20 May 2020 02:00:16 -0400 Subject: rewrite renamed 'prioritiy' field (#711) --- .../Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'src') diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs index a7a0b9c3..be98a666 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs @@ -57,6 +57,14 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters if (this.TryRewriteMethodsToFacade(module, methodRef)) return true; + // rewrite renamed fields + FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + if (fieldRef != null) + { + if (fieldRef.DeclaringType.FullName == "HarmonyLib.HarmonyMethod" && fieldRef.Name == "prioritiy") + fieldRef.Name = nameof(HarmonyMethod.priority); + } + return false; } -- cgit From c5c30189e43f93c3f3c66207945187a974656c9e Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 20 May 2020 02:14:30 -0400 Subject: fix error-handling when patch is called with a null target method (#711) --- .../Framework/ModLoading/RewriteFacades/HarmonyInstanceMethods.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyInstanceMethods.cs b/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyInstanceMethods.cs index 78cf25f8..17b6bcd9 100644 --- a/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyInstanceMethods.cs +++ b/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyInstanceMethods.cs @@ -34,6 +34,7 @@ namespace StardewModdingAPI.Framework.ModLoading.RewriteFacades } catch (Exception ex) { + // get patch types var patchTypes = new List(); if (prefix != null) patchTypes.Add("prefix"); @@ -42,7 +43,12 @@ namespace StardewModdingAPI.Framework.ModLoading.RewriteFacades if (transpiler != null) patchTypes.Add("transpiler"); - throw new Exception($"Harmony instance {this.Id} failed applying {string.Join("/", patchTypes)} to method {original.DeclaringType?.FullName}.{original.Name}.", ex); + // get original method label + string methodLabel = original != null + ? $"method {original.DeclaringType?.FullName}.{original.Name}" + : "null method"; + + throw new Exception($"Harmony instance {this.Id} failed applying {string.Join("/", patchTypes)} to {methodLabel}.", ex); } } } -- cgit