JumpTable.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. private 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 item in ptcJumpTable.Dependants)
  70. {
  71. Dependants.TryAdd(item.Key, new List<int>(item.Value));
  72. }
  73. foreach (var item in ptcJumpTable.Owners)
  74. {
  75. Owners.TryAdd(item.Key, new List<int>(item.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. if (Owners.TryRemove(guestAddress, out List<int> list))
  146. {
  147. for (int i = 0; i < list.Count; i++)
  148. {
  149. int entry = list[i];
  150. bool isDynamic = (entry & DynamicEntryTag) != 0;
  151. entry &= ~DynamicEntryTag;
  152. if (isDynamic)
  153. {
  154. IntPtr addr = GetEntryAddressDynamicTable(entry);
  155. for (int j = 0; j < DynamicTableElems; j++)
  156. {
  157. Marshal.WriteInt64(addr + j * JumpTableStride, 0, 0L);
  158. Marshal.WriteInt64(addr + j * JumpTableStride, 8, 0L);
  159. }
  160. DynTable.FreeEntry(entry);
  161. }
  162. else
  163. {
  164. IntPtr addr = GetEntryAddressJumpTable(entry);
  165. Marshal.WriteInt64(addr, 0, 0L);
  166. Marshal.WriteInt64(addr, 8, 0L);
  167. Table.FreeEntry(entry);
  168. }
  169. }
  170. }
  171. }
  172. public void ExpandIfNeededJumpTable(int entry)
  173. {
  174. Debug.Assert(entry >= 0);
  175. if (entry < JumpTableSize)
  176. {
  177. _jumpRegion.ExpandIfNeeded((ulong)((entry + 1) * JumpTableStride));
  178. }
  179. else
  180. {
  181. throw new OutOfMemoryException("JIT Direct Jump Table exhausted.");
  182. }
  183. }
  184. public void ExpandIfNeededDynamicTable(int entry)
  185. {
  186. Debug.Assert(entry >= 0);
  187. if (entry < DynamicTableSize)
  188. {
  189. _dynamicRegion.ExpandIfNeeded((ulong)((entry + 1) * DynamicTableStride));
  190. }
  191. else
  192. {
  193. throw new OutOfMemoryException("JIT Dynamic Jump Table exhausted.");
  194. }
  195. }
  196. public IntPtr GetEntryAddressJumpTable(int entry)
  197. {
  198. Debug.Assert(Table.EntryIsValid(entry));
  199. return _jumpRegion.Pointer + entry * JumpTableStride;
  200. }
  201. public IntPtr GetEntryAddressDynamicTable(int entry)
  202. {
  203. Debug.Assert(DynTable.EntryIsValid(entry));
  204. return _dynamicRegion.Pointer + entry * DynamicTableStride;
  205. }
  206. public void Dispose()
  207. {
  208. _jumpRegion.Dispose();
  209. _dynamicRegion.Dispose();
  210. }
  211. }
  212. }