LLVM  4.0.0
CrossDSOCFI.cpp
Go to the documentation of this file.
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 
16 #include "llvm/ADT/DenseSet.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"
33 #include "llvm/Transforms/IPO.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) {
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.
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  LLVMContext &Ctx = M.getContext();
100  "__cfi_check", Type::getVoidTy(Ctx), Type::getInt64Ty(Ctx),
101  Type::getInt8PtrTy(Ctx), Type::getInt8PtrTy(Ctx), nullptr);
103  F->setAlignment(4096);
104  auto args = F->arg_begin();
105  Value &CallSiteTypeId = *(args++);
106  CallSiteTypeId.setName("CallSiteTypeId");
107  Value &Addr = *(args++);
108  Addr.setName("Addr");
109  Value &CFICheckFailData = *(args++);
110  CFICheckFailData.setName("CFICheckFailData");
111  assert(args == F->arg_end());
112 
113  BasicBlock *BB = BasicBlock::Create(Ctx, "entry", F);
114  BasicBlock *ExitBB = BasicBlock::Create(Ctx, "exit", F);
115 
116  BasicBlock *TrapBB = BasicBlock::Create(Ctx, "fail", F);
117  IRBuilder<> IRBFail(TrapBB);
118  Constant *CFICheckFailFn = M.getOrInsertFunction(
119  "__cfi_check_fail", Type::getVoidTy(Ctx), Type::getInt8PtrTy(Ctx),
120  Type::getInt8PtrTy(Ctx), nullptr);
121  IRBFail.CreateCall(CFICheckFailFn, {&CFICheckFailData, &Addr});
122  IRBFail.CreateBr(ExitBB);
123 
124  IRBuilder<> IRBExit(ExitBB);
125  IRBExit.CreateRetVoid();
126 
127  IRBuilder<> IRB(BB);
128  SwitchInst *SI = IRB.CreateSwitch(&CallSiteTypeId, TrapBB, TypeIds.size());
129  for (uint64_t TypeId : TypeIds) {
130  ConstantInt *CaseTypeId = ConstantInt::get(Type::getInt64Ty(Ctx), TypeId);
131  BasicBlock *TestBB = BasicBlock::Create(Ctx, "test", F);
132  IRBuilder<> IRBTest(TestBB);
133  Function *BitsetTestFn = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
134 
135  Value *Test = IRBTest.CreateCall(
136  BitsetTestFn, {&Addr, MetadataAsValue::get(
137  Ctx, ConstantAsMetadata::get(CaseTypeId))});
138  BranchInst *BI = IRBTest.CreateCondBr(Test, ExitBB, TrapBB);
139  BI->setMetadata(LLVMContext::MD_prof, VeryLikelyWeights);
140 
141  SI->addCase(CaseTypeId, TestBB);
142  ++NumTypeIds;
143  }
144 }
145 
146 bool CrossDSOCFI::runOnModule(Module &M) {
147  if (skipModule(M))
148  return false;
149 
150  VeryLikelyWeights =
151  MDBuilder(M.getContext()).createBranchWeights((1U << 20) - 1, 1);
152  if (M.getModuleFlag("Cross-DSO CFI") == nullptr)
153  return false;
154  buildCFICheck(M);
155  return true;
156 }
157 
159  CrossDSOCFI Impl;
160  bool Changed = Impl.runOnModule(M);
161  if (!Changed)
162  return PreservedAnalyses::all();
163  return PreservedAnalyses::none();
164 }
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
STATISTIC(NumFunctions,"Total number of functions")
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
Implements a dense probed hash-table based set.
Definition: DenseSet.h:202
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
arg_iterator arg_end()
Definition: Function.h:559
Metadata node.
Definition: Metadata.h:830
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:170
void setAlignment(unsigned Align)
Definition: Globals.cpp:86
iterator_range< global_object_iterator > global_objects()
Definition: Module.h:599
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:588
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:257
#define F(x, y, z)
Definition: MD5.cpp:51
void initializeCrossDSOCFIPass(PassRegistry &)
Function Alias Analysis false
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:949
Value wrapper in the Metadata hierarchy.
Definition: Metadata.h:325
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:392
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:110
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:74
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:107
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeSet AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:123
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
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:48
Conditional or Unconditional Branch instruction.
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:154
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:93
arg_iterator arg_begin()
Definition: Function.h:550
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:113
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:213
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1183
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition: Module.cpp:325
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1034
This is the shared class of boolean and integer constants.
Definition: Constants.h:88
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
Module.h This file contains the declarations for the Module class.
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:50
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:558
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:235
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:287
Multiway switch.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:71
A container for analyses that lazily runs them and caches their results.
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:222