blob: fbef34772b086cd15936b1e72aebc40b376b8d43 [file] [log] [blame]
Bill Wendling2b58ce52008-11-04 02:10:20 +00001//===-- 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//
Bill Wendling80a320d2008-11-04 21:53:09 +000010// 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
Bill Wendling2b58ce52008-11-04 02:10:20 +000013// 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"
Bill Wendlinge4957fb2013-01-23 06:43:53 +000019#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000021#include "llvm/ADT/Triple.h"
Cameron Zwarich80f6a502011-01-08 17:01:52 +000022#include "llvm/Analysis/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000023#include "llvm/IR/Attributes.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Module.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000031#include "llvm/Pass.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000032#include "llvm/Support/CommandLine.h"
Bill Wendling80a320d2008-11-04 21:53:09 +000033#include "llvm/Target/TargetLowering.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000034using namespace llvm;
35
Bill Wendlinge4957fb2013-01-23 06:43:53 +000036STATISTIC(NumFunProtected, "Number of functions protected");
37STATISTIC(NumAddrTaken, "Number of local variables that have their address"
38 " taken.");
39
Bill Wendling2b58ce52008-11-04 02:10:20 +000040namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000041 class StackProtector : public FunctionPass {
Bill Wendling80a320d2008-11-04 21:53:09 +000042 /// TLI - Keep a pointer of a TargetLowering to consult for determining
43 /// target type sizes.
Benjamin Kramer69e42db2013-01-11 20:05:37 +000044 const TargetLoweringBase *TLI;
Bill Wendling2b58ce52008-11-04 02:10:20 +000045
Bill Wendling2b58ce52008-11-04 02:10:20 +000046 Function *F;
47 Module *M;
48
Bill Wendling6d86f3c2012-08-13 21:20:43 +000049 DominatorTree *DT;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000050
Bill Wendlinge4957fb2013-01-23 06:43:53 +000051 /// VisitedPHIs - The set of PHI nodes visited when determining
52 /// if a variable's reference has been taken. This set
53 /// is maintained to ensure we don't visit the same PHI node multiple
54 /// times.
55 SmallPtrSet<const PHINode*, 16> VisitedPHIs;
56
Bill Wendling613f7742008-11-05 00:00:21 +000057 /// InsertStackProtectors - Insert code into the prologue and epilogue of
58 /// the function.
59 ///
60 /// - The prologue code loads and stores the stack guard onto the stack.
61 /// - The epilogue checks the value stored in the prologue against the
62 /// original value. It calls __stack_chk_fail if they differ.
63 bool InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +000064
65 /// CreateFailBB - Create a basic block to jump to when the stack protector
66 /// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +000067 BasicBlock *CreateFailBB();
Bill Wendling2b58ce52008-11-04 02:10:20 +000068
Bill Wendlinga67eda72012-08-17 20:59:56 +000069 /// ContainsProtectableArray - Check whether the type either is an array or
70 /// contains an array of sufficient size so that we need stack protectors
71 /// for it.
Bill Wendlinge4957fb2013-01-23 06:43:53 +000072 bool ContainsProtectableArray(Type *Ty, bool Strong = false,
73 bool InStruct = false) const;
74
75 /// \brief Check whether a stack allocation has its address taken.
76 bool HasAddressTaken(const Instruction *AI);
Bill Wendlinga67eda72012-08-17 20:59:56 +000077
Bill Wendling2b58ce52008-11-04 02:10:20 +000078 /// RequiresStackProtector - Check whether or not this function needs a
79 /// stack protector based upon the stack protector level.
Bill Wendlinge4957fb2013-01-23 06:43:53 +000080 bool RequiresStackProtector();
Bill Wendling2b58ce52008-11-04 02:10:20 +000081 public:
82 static char ID; // Pass identification, replacement for typeid.
Owen Anderson081c34b2010-10-19 17:21:58 +000083 StackProtector() : FunctionPass(ID), TLI(0) {
84 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
85 }
Benjamin Kramer69e42db2013-01-11 20:05:37 +000086 StackProtector(const TargetLoweringBase *tli)
Owen Anderson081c34b2010-10-19 17:21:58 +000087 : FunctionPass(ID), TLI(tli) {
Bill Wendling6d86f3c2012-08-13 21:20:43 +000088 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
89 }
Bill Wendling2b58ce52008-11-04 02:10:20 +000090
Cameron Zwarich80f6a502011-01-08 17:01:52 +000091 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
92 AU.addPreserved<DominatorTree>();
93 }
94
Bill Wendling2b58ce52008-11-04 02:10:20 +000095 virtual bool runOnFunction(Function &Fn);
96 };
97} // end anonymous namespace
98
99char StackProtector::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000100INITIALIZE_PASS(StackProtector, "stack-protector",
Owen Andersonce665bd2010-10-07 22:25:06 +0000101 "Insert stack protectors", false, false)
Bill Wendling2b58ce52008-11-04 02:10:20 +0000102
Benjamin Kramer69e42db2013-01-11 20:05:37 +0000103FunctionPass *llvm::createStackProtectorPass(const TargetLoweringBase *tli) {
Bill Wendlinge9e6bdf2008-11-13 01:02:14 +0000104 return new StackProtector(tli);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000105}
106
107bool StackProtector::runOnFunction(Function &Fn) {
108 F = &Fn;
109 M = F->getParent();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000110 DT = getAnalysisIfAvailable<DominatorTree>();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000111
112 if (!RequiresStackProtector()) return false;
Bill Wendling6d86f3c2012-08-13 21:20:43 +0000113
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000114 ++NumFunProtected;
Bill Wendling613f7742008-11-05 00:00:21 +0000115 return InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000116}
117
Bill Wendlinga67eda72012-08-17 20:59:56 +0000118/// ContainsProtectableArray - Check whether the type either is an array or
119/// contains a char array of sufficient size so that we need stack protectors
120/// for it.
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000121bool StackProtector::ContainsProtectableArray(Type *Ty, bool Strong,
122 bool InStruct) const {
Bill Wendlinga67eda72012-08-17 20:59:56 +0000123 if (!Ty) return false;
124 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000125 // In strong mode any array, regardless of type and size, triggers a
126 // protector
127 if (Strong)
128 return true;
Chad Rosier35907e92012-08-21 16:15:24 +0000129 const TargetMachine &TM = TLI->getTargetMachine();
Bill Wendlinga67eda72012-08-17 20:59:56 +0000130 if (!AT->getElementType()->isIntegerTy(8)) {
Bill Wendlinga67eda72012-08-17 20:59:56 +0000131 Triple Trip(TM.getTargetTriple());
132
133 // If we're on a non-Darwin platform or we're inside of a structure, don't
134 // add stack protectors unless the array is a character array.
135 if (InStruct || !Trip.isOSDarwin())
136 return false;
137 }
138
139 // If an array has more than SSPBufferSize bytes of allocated space, then we
140 // emit stack protectors.
Micah Villmow3574eca2012-10-08 16:38:25 +0000141 if (TM.Options.SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT))
Bill Wendlinga67eda72012-08-17 20:59:56 +0000142 return true;
143 }
144
145 const StructType *ST = dyn_cast<StructType>(Ty);
146 if (!ST) return false;
147
148 for (StructType::element_iterator I = ST->element_begin(),
149 E = ST->element_end(); I != E; ++I)
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000150 if (ContainsProtectableArray(*I, Strong, true))
Bill Wendlinga67eda72012-08-17 20:59:56 +0000151 return true;
152
153 return false;
154}
155
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000156bool StackProtector::HasAddressTaken(const Instruction *AI) {
157 for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
158 UI != UE; ++UI) {
159 const User *U = *UI;
160 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
161 if (AI == SI->getValueOperand())
162 return true;
163 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
164 if (AI == SI->getOperand(0))
165 return true;
166 } else if (isa<CallInst>(U)) {
167 return true;
168 } else if (isa<InvokeInst>(U)) {
169 return true;
170 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
171 if (HasAddressTaken(SI))
172 return true;
173 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
174 // Keep track of what PHI nodes we have already visited to ensure
175 // they are only visited once.
176 if (VisitedPHIs.insert(PN))
177 if (HasAddressTaken(PN))
178 return true;
179 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
180 if (HasAddressTaken(GEP))
181 return true;
182 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
183 if (HasAddressTaken(BI))
184 return true;
185 }
186 }
187 return false;
188}
189
190/// \brief Check whether or not this function needs a stack protector based
191/// upon the stack protector level.
192///
193/// We use two heuristics: a standard (ssp) and strong (sspstrong).
194/// The standard heuristic which will add a guard variable to functions that
195/// call alloca with a either a variable size or a size >= SSPBufferSize,
196/// functions with character buffers larger than SSPBufferSize, and functions
197/// with aggregates containing character buffers larger than SSPBufferSize. The
198/// strong heuristic will add a guard variables to functions that call alloca
199/// regardless of size, functions with any buffer regardless of type and size,
200/// functions with aggregates that contain any buffer regardless of type and
201/// size, and functions that contain stack-based variables that have had their
202/// address taken.
203bool StackProtector::RequiresStackProtector() {
204 bool Strong = false;
Bill Wendling831737d2012-12-30 10:32:01 +0000205 if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
206 Attribute::StackProtectReq))
Bill Wendlingc3348a72008-11-18 05:32:11 +0000207 return true;
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000208 else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
209 Attribute::StackProtectStrong))
210 Strong = true;
211 else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
212 Attribute::StackProtect))
Bill Wendlingc3348a72008-11-18 05:32:11 +0000213 return false;
214
Bill Wendlingc3348a72008-11-18 05:32:11 +0000215 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
216 BasicBlock *BB = I;
217
218 for (BasicBlock::iterator
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000219 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
Bill Wendlingc3348a72008-11-18 05:32:11 +0000220 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000221 if (AI->isArrayAllocation()) {
222 // SSP-Strong: Enable protectors for any call to alloca, regardless
223 // of size.
224 if (Strong)
225 return true;
226
227 if (const ConstantInt *CI =
228 dyn_cast<ConstantInt>(AI->getArraySize())) {
229 unsigned BufferSize = TLI->getTargetMachine().Options.SSPBufferSize;
230 if (CI->getLimitedValue(BufferSize) >= BufferSize)
231 // A call to alloca with size >= SSPBufferSize requires
232 // stack protectors.
233 return true;
234 } else // A call to alloca with a variable size requires protectors.
235 return true;
236 }
237
238 if (ContainsProtectableArray(AI->getAllocatedType(), Strong))
Bill Wendlingc3348a72008-11-18 05:32:11 +0000239 return true;
240
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000241 if (Strong && HasAddressTaken(AI)) {
242 ++NumAddrTaken;
Bill Wendlinga67eda72012-08-17 20:59:56 +0000243 return true;
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000244 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000245 }
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000246 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000247 }
248
249 return false;
250}
251
Bill Wendling613f7742008-11-05 00:00:21 +0000252/// InsertStackProtectors - Insert code into the prologue and epilogue of the
253/// function.
254///
255/// - The prologue code loads and stores the stack guard onto the stack.
256/// - The epilogue checks the value stored in the prologue against the original
257/// value. It calls __stack_chk_fail if they differ.
258bool StackProtector::InsertStackProtectors() {
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000259 BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000260 BasicBlock *FailBBDom = 0; // FailBB's dominator.
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000261 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000262 Value *StackGuardVar = 0; // The stack guard variable.
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000263
Bill Wendling72056772008-11-10 21:13:10 +0000264 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
Bill Wendlingc3348a72008-11-18 05:32:11 +0000265 BasicBlock *BB = I++;
Bill Wendlingc3348a72008-11-18 05:32:11 +0000266 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
267 if (!RI) continue;
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000268
Bill Wendlingc3348a72008-11-18 05:32:11 +0000269 if (!FailBB) {
270 // Insert code into the entry block that stores the __stack_chk_guard
271 // variable onto the stack:
272 //
273 // entry:
274 // StackGuardSlot = alloca i8*
275 // StackGuard = load __stack_chk_guard
276 // call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
Bill Wendling6d86f3c2012-08-13 21:20:43 +0000277 //
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000278 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000279 unsigned AddressSpace, Offset;
280 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
Chris Lattnerf8bd3922010-07-06 15:59:27 +0000281 Constant *OffsetVal =
282 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
Bill Wendling6d86f3c2012-08-13 21:20:43 +0000283
Chris Lattnerf8bd3922010-07-06 15:59:27 +0000284 StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
285 PointerType::get(PtrTy, AddressSpace));
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000286 } else {
Bill Wendling6d86f3c2012-08-13 21:20:43 +0000287 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000288 }
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000289
Bill Wendling3c288b92011-03-29 07:28:52 +0000290 BasicBlock &Entry = F->getEntryBlock();
Bill Wendlingc3348a72008-11-18 05:32:11 +0000291 Instruction *InsPt = &Entry.front();
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000292
Owen Anderson50dead02009-07-15 23:53:25 +0000293 AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
Bill Wendlingc3348a72008-11-18 05:32:11 +0000294 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
Bill Wendling72056772008-11-10 21:13:10 +0000295
Bill Wendlingc3348a72008-11-18 05:32:11 +0000296 Value *Args[] = { LI, AI };
297 CallInst::
Bill Wendling57344502008-11-18 11:01:33 +0000298 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
Jay Foada3efbb12011-07-15 08:37:34 +0000299 Args, "", InsPt);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000300
Bill Wendlingc3348a72008-11-18 05:32:11 +0000301 // Create the basic block to jump to when the guard check fails.
302 FailBB = CreateFailBB();
Bill Wendling1fb615f2008-11-06 23:55:49 +0000303 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000304
305 // For each block with a return instruction, convert this:
306 //
307 // return:
308 // ...
309 // ret ...
310 //
311 // into this:
312 //
313 // return:
314 // ...
315 // %1 = load __stack_chk_guard
Bill Wendling733bbc52008-11-18 07:30:57 +0000316 // %2 = load StackGuardSlot
Bill Wendlingc3348a72008-11-18 05:32:11 +0000317 // %3 = cmp i1 %1, %2
318 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
319 //
320 // SP_return:
321 // ret ...
322 //
323 // CallStackCheckFailBlk:
324 // call void @__stack_chk_fail()
325 // unreachable
326
327 // Split the basic block before the return instruction.
328 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
Bill Wendling3c288b92011-03-29 07:28:52 +0000329
Bill Wendling3f782f42011-03-29 17:12:55 +0000330 if (DT && DT->isReachableFromEntry(BB)) {
Cameron Zwarich53aac152011-03-11 21:51:56 +0000331 DT->addNewBlock(NewBB, BB);
Bill Wendling3c288b92011-03-29 07:28:52 +0000332 FailBBDom = FailBBDom ? DT->findNearestCommonDominator(FailBBDom, BB) :BB;
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000333 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000334
Bill Wendling56016992009-03-06 01:41:15 +0000335 // Remove default branch instruction to the new BB.
336 BB->getTerminator()->eraseFromParent();
337
Bill Wendlingc3348a72008-11-18 05:32:11 +0000338 // Move the newly created basic block to the point right after the old basic
339 // block so that it's in the "fall through" position.
340 NewBB->moveAfter(BB);
341
342 // Generate the stack protector instructions in the old basic block.
Bill Wendling733bbc52008-11-18 07:30:57 +0000343 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
344 LoadInst *LI2 = new LoadInst(AI, "", true, BB);
Owen Anderson333c4002009-07-09 23:48:35 +0000345 ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
Bill Wendlingc3348a72008-11-18 05:32:11 +0000346 BranchInst::Create(NewBB, FailBB, Cmp, BB);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000347 }
Bill Wendling613f7742008-11-05 00:00:21 +0000348
Bill Wendling1fb615f2008-11-06 23:55:49 +0000349 // Return if we didn't modify any basic blocks. I.e., there are no return
350 // statements in the function.
351 if (!FailBB) return false;
352
Cameron Zwarich53aac152011-03-11 21:51:56 +0000353 if (DT && FailBBDom)
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000354 DT->addNewBlock(FailBB, FailBBDom);
355
Bill Wendling613f7742008-11-05 00:00:21 +0000356 return true;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000357}
358
359/// CreateFailBB - Create a basic block to jump to when the stack protector
360/// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +0000361BasicBlock *StackProtector::CreateFailBB() {
Owen Anderson1d0be152009-08-13 21:58:54 +0000362 BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
363 "CallStackCheckFailBlk", F);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000364 Constant *StackChkFail =
Owen Anderson1d0be152009-08-13 21:58:54 +0000365 M->getOrInsertFunction("__stack_chk_fail",
366 Type::getVoidTy(F->getContext()), NULL);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000367 CallInst::Create(StackChkFail, "", FailBB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000368 new UnreachableInst(F->getContext(), FailBB);
Bill Wendling613f7742008-11-05 00:00:21 +0000369 return FailBB;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000370}