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 #define DEBUG_TYPE "stack-protector" 18 #include "llvm/CodeGen/StackProtector.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/ValueTracking.h" 22 #include "llvm/CodeGen/Analysis.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/DerivedTypes.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/GlobalValue.h" 30 #include "llvm/IR/GlobalVariable.h" 31 #include "llvm/IR/IRBuilder.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/Intrinsics.h" 35 #include "llvm/IR/Module.h" 36 #include "llvm/Support/CommandLine.h" 37 #include <cstdlib> 38 using namespace llvm; 39 40 STATISTIC(NumFunProtected, "Number of functions protected"); 41 STATISTIC(NumAddrTaken, "Number of local variables that have their address" 42 " taken."); 43 44 static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp", 45 cl::init(true), cl::Hidden); 46 47 char StackProtector::ID = 0; 48 INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors", 49 false, true) 50 51 FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) { 52 return new StackProtector(TM); 53 } 54 55 StackProtector::SSPLayoutKind 56 StackProtector::getSSPLayout(const AllocaInst *AI) const { 57 return AI ? Layout.lookup(AI) : SSPLK_None; 58 } 59 60 void StackProtector::adjustForColoring(const AllocaInst *From, 61 const AllocaInst *To) { 62 // When coloring replaces one alloca with another, transfer the SSPLayoutKind 63 // tag from the remapped to the target alloca. The remapped alloca should 64 // have a size smaller than or equal to the replacement alloca. 65 SSPLayoutMap::iterator I = Layout.find(From); 66 if (I != Layout.end()) { 67 SSPLayoutKind Kind = I->second; 68 Layout.erase(I); 69 70 // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite 71 // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that 72 // SSPLK_SmallArray does not overwrite SSPLK_LargeArray. 73 I = Layout.find(To); 74 if (I == Layout.end()) 75 Layout.insert(std::make_pair(To, Kind)); 76 else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf) 77 I->second = Kind; 78 } 79 } 80 81 bool StackProtector::runOnFunction(Function &Fn) { 82 F = &Fn; 83 M = F->getParent(); 84 DominatorTreeWrapperPass *DTWP = 85 getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 86 DT = DTWP ? &DTWP->getDomTree() : 0; 87 TLI = TM->getTargetLowering(); 88 89 if (!RequiresStackProtector()) 90 return false; 91 92 Attribute Attr = Fn.getAttributes().getAttribute( 93 AttributeSet::FunctionIndex, "stack-protector-buffer-size"); 94 if (Attr.isStringAttribute()) 95 Attr.getValueAsString().getAsInteger(10, SSPBufferSize); 96 97 ++NumFunProtected; 98 return InsertStackProtectors(); 99 } 100 101 /// \param [out] IsLarge is set to true if a protectable array is found and 102 /// it is "large" ( >= ssp-buffer-size). In the case of a structure with 103 /// multiple arrays, this gets set if any of them is large. 104 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge, 105 bool Strong, 106 bool InStruct) const { 107 if (!Ty) 108 return false; 109 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 110 if (!AT->getElementType()->isIntegerTy(8)) { 111 // If we're on a non-Darwin platform or we're inside of a structure, don't 112 // add stack protectors unless the array is a character array. 113 // However, in strong mode any array, regardless of type and size, 114 // triggers a protector. 115 if (!Strong && (InStruct || !Trip.isOSDarwin())) 116 return false; 117 } 118 119 // If an array has more than SSPBufferSize bytes of allocated space, then we 120 // emit stack protectors. 121 if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT)) { 122 IsLarge = true; 123 return true; 124 } 125 126 if (Strong) 127 // Require a protector for all arrays in strong mode 128 return true; 129 } 130 131 const StructType *ST = dyn_cast<StructType>(Ty); 132 if (!ST) 133 return false; 134 135 bool NeedsProtector = false; 136 for (StructType::element_iterator I = ST->element_begin(), 137 E = ST->element_end(); 138 I != E; ++I) 139 if (ContainsProtectableArray(*I, IsLarge, Strong, true)) { 140 // If the element is a protectable array and is large (>= SSPBufferSize) 141 // then we are done. If the protectable array is not large, then 142 // keep looking in case a subsequent element is a large array. 143 if (IsLarge) 144 return true; 145 NeedsProtector = true; 146 } 147 148 return NeedsProtector; 149 } 150 151 bool StackProtector::HasAddressTaken(const Instruction *AI) { 152 for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end(); 153 UI != UE; ++UI) { 154 const User *U = *UI; 155 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) { 156 if (AI == SI->getValueOperand()) 157 return true; 158 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) { 159 if (AI == SI->getOperand(0)) 160 return true; 161 } else if (isa<CallInst>(U)) { 162 return true; 163 } else if (isa<InvokeInst>(U)) { 164 return true; 165 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) { 166 if (HasAddressTaken(SI)) 167 return true; 168 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) { 169 // Keep track of what PHI nodes we have already visited to ensure 170 // they are only visited once. 171 if (VisitedPHIs.insert(PN)) 172 if (HasAddressTaken(PN)) 173 return true; 174 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) { 175 if (HasAddressTaken(GEP)) 176 return true; 177 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) { 178 if (HasAddressTaken(BI)) 179 return true; 180 } 181 } 182 return false; 183 } 184 185 /// \brief Check whether or not this function needs a stack protector based 186 /// upon the stack protector level. 187 /// 188 /// We use two heuristics: a standard (ssp) and strong (sspstrong). 189 /// The standard heuristic which will add a guard variable to functions that 190 /// call alloca with a either a variable size or a size >= SSPBufferSize, 191 /// functions with character buffers larger than SSPBufferSize, and functions 192 /// with aggregates containing character buffers larger than SSPBufferSize. The 193 /// strong heuristic will add a guard variables to functions that call alloca 194 /// regardless of size, functions with any buffer regardless of type and size, 195 /// functions with aggregates that contain any buffer regardless of type and 196 /// size, and functions that contain stack-based variables that have had their 197 /// address taken. 198 bool StackProtector::RequiresStackProtector() { 199 bool Strong = false; 200 bool NeedsProtector = false; 201 if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 202 Attribute::StackProtectReq)) { 203 NeedsProtector = true; 204 Strong = true; // Use the same heuristic as strong to determine SSPLayout 205 } else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 206 Attribute::StackProtectStrong)) 207 Strong = true; 208 else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 209 Attribute::StackProtect)) 210 return false; 211 212 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) { 213 BasicBlock *BB = I; 214 215 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; 216 ++II) { 217 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) { 218 if (AI->isArrayAllocation()) { 219 // SSP-Strong: Enable protectors for any call to alloca, regardless 220 // of size. 221 if (Strong) 222 return true; 223 224 if (const ConstantInt *CI = 225 dyn_cast<ConstantInt>(AI->getArraySize())) { 226 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) { 227 // A call to alloca with size >= SSPBufferSize requires 228 // stack protectors. 229 Layout.insert(std::make_pair(AI, SSPLK_LargeArray)); 230 NeedsProtector = true; 231 } else if (Strong) { 232 // Require protectors for all alloca calls in strong mode. 233 Layout.insert(std::make_pair(AI, SSPLK_SmallArray)); 234 NeedsProtector = true; 235 } 236 } else { 237 // A call to alloca with a variable size requires protectors. 238 Layout.insert(std::make_pair(AI, SSPLK_LargeArray)); 239 NeedsProtector = true; 240 } 241 continue; 242 } 243 244 bool IsLarge = false; 245 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) { 246 Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray 247 : SSPLK_SmallArray)); 248 NeedsProtector = true; 249 continue; 250 } 251 252 if (Strong && HasAddressTaken(AI)) { 253 ++NumAddrTaken; 254 Layout.insert(std::make_pair(AI, SSPLK_AddrOf)); 255 NeedsProtector = true; 256 } 257 } 258 } 259 } 260 261 return NeedsProtector; 262 } 263 264 static bool InstructionWillNotHaveChain(const Instruction *I) { 265 return !I->mayHaveSideEffects() && !I->mayReadFromMemory() && 266 isSafeToSpeculativelyExecute(I); 267 } 268 269 /// Identify if RI has a previous instruction in the "Tail Position" and return 270 /// it. Otherwise return 0. 271 /// 272 /// This is based off of the code in llvm::isInTailCallPosition. The difference 273 /// is that it inverts the first part of llvm::isInTailCallPosition since 274 /// isInTailCallPosition is checking if a call is in a tail call position, and 275 /// we are searching for an unknown tail call that might be in the tail call 276 /// position. Once we find the call though, the code uses the same refactored 277 /// code, returnTypeIsEligibleForTailCall. 278 static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI, 279 const TargetLoweringBase *TLI) { 280 // Establish a reasonable upper bound on the maximum amount of instructions we 281 // will look through to find a tail call. 282 unsigned SearchCounter = 0; 283 const unsigned MaxSearch = 4; 284 bool NoInterposingChain = true; 285 286 for (BasicBlock::reverse_iterator I = llvm::next(BB->rbegin()), 287 E = BB->rend(); 288 I != E && SearchCounter < MaxSearch; ++I) { 289 Instruction *Inst = &*I; 290 291 // Skip over debug intrinsics and do not allow them to affect our MaxSearch 292 // counter. 293 if (isa<DbgInfoIntrinsic>(Inst)) 294 continue; 295 296 // If we find a call and the following conditions are satisifed, then we 297 // have found a tail call that satisfies at least the target independent 298 // requirements of a tail call: 299 // 300 // 1. The call site has the tail marker. 301 // 302 // 2. The call site either will not cause the creation of a chain or if a 303 // chain is necessary there are no instructions in between the callsite and 304 // the call which would create an interposing chain. 305 // 306 // 3. The return type of the function does not impede tail call 307 // optimization. 308 if (CallInst *CI = dyn_cast<CallInst>(Inst)) { 309 if (CI->isTailCall() && 310 (InstructionWillNotHaveChain(CI) || NoInterposingChain) && 311 returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI)) 312 return CI; 313 } 314 315 // If we did not find a call see if we have an instruction that may create 316 // an interposing chain. 317 NoInterposingChain = 318 NoInterposingChain && InstructionWillNotHaveChain(Inst); 319 320 // Increment max search. 321 SearchCounter++; 322 } 323 324 return 0; 325 } 326 327 /// Insert code into the entry block that stores the __stack_chk_guard 328 /// variable onto the stack: 329 /// 330 /// entry: 331 /// StackGuardSlot = alloca i8* 332 /// StackGuard = load __stack_chk_guard 333 /// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot) 334 /// 335 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo 336 /// node. 337 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI, 338 const TargetLoweringBase *TLI, const Triple &Trip, 339 AllocaInst *&AI, Value *&StackGuardVar) { 340 bool SupportsSelectionDAGSP = false; 341 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext()); 342 unsigned AddressSpace, Offset; 343 if (TLI->getStackCookieLocation(AddressSpace, Offset)) { 344 Constant *OffsetVal = 345 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset); 346 347 StackGuardVar = ConstantExpr::getIntToPtr( 348 OffsetVal, PointerType::get(PtrTy, AddressSpace)); 349 } else if (Trip.getOS() == llvm::Triple::OpenBSD) { 350 StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy); 351 cast<GlobalValue>(StackGuardVar) 352 ->setVisibility(GlobalValue::HiddenVisibility); 353 } else { 354 SupportsSelectionDAGSP = true; 355 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy); 356 } 357 358 IRBuilder<> B(&F->getEntryBlock().front()); 359 AI = B.CreateAlloca(PtrTy, 0, "StackGuardSlot"); 360 LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard"); 361 B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI, 362 AI); 363 364 return SupportsSelectionDAGSP; 365 } 366 367 /// InsertStackProtectors - Insert code into the prologue and epilogue of the 368 /// function. 369 /// 370 /// - The prologue code loads and stores the stack guard onto the stack. 371 /// - The epilogue checks the value stored in the prologue against the original 372 /// value. It calls __stack_chk_fail if they differ. 373 bool StackProtector::InsertStackProtectors() { 374 bool HasPrologue = false; 375 bool SupportsSelectionDAGSP = 376 EnableSelectionDAGSP && !TM->Options.EnableFastISel; 377 AllocaInst *AI = 0; // Place on stack that stores the stack guard. 378 Value *StackGuardVar = 0; // The stack guard variable. 379 380 for (Function::iterator I = F->begin(), E = F->end(); I != E;) { 381 BasicBlock *BB = I++; 382 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); 383 if (!RI) 384 continue; 385 386 if (!HasPrologue) { 387 HasPrologue = true; 388 SupportsSelectionDAGSP &= 389 CreatePrologue(F, M, RI, TLI, Trip, AI, StackGuardVar); 390 } 391 392 if (SupportsSelectionDAGSP) { 393 // Since we have a potential tail call, insert the special stack check 394 // intrinsic. 395 Instruction *InsertionPt = 0; 396 if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) { 397 InsertionPt = CI; 398 } else { 399 InsertionPt = RI; 400 // At this point we know that BB has a return statement so it *DOES* 401 // have a terminator. 402 assert(InsertionPt != 0 && "BB must have a terminator instruction at " 403 "this point."); 404 } 405 406 Function *Intrinsic = 407 Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck); 408 CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt); 409 410 } else { 411 // If we do not support SelectionDAG based tail calls, generate IR level 412 // tail calls. 413 // 414 // For each block with a return instruction, convert this: 415 // 416 // return: 417 // ... 418 // ret ... 419 // 420 // into this: 421 // 422 // return: 423 // ... 424 // %1 = load __stack_chk_guard 425 // %2 = load StackGuardSlot 426 // %3 = cmp i1 %1, %2 427 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk 428 // 429 // SP_return: 430 // ret ... 431 // 432 // CallStackCheckFailBlk: 433 // call void @__stack_chk_fail() 434 // unreachable 435 436 // Create the FailBB. We duplicate the BB every time since the MI tail 437 // merge pass will merge together all of the various BB into one including 438 // fail BB generated by the stack protector pseudo instruction. 439 BasicBlock *FailBB = CreateFailBB(); 440 441 // Split the basic block before the return instruction. 442 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return"); 443 444 // Update the dominator tree if we need to. 445 if (DT && DT->isReachableFromEntry(BB)) { 446 DT->addNewBlock(NewBB, BB); 447 DT->addNewBlock(FailBB, BB); 448 } 449 450 // Remove default branch instruction to the new BB. 451 BB->getTerminator()->eraseFromParent(); 452 453 // Move the newly created basic block to the point right after the old 454 // basic block so that it's in the "fall through" position. 455 NewBB->moveAfter(BB); 456 457 // Generate the stack protector instructions in the old basic block. 458 IRBuilder<> B(BB); 459 LoadInst *LI1 = B.CreateLoad(StackGuardVar); 460 LoadInst *LI2 = B.CreateLoad(AI); 461 Value *Cmp = B.CreateICmpEQ(LI1, LI2); 462 B.CreateCondBr(Cmp, NewBB, FailBB); 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 if (!HasPrologue) 469 return false; 470 471 return true; 472 } 473 474 /// CreateFailBB - Create a basic block to jump to when the stack protector 475 /// check fails. 476 BasicBlock *StackProtector::CreateFailBB() { 477 LLVMContext &Context = F->getContext(); 478 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F); 479 IRBuilder<> B(FailBB); 480 if (Trip.getOS() == llvm::Triple::OpenBSD) { 481 Constant *StackChkFail = M->getOrInsertFunction( 482 "__stack_smash_handler", Type::getVoidTy(Context), 483 Type::getInt8PtrTy(Context), NULL); 484 485 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH")); 486 } else { 487 Constant *StackChkFail = M->getOrInsertFunction( 488 "__stack_chk_fail", Type::getVoidTy(Context), NULL); 489 B.CreateCall(StackChkFail); 490 } 491 B.CreateUnreachable(); 492 return FailBB; 493 } 494