In some cases, the "fail BB dominator" may be null after the BB was split (and
[oota-llvm.git] / lib / CodeGen / StackProtector.cpp
1 //===-- StackProtector.cpp - Stack Protector Insertion --------------------===//
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 inserts stack protectors into functions which need them. A variable
11 // with a random value in it is stored onto the stack before the local variables
12 // are allocated. Upon exiting the block, the stored value is checked. If it's
13 // changed, then there was some sort of violation and the program aborts.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "stack-protector"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/Analysis/Dominators.h"
20 #include "llvm/Attributes.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/Module.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLowering.h"
31 using namespace llvm;
32
33 // SSPBufferSize - The lower bound for a buffer to be considered for stack
34 // smashing protection.
35 static cl::opt<unsigned>
36 SSPBufferSize("stack-protector-buffer-size", cl::init(8),
37               cl::desc("Lower bound for a buffer to be considered for "
38                        "stack protection"));
39
40 namespace {
41   class StackProtector : public FunctionPass {
42     /// TLI - Keep a pointer of a TargetLowering to consult for determining
43     /// target type sizes.
44     const TargetLowering *TLI;
45
46     Function *F;
47     Module *M;
48
49     DominatorTree* DT;
50
51     /// InsertStackProtectors - Insert code into the prologue and epilogue of
52     /// the function.
53     ///
54     ///  - The prologue code loads and stores the stack guard onto the stack.
55     ///  - The epilogue checks the value stored in the prologue against the
56     ///    original value. It calls __stack_chk_fail if they differ.
57     bool InsertStackProtectors();
58
59     /// CreateFailBB - Create a basic block to jump to when the stack protector
60     /// check fails.
61     BasicBlock *CreateFailBB();
62
63     /// RequiresStackProtector - Check whether or not this function needs a
64     /// stack protector based upon the stack protector level.
65     bool RequiresStackProtector() const;
66   public:
67     static char ID;             // Pass identification, replacement for typeid.
68     StackProtector() : FunctionPass(ID), TLI(0) {
69       initializeStackProtectorPass(*PassRegistry::getPassRegistry());
70     }
71     StackProtector(const TargetLowering *tli)
72       : FunctionPass(ID), TLI(tli) {
73         initializeStackProtectorPass(*PassRegistry::getPassRegistry());
74       }
75
76     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77       AU.addPreserved<DominatorTree>();
78     }
79
80     virtual bool runOnFunction(Function &Fn);
81   };
82 } // end anonymous namespace
83
84 char StackProtector::ID = 0;
85 INITIALIZE_PASS(StackProtector, "stack-protector",
86                 "Insert stack protectors", false, false)
87
88 FunctionPass *llvm::createStackProtectorPass(const TargetLowering *tli) {
89   return new StackProtector(tli);
90 }
91
92 bool StackProtector::runOnFunction(Function &Fn) {
93   F = &Fn;
94   M = F->getParent();
95   DT = getAnalysisIfAvailable<DominatorTree>();
96
97   if (!RequiresStackProtector()) return false;
98   
99   return InsertStackProtectors();
100 }
101
102 /// RequiresStackProtector - Check whether or not this function needs a stack
103 /// protector based upon the stack protector level. The heuristic we use is to
104 /// add a guard variable to functions that call alloca, and functions with
105 /// buffers larger than SSPBufferSize bytes.
106 bool StackProtector::RequiresStackProtector() const {
107   if (F->hasFnAttr(Attribute::StackProtectReq))
108     return true;
109
110   if (!F->hasFnAttr(Attribute::StackProtect))
111     return false;
112
113   const TargetData *TD = TLI->getTargetData();
114
115   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
116     BasicBlock *BB = I;
117
118     for (BasicBlock::iterator
119            II = BB->begin(), IE = BB->end(); II != IE; ++II)
120       if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
121         if (AI->isArrayAllocation())
122           // This is a call to alloca with a variable size. Emit stack
123           // protectors.
124           return true;
125
126         if (const ArrayType *AT = dyn_cast<ArrayType>(AI->getAllocatedType())) {
127           // We apparently only care about character arrays.
128           if (!AT->getElementType()->isIntegerTy(8))
129             continue;
130
131           // If an array has more than SSPBufferSize bytes of allocated space,
132           // then we emit stack protectors.
133           if (SSPBufferSize <= TD->getTypeAllocSize(AT))
134             return true;
135         }
136       }
137   }
138
139   return false;
140 }
141
142 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
143 /// function.
144 ///
145 ///  - The prologue code loads and stores the stack guard onto the stack.
146 ///  - The epilogue checks the value stored in the prologue against the original
147 ///    value. It calls __stack_chk_fail if they differ.
148 bool StackProtector::InsertStackProtectors() {
149   BasicBlock *FailBB = 0;       // The basic block to jump to if check fails.
150   BasicBlock *FailBBDom = 0;    // FailBB's dominator.
151   AllocaInst *AI = 0;           // Place on stack that stores the stack guard.
152   Value *StackGuardVar = 0;  // The stack guard variable.
153
154   for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
155     BasicBlock *BB = I++;
156
157     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
158     if (!RI) continue;
159
160     if (!FailBB) {
161       // Insert code into the entry block that stores the __stack_chk_guard
162       // variable onto the stack:
163       //
164       //   entry:
165       //     StackGuardSlot = alloca i8*
166       //     StackGuard = load __stack_chk_guard
167       //     call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
168       // 
169       const PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
170       unsigned AddressSpace, Offset;
171       if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
172         Constant *OffsetVal =
173           ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
174         
175         StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
176                                       PointerType::get(PtrTy, AddressSpace));
177       } else {
178         StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy); 
179       }
180
181       BasicBlock &Entry = F->getEntryBlock();
182       Instruction *InsPt = &Entry.front();
183
184       AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
185       LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
186
187       Value *Args[] = { LI, AI };
188       CallInst::
189         Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
190                &Args[0], array_endof(Args), "", InsPt);
191
192       // Create the basic block to jump to when the guard check fails.
193       FailBB = CreateFailBB();
194       if (DT)
195         FailBBDom = DT->isReachableFromEntry(BB) ? BB : 0;
196     }
197
198     // For each block with a return instruction, convert this:
199     //
200     //   return:
201     //     ...
202     //     ret ...
203     //
204     // into this:
205     //
206     //   return:
207     //     ...
208     //     %1 = load __stack_chk_guard
209     //     %2 = load StackGuardSlot
210     //     %3 = cmp i1 %1, %2
211     //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
212     //
213     //   SP_return:
214     //     ret ...
215     //
216     //   CallStackCheckFailBlk:
217     //     call void @__stack_chk_fail()
218     //     unreachable
219
220     // Split the basic block before the return instruction.
221     BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
222     if (DT && DT->isReachableFromEntry(BB)) {
223       DT->addNewBlock(NewBB, BB);
224       if (FailBBDom)
225         FailBBDom = DT->findNearestCommonDominator(FailBBDom, BB);
226     }
227
228     // Remove default branch instruction to the new BB.
229     BB->getTerminator()->eraseFromParent();
230
231     // Move the newly created basic block to the point right after the old basic
232     // block so that it's in the "fall through" position.
233     NewBB->moveAfter(BB);
234
235     // Generate the stack protector instructions in the old basic block.
236     LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
237     LoadInst *LI2 = new LoadInst(AI, "", true, BB);
238     ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
239     BranchInst::Create(NewBB, FailBB, Cmp, BB);
240   }
241
242   // Return if we didn't modify any basic blocks. I.e., there are no return
243   // statements in the function.
244   if (!FailBB) return false;
245
246   if (DT && FailBBDom)
247     DT->addNewBlock(FailBB, FailBBDom);
248
249   return true;
250 }
251
252 /// CreateFailBB - Create a basic block to jump to when the stack protector
253 /// check fails.
254 BasicBlock *StackProtector::CreateFailBB() {
255   BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
256                                           "CallStackCheckFailBlk", F);
257   Constant *StackChkFail =
258     M->getOrInsertFunction("__stack_chk_fail",
259                            Type::getVoidTy(F->getContext()), NULL);
260   CallInst::Create(StackChkFail, "", FailBB);
261   new UnreachableInst(F->getContext(), FailBB);
262   return FailBB;
263 }