1f22ef01cSRoman Divacky //===-- StackProtector.cpp - Stack Protector Insertion --------------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This pass inserts stack protectors into functions which need them. A variable
11f22ef01cSRoman Divacky // with a random value in it is stored onto the stack before the local variables
12f22ef01cSRoman Divacky // are allocated. Upon exiting the block, the stored value is checked. If it's
13f22ef01cSRoman Divacky // changed, then there was some sort of violation and the program aborts.
14f22ef01cSRoman Divacky //
15f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
16f22ef01cSRoman Divacky 
17f22ef01cSRoman Divacky #define DEBUG_TYPE "stack-protector"
18f785676fSDimitry Andric #include "llvm/CodeGen/StackProtector.h"
19f785676fSDimitry Andric #include "llvm/CodeGen/Analysis.h"
20f22ef01cSRoman Divacky #include "llvm/CodeGen/Passes.h"
21139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
22139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
232754fe60SDimitry Andric #include "llvm/Analysis/Dominators.h"
24f785676fSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
25139f7f9bSDimitry Andric #include "llvm/IR/Attributes.h"
26139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
27139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
28139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
29139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
30f785676fSDimitry Andric #include "llvm/IR/GlobalValue.h"
31f785676fSDimitry Andric #include "llvm/IR/GlobalVariable.h"
32f785676fSDimitry Andric #include "llvm/IR/IRBuilder.h"
33139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
34f785676fSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
35139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
36139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
37f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h"
38f785676fSDimitry Andric #include <cstdlib>
39f22ef01cSRoman Divacky using namespace llvm;
40f22ef01cSRoman Divacky 
41139f7f9bSDimitry Andric STATISTIC(NumFunProtected, "Number of functions protected");
42139f7f9bSDimitry Andric STATISTIC(NumAddrTaken, "Number of local variables that have their address"
43139f7f9bSDimitry Andric                         " taken.");
44139f7f9bSDimitry Andric 
45f785676fSDimitry Andric static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
46f785676fSDimitry Andric                                           cl::init(true), cl::Hidden);
47f22ef01cSRoman Divacky 
48f22ef01cSRoman Divacky char StackProtector::ID = 0;
49f785676fSDimitry Andric INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
50f785676fSDimitry Andric                 false, true)
51f22ef01cSRoman Divacky 
52f785676fSDimitry Andric FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
53f785676fSDimitry Andric   return new StackProtector(TM);
54f785676fSDimitry Andric }
55f785676fSDimitry Andric 
56f785676fSDimitry Andric StackProtector::SSPLayoutKind
57f785676fSDimitry Andric StackProtector::getSSPLayout(const AllocaInst *AI) const {
58f785676fSDimitry Andric   return AI ? Layout.lookup(AI) : SSPLK_None;
59f22ef01cSRoman Divacky }
60f22ef01cSRoman Divacky 
61f22ef01cSRoman Divacky bool StackProtector::runOnFunction(Function &Fn) {
62f22ef01cSRoman Divacky   F = &Fn;
63f22ef01cSRoman Divacky   M = F->getParent();
642754fe60SDimitry Andric   DT = getAnalysisIfAvailable<DominatorTree>();
65f785676fSDimitry Andric   TLI = TM->getTargetLowering();
66f22ef01cSRoman Divacky 
67f785676fSDimitry Andric   if (!RequiresStackProtector())
68f785676fSDimitry Andric     return false;
69f785676fSDimitry Andric 
70f785676fSDimitry Andric   Attribute Attr = Fn.getAttributes().getAttribute(
71f785676fSDimitry Andric       AttributeSet::FunctionIndex, "stack-protector-buffer-size");
72f785676fSDimitry Andric   if (Attr.isStringAttribute())
73f785676fSDimitry Andric     Attr.getValueAsString().getAsInteger(10, SSPBufferSize);
74f22ef01cSRoman Divacky 
75139f7f9bSDimitry Andric   ++NumFunProtected;
76f22ef01cSRoman Divacky   return InsertStackProtectors();
77f22ef01cSRoman Divacky }
78f22ef01cSRoman Divacky 
79f785676fSDimitry Andric /// \param [out] IsLarge is set to true if a protectable array is found and
80f785676fSDimitry Andric /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
81f785676fSDimitry Andric /// multiple arrays, this gets set if any of them is large.
82f785676fSDimitry Andric bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
83f785676fSDimitry Andric                                               bool Strong,
84139f7f9bSDimitry Andric                                               bool InStruct) const {
85f785676fSDimitry Andric   if (!Ty)
86f785676fSDimitry Andric     return false;
873861d79fSDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
883861d79fSDimitry Andric     if (!AT->getElementType()->isIntegerTy(8)) {
893861d79fSDimitry Andric       // If we're on a non-Darwin platform or we're inside of a structure, don't
903861d79fSDimitry Andric       // add stack protectors unless the array is a character array.
91f785676fSDimitry Andric       // However, in strong mode any array, regardless of type and size,
92f785676fSDimitry Andric       // triggers a protector.
93f785676fSDimitry Andric       if (!Strong && (InStruct || !Trip.isOSDarwin()))
943861d79fSDimitry Andric         return false;
953861d79fSDimitry Andric     }
963861d79fSDimitry Andric 
973861d79fSDimitry Andric     // If an array has more than SSPBufferSize bytes of allocated space, then we
983861d79fSDimitry Andric     // emit stack protectors.
99f785676fSDimitry Andric     if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT)) {
100f785676fSDimitry Andric       IsLarge = true;
101f785676fSDimitry Andric       return true;
102f785676fSDimitry Andric     }
103f785676fSDimitry Andric 
104f785676fSDimitry Andric     if (Strong)
105f785676fSDimitry Andric       // Require a protector for all arrays in strong mode
1063861d79fSDimitry Andric       return true;
1073861d79fSDimitry Andric   }
1083861d79fSDimitry Andric 
1093861d79fSDimitry Andric   const StructType *ST = dyn_cast<StructType>(Ty);
110f785676fSDimitry Andric   if (!ST)
1113861d79fSDimitry Andric     return false;
112f785676fSDimitry Andric 
113f785676fSDimitry Andric   bool NeedsProtector = false;
114f785676fSDimitry Andric   for (StructType::element_iterator I = ST->element_begin(),
115f785676fSDimitry Andric                                     E = ST->element_end();
116f785676fSDimitry Andric        I != E; ++I)
117f785676fSDimitry Andric     if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
118f785676fSDimitry Andric       // If the element is a protectable array and is large (>= SSPBufferSize)
119f785676fSDimitry Andric       // then we are done.  If the protectable array is not large, then
120f785676fSDimitry Andric       // keep looking in case a subsequent element is a large array.
121f785676fSDimitry Andric       if (IsLarge)
122f785676fSDimitry Andric         return true;
123f785676fSDimitry Andric       NeedsProtector = true;
124f785676fSDimitry Andric     }
125f785676fSDimitry Andric 
126f785676fSDimitry Andric   return NeedsProtector;
1273861d79fSDimitry Andric }
1283861d79fSDimitry Andric 
129139f7f9bSDimitry Andric bool StackProtector::HasAddressTaken(const Instruction *AI) {
130139f7f9bSDimitry Andric   for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
131139f7f9bSDimitry Andric        UI != UE; ++UI) {
132139f7f9bSDimitry Andric     const User *U = *UI;
133139f7f9bSDimitry Andric     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
134139f7f9bSDimitry Andric       if (AI == SI->getValueOperand())
135f22ef01cSRoman Divacky         return true;
136139f7f9bSDimitry Andric     } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
137139f7f9bSDimitry Andric       if (AI == SI->getOperand(0))
138139f7f9bSDimitry Andric         return true;
139139f7f9bSDimitry Andric     } else if (isa<CallInst>(U)) {
140139f7f9bSDimitry Andric       return true;
141139f7f9bSDimitry Andric     } else if (isa<InvokeInst>(U)) {
142139f7f9bSDimitry Andric       return true;
143139f7f9bSDimitry Andric     } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
144139f7f9bSDimitry Andric       if (HasAddressTaken(SI))
145139f7f9bSDimitry Andric         return true;
146139f7f9bSDimitry Andric     } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
147139f7f9bSDimitry Andric       // Keep track of what PHI nodes we have already visited to ensure
148139f7f9bSDimitry Andric       // they are only visited once.
149139f7f9bSDimitry Andric       if (VisitedPHIs.insert(PN))
150139f7f9bSDimitry Andric         if (HasAddressTaken(PN))
151139f7f9bSDimitry Andric           return true;
152139f7f9bSDimitry Andric     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
153139f7f9bSDimitry Andric       if (HasAddressTaken(GEP))
154139f7f9bSDimitry Andric         return true;
155139f7f9bSDimitry Andric     } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
156139f7f9bSDimitry Andric       if (HasAddressTaken(BI))
157139f7f9bSDimitry Andric         return true;
158139f7f9bSDimitry Andric     }
159139f7f9bSDimitry Andric   }
160139f7f9bSDimitry Andric   return false;
161139f7f9bSDimitry Andric }
162f22ef01cSRoman Divacky 
163139f7f9bSDimitry Andric /// \brief Check whether or not this function needs a stack protector based
164139f7f9bSDimitry Andric /// upon the stack protector level.
165139f7f9bSDimitry Andric ///
166139f7f9bSDimitry Andric /// We use two heuristics: a standard (ssp) and strong (sspstrong).
167139f7f9bSDimitry Andric /// The standard heuristic which will add a guard variable to functions that
168139f7f9bSDimitry Andric /// call alloca with a either a variable size or a size >= SSPBufferSize,
169139f7f9bSDimitry Andric /// functions with character buffers larger than SSPBufferSize, and functions
170139f7f9bSDimitry Andric /// with aggregates containing character buffers larger than SSPBufferSize. The
171139f7f9bSDimitry Andric /// strong heuristic will add a guard variables to functions that call alloca
172139f7f9bSDimitry Andric /// regardless of size, functions with any buffer regardless of type and size,
173139f7f9bSDimitry Andric /// functions with aggregates that contain any buffer regardless of type and
174139f7f9bSDimitry Andric /// size, and functions that contain stack-based variables that have had their
175139f7f9bSDimitry Andric /// address taken.
176139f7f9bSDimitry Andric bool StackProtector::RequiresStackProtector() {
177139f7f9bSDimitry Andric   bool Strong = false;
178f785676fSDimitry Andric   bool NeedsProtector = false;
179139f7f9bSDimitry Andric   if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
180f785676fSDimitry Andric                                       Attribute::StackProtectReq)) {
181f785676fSDimitry Andric     NeedsProtector = true;
182f785676fSDimitry Andric     Strong = true; // Use the same heuristic as strong to determine SSPLayout
183f785676fSDimitry Andric   } else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
184139f7f9bSDimitry Andric                                              Attribute::StackProtectStrong))
185139f7f9bSDimitry Andric     Strong = true;
186139f7f9bSDimitry Andric   else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
187139f7f9bSDimitry Andric                                             Attribute::StackProtect))
188f22ef01cSRoman Divacky     return false;
189f22ef01cSRoman Divacky 
190f22ef01cSRoman Divacky   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
191f22ef01cSRoman Divacky     BasicBlock *BB = I;
192f22ef01cSRoman Divacky 
193f785676fSDimitry Andric     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
194f785676fSDimitry Andric          ++II) {
195f22ef01cSRoman Divacky       if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
196139f7f9bSDimitry Andric         if (AI->isArrayAllocation()) {
197139f7f9bSDimitry Andric           // SSP-Strong: Enable protectors for any call to alloca, regardless
198139f7f9bSDimitry Andric           // of size.
199139f7f9bSDimitry Andric           if (Strong)
200f22ef01cSRoman Divacky             return true;
201f22ef01cSRoman Divacky 
202139f7f9bSDimitry Andric           if (const ConstantInt *CI =
203139f7f9bSDimitry Andric                   dyn_cast<ConstantInt>(AI->getArraySize())) {
204f785676fSDimitry Andric             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
205139f7f9bSDimitry Andric               // A call to alloca with size >= SSPBufferSize requires
206139f7f9bSDimitry Andric               // stack protectors.
207f785676fSDimitry Andric               Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
208f785676fSDimitry Andric               NeedsProtector = true;
209f785676fSDimitry Andric             } else if (Strong) {
210f785676fSDimitry Andric               // Require protectors for all alloca calls in strong mode.
211f785676fSDimitry Andric               Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
212f785676fSDimitry Andric               NeedsProtector = true;
213f785676fSDimitry Andric             }
214f785676fSDimitry Andric           } else {
215f785676fSDimitry Andric             // A call to alloca with a variable size requires protectors.
216f785676fSDimitry Andric             Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
217f785676fSDimitry Andric             NeedsProtector = true;
218f785676fSDimitry Andric           }
219f785676fSDimitry Andric           continue;
220139f7f9bSDimitry Andric         }
221139f7f9bSDimitry Andric 
222f785676fSDimitry Andric         bool IsLarge = false;
223f785676fSDimitry Andric         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
224f785676fSDimitry Andric           Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
225f785676fSDimitry Andric                                                    : SSPLK_SmallArray));
226f785676fSDimitry Andric           NeedsProtector = true;
227f785676fSDimitry Andric           continue;
228f785676fSDimitry Andric         }
229139f7f9bSDimitry Andric 
230139f7f9bSDimitry Andric         if (Strong && HasAddressTaken(AI)) {
231139f7f9bSDimitry Andric           ++NumAddrTaken;
232f785676fSDimitry Andric           Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
233f785676fSDimitry Andric           NeedsProtector = true;
234139f7f9bSDimitry Andric         }
235139f7f9bSDimitry Andric       }
236f22ef01cSRoman Divacky     }
237f22ef01cSRoman Divacky   }
238f22ef01cSRoman Divacky 
239f785676fSDimitry Andric   return NeedsProtector;
240f785676fSDimitry Andric }
241f785676fSDimitry Andric 
242f785676fSDimitry Andric static bool InstructionWillNotHaveChain(const Instruction *I) {
243f785676fSDimitry Andric   return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
244f785676fSDimitry Andric          isSafeToSpeculativelyExecute(I);
245f785676fSDimitry Andric }
246f785676fSDimitry Andric 
247f785676fSDimitry Andric /// Identify if RI has a previous instruction in the "Tail Position" and return
248f785676fSDimitry Andric /// it. Otherwise return 0.
249f785676fSDimitry Andric ///
250f785676fSDimitry Andric /// This is based off of the code in llvm::isInTailCallPosition. The difference
251f785676fSDimitry Andric /// is that it inverts the first part of llvm::isInTailCallPosition since
252f785676fSDimitry Andric /// isInTailCallPosition is checking if a call is in a tail call position, and
253f785676fSDimitry Andric /// we are searching for an unknown tail call that might be in the tail call
254f785676fSDimitry Andric /// position. Once we find the call though, the code uses the same refactored
255f785676fSDimitry Andric /// code, returnTypeIsEligibleForTailCall.
256f785676fSDimitry Andric static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
257f785676fSDimitry Andric                                        const TargetLoweringBase *TLI) {
258f785676fSDimitry Andric   // Establish a reasonable upper bound on the maximum amount of instructions we
259f785676fSDimitry Andric   // will look through to find a tail call.
260f785676fSDimitry Andric   unsigned SearchCounter = 0;
261f785676fSDimitry Andric   const unsigned MaxSearch = 4;
262f785676fSDimitry Andric   bool NoInterposingChain = true;
263f785676fSDimitry Andric 
264f785676fSDimitry Andric   for (BasicBlock::reverse_iterator I = llvm::next(BB->rbegin()),
265f785676fSDimitry Andric                                     E = BB->rend();
266f785676fSDimitry Andric        I != E && SearchCounter < MaxSearch; ++I) {
267f785676fSDimitry Andric     Instruction *Inst = &*I;
268f785676fSDimitry Andric 
269f785676fSDimitry Andric     // Skip over debug intrinsics and do not allow them to affect our MaxSearch
270f785676fSDimitry Andric     // counter.
271f785676fSDimitry Andric     if (isa<DbgInfoIntrinsic>(Inst))
272f785676fSDimitry Andric       continue;
273f785676fSDimitry Andric 
274f785676fSDimitry Andric     // If we find a call and the following conditions are satisifed, then we
275f785676fSDimitry Andric     // have found a tail call that satisfies at least the target independent
276f785676fSDimitry Andric     // requirements of a tail call:
277f785676fSDimitry Andric     //
278f785676fSDimitry Andric     // 1. The call site has the tail marker.
279f785676fSDimitry Andric     //
280f785676fSDimitry Andric     // 2. The call site either will not cause the creation of a chain or if a
281f785676fSDimitry Andric     // chain is necessary there are no instructions in between the callsite and
282f785676fSDimitry Andric     // the call which would create an interposing chain.
283f785676fSDimitry Andric     //
284f785676fSDimitry Andric     // 3. The return type of the function does not impede tail call
285f785676fSDimitry Andric     // optimization.
286f785676fSDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
287f785676fSDimitry Andric       if (CI->isTailCall() &&
288f785676fSDimitry Andric           (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
289f785676fSDimitry Andric           returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
290f785676fSDimitry Andric         return CI;
291f785676fSDimitry Andric     }
292f785676fSDimitry Andric 
293f785676fSDimitry Andric     // If we did not find a call see if we have an instruction that may create
294f785676fSDimitry Andric     // an interposing chain.
295f785676fSDimitry Andric     NoInterposingChain =
296f785676fSDimitry Andric         NoInterposingChain && InstructionWillNotHaveChain(Inst);
297f785676fSDimitry Andric 
298f785676fSDimitry Andric     // Increment max search.
299f785676fSDimitry Andric     SearchCounter++;
300f785676fSDimitry Andric   }
301f785676fSDimitry Andric 
302f785676fSDimitry Andric   return 0;
303f785676fSDimitry Andric }
304f785676fSDimitry Andric 
305f785676fSDimitry Andric /// Insert code into the entry block that stores the __stack_chk_guard
306f785676fSDimitry Andric /// variable onto the stack:
307f785676fSDimitry Andric ///
308f785676fSDimitry Andric ///   entry:
309f785676fSDimitry Andric ///     StackGuardSlot = alloca i8*
310f785676fSDimitry Andric ///     StackGuard = load __stack_chk_guard
311f785676fSDimitry Andric ///     call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
312f785676fSDimitry Andric ///
313f785676fSDimitry Andric /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
314f785676fSDimitry Andric /// node.
315f785676fSDimitry Andric static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
316f785676fSDimitry Andric                            const TargetLoweringBase *TLI, const Triple &Trip,
317f785676fSDimitry Andric                            AllocaInst *&AI, Value *&StackGuardVar) {
318f785676fSDimitry Andric   bool SupportsSelectionDAGSP = false;
319f785676fSDimitry Andric   PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
320f785676fSDimitry Andric   unsigned AddressSpace, Offset;
321f785676fSDimitry Andric   if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
322f785676fSDimitry Andric     Constant *OffsetVal =
323f785676fSDimitry Andric         ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
324f785676fSDimitry Andric 
325f785676fSDimitry Andric     StackGuardVar = ConstantExpr::getIntToPtr(
326f785676fSDimitry Andric         OffsetVal, PointerType::get(PtrTy, AddressSpace));
327f785676fSDimitry Andric   } else if (Trip.getOS() == llvm::Triple::OpenBSD) {
328f785676fSDimitry Andric     StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
329f785676fSDimitry Andric     cast<GlobalValue>(StackGuardVar)
330f785676fSDimitry Andric         ->setVisibility(GlobalValue::HiddenVisibility);
331f785676fSDimitry Andric   } else {
332f785676fSDimitry Andric     SupportsSelectionDAGSP = true;
333f785676fSDimitry Andric     StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
334f785676fSDimitry Andric   }
335f785676fSDimitry Andric 
336f785676fSDimitry Andric   IRBuilder<> B(&F->getEntryBlock().front());
337f785676fSDimitry Andric   AI = B.CreateAlloca(PtrTy, 0, "StackGuardSlot");
338f785676fSDimitry Andric   LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
339f785676fSDimitry Andric   B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI,
340f785676fSDimitry Andric                 AI);
341f785676fSDimitry Andric 
342f785676fSDimitry Andric   return SupportsSelectionDAGSP;
343f22ef01cSRoman Divacky }
344f22ef01cSRoman Divacky 
345f22ef01cSRoman Divacky /// InsertStackProtectors - Insert code into the prologue and epilogue of the
346f22ef01cSRoman Divacky /// function.
347f22ef01cSRoman Divacky ///
348f22ef01cSRoman Divacky ///  - The prologue code loads and stores the stack guard onto the stack.
349f22ef01cSRoman Divacky ///  - The epilogue checks the value stored in the prologue against the original
350f22ef01cSRoman Divacky ///    value. It calls __stack_chk_fail if they differ.
351f22ef01cSRoman Divacky bool StackProtector::InsertStackProtectors() {
352f785676fSDimitry Andric   bool HasPrologue = false;
353f785676fSDimitry Andric   bool SupportsSelectionDAGSP =
354f785676fSDimitry Andric       EnableSelectionDAGSP && !TM->Options.EnableFastISel;
355f22ef01cSRoman Divacky   AllocaInst *AI = 0;       // Place on stack that stores the stack guard.
356ffd1746dSEd Schouten   Value *StackGuardVar = 0; // The stack guard variable.
357f22ef01cSRoman Divacky 
358f22ef01cSRoman Divacky   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
359f22ef01cSRoman Divacky     BasicBlock *BB = I++;
360f22ef01cSRoman Divacky     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
361f785676fSDimitry Andric     if (!RI)
362f785676fSDimitry Andric       continue;
363f22ef01cSRoman Divacky 
364f785676fSDimitry Andric     if (!HasPrologue) {
365f785676fSDimitry Andric       HasPrologue = true;
366f785676fSDimitry Andric       SupportsSelectionDAGSP &=
367f785676fSDimitry Andric           CreatePrologue(F, M, RI, TLI, Trip, AI, StackGuardVar);
368f785676fSDimitry Andric     }
369ffd1746dSEd Schouten 
370f785676fSDimitry Andric     if (SupportsSelectionDAGSP) {
371f785676fSDimitry Andric       // Since we have a potential tail call, insert the special stack check
372f785676fSDimitry Andric       // intrinsic.
373f785676fSDimitry Andric       Instruction *InsertionPt = 0;
374f785676fSDimitry Andric       if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
375f785676fSDimitry Andric         InsertionPt = CI;
376ffd1746dSEd Schouten       } else {
377f785676fSDimitry Andric         InsertionPt = RI;
378f785676fSDimitry Andric         // At this point we know that BB has a return statement so it *DOES*
379f785676fSDimitry Andric         // have a terminator.
380f785676fSDimitry Andric         assert(InsertionPt != 0 && "BB must have a terminator instruction at "
381f785676fSDimitry Andric                                    "this point.");
382ffd1746dSEd Schouten       }
383f22ef01cSRoman Divacky 
384f785676fSDimitry Andric       Function *Intrinsic =
385f785676fSDimitry Andric           Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
386f785676fSDimitry Andric       CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt);
387f22ef01cSRoman Divacky 
388f785676fSDimitry Andric     } else {
389f785676fSDimitry Andric       // If we do not support SelectionDAG based tail calls, generate IR level
390f785676fSDimitry Andric       // tail calls.
391f785676fSDimitry Andric       //
392f22ef01cSRoman Divacky       // For each block with a return instruction, convert this:
393f22ef01cSRoman Divacky       //
394f22ef01cSRoman Divacky       //   return:
395f22ef01cSRoman Divacky       //     ...
396f22ef01cSRoman Divacky       //     ret ...
397f22ef01cSRoman Divacky       //
398f22ef01cSRoman Divacky       // into this:
399f22ef01cSRoman Divacky       //
400f22ef01cSRoman Divacky       //   return:
401f22ef01cSRoman Divacky       //     ...
402f22ef01cSRoman Divacky       //     %1 = load __stack_chk_guard
403f22ef01cSRoman Divacky       //     %2 = load StackGuardSlot
404f22ef01cSRoman Divacky       //     %3 = cmp i1 %1, %2
405f22ef01cSRoman Divacky       //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
406f22ef01cSRoman Divacky       //
407f22ef01cSRoman Divacky       //   SP_return:
408f22ef01cSRoman Divacky       //     ret ...
409f22ef01cSRoman Divacky       //
410f22ef01cSRoman Divacky       //   CallStackCheckFailBlk:
411f22ef01cSRoman Divacky       //     call void @__stack_chk_fail()
412f22ef01cSRoman Divacky       //     unreachable
413f22ef01cSRoman Divacky 
414f785676fSDimitry Andric       // Create the FailBB. We duplicate the BB every time since the MI tail
415f785676fSDimitry Andric       // merge pass will merge together all of the various BB into one including
416f785676fSDimitry Andric       // fail BB generated by the stack protector pseudo instruction.
417f785676fSDimitry Andric       BasicBlock *FailBB = CreateFailBB();
418f785676fSDimitry Andric 
419f22ef01cSRoman Divacky       // Split the basic block before the return instruction.
420f22ef01cSRoman Divacky       BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
4213b0f4066SDimitry Andric 
422f785676fSDimitry Andric       // Update the dominator tree if we need to.
4233b0f4066SDimitry Andric       if (DT && DT->isReachableFromEntry(BB)) {
4243b0f4066SDimitry Andric         DT->addNewBlock(NewBB, BB);
425f785676fSDimitry Andric         DT->addNewBlock(FailBB, BB);
4262754fe60SDimitry Andric       }
427f22ef01cSRoman Divacky 
428f22ef01cSRoman Divacky       // Remove default branch instruction to the new BB.
429f22ef01cSRoman Divacky       BB->getTerminator()->eraseFromParent();
430f22ef01cSRoman Divacky 
431f785676fSDimitry Andric       // Move the newly created basic block to the point right after the old
432f785676fSDimitry Andric       // basic block so that it's in the "fall through" position.
433f22ef01cSRoman Divacky       NewBB->moveAfter(BB);
434f22ef01cSRoman Divacky 
435f22ef01cSRoman Divacky       // Generate the stack protector instructions in the old basic block.
436f785676fSDimitry Andric       IRBuilder<> B(BB);
437f785676fSDimitry Andric       LoadInst *LI1 = B.CreateLoad(StackGuardVar);
438f785676fSDimitry Andric       LoadInst *LI2 = B.CreateLoad(AI);
439f785676fSDimitry Andric       Value *Cmp = B.CreateICmpEQ(LI1, LI2);
440f785676fSDimitry Andric       B.CreateCondBr(Cmp, NewBB, FailBB);
441f785676fSDimitry Andric     }
442f22ef01cSRoman Divacky   }
443f22ef01cSRoman Divacky 
444f22ef01cSRoman Divacky   // Return if we didn't modify any basic blocks. I.e., there are no return
445f22ef01cSRoman Divacky   // statements in the function.
446f785676fSDimitry Andric   if (!HasPrologue)
447f785676fSDimitry Andric     return false;
4482754fe60SDimitry Andric 
449f22ef01cSRoman Divacky   return true;
450f22ef01cSRoman Divacky }
451f22ef01cSRoman Divacky 
452f22ef01cSRoman Divacky /// CreateFailBB - Create a basic block to jump to when the stack protector
453f22ef01cSRoman Divacky /// check fails.
454f22ef01cSRoman Divacky BasicBlock *StackProtector::CreateFailBB() {
455f785676fSDimitry Andric   LLVMContext &Context = F->getContext();
456f785676fSDimitry Andric   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
457f785676fSDimitry Andric   IRBuilder<> B(FailBB);
458f785676fSDimitry Andric   if (Trip.getOS() == llvm::Triple::OpenBSD) {
459f785676fSDimitry Andric     Constant *StackChkFail = M->getOrInsertFunction(
460f785676fSDimitry Andric         "__stack_smash_handler", Type::getVoidTy(Context),
461f785676fSDimitry Andric         Type::getInt8PtrTy(Context), NULL);
462f785676fSDimitry Andric 
463f785676fSDimitry Andric     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
464f785676fSDimitry Andric   } else {
465f785676fSDimitry Andric     Constant *StackChkFail = M->getOrInsertFunction(
466f785676fSDimitry Andric         "__stack_chk_fail", Type::getVoidTy(Context), NULL);
467f785676fSDimitry Andric     B.CreateCall(StackChkFail);
468f785676fSDimitry Andric   }
469f785676fSDimitry Andric   B.CreateUnreachable();
470f22ef01cSRoman Divacky   return FailBB;
471f22ef01cSRoman Divacky }
472