From ec5fbb06113b29342e6d4b213144f4dc3e358b03 Mon Sep 17 00:00:00 2001 From: Chase Warrington Date: Sun, 29 Aug 2021 15:48:28 -0400 Subject: Rewrite 32-bit assemblies for 64-bit --- src/SMAPI/Metadata/InstructionMetadata.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src/SMAPI/Metadata') diff --git a/src/SMAPI/Metadata/InstructionMetadata.cs b/src/SMAPI/Metadata/InstructionMetadata.cs index a787993a..54e46ed3 100644 --- a/src/SMAPI/Metadata/InstructionMetadata.cs +++ b/src/SMAPI/Metadata/InstructionMetadata.cs @@ -50,6 +50,9 @@ namespace StardewModdingAPI.Metadata // rewrite for SMAPI 3.12 (Harmony 1.x => 2.0 update) yield return new Harmony1AssemblyRewriter(); + + // rewrite for 64-bit mode + yield return new ArchitectureAssemblyRewriter(); } /**** -- cgit From 789b62bcd6af0f87ab8d71ff5190fdb9163d9bef Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 1 Sep 2021 19:56:17 -0400 Subject: adjust rewriter for backport to Stardew Valley 1.5.4 --- src/SMAPI/Metadata/InstructionMetadata.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/SMAPI/Metadata') diff --git a/src/SMAPI/Metadata/InstructionMetadata.cs b/src/SMAPI/Metadata/InstructionMetadata.cs index 54e46ed3..9f537c92 100644 --- a/src/SMAPI/Metadata/InstructionMetadata.cs +++ b/src/SMAPI/Metadata/InstructionMetadata.cs @@ -52,7 +52,9 @@ namespace StardewModdingAPI.Metadata yield return new Harmony1AssemblyRewriter(); // rewrite for 64-bit mode +#if SMAPI_FOR_WINDOWS_64BIT_HACK yield return new ArchitectureAssemblyRewriter(); +#endif } /**** -- cgit From 8bfab94213e86c4245961150bd3423ee85213c5d Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 31 Aug 2021 01:13:22 -0400 Subject: reduce unneeded operations when scanning/rewriting mod DLLs --- docs/release-notes.md | 1 + src/SMAPI/Framework/ModLoading/AssemblyLoader.cs | 15 +-- .../Framework/ModLoading/Finders/EventFinder.cs | 57 ++++---- .../Framework/ModLoading/Finders/FieldFinder.cs | 34 +++-- .../ReferenceToMemberWithUnexpectedTypeFinder.cs | 6 +- .../Finders/ReferenceToMissingMemberFinder.cs | 6 +- .../Framework/ModLoading/Finders/TypeFinder.cs | 27 +++- .../Rewriters/Harmony1AssemblyRewriter.cs | 129 ------------------- .../ModLoading/Rewriters/HarmonyRewriter.cs | 143 +++++++++++++++++++++ .../ModLoading/Rewriters/HeuristicFieldRewriter.cs | 6 +- .../Rewriters/HeuristicMethodRewriter.cs | 6 +- src/SMAPI/Metadata/InstructionMetadata.cs | 36 +++--- 12 files changed, 262 insertions(+), 204 deletions(-) delete mode 100644 src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs create mode 100644 src/SMAPI/Framework/ModLoading/Rewriters/HarmonyRewriter.cs (limited to 'src/SMAPI/Metadata') diff --git a/docs/release-notes.md b/docs/release-notes.md index e8b019a9..a8db9cbd 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -4,6 +4,7 @@ ## Upcoming release * For players: * Improved mod compatibility in 64-bit mode (thanks to spacechase0!). + * Reducing load time when scanning/rewriting many mods for compatibility. * For console commands: * Added `hurry_all` command which immediately warps all NPCs to their scheduled positions. diff --git a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs index 7668e8a9..57a76a35 100644 --- a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs +++ b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs @@ -300,10 +300,10 @@ namespace StardewModdingAPI.Framework.ModLoading // remove old assembly reference if (this.AssemblyMap.RemoveNames.Any(name => module.AssemblyReferences[i].Name == name)) { - this.Monitor.LogOnce(loggedMessages, $"{logPrefix}Rewriting {filename} for OS..."); platformChanged = true; module.AssemblyReferences.RemoveAt(i); i--; + this.Monitor.LogOnce(loggedMessages, $"{logPrefix}Rewrote {filename} for OS..."); } } if (platformChanged) @@ -394,7 +394,7 @@ namespace StardewModdingAPI.Framework.ModLoading break; case InstructionHandleResult.DetectedGamePatch: - template = $"{logPrefix}Detected game patcher ($phrase) in assembly {filename}."; + template = $"{logPrefix}Detected game patcher in assembly {filename}."; // no need for phrase, which would confusingly be 'Harmony 1.x' here mod.SetWarning(ModWarning.PatchesGame); break; @@ -438,13 +438,10 @@ namespace StardewModdingAPI.Framework.ModLoading return; // format messages - if (handler.Phrases.Any()) - { - foreach (string message in handler.Phrases) - this.Monitor.LogOnce(loggedMessages, template.Replace("$phrase", message)); - } - else - this.Monitor.LogOnce(loggedMessages, template.Replace("$phrase", handler.DefaultPhrase ?? handler.GetType().Name)); + string phrase = handler.Phrases.Any() + ? string.Join(", ", handler.Phrases) + : handler.DefaultPhrase ?? handler.GetType().Name; + this.Monitor.LogOnce(loggedMessages, template.Replace("$phrase", phrase)); } /// 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 01ed153b..a2ea3232 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs @@ -1,3 +1,5 @@ +using System.Collections.Generic; +using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; using StardewModdingAPI.Framework.ModLoading.Framework; @@ -13,8 +15,8 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The full type name for which to find references. private readonly string FullTypeName; - /// The event name for which to find references. - private readonly string EventName; + /// The method names for which to find references. + private readonly ISet MethodNames; /// The result to return for matching instructions. private readonly InstructionHandleResult Result; @@ -25,38 +27,47 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders *********/ /// Construct an instance. /// The full type name for which to find references. - /// The event name for which to find references. + /// The event names for which to find references. /// The result to return for matching instructions. - public EventFinder(string fullTypeName, string eventName, InstructionHandleResult result) - : base(defaultPhrase: $"{fullTypeName}.{eventName} event") + public EventFinder(string fullTypeName, string[] eventNames, InstructionHandleResult result) + : base(defaultPhrase: $"{string.Join(", ", eventNames.Select(p => $"{fullTypeName}.{p}"))} event{(eventNames.Length != 1 ? "s" : "")}") // default phrase should never be used { this.FullTypeName = fullTypeName; - this.EventName = eventName; this.Result = result; + + this.MethodNames = new HashSet(); + foreach (string name in eventNames) + { + this.MethodNames.Add($"add_{name}"); + this.MethodNames.Add($"remove_{name}"); + } } + /// Construct an instance. + /// The full type name for which to find references. + /// The event name for which to find references. + /// The result to return for matching instructions. + public EventFinder(string fullTypeName, string eventName, InstructionHandleResult result) + : this(fullTypeName, new[] { eventName }, result) { } + /// public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction) { - if (!this.Flags.Contains(this.Result) && this.IsMatch(instruction)) - this.MarkFlag(this.Result); - - return false; - } + if (this.MethodNames.Any()) + { + MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + if (methodRef is not null && methodRef.DeclaringType.FullName == this.FullTypeName && this.MethodNames.Contains(methodRef.Name)) + { + string eventName = methodRef.Name.Split(new[] { '_' }, 2)[1]; + this.MethodNames.Remove($"add_{eventName}"); + this.MethodNames.Remove($"remove_{eventName}"); + this.MarkFlag(this.Result); + this.Phrases.Add($"{this.FullTypeName}.{eventName} event"); + } + } - /********* - ** Protected methods - *********/ - /// Get whether a CIL instruction matches. - /// The IL instruction. - protected bool IsMatch(Instruction instruction) - { - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); - return - methodRef != null - && methodRef.DeclaringType.FullName == this.FullTypeName - && (methodRef.Name == "add_" + this.EventName || methodRef.Name == "remove_" + this.EventName); + return false; } } } diff --git a/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs index 2c062243..0947062c 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs @@ -1,3 +1,5 @@ +using System.Collections.Generic; +using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; using StardewModdingAPI.Framework.ModLoading.Framework; @@ -13,8 +15,8 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The full type name for which to find references. private readonly string FullTypeName; - /// The field name for which to find references. - private readonly string FieldName; + /// The field names for which to find references. + private readonly ISet FieldNames; /// The result to return for matching instructions. private readonly InstructionHandleResult Result; @@ -25,21 +27,37 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders *********/ /// Construct an instance. /// The full type name for which to find references. - /// The field name for which to find references. + /// The field names for which to find references. /// The result to return for matching instructions. - public FieldFinder(string fullTypeName, string fieldName, InstructionHandleResult result) - : base(defaultPhrase: $"{fullTypeName}.{fieldName} field") + public FieldFinder(string fullTypeName, string[] fieldNames, InstructionHandleResult result) + : base(defaultPhrase: $"{string.Join(", ", fieldNames.Select(p => $"{fullTypeName}.{p}"))} field{(fieldNames.Length != 1 ? "s" : "")}") // default phrase should never be used { this.FullTypeName = fullTypeName; - this.FieldName = fieldName; + this.FieldNames = new HashSet(fieldNames); this.Result = result; } + /// Construct an instance. + /// The full type name for which to find references. + /// The field name for which to find references. + /// The result to return for matching instructions. + public FieldFinder(string fullTypeName, string fieldName, InstructionHandleResult result) + : this(fullTypeName, new[] { fieldName }, result) { } + /// public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction) { - if (!this.Flags.Contains(this.Result) && RewriteHelper.IsFieldReferenceTo(instruction, this.FullTypeName, this.FieldName)) - this.MarkFlag(this.Result); + if (this.FieldNames.Any()) + { + FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + if (fieldRef is not null && fieldRef.DeclaringType.FullName == this.FullTypeName && this.FieldNames.Contains(fieldRef.Name)) + { + this.FieldNames.Remove(fieldRef.Name); + + this.MarkFlag(this.Result); + this.Phrases.Add($"{this.FullTypeName}.{fieldRef.Name} field"); + } + } return false; } diff --git a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs index b01a3240..8c1cae2b 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs @@ -14,7 +14,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders ** Fields *********/ /// The assembly names to which to heuristically detect broken references. - private readonly HashSet ValidateReferencesToAssemblies; + private readonly ISet ValidateReferencesToAssemblies; /********* @@ -22,10 +22,10 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders *********/ /// Construct an instance. /// The assembly names to which to heuristically detect broken references. - public ReferenceToMemberWithUnexpectedTypeFinder(string[] validateReferencesToAssemblies) + public ReferenceToMemberWithUnexpectedTypeFinder(ISet validateReferencesToAssemblies) : base(defaultPhrase: "") { - this.ValidateReferencesToAssemblies = new HashSet(validateReferencesToAssemblies); + this.ValidateReferencesToAssemblies = validateReferencesToAssemblies; } /// diff --git a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs index b64a255e..d305daf4 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs @@ -13,7 +13,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders ** Fields *********/ /// The assembly names to which to heuristically detect broken references. - private readonly HashSet ValidateReferencesToAssemblies; + private readonly ISet ValidateReferencesToAssemblies; /********* @@ -21,10 +21,10 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders *********/ /// Construct an instance. /// The assembly names to which to heuristically detect broken references. - public ReferenceToMissingMemberFinder(string[] validateReferencesToAssemblies) + public ReferenceToMissingMemberFinder(ISet validateReferencesToAssemblies) : base(defaultPhrase: "") { - this.ValidateReferencesToAssemblies = new HashSet(validateReferencesToAssemblies); + this.ValidateReferencesToAssemblies = validateReferencesToAssemblies; } /// diff --git a/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs index bbd081e8..260a8df8 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using Mono.Cecil; using StardewModdingAPI.Framework.ModLoading.Framework; @@ -10,8 +11,8 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /********* ** Fields *********/ - /// The full type name to match. - private readonly string FullTypeName; + /// The full type names remaining to match. + private readonly ISet FullTypeNames; /// The result to return for matching instructions. private readonly InstructionHandleResult Result; @@ -24,22 +25,34 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders ** Public methods *********/ /// Construct an instance. - /// The full type name to match. + /// The full type names to match. /// The result to return for matching instructions. /// Get whether a matched type should be ignored. - public TypeFinder(string fullTypeName, InstructionHandleResult result, Func shouldIgnore = null) - : base(defaultPhrase: $"{fullTypeName} type") + public TypeFinder(string[] fullTypeNames, InstructionHandleResult result, Func shouldIgnore = null) + : base(defaultPhrase: $"{string.Join(", ", fullTypeNames)} type{(fullTypeNames.Length != 1 ? "s" : "")}") // default phrase should never be used { - this.FullTypeName = fullTypeName; + this.FullTypeNames = new HashSet(fullTypeNames); this.Result = result; this.ShouldIgnore = shouldIgnore; } + /// Construct an instance. + /// The full type name to match. + /// The result to return for matching instructions. + /// Get whether a matched type should be ignored. + public TypeFinder(string fullTypeName, InstructionHandleResult result, Func shouldIgnore = null) + : this(new[] { fullTypeName }, result, shouldIgnore) { } + /// public override bool Handle(ModuleDefinition module, TypeReference type, Action replaceWith) { - if (type.FullName == this.FullTypeName && this.ShouldIgnore?.Invoke(type) != true) + if (this.FullTypeNames.Contains(type.FullName) && this.ShouldIgnore?.Invoke(type) != true) + { + this.FullTypeNames.Remove(type.FullName); + this.MarkFlag(this.Result); + this.Phrases.Add($"{type.FullName} type"); + } return false; } diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs deleted file mode 100644 index 7a3b428d..00000000 --- a/src/SMAPI/Framework/ModLoading/Rewriters/Harmony1AssemblyRewriter.cs +++ /dev/null @@ -1,129 +0,0 @@ -using System; -using HarmonyLib; -using Mono.Cecil; -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 : BaseInstructionHandler - { - /********* - ** Fields - *********/ - /// Whether any Harmony 1.x types were replaced. - private bool ReplacedTypes; - - - /********* - ** Public methods - *********/ - /// Construct an instance. - public Harmony1AssemblyRewriter() - : base(defaultPhrase: "Harmony 1.x") { } - - /// - 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 { Name: "0Harmony" } scope && scope.Version.Major == 1) - { - Type targetType = this.GetMappedType(type); - replaceWith(module.ImportReference(targetType)); - this.OnChanged(); - this.ReplacedTypes = true; - return true; - } - - return false; - } - - /// - public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction) - { - // rewrite Harmony 1.x methods to Harmony 2.0 - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); - if (this.TryRewriteMethodsToFacade(module, methodRef)) - { - this.OnChanged(); - 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); - this.OnChanged(); - } - } - - return false; - } - - - /********* - ** Private methods - *********/ - /// Update the mod metadata when any Harmony 1.x code is migrated. - private void OnChanged() - { - this.MarkRewritten(); - this.MarkFlag(InstructionHandleResult.DetectedGamePatch); - } - - /// 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) - { - if (!this.ReplacedTypes) - return false; // not Harmony (or already using Harmony 2.0) - - // get facade type - Type toType = methodRef?.DeclaringType.FullName switch - { - "HarmonyLib.Harmony" => typeof(HarmonyInstanceFacade), - "HarmonyLib.AccessTools" => typeof(AccessToolsFacade), - "HarmonyLib.HarmonyMethod" => typeof(HarmonyMethodFacade), - _ => null - }; - if (toType == null) - return false; - - // map if there's a matching method - if (RewriteHelper.HasMatchingSignature(toType, methodRef)) - { - methodRef.DeclaringType = module.ImportReference(toType); - return true; - } - - return false; - } - - /// Get an equivalent Harmony 2.x type. - /// The Harmony 1.x type. - private Type GetMappedType(TypeReference type) - { - return type.FullName switch - { - "Harmony.HarmonyInstance" => typeof(Harmony), - "Harmony.ILCopying.ExceptionBlock" => typeof(ExceptionBlock), - _ => this.GetMappedTypeByConvention(type) - }; - } - - /// Get an equivalent Harmony 2.x type using the convention expected for most types. - /// The Harmony 1.x type. - private Type GetMappedTypeByConvention(TypeReference type) - { - string fullName = type.FullName.Replace("Harmony.", "HarmonyLib."); - string targetName = typeof(Harmony).AssemblyQualifiedName!.Replace(typeof(Harmony).FullName!, fullName); - return Type.GetType(targetName, throwOnError: true); - } - } -} diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/HarmonyRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/HarmonyRewriter.cs new file mode 100644 index 00000000..38ab3d80 --- /dev/null +++ b/src/SMAPI/Framework/ModLoading/Rewriters/HarmonyRewriter.cs @@ -0,0 +1,143 @@ +using System; +using HarmonyLib; +using Mono.Cecil; +using Mono.Cecil.Cil; +using StardewModdingAPI.Framework.ModLoading.Framework; +using StardewModdingAPI.Framework.ModLoading.RewriteFacades; + +namespace StardewModdingAPI.Framework.ModLoading.Rewriters +{ + /// Detects Harmony references, and rewrites Harmony 1.x assembly references to work with Harmony 2.x. + internal class HarmonyRewriter : BaseInstructionHandler + { + /********* + ** Fields + *********/ + /// Whether any Harmony 1.x types were replaced. + private bool ReplacedTypes; + + /// Whether to rewrite Harmony 1.x code. + private readonly bool ShouldRewrite; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + public HarmonyRewriter(bool shouldRewrite = true) + : base(defaultPhrase: "Harmony 1.x") + { + this.ShouldRewrite = shouldRewrite; + } + + /// + public override bool Handle(ModuleDefinition module, TypeReference type, Action replaceWith) + { + // detect Harmony + if (type.Scope is not AssemblyNameReference { Name: "0Harmony" } scope) + return false; + + // rewrite Harmony 1.x type to Harmony 2.0 type + if (this.ShouldRewrite && scope.Version.Major == 1) + { + Type targetType = this.GetMappedType(type); + replaceWith(module.ImportReference(targetType)); + this.OnChanged(); + this.ReplacedTypes = true; + return true; + } + + this.MarkFlag(InstructionHandleResult.DetectedGamePatch); + return false; + } + + /// + public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction) + { + if (this.ShouldRewrite) + { + // rewrite Harmony 1.x methods to Harmony 2.0 + MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + if (this.TryRewriteMethodsToFacade(module, methodRef)) + { + this.OnChanged(); + 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); + this.OnChanged(); + } + } + } + + return false; + } + + + /********* + ** Private methods + *********/ + /// Update the mod metadata when any Harmony 1.x code is migrated. + private void OnChanged() + { + this.MarkRewritten(); + this.MarkFlag(InstructionHandleResult.DetectedGamePatch); + } + + /// 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) + { + if (!this.ReplacedTypes) + return false; // not Harmony (or already using Harmony 2.0) + + // get facade type + Type toType = methodRef?.DeclaringType.FullName switch + { + "HarmonyLib.Harmony" => typeof(HarmonyInstanceFacade), + "HarmonyLib.AccessTools" => typeof(AccessToolsFacade), + "HarmonyLib.HarmonyMethod" => typeof(HarmonyMethodFacade), + _ => null + }; + if (toType == null) + return false; + + // map if there's a matching method + if (RewriteHelper.HasMatchingSignature(toType, methodRef)) + { + methodRef.DeclaringType = module.ImportReference(toType); + return true; + } + + return false; + } + + /// Get an equivalent Harmony 2.x type. + /// The Harmony 1.x type. + private Type GetMappedType(TypeReference type) + { + return type.FullName switch + { + "Harmony.HarmonyInstance" => typeof(Harmony), + "Harmony.ILCopying.ExceptionBlock" => typeof(ExceptionBlock), + _ => this.GetMappedTypeByConvention(type) + }; + } + + /// Get an equivalent Harmony 2.x type using the convention expected for most types. + /// The Harmony 1.x type. + private Type GetMappedTypeByConvention(TypeReference type) + { + string fullName = type.FullName.Replace("Harmony.", "HarmonyLib."); + string targetName = typeof(Harmony).AssemblyQualifiedName!.Replace(typeof(Harmony).FullName!, fullName); + return Type.GetType(targetName, throwOnError: true); + } + } +} diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicFieldRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicFieldRewriter.cs index f59a6ab1..57f1dd17 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicFieldRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicFieldRewriter.cs @@ -13,7 +13,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters ** Fields *********/ /// The assembly names to which to rewrite broken references. - private readonly HashSet RewriteReferencesToAssemblies; + private readonly ISet RewriteReferencesToAssemblies; /********* @@ -21,10 +21,10 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters *********/ /// Construct an instance. /// The assembly names to which to rewrite broken references. - public HeuristicFieldRewriter(string[] rewriteReferencesToAssemblies) + public HeuristicFieldRewriter(ISet rewriteReferencesToAssemblies) : base(defaultPhrase: "field changed to property") // ignored since we specify phrases { - this.RewriteReferencesToAssemblies = new HashSet(rewriteReferencesToAssemblies); + this.RewriteReferencesToAssemblies = rewriteReferencesToAssemblies; } /// diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicMethodRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicMethodRewriter.cs index e133b6fa..89de437e 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicMethodRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicMethodRewriter.cs @@ -13,7 +13,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters ** Fields *********/ /// The assembly names to which to rewrite broken references. - private readonly HashSet RewriteReferencesToAssemblies; + private readonly ISet RewriteReferencesToAssemblies; /********* @@ -21,10 +21,10 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters *********/ /// Construct an instance. /// The assembly names to which to rewrite broken references. - public HeuristicMethodRewriter(string[] rewriteReferencesToAssemblies) + public HeuristicMethodRewriter(ISet rewriteReferencesToAssemblies) : base(defaultPhrase: "methods with missing parameters") // ignored since we specify phrases { - this.RewriteReferencesToAssemblies = new HashSet(rewriteReferencesToAssemblies); + this.RewriteReferencesToAssemblies = rewriteReferencesToAssemblies; } /// diff --git a/src/SMAPI/Metadata/InstructionMetadata.cs b/src/SMAPI/Metadata/InstructionMetadata.cs index 9f537c92..44d906ea 100644 --- a/src/SMAPI/Metadata/InstructionMetadata.cs +++ b/src/SMAPI/Metadata/InstructionMetadata.cs @@ -18,7 +18,7 @@ namespace StardewModdingAPI.Metadata *********/ /// The assembly names to which to heuristically detect broken references. /// The current implementation only works correctly with assemblies that should always be present. - private readonly string[] ValidateReferencesToAssemblies = { "StardewModdingAPI", "Stardew Valley", "StardewValley", "Netcode" }; + private readonly ISet ValidateReferencesToAssemblies = new HashSet { "StardewModdingAPI", "Stardew Valley", "StardewValley", "Netcode" }; /********* @@ -48,14 +48,16 @@ namespace StardewModdingAPI.Metadata yield return new HeuristicFieldRewriter(this.ValidateReferencesToAssemblies); yield return new HeuristicMethodRewriter(this.ValidateReferencesToAssemblies); - // rewrite for SMAPI 3.12 (Harmony 1.x => 2.0 update) - yield return new Harmony1AssemblyRewriter(); + // detect Harmony & rewrite for SMAPI 3.12 (Harmony 1.x => 2.0 update) + yield return new HarmonyRewriter(); // rewrite for 64-bit mode #if SMAPI_FOR_WINDOWS_64BIT_HACK yield return new ArchitectureAssemblyRewriter(); #endif } + else + yield return new HarmonyRewriter(shouldRewrite: false); /**** ** detect mod issues @@ -67,13 +69,9 @@ namespace StardewModdingAPI.Metadata /**** ** detect code which may impact game stability ****/ - 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); - yield return new FieldFinder(typeof(SaveGame).FullName, nameof(SaveGame.locationSerializer), InstructionHandleResult.DetectedSaveSerializer); - yield return new EventFinder(typeof(ISpecializedEvents).FullName, nameof(ISpecializedEvents.UnvalidatedUpdateTicked), InstructionHandleResult.DetectedUnvalidatedUpdateTick); - yield return new EventFinder(typeof(ISpecializedEvents).FullName, nameof(ISpecializedEvents.UnvalidatedUpdateTicking), InstructionHandleResult.DetectedUnvalidatedUpdateTick); + yield return new FieldFinder(typeof(SaveGame).FullName, new[] { nameof(SaveGame.serializer), nameof(SaveGame.farmerSerializer), nameof(SaveGame.locationSerializer) }, InstructionHandleResult.DetectedSaveSerializer); + yield return new EventFinder(typeof(ISpecializedEvents).FullName, new[] { nameof(ISpecializedEvents.UnvalidatedUpdateTicked), nameof(ISpecializedEvents.UnvalidatedUpdateTicking) }, InstructionHandleResult.DetectedUnvalidatedUpdateTick); /**** ** detect paranoid issues @@ -82,13 +80,19 @@ namespace StardewModdingAPI.Metadata { // filesystem access yield return new TypeFinder(typeof(System.Console).FullName, InstructionHandleResult.DetectedConsoleAccess); - yield return new TypeFinder(typeof(System.IO.File).FullName, InstructionHandleResult.DetectedFilesystemAccess); - yield return new TypeFinder(typeof(System.IO.FileStream).FullName, InstructionHandleResult.DetectedFilesystemAccess); - yield return new TypeFinder(typeof(System.IO.FileInfo).FullName, InstructionHandleResult.DetectedFilesystemAccess); - yield return new TypeFinder(typeof(System.IO.Directory).FullName, InstructionHandleResult.DetectedFilesystemAccess); - yield return new TypeFinder(typeof(System.IO.DirectoryInfo).FullName, InstructionHandleResult.DetectedFilesystemAccess); - yield return new TypeFinder(typeof(System.IO.DriveInfo).FullName, InstructionHandleResult.DetectedFilesystemAccess); - yield return new TypeFinder(typeof(System.IO.FileSystemWatcher).FullName, InstructionHandleResult.DetectedFilesystemAccess); + yield return new TypeFinder( + new[] + { + typeof(System.IO.File).FullName, + typeof(System.IO.FileStream).FullName, + typeof(System.IO.FileInfo).FullName, + typeof(System.IO.Directory).FullName, + typeof(System.IO.DirectoryInfo).FullName, + typeof(System.IO.DriveInfo).FullName, + typeof(System.IO.FileSystemWatcher).FullName + }, + InstructionHandleResult.DetectedFilesystemAccess + ); // shell access yield return new TypeFinder(typeof(System.Diagnostics.Process).FullName, InstructionHandleResult.DetectedShellAccess); -- cgit From bbaa260007f67d6e3c88c1aae387b42b0c237063 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 2 Sep 2021 23:01:40 -0400 Subject: drop support for unofficial 64-bit mode --- build/common.targets | 7 +--- docs/release-notes.md | 3 +- docs/technical/smapi.md | 16 ++------ src/SMAPI.Installer/InteractiveInstaller.cs | 48 +++++++--------------- .../SMAPI.Mods.ConsoleCommands.csproj | 2 +- .../SMAPI.Mods.ErrorHandler.csproj | 2 +- src/SMAPI/Constants.cs | 12 +----- src/SMAPI/Framework/Content/ContentCache.cs | 2 - src/SMAPI/Framework/Logging/LogManager.cs | 22 +--------- src/SMAPI/Framework/SCore.cs | 18 ++++---- src/SMAPI/Metadata/InstructionMetadata.cs | 9 ++-- src/SMAPI/Program.cs | 20 ++++----- src/SMAPI/SMAPI.csproj | 6 +-- 13 files changed, 48 insertions(+), 119 deletions(-) (limited to 'src/SMAPI/Metadata') diff --git a/build/common.targets b/build/common.targets index 70f0a741..e688ae65 100644 --- a/build/common.targets +++ b/build/common.targets @@ -6,13 +6,8 @@ latest $(AssemblySearchPaths);{GAC} - - - - $(DefineConstants);SMAPI_FOR_WINDOWS - $(DefineConstants);SMAPI_FOR_XNA + $(DefineConstants);SMAPI_FOR_WINDOWS;SMAPI_FOR_XNA diff --git a/docs/release-notes.md b/docs/release-notes.md index 53640c93..3779bcac 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -5,7 +5,8 @@ * For players: * Added friendly error when using SMAPI 3.2._x_ with Stardew Valley 1.5.5 or later. * Improved mod compatibility in 64-bit mode (thanks to spacechase0!). - * Reducing load time when scanning/rewriting many mods for compatibility. + * Reduced load time when scanning/rewriting many mods for compatibility. + * **Dropped support for unofficial 64-bit mode**. You can now use the [official 64-bit Stardew Valley 1.5.5 beta](https://stardewvalleywiki.com/Modding:Migrate_to_64-bit_on_Windows) instead. * Updated compatibility list. * For mod authors: diff --git a/docs/technical/smapi.md b/docs/technical/smapi.md index 586b17aa..4be062e2 100644 --- a/docs/technical/smapi.md +++ b/docs/technical/smapi.md @@ -57,8 +57,7 @@ SMAPI uses a small number of conditional compilation constants, which you can se flag | purpose ---- | ------- `SMAPI_FOR_WINDOWS` | Whether SMAPI is being compiled for Windows; if not set, the code assumes Linux/macOS. Set automatically in `common.targets`. -`SMAPI_FOR_WINDOWS_64BIT_HACK` | Whether SMAPI is being [compiled for Windows with a 64-bit Linux version of the game](https://github.com/Pathoschild/SMAPI/issues/767). This is highly specialized and shouldn't be used in most cases. False by default. -`SMAPI_FOR_XNA` | Whether SMAPI is being compiled for XNA Framework; if not set, the code assumes MonoGame. Set automatically in `common.targets` with the same value as `SMAPI_FOR_WINDOWS` (unless `SMAPI_FOR_WINDOWS_64BIT_HACK` is set). +`SMAPI_FOR_XNA` | Whether SMAPI is being compiled for XNA Framework; if not set, the code assumes MonoGame. Set automatically in `common.targets` with the same value as `SMAPI_FOR_WINDOWS`. ## For SMAPI developers ### Compiling from source @@ -81,9 +80,7 @@ To prepare a crossplatform SMAPI release, you'll need to compile it on two platf [crossplatforming info](https://stardewvalleywiki.com/Modding:Modder_Guide/Test_and_Troubleshoot#Testing_on_all_platforms) on the wiki for the first-time setup. -1. [Install a separate 64-bit version of Stardew Valley](https://github.com/Steviegt6/Stardew64Installer#readme) - on Windows. -2. Update the version numbers in `build/common.targets`, `Constants`, and the `manifest.json` for +1. Update the version numbers in `build/common.targets`, `Constants`, and the `manifest.json` for bundled mods. Make sure you use a [semantic version](https://semver.org). Recommended format: build type | format | example @@ -91,14 +88,9 @@ on the wiki for the first-time setup. dev build | `-alpha.` | `3.0.0-alpha.20171230` prerelease | `-beta.` | `3.0.0-beta.20171230` release | `` | `3.0.0` -3. In Windows: +2. In Windows: 1. Rebuild the solution with the _release_ solution configuration. - 2. Back up the `bin/SMAPI installer` and `bin/SMAPI installer for developers` folders. - 3. Edit `common.targets` and uncomment the Stardew Valley 64-bit section at the top. - 4. Rebuild the solution again. - 5. Rename the compiled `StardewModdingAPI.exe` file to `StardewModdingAPI-x64.exe`, and copy it - into the `windows-install.dat` files from step ii. - 6. Copy the folders from step ii to Linux/MacOS. + 2. Copy the `bin/SMAPI installer` and `bin/SMAPI installer for developers` folders to Linux/macOS. 4. In Linux/macOS: 1. Rebuild the solution with the _release_ solution configuration. 2. Add the `windows-install.*` files from Windows to the `bin/SMAPI installer` and diff --git a/src/SMAPI.Installer/InteractiveInstaller.cs b/src/SMAPI.Installer/InteractiveInstaller.cs index 17c3198f..9f49137f 100644 --- a/src/SMAPI.Installer/InteractiveInstaller.cs +++ b/src/SMAPI.Installer/InteractiveInstaller.cs @@ -275,21 +275,20 @@ namespace StardewModdingApi.Installer /********* - ** Step 4: detect 64-bit Stardew Valley + ** Step 4: validate assumptions *********/ - // detect 64-bit mode - bool isWindows64Bit = false; + // not 64-bit on Windows if (context.Platform == Platform.Windows) { FileInfo linuxExecutable = new FileInfo(Path.Combine(paths.GamePath, "StardewValley.exe")); - isWindows64Bit = linuxExecutable.Exists && this.Is64Bit(linuxExecutable.FullName); - if (isWindows64Bit) - paths.SetExecutableFileName(linuxExecutable.Name); + if (linuxExecutable.Exists && this.Is64Bit(linuxExecutable.FullName)) + { + this.PrintError("Oops! The detected game install path seems to be unofficial 64-bit mode, which is no longer supported. You can update to Stardew Valley 1.5.5 or later instead. See https://stardewvalleywiki.com/Modding:Migrate_to_64-bit_on_Windows for more info."); + Console.ReadLine(); + return; + } } - /********* - ** Step 5: validate assumptions - *********/ // executable exists if (!File.Exists(paths.ExecutablePath)) { @@ -301,7 +300,7 @@ namespace StardewModdingApi.Installer // not Stardew Valley 1.5.5+ if (File.Exists(Path.Combine(paths.GamePath, "Stardew Valley.dll"))) { - this.PrintError($"Oops! The detected game install path seems to be Stardew Valley 1.5.5 or later, but this version of SMAPI is only compatible up to Stardew Valley 1.5.4. Please check for a newer version of SMAPI: https://smapi.io."); + this.PrintError("Oops! The detected game install path seems to be Stardew Valley 1.5.5 or later, but this version of SMAPI is only compatible up to Stardew Valley 1.5.4. Please check for a newer version of SMAPI: https://smapi.io."); Console.ReadLine(); return; } @@ -320,7 +319,7 @@ namespace StardewModdingApi.Installer /********* - ** Step 6: ask what to do + ** Step 5: ask what to do *********/ ScriptAction action; { @@ -328,7 +327,7 @@ namespace StardewModdingApi.Installer ** print header ****/ this.PrintInfo("Hi there! I'll help you install or remove SMAPI. Just one question first."); - this.PrintDebug($"Game path: {paths.GamePath}{(context.IsWindows ? $" [{(isWindows64Bit ? "64-bit" : "32-bit")}]" : "")}"); + this.PrintDebug($"Game path: {paths.GamePath}"); this.PrintDebug($"Color scheme: {this.GetDisplayText(scheme)}"); this.PrintDebug("----------------------------------------------------------------------------"); Console.WriteLine(); @@ -366,14 +365,14 @@ namespace StardewModdingApi.Installer /********* - ** Step 7: apply + ** Step 6: apply *********/ { /**** ** print header ****/ this.PrintInfo($"That's all I need! I'll {action.ToString().ToLower()} SMAPI now."); - this.PrintDebug($"Game path: {paths.GamePath}{(context.IsWindows ? $" [{(isWindows64Bit ? "64-bit" : "32-bit")}]" : "")}"); + this.PrintDebug($"Game path: {paths.GamePath}"); this.PrintDebug($"Color scheme: {this.GetDisplayText(scheme)}"); this.PrintDebug("----------------------------------------------------------------------------"); Console.WriteLine(); @@ -434,25 +433,6 @@ namespace StardewModdingApi.Installer this.RecursiveCopy(sourceEntry, paths.GameDir); } - // handle 64-bit file - { - FileInfo x64Executable = new FileInfo(Path.Combine(paths.GameDir.FullName, "StardewModdingAPI-x64.exe")); - if (isWindows64Bit) - { - this.PrintDebug("Making SMAPI 64-bit..."); - if (x64Executable.Exists) - { - string targetPath = Path.Combine(paths.GameDir.FullName, "StardewModdingAPI.exe"); - this.InteractivelyDelete(targetPath); - x64Executable.MoveTo(targetPath); - } - else - this.PrintError($"Oops! Could not find the required '{x64Executable.Name}' installer file. SMAPI may not work correctly."); - } - else if (x64Executable.Exists) - x64Executable.Delete(); - } - // replace mod launcher (if possible) if (context.IsUnix) { @@ -547,7 +527,7 @@ namespace StardewModdingApi.Installer /********* - ** Step 7: final instructions + ** Step 6: final instructions *********/ if (context.IsWindows) { diff --git a/src/SMAPI.Mods.ConsoleCommands/SMAPI.Mods.ConsoleCommands.csproj b/src/SMAPI.Mods.ConsoleCommands/SMAPI.Mods.ConsoleCommands.csproj index 432fdc35..a187c1ff 100644 --- a/src/SMAPI.Mods.ConsoleCommands/SMAPI.Mods.ConsoleCommands.csproj +++ b/src/SMAPI.Mods.ConsoleCommands/SMAPI.Mods.ConsoleCommands.csproj @@ -19,7 +19,7 @@ - + diff --git a/src/SMAPI.Mods.ErrorHandler/SMAPI.Mods.ErrorHandler.csproj b/src/SMAPI.Mods.ErrorHandler/SMAPI.Mods.ErrorHandler.csproj index ffda5f89..eb878bc5 100644 --- a/src/SMAPI.Mods.ErrorHandler/SMAPI.Mods.ErrorHandler.csproj +++ b/src/SMAPI.Mods.ErrorHandler/SMAPI.Mods.ErrorHandler.csproj @@ -21,7 +21,7 @@ - + diff --git a/src/SMAPI/Constants.cs b/src/SMAPI/Constants.cs index 247e32b7..ebb504db 100644 --- a/src/SMAPI/Constants.cs +++ b/src/SMAPI/Constants.cs @@ -39,14 +39,6 @@ namespace StardewModdingAPI /// The target game platform. internal static GamePlatform Platform { get; } = (GamePlatform)Enum.Parse(typeof(GamePlatform), LowLevelEnvironmentUtility.DetectPlatform()); - /// Whether SMAPI is being compiled for Windows with a 64-bit Linux version of the game. This is highly specialized and shouldn't be used in most cases. - internal static bool IsWindows64BitHack { get; } = -#if SMAPI_FOR_WINDOWS_64BIT_HACK - true; -#else - false; -#endif - /// The game framework running the game. internal static GameFramework GameFramework { get; } = #if SMAPI_FOR_XNA @@ -56,7 +48,7 @@ namespace StardewModdingAPI #endif /// The game's assembly name. - internal static string GameAssemblyName => EarlyConstants.Platform == GamePlatform.Windows && !EarlyConstants.IsWindows64BitHack ? "Stardew Valley" : "StardewValley"; + internal static string GameAssemblyName => EarlyConstants.Platform == GamePlatform.Windows ? "Stardew Valley" : "StardewValley"; /// The value which should appear in the SMAPI log, if any. internal static int? LogScreenId { get; set; } @@ -269,7 +261,7 @@ namespace StardewModdingAPI targetAssemblies.Add(typeof(StardewModdingAPI.IManifest).Assembly); // get changes for platform - if (Constants.Platform != Platform.Windows || EarlyConstants.IsWindows64BitHack) + if (Constants.Platform != Platform.Windows) { removeAssemblyReferences.AddRange(new[] { diff --git a/src/SMAPI/Framework/Content/ContentCache.cs b/src/SMAPI/Framework/Content/ContentCache.cs index 5c7ad778..7edc9ab9 100644 --- a/src/SMAPI/Framework/Content/ContentCache.cs +++ b/src/SMAPI/Framework/Content/ContentCache.cs @@ -57,8 +57,6 @@ namespace StardewModdingAPI.Framework.Content IReflectedMethod method = reflection.GetMethod(typeof(TitleContainer), "GetCleanPath"); this.NormalizeAssetNameForPlatform = path => method.Invoke(path); } - else if (EarlyConstants.IsWindows64BitHack) - this.NormalizeAssetNameForPlatform = PathUtilities.NormalizePath; else this.NormalizeAssetNameForPlatform = key => key.Replace('\\', '/'); // based on MonoGame's ContentManager.Load logic } diff --git a/src/SMAPI/Framework/Logging/LogManager.cs b/src/SMAPI/Framework/Logging/LogManager.cs index c6faa90d..6fe44d98 100644 --- a/src/SMAPI/Framework/Logging/LogManager.cs +++ b/src/SMAPI/Framework/Logging/LogManager.cs @@ -291,13 +291,7 @@ namespace StardewModdingAPI.Framework.Logging public void LogIntro(string modsPath, IDictionary customSettings) { // log platform & patches - { - this.Monitor.Log($"SMAPI {Constants.ApiVersion} with Stardew Valley {Constants.GameVersion} on {EnvironmentUtility.GetFriendlyPlatformName(Constants.Platform)}", LogLevel.Info); - - string[] patchLabels = this.GetPatchLabels().ToArray(); - if (patchLabels.Any()) - this.Monitor.Log($"Detected custom version: {string.Join(", ", patchLabels)}", LogLevel.Info); - } + this.Monitor.Log($"SMAPI {Constants.ApiVersion} with Stardew Valley {Constants.GameVersion} on {EnvironmentUtility.GetFriendlyPlatformName(Constants.Platform)}", LogLevel.Info); // log basic info this.Monitor.Log($"Mods go here: {modsPath}", LogLevel.Info); @@ -416,20 +410,6 @@ namespace StardewModdingAPI.Framework.Logging gameMonitor.Log(message, level); } - /// Get human-readable labels to log for detected SMAPI and Stardew Valley customizations. - private IEnumerable GetPatchLabels() - { - // custom game framework - if (EarlyConstants.IsWindows64BitHack) - yield return $"running 64-bit SMAPI with {Constants.GameFramework}"; - else if ((Constants.GameFramework == GameFramework.Xna) != (Constants.Platform == Platform.Windows)) - yield return $"running {Constants.GameFramework}"; - - // patched by Stardew64Installer - if (Constants.IsPatchedByStardew64Installer(out ISemanticVersion patchedByVersion)) - yield return $"patched by Stardew64Installer {patchedByVersion}"; - } - /// Write a summary of mod warnings to the console and log. /// The loaded mods. /// The mods which could not be loaded. diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index f7efc89e..ce5a701d 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -12,10 +12,10 @@ using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; +using Microsoft.Xna.Framework; #if SMAPI_FOR_WINDOWS using Microsoft.Win32; #endif -using Microsoft.Xna.Framework; #if SMAPI_FOR_XNA using System.Windows.Forms; #endif @@ -436,7 +436,7 @@ namespace StardewModdingAPI.Framework Game1.mapDisplayDevice = new SDisplayDevice(Game1.content, Game1.game1.GraphicsDevice); // log GPU info -#if SMAPI_FOR_WINDOWS && !SMAPI_FOR_WINDOWS_64BIT_HACK +#if SMAPI_FOR_WINDOWS this.Monitor.Log($"Running on GPU: {Game1.game1.GraphicsDevice?.Adapter?.Description ?? ""}"); #endif } @@ -1267,10 +1267,8 @@ namespace StardewModdingAPI.Framework /// Set the titles for the game and console windows. private void UpdateWindowTitles() { - string smapiVersion = $"{Constants.ApiVersion}{(EarlyConstants.IsWindows64BitHack ? " [64-bit]" : "")}"; - - string consoleTitle = $"SMAPI {smapiVersion} - running Stardew Valley {Constants.GameVersion}"; - string gameTitle = $"Stardew Valley {Constants.GameVersion} - running SMAPI {smapiVersion}"; + string consoleTitle = $"SMAPI {Constants.ApiVersion} - running Stardew Valley {Constants.GameVersion}"; + string gameTitle = $"Stardew Valley {Constants.GameVersion} - running SMAPI {Constants.ApiVersion}"; if (this.ModRegistry.AreAllModsLoaded) { @@ -1737,10 +1735,10 @@ namespace StardewModdingAPI.Framework catch (Exception ex) { errorReasonPhrase = "its DLL couldn't be loaded."; -#if SMAPI_FOR_WINDOWS_64BIT_HACK - if (ex is BadImageFormatException && !EnvironmentUtility.Is64BitAssembly(assemblyPath)) - errorReasonPhrase = "it needs to be updated for 64-bit mode."; -#endif + // re-enable in Stardew Valley 1.5.5 + //if (ex is BadImageFormatException && !EnvironmentUtility.Is64BitAssembly(assemblyPath)) + // errorReasonPhrase = "it needs to be updated for 64-bit mode."; + errorDetails = $"Error: {ex.GetLogSummary()}"; failReason = ModFailReason.LoadFailed; return false; diff --git a/src/SMAPI/Metadata/InstructionMetadata.cs b/src/SMAPI/Metadata/InstructionMetadata.cs index 44d906ea..76371e50 100644 --- a/src/SMAPI/Metadata/InstructionMetadata.cs +++ b/src/SMAPI/Metadata/InstructionMetadata.cs @@ -48,13 +48,12 @@ namespace StardewModdingAPI.Metadata yield return new HeuristicFieldRewriter(this.ValidateReferencesToAssemblies); yield return new HeuristicMethodRewriter(this.ValidateReferencesToAssemblies); + // rewrite for 64-bit mode + // re-enable in Stardew Valley 1.5.5 + //yield return new ArchitectureAssemblyRewriter(); + // detect Harmony & rewrite for SMAPI 3.12 (Harmony 1.x => 2.0 update) yield return new HarmonyRewriter(); - - // rewrite for 64-bit mode -#if SMAPI_FOR_WINDOWS_64BIT_HACK - yield return new ArchitectureAssemblyRewriter(); -#endif } else yield return new HarmonyRewriter(shouldRewrite: false); diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index b6464f3c..3f97e531 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -26,7 +26,7 @@ namespace StardewModdingAPI /// The command-line arguments. public static void Main(string[] args) { - Console.Title = $"SMAPI {EarlyConstants.RawApiVersion}{(EarlyConstants.IsWindows64BitHack ? " 64-bit" : "")} - {Console.Title}"; + Console.Title = $"SMAPI {EarlyConstants.RawApiVersion} - {Console.Title}"; try { @@ -84,6 +84,14 @@ namespace StardewModdingAPI } catch (Exception ex) { + // unofficial 64-bit + if (EarlyConstants.Platform == GamePlatform.Windows) + { + FileInfo linuxExecutable = new FileInfo(Path.Combine(EarlyConstants.ExecutionPath, "StardewValley.exe")); + if (linuxExecutable.Exists && LowLevelEnvironmentUtility.Is64BitAssembly(linuxExecutable.FullName)) + Program.PrintErrorAndExit("Oops! You're running Stardew Valley in unofficial 64-bit mode, which is no longer supported. You can update to Stardew Valley 1.5.5 or later instead. See https://stardewvalleywiki.com/Modding:Migrate_to_64-bit_on_Windows for more info."); + } + // file doesn't exist if (!File.Exists(Path.Combine(EarlyConstants.ExecutionPath, $"{EarlyConstants.GameAssemblyName}.exe"))) Program.PrintErrorAndExit("Oops! SMAPI can't find the game. Make sure you're running StardewModdingAPI.exe in your game folder."); @@ -116,16 +124,6 @@ namespace StardewModdingAPI // max version if (Constants.MaximumGameVersion != null && Constants.GameVersion.IsNewerThan(Constants.MaximumGameVersion)) Program.PrintErrorAndExit($"Oops! You're running Stardew Valley {Constants.GameVersion}, but this version of SMAPI is only compatible up to Stardew Valley {Constants.MaximumGameVersion}. Please check for a newer version of SMAPI: https://smapi.io."); - - // bitness - bool is64BitGame = LowLevelEnvironmentUtility.Is64BitAssembly(Path.Combine(EarlyConstants.ExecutionPath, $"{EarlyConstants.GameAssemblyName}.exe")); -#if SMAPI_FOR_WINDOWS_64BIT_HACK - if (!is64BitGame) - Program.PrintErrorAndExit("Oops! This is the 64-bit version of SMAPI, but you have the 32-bit version of Stardew Valley. You can reinstall SMAPI using its installer to automatically install the correct version of SMAPI."); -#elif SMAPI_FOR_WINDOWS - if (is64BitGame) - Program.PrintErrorAndExit("Oops! This is the 32-bit version of SMAPI, but you have the 64-bit version of Stardew Valley. You can reinstall SMAPI using its installer to automatically install the correct version of SMAPI."); -#endif } /// Assert that the versions of all SMAPI components are correct. diff --git a/src/SMAPI/SMAPI.csproj b/src/SMAPI/SMAPI.csproj index 7d5e7ef9..0f1b0516 100644 --- a/src/SMAPI/SMAPI.csproj +++ b/src/SMAPI/SMAPI.csproj @@ -14,10 +14,6 @@ - - x64 - - @@ -39,7 +35,7 @@ - + -- cgit From 9f1c4549345ba20d799cf46ee44851a1f61f561e Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 3 Sep 2021 18:35:23 -0400 Subject: remove asset propagation for Data/Bundles --- docs/release-notes.md | 2 ++ src/SMAPI/Framework/SCore.cs | 37 ------------------------------- src/SMAPI/Metadata/CoreAssetPropagator.cs | 28 ----------------------- 3 files changed, 2 insertions(+), 65 deletions(-) (limited to 'src/SMAPI/Metadata') diff --git a/docs/release-notes.md b/docs/release-notes.md index 3779bcac..65e6a489 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -11,6 +11,8 @@ * For mod authors: * Added `PathUtilities.NormalizeAssetName` and `PathUtilities.PreferredAssetSeparator` to prepare for the upcoming Stardew Valley 1.5.5. + * **SMAPI no longer propagates changes to `Data/Bundles`.** + _You can still load/edit the asset like usual, but if bundles have already been loaded for a save, SMAPI will no longer dynamically update the in-game bundles to reflect the changes. Unfortunately this caused bundle corruption when playing in non-English._ * Fixed content packs created via `helper.ContentPacks.CreateFake` or `CreateTemporary` not initializing translations correctly. * For console commands: diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index ce5a701d..5913430e 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -787,9 +787,6 @@ namespace StardewModdingAPI.Framework this.Monitor.Log(context); - // apply save fixes - this.ApplySaveFixes(); - // raise events this.OnLoadStageChanged(LoadStage.Ready); events.SaveLoaded.RaiseEmpty(); @@ -1107,40 +1104,6 @@ namespace StardewModdingAPI.Framework this.EventManager.ReturnedToTitle.RaiseEmpty(); } - /// Apply fixes to the save after it's loaded. - private void ApplySaveFixes() - { - // get last SMAPI version used with this save - const string migrationKey = "Pathoschild.SMAPI/api-version"; - if (!Game1.CustomData.TryGetValue(migrationKey, out string rawVersion) || !SemanticVersion.TryParse(rawVersion, out ISemanticVersion lastVersion)) - lastVersion = new SemanticVersion(3, 8, 0); - - // fix bundle corruption in SMAPI 3.8.0 - // For non-English players who created a new save in SMAPI 3.8.0, bundle data was - // incorrectly translated which caused the code to crash whenever the game tried to - // read it. - if (lastVersion.IsOlderThan(new SemanticVersion(3, 8, 1)) && Game1.netWorldState?.Value?.BundleData != null) - { - var oldData = new Dictionary(Game1.netWorldState.Value.BundleData); - - try - { - Game1.applySaveFix(SaveGame.SaveFixes.FixBotchedBundleData); - bool changed = Game1.netWorldState.Value.BundleData.Any(p => oldData.TryGetValue(p.Key, out string oldValue) && oldValue != p.Value); - if (changed) - this.Monitor.Log("Found broken community center bundles and fixed them automatically.", LogLevel.Info); - } - catch (Exception ex) - { - this.Monitor.Log("Failed to verify community center data.", LogLevel.Error); // should never happen - this.Monitor.Log($"Technical details: {ex}"); - } - } - - // update last run - Game1.CustomData[migrationKey] = Constants.ApiVersion.ToString(); - } - /// A callback invoked before runs. protected void OnNewDayAfterFade() { diff --git a/src/SMAPI/Metadata/CoreAssetPropagator.cs b/src/SMAPI/Metadata/CoreAssetPropagator.cs index a8686ca4..708673c3 100644 --- a/src/SMAPI/Metadata/CoreAssetPropagator.cs +++ b/src/SMAPI/Metadata/CoreAssetPropagator.cs @@ -4,7 +4,6 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using Microsoft.Xna.Framework.Graphics; -using Netcode; using StardewModdingAPI.Framework.ContentManagers; using StardewModdingAPI.Framework.Reflection; using StardewModdingAPI.Internal; @@ -16,7 +15,6 @@ using StardewValley.Characters; using StardewValley.GameData.Movies; using StardewValley.Locations; using StardewValley.Menus; -using StardewValley.Network; using StardewValley.Objects; using StardewValley.Projectiles; using StardewValley.TerrainFeatures; @@ -283,32 +281,6 @@ namespace StardewModdingAPI.Metadata Game1.bigCraftablesInformation = content.Load>(key); return true; - case "data\\bundles": // NetWorldState constructor - if (Context.IsMainPlayer && Game1.netWorldState != null) - { - var bundles = this.Reflection.GetField(Game1.netWorldState.Value, "bundles").GetValue(); - var rewards = this.Reflection.GetField>(Game1.netWorldState.Value, "bundleRewards").GetValue(); - foreach (var pair in content.Load>(key)) - { - int bundleKey = int.Parse(pair.Key.Split('/')[1]); - int rewardsCount = pair.Value.Split('/')[2].Split(' ').Length; - - // add bundles - if (!bundles.TryGetValue(bundleKey, out bool[] values) || values.Length < rewardsCount) - { - values ??= new bool[0]; - - bundles.Remove(bundleKey); - bundles[bundleKey] = values.Concat(Enumerable.Repeat(false, rewardsCount - values.Length)).ToArray(); - } - - // add bundle rewards - if (!rewards.ContainsKey(bundleKey)) - rewards[bundleKey] = false; - } - } - break; - case "data\\clothinginformation": // Game1.LoadContent Game1.clothingInformation = content.Load>(key); return true; -- cgit