mirror of
https://github.com/BepInEx/BepInEx.git
synced 2026-10-19 15:51:45 +00:00
Merge remote-tracking branch 'kasuromi/master' into feature-doorstop-4
# Conflicts: # BepInEx.IL2CPP/BepInEx.IL2CPP.csproj # BepInEx.IL2CPP/Hook/FastNativeDetour.cs # BepInEx.IL2CPP/Hook/IL2CPPDetourMethodPatcher.cs # BepInEx.IL2CPP/IL2CPPChainloader.cs # BepInEx.IL2CPP/ProxyAssemblyGenerator.cs
This commit is contained in:
commit
5a84aed435
22 files changed
+447
-530
No files matched your search
@@ -21,9 +21,9 @@
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.2" PrivateAssets="All"/>
|
||||
<PackageReference Include="HarmonyX" Version="2.9.0"/>
|
||||
<PackageReference Include="MonoMod.Utils" Version="22.1.29.1"/>
|
||||
<PackageReference Include="SemanticVersioning" Version="2.0.0"/>
|
||||
<PackageReference Include="HarmonyX" Version="2.10.0"/>
|
||||
<PackageReference Include="MonoMod.Utils" Version="22.3.23.4"/>
|
||||
<PackageReference Include="SemanticVersioning" Version="2.0.2"/>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Remove="Contract\IPlugin.cs"/>
|
||||
|
||||
@@ -64,7 +64,7 @@ public abstract class ConfigEntryBase
|
||||
/// <summary>
|
||||
/// Types of defaultValue and definition.AcceptableValues have to be the same as settingType.
|
||||
/// </summary>
|
||||
internal ConfigEntryBase(ConfigFile configFile,
|
||||
internal protected ConfigEntryBase(ConfigFile configFile,
|
||||
ConfigDefinition definition,
|
||||
Type settingType,
|
||||
object defaultValue,
|
||||
|
||||
@@ -1,247 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using BepInEx.IL2CPP.Hook.Allocator;
|
||||
using BepInEx.Logging;
|
||||
using Iced.Intel;
|
||||
using MonoMod.RuntimeDetour;
|
||||
|
||||
namespace BepInEx.IL2CPP;
|
||||
|
||||
public static class DetourGenerator
|
||||
{
|
||||
private static ManualLogSource logger = Logger.CreateLogSource("DetourGen");
|
||||
|
||||
public static void Disassemble(ManualLogSource logSource, IntPtr memoryPtr, int size)
|
||||
{
|
||||
var data = new byte[size];
|
||||
Marshal.Copy(memoryPtr, data, 0, size);
|
||||
|
||||
var formatter = new NasmFormatter();
|
||||
var output = new StringOutput();
|
||||
var codeReader = new ByteArrayCodeReader(data);
|
||||
var decoder = Decoder.Create(64, codeReader);
|
||||
decoder.IP = (ulong)memoryPtr.ToInt64();
|
||||
while (codeReader.CanReadByte)
|
||||
{
|
||||
decoder.Decode(out var instr);
|
||||
formatter.Format(instr, output);
|
||||
logSource.LogDebug($"{instr.IP:X16} {output.ToStringAndReset()}");
|
||||
|
||||
if (instr.Code == Code.Jmp_rm64 && instr.Immediate32 == 0
|
||||
) // && instr.IsIPRelativeMemoryOperand && instr.IPRelativeMemoryAddress = 6
|
||||
{
|
||||
var address = new byte[8];
|
||||
|
||||
for (var i = 0; i < 8; i++)
|
||||
address[i] = (byte)codeReader.ReadByte();
|
||||
|
||||
logSource.LogDebug($"{instr.IP + (ulong)instr.Length:X16} db 0x{BitConverter.ToUInt64(address, 0):X16}");
|
||||
decoder.IP += 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static int GetDetourLength(Architecture arch) => arch == Architecture.X64 ? 14 : 5;
|
||||
|
||||
/// <summary>
|
||||
/// Writes a detour on <see cref="functionPtr" /> to redirect to <see cref="detourPtr" />.
|
||||
/// </summary>
|
||||
/// <param name="functionPtr">The pointer to the function to apply the detour to.</param>
|
||||
/// <param name="detourPtr">The pointer to the function to redirect to.</param>
|
||||
/// <param name="architecture">The architecture of the current platform.</param>
|
||||
/// <param name="minimumLength">
|
||||
/// The minimum amount of length that the detour should consume. If the generated redirect is
|
||||
/// smaller than this, the remaining space is padded with NOPs.
|
||||
/// </param>
|
||||
public static void ApplyDetour(IntPtr functionPtr,
|
||||
IntPtr detourPtr,
|
||||
Architecture architecture,
|
||||
int minimumLength = 0)
|
||||
{
|
||||
var jmp = GenerateAbsoluteJump(detourPtr, functionPtr, architecture);
|
||||
|
||||
Marshal.Copy(jmp, 0, functionPtr, jmp.Length);
|
||||
|
||||
// Fill remaining space with NOP instructions
|
||||
for (var i = jmp.Length; i < minimumLength; i++)
|
||||
Marshal.WriteByte(functionPtr + i, 0x90);
|
||||
}
|
||||
|
||||
public static IntPtr CreateTrampolineFromFunction(IntPtr originalFuncPointer,
|
||||
out int trampolineLength,
|
||||
out int jmpLength)
|
||||
{
|
||||
var instructionBuffer = new byte[32];
|
||||
Marshal.Copy(originalFuncPointer, instructionBuffer, 0, 32);
|
||||
|
||||
var trampolinePtr = PageAllocator.Instance.Allocate(originalFuncPointer);
|
||||
|
||||
DetourHelper.Native.MakeWritable(trampolinePtr, PageAllocator.PAGE_SIZE);
|
||||
|
||||
var arch = IntPtr.Size == 8 ? Architecture.X64 : Architecture.X86;
|
||||
|
||||
var minimumTrampolineLength = GetDetourLength(arch);
|
||||
|
||||
CreateTrampolineFromFunction(instructionBuffer, originalFuncPointer, trampolinePtr, minimumTrampolineLength,
|
||||
arch, out trampolineLength, out jmpLength);
|
||||
|
||||
DetourHelper.Native.MakeExecutable(originalFuncPointer, 32);
|
||||
DetourHelper.Native.MakeExecutable(trampolinePtr, PageAllocator.PAGE_SIZE);
|
||||
|
||||
return trampolinePtr;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads assembly from <see cref="functionPtr" /> (at least <see cref="minimumTrampolineLength" /> bytes), and writes
|
||||
/// it to <see cref="trampolinePtr" /> plus a jmp to continue execution.
|
||||
/// </summary>
|
||||
/// <param name="instructionBuffer">The buffer to copy assembly from.</param>
|
||||
/// <param name="functionPtr">The pointer to the function to copy assembly from.</param>
|
||||
/// <param name="trampolinePtr">The pointer to write the trampoline assembly to.</param>
|
||||
/// <param name="arch">The architecture of the current platform.</param>
|
||||
/// <param name="minimumTrampolineLength">Copies at least this many bytes of assembly from <see cref="functionPtr" />.</param>
|
||||
/// <param name="trampolineLength">Returns the total length of the trampoline, in bytes.</param>
|
||||
/// <param name="jmpLength">Returns the length of the jmp at the end of the trampoline, in bytes.</param>
|
||||
public static void CreateTrampolineFromFunction(byte[] instructionBuffer,
|
||||
IntPtr functionPtr,
|
||||
IntPtr trampolinePtr,
|
||||
int minimumTrampolineLength,
|
||||
Architecture arch,
|
||||
out int trampolineLength,
|
||||
out int jmpLength)
|
||||
{
|
||||
// Decode original function up until we go past the needed bytes to write the jump to patchedFunctionPtr
|
||||
|
||||
var codeReader = new ByteArrayCodeReader(instructionBuffer);
|
||||
var decoder = Decoder.Create(arch == Architecture.X64 ? 64 : 32, codeReader);
|
||||
decoder.IP = (ulong)functionPtr.ToInt64();
|
||||
|
||||
uint totalBytes = 0;
|
||||
var origInstructions = new InstructionList();
|
||||
var readOverflowArea = false;
|
||||
while (codeReader.CanReadByte)
|
||||
{
|
||||
decoder.Decode(out var instr);
|
||||
|
||||
// FIXME: This hack somehow fixes the issue with il2cpp_unity_install_unitytls_interface hook crash
|
||||
_ = instr.ToString();
|
||||
|
||||
if (!readOverflowArea)
|
||||
origInstructions.Add(instr);
|
||||
|
||||
totalBytes += (uint)instr.Length;
|
||||
if (instr.Code == Code.INVALID)
|
||||
throw new Exception("Found garbage");
|
||||
if (totalBytes >= minimumTrampolineLength)
|
||||
break;
|
||||
|
||||
if (readOverflowArea)
|
||||
{
|
||||
if (instr.Mnemonic != Mnemonic.Int3 && instr.Mnemonic != Mnemonic.Nop)
|
||||
throw new Exception("Function is too short to hook");
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (instr.FlowControl)
|
||||
{
|
||||
case FlowControl.Next:
|
||||
break;
|
||||
|
||||
// Interrupts are usually used for aligning
|
||||
case FlowControl.Interrupt: // eg. int n
|
||||
break;
|
||||
|
||||
// Handled by BlockEncoder in most cases
|
||||
case FlowControl.UnconditionalBranch:
|
||||
case FlowControl.IndirectBranch: // eg. jmp reg/mem
|
||||
case FlowControl.ConditionalBranch: // eg. je, jno, etc
|
||||
break;
|
||||
case FlowControl.Return: // eg. ret
|
||||
// There is a possibility of an overflow area, attempt to allocate trampoline onto it
|
||||
readOverflowArea = true;
|
||||
break;
|
||||
case FlowControl.Call: // eg. call method
|
||||
case FlowControl.IndirectCall: // eg. call reg/mem
|
||||
case FlowControl.XbeginXabortXend:
|
||||
case FlowControl.Exception: // eg. ud0
|
||||
default:
|
||||
throw new Exception("Not supported yet - " + instr.FlowControl);
|
||||
}
|
||||
}
|
||||
|
||||
if (totalBytes < minimumTrampolineLength)
|
||||
throw new Exception("Not enough bytes!");
|
||||
|
||||
if (origInstructions.Count == 0)
|
||||
throw new Exception("Not enough instructions!");
|
||||
|
||||
|
||||
ref readonly var lastInstr = ref origInstructions[^1];
|
||||
|
||||
if (lastInstr.FlowControl != FlowControl.Return)
|
||||
{
|
||||
Instruction detourInstruction;
|
||||
|
||||
if (arch == Architecture.X64)
|
||||
detourInstruction = Instruction.CreateBranch(Code.Jmp_rel32_64, lastInstr.NextIP);
|
||||
else
|
||||
detourInstruction = Instruction.CreateBranch(Code.Jmp_rel32_32, lastInstr.NextIP);
|
||||
|
||||
origInstructions.Add(detourInstruction);
|
||||
}
|
||||
|
||||
// Generate trampoline from instruction list
|
||||
var codeWriter = new CodeWriterImpl();
|
||||
var relocatedBaseAddress = (ulong)trampolinePtr;
|
||||
var block = new InstructionBlock(codeWriter, origInstructions, relocatedBaseAddress);
|
||||
|
||||
var success = BlockEncoder.TryEncode(decoder.Bitness, block, out var errorMessage, out var result);
|
||||
|
||||
if (!success) throw new Exception(errorMessage);
|
||||
|
||||
// Write generated trampoline
|
||||
var newCode = codeWriter.ToArray();
|
||||
Marshal.Copy(newCode, 0, trampolinePtr, newCode.Length);
|
||||
|
||||
jmpLength = newCode.Length - (int)totalBytes;
|
||||
trampolineLength = newCode.Length;
|
||||
}
|
||||
|
||||
public static byte[] GenerateAbsoluteJump(IntPtr targetAddress, IntPtr currentAddress, Architecture arch)
|
||||
{
|
||||
byte[] jmpBytes;
|
||||
|
||||
if (arch == Architecture.X64)
|
||||
{
|
||||
jmpBytes = new byte[]
|
||||
{
|
||||
0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, // FF25 00000000: JMP [RIP+6]
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Absolute destination address
|
||||
};
|
||||
|
||||
Array.Copy(BitConverter.GetBytes(targetAddress.ToInt64()), 0, jmpBytes, 6, 8);
|
||||
}
|
||||
else
|
||||
{
|
||||
jmpBytes = new byte[]
|
||||
{
|
||||
0xE9, // E9: JMP rel destination
|
||||
0x00, 0x00, 0x00, 0x00 // Relative destination address
|
||||
};
|
||||
|
||||
Array.Copy(BitConverter.GetBytes(targetAddress.ToInt32() - (currentAddress.ToInt32() + 5)), 0, jmpBytes,
|
||||
1, 4);
|
||||
}
|
||||
|
||||
return jmpBytes;
|
||||
}
|
||||
|
||||
|
||||
private sealed class CodeWriterImpl : CodeWriter
|
||||
{
|
||||
private readonly List<byte> allBytes = new();
|
||||
public override void WriteByte(byte value) => allBytes.Add(value);
|
||||
public byte[] ToArray() => allBytes.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using BepInEx.IL2CPP.Hook.Allocator;
|
||||
using BepInEx.Logging;
|
||||
using MonoMod.RuntimeDetour;
|
||||
using MonoMod.Utils;
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
namespace BepInEx.IL2CPP.Hook.Dobby;
|
||||
|
||||
internal class DobbyDetour : INativeDetour
|
||||
{
|
||||
private static readonly ManualLogSource logger = Logger.CreateLogSource("DobbyDetour");
|
||||
public DobbyDetour(nint originalMethodPtr, nint detourMethodPtr)
|
||||
{
|
||||
OriginalMethodPtr = originalMethodPtr;
|
||||
DetourMethodPtr = detourMethodPtr;
|
||||
}
|
||||
|
||||
public nint OriginalMethodPtr { get; protected set; }
|
||||
public nint DetourMethodPtr { get; protected set; }
|
||||
public nint TrampolinePtr { get; protected set; }
|
||||
|
||||
public bool IsValid { get; protected set; } = true;
|
||||
public bool IsApplied { get; protected set; }
|
||||
public bool IsPrepared { get; protected set; }
|
||||
protected MethodInfo TrampolineMethod { get; set; }
|
||||
|
||||
public void Apply()
|
||||
{
|
||||
if (IsApplied) return;
|
||||
|
||||
PrepareDetour();
|
||||
DobbyImports.DobbyCommit(OriginalMethodPtr);
|
||||
|
||||
logger.Log(LogLevel.Debug,
|
||||
$"Original: {OriginalMethodPtr:X}, Trampoline: {TrampolinePtr:X}, diff: {Math.Abs(OriginalMethodPtr - TrampolinePtr):X}; is within +-1GB range: {PageAllocator.IsInRelJmpRange(OriginalMethodPtr, TrampolinePtr)}");
|
||||
|
||||
IsApplied = true;
|
||||
}
|
||||
public unsafe void Undo()
|
||||
{
|
||||
if (!IsApplied && !IsPrepared) return;
|
||||
|
||||
if (NativeDetourHelper.DEBUG_DETOURS) logger.LogDebug($"Destroying detour");
|
||||
|
||||
DobbyImports.DobbyDestroy(OriginalMethodPtr);
|
||||
}
|
||||
|
||||
private unsafe void PrepareDetour()
|
||||
{
|
||||
if (IsPrepared) return;
|
||||
|
||||
if (NativeDetourHelper.DEBUG_DETOURS) logger.LogDebug($"Preparing detour from 0x{OriginalMethodPtr:X2} to 0x{DetourMethodPtr:X2}");
|
||||
|
||||
var trampolinePtr = IntPtr.Zero;
|
||||
DobbyImports.DobbyPrepare(OriginalMethodPtr, DetourMethodPtr, &trampolinePtr);
|
||||
|
||||
if (NativeDetourHelper.DEBUG_DETOURS) logger.LogDebug($"Prepared detour; Trampoline: 0x{trampolinePtr:X2}");
|
||||
|
||||
TrampolinePtr = trampolinePtr;
|
||||
IsPrepared = true;
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
if (!IsValid) return;
|
||||
Undo();
|
||||
Free();
|
||||
}
|
||||
|
||||
public void Free() => IsValid = false;
|
||||
|
||||
public MethodBase GenerateTrampoline(MethodBase signature = null)
|
||||
{
|
||||
if (TrampolineMethod == null)
|
||||
{
|
||||
PrepareDetour();
|
||||
TrampolineMethod = DetourHelper.GenerateNativeProxy(TrampolinePtr, signature);
|
||||
}
|
||||
return TrampolineMethod;
|
||||
}
|
||||
public T GenerateTrampoline<T>() where T : Delegate
|
||||
{
|
||||
if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
|
||||
throw new InvalidOperationException($"Type {typeof(T)} not a delegate type.");
|
||||
|
||||
return GenerateTrampoline(typeof(T).GetMethod("Invoke")).CreateDelegate(typeof(T)) as T;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using MonoMod.Utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace BepInEx.IL2CPP.Hook.Dobby;
|
||||
|
||||
internal static unsafe class DobbyImports
|
||||
{
|
||||
#region Delegates
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate int d_DobbyHook(IntPtr address, IntPtr replace_call, IntPtr* origin_call);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate int d_DobbyPrepare(IntPtr address, IntPtr replace_call, IntPtr* origin_call);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate int d_DobbyCommit(IntPtr address);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate int d_DobbyDestroy(IntPtr address);
|
||||
#endregion
|
||||
|
||||
[DynDllImport("dobby")]
|
||||
public static d_DobbyHook DobbyHook;
|
||||
|
||||
[DynDllImport("dobby")]
|
||||
public static d_DobbyPrepare DobbyPrepare;
|
||||
|
||||
[DynDllImport("dobby")]
|
||||
public static d_DobbyCommit DobbyCommit;
|
||||
|
||||
[DynDllImport("dobby")]
|
||||
public static d_DobbyDestroy DobbyDestroy;
|
||||
|
||||
static DobbyImports()
|
||||
{
|
||||
var dobbyImports = new Dictionary<string, List<DynDllMapping>>()
|
||||
{
|
||||
["dobby"] = new()
|
||||
{
|
||||
$"{Paths.BepInExAssemblyDirectory}/native/dobby.dll" // Windows
|
||||
}
|
||||
};
|
||||
|
||||
typeof(DobbyImports).ResolveDynDllImports(dobbyImports);
|
||||
}
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using BepInEx.IL2CPP.Hook.Allocator;
|
||||
using BepInEx.Logging;
|
||||
using MonoMod.RuntimeDetour;
|
||||
|
||||
namespace BepInEx.IL2CPP.Hook;
|
||||
|
||||
public class FastNativeDetour : IDetour
|
||||
{
|
||||
private static readonly ManualLogSource logger = Logger.CreateLogSource("FastNativeDetour");
|
||||
|
||||
|
||||
public FastNativeDetour(IntPtr originalFunctionPtr, IntPtr detourFunctionPtr)
|
||||
{
|
||||
OriginalFunctionPtr = originalFunctionPtr;
|
||||
DetourFunctionPtr = detourFunctionPtr;
|
||||
|
||||
// TODO: This may not be safe during undo if the method is smaller than 20 bytes
|
||||
BackupBytes = new byte[20];
|
||||
Marshal.Copy(originalFunctionPtr, BackupBytes, 0, 20);
|
||||
}
|
||||
|
||||
protected byte[] BackupBytes { get; set; }
|
||||
|
||||
|
||||
public IntPtr OriginalFunctionPtr { get; protected set; }
|
||||
public IntPtr DetourFunctionPtr { get; protected set; }
|
||||
|
||||
|
||||
public IntPtr TrampolinePtr { get; protected set; } = IntPtr.Zero;
|
||||
public int TrampolineSize { get; protected set; }
|
||||
protected int TrampolineJmpSize { get; set; }
|
||||
|
||||
protected MethodInfo TrampolineMethod { get; set; }
|
||||
|
||||
public bool IsValid { get; protected set; } = true;
|
||||
public bool IsApplied { get; protected set; }
|
||||
|
||||
public void Apply() => Apply(null);
|
||||
|
||||
|
||||
public void Undo()
|
||||
{
|
||||
if (!IsApplied)
|
||||
return;
|
||||
|
||||
Marshal.Copy(BackupBytes, 0, OriginalFunctionPtr, BackupBytes.Length);
|
||||
|
||||
PageAllocator.Instance.Free(TrampolinePtr);
|
||||
|
||||
TrampolinePtr = IntPtr.Zero;
|
||||
TrampolineSize = 0;
|
||||
|
||||
IsApplied = false;
|
||||
}
|
||||
|
||||
public void Free() => IsValid = false;
|
||||
|
||||
public MethodBase GenerateTrampoline(MethodBase signature = null)
|
||||
{
|
||||
if (TrampolineMethod == null)
|
||||
{
|
||||
// Generate trampoline without applying the detour
|
||||
GenerateTrampolineInner(out _, out _);
|
||||
|
||||
if (TrampolinePtr == IntPtr.Zero)
|
||||
throw new InvalidOperationException("Trampoline pointer is not available");
|
||||
|
||||
TrampolineMethod = DetourHelper.GenerateNativeProxy(TrampolinePtr, signature);
|
||||
}
|
||||
|
||||
return TrampolineMethod;
|
||||
}
|
||||
|
||||
public T GenerateTrampoline<T>() where T : Delegate
|
||||
{
|
||||
if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
|
||||
throw new InvalidOperationException($"Type {typeof(T)} not a delegate type.");
|
||||
|
||||
_ = GenerateTrampoline(typeof(T).GetMethod("Invoke"));
|
||||
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(TrampolinePtr);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!IsValid)
|
||||
return;
|
||||
|
||||
Undo();
|
||||
Free();
|
||||
}
|
||||
|
||||
public void Apply(ManualLogSource debuggerLogSource)
|
||||
{
|
||||
if (IsApplied)
|
||||
return;
|
||||
|
||||
|
||||
DetourHelper.Native.MakeWritable(OriginalFunctionPtr, 32);
|
||||
|
||||
if (debuggerLogSource != null)
|
||||
{
|
||||
debuggerLogSource
|
||||
.LogDebug($"Detouring 0x{OriginalFunctionPtr.ToString("X")} -> 0x{DetourFunctionPtr.ToString("X")}");
|
||||
debuggerLogSource.Log(LogLevel.Debug, "Original (32) asm");
|
||||
DetourGenerator.Disassemble(debuggerLogSource, OriginalFunctionPtr, 32);
|
||||
}
|
||||
|
||||
var arch = IntPtr.Size == 8 ? Architecture.X64 : Architecture.X86;
|
||||
|
||||
GenerateTrampolineInner(out var trampolineLength, out var jmpLength);
|
||||
|
||||
DetourGenerator.ApplyDetour(OriginalFunctionPtr, DetourFunctionPtr, arch, trampolineLength - jmpLength);
|
||||
|
||||
if (debuggerLogSource != null)
|
||||
{
|
||||
debuggerLogSource.Log(LogLevel.Debug, $"Trampoline allocation: 0x{TrampolinePtr.ToString("X")}");
|
||||
debuggerLogSource.Log(LogLevel.Debug, "Modified (32) asm");
|
||||
DetourGenerator.Disassemble(debuggerLogSource, OriginalFunctionPtr, 32);
|
||||
debuggerLogSource.Log(LogLevel.Debug, $"Trampoline ({trampolineLength}) asm");
|
||||
DetourGenerator.Disassemble(debuggerLogSource, TrampolinePtr, trampolineLength);
|
||||
}
|
||||
|
||||
DetourHelper.Native.MakeExecutable(OriginalFunctionPtr, 32);
|
||||
|
||||
IsApplied = true;
|
||||
}
|
||||
|
||||
|
||||
private void GenerateTrampolineInner(out int trampolineLength, out int jmpLength)
|
||||
{
|
||||
if (TrampolinePtr != IntPtr.Zero)
|
||||
{
|
||||
trampolineLength = TrampolineSize;
|
||||
jmpLength = TrampolineJmpSize;
|
||||
return;
|
||||
}
|
||||
|
||||
var instructionBuffer = new byte[32];
|
||||
Marshal.Copy(OriginalFunctionPtr, instructionBuffer, 0, 32);
|
||||
|
||||
var trampolineAlloc = PageAllocator.Instance.Allocate(OriginalFunctionPtr);
|
||||
|
||||
logger.Log(LogLevel.Debug,
|
||||
$"Original: {OriginalFunctionPtr.ToInt64():X}, Trampoline: {trampolineAlloc:X}, diff: {Math.Abs(OriginalFunctionPtr.ToInt64() - trampolineAlloc):X}; is within +-1GB range: {PageAllocator.IsInRelJmpRange(OriginalFunctionPtr, trampolineAlloc)}");
|
||||
|
||||
DetourHelper.Native.MakeWritable(trampolineAlloc, PageAllocator.PAGE_SIZE);
|
||||
|
||||
var arch = IntPtr.Size == 8 ? Architecture.X64 : Architecture.X86;
|
||||
|
||||
DetourGenerator.CreateTrampolineFromFunction(instructionBuffer, OriginalFunctionPtr, trampolineAlloc,
|
||||
DetourGenerator.GetDetourLength(arch), arch,
|
||||
out trampolineLength, out jmpLength);
|
||||
|
||||
DetourHelper.Native.MakeExecutable(trampolineAlloc, PageAllocator.PAGE_SIZE);
|
||||
|
||||
TrampolinePtr = trampolineAlloc;
|
||||
TrampolineSize = trampolineLength;
|
||||
TrampolineJmpSize = jmpLength;
|
||||
}
|
||||
|
||||
public static FastNativeDetour CreateAndApply<T>(IntPtr from,
|
||||
T to,
|
||||
out T original) where T : Delegate
|
||||
{
|
||||
var toPtr = Marshal.GetFunctionPointerForDelegate(to);
|
||||
var result = new FastNativeDetour(from, toPtr);
|
||||
original = result.GenerateTrampoline<T>();
|
||||
result.Apply();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using BepInEx.IL2CPP.Hook.Allocator;
|
||||
using BepInEx.Logging;
|
||||
using MonoMod.RuntimeDetour;
|
||||
using MonoMod.Utils;
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace BepInEx.IL2CPP.Hook.Funchook;
|
||||
|
||||
internal class FunchookDetour : INativeDetour
|
||||
{
|
||||
private static readonly ManualLogSource logger = Logger.CreateLogSource("FunchookDetour");
|
||||
public FunchookDetour(nint originalMethodPtr, nint detourMethodPtr)
|
||||
{
|
||||
OriginalMethodPtr = originalMethodPtr;
|
||||
DetourMethodPtr = detourMethodPtr;
|
||||
}
|
||||
|
||||
public nint OriginalMethodPtr { get; protected set; }
|
||||
public nint DetourMethodPtr { get; protected set; }
|
||||
public nint TrampolinePtr { get; protected set; }
|
||||
|
||||
public bool IsValid { get; protected set; } = true;
|
||||
|
||||
public bool IsApplied { get; protected set; }
|
||||
public bool IsPrepared { get; protected set; }
|
||||
|
||||
internal FunchookWrapper FunchookInstance { get; set; }
|
||||
protected MethodInfo TrampolineMethod { get; set; }
|
||||
|
||||
public void Apply()
|
||||
{
|
||||
if (IsApplied) return;
|
||||
|
||||
PrepareDetour();
|
||||
if (NativeDetourHelper.DEBUG_DETOURS) logger.LogDebug($"Installing funchook instance");
|
||||
FunchookInstance.Install();
|
||||
|
||||
logger.Log(LogLevel.Debug,
|
||||
$"Original: {OriginalMethodPtr:X}, Trampoline: {TrampolinePtr:X}, diff: {Math.Abs(OriginalMethodPtr - TrampolinePtr):X}; is within +-1GB range: {PageAllocator.IsInRelJmpRange(OriginalMethodPtr, TrampolinePtr)}");
|
||||
|
||||
IsApplied = true;
|
||||
}
|
||||
public void Undo()
|
||||
{
|
||||
if (IsApplied && IsPrepared)
|
||||
{
|
||||
if (NativeDetourHelper.DEBUG_DETOURS) logger.LogDebug($"Uninstalling funchook instance");
|
||||
FunchookInstance.Uninstall();
|
||||
}
|
||||
}
|
||||
|
||||
private unsafe void PrepareDetour()
|
||||
{
|
||||
if (IsPrepared) return;
|
||||
|
||||
if (NativeDetourHelper.DEBUG_DETOURS) logger.LogDebug($"Creating funchook instance");
|
||||
|
||||
if (FunchookInstance == null)
|
||||
FunchookInstance = new FunchookWrapper();
|
||||
|
||||
if (NativeDetourHelper.DEBUG_DETOURS) logger.LogDebug($"Preparing detour from 0x{OriginalMethodPtr:X2} to 0x{DetourMethodPtr:X2}");
|
||||
|
||||
var trampolinePtr = OriginalMethodPtr;
|
||||
FunchookInstance.Prepare(&trampolinePtr, DetourMethodPtr);
|
||||
|
||||
if (NativeDetourHelper.DEBUG_DETOURS) logger.LogDebug($"Prepared detour; Trampoline: 0x{trampolinePtr:X2}");
|
||||
|
||||
TrampolinePtr = trampolinePtr;
|
||||
IsPrepared = true;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!IsValid) return;
|
||||
Undo();
|
||||
Free();
|
||||
}
|
||||
|
||||
public void Free()
|
||||
{
|
||||
if (NativeDetourHelper.DEBUG_DETOURS) logger.LogDebug($"Destroying funchook instance");
|
||||
FunchookInstance.Destroy();
|
||||
IsValid = false;
|
||||
}
|
||||
|
||||
public MethodBase GenerateTrampoline(MethodBase signature = null)
|
||||
{
|
||||
if (TrampolineMethod == null)
|
||||
{
|
||||
PrepareDetour();
|
||||
TrampolineMethod = DetourHelper.GenerateNativeProxy(TrampolinePtr, signature);
|
||||
}
|
||||
return TrampolineMethod;
|
||||
}
|
||||
public T GenerateTrampoline<T>() where T : Delegate
|
||||
{
|
||||
if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
|
||||
throw new InvalidOperationException($"Type {typeof(T)} not a delegate type.");
|
||||
|
||||
return GenerateTrampoline(typeof(T).GetMethod("Invoke")).CreateDelegate(typeof(T)) as T;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using MonoMod.Utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace BepInEx.IL2CPP.Hook.Funchook;
|
||||
|
||||
internal static unsafe class FunchookImports
|
||||
{
|
||||
#region Delegates
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate IntPtr d_funchook_create();
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate FunchookResult d_funchook_destroy(IntPtr funchook);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate FunchookResult d_funchook_prepare(IntPtr funchook, IntPtr* target_func, IntPtr hook_func);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate FunchookResult d_funchook_install(IntPtr funchook, int flags);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate FunchookResult d_funchook_uninstall(IntPtr funchook, int flags);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
|
||||
public delegate string d_funchook_error_message(IntPtr funchook);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
|
||||
public delegate FunchookResult d_funchook_set_debug_file([MarshalAs(UnmanagedType.LPStr)] string name);
|
||||
#endregion
|
||||
|
||||
[DynDllImport("funchook")]
|
||||
public static d_funchook_create funchook_create;
|
||||
|
||||
[DynDllImport("funchook")]
|
||||
public static d_funchook_destroy funchook_destroy;
|
||||
|
||||
[DynDllImport("funchook")]
|
||||
public static d_funchook_prepare funchook_prepare;
|
||||
|
||||
[DynDllImport("funchook")]
|
||||
public static d_funchook_install funchook_install;
|
||||
|
||||
[DynDllImport("funchook")]
|
||||
public static d_funchook_uninstall funchook_uninstall;
|
||||
|
||||
[DynDllImport("funchook")]
|
||||
public static d_funchook_error_message funchook_error_message;
|
||||
|
||||
[DynDllImport("funchook")]
|
||||
public static d_funchook_set_debug_file funchook_set_debug_file;
|
||||
|
||||
static FunchookImports()
|
||||
{
|
||||
var funchookImports = new Dictionary<string, List<DynDllMapping>>()
|
||||
{
|
||||
["funchook"] = new()
|
||||
{
|
||||
$"{Paths.BepInExAssemblyDirectory}/native/funchook.dll" // Windows
|
||||
}
|
||||
};
|
||||
|
||||
typeof(FunchookImports).ResolveDynDllImports(funchookImports);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
|
||||
namespace BepInEx.IL2CPP.Hook.Funchook;
|
||||
|
||||
internal enum FunchookResult : int
|
||||
{
|
||||
InternalError = -1,
|
||||
Success = 0,
|
||||
OutOfMemory = 1,
|
||||
AlreadyInstalled = 2,
|
||||
Disassembly = 3,
|
||||
IPRelativeOffset = 4,
|
||||
CannotFixIPRelative = 5,
|
||||
FoundBackJump = 6,
|
||||
TooShortInstructions = 7,
|
||||
MemoryAllocation = 8,
|
||||
MemoryFunction = 9,
|
||||
NotInstalled = 10,
|
||||
NoAvailableRegisters = 11,
|
||||
}
|
||||
|
||||
internal unsafe class FunchookWrapper
|
||||
{
|
||||
internal static void SetDebugFile(string path) => FunchookImports.funchook_set_debug_file(path);
|
||||
|
||||
public FunchookWrapper()
|
||||
{
|
||||
funchookInstance = FunchookImports.funchook_create();
|
||||
}
|
||||
|
||||
public void Prepare(IntPtr* targetFunc, IntPtr detourFunc)
|
||||
=> EnsureSuccess(FunchookImports.funchook_prepare(funchookInstance, targetFunc, detourFunc), nameof(FunchookImports.funchook_prepare));
|
||||
|
||||
public void Install(int flags = 0)
|
||||
=> EnsureSuccess(FunchookImports.funchook_install(funchookInstance, flags), nameof(FunchookImports.funchook_install));
|
||||
|
||||
public void Uninstall(int flags = 0)
|
||||
=> EnsureSuccess(FunchookImports.funchook_uninstall(funchookInstance, flags), nameof(FunchookImports.funchook_uninstall));
|
||||
|
||||
public string GetErrorMessage()
|
||||
=> FunchookImports.funchook_error_message(funchookInstance);
|
||||
|
||||
public void Destroy()
|
||||
=> EnsureSuccess(FunchookImports.funchook_destroy(funchookInstance), nameof(FunchookImports.funchook_destroy));
|
||||
|
||||
private void EnsureSuccess(FunchookResult result, string methodName)
|
||||
{
|
||||
if (result == FunchookResult.Success) return;
|
||||
var errorMsg = GetErrorMessage();
|
||||
if (result == FunchookResult.OutOfMemory) throw new OutOfMemoryException($"{methodName} failed: {errorMsg}");
|
||||
throw new Exception($"{methodName} failed with result {result}: {errorMsg}");
|
||||
}
|
||||
|
||||
private readonly IntPtr funchookInstance;
|
||||
}
|
||||
@@ -62,7 +62,7 @@ public unsafe class IL2CPPDetourMethodPatcher : MethodPatcher
|
||||
private bool isValid;
|
||||
private INativeMethodInfoStruct modifiedNativeMethodInfo;
|
||||
|
||||
private FastNativeDetour nativeDetour;
|
||||
private INativeDetour nativeDetour;
|
||||
|
||||
private INativeMethodInfoStruct originalNativeMethodInfo;
|
||||
|
||||
@@ -98,16 +98,11 @@ public unsafe class IL2CPPDetourMethodPatcher : MethodPatcher
|
||||
originalNativeMethodInfo =
|
||||
UnityVersionHandler.Wrap((Il2CppMethodInfo*) (IntPtr) methodField.GetValue(null));
|
||||
|
||||
// Create a trampoline from the original target method
|
||||
var trampolinePtr =
|
||||
DetourGenerator.CreateTrampolineFromFunction(originalNativeMethodInfo.MethodPointer, out _, out _);
|
||||
|
||||
// Create a modified native MethodInfo struct to point towards the trampoline
|
||||
// Create a modified native MethodInfo struct, that will point towards the trampoline
|
||||
modifiedNativeMethodInfo = UnityVersionHandler.NewMethod();
|
||||
Buffer.MemoryCopy(originalNativeMethodInfo.Pointer.ToPointer(),
|
||||
modifiedNativeMethodInfo.Pointer.ToPointer(), UnityVersionHandler.MethodSize(),
|
||||
UnityVersionHandler.MethodSize());
|
||||
modifiedNativeMethodInfo.MethodPointer = trampolinePtr;
|
||||
isValid = true;
|
||||
}
|
||||
catch (Exception e)
|
||||
@@ -124,7 +119,12 @@ public unsafe class IL2CPPDetourMethodPatcher : MethodPatcher
|
||||
public override MethodBase DetourTo(MethodBase replacement)
|
||||
{
|
||||
// Unpatch an existing detour if it exists
|
||||
nativeDetour?.Dispose();
|
||||
if (nativeDetour != null)
|
||||
{
|
||||
// Point back to the original method before we unpatch
|
||||
modifiedNativeMethodInfo.MethodPointer = originalNativeMethodInfo.MethodPointer;
|
||||
nativeDetour.Dispose();
|
||||
}
|
||||
|
||||
// Generate a new DMD of the modified unhollowed method, and apply harmony patches to it
|
||||
var copiedDmd = CopyOriginal();
|
||||
@@ -142,8 +142,9 @@ public unsafe class IL2CPPDetourMethodPatcher : MethodPatcher
|
||||
|
||||
var detourPtr =
|
||||
Marshal.GetFunctionPointerForDelegate(unmanagedTrampolineMethod.CreateDelegate(unmanagedDelegateType));
|
||||
nativeDetour = new FastNativeDetour(originalNativeMethodInfo.MethodPointer, detourPtr);
|
||||
nativeDetour = NativeDetourHelper.Create(originalNativeMethodInfo.MethodPointer, detourPtr);
|
||||
nativeDetour.Apply();
|
||||
modifiedNativeMethodInfo.MethodPointer = nativeDetour.TrampolinePtr;
|
||||
|
||||
// TODO: Add an ILHook for the original unhollowed method to go directly to managedHookedMethod
|
||||
// Right now it goes through three times as much interop conversion as it needs to, when being called from managed side
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
using MonoMod.RuntimeDetour;
|
||||
|
||||
namespace BepInEx.IL2CPP.Hook;
|
||||
|
||||
public interface INativeDetour : IDetour
|
||||
{
|
||||
public nint OriginalMethodPtr { get; }
|
||||
public nint DetourMethodPtr { get; }
|
||||
public nint TrampolinePtr { get; }
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using BepInEx.Configuration;
|
||||
using BepInEx.IL2CPP.Hook.Dobby;
|
||||
using BepInEx.IL2CPP.Hook.Funchook;
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace BepInEx.IL2CPP.Hook;
|
||||
|
||||
public class NativeDetourHelper
|
||||
{
|
||||
internal enum DetourProvider
|
||||
{
|
||||
Default,
|
||||
Dobby,
|
||||
Funchook
|
||||
}
|
||||
private static readonly ConfigEntry<DetourProvider> DetourProviderType = ConfigFile.CoreConfig.Bind(
|
||||
"Detours", "DetourProviderType",
|
||||
DetourProvider.Default,
|
||||
"The native provider to use for managed detours"
|
||||
);
|
||||
|
||||
public static bool DEBUG_DETOURS = false;
|
||||
|
||||
private static INativeDetour CreateDefault(nint original, nint target)
|
||||
{
|
||||
// TODO: check and provide an OS accurate provider
|
||||
return new DobbyDetour(original, target);
|
||||
}
|
||||
|
||||
public static INativeDetour Create(nint original, nint target)
|
||||
{
|
||||
return DetourProviderType.Value switch
|
||||
{
|
||||
DetourProvider.Dobby => new DobbyDetour(original, target),
|
||||
DetourProvider.Funchook => new FunchookDetour(original, target),
|
||||
_ => CreateDefault(original, target)
|
||||
};
|
||||
}
|
||||
|
||||
public static INativeDetour CreateAndApply<T>(nint from, T to, out T original, CallingConvention? callingConvention = null)
|
||||
where T : Delegate
|
||||
{
|
||||
var toPtr = callingConvention != null
|
||||
? MonoExtensions.GetFunctionPointerForDelegate(to, callingConvention.Value)
|
||||
: Marshal.GetFunctionPointerForDelegate(to);
|
||||
|
||||
var detour = Create(from, toPtr);
|
||||
original = detour.GenerateTrampoline<T>();
|
||||
detour.Apply();
|
||||
return detour;
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ public class UnhollowerDetourHandler : IManagedDetour
|
||||
{
|
||||
public T Detour<T>(IntPtr from, T to) where T : Delegate
|
||||
{
|
||||
FastNativeDetour.CreateAndApply(from, to, out var original);
|
||||
NativeDetourHelper.CreateAndApply(from, to, out var original);
|
||||
return original;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
@@ -34,7 +35,7 @@ public class IL2CPPChainloader : BaseChainloader<BasePlugin>
|
||||
false,
|
||||
"Include unity log messages in log file output.");
|
||||
|
||||
private static FastNativeDetour RuntimeInvokeDetour { get; set; }
|
||||
private static INativeDetour RuntimeInvokeDetour { get; set; }
|
||||
|
||||
public static IL2CPPChainloader Instance { get; set; }
|
||||
|
||||
@@ -75,7 +76,7 @@ public class IL2CPPChainloader : BaseChainloader<BasePlugin>
|
||||
gameAssemblyModule.BaseAddress.TryGetFunction("il2cpp_runtime_invoke", out var runtimeInvokePtr);
|
||||
PreloaderLogger.Log.Log(LogLevel.Debug, $"Runtime invoke pointer: 0x{runtimeInvokePtr.ToInt64():X}");
|
||||
RuntimeInvokeDetour =
|
||||
FastNativeDetour.CreateAndApply(runtimeInvokePtr, OnInvokeMethod, out originalInvoke);
|
||||
NativeDetourHelper.CreateAndApply(runtimeInvokePtr, OnInvokeMethod, out originalInvoke);
|
||||
|
||||
PreloaderLogger.Log.Log(LogLevel.Debug, "Runtime invoke patched");
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="HarmonyX" Version="2.9.0"/>
|
||||
<PackageReference Include="HarmonyX" Version="2.10.0"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
<ProjectReference Include="..\BepInEx.Preloader.Core\BepInEx.Preloader.Core.csproj" PrivateAssets="All"/>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="HarmonyX" Version="2.9.0"/>
|
||||
<PackageReference Include="HarmonyX" Version="2.10.0"/>
|
||||
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.2" PrivateAssets="All"/>
|
||||
</ItemGroup>
|
||||
<Import Project="..\BepInEx.Shared\BepInEx.Shared.projitems" Label="Shared"/>
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
<Import Project="..\BepInEx.Shared\BepInEx.Shared.projitems" Label="Shared"/>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.2" PrivateAssets="All"/>
|
||||
<PackageReference Include="HarmonyX" Version="2.9.0"/>
|
||||
<PackageReference Include="MonoMod.RuntimeDetour" Version="22.1.29.1"/>
|
||||
<PackageReference Include="MonoMod.Utils" Version="22.1.29.1"/>
|
||||
<PackageReference Include="HarmonyX" Version="2.10.0"/>
|
||||
<PackageReference Include="MonoMod.RuntimeDetour" Version="22.3.23.4"/>
|
||||
<PackageReference Include="MonoMod.Utils" Version="22.3.23.4"/>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -23,7 +23,7 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.2" PrivateAssets="All"/>
|
||||
<PackageReference Include="HarmonyX" Version="2.9.0"/>
|
||||
<PackageReference Include="HarmonyX" Version="2.10.0"/>
|
||||
</ItemGroup>
|
||||
<Import Project="..\BepInEx.Shared\BepInEx.Shared.projitems" Label="Shared"/>
|
||||
</Project>
|
||||
@@ -26,7 +26,7 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.2" PrivateAssets="All"/>
|
||||
<PackageReference Include="HarmonyX" Version="2.9.0"/>
|
||||
<PackageReference Include="HarmonyX" Version="2.10.0"/>
|
||||
<PackageReference Include="UnityEngine" Version="5.6.1" IncludeAssets="compile"/>
|
||||
</ItemGroup>
|
||||
<Import Project="..\BepInEx.Shared\BepInEx.Shared.projitems" Label="Shared"/>
|
||||
|
||||
@@ -23,9 +23,9 @@
|
||||
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')"/>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Iced" Version="1.17.0"/>
|
||||
<PackageReference Include="MSTest.TestAdapter" Version="2.2.8"/>
|
||||
<PackageReference Include="MSTest.TestFramework" Version="2.2.8"/>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0-release-20220113-05"/>
|
||||
<PackageReference Include="MSTest.TestAdapter" Version="2.2.9"/>
|
||||
<PackageReference Include="MSTest.TestFramework" Version="2.2.9"/>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0"/>
|
||||
<PackageReference Include="UnityEngine" Version="5.6.1" Aliases="UEC"/>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using BepInEx.IL2CPP;
|
||||
using Iced.Intel;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
|
||||
namespace BepInEx.Tests;
|
||||
|
||||
[TestClass]
|
||||
public class TrampolineTests
|
||||
{
|
||||
[DataTestMethod]
|
||||
[DataRow(64)]
|
||||
[DataRow(32)]
|
||||
public void TrampolineTest(int bitness)
|
||||
{
|
||||
byte[] exampleCode =
|
||||
{
|
||||
0x48, 0x89, 0x5C, 0x24, 0x10, 0x48, 0x89, 0x74, 0x24, 0x18, 0x55, 0x57, 0x41, 0x56, 0x48, 0x8D,
|
||||
0xAC, 0x24, 0x00, 0xFF, 0xFF, 0xFF, 0x48, 0x81, 0xEC, 0x00, 0x02, 0x00, 0x00, 0x48, 0x8B, 0x05,
|
||||
0x18, 0x57, 0x0A, 0x00, 0x48, 0x33, 0xC4, 0x48, 0x89, 0x85, 0xF0, 0x00, 0x00, 0x00, 0x4C, 0x8B,
|
||||
0x05, 0x2F, 0x24, 0x0A, 0x00, 0x48, 0x8D, 0x05, 0x78, 0x7C, 0x04, 0x00, 0x33, 0xFF
|
||||
};
|
||||
|
||||
var exampleCodePointer = Marshal.AllocHGlobal(80);
|
||||
var trampolineCodePointer = Marshal.AllocHGlobal(80);
|
||||
Marshal.Copy(exampleCode, 0, exampleCodePointer, exampleCode.Length);
|
||||
|
||||
|
||||
void Disassemble(byte[] data, ulong ip)
|
||||
{
|
||||
var formatter = new NasmFormatter();
|
||||
var output = new StringOutput();
|
||||
var codeReader = new ByteArrayCodeReader(data);
|
||||
var decoder = Decoder.Create(bitness, codeReader);
|
||||
decoder.IP = ip;
|
||||
while (codeReader.CanReadByte)
|
||||
{
|
||||
decoder.Decode(out var instr);
|
||||
formatter.Format(instr, output);
|
||||
Console.WriteLine($"{instr.IP:X16} {output.ToStringAndReset()}");
|
||||
}
|
||||
|
||||
Console.WriteLine();
|
||||
}
|
||||
|
||||
|
||||
Console.WriteLine("Original:");
|
||||
Console.WriteLine();
|
||||
|
||||
|
||||
Disassemble(exampleCode, (ulong) exampleCodePointer.ToInt64());
|
||||
|
||||
DetourGenerator.CreateTrampolineFromFunction(exampleCodePointer, out var trampolineLength, out _);
|
||||
|
||||
Console.WriteLine("Modified:");
|
||||
Console.WriteLine();
|
||||
|
||||
|
||||
Marshal.Copy(exampleCodePointer, exampleCode, 0, exampleCode.Length);
|
||||
Disassemble(exampleCode, (ulong) exampleCodePointer.ToInt64());
|
||||
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Trampoline:");
|
||||
Console.WriteLine();
|
||||
|
||||
var trampolineArray = new byte[trampolineLength];
|
||||
Marshal.Copy(trampolineCodePointer, trampolineArray, 0, trampolineLength);
|
||||
|
||||
Disassemble(trampolineArray, (ulong) trampolineCodePointer.ToInt64());
|
||||
|
||||
|
||||
Marshal.FreeHGlobal(exampleCodePointer);
|
||||
Marshal.FreeHGlobal(trampolineCodePointer);
|
||||
|
||||
Assert.IsFalse(false);
|
||||
}
|
||||
}
|
||||
@@ -72,9 +72,8 @@ A more comprehensive comparison list of features and compatibility is available
|
||||
|
||||
- [Perfare/Il2CppDumper](https://github.com/Perfare/Il2CppDumper) - v6.6.3
|
||||
fork ([112e2e8](https://github.com/BepInEx/Il2CppDumper/commit/112e2e8c369dfcb6d5718fd4ad7e3838d7ddabbf))
|
||||
- [SamboyCoding/Cpp2IL](https://github.com/SamboyCoding/Cpp2IL) -
|
||||
2022.0.1 ([21a45ea](https://github.com/SamboyCoding/Cpp2IL/commit/21a45ea108b11296fd2f5a015d8f818b743c3c5d))
|
||||
- [BepInEx/Il2CppAssemblyUnhollower](https://github.com/BepInEx/Il2CppAssemblyUnhollower) - v0.4.23.0 (fork of
|
||||
- [SamboyCoding/Cpp2IL](https://github.com/SamboyCoding/Cpp2IL) - 2022.0.2
|
||||
- [BepInEx/Il2CppAssemblyUnhollower](https://github.com/BepInEx/Il2CppAssemblyUnhollower) - v0.4.31.0 (fork of
|
||||
knah/Il2CppAssemblyUnhollower)
|
||||
fork ([7f059df](https://github.com/BepInEx/Il2CppAssemblyUnhollower/commit/7f059dfd74c7b9dfb4a497965d241943f611bdfb))
|
||||
- [mono/mono](https://github.com/mono/mono) - 6.12.0.93
|
||||
|
||||
Reference in new issue
Block a user