1 //===-- StackProtector.cpp - Stack Protector Insertion --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "stack-protector"
18 #include "llvm/CodeGen/Analysis.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/Analysis/Dominators.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/IR/Attributes.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalValue.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Target/TargetLowering.h"
43 STATISTIC(NumFunProtected, "Number of functions protected");
44 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
48 EnableSelectionDAGSP("enable-selectiondag-sp", cl::init(true),
52 class StackProtector : public FunctionPass {
53 const TargetMachine *TM;
55 /// TLI - Keep a pointer of a TargetLowering to consult for determining
56 /// target type sizes.
57 const TargetLoweringBase *TLI;
65 /// \brief The minimum size of buffers that will receive stack smashing
66 /// protection when -fstack-protection is used.
67 unsigned SSPBufferSize;
69 /// VisitedPHIs - The set of PHI nodes visited when determining
70 /// if a variable's reference has been taken. This set
71 /// is maintained to ensure we don't visit the same PHI node multiple
73 SmallPtrSet<const PHINode*, 16> VisitedPHIs;
75 /// InsertStackProtectors - Insert code into the prologue and epilogue of
78 /// - The prologue code loads and stores the stack guard onto the stack.
79 /// - The epilogue checks the value stored in the prologue against the
80 /// original value. It calls __stack_chk_fail if they differ.
81 bool InsertStackProtectors();
83 /// CreateFailBB - Create a basic block to jump to when the stack protector
85 BasicBlock *CreateFailBB();
87 /// ContainsProtectableArray - Check whether the type either is an array or
88 /// contains an array of sufficient size so that we need stack protectors
90 bool ContainsProtectableArray(Type *Ty, bool Strong = false,
91 bool InStruct = false) const;
93 /// \brief Check whether a stack allocation has its address taken.
94 bool HasAddressTaken(const Instruction *AI);
96 /// RequiresStackProtector - Check whether or not this function needs a
97 /// stack protector based upon the stack protector level.
98 bool RequiresStackProtector();
100 static char ID; // Pass identification, replacement for typeid.
101 StackProtector() : FunctionPass(ID), TM(0), TLI(0), SSPBufferSize(0) {
102 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
104 StackProtector(const TargetMachine *TM)
105 : FunctionPass(ID), TM(TM), TLI(0), Trip(TM->getTargetTriple()),
107 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
110 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
111 AU.addPreserved<DominatorTree>();
114 virtual bool runOnFunction(Function &Fn);
116 } // end anonymous namespace
118 char StackProtector::ID = 0;
119 INITIALIZE_PASS(StackProtector, "stack-protector",
120 "Insert stack protectors", false, false)
122 FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
123 return new StackProtector(TM);
126 bool StackProtector::runOnFunction(Function &Fn) {
129 DT = getAnalysisIfAvailable<DominatorTree>();
130 TLI = TM->getTargetLowering();
132 if (!RequiresStackProtector()) return false;
135 Fn.getAttributes().getAttribute(AttributeSet::FunctionIndex,
136 "stack-protector-buffer-size");
137 if (Attr.isStringAttribute())
138 Attr.getValueAsString().getAsInteger(10, SSPBufferSize);
141 return InsertStackProtectors();
144 /// ContainsProtectableArray - Check whether the type either is an array or
145 /// contains a char array of sufficient size so that we need stack protectors
147 bool StackProtector::ContainsProtectableArray(Type *Ty, bool Strong,
148 bool InStruct) const {
149 if (!Ty) return false;
150 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
151 // In strong mode any array, regardless of type and size, triggers a
155 if (!AT->getElementType()->isIntegerTy(8)) {
156 // If we're on a non-Darwin platform or we're inside of a structure, don't
157 // add stack protectors unless the array is a character array.
158 if (InStruct || !Trip.isOSDarwin())
162 // If an array has more than SSPBufferSize bytes of allocated space, then we
163 // emit stack protectors.
164 if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT))
168 const StructType *ST = dyn_cast<StructType>(Ty);
169 if (!ST) return false;
171 for (StructType::element_iterator I = ST->element_begin(),
172 E = ST->element_end(); I != E; ++I)
173 if (ContainsProtectableArray(*I, Strong, true))
179 bool StackProtector::HasAddressTaken(const Instruction *AI) {
180 for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
183 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
184 if (AI == SI->getValueOperand())
186 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
187 if (AI == SI->getOperand(0))
189 } else if (isa<CallInst>(U)) {
191 } else if (isa<InvokeInst>(U)) {
193 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
194 if (HasAddressTaken(SI))
196 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
197 // Keep track of what PHI nodes we have already visited to ensure
198 // they are only visited once.
199 if (VisitedPHIs.insert(PN))
200 if (HasAddressTaken(PN))
202 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
203 if (HasAddressTaken(GEP))
205 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
206 if (HasAddressTaken(BI))
213 /// \brief Check whether or not this function needs a stack protector based
214 /// upon the stack protector level.
216 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
217 /// The standard heuristic which will add a guard variable to functions that
218 /// call alloca with a either a variable size or a size >= SSPBufferSize,
219 /// functions with character buffers larger than SSPBufferSize, and functions
220 /// with aggregates containing character buffers larger than SSPBufferSize. The
221 /// strong heuristic will add a guard variables to functions that call alloca
222 /// regardless of size, functions with any buffer regardless of type and size,
223 /// functions with aggregates that contain any buffer regardless of type and
224 /// size, and functions that contain stack-based variables that have had their
226 bool StackProtector::RequiresStackProtector() {
228 if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
229 Attribute::StackProtectReq))
231 else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
232 Attribute::StackProtectStrong))
234 else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
235 Attribute::StackProtect))
238 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
241 for (BasicBlock::iterator
242 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
243 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
244 if (AI->isArrayAllocation()) {
245 // SSP-Strong: Enable protectors for any call to alloca, regardless
250 if (const ConstantInt *CI =
251 dyn_cast<ConstantInt>(AI->getArraySize())) {
252 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize)
253 // A call to alloca with size >= SSPBufferSize requires
257 // A call to alloca with a variable size requires protectors.
262 if (ContainsProtectableArray(AI->getAllocatedType(), Strong))
265 if (Strong && HasAddressTaken(AI)) {
276 static bool InstructionWillNotHaveChain(const Instruction *I) {
277 return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
278 isSafeToSpeculativelyExecute(I);
281 /// Identify if RI has a previous instruction in the "Tail Position" and return
282 /// it. Otherwise return 0.
284 /// This is based off of the code in llvm::isInTailCallPosition. The difference
285 /// is that it inverts the first part of llvm::isInTailCallPosition since
286 /// isInTailCallPosition is checking if a call is in a tail call position, and
287 /// we are searching for an unknown tail call that might be in the tail call
288 /// position. Once we find the call though, the code uses the same refactored
289 /// code, returnTypeIsEligibleForTailCall.
290 static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
291 const TargetLoweringBase *TLI) {
292 // Establish a reasonable upper bound on the maximum amount of instructions we
293 // will look through to find a tail call.
294 unsigned SearchCounter = 0;
295 const unsigned MaxSearch = 4;
296 bool NoInterposingChain = true;
298 for (BasicBlock::reverse_iterator I = llvm::next(BB->rbegin()), E = BB->rend();
299 I != E && SearchCounter < MaxSearch; ++I) {
300 Instruction *Inst = &*I;
302 // Skip over debug intrinsics and do not allow them to affect our MaxSearch
304 if (isa<DbgInfoIntrinsic>(Inst))
307 // If we find a call and the following conditions are satisifed, then we
308 // have found a tail call that satisfies at least the target independent
309 // requirements of a tail call:
311 // 1. The call site has the tail marker.
313 // 2. The call site either will not cause the creation of a chain or if a
314 // chain is necessary there are no instructions in between the callsite and
315 // the call which would create an interposing chain.
317 // 3. The return type of the function does not impede tail call
319 if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
320 if (CI->isTailCall() &&
321 (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
322 returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
326 // If we did not find a call see if we have an instruction that may create
327 // an interposing chain.
328 NoInterposingChain = NoInterposingChain && InstructionWillNotHaveChain(Inst);
330 // Increment max search.
337 /// Insert code into the entry block that stores the __stack_chk_guard
338 /// variable onto the stack:
341 /// StackGuardSlot = alloca i8*
342 /// StackGuard = load __stack_chk_guard
343 /// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
345 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
347 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
348 const TargetLoweringBase *TLI, const Triple &Trip,
349 AllocaInst *&AI, Value *&StackGuardVar) {
350 bool SupportsSelectionDAGSP = false;
351 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
352 unsigned AddressSpace, Offset;
353 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
354 Constant *OffsetVal =
355 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
357 StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
358 PointerType::get(PtrTy,
360 } else if (Trip.getOS() == llvm::Triple::OpenBSD) {
361 StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
362 cast<GlobalValue>(StackGuardVar)
363 ->setVisibility(GlobalValue::HiddenVisibility);
365 SupportsSelectionDAGSP = true;
366 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
369 IRBuilder<> B(&F->getEntryBlock().front());
370 AI = B.CreateAlloca(PtrTy, 0, "StackGuardSlot");
371 LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
372 B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI,
375 return SupportsSelectionDAGSP;
378 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
381 /// - The prologue code loads and stores the stack guard onto the stack.
382 /// - The epilogue checks the value stored in the prologue against the original
383 /// value. It calls __stack_chk_fail if they differ.
384 bool StackProtector::InsertStackProtectors() {
385 bool HasPrologue = false;
386 bool SupportsSelectionDAGSP =
387 EnableSelectionDAGSP && !TM->Options.EnableFastISel;
388 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
389 Value *StackGuardVar = 0; // The stack guard variable.
391 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
392 BasicBlock *BB = I++;
393 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
399 SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, Trip, AI,
403 if (SupportsSelectionDAGSP) {
404 // Since we have a potential tail call, insert the special stack check
406 Instruction *InsertionPt = 0;
407 if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
411 // At this point we know that BB has a return statement so it *DOES*
412 // have a terminator.
413 assert(InsertionPt != 0 && "BB must have a terminator instruction at "
417 Function *Intrinsic =
418 Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
419 CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt);
422 // If we do not support SelectionDAG based tail calls, generate IR level
425 // For each block with a return instruction, convert this:
435 // %1 = load __stack_chk_guard
436 // %2 = load StackGuardSlot
437 // %3 = cmp i1 %1, %2
438 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
443 // CallStackCheckFailBlk:
444 // call void @__stack_chk_fail()
447 // Create the FailBB. We duplicate the BB every time since the MI tail
448 // merge pass will merge together all of the various BB into one including
449 // fail BB generated by the stack protector pseudo instruction.
450 BasicBlock *FailBB = CreateFailBB();
452 // Split the basic block before the return instruction.
453 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
455 // Update the dominator tree if we need to.
456 if (DT && DT->isReachableFromEntry(BB)) {
457 DT->addNewBlock(NewBB, BB);
458 DT->addNewBlock(FailBB, BB);
461 // Remove default branch instruction to the new BB.
462 BB->getTerminator()->eraseFromParent();
464 // Move the newly created basic block to the point right after the old
465 // basic block so that it's in the "fall through" position.
466 NewBB->moveAfter(BB);
468 // Generate the stack protector instructions in the old basic block.
470 LoadInst *LI1 = B.CreateLoad(StackGuardVar);
471 LoadInst *LI2 = B.CreateLoad(AI);
472 Value *Cmp = B.CreateICmpEQ(LI1, LI2);
473 B.CreateCondBr(Cmp, NewBB, FailBB);
477 // Return if we didn't modify any basic blocks. I.e., there are no return
478 // statements in the function.
485 /// CreateFailBB - Create a basic block to jump to when the stack protector
487 BasicBlock *StackProtector::CreateFailBB() {
488 LLVMContext &Context = F->getContext();
489 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
490 IRBuilder<> B(FailBB);
491 if (Trip.getOS() == llvm::Triple::OpenBSD) {
492 Constant *StackChkFail = M->getOrInsertFunction(
493 "__stack_smash_handler", Type::getVoidTy(Context),
494 Type::getInt8PtrTy(Context), NULL);
496 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
498 Constant *StackChkFail = M->getOrInsertFunction(
499 "__stack_chk_fail", Type::getVoidTy(Context), NULL);
500 B.CreateCall(StackChkFail);
502 B.CreateUnreachable();