MemoryAllocator.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using MonoMod.Utils;
  4. namespace BepInEx.IL2CPP
  5. {
  6. /// <summary>
  7. /// A general purpose memory allocator for patching purposes.
  8. /// Allows to allocate memory within the 2GB radius of a given address.
  9. /// </summary>
  10. /// <remarks>Based on https://github.com/kubo/funchook</remarks>
  11. internal abstract class MemoryAllocator
  12. {
  13. /// <summary>
  14. /// Common page size on Unix and Windows (4k).
  15. /// </summary>
  16. protected const int PAGE_SIZE = 0x1000;
  17. /// <summary>
  18. /// Allocation granularity on Windows (but can be reused in other implementations).
  19. /// </summary>
  20. protected const int ALLOCATION_UNIT = 0x100000;
  21. private static MemoryAllocator instance;
  22. public static MemoryAllocator Instance => instance ??= Init();
  23. public abstract IntPtr Allocate(IntPtr func);
  24. public abstract void Free(IntPtr buffer);
  25. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  26. protected static long RoundDown(long num, long unit)
  27. {
  28. return num & ~(unit - 1);
  29. }
  30. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  31. protected static long RoundUp(long num, long unit)
  32. {
  33. return (num + unit - 1) & ~ (unit - 1);
  34. }
  35. private static MemoryAllocator Init()
  36. {
  37. if (PlatformHelper.Is(Platform.Windows))
  38. return new WindowsMemoryAllocator();
  39. if (PlatformHelper.Is(Platform.Unix))
  40. return new UnixMemoryAllocator();
  41. throw new NotImplementedException();
  42. }
  43. }
  44. }