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