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