LLVM  10.0.0svn
CrossDSOCFI.cpp
Go to the documentation of this file.
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 
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/IR/Constant.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/GlobalObject.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/MDBuilder.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/Debug.h"
32 #include "llvm/Transforms/IPO.h"
33 
34 using namespace llvm;
35 
36 #define DEBUG_TYPE "cross-dso-cfi"
37 
38 STATISTIC(NumTypeIds, "Number of unique type identifiers");
39 
40 namespace {
41 
42 struct CrossDSOCFI : public ModulePass {
43  static char ID;
44  CrossDSOCFI() : ModulePass(ID) {
46  }
47 
48  MDNode *VeryLikelyWeights;
49 
50  ConstantInt *extractNumericTypeId(MDNode *MD);
51  void buildCFICheck(Module &M);
52  bool runOnModule(Module &M) override;
53 };
54 
55 } // anonymous namespace
56 
57 INITIALIZE_PASS_BEGIN(CrossDSOCFI, "cross-dso-cfi", "Cross-DSO CFI", false,
58  false)
59 INITIALIZE_PASS_END(CrossDSOCFI, "cross-dso-cfi", "Cross-DSO CFI", false, false)
60 char CrossDSOCFI::ID = 0;
61 
62 ModulePass *llvm::createCrossDSOCFIPass() { return new CrossDSOCFI; }
63 
64 /// Extracts a numeric type identifier from an MDNode containing type metadata.
65 ConstantInt *CrossDSOCFI::extractNumericTypeId(MDNode *MD) {
66  // This check excludes vtables for classes inside anonymous namespaces.
67  auto TM = dyn_cast<ValueAsMetadata>(MD->getOperand(1));
68  if (!TM)
69  return nullptr;
70  auto C = dyn_cast_or_null<ConstantInt>(TM->getValue());
71  if (!C) return nullptr;
72  // We are looking for i64 constants.
73  if (C->getBitWidth() != 64) return nullptr;
74 
75  return C;
76 }
77 
78 /// buildCFICheck - emits __cfi_check for the current module.
79 void CrossDSOCFI::buildCFICheck(Module &M) {
80  // FIXME: verify that __cfi_check ends up near the end of the code section,
81  // but before the jump slots created in LowerTypeTests.
82  SetVector<uint64_t> TypeIds;
84  for (GlobalObject &GO : M.global_objects()) {
85  Types.clear();
86  GO.getMetadata(LLVMContext::MD_type, Types);
87  for (MDNode *Type : Types)
88  if (ConstantInt *TypeId = extractNumericTypeId(Type))
89  TypeIds.insert(TypeId->getZExtValue());
90  }
91 
92  NamedMDNode *CfiFunctionsMD = M.getNamedMetadata("cfi.functions");
93  if (CfiFunctionsMD) {
94  for (auto Func : CfiFunctionsMD->operands()) {
95  assert(Func->getNumOperands() >= 2);
96  for (unsigned I = 2; I < Func->getNumOperands(); ++I)
97  if (ConstantInt *TypeId =
98  extractNumericTypeId(cast<MDNode>(Func->getOperand(I).get())))
99  TypeIds.insert(TypeId->getZExtValue());
100  }
101  }
102 
103  LLVMContext &Ctx = M.getContext();
105  "__cfi_check", Type::getVoidTy(Ctx), Type::getInt64Ty(Ctx),
108  // Take over the existing function. The frontend emits a weak stub so that the
109  // linker knows about the symbol; this pass replaces the function body.
110  F->deleteBody();
111  F->setAlignment(4096);
112 
113  Triple T(M.getTargetTriple());
114  if (T.isARM() || T.isThumb())
115  F->addFnAttr("target-features", "+thumb-mode");
116 
117  auto args = F->arg_begin();
118  Value &CallSiteTypeId = *(args++);
119  CallSiteTypeId.setName("CallSiteTypeId");
120  Value &Addr = *(args++);
121  Addr.setName("Addr");
122  Value &CFICheckFailData = *(args++);
123  CFICheckFailData.setName("CFICheckFailData");
124  assert(args == F->arg_end());
125 
126  BasicBlock *BB = BasicBlock::Create(Ctx, "entry", F);
127  BasicBlock *ExitBB = BasicBlock::Create(Ctx, "exit", F);
128 
129  BasicBlock *TrapBB = BasicBlock::Create(Ctx, "fail", F);
130  IRBuilder<> IRBFail(TrapBB);
131  FunctionCallee CFICheckFailFn =
132  M.getOrInsertFunction("__cfi_check_fail", Type::getVoidTy(Ctx),
134  IRBFail.CreateCall(CFICheckFailFn, {&CFICheckFailData, &Addr});
135  IRBFail.CreateBr(ExitBB);
136 
137  IRBuilder<> IRBExit(ExitBB);
138  IRBExit.CreateRetVoid();
139 
140  IRBuilder<> IRB(BB);
141  SwitchInst *SI = IRB.CreateSwitch(&CallSiteTypeId, TrapBB, TypeIds.size());
142  for (uint64_t TypeId : TypeIds) {
143  ConstantInt *CaseTypeId = ConstantInt::get(Type::getInt64Ty(Ctx), TypeId);
144  BasicBlock *TestBB = BasicBlock::Create(Ctx, "test", F);
145  IRBuilder<> IRBTest(TestBB);
146  Function *BitsetTestFn = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
147 
148  Value *Test = IRBTest.CreateCall(
149  BitsetTestFn, {&Addr, MetadataAsValue::get(
150  Ctx, ConstantAsMetadata::get(CaseTypeId))});
151  BranchInst *BI = IRBTest.CreateCondBr(Test, ExitBB, TrapBB);
152  BI->setMetadata(LLVMContext::MD_prof, VeryLikelyWeights);
153 
154  SI->addCase(CaseTypeId, TestBB);
155  ++NumTypeIds;
156  }
157 }
158 
159 bool CrossDSOCFI::runOnModule(Module &M) {
160  VeryLikelyWeights =
161  MDBuilder(M.getContext()).createBranchWeights((1U << 20) - 1, 1);
162  if (M.getModuleFlag("Cross-DSO CFI") == nullptr)
163  return false;
164  buildCFICheck(M);
165  return true;
166 }
167 
169  CrossDSOCFI Impl;
170  bool Changed = Impl.runOnModule(M);
171  if (!Changed)
172  return PreservedAnalyses::all();
173  return PreservedAnalyses::none();
174 }
uint64_t CallInst * C
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:240
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents lattice values for constants.
Definition: AllocatorList.h:23
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:77
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:165
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
arg_iterator arg_end()
Definition: Function.h:704
STATISTIC(NumFunctions, "Total number of functions")
Metadata node.
Definition: Metadata.h:863
F(f)
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1068
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:176
void setAlignment(unsigned Align)
FIXME: Remove this setter once the migration to MaybeAlign is over.
Definition: Globals.cpp:116
iterator_range< global_object_iterator > global_objects()
Definition: Module.h:662
A tuple of MDNodes.
Definition: Metadata.h:1325
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:244
ModulePass * createCrossDSOCFIPass()
This pass export CFI checks for use by external modules.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:779
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:285
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:141
void initializeCrossDSOCFIPass(PassRegistry &)
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:250
Value wrapper in the Metadata hierarchy.
Definition: Metadata.h:338
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:409
iterator_range< op_iterator > operands()
Definition: Metadata.h:1417
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1043
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:156
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:105
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
Conditional or Unconditional Branch instruction.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition: Module.cpp:310
void deleteBody()
deleteBody - This method deletes the body of the function, and converts the linkage to external...
Definition: Function.h:633
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:160
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:99
arg_iterator arg_begin()
Definition: Function.h:695
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:219
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1222
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Module.h This file contains the declarations for the Module class.
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:47
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:638
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:143
#define I(x, y, z)
Definition: MD5.cpp:58
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:224
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
Multiway switch.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
A vector that has set insertion semantics.
Definition: SetVector.h:40
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.h:229
A container for analyses that lazily runs them and caches their results.