blob: ac5d70de706446738202d66c3a0286225b64a0ca [file] [log] [blame]
Bill Wendling05d84172008-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 Wendling64adc712008-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 Wendling05d84172008-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"
Josh Magee8ecfb522013-09-27 21:58:43 +000018#include "llvm/CodeGen/StackProtector.h"
Bill Wendling7c8f96a2013-01-23 06:43:53 +000019#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/Statistic.h"
Michael Gottesman5e570682013-08-20 08:36:53 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000022#include "llvm/CodeGen/Analysis.h"
23#include "llvm/CodeGen/Passes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Attributes.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
Rafael Espindolaaad6c242013-06-07 16:35:57 +000029#include "llvm/IR/GlobalValue.h"
30#include "llvm/IR/GlobalVariable.h"
Benjamin Kramerd93817f2013-09-09 17:38:01 +000031#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Instructions.h"
Michael Gottesman5e570682013-08-20 08:36:53 +000033#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/Module.h"
Bill Wendling05d84172008-11-04 02:10:20 +000036#include "llvm/Support/CommandLine.h"
Bill Wendlingc02a0aa2013-07-22 20:15:21 +000037#include <cstdlib>
Bill Wendling05d84172008-11-04 02:10:20 +000038using namespace llvm;
39
Bill Wendling7c8f96a2013-01-23 06:43:53 +000040STATISTIC(NumFunProtected, "Number of functions protected");
41STATISTIC(NumAddrTaken, "Number of local variables that have their address"
42 " taken.");
43
Josh Magee7245f1d2013-10-30 02:25:14 +000044static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
45 cl::init(true), cl::Hidden);
Michael Gottesman5e570682013-08-20 08:36:53 +000046
Bill Wendling05d84172008-11-04 02:10:20 +000047char StackProtector::ID = 0;
Josh Magee7245f1d2013-10-30 02:25:14 +000048INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
49 false, true)
Bill Wendling05d84172008-11-04 02:10:20 +000050
Bill Wendlingafc10362013-06-19 20:51:24 +000051FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
52 return new StackProtector(TM);
Bill Wendling05d84172008-11-04 02:10:20 +000053}
54
Josh Magee7245f1d2013-10-30 02:25:14 +000055StackProtector::SSPLayoutKind
56StackProtector::getSSPLayout(const AllocaInst *AI) const {
Josh Magee3f1c0e32013-10-29 21:16:16 +000057 return AI ? Layout.lookup(AI) : SSPLK_None;
58}
59
Bill Wendling05d84172008-11-04 02:10:20 +000060bool StackProtector::runOnFunction(Function &Fn) {
61 F = &Fn;
62 M = F->getParent();
Cameron Zwarich84986b22011-01-08 17:01:52 +000063 DT = getAnalysisIfAvailable<DominatorTree>();
Bill Wendlingafc10362013-06-19 20:51:24 +000064 TLI = TM->getTargetLowering();
Bill Wendling05d84172008-11-04 02:10:20 +000065
Josh Magee7245f1d2013-10-30 02:25:14 +000066 if (!RequiresStackProtector())
67 return false;
Bill Wendling49aeb5c2012-08-13 21:20:43 +000068
Josh Magee7245f1d2013-10-30 02:25:14 +000069 Attribute Attr = Fn.getAttributes().getAttribute(
70 AttributeSet::FunctionIndex, "stack-protector-buffer-size");
Bill Wendlingc02a0aa2013-07-22 20:15:21 +000071 if (Attr.isStringAttribute())
Benjamin Kramerd93817f2013-09-09 17:38:01 +000072 Attr.getValueAsString().getAsInteger(10, SSPBufferSize);
Bill Wendlingc02a0aa2013-07-22 20:15:21 +000073
Bill Wendling7c8f96a2013-01-23 06:43:53 +000074 ++NumFunProtected;
Bill Wendling782e8342008-11-05 00:00:21 +000075 return InsertStackProtectors();
Bill Wendling05d84172008-11-04 02:10:20 +000076}
77
Josh Magee3f1c0e32013-10-29 21:16:16 +000078/// \param [out] IsLarge is set to true if a protectable array is found and
79/// it is "large" ( >= ssp-buffer-size). In the case of a structure with
80/// multiple arrays, this gets set if any of them is large.
81bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
Josh Magee7245f1d2013-10-30 02:25:14 +000082 bool Strong,
83 bool InStruct) const {
84 if (!Ty)
85 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +000086 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
87 if (!AT->getElementType()->isIntegerTy(8)) {
Bill Wendlingbfb9b752012-08-17 20:59:56 +000088 // If we're on a non-Darwin platform or we're inside of a structure, don't
89 // add stack protectors unless the array is a character array.
Josh Magee3f1c0e32013-10-29 21:16:16 +000090 // However, in strong mode any array, regardless of type and size,
91 // triggers a protector.
92 if (!Strong && (InStruct || !Trip.isOSDarwin()))
93 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +000094 }
95
96 // If an array has more than SSPBufferSize bytes of allocated space, then we
97 // emit stack protectors.
Josh Magee3f1c0e32013-10-29 21:16:16 +000098 if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT)) {
99 IsLarge = true;
100 return true;
Josh Magee7245f1d2013-10-30 02:25:14 +0000101 }
Josh Magee3f1c0e32013-10-29 21:16:16 +0000102
103 if (Strong)
104 // Require a protector for all arrays in strong mode
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000105 return true;
106 }
107
108 const StructType *ST = dyn_cast<StructType>(Ty);
Josh Magee7245f1d2013-10-30 02:25:14 +0000109 if (!ST)
110 return false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000111
Josh Magee3f1c0e32013-10-29 21:16:16 +0000112 bool NeedsProtector = false;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000113 for (StructType::element_iterator I = ST->element_begin(),
Josh Magee7245f1d2013-10-30 02:25:14 +0000114 E = ST->element_end();
115 I != E; ++I)
Josh Magee3f1c0e32013-10-29 21:16:16 +0000116 if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
117 // If the element is a protectable array and is large (>= SSPBufferSize)
118 // then we are done. If the protectable array is not large, then
119 // keep looking in case a subsequent element is a large array.
120 if (IsLarge)
121 return true;
122 NeedsProtector = true;
123 }
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000124
Josh Magee3f1c0e32013-10-29 21:16:16 +0000125 return NeedsProtector;
Bill Wendlingbfb9b752012-08-17 20:59:56 +0000126}
127
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000128bool StackProtector::HasAddressTaken(const Instruction *AI) {
129 for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
Josh Magee7245f1d2013-10-30 02:25:14 +0000130 UI != UE; ++UI) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000131 const User *U = *UI;
132 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
133 if (AI == SI->getValueOperand())
134 return true;
135 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
136 if (AI == SI->getOperand(0))
137 return true;
138 } else if (isa<CallInst>(U)) {
139 return true;
140 } else if (isa<InvokeInst>(U)) {
141 return true;
142 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
143 if (HasAddressTaken(SI))
144 return true;
145 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
146 // Keep track of what PHI nodes we have already visited to ensure
147 // they are only visited once.
148 if (VisitedPHIs.insert(PN))
149 if (HasAddressTaken(PN))
150 return true;
151 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
152 if (HasAddressTaken(GEP))
153 return true;
154 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
155 if (HasAddressTaken(BI))
156 return true;
157 }
158 }
159 return false;
160}
161
162/// \brief Check whether or not this function needs a stack protector based
163/// upon the stack protector level.
164///
165/// We use two heuristics: a standard (ssp) and strong (sspstrong).
166/// The standard heuristic which will add a guard variable to functions that
167/// call alloca with a either a variable size or a size >= SSPBufferSize,
168/// functions with character buffers larger than SSPBufferSize, and functions
169/// with aggregates containing character buffers larger than SSPBufferSize. The
170/// strong heuristic will add a guard variables to functions that call alloca
171/// regardless of size, functions with any buffer regardless of type and size,
172/// functions with aggregates that contain any buffer regardless of type and
173/// size, and functions that contain stack-based variables that have had their
174/// address taken.
175bool StackProtector::RequiresStackProtector() {
176 bool Strong = false;
Josh Magee3f1c0e32013-10-29 21:16:16 +0000177 bool NeedsProtector = false;
Bill Wendling698e84f2012-12-30 10:32:01 +0000178 if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
Josh Magee3f1c0e32013-10-29 21:16:16 +0000179 Attribute::StackProtectReq)) {
180 NeedsProtector = true;
181 Strong = true; // Use the same heuristic as strong to determine SSPLayout
182 } else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
183 Attribute::StackProtectStrong))
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000184 Strong = true;
185 else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
186 Attribute::StackProtect))
Bill Wendlingeeb04152008-11-18 05:32:11 +0000187 return false;
188
Bill Wendlingeeb04152008-11-18 05:32:11 +0000189 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
190 BasicBlock *BB = I;
191
Josh Magee7245f1d2013-10-30 02:25:14 +0000192 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
193 ++II) {
Bill Wendlingeeb04152008-11-18 05:32:11 +0000194 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000195 if (AI->isArrayAllocation()) {
196 // SSP-Strong: Enable protectors for any call to alloca, regardless
197 // of size.
198 if (Strong)
199 return true;
Michael Gottesman62c5d712013-08-20 08:46:16 +0000200
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000201 if (const ConstantInt *CI =
Josh Magee7245f1d2013-10-30 02:25:14 +0000202 dyn_cast<ConstantInt>(AI->getArraySize())) {
Josh Magee3f1c0e32013-10-29 21:16:16 +0000203 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000204 // A call to alloca with size >= SSPBufferSize requires
205 // stack protectors.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000206 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
207 NeedsProtector = true;
208 } else if (Strong) {
209 // Require protectors for all alloca calls in strong mode.
210 Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
211 NeedsProtector = true;
212 }
Bill Wendlingc02a0aa2013-07-22 20:15:21 +0000213 } else {
214 // A call to alloca with a variable size requires protectors.
Josh Magee3f1c0e32013-10-29 21:16:16 +0000215 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
216 NeedsProtector = true;
Bill Wendlingc02a0aa2013-07-22 20:15:21 +0000217 }
Josh Magee3f1c0e32013-10-29 21:16:16 +0000218 continue;
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000219 }
220
Josh Magee3f1c0e32013-10-29 21:16:16 +0000221 bool IsLarge = false;
222 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
223 Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
224 : SSPLK_SmallArray));
225 NeedsProtector = true;
226 continue;
227 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000228
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000229 if (Strong && HasAddressTaken(AI)) {
Michael Gottesman62c5d712013-08-20 08:46:16 +0000230 ++NumAddrTaken;
Josh Magee3f1c0e32013-10-29 21:16:16 +0000231 Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
232 NeedsProtector = true;
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000233 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000234 }
Bill Wendling7c8f96a2013-01-23 06:43:53 +0000235 }
Bill Wendlingeeb04152008-11-18 05:32:11 +0000236 }
237
Josh Magee3f1c0e32013-10-29 21:16:16 +0000238 return NeedsProtector;
Bill Wendlingeeb04152008-11-18 05:32:11 +0000239}
240
Michael Gottesman5e570682013-08-20 08:36:53 +0000241static bool InstructionWillNotHaveChain(const Instruction *I) {
242 return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
Josh Magee7245f1d2013-10-30 02:25:14 +0000243 isSafeToSpeculativelyExecute(I);
Michael Gottesman5e570682013-08-20 08:36:53 +0000244}
245
246/// Identify if RI has a previous instruction in the "Tail Position" and return
247/// it. Otherwise return 0.
248///
Michael Gottesman1977d152013-08-20 08:56:23 +0000249/// This is based off of the code in llvm::isInTailCallPosition. The difference
250/// is that it inverts the first part of llvm::isInTailCallPosition since
251/// isInTailCallPosition is checking if a call is in a tail call position, and
252/// we are searching for an unknown tail call that might be in the tail call
253/// position. Once we find the call though, the code uses the same refactored
254/// code, returnTypeIsEligibleForTailCall.
Michael Gottesman5e570682013-08-20 08:36:53 +0000255static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
256 const TargetLoweringBase *TLI) {
257 // Establish a reasonable upper bound on the maximum amount of instructions we
258 // will look through to find a tail call.
259 unsigned SearchCounter = 0;
260 const unsigned MaxSearch = 4;
261 bool NoInterposingChain = true;
262
Josh Magee7245f1d2013-10-30 02:25:14 +0000263 for (BasicBlock::reverse_iterator I = llvm::next(BB->rbegin()),
264 E = BB->rend();
Michael Gottesman5e570682013-08-20 08:36:53 +0000265 I != E && SearchCounter < MaxSearch; ++I) {
266 Instruction *Inst = &*I;
267
268 // Skip over debug intrinsics and do not allow them to affect our MaxSearch
269 // counter.
270 if (isa<DbgInfoIntrinsic>(Inst))
271 continue;
272
273 // If we find a call and the following conditions are satisifed, then we
274 // have found a tail call that satisfies at least the target independent
275 // requirements of a tail call:
276 //
277 // 1. The call site has the tail marker.
278 //
279 // 2. The call site either will not cause the creation of a chain or if a
280 // chain is necessary there are no instructions in between the callsite and
281 // the call which would create an interposing chain.
282 //
283 // 3. The return type of the function does not impede tail call
284 // optimization.
285 if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
286 if (CI->isTailCall() &&
287 (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
288 returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
289 return CI;
290 }
291
292 // If we did not find a call see if we have an instruction that may create
293 // an interposing chain.
Josh Magee7245f1d2013-10-30 02:25:14 +0000294 NoInterposingChain =
295 NoInterposingChain && InstructionWillNotHaveChain(Inst);
Michael Gottesman5e570682013-08-20 08:36:53 +0000296
297 // Increment max search.
298 SearchCounter++;
299 }
300
301 return 0;
302}
303
Michael Gottesmana6188f92013-07-22 20:44:11 +0000304/// Insert code into the entry block that stores the __stack_chk_guard
305/// variable onto the stack:
306///
307/// entry:
308/// StackGuardSlot = alloca i8*
309/// StackGuard = load __stack_chk_guard
310/// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
311///
Michael Gottesman5e570682013-08-20 08:36:53 +0000312/// Returns true if the platform/triple supports the stackprotectorcreate pseudo
313/// node.
314static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
Michael Gottesmana6188f92013-07-22 20:44:11 +0000315 const TargetLoweringBase *TLI, const Triple &Trip,
316 AllocaInst *&AI, Value *&StackGuardVar) {
Michael Gottesman5e570682013-08-20 08:36:53 +0000317 bool SupportsSelectionDAGSP = false;
Michael Gottesmana6188f92013-07-22 20:44:11 +0000318 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
319 unsigned AddressSpace, Offset;
320 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
321 Constant *OffsetVal =
Josh Magee7245f1d2013-10-30 02:25:14 +0000322 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
Michael Gottesman62c5d712013-08-20 08:46:16 +0000323
Josh Magee7245f1d2013-10-30 02:25:14 +0000324 StackGuardVar = ConstantExpr::getIntToPtr(
325 OffsetVal, PointerType::get(PtrTy, AddressSpace));
Michael Gottesmana6188f92013-07-22 20:44:11 +0000326 } else if (Trip.getOS() == llvm::Triple::OpenBSD) {
327 StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
328 cast<GlobalValue>(StackGuardVar)
Josh Magee7245f1d2013-10-30 02:25:14 +0000329 ->setVisibility(GlobalValue::HiddenVisibility);
Michael Gottesmana6188f92013-07-22 20:44:11 +0000330 } else {
Michael Gottesman5e570682013-08-20 08:36:53 +0000331 SupportsSelectionDAGSP = true;
Michael Gottesman62c5d712013-08-20 08:46:16 +0000332 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
Michael Gottesmana6188f92013-07-22 20:44:11 +0000333 }
Michael Gottesman62c5d712013-08-20 08:46:16 +0000334
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000335 IRBuilder<> B(&F->getEntryBlock().front());
336 AI = B.CreateAlloca(PtrTy, 0, "StackGuardSlot");
337 LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
338 B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI,
339 AI);
Michael Gottesman5e570682013-08-20 08:36:53 +0000340
341 return SupportsSelectionDAGSP;
Michael Gottesmana6188f92013-07-22 20:44:11 +0000342}
343
Bill Wendling782e8342008-11-05 00:00:21 +0000344/// InsertStackProtectors - Insert code into the prologue and epilogue of the
345/// function.
346///
347/// - The prologue code loads and stores the stack guard onto the stack.
348/// - The epilogue checks the value stored in the prologue against the original
349/// value. It calls __stack_chk_fail if they differ.
350bool StackProtector::InsertStackProtectors() {
Michael Gottesman8afcf3a2013-08-09 21:26:18 +0000351 bool HasPrologue = false;
Michael Gottesman76c44be2013-08-20 08:56:26 +0000352 bool SupportsSelectionDAGSP =
Josh Magee7245f1d2013-10-30 02:25:14 +0000353 EnableSelectionDAGSP && !TM->Options.EnableFastISel;
354 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
355 Value *StackGuardVar = 0; // The stack guard variable.
Bill Wendlingeb4268d2008-11-07 01:23:58 +0000356
Josh Magee7245f1d2013-10-30 02:25:14 +0000357 for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
Bill Wendlingeeb04152008-11-18 05:32:11 +0000358 BasicBlock *BB = I++;
Bill Wendlingeeb04152008-11-18 05:32:11 +0000359 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
Michael Gottesmandc985ef2013-08-20 08:56:28 +0000360 if (!RI)
361 continue;
Bill Wendlingeb4268d2008-11-07 01:23:58 +0000362
Michael Gottesman8afcf3a2013-08-09 21:26:18 +0000363 if (!HasPrologue) {
364 HasPrologue = true;
Josh Magee7245f1d2013-10-30 02:25:14 +0000365 SupportsSelectionDAGSP &=
366 CreatePrologue(F, M, RI, TLI, Trip, AI, StackGuardVar);
Michael Gottesman62c5d712013-08-20 08:46:16 +0000367 }
Michael Gottesman5e570682013-08-20 08:36:53 +0000368
Michael Gottesman76c44be2013-08-20 08:56:26 +0000369 if (SupportsSelectionDAGSP) {
Michael Gottesman5e570682013-08-20 08:36:53 +0000370 // Since we have a potential tail call, insert the special stack check
371 // intrinsic.
372 Instruction *InsertionPt = 0;
373 if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
374 InsertionPt = CI;
Michael Gottesman62c5d712013-08-20 08:46:16 +0000375 } else {
Michael Gottesman5e570682013-08-20 08:36:53 +0000376 InsertionPt = RI;
377 // At this point we know that BB has a return statement so it *DOES*
378 // have a terminator.
379 assert(InsertionPt != 0 && "BB must have a terminator instruction at "
Josh Magee7245f1d2013-10-30 02:25:14 +0000380 "this point.");
Michael Gottesman5e570682013-08-20 08:36:53 +0000381 }
382
383 Function *Intrinsic =
Josh Magee7245f1d2013-10-30 02:25:14 +0000384 Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000385 CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt);
Michael Gottesman5e570682013-08-20 08:36:53 +0000386
387 } else {
Michael Gottesman56e246b2013-08-20 08:46:13 +0000388 // If we do not support SelectionDAG based tail calls, generate IR level
389 // tail calls.
390 //
Michael Gottesman5e570682013-08-20 08:36:53 +0000391 // For each block with a return instruction, convert this:
392 //
393 // return:
394 // ...
395 // ret ...
396 //
397 // into this:
398 //
399 // return:
400 // ...
401 // %1 = load __stack_chk_guard
402 // %2 = load StackGuardSlot
403 // %3 = cmp i1 %1, %2
404 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
405 //
406 // SP_return:
407 // ret ...
408 //
409 // CallStackCheckFailBlk:
410 // call void @__stack_chk_fail()
411 // unreachable
412
413 // Create the FailBB. We duplicate the BB every time since the MI tail
414 // merge pass will merge together all of the various BB into one including
Michael Gottesman62c5d712013-08-20 08:46:16 +0000415 // fail BB generated by the stack protector pseudo instruction.
Michael Gottesman5e570682013-08-20 08:36:53 +0000416 BasicBlock *FailBB = CreateFailBB();
Michael Gottesman62c5d712013-08-20 08:46:16 +0000417
Michael Gottesman5e570682013-08-20 08:36:53 +0000418 // Split the basic block before the return instruction.
419 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
Michael Gottesman62c5d712013-08-20 08:46:16 +0000420
Michael Gottesman5e570682013-08-20 08:36:53 +0000421 // Update the dominator tree if we need to.
422 if (DT && DT->isReachableFromEntry(BB)) {
423 DT->addNewBlock(NewBB, BB);
424 DT->addNewBlock(FailBB, BB);
425 }
Michael Gottesman62c5d712013-08-20 08:46:16 +0000426
Michael Gottesman5e570682013-08-20 08:36:53 +0000427 // Remove default branch instruction to the new BB.
428 BB->getTerminator()->eraseFromParent();
Michael Gottesman62c5d712013-08-20 08:46:16 +0000429
Michael Gottesman5e570682013-08-20 08:36:53 +0000430 // Move the newly created basic block to the point right after the old
431 // basic block so that it's in the "fall through" position.
432 NewBB->moveAfter(BB);
Michael Gottesman62c5d712013-08-20 08:46:16 +0000433
Michael Gottesman5e570682013-08-20 08:36:53 +0000434 // Generate the stack protector instructions in the old basic block.
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000435 IRBuilder<> B(BB);
436 LoadInst *LI1 = B.CreateLoad(StackGuardVar);
437 LoadInst *LI2 = B.CreateLoad(AI);
438 Value *Cmp = B.CreateICmpEQ(LI1, LI2);
439 B.CreateCondBr(Cmp, NewBB, FailBB);
Bill Wendlinga0826e182008-11-06 23:55:49 +0000440 }
Bill Wendling05d84172008-11-04 02:10:20 +0000441 }
Bill Wendling782e8342008-11-05 00:00:21 +0000442
Bill Wendlinga0826e182008-11-06 23:55:49 +0000443 // Return if we didn't modify any basic blocks. I.e., there are no return
444 // statements in the function.
Michael Gottesman8afcf3a2013-08-09 21:26:18 +0000445 if (!HasPrologue)
446 return false;
Cameron Zwarich84986b22011-01-08 17:01:52 +0000447
Bill Wendling782e8342008-11-05 00:00:21 +0000448 return true;
Bill Wendling05d84172008-11-04 02:10:20 +0000449}
450
451/// CreateFailBB - Create a basic block to jump to when the stack protector
452/// check fails.
Bill Wendling782e8342008-11-05 00:00:21 +0000453BasicBlock *StackProtector::CreateFailBB() {
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000454 LLVMContext &Context = F->getContext();
455 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000456 IRBuilder<> B(FailBB);
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000457 if (Trip.getOS() == llvm::Triple::OpenBSD) {
458 Constant *StackChkFail = M->getOrInsertFunction(
459 "__stack_smash_handler", Type::getVoidTy(Context),
460 Type::getInt8PtrTy(Context), NULL);
461
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000462 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000463 } else {
464 Constant *StackChkFail = M->getOrInsertFunction(
465 "__stack_chk_fail", Type::getVoidTy(Context), NULL);
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000466 B.CreateCall(StackChkFail);
Rafael Espindolaaad6c242013-06-07 16:35:57 +0000467 }
Benjamin Kramerd93817f2013-09-09 17:38:01 +0000468 B.CreateUnreachable();
Bill Wendling782e8342008-11-05 00:00:21 +0000469 return FailBB;
Bill Wendling05d84172008-11-04 02:10:20 +0000470}