From cda99844b26ad6494f2bec03180d18275eb2309b Mon Sep 17 00:00:00 2001 From: zznty <94796179+zznty@users.noreply.github.com> Date: Sun, 3 Nov 2024 00:07:50 +0700 Subject: [PATCH] Add XmlSerializerPatch (Prevents Exception when using collectable type in generic for xml serialization) --- CringeLauncher/Patches/XmlSerializerPatch.cs | 37 ++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 CringeLauncher/Patches/XmlSerializerPatch.cs diff --git a/CringeLauncher/Patches/XmlSerializerPatch.cs b/CringeLauncher/Patches/XmlSerializerPatch.cs new file mode 100644 index 0000000..0a98475 --- /dev/null +++ b/CringeLauncher/Patches/XmlSerializerPatch.cs @@ -0,0 +1,37 @@ +using HarmonyLib; +using System.Reflection; +using System.Xml.Serialization; + +namespace CringeLauncher.Patches; + +[HarmonyPatch] +internal static class XmlSerializerPatch +{ + [HarmonyTargetMethod] + private static MethodInfo TargetMethod() => AccessTools.Method( + typeof(XmlSerializer).Assembly.GetType("System.Xml.Serialization.TempAssembly"), + "GenerateRefEmitAssembly"); + + [HarmonyTranspiler] + private static List Transpiler(IEnumerable instructions) + { + var list = instructions.ToList(); + var method = AccessTools.PropertyGetter(typeof(Type), nameof(Type.Assembly)); + var index = list.FindIndex(x => x.Calls(method)); + list[index] = CodeInstruction.Call(typeof(XmlSerializerPatch), nameof(GetCorrectAssembly)); + return list; + } + + private static Assembly GetCorrectAssembly(Type type) + { + if (type.Assembly.IsCollectible || type.GenericTypeArguments is not { } genericArgs || genericArgs.Length == 0) + return type.Assembly; + + foreach (var assembly in genericArgs.Select(x => x.Assembly)) + { + if (assembly.IsCollectible) + return assembly; + } + return type.Assembly; + } +}