MemoryBuffer.cs 1.3 KB

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