1 //===- StackProtector.cpp - Stack Protector Insertion ---------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass inserts stack protectors into functions which need them. A variable 11 // with a random value in it is stored onto the stack before the local variables 12 // are allocated. Upon exiting the block, the stored value is checked. If it's 13 // changed, then there was some sort of violation and the program aborts. 14 // 15 //===----------------------------------------------------------------------===// 16 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/OptimizationDiagnosticInfo.h" 22 #include "llvm/CodeGen/Passes.h" 23 #include "llvm/CodeGen/StackProtector.h" 24 #include "llvm/IR/Attributes.h" 25 #include "llvm/IR/BasicBlock.h" 26 #include "llvm/IR/Constants.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/DebugInfo.h" 29 #include "llvm/IR/DebugLoc.h" 30 #include "llvm/IR/DerivedTypes.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/IRBuilder.h" 33 #include "llvm/IR/Instruction.h" 34 #include "llvm/IR/Instructions.h" 35 #include "llvm/IR/Intrinsics.h" 36 #include "llvm/IR/MDBuilder.h" 37 #include "llvm/IR/Module.h" 38 #include "llvm/IR/Type.h" 39 #include "llvm/IR/User.h" 40 #include "llvm/Pass.h" 41 #include "llvm/Support/Casting.h" 42 #include "llvm/Support/CommandLine.h" 43 #include "llvm/Target/TargetLowering.h" 44 #include "llvm/Target/TargetMachine.h" 45 #include "llvm/Target/TargetOptions.h" 46 #include "llvm/Target/TargetSubtargetInfo.h" 47 #include <utility> 48 49 using namespace llvm; 50 51 #define DEBUG_TYPE "stack-protector" 52 53 STATISTIC(NumFunProtected, "Number of functions protected"); 54 STATISTIC(NumAddrTaken, "Number of local variables that have their address" 55 " taken."); 56 57 static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp", 58 cl::init(true), cl::Hidden); 59 60 char StackProtector::ID = 0; 61 INITIALIZE_TM_PASS(StackProtector, "stack-protector", "Insert stack protectors", 62 false, true) 63 64 FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) { 65 return new StackProtector(TM); 66 } 67 68 StackProtector::SSPLayoutKind 69 StackProtector::getSSPLayout(const AllocaInst *AI) const { 70 return AI ? Layout.lookup(AI) : SSPLK_None; 71 } 72 73 void StackProtector::adjustForColoring(const AllocaInst *From, 74 const AllocaInst *To) { 75 // When coloring replaces one alloca with another, transfer the SSPLayoutKind 76 // tag from the remapped to the target alloca. The remapped alloca should 77 // have a size smaller than or equal to the replacement alloca. 78 SSPLayoutMap::iterator I = Layout.find(From); 79 if (I != Layout.end()) { 80 SSPLayoutKind Kind = I->second; 81 Layout.erase(I); 82 83 // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite 84 // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that 85 // SSPLK_SmallArray does not overwrite SSPLK_LargeArray. 86 I = Layout.find(To); 87 if (I == Layout.end()) 88 Layout.insert(std::make_pair(To, Kind)); 89 else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf) 90 I->second = Kind; 91 } 92 } 93 94 bool StackProtector::runOnFunction(Function &Fn) { 95 F = &Fn; 96 M = F->getParent(); 97 DominatorTreeWrapperPass *DTWP = 98 getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 99 DT = DTWP ? &DTWP->getDomTree() : nullptr; 100 TLI = TM->getSubtargetImpl(Fn)->getTargetLowering(); 101 HasPrologue = false; 102 HasIRCheck = false; 103 104 Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size"); 105 if (Attr.isStringAttribute() && 106 Attr.getValueAsString().getAsInteger(10, SSPBufferSize)) 107 return false; // Invalid integer string 108 109 if (!RequiresStackProtector()) 110 return false; 111 112 // TODO(etienneb): Functions with funclets are not correctly supported now. 113 // Do nothing if this is funclet-based personality. 114 if (Fn.hasPersonalityFn()) { 115 EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn()); 116 if (isFuncletEHPersonality(Personality)) 117 return false; 118 } 119 120 ++NumFunProtected; 121 return InsertStackProtectors(); 122 } 123 124 /// \param [out] IsLarge is set to true if a protectable array is found and 125 /// it is "large" ( >= ssp-buffer-size). In the case of a structure with 126 /// multiple arrays, this gets set if any of them is large. 127 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge, 128 bool Strong, 129 bool InStruct) const { 130 if (!Ty) 131 return false; 132 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 133 if (!AT->getElementType()->isIntegerTy(8)) { 134 // If we're on a non-Darwin platform or we're inside of a structure, don't 135 // add stack protectors unless the array is a character array. 136 // However, in strong mode any array, regardless of type and size, 137 // triggers a protector. 138 if (!Strong && (InStruct || !Trip.isOSDarwin())) 139 return false; 140 } 141 142 // If an array has more than SSPBufferSize bytes of allocated space, then we 143 // emit stack protectors. 144 if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) { 145 IsLarge = true; 146 return true; 147 } 148 149 if (Strong) 150 // Require a protector for all arrays in strong mode 151 return true; 152 } 153 154 const StructType *ST = dyn_cast<StructType>(Ty); 155 if (!ST) 156 return false; 157 158 bool NeedsProtector = false; 159 for (StructType::element_iterator I = ST->element_begin(), 160 E = ST->element_end(); 161 I != E; ++I) 162 if (ContainsProtectableArray(*I, IsLarge, Strong, true)) { 163 // If the element is a protectable array and is large (>= SSPBufferSize) 164 // then we are done. If the protectable array is not large, then 165 // keep looking in case a subsequent element is a large array. 166 if (IsLarge) 167 return true; 168 NeedsProtector = true; 169 } 170 171 return NeedsProtector; 172 } 173 174 bool StackProtector::HasAddressTaken(const Instruction *AI) { 175 for (const User *U : AI->users()) { 176 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) { 177 if (AI == SI->getValueOperand()) 178 return true; 179 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) { 180 if (AI == SI->getOperand(0)) 181 return true; 182 } else if (isa<CallInst>(U)) { 183 return true; 184 } else if (isa<InvokeInst>(U)) { 185 return true; 186 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) { 187 if (HasAddressTaken(SI)) 188 return true; 189 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) { 190 // Keep track of what PHI nodes we have already visited to ensure 191 // they are only visited once. 192 if (VisitedPHIs.insert(PN).second) 193 if (HasAddressTaken(PN)) 194 return true; 195 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) { 196 if (HasAddressTaken(GEP)) 197 return true; 198 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) { 199 if (HasAddressTaken(BI)) 200 return true; 201 } 202 } 203 return false; 204 } 205 206 /// \brief Check whether or not this function needs a stack protector based 207 /// upon the stack protector level. 208 /// 209 /// We use two heuristics: a standard (ssp) and strong (sspstrong). 210 /// The standard heuristic which will add a guard variable to functions that 211 /// call alloca with a either a variable size or a size >= SSPBufferSize, 212 /// functions with character buffers larger than SSPBufferSize, and functions 213 /// with aggregates containing character buffers larger than SSPBufferSize. The 214 /// strong heuristic will add a guard variables to functions that call alloca 215 /// regardless of size, functions with any buffer regardless of type and size, 216 /// functions with aggregates that contain any buffer regardless of type and 217 /// size, and functions that contain stack-based variables that have had their 218 /// address taken. 219 bool StackProtector::RequiresStackProtector() { 220 bool Strong = false; 221 bool NeedsProtector = false; 222 for (const BasicBlock &BB : *F) 223 for (const Instruction &I : BB) 224 if (const CallInst *CI = dyn_cast<CallInst>(&I)) 225 if (CI->getCalledFunction() == 226 Intrinsic::getDeclaration(F->getParent(), 227 Intrinsic::stackprotector)) 228 HasPrologue = true; 229 230 if (F->hasFnAttribute(Attribute::SafeStack)) 231 return false; 232 233 // We are constructing the OptimizationRemarkEmitter on the fly rather than 234 // using the analysis pass to avoid building DominatorTree and LoopInfo which 235 // are not available this late in the IR pipeline. 236 OptimizationRemarkEmitter ORE(F); 237 auto ReasonStub = 238 Twine("Stack protection applied to function " + F->getName() + " due to ") 239 .str(); 240 241 if (F->hasFnAttribute(Attribute::StackProtectReq)) { 242 ORE.emit(OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F) 243 << ReasonStub << "a function attribute or command-line switch"); 244 NeedsProtector = true; 245 Strong = true; // Use the same heuristic as strong to determine SSPLayout 246 } else if (F->hasFnAttribute(Attribute::StackProtectStrong)) 247 Strong = true; 248 else if (HasPrologue) 249 NeedsProtector = true; 250 else if (!F->hasFnAttribute(Attribute::StackProtect)) 251 return false; 252 253 for (const BasicBlock &BB : *F) { 254 for (const Instruction &I : BB) { 255 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 256 if (AI->isArrayAllocation()) { 257 OptimizationRemark Remark(DEBUG_TYPE, "StackProtectorAllocaOrArray", 258 &I); 259 Remark << ReasonStub 260 << "a call to alloca or use of a variable length array"; 261 if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) { 262 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) { 263 // A call to alloca with size >= SSPBufferSize requires 264 // stack protectors. 265 Layout.insert(std::make_pair(AI, SSPLK_LargeArray)); 266 ORE.emit(Remark); 267 NeedsProtector = true; 268 } else if (Strong) { 269 // Require protectors for all alloca calls in strong mode. 270 Layout.insert(std::make_pair(AI, SSPLK_SmallArray)); 271 ORE.emit(Remark); 272 NeedsProtector = true; 273 } 274 } else { 275 // A call to alloca with a variable size requires protectors. 276 Layout.insert(std::make_pair(AI, SSPLK_LargeArray)); 277 ORE.emit(Remark); 278 NeedsProtector = true; 279 } 280 continue; 281 } 282 283 bool IsLarge = false; 284 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) { 285 Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray 286 : SSPLK_SmallArray)); 287 ORE.emit(OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I) 288 << ReasonStub 289 << "a stack allocated buffer or struct containing a buffer"); 290 NeedsProtector = true; 291 continue; 292 } 293 294 if (Strong && HasAddressTaken(AI)) { 295 ++NumAddrTaken; 296 Layout.insert(std::make_pair(AI, SSPLK_AddrOf)); 297 ORE.emit( 298 OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken", &I) 299 << ReasonStub << "the address of a local variable being taken"); 300 NeedsProtector = true; 301 } 302 } 303 } 304 } 305 306 return NeedsProtector; 307 } 308 309 /// Create a stack guard loading and populate whether SelectionDAG SSP is 310 /// supported. 311 static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M, 312 IRBuilder<> &B, 313 bool *SupportsSelectionDAGSP = nullptr) { 314 if (Value *Guard = TLI->getIRStackGuard(B)) 315 return B.CreateLoad(Guard, true, "StackGuard"); 316 317 // Use SelectionDAG SSP handling, since there isn't an IR guard. 318 // 319 // This is more or less weird, since we optionally output whether we 320 // should perform a SelectionDAG SP here. The reason is that it's strictly 321 // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also 322 // mutating. There is no way to get this bit without mutating the IR, so 323 // getting this bit has to happen in this right time. 324 // 325 // We could have define a new function TLI::supportsSelectionDAGSP(), but that 326 // will put more burden on the backends' overriding work, especially when it 327 // actually conveys the same information getIRStackGuard() already gives. 328 if (SupportsSelectionDAGSP) 329 *SupportsSelectionDAGSP = true; 330 TLI->insertSSPDeclarations(*M); 331 return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard)); 332 } 333 334 /// Insert code into the entry block that stores the stack guard 335 /// variable onto the stack: 336 /// 337 /// entry: 338 /// StackGuardSlot = alloca i8* 339 /// StackGuard = <stack guard> 340 /// call void @llvm.stackprotector(StackGuard, StackGuardSlot) 341 /// 342 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo 343 /// node. 344 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI, 345 const TargetLoweringBase *TLI, AllocaInst *&AI) { 346 bool SupportsSelectionDAGSP = false; 347 IRBuilder<> B(&F->getEntryBlock().front()); 348 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext()); 349 AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot"); 350 351 Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP); 352 B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), 353 {GuardSlot, AI}); 354 return SupportsSelectionDAGSP; 355 } 356 357 /// InsertStackProtectors - Insert code into the prologue and epilogue of the 358 /// function. 359 /// 360 /// - The prologue code loads and stores the stack guard onto the stack. 361 /// - The epilogue checks the value stored in the prologue against the original 362 /// value. It calls __stack_chk_fail if they differ. 363 bool StackProtector::InsertStackProtectors() { 364 bool SupportsSelectionDAGSP = 365 EnableSelectionDAGSP && !TM->Options.EnableFastISel; 366 AllocaInst *AI = nullptr; // Place on stack that stores the stack guard. 367 368 for (Function::iterator I = F->begin(), E = F->end(); I != E;) { 369 BasicBlock *BB = &*I++; 370 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); 371 if (!RI) 372 continue; 373 374 // Generate prologue instrumentation if not already generated. 375 if (!HasPrologue) { 376 HasPrologue = true; 377 SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI); 378 } 379 380 // SelectionDAG based code generation. Nothing else needs to be done here. 381 // The epilogue instrumentation is postponed to SelectionDAG. 382 if (SupportsSelectionDAGSP) 383 break; 384 385 // Set HasIRCheck to true, so that SelectionDAG will not generate its own 386 // version. SelectionDAG called 'shouldEmitSDCheck' to check whether 387 // instrumentation has already been generated. 388 HasIRCheck = true; 389 390 // Generate epilogue instrumentation. The epilogue intrumentation can be 391 // function-based or inlined depending on which mechanism the target is 392 // providing. 393 if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) { 394 // Generate the function-based epilogue instrumentation. 395 // The target provides a guard check function, generate a call to it. 396 IRBuilder<> B(RI); 397 LoadInst *Guard = B.CreateLoad(AI, true, "Guard"); 398 CallInst *Call = B.CreateCall(GuardCheck, {Guard}); 399 llvm::Function *Function = cast<llvm::Function>(GuardCheck); 400 Call->setAttributes(Function->getAttributes()); 401 Call->setCallingConv(Function->getCallingConv()); 402 } else { 403 // Generate the epilogue with inline instrumentation. 404 // If we do not support SelectionDAG based tail calls, generate IR level 405 // tail calls. 406 // 407 // For each block with a return instruction, convert this: 408 // 409 // return: 410 // ... 411 // ret ... 412 // 413 // into this: 414 // 415 // return: 416 // ... 417 // %1 = <stack guard> 418 // %2 = load StackGuardSlot 419 // %3 = cmp i1 %1, %2 420 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk 421 // 422 // SP_return: 423 // ret ... 424 // 425 // CallStackCheckFailBlk: 426 // call void @__stack_chk_fail() 427 // unreachable 428 429 // Create the FailBB. We duplicate the BB every time since the MI tail 430 // merge pass will merge together all of the various BB into one including 431 // fail BB generated by the stack protector pseudo instruction. 432 BasicBlock *FailBB = CreateFailBB(); 433 434 // Split the basic block before the return instruction. 435 BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return"); 436 437 // Update the dominator tree if we need to. 438 if (DT && DT->isReachableFromEntry(BB)) { 439 DT->addNewBlock(NewBB, BB); 440 DT->addNewBlock(FailBB, BB); 441 } 442 443 // Remove default branch instruction to the new BB. 444 BB->getTerminator()->eraseFromParent(); 445 446 // Move the newly created basic block to the point right after the old 447 // basic block so that it's in the "fall through" position. 448 NewBB->moveAfter(BB); 449 450 // Generate the stack protector instructions in the old basic block. 451 IRBuilder<> B(BB); 452 Value *Guard = getStackGuard(TLI, M, B); 453 LoadInst *LI2 = B.CreateLoad(AI, true); 454 Value *Cmp = B.CreateICmpEQ(Guard, LI2); 455 auto SuccessProb = 456 BranchProbabilityInfo::getBranchProbStackProtector(true); 457 auto FailureProb = 458 BranchProbabilityInfo::getBranchProbStackProtector(false); 459 MDNode *Weights = MDBuilder(F->getContext()) 460 .createBranchWeights(SuccessProb.getNumerator(), 461 FailureProb.getNumerator()); 462 B.CreateCondBr(Cmp, NewBB, FailBB, Weights); 463 } 464 } 465 466 // Return if we didn't modify any basic blocks. i.e., there are no return 467 // statements in the function. 468 return HasPrologue; 469 } 470 471 /// CreateFailBB - Create a basic block to jump to when the stack protector 472 /// check fails. 473 BasicBlock *StackProtector::CreateFailBB() { 474 LLVMContext &Context = F->getContext(); 475 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F); 476 IRBuilder<> B(FailBB); 477 B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram())); 478 if (Trip.isOSOpenBSD()) { 479 Constant *StackChkFail = 480 M->getOrInsertFunction("__stack_smash_handler", 481 Type::getVoidTy(Context), 482 Type::getInt8PtrTy(Context), nullptr); 483 484 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH")); 485 } else { 486 Constant *StackChkFail = 487 M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context), 488 nullptr); 489 B.CreateCall(StackChkFail, {}); 490 } 491 B.CreateUnreachable(); 492 return FailBB; 493 } 494 495 bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const { 496 return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator()); 497 } 498