Debug Info: Move DIEDwarfExpression into DwarfExpression.h because it
[oota-llvm.git] / lib / CodeGen / StackProtector.cpp
1 //===-- 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 //
10 // 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
13 // changed, then there was some sort of violation and the program aborts.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/CodeGen/StackProtector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/BranchProbabilityInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/CodeGen/Analysis.h"
23 #include "llvm/CodeGen/Passes.h"
24 #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"
29 #include "llvm/IR/GlobalValue.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/IR/MDBuilder.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 #include <cstdlib>
40 using namespace llvm;
41
42 #define DEBUG_TYPE "stack-protector"
43
44 STATISTIC(NumFunProtected, "Number of functions protected");
45 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
46                         " taken.");
47
48 static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
49                                           cl::init(true), cl::Hidden);
50
51 char StackProtector::ID = 0;
52 INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
53                 false, true)
54
55 FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
56   return new StackProtector(TM);
57 }
58
59 StackProtector::SSPLayoutKind
60 StackProtector::getSSPLayout(const AllocaInst *AI) const {
61   return AI ? Layout.lookup(AI) : SSPLK_None;
62 }
63
64 void StackProtector::adjustForColoring(const AllocaInst *From,
65                                        const AllocaInst *To) {
66   // When coloring replaces one alloca with another, transfer the SSPLayoutKind
67   // tag from the remapped to the target alloca. The remapped alloca should
68   // have a size smaller than or equal to the replacement alloca.
69   SSPLayoutMap::iterator I = Layout.find(From);
70   if (I != Layout.end()) {
71     SSPLayoutKind Kind = I->second;
72     Layout.erase(I);
73
74     // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
75     // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
76     // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
77     I = Layout.find(To);
78     if (I == Layout.end())
79       Layout.insert(std::make_pair(To, Kind));
80     else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
81       I->second = Kind;
82   }
83 }
84
85 bool StackProtector::runOnFunction(Function &Fn) {
86   F = &Fn;
87   M = F->getParent();
88   DominatorTreeWrapperPass *DTWP =
89       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
90   DT = DTWP ? &DTWP->getDomTree() : nullptr;
91   TLI = TM->getSubtargetImpl()->getTargetLowering();
92
93   Attribute Attr = Fn.getAttributes().getAttribute(
94       AttributeSet::FunctionIndex, "stack-protector-buffer-size");
95   if (Attr.isStringAttribute() &&
96       Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
97       return false; // Invalid integer string
98
99   if (!RequiresStackProtector())
100     return false;
101
102   ++NumFunProtected;
103   return InsertStackProtectors();
104 }
105
106 /// \param [out] IsLarge is set to true if a protectable array is found and
107 /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
108 /// multiple arrays, this gets set if any of them is large.
109 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
110                                               bool Strong,
111                                               bool InStruct) const {
112   if (!Ty)
113     return false;
114   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
115     if (!AT->getElementType()->isIntegerTy(8)) {
116       // If we're on a non-Darwin platform or we're inside of a structure, don't
117       // add stack protectors unless the array is a character array.
118       // However, in strong mode any array, regardless of type and size,
119       // triggers a protector.
120       if (!Strong && (InStruct || !Trip.isOSDarwin()))
121         return false;
122     }
123
124     // If an array has more than SSPBufferSize bytes of allocated space, then we
125     // emit stack protectors.
126     if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT)) {
127       IsLarge = true;
128       return true;
129     }
130
131     if (Strong)
132       // Require a protector for all arrays in strong mode
133       return true;
134   }
135
136   const StructType *ST = dyn_cast<StructType>(Ty);
137   if (!ST)
138     return false;
139
140   bool NeedsProtector = false;
141   for (StructType::element_iterator I = ST->element_begin(),
142                                     E = ST->element_end();
143        I != E; ++I)
144     if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
145       // If the element is a protectable array and is large (>= SSPBufferSize)
146       // then we are done.  If the protectable array is not large, then
147       // keep looking in case a subsequent element is a large array.
148       if (IsLarge)
149         return true;
150       NeedsProtector = true;
151     }
152
153   return NeedsProtector;
154 }
155
156 bool StackProtector::HasAddressTaken(const Instruction *AI) {
157   for (const User *U : AI->users()) {
158     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
159       if (AI == SI->getValueOperand())
160         return true;
161     } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
162       if (AI == SI->getOperand(0))
163         return true;
164     } else if (isa<CallInst>(U)) {
165       return true;
166     } else if (isa<InvokeInst>(U)) {
167       return true;
168     } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
169       if (HasAddressTaken(SI))
170         return true;
171     } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
172       // Keep track of what PHI nodes we have already visited to ensure
173       // they are only visited once.
174       if (VisitedPHIs.insert(PN).second)
175         if (HasAddressTaken(PN))
176           return true;
177     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
178       if (HasAddressTaken(GEP))
179         return true;
180     } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
181       if (HasAddressTaken(BI))
182         return true;
183     }
184   }
185   return false;
186 }
187
188 /// \brief Check whether or not this function needs a stack protector based
189 /// upon the stack protector level.
190 ///
191 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
192 /// The standard heuristic which will add a guard variable to functions that
193 /// call alloca with a either a variable size or a size >= SSPBufferSize,
194 /// functions with character buffers larger than SSPBufferSize, and functions
195 /// with aggregates containing character buffers larger than SSPBufferSize. The
196 /// strong heuristic will add a guard variables to functions that call alloca
197 /// regardless of size, functions with any buffer regardless of type and size,
198 /// functions with aggregates that contain any buffer regardless of type and
199 /// size, and functions that contain stack-based variables that have had their
200 /// address taken.
201 bool StackProtector::RequiresStackProtector() {
202   bool Strong = false;
203   bool NeedsProtector = false;
204   if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
205                                       Attribute::StackProtectReq)) {
206     NeedsProtector = true;
207     Strong = true; // Use the same heuristic as strong to determine SSPLayout
208   } else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
209                                              Attribute::StackProtectStrong))
210     Strong = true;
211   else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
212                                             Attribute::StackProtect))
213     return false;
214
215   for (const BasicBlock &BB : *F) {
216     for (const Instruction &I : BB) {
217       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
218         if (AI->isArrayAllocation()) {
219           // SSP-Strong: Enable protectors for any call to alloca, regardless
220           // of size.
221           if (Strong)
222             return true;
223
224           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
225             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
226               // A call to alloca with size >= SSPBufferSize requires
227               // stack protectors.
228               Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
229               NeedsProtector = true;
230             } else if (Strong) {
231               // Require protectors for all alloca calls in strong mode.
232               Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
233               NeedsProtector = true;
234             }
235           } else {
236             // A call to alloca with a variable size requires protectors.
237             Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
238             NeedsProtector = true;
239           }
240           continue;
241         }
242
243         bool IsLarge = false;
244         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
245           Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
246                                                    : SSPLK_SmallArray));
247           NeedsProtector = true;
248           continue;
249         }
250
251         if (Strong && HasAddressTaken(AI)) {
252           ++NumAddrTaken;
253           Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
254           NeedsProtector = true;
255         }
256       }
257     }
258   }
259
260   return NeedsProtector;
261 }
262
263 static bool InstructionWillNotHaveChain(const Instruction *I) {
264   return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
265          isSafeToSpeculativelyExecute(I);
266 }
267
268 /// Identify if RI has a previous instruction in the "Tail Position" and return
269 /// it. Otherwise return 0.
270 ///
271 /// This is based off of the code in llvm::isInTailCallPosition. The difference
272 /// is that it inverts the first part of llvm::isInTailCallPosition since
273 /// isInTailCallPosition is checking if a call is in a tail call position, and
274 /// we are searching for an unknown tail call that might be in the tail call
275 /// position. Once we find the call though, the code uses the same refactored
276 /// code, returnTypeIsEligibleForTailCall.
277 static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
278                                        const TargetLoweringBase *TLI) {
279   // Establish a reasonable upper bound on the maximum amount of instructions we
280   // will look through to find a tail call.
281   unsigned SearchCounter = 0;
282   const unsigned MaxSearch = 4;
283   bool NoInterposingChain = true;
284
285   for (BasicBlock::reverse_iterator I = std::next(BB->rbegin()), E = BB->rend();
286        I != E && SearchCounter < MaxSearch; ++I) {
287     Instruction *Inst = &*I;
288
289     // Skip over debug intrinsics and do not allow them to affect our MaxSearch
290     // counter.
291     if (isa<DbgInfoIntrinsic>(Inst))
292       continue;
293
294     // If we find a call and the following conditions are satisifed, then we
295     // have found a tail call that satisfies at least the target independent
296     // requirements of a tail call:
297     //
298     // 1. The call site has the tail marker.
299     //
300     // 2. The call site either will not cause the creation of a chain or if a
301     // chain is necessary there are no instructions in between the callsite and
302     // the call which would create an interposing chain.
303     //
304     // 3. The return type of the function does not impede tail call
305     // optimization.
306     if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
307       if (CI->isTailCall() &&
308           (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
309           returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
310         return CI;
311     }
312
313     // If we did not find a call see if we have an instruction that may create
314     // an interposing chain.
315     NoInterposingChain =
316         NoInterposingChain && InstructionWillNotHaveChain(Inst);
317
318     // Increment max search.
319     SearchCounter++;
320   }
321
322   return nullptr;
323 }
324
325 /// Insert code into the entry block that stores the __stack_chk_guard
326 /// variable onto the stack:
327 ///
328 ///   entry:
329 ///     StackGuardSlot = alloca i8*
330 ///     StackGuard = load __stack_chk_guard
331 ///     call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
332 ///
333 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
334 /// node.
335 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
336                            const TargetLoweringBase *TLI, const Triple &TT,
337                            AllocaInst *&AI, Value *&StackGuardVar) {
338   bool SupportsSelectionDAGSP = false;
339   PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
340   unsigned AddressSpace, Offset;
341   if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
342     Constant *OffsetVal =
343         ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
344
345     StackGuardVar =
346         ConstantExpr::getIntToPtr(OffsetVal, PointerType::get(PtrTy,
347                                                               AddressSpace));
348   } else if (TT.isOSOpenBSD()) {
349     StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
350     cast<GlobalValue>(StackGuardVar)
351         ->setVisibility(GlobalValue::HiddenVisibility);
352   } else {
353     SupportsSelectionDAGSP = true;
354     StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
355   }
356
357   IRBuilder<> B(&F->getEntryBlock().front());
358   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
359   LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
360   B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI,
361                 AI);
362
363   return SupportsSelectionDAGSP;
364 }
365
366 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
367 /// function.
368 ///
369 ///  - The prologue code loads and stores the stack guard onto the stack.
370 ///  - The epilogue checks the value stored in the prologue against the original
371 ///    value. It calls __stack_chk_fail if they differ.
372 bool StackProtector::InsertStackProtectors() {
373   bool HasPrologue = false;
374   bool SupportsSelectionDAGSP =
375       EnableSelectionDAGSP && !TM->Options.EnableFastISel;
376   AllocaInst *AI = nullptr;       // Place on stack that stores the stack guard.
377   Value *StackGuardVar = nullptr; // The stack guard variable.
378
379   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
380     BasicBlock *BB = I++;
381     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
382     if (!RI)
383       continue;
384
385     if (!HasPrologue) {
386       HasPrologue = true;
387       SupportsSelectionDAGSP &=
388           CreatePrologue(F, M, RI, TLI, Trip, AI, StackGuardVar);
389     }
390
391     if (SupportsSelectionDAGSP) {
392       // Since we have a potential tail call, insert the special stack check
393       // intrinsic.
394       Instruction *InsertionPt = nullptr;
395       if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
396         InsertionPt = CI;
397       } else {
398         InsertionPt = RI;
399         // At this point we know that BB has a return statement so it *DOES*
400         // have a terminator.
401         assert(InsertionPt != nullptr &&
402                "BB must have a terminator instruction at this point.");
403       }
404
405       Function *Intrinsic =
406           Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
407       CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt);
408     } else {
409       // If we do not support SelectionDAG based tail calls, generate IR level
410       // tail calls.
411       //
412       // For each block with a return instruction, convert this:
413       //
414       //   return:
415       //     ...
416       //     ret ...
417       //
418       // into this:
419       //
420       //   return:
421       //     ...
422       //     %1 = load __stack_chk_guard
423       //     %2 = load StackGuardSlot
424       //     %3 = cmp i1 %1, %2
425       //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
426       //
427       //   SP_return:
428       //     ret ...
429       //
430       //   CallStackCheckFailBlk:
431       //     call void @__stack_chk_fail()
432       //     unreachable
433
434       // Create the FailBB. We duplicate the BB every time since the MI tail
435       // merge pass will merge together all of the various BB into one including
436       // fail BB generated by the stack protector pseudo instruction.
437       BasicBlock *FailBB = CreateFailBB();
438
439       // Split the basic block before the return instruction.
440       BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
441
442       // Update the dominator tree if we need to.
443       if (DT && DT->isReachableFromEntry(BB)) {
444         DT->addNewBlock(NewBB, BB);
445         DT->addNewBlock(FailBB, BB);
446       }
447
448       // Remove default branch instruction to the new BB.
449       BB->getTerminator()->eraseFromParent();
450
451       // Move the newly created basic block to the point right after the old
452       // basic block so that it's in the "fall through" position.
453       NewBB->moveAfter(BB);
454
455       // Generate the stack protector instructions in the old basic block.
456       IRBuilder<> B(BB);
457       LoadInst *LI1 = B.CreateLoad(StackGuardVar);
458       LoadInst *LI2 = B.CreateLoad(AI);
459       Value *Cmp = B.CreateICmpEQ(LI1, LI2);
460       unsigned SuccessWeight =
461           BranchProbabilityInfo::getBranchWeightStackProtector(true);
462       unsigned FailureWeight =
463           BranchProbabilityInfo::getBranchWeightStackProtector(false);
464       MDNode *Weights = MDBuilder(F->getContext())
465                             .createBranchWeights(SuccessWeight, FailureWeight);
466       B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
467     }
468   }
469
470   // Return if we didn't modify any basic blocks. i.e., there are no return
471   // statements in the function.
472   if (!HasPrologue)
473     return false;
474
475   return true;
476 }
477
478 /// CreateFailBB - Create a basic block to jump to when the stack protector
479 /// check fails.
480 BasicBlock *StackProtector::CreateFailBB() {
481   LLVMContext &Context = F->getContext();
482   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
483   IRBuilder<> B(FailBB);
484   if (Trip.isOSOpenBSD()) {
485     Constant *StackChkFail =
486         M->getOrInsertFunction("__stack_smash_handler",
487                                Type::getVoidTy(Context),
488                                Type::getInt8PtrTy(Context), nullptr);
489
490     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
491   } else {
492     Constant *StackChkFail =
493         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context),
494                                nullptr);
495     B.CreateCall(StackChkFail);
496   }
497   B.CreateUnreachable();
498   return FailBB;
499 }