109467b48Spatrick //===- StackProtector.cpp - Stack Protector Insertion ---------------------===// 209467b48Spatrick // 309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information. 509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 609467b48Spatrick // 709467b48Spatrick //===----------------------------------------------------------------------===// 809467b48Spatrick // 909467b48Spatrick // This pass inserts stack protectors into functions which need them. A variable 1009467b48Spatrick // with a random value in it is stored onto the stack before the local variables 1109467b48Spatrick // are allocated. Upon exiting the block, the stored value is checked. If it's 1209467b48Spatrick // changed, then there was some sort of violation and the program aborts. 1309467b48Spatrick // 1409467b48Spatrick //===----------------------------------------------------------------------===// 1509467b48Spatrick 1609467b48Spatrick #include "llvm/CodeGen/StackProtector.h" 1709467b48Spatrick #include "llvm/ADT/SmallPtrSet.h" 1809467b48Spatrick #include "llvm/ADT/Statistic.h" 1909467b48Spatrick #include "llvm/Analysis/BranchProbabilityInfo.h" 2009467b48Spatrick #include "llvm/Analysis/EHPersonalities.h" 21097a140dSpatrick #include "llvm/Analysis/MemoryLocation.h" 2209467b48Spatrick #include "llvm/Analysis/OptimizationRemarkEmitter.h" 2309467b48Spatrick #include "llvm/CodeGen/Passes.h" 2409467b48Spatrick #include "llvm/CodeGen/TargetLowering.h" 2509467b48Spatrick #include "llvm/CodeGen/TargetPassConfig.h" 2609467b48Spatrick #include "llvm/CodeGen/TargetSubtargetInfo.h" 2709467b48Spatrick #include "llvm/IR/Attributes.h" 2809467b48Spatrick #include "llvm/IR/BasicBlock.h" 2909467b48Spatrick #include "llvm/IR/Constants.h" 3009467b48Spatrick #include "llvm/IR/DataLayout.h" 3109467b48Spatrick #include "llvm/IR/DebugInfo.h" 3209467b48Spatrick #include "llvm/IR/DebugLoc.h" 3309467b48Spatrick #include "llvm/IR/DerivedTypes.h" 3409467b48Spatrick #include "llvm/IR/Dominators.h" 3509467b48Spatrick #include "llvm/IR/Function.h" 3609467b48Spatrick #include "llvm/IR/IRBuilder.h" 3709467b48Spatrick #include "llvm/IR/Instruction.h" 3809467b48Spatrick #include "llvm/IR/Instructions.h" 3909467b48Spatrick #include "llvm/IR/IntrinsicInst.h" 4009467b48Spatrick #include "llvm/IR/Intrinsics.h" 4109467b48Spatrick #include "llvm/IR/MDBuilder.h" 4209467b48Spatrick #include "llvm/IR/Module.h" 4309467b48Spatrick #include "llvm/IR/Type.h" 4409467b48Spatrick #include "llvm/IR/User.h" 4509467b48Spatrick #include "llvm/InitializePasses.h" 4609467b48Spatrick #include "llvm/Pass.h" 4709467b48Spatrick #include "llvm/Support/Casting.h" 4809467b48Spatrick #include "llvm/Support/CommandLine.h" 4909467b48Spatrick #include "llvm/Target/TargetMachine.h" 5009467b48Spatrick #include "llvm/Target/TargetOptions.h" 5109467b48Spatrick #include <utility> 5209467b48Spatrick 5309467b48Spatrick using namespace llvm; 5409467b48Spatrick 5509467b48Spatrick #define DEBUG_TYPE "stack-protector" 5609467b48Spatrick 5709467b48Spatrick STATISTIC(NumFunProtected, "Number of functions protected"); 5809467b48Spatrick STATISTIC(NumAddrTaken, "Number of local variables that have their address" 5909467b48Spatrick " taken."); 6009467b48Spatrick 6109467b48Spatrick static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp", 6209467b48Spatrick cl::init(true), cl::Hidden); 6309467b48Spatrick 6409467b48Spatrick char StackProtector::ID = 0; 6509467b48Spatrick 6609467b48Spatrick StackProtector::StackProtector() : FunctionPass(ID), SSPBufferSize(8) { 6709467b48Spatrick initializeStackProtectorPass(*PassRegistry::getPassRegistry()); 6809467b48Spatrick } 6909467b48Spatrick 7009467b48Spatrick INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE, 7109467b48Spatrick "Insert stack protectors", false, true) 7209467b48Spatrick INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 73*73471bf0Spatrick INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 7409467b48Spatrick INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE, 7509467b48Spatrick "Insert stack protectors", false, true) 7609467b48Spatrick 7709467b48Spatrick FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); } 7809467b48Spatrick 7909467b48Spatrick void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const { 8009467b48Spatrick AU.addRequired<TargetPassConfig>(); 8109467b48Spatrick AU.addPreserved<DominatorTreeWrapperPass>(); 8209467b48Spatrick } 8309467b48Spatrick 8409467b48Spatrick bool StackProtector::runOnFunction(Function &Fn) { 8509467b48Spatrick F = &Fn; 8609467b48Spatrick M = F->getParent(); 8709467b48Spatrick DominatorTreeWrapperPass *DTWP = 8809467b48Spatrick getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 8909467b48Spatrick DT = DTWP ? &DTWP->getDomTree() : nullptr; 9009467b48Spatrick TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>(); 9109467b48Spatrick Trip = TM->getTargetTriple(); 9209467b48Spatrick TLI = TM->getSubtargetImpl(Fn)->getTargetLowering(); 9309467b48Spatrick HasPrologue = false; 9409467b48Spatrick HasIRCheck = false; 9509467b48Spatrick 9609467b48Spatrick Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size"); 9709467b48Spatrick if (Attr.isStringAttribute() && 9809467b48Spatrick Attr.getValueAsString().getAsInteger(10, SSPBufferSize)) 9909467b48Spatrick return false; // Invalid integer string 10009467b48Spatrick 10109467b48Spatrick if (!RequiresStackProtector()) 10209467b48Spatrick return false; 10309467b48Spatrick 10409467b48Spatrick // TODO(etienneb): Functions with funclets are not correctly supported now. 10509467b48Spatrick // Do nothing if this is funclet-based personality. 10609467b48Spatrick if (Fn.hasPersonalityFn()) { 10709467b48Spatrick EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn()); 10809467b48Spatrick if (isFuncletEHPersonality(Personality)) 10909467b48Spatrick return false; 11009467b48Spatrick } 11109467b48Spatrick 11209467b48Spatrick ++NumFunProtected; 11309467b48Spatrick return InsertStackProtectors(); 11409467b48Spatrick } 11509467b48Spatrick 11609467b48Spatrick /// \param [out] IsLarge is set to true if a protectable array is found and 11709467b48Spatrick /// it is "large" ( >= ssp-buffer-size). In the case of a structure with 11809467b48Spatrick /// multiple arrays, this gets set if any of them is large. 11909467b48Spatrick bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge, 12009467b48Spatrick bool Strong, 12109467b48Spatrick bool InStruct) const { 12209467b48Spatrick if (!Ty) 12309467b48Spatrick return false; 12409467b48Spatrick if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 12509467b48Spatrick if (!AT->getElementType()->isIntegerTy(8)) { 12609467b48Spatrick // If we're on a non-Darwin platform or we're inside of a structure, don't 12709467b48Spatrick // add stack protectors unless the array is a character array. 12809467b48Spatrick // However, in strong mode any array, regardless of type and size, 12909467b48Spatrick // triggers a protector. 13009467b48Spatrick if (!Strong && (InStruct || !Trip.isOSDarwin())) 13109467b48Spatrick return false; 13209467b48Spatrick } 13309467b48Spatrick 13409467b48Spatrick // If an array has more than SSPBufferSize bytes of allocated space, then we 13509467b48Spatrick // emit stack protectors. 13609467b48Spatrick if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) { 13709467b48Spatrick IsLarge = true; 13809467b48Spatrick return true; 13909467b48Spatrick } 14009467b48Spatrick 14109467b48Spatrick if (Strong) 14209467b48Spatrick // Require a protector for all arrays in strong mode 14309467b48Spatrick return true; 14409467b48Spatrick } 14509467b48Spatrick 14609467b48Spatrick const StructType *ST = dyn_cast<StructType>(Ty); 14709467b48Spatrick if (!ST) 14809467b48Spatrick return false; 14909467b48Spatrick 15009467b48Spatrick bool NeedsProtector = false; 15109467b48Spatrick for (StructType::element_iterator I = ST->element_begin(), 15209467b48Spatrick E = ST->element_end(); 15309467b48Spatrick I != E; ++I) 15409467b48Spatrick if (ContainsProtectableArray(*I, IsLarge, Strong, true)) { 15509467b48Spatrick // If the element is a protectable array and is large (>= SSPBufferSize) 15609467b48Spatrick // then we are done. If the protectable array is not large, then 15709467b48Spatrick // keep looking in case a subsequent element is a large array. 15809467b48Spatrick if (IsLarge) 15909467b48Spatrick return true; 16009467b48Spatrick NeedsProtector = true; 16109467b48Spatrick } 16209467b48Spatrick 16309467b48Spatrick return NeedsProtector; 16409467b48Spatrick } 16509467b48Spatrick 166097a140dSpatrick bool StackProtector::HasAddressTaken(const Instruction *AI, 167097a140dSpatrick uint64_t AllocSize) { 168097a140dSpatrick const DataLayout &DL = M->getDataLayout(); 16909467b48Spatrick for (const User *U : AI->users()) { 17009467b48Spatrick const auto *I = cast<Instruction>(U); 171097a140dSpatrick // If this instruction accesses memory make sure it doesn't access beyond 172097a140dSpatrick // the bounds of the allocated object. 173097a140dSpatrick Optional<MemoryLocation> MemLoc = MemoryLocation::getOrNone(I); 174*73471bf0Spatrick if (MemLoc.hasValue() && MemLoc->Size.hasValue() && 175*73471bf0Spatrick MemLoc->Size.getValue() > AllocSize) 176097a140dSpatrick return true; 17709467b48Spatrick switch (I->getOpcode()) { 17809467b48Spatrick case Instruction::Store: 17909467b48Spatrick if (AI == cast<StoreInst>(I)->getValueOperand()) 18009467b48Spatrick return true; 18109467b48Spatrick break; 18209467b48Spatrick case Instruction::AtomicCmpXchg: 18309467b48Spatrick // cmpxchg conceptually includes both a load and store from the same 18409467b48Spatrick // location. So, like store, the value being stored is what matters. 18509467b48Spatrick if (AI == cast<AtomicCmpXchgInst>(I)->getNewValOperand()) 18609467b48Spatrick return true; 18709467b48Spatrick break; 18809467b48Spatrick case Instruction::PtrToInt: 18909467b48Spatrick if (AI == cast<PtrToIntInst>(I)->getOperand(0)) 19009467b48Spatrick return true; 19109467b48Spatrick break; 19209467b48Spatrick case Instruction::Call: { 19309467b48Spatrick // Ignore intrinsics that do not become real instructions. 19409467b48Spatrick // TODO: Narrow this to intrinsics that have store-like effects. 19509467b48Spatrick const auto *CI = cast<CallInst>(I); 196*73471bf0Spatrick if (!CI->isDebugOrPseudoInst() && !CI->isLifetimeStartOrEnd()) 19709467b48Spatrick return true; 19809467b48Spatrick break; 19909467b48Spatrick } 20009467b48Spatrick case Instruction::Invoke: 20109467b48Spatrick return true; 202097a140dSpatrick case Instruction::GetElementPtr: { 203097a140dSpatrick // If the GEP offset is out-of-bounds, or is non-constant and so has to be 204097a140dSpatrick // assumed to be potentially out-of-bounds, then any memory access that 205097a140dSpatrick // would use it could also be out-of-bounds meaning stack protection is 206097a140dSpatrick // required. 207097a140dSpatrick const GetElementPtrInst *GEP = cast<GetElementPtrInst>(I); 208097a140dSpatrick unsigned TypeSize = DL.getIndexTypeSizeInBits(I->getType()); 209097a140dSpatrick APInt Offset(TypeSize, 0); 210097a140dSpatrick APInt MaxOffset(TypeSize, AllocSize); 211097a140dSpatrick if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.ugt(MaxOffset)) 212097a140dSpatrick return true; 213097a140dSpatrick // Adjust AllocSize to be the space remaining after this offset. 214097a140dSpatrick if (HasAddressTaken(I, AllocSize - Offset.getLimitedValue())) 215097a140dSpatrick return true; 216097a140dSpatrick break; 217097a140dSpatrick } 21809467b48Spatrick case Instruction::BitCast: 21909467b48Spatrick case Instruction::Select: 22009467b48Spatrick case Instruction::AddrSpaceCast: 221097a140dSpatrick if (HasAddressTaken(I, AllocSize)) 22209467b48Spatrick return true; 22309467b48Spatrick break; 22409467b48Spatrick case Instruction::PHI: { 22509467b48Spatrick // Keep track of what PHI nodes we have already visited to ensure 22609467b48Spatrick // they are only visited once. 22709467b48Spatrick const auto *PN = cast<PHINode>(I); 22809467b48Spatrick if (VisitedPHIs.insert(PN).second) 229097a140dSpatrick if (HasAddressTaken(PN, AllocSize)) 23009467b48Spatrick return true; 23109467b48Spatrick break; 23209467b48Spatrick } 23309467b48Spatrick case Instruction::Load: 23409467b48Spatrick case Instruction::AtomicRMW: 23509467b48Spatrick case Instruction::Ret: 23609467b48Spatrick // These instructions take an address operand, but have load-like or 23709467b48Spatrick // other innocuous behavior that should not trigger a stack protector. 23809467b48Spatrick // atomicrmw conceptually has both load and store semantics, but the 23909467b48Spatrick // value being stored must be integer; so if a pointer is being stored, 24009467b48Spatrick // we'll catch it in the PtrToInt case above. 24109467b48Spatrick break; 24209467b48Spatrick default: 24309467b48Spatrick // Conservatively return true for any instruction that takes an address 24409467b48Spatrick // operand, but is not handled above. 24509467b48Spatrick return true; 24609467b48Spatrick } 24709467b48Spatrick } 24809467b48Spatrick return false; 24909467b48Spatrick } 25009467b48Spatrick 25109467b48Spatrick /// Search for the first call to the llvm.stackprotector intrinsic and return it 25209467b48Spatrick /// if present. 25309467b48Spatrick static const CallInst *findStackProtectorIntrinsic(Function &F) { 25409467b48Spatrick for (const BasicBlock &BB : F) 25509467b48Spatrick for (const Instruction &I : BB) 256*73471bf0Spatrick if (const auto *II = dyn_cast<IntrinsicInst>(&I)) 257*73471bf0Spatrick if (II->getIntrinsicID() == Intrinsic::stackprotector) 258*73471bf0Spatrick return II; 25909467b48Spatrick return nullptr; 26009467b48Spatrick } 26109467b48Spatrick 26209467b48Spatrick /// Check whether or not this function needs a stack protector based 26309467b48Spatrick /// upon the stack protector level. 26409467b48Spatrick /// 26509467b48Spatrick /// We use two heuristics: a standard (ssp) and strong (sspstrong). 26609467b48Spatrick /// The standard heuristic which will add a guard variable to functions that 26709467b48Spatrick /// call alloca with a either a variable size or a size >= SSPBufferSize, 26809467b48Spatrick /// functions with character buffers larger than SSPBufferSize, and functions 26909467b48Spatrick /// with aggregates containing character buffers larger than SSPBufferSize. The 27009467b48Spatrick /// strong heuristic will add a guard variables to functions that call alloca 27109467b48Spatrick /// regardless of size, functions with any buffer regardless of type and size, 27209467b48Spatrick /// functions with aggregates that contain any buffer regardless of type and 27309467b48Spatrick /// size, and functions that contain stack-based variables that have had their 27409467b48Spatrick /// address taken. 27509467b48Spatrick bool StackProtector::RequiresStackProtector() { 27609467b48Spatrick bool Strong = false; 27709467b48Spatrick bool NeedsProtector = false; 27809467b48Spatrick 27909467b48Spatrick if (F->hasFnAttribute(Attribute::SafeStack)) 28009467b48Spatrick return false; 28109467b48Spatrick 28209467b48Spatrick // We are constructing the OptimizationRemarkEmitter on the fly rather than 28309467b48Spatrick // using the analysis pass to avoid building DominatorTree and LoopInfo which 28409467b48Spatrick // are not available this late in the IR pipeline. 28509467b48Spatrick OptimizationRemarkEmitter ORE(F); 28609467b48Spatrick 28709467b48Spatrick if (F->hasFnAttribute(Attribute::StackProtectReq)) { 28809467b48Spatrick ORE.emit([&]() { 28909467b48Spatrick return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F) 29009467b48Spatrick << "Stack protection applied to function " 29109467b48Spatrick << ore::NV("Function", F) 29209467b48Spatrick << " due to a function attribute or command-line switch"; 29309467b48Spatrick }); 29409467b48Spatrick NeedsProtector = true; 29509467b48Spatrick Strong = true; // Use the same heuristic as strong to determine SSPLayout 29609467b48Spatrick } else if (F->hasFnAttribute(Attribute::StackProtectStrong)) 29709467b48Spatrick Strong = true; 29809467b48Spatrick else if (!F->hasFnAttribute(Attribute::StackProtect)) 29909467b48Spatrick return false; 30009467b48Spatrick 30109467b48Spatrick for (const BasicBlock &BB : *F) { 30209467b48Spatrick for (const Instruction &I : BB) { 30309467b48Spatrick if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 30409467b48Spatrick if (AI->isArrayAllocation()) { 30509467b48Spatrick auto RemarkBuilder = [&]() { 30609467b48Spatrick return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray", 30709467b48Spatrick &I) 30809467b48Spatrick << "Stack protection applied to function " 30909467b48Spatrick << ore::NV("Function", F) 31009467b48Spatrick << " due to a call to alloca or use of a variable length " 31109467b48Spatrick "array"; 31209467b48Spatrick }; 31309467b48Spatrick if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) { 31409467b48Spatrick if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) { 31509467b48Spatrick // A call to alloca with size >= SSPBufferSize requires 31609467b48Spatrick // stack protectors. 31709467b48Spatrick Layout.insert(std::make_pair(AI, 31809467b48Spatrick MachineFrameInfo::SSPLK_LargeArray)); 31909467b48Spatrick ORE.emit(RemarkBuilder); 32009467b48Spatrick NeedsProtector = true; 32109467b48Spatrick } else if (Strong) { 32209467b48Spatrick // Require protectors for all alloca calls in strong mode. 32309467b48Spatrick Layout.insert(std::make_pair(AI, 32409467b48Spatrick MachineFrameInfo::SSPLK_SmallArray)); 32509467b48Spatrick ORE.emit(RemarkBuilder); 32609467b48Spatrick NeedsProtector = true; 32709467b48Spatrick } 32809467b48Spatrick } else { 32909467b48Spatrick // A call to alloca with a variable size requires protectors. 33009467b48Spatrick Layout.insert(std::make_pair(AI, 33109467b48Spatrick MachineFrameInfo::SSPLK_LargeArray)); 33209467b48Spatrick ORE.emit(RemarkBuilder); 33309467b48Spatrick NeedsProtector = true; 33409467b48Spatrick } 33509467b48Spatrick continue; 33609467b48Spatrick } 33709467b48Spatrick 33809467b48Spatrick bool IsLarge = false; 33909467b48Spatrick if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) { 34009467b48Spatrick Layout.insert(std::make_pair(AI, IsLarge 34109467b48Spatrick ? MachineFrameInfo::SSPLK_LargeArray 34209467b48Spatrick : MachineFrameInfo::SSPLK_SmallArray)); 34309467b48Spatrick ORE.emit([&]() { 34409467b48Spatrick return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I) 34509467b48Spatrick << "Stack protection applied to function " 34609467b48Spatrick << ore::NV("Function", F) 34709467b48Spatrick << " due to a stack allocated buffer or struct containing a " 34809467b48Spatrick "buffer"; 34909467b48Spatrick }); 35009467b48Spatrick NeedsProtector = true; 35109467b48Spatrick continue; 35209467b48Spatrick } 35309467b48Spatrick 354097a140dSpatrick if (Strong && HasAddressTaken(AI, M->getDataLayout().getTypeAllocSize( 355097a140dSpatrick AI->getAllocatedType()))) { 35609467b48Spatrick ++NumAddrTaken; 35709467b48Spatrick Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf)); 35809467b48Spatrick ORE.emit([&]() { 35909467b48Spatrick return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken", 36009467b48Spatrick &I) 36109467b48Spatrick << "Stack protection applied to function " 36209467b48Spatrick << ore::NV("Function", F) 36309467b48Spatrick << " due to the address of a local variable being taken"; 36409467b48Spatrick }); 36509467b48Spatrick NeedsProtector = true; 36609467b48Spatrick } 367097a140dSpatrick // Clear any PHIs that we visited, to make sure we examine all uses of 368097a140dSpatrick // any subsequent allocas that we look at. 369097a140dSpatrick VisitedPHIs.clear(); 37009467b48Spatrick } 37109467b48Spatrick } 37209467b48Spatrick } 37309467b48Spatrick 37409467b48Spatrick return NeedsProtector; 37509467b48Spatrick } 37609467b48Spatrick 37709467b48Spatrick /// Create a stack guard loading and populate whether SelectionDAG SSP is 37809467b48Spatrick /// supported. 37909467b48Spatrick static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M, 38009467b48Spatrick IRBuilder<> &B, 38109467b48Spatrick bool *SupportsSelectionDAGSP = nullptr) { 382*73471bf0Spatrick Value *Guard = TLI->getIRStackGuard(B); 383*73471bf0Spatrick StringRef GuardMode = M->getStackProtectorGuard(); 384*73471bf0Spatrick if ((GuardMode == "tls" || GuardMode.empty()) && Guard) 38509467b48Spatrick return B.CreateLoad(B.getInt8PtrTy(), Guard, true, "StackGuard"); 38609467b48Spatrick 38709467b48Spatrick // Use SelectionDAG SSP handling, since there isn't an IR guard. 38809467b48Spatrick // 38909467b48Spatrick // This is more or less weird, since we optionally output whether we 39009467b48Spatrick // should perform a SelectionDAG SP here. The reason is that it's strictly 39109467b48Spatrick // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also 39209467b48Spatrick // mutating. There is no way to get this bit without mutating the IR, so 39309467b48Spatrick // getting this bit has to happen in this right time. 39409467b48Spatrick // 39509467b48Spatrick // We could have define a new function TLI::supportsSelectionDAGSP(), but that 39609467b48Spatrick // will put more burden on the backends' overriding work, especially when it 39709467b48Spatrick // actually conveys the same information getIRStackGuard() already gives. 39809467b48Spatrick if (SupportsSelectionDAGSP) 39909467b48Spatrick *SupportsSelectionDAGSP = true; 40009467b48Spatrick TLI->insertSSPDeclarations(*M); 40109467b48Spatrick return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard)); 40209467b48Spatrick } 40309467b48Spatrick 40409467b48Spatrick /// Insert code into the entry block that stores the stack guard 40509467b48Spatrick /// variable onto the stack: 40609467b48Spatrick /// 40709467b48Spatrick /// entry: 40809467b48Spatrick /// StackGuardSlot = alloca i8* 40909467b48Spatrick /// StackGuard = <stack guard> 41009467b48Spatrick /// call void @llvm.stackprotector(StackGuard, StackGuardSlot) 41109467b48Spatrick /// 41209467b48Spatrick /// Returns true if the platform/triple supports the stackprotectorcreate pseudo 41309467b48Spatrick /// node. 41409467b48Spatrick static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI, 41509467b48Spatrick const TargetLoweringBase *TLI, AllocaInst *&AI) { 41609467b48Spatrick bool SupportsSelectionDAGSP = false; 41709467b48Spatrick IRBuilder<> B(&F->getEntryBlock().front()); 41809467b48Spatrick PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext()); 41909467b48Spatrick AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot"); 42009467b48Spatrick 42109467b48Spatrick Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP); 42209467b48Spatrick B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), 42309467b48Spatrick {GuardSlot, AI}); 42409467b48Spatrick return SupportsSelectionDAGSP; 42509467b48Spatrick } 42609467b48Spatrick 42709467b48Spatrick /// InsertStackProtectors - Insert code into the prologue and epilogue of the 42809467b48Spatrick /// function. 42909467b48Spatrick /// 43009467b48Spatrick /// - The prologue code loads and stores the stack guard onto the stack. 43109467b48Spatrick /// - The epilogue checks the value stored in the prologue against the original 43209467b48Spatrick /// value. It calls __stack_chk_fail if they differ. 43309467b48Spatrick bool StackProtector::InsertStackProtectors() { 43409467b48Spatrick // If the target wants to XOR the frame pointer into the guard value, it's 43509467b48Spatrick // impossible to emit the check in IR, so the target *must* support stack 43609467b48Spatrick // protection in SDAG. 43709467b48Spatrick bool SupportsSelectionDAGSP = 43809467b48Spatrick TLI->useStackGuardXorFP() || 43909467b48Spatrick (EnableSelectionDAGSP && !TM->Options.EnableFastISel && 44009467b48Spatrick !TM->Options.EnableGlobalISel); 44109467b48Spatrick AllocaInst *AI = nullptr; // Place on stack that stores the stack guard. 44209467b48Spatrick 44309467b48Spatrick for (Function::iterator I = F->begin(), E = F->end(); I != E;) { 44409467b48Spatrick BasicBlock *BB = &*I++; 44509467b48Spatrick ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); 44609467b48Spatrick if (!RI) 44709467b48Spatrick continue; 44809467b48Spatrick 44909467b48Spatrick // Generate prologue instrumentation if not already generated. 45009467b48Spatrick if (!HasPrologue) { 45109467b48Spatrick HasPrologue = true; 45209467b48Spatrick SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI); 45309467b48Spatrick } 45409467b48Spatrick 45509467b48Spatrick // SelectionDAG based code generation. Nothing else needs to be done here. 45609467b48Spatrick // The epilogue instrumentation is postponed to SelectionDAG. 45709467b48Spatrick if (SupportsSelectionDAGSP) 45809467b48Spatrick break; 45909467b48Spatrick 46009467b48Spatrick // Find the stack guard slot if the prologue was not created by this pass 46109467b48Spatrick // itself via a previous call to CreatePrologue(). 46209467b48Spatrick if (!AI) { 46309467b48Spatrick const CallInst *SPCall = findStackProtectorIntrinsic(*F); 46409467b48Spatrick assert(SPCall && "Call to llvm.stackprotector is missing"); 46509467b48Spatrick AI = cast<AllocaInst>(SPCall->getArgOperand(1)); 46609467b48Spatrick } 46709467b48Spatrick 46809467b48Spatrick // Set HasIRCheck to true, so that SelectionDAG will not generate its own 46909467b48Spatrick // version. SelectionDAG called 'shouldEmitSDCheck' to check whether 47009467b48Spatrick // instrumentation has already been generated. 47109467b48Spatrick HasIRCheck = true; 47209467b48Spatrick 473*73471bf0Spatrick // If we're instrumenting a block with a musttail call, the check has to be 474*73471bf0Spatrick // inserted before the call rather than between it and the return. The 475*73471bf0Spatrick // verifier guarantees that a musttail call is either directly before the 476*73471bf0Spatrick // return or with a single correct bitcast of the return value in between so 477*73471bf0Spatrick // we don't need to worry about many situations here. 478*73471bf0Spatrick Instruction *CheckLoc = RI; 479*73471bf0Spatrick Instruction *Prev = RI->getPrevNonDebugInstruction(); 480*73471bf0Spatrick if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isMustTailCall()) 481*73471bf0Spatrick CheckLoc = Prev; 482*73471bf0Spatrick else if (Prev) { 483*73471bf0Spatrick Prev = Prev->getPrevNonDebugInstruction(); 484*73471bf0Spatrick if (Prev && isa<CallInst>(Prev) && cast<CallInst>(Prev)->isMustTailCall()) 485*73471bf0Spatrick CheckLoc = Prev; 486*73471bf0Spatrick } 487*73471bf0Spatrick 48809467b48Spatrick // Generate epilogue instrumentation. The epilogue intrumentation can be 48909467b48Spatrick // function-based or inlined depending on which mechanism the target is 49009467b48Spatrick // providing. 49109467b48Spatrick if (Function *GuardCheck = TLI->getSSPStackGuardCheck(*M)) { 49209467b48Spatrick // Generate the function-based epilogue instrumentation. 49309467b48Spatrick // The target provides a guard check function, generate a call to it. 494*73471bf0Spatrick IRBuilder<> B(CheckLoc); 49509467b48Spatrick LoadInst *Guard = B.CreateLoad(B.getInt8PtrTy(), AI, true, "Guard"); 49609467b48Spatrick CallInst *Call = B.CreateCall(GuardCheck, {Guard}); 49709467b48Spatrick Call->setAttributes(GuardCheck->getAttributes()); 49809467b48Spatrick Call->setCallingConv(GuardCheck->getCallingConv()); 49909467b48Spatrick } else { 50009467b48Spatrick // Generate the epilogue with inline instrumentation. 501*73471bf0Spatrick // If we do not support SelectionDAG based calls, generate IR level 502*73471bf0Spatrick // calls. 50309467b48Spatrick // 50409467b48Spatrick // For each block with a return instruction, convert this: 50509467b48Spatrick // 50609467b48Spatrick // return: 50709467b48Spatrick // ... 50809467b48Spatrick // ret ... 50909467b48Spatrick // 51009467b48Spatrick // into this: 51109467b48Spatrick // 51209467b48Spatrick // return: 51309467b48Spatrick // ... 51409467b48Spatrick // %1 = <stack guard> 51509467b48Spatrick // %2 = load StackGuardSlot 51609467b48Spatrick // %3 = cmp i1 %1, %2 51709467b48Spatrick // br i1 %3, label %SP_return, label %CallStackCheckFailBlk 51809467b48Spatrick // 51909467b48Spatrick // SP_return: 52009467b48Spatrick // ret ... 52109467b48Spatrick // 52209467b48Spatrick // CallStackCheckFailBlk: 52309467b48Spatrick // call void @__stack_chk_fail() 52409467b48Spatrick // unreachable 52509467b48Spatrick 52609467b48Spatrick // Create the FailBB. We duplicate the BB every time since the MI tail 52709467b48Spatrick // merge pass will merge together all of the various BB into one including 52809467b48Spatrick // fail BB generated by the stack protector pseudo instruction. 52909467b48Spatrick BasicBlock *FailBB = CreateFailBB(); 53009467b48Spatrick 53109467b48Spatrick // Split the basic block before the return instruction. 532*73471bf0Spatrick BasicBlock *NewBB = 533*73471bf0Spatrick BB->splitBasicBlock(CheckLoc->getIterator(), "SP_return"); 53409467b48Spatrick 53509467b48Spatrick // Update the dominator tree if we need to. 53609467b48Spatrick if (DT && DT->isReachableFromEntry(BB)) { 53709467b48Spatrick DT->addNewBlock(NewBB, BB); 53809467b48Spatrick DT->addNewBlock(FailBB, BB); 53909467b48Spatrick } 54009467b48Spatrick 54109467b48Spatrick // Remove default branch instruction to the new BB. 54209467b48Spatrick BB->getTerminator()->eraseFromParent(); 54309467b48Spatrick 54409467b48Spatrick // Move the newly created basic block to the point right after the old 54509467b48Spatrick // basic block so that it's in the "fall through" position. 54609467b48Spatrick NewBB->moveAfter(BB); 54709467b48Spatrick 54809467b48Spatrick // Generate the stack protector instructions in the old basic block. 54909467b48Spatrick IRBuilder<> B(BB); 55009467b48Spatrick Value *Guard = getStackGuard(TLI, M, B); 55109467b48Spatrick LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true); 55209467b48Spatrick Value *Cmp = B.CreateICmpEQ(Guard, LI2); 55309467b48Spatrick auto SuccessProb = 55409467b48Spatrick BranchProbabilityInfo::getBranchProbStackProtector(true); 55509467b48Spatrick auto FailureProb = 55609467b48Spatrick BranchProbabilityInfo::getBranchProbStackProtector(false); 55709467b48Spatrick MDNode *Weights = MDBuilder(F->getContext()) 55809467b48Spatrick .createBranchWeights(SuccessProb.getNumerator(), 55909467b48Spatrick FailureProb.getNumerator()); 56009467b48Spatrick B.CreateCondBr(Cmp, NewBB, FailBB, Weights); 56109467b48Spatrick } 56209467b48Spatrick } 56309467b48Spatrick 56409467b48Spatrick // Return if we didn't modify any basic blocks. i.e., there are no return 56509467b48Spatrick // statements in the function. 56609467b48Spatrick return HasPrologue; 56709467b48Spatrick } 56809467b48Spatrick 56909467b48Spatrick /// CreateFailBB - Create a basic block to jump to when the stack protector 57009467b48Spatrick /// check fails. 57109467b48Spatrick BasicBlock *StackProtector::CreateFailBB() { 57209467b48Spatrick LLVMContext &Context = F->getContext(); 57309467b48Spatrick BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F); 57409467b48Spatrick IRBuilder<> B(FailBB); 575*73471bf0Spatrick if (F->getSubprogram()) 576*73471bf0Spatrick B.SetCurrentDebugLocation( 577*73471bf0Spatrick DILocation::get(Context, 0, 0, F->getSubprogram())); 57809467b48Spatrick if (Trip.isOSOpenBSD()) { 57909467b48Spatrick FunctionCallee StackChkFail = M->getOrInsertFunction( 58009467b48Spatrick "__stack_smash_handler", Type::getVoidTy(Context), 58109467b48Spatrick Type::getInt8PtrTy(Context)); 58209467b48Spatrick 58309467b48Spatrick B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH")); 58409467b48Spatrick } else { 58509467b48Spatrick FunctionCallee StackChkFail = 58609467b48Spatrick M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context)); 58709467b48Spatrick 58809467b48Spatrick B.CreateCall(StackChkFail, {}); 58909467b48Spatrick } 59009467b48Spatrick B.CreateUnreachable(); 59109467b48Spatrick return FailBB; 59209467b48Spatrick } 59309467b48Spatrick 59409467b48Spatrick bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const { 59509467b48Spatrick return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator()); 59609467b48Spatrick } 59709467b48Spatrick 59809467b48Spatrick void StackProtector::copyToMachineFrameInfo(MachineFrameInfo &MFI) const { 59909467b48Spatrick if (Layout.empty()) 60009467b48Spatrick return; 60109467b48Spatrick 60209467b48Spatrick for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) { 60309467b48Spatrick if (MFI.isDeadObjectIndex(I)) 60409467b48Spatrick continue; 60509467b48Spatrick 60609467b48Spatrick const AllocaInst *AI = MFI.getObjectAllocation(I); 60709467b48Spatrick if (!AI) 60809467b48Spatrick continue; 60909467b48Spatrick 61009467b48Spatrick SSPLayoutMap::const_iterator LI = Layout.find(AI); 61109467b48Spatrick if (LI == Layout.end()) 61209467b48Spatrick continue; 61309467b48Spatrick 61409467b48Spatrick MFI.setObjectSSPLayout(I, LI->second); 61509467b48Spatrick } 61609467b48Spatrick } 617