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