GraphBuilder.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. //===- GraphBuilder.cpp -----------------------------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "GraphBuilder.h"
  9. #include "llvm/BinaryFormat/ELF.h"
  10. #include "llvm/MC/MCAsmInfo.h"
  11. #include "llvm/MC/MCContext.h"
  12. #include "llvm/MC/MCDisassembler/MCDisassembler.h"
  13. #include "llvm/MC/MCInst.h"
  14. #include "llvm/MC/MCInstPrinter.h"
  15. #include "llvm/MC/MCInstrAnalysis.h"
  16. #include "llvm/MC/MCInstrDesc.h"
  17. #include "llvm/MC/MCInstrInfo.h"
  18. #include "llvm/MC/MCObjectFileInfo.h"
  19. #include "llvm/MC/MCRegisterInfo.h"
  20. #include "llvm/MC/MCSubtargetInfo.h"
  21. #include "llvm/MC/TargetRegistry.h"
  22. #include "llvm/Object/Binary.h"
  23. #include "llvm/Object/COFF.h"
  24. #include "llvm/Object/ELFObjectFile.h"
  25. #include "llvm/Object/ObjectFile.h"
  26. #include "llvm/Support/Casting.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/Error.h"
  29. #include "llvm/Support/MemoryBuffer.h"
  30. #include "llvm/Support/TargetSelect.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. using Instr = llvm::cfi_verify::FileAnalysis::Instr;
  33. namespace llvm {
  34. namespace cfi_verify {
  35. uint64_t SearchLengthForUndef;
  36. uint64_t SearchLengthForConditionalBranch;
  37. static cl::opt<uint64_t, true> SearchLengthForUndefArg(
  38. "search-length-undef",
  39. cl::desc("Specify the maximum amount of instructions "
  40. "to inspect when searching for an undefined "
  41. "instruction from a conditional branch."),
  42. cl::location(SearchLengthForUndef), cl::init(2));
  43. static cl::opt<uint64_t, true> SearchLengthForConditionalBranchArg(
  44. "search-length-cb",
  45. cl::desc("Specify the maximum amount of instructions "
  46. "to inspect when searching for a conditional "
  47. "branch from an indirect control flow."),
  48. cl::location(SearchLengthForConditionalBranch), cl::init(20));
  49. std::vector<uint64_t> GraphResult::flattenAddress(uint64_t Address) const {
  50. std::vector<uint64_t> Addresses;
  51. auto It = IntermediateNodes.find(Address);
  52. Addresses.push_back(Address);
  53. while (It != IntermediateNodes.end()) {
  54. Addresses.push_back(It->second);
  55. It = IntermediateNodes.find(It->second);
  56. }
  57. return Addresses;
  58. }
  59. void printPairToDOT(const FileAnalysis &Analysis, raw_ostream &OS,
  60. uint64_t From, uint64_t To) {
  61. OS << " \"" << format_hex(From, 2) << ": ";
  62. Analysis.printInstruction(Analysis.getInstructionOrDie(From), OS);
  63. OS << "\" -> \"" << format_hex(To, 2) << ": ";
  64. Analysis.printInstruction(Analysis.getInstructionOrDie(To), OS);
  65. OS << "\"\n";
  66. }
  67. void GraphResult::printToDOT(const FileAnalysis &Analysis,
  68. raw_ostream &OS) const {
  69. std::map<uint64_t, uint64_t> SortedIntermediateNodes(
  70. IntermediateNodes.begin(), IntermediateNodes.end());
  71. OS << "digraph graph_" << format_hex(BaseAddress, 2) << " {\n";
  72. for (const auto &KV : SortedIntermediateNodes)
  73. printPairToDOT(Analysis, OS, KV.first, KV.second);
  74. for (auto &BranchNode : ConditionalBranchNodes) {
  75. for (auto &V : {BranchNode.Target, BranchNode.Fallthrough})
  76. printPairToDOT(Analysis, OS, BranchNode.Address, V);
  77. }
  78. OS << "}\n";
  79. }
  80. GraphResult GraphBuilder::buildFlowGraph(const FileAnalysis &Analysis,
  81. object::SectionedAddress Address) {
  82. GraphResult Result;
  83. Result.BaseAddress = Address.Address;
  84. DenseSet<uint64_t> OpenedNodes;
  85. const auto &IndirectInstructions = Analysis.getIndirectInstructions();
  86. // check that IndirectInstructions contains specified Address
  87. if (IndirectInstructions.find(Address) == IndirectInstructions.end()) {
  88. return Result;
  89. }
  90. buildFlowGraphImpl(Analysis, OpenedNodes, Result, Address.Address, 0);
  91. return Result;
  92. }
  93. void GraphBuilder::buildFlowsToUndefined(const FileAnalysis &Analysis,
  94. GraphResult &Result,
  95. ConditionalBranchNode &BranchNode,
  96. const Instr &BranchInstrMeta) {
  97. assert(SearchLengthForUndef > 0 &&
  98. "Search length for undefined flow must be greater than zero.");
  99. // Start setting up the next node in the block.
  100. uint64_t NextAddress = 0;
  101. const Instr *NextMetaPtr;
  102. // Find out the next instruction in the block and add it to the new
  103. // node.
  104. if (BranchNode.Target && !BranchNode.Fallthrough) {
  105. // We know the target of the branch, find the fallthrough.
  106. NextMetaPtr = Analysis.getNextInstructionSequential(BranchInstrMeta);
  107. if (!NextMetaPtr) {
  108. errs() << "Failed to get next instruction from "
  109. << format_hex(BranchNode.Address, 2) << ".\n";
  110. return;
  111. }
  112. NextAddress = NextMetaPtr->VMAddress;
  113. BranchNode.Fallthrough =
  114. NextMetaPtr->VMAddress; // Add the new node to the branch head.
  115. } else if (BranchNode.Fallthrough && !BranchNode.Target) {
  116. // We already know the fallthrough, evaluate the target.
  117. uint64_t Target;
  118. if (!Analysis.getMCInstrAnalysis()->evaluateBranch(
  119. BranchInstrMeta.Instruction, BranchInstrMeta.VMAddress,
  120. BranchInstrMeta.InstructionSize, Target)) {
  121. errs() << "Failed to get branch target for conditional branch at address "
  122. << format_hex(BranchInstrMeta.VMAddress, 2) << ".\n";
  123. return;
  124. }
  125. // Resolve the meta pointer for the target of this branch.
  126. NextMetaPtr = Analysis.getInstruction(Target);
  127. if (!NextMetaPtr) {
  128. errs() << "Failed to find instruction at address "
  129. << format_hex(Target, 2) << ".\n";
  130. return;
  131. }
  132. NextAddress = Target;
  133. BranchNode.Target =
  134. NextMetaPtr->VMAddress; // Add the new node to the branch head.
  135. } else {
  136. errs() << "ControlBranchNode supplied to buildFlowsToUndefined should "
  137. "provide Target xor Fallthrough.\n";
  138. return;
  139. }
  140. uint64_t CurrentAddress = NextAddress;
  141. const Instr *CurrentMetaPtr = NextMetaPtr;
  142. // Now the branch head has been set properly, complete the rest of the block.
  143. for (uint64_t i = 1; i < SearchLengthForUndef; ++i) {
  144. // Check to see whether the block should die.
  145. if (Analysis.isCFITrap(*CurrentMetaPtr)) {
  146. BranchNode.CFIProtection = true;
  147. return;
  148. }
  149. // Find the metadata of the next instruction.
  150. NextMetaPtr = Analysis.getDefiniteNextInstruction(*CurrentMetaPtr);
  151. if (!NextMetaPtr)
  152. return;
  153. // Setup the next node.
  154. NextAddress = NextMetaPtr->VMAddress;
  155. // Add this as an intermediate.
  156. Result.IntermediateNodes[CurrentAddress] = NextAddress;
  157. // Move the 'current' pointers to the new tail of the block.
  158. CurrentMetaPtr = NextMetaPtr;
  159. CurrentAddress = NextAddress;
  160. }
  161. // Final check of the last thing we added to the block.
  162. if (Analysis.isCFITrap(*CurrentMetaPtr))
  163. BranchNode.CFIProtection = true;
  164. }
  165. void GraphBuilder::buildFlowGraphImpl(const FileAnalysis &Analysis,
  166. DenseSet<uint64_t> &OpenedNodes,
  167. GraphResult &Result, uint64_t Address,
  168. uint64_t Depth) {
  169. // If we've exceeded the flow length, terminate.
  170. if (Depth >= SearchLengthForConditionalBranch) {
  171. Result.OrphanedNodes.push_back(Address);
  172. return;
  173. }
  174. // Ensure this flow is acyclic.
  175. if (OpenedNodes.count(Address))
  176. Result.OrphanedNodes.push_back(Address);
  177. // If this flow is already explored, stop here.
  178. if (Result.IntermediateNodes.count(Address))
  179. return;
  180. // Get the metadata for the node instruction.
  181. const auto &InstrMetaPtr = Analysis.getInstruction(Address);
  182. if (!InstrMetaPtr) {
  183. errs() << "Failed to build flow graph for instruction at address "
  184. << format_hex(Address, 2) << ".\n";
  185. Result.OrphanedNodes.push_back(Address);
  186. return;
  187. }
  188. const auto &ChildMeta = *InstrMetaPtr;
  189. OpenedNodes.insert(Address);
  190. std::set<const Instr *> CFCrossRefs =
  191. Analysis.getDirectControlFlowXRefs(ChildMeta);
  192. bool HasValidCrossRef = false;
  193. for (const auto *ParentMetaPtr : CFCrossRefs) {
  194. assert(ParentMetaPtr && "CFCrossRefs returned nullptr.");
  195. const auto &ParentMeta = *ParentMetaPtr;
  196. const auto &ParentDesc =
  197. Analysis.getMCInstrInfo()->get(ParentMeta.Instruction.getOpcode());
  198. if (!ParentDesc.mayAffectControlFlow(ParentMeta.Instruction,
  199. *Analysis.getRegisterInfo())) {
  200. // If this cross reference doesn't affect CF, continue the graph.
  201. buildFlowGraphImpl(Analysis, OpenedNodes, Result, ParentMeta.VMAddress,
  202. Depth + 1);
  203. Result.IntermediateNodes[ParentMeta.VMAddress] = Address;
  204. HasValidCrossRef = true;
  205. continue;
  206. }
  207. // Call instructions are not valid in the upwards traversal.
  208. if (ParentDesc.isCall()) {
  209. Result.IntermediateNodes[ParentMeta.VMAddress] = Address;
  210. Result.OrphanedNodes.push_back(ParentMeta.VMAddress);
  211. continue;
  212. }
  213. // Evaluate the branch target to ascertain whether this XRef is the result
  214. // of a fallthrough or the target of a branch.
  215. uint64_t BranchTarget;
  216. if (!Analysis.getMCInstrAnalysis()->evaluateBranch(
  217. ParentMeta.Instruction, ParentMeta.VMAddress,
  218. ParentMeta.InstructionSize, BranchTarget)) {
  219. errs() << "Failed to evaluate branch target for instruction at address "
  220. << format_hex(ParentMeta.VMAddress, 2) << ".\n";
  221. Result.IntermediateNodes[ParentMeta.VMAddress] = Address;
  222. Result.OrphanedNodes.push_back(ParentMeta.VMAddress);
  223. continue;
  224. }
  225. // Allow unconditional branches to be part of the upwards traversal.
  226. if (ParentDesc.isUnconditionalBranch()) {
  227. // Ensures that the unconditional branch is actually an XRef to the child.
  228. if (BranchTarget != Address) {
  229. errs() << "Control flow to " << format_hex(Address, 2)
  230. << ", but target resolution of "
  231. << format_hex(ParentMeta.VMAddress, 2)
  232. << " is not this address?\n";
  233. Result.IntermediateNodes[ParentMeta.VMAddress] = Address;
  234. Result.OrphanedNodes.push_back(ParentMeta.VMAddress);
  235. continue;
  236. }
  237. buildFlowGraphImpl(Analysis, OpenedNodes, Result, ParentMeta.VMAddress,
  238. Depth + 1);
  239. Result.IntermediateNodes[ParentMeta.VMAddress] = Address;
  240. HasValidCrossRef = true;
  241. continue;
  242. }
  243. // Ensure that any unknown CFs are caught.
  244. if (!ParentDesc.isConditionalBranch()) {
  245. errs() << "Unknown control flow encountered when building graph at "
  246. << format_hex(Address, 2) << "\n.";
  247. Result.IntermediateNodes[ParentMeta.VMAddress] = Address;
  248. Result.OrphanedNodes.push_back(ParentMeta.VMAddress);
  249. continue;
  250. }
  251. // Only direct conditional branches should be present at this point. Setup
  252. // a conditional branch node and build flows to the ud2.
  253. ConditionalBranchNode BranchNode;
  254. BranchNode.Address = ParentMeta.VMAddress;
  255. BranchNode.Target = 0;
  256. BranchNode.Fallthrough = 0;
  257. BranchNode.CFIProtection = false;
  258. BranchNode.IndirectCFIsOnTargetPath = (BranchTarget == Address);
  259. if (BranchTarget == Address)
  260. BranchNode.Target = Address;
  261. else
  262. BranchNode.Fallthrough = Address;
  263. HasValidCrossRef = true;
  264. buildFlowsToUndefined(Analysis, Result, BranchNode, ParentMeta);
  265. Result.ConditionalBranchNodes.push_back(BranchNode);
  266. }
  267. // When using cross-DSO, some indirect calls are not guarded by a branch to a
  268. // trap but instead follow a call to __cfi_slowpath. For example:
  269. // if (!InlinedFastCheck(f))
  270. // call *f
  271. // else {
  272. // __cfi_slowpath(CallSiteTypeId, f);
  273. // call *f
  274. // }
  275. // To mark the second call as protected, we recognize indirect calls that
  276. // directly follow calls to functions that will trap on CFI violations.
  277. if (CFCrossRefs.empty()) {
  278. const Instr *PrevInstr = Analysis.getPrevInstructionSequential(ChildMeta);
  279. if (PrevInstr && Analysis.willTrapOnCFIViolation(*PrevInstr)) {
  280. Result.IntermediateNodes[PrevInstr->VMAddress] = Address;
  281. HasValidCrossRef = true;
  282. }
  283. }
  284. if (!HasValidCrossRef)
  285. Result.OrphanedNodes.push_back(Address);
  286. OpenedNodes.erase(Address);
  287. }
  288. } // namespace cfi_verify
  289. } // namespace llvm