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