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