Decoder.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. using ChocolArm64.Instructions;
  2. using ChocolArm64.Memory;
  3. using ChocolArm64.State;
  4. using System;
  5. using System.Collections.Concurrent;
  6. using System.Collections.Generic;
  7. using System.Reflection.Emit;
  8. namespace ChocolArm64.Decoders
  9. {
  10. static class Decoder
  11. {
  12. private delegate object OpActivator(Inst inst, long position, int opCode);
  13. private static ConcurrentDictionary<Type, OpActivator> _opActivators;
  14. static Decoder()
  15. {
  16. _opActivators = new ConcurrentDictionary<Type, OpActivator>();
  17. }
  18. public static Block DecodeBasicBlock(CpuThreadState state, MemoryManager memory, long start)
  19. {
  20. Block block = new Block(start);
  21. FillBlock(state, memory, block);
  22. return block;
  23. }
  24. public static (Block[] Graph, Block Root) DecodeSubroutine(
  25. TranslatorCache cache,
  26. CpuThreadState state,
  27. MemoryManager memory,
  28. long start)
  29. {
  30. Dictionary<long, Block> visited = new Dictionary<long, Block>();
  31. Dictionary<long, Block> visitedEnd = new Dictionary<long, Block>();
  32. Queue<Block> blocks = new Queue<Block>();
  33. Block Enqueue(long position)
  34. {
  35. if (!visited.TryGetValue(position, out Block output))
  36. {
  37. output = new Block(position);
  38. blocks.Enqueue(output);
  39. visited.Add(position, output);
  40. }
  41. return output;
  42. }
  43. Block root = Enqueue(start);
  44. while (blocks.Count > 0)
  45. {
  46. Block current = blocks.Dequeue();
  47. FillBlock(state, memory, current);
  48. //Set child blocks. "Branch" is the block the branch instruction
  49. //points to (when taken), "Next" is the block at the next address,
  50. //executed when the branch is not taken. For Unconditional Branches
  51. //(except BL/BLR that are sub calls) or end of executable, Next is null.
  52. if (current.OpCodes.Count > 0)
  53. {
  54. bool hasCachedSub = false;
  55. OpCode64 lastOp = current.GetLastOp();
  56. if (lastOp is OpCodeBImm64 op)
  57. {
  58. if (op.Emitter == InstEmit.Bl)
  59. {
  60. hasCachedSub = cache.HasSubroutine(op.Imm);
  61. }
  62. else
  63. {
  64. current.Branch = Enqueue(op.Imm);
  65. }
  66. }
  67. if (!((lastOp is OpCodeBImmAl64) ||
  68. (lastOp is OpCodeBReg64)) || hasCachedSub)
  69. {
  70. current.Next = Enqueue(current.EndPosition);
  71. }
  72. }
  73. //If we have on the graph two blocks with the same end position,
  74. //then we need to split the bigger block and have two small blocks,
  75. //the end position of the bigger "Current" block should then be == to
  76. //the position of the "Smaller" block.
  77. while (visitedEnd.TryGetValue(current.EndPosition, out Block smaller))
  78. {
  79. if (current.Position > smaller.Position)
  80. {
  81. Block temp = smaller;
  82. smaller = current;
  83. current = temp;
  84. }
  85. current.EndPosition = smaller.Position;
  86. current.Next = smaller;
  87. current.Branch = null;
  88. current.OpCodes.RemoveRange(
  89. current.OpCodes.Count - smaller.OpCodes.Count,
  90. smaller.OpCodes.Count);
  91. visitedEnd[smaller.EndPosition] = smaller;
  92. }
  93. visitedEnd.Add(current.EndPosition, current);
  94. }
  95. //Make and sort Graph blocks array by position.
  96. Block[] graph = new Block[visited.Count];
  97. while (visited.Count > 0)
  98. {
  99. ulong firstPos = ulong.MaxValue;
  100. foreach (Block block in visited.Values)
  101. {
  102. if (firstPos > (ulong)block.Position)
  103. firstPos = (ulong)block.Position;
  104. }
  105. Block current = visited[(long)firstPos];
  106. do
  107. {
  108. graph[graph.Length - visited.Count] = current;
  109. visited.Remove(current.Position);
  110. current = current.Next;
  111. }
  112. while (current != null);
  113. }
  114. return (graph, root);
  115. }
  116. private static void FillBlock(CpuThreadState state, MemoryManager memory, Block block)
  117. {
  118. long position = block.Position;
  119. OpCode64 opCode;
  120. do
  121. {
  122. //TODO: This needs to be changed to support both AArch32 and AArch64,
  123. //once JIT support is introduced on AArch32 aswell.
  124. opCode = DecodeOpCode(state, memory, position);
  125. block.OpCodes.Add(opCode);
  126. position += 4;
  127. }
  128. while (!(IsBranch(opCode) || IsException(opCode)));
  129. block.EndPosition = position;
  130. }
  131. private static bool IsBranch(OpCode64 opCode)
  132. {
  133. return opCode is OpCodeBImm64 ||
  134. opCode is OpCodeBReg64;
  135. }
  136. private static bool IsException(OpCode64 opCode)
  137. {
  138. return opCode.Emitter == InstEmit.Brk ||
  139. opCode.Emitter == InstEmit.Svc ||
  140. opCode.Emitter == InstEmit.Und;
  141. }
  142. public static OpCode64 DecodeOpCode(CpuThreadState state, MemoryManager memory, long position)
  143. {
  144. int opCode = memory.ReadInt32(position);
  145. Inst inst;
  146. if (state.ExecutionMode == ExecutionMode.AArch64)
  147. {
  148. inst = OpCodeTable.GetInstA64(opCode);
  149. }
  150. else
  151. {
  152. //TODO: Thumb support.
  153. inst = OpCodeTable.GetInstA32(opCode);
  154. }
  155. OpCode64 decodedOpCode = new OpCode64(Inst.Undefined, position, opCode);
  156. if (inst.Type != null)
  157. {
  158. decodedOpCode = MakeOpCode(inst.Type, inst, position, opCode);
  159. }
  160. return decodedOpCode;
  161. }
  162. private static OpCode64 MakeOpCode(Type type, Inst inst, long position, int opCode)
  163. {
  164. if (type == null)
  165. {
  166. throw new ArgumentNullException(nameof(type));
  167. }
  168. OpActivator createInstance = _opActivators.GetOrAdd(type, CacheOpActivator);
  169. return (OpCode64)createInstance(inst, position, opCode);
  170. }
  171. private static OpActivator CacheOpActivator(Type type)
  172. {
  173. Type[] argTypes = new Type[] { typeof(Inst), typeof(long), typeof(int) };
  174. DynamicMethod mthd = new DynamicMethod($"Make{type.Name}", type, argTypes);
  175. ILGenerator generator = mthd.GetILGenerator();
  176. generator.Emit(OpCodes.Ldarg_0);
  177. generator.Emit(OpCodes.Ldarg_1);
  178. generator.Emit(OpCodes.Ldarg_2);
  179. generator.Emit(OpCodes.Newobj, type.GetConstructor(argTypes));
  180. generator.Emit(OpCodes.Ret);
  181. return (OpActivator)mthd.CreateDelegate(typeof(OpActivator));
  182. }
  183. }
  184. }