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) 73*0b57cec5SDimitry Andric INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE, 74*0b57cec5SDimitry Andric "Insert stack protectors", false, true) 75*0b57cec5SDimitry Andric 76*0b57cec5SDimitry Andric FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); } 77*0b57cec5SDimitry Andric 78*0b57cec5SDimitry Andric void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const { 79*0b57cec5SDimitry Andric AU.addRequired<TargetPassConfig>(); 80*0b57cec5SDimitry Andric AU.addPreserved<DominatorTreeWrapperPass>(); 81*0b57cec5SDimitry Andric } 82*0b57cec5SDimitry Andric 83*0b57cec5SDimitry Andric bool StackProtector::runOnFunction(Function &Fn) { 84*0b57cec5SDimitry Andric F = &Fn; 85*0b57cec5SDimitry Andric M = F->getParent(); 86*0b57cec5SDimitry Andric DominatorTreeWrapperPass *DTWP = 87*0b57cec5SDimitry Andric getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 88*0b57cec5SDimitry Andric DT = DTWP ? &DTWP->getDomTree() : nullptr; 89*0b57cec5SDimitry Andric TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>(); 90*0b57cec5SDimitry Andric Trip = TM->getTargetTriple(); 91*0b57cec5SDimitry Andric TLI = TM->getSubtargetImpl(Fn)->getTargetLowering(); 92*0b57cec5SDimitry Andric HasPrologue = false; 93*0b57cec5SDimitry Andric HasIRCheck = false; 94*0b57cec5SDimitry Andric 95*0b57cec5SDimitry Andric Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size"); 96*0b57cec5SDimitry Andric if (Attr.isStringAttribute() && 97*0b57cec5SDimitry Andric Attr.getValueAsString().getAsInteger(10, SSPBufferSize)) 98*0b57cec5SDimitry Andric return false; // Invalid integer string 99*0b57cec5SDimitry Andric 100*0b57cec5SDimitry Andric if (!RequiresStackProtector()) 101*0b57cec5SDimitry Andric return false; 102*0b57cec5SDimitry Andric 103*0b57cec5SDimitry Andric // TODO(etienneb): Functions with funclets are not correctly supported now. 104*0b57cec5SDimitry Andric // Do nothing if this is funclet-based personality. 105*0b57cec5SDimitry Andric if (Fn.hasPersonalityFn()) { 106*0b57cec5SDimitry Andric EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn()); 107*0b57cec5SDimitry Andric if (isFuncletEHPersonality(Personality)) 108*0b57cec5SDimitry Andric return false; 109*0b57cec5SDimitry Andric } 110*0b57cec5SDimitry Andric 111*0b57cec5SDimitry Andric ++NumFunProtected; 112*0b57cec5SDimitry Andric return InsertStackProtectors(); 113*0b57cec5SDimitry Andric } 114*0b57cec5SDimitry Andric 115*0b57cec5SDimitry Andric /// \param [out] IsLarge is set to true if a protectable array is found and 116*0b57cec5SDimitry Andric /// it is "large" ( >= ssp-buffer-size). In the case of a structure with 117*0b57cec5SDimitry Andric /// multiple arrays, this gets set if any of them is large. 118*0b57cec5SDimitry Andric bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge, 119*0b57cec5SDimitry Andric bool Strong, 120*0b57cec5SDimitry Andric bool InStruct) const { 121*0b57cec5SDimitry Andric if (!Ty) 122*0b57cec5SDimitry Andric return false; 123*0b57cec5SDimitry Andric if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 124*0b57cec5SDimitry Andric if (!AT->getElementType()->isIntegerTy(8)) { 125*0b57cec5SDimitry Andric // If we're on a non-Darwin platform or we're inside of a structure, don't 126*0b57cec5SDimitry Andric // add stack protectors unless the array is a character array. 127*0b57cec5SDimitry Andric // However, in strong mode any array, regardless of type and size, 128*0b57cec5SDimitry Andric // triggers a protector. 129*0b57cec5SDimitry Andric if (!Strong && (InStruct || !Trip.isOSDarwin())) 130*0b57cec5SDimitry Andric return false; 131*0b57cec5SDimitry Andric } 132*0b57cec5SDimitry Andric 133*0b57cec5SDimitry Andric // If an array has more than SSPBufferSize bytes of allocated space, then we 134*0b57cec5SDimitry Andric // emit stack protectors. 135*0b57cec5SDimitry Andric if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) { 136*0b57cec5SDimitry Andric IsLarge = true; 137*0b57cec5SDimitry Andric return true; 138*0b57cec5SDimitry Andric } 139*0b57cec5SDimitry Andric 140*0b57cec5SDimitry Andric if (Strong) 141*0b57cec5SDimitry Andric // Require a protector for all arrays in strong mode 142*0b57cec5SDimitry Andric return true; 143*0b57cec5SDimitry Andric } 144*0b57cec5SDimitry Andric 145*0b57cec5SDimitry Andric const StructType *ST = dyn_cast<StructType>(Ty); 146*0b57cec5SDimitry Andric if (!ST) 147*0b57cec5SDimitry Andric return false; 148*0b57cec5SDimitry Andric 149*0b57cec5SDimitry Andric bool NeedsProtector = false; 150*0b57cec5SDimitry Andric for (StructType::element_iterator I = ST->element_begin(), 151*0b57cec5SDimitry Andric E = ST->element_end(); 152*0b57cec5SDimitry Andric I != E; ++I) 153*0b57cec5SDimitry Andric if (ContainsProtectableArray(*I, IsLarge, Strong, true)) { 154*0b57cec5SDimitry Andric // If the element is a protectable array and is large (>= SSPBufferSize) 155*0b57cec5SDimitry Andric // then we are done. If the protectable array is not large, then 156*0b57cec5SDimitry Andric // keep looking in case a subsequent element is a large array. 157*0b57cec5SDimitry Andric if (IsLarge) 158*0b57cec5SDimitry Andric return true; 159*0b57cec5SDimitry Andric NeedsProtector = true; 160*0b57cec5SDimitry Andric } 161*0b57cec5SDimitry Andric 162*0b57cec5SDimitry Andric return NeedsProtector; 163*0b57cec5SDimitry Andric } 164*0b57cec5SDimitry Andric 1655ffd83dbSDimitry Andric bool StackProtector::HasAddressTaken(const Instruction *AI, 1665ffd83dbSDimitry Andric uint64_t AllocSize) { 1675ffd83dbSDimitry Andric const DataLayout &DL = M->getDataLayout(); 168c14a5a88SDimitry Andric for (const User *U : AI->users()) { 169c14a5a88SDimitry Andric const auto *I = cast<Instruction>(U); 1705ffd83dbSDimitry Andric // If this instruction accesses memory make sure it doesn't access beyond 1715ffd83dbSDimitry Andric // the bounds of the allocated object. 1725ffd83dbSDimitry Andric Optional<MemoryLocation> MemLoc = MemoryLocation::getOrNone(I); 1735ffd83dbSDimitry Andric if (MemLoc.hasValue() && MemLoc->Size.getValue() > AllocSize) 1745ffd83dbSDimitry Andric return true; 175c14a5a88SDimitry Andric switch (I->getOpcode()) { 176c14a5a88SDimitry Andric case Instruction::Store: 177c14a5a88SDimitry Andric if (AI == cast<StoreInst>(I)->getValueOperand()) 178c14a5a88SDimitry Andric return true; 179c14a5a88SDimitry Andric break; 180c14a5a88SDimitry Andric case Instruction::AtomicCmpXchg: 181c14a5a88SDimitry Andric // cmpxchg conceptually includes both a load and store from the same 182c14a5a88SDimitry Andric // location. So, like store, the value being stored is what matters. 183c14a5a88SDimitry Andric if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand()) 184c14a5a88SDimitry Andric return true; 185c14a5a88SDimitry Andric break; 186c14a5a88SDimitry Andric case Instruction::PtrToInt: 187c14a5a88SDimitry Andric if (AI == cast<PtrToIntInst>(I)->getOperand(0)) 188c14a5a88SDimitry Andric return true; 189c14a5a88SDimitry Andric break; 190c14a5a88SDimitry Andric case Instruction::Call: { 191c14a5a88SDimitry Andric // Ignore intrinsics that do not become real instructions. 192c14a5a88SDimitry Andric // TODO: Narrow this to intrinsics that have store-like effects. 193c14a5a88SDimitry Andric const auto *CI = cast<CallInst>(I); 194c14a5a88SDimitry Andric if (!isa<DbgInfoIntrinsic>(CI) && !CI->isLifetimeStartOrEnd()) 195c14a5a88SDimitry Andric return true; 196c14a5a88SDimitry Andric break; 197c14a5a88SDimitry Andric } 198c14a5a88SDimitry Andric case Instruction::Invoke: 199c14a5a88SDimitry Andric return true; 2005ffd83dbSDimitry Andric case Instruction::GetElementPtr: { 2015ffd83dbSDimitry Andric // If the GEP offset is out-of-bounds, or is non-constant and so has to be 2025ffd83dbSDimitry Andric // assumed to be potentially out-of-bounds, then any memory access that 2035ffd83dbSDimitry Andric // would use it could also be out-of-bounds meaning stack protection is 2045ffd83dbSDimitry Andric // required. 2055ffd83dbSDimitry Andric const GetElementPtrInst *GEP = cast<GetElementPtrInst>(I); 2065ffd83dbSDimitry Andric unsigned TypeSize = DL.getIndexTypeSizeInBits(I->getType()); 2075ffd83dbSDimitry Andric APInt Offset(TypeSize, 0); 2085ffd83dbSDimitry Andric APInt MaxOffset(TypeSize, AllocSize); 2095ffd83dbSDimitry Andric if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.ugt(MaxOffset)) 2105ffd83dbSDimitry Andric return true; 2115ffd83dbSDimitry Andric // Adjust AllocSize to be the space remaining after this offset. 2125ffd83dbSDimitry Andric if (HasAddressTaken(I, AllocSize - Offset.getLimitedValue())) 2135ffd83dbSDimitry Andric return true; 2145ffd83dbSDimitry Andric break; 2155ffd83dbSDimitry Andric } 216c14a5a88SDimitry Andric case Instruction::BitCast: 217c14a5a88SDimitry Andric case Instruction::Select: 218c14a5a88SDimitry Andric case Instruction::AddrSpaceCast: 2195ffd83dbSDimitry Andric if (HasAddressTaken(I, AllocSize)) 220c14a5a88SDimitry Andric return true; 221c14a5a88SDimitry Andric break; 222c14a5a88SDimitry Andric case Instruction::PHI: { 223c14a5a88SDimitry Andric // Keep track of what PHI nodes we have already visited to ensure 224c14a5a88SDimitry Andric // they are only visited once. 225c14a5a88SDimitry Andric const auto *PN = cast<PHINode>(I); 226c14a5a88SDimitry Andric if (VisitedPHIs.insert(PN).second) 2275ffd83dbSDimitry Andric if (HasAddressTaken(PN, AllocSize)) 228c14a5a88SDimitry Andric return true; 229c14a5a88SDimitry Andric break; 230c14a5a88SDimitry Andric } 231c14a5a88SDimitry Andric case Instruction::Load: 232c14a5a88SDimitry Andric case Instruction::AtomicRMW: 233c14a5a88SDimitry Andric case Instruction::Ret: 234c14a5a88SDimitry Andric // These instructions take an address operand, but have load-like or 235c14a5a88SDimitry Andric // other innocuous behavior that should not trigger a stack protector. 236c14a5a88SDimitry Andric // atomicrmw conceptually has both load and store semantics, but the 237c14a5a88SDimitry Andric // value being stored must be integer; so if a pointer is being stored, 238c14a5a88SDimitry Andric // we'll catch it in the PtrToInt case above. 239c14a5a88SDimitry Andric break; 240c14a5a88SDimitry Andric default: 241c14a5a88SDimitry Andric // Conservatively return true for any instruction that takes an address 242c14a5a88SDimitry Andric // operand, but is not handled above. 243c14a5a88SDimitry Andric return true; 244c14a5a88SDimitry Andric } 245c14a5a88SDimitry Andric } 246c14a5a88SDimitry Andric return false; 247c14a5a88SDimitry Andric } 248c14a5a88SDimitry Andric 249*0b57cec5SDimitry Andric /// Search for the first call to the llvm.stackprotector intrinsic and return it 250*0b57cec5SDimitry Andric /// if present. 251*0b57cec5SDimitry Andric static const CallInst *findStackProtectorIntrinsic(Function &F) { 252*0b57cec5SDimitry Andric for (const BasicBlock &BB : F) 253*0b57cec5SDimitry Andric for (const Instruction &I : BB) 254*0b57cec5SDimitry Andric if (const CallInst *CI = dyn_cast<CallInst>(&I)) 255*0b57cec5SDimitry Andric if (CI->getCalledFunction() == 256*0b57cec5SDimitry Andric Intrinsic::getDeclaration(F.getParent(), Intrinsic::stackprotector)) 257*0b57cec5SDimitry Andric return CI; 258*0b57cec5SDimitry Andric return nullptr; 259*0b57cec5SDimitry Andric } 260*0b57cec5SDimitry Andric 261*0b57cec5SDimitry Andric /// Check whether or not this function needs a stack protector based 262*0b57cec5SDimitry Andric /// upon the stack protector level. 263*0b57cec5SDimitry Andric /// 264*0b57cec5SDimitry Andric /// We use two heuristics: a standard (ssp) and strong (sspstrong). 265*0b57cec5SDimitry Andric /// The standard heuristic which will add a guard variable to functions that 266*0b57cec5SDimitry Andric /// call alloca with a either a variable size or a size >= SSPBufferSize, 267*0b57cec5SDimitry Andric /// functions with character buffers larger than SSPBufferSize, and functions 268*0b57cec5SDimitry Andric /// with aggregates containing character buffers larger than SSPBufferSize. The 269*0b57cec5SDimitry Andric /// strong heuristic will add a guard variables to functions that call alloca 270*0b57cec5SDimitry Andric /// regardless of size, functions with any buffer regardless of type and size, 271*0b57cec5SDimitry Andric /// functions with aggregates that contain any buffer regardless of type and 272*0b57cec5SDimitry Andric /// size, and functions that contain stack-based variables that have had their 273*0b57cec5SDimitry Andric /// address taken. 274*0b57cec5SDimitry Andric bool StackProtector::RequiresStackProtector() { 275*0b57cec5SDimitry Andric bool Strong = false; 276*0b57cec5SDimitry Andric bool NeedsProtector = false; 277*0b57cec5SDimitry Andric HasPrologue = findStackProtectorIntrinsic(*F); 278*0b57cec5SDimitry Andric 279*0b57cec5SDimitry Andric if (F->hasFnAttribute(Attribute::SafeStack)) 280*0b57cec5SDimitry Andric return false; 281*0b57cec5SDimitry Andric 282*0b57cec5SDimitry Andric // We are constructing the OptimizationRemarkEmitter on the fly rather than 283*0b57cec5SDimitry Andric // using the analysis pass to avoid building DominatorTree and LoopInfo which 284*0b57cec5SDimitry Andric // are not available this late in the IR pipeline. 285*0b57cec5SDimitry Andric OptimizationRemarkEmitter ORE(F); 286*0b57cec5SDimitry Andric 287*0b57cec5SDimitry Andric if (F->hasFnAttribute(Attribute::StackProtectReq)) { 288*0b57cec5SDimitry Andric ORE.emit([&]() { 289*0b57cec5SDimitry Andric return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F) 290*0b57cec5SDimitry Andric << "Stack protection applied to function " 291*0b57cec5SDimitry Andric << ore::NV("Function", F) 292*0b57cec5SDimitry Andric << " due to a function attribute or command-line switch"; 293*0b57cec5SDimitry Andric }); 294*0b57cec5SDimitry Andric NeedsProtector = true; 295*0b57cec5SDimitry Andric Strong = true; // Use the same heuristic as strong to determine SSPLayout 296*0b57cec5SDimitry Andric } else if (F->hasFnAttribute(Attribute::StackProtectStrong)) 297*0b57cec5SDimitry Andric Strong = true; 298*0b57cec5SDimitry Andric else if (HasPrologue) 299*0b57cec5SDimitry Andric NeedsProtector = true; 300*0b57cec5SDimitry Andric else if (!F->hasFnAttribute(Attribute::StackProtect)) 301*0b57cec5SDimitry Andric return false; 302*0b57cec5SDimitry Andric 303*0b57cec5SDimitry Andric for (const BasicBlock &BB : *F) { 304*0b57cec5SDimitry Andric for (const Instruction &I : BB) { 305*0b57cec5SDimitry Andric if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 306*0b57cec5SDimitry Andric if (AI->isArrayAllocation()) { 307*0b57cec5SDimitry Andric auto RemarkBuilder = [&]() { 308*0b57cec5SDimitry Andric return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray", 309*0b57cec5SDimitry Andric &I) 310*0b57cec5SDimitry Andric << "Stack protection applied to function " 311*0b57cec5SDimitry Andric << ore::NV("Function", F) 312*0b57cec5SDimitry Andric << " due to a call to alloca or use of a variable length " 313*0b57cec5SDimitry Andric "array"; 314*0b57cec5SDimitry Andric }; 315*0b57cec5SDimitry Andric if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) { 316*0b57cec5SDimitry Andric if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) { 317*0b57cec5SDimitry Andric // A call to alloca with size >= SSPBufferSize requires 318*0b57cec5SDimitry Andric // stack protectors. 319*0b57cec5SDimitry Andric Layout.insert(std::make_pair(AI, 320*0b57cec5SDimitry Andric MachineFrameInfo::SSPLK_LargeArray)); 321*0b57cec5SDimitry Andric ORE.emit(RemarkBuilder); 322*0b57cec5SDimitry Andric NeedsProtector = true; 323*0b57cec5SDimitry Andric } else if (Strong) { 324*0b57cec5SDimitry Andric // Require protectors for all alloca calls in strong mode. 325*0b57cec5SDimitry Andric Layout.insert(std::make_pair(AI, 326*0b57cec5SDimitry Andric MachineFrameInfo::SSPLK_SmallArray)); 327*0b57cec5SDimitry Andric ORE.emit(RemarkBuilder); 328*0b57cec5SDimitry Andric NeedsProtector = true; 329*0b57cec5SDimitry Andric } 330*0b57cec5SDimitry Andric } else { 331*0b57cec5SDimitry Andric // A call to alloca with a variable size requires protectors. 332*0b57cec5SDimitry Andric Layout.insert(std::make_pair(AI, 333*0b57cec5SDimitry Andric MachineFrameInfo::SSPLK_LargeArray)); 334*0b57cec5SDimitry Andric ORE.emit(RemarkBuilder); 335*0b57cec5SDimitry Andric NeedsProtector = true; 336*0b57cec5SDimitry Andric } 337*0b57cec5SDimitry Andric continue; 338*0b57cec5SDimitry Andric } 339*0b57cec5SDimitry Andric 340*0b57cec5SDimitry Andric bool IsLarge = false; 341*0b57cec5SDimitry Andric if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) { 342*0b57cec5SDimitry Andric Layout.insert(std::make_pair(AI, IsLarge 343*0b57cec5SDimitry Andric ? MachineFrameInfo::SSPLK_LargeArray 344*0b57cec5SDimitry Andric : MachineFrameInfo::SSPLK_SmallArray)); 345*0b57cec5SDimitry Andric ORE.emit([&]() { 346*0b57cec5SDimitry Andric return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I) 347*0b57cec5SDimitry Andric << "Stack protection applied to function " 348*0b57cec5SDimitry Andric << ore::NV("Function", F) 349*0b57cec5SDimitry Andric << " due to a stack allocated buffer or struct containing a " 350*0b57cec5SDimitry Andric "buffer"; 351*0b57cec5SDimitry Andric }); 352*0b57cec5SDimitry Andric NeedsProtector = true; 353*0b57cec5SDimitry Andric continue; 354*0b57cec5SDimitry Andric } 355*0b57cec5SDimitry Andric 3565ffd83dbSDimitry Andric if (Strong && HasAddressTaken(AI, M->getDataLayout().getTypeAllocSize( 3575ffd83dbSDimitry Andric AI->getAllocatedType()))) { 358*0b57cec5SDimitry Andric ++NumAddrTaken; 359*0b57cec5SDimitry Andric Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf)); 360*0b57cec5SDimitry Andric ORE.emit([&]() { 361*0b57cec5SDimitry Andric return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken", 362*0b57cec5SDimitry Andric &I) 363*0b57cec5SDimitry Andric << "Stack protection applied to function " 364*0b57cec5SDimitry Andric << ore::NV("Function", F) 365*0b57cec5SDimitry Andric << " due to the address of a local variable being taken"; 366*0b57cec5SDimitry Andric }); 367*0b57cec5SDimitry Andric NeedsProtector = true; 368*0b57cec5SDimitry Andric } 3695ffd83dbSDimitry Andric // Clear any PHIs that we visited, to make sure we examine all uses of 3705ffd83dbSDimitry Andric // any subsequent allocas that we look at. 3715ffd83dbSDimitry Andric VisitedPHIs.clear(); 372*0b57cec5SDimitry Andric } 373*0b57cec5SDimitry Andric } 374*0b57cec5SDimitry Andric } 375*0b57cec5SDimitry Andric 376*0b57cec5SDimitry Andric return NeedsProtector; 377*0b57cec5SDimitry Andric } 378*0b57cec5SDimitry Andric 379*0b57cec5SDimitry Andric /// Create a stack guard loading and populate whether SelectionDAG SSP is 380*0b57cec5SDimitry Andric /// supported. 381*0b57cec5SDimitry Andric static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M, 382*0b57cec5SDimitry Andric IRBuilder<> &B, 383*0b57cec5SDimitry Andric bool *SupportsSelectionDAGSP = nullptr) { 384*0b57cec5SDimitry Andric if (Value *Guard = TLI->getIRStackGuard(B)) 385*0b57cec5SDimitry Andric return B.CreateLoad(B.getInt8PtrTy(), Guard, true, "StackGuard"); 386*0b57cec5SDimitry Andric 387*0b57cec5SDimitry Andric // Use SelectionDAG SSP handling, since there isn't an IR guard. 388*0b57cec5SDimitry Andric // 389*0b57cec5SDimitry Andric // This is more or less weird, since we optionally output whether we 390*0b57cec5SDimitry Andric // should perform a SelectionDAG SP here. The reason is that it's strictly 391*0b57cec5SDimitry Andric // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also 392*0b57cec5SDimitry Andric // mutating. There is no way to get this bit without mutating the IR, so 393*0b57cec5SDimitry Andric // getting this bit has to happen in this right time. 394*0b57cec5SDimitry Andric // 395*0b57cec5SDimitry Andric // We could have define a new function TLI::supportsSelectionDAGSP(), but that 396*0b57cec5SDimitry Andric // will put more burden on the backends' overriding work, especially when it 397*0b57cec5SDimitry Andric // actually conveys the same information getIRStackGuard() already gives. 398*0b57cec5SDimitry Andric if (SupportsSelectionDAGSP) 399*0b57cec5SDimitry Andric *SupportsSelectionDAGSP = true; 400*0b57cec5SDimitry Andric TLI->insertSSPDeclarations(*M); 401*0b57cec5SDimitry Andric return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard)); 402*0b57cec5SDimitry Andric } 403*0b57cec5SDimitry Andric 404*0b57cec5SDimitry Andric /// Insert code into the entry block that stores the stack guard 405*0b57cec5SDimitry Andric /// variable onto the stack: 406*0b57cec5SDimitry Andric /// 407*0b57cec5SDimitry Andric /// entry: 408*0b57cec5SDimitry Andric /// StackGuardSlot = alloca i8* 409*0b57cec5SDimitry Andric /// StackGuard = <stack guard> 410*0b57cec5SDimitry Andric /// call void @llvm.stackprotector(StackGuard, StackGuardSlot) 411*0b57cec5SDimitry Andric /// 412*0b57cec5SDimitry Andric /// Returns true if the platform/triple supports the stackprotectorcreate pseudo 413*0b57cec5SDimitry Andric /// node. 414*0b57cec5SDimitry Andric static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI, 415*0b57cec5SDimitry Andric const TargetLoweringBase *TLI, AllocaInst *&AI) { 416*0b57cec5SDimitry Andric bool SupportsSelectionDAGSP = false; 417*0b57cec5SDimitry Andric IRBuilder<> B(&F->getEntryBlock().front()); 418*0b57cec5SDimitry Andric PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext()); 419*0b57cec5SDimitry Andric AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot"); 420*0b57cec5SDimitry Andric 421*0b57cec5SDimitry Andric Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP); 422*0b57cec5SDimitry Andric B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), 423*0b57cec5SDimitry Andric {GuardSlot, AI}); 424*0b57cec5SDimitry Andric return SupportsSelectionDAGSP; 425*0b57cec5SDimitry Andric } 426*0b57cec5SDimitry Andric 427*0b57cec5SDimitry Andric /// InsertStackProtectors - Insert code into the prologue and epilogue of the 428*0b57cec5SDimitry Andric /// function. 429*0b57cec5SDimitry Andric /// 430*0b57cec5SDimitry Andric /// - The prologue code loads and stores the stack guard onto the stack. 431*0b57cec5SDimitry Andric /// - The epilogue checks the value stored in the prologue against the original 432*0b57cec5SDimitry Andric /// value. It calls __stack_chk_fail if they differ. 433*0b57cec5SDimitry Andric bool StackProtector::InsertStackProtectors() { 434*0b57cec5SDimitry Andric // If the target wants to XOR the frame pointer into the guard value, it's 435*0b57cec5SDimitry Andric // impossible to emit the check in IR, so the target *must* support stack 436*0b57cec5SDimitry Andric // protection in SDAG. 437*0b57cec5SDimitry Andric bool SupportsSelectionDAGSP = 438*0b57cec5SDimitry Andric TLI->useStackGuardXorFP() || 439*0b57cec5SDimitry Andric (EnableSelectionDAGSP && !TM->Options.EnableFastISel && 440*0b57cec5SDimitry Andric !TM->Options.EnableGlobalISel); 441*0b57cec5SDimitry Andric AllocaInst *AI = nullptr; // Place on stack that stores the stack guard. 442*0b57cec5SDimitry Andric 443*0b57cec5SDimitry Andric for (Function::iterator I = F->begin(), E = F->end(); I != E;) { 444*0b57cec5SDimitry Andric BasicBlock *BB = &*I++; 445*0b57cec5SDimitry Andric ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); 446*0b57cec5SDimitry Andric if (!RI) 447*0b57cec5SDimitry Andric continue; 448*0b57cec5SDimitry Andric 449*0b57cec5SDimitry Andric // Generate prologue instrumentation if not already generated. 450*0b57cec5SDimitry Andric if (!HasPrologue) { 451*0b57cec5SDimitry Andric HasPrologue = true; 452*0b57cec5SDimitry Andric SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI); 453*0b57cec5SDimitry Andric } 454*0b57cec5SDimitry Andric 455*0b57cec5SDimitry Andric // SelectionDAG based code generation. Nothing else needs to be done here. 456*0b57cec5SDimitry Andric // The epilogue instrumentation is postponed to SelectionDAG. 457*0b57cec5SDimitry Andric if (SupportsSelectionDAGSP) 458*0b57cec5SDimitry Andric break; 459*0b57cec5SDimitry Andric 460*0b57cec5SDimitry Andric // Find the stack guard slot if the prologue was not created by this pass 461*0b57cec5SDimitry Andric // itself via a previous call to CreatePrologue(). 462*0b57cec5SDimitry Andric if (!AI) { 463*0b57cec5SDimitry Andric const CallInst *SPCall = findStackProtectorIntrinsic(*F); 464*0b57cec5SDimitry Andric assert(SPCall && "Call to llvm.stackprotector is missing"); 465*0b57cec5SDimitry Andric AI = cast<AllocaInst>(SPCall->getArgOperand(1)); 466*0b57cec5SDimitry Andric } 467*0b57cec5SDimitry Andric 468*0b57cec5SDimitry Andric // Set HasIRCheck to true, so that SelectionDAG will not generate its own 469*0b57cec5SDimitry Andric // version. SelectionDAG called 'shouldEmitSDCheck' to check whether 470*0b57cec5SDimitry Andric // instrumentation has already been generated. 471*0b57cec5SDimitry Andric HasIRCheck = true; 472*0b57cec5SDimitry Andric 473*0b57cec5SDimitry Andric // Generate epilogue instrumentation. The epilogue intrumentation can be 474*0b57cec5SDimitry Andric // function-based or inlined depending on which mechanism the target is 475*0b57cec5SDimitry Andric // providing. 476*0b57cec5SDimitry Andric if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) { 477*0b57cec5SDimitry Andric // Generate the function-based epilogue instrumentation. 478*0b57cec5SDimitry Andric // The target provides a guard check function, generate a call to it. 479*0b57cec5SDimitry Andric IRBuilder<> B(RI); 480*0b57cec5SDimitry Andric LoadInst *Guard = B.CreateLoad(B.getInt8PtrTy(), AI, true, "Guard"); 481*0b57cec5SDimitry Andric CallInst *Call = B.CreateCall(GuardCheck, {Guard}); 482*0b57cec5SDimitry Andric Call->setAttributes(GuardCheck->getAttributes()); 483*0b57cec5SDimitry Andric Call->setCallingConv(GuardCheck->getCallingConv()); 484*0b57cec5SDimitry Andric } else { 485*0b57cec5SDimitry Andric // Generate the epilogue with inline instrumentation. 486*0b57cec5SDimitry Andric // If we do not support SelectionDAG based tail calls, generate IR level 487*0b57cec5SDimitry Andric // tail calls. 488*0b57cec5SDimitry Andric // 489*0b57cec5SDimitry Andric // For each block with a return instruction, convert this: 490*0b57cec5SDimitry Andric // 491*0b57cec5SDimitry Andric // return: 492*0b57cec5SDimitry Andric // ... 493*0b57cec5SDimitry Andric // ret ... 494*0b57cec5SDimitry Andric // 495*0b57cec5SDimitry Andric // into this: 496*0b57cec5SDimitry Andric // 497*0b57cec5SDimitry Andric // return: 498*0b57cec5SDimitry Andric // ... 499*0b57cec5SDimitry Andric // %1 = <stack guard> 500*0b57cec5SDimitry Andric // %2 = load StackGuardSlot 501*0b57cec5SDimitry Andric // %3 = cmp i1 %1, %2 502*0b57cec5SDimitry Andric // br i1 %3, label %SP_return, label %CallStackCheckFailBlk 503*0b57cec5SDimitry Andric // 504*0b57cec5SDimitry Andric // SP_return: 505*0b57cec5SDimitry Andric // ret ... 506*0b57cec5SDimitry Andric // 507*0b57cec5SDimitry Andric // CallStackCheckFailBlk: 508*0b57cec5SDimitry Andric // call void @__stack_chk_fail() 509*0b57cec5SDimitry Andric // unreachable 510*0b57cec5SDimitry Andric 511*0b57cec5SDimitry Andric // Create the FailBB. We duplicate the BB every time since the MI tail 512*0b57cec5SDimitry Andric // merge pass will merge together all of the various BB into one including 513*0b57cec5SDimitry Andric // fail BB generated by the stack protector pseudo instruction. 514*0b57cec5SDimitry Andric BasicBlock *FailBB = CreateFailBB(); 515*0b57cec5SDimitry Andric 516*0b57cec5SDimitry Andric // Split the basic block before the return instruction. 517*0b57cec5SDimitry Andric BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return"); 518*0b57cec5SDimitry Andric 519*0b57cec5SDimitry Andric // Update the dominator tree if we need to. 520*0b57cec5SDimitry Andric if (DT && DT->isReachableFromEntry(BB)) { 521*0b57cec5SDimitry Andric DT->addNewBlock(NewBB, BB); 522*0b57cec5SDimitry Andric DT->addNewBlock(FailBB, BB); 523*0b57cec5SDimitry Andric } 524*0b57cec5SDimitry Andric 525*0b57cec5SDimitry Andric // Remove default branch instruction to the new BB. 526*0b57cec5SDimitry Andric BB->getTerminator()->eraseFromParent(); 527*0b57cec5SDimitry Andric 528*0b57cec5SDimitry Andric // Move the newly created basic block to the point right after the old 529*0b57cec5SDimitry Andric // basic block so that it's in the "fall through" position. 530*0b57cec5SDimitry Andric NewBB->moveAfter(BB); 531*0b57cec5SDimitry Andric 532*0b57cec5SDimitry Andric // Generate the stack protector instructions in the old basic block. 533*0b57cec5SDimitry Andric IRBuilder<> B(BB); 534*0b57cec5SDimitry Andric Value *Guard = getStackGuard(TLI, M, B); 535*0b57cec5SDimitry Andric LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true); 536*0b57cec5SDimitry Andric Value *Cmp = B.CreateICmpEQ(Guard, LI2); 537*0b57cec5SDimitry Andric auto SuccessProb = 538*0b57cec5SDimitry Andric BranchProbabilityInfo::getBranchProbStackProtector(true); 539*0b57cec5SDimitry Andric auto FailureProb = 540*0b57cec5SDimitry Andric BranchProbabilityInfo::getBranchProbStackProtector(false); 541*0b57cec5SDimitry Andric MDNode *Weights = MDBuilder(F->getContext()) 542*0b57cec5SDimitry Andric .createBranchWeights(SuccessProb.getNumerator(), 543*0b57cec5SDimitry Andric FailureProb.getNumerator()); 544*0b57cec5SDimitry Andric B.CreateCondBr(Cmp, NewBB, FailBB, Weights); 545*0b57cec5SDimitry Andric } 546*0b57cec5SDimitry Andric } 547*0b57cec5SDimitry Andric 548*0b57cec5SDimitry Andric // Return if we didn't modify any basic blocks. i.e., there are no return 549*0b57cec5SDimitry Andric // statements in the function. 550*0b57cec5SDimitry Andric return HasPrologue; 551*0b57cec5SDimitry Andric } 552*0b57cec5SDimitry Andric 553*0b57cec5SDimitry Andric /// CreateFailBB - Create a basic block to jump to when the stack protector 554*0b57cec5SDimitry Andric /// check fails. 555*0b57cec5SDimitry Andric BasicBlock *StackProtector::CreateFailBB() { 556*0b57cec5SDimitry Andric LLVMContext &Context = F->getContext(); 557*0b57cec5SDimitry Andric BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F); 558*0b57cec5SDimitry Andric IRBuilder<> B(FailBB); 559*0b57cec5SDimitry Andric B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram())); 560*0b57cec5SDimitry Andric if (Trip.isOSOpenBSD()) { 561*0b57cec5SDimitry Andric FunctionCallee StackChkFail = M->getOrInsertFunction( 562*0b57cec5SDimitry Andric "__stack_smash_handler", Type::getVoidTy(Context), 563*0b57cec5SDimitry Andric Type::getInt8PtrTy(Context)); 564*0b57cec5SDimitry Andric 565*0b57cec5SDimitry Andric B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH")); 566*0b57cec5SDimitry Andric } else { 567*0b57cec5SDimitry Andric FunctionCallee StackChkFail = 568*0b57cec5SDimitry Andric M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context)); 569*0b57cec5SDimitry Andric 570*0b57cec5SDimitry Andric B.CreateCall(StackChkFail, {}); 571*0b57cec5SDimitry Andric } 572*0b57cec5SDimitry Andric B.CreateUnreachable(); 573*0b57cec5SDimitry Andric return FailBB; 574*0b57cec5SDimitry Andric } 575*0b57cec5SDimitry Andric 576*0b57cec5SDimitry Andric bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const { 577*0b57cec5SDimitry Andric return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator()); 578*0b57cec5SDimitry Andric } 579*0b57cec5SDimitry Andric 580*0b57cec5SDimitry Andric void StackProtector::copyToMachineFrameInfo(MachineFrameInfo &MFI) const { 581*0b57cec5SDimitry Andric if (Layout.empty()) 582*0b57cec5SDimitry Andric return; 583*0b57cec5SDimitry Andric 584*0b57cec5SDimitry Andric for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) { 585*0b57cec5SDimitry Andric if (MFI.isDeadObjectIndex(I)) 586*0b57cec5SDimitry Andric continue; 587*0b57cec5SDimitry Andric 588*0b57cec5SDimitry Andric const AllocaInst *AI = MFI.getObjectAllocation(I); 589*0b57cec5SDimitry Andric if (!AI) 590*0b57cec5SDimitry Andric continue; 591*0b57cec5SDimitry Andric 592*0b57cec5SDimitry Andric SSPLayoutMap::const_iterator LI = Layout.find(AI); 593*0b57cec5SDimitry Andric if (LI == Layout.end()) 594*0b57cec5SDimitry Andric continue; 595*0b57cec5SDimitry Andric 596*0b57cec5SDimitry Andric MFI.setObjectSSPLayout(I, LI->second); 597*0b57cec5SDimitry Andric } 598*0b57cec5SDimitry Andric } 599