blob: f3be37c9ee6b515c9c1a2a134b3b44a7068b6aad [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"
Chad Rosier35907e92012-08-21 16:15:24 +000034#include "llvm/Target/TargetOptions.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000035using namespace llvm;
36
Bill Wendlinge4957fb2013-01-23 06:43:53 +000037STATISTIC(NumFunProtected, "Number of functions protected");
38STATISTIC(NumAddrTaken, "Number of local variables that have their address"
39 " taken.");
40
Bill Wendling2b58ce52008-11-04 02:10:20 +000041namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000042 class StackProtector : public FunctionPass {
Bill Wendling80a320d2008-11-04 21:53:09 +000043 /// TLI - Keep a pointer of a TargetLowering to consult for determining
44 /// target type sizes.
Benjamin Kramer69e42db2013-01-11 20:05:37 +000045 const TargetLoweringBase *TLI;
Bill Wendling2b58ce52008-11-04 02:10:20 +000046
Bill Wendling2b58ce52008-11-04 02:10:20 +000047 Function *F;
48 Module *M;
49
Bill Wendling6d86f3c2012-08-13 21:20:43 +000050 DominatorTree *DT;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000051
Bill Wendlinge4957fb2013-01-23 06:43:53 +000052 /// VisitedPHIs - The set of PHI nodes visited when determining
53 /// if a variable's reference has been taken. This set
54 /// is maintained to ensure we don't visit the same PHI node multiple
55 /// times.
56 SmallPtrSet<const PHINode*, 16> VisitedPHIs;
57
Bill Wendling613f7742008-11-05 00:00:21 +000058 /// InsertStackProtectors - Insert code into the prologue and epilogue of
59 /// the function.
60 ///
61 /// - The prologue code loads and stores the stack guard onto the stack.
62 /// - The epilogue checks the value stored in the prologue against the
63 /// original value. It calls __stack_chk_fail if they differ.
64 bool InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +000065
66 /// CreateFailBB - Create a basic block to jump to when the stack protector
67 /// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +000068 BasicBlock *CreateFailBB();
Bill Wendling2b58ce52008-11-04 02:10:20 +000069
Bill Wendlinga67eda72012-08-17 20:59:56 +000070 /// ContainsProtectableArray - Check whether the type either is an array or
71 /// contains an array of sufficient size so that we need stack protectors
72 /// for it.
Bill Wendlinge4957fb2013-01-23 06:43:53 +000073 bool ContainsProtectableArray(Type *Ty, bool Strong = false,
74 bool InStruct = false) const;
75
76 /// \brief Check whether a stack allocation has its address taken.
77 bool HasAddressTaken(const Instruction *AI);
Bill Wendlinga67eda72012-08-17 20:59:56 +000078
Bill Wendling2b58ce52008-11-04 02:10:20 +000079 /// RequiresStackProtector - Check whether or not this function needs a
80 /// stack protector based upon the stack protector level.
Bill Wendlinge4957fb2013-01-23 06:43:53 +000081 bool RequiresStackProtector();
Bill Wendling2b58ce52008-11-04 02:10:20 +000082 public:
83 static char ID; // Pass identification, replacement for typeid.
Owen Anderson081c34b2010-10-19 17:21:58 +000084 StackProtector() : FunctionPass(ID), TLI(0) {
85 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
86 }
Benjamin Kramer69e42db2013-01-11 20:05:37 +000087 StackProtector(const TargetLoweringBase *tli)
Owen Anderson081c34b2010-10-19 17:21:58 +000088 : FunctionPass(ID), TLI(tli) {
Bill Wendling6d86f3c2012-08-13 21:20:43 +000089 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
90 }
Bill Wendling2b58ce52008-11-04 02:10:20 +000091
Cameron Zwarich80f6a502011-01-08 17:01:52 +000092 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
93 AU.addPreserved<DominatorTree>();
94 }
95
Bill Wendling2b58ce52008-11-04 02:10:20 +000096 virtual bool runOnFunction(Function &Fn);
97 };
98} // end anonymous namespace
99
100char StackProtector::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000101INITIALIZE_PASS(StackProtector, "stack-protector",
Owen Andersonce665bd2010-10-07 22:25:06 +0000102 "Insert stack protectors", false, false)
Bill Wendling2b58ce52008-11-04 02:10:20 +0000103
Benjamin Kramer69e42db2013-01-11 20:05:37 +0000104FunctionPass *llvm::createStackProtectorPass(const TargetLoweringBase *tli) {
Bill Wendlinge9e6bdf2008-11-13 01:02:14 +0000105 return new StackProtector(tli);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000106}
107
108bool StackProtector::runOnFunction(Function &Fn) {
109 F = &Fn;
110 M = F->getParent();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000111 DT = getAnalysisIfAvailable<DominatorTree>();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000112
113 if (!RequiresStackProtector()) return false;
Bill Wendling6d86f3c2012-08-13 21:20:43 +0000114
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000115 ++NumFunProtected;
Bill Wendling613f7742008-11-05 00:00:21 +0000116 return InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000117}
118
Bill Wendlinga67eda72012-08-17 20:59:56 +0000119/// ContainsProtectableArray - Check whether the type either is an array or
120/// contains a char array of sufficient size so that we need stack protectors
121/// for it.
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000122bool StackProtector::ContainsProtectableArray(Type *Ty, bool Strong,
123 bool InStruct) const {
Bill Wendlinga67eda72012-08-17 20:59:56 +0000124 if (!Ty) return false;
125 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000126 // In strong mode any array, regardless of type and size, triggers a
127 // protector
128 if (Strong)
129 return true;
Chad Rosier35907e92012-08-21 16:15:24 +0000130 const TargetMachine &TM = TLI->getTargetMachine();
Bill Wendlinga67eda72012-08-17 20:59:56 +0000131 if (!AT->getElementType()->isIntegerTy(8)) {
Bill Wendlinga67eda72012-08-17 20:59:56 +0000132 Triple Trip(TM.getTargetTriple());
133
134 // If we're on a non-Darwin platform or we're inside of a structure, don't
135 // add stack protectors unless the array is a character array.
136 if (InStruct || !Trip.isOSDarwin())
137 return false;
138 }
139
140 // If an array has more than SSPBufferSize bytes of allocated space, then we
141 // emit stack protectors.
Micah Villmow3574eca2012-10-08 16:38:25 +0000142 if (TM.Options.SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT))
Bill Wendlinga67eda72012-08-17 20:59:56 +0000143 return true;
144 }
145
146 const StructType *ST = dyn_cast<StructType>(Ty);
147 if (!ST) return false;
148
149 for (StructType::element_iterator I = ST->element_begin(),
150 E = ST->element_end(); I != E; ++I)
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000151 if (ContainsProtectableArray(*I, Strong, true))
Bill Wendlinga67eda72012-08-17 20:59:56 +0000152 return true;
153
154 return false;
155}
156
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000157bool StackProtector::HasAddressTaken(const Instruction *AI) {
158 for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
159 UI != UE; ++UI) {
160 const User *U = *UI;
161 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
162 if (AI == SI->getValueOperand())
163 return true;
164 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
165 if (AI == SI->getOperand(0))
166 return true;
167 } else if (isa<CallInst>(U)) {
168 return true;
169 } else if (isa<InvokeInst>(U)) {
170 return true;
171 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
172 if (HasAddressTaken(SI))
173 return true;
174 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
175 // Keep track of what PHI nodes we have already visited to ensure
176 // they are only visited once.
177 if (VisitedPHIs.insert(PN))
178 if (HasAddressTaken(PN))
179 return true;
180 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
181 if (HasAddressTaken(GEP))
182 return true;
183 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
184 if (HasAddressTaken(BI))
185 return true;
186 }
187 }
188 return false;
189}
190
191/// \brief Check whether or not this function needs a stack protector based
192/// upon the stack protector level.
193///
194/// We use two heuristics: a standard (ssp) and strong (sspstrong).
195/// The standard heuristic which will add a guard variable to functions that
196/// call alloca with a either a variable size or a size >= SSPBufferSize,
197/// functions with character buffers larger than SSPBufferSize, and functions
198/// with aggregates containing character buffers larger than SSPBufferSize. The
199/// strong heuristic will add a guard variables to functions that call alloca
200/// regardless of size, functions with any buffer regardless of type and size,
201/// functions with aggregates that contain any buffer regardless of type and
202/// size, and functions that contain stack-based variables that have had their
203/// address taken.
204bool StackProtector::RequiresStackProtector() {
205 bool Strong = false;
Bill Wendling831737d2012-12-30 10:32:01 +0000206 if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
207 Attribute::StackProtectReq))
Bill Wendlingc3348a72008-11-18 05:32:11 +0000208 return true;
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000209 else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
210 Attribute::StackProtectStrong))
211 Strong = true;
212 else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
213 Attribute::StackProtect))
Bill Wendlingc3348a72008-11-18 05:32:11 +0000214 return false;
215
Bill Wendlingc3348a72008-11-18 05:32:11 +0000216 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
217 BasicBlock *BB = I;
218
219 for (BasicBlock::iterator
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000220 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
Bill Wendlingc3348a72008-11-18 05:32:11 +0000221 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000222 if (AI->isArrayAllocation()) {
223 // SSP-Strong: Enable protectors for any call to alloca, regardless
224 // of size.
225 if (Strong)
226 return true;
227
228 if (const ConstantInt *CI =
229 dyn_cast<ConstantInt>(AI->getArraySize())) {
230 unsigned BufferSize = TLI->getTargetMachine().Options.SSPBufferSize;
231 if (CI->getLimitedValue(BufferSize) >= BufferSize)
232 // A call to alloca with size >= SSPBufferSize requires
233 // stack protectors.
234 return true;
235 } else // A call to alloca with a variable size requires protectors.
236 return true;
237 }
238
239 if (ContainsProtectableArray(AI->getAllocatedType(), Strong))
Bill Wendlingc3348a72008-11-18 05:32:11 +0000240 return true;
241
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000242 if (Strong && HasAddressTaken(AI)) {
243 ++NumAddrTaken;
Bill Wendlinga67eda72012-08-17 20:59:56 +0000244 return true;
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000245 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000246 }
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000247 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000248 }
249
250 return false;
251}
252
Bill Wendling613f7742008-11-05 00:00:21 +0000253/// InsertStackProtectors - Insert code into the prologue and epilogue of the
254/// function.
255///
256/// - The prologue code loads and stores the stack guard onto the stack.
257/// - The epilogue checks the value stored in the prologue against the original
258/// value. It calls __stack_chk_fail if they differ.
259bool StackProtector::InsertStackProtectors() {
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000260 BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000261 BasicBlock *FailBBDom = 0; // FailBB's dominator.
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000262 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000263 Value *StackGuardVar = 0; // The stack guard variable.
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000264
Bill Wendling72056772008-11-10 21:13:10 +0000265 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
Bill Wendlingc3348a72008-11-18 05:32:11 +0000266 BasicBlock *BB = I++;
Bill Wendlingc3348a72008-11-18 05:32:11 +0000267 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
268 if (!RI) continue;
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000269
Bill Wendlingc3348a72008-11-18 05:32:11 +0000270 if (!FailBB) {
271 // Insert code into the entry block that stores the __stack_chk_guard
272 // variable onto the stack:
273 //
274 // entry:
275 // StackGuardSlot = alloca i8*
276 // StackGuard = load __stack_chk_guard
277 // call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
Bill Wendling6d86f3c2012-08-13 21:20:43 +0000278 //
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000279 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000280 unsigned AddressSpace, Offset;
281 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
Chris Lattnerf8bd3922010-07-06 15:59:27 +0000282 Constant *OffsetVal =
283 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
Bill Wendling6d86f3c2012-08-13 21:20:43 +0000284
Chris Lattnerf8bd3922010-07-06 15:59:27 +0000285 StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
286 PointerType::get(PtrTy, AddressSpace));
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000287 } else {
Bill Wendling6d86f3c2012-08-13 21:20:43 +0000288 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000289 }
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000290
Bill Wendling3c288b92011-03-29 07:28:52 +0000291 BasicBlock &Entry = F->getEntryBlock();
Bill Wendlingc3348a72008-11-18 05:32:11 +0000292 Instruction *InsPt = &Entry.front();
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000293
Owen Anderson50dead02009-07-15 23:53:25 +0000294 AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
Bill Wendlingc3348a72008-11-18 05:32:11 +0000295 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
Bill Wendling72056772008-11-10 21:13:10 +0000296
Bill Wendlingc3348a72008-11-18 05:32:11 +0000297 Value *Args[] = { LI, AI };
298 CallInst::
Bill Wendling57344502008-11-18 11:01:33 +0000299 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
Jay Foada3efbb12011-07-15 08:37:34 +0000300 Args, "", InsPt);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000301
Bill Wendlingc3348a72008-11-18 05:32:11 +0000302 // Create the basic block to jump to when the guard check fails.
303 FailBB = CreateFailBB();
Bill Wendling1fb615f2008-11-06 23:55:49 +0000304 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000305
306 // For each block with a return instruction, convert this:
307 //
308 // return:
309 // ...
310 // ret ...
311 //
312 // into this:
313 //
314 // return:
315 // ...
316 // %1 = load __stack_chk_guard
Bill Wendling733bbc52008-11-18 07:30:57 +0000317 // %2 = load StackGuardSlot
Bill Wendlingc3348a72008-11-18 05:32:11 +0000318 // %3 = cmp i1 %1, %2
319 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
320 //
321 // SP_return:
322 // ret ...
323 //
324 // CallStackCheckFailBlk:
325 // call void @__stack_chk_fail()
326 // unreachable
327
328 // Split the basic block before the return instruction.
329 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
Bill Wendling3c288b92011-03-29 07:28:52 +0000330
Bill Wendling3f782f42011-03-29 17:12:55 +0000331 if (DT && DT->isReachableFromEntry(BB)) {
Cameron Zwarich53aac152011-03-11 21:51:56 +0000332 DT->addNewBlock(NewBB, BB);
Bill Wendling3c288b92011-03-29 07:28:52 +0000333 FailBBDom = FailBBDom ? DT->findNearestCommonDominator(FailBBDom, BB) :BB;
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000334 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000335
Bill Wendling56016992009-03-06 01:41:15 +0000336 // Remove default branch instruction to the new BB.
337 BB->getTerminator()->eraseFromParent();
338
Bill Wendlingc3348a72008-11-18 05:32:11 +0000339 // Move the newly created basic block to the point right after the old basic
340 // block so that it's in the "fall through" position.
341 NewBB->moveAfter(BB);
342
343 // Generate the stack protector instructions in the old basic block.
Bill Wendling733bbc52008-11-18 07:30:57 +0000344 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
345 LoadInst *LI2 = new LoadInst(AI, "", true, BB);
Owen Anderson333c4002009-07-09 23:48:35 +0000346 ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
Bill Wendlingc3348a72008-11-18 05:32:11 +0000347 BranchInst::Create(NewBB, FailBB, Cmp, BB);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000348 }
Bill Wendling613f7742008-11-05 00:00:21 +0000349
Bill Wendling1fb615f2008-11-06 23:55:49 +0000350 // Return if we didn't modify any basic blocks. I.e., there are no return
351 // statements in the function.
352 if (!FailBB) return false;
353
Cameron Zwarich53aac152011-03-11 21:51:56 +0000354 if (DT && FailBBDom)
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000355 DT->addNewBlock(FailBB, FailBBDom);
356
Bill Wendling613f7742008-11-05 00:00:21 +0000357 return true;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000358}
359
360/// CreateFailBB - Create a basic block to jump to when the stack protector
361/// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +0000362BasicBlock *StackProtector::CreateFailBB() {
Owen Anderson1d0be152009-08-13 21:58:54 +0000363 BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
364 "CallStackCheckFailBlk", F);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000365 Constant *StackChkFail =
Owen Anderson1d0be152009-08-13 21:58:54 +0000366 M->getOrInsertFunction("__stack_chk_fail",
367 Type::getVoidTy(F->getContext()), NULL);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000368 CallInst::Create(StackChkFail, "", FailBB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000369 new UnreachableInst(F->getContext(), FailBB);
Bill Wendling613f7742008-11-05 00:00:21 +0000370 return FailBB;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000371}