CrossDSOCFI.cpp 5.8 KB

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