17a7e6055SDimitry Andric //===- 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 
17139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
18139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
1939d628a0SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
203ca95b02SDimitry Andric #include "llvm/Analysis/EHPersonalities.h"
217a7e6055SDimitry Andric #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
2291bc56edSDimitry Andric #include "llvm/CodeGen/Passes.h"
237a7e6055SDimitry Andric #include "llvm/CodeGen/StackProtector.h"
24db17bf38SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
25139f7f9bSDimitry Andric #include "llvm/IR/Attributes.h"
267a7e6055SDimitry Andric #include "llvm/IR/BasicBlock.h"
27139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
28139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
293ca95b02SDimitry Andric #include "llvm/IR/DebugInfo.h"
307a7e6055SDimitry Andric #include "llvm/IR/DebugLoc.h"
31139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
32db17bf38SDimitry Andric #include "llvm/IR/Dominators.h"
33139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
34f785676fSDimitry Andric #include "llvm/IR/IRBuilder.h"
357a7e6055SDimitry Andric #include "llvm/IR/Instruction.h"
36139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
37139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
3839d628a0SDimitry Andric #include "llvm/IR/MDBuilder.h"
39139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
407a7e6055SDimitry Andric #include "llvm/IR/Type.h"
417a7e6055SDimitry Andric #include "llvm/IR/User.h"
427a7e6055SDimitry Andric #include "llvm/Pass.h"
437a7e6055SDimitry Andric #include "llvm/Support/Casting.h"
44f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h"
457a7e6055SDimitry Andric #include "llvm/Target/TargetLowering.h"
467a7e6055SDimitry Andric #include "llvm/Target/TargetMachine.h"
477a7e6055SDimitry Andric #include "llvm/Target/TargetOptions.h"
4839d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
497a7e6055SDimitry Andric #include <utility>
507a7e6055SDimitry Andric 
51f22ef01cSRoman Divacky using namespace llvm;
52f22ef01cSRoman Divacky 
5391bc56edSDimitry Andric #define DEBUG_TYPE "stack-protector"
5491bc56edSDimitry Andric 
55139f7f9bSDimitry Andric STATISTIC(NumFunProtected, "Number of functions protected");
56139f7f9bSDimitry Andric STATISTIC(NumAddrTaken, "Number of local variables that have their address"
57139f7f9bSDimitry Andric                         " taken.");
58139f7f9bSDimitry Andric 
59f785676fSDimitry Andric static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
60f785676fSDimitry Andric                                           cl::init(true), cl::Hidden);
61f22ef01cSRoman Divacky 
62f22ef01cSRoman Divacky char StackProtector::ID = 0;
63db17bf38SDimitry Andric 
64302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
65d8866befSDimitry Andric                       "Insert stack protectors", false, true)
66d8866befSDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
67302affcbSDimitry Andric INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
68d8866befSDimitry Andric                     "Insert stack protectors", false, true)
69f22ef01cSRoman Divacky 
70d8866befSDimitry Andric FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
71f785676fSDimitry Andric 
72f785676fSDimitry Andric StackProtector::SSPLayoutKind
73f785676fSDimitry Andric StackProtector::getSSPLayout(const AllocaInst *AI) const {
74f785676fSDimitry Andric   return AI ? Layout.lookup(AI) : SSPLK_None;
75f22ef01cSRoman Divacky }
76f22ef01cSRoman Divacky 
7791bc56edSDimitry Andric void StackProtector::adjustForColoring(const AllocaInst *From,
7891bc56edSDimitry Andric                                        const AllocaInst *To) {
7991bc56edSDimitry Andric   // When coloring replaces one alloca with another, transfer the SSPLayoutKind
8091bc56edSDimitry Andric   // tag from the remapped to the target alloca. The remapped alloca should
8191bc56edSDimitry Andric   // have a size smaller than or equal to the replacement alloca.
8291bc56edSDimitry Andric   SSPLayoutMap::iterator I = Layout.find(From);
8391bc56edSDimitry Andric   if (I != Layout.end()) {
8491bc56edSDimitry Andric     SSPLayoutKind Kind = I->second;
8591bc56edSDimitry Andric     Layout.erase(I);
8691bc56edSDimitry Andric 
8791bc56edSDimitry Andric     // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
8891bc56edSDimitry Andric     // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
8991bc56edSDimitry Andric     // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
9091bc56edSDimitry Andric     I = Layout.find(To);
9191bc56edSDimitry Andric     if (I == Layout.end())
9291bc56edSDimitry Andric       Layout.insert(std::make_pair(To, Kind));
9391bc56edSDimitry Andric     else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
9491bc56edSDimitry Andric       I->second = Kind;
9591bc56edSDimitry Andric   }
9691bc56edSDimitry Andric }
9791bc56edSDimitry Andric 
98db17bf38SDimitry Andric void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
99db17bf38SDimitry Andric   AU.addRequired<TargetPassConfig>();
100db17bf38SDimitry Andric   AU.addPreserved<DominatorTreeWrapperPass>();
101db17bf38SDimitry Andric }
102db17bf38SDimitry Andric 
103f22ef01cSRoman Divacky bool StackProtector::runOnFunction(Function &Fn) {
104f22ef01cSRoman Divacky   F = &Fn;
105f22ef01cSRoman Divacky   M = F->getParent();
10691bc56edSDimitry Andric   DominatorTreeWrapperPass *DTWP =
10791bc56edSDimitry Andric       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
10891bc56edSDimitry Andric   DT = DTWP ? &DTWP->getDomTree() : nullptr;
109d8866befSDimitry Andric   TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
110d8866befSDimitry Andric   Trip = TM->getTargetTriple();
111ff0cc061SDimitry Andric   TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
1123ca95b02SDimitry Andric   HasPrologue = false;
1133ca95b02SDimitry Andric   HasIRCheck = false;
114f22ef01cSRoman Divacky 
115ff0cc061SDimitry Andric   Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
11691bc56edSDimitry Andric   if (Attr.isStringAttribute() &&
11791bc56edSDimitry Andric       Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
11891bc56edSDimitry Andric     return false; // Invalid integer string
11991bc56edSDimitry Andric 
12091bc56edSDimitry Andric   if (!RequiresStackProtector())
12191bc56edSDimitry Andric     return false;
122f22ef01cSRoman Divacky 
1233ca95b02SDimitry Andric   // TODO(etienneb): Functions with funclets are not correctly supported now.
1243ca95b02SDimitry Andric   // Do nothing if this is funclet-based personality.
1253ca95b02SDimitry Andric   if (Fn.hasPersonalityFn()) {
1263ca95b02SDimitry Andric     EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
1273ca95b02SDimitry Andric     if (isFuncletEHPersonality(Personality))
1283ca95b02SDimitry Andric       return false;
1293ca95b02SDimitry Andric   }
1303ca95b02SDimitry Andric 
131139f7f9bSDimitry Andric   ++NumFunProtected;
132f22ef01cSRoman Divacky   return InsertStackProtectors();
133f22ef01cSRoman Divacky }
134f22ef01cSRoman Divacky 
135f785676fSDimitry Andric /// \param [out] IsLarge is set to true if a protectable array is found and
136f785676fSDimitry Andric /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
137f785676fSDimitry Andric /// multiple arrays, this gets set if any of them is large.
138f785676fSDimitry Andric bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
139f785676fSDimitry Andric                                               bool Strong,
140139f7f9bSDimitry Andric                                               bool InStruct) const {
141f785676fSDimitry Andric   if (!Ty)
142f785676fSDimitry Andric     return false;
1433861d79fSDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1443861d79fSDimitry Andric     if (!AT->getElementType()->isIntegerTy(8)) {
1453861d79fSDimitry Andric       // If we're on a non-Darwin platform or we're inside of a structure, don't
1463861d79fSDimitry Andric       // add stack protectors unless the array is a character array.
147f785676fSDimitry Andric       // However, in strong mode any array, regardless of type and size,
148f785676fSDimitry Andric       // triggers a protector.
149f785676fSDimitry Andric       if (!Strong && (InStruct || !Trip.isOSDarwin()))
1503861d79fSDimitry Andric         return false;
1513861d79fSDimitry Andric     }
1523861d79fSDimitry Andric 
1533861d79fSDimitry Andric     // If an array has more than SSPBufferSize bytes of allocated space, then we
1543861d79fSDimitry Andric     // emit stack protectors.
155875ed548SDimitry Andric     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
156f785676fSDimitry Andric       IsLarge = true;
157f785676fSDimitry Andric       return true;
158f785676fSDimitry Andric     }
159f785676fSDimitry Andric 
160f785676fSDimitry Andric     if (Strong)
161f785676fSDimitry Andric       // Require a protector for all arrays in strong mode
1623861d79fSDimitry Andric       return true;
1633861d79fSDimitry Andric   }
1643861d79fSDimitry Andric 
1653861d79fSDimitry Andric   const StructType *ST = dyn_cast<StructType>(Ty);
166f785676fSDimitry Andric   if (!ST)
1673861d79fSDimitry Andric     return false;
168f785676fSDimitry Andric 
169f785676fSDimitry Andric   bool NeedsProtector = false;
170f785676fSDimitry Andric   for (StructType::element_iterator I = ST->element_begin(),
171f785676fSDimitry Andric                                     E = ST->element_end();
172f785676fSDimitry Andric        I != E; ++I)
173f785676fSDimitry Andric     if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
174f785676fSDimitry Andric       // If the element is a protectable array and is large (>= SSPBufferSize)
175f785676fSDimitry Andric       // then we are done.  If the protectable array is not large, then
176f785676fSDimitry Andric       // keep looking in case a subsequent element is a large array.
177f785676fSDimitry Andric       if (IsLarge)
178f785676fSDimitry Andric         return true;
179f785676fSDimitry Andric       NeedsProtector = true;
180f785676fSDimitry Andric     }
181f785676fSDimitry Andric 
182f785676fSDimitry Andric   return NeedsProtector;
1833861d79fSDimitry Andric }
1843861d79fSDimitry Andric 
185139f7f9bSDimitry Andric bool StackProtector::HasAddressTaken(const Instruction *AI) {
18691bc56edSDimitry Andric   for (const User *U : AI->users()) {
187139f7f9bSDimitry Andric     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
188139f7f9bSDimitry Andric       if (AI == SI->getValueOperand())
189f22ef01cSRoman Divacky         return true;
190139f7f9bSDimitry Andric     } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
191139f7f9bSDimitry Andric       if (AI == SI->getOperand(0))
192139f7f9bSDimitry Andric         return true;
193139f7f9bSDimitry Andric     } else if (isa<CallInst>(U)) {
194139f7f9bSDimitry Andric       return true;
195139f7f9bSDimitry Andric     } else if (isa<InvokeInst>(U)) {
196139f7f9bSDimitry Andric       return true;
197139f7f9bSDimitry Andric     } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
198139f7f9bSDimitry Andric       if (HasAddressTaken(SI))
199139f7f9bSDimitry Andric         return true;
200139f7f9bSDimitry Andric     } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
201139f7f9bSDimitry Andric       // Keep track of what PHI nodes we have already visited to ensure
202139f7f9bSDimitry Andric       // they are only visited once.
20339d628a0SDimitry Andric       if (VisitedPHIs.insert(PN).second)
204139f7f9bSDimitry Andric         if (HasAddressTaken(PN))
205139f7f9bSDimitry Andric           return true;
206139f7f9bSDimitry Andric     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
207139f7f9bSDimitry Andric       if (HasAddressTaken(GEP))
208139f7f9bSDimitry Andric         return true;
209139f7f9bSDimitry Andric     } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
210139f7f9bSDimitry Andric       if (HasAddressTaken(BI))
211139f7f9bSDimitry Andric         return true;
212139f7f9bSDimitry Andric     }
213139f7f9bSDimitry Andric   }
214139f7f9bSDimitry Andric   return false;
215139f7f9bSDimitry Andric }
216f22ef01cSRoman Divacky 
217139f7f9bSDimitry Andric /// \brief Check whether or not this function needs a stack protector based
218139f7f9bSDimitry Andric /// upon the stack protector level.
219139f7f9bSDimitry Andric ///
220139f7f9bSDimitry Andric /// We use two heuristics: a standard (ssp) and strong (sspstrong).
221139f7f9bSDimitry Andric /// The standard heuristic which will add a guard variable to functions that
222139f7f9bSDimitry Andric /// call alloca with a either a variable size or a size >= SSPBufferSize,
223139f7f9bSDimitry Andric /// functions with character buffers larger than SSPBufferSize, and functions
224139f7f9bSDimitry Andric /// with aggregates containing character buffers larger than SSPBufferSize. The
225139f7f9bSDimitry Andric /// strong heuristic will add a guard variables to functions that call alloca
226139f7f9bSDimitry Andric /// regardless of size, functions with any buffer regardless of type and size,
227139f7f9bSDimitry Andric /// functions with aggregates that contain any buffer regardless of type and
228139f7f9bSDimitry Andric /// size, and functions that contain stack-based variables that have had their
229139f7f9bSDimitry Andric /// address taken.
230139f7f9bSDimitry Andric bool StackProtector::RequiresStackProtector() {
231139f7f9bSDimitry Andric   bool Strong = false;
232f785676fSDimitry Andric   bool NeedsProtector = false;
2333ca95b02SDimitry Andric   for (const BasicBlock &BB : *F)
2343ca95b02SDimitry Andric     for (const Instruction &I : BB)
2353ca95b02SDimitry Andric       if (const CallInst *CI = dyn_cast<CallInst>(&I))
2363ca95b02SDimitry Andric         if (CI->getCalledFunction() ==
2373ca95b02SDimitry Andric             Intrinsic::getDeclaration(F->getParent(),
2383ca95b02SDimitry Andric                                       Intrinsic::stackprotector))
2393ca95b02SDimitry Andric           HasPrologue = true;
2403ca95b02SDimitry Andric 
2413ca95b02SDimitry Andric   if (F->hasFnAttribute(Attribute::SafeStack))
2423ca95b02SDimitry Andric     return false;
2433ca95b02SDimitry Andric 
2447a7e6055SDimitry Andric   // We are constructing the OptimizationRemarkEmitter on the fly rather than
2457a7e6055SDimitry Andric   // using the analysis pass to avoid building DominatorTree and LoopInfo which
2467a7e6055SDimitry Andric   // are not available this late in the IR pipeline.
2477a7e6055SDimitry Andric   OptimizationRemarkEmitter ORE(F);
2487a7e6055SDimitry Andric 
249ff0cc061SDimitry Andric   if (F->hasFnAttribute(Attribute::StackProtectReq)) {
2507a7e6055SDimitry Andric     ORE.emit(OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
2517a7e6055SDimitry Andric              << "Stack protection applied to function "
2527a7e6055SDimitry Andric              << ore::NV("Function", F)
2537a7e6055SDimitry Andric              << " due to a function attribute or command-line switch");
254f785676fSDimitry Andric     NeedsProtector = true;
255f785676fSDimitry Andric     Strong = true; // Use the same heuristic as strong to determine SSPLayout
256ff0cc061SDimitry Andric   } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
257139f7f9bSDimitry Andric     Strong = true;
2583ca95b02SDimitry Andric   else if (HasPrologue)
2593ca95b02SDimitry Andric     NeedsProtector = true;
260ff0cc061SDimitry Andric   else if (!F->hasFnAttribute(Attribute::StackProtect))
261f22ef01cSRoman Divacky     return false;
262f22ef01cSRoman Divacky 
26339d628a0SDimitry Andric   for (const BasicBlock &BB : *F) {
26439d628a0SDimitry Andric     for (const Instruction &I : BB) {
26539d628a0SDimitry Andric       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
266139f7f9bSDimitry Andric         if (AI->isArrayAllocation()) {
2677a7e6055SDimitry Andric           OptimizationRemark Remark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
2687a7e6055SDimitry Andric                                     &I);
2697a7e6055SDimitry Andric           Remark
2707a7e6055SDimitry Andric               << "Stack protection applied to function "
2717a7e6055SDimitry Andric               << ore::NV("Function", F)
2727a7e6055SDimitry Andric               << " due to a call to alloca or use of a variable length array";
27339d628a0SDimitry Andric           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
274f785676fSDimitry Andric             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
275139f7f9bSDimitry Andric               // A call to alloca with size >= SSPBufferSize requires
276139f7f9bSDimitry Andric               // stack protectors.
277f785676fSDimitry Andric               Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
2787a7e6055SDimitry Andric               ORE.emit(Remark);
279f785676fSDimitry Andric               NeedsProtector = true;
280f785676fSDimitry Andric             } else if (Strong) {
281f785676fSDimitry Andric               // Require protectors for all alloca calls in strong mode.
282f785676fSDimitry Andric               Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
2837a7e6055SDimitry Andric               ORE.emit(Remark);
284f785676fSDimitry Andric               NeedsProtector = true;
285f785676fSDimitry Andric             }
286f785676fSDimitry Andric           } else {
287f785676fSDimitry Andric             // A call to alloca with a variable size requires protectors.
288f785676fSDimitry Andric             Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
2897a7e6055SDimitry Andric             ORE.emit(Remark);
290f785676fSDimitry Andric             NeedsProtector = true;
291f785676fSDimitry Andric           }
292f785676fSDimitry Andric           continue;
293139f7f9bSDimitry Andric         }
294139f7f9bSDimitry Andric 
295f785676fSDimitry Andric         bool IsLarge = false;
296f785676fSDimitry Andric         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
297f785676fSDimitry Andric           Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
298f785676fSDimitry Andric                                                    : SSPLK_SmallArray));
2997a7e6055SDimitry Andric           ORE.emit(OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
3007a7e6055SDimitry Andric                    << "Stack protection applied to function "
3017a7e6055SDimitry Andric                    << ore::NV("Function", F)
3027a7e6055SDimitry Andric                    << " due to a stack allocated buffer or struct containing a "
3037a7e6055SDimitry Andric                       "buffer");
304f785676fSDimitry Andric           NeedsProtector = true;
305f785676fSDimitry Andric           continue;
306f785676fSDimitry Andric         }
307139f7f9bSDimitry Andric 
308139f7f9bSDimitry Andric         if (Strong && HasAddressTaken(AI)) {
309139f7f9bSDimitry Andric           ++NumAddrTaken;
310f785676fSDimitry Andric           Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
3117a7e6055SDimitry Andric           ORE.emit(
3127a7e6055SDimitry Andric               OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken", &I)
3137a7e6055SDimitry Andric               << "Stack protection applied to function "
3147a7e6055SDimitry Andric               << ore::NV("Function", F)
3157a7e6055SDimitry Andric               << " due to the address of a local variable being taken");
316f785676fSDimitry Andric           NeedsProtector = true;
317139f7f9bSDimitry Andric         }
318139f7f9bSDimitry Andric       }
319f22ef01cSRoman Divacky     }
320f22ef01cSRoman Divacky   }
321f22ef01cSRoman Divacky 
322f785676fSDimitry Andric   return NeedsProtector;
323f785676fSDimitry Andric }
324f785676fSDimitry Andric 
3253ca95b02SDimitry Andric /// Create a stack guard loading and populate whether SelectionDAG SSP is
3263ca95b02SDimitry Andric /// supported.
3273ca95b02SDimitry Andric static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
3283ca95b02SDimitry Andric                             IRBuilder<> &B,
3293ca95b02SDimitry Andric                             bool *SupportsSelectionDAGSP = nullptr) {
3303ca95b02SDimitry Andric   if (Value *Guard = TLI->getIRStackGuard(B))
3313ca95b02SDimitry Andric     return B.CreateLoad(Guard, true, "StackGuard");
332f785676fSDimitry Andric 
3333ca95b02SDimitry Andric   // Use SelectionDAG SSP handling, since there isn't an IR guard.
334f785676fSDimitry Andric   //
3353ca95b02SDimitry Andric   // This is more or less weird, since we optionally output whether we
3363ca95b02SDimitry Andric   // should perform a SelectionDAG SP here. The reason is that it's strictly
3373ca95b02SDimitry Andric   // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
3383ca95b02SDimitry Andric   // mutating. There is no way to get this bit without mutating the IR, so
3393ca95b02SDimitry Andric   // getting this bit has to happen in this right time.
340f785676fSDimitry Andric   //
3413ca95b02SDimitry Andric   // We could have define a new function TLI::supportsSelectionDAGSP(), but that
3423ca95b02SDimitry Andric   // will put more burden on the backends' overriding work, especially when it
3433ca95b02SDimitry Andric   // actually conveys the same information getIRStackGuard() already gives.
3443ca95b02SDimitry Andric   if (SupportsSelectionDAGSP)
3453ca95b02SDimitry Andric     *SupportsSelectionDAGSP = true;
3463ca95b02SDimitry Andric   TLI->insertSSPDeclarations(*M);
3473ca95b02SDimitry Andric   return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
348f785676fSDimitry Andric }
349f785676fSDimitry Andric 
3503ca95b02SDimitry Andric /// Insert code into the entry block that stores the stack guard
351f785676fSDimitry Andric /// variable onto the stack:
352f785676fSDimitry Andric ///
353f785676fSDimitry Andric ///   entry:
354f785676fSDimitry Andric ///     StackGuardSlot = alloca i8*
3553ca95b02SDimitry Andric ///     StackGuard = <stack guard>
3563ca95b02SDimitry Andric ///     call void @llvm.stackprotector(StackGuard, StackGuardSlot)
357f785676fSDimitry Andric ///
358f785676fSDimitry Andric /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
359f785676fSDimitry Andric /// node.
360f785676fSDimitry Andric static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
3613ca95b02SDimitry Andric                            const TargetLoweringBase *TLI, AllocaInst *&AI) {
362f785676fSDimitry Andric   bool SupportsSelectionDAGSP = false;
363f785676fSDimitry Andric   IRBuilder<> B(&F->getEntryBlock().front());
3643ca95b02SDimitry Andric   PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
36591bc56edSDimitry Andric   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
366f785676fSDimitry Andric 
3673ca95b02SDimitry Andric   Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
3683ca95b02SDimitry Andric   B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
3693ca95b02SDimitry Andric                {GuardSlot, AI});
370f785676fSDimitry Andric   return SupportsSelectionDAGSP;
371f22ef01cSRoman Divacky }
372f22ef01cSRoman Divacky 
373f22ef01cSRoman Divacky /// InsertStackProtectors - Insert code into the prologue and epilogue of the
374f22ef01cSRoman Divacky /// function.
375f22ef01cSRoman Divacky ///
376f22ef01cSRoman Divacky ///  - The prologue code loads and stores the stack guard onto the stack.
377f22ef01cSRoman Divacky ///  - The epilogue checks the value stored in the prologue against the original
378f22ef01cSRoman Divacky ///    value. It calls __stack_chk_fail if they differ.
379f22ef01cSRoman Divacky bool StackProtector::InsertStackProtectors() {
380f785676fSDimitry Andric   bool SupportsSelectionDAGSP =
381f785676fSDimitry Andric       EnableSelectionDAGSP && !TM->Options.EnableFastISel;
38291bc56edSDimitry Andric   AllocaInst *AI = nullptr;       // Place on stack that stores the stack guard.
383f22ef01cSRoman Divacky 
384f22ef01cSRoman Divacky   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
3857d523365SDimitry Andric     BasicBlock *BB = &*I++;
386f22ef01cSRoman Divacky     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
387f785676fSDimitry Andric     if (!RI)
388f785676fSDimitry Andric       continue;
389f22ef01cSRoman Divacky 
3903ca95b02SDimitry Andric     // Generate prologue instrumentation if not already generated.
391f785676fSDimitry Andric     if (!HasPrologue) {
392f785676fSDimitry Andric       HasPrologue = true;
3933ca95b02SDimitry Andric       SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
394f785676fSDimitry Andric     }
395ffd1746dSEd Schouten 
3963ca95b02SDimitry Andric     // SelectionDAG based code generation. Nothing else needs to be done here.
3973ca95b02SDimitry Andric     // The epilogue instrumentation is postponed to SelectionDAG.
3983ca95b02SDimitry Andric     if (SupportsSelectionDAGSP)
3993ca95b02SDimitry Andric       break;
400f22ef01cSRoman Divacky 
4013ca95b02SDimitry Andric     // Set HasIRCheck to true, so that SelectionDAG will not generate its own
4023ca95b02SDimitry Andric     // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
4033ca95b02SDimitry Andric     // instrumentation has already been generated.
4043ca95b02SDimitry Andric     HasIRCheck = true;
4053ca95b02SDimitry Andric 
4063ca95b02SDimitry Andric     // Generate epilogue instrumentation. The epilogue intrumentation can be
4073ca95b02SDimitry Andric     // function-based or inlined depending on which mechanism the target is
4083ca95b02SDimitry Andric     // providing.
4093ca95b02SDimitry Andric     if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
4103ca95b02SDimitry Andric       // Generate the function-based epilogue instrumentation.
4113ca95b02SDimitry Andric       // The target provides a guard check function, generate a call to it.
4123ca95b02SDimitry Andric       IRBuilder<> B(RI);
4133ca95b02SDimitry Andric       LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
4143ca95b02SDimitry Andric       CallInst *Call = B.CreateCall(GuardCheck, {Guard});
4153ca95b02SDimitry Andric       llvm::Function *Function = cast<llvm::Function>(GuardCheck);
4163ca95b02SDimitry Andric       Call->setAttributes(Function->getAttributes());
4173ca95b02SDimitry Andric       Call->setCallingConv(Function->getCallingConv());
418f785676fSDimitry Andric     } else {
4193ca95b02SDimitry Andric       // Generate the epilogue with inline instrumentation.
420f785676fSDimitry Andric       // If we do not support SelectionDAG based tail calls, generate IR level
421f785676fSDimitry Andric       // tail calls.
422f785676fSDimitry Andric       //
423f22ef01cSRoman Divacky       // For each block with a return instruction, convert this:
424f22ef01cSRoman Divacky       //
425f22ef01cSRoman Divacky       //   return:
426f22ef01cSRoman Divacky       //     ...
427f22ef01cSRoman Divacky       //     ret ...
428f22ef01cSRoman Divacky       //
429f22ef01cSRoman Divacky       // into this:
430f22ef01cSRoman Divacky       //
431f22ef01cSRoman Divacky       //   return:
432f22ef01cSRoman Divacky       //     ...
4333ca95b02SDimitry Andric       //     %1 = <stack guard>
434f22ef01cSRoman Divacky       //     %2 = load StackGuardSlot
435f22ef01cSRoman Divacky       //     %3 = cmp i1 %1, %2
436f22ef01cSRoman Divacky       //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
437f22ef01cSRoman Divacky       //
438f22ef01cSRoman Divacky       //   SP_return:
439f22ef01cSRoman Divacky       //     ret ...
440f22ef01cSRoman Divacky       //
441f22ef01cSRoman Divacky       //   CallStackCheckFailBlk:
442f22ef01cSRoman Divacky       //     call void @__stack_chk_fail()
443f22ef01cSRoman Divacky       //     unreachable
444f22ef01cSRoman Divacky 
445f785676fSDimitry Andric       // Create the FailBB. We duplicate the BB every time since the MI tail
446f785676fSDimitry Andric       // merge pass will merge together all of the various BB into one including
447f785676fSDimitry Andric       // fail BB generated by the stack protector pseudo instruction.
448f785676fSDimitry Andric       BasicBlock *FailBB = CreateFailBB();
449f785676fSDimitry Andric 
450f22ef01cSRoman Divacky       // Split the basic block before the return instruction.
4517d523365SDimitry Andric       BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
4523b0f4066SDimitry Andric 
453f785676fSDimitry Andric       // Update the dominator tree if we need to.
4543b0f4066SDimitry Andric       if (DT && DT->isReachableFromEntry(BB)) {
4553b0f4066SDimitry Andric         DT->addNewBlock(NewBB, BB);
456f785676fSDimitry Andric         DT->addNewBlock(FailBB, BB);
4572754fe60SDimitry Andric       }
458f22ef01cSRoman Divacky 
459f22ef01cSRoman Divacky       // Remove default branch instruction to the new BB.
460f22ef01cSRoman Divacky       BB->getTerminator()->eraseFromParent();
461f22ef01cSRoman Divacky 
462f785676fSDimitry Andric       // Move the newly created basic block to the point right after the old
463f785676fSDimitry Andric       // basic block so that it's in the "fall through" position.
464f22ef01cSRoman Divacky       NewBB->moveAfter(BB);
465f22ef01cSRoman Divacky 
466f22ef01cSRoman Divacky       // Generate the stack protector instructions in the old basic block.
467f785676fSDimitry Andric       IRBuilder<> B(BB);
4683ca95b02SDimitry Andric       Value *Guard = getStackGuard(TLI, M, B);
4693ca95b02SDimitry Andric       LoadInst *LI2 = B.CreateLoad(AI, true);
4703ca95b02SDimitry Andric       Value *Cmp = B.CreateICmpEQ(Guard, LI2);
4717d523365SDimitry Andric       auto SuccessProb =
4727d523365SDimitry Andric           BranchProbabilityInfo::getBranchProbStackProtector(true);
4737d523365SDimitry Andric       auto FailureProb =
4747d523365SDimitry Andric           BranchProbabilityInfo::getBranchProbStackProtector(false);
47539d628a0SDimitry Andric       MDNode *Weights = MDBuilder(F->getContext())
4767d523365SDimitry Andric                             .createBranchWeights(SuccessProb.getNumerator(),
4777d523365SDimitry Andric                                                  FailureProb.getNumerator());
47839d628a0SDimitry Andric       B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
479f785676fSDimitry Andric     }
480f22ef01cSRoman Divacky   }
481f22ef01cSRoman Divacky 
48239d628a0SDimitry Andric   // Return if we didn't modify any basic blocks. i.e., there are no return
483f22ef01cSRoman Divacky   // statements in the function.
4847d523365SDimitry Andric   return HasPrologue;
485f22ef01cSRoman Divacky }
486f22ef01cSRoman Divacky 
487f22ef01cSRoman Divacky /// CreateFailBB - Create a basic block to jump to when the stack protector
488f22ef01cSRoman Divacky /// check fails.
489f22ef01cSRoman Divacky BasicBlock *StackProtector::CreateFailBB() {
490f785676fSDimitry Andric   LLVMContext &Context = F->getContext();
491f785676fSDimitry Andric   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
492f785676fSDimitry Andric   IRBuilder<> B(FailBB);
4933ca95b02SDimitry Andric   B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
49439d628a0SDimitry Andric   if (Trip.isOSOpenBSD()) {
49539d628a0SDimitry Andric     Constant *StackChkFail =
49639d628a0SDimitry Andric         M->getOrInsertFunction("__stack_smash_handler",
49739d628a0SDimitry Andric                                Type::getVoidTy(Context),
4987a7e6055SDimitry Andric                                Type::getInt8PtrTy(Context));
499f785676fSDimitry Andric 
500f785676fSDimitry Andric     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
501f785676fSDimitry Andric   } else {
50239d628a0SDimitry Andric     Constant *StackChkFail =
5037a7e6055SDimitry Andric         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
5047a7e6055SDimitry Andric 
505ff0cc061SDimitry Andric     B.CreateCall(StackChkFail, {});
506f785676fSDimitry Andric   }
507f785676fSDimitry Andric   B.CreateUnreachable();
508f22ef01cSRoman Divacky   return FailBB;
509f22ef01cSRoman Divacky }
5103ca95b02SDimitry Andric 
5113ca95b02SDimitry Andric bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
5123ca95b02SDimitry Andric   return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
5133ca95b02SDimitry Andric }
514