Decompiled source of FeelingBetterAlready v1.0.2

BepInEx/plugins/FeelingBetterAlready/FeelingBetterAlready.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.Text.Json;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Runtime;
using NativePatches;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("FeelingBetterAlready")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2")]
[assembly: AssemblyProduct("FeelingBetterAlready")]
[assembly: AssemblyTitle("FeelingBetterAlready")]
[assembly: AssemblyVersion("1.0.2.0")]
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();
	}
}
namespace FeelingBetterAlready
{
	[HarmonyPatch(typeof(ANBGameLogic), "Update")]
	internal static class KeepRegenerating
	{
		private static bool failed;

		private static void Prefix(ANBGameLogic __instance)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			if (failed)
			{
				return;
			}
			try
			{
				if (__instance.playerHitPoints <= 0f)
				{
					__instance.regainHealthTimeCurrent = 0f;
				}
			}
			catch (Exception ex)
			{
				failed = true;
				ManualLogSource logger = Plugin.Logger;
				if (logger != null)
				{
					bool flag = default(bool);
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(49, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("FeelingBetterAlready regeneration timer stopped: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
					}
					logger.LogWarning(val);
				}
			}
		}

		private static void Postfix(ANBGameLogic __instance)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			if (failed)
			{
				return;
			}
			try
			{
				if (!(__instance.regainHealthTimeCurrent > 0f))
				{
					float playerHitPoints = __instance.playerHitPoints;
					if (!(playerHitPoints <= 0f) && !(playerHitPoints >= __instance.playerHitPointsMaxRecharge))
					{
						__instance.StartRegainHealth();
					}
				}
			}
			catch (Exception ex)
			{
				failed = true;
				ManualLogSource logger = Plugin.Logger;
				if (logger != null)
				{
					bool flag = default(bool);
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(49, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("FeelingBetterAlready regeneration timer stopped: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
					}
					logger.LogWarning(val);
				}
			}
		}
	}
	[BepInPlugin("feelingbetteralready.gunmancontracts", "FeelingBetterAlready", "1.0.2")]
	[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_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Expected O, but got Unknown
			//IL_00bb: 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("FeelingBetterAlready.patches.json"), processModule.BaseAddress);
				Logger.LogInfo((object)(flag ? "FeelingBetterAlready enabled: health regenerates up to the difficulty's own maximum instead of stopping at 2 HP." : "FeelingBetterAlready patches already present. No duplicate changes applied."));
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Logger;
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(41, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("FeelingBetterAlready could not activate: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				logger.LogError(val);
			}
			try
			{
				new Harmony("feelingbetteralready.gunmancontracts").PatchAll(typeof(KeepRegenerating));
			}
			catch (Exception ex2)
			{
				ManualLogSource logger2 = Logger;
				BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(63, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("FeelingBetterAlready could not restart the regeneration timer: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex2);
				}
				logger2.LogWarning(val2);
			}
		}
	}
}