PageAllocator.cs 4.6 KB

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