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