CrossDSOCFI.cpp 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. //===-- CrossDSOCFI.cpp - Externalize this module's CFI checks ------------===//
  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. //
  9. // This pass exports all llvm.bitset's found in the module in the form of a
  10. // __cfi_check function, which can be used to verify cross-DSO call targets.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/IPO/CrossDSOCFI.h"
  14. #include "llvm/ADT/SetVector.h"
  15. #include "llvm/ADT/Statistic.h"
  16. #include "llvm/ADT/Triple.h"
  17. #include "llvm/IR/Constant.h"
  18. #include "llvm/IR/Constants.h"
  19. #include "llvm/IR/Function.h"
  20. #include "llvm/IR/GlobalObject.h"
  21. #include "llvm/IR/GlobalVariable.h"
  22. #include "llvm/IR/IRBuilder.h"
  23. #include "llvm/IR/Instructions.h"
  24. #include "llvm/IR/Intrinsics.h"
  25. #include "llvm/IR/MDBuilder.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/IR/Operator.h"
  28. #include "llvm/InitializePasses.h"
  29. #include "llvm/Pass.h"
  30. #include "llvm/Support/Debug.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include "llvm/Transforms/IPO.h"
  33. using namespace llvm;
  34. #define DEBUG_TYPE "cross-dso-cfi"
  35. STATISTIC(NumTypeIds, "Number of unique type identifiers");
  36. namespace {
  37. struct CrossDSOCFI : public ModulePass {
  38. static char ID;
  39. CrossDSOCFI() : ModulePass(ID) {
  40. initializeCrossDSOCFIPass(*PassRegistry::getPassRegistry());
  41. }
  42. MDNode *VeryLikelyWeights;
  43. ConstantInt *extractNumericTypeId(MDNode *MD);
  44. void buildCFICheck(Module &M);
  45. bool runOnModule(Module &M) override;
  46. };
  47. } // anonymous namespace
  48. INITIALIZE_PASS_BEGIN(CrossDSOCFI, "cross-dso-cfi", "Cross-DSO CFI", false,
  49. false)
  50. INITIALIZE_PASS_END(CrossDSOCFI, "cross-dso-cfi", "Cross-DSO CFI", false, false)
  51. char CrossDSOCFI::ID = 0;
  52. ModulePass *llvm::createCrossDSOCFIPass() { return new CrossDSOCFI; }
  53. /// Extracts a numeric type identifier from an MDNode containing type metadata.
  54. ConstantInt *CrossDSOCFI::extractNumericTypeId(MDNode *MD) {
  55. // This check excludes vtables for classes inside anonymous namespaces.
  56. auto TM = dyn_cast<ValueAsMetadata>(MD->getOperand(1));
  57. if (!TM)
  58. return nullptr;
  59. auto C = dyn_cast_or_null<ConstantInt>(TM->getValue());
  60. if (!C) return nullptr;
  61. // We are looking for i64 constants.
  62. if (C->getBitWidth() != 64) return nullptr;
  63. return C;
  64. }
  65. /// buildCFICheck - emits __cfi_check for the current module.
  66. void CrossDSOCFI::buildCFICheck(Module &M) {
  67. // FIXME: verify that __cfi_check ends up near the end of the code section,
  68. // but before the jump slots created in LowerTypeTests.
  69. SetVector<uint64_t> TypeIds;
  70. SmallVector<MDNode *, 2> Types;
  71. for (GlobalObject &GO : M.global_objects()) {
  72. Types.clear();
  73. GO.getMetadata(LLVMContext::MD_type, Types);
  74. for (MDNode *Type : Types)
  75. if (ConstantInt *TypeId = extractNumericTypeId(Type))
  76. TypeIds.insert(TypeId->getZExtValue());
  77. }
  78. NamedMDNode *CfiFunctionsMD = M.getNamedMetadata("cfi.functions");
  79. if (CfiFunctionsMD) {
  80. for (auto Func : CfiFunctionsMD->operands()) {
  81. assert(Func->getNumOperands() >= 2);
  82. for (unsigned I = 2; I < Func->getNumOperands(); ++I)
  83. if (ConstantInt *TypeId =
  84. extractNumericTypeId(cast<MDNode>(Func->getOperand(I).get())))
  85. TypeIds.insert(TypeId->getZExtValue());
  86. }
  87. }
  88. LLVMContext &Ctx = M.getContext();
  89. FunctionCallee C = M.getOrInsertFunction(
  90. "__cfi_check", Type::getVoidTy(Ctx), Type::getInt64Ty(Ctx),
  91. Type::getInt8PtrTy(Ctx), Type::getInt8PtrTy(Ctx));
  92. Function *F = cast<Function>(C.getCallee());
  93. // Take over the existing function. The frontend emits a weak stub so that the
  94. // linker knows about the symbol; this pass replaces the function body.
  95. F->deleteBody();
  96. F->setAlignment(Align(4096));
  97. Triple T(M.getTargetTriple());
  98. if (T.isARM() || T.isThumb())
  99. F->addFnAttr("target-features", "+thumb-mode");
  100. auto args = F->arg_begin();
  101. Value &CallSiteTypeId = *(args++);
  102. CallSiteTypeId.setName("CallSiteTypeId");
  103. Value &Addr = *(args++);
  104. Addr.setName("Addr");
  105. Value &CFICheckFailData = *(args++);
  106. CFICheckFailData.setName("CFICheckFailData");
  107. assert(args == F->arg_end());
  108. BasicBlock *BB = BasicBlock::Create(Ctx, "entry", F);
  109. BasicBlock *ExitBB = BasicBlock::Create(Ctx, "exit", F);
  110. BasicBlock *TrapBB = BasicBlock::Create(Ctx, "fail", F);
  111. IRBuilder<> IRBFail(TrapBB);
  112. FunctionCallee CFICheckFailFn =
  113. M.getOrInsertFunction("__cfi_check_fail", Type::getVoidTy(Ctx),
  114. Type::getInt8PtrTy(Ctx), Type::getInt8PtrTy(Ctx));
  115. IRBFail.CreateCall(CFICheckFailFn, {&CFICheckFailData, &Addr});
  116. IRBFail.CreateBr(ExitBB);
  117. IRBuilder<> IRBExit(ExitBB);
  118. IRBExit.CreateRetVoid();
  119. IRBuilder<> IRB(BB);
  120. SwitchInst *SI = IRB.CreateSwitch(&CallSiteTypeId, TrapBB, TypeIds.size());
  121. for (uint64_t TypeId : TypeIds) {
  122. ConstantInt *CaseTypeId = ConstantInt::get(Type::getInt64Ty(Ctx), TypeId);
  123. BasicBlock *TestBB = BasicBlock::Create(Ctx, "test", F);
  124. IRBuilder<> IRBTest(TestBB);
  125. Function *BitsetTestFn = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
  126. Value *Test = IRBTest.CreateCall(
  127. BitsetTestFn, {&Addr, MetadataAsValue::get(
  128. Ctx, ConstantAsMetadata::get(CaseTypeId))});
  129. BranchInst *BI = IRBTest.CreateCondBr(Test, ExitBB, TrapBB);
  130. BI->setMetadata(LLVMContext::MD_prof, VeryLikelyWeights);
  131. SI->addCase(CaseTypeId, TestBB);
  132. ++NumTypeIds;
  133. }
  134. }
  135. bool CrossDSOCFI::runOnModule(Module &M) {
  136. VeryLikelyWeights =
  137. MDBuilder(M.getContext()).createBranchWeights((1U << 20) - 1, 1);
  138. if (M.getModuleFlag("Cross-DSO CFI") == nullptr)
  139. return false;
  140. buildCFICheck(M);
  141. return true;
  142. }
  143. PreservedAnalyses CrossDSOCFIPass::run(Module &M, ModuleAnalysisManager &AM) {
  144. CrossDSOCFI Impl;
  145. bool Changed = Impl.runOnModule(M);
  146. if (!Changed)
  147. return PreservedAnalyses::all();
  148. return PreservedAnalyses::none();
  149. }