PageAllocator.cs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.CompilerServices;
  4. using MonoMod.Utils;
  5. namespace BepInEx.IL2CPP.Allocator
  6. {
  7. public class PageAllocatorException : Exception
  8. {
  9. public PageAllocatorException(string message) : base(message) { }
  10. }
  11. /// <summary>
  12. /// A general purpose page allocator for patching purposes.
  13. /// Allows to allocate pages (4k memory chunks) within the 1GB radius of a given address.
  14. /// </summary>
  15. /// <remarks>Based on https://github.com/kubo/funchook</remarks>
  16. internal abstract class PageAllocator
  17. {
  18. /// <summary>
  19. /// Common page size on Unix and Windows (4k).
  20. /// Call to <see cref="Allocate" /> will allocate a single page of this size.
  21. /// </summary>
  22. public const int PAGE_SIZE = 0x1000;
  23. /// <summary>
  24. /// Allocation granularity on Windows (but can be reused in other implementations).
  25. /// </summary>
  26. protected const int ALLOCATION_UNIT = 0x100000;
  27. protected const int PAGES_PER_UNIT = ALLOCATION_UNIT / PAGE_SIZE;
  28. private static PageAllocator instance;
  29. /// <summary>
  30. /// Platform-specific instance of page allocator.
  31. /// </summary>
  32. public static PageAllocator Instance => instance ??= Init();
  33. /// <summary>
  34. /// Allocates a single 64k chunk of memory near the given address
  35. /// </summary>
  36. /// <param name="hint">Address near which to attempt allocate the chunk</param>
  37. /// <returns>Allocated chunk</returns>
  38. /// <exception cref="PageAllocatorException">Allocation failed</exception>
  39. protected abstract IntPtr AllocateChunk(IntPtr hint);
  40. /// <summary>
  41. /// Allocates a single page of size <see cref="PAGE_SIZE" /> near the provided address.
  42. /// Attempts to allocate the page within the +-1GB region of the hinted address.
  43. /// </summary>
  44. /// <param name="hint">Address near which to attempt to allocate the page.</param>
  45. /// <returns>Address to the allocated page.</returns>
  46. public virtual IntPtr Allocate(IntPtr hint)
  47. {
  48. foreach (var allocatedChunk in allocatedChunks)
  49. {
  50. // Small shortcut to speed up page lookup
  51. if (allocatedChunk.UsedPages == PAGES_PER_UNIT)
  52. continue;
  53. for (var i = 0; i < allocatedChunk.Pages.Length; i++)
  54. {
  55. if (allocatedChunk.Pages[i])
  56. continue;
  57. var pageAddr = allocatedChunk.GetPage(i);
  58. if (!IsInRelJmpRange(hint, pageAddr))
  59. continue;
  60. allocatedChunk.Pages[i] = true;
  61. allocatedChunk.UsedPages++;
  62. return pageAddr;
  63. }
  64. }
  65. var chunk = new PageChunk
  66. {
  67. BaseAddress = AllocateChunk(hint)
  68. };
  69. allocatedChunks.Add(chunk);
  70. chunk.Pages[0] = true;
  71. chunk.UsedPages++;
  72. return chunk.BaseAddress;
  73. }
  74. /// <summary>
  75. /// Frees the page allocated with <see cref="Allocate" />
  76. /// </summary>
  77. /// <param name="page"></param>
  78. public void Free(IntPtr page)
  79. {
  80. foreach (var allocatedChunk in allocatedChunks)
  81. {
  82. long index = (page.ToInt64() - allocatedChunk.BaseAddress.ToInt64()) / PAGE_SIZE;
  83. if (index < 0 || index > PAGES_PER_UNIT)
  84. continue;
  85. allocatedChunk.Pages[index] = false;
  86. return;
  87. }
  88. }
  89. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  90. protected static long RoundUp(long num, long unit)
  91. {
  92. return (num + unit - 1) & ~ (unit - 1);
  93. }
  94. /// <summary>
  95. /// Checks if the given address is within the relative jump range.
  96. /// </summary>
  97. /// <param name="src">Source address to jump from.</param>
  98. /// <param name="dst">Destination address to jump to.</param>
  99. /// <returns>True, if the distance between the addresses is within the relative jump range (usually 1GB), otherwise false.</returns>
  100. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  101. public static bool IsInRelJmpRange(IntPtr src, IntPtr dst)
  102. {
  103. long diff = dst.ToInt64() - src.ToInt64();
  104. return int.MinValue <= diff && diff <= int.MaxValue;
  105. }
  106. private static PageAllocator Init() =>
  107. PlatformHelper.Current switch
  108. {
  109. var v when v.Is(Platform.Windows) => new WindowsPageAllocator(),
  110. var v when v.Is(Platform.Linux) => new LinuxPageAllocator(),
  111. var v when v.Is(Platform.MacOS) => new MacOsPageAllocator(),
  112. _ => throw new NotImplementedException()
  113. };
  114. private class PageChunk
  115. {
  116. public readonly bool[] Pages = new bool[PAGES_PER_UNIT];
  117. public IntPtr BaseAddress;
  118. public int UsedPages;
  119. public IntPtr GetPage(int index)
  120. {
  121. return BaseAddress + index * PAGE_SIZE;
  122. }
  123. }
  124. private readonly List<PageChunk> allocatedChunks = new List<PageChunk>();
  125. }
  126. internal static class PlatformExt
  127. {
  128. public static bool Is(this Platform pl, Platform val) => (pl & val) == val;
  129. }
  130. }