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