JumpTable.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. using ARMeilleure.Diagnostics;
  2. using ARMeilleure.Memory;
  3. using ARMeilleure.Translation.PTC;
  4. using System;
  5. using System.Collections.Concurrent;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Runtime.InteropServices;
  9. namespace ARMeilleure.Translation.Cache
  10. {
  11. class JumpTable : IDisposable
  12. {
  13. // The jump table is a block of (guestAddress, hostAddress) function mappings.
  14. // Each entry corresponds to one branch in a JIT compiled function. The entries are
  15. // reserved specifically for each call.
  16. // The Dependants dictionary can be used to update the hostAddress for any functions that change.
  17. public const int JumpTableStride = 16; // 8 byte guest address, 8 byte host address.
  18. private const int JumpTableSize = 1048576;
  19. private const int JumpTableByteSize = JumpTableSize * JumpTableStride;
  20. // The dynamic table is also a block of (guestAddress, hostAddress) function mappings.
  21. // The main difference is that indirect calls and jumps reserve _multiple_ entries on the table.
  22. // These start out as all 0. When an indirect call is made, it tries to find the guest address on the table.
  23. // If we get to an empty address, the guestAddress is set to the call that we want.
  24. // If we get to a guestAddress that matches our own (or we just claimed it), the hostAddress is read.
  25. // If it is non-zero, we immediately branch or call the host function.
  26. // If it is 0, NativeInterface is called to find the rejited address of the call.
  27. // If none is found, the hostAddress entry stays at 0. Otherwise, the new address is placed in the entry.
  28. // If the table size is exhausted and we didn't find our desired address, we fall back to requesting
  29. // the function from the JIT.
  30. public const int DynamicTableElems = 1;
  31. public const int DynamicTableStride = DynamicTableElems * JumpTableStride;
  32. private const int DynamicTableSize = 1048576;
  33. private const int DynamicTableByteSize = DynamicTableSize * DynamicTableStride;
  34. public const int DynamicEntryTag = 1 << 31;
  35. private readonly ReservedRegion _jumpRegion;
  36. private readonly ReservedRegion _dynamicRegion;
  37. public IntPtr JumpPointer => _jumpRegion.Pointer;
  38. public IntPtr DynamicPointer => _dynamicRegion.Pointer;
  39. public JumpTableEntryAllocator Table { get; }
  40. public JumpTableEntryAllocator DynTable { get; }
  41. public ConcurrentDictionary<ulong, TranslatedFunction> Targets { get; }
  42. public ConcurrentDictionary<ulong, List<int>> Dependants { get; } // TODO: Attach to TranslatedFunction or a wrapper class.
  43. public ConcurrentDictionary<ulong, List<int>> Owners { get; }
  44. public JumpTable(IJitMemoryAllocator allocator)
  45. {
  46. _jumpRegion = new ReservedRegion(allocator, JumpTableByteSize);
  47. _dynamicRegion = new ReservedRegion(allocator, DynamicTableByteSize);
  48. Table = new JumpTableEntryAllocator();
  49. DynTable = new JumpTableEntryAllocator();
  50. Targets = new ConcurrentDictionary<ulong, TranslatedFunction>();
  51. Dependants = new ConcurrentDictionary<ulong, List<int>>();
  52. Owners = new ConcurrentDictionary<ulong, List<int>>();
  53. Symbols.Add((ulong)_jumpRegion.Pointer.ToInt64(), JumpTableByteSize, JumpTableStride, "JMP_TABLE");
  54. Symbols.Add((ulong)_dynamicRegion.Pointer.ToInt64(), DynamicTableByteSize, DynamicTableStride, "DYN_TABLE");
  55. }
  56. public void Initialize(PtcJumpTable ptcJumpTable, ConcurrentDictionary<ulong, TranslatedFunction> funcs)
  57. {
  58. foreach (ulong guestAddress in ptcJumpTable.Targets)
  59. {
  60. if (funcs.TryGetValue(guestAddress, out TranslatedFunction func))
  61. {
  62. Targets.TryAdd(guestAddress, func);
  63. }
  64. else
  65. {
  66. throw new KeyNotFoundException($"({nameof(guestAddress)} = 0x{guestAddress:X16})");
  67. }
  68. }
  69. foreach (var kv in ptcJumpTable.Dependants)
  70. {
  71. Dependants.TryAdd(kv.Key, new List<int>(kv.Value));
  72. }
  73. foreach (var kv in ptcJumpTable.Owners)
  74. {
  75. Owners.TryAdd(kv.Key, new List<int>(kv.Value));
  76. }
  77. }
  78. public void RegisterFunction(ulong address, TranslatedFunction func)
  79. {
  80. Targets.AddOrUpdate(address, func, (key, oldFunc) => func);
  81. long funcPtr = func.FuncPtr.ToInt64();
  82. // Update all jump table entries that target this address.
  83. if (Dependants.TryGetValue(address, out List<int> myDependants))
  84. {
  85. lock (myDependants)
  86. {
  87. foreach (int entry in myDependants)
  88. {
  89. IntPtr addr = GetEntryAddressJumpTable(entry);
  90. Marshal.WriteInt64(addr, 8, funcPtr);
  91. }
  92. }
  93. }
  94. }
  95. public int ReserveTableEntry(ulong ownerGuestAddress, ulong address, bool isJump)
  96. {
  97. int entry = Table.AllocateEntry();
  98. ExpandIfNeededJumpTable(entry);
  99. // Is the address we have already registered? If so, put the function address in the jump table.
  100. // If not, it will point to the direct call stub.
  101. long value = DirectCallStubs.DirectCallStub(isJump).ToInt64();
  102. if (Targets.TryGetValue(address, out TranslatedFunction func))
  103. {
  104. value = func.FuncPtr.ToInt64();
  105. }
  106. // Make sure changes to the function at the target address update this jump table entry.
  107. List<int> targetDependants = Dependants.GetOrAdd(address, (addr) => new List<int>());
  108. lock (targetDependants)
  109. {
  110. targetDependants.Add(entry);
  111. }
  112. // Keep track of ownership for jump table entries.
  113. List<int> ownerEntries = Owners.GetOrAdd(ownerGuestAddress, (addr) => new List<int>());
  114. lock (ownerEntries)
  115. {
  116. ownerEntries.Add(entry);
  117. }
  118. IntPtr addr = GetEntryAddressJumpTable(entry);
  119. Marshal.WriteInt64(addr, 0, (long)address);
  120. Marshal.WriteInt64(addr, 8, value);
  121. return entry;
  122. }
  123. public int ReserveDynamicEntry(ulong ownerGuestAddress, bool isJump)
  124. {
  125. int entry = DynTable.AllocateEntry();
  126. ExpandIfNeededDynamicTable(entry);
  127. // Keep track of ownership for jump table entries.
  128. List<int> ownerEntries = Owners.GetOrAdd(ownerGuestAddress, (addr) => new List<int>());
  129. lock (ownerEntries)
  130. {
  131. ownerEntries.Add(entry | DynamicEntryTag);
  132. }
  133. // Initialize all host function pointers to the indirect call stub.
  134. IntPtr addr = GetEntryAddressDynamicTable(entry);
  135. long stubPtr = DirectCallStubs.IndirectCallStub(isJump).ToInt64();
  136. for (int i = 0; i < DynamicTableElems; i++)
  137. {
  138. Marshal.WriteInt64(addr, i * JumpTableStride + 8, stubPtr);
  139. }
  140. return entry;
  141. }
  142. // For future use.
  143. public void RemoveFunctionEntries(ulong guestAddress)
  144. {
  145. Targets.TryRemove(guestAddress, out _);
  146. Dependants.TryRemove(guestAddress, out _);
  147. if (Owners.TryRemove(guestAddress, out List<int> entries))
  148. {
  149. foreach (int entry in entries)
  150. {
  151. if ((entry & DynamicEntryTag) == 0)
  152. {
  153. IntPtr addr = GetEntryAddressJumpTable(entry);
  154. Marshal.WriteInt64(addr, 0, 0L);
  155. Marshal.WriteInt64(addr, 8, 0L);
  156. Table.FreeEntry(entry);
  157. }
  158. else
  159. {
  160. IntPtr addr = GetEntryAddressDynamicTable(entry & ~DynamicEntryTag);
  161. for (int j = 0; j < DynamicTableElems; j++)
  162. {
  163. Marshal.WriteInt64(addr + j * JumpTableStride, 0, 0L);
  164. Marshal.WriteInt64(addr + j * JumpTableStride, 8, 0L);
  165. }
  166. DynTable.FreeEntry(entry & ~DynamicEntryTag);
  167. }
  168. }
  169. }
  170. }
  171. public void ExpandIfNeededJumpTable(int entry)
  172. {
  173. Debug.Assert(entry >= 0);
  174. if (entry < JumpTableSize)
  175. {
  176. _jumpRegion.ExpandIfNeeded((ulong)((entry + 1) * JumpTableStride));
  177. }
  178. else
  179. {
  180. throw new OutOfMemoryException("JIT Direct Jump Table exhausted.");
  181. }
  182. }
  183. public void ExpandIfNeededDynamicTable(int entry)
  184. {
  185. Debug.Assert(entry >= 0);
  186. if (entry < DynamicTableSize)
  187. {
  188. _dynamicRegion.ExpandIfNeeded((ulong)((entry + 1) * DynamicTableStride));
  189. }
  190. else
  191. {
  192. throw new OutOfMemoryException("JIT Dynamic Jump Table exhausted.");
  193. }
  194. }
  195. public IntPtr GetEntryAddressJumpTable(int entry)
  196. {
  197. Debug.Assert(Table.EntryIsValid(entry));
  198. return _jumpRegion.Pointer + entry * JumpTableStride;
  199. }
  200. public IntPtr GetEntryAddressDynamicTable(int entry)
  201. {
  202. Debug.Assert(DynTable.EntryIsValid(entry));
  203. return _dynamicRegion.Pointer + entry * DynamicTableStride;
  204. }
  205. public bool CheckEntryFromAddressJumpTable(IntPtr entryAddress)
  206. {
  207. int entry = Math.DivRem((int)((ulong)entryAddress - (ulong)_jumpRegion.Pointer), JumpTableStride, out int rem);
  208. return rem == 0 && Table.EntryIsValid(entry);
  209. }
  210. public bool CheckEntryFromAddressDynamicTable(IntPtr entryAddress)
  211. {
  212. int entry = Math.DivRem((int)((ulong)entryAddress - (ulong)_dynamicRegion.Pointer), DynamicTableStride, out int rem);
  213. return rem == 0 && DynTable.EntryIsValid(entry);
  214. }
  215. public void Dispose()
  216. {
  217. _jumpRegion.Dispose();
  218. _dynamicRegion.Dispose();
  219. }
  220. }
  221. }