Decoder.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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(MemoryManager memory, long start, ExecutionMode mode)
  19. {
  20. Block block = new Block(start);
  21. FillBlock(memory, mode, block);
  22. return block;
  23. }
  24. public static Block DecodeSubroutine(
  25. TranslatorCache cache,
  26. MemoryManager memory,
  27. long start,
  28. ExecutionMode mode)
  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 entry = Enqueue(start);
  44. while (blocks.Count > 0)
  45. {
  46. Block current = blocks.Dequeue();
  47. FillBlock(memory, mode, 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 IOpCodeBImm 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 (!IsUnconditionalBranch(lastOp) || hasCachedSub)
  68. {
  69. current.Next = Enqueue(current.EndPosition);
  70. }
  71. }
  72. //If we have on the graph two blocks with the same end position,
  73. //then we need to split the bigger block and have two small blocks,
  74. //the end position of the bigger "Current" block should then be == to
  75. //the position of the "Smaller" block.
  76. while (visitedEnd.TryGetValue(current.EndPosition, out Block smaller))
  77. {
  78. if (current.Position > smaller.Position)
  79. {
  80. Block temp = smaller;
  81. smaller = current;
  82. current = temp;
  83. }
  84. current.EndPosition = smaller.Position;
  85. current.Next = smaller;
  86. current.Branch = null;
  87. current.OpCodes.RemoveRange(
  88. current.OpCodes.Count - smaller.OpCodes.Count,
  89. smaller.OpCodes.Count);
  90. visitedEnd[smaller.EndPosition] = smaller;
  91. }
  92. visitedEnd.Add(current.EndPosition, current);
  93. }
  94. return entry;
  95. }
  96. private static void FillBlock(MemoryManager memory, ExecutionMode mode, Block block)
  97. {
  98. long position = block.Position;
  99. OpCode64 opCode;
  100. do
  101. {
  102. opCode = DecodeOpCode(memory, position, mode);
  103. block.OpCodes.Add(opCode);
  104. position += opCode.OpCodeSizeInBytes;
  105. }
  106. while (!(IsBranch(opCode) || IsException(opCode)));
  107. block.EndPosition = position;
  108. }
  109. private static bool IsBranch(OpCode64 opCode)
  110. {
  111. return opCode is OpCodeBImm64 ||
  112. opCode is OpCodeBReg64 || IsAarch32Branch(opCode);
  113. }
  114. private static bool IsUnconditionalBranch(OpCode64 opCode)
  115. {
  116. return opCode is OpCodeBImmAl64 ||
  117. opCode is OpCodeBReg64 || IsAarch32UnconditionalBranch(opCode);
  118. }
  119. private static bool IsAarch32UnconditionalBranch(OpCode64 opCode)
  120. {
  121. if (!(opCode is OpCode32 op))
  122. {
  123. return false;
  124. }
  125. //Note: On ARM32, most instructions have conditional execution,
  126. //so there's no "Always" (unconditional) branch like on ARM64.
  127. //We need to check if the condition is "Always" instead.
  128. return IsAarch32Branch(op) && op.Cond >= Condition.Al;
  129. }
  130. private static bool IsAarch32Branch(OpCode64 opCode)
  131. {
  132. //Note: On ARM32, most ALU operations can write to R15 (PC),
  133. //so we must consider such operations as a branch in potential aswell.
  134. if (opCode is IOpCode32Alu opAlu && opAlu.Rd == RegisterAlias.Aarch32Pc)
  135. {
  136. return true;
  137. }
  138. //Same thing for memory operations. We have the cases where PC is a target
  139. //register (Rt == 15 or (mask & (1 << 15)) != 0), and cases where there is
  140. //a write back to PC (wback == true && Rn == 15), however the later may
  141. //be "undefined" depending on the CPU, so compilers should not produce that.
  142. if (opCode is IOpCode32Mem || opCode is IOpCode32MemMult)
  143. {
  144. int rt, rn;
  145. bool wBack, isLoad;
  146. if (opCode is IOpCode32Mem opMem)
  147. {
  148. rt = opMem.Rt;
  149. rn = opMem.Rn;
  150. wBack = opMem.WBack;
  151. isLoad = opMem.IsLoad;
  152. //For the dual load, we also need to take into account the
  153. //case were Rt2 == 15 (PC).
  154. if (rt == 14 && opMem.Emitter == InstEmit32.Ldrd)
  155. {
  156. rt = RegisterAlias.Aarch32Pc;
  157. }
  158. }
  159. else if (opCode is IOpCode32MemMult opMemMult)
  160. {
  161. const int pcMask = 1 << RegisterAlias.Aarch32Pc;
  162. rt = (opMemMult.RegisterMask & pcMask) != 0 ? RegisterAlias.Aarch32Pc : 0;
  163. rn = opMemMult.Rn;
  164. wBack = opMemMult.PostOffset != 0;
  165. isLoad = opMemMult.IsLoad;
  166. }
  167. else
  168. {
  169. throw new NotImplementedException($"The type \"{opCode.GetType().Name}\" is not implemented on the decoder.");
  170. }
  171. if ((rt == RegisterAlias.Aarch32Pc && isLoad) ||
  172. (rn == RegisterAlias.Aarch32Pc && wBack))
  173. {
  174. return true;
  175. }
  176. }
  177. //Explicit branch instructions.
  178. return opCode is IOpCode32BImm ||
  179. opCode is IOpCode32BReg;
  180. }
  181. private static bool IsException(OpCode64 opCode)
  182. {
  183. return opCode.Emitter == InstEmit.Brk ||
  184. opCode.Emitter == InstEmit.Svc ||
  185. opCode.Emitter == InstEmit.Und;
  186. }
  187. public static OpCode64 DecodeOpCode(MemoryManager memory, long position, ExecutionMode mode)
  188. {
  189. int opCode = memory.ReadInt32(position);
  190. Inst inst;
  191. if (mode == ExecutionMode.Aarch64)
  192. {
  193. inst = OpCodeTable.GetInstA64(opCode);
  194. }
  195. else
  196. {
  197. if (mode == ExecutionMode.Aarch32Arm)
  198. {
  199. inst = OpCodeTable.GetInstA32(opCode);
  200. }
  201. else /* if (mode == ExecutionMode.Aarch32Thumb) */
  202. {
  203. inst = OpCodeTable.GetInstT32(opCode);
  204. }
  205. }
  206. OpCode64 decodedOpCode = new OpCode64(Inst.Undefined, position, opCode);
  207. if (inst.Type != null)
  208. {
  209. decodedOpCode = MakeOpCode(inst.Type, inst, position, opCode);
  210. }
  211. return decodedOpCode;
  212. }
  213. private static OpCode64 MakeOpCode(Type type, Inst inst, long position, int opCode)
  214. {
  215. if (type == null)
  216. {
  217. throw new ArgumentNullException(nameof(type));
  218. }
  219. OpActivator createInstance = _opActivators.GetOrAdd(type, CacheOpActivator);
  220. return (OpCode64)createInstance(inst, position, opCode);
  221. }
  222. private static OpActivator CacheOpActivator(Type type)
  223. {
  224. Type[] argTypes = new Type[] { typeof(Inst), typeof(long), typeof(int) };
  225. DynamicMethod mthd = new DynamicMethod($"Make{type.Name}", type, argTypes);
  226. ILGenerator generator = mthd.GetILGenerator();
  227. generator.Emit(OpCodes.Ldarg_0);
  228. generator.Emit(OpCodes.Ldarg_1);
  229. generator.Emit(OpCodes.Ldarg_2);
  230. generator.Emit(OpCodes.Newobj, type.GetConstructor(argTypes));
  231. generator.Emit(OpCodes.Ret);
  232. return (OpActivator)mthd.CreateDelegate(typeof(OpActivator));
  233. }
  234. }
  235. }