blob: 45675c9469563d5ef2ba43a7d51df603d5e7ada1 [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"
Michael Gottesman3480d1b2013-08-20 08:36:53 +000018#include "llvm/CodeGen/Analysis.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000019#include "llvm/CodeGen/Passes.h"
Bill Wendlinge4957fb2013-01-23 06:43:53 +000020#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000022#include "llvm/ADT/Triple.h"
Cameron Zwarich80f6a502011-01-08 17:01:52 +000023#include "llvm/Analysis/Dominators.h"
Michael Gottesman3480d1b2013-08-20 08:36:53 +000024#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000025#include "llvm/IR/Attributes.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Function.h"
Rafael Espindola62ed8d32013-06-07 16:35:57 +000030#include "llvm/IR/GlobalValue.h"
31#include "llvm/IR/GlobalVariable.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000032#include "llvm/IR/Instructions.h"
Michael Gottesman3480d1b2013-08-20 08:36:53 +000033#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000034#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/Module.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000036#include "llvm/Pass.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000037#include "llvm/Support/CommandLine.h"
Bill Wendling80a320d2008-11-04 21:53:09 +000038#include "llvm/Target/TargetLowering.h"
Bill Wendling0dcba2f2013-07-22 20:15:21 +000039#include <cstdlib>
Bill Wendling2b58ce52008-11-04 02:10:20 +000040using namespace llvm;
41
Bill Wendlinge4957fb2013-01-23 06:43:53 +000042STATISTIC(NumFunProtected, "Number of functions protected");
43STATISTIC(NumAddrTaken, "Number of local variables that have their address"
44 " taken.");
45
Michael Gottesman3480d1b2013-08-20 08:36:53 +000046static cl::opt<bool>
47EnableSelectionDAGSP("enable-selectiondag-sp", cl::init(true),
48 cl::Hidden);
49
Bill Wendling2b58ce52008-11-04 02:10:20 +000050namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000051 class StackProtector : public FunctionPass {
Bill Wendlingea442812013-06-19 20:51:24 +000052 const TargetMachine *TM;
53
Bill Wendling80a320d2008-11-04 21:53:09 +000054 /// TLI - Keep a pointer of a TargetLowering to consult for determining
55 /// target type sizes.
Bill Wendlingea442812013-06-19 20:51:24 +000056 const TargetLoweringBase *TLI;
Rafael Espindola62ed8d32013-06-07 16:35:57 +000057 const Triple Trip;
Bill Wendling2b58ce52008-11-04 02:10:20 +000058
Bill Wendling2b58ce52008-11-04 02:10:20 +000059 Function *F;
60 Module *M;
61
Bill Wendling6d86f3c2012-08-13 21:20:43 +000062 DominatorTree *DT;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000063
Bill Wendling0dcba2f2013-07-22 20:15:21 +000064 /// \brief The minimum size of buffers that will receive stack smashing
65 /// protection when -fstack-protection is used.
66 unsigned SSPBufferSize;
67
Bill Wendlinge4957fb2013-01-23 06:43:53 +000068 /// VisitedPHIs - The set of PHI nodes visited when determining
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +000069 /// if a variable's reference has been taken. This set
Bill Wendlinge4957fb2013-01-23 06:43:53 +000070 /// is maintained to ensure we don't visit the same PHI node multiple
71 /// times.
72 SmallPtrSet<const PHINode*, 16> VisitedPHIs;
73
Bill Wendling613f7742008-11-05 00:00:21 +000074 /// InsertStackProtectors - Insert code into the prologue and epilogue of
75 /// the function.
76 ///
77 /// - The prologue code loads and stores the stack guard onto the stack.
78 /// - The epilogue checks the value stored in the prologue against the
79 /// original value. It calls __stack_chk_fail if they differ.
80 bool InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +000081
82 /// CreateFailBB - Create a basic block to jump to when the stack protector
83 /// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +000084 BasicBlock *CreateFailBB();
Bill Wendling2b58ce52008-11-04 02:10:20 +000085
Bill Wendlinga67eda72012-08-17 20:59:56 +000086 /// ContainsProtectableArray - Check whether the type either is an array or
87 /// contains an array of sufficient size so that we need stack protectors
88 /// for it.
Bill Wendlinge4957fb2013-01-23 06:43:53 +000089 bool ContainsProtectableArray(Type *Ty, bool Strong = false,
90 bool InStruct = false) const;
91
92 /// \brief Check whether a stack allocation has its address taken.
93 bool HasAddressTaken(const Instruction *AI);
Bill Wendlinga67eda72012-08-17 20:59:56 +000094
Bill Wendling2b58ce52008-11-04 02:10:20 +000095 /// RequiresStackProtector - Check whether or not this function needs a
96 /// stack protector based upon the stack protector level.
Bill Wendlinge4957fb2013-01-23 06:43:53 +000097 bool RequiresStackProtector();
Bill Wendling2b58ce52008-11-04 02:10:20 +000098 public:
99 static char ID; // Pass identification, replacement for typeid.
Bill Wendling0dcba2f2013-07-22 20:15:21 +0000100 StackProtector() : FunctionPass(ID), TM(0), TLI(0), SSPBufferSize(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000101 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
102 }
Bill Wendlingea442812013-06-19 20:51:24 +0000103 StackProtector(const TargetMachine *TM)
Bill Wendling0dcba2f2013-07-22 20:15:21 +0000104 : FunctionPass(ID), TM(TM), TLI(0), Trip(TM->getTargetTriple()),
105 SSPBufferSize(8) {
Bill Wendling6d86f3c2012-08-13 21:20:43 +0000106 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
107 }
Bill Wendling2b58ce52008-11-04 02:10:20 +0000108
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
110 AU.addPreserved<DominatorTree>();
111 }
112
Bill Wendling2b58ce52008-11-04 02:10:20 +0000113 virtual bool runOnFunction(Function &Fn);
114 };
115} // end anonymous namespace
116
117char StackProtector::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000118INITIALIZE_PASS(StackProtector, "stack-protector",
Owen Andersonce665bd2010-10-07 22:25:06 +0000119 "Insert stack protectors", false, false)
Bill Wendling2b58ce52008-11-04 02:10:20 +0000120
Bill Wendlingea442812013-06-19 20:51:24 +0000121FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
122 return new StackProtector(TM);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000123}
124
125bool StackProtector::runOnFunction(Function &Fn) {
126 F = &Fn;
127 M = F->getParent();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000128 DT = getAnalysisIfAvailable<DominatorTree>();
Bill Wendlingea442812013-06-19 20:51:24 +0000129 TLI = TM->getTargetLowering();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000130
131 if (!RequiresStackProtector()) return false;
Bill Wendling6d86f3c2012-08-13 21:20:43 +0000132
Bill Wendling0dcba2f2013-07-22 20:15:21 +0000133 Attribute Attr =
134 Fn.getAttributes().getAttribute(AttributeSet::FunctionIndex,
135 "stack-protector-buffer-size");
136 if (Attr.isStringAttribute())
137 SSPBufferSize = atoi(Attr.getValueAsString().data());
138
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000139 ++NumFunProtected;
Bill Wendling613f7742008-11-05 00:00:21 +0000140 return InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000141}
142
Bill Wendlinga67eda72012-08-17 20:59:56 +0000143/// ContainsProtectableArray - Check whether the type either is an array or
144/// contains a char array of sufficient size so that we need stack protectors
145/// for it.
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000146bool StackProtector::ContainsProtectableArray(Type *Ty, bool Strong,
147 bool InStruct) const {
Bill Wendlinga67eda72012-08-17 20:59:56 +0000148 if (!Ty) return false;
149 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000150 // In strong mode any array, regardless of type and size, triggers a
151 // protector
152 if (Strong)
153 return true;
Bill Wendlinga67eda72012-08-17 20:59:56 +0000154 if (!AT->getElementType()->isIntegerTy(8)) {
Bill Wendlinga67eda72012-08-17 20:59:56 +0000155 // If we're on a non-Darwin platform or we're inside of a structure, don't
156 // add stack protectors unless the array is a character array.
157 if (InStruct || !Trip.isOSDarwin())
158 return false;
159 }
160
161 // If an array has more than SSPBufferSize bytes of allocated space, then we
162 // emit stack protectors.
Bill Wendling0dcba2f2013-07-22 20:15:21 +0000163 if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT))
Bill Wendlinga67eda72012-08-17 20:59:56 +0000164 return true;
165 }
166
167 const StructType *ST = dyn_cast<StructType>(Ty);
168 if (!ST) return false;
169
170 for (StructType::element_iterator I = ST->element_begin(),
171 E = ST->element_end(); I != E; ++I)
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000172 if (ContainsProtectableArray(*I, Strong, true))
Bill Wendlinga67eda72012-08-17 20:59:56 +0000173 return true;
174
175 return false;
176}
177
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000178bool StackProtector::HasAddressTaken(const Instruction *AI) {
179 for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
180 UI != UE; ++UI) {
181 const User *U = *UI;
182 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
183 if (AI == SI->getValueOperand())
184 return true;
185 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
186 if (AI == SI->getOperand(0))
187 return true;
188 } else if (isa<CallInst>(U)) {
189 return true;
190 } else if (isa<InvokeInst>(U)) {
191 return true;
192 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
193 if (HasAddressTaken(SI))
194 return true;
195 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
196 // Keep track of what PHI nodes we have already visited to ensure
197 // they are only visited once.
198 if (VisitedPHIs.insert(PN))
199 if (HasAddressTaken(PN))
200 return true;
201 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
202 if (HasAddressTaken(GEP))
203 return true;
204 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
205 if (HasAddressTaken(BI))
206 return true;
207 }
208 }
209 return false;
210}
211
212/// \brief Check whether or not this function needs a stack protector based
213/// upon the stack protector level.
214///
215/// We use two heuristics: a standard (ssp) and strong (sspstrong).
216/// The standard heuristic which will add a guard variable to functions that
217/// call alloca with a either a variable size or a size >= SSPBufferSize,
218/// functions with character buffers larger than SSPBufferSize, and functions
219/// with aggregates containing character buffers larger than SSPBufferSize. The
220/// strong heuristic will add a guard variables to functions that call alloca
221/// regardless of size, functions with any buffer regardless of type and size,
222/// functions with aggregates that contain any buffer regardless of type and
223/// size, and functions that contain stack-based variables that have had their
224/// address taken.
225bool StackProtector::RequiresStackProtector() {
226 bool Strong = false;
Bill Wendling831737d2012-12-30 10:32:01 +0000227 if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
228 Attribute::StackProtectReq))
Bill Wendlingc3348a72008-11-18 05:32:11 +0000229 return true;
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000230 else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
231 Attribute::StackProtectStrong))
232 Strong = true;
233 else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
234 Attribute::StackProtect))
Bill Wendlingc3348a72008-11-18 05:32:11 +0000235 return false;
236
Bill Wendlingc3348a72008-11-18 05:32:11 +0000237 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
238 BasicBlock *BB = I;
239
240 for (BasicBlock::iterator
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000241 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
Bill Wendlingc3348a72008-11-18 05:32:11 +0000242 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000243 if (AI->isArrayAllocation()) {
244 // SSP-Strong: Enable protectors for any call to alloca, regardless
245 // of size.
246 if (Strong)
247 return true;
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000248
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000249 if (const ConstantInt *CI =
250 dyn_cast<ConstantInt>(AI->getArraySize())) {
Bill Wendling0dcba2f2013-07-22 20:15:21 +0000251 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize)
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000252 // A call to alloca with size >= SSPBufferSize requires
253 // stack protectors.
254 return true;
Bill Wendling0dcba2f2013-07-22 20:15:21 +0000255 } else {
256 // A call to alloca with a variable size requires protectors.
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000257 return true;
Bill Wendling0dcba2f2013-07-22 20:15:21 +0000258 }
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000259 }
260
261 if (ContainsProtectableArray(AI->getAllocatedType(), Strong))
Bill Wendlingc3348a72008-11-18 05:32:11 +0000262 return true;
263
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000264 if (Strong && HasAddressTaken(AI)) {
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000265 ++NumAddrTaken;
Bill Wendlinga67eda72012-08-17 20:59:56 +0000266 return true;
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000267 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000268 }
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000269 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000270 }
271
272 return false;
273}
274
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000275static bool InstructionWillNotHaveChain(const Instruction *I) {
276 return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
277 isSafeToSpeculativelyExecute(I);
278}
279
280/// Identify if RI has a previous instruction in the "Tail Position" and return
281/// it. Otherwise return 0.
282///
Michael Gottesmanb99272a2013-08-20 08:56:23 +0000283/// This is based off of the code in llvm::isInTailCallPosition. The difference
284/// is that it inverts the first part of llvm::isInTailCallPosition since
285/// isInTailCallPosition is checking if a call is in a tail call position, and
286/// we are searching for an unknown tail call that might be in the tail call
287/// position. Once we find the call though, the code uses the same refactored
288/// code, returnTypeIsEligibleForTailCall.
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000289static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
290 const TargetLoweringBase *TLI) {
291 // Establish a reasonable upper bound on the maximum amount of instructions we
292 // will look through to find a tail call.
293 unsigned SearchCounter = 0;
294 const unsigned MaxSearch = 4;
295 bool NoInterposingChain = true;
296
297 for (BasicBlock::reverse_iterator I = llvm::next(BB->rbegin()), E = BB->rend();
298 I != E && SearchCounter < MaxSearch; ++I) {
299 Instruction *Inst = &*I;
300
301 // Skip over debug intrinsics and do not allow them to affect our MaxSearch
302 // counter.
303 if (isa<DbgInfoIntrinsic>(Inst))
304 continue;
305
306 // If we find a call and the following conditions are satisifed, then we
307 // have found a tail call that satisfies at least the target independent
308 // requirements of a tail call:
309 //
310 // 1. The call site has the tail marker.
311 //
312 // 2. The call site either will not cause the creation of a chain or if a
313 // chain is necessary there are no instructions in between the callsite and
314 // the call which would create an interposing chain.
315 //
316 // 3. The return type of the function does not impede tail call
317 // optimization.
318 if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
319 if (CI->isTailCall() &&
320 (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
321 returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
322 return CI;
323 }
324
325 // If we did not find a call see if we have an instruction that may create
326 // an interposing chain.
327 NoInterposingChain = NoInterposingChain && InstructionWillNotHaveChain(Inst);
328
329 // Increment max search.
330 SearchCounter++;
331 }
332
333 return 0;
334}
335
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000336/// Insert code into the entry block that stores the __stack_chk_guard
337/// variable onto the stack:
338///
339/// entry:
340/// StackGuardSlot = alloca i8*
341/// StackGuard = load __stack_chk_guard
342/// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
343///
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000344/// Returns true if the platform/triple supports the stackprotectorcreate pseudo
345/// node.
346static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000347 const TargetLoweringBase *TLI, const Triple &Trip,
348 AllocaInst *&AI, Value *&StackGuardVar) {
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000349 bool SupportsSelectionDAGSP = false;
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000350 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
351 unsigned AddressSpace, Offset;
352 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
353 Constant *OffsetVal =
354 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000355
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000356 StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
357 PointerType::get(PtrTy,
358 AddressSpace));
359 } else if (Trip.getOS() == llvm::Triple::OpenBSD) {
360 StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
361 cast<GlobalValue>(StackGuardVar)
362 ->setVisibility(GlobalValue::HiddenVisibility);
363 } else {
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000364 SupportsSelectionDAGSP = true;
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000365 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000366 }
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000367
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000368 BasicBlock &Entry = F->getEntryBlock();
369 Instruction *InsPt = &Entry.front();
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000370
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000371 AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
372 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000373
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000374 Value *Args[] = { LI, AI };
375 CallInst::
376 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
377 Args, "", InsPt);
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000378
379 return SupportsSelectionDAGSP;
Michael Gottesmanc03d5ec2013-07-22 20:44:11 +0000380}
381
Bill Wendling613f7742008-11-05 00:00:21 +0000382/// InsertStackProtectors - Insert code into the prologue and epilogue of the
383/// function.
384///
385/// - The prologue code loads and stores the stack guard onto the stack.
386/// - The epilogue checks the value stored in the prologue against the original
387/// value. It calls __stack_chk_fail if they differ.
388bool StackProtector::InsertStackProtectors() {
Michael Gottesman236e3892013-08-09 21:26:18 +0000389 bool HasPrologue = false;
Michael Gottesmand4f47882013-08-20 08:56:26 +0000390 bool SupportsSelectionDAGSP =
391 EnableSelectionDAGSP && !TM->Options.EnableFastISel;
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000392 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000393 Value *StackGuardVar = 0; // The stack guard variable.
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000394
Bill Wendling72056772008-11-10 21:13:10 +0000395 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
Bill Wendlingc3348a72008-11-18 05:32:11 +0000396 BasicBlock *BB = I++;
Bill Wendlingc3348a72008-11-18 05:32:11 +0000397 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
Michael Gottesmanade30752013-08-20 08:56:28 +0000398 if (!RI)
399 continue;
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000400
Michael Gottesman236e3892013-08-09 21:26:18 +0000401 if (!HasPrologue) {
402 HasPrologue = true;
Michael Gottesmand4f47882013-08-20 08:56:26 +0000403 SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, Trip, AI,
404 StackGuardVar);
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000405 }
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000406
Michael Gottesmand4f47882013-08-20 08:56:26 +0000407 if (SupportsSelectionDAGSP) {
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000408 // Since we have a potential tail call, insert the special stack check
409 // intrinsic.
410 Instruction *InsertionPt = 0;
411 if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
412 InsertionPt = CI;
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000413 } else {
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000414 InsertionPt = RI;
415 // At this point we know that BB has a return statement so it *DOES*
416 // have a terminator.
417 assert(InsertionPt != 0 && "BB must have a terminator instruction at "
418 "this point.");
419 }
420
421 Function *Intrinsic =
422 Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
423 Value *Args[] = { StackGuardVar };
424 CallInst::Create(Intrinsic, Args, "", InsertionPt);
425
426 } else {
Michael Gottesman47d6e072013-08-20 08:46:13 +0000427 // If we do not support SelectionDAG based tail calls, generate IR level
428 // tail calls.
429 //
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000430 // For each block with a return instruction, convert this:
431 //
432 // return:
433 // ...
434 // ret ...
435 //
436 // into this:
437 //
438 // return:
439 // ...
440 // %1 = load __stack_chk_guard
441 // %2 = load StackGuardSlot
442 // %3 = cmp i1 %1, %2
443 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
444 //
445 // SP_return:
446 // ret ...
447 //
448 // CallStackCheckFailBlk:
449 // call void @__stack_chk_fail()
450 // unreachable
451
452 // Create the FailBB. We duplicate the BB every time since the MI tail
453 // merge pass will merge together all of the various BB into one including
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000454 // fail BB generated by the stack protector pseudo instruction.
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000455 BasicBlock *FailBB = CreateFailBB();
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000456
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000457 // Split the basic block before the return instruction.
458 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000459
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000460 // Update the dominator tree if we need to.
461 if (DT && DT->isReachableFromEntry(BB)) {
462 DT->addNewBlock(NewBB, BB);
463 DT->addNewBlock(FailBB, BB);
464 }
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000465
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000466 // Remove default branch instruction to the new BB.
467 BB->getTerminator()->eraseFromParent();
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000468
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000469 // Move the newly created basic block to the point right after the old
470 // basic block so that it's in the "fall through" position.
471 NewBB->moveAfter(BB);
Michael Gottesmanc02dbeb2013-08-20 08:46:16 +0000472
Michael Gottesman3480d1b2013-08-20 08:36:53 +0000473 // Generate the stack protector instructions in the old basic block.
474 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
475 LoadInst *LI2 = new LoadInst(AI, "", true, BB);
476 ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
477 BranchInst::Create(NewBB, FailBB, Cmp, BB);
Bill Wendling1fb615f2008-11-06 23:55:49 +0000478 }
Bill Wendling2b58ce52008-11-04 02:10:20 +0000479 }
Bill Wendling613f7742008-11-05 00:00:21 +0000480
Bill Wendling1fb615f2008-11-06 23:55:49 +0000481 // Return if we didn't modify any basic blocks. I.e., there are no return
482 // statements in the function.
Michael Gottesman236e3892013-08-09 21:26:18 +0000483 if (!HasPrologue)
484 return false;
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000485
Bill Wendling613f7742008-11-05 00:00:21 +0000486 return true;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000487}
488
489/// CreateFailBB - Create a basic block to jump to when the stack protector
490/// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +0000491BasicBlock *StackProtector::CreateFailBB() {
Rafael Espindola62ed8d32013-06-07 16:35:57 +0000492 LLVMContext &Context = F->getContext();
493 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
494 if (Trip.getOS() == llvm::Triple::OpenBSD) {
495 Constant *StackChkFail = M->getOrInsertFunction(
496 "__stack_smash_handler", Type::getVoidTy(Context),
497 Type::getInt8PtrTy(Context), NULL);
498
499 Constant *NameStr = ConstantDataArray::getString(Context, F->getName());
500 Constant *FuncName =
501 new GlobalVariable(*M, NameStr->getType(), true,
502 GlobalVariable::PrivateLinkage, NameStr, "SSH");
503
504 SmallVector<Constant *, 2> IdxList;
505 IdxList.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
506 IdxList.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
507
508 SmallVector<Value *, 1> Args;
509 Args.push_back(ConstantExpr::getGetElementPtr(FuncName, IdxList));
510
511 CallInst::Create(StackChkFail, Args, "", FailBB);
512 } else {
513 Constant *StackChkFail = M->getOrInsertFunction(
514 "__stack_chk_fail", Type::getVoidTy(Context), NULL);
515 CallInst::Create(StackChkFail, "", FailBB);
516 }
517 new UnreachableInst(Context, FailBB);
Bill Wendling613f7742008-11-05 00:00:21 +0000518 return FailBB;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000519}