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