TrampolineTests.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using Microsoft.VisualStudio.TestTools.UnitTesting;
  3. using System.Runtime.InteropServices;
  4. using BepInEx.IL2CPP;
  5. using Iced.Intel;
  6. namespace BepInEx.Tests
  7. {
  8. [TestClass]
  9. public class TrampolineTests
  10. {
  11. [TestMethod]
  12. public void TrampolineTest()
  13. {
  14. byte[] exampleCode = new byte[] {
  15. 0x48, 0x89, 0x5C, 0x24, 0x10, 0x48, 0x89, 0x74, 0x24, 0x18, 0x55, 0x57, 0x41, 0x56, 0x48, 0x8D,
  16. 0xAC, 0x24, 0x00, 0xFF, 0xFF, 0xFF, 0x48, 0x81, 0xEC, 0x00, 0x02, 0x00, 0x00, 0x48, 0x8B, 0x05,
  17. 0x18, 0x57, 0x0A, 0x00, 0x48, 0x33, 0xC4, 0x48, 0x89, 0x85, 0xF0, 0x00, 0x00, 0x00, 0x4C, 0x8B,
  18. 0x05, 0x2F, 0x24, 0x0A, 0x00, 0x48, 0x8D, 0x05, 0x78, 0x7C, 0x04, 0x00, 0x33, 0xFF
  19. };
  20. var exampleCodePointer = Marshal.AllocHGlobal(80);
  21. var trampolineCodePointer = Marshal.AllocHGlobal(80);
  22. Marshal.Copy(exampleCode, 0, exampleCodePointer, exampleCode.Length);
  23. void Disassemble(byte[] data, ulong ip)
  24. {
  25. var formatter = new NasmFormatter();
  26. var output = new StringOutput();
  27. var codeReader = new ByteArrayCodeReader(data);
  28. var decoder = Decoder.Create(64, codeReader);
  29. decoder.IP = ip;
  30. while (codeReader.CanReadByte)
  31. {
  32. decoder.Decode(out var instr);
  33. formatter.Format(instr, output);
  34. Console.WriteLine($"{instr.IP:X16} {output.ToStringAndReset()}");
  35. }
  36. Console.WriteLine();
  37. }
  38. Console.WriteLine("Original:");
  39. Console.WriteLine();
  40. Disassemble(exampleCode, (ulong)exampleCodePointer.ToInt64());
  41. int trampolineLength = TrampolineGenerator.Generate(exampleCodePointer, new IntPtr(0xBEEF), trampolineCodePointer, 64);
  42. Console.WriteLine();
  43. Console.WriteLine("Trampoline:");
  44. Console.WriteLine();
  45. byte[] trampolineArray = new byte[trampolineLength];
  46. Marshal.Copy(trampolineCodePointer, trampolineArray, 0, trampolineLength);
  47. Disassemble(trampolineArray, (ulong)trampolineCodePointer.ToInt64());
  48. Marshal.FreeHGlobal(exampleCodePointer);
  49. Marshal.FreeHGlobal(trampolineCodePointer);
  50. Assert.IsFalse(false);
  51. }
  52. }
  53. }