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 17f785676fSDimitry Andric #include "llvm/CodeGen/StackProtector.h" 18139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 19139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h" 2039d628a0SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h" 21f785676fSDimitry Andric #include "llvm/Analysis/ValueTracking.h" 2291bc56edSDimitry Andric #include "llvm/CodeGen/Analysis.h" 2391bc56edSDimitry Andric #include "llvm/CodeGen/Passes.h" 24139f7f9bSDimitry Andric #include "llvm/IR/Attributes.h" 25139f7f9bSDimitry Andric #include "llvm/IR/Constants.h" 26139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h" 27139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h" 28139f7f9bSDimitry Andric #include "llvm/IR/Function.h" 29f785676fSDimitry Andric #include "llvm/IR/GlobalValue.h" 30f785676fSDimitry Andric #include "llvm/IR/GlobalVariable.h" 31f785676fSDimitry Andric #include "llvm/IR/IRBuilder.h" 32139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h" 33f785676fSDimitry Andric #include "llvm/IR/IntrinsicInst.h" 34139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h" 3539d628a0SDimitry Andric #include "llvm/IR/MDBuilder.h" 36139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 37f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h" 3839d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h" 39f785676fSDimitry Andric #include <cstdlib> 40f22ef01cSRoman Divacky using namespace llvm; 41f22ef01cSRoman Divacky 4291bc56edSDimitry Andric #define DEBUG_TYPE "stack-protector" 4391bc56edSDimitry Andric 44139f7f9bSDimitry Andric STATISTIC(NumFunProtected, "Number of functions protected"); 45139f7f9bSDimitry Andric STATISTIC(NumAddrTaken, "Number of local variables that have their address" 46139f7f9bSDimitry Andric " taken."); 47139f7f9bSDimitry Andric 48f785676fSDimitry Andric static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp", 49f785676fSDimitry Andric cl::init(true), cl::Hidden); 50f22ef01cSRoman Divacky 51f22ef01cSRoman Divacky char StackProtector::ID = 0; 52f785676fSDimitry Andric INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors", 53f785676fSDimitry Andric false, true) 54f22ef01cSRoman Divacky 55f785676fSDimitry Andric FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) { 56f785676fSDimitry Andric return new StackProtector(TM); 57f785676fSDimitry Andric } 58f785676fSDimitry Andric 59f785676fSDimitry Andric StackProtector::SSPLayoutKind 60f785676fSDimitry Andric StackProtector::getSSPLayout(const AllocaInst *AI) const { 61f785676fSDimitry Andric return AI ? Layout.lookup(AI) : SSPLK_None; 62f22ef01cSRoman Divacky } 63f22ef01cSRoman Divacky 6491bc56edSDimitry Andric void StackProtector::adjustForColoring(const AllocaInst *From, 6591bc56edSDimitry Andric const AllocaInst *To) { 6691bc56edSDimitry Andric // When coloring replaces one alloca with another, transfer the SSPLayoutKind 6791bc56edSDimitry Andric // tag from the remapped to the target alloca. The remapped alloca should 6891bc56edSDimitry Andric // have a size smaller than or equal to the replacement alloca. 6991bc56edSDimitry Andric SSPLayoutMap::iterator I = Layout.find(From); 7091bc56edSDimitry Andric if (I != Layout.end()) { 7191bc56edSDimitry Andric SSPLayoutKind Kind = I->second; 7291bc56edSDimitry Andric Layout.erase(I); 7391bc56edSDimitry Andric 7491bc56edSDimitry Andric // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite 7591bc56edSDimitry Andric // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that 7691bc56edSDimitry Andric // SSPLK_SmallArray does not overwrite SSPLK_LargeArray. 7791bc56edSDimitry Andric I = Layout.find(To); 7891bc56edSDimitry Andric if (I == Layout.end()) 7991bc56edSDimitry Andric Layout.insert(std::make_pair(To, Kind)); 8091bc56edSDimitry Andric else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf) 8191bc56edSDimitry Andric I->second = Kind; 8291bc56edSDimitry Andric } 8391bc56edSDimitry Andric } 8491bc56edSDimitry Andric 85f22ef01cSRoman Divacky bool StackProtector::runOnFunction(Function &Fn) { 86f22ef01cSRoman Divacky F = &Fn; 87f22ef01cSRoman Divacky M = F->getParent(); 8891bc56edSDimitry Andric DominatorTreeWrapperPass *DTWP = 8991bc56edSDimitry Andric getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 9091bc56edSDimitry Andric DT = DTWP ? &DTWP->getDomTree() : nullptr; 9139d628a0SDimitry Andric TLI = TM->getSubtargetImpl()->getTargetLowering(); 92f22ef01cSRoman Divacky 93f785676fSDimitry Andric Attribute Attr = Fn.getAttributes().getAttribute( 94f785676fSDimitry Andric AttributeSet::FunctionIndex, "stack-protector-buffer-size"); 9591bc56edSDimitry Andric if (Attr.isStringAttribute() && 9691bc56edSDimitry Andric Attr.getValueAsString().getAsInteger(10, SSPBufferSize)) 9791bc56edSDimitry Andric return false; // Invalid integer string 9891bc56edSDimitry Andric 9991bc56edSDimitry Andric if (!RequiresStackProtector()) 10091bc56edSDimitry Andric return false; 101f22ef01cSRoman Divacky 102139f7f9bSDimitry Andric ++NumFunProtected; 103f22ef01cSRoman Divacky return InsertStackProtectors(); 104f22ef01cSRoman Divacky } 105f22ef01cSRoman Divacky 106f785676fSDimitry Andric /// \param [out] IsLarge is set to true if a protectable array is found and 107f785676fSDimitry Andric /// it is "large" ( >= ssp-buffer-size). In the case of a structure with 108f785676fSDimitry Andric /// multiple arrays, this gets set if any of them is large. 109f785676fSDimitry Andric bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge, 110f785676fSDimitry Andric bool Strong, 111139f7f9bSDimitry Andric bool InStruct) const { 112f785676fSDimitry Andric if (!Ty) 113f785676fSDimitry Andric return false; 1143861d79fSDimitry Andric if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 1153861d79fSDimitry Andric if (!AT->getElementType()->isIntegerTy(8)) { 1163861d79fSDimitry Andric // If we're on a non-Darwin platform or we're inside of a structure, don't 1173861d79fSDimitry Andric // add stack protectors unless the array is a character array. 118f785676fSDimitry Andric // However, in strong mode any array, regardless of type and size, 119f785676fSDimitry Andric // triggers a protector. 120f785676fSDimitry Andric if (!Strong && (InStruct || !Trip.isOSDarwin())) 1213861d79fSDimitry Andric return false; 1223861d79fSDimitry Andric } 1233861d79fSDimitry Andric 1243861d79fSDimitry Andric // If an array has more than SSPBufferSize bytes of allocated space, then we 1253861d79fSDimitry Andric // emit stack protectors. 126f785676fSDimitry Andric if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT)) { 127f785676fSDimitry Andric IsLarge = true; 128f785676fSDimitry Andric return true; 129f785676fSDimitry Andric } 130f785676fSDimitry Andric 131f785676fSDimitry Andric if (Strong) 132f785676fSDimitry Andric // Require a protector for all arrays in strong mode 1333861d79fSDimitry Andric return true; 1343861d79fSDimitry Andric } 1353861d79fSDimitry Andric 1363861d79fSDimitry Andric const StructType *ST = dyn_cast<StructType>(Ty); 137f785676fSDimitry Andric if (!ST) 1383861d79fSDimitry Andric return false; 139f785676fSDimitry Andric 140f785676fSDimitry Andric bool NeedsProtector = false; 141f785676fSDimitry Andric for (StructType::element_iterator I = ST->element_begin(), 142f785676fSDimitry Andric E = ST->element_end(); 143f785676fSDimitry Andric I != E; ++I) 144f785676fSDimitry Andric if (ContainsProtectableArray(*I, IsLarge, Strong, true)) { 145f785676fSDimitry Andric // If the element is a protectable array and is large (>= SSPBufferSize) 146f785676fSDimitry Andric // then we are done. If the protectable array is not large, then 147f785676fSDimitry Andric // keep looking in case a subsequent element is a large array. 148f785676fSDimitry Andric if (IsLarge) 149f785676fSDimitry Andric return true; 150f785676fSDimitry Andric NeedsProtector = true; 151f785676fSDimitry Andric } 152f785676fSDimitry Andric 153f785676fSDimitry Andric return NeedsProtector; 1543861d79fSDimitry Andric } 1553861d79fSDimitry Andric 156139f7f9bSDimitry Andric bool StackProtector::HasAddressTaken(const Instruction *AI) { 15791bc56edSDimitry Andric for (const User *U : AI->users()) { 158139f7f9bSDimitry Andric if (const StoreInst *SI = dyn_cast<StoreInst>(U)) { 159139f7f9bSDimitry Andric if (AI == SI->getValueOperand()) 160f22ef01cSRoman Divacky return true; 161139f7f9bSDimitry Andric } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) { 162139f7f9bSDimitry Andric if (AI == SI->getOperand(0)) 163139f7f9bSDimitry Andric return true; 164139f7f9bSDimitry Andric } else if (isa<CallInst>(U)) { 165139f7f9bSDimitry Andric return true; 166139f7f9bSDimitry Andric } else if (isa<InvokeInst>(U)) { 167139f7f9bSDimitry Andric return true; 168139f7f9bSDimitry Andric } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) { 169139f7f9bSDimitry Andric if (HasAddressTaken(SI)) 170139f7f9bSDimitry Andric return true; 171139f7f9bSDimitry Andric } else if (const PHINode *PN = dyn_cast<PHINode>(U)) { 172139f7f9bSDimitry Andric // Keep track of what PHI nodes we have already visited to ensure 173139f7f9bSDimitry Andric // they are only visited once. 17439d628a0SDimitry Andric if (VisitedPHIs.insert(PN).second) 175139f7f9bSDimitry Andric if (HasAddressTaken(PN)) 176139f7f9bSDimitry Andric return true; 177139f7f9bSDimitry Andric } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) { 178139f7f9bSDimitry Andric if (HasAddressTaken(GEP)) 179139f7f9bSDimitry Andric return true; 180139f7f9bSDimitry Andric } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) { 181139f7f9bSDimitry Andric if (HasAddressTaken(BI)) 182139f7f9bSDimitry Andric return true; 183139f7f9bSDimitry Andric } 184139f7f9bSDimitry Andric } 185139f7f9bSDimitry Andric return false; 186139f7f9bSDimitry Andric } 187f22ef01cSRoman Divacky 188139f7f9bSDimitry Andric /// \brief Check whether or not this function needs a stack protector based 189139f7f9bSDimitry Andric /// upon the stack protector level. 190139f7f9bSDimitry Andric /// 191139f7f9bSDimitry Andric /// We use two heuristics: a standard (ssp) and strong (sspstrong). 192139f7f9bSDimitry Andric /// The standard heuristic which will add a guard variable to functions that 193139f7f9bSDimitry Andric /// call alloca with a either a variable size or a size >= SSPBufferSize, 194139f7f9bSDimitry Andric /// functions with character buffers larger than SSPBufferSize, and functions 195139f7f9bSDimitry Andric /// with aggregates containing character buffers larger than SSPBufferSize. The 196139f7f9bSDimitry Andric /// strong heuristic will add a guard variables to functions that call alloca 197139f7f9bSDimitry Andric /// regardless of size, functions with any buffer regardless of type and size, 198139f7f9bSDimitry Andric /// functions with aggregates that contain any buffer regardless of type and 199139f7f9bSDimitry Andric /// size, and functions that contain stack-based variables that have had their 200139f7f9bSDimitry Andric /// address taken. 201139f7f9bSDimitry Andric bool StackProtector::RequiresStackProtector() { 202139f7f9bSDimitry Andric bool Strong = false; 203f785676fSDimitry Andric bool NeedsProtector = false; 204139f7f9bSDimitry Andric if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 205f785676fSDimitry Andric Attribute::StackProtectReq)) { 206f785676fSDimitry Andric NeedsProtector = true; 207f785676fSDimitry Andric Strong = true; // Use the same heuristic as strong to determine SSPLayout 208f785676fSDimitry Andric } else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 209139f7f9bSDimitry Andric Attribute::StackProtectStrong)) 210139f7f9bSDimitry Andric Strong = true; 211139f7f9bSDimitry Andric else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 212139f7f9bSDimitry Andric Attribute::StackProtect)) 213f22ef01cSRoman Divacky return false; 214f22ef01cSRoman Divacky 21539d628a0SDimitry Andric for (const BasicBlock &BB : *F) { 21639d628a0SDimitry Andric for (const Instruction &I : BB) { 21739d628a0SDimitry Andric if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 218139f7f9bSDimitry Andric if (AI->isArrayAllocation()) { 219139f7f9bSDimitry Andric // SSP-Strong: Enable protectors for any call to alloca, regardless 220139f7f9bSDimitry Andric // of size. 221139f7f9bSDimitry Andric if (Strong) 222f22ef01cSRoman Divacky return true; 223f22ef01cSRoman Divacky 22439d628a0SDimitry Andric if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) { 225f785676fSDimitry Andric if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) { 226139f7f9bSDimitry Andric // A call to alloca with size >= SSPBufferSize requires 227139f7f9bSDimitry Andric // stack protectors. 228f785676fSDimitry Andric Layout.insert(std::make_pair(AI, SSPLK_LargeArray)); 229f785676fSDimitry Andric NeedsProtector = true; 230f785676fSDimitry Andric } else if (Strong) { 231f785676fSDimitry Andric // Require protectors for all alloca calls in strong mode. 232f785676fSDimitry Andric Layout.insert(std::make_pair(AI, SSPLK_SmallArray)); 233f785676fSDimitry Andric NeedsProtector = true; 234f785676fSDimitry Andric } 235f785676fSDimitry Andric } else { 236f785676fSDimitry Andric // A call to alloca with a variable size requires protectors. 237f785676fSDimitry Andric Layout.insert(std::make_pair(AI, SSPLK_LargeArray)); 238f785676fSDimitry Andric NeedsProtector = true; 239f785676fSDimitry Andric } 240f785676fSDimitry Andric continue; 241139f7f9bSDimitry Andric } 242139f7f9bSDimitry Andric 243f785676fSDimitry Andric bool IsLarge = false; 244f785676fSDimitry Andric if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) { 245f785676fSDimitry Andric Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray 246f785676fSDimitry Andric : SSPLK_SmallArray)); 247f785676fSDimitry Andric NeedsProtector = true; 248f785676fSDimitry Andric continue; 249f785676fSDimitry Andric } 250139f7f9bSDimitry Andric 251139f7f9bSDimitry Andric if (Strong && HasAddressTaken(AI)) { 252139f7f9bSDimitry Andric ++NumAddrTaken; 253f785676fSDimitry Andric Layout.insert(std::make_pair(AI, SSPLK_AddrOf)); 254f785676fSDimitry Andric NeedsProtector = true; 255139f7f9bSDimitry Andric } 256139f7f9bSDimitry Andric } 257f22ef01cSRoman Divacky } 258f22ef01cSRoman Divacky } 259f22ef01cSRoman Divacky 260f785676fSDimitry Andric return NeedsProtector; 261f785676fSDimitry Andric } 262f785676fSDimitry Andric 263f785676fSDimitry Andric static bool InstructionWillNotHaveChain(const Instruction *I) { 264f785676fSDimitry Andric return !I->mayHaveSideEffects() && !I->mayReadFromMemory() && 265f785676fSDimitry Andric isSafeToSpeculativelyExecute(I); 266f785676fSDimitry Andric } 267f785676fSDimitry Andric 268f785676fSDimitry Andric /// Identify if RI has a previous instruction in the "Tail Position" and return 269f785676fSDimitry Andric /// it. Otherwise return 0. 270f785676fSDimitry Andric /// 271f785676fSDimitry Andric /// This is based off of the code in llvm::isInTailCallPosition. The difference 272f785676fSDimitry Andric /// is that it inverts the first part of llvm::isInTailCallPosition since 273f785676fSDimitry Andric /// isInTailCallPosition is checking if a call is in a tail call position, and 274f785676fSDimitry Andric /// we are searching for an unknown tail call that might be in the tail call 275f785676fSDimitry Andric /// position. Once we find the call though, the code uses the same refactored 276f785676fSDimitry Andric /// code, returnTypeIsEligibleForTailCall. 277f785676fSDimitry Andric static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI, 278f785676fSDimitry Andric const TargetLoweringBase *TLI) { 279f785676fSDimitry Andric // Establish a reasonable upper bound on the maximum amount of instructions we 280f785676fSDimitry Andric // will look through to find a tail call. 281f785676fSDimitry Andric unsigned SearchCounter = 0; 282f785676fSDimitry Andric const unsigned MaxSearch = 4; 283f785676fSDimitry Andric bool NoInterposingChain = true; 284f785676fSDimitry Andric 28591bc56edSDimitry Andric for (BasicBlock::reverse_iterator I = std::next(BB->rbegin()), E = BB->rend(); 286f785676fSDimitry Andric I != E && SearchCounter < MaxSearch; ++I) { 287f785676fSDimitry Andric Instruction *Inst = &*I; 288f785676fSDimitry Andric 289f785676fSDimitry Andric // Skip over debug intrinsics and do not allow them to affect our MaxSearch 290f785676fSDimitry Andric // counter. 291f785676fSDimitry Andric if (isa<DbgInfoIntrinsic>(Inst)) 292f785676fSDimitry Andric continue; 293f785676fSDimitry Andric 294f785676fSDimitry Andric // If we find a call and the following conditions are satisifed, then we 295f785676fSDimitry Andric // have found a tail call that satisfies at least the target independent 296f785676fSDimitry Andric // requirements of a tail call: 297f785676fSDimitry Andric // 298f785676fSDimitry Andric // 1. The call site has the tail marker. 299f785676fSDimitry Andric // 300f785676fSDimitry Andric // 2. The call site either will not cause the creation of a chain or if a 301f785676fSDimitry Andric // chain is necessary there are no instructions in between the callsite and 302f785676fSDimitry Andric // the call which would create an interposing chain. 303f785676fSDimitry Andric // 304f785676fSDimitry Andric // 3. The return type of the function does not impede tail call 305f785676fSDimitry Andric // optimization. 306f785676fSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(Inst)) { 307f785676fSDimitry Andric if (CI->isTailCall() && 308f785676fSDimitry Andric (InstructionWillNotHaveChain(CI) || NoInterposingChain) && 309f785676fSDimitry Andric returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI)) 310f785676fSDimitry Andric return CI; 311f785676fSDimitry Andric } 312f785676fSDimitry Andric 313f785676fSDimitry Andric // If we did not find a call see if we have an instruction that may create 314f785676fSDimitry Andric // an interposing chain. 315f785676fSDimitry Andric NoInterposingChain = 316f785676fSDimitry Andric NoInterposingChain && InstructionWillNotHaveChain(Inst); 317f785676fSDimitry Andric 318f785676fSDimitry Andric // Increment max search. 319f785676fSDimitry Andric SearchCounter++; 320f785676fSDimitry Andric } 321f785676fSDimitry Andric 32291bc56edSDimitry Andric return nullptr; 323f785676fSDimitry Andric } 324f785676fSDimitry Andric 325f785676fSDimitry Andric /// Insert code into the entry block that stores the __stack_chk_guard 326f785676fSDimitry Andric /// variable onto the stack: 327f785676fSDimitry Andric /// 328f785676fSDimitry Andric /// entry: 329f785676fSDimitry Andric /// StackGuardSlot = alloca i8* 330f785676fSDimitry Andric /// StackGuard = load __stack_chk_guard 331f785676fSDimitry Andric /// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot) 332f785676fSDimitry Andric /// 333f785676fSDimitry Andric /// Returns true if the platform/triple supports the stackprotectorcreate pseudo 334f785676fSDimitry Andric /// node. 335f785676fSDimitry Andric static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI, 33639d628a0SDimitry Andric const TargetLoweringBase *TLI, const Triple &TT, 337f785676fSDimitry Andric AllocaInst *&AI, Value *&StackGuardVar) { 338f785676fSDimitry Andric bool SupportsSelectionDAGSP = false; 339f785676fSDimitry Andric PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext()); 340f785676fSDimitry Andric unsigned AddressSpace, Offset; 341f785676fSDimitry Andric if (TLI->getStackCookieLocation(AddressSpace, Offset)) { 342f785676fSDimitry Andric Constant *OffsetVal = 343f785676fSDimitry Andric ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset); 344f785676fSDimitry Andric 34539d628a0SDimitry Andric StackGuardVar = 34639d628a0SDimitry Andric ConstantExpr::getIntToPtr(OffsetVal, PointerType::get(PtrTy, 34739d628a0SDimitry Andric AddressSpace)); 34839d628a0SDimitry Andric } else if (TT.isOSOpenBSD()) { 349f785676fSDimitry Andric StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy); 350f785676fSDimitry Andric cast<GlobalValue>(StackGuardVar) 351f785676fSDimitry Andric ->setVisibility(GlobalValue::HiddenVisibility); 352f785676fSDimitry Andric } else { 353f785676fSDimitry Andric SupportsSelectionDAGSP = true; 354f785676fSDimitry Andric StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy); 355f785676fSDimitry Andric } 356f785676fSDimitry Andric 357f785676fSDimitry Andric IRBuilder<> B(&F->getEntryBlock().front()); 35891bc56edSDimitry Andric AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot"); 359f785676fSDimitry Andric LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard"); 360f785676fSDimitry Andric B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI, 361f785676fSDimitry Andric AI); 362f785676fSDimitry Andric 363f785676fSDimitry Andric return SupportsSelectionDAGSP; 364f22ef01cSRoman Divacky } 365f22ef01cSRoman Divacky 366f22ef01cSRoman Divacky /// InsertStackProtectors - Insert code into the prologue and epilogue of the 367f22ef01cSRoman Divacky /// function. 368f22ef01cSRoman Divacky /// 369f22ef01cSRoman Divacky /// - The prologue code loads and stores the stack guard onto the stack. 370f22ef01cSRoman Divacky /// - The epilogue checks the value stored in the prologue against the original 371f22ef01cSRoman Divacky /// value. It calls __stack_chk_fail if they differ. 372f22ef01cSRoman Divacky bool StackProtector::InsertStackProtectors() { 373f785676fSDimitry Andric bool HasPrologue = false; 374f785676fSDimitry Andric bool SupportsSelectionDAGSP = 375f785676fSDimitry Andric EnableSelectionDAGSP && !TM->Options.EnableFastISel; 37691bc56edSDimitry Andric AllocaInst *AI = nullptr; // Place on stack that stores the stack guard. 37791bc56edSDimitry Andric Value *StackGuardVar = nullptr; // The stack guard variable. 378f22ef01cSRoman Divacky 379f22ef01cSRoman Divacky for (Function::iterator I = F->begin(), E = F->end(); I != E;) { 380f22ef01cSRoman Divacky BasicBlock *BB = I++; 381f22ef01cSRoman Divacky ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); 382f785676fSDimitry Andric if (!RI) 383f785676fSDimitry Andric continue; 384f22ef01cSRoman Divacky 385f785676fSDimitry Andric if (!HasPrologue) { 386f785676fSDimitry Andric HasPrologue = true; 387f785676fSDimitry Andric SupportsSelectionDAGSP &= 388f785676fSDimitry Andric CreatePrologue(F, M, RI, TLI, Trip, AI, StackGuardVar); 389f785676fSDimitry Andric } 390ffd1746dSEd Schouten 391f785676fSDimitry Andric if (SupportsSelectionDAGSP) { 392f785676fSDimitry Andric // Since we have a potential tail call, insert the special stack check 393f785676fSDimitry Andric // intrinsic. 39491bc56edSDimitry Andric Instruction *InsertionPt = nullptr; 395f785676fSDimitry Andric if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) { 396f785676fSDimitry Andric InsertionPt = CI; 397ffd1746dSEd Schouten } else { 398f785676fSDimitry Andric InsertionPt = RI; 399f785676fSDimitry Andric // At this point we know that BB has a return statement so it *DOES* 400f785676fSDimitry Andric // have a terminator. 40139d628a0SDimitry Andric assert(InsertionPt != nullptr && 40239d628a0SDimitry Andric "BB must have a terminator instruction at this point."); 403ffd1746dSEd Schouten } 404f22ef01cSRoman Divacky 405f785676fSDimitry Andric Function *Intrinsic = 406f785676fSDimitry Andric Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck); 407f785676fSDimitry Andric CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt); 408f785676fSDimitry Andric } else { 409f785676fSDimitry Andric // If we do not support SelectionDAG based tail calls, generate IR level 410f785676fSDimitry Andric // tail calls. 411f785676fSDimitry Andric // 412f22ef01cSRoman Divacky // For each block with a return instruction, convert this: 413f22ef01cSRoman Divacky // 414f22ef01cSRoman Divacky // return: 415f22ef01cSRoman Divacky // ... 416f22ef01cSRoman Divacky // ret ... 417f22ef01cSRoman Divacky // 418f22ef01cSRoman Divacky // into this: 419f22ef01cSRoman Divacky // 420f22ef01cSRoman Divacky // return: 421f22ef01cSRoman Divacky // ... 422f22ef01cSRoman Divacky // %1 = load __stack_chk_guard 423f22ef01cSRoman Divacky // %2 = load StackGuardSlot 424f22ef01cSRoman Divacky // %3 = cmp i1 %1, %2 425f22ef01cSRoman Divacky // br i1 %3, label %SP_return, label %CallStackCheckFailBlk 426f22ef01cSRoman Divacky // 427f22ef01cSRoman Divacky // SP_return: 428f22ef01cSRoman Divacky // ret ... 429f22ef01cSRoman Divacky // 430f22ef01cSRoman Divacky // CallStackCheckFailBlk: 431f22ef01cSRoman Divacky // call void @__stack_chk_fail() 432f22ef01cSRoman Divacky // unreachable 433f22ef01cSRoman Divacky 434f785676fSDimitry Andric // Create the FailBB. We duplicate the BB every time since the MI tail 435f785676fSDimitry Andric // merge pass will merge together all of the various BB into one including 436f785676fSDimitry Andric // fail BB generated by the stack protector pseudo instruction. 437f785676fSDimitry Andric BasicBlock *FailBB = CreateFailBB(); 438f785676fSDimitry Andric 439f22ef01cSRoman Divacky // Split the basic block before the return instruction. 440f22ef01cSRoman Divacky BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return"); 4413b0f4066SDimitry Andric 442f785676fSDimitry Andric // Update the dominator tree if we need to. 4433b0f4066SDimitry Andric if (DT && DT->isReachableFromEntry(BB)) { 4443b0f4066SDimitry Andric DT->addNewBlock(NewBB, BB); 445f785676fSDimitry Andric DT->addNewBlock(FailBB, BB); 4462754fe60SDimitry Andric } 447f22ef01cSRoman Divacky 448f22ef01cSRoman Divacky // Remove default branch instruction to the new BB. 449f22ef01cSRoman Divacky BB->getTerminator()->eraseFromParent(); 450f22ef01cSRoman Divacky 451f785676fSDimitry Andric // Move the newly created basic block to the point right after the old 452f785676fSDimitry Andric // basic block so that it's in the "fall through" position. 453f22ef01cSRoman Divacky NewBB->moveAfter(BB); 454f22ef01cSRoman Divacky 455f22ef01cSRoman Divacky // Generate the stack protector instructions in the old basic block. 456f785676fSDimitry Andric IRBuilder<> B(BB); 457f785676fSDimitry Andric LoadInst *LI1 = B.CreateLoad(StackGuardVar); 458f785676fSDimitry Andric LoadInst *LI2 = B.CreateLoad(AI); 459f785676fSDimitry Andric Value *Cmp = B.CreateICmpEQ(LI1, LI2); 46039d628a0SDimitry Andric unsigned SuccessWeight = 46139d628a0SDimitry Andric BranchProbabilityInfo::getBranchWeightStackProtector(true); 46239d628a0SDimitry Andric unsigned FailureWeight = 46339d628a0SDimitry Andric BranchProbabilityInfo::getBranchWeightStackProtector(false); 46439d628a0SDimitry Andric MDNode *Weights = MDBuilder(F->getContext()) 46539d628a0SDimitry Andric .createBranchWeights(SuccessWeight, FailureWeight); 46639d628a0SDimitry Andric B.CreateCondBr(Cmp, NewBB, FailBB, Weights); 467f785676fSDimitry Andric } 468f22ef01cSRoman Divacky } 469f22ef01cSRoman Divacky 47039d628a0SDimitry Andric // Return if we didn't modify any basic blocks. i.e., there are no return 471f22ef01cSRoman Divacky // statements in the function. 472f785676fSDimitry Andric if (!HasPrologue) 473f785676fSDimitry Andric return false; 4742754fe60SDimitry Andric 475f22ef01cSRoman Divacky return true; 476f22ef01cSRoman Divacky } 477f22ef01cSRoman Divacky 478f22ef01cSRoman Divacky /// CreateFailBB - Create a basic block to jump to when the stack protector 479f22ef01cSRoman Divacky /// check fails. 480f22ef01cSRoman Divacky BasicBlock *StackProtector::CreateFailBB() { 481f785676fSDimitry Andric LLVMContext &Context = F->getContext(); 482f785676fSDimitry Andric BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F); 483f785676fSDimitry Andric IRBuilder<> B(FailBB); 48439d628a0SDimitry Andric if (Trip.isOSOpenBSD()) { 48539d628a0SDimitry Andric Constant *StackChkFail = 48639d628a0SDimitry Andric M->getOrInsertFunction("__stack_smash_handler", 48739d628a0SDimitry Andric Type::getVoidTy(Context), 48839d628a0SDimitry Andric Type::getInt8PtrTy(Context), nullptr); 489f785676fSDimitry Andric 490f785676fSDimitry Andric B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH")); 491f785676fSDimitry Andric } else { 49239d628a0SDimitry Andric Constant *StackChkFail = 49339d628a0SDimitry Andric M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context), 49439d628a0SDimitry Andric nullptr); 495f785676fSDimitry Andric B.CreateCall(StackChkFail); 496f785676fSDimitry Andric } 497f785676fSDimitry Andric B.CreateUnreachable(); 498f22ef01cSRoman Divacky return FailBB; 499f22ef01cSRoman Divacky } 500