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