1f22ef01cSRoman Divacky //===-- StackProtector.cpp - Stack Protector Insertion --------------------===// 2f22ef01cSRoman Divacky // 3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure 4f22ef01cSRoman Divacky // 5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source 6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details. 7f22ef01cSRoman Divacky // 8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 9f22ef01cSRoman Divacky // 10f22ef01cSRoman Divacky // This pass inserts stack protectors into functions which need them. A variable 11f22ef01cSRoman Divacky // with a random value in it is stored onto the stack before the local variables 12f22ef01cSRoman Divacky // are allocated. Upon exiting the block, the stored value is checked. If it's 13f22ef01cSRoman Divacky // changed, then there was some sort of violation and the program aborts. 14f22ef01cSRoman Divacky // 15f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 16f22ef01cSRoman Divacky 17f785676fSDimitry Andric #include "llvm/CodeGen/StackProtector.h" 18139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 19139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h" 2039d628a0SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h" 213ca95b02SDimitry Andric #include "llvm/Analysis/EHPersonalities.h" 22f785676fSDimitry Andric #include "llvm/Analysis/ValueTracking.h" 2391bc56edSDimitry Andric #include "llvm/CodeGen/Passes.h" 24139f7f9bSDimitry Andric #include "llvm/IR/Attributes.h" 25139f7f9bSDimitry Andric #include "llvm/IR/Constants.h" 26139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h" 273ca95b02SDimitry Andric #include "llvm/IR/DebugInfo.h" 28139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h" 29139f7f9bSDimitry Andric #include "llvm/IR/Function.h" 30f785676fSDimitry Andric #include "llvm/IR/GlobalValue.h" 31f785676fSDimitry Andric #include "llvm/IR/GlobalVariable.h" 32f785676fSDimitry Andric #include "llvm/IR/IRBuilder.h" 33139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h" 34f785676fSDimitry Andric #include "llvm/IR/IntrinsicInst.h" 35139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h" 3639d628a0SDimitry Andric #include "llvm/IR/MDBuilder.h" 37139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 38f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h" 3939d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h" 40f785676fSDimitry Andric #include <cstdlib> 41f22ef01cSRoman Divacky using namespace llvm; 42f22ef01cSRoman Divacky 4391bc56edSDimitry Andric #define DEBUG_TYPE "stack-protector" 4491bc56edSDimitry Andric 45139f7f9bSDimitry Andric STATISTIC(NumFunProtected, "Number of functions protected"); 46139f7f9bSDimitry Andric STATISTIC(NumAddrTaken, "Number of local variables that have their address" 47139f7f9bSDimitry Andric " taken."); 48139f7f9bSDimitry Andric 49f785676fSDimitry Andric static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp", 50f785676fSDimitry Andric cl::init(true), cl::Hidden); 51f22ef01cSRoman Divacky 52f22ef01cSRoman Divacky char StackProtector::ID = 0; 53d88c1a5aSDimitry Andric INITIALIZE_TM_PASS(StackProtector, "stack-protector", "Insert stack protectors", 54f785676fSDimitry Andric false, true) 55f22ef01cSRoman Divacky 56f785676fSDimitry Andric FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) { 57f785676fSDimitry Andric return new StackProtector(TM); 58f785676fSDimitry Andric } 59f785676fSDimitry Andric 60f785676fSDimitry Andric StackProtector::SSPLayoutKind 61f785676fSDimitry Andric StackProtector::getSSPLayout(const AllocaInst *AI) const { 62f785676fSDimitry Andric return AI ? Layout.lookup(AI) : SSPLK_None; 63f22ef01cSRoman Divacky } 64f22ef01cSRoman Divacky 6591bc56edSDimitry Andric void StackProtector::adjustForColoring(const AllocaInst *From, 6691bc56edSDimitry Andric const AllocaInst *To) { 6791bc56edSDimitry Andric // When coloring replaces one alloca with another, transfer the SSPLayoutKind 6891bc56edSDimitry Andric // tag from the remapped to the target alloca. The remapped alloca should 6991bc56edSDimitry Andric // have a size smaller than or equal to the replacement alloca. 7091bc56edSDimitry Andric SSPLayoutMap::iterator I = Layout.find(From); 7191bc56edSDimitry Andric if (I != Layout.end()) { 7291bc56edSDimitry Andric SSPLayoutKind Kind = I->second; 7391bc56edSDimitry Andric Layout.erase(I); 7491bc56edSDimitry Andric 7591bc56edSDimitry Andric // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite 7691bc56edSDimitry Andric // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that 7791bc56edSDimitry Andric // SSPLK_SmallArray does not overwrite SSPLK_LargeArray. 7891bc56edSDimitry Andric I = Layout.find(To); 7991bc56edSDimitry Andric if (I == Layout.end()) 8091bc56edSDimitry Andric Layout.insert(std::make_pair(To, Kind)); 8191bc56edSDimitry Andric else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf) 8291bc56edSDimitry Andric I->second = Kind; 8391bc56edSDimitry Andric } 8491bc56edSDimitry Andric } 8591bc56edSDimitry Andric 86f22ef01cSRoman Divacky bool StackProtector::runOnFunction(Function &Fn) { 87f22ef01cSRoman Divacky F = &Fn; 88f22ef01cSRoman Divacky M = F->getParent(); 8991bc56edSDimitry Andric DominatorTreeWrapperPass *DTWP = 9091bc56edSDimitry Andric getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 9191bc56edSDimitry Andric DT = DTWP ? &DTWP->getDomTree() : nullptr; 92ff0cc061SDimitry Andric TLI = TM->getSubtargetImpl(Fn)->getTargetLowering(); 933ca95b02SDimitry Andric HasPrologue = false; 943ca95b02SDimitry Andric HasIRCheck = false; 95f22ef01cSRoman Divacky 96ff0cc061SDimitry Andric Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size"); 9791bc56edSDimitry Andric if (Attr.isStringAttribute() && 9891bc56edSDimitry Andric Attr.getValueAsString().getAsInteger(10, SSPBufferSize)) 9991bc56edSDimitry Andric return false; // Invalid integer string 10091bc56edSDimitry Andric 10191bc56edSDimitry Andric if (!RequiresStackProtector()) 10291bc56edSDimitry Andric return false; 103f22ef01cSRoman Divacky 1043ca95b02SDimitry Andric // TODO(etienneb): Functions with funclets are not correctly supported now. 1053ca95b02SDimitry Andric // Do nothing if this is funclet-based personality. 1063ca95b02SDimitry Andric if (Fn.hasPersonalityFn()) { 1073ca95b02SDimitry Andric EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn()); 1083ca95b02SDimitry Andric if (isFuncletEHPersonality(Personality)) 1093ca95b02SDimitry Andric return false; 1103ca95b02SDimitry Andric } 1113ca95b02SDimitry Andric 112139f7f9bSDimitry Andric ++NumFunProtected; 113f22ef01cSRoman Divacky return InsertStackProtectors(); 114f22ef01cSRoman Divacky } 115f22ef01cSRoman Divacky 116f785676fSDimitry Andric /// \param [out] IsLarge is set to true if a protectable array is found and 117f785676fSDimitry Andric /// it is "large" ( >= ssp-buffer-size). In the case of a structure with 118f785676fSDimitry Andric /// multiple arrays, this gets set if any of them is large. 119f785676fSDimitry Andric bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge, 120f785676fSDimitry Andric bool Strong, 121139f7f9bSDimitry Andric bool InStruct) const { 122f785676fSDimitry Andric if (!Ty) 123f785676fSDimitry Andric return false; 1243861d79fSDimitry Andric if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 1253861d79fSDimitry Andric if (!AT->getElementType()->isIntegerTy(8)) { 1263861d79fSDimitry Andric // If we're on a non-Darwin platform or we're inside of a structure, don't 1273861d79fSDimitry Andric // add stack protectors unless the array is a character array. 128f785676fSDimitry Andric // However, in strong mode any array, regardless of type and size, 129f785676fSDimitry Andric // triggers a protector. 130f785676fSDimitry Andric if (!Strong && (InStruct || !Trip.isOSDarwin())) 1313861d79fSDimitry Andric return false; 1323861d79fSDimitry Andric } 1333861d79fSDimitry Andric 1343861d79fSDimitry Andric // If an array has more than SSPBufferSize bytes of allocated space, then we 1353861d79fSDimitry Andric // emit stack protectors. 136875ed548SDimitry Andric if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) { 137f785676fSDimitry Andric IsLarge = true; 138f785676fSDimitry Andric return true; 139f785676fSDimitry Andric } 140f785676fSDimitry Andric 141f785676fSDimitry Andric if (Strong) 142f785676fSDimitry Andric // Require a protector for all arrays in strong mode 1433861d79fSDimitry Andric return true; 1443861d79fSDimitry Andric } 1453861d79fSDimitry Andric 1463861d79fSDimitry Andric const StructType *ST = dyn_cast<StructType>(Ty); 147f785676fSDimitry Andric if (!ST) 1483861d79fSDimitry Andric return false; 149f785676fSDimitry Andric 150f785676fSDimitry Andric bool NeedsProtector = false; 151f785676fSDimitry Andric for (StructType::element_iterator I = ST->element_begin(), 152f785676fSDimitry Andric E = ST->element_end(); 153f785676fSDimitry Andric I != E; ++I) 154f785676fSDimitry Andric if (ContainsProtectableArray(*I, IsLarge, Strong, true)) { 155f785676fSDimitry Andric // If the element is a protectable array and is large (>= SSPBufferSize) 156f785676fSDimitry Andric // then we are done. If the protectable array is not large, then 157f785676fSDimitry Andric // keep looking in case a subsequent element is a large array. 158f785676fSDimitry Andric if (IsLarge) 159f785676fSDimitry Andric return true; 160f785676fSDimitry Andric NeedsProtector = true; 161f785676fSDimitry Andric } 162f785676fSDimitry Andric 163f785676fSDimitry Andric return NeedsProtector; 1643861d79fSDimitry Andric } 1653861d79fSDimitry Andric 166139f7f9bSDimitry Andric bool StackProtector::HasAddressTaken(const Instruction *AI) { 16791bc56edSDimitry Andric for (const User *U : AI->users()) { 168139f7f9bSDimitry Andric if (const StoreInst *SI = dyn_cast<StoreInst>(U)) { 169139f7f9bSDimitry Andric if (AI == SI->getValueOperand()) 170f22ef01cSRoman Divacky return true; 171139f7f9bSDimitry Andric } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) { 172139f7f9bSDimitry Andric if (AI == SI->getOperand(0)) 173139f7f9bSDimitry Andric return true; 174139f7f9bSDimitry Andric } else if (isa<CallInst>(U)) { 175139f7f9bSDimitry Andric return true; 176139f7f9bSDimitry Andric } else if (isa<InvokeInst>(U)) { 177139f7f9bSDimitry Andric return true; 178139f7f9bSDimitry Andric } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) { 179139f7f9bSDimitry Andric if (HasAddressTaken(SI)) 180139f7f9bSDimitry Andric return true; 181139f7f9bSDimitry Andric } else if (const PHINode *PN = dyn_cast<PHINode>(U)) { 182139f7f9bSDimitry Andric // Keep track of what PHI nodes we have already visited to ensure 183139f7f9bSDimitry Andric // they are only visited once. 18439d628a0SDimitry Andric if (VisitedPHIs.insert(PN).second) 185139f7f9bSDimitry Andric if (HasAddressTaken(PN)) 186139f7f9bSDimitry Andric return true; 187139f7f9bSDimitry Andric } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) { 188139f7f9bSDimitry Andric if (HasAddressTaken(GEP)) 189139f7f9bSDimitry Andric return true; 190139f7f9bSDimitry Andric } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) { 191139f7f9bSDimitry Andric if (HasAddressTaken(BI)) 192139f7f9bSDimitry Andric return true; 193139f7f9bSDimitry Andric } 194139f7f9bSDimitry Andric } 195139f7f9bSDimitry Andric return false; 196139f7f9bSDimitry Andric } 197f22ef01cSRoman Divacky 198139f7f9bSDimitry Andric /// \brief Check whether or not this function needs a stack protector based 199139f7f9bSDimitry Andric /// upon the stack protector level. 200139f7f9bSDimitry Andric /// 201139f7f9bSDimitry Andric /// We use two heuristics: a standard (ssp) and strong (sspstrong). 202139f7f9bSDimitry Andric /// The standard heuristic which will add a guard variable to functions that 203139f7f9bSDimitry Andric /// call alloca with a either a variable size or a size >= SSPBufferSize, 204139f7f9bSDimitry Andric /// functions with character buffers larger than SSPBufferSize, and functions 205139f7f9bSDimitry Andric /// with aggregates containing character buffers larger than SSPBufferSize. The 206139f7f9bSDimitry Andric /// strong heuristic will add a guard variables to functions that call alloca 207139f7f9bSDimitry Andric /// regardless of size, functions with any buffer regardless of type and size, 208139f7f9bSDimitry Andric /// functions with aggregates that contain any buffer regardless of type and 209139f7f9bSDimitry Andric /// size, and functions that contain stack-based variables that have had their 210139f7f9bSDimitry Andric /// address taken. 211139f7f9bSDimitry Andric bool StackProtector::RequiresStackProtector() { 212139f7f9bSDimitry Andric bool Strong = false; 213f785676fSDimitry Andric bool NeedsProtector = false; 2143ca95b02SDimitry Andric for (const BasicBlock &BB : *F) 2153ca95b02SDimitry Andric for (const Instruction &I : BB) 2163ca95b02SDimitry Andric if (const CallInst *CI = dyn_cast<CallInst>(&I)) 2173ca95b02SDimitry Andric if (CI->getCalledFunction() == 2183ca95b02SDimitry Andric Intrinsic::getDeclaration(F->getParent(), 2193ca95b02SDimitry Andric Intrinsic::stackprotector)) 2203ca95b02SDimitry Andric HasPrologue = true; 2213ca95b02SDimitry Andric 2223ca95b02SDimitry Andric if (F->hasFnAttribute(Attribute::SafeStack)) 2233ca95b02SDimitry Andric return false; 2243ca95b02SDimitry Andric 225ff0cc061SDimitry Andric if (F->hasFnAttribute(Attribute::StackProtectReq)) { 226f785676fSDimitry Andric NeedsProtector = true; 227f785676fSDimitry Andric Strong = true; // Use the same heuristic as strong to determine SSPLayout 228ff0cc061SDimitry Andric } else if (F->hasFnAttribute(Attribute::StackProtectStrong)) 229139f7f9bSDimitry Andric Strong = true; 2303ca95b02SDimitry Andric else if (HasPrologue) 2313ca95b02SDimitry Andric NeedsProtector = true; 232ff0cc061SDimitry Andric else if (!F->hasFnAttribute(Attribute::StackProtect)) 233f22ef01cSRoman Divacky return false; 234f22ef01cSRoman Divacky 23539d628a0SDimitry Andric for (const BasicBlock &BB : *F) { 23639d628a0SDimitry Andric for (const Instruction &I : BB) { 23739d628a0SDimitry Andric if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 238139f7f9bSDimitry Andric if (AI->isArrayAllocation()) { 23939d628a0SDimitry Andric if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) { 240f785676fSDimitry Andric if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) { 241139f7f9bSDimitry Andric // A call to alloca with size >= SSPBufferSize requires 242139f7f9bSDimitry Andric // stack protectors. 243f785676fSDimitry Andric Layout.insert(std::make_pair(AI, SSPLK_LargeArray)); 244f785676fSDimitry Andric NeedsProtector = true; 245f785676fSDimitry Andric } else if (Strong) { 246f785676fSDimitry Andric // Require protectors for all alloca calls in strong mode. 247f785676fSDimitry Andric Layout.insert(std::make_pair(AI, SSPLK_SmallArray)); 248f785676fSDimitry Andric NeedsProtector = true; 249f785676fSDimitry Andric } 250f785676fSDimitry Andric } else { 251f785676fSDimitry Andric // A call to alloca with a variable size requires protectors. 252f785676fSDimitry Andric Layout.insert(std::make_pair(AI, SSPLK_LargeArray)); 253f785676fSDimitry Andric NeedsProtector = true; 254f785676fSDimitry Andric } 255f785676fSDimitry Andric continue; 256139f7f9bSDimitry Andric } 257139f7f9bSDimitry Andric 258f785676fSDimitry Andric bool IsLarge = false; 259f785676fSDimitry Andric if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) { 260f785676fSDimitry Andric Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray 261f785676fSDimitry Andric : SSPLK_SmallArray)); 262f785676fSDimitry Andric NeedsProtector = true; 263f785676fSDimitry Andric continue; 264f785676fSDimitry Andric } 265139f7f9bSDimitry Andric 266139f7f9bSDimitry Andric if (Strong && HasAddressTaken(AI)) { 267139f7f9bSDimitry Andric ++NumAddrTaken; 268f785676fSDimitry Andric Layout.insert(std::make_pair(AI, SSPLK_AddrOf)); 269f785676fSDimitry Andric NeedsProtector = true; 270139f7f9bSDimitry Andric } 271139f7f9bSDimitry Andric } 272f22ef01cSRoman Divacky } 273f22ef01cSRoman Divacky } 274f22ef01cSRoman Divacky 275f785676fSDimitry Andric return NeedsProtector; 276f785676fSDimitry Andric } 277f785676fSDimitry Andric 2783ca95b02SDimitry Andric /// Create a stack guard loading and populate whether SelectionDAG SSP is 2793ca95b02SDimitry Andric /// supported. 2803ca95b02SDimitry Andric static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M, 2813ca95b02SDimitry Andric IRBuilder<> &B, 2823ca95b02SDimitry Andric bool *SupportsSelectionDAGSP = nullptr) { 2833ca95b02SDimitry Andric if (Value *Guard = TLI->getIRStackGuard(B)) 2843ca95b02SDimitry Andric return B.CreateLoad(Guard, true, "StackGuard"); 285f785676fSDimitry Andric 2863ca95b02SDimitry Andric // Use SelectionDAG SSP handling, since there isn't an IR guard. 287f785676fSDimitry Andric // 2883ca95b02SDimitry Andric // This is more or less weird, since we optionally output whether we 2893ca95b02SDimitry Andric // should perform a SelectionDAG SP here. The reason is that it's strictly 2903ca95b02SDimitry Andric // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also 2913ca95b02SDimitry Andric // mutating. There is no way to get this bit without mutating the IR, so 2923ca95b02SDimitry Andric // getting this bit has to happen in this right time. 293f785676fSDimitry Andric // 2943ca95b02SDimitry Andric // We could have define a new function TLI::supportsSelectionDAGSP(), but that 2953ca95b02SDimitry Andric // will put more burden on the backends' overriding work, especially when it 2963ca95b02SDimitry Andric // actually conveys the same information getIRStackGuard() already gives. 2973ca95b02SDimitry Andric if (SupportsSelectionDAGSP) 2983ca95b02SDimitry Andric *SupportsSelectionDAGSP = true; 2993ca95b02SDimitry Andric TLI->insertSSPDeclarations(*M); 3003ca95b02SDimitry Andric return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard)); 301f785676fSDimitry Andric } 302f785676fSDimitry Andric 3033ca95b02SDimitry Andric /// Insert code into the entry block that stores the stack guard 304f785676fSDimitry Andric /// variable onto the stack: 305f785676fSDimitry Andric /// 306f785676fSDimitry Andric /// entry: 307f785676fSDimitry Andric /// StackGuardSlot = alloca i8* 3083ca95b02SDimitry Andric /// StackGuard = <stack guard> 3093ca95b02SDimitry Andric /// call void @llvm.stackprotector(StackGuard, StackGuardSlot) 310f785676fSDimitry Andric /// 311f785676fSDimitry Andric /// Returns true if the platform/triple supports the stackprotectorcreate pseudo 312f785676fSDimitry Andric /// node. 313f785676fSDimitry Andric static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI, 3143ca95b02SDimitry Andric const TargetLoweringBase *TLI, AllocaInst *&AI) { 315f785676fSDimitry Andric bool SupportsSelectionDAGSP = false; 316f785676fSDimitry Andric IRBuilder<> B(&F->getEntryBlock().front()); 3173ca95b02SDimitry Andric PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext()); 31891bc56edSDimitry Andric AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot"); 319f785676fSDimitry Andric 3203ca95b02SDimitry Andric Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP); 3213ca95b02SDimitry Andric B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), 3223ca95b02SDimitry Andric {GuardSlot, AI}); 323f785676fSDimitry Andric return SupportsSelectionDAGSP; 324f22ef01cSRoman Divacky } 325f22ef01cSRoman Divacky 326f22ef01cSRoman Divacky /// InsertStackProtectors - Insert code into the prologue and epilogue of the 327f22ef01cSRoman Divacky /// function. 328f22ef01cSRoman Divacky /// 329f22ef01cSRoman Divacky /// - The prologue code loads and stores the stack guard onto the stack. 330f22ef01cSRoman Divacky /// - The epilogue checks the value stored in the prologue against the original 331f22ef01cSRoman Divacky /// value. It calls __stack_chk_fail if they differ. 332f22ef01cSRoman Divacky bool StackProtector::InsertStackProtectors() { 333f785676fSDimitry Andric bool SupportsSelectionDAGSP = 334f785676fSDimitry Andric EnableSelectionDAGSP && !TM->Options.EnableFastISel; 33591bc56edSDimitry Andric AllocaInst *AI = nullptr; // Place on stack that stores the stack guard. 336f22ef01cSRoman Divacky 337f22ef01cSRoman Divacky for (Function::iterator I = F->begin(), E = F->end(); I != E;) { 3387d523365SDimitry Andric BasicBlock *BB = &*I++; 339f22ef01cSRoman Divacky ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); 340f785676fSDimitry Andric if (!RI) 341f785676fSDimitry Andric continue; 342f22ef01cSRoman Divacky 3433ca95b02SDimitry Andric // Generate prologue instrumentation if not already generated. 344f785676fSDimitry Andric if (!HasPrologue) { 345f785676fSDimitry Andric HasPrologue = true; 3463ca95b02SDimitry Andric SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI); 347f785676fSDimitry Andric } 348ffd1746dSEd Schouten 3493ca95b02SDimitry Andric // SelectionDAG based code generation. Nothing else needs to be done here. 3503ca95b02SDimitry Andric // The epilogue instrumentation is postponed to SelectionDAG. 3513ca95b02SDimitry Andric if (SupportsSelectionDAGSP) 3523ca95b02SDimitry Andric break; 353f22ef01cSRoman Divacky 3543ca95b02SDimitry Andric // Set HasIRCheck to true, so that SelectionDAG will not generate its own 3553ca95b02SDimitry Andric // version. SelectionDAG called 'shouldEmitSDCheck' to check whether 3563ca95b02SDimitry Andric // instrumentation has already been generated. 3573ca95b02SDimitry Andric HasIRCheck = true; 3583ca95b02SDimitry Andric 3593ca95b02SDimitry Andric // Generate epilogue instrumentation. The epilogue intrumentation can be 3603ca95b02SDimitry Andric // function-based or inlined depending on which mechanism the target is 3613ca95b02SDimitry Andric // providing. 3623ca95b02SDimitry Andric if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) { 3633ca95b02SDimitry Andric // Generate the function-based epilogue instrumentation. 3643ca95b02SDimitry Andric // The target provides a guard check function, generate a call to it. 3653ca95b02SDimitry Andric IRBuilder<> B(RI); 3663ca95b02SDimitry Andric LoadInst *Guard = B.CreateLoad(AI, true, "Guard"); 3673ca95b02SDimitry Andric CallInst *Call = B.CreateCall(GuardCheck, {Guard}); 3683ca95b02SDimitry Andric llvm::Function *Function = cast<llvm::Function>(GuardCheck); 3693ca95b02SDimitry Andric Call->setAttributes(Function->getAttributes()); 3703ca95b02SDimitry Andric Call->setCallingConv(Function->getCallingConv()); 371f785676fSDimitry Andric } else { 3723ca95b02SDimitry Andric // Generate the epilogue with inline instrumentation. 373f785676fSDimitry Andric // If we do not support SelectionDAG based tail calls, generate IR level 374f785676fSDimitry Andric // tail calls. 375f785676fSDimitry Andric // 376f22ef01cSRoman Divacky // For each block with a return instruction, convert this: 377f22ef01cSRoman Divacky // 378f22ef01cSRoman Divacky // return: 379f22ef01cSRoman Divacky // ... 380f22ef01cSRoman Divacky // ret ... 381f22ef01cSRoman Divacky // 382f22ef01cSRoman Divacky // into this: 383f22ef01cSRoman Divacky // 384f22ef01cSRoman Divacky // return: 385f22ef01cSRoman Divacky // ... 3863ca95b02SDimitry Andric // %1 = <stack guard> 387f22ef01cSRoman Divacky // %2 = load StackGuardSlot 388f22ef01cSRoman Divacky // %3 = cmp i1 %1, %2 389f22ef01cSRoman Divacky // br i1 %3, label %SP_return, label %CallStackCheckFailBlk 390f22ef01cSRoman Divacky // 391f22ef01cSRoman Divacky // SP_return: 392f22ef01cSRoman Divacky // ret ... 393f22ef01cSRoman Divacky // 394f22ef01cSRoman Divacky // CallStackCheckFailBlk: 395f22ef01cSRoman Divacky // call void @__stack_chk_fail() 396f22ef01cSRoman Divacky // unreachable 397f22ef01cSRoman Divacky 398f785676fSDimitry Andric // Create the FailBB. We duplicate the BB every time since the MI tail 399f785676fSDimitry Andric // merge pass will merge together all of the various BB into one including 400f785676fSDimitry Andric // fail BB generated by the stack protector pseudo instruction. 401f785676fSDimitry Andric BasicBlock *FailBB = CreateFailBB(); 402f785676fSDimitry Andric 403f22ef01cSRoman Divacky // Split the basic block before the return instruction. 4047d523365SDimitry Andric BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return"); 4053b0f4066SDimitry Andric 406f785676fSDimitry Andric // Update the dominator tree if we need to. 4073b0f4066SDimitry Andric if (DT && DT->isReachableFromEntry(BB)) { 4083b0f4066SDimitry Andric DT->addNewBlock(NewBB, BB); 409f785676fSDimitry Andric DT->addNewBlock(FailBB, BB); 4102754fe60SDimitry Andric } 411f22ef01cSRoman Divacky 412f22ef01cSRoman Divacky // Remove default branch instruction to the new BB. 413f22ef01cSRoman Divacky BB->getTerminator()->eraseFromParent(); 414f22ef01cSRoman Divacky 415f785676fSDimitry Andric // Move the newly created basic block to the point right after the old 416f785676fSDimitry Andric // basic block so that it's in the "fall through" position. 417f22ef01cSRoman Divacky NewBB->moveAfter(BB); 418f22ef01cSRoman Divacky 419f22ef01cSRoman Divacky // Generate the stack protector instructions in the old basic block. 420f785676fSDimitry Andric IRBuilder<> B(BB); 4213ca95b02SDimitry Andric Value *Guard = getStackGuard(TLI, M, B); 4223ca95b02SDimitry Andric LoadInst *LI2 = B.CreateLoad(AI, true); 4233ca95b02SDimitry Andric Value *Cmp = B.CreateICmpEQ(Guard, LI2); 4247d523365SDimitry Andric auto SuccessProb = 4257d523365SDimitry Andric BranchProbabilityInfo::getBranchProbStackProtector(true); 4267d523365SDimitry Andric auto FailureProb = 4277d523365SDimitry Andric BranchProbabilityInfo::getBranchProbStackProtector(false); 42839d628a0SDimitry Andric MDNode *Weights = MDBuilder(F->getContext()) 4297d523365SDimitry Andric .createBranchWeights(SuccessProb.getNumerator(), 4307d523365SDimitry Andric FailureProb.getNumerator()); 43139d628a0SDimitry Andric B.CreateCondBr(Cmp, NewBB, FailBB, Weights); 432f785676fSDimitry Andric } 433f22ef01cSRoman Divacky } 434f22ef01cSRoman Divacky 43539d628a0SDimitry Andric // Return if we didn't modify any basic blocks. i.e., there are no return 436f22ef01cSRoman Divacky // statements in the function. 4377d523365SDimitry Andric return HasPrologue; 438f22ef01cSRoman Divacky } 439f22ef01cSRoman Divacky 440f22ef01cSRoman Divacky /// CreateFailBB - Create a basic block to jump to when the stack protector 441f22ef01cSRoman Divacky /// check fails. 442f22ef01cSRoman Divacky BasicBlock *StackProtector::CreateFailBB() { 443f785676fSDimitry Andric LLVMContext &Context = F->getContext(); 444f785676fSDimitry Andric BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F); 445f785676fSDimitry Andric IRBuilder<> B(FailBB); 4463ca95b02SDimitry Andric B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram())); 44739d628a0SDimitry Andric if (Trip.isOSOpenBSD()) { 44839d628a0SDimitry Andric Constant *StackChkFail = 44939d628a0SDimitry Andric M->getOrInsertFunction("__stack_smash_handler", 45039d628a0SDimitry Andric Type::getVoidTy(Context), 45139d628a0SDimitry Andric Type::getInt8PtrTy(Context), nullptr); 452f785676fSDimitry Andric 453f785676fSDimitry Andric B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH")); 454f785676fSDimitry Andric } else { 45539d628a0SDimitry Andric Constant *StackChkFail = 45639d628a0SDimitry Andric M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context), 45739d628a0SDimitry Andric nullptr); 458ff0cc061SDimitry Andric B.CreateCall(StackChkFail, {}); 459f785676fSDimitry Andric } 460f785676fSDimitry Andric B.CreateUnreachable(); 461f22ef01cSRoman Divacky return FailBB; 462f22ef01cSRoman Divacky } 4633ca95b02SDimitry Andric 4643ca95b02SDimitry Andric bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const { 4653ca95b02SDimitry Andric return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator()); 4663ca95b02SDimitry Andric } 467