Decoder.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. using ARMeilleure.Instructions;
  2. using ARMeilleure.Memory;
  3. using ARMeilleure.State;
  4. using System;
  5. using System.Collections.Concurrent;
  6. using System.Collections.Generic;
  7. using System.Reflection.Emit;
  8. namespace ARMeilleure.Decoders
  9. {
  10. static class Decoder
  11. {
  12. private delegate object MakeOp(InstDescriptor inst, ulong address, int opCode);
  13. private static ConcurrentDictionary<Type, MakeOp> _opActivators;
  14. static Decoder()
  15. {
  16. _opActivators = new ConcurrentDictionary<Type, MakeOp>();
  17. }
  18. public static Block[] DecodeBasicBlock(MemoryManager memory, ulong address, ExecutionMode mode)
  19. {
  20. Block block = new Block(address);
  21. FillBlock(memory, mode, block, ulong.MaxValue);
  22. return new Block[] { block };
  23. }
  24. public static Block[] DecodeFunction(MemoryManager memory, ulong address, ExecutionMode mode)
  25. {
  26. List<Block> blocks = new List<Block>();
  27. Queue<Block> workQueue = new Queue<Block>();
  28. Dictionary<ulong, Block> visited = new Dictionary<ulong, Block>();
  29. Block GetBlock(ulong blkAddress)
  30. {
  31. if (!visited.TryGetValue(blkAddress, out Block block))
  32. {
  33. block = new Block(blkAddress);
  34. workQueue.Enqueue(block);
  35. visited.Add(blkAddress, block);
  36. }
  37. return block;
  38. }
  39. GetBlock(address);
  40. while (workQueue.TryDequeue(out Block currBlock))
  41. {
  42. // Check if the current block is inside another block.
  43. if (BinarySearch(blocks, currBlock.Address, out int nBlkIndex))
  44. {
  45. Block nBlock = blocks[nBlkIndex];
  46. if (nBlock.Address == currBlock.Address)
  47. {
  48. throw new InvalidOperationException("Found duplicate block address on the list.");
  49. }
  50. nBlock.Split(currBlock);
  51. blocks.Insert(nBlkIndex + 1, currBlock);
  52. continue;
  53. }
  54. // If we have a block after the current one, set the limit address.
  55. ulong limitAddress = ulong.MaxValue;
  56. if (nBlkIndex != blocks.Count)
  57. {
  58. Block nBlock = blocks[nBlkIndex];
  59. int nextIndex = nBlkIndex + 1;
  60. if (nBlock.Address < currBlock.Address && nextIndex < blocks.Count)
  61. {
  62. limitAddress = blocks[nextIndex].Address;
  63. }
  64. else if (nBlock.Address > currBlock.Address)
  65. {
  66. limitAddress = blocks[nBlkIndex].Address;
  67. }
  68. }
  69. FillBlock(memory, mode, currBlock, limitAddress);
  70. if (currBlock.OpCodes.Count != 0)
  71. {
  72. // Set child blocks. "Branch" is the block the branch instruction
  73. // points to (when taken), "Next" is the block at the next address,
  74. // executed when the branch is not taken. For Unconditional Branches
  75. // (except BL/BLR that are sub calls) or end of executable, Next is null.
  76. OpCode lastOp = currBlock.GetLastOp();
  77. bool isCall = IsCall(lastOp);
  78. if (lastOp is IOpCodeBImm op && !isCall)
  79. {
  80. currBlock.Branch = GetBlock((ulong)op.Immediate);
  81. }
  82. if (!IsUnconditionalBranch(lastOp) /*|| isCall*/)
  83. {
  84. currBlock.Next = GetBlock(currBlock.EndAddress);
  85. }
  86. }
  87. // Insert the new block on the list (sorted by address).
  88. if (blocks.Count != 0)
  89. {
  90. Block nBlock = blocks[nBlkIndex];
  91. blocks.Insert(nBlkIndex + (nBlock.Address < currBlock.Address ? 1 : 0), currBlock);
  92. }
  93. else
  94. {
  95. blocks.Add(currBlock);
  96. }
  97. }
  98. return blocks.ToArray();
  99. }
  100. private static bool BinarySearch(List<Block> blocks, ulong address, out int index)
  101. {
  102. index = 0;
  103. int left = 0;
  104. int right = blocks.Count - 1;
  105. while (left <= right)
  106. {
  107. int size = right - left;
  108. int middle = left + (size >> 1);
  109. Block block = blocks[middle];
  110. index = middle;
  111. if (address >= block.Address && address < block.EndAddress)
  112. {
  113. return true;
  114. }
  115. if (address < block.Address)
  116. {
  117. right = middle - 1;
  118. }
  119. else
  120. {
  121. left = middle + 1;
  122. }
  123. }
  124. return false;
  125. }
  126. private static void FillBlock(
  127. MemoryManager memory,
  128. ExecutionMode mode,
  129. Block block,
  130. ulong limitAddress)
  131. {
  132. ulong address = block.Address;
  133. OpCode opCode;
  134. do
  135. {
  136. if (address >= limitAddress)
  137. {
  138. break;
  139. }
  140. opCode = DecodeOpCode(memory, address, mode);
  141. block.OpCodes.Add(opCode);
  142. address += (ulong)opCode.OpCodeSizeInBytes;
  143. }
  144. while (!(IsBranch(opCode) || IsException(opCode)));
  145. block.EndAddress = address;
  146. }
  147. private static bool IsBranch(OpCode opCode)
  148. {
  149. return opCode is OpCodeBImm ||
  150. opCode is OpCodeBReg || IsAarch32Branch(opCode);
  151. }
  152. private static bool IsUnconditionalBranch(OpCode opCode)
  153. {
  154. return opCode is OpCodeBImmAl ||
  155. opCode is OpCodeBReg || IsAarch32UnconditionalBranch(opCode);
  156. }
  157. private static bool IsAarch32UnconditionalBranch(OpCode opCode)
  158. {
  159. if (!(opCode is OpCode32 op))
  160. {
  161. return false;
  162. }
  163. // Note: On ARM32, most instructions have conditional execution,
  164. // so there's no "Always" (unconditional) branch like on ARM64.
  165. // We need to check if the condition is "Always" instead.
  166. return IsAarch32Branch(op) && op.Cond >= Condition.Al;
  167. }
  168. private static bool IsAarch32Branch(OpCode opCode)
  169. {
  170. // Note: On ARM32, most ALU operations can write to R15 (PC),
  171. // so we must consider such operations as a branch in potential aswell.
  172. if (opCode is IOpCode32Alu opAlu && opAlu.Rd == RegisterAlias.Aarch32Pc)
  173. {
  174. return true;
  175. }
  176. // Same thing for memory operations. We have the cases where PC is a target
  177. // register (Rt == 15 or (mask & (1 << 15)) != 0), and cases where there is
  178. // a write back to PC (wback == true && Rn == 15), however the later may
  179. // be "undefined" depending on the CPU, so compilers should not produce that.
  180. if (opCode is IOpCode32Mem || opCode is IOpCode32MemMult)
  181. {
  182. int rt, rn;
  183. bool wBack, isLoad;
  184. if (opCode is IOpCode32Mem opMem)
  185. {
  186. rt = opMem.Rt;
  187. rn = opMem.Rn;
  188. wBack = opMem.WBack;
  189. isLoad = opMem.IsLoad;
  190. // For the dual load, we also need to take into account the
  191. // case were Rt2 == 15 (PC).
  192. if (rt == 14 && opMem.Instruction.Name == InstName.Ldrd)
  193. {
  194. rt = RegisterAlias.Aarch32Pc;
  195. }
  196. }
  197. else if (opCode is IOpCode32MemMult opMemMult)
  198. {
  199. const int pcMask = 1 << RegisterAlias.Aarch32Pc;
  200. rt = (opMemMult.RegisterMask & pcMask) != 0 ? RegisterAlias.Aarch32Pc : 0;
  201. rn = opMemMult.Rn;
  202. wBack = opMemMult.PostOffset != 0;
  203. isLoad = opMemMult.IsLoad;
  204. }
  205. else
  206. {
  207. throw new NotImplementedException($"The type \"{opCode.GetType().Name}\" is not implemented on the decoder.");
  208. }
  209. if ((rt == RegisterAlias.Aarch32Pc && isLoad) ||
  210. (rn == RegisterAlias.Aarch32Pc && wBack))
  211. {
  212. return true;
  213. }
  214. }
  215. // Explicit branch instructions.
  216. return opCode is IOpCode32BImm ||
  217. opCode is IOpCode32BReg;
  218. }
  219. private static bool IsCall(OpCode opCode)
  220. {
  221. // TODO (CQ): ARM32 support.
  222. return opCode.Instruction.Name == InstName.Bl ||
  223. opCode.Instruction.Name == InstName.Blr;
  224. }
  225. private static bool IsException(OpCode opCode)
  226. {
  227. return opCode.Instruction.Name == InstName.Brk ||
  228. opCode.Instruction.Name == InstName.Svc ||
  229. opCode.Instruction.Name == InstName.Und;
  230. }
  231. public static OpCode DecodeOpCode(MemoryManager memory, ulong address, ExecutionMode mode)
  232. {
  233. int opCode = memory.ReadInt32((long)address);
  234. InstDescriptor inst;
  235. Type type;
  236. if (mode == ExecutionMode.Aarch64)
  237. {
  238. (inst, type) = OpCodeTable.GetInstA64(opCode);
  239. }
  240. else
  241. {
  242. if (mode == ExecutionMode.Aarch32Arm)
  243. {
  244. (inst, type) = OpCodeTable.GetInstA32(opCode);
  245. }
  246. else /* if (mode == ExecutionMode.Aarch32Thumb) */
  247. {
  248. (inst, type) = OpCodeTable.GetInstT32(opCode);
  249. }
  250. }
  251. if (type != null)
  252. {
  253. return MakeOpCode(inst, type, address, opCode);
  254. }
  255. else
  256. {
  257. return new OpCode(inst, address, opCode);
  258. }
  259. }
  260. private static OpCode MakeOpCode(InstDescriptor inst, Type type, ulong address, int opCode)
  261. {
  262. MakeOp createInstance = _opActivators.GetOrAdd(type, CacheOpActivator);
  263. return (OpCode)createInstance(inst, address, opCode);
  264. }
  265. private static MakeOp CacheOpActivator(Type type)
  266. {
  267. Type[] argTypes = new Type[] { typeof(InstDescriptor), typeof(ulong), typeof(int) };
  268. DynamicMethod mthd = new DynamicMethod($"Make{type.Name}", type, argTypes);
  269. ILGenerator generator = mthd.GetILGenerator();
  270. generator.Emit(OpCodes.Ldarg_0);
  271. generator.Emit(OpCodes.Ldarg_1);
  272. generator.Emit(OpCodes.Ldarg_2);
  273. generator.Emit(OpCodes.Newobj, type.GetConstructor(argTypes));
  274. generator.Emit(OpCodes.Ret);
  275. return (MakeOp)mthd.CreateDelegate(typeof(MakeOp));
  276. }
  277. }
  278. }