1*0b57cec5SDimitry Andric //===- StackProtector.cpp - Stack Protector Insertion ---------------------===// 2*0b57cec5SDimitry Andric // 3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6*0b57cec5SDimitry Andric // 7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 8*0b57cec5SDimitry Andric // 9*0b57cec5SDimitry Andric // This pass inserts stack protectors into functions which need them. A variable 10*0b57cec5SDimitry Andric // with a random value in it is stored onto the stack before the local variables 11*0b57cec5SDimitry Andric // are allocated. Upon exiting the block, the stored value is checked. If it's 12*0b57cec5SDimitry Andric // changed, then there was some sort of violation and the program aborts. 13*0b57cec5SDimitry Andric // 14*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 15*0b57cec5SDimitry Andric 16*0b57cec5SDimitry Andric #include "llvm/CodeGen/StackProtector.h" 17*0b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 18*0b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h" 19*0b57cec5SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h" 20*0b57cec5SDimitry Andric #include "llvm/Analysis/EHPersonalities.h" 215ffd83dbSDimitry Andric #include "llvm/Analysis/MemoryLocation.h" 22*0b57cec5SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h" 23*0b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h" 24*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h" 25*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h" 26*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h" 27*0b57cec5SDimitry Andric #include "llvm/IR/Attributes.h" 28*0b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h" 29*0b57cec5SDimitry Andric #include "llvm/IR/Constants.h" 30*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 31*0b57cec5SDimitry Andric #include "llvm/IR/DebugInfo.h" 32*0b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h" 33*0b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h" 34*0b57cec5SDimitry Andric #include "llvm/IR/Dominators.h" 35*0b57cec5SDimitry Andric #include "llvm/IR/Function.h" 36*0b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h" 37*0b57cec5SDimitry Andric #include "llvm/IR/Instruction.h" 38*0b57cec5SDimitry Andric #include "llvm/IR/Instructions.h" 39*0b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h" 40*0b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 41*0b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h" 42*0b57cec5SDimitry Andric #include "llvm/IR/Module.h" 43*0b57cec5SDimitry Andric #include "llvm/IR/Type.h" 44*0b57cec5SDimitry Andric #include "llvm/IR/User.h" 45480093f4SDimitry Andric #include "llvm/InitializePasses.h" 46*0b57cec5SDimitry Andric #include "llvm/Pass.h" 47*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h" 48*0b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 49*0b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h" 50*0b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h" 51*0b57cec5SDimitry Andric #include <utility> 52*0b57cec5SDimitry Andric 53*0b57cec5SDimitry Andric using namespace llvm; 54*0b57cec5SDimitry Andric 55*0b57cec5SDimitry Andric #define DEBUG_TYPE "stack-protector" 56*0b57cec5SDimitry Andric 57*0b57cec5SDimitry Andric STATISTIC(NumFunProtected, "Number of functions protected"); 58*0b57cec5SDimitry Andric STATISTIC(NumAddrTaken, "Number of local variables that have their address" 59*0b57cec5SDimitry Andric " taken."); 60*0b57cec5SDimitry Andric 61*0b57cec5SDimitry Andric static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp", 62*0b57cec5SDimitry Andric cl::init(true), cl::Hidden); 63*0b57cec5SDimitry Andric 64*0b57cec5SDimitry Andric char StackProtector::ID = 0; 65*0b57cec5SDimitry Andric 66480093f4SDimitry Andric StackProtector::StackProtector() : FunctionPass(ID), SSPBufferSize(8) { 67480093f4SDimitry Andric initializeStackProtectorPass(*PassRegistry::getPassRegistry()); 68480093f4SDimitry Andric } 69480093f4SDimitry Andric 70*0b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE, 71*0b57cec5SDimitry Andric "Insert stack protectors", false, true) 72*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 73fe6060f1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 74*0b57cec5SDimitry Andric INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE, 75*0b57cec5SDimitry Andric "Insert stack protectors", false, true) 76*0b57cec5SDimitry Andric 77*0b57cec5SDimitry Andric FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); } 78*0b57cec5SDimitry Andric 79*0b57cec5SDimitry Andric void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const { 80*0b57cec5SDimitry Andric AU.addRequired<TargetPassConfig>(); 81*0b57cec5SDimitry Andric AU.addPreserved<DominatorTreeWrapperPass>(); 82*0b57cec5SDimitry Andric } 83*0b57cec5SDimitry Andric 84*0b57cec5SDimitry Andric bool StackProtector::runOnFunction(Function &Fn) { 85*0b57cec5SDimitry Andric F = &Fn; 86*0b57cec5SDimitry Andric M = F->getParent(); 87*0b57cec5SDimitry Andric DominatorTreeWrapperPass *DTWP = 88*0b57cec5SDimitry Andric getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 89*0b57cec5SDimitry Andric DT = DTWP ? &DTWP->getDomTree() : nullptr; 90*0b57cec5SDimitry Andric TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>(); 91*0b57cec5SDimitry Andric Trip = TM->getTargetTriple(); 92*0b57cec5SDimitry Andric TLI = TM->getSubtargetImpl(Fn)->getTargetLowering(); 93*0b57cec5SDimitry Andric HasPrologue = false; 94*0b57cec5SDimitry Andric HasIRCheck = false; 95*0b57cec5SDimitry Andric 96*0b57cec5SDimitry Andric Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size"); 97*0b57cec5SDimitry Andric if (Attr.isStringAttribute() && 98*0b57cec5SDimitry Andric Attr.getValueAsString().getAsInteger(10, SSPBufferSize)) 99*0b57cec5SDimitry Andric return false; // Invalid integer string 100*0b57cec5SDimitry Andric 101*0b57cec5SDimitry Andric if (!RequiresStackProtector()) 102*0b57cec5SDimitry Andric return false; 103*0b57cec5SDimitry Andric 104*0b57cec5SDimitry Andric // TODO(etienneb): Functions with funclets are not correctly supported now. 105*0b57cec5SDimitry Andric // Do nothing if this is funclet-based personality. 106*0b57cec5SDimitry Andric if (Fn.hasPersonalityFn()) { 107*0b57cec5SDimitry Andric EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn()); 108*0b57cec5SDimitry Andric if (isFuncletEHPersonality(Personality)) 109*0b57cec5SDimitry Andric return false; 110*0b57cec5SDimitry Andric } 111*0b57cec5SDimitry Andric 112*0b57cec5SDimitry Andric ++NumFunProtected; 113*0b57cec5SDimitry Andric return InsertStackProtectors(); 114*0b57cec5SDimitry Andric } 115*0b57cec5SDimitry Andric 116*0b57cec5SDimitry Andric /// \param [out] IsLarge is set to true if a protectable array is found and 117*0b57cec5SDimitry Andric /// it is "large" ( >= ssp-buffer-size). In the case of a structure with 118*0b57cec5SDimitry Andric /// multiple arrays, this gets set if any of them is large. 119*0b57cec5SDimitry Andric bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge, 120*0b57cec5SDimitry Andric bool Strong, 121*0b57cec5SDimitry Andric bool InStruct) const { 122*0b57cec5SDimitry Andric if (!Ty) 123*0b57cec5SDimitry Andric return false; 124*0b57cec5SDimitry Andric if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 125*0b57cec5SDimitry Andric if (!AT->getElementType()->isIntegerTy(8)) { 126*0b57cec5SDimitry Andric // If we're on a non-Darwin platform or we're inside of a structure, don't 127*0b57cec5SDimitry Andric // add stack protectors unless the array is a character array. 128*0b57cec5SDimitry Andric // However, in strong mode any array, regardless of type and size, 129*0b57cec5SDimitry Andric // triggers a protector. 130*0b57cec5SDimitry Andric if (!Strong && (InStruct || !Trip.isOSDarwin())) 131*0b57cec5SDimitry Andric return false; 132*0b57cec5SDimitry Andric } 133*0b57cec5SDimitry Andric 134*0b57cec5SDimitry Andric // If an array has more than SSPBufferSize bytes of allocated space, then we 135*0b57cec5SDimitry Andric // emit stack protectors. 136*0b57cec5SDimitry Andric if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) { 137*0b57cec5SDimitry Andric IsLarge = true; 138*0b57cec5SDimitry Andric return true; 139*0b57cec5SDimitry Andric } 140*0b57cec5SDimitry Andric 141*0b57cec5SDimitry Andric if (Strong) 142*0b57cec5SDimitry Andric // Require a protector for all arrays in strong mode 143*0b57cec5SDimitry Andric return true; 144*0b57cec5SDimitry Andric } 145*0b57cec5SDimitry Andric 146*0b57cec5SDimitry Andric const StructType *ST = dyn_cast<StructType>(Ty); 147*0b57cec5SDimitry Andric if (!ST) 148*0b57cec5SDimitry Andric return false; 149*0b57cec5SDimitry Andric 150*0b57cec5SDimitry Andric bool NeedsProtector = false; 151349cc55cSDimitry Andric for (Type *ET : ST->elements()) 152349cc55cSDimitry Andric if (ContainsProtectableArray(ET, IsLarge, Strong, true)) { 153*0b57cec5SDimitry Andric // If the element is a protectable array and is large (>= SSPBufferSize) 154*0b57cec5SDimitry Andric // then we are done. If the protectable array is not large, then 155*0b57cec5SDimitry Andric // keep looking in case a subsequent element is a large array. 156*0b57cec5SDimitry Andric if (IsLarge) 157*0b57cec5SDimitry Andric return true; 158*0b57cec5SDimitry Andric NeedsProtector = true; 159*0b57cec5SDimitry Andric } 160*0b57cec5SDimitry Andric 161*0b57cec5SDimitry Andric return NeedsProtector; 162*0b57cec5SDimitry Andric } 163*0b57cec5SDimitry Andric 1645ffd83dbSDimitry Andric bool StackProtector::HasAddressTaken(const Instruction *AI, 1650eae32dcSDimitry Andric TypeSize AllocSize) { 1665ffd83dbSDimitry Andric const DataLayout &DL = M->getDataLayout(); 167c14a5a88SDimitry Andric for (const User *U : AI->users()) { 168c14a5a88SDimitry Andric const auto *I = cast<Instruction>(U); 1695ffd83dbSDimitry Andric // If this instruction accesses memory make sure it doesn't access beyond 1705ffd83dbSDimitry Andric // the bounds of the allocated object. 1715ffd83dbSDimitry Andric Optional<MemoryLocation> MemLoc = MemoryLocation::getOrNone(I); 172e8d8bef9SDimitry Andric if (MemLoc.hasValue() && MemLoc->Size.hasValue() && 1730eae32dcSDimitry Andric !TypeSize::isKnownGE(AllocSize, 1740eae32dcSDimitry Andric TypeSize::getFixed(MemLoc->Size.getValue()))) 1755ffd83dbSDimitry Andric return true; 176c14a5a88SDimitry Andric switch (I->getOpcode()) { 177c14a5a88SDimitry Andric case Instruction::Store: 178c14a5a88SDimitry Andric if (AI == cast<StoreInst>(I)->getValueOperand()) 179c14a5a88SDimitry Andric return true; 180c14a5a88SDimitry Andric break; 181c14a5a88SDimitry Andric case Instruction::AtomicCmpXchg: 182c14a5a88SDimitry Andric // cmpxchg conceptually includes both a load and store from the same 183c14a5a88SDimitry Andric // location. So, like store, the value being stored is what matters. 184c14a5a88SDimitry Andric if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand()) 185c14a5a88SDimitry Andric return true; 186c14a5a88SDimitry Andric break; 187c14a5a88SDimitry Andric case Instruction::PtrToInt: 188c14a5a88SDimitry Andric if (AI == cast<PtrToIntInst>(I)->getOperand(0)) 189c14a5a88SDimitry Andric return true; 190c14a5a88SDimitry Andric break; 191c14a5a88SDimitry Andric case Instruction::Call: { 192c14a5a88SDimitry Andric // Ignore intrinsics that do not become real instructions. 193c14a5a88SDimitry Andric // TODO: Narrow this to intrinsics that have store-like effects. 194c14a5a88SDimitry Andric const auto *CI = cast<CallInst>(I); 195d409305fSDimitry Andric if (!CI->isDebugOrPseudoInst() && !CI->isLifetimeStartOrEnd()) 196c14a5a88SDimitry Andric return true; 197c14a5a88SDimitry Andric break; 198c14a5a88SDimitry Andric } 199c14a5a88SDimitry Andric case Instruction::Invoke: 200c14a5a88SDimitry Andric return true; 2015ffd83dbSDimitry Andric case Instruction::GetElementPtr: { 2025ffd83dbSDimitry Andric // If the GEP offset is out-of-bounds, or is non-constant and so has to be 2035ffd83dbSDimitry Andric // assumed to be potentially out-of-bounds, then any memory access that 2045ffd83dbSDimitry Andric // would use it could also be out-of-bounds meaning stack protection is 2055ffd83dbSDimitry Andric // required. 2065ffd83dbSDimitry Andric const GetElementPtrInst *GEP = cast<GetElementPtrInst>(I); 2070eae32dcSDimitry Andric unsigned IndexSize = DL.getIndexTypeSizeInBits(I->getType()); 2080eae32dcSDimitry Andric APInt Offset(IndexSize, 0); 2090eae32dcSDimitry Andric if (!GEP->accumulateConstantOffset(DL, Offset)) 2100eae32dcSDimitry Andric return true; 2110eae32dcSDimitry Andric TypeSize OffsetSize = TypeSize::Fixed(Offset.getLimitedValue()); 2120eae32dcSDimitry Andric if (!TypeSize::isKnownGT(AllocSize, OffsetSize)) 2135ffd83dbSDimitry Andric return true; 2145ffd83dbSDimitry Andric // Adjust AllocSize to be the space remaining after this offset. 2150eae32dcSDimitry Andric // We can't subtract a fixed size from a scalable one, so in that case 2160eae32dcSDimitry Andric // assume the scalable value is of minimum size. 2170eae32dcSDimitry Andric TypeSize NewAllocSize = 2180eae32dcSDimitry Andric TypeSize::Fixed(AllocSize.getKnownMinValue()) - OffsetSize; 2190eae32dcSDimitry Andric if (HasAddressTaken(I, NewAllocSize)) 2205ffd83dbSDimitry Andric return true; 2215ffd83dbSDimitry Andric break; 2225ffd83dbSDimitry Andric } 223c14a5a88SDimitry Andric case Instruction::BitCast: 224c14a5a88SDimitry Andric case Instruction::Select: 225c14a5a88SDimitry Andric case Instruction::AddrSpaceCast: 2265ffd83dbSDimitry Andric if (HasAddressTaken(I, AllocSize)) 227c14a5a88SDimitry Andric return true; 228c14a5a88SDimitry Andric break; 229c14a5a88SDimitry Andric case Instruction::PHI: { 230c14a5a88SDimitry Andric // Keep track of what PHI nodes we have already visited to ensure 231c14a5a88SDimitry Andric // they are only visited once. 232c14a5a88SDimitry Andric const auto *PN = cast<PHINode>(I); 233c14a5a88SDimitry Andric if (VisitedPHIs.insert(PN).second) 2345ffd83dbSDimitry Andric if (HasAddressTaken(PN, AllocSize)) 235c14a5a88SDimitry Andric return true; 236c14a5a88SDimitry Andric break; 237c14a5a88SDimitry Andric } 238c14a5a88SDimitry Andric case Instruction::Load: 239c14a5a88SDimitry Andric case Instruction::AtomicRMW: 240c14a5a88SDimitry Andric case Instruction::Ret: 241c14a5a88SDimitry Andric // These instructions take an address operand, but have load-like or 242c14a5a88SDimitry Andric // other innocuous behavior that should not trigger a stack protector. 243c14a5a88SDimitry Andric // atomicrmw conceptually has both load and store semantics, but the 244c14a5a88SDimitry Andric // value being stored must be integer; so if a pointer is being stored, 245c14a5a88SDimitry Andric // we'll catch it in the PtrToInt case above. 246c14a5a88SDimitry Andric break; 247c14a5a88SDimitry Andric default: 248c14a5a88SDimitry Andric // Conservatively return true for any instruction that takes an address 249c14a5a88SDimitry Andric // operand, but is not handled above. 250c14a5a88SDimitry Andric return true; 251c14a5a88SDimitry Andric } 252c14a5a88SDimitry Andric } 253c14a5a88SDimitry Andric return false; 254c14a5a88SDimitry Andric } 255c14a5a88SDimitry Andric 256*0b57cec5SDimitry Andric /// Search for the first call to the llvm.stackprotector intrinsic and return it 257*0b57cec5SDimitry Andric /// if present. 258*0b57cec5SDimitry Andric static const CallInst *findStackProtectorIntrinsic(Function &F) { 259*0b57cec5SDimitry Andric for (const BasicBlock &BB : F) 260*0b57cec5SDimitry Andric for (const Instruction &I : BB) 261e8d8bef9SDimitry Andric if (const auto *II = dyn_cast<IntrinsicInst>(&I)) 262e8d8bef9SDimitry Andric if (II->getIntrinsicID() == Intrinsic::stackprotector) 263e8d8bef9SDimitry Andric return II; 264*0b57cec5SDimitry Andric return nullptr; 265*0b57cec5SDimitry Andric } 266*0b57cec5SDimitry Andric 267*0b57cec5SDimitry Andric /// Check whether or not this function needs a stack protector based 268*0b57cec5SDimitry Andric /// upon the stack protector level. 269*0b57cec5SDimitry Andric /// 270*0b57cec5SDimitry Andric /// We use two heuristics: a standard (ssp) and strong (sspstrong). 271*0b57cec5SDimitry Andric /// The standard heuristic which will add a guard variable to functions that 272*0b57cec5SDimitry Andric /// call alloca with a either a variable size or a size >= SSPBufferSize, 273*0b57cec5SDimitry Andric /// functions with character buffers larger than SSPBufferSize, and functions 274*0b57cec5SDimitry Andric /// with aggregates containing character buffers larger than SSPBufferSize. The 275*0b57cec5SDimitry Andric /// strong heuristic will add a guard variables to functions that call alloca 276*0b57cec5SDimitry Andric /// regardless of size, functions with any buffer regardless of type and size, 277*0b57cec5SDimitry Andric /// functions with aggregates that contain any buffer regardless of type and 278*0b57cec5SDimitry Andric /// size, and functions that contain stack-based variables that have had their 279*0b57cec5SDimitry Andric /// address taken. 280*0b57cec5SDimitry Andric bool StackProtector::RequiresStackProtector() { 281*0b57cec5SDimitry Andric bool Strong = false; 282*0b57cec5SDimitry Andric bool NeedsProtector = false; 283*0b57cec5SDimitry Andric 284*0b57cec5SDimitry Andric if (F->hasFnAttribute(Attribute::SafeStack)) 285*0b57cec5SDimitry Andric return false; 286*0b57cec5SDimitry Andric 287*0b57cec5SDimitry Andric // We are constructing the OptimizationRemarkEmitter on the fly rather than 288*0b57cec5SDimitry Andric // using the analysis pass to avoid building DominatorTree and LoopInfo which 289*0b57cec5SDimitry Andric // are not available this late in the IR pipeline. 290*0b57cec5SDimitry Andric OptimizationRemarkEmitter ORE(F); 291*0b57cec5SDimitry Andric 292*0b57cec5SDimitry Andric if (F->hasFnAttribute(Attribute::StackProtectReq)) { 293*0b57cec5SDimitry Andric ORE.emit([&]() { 294*0b57cec5SDimitry Andric return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F) 295*0b57cec5SDimitry Andric << "Stack protection applied to function " 296*0b57cec5SDimitry Andric << ore::NV("Function", F) 297*0b57cec5SDimitry Andric << " due to a function attribute or command-line switch"; 298*0b57cec5SDimitry Andric }); 299*0b57cec5SDimitry Andric NeedsProtector = true; 300*0b57cec5SDimitry Andric Strong = true; // Use the same heuristic as strong to determine SSPLayout 301*0b57cec5SDimitry Andric } else if (F->hasFnAttribute(Attribute::StackProtectStrong)) 302*0b57cec5SDimitry Andric Strong = true; 303*0b57cec5SDimitry Andric else if (!F->hasFnAttribute(Attribute::StackProtect)) 304*0b57cec5SDimitry Andric return false; 305*0b57cec5SDimitry Andric 306*0b57cec5SDimitry Andric for (const BasicBlock &BB : *F) { 307*0b57cec5SDimitry Andric for (const Instruction &I : BB) { 308*0b57cec5SDimitry Andric if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 309*0b57cec5SDimitry Andric if (AI->isArrayAllocation()) { 310*0b57cec5SDimitry Andric auto RemarkBuilder = [&]() { 311*0b57cec5SDimitry Andric return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray", 312*0b57cec5SDimitry Andric &I) 313*0b57cec5SDimitry Andric << "Stack protection applied to function " 314*0b57cec5SDimitry Andric << ore::NV("Function", F) 315*0b57cec5SDimitry Andric << " due to a call to alloca or use of a variable length " 316*0b57cec5SDimitry Andric "array"; 317*0b57cec5SDimitry Andric }; 318*0b57cec5SDimitry Andric if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) { 319*0b57cec5SDimitry Andric if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) { 320*0b57cec5SDimitry Andric // A call to alloca with size >= SSPBufferSize requires 321*0b57cec5SDimitry Andric // stack protectors. 322*0b57cec5SDimitry Andric Layout.insert(std::make_pair(AI, 323*0b57cec5SDimitry Andric MachineFrameInfo::SSPLK_LargeArray)); 324*0b57cec5SDimitry Andric ORE.emit(RemarkBuilder); 325*0b57cec5SDimitry Andric NeedsProtector = true; 326*0b57cec5SDimitry Andric } else if (Strong) { 327*0b57cec5SDimitry Andric // Require protectors for all alloca calls in strong mode. 328*0b57cec5SDimitry Andric Layout.insert(std::make_pair(AI, 329*0b57cec5SDimitry Andric MachineFrameInfo::SSPLK_SmallArray)); 330*0b57cec5SDimitry Andric ORE.emit(RemarkBuilder); 331*0b57cec5SDimitry Andric NeedsProtector = true; 332*0b57cec5SDimitry Andric } 333*0b57cec5SDimitry Andric } else { 334*0b57cec5SDimitry Andric // A call to alloca with a variable size requires protectors. 335*0b57cec5SDimitry Andric Layout.insert(std::make_pair(AI, 336*0b57cec5SDimitry Andric MachineFrameInfo::SSPLK_LargeArray)); 337*0b57cec5SDimitry Andric ORE.emit(RemarkBuilder); 338*0b57cec5SDimitry Andric NeedsProtector = true; 339*0b57cec5SDimitry Andric } 340*0b57cec5SDimitry Andric continue; 341*0b57cec5SDimitry Andric } 342*0b57cec5SDimitry Andric 343*0b57cec5SDimitry Andric bool IsLarge = false; 344*0b57cec5SDimitry Andric if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) { 345*0b57cec5SDimitry Andric Layout.insert(std::make_pair(AI, IsLarge 346*0b57cec5SDimitry Andric ? MachineFrameInfo::SSPLK_LargeArray 347*0b57cec5SDimitry Andric : MachineFrameInfo::SSPLK_SmallArray)); 348*0b57cec5SDimitry Andric ORE.emit([&]() { 349*0b57cec5SDimitry Andric return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I) 350*0b57cec5SDimitry Andric << "Stack protection applied to function " 351*0b57cec5SDimitry Andric << ore::NV("Function", F) 352*0b57cec5SDimitry Andric << " due to a stack allocated buffer or struct containing a " 353*0b57cec5SDimitry Andric "buffer"; 354*0b57cec5SDimitry Andric }); 355*0b57cec5SDimitry Andric NeedsProtector = true; 356*0b57cec5SDimitry Andric continue; 357*0b57cec5SDimitry Andric } 358*0b57cec5SDimitry Andric 3595ffd83dbSDimitry Andric if (Strong && HasAddressTaken(AI, M->getDataLayout().getTypeAllocSize( 3605ffd83dbSDimitry Andric AI->getAllocatedType()))) { 361*0b57cec5SDimitry Andric ++NumAddrTaken; 362*0b57cec5SDimitry Andric Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf)); 363*0b57cec5SDimitry Andric ORE.emit([&]() { 364*0b57cec5SDimitry Andric return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken", 365*0b57cec5SDimitry Andric &I) 366*0b57cec5SDimitry Andric << "Stack protection applied to function " 367*0b57cec5SDimitry Andric << ore::NV("Function", F) 368*0b57cec5SDimitry Andric << " due to the address of a local variable being taken"; 369*0b57cec5SDimitry Andric }); 370*0b57cec5SDimitry Andric NeedsProtector = true; 371*0b57cec5SDimitry Andric } 3725ffd83dbSDimitry Andric // Clear any PHIs that we visited, to make sure we examine all uses of 3735ffd83dbSDimitry Andric // any subsequent allocas that we look at. 3745ffd83dbSDimitry Andric VisitedPHIs.clear(); 375*0b57cec5SDimitry Andric } 376*0b57cec5SDimitry Andric } 377*0b57cec5SDimitry Andric } 378*0b57cec5SDimitry Andric 379*0b57cec5SDimitry Andric return NeedsProtector; 380*0b57cec5SDimitry Andric } 381*0b57cec5SDimitry Andric 382*0b57cec5SDimitry Andric /// Create a stack guard loading and populate whether SelectionDAG SSP is 383*0b57cec5SDimitry Andric /// supported. 384*0b57cec5SDimitry Andric static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M, 385*0b57cec5SDimitry Andric IRBuilder<> &B, 386*0b57cec5SDimitry Andric bool *SupportsSelectionDAGSP = nullptr) { 387e8d8bef9SDimitry Andric Value *Guard = TLI->getIRStackGuard(B); 388fe6060f1SDimitry Andric StringRef GuardMode = M->getStackProtectorGuard(); 389fe6060f1SDimitry Andric if ((GuardMode == "tls" || GuardMode.empty()) && Guard) 390*0b57cec5SDimitry Andric return B.CreateLoad(B.getInt8PtrTy(), Guard, true, "StackGuard"); 391*0b57cec5SDimitry Andric 392*0b57cec5SDimitry Andric // Use SelectionDAG SSP handling, since there isn't an IR guard. 393*0b57cec5SDimitry Andric // 394*0b57cec5SDimitry Andric // This is more or less weird, since we optionally output whether we 395*0b57cec5SDimitry Andric // should perform a SelectionDAG SP here. The reason is that it's strictly 396*0b57cec5SDimitry Andric // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also 397*0b57cec5SDimitry Andric // mutating. There is no way to get this bit without mutating the IR, so 398*0b57cec5SDimitry Andric // getting this bit has to happen in this right time. 399*0b57cec5SDimitry Andric // 400*0b57cec5SDimitry Andric // We could have define a new function TLI::supportsSelectionDAGSP(), but that 401*0b57cec5SDimitry Andric // will put more burden on the backends' overriding work, especially when it 402*0b57cec5SDimitry Andric // actually conveys the same information getIRStackGuard() already gives. 403*0b57cec5SDimitry Andric if (SupportsSelectionDAGSP) 404*0b57cec5SDimitry Andric *SupportsSelectionDAGSP = true; 405*0b57cec5SDimitry Andric TLI->insertSSPDeclarations(*M); 406*0b57cec5SDimitry Andric return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard)); 407*0b57cec5SDimitry Andric } 408*0b57cec5SDimitry Andric 409*0b57cec5SDimitry Andric /// Insert code into the entry block that stores the stack guard 410*0b57cec5SDimitry Andric /// variable onto the stack: 411*0b57cec5SDimitry Andric /// 412*0b57cec5SDimitry Andric /// entry: 413*0b57cec5SDimitry Andric /// StackGuardSlot = alloca i8* 414*0b57cec5SDimitry Andric /// StackGuard = <stack guard> 415*0b57cec5SDimitry Andric /// call void @llvm.stackprotector(StackGuard, StackGuardSlot) 416*0b57cec5SDimitry Andric /// 417*0b57cec5SDimitry Andric /// Returns true if the platform/triple supports the stackprotectorcreate pseudo 418*0b57cec5SDimitry Andric /// node. 419*0b57cec5SDimitry Andric static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI, 420*0b57cec5SDimitry Andric const TargetLoweringBase *TLI, AllocaInst *&AI) { 421*0b57cec5SDimitry Andric bool SupportsSelectionDAGSP = false; 422*0b57cec5SDimitry Andric IRBuilder<> B(&F->getEntryBlock().front()); 423*0b57cec5SDimitry Andric PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext()); 424*0b57cec5SDimitry Andric AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot"); 425*0b57cec5SDimitry Andric 426*0b57cec5SDimitry Andric Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP); 427*0b57cec5SDimitry Andric B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), 428*0b57cec5SDimitry Andric {GuardSlot, AI}); 429*0b57cec5SDimitry Andric return SupportsSelectionDAGSP; 430*0b57cec5SDimitry Andric } 431*0b57cec5SDimitry Andric 432*0b57cec5SDimitry Andric /// InsertStackProtectors - Insert code into the prologue and epilogue of the 433*0b57cec5SDimitry Andric /// function. 434*0b57cec5SDimitry Andric /// 435*0b57cec5SDimitry Andric /// - The prologue code loads and stores the stack guard onto the stack. 436*0b57cec5SDimitry Andric /// - The epilogue checks the value stored in the prologue against the original 437*0b57cec5SDimitry Andric /// value. It calls __stack_chk_fail if they differ. 438*0b57cec5SDimitry Andric bool StackProtector::InsertStackProtectors() { 439*0b57cec5SDimitry Andric // If the target wants to XOR the frame pointer into the guard value, it's 440*0b57cec5SDimitry Andric // impossible to emit the check in IR, so the target *must* support stack 441*0b57cec5SDimitry Andric // protection in SDAG. 442*0b57cec5SDimitry Andric bool SupportsSelectionDAGSP = 443*0b57cec5SDimitry Andric TLI->useStackGuardXorFP() || 444349cc55cSDimitry Andric (EnableSelectionDAGSP && !TM->Options.EnableFastISel); 445*0b57cec5SDimitry Andric AllocaInst *AI = nullptr; // Place on stack that stores the stack guard. 446*0b57cec5SDimitry Andric 447349cc55cSDimitry Andric for (BasicBlock &BB : llvm::make_early_inc_range(*F)) { 448349cc55cSDimitry Andric ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()); 449*0b57cec5SDimitry Andric if (!RI) 450*0b57cec5SDimitry Andric continue; 451*0b57cec5SDimitry Andric 452*0b57cec5SDimitry Andric // Generate prologue instrumentation if not already generated. 453*0b57cec5SDimitry Andric if (!HasPrologue) { 454*0b57cec5SDimitry Andric HasPrologue = true; 455*0b57cec5SDimitry Andric SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI); 456*0b57cec5SDimitry Andric } 457*0b57cec5SDimitry Andric 458*0b57cec5SDimitry Andric // SelectionDAG based code generation. Nothing else needs to be done here. 459*0b57cec5SDimitry Andric // The epilogue instrumentation is postponed to SelectionDAG. 460*0b57cec5SDimitry Andric if (SupportsSelectionDAGSP) 461*0b57cec5SDimitry Andric break; 462*0b57cec5SDimitry Andric 463*0b57cec5SDimitry Andric // Find the stack guard slot if the prologue was not created by this pass 464*0b57cec5SDimitry Andric // itself via a previous call to CreatePrologue(). 465*0b57cec5SDimitry Andric if (!AI) { 466*0b57cec5SDimitry Andric const CallInst *SPCall = findStackProtectorIntrinsic(*F); 467*0b57cec5SDimitry Andric assert(SPCall && "Call to llvm.stackprotector is missing"); 468*0b57cec5SDimitry Andric AI = cast<AllocaInst>(SPCall->getArgOperand(1)); 469*0b57cec5SDimitry Andric } 470*0b57cec5SDimitry Andric 471*0b57cec5SDimitry Andric // Set HasIRCheck to true, so that SelectionDAG will not generate its own 472*0b57cec5SDimitry Andric // version. SelectionDAG called 'shouldEmitSDCheck' to check whether 473*0b57cec5SDimitry Andric // instrumentation has already been generated. 474*0b57cec5SDimitry Andric HasIRCheck = true; 475*0b57cec5SDimitry Andric 47623408297SDimitry Andric // If we're instrumenting a block with a musttail call, the check has to be 47723408297SDimitry Andric // inserted before the call rather than between it and the return. The 47823408297SDimitry Andric // verifier guarantees that a musttail call is either directly before the 47923408297SDimitry Andric // return or with a single correct bitcast of the return value in between so 48023408297SDimitry Andric // we don't need to worry about many situations here. 48123408297SDimitry Andric Instruction *CheckLoc = RI; 48223408297SDimitry Andric Instruction *Prev = RI->getPrevNonDebugInstruction(); 48323408297SDimitry Andric if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isMustTailCall()) 48423408297SDimitry Andric CheckLoc = Prev; 48523408297SDimitry Andric else if (Prev) { 48623408297SDimitry Andric Prev = Prev->getPrevNonDebugInstruction(); 48723408297SDimitry Andric if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isMustTailCall()) 48823408297SDimitry Andric CheckLoc = Prev; 48923408297SDimitry Andric } 49023408297SDimitry Andric 491*0b57cec5SDimitry Andric // Generate epilogue instrumentation. The epilogue intrumentation can be 492*0b57cec5SDimitry Andric // function-based or inlined depending on which mechanism the target is 493*0b57cec5SDimitry Andric // providing. 494*0b57cec5SDimitry Andric if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) { 495*0b57cec5SDimitry Andric // Generate the function-based epilogue instrumentation. 496*0b57cec5SDimitry Andric // The target provides a guard check function, generate a call to it. 49723408297SDimitry Andric IRBuilder<> B(CheckLoc); 498*0b57cec5SDimitry Andric LoadInst *Guard = B.CreateLoad(B.getInt8PtrTy(), AI, true, "Guard"); 499*0b57cec5SDimitry Andric CallInst *Call = B.CreateCall(GuardCheck, {Guard}); 500*0b57cec5SDimitry Andric Call->setAttributes(GuardCheck->getAttributes()); 501*0b57cec5SDimitry Andric Call->setCallingConv(GuardCheck->getCallingConv()); 502*0b57cec5SDimitry Andric } else { 503*0b57cec5SDimitry Andric // Generate the epilogue with inline instrumentation. 50423408297SDimitry Andric // If we do not support SelectionDAG based calls, generate IR level 50523408297SDimitry Andric // calls. 506*0b57cec5SDimitry Andric // 507*0b57cec5SDimitry Andric // For each block with a return instruction, convert this: 508*0b57cec5SDimitry Andric // 509*0b57cec5SDimitry Andric // return: 510*0b57cec5SDimitry Andric // ... 511*0b57cec5SDimitry Andric // ret ... 512*0b57cec5SDimitry Andric // 513*0b57cec5SDimitry Andric // into this: 514*0b57cec5SDimitry Andric // 515*0b57cec5SDimitry Andric // return: 516*0b57cec5SDimitry Andric // ... 517*0b57cec5SDimitry Andric // %1 = <stack guard> 518*0b57cec5SDimitry Andric // %2 = load StackGuardSlot 519*0b57cec5SDimitry Andric // %3 = cmp i1 %1, %2 520*0b57cec5SDimitry Andric // br i1 %3, label %SP_return, label %CallStackCheckFailBlk 521*0b57cec5SDimitry Andric // 522*0b57cec5SDimitry Andric // SP_return: 523*0b57cec5SDimitry Andric // ret ... 524*0b57cec5SDimitry Andric // 525*0b57cec5SDimitry Andric // CallStackCheckFailBlk: 526*0b57cec5SDimitry Andric // call void @__stack_chk_fail() 527*0b57cec5SDimitry Andric // unreachable 528*0b57cec5SDimitry Andric 529*0b57cec5SDimitry Andric // Create the FailBB. We duplicate the BB every time since the MI tail 530*0b57cec5SDimitry Andric // merge pass will merge together all of the various BB into one including 531*0b57cec5SDimitry Andric // fail BB generated by the stack protector pseudo instruction. 532*0b57cec5SDimitry Andric BasicBlock *FailBB = CreateFailBB(); 533*0b57cec5SDimitry Andric 534*0b57cec5SDimitry Andric // Split the basic block before the return instruction. 53523408297SDimitry Andric BasicBlock *NewBB = 536349cc55cSDimitry Andric BB.splitBasicBlock(CheckLoc->getIterator(), "SP_return"); 537*0b57cec5SDimitry Andric 538*0b57cec5SDimitry Andric // Update the dominator tree if we need to. 539349cc55cSDimitry Andric if (DT && DT->isReachableFromEntry(&BB)) { 540349cc55cSDimitry Andric DT->addNewBlock(NewBB, &BB); 541349cc55cSDimitry Andric DT->addNewBlock(FailBB, &BB); 542*0b57cec5SDimitry Andric } 543*0b57cec5SDimitry Andric 544*0b57cec5SDimitry Andric // Remove default branch instruction to the new BB. 545349cc55cSDimitry Andric BB.getTerminator()->eraseFromParent(); 546*0b57cec5SDimitry Andric 547*0b57cec5SDimitry Andric // Move the newly created basic block to the point right after the old 548*0b57cec5SDimitry Andric // basic block so that it's in the "fall through" position. 549349cc55cSDimitry Andric NewBB->moveAfter(&BB); 550*0b57cec5SDimitry Andric 551*0b57cec5SDimitry Andric // Generate the stack protector instructions in the old basic block. 552349cc55cSDimitry Andric IRBuilder<> B(&BB); 553*0b57cec5SDimitry Andric Value *Guard = getStackGuard(TLI, M, B); 554*0b57cec5SDimitry Andric LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true); 555*0b57cec5SDimitry Andric Value *Cmp = B.CreateICmpEQ(Guard, LI2); 556*0b57cec5SDimitry Andric auto SuccessProb = 557*0b57cec5SDimitry Andric BranchProbabilityInfo::getBranchProbStackProtector(true); 558*0b57cec5SDimitry Andric auto FailureProb = 559*0b57cec5SDimitry Andric BranchProbabilityInfo::getBranchProbStackProtector(false); 560*0b57cec5SDimitry Andric MDNode *Weights = MDBuilder(F->getContext()) 561*0b57cec5SDimitry Andric .createBranchWeights(SuccessProb.getNumerator(), 562*0b57cec5SDimitry Andric FailureProb.getNumerator()); 563*0b57cec5SDimitry Andric B.CreateCondBr(Cmp, NewBB, FailBB, Weights); 564*0b57cec5SDimitry Andric } 565*0b57cec5SDimitry Andric } 566*0b57cec5SDimitry Andric 567*0b57cec5SDimitry Andric // Return if we didn't modify any basic blocks. i.e., there are no return 568*0b57cec5SDimitry Andric // statements in the function. 569*0b57cec5SDimitry Andric return HasPrologue; 570*0b57cec5SDimitry Andric } 571*0b57cec5SDimitry Andric 572*0b57cec5SDimitry Andric /// CreateFailBB - Create a basic block to jump to when the stack protector 573*0b57cec5SDimitry Andric /// check fails. 574*0b57cec5SDimitry Andric BasicBlock *StackProtector::CreateFailBB() { 575*0b57cec5SDimitry Andric LLVMContext &Context = F->getContext(); 576*0b57cec5SDimitry Andric BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F); 577*0b57cec5SDimitry Andric IRBuilder<> B(FailBB); 578e8d8bef9SDimitry Andric if (F->getSubprogram()) 579e8d8bef9SDimitry Andric B.SetCurrentDebugLocation( 580e8d8bef9SDimitry Andric DILocation::get(Context, 0, 0, F->getSubprogram())); 581*0b57cec5SDimitry Andric if (Trip.isOSOpenBSD()) { 582*0b57cec5SDimitry Andric FunctionCallee StackChkFail = M->getOrInsertFunction( 583*0b57cec5SDimitry Andric "__stack_smash_handler", Type::getVoidTy(Context), 584*0b57cec5SDimitry Andric Type::getInt8PtrTy(Context)); 585*0b57cec5SDimitry Andric 586*0b57cec5SDimitry Andric B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH")); 587*0b57cec5SDimitry Andric } else { 588*0b57cec5SDimitry Andric FunctionCallee StackChkFail = 589*0b57cec5SDimitry Andric M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context)); 590*0b57cec5SDimitry Andric 591*0b57cec5SDimitry Andric B.CreateCall(StackChkFail, {}); 592*0b57cec5SDimitry Andric } 593*0b57cec5SDimitry Andric B.CreateUnreachable(); 594*0b57cec5SDimitry Andric return FailBB; 595*0b57cec5SDimitry Andric } 596*0b57cec5SDimitry Andric 597*0b57cec5SDimitry Andric bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const { 598*0b57cec5SDimitry Andric return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator()); 599*0b57cec5SDimitry Andric } 600*0b57cec5SDimitry Andric 601*0b57cec5SDimitry Andric void StackProtector::copyToMachineFrameInfo(MachineFrameInfo &MFI) const { 602*0b57cec5SDimitry Andric if (Layout.empty()) 603*0b57cec5SDimitry Andric return; 604*0b57cec5SDimitry Andric 605*0b57cec5SDimitry Andric for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) { 606*0b57cec5SDimitry Andric if (MFI.isDeadObjectIndex(I)) 607*0b57cec5SDimitry Andric continue; 608*0b57cec5SDimitry Andric 609*0b57cec5SDimitry Andric const AllocaInst *AI = MFI.getObjectAllocation(I); 610*0b57cec5SDimitry Andric if (!AI) 611*0b57cec5SDimitry Andric continue; 612*0b57cec5SDimitry Andric 613*0b57cec5SDimitry Andric SSPLayoutMap::const_iterator LI = Layout.find(AI); 614*0b57cec5SDimitry Andric if (LI == Layout.end()) 615*0b57cec5SDimitry Andric continue; 616*0b57cec5SDimitry Andric 617*0b57cec5SDimitry Andric MFI.setObjectSSPLayout(I, LI->second); 618*0b57cec5SDimitry Andric } 619*0b57cec5SDimitry Andric } 620