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