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