Decompiled source of IDGAFMan v1.0.3

BepInEx/plugins/IDGAFMan/IDGAFMan.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using CI.QuickSave;
using CI.QuickSave.Core.Storage;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using NativePatches;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("IDGAFMan")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.3.0")]
[assembly: AssemblyInformationalVersion("1.0.3")]
[assembly: AssemblyProduct("IDGAFMan")]
[assembly: AssemblyTitle("IDGAFMan")]
[assembly: AssemblyVersion("1.0.3.0")]
namespace IDGAFMan
{
	[BepInPlugin("idgafman.gunmancontracts", "IDGAFMan", "1.0.3")]
	[BepInProcess("GunmanContracts.exe")]
	public sealed class Plugin : BasePlugin
	{
		internal static ManualLogSource Logger;

		public override void Load()
		{
			Logger = ((BasePlugin)this).Log;
			Start();
		}

		public override bool Unload()
		{
			return false;
		}

		private static void Start()
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Expected O, but got Unknown
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			bool flag2 = default(bool);
			try
			{
				using Process process = Process.GetCurrentProcess();
				ProcessModule processModule = ((IEnumerable)process.Modules).Cast<ProcessModule>().Single((ProcessModule m) => string.Equals(m.ModuleName, "GameAssembly.dll", StringComparison.OrdinalIgnoreCase));
				bool flag = PatchEngine.Apply(typeof(Plugin).Assembly.GetManifestResourceStream("IDGAFMan.patches.json"), processModule.BaseAddress);
				Logger.LogInfo((object)(flag ? "IDGAFMan enabled: cheats always available, cheat-compatible personal scores, every score deduction zeroed, all-weapon bonus. Steam leaderboard uploads blocked." : "IDGAFMan patches already present (for example, standalone installation). No duplicate changes applied."));
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Logger;
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(29, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("IDGAFMan could not activate: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				logger.LogError(val);
			}
			try
			{
				Harmony val2 = new Harmony("idgafman.gunmancontracts");
				val2.PatchAll(typeof(ResultsScreen));
				val2.PatchAll(typeof(TextOverrides));
				val2.PatchAll(typeof(SaveRedirect.Reader));
				val2.PatchAll(typeof(SaveRedirect.Writer));
				val2.PatchAll(typeof(SaveRedirect.Disk));
			}
			catch (Exception ex2)
			{
				ManualLogSource logger2 = Logger;
				BepInExWarningLogInterpolatedStringHandler val3 = new BepInExWarningLogInterpolatedStringHandler(44, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("IDGAFMan results-screen tweaks unavailable: ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<Exception>(ex2);
				}
				logger2.LogWarning(val3);
			}
		}
	}
	[HarmonyPatch(typeof(ANBHighscoreDisplay), "UpdateHighscoreDisplay")]
	internal static class ResultsScreen
	{
		private const string PistolBonusLabel = "Special Bonus, just for you <3";

		private static bool failed;

		private static bool described;

		private static (GameObject Row, TextMeshProUGUI Value, TextMeshProUGUI Points)[] Deductions(ANBHighscoreDisplay display)
		{
			return new(GameObject, TextMeshProUGUI, TextMeshProUGUI)[4]
			{
				(display.civilianCasultiesElement, display.displayCivilianCasulties, display.displayCivilianCasultiesPts),
				(display.hitsTakenElement, display.displayHitstaken, display.displayHitstakenPts),
				(display.checkpointsUsedElement, display.displayCheckpointsUsed, display.displayCheckpointsUsedPts),
				(display.slomoTimeElement, display.displaySlomotime, display.displaySlomotimePts)
			};
		}

		private static void Postfix(ANBHighscoreDisplay __instance)
		{
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Expected O, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			if (failed)
			{
				return;
			}
			try
			{
				Describe(__instance);
				TextMeshProUGUI displayNoDamgebonus = __instance.displayNoDamgebonus;
				Color valueColor = (((Object)(object)displayNoDamgebonus != (Object)null) ? ((Graphic)displayNoDamgebonus).color : Color.white);
				(GameObject, TextMeshProUGUI, TextMeshProUGUI)[] array = Deductions(__instance);
				for (int i = 0; i < array.Length; i++)
				{
					var (row, value, points) = array[i];
					Restyle(row, (TMP_Text)(object)value, (TMP_Text)(object)points, valueColor);
				}
				TMP_Text val = Others(__instance.pistolOnlyElement, (TMP_Text)__instance.displayPistolOnlybonus).FirstOrDefault((Func<TMP_Text, bool>)((TMP_Text text) => !IsUnit(text.text)));
				if ((Object)(object)val != (Object)null && val.text != "Special Bonus, just for you <3")
				{
					ANBLanguageText component = ((Component)val).GetComponent<ANBLanguageText>();
					if ((Object)(object)component != (Object)null)
					{
						((Behaviour)component).enabled = false;
					}
					val.richText = false;
					val.text = "Special Bonus, just for you <3";
				}
			}
			catch (Exception ex)
			{
				failed = true;
				ManualLogSource logger = Plugin.Logger;
				if (logger != null)
				{
					bool flag = default(bool);
					BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(40, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("IDGAFMan results-screen tweaks stopped: ");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex);
					}
					logger.LogWarning(val2);
				}
			}
		}

		private static void Restyle(GameObject row, TMP_Text value, TMP_Text points, Color valueColor)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)value == (Object)null || (Object)(object)points == (Object)null)
			{
				return;
			}
			((Component)value).gameObject.SetActive(false);
			points.text = value.text;
			((Graphic)points).color = valueColor;
			foreach (TMP_Text item in Others(row, value, points))
			{
				if (IsUnit(item.text))
				{
					((Component)item).gameObject.SetActive(false);
				}
				else
				{
					((Graphic)item).color = Color.white;
				}
			}
		}

		private static IEnumerable<TMP_Text> Others(GameObject row, params TMP_Text[] known)
		{
			if (!((Object)(object)row == (Object)null))
			{
				return ((IEnumerable<TMP_Text>)row.GetComponentsInChildren<TMP_Text>(true)).Where((TMP_Text text) => known.All((TMP_Text other) => (Object)(object)other == (Object)null || ((Il2CppObjectBase)other).Pointer != ((Il2CppObjectBase)text).Pointer));
			}
			return Enumerable.Empty<TMP_Text>();
		}

		private static bool IsUnit(string text)
		{
			switch (text?.Trim().ToLowerInvariant())
			{
			case "pts":
			case "pkt":
			case "pt":
				return true;
			default:
				return false;
			}
		}

		private static void Describe(ANBHighscoreDisplay display)
		{
			if (described)
			{
				return;
			}
			described = true;
			foreach (GameObject item in (from entry in Deductions(display)
				select entry.Row).Append(display.pistolOnlyElement))
			{
				if (!((Object)(object)item != (Object)null))
				{
					continue;
				}
				ManualLogSource logger = Plugin.Logger;
				if (logger != null)
				{
					logger.LogInfo((object)("IDGAFMan row '" + ((Object)item).name + "': " + string.Join(", ", ((IEnumerable<TMP_Text>)item.GetComponentsInChildren<TMP_Text>(true)).Select((TMP_Text text) => ((Object)text).name + "='" + text.text + "'"))));
				}
			}
		}
	}
	internal static class SaveRedirect
	{
		[HarmonyPatch(typeof(QuickSaveReader), "Create", new Type[] { typeof(string) })]
		internal static class Reader
		{
			private static void Prefix(ref string root)
			{
				Redirect(ref root);
			}
		}

		[HarmonyPatch(typeof(QuickSaveWriter), "Create", new Type[] { typeof(string) })]
		internal static class Writer
		{
			private static void Prefix(ref string root)
			{
				Redirect(ref root);
			}
		}

		[HarmonyPatch(typeof(FileAccess))]
		internal static class Disk
		{
			[HarmonyPrefix]
			[HarmonyPatch("LoadString")]
			private static void Load(ref string filename)
			{
				Redirect(ref filename);
			}

			[HarmonyPrefix]
			[HarmonyPatch("SaveString")]
			private static void Save(ref string filename, ref string value)
			{
				bool num = filename == "SaveData_Highscores" || filename == "SaveData_Highscores_IDGAFMan";
				Redirect(ref filename);
				if (num)
				{
					value = ScoreVault.Protect(value);
				}
			}

			[HarmonyPostfix]
			[HarmonyPatch("LoadString")]
			private static void Loaded(string filename, ref string __result)
			{
				if (filename == "SaveData_Highscores_IDGAFMan")
				{
					__result = ScoreVault.Unprotect(__result);
				}
			}

			[HarmonyPrefix]
			[HarmonyPatch("Exists")]
			private static void Exists(ref string filename)
			{
				Redirect(ref filename);
			}

			[HarmonyPrefix]
			[HarmonyPatch("Delete")]
			private static void Delete(ref string filename)
			{
				Redirect(ref filename);
			}

			[HarmonyPrefix]
			[HarmonyPatch("getBasePath")]
			private static void BasePath(ref string filename)
			{
				Redirect(ref filename);
			}
		}

		private const string Stock = "SaveData_Highscores";

		private const string Modded = "SaveData_Highscores_IDGAFMan";

		private static bool logged;

		private static void Redirect(ref string name)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			if (name != "SaveData_Highscores")
			{
				return;
			}
			name = "SaveData_Highscores_IDGAFMan";
			if (logged)
			{
				return;
			}
			logged = true;
			ManualLogSource logger = Plugin.Logger;
			if (logger != null)
			{
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(73, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("IDGAFMan: high scores read and written as ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("SaveData_Highscores_IDGAFMan");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".json; ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("SaveData_Highscores");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".json is left untouched.");
				}
				logger.LogInfo(val);
			}
		}
	}
	internal static class ScoreVault
	{
		private const string Header = "IDGAFMan1:";

		private static readonly byte[] Key = SHA256.HashData(Encoding.UTF8.GetBytes("IDGAFMan/GunmanContracts/local-scores/v1"));

		internal static string Protect(string plain)
		{
			if (string.IsNullOrEmpty(plain))
			{
				return plain;
			}
			using Aes aes = Aes.Create();
			aes.Key = Key;
			aes.GenerateIV();
			using ICryptoTransform cryptoTransform = aes.CreateEncryptor();
			byte[] bytes = Encoding.UTF8.GetBytes(plain);
			byte[] array = cryptoTransform.TransformFinalBlock(bytes, 0, bytes.Length);
			byte[] array2 = new byte[aes.IV.Length + array.Length];
			aes.IV.CopyTo(array2, 0);
			array.CopyTo(array2, aes.IV.Length);
			return "IDGAFMan1:" + Convert.ToBase64String(array2);
		}

		internal static string Unprotect(string stored)
		{
			if (string.IsNullOrEmpty(stored) || !stored.StartsWith("IDGAFMan1:", StringComparison.Ordinal))
			{
				return stored;
			}
			try
			{
				byte[] array = Convert.FromBase64String(stored.Substring("IDGAFMan1:".Length));
				using Aes aes = Aes.Create();
				aes.Key = Key;
				aes.IV = array[..16];
				using ICryptoTransform cryptoTransform = aes.CreateDecryptor();
				return Encoding.UTF8.GetString(cryptoTransform.TransformFinalBlock(array, 16, array.Length - 16));
			}
			catch (Exception)
			{
				return "";
			}
		}
	}
	[HarmonyPatch(typeof(ANBLanguageText), "SetText")]
	internal static class TextOverrides
	{
		private static readonly Dictionary<string, string> Replacements = new Dictionary<string, string>
		{
			["cheats_unlock"] = "Even though you can gain score and achievements, your score won't be published to steam leaderboards with this mod.",
			["hs_nodmage"] = "Bonus for being Sexy"
		};

		private static readonly HashSet<string> logged = new HashSet<string>();

		private static bool failed;

		private static void Postfix(ANBLanguageText __instance)
		{
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			if (failed)
			{
				return;
			}
			bool flag = default(bool);
			try
			{
				string textID = __instance.TextID;
				if (textID == null || !Replacements.TryGetValue(textID, out var value))
				{
					return;
				}
				TextMeshProUGUI txtField = __instance.txtField;
				if ((Object)(object)txtField == (Object)null)
				{
					return;
				}
				if (logged.Add(textID))
				{
					ManualLogSource logger = Plugin.Logger;
					if (logger != null)
					{
						BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(34, 3, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("IDGAFMan rewrote '");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(textID);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' on '");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(((Object)txtField).name);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("', was '");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(((TMP_Text)txtField).text);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("'.");
						}
						logger.LogInfo(val);
					}
				}
				((TMP_Text)txtField).text = value;
			}
			catch (Exception ex)
			{
				failed = true;
				ManualLogSource logger = Plugin.Logger;
				if (logger != null)
				{
					BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(33, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("IDGAFMan text overrides stopped: ");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex);
					}
					logger.LogWarning(val2);
				}
			}
		}
	}
}
namespace NativePatches
{
	internal static class PatchEngine
	{
		internal sealed class Manifest
		{
			public Patch[] Patches { get; set; } = Array.Empty<Patch>();
		}

		internal sealed class Patch
		{
			public string Name { get; set; } = "";

			public string Namespace { get; set; } = "";

			public string Class { get; set; } = "";

			public string Method { get; set; } = "";

			public int Args { get; set; }

			public string Find { get; set; } = "";

			public string Replace { get; set; } = "";
		}

		internal static bool Apply(Stream manifest, IntPtr module)
		{
			return Apply(manifest, module, delegate(Patch p)
			{
				IntPtr intPtr = IL2CPP.il2cpp_class_get_method_from_name(Il2CppClass(p), p.Method, p.Args);
				return (!(intPtr == IntPtr.Zero)) ? Marshal.ReadIntPtr(intPtr) : IntPtr.Zero;
			}, delegate(Patch p, string name)
			{
				IntPtr il2CppField = IL2CPP.GetIl2CppField(Il2CppClass(p), name);
				if (il2CppField == IntPtr.Zero)
				{
					throw new InvalidOperationException($"Field {p.Class}.{name} not found.");
				}
				return checked((int)IL2CPP.il2cpp_field_get_offset(il2CppField));
			});
		}

		private static IntPtr Il2CppClass(Patch p)
		{
			UIntPtr size;
			IntPtr ptr = il2cpp_domain_get_assemblies(IL2CPP.il2cpp_domain_get(), out size);
			for (int i = 0; i < (int)(uint)size; i++)
			{
				IntPtr intPtr = IL2CPP.il2cpp_class_from_name(IL2CPP.il2cpp_assembly_get_image(Marshal.ReadIntPtr(ptr, i * IntPtr.Size)), p.Namespace, p.Class);
				if (intPtr != IntPtr.Zero)
				{
					return intPtr;
				}
			}
			throw new InvalidOperationException($"Class {p.Namespace}.{p.Class} not found.");
		}

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl)]
		private static extern IntPtr il2cpp_domain_get_assemblies(IntPtr domain, out UIntPtr size);

		internal static bool Apply(Stream manifest, IntPtr module, Func<Patch, IntPtr> resolveMethod, Func<Patch, string, int> resolveField)
		{
			if (!OperatingSystem.IsWindows() || IntPtr.Size != 8)
			{
				throw new PlatformNotSupportedException("Native patches require Windows x64.");
			}
			Patch[] patches = JsonSerializer.Deserialize<Manifest>(manifest, new JsonSerializerOptions
			{
				PropertyNameCaseInsensitive = true
			}).Patches;
			int[] unwind = UnwindTable(module);
			(IntPtr, byte[], byte[], bool)[] array = patches.Select((Patch p) => Locate(p, module, unwind, resolveMethod, resolveField)).ToArray();
			if (array.All(((IntPtr Address, byte[] Before, byte[] After, bool Applied) c) => c.Applied))
			{
				return false;
			}
			if (array.Any(((IntPtr Address, byte[] Before, byte[] After, bool Applied) c) => c.Applied))
			{
				throw new InvalidOperationException("Only some patches are already present. No memory changed; check other mods.");
			}
			int num = -1;
			try
			{
				for (int num2 = 0; num2 < array.Length; num2++)
				{
					num = num2;
					Write(array[num2].Item1, array[num2].Item3);
				}
			}
			catch (Exception item)
			{
				List<Exception> list = new List<Exception> { item };
				for (int num3 = num; num3 >= 0; num3--)
				{
					try
					{
						Write(array[num3].Item1, array[num3].Item2);
					}
					catch (Exception item2)
					{
						list.Add(item2);
					}
				}
				throw new AggregateException("Patch failed; original memory restoration was attempted for every changed site. Restart the game before playing.", list);
			}
			return true;
		}

		private static (IntPtr Address, byte[] Before, byte[] After, bool Applied) Locate(Patch p, IntPtr module, int[] unwind, Func<Patch, IntPtr> resolveMethod, Func<Patch, string, int> resolveField)
		{
			IntPtr intPtr = resolveMethod(p);
			if (intPtr == IntPtr.Zero)
			{
				throw new InvalidOperationException($"{p.Name}: method {p.Class}.{p.Method} not found.");
			}
			byte[] array = new byte[FunctionLength(module, unwind, intPtr)];
			Marshal.Copy(intPtr, array, 0, array.Length);
			bool anchored = p.Find.StartsWith('^');
			byte?[] array2 = Parse(p.Find.TrimStart('^'));
			string text = p.Replace;
			foreach (Match item in Regex.Matches(p.Replace, "<(\\w+)>"))
			{
				text = text.Replace(item.Value, Convert.ToHexString(BitConverter.GetBytes(resolveField(p, item.Groups[1].Value))));
			}
			byte?[] replace = Parse(text);
			if (array2.Length == 0 || replace.Length != array2.Length)
			{
				throw new InvalidOperationException("Invalid patch: " + p.Name);
			}
			List<int> list = Matches(array, array2, anchored);
			List<int> list2 = Matches(array, array2.Zip(replace, (byte? f, byte? r) => r ?? f).ToArray(), anchored);
			bool flag = list2.Count == 1;
			if (!flag && (list.Count != 1 || list2.Count != 0))
			{
				throw new InvalidOperationException($"{p.Name}: signature matched {list.Count} times in {p.Class}.{p.Method}, " + "so the game changed this code or another mod patched it. No memory changed.");
			}
			int num = (flag ? list2[0] : list[0]);
			byte[] subArray = array[num..(num + array2.Length)];
			return (Address: intPtr + num, Before: subArray, After: subArray.Select((byte b, int i) => replace[i] ?? b).ToArray(), Applied: flag);
		}

		private static byte?[] Parse(string hex)
		{
			if (hex.Length % 2 != 0)
			{
				throw new FormatException("Odd-length pattern: " + hex);
			}
			byte?[] array = new byte?[hex.Length / 2];
			for (int i = 0; i < array.Length; i++)
			{
				string text = hex.Substring(i * 2, 2);
				array[i] = ((text == "??") ? ((byte?)null) : new byte?(byte.Parse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture)));
			}
			return array;
		}

		private static List<int> Matches(byte[] body, byte?[] pattern, bool anchored)
		{
			List<int> list = new List<int>();
			int num = (anchored ? Math.Min(0, body.Length - pattern.Length) : (body.Length - pattern.Length));
			for (int i = 0; i <= num; i++)
			{
				int j;
				for (j = 0; j < pattern.Length && (!pattern[j].HasValue || pattern[j] == body[i + j]); j++)
				{
				}
				if (j == pattern.Length)
				{
					list.Add(i);
				}
			}
			return list;
		}

		private static int[] UnwindTable(IntPtr module)
		{
			int num = Marshal.ReadInt32(module, 60);
			int[] array = new int[Marshal.ReadInt32(module, num + 164) / 4];
			Marshal.Copy(module + Marshal.ReadInt32(module, num + 160), array, 0, array.Length);
			return array;
		}

		private static int FunctionLength(IntPtr module, int[] table, IntPtr code)
		{
			int num = checked((int)(code.ToInt64() - module.ToInt64()));
			int i;
			for (i = 0; i < table.Length && table[i] != num; i += 3)
			{
			}
			if (i >= table.Length)
			{
				throw new InvalidOperationException($"No unwind entry at RVA 0x{num:X}: a leaf function or code outside the game DLL.");
			}
			int num2 = table[i + 1];
			for (i += 3; i < table.Length && table[i] == num2 && (Marshal.ReadByte(module, table[i + 2] & -2) & 0x20) != 0; i += 3)
			{
				num2 = table[i + 1];
			}
			return num2 - num;
		}

		private static void Write(IntPtr address, byte[] bytes)
		{
			if (!VirtualProtect(address, (UIntPtr)(ulong)bytes.Length, 64u, out var oldProtection))
			{
				throw new Win32Exception(Marshal.GetLastWin32Error());
			}
			bool flag;
			try
			{
				Marshal.Copy(bytes, 0, address, bytes.Length);
				if (!FlushInstructionCache(GetCurrentProcess(), address, (UIntPtr)(ulong)bytes.Length))
				{
					throw new Win32Exception(Marshal.GetLastWin32Error());
				}
				byte[] array = new byte[bytes.Length];
				Marshal.Copy(address, array, 0, array.Length);
				if (!array.SequenceEqual(bytes))
				{
					throw new IOException("Memory patch verification failed.");
				}
			}
			finally
			{
				flag = VirtualProtect(address, (UIntPtr)(ulong)bytes.Length, oldProtection, out var _);
			}
			if (!flag)
			{
				throw new Win32Exception(Marshal.GetLastWin32Error());
			}
		}

		[DllImport("kernel32", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private static extern bool VirtualProtect(IntPtr address, UIntPtr size, uint protection, out uint oldProtection);

		[DllImport("kernel32", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private static extern bool FlushInstructionCache(IntPtr process, IntPtr address, UIntPtr size);

		[DllImport("kernel32")]
		private static extern IntPtr GetCurrentProcess();
	}
}