17a7e6055SDimitry Andric //===- StackProtector.cpp - Stack Protector Insertion ---------------------===// 2f22ef01cSRoman Divacky // 3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure 4f22ef01cSRoman Divacky // 5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source 6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details. 7f22ef01cSRoman Divacky // 8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 9f22ef01cSRoman Divacky // 10f22ef01cSRoman Divacky // This pass inserts stack protectors into functions which need them. A variable 11f22ef01cSRoman Divacky // with a random value in it is stored onto the stack before the local variables 12f22ef01cSRoman Divacky // are allocated. Upon exiting the block, the stored value is checked. If it's 13f22ef01cSRoman Divacky // changed, then there was some sort of violation and the program aborts. 14f22ef01cSRoman Divacky // 15f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 16f22ef01cSRoman Divacky 17139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 18139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h" 1939d628a0SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h" 203ca95b02SDimitry Andric #include "llvm/Analysis/EHPersonalities.h" 217a7e6055SDimitry Andric #include "llvm/Analysis/OptimizationDiagnosticInfo.h" 2291bc56edSDimitry Andric #include "llvm/CodeGen/Passes.h" 237a7e6055SDimitry Andric #include "llvm/CodeGen/StackProtector.h" 24139f7f9bSDimitry Andric #include "llvm/IR/Attributes.h" 257a7e6055SDimitry Andric #include "llvm/IR/BasicBlock.h" 26139f7f9bSDimitry Andric #include "llvm/IR/Constants.h" 27139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h" 283ca95b02SDimitry Andric #include "llvm/IR/DebugInfo.h" 297a7e6055SDimitry Andric #include "llvm/IR/DebugLoc.h" 30139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h" 31139f7f9bSDimitry Andric #include "llvm/IR/Function.h" 32f785676fSDimitry Andric #include "llvm/IR/IRBuilder.h" 337a7e6055SDimitry Andric #include "llvm/IR/Instruction.h" 34139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h" 35139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h" 3639d628a0SDimitry Andric #include "llvm/IR/MDBuilder.h" 37139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 387a7e6055SDimitry Andric #include "llvm/IR/Type.h" 397a7e6055SDimitry Andric #include "llvm/IR/User.h" 407a7e6055SDimitry Andric #include "llvm/Pass.h" 417a7e6055SDimitry Andric #include "llvm/Support/Casting.h" 42f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h" 437a7e6055SDimitry Andric #include "llvm/Target/TargetLowering.h" 447a7e6055SDimitry Andric #include "llvm/Target/TargetMachine.h" 457a7e6055SDimitry Andric #include "llvm/Target/TargetOptions.h" 4639d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h" 477a7e6055SDimitry Andric #include <utility> 487a7e6055SDimitry Andric 49f22ef01cSRoman Divacky using namespace llvm; 50f22ef01cSRoman Divacky 5191bc56edSDimitry Andric #define DEBUG_TYPE "stack-protector" 5291bc56edSDimitry Andric 53139f7f9bSDimitry Andric STATISTIC(NumFunProtected, "Number of functions protected"); 54139f7f9bSDimitry Andric STATISTIC(NumAddrTaken, "Number of local variables that have their address" 55139f7f9bSDimitry Andric " taken."); 56139f7f9bSDimitry Andric 57f785676fSDimitry Andric static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp", 58f785676fSDimitry Andric cl::init(true), cl::Hidden); 59f22ef01cSRoman Divacky 60f22ef01cSRoman Divacky char StackProtector::ID = 0; 61302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE, 62d8866befSDimitry Andric "Insert stack protectors", false, true) 63d8866befSDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 64302affcbSDimitry Andric INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE, 65d8866befSDimitry Andric "Insert stack protectors", false, true) 66f22ef01cSRoman Divacky 67d8866befSDimitry Andric FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); } 68f785676fSDimitry Andric 69f785676fSDimitry Andric StackProtector::SSPLayoutKind 70f785676fSDimitry Andric StackProtector::getSSPLayout(const AllocaInst *AI) const { 71f785676fSDimitry Andric return AI ? Layout.lookup(AI) : SSPLK_None; 72f22ef01cSRoman Divacky } 73f22ef01cSRoman Divacky 7491bc56edSDimitry Andric void StackProtector::adjustForColoring(const AllocaInst *From, 7591bc56edSDimitry Andric const AllocaInst *To) { 7691bc56edSDimitry Andric // When coloring replaces one alloca with another, transfer the SSPLayoutKind 7791bc56edSDimitry Andric // tag from the remapped to the target alloca. The remapped alloca should 7891bc56edSDimitry Andric // have a size smaller than or equal to the replacement alloca. 7991bc56edSDimitry Andric SSPLayoutMap::iterator I = Layout.find(From); 8091bc56edSDimitry Andric if (I != Layout.end()) { 8191bc56edSDimitry Andric SSPLayoutKind Kind = I->second; 8291bc56edSDimitry Andric Layout.erase(I); 8391bc56edSDimitry Andric 8491bc56edSDimitry Andric // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite 8591bc56edSDimitry Andric // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that 8691bc56edSDimitry Andric // SSPLK_SmallArray does not overwrite SSPLK_LargeArray. 8791bc56edSDimitry Andric I = Layout.find(To); 8891bc56edSDimitry Andric if (I == Layout.end()) 8991bc56edSDimitry Andric Layout.insert(std::make_pair(To, Kind)); 9091bc56edSDimitry Andric else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf) 9191bc56edSDimitry Andric I->second = Kind; 9291bc56edSDimitry Andric } 9391bc56edSDimitry Andric } 9491bc56edSDimitry Andric 95f22ef01cSRoman Divacky bool StackProtector::runOnFunction(Function &Fn) { 96f22ef01cSRoman Divacky F = &Fn; 97f22ef01cSRoman Divacky M = F->getParent(); 9891bc56edSDimitry Andric DominatorTreeWrapperPass *DTWP = 9991bc56edSDimitry Andric getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 10091bc56edSDimitry Andric DT = DTWP ? &DTWP->getDomTree() : nullptr; 101d8866befSDimitry Andric TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>(); 102d8866befSDimitry Andric Trip = TM->getTargetTriple(); 103ff0cc061SDimitry Andric TLI = TM->getSubtargetImpl(Fn)->getTargetLowering(); 1043ca95b02SDimitry Andric HasPrologue = false; 1053ca95b02SDimitry Andric HasIRCheck = false; 106f22ef01cSRoman Divacky 107ff0cc061SDimitry Andric Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size"); 10891bc56edSDimitry Andric if (Attr.isStringAttribute() && 10991bc56edSDimitry Andric Attr.getValueAsString().getAsInteger(10, SSPBufferSize)) 11091bc56edSDimitry Andric return false; // Invalid integer string 11191bc56edSDimitry Andric 11291bc56edSDimitry Andric if (!RequiresStackProtector()) 11391bc56edSDimitry Andric return false; 114f22ef01cSRoman Divacky 1153ca95b02SDimitry Andric // TODO(etienneb): Functions with funclets are not correctly supported now. 1163ca95b02SDimitry Andric // Do nothing if this is funclet-based personality. 1173ca95b02SDimitry Andric if (Fn.hasPersonalityFn()) { 1183ca95b02SDimitry Andric EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn()); 1193ca95b02SDimitry Andric if (isFuncletEHPersonality(Personality)) 1203ca95b02SDimitry Andric return false; 1213ca95b02SDimitry Andric } 1223ca95b02SDimitry Andric 123139f7f9bSDimitry Andric ++NumFunProtected; 124f22ef01cSRoman Divacky return InsertStackProtectors(); 125f22ef01cSRoman Divacky } 126f22ef01cSRoman Divacky 127f785676fSDimitry Andric /// \param [out] IsLarge is set to true if a protectable array is found and 128f785676fSDimitry Andric /// it is "large" ( >= ssp-buffer-size). In the case of a structure with 129f785676fSDimitry Andric /// multiple arrays, this gets set if any of them is large. 130f785676fSDimitry Andric bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge, 131f785676fSDimitry Andric bool Strong, 132139f7f9bSDimitry Andric bool InStruct) const { 133f785676fSDimitry Andric if (!Ty) 134f785676fSDimitry Andric return false; 1353861d79fSDimitry Andric if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 1363861d79fSDimitry Andric if (!AT->getElementType()->isIntegerTy(8)) { 1373861d79fSDimitry Andric // If we're on a non-Darwin platform or we're inside of a structure, don't 1383861d79fSDimitry Andric // add stack protectors unless the array is a character array. 139f785676fSDimitry Andric // However, in strong mode any array, regardless of type and size, 140f785676fSDimitry Andric // triggers a protector. 141f785676fSDimitry Andric if (!Strong && (InStruct || !Trip.isOSDarwin())) 1423861d79fSDimitry Andric return false; 1433861d79fSDimitry Andric } 1443861d79fSDimitry Andric 1453861d79fSDimitry Andric // If an array has more than SSPBufferSize bytes of allocated space, then we 1463861d79fSDimitry Andric // emit stack protectors. 147875ed548SDimitry Andric if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) { 148f785676fSDimitry Andric IsLarge = true; 149f785676fSDimitry Andric return true; 150f785676fSDimitry Andric } 151f785676fSDimitry Andric 152f785676fSDimitry Andric if (Strong) 153f785676fSDimitry Andric // Require a protector for all arrays in strong mode 1543861d79fSDimitry Andric return true; 1553861d79fSDimitry Andric } 1563861d79fSDimitry Andric 1573861d79fSDimitry Andric const StructType *ST = dyn_cast<StructType>(Ty); 158f785676fSDimitry Andric if (!ST) 1593861d79fSDimitry Andric return false; 160f785676fSDimitry Andric 161f785676fSDimitry Andric bool NeedsProtector = false; 162f785676fSDimitry Andric for (StructType::element_iterator I = ST->element_begin(), 163f785676fSDimitry Andric E = ST->element_end(); 164f785676fSDimitry Andric I != E; ++I) 165f785676fSDimitry Andric if (ContainsProtectableArray(*I, IsLarge, Strong, true)) { 166f785676fSDimitry Andric // If the element is a protectable array and is large (>= SSPBufferSize) 167f785676fSDimitry Andric // then we are done. If the protectable array is not large, then 168f785676fSDimitry Andric // keep looking in case a subsequent element is a large array. 169f785676fSDimitry Andric if (IsLarge) 170f785676fSDimitry Andric return true; 171f785676fSDimitry Andric NeedsProtector = true; 172f785676fSDimitry Andric } 173f785676fSDimitry Andric 174f785676fSDimitry Andric return NeedsProtector; 1753861d79fSDimitry Andric } 1763861d79fSDimitry Andric 177139f7f9bSDimitry Andric bool StackProtector::HasAddressTaken(const Instruction *AI) { 17891bc56edSDimitry Andric for (const User *U : AI->users()) { 179139f7f9bSDimitry Andric if (const StoreInst *SI = dyn_cast<StoreInst>(U)) { 180139f7f9bSDimitry Andric if (AI == SI->getValueOperand()) 181f22ef01cSRoman Divacky return true; 182139f7f9bSDimitry Andric } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) { 183139f7f9bSDimitry Andric if (AI == SI->getOperand(0)) 184139f7f9bSDimitry Andric return true; 185139f7f9bSDimitry Andric } else if (isa<CallInst>(U)) { 186139f7f9bSDimitry Andric return true; 187139f7f9bSDimitry Andric } else if (isa<InvokeInst>(U)) { 188139f7f9bSDimitry Andric return true; 189139f7f9bSDimitry Andric } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) { 190139f7f9bSDimitry Andric if (HasAddressTaken(SI)) 191139f7f9bSDimitry Andric return true; 192139f7f9bSDimitry Andric } else if (const PHINode *PN = dyn_cast<PHINode>(U)) { 193139f7f9bSDimitry Andric // Keep track of what PHI nodes we have already visited to ensure 194139f7f9bSDimitry Andric // they are only visited once. 19539d628a0SDimitry Andric if (VisitedPHIs.insert(PN).second) 196139f7f9bSDimitry Andric if (HasAddressTaken(PN)) 197139f7f9bSDimitry Andric return true; 198139f7f9bSDimitry Andric } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) { 199139f7f9bSDimitry Andric if (HasAddressTaken(GEP)) 200139f7f9bSDimitry Andric return true; 201139f7f9bSDimitry Andric } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) { 202139f7f9bSDimitry Andric if (HasAddressTaken(BI)) 203139f7f9bSDimitry Andric return true; 204139f7f9bSDimitry Andric } 205139f7f9bSDimitry Andric } 206139f7f9bSDimitry Andric return false; 207139f7f9bSDimitry Andric } 208f22ef01cSRoman Divacky 209139f7f9bSDimitry Andric /// \brief Check whether or not this function needs a stack protector based 210139f7f9bSDimitry Andric /// upon the stack protector level. 211139f7f9bSDimitry Andric /// 212139f7f9bSDimitry Andric /// We use two heuristics: a standard (ssp) and strong (sspstrong). 213139f7f9bSDimitry Andric /// The standard heuristic which will add a guard variable to functions that 214139f7f9bSDimitry Andric /// call alloca with a either a variable size or a size >= SSPBufferSize, 215139f7f9bSDimitry Andric /// functions with character buffers larger than SSPBufferSize, and functions 216139f7f9bSDimitry Andric /// with aggregates containing character buffers larger than SSPBufferSize. The 217139f7f9bSDimitry Andric /// strong heuristic will add a guard variables to functions that call alloca 218139f7f9bSDimitry Andric /// regardless of size, functions with any buffer regardless of type and size, 219139f7f9bSDimitry Andric /// functions with aggregates that contain any buffer regardless of type and 220139f7f9bSDimitry Andric /// size, and functions that contain stack-based variables that have had their 221139f7f9bSDimitry Andric /// address taken. 222139f7f9bSDimitry Andric bool StackProtector::RequiresStackProtector() { 223139f7f9bSDimitry Andric bool Strong = false; 224f785676fSDimitry Andric bool NeedsProtector = false; 2253ca95b02SDimitry Andric for (const BasicBlock &BB : *F) 2263ca95b02SDimitry Andric for (const Instruction &I : BB) 2273ca95b02SDimitry Andric if (const CallInst *CI = dyn_cast<CallInst>(&I)) 2283ca95b02SDimitry Andric if (CI->getCalledFunction() == 2293ca95b02SDimitry Andric Intrinsic::getDeclaration(F->getParent(), 2303ca95b02SDimitry Andric Intrinsic::stackprotector)) 2313ca95b02SDimitry Andric HasPrologue = true; 2323ca95b02SDimitry Andric 2333ca95b02SDimitry Andric if (F->hasFnAttribute(Attribute::SafeStack)) 2343ca95b02SDimitry Andric return false; 2353ca95b02SDimitry Andric 2367a7e6055SDimitry Andric // We are constructing the OptimizationRemarkEmitter on the fly rather than 2377a7e6055SDimitry Andric // using the analysis pass to avoid building DominatorTree and LoopInfo which 2387a7e6055SDimitry Andric // are not available this late in the IR pipeline. 2397a7e6055SDimitry Andric OptimizationRemarkEmitter ORE(F); 2407a7e6055SDimitry Andric 241ff0cc061SDimitry Andric if (F->hasFnAttribute(Attribute::StackProtectReq)) { 2427a7e6055SDimitry Andric ORE.emit(OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F) 2437a7e6055SDimitry Andric << "Stack protection applied to function " 2447a7e6055SDimitry Andric << ore::NV("Function", F) 2457a7e6055SDimitry Andric << " due to a function attribute or command-line switch"); 246f785676fSDimitry Andric NeedsProtector = true; 247f785676fSDimitry Andric Strong = true; // Use the same heuristic as strong to determine SSPLayout 248ff0cc061SDimitry Andric } else if (F->hasFnAttribute(Attribute::StackProtectStrong)) 249139f7f9bSDimitry Andric Strong = true; 2503ca95b02SDimitry Andric else if (HasPrologue) 2513ca95b02SDimitry Andric NeedsProtector = true; 252ff0cc061SDimitry Andric else if (!F->hasFnAttribute(Attribute::StackProtect)) 253f22ef01cSRoman Divacky return false; 254f22ef01cSRoman Divacky 25539d628a0SDimitry Andric for (const BasicBlock &BB : *F) { 25639d628a0SDimitry Andric for (const Instruction &I : BB) { 25739d628a0SDimitry Andric if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 258139f7f9bSDimitry Andric if (AI->isArrayAllocation()) { 2597a7e6055SDimitry Andric OptimizationRemark Remark(DEBUG_TYPE, "StackProtectorAllocaOrArray", 2607a7e6055SDimitry Andric &I); 2617a7e6055SDimitry Andric Remark 2627a7e6055SDimitry Andric << "Stack protection applied to function " 2637a7e6055SDimitry Andric << ore::NV("Function", F) 2647a7e6055SDimitry Andric << " due to a call to alloca or use of a variable length array"; 26539d628a0SDimitry Andric if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) { 266f785676fSDimitry Andric if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) { 267139f7f9bSDimitry Andric // A call to alloca with size >= SSPBufferSize requires 268139f7f9bSDimitry Andric // stack protectors. 269f785676fSDimitry Andric Layout.insert(std::make_pair(AI, SSPLK_LargeArray)); 2707a7e6055SDimitry Andric ORE.emit(Remark); 271f785676fSDimitry Andric NeedsProtector = true; 272f785676fSDimitry Andric } else if (Strong) { 273f785676fSDimitry Andric // Require protectors for all alloca calls in strong mode. 274f785676fSDimitry Andric Layout.insert(std::make_pair(AI, SSPLK_SmallArray)); 2757a7e6055SDimitry Andric ORE.emit(Remark); 276f785676fSDimitry Andric NeedsProtector = true; 277f785676fSDimitry Andric } 278f785676fSDimitry Andric } else { 279f785676fSDimitry Andric // A call to alloca with a variable size requires protectors. 280f785676fSDimitry Andric Layout.insert(std::make_pair(AI, SSPLK_LargeArray)); 2817a7e6055SDimitry Andric ORE.emit(Remark); 282f785676fSDimitry Andric NeedsProtector = true; 283f785676fSDimitry Andric } 284f785676fSDimitry Andric continue; 285139f7f9bSDimitry Andric } 286139f7f9bSDimitry Andric 287f785676fSDimitry Andric bool IsLarge = false; 288f785676fSDimitry Andric if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) { 289f785676fSDimitry Andric Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray 290f785676fSDimitry Andric : SSPLK_SmallArray)); 2917a7e6055SDimitry Andric ORE.emit(OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I) 2927a7e6055SDimitry Andric << "Stack protection applied to function " 2937a7e6055SDimitry Andric << ore::NV("Function", F) 2947a7e6055SDimitry Andric << " due to a stack allocated buffer or struct containing a " 2957a7e6055SDimitry Andric "buffer"); 296f785676fSDimitry Andric NeedsProtector = true; 297f785676fSDimitry Andric continue; 298f785676fSDimitry Andric } 299139f7f9bSDimitry Andric 300139f7f9bSDimitry Andric if (Strong && HasAddressTaken(AI)) { 301139f7f9bSDimitry Andric ++NumAddrTaken; 302f785676fSDimitry Andric Layout.insert(std::make_pair(AI, SSPLK_AddrOf)); 3037a7e6055SDimitry Andric ORE.emit( 3047a7e6055SDimitry Andric OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken", &I) 3057a7e6055SDimitry Andric << "Stack protection applied to function " 3067a7e6055SDimitry Andric << ore::NV("Function", F) 3077a7e6055SDimitry Andric << " due to the address of a local variable being taken"); 308f785676fSDimitry Andric NeedsProtector = true; 309139f7f9bSDimitry Andric } 310139f7f9bSDimitry Andric } 311f22ef01cSRoman Divacky } 312f22ef01cSRoman Divacky } 313f22ef01cSRoman Divacky 314f785676fSDimitry Andric return NeedsProtector; 315f785676fSDimitry Andric } 316f785676fSDimitry Andric 3173ca95b02SDimitry Andric /// Create a stack guard loading and populate whether SelectionDAG SSP is 3183ca95b02SDimitry Andric /// supported. 3193ca95b02SDimitry Andric static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M, 3203ca95b02SDimitry Andric IRBuilder<> &B, 3213ca95b02SDimitry Andric bool *SupportsSelectionDAGSP = nullptr) { 3223ca95b02SDimitry Andric if (Value *Guard = TLI->getIRStackGuard(B)) 3233ca95b02SDimitry Andric return B.CreateLoad(Guard, true, "StackGuard"); 324f785676fSDimitry Andric 3253ca95b02SDimitry Andric // Use SelectionDAG SSP handling, since there isn't an IR guard. 326f785676fSDimitry Andric // 3273ca95b02SDimitry Andric // This is more or less weird, since we optionally output whether we 3283ca95b02SDimitry Andric // should perform a SelectionDAG SP here. The reason is that it's strictly 3293ca95b02SDimitry Andric // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also 3303ca95b02SDimitry Andric // mutating. There is no way to get this bit without mutating the IR, so 3313ca95b02SDimitry Andric // getting this bit has to happen in this right time. 332f785676fSDimitry Andric // 3333ca95b02SDimitry Andric // We could have define a new function TLI::supportsSelectionDAGSP(), but that 3343ca95b02SDimitry Andric // will put more burden on the backends' overriding work, especially when it 3353ca95b02SDimitry Andric // actually conveys the same information getIRStackGuard() already gives. 3363ca95b02SDimitry Andric if (SupportsSelectionDAGSP) 3373ca95b02SDimitry Andric *SupportsSelectionDAGSP = true; 3383ca95b02SDimitry Andric TLI->insertSSPDeclarations(*M); 3393ca95b02SDimitry Andric return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard)); 340f785676fSDimitry Andric } 341f785676fSDimitry Andric 3423ca95b02SDimitry Andric /// Insert code into the entry block that stores the stack guard 343f785676fSDimitry Andric /// variable onto the stack: 344f785676fSDimitry Andric /// 345f785676fSDimitry Andric /// entry: 346f785676fSDimitry Andric /// StackGuardSlot = alloca i8* 3473ca95b02SDimitry Andric /// StackGuard = <stack guard> 3483ca95b02SDimitry Andric /// call void @llvm.stackprotector(StackGuard, StackGuardSlot) 349f785676fSDimitry Andric /// 350f785676fSDimitry Andric /// Returns true if the platform/triple supports the stackprotectorcreate pseudo 351f785676fSDimitry Andric /// node. 352f785676fSDimitry Andric static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI, 3533ca95b02SDimitry Andric const TargetLoweringBase *TLI, AllocaInst *&AI) { 354f785676fSDimitry Andric bool SupportsSelectionDAGSP = false; 355f785676fSDimitry Andric IRBuilder<> B(&F->getEntryBlock().front()); 3563ca95b02SDimitry Andric PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext()); 35791bc56edSDimitry Andric AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot"); 358f785676fSDimitry Andric 3593ca95b02SDimitry Andric Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP); 3603ca95b02SDimitry Andric B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), 3613ca95b02SDimitry Andric {GuardSlot, AI}); 362f785676fSDimitry Andric return SupportsSelectionDAGSP; 363f22ef01cSRoman Divacky } 364f22ef01cSRoman Divacky 365f22ef01cSRoman Divacky /// InsertStackProtectors - Insert code into the prologue and epilogue of the 366f22ef01cSRoman Divacky /// function. 367f22ef01cSRoman Divacky /// 368f22ef01cSRoman Divacky /// - The prologue code loads and stores the stack guard onto the stack. 369f22ef01cSRoman Divacky /// - The epilogue checks the value stored in the prologue against the original 370f22ef01cSRoman Divacky /// value. It calls __stack_chk_fail if they differ. 371f22ef01cSRoman Divacky bool StackProtector::InsertStackProtectors() { 372f785676fSDimitry Andric bool SupportsSelectionDAGSP = 373f785676fSDimitry Andric EnableSelectionDAGSP && !TM->Options.EnableFastISel; 37491bc56edSDimitry Andric AllocaInst *AI = nullptr; // Place on stack that stores the stack guard. 375f22ef01cSRoman Divacky 376f22ef01cSRoman Divacky for (Function::iterator I = F->begin(), E = F->end(); I != E;) { 3777d523365SDimitry Andric BasicBlock *BB = &*I++; 378f22ef01cSRoman Divacky ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); 379f785676fSDimitry Andric if (!RI) 380f785676fSDimitry Andric continue; 381f22ef01cSRoman Divacky 3823ca95b02SDimitry Andric // Generate prologue instrumentation if not already generated. 383f785676fSDimitry Andric if (!HasPrologue) { 384f785676fSDimitry Andric HasPrologue = true; 3853ca95b02SDimitry Andric SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI); 386f785676fSDimitry Andric } 387ffd1746dSEd Schouten 3883ca95b02SDimitry Andric // SelectionDAG based code generation. Nothing else needs to be done here. 3893ca95b02SDimitry Andric // The epilogue instrumentation is postponed to SelectionDAG. 3903ca95b02SDimitry Andric if (SupportsSelectionDAGSP) 3913ca95b02SDimitry Andric break; 392f22ef01cSRoman Divacky 3933ca95b02SDimitry Andric // Set HasIRCheck to true, so that SelectionDAG will not generate its own 3943ca95b02SDimitry Andric // version. SelectionDAG called 'shouldEmitSDCheck' to check whether 3953ca95b02SDimitry Andric // instrumentation has already been generated. 3963ca95b02SDimitry Andric HasIRCheck = true; 3973ca95b02SDimitry Andric 3983ca95b02SDimitry Andric // Generate epilogue instrumentation. The epilogue intrumentation can be 3993ca95b02SDimitry Andric // function-based or inlined depending on which mechanism the target is 4003ca95b02SDimitry Andric // providing. 4013ca95b02SDimitry Andric if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) { 4023ca95b02SDimitry Andric // Generate the function-based epilogue instrumentation. 4033ca95b02SDimitry Andric // The target provides a guard check function, generate a call to it. 4043ca95b02SDimitry Andric IRBuilder<> B(RI); 4053ca95b02SDimitry Andric LoadInst *Guard = B.CreateLoad(AI, true, "Guard"); 4063ca95b02SDimitry Andric CallInst *Call = B.CreateCall(GuardCheck, {Guard}); 4073ca95b02SDimitry Andric llvm::Function *Function = cast<llvm::Function>(GuardCheck); 4083ca95b02SDimitry Andric Call->setAttributes(Function->getAttributes()); 4093ca95b02SDimitry Andric Call->setCallingConv(Function->getCallingConv()); 410f785676fSDimitry Andric } else { 4113ca95b02SDimitry Andric // Generate the epilogue with inline instrumentation. 412f785676fSDimitry Andric // If we do not support SelectionDAG based tail calls, generate IR level 413f785676fSDimitry Andric // tail calls. 414f785676fSDimitry Andric // 415f22ef01cSRoman Divacky // For each block with a return instruction, convert this: 416f22ef01cSRoman Divacky // 417f22ef01cSRoman Divacky // return: 418f22ef01cSRoman Divacky // ... 419f22ef01cSRoman Divacky // ret ... 420f22ef01cSRoman Divacky // 421f22ef01cSRoman Divacky // into this: 422f22ef01cSRoman Divacky // 423f22ef01cSRoman Divacky // return: 424f22ef01cSRoman Divacky // ... 4253ca95b02SDimitry Andric // %1 = <stack guard> 426f22ef01cSRoman Divacky // %2 = load StackGuardSlot 427f22ef01cSRoman Divacky // %3 = cmp i1 %1, %2 428f22ef01cSRoman Divacky // br i1 %3, label %SP_return, label %CallStackCheckFailBlk 429f22ef01cSRoman Divacky // 430f22ef01cSRoman Divacky // SP_return: 431f22ef01cSRoman Divacky // ret ... 432f22ef01cSRoman Divacky // 433f22ef01cSRoman Divacky // CallStackCheckFailBlk: 434f22ef01cSRoman Divacky // call void @__stack_chk_fail() 435f22ef01cSRoman Divacky // unreachable 436f22ef01cSRoman Divacky 437f785676fSDimitry Andric // Create the FailBB. We duplicate the BB every time since the MI tail 438f785676fSDimitry Andric // merge pass will merge together all of the various BB into one including 439f785676fSDimitry Andric // fail BB generated by the stack protector pseudo instruction. 440f785676fSDimitry Andric BasicBlock *FailBB = CreateFailBB(); 441f785676fSDimitry Andric 442f22ef01cSRoman Divacky // Split the basic block before the return instruction. 4437d523365SDimitry Andric BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return"); 4443b0f4066SDimitry Andric 445f785676fSDimitry Andric // Update the dominator tree if we need to. 4463b0f4066SDimitry Andric if (DT && DT->isReachableFromEntry(BB)) { 4473b0f4066SDimitry Andric DT->addNewBlock(NewBB, BB); 448f785676fSDimitry Andric DT->addNewBlock(FailBB, BB); 4492754fe60SDimitry Andric } 450f22ef01cSRoman Divacky 451f22ef01cSRoman Divacky // Remove default branch instruction to the new BB. 452f22ef01cSRoman Divacky BB->getTerminator()->eraseFromParent(); 453f22ef01cSRoman Divacky 454f785676fSDimitry Andric // Move the newly created basic block to the point right after the old 455f785676fSDimitry Andric // basic block so that it's in the "fall through" position. 456f22ef01cSRoman Divacky NewBB->moveAfter(BB); 457f22ef01cSRoman Divacky 458f22ef01cSRoman Divacky // Generate the stack protector instructions in the old basic block. 459f785676fSDimitry Andric IRBuilder<> B(BB); 4603ca95b02SDimitry Andric Value *Guard = getStackGuard(TLI, M, B); 4613ca95b02SDimitry Andric LoadInst *LI2 = B.CreateLoad(AI, true); 4623ca95b02SDimitry Andric Value *Cmp = B.CreateICmpEQ(Guard, LI2); 4637d523365SDimitry Andric auto SuccessProb = 4647d523365SDimitry Andric BranchProbabilityInfo::getBranchProbStackProtector(true); 4657d523365SDimitry Andric auto FailureProb = 4667d523365SDimitry Andric BranchProbabilityInfo::getBranchProbStackProtector(false); 46739d628a0SDimitry Andric MDNode *Weights = MDBuilder(F->getContext()) 4687d523365SDimitry Andric .createBranchWeights(SuccessProb.getNumerator(), 4697d523365SDimitry Andric FailureProb.getNumerator()); 47039d628a0SDimitry Andric B.CreateCondBr(Cmp, NewBB, FailBB, Weights); 471f785676fSDimitry Andric } 472f22ef01cSRoman Divacky } 473f22ef01cSRoman Divacky 47439d628a0SDimitry Andric // Return if we didn't modify any basic blocks. i.e., there are no return 475f22ef01cSRoman Divacky // statements in the function. 4767d523365SDimitry Andric return HasPrologue; 477f22ef01cSRoman Divacky } 478f22ef01cSRoman Divacky 479f22ef01cSRoman Divacky /// CreateFailBB - Create a basic block to jump to when the stack protector 480f22ef01cSRoman Divacky /// check fails. 481f22ef01cSRoman Divacky BasicBlock *StackProtector::CreateFailBB() { 482f785676fSDimitry Andric LLVMContext &Context = F->getContext(); 483f785676fSDimitry Andric BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F); 484f785676fSDimitry Andric IRBuilder<> B(FailBB); 4853ca95b02SDimitry Andric B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram())); 48639d628a0SDimitry Andric if (Trip.isOSOpenBSD()) { 48739d628a0SDimitry Andric Constant *StackChkFail = 48839d628a0SDimitry Andric M->getOrInsertFunction("__stack_smash_handler", 48939d628a0SDimitry Andric Type::getVoidTy(Context), 4907a7e6055SDimitry Andric Type::getInt8PtrTy(Context)); 491f785676fSDimitry Andric 492f785676fSDimitry Andric B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH")); 493f785676fSDimitry Andric } else { 49439d628a0SDimitry Andric Constant *StackChkFail = 4957a7e6055SDimitry Andric M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context)); 4967a7e6055SDimitry Andric 497ff0cc061SDimitry Andric B.CreateCall(StackChkFail, {}); 498f785676fSDimitry Andric } 499f785676fSDimitry Andric B.CreateUnreachable(); 500f22ef01cSRoman Divacky return FailBB; 501f22ef01cSRoman Divacky } 5023ca95b02SDimitry Andric 5033ca95b02SDimitry Andric bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const { 5043ca95b02SDimitry Andric return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator()); 5053ca95b02SDimitry Andric } 506