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/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/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/Support/CommandLine.h"
41 STATISTIC(NumFunProtected, "Number of functions protected");
42 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
46 EnableSelectionDAGSP("enable-selectiondag-sp", cl::init(true),
49 char StackProtector::ID = 0;
50 INITIALIZE_PASS(StackProtector, "stack-protector",
51 "Insert stack protectors", false, false)
53 FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
54 return new StackProtector(TM);
57 bool StackProtector::runOnFunction(Function &Fn) {
60 DT = getAnalysisIfAvailable<DominatorTree>();
61 TLI = TM->getTargetLowering();
63 if (!RequiresStackProtector()) return false;
66 Fn.getAttributes().getAttribute(AttributeSet::FunctionIndex,
67 "stack-protector-buffer-size");
68 if (Attr.isStringAttribute())
69 Attr.getValueAsString().getAsInteger(10, SSPBufferSize);
72 return InsertStackProtectors();
75 /// ContainsProtectableArray - Check whether the type either is an array or
76 /// contains a char array of sufficient size so that we need stack protectors
78 bool StackProtector::ContainsProtectableArray(Type *Ty, bool Strong,
79 bool InStruct) const {
80 if (!Ty) return false;
81 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
82 // In strong mode any array, regardless of type and size, triggers a
86 if (!AT->getElementType()->isIntegerTy(8)) {
87 // If we're on a non-Darwin platform or we're inside of a structure, don't
88 // add stack protectors unless the array is a character array.
89 if (InStruct || !Trip.isOSDarwin())
93 // If an array has more than SSPBufferSize bytes of allocated space, then we
94 // emit stack protectors.
95 if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT))
99 const StructType *ST = dyn_cast<StructType>(Ty);
100 if (!ST) return false;
102 for (StructType::element_iterator I = ST->element_begin(),
103 E = ST->element_end(); I != E; ++I)
104 if (ContainsProtectableArray(*I, Strong, true))
110 bool StackProtector::HasAddressTaken(const Instruction *AI) {
111 for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
114 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
115 if (AI == SI->getValueOperand())
117 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
118 if (AI == SI->getOperand(0))
120 } else if (isa<CallInst>(U)) {
122 } else if (isa<InvokeInst>(U)) {
124 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
125 if (HasAddressTaken(SI))
127 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
128 // Keep track of what PHI nodes we have already visited to ensure
129 // they are only visited once.
130 if (VisitedPHIs.insert(PN))
131 if (HasAddressTaken(PN))
133 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
134 if (HasAddressTaken(GEP))
136 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
137 if (HasAddressTaken(BI))
144 /// \brief Check whether or not this function needs a stack protector based
145 /// upon the stack protector level.
147 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
148 /// The standard heuristic which will add a guard variable to functions that
149 /// call alloca with a either a variable size or a size >= SSPBufferSize,
150 /// functions with character buffers larger than SSPBufferSize, and functions
151 /// with aggregates containing character buffers larger than SSPBufferSize. The
152 /// strong heuristic will add a guard variables to functions that call alloca
153 /// regardless of size, functions with any buffer regardless of type and size,
154 /// functions with aggregates that contain any buffer regardless of type and
155 /// size, and functions that contain stack-based variables that have had their
157 bool StackProtector::RequiresStackProtector() {
159 if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
160 Attribute::StackProtectReq))
162 else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
163 Attribute::StackProtectStrong))
165 else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
166 Attribute::StackProtect))
169 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
172 for (BasicBlock::iterator
173 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
174 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
175 if (AI->isArrayAllocation()) {
176 // SSP-Strong: Enable protectors for any call to alloca, regardless
181 if (const ConstantInt *CI =
182 dyn_cast<ConstantInt>(AI->getArraySize())) {
183 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize)
184 // A call to alloca with size >= SSPBufferSize requires
188 // A call to alloca with a variable size requires protectors.
193 if (ContainsProtectableArray(AI->getAllocatedType(), Strong))
196 if (Strong && HasAddressTaken(AI)) {
207 static bool InstructionWillNotHaveChain(const Instruction *I) {
208 return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
209 isSafeToSpeculativelyExecute(I);
212 /// Identify if RI has a previous instruction in the "Tail Position" and return
213 /// it. Otherwise return 0.
215 /// This is based off of the code in llvm::isInTailCallPosition. The difference
216 /// is that it inverts the first part of llvm::isInTailCallPosition since
217 /// isInTailCallPosition is checking if a call is in a tail call position, and
218 /// we are searching for an unknown tail call that might be in the tail call
219 /// position. Once we find the call though, the code uses the same refactored
220 /// code, returnTypeIsEligibleForTailCall.
221 static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
222 const TargetLoweringBase *TLI) {
223 // Establish a reasonable upper bound on the maximum amount of instructions we
224 // will look through to find a tail call.
225 unsigned SearchCounter = 0;
226 const unsigned MaxSearch = 4;
227 bool NoInterposingChain = true;
229 for (BasicBlock::reverse_iterator I = llvm::next(BB->rbegin()), E = BB->rend();
230 I != E && SearchCounter < MaxSearch; ++I) {
231 Instruction *Inst = &*I;
233 // Skip over debug intrinsics and do not allow them to affect our MaxSearch
235 if (isa<DbgInfoIntrinsic>(Inst))
238 // If we find a call and the following conditions are satisifed, then we
239 // have found a tail call that satisfies at least the target independent
240 // requirements of a tail call:
242 // 1. The call site has the tail marker.
244 // 2. The call site either will not cause the creation of a chain or if a
245 // chain is necessary there are no instructions in between the callsite and
246 // the call which would create an interposing chain.
248 // 3. The return type of the function does not impede tail call
250 if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
251 if (CI->isTailCall() &&
252 (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
253 returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
257 // If we did not find a call see if we have an instruction that may create
258 // an interposing chain.
259 NoInterposingChain = NoInterposingChain && InstructionWillNotHaveChain(Inst);
261 // Increment max search.
268 /// Insert code into the entry block that stores the __stack_chk_guard
269 /// variable onto the stack:
272 /// StackGuardSlot = alloca i8*
273 /// StackGuard = load __stack_chk_guard
274 /// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
276 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
278 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
279 const TargetLoweringBase *TLI, const Triple &Trip,
280 AllocaInst *&AI, Value *&StackGuardVar) {
281 bool SupportsSelectionDAGSP = false;
282 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
283 unsigned AddressSpace, Offset;
284 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
285 Constant *OffsetVal =
286 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
288 StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
289 PointerType::get(PtrTy,
291 } else if (Trip.getOS() == llvm::Triple::OpenBSD) {
292 StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
293 cast<GlobalValue>(StackGuardVar)
294 ->setVisibility(GlobalValue::HiddenVisibility);
296 SupportsSelectionDAGSP = true;
297 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
300 IRBuilder<> B(&F->getEntryBlock().front());
301 AI = B.CreateAlloca(PtrTy, 0, "StackGuardSlot");
302 LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
303 B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI,
306 return SupportsSelectionDAGSP;
309 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
312 /// - The prologue code loads and stores the stack guard onto the stack.
313 /// - The epilogue checks the value stored in the prologue against the original
314 /// value. It calls __stack_chk_fail if they differ.
315 bool StackProtector::InsertStackProtectors() {
316 bool HasPrologue = false;
317 bool SupportsSelectionDAGSP =
318 EnableSelectionDAGSP && !TM->Options.EnableFastISel;
319 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
320 Value *StackGuardVar = 0; // The stack guard variable.
322 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
323 BasicBlock *BB = I++;
324 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
330 SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, Trip, AI,
334 if (SupportsSelectionDAGSP) {
335 // Since we have a potential tail call, insert the special stack check
337 Instruction *InsertionPt = 0;
338 if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
342 // At this point we know that BB has a return statement so it *DOES*
343 // have a terminator.
344 assert(InsertionPt != 0 && "BB must have a terminator instruction at "
348 Function *Intrinsic =
349 Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
350 CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt);
353 // If we do not support SelectionDAG based tail calls, generate IR level
356 // For each block with a return instruction, convert this:
366 // %1 = load __stack_chk_guard
367 // %2 = load StackGuardSlot
368 // %3 = cmp i1 %1, %2
369 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
374 // CallStackCheckFailBlk:
375 // call void @__stack_chk_fail()
378 // Create the FailBB. We duplicate the BB every time since the MI tail
379 // merge pass will merge together all of the various BB into one including
380 // fail BB generated by the stack protector pseudo instruction.
381 BasicBlock *FailBB = CreateFailBB();
383 // Split the basic block before the return instruction.
384 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
386 // Update the dominator tree if we need to.
387 if (DT && DT->isReachableFromEntry(BB)) {
388 DT->addNewBlock(NewBB, BB);
389 DT->addNewBlock(FailBB, BB);
392 // Remove default branch instruction to the new BB.
393 BB->getTerminator()->eraseFromParent();
395 // Move the newly created basic block to the point right after the old
396 // basic block so that it's in the "fall through" position.
397 NewBB->moveAfter(BB);
399 // Generate the stack protector instructions in the old basic block.
401 LoadInst *LI1 = B.CreateLoad(StackGuardVar);
402 LoadInst *LI2 = B.CreateLoad(AI);
403 Value *Cmp = B.CreateICmpEQ(LI1, LI2);
404 B.CreateCondBr(Cmp, NewBB, FailBB);
408 // Return if we didn't modify any basic blocks. I.e., there are no return
409 // statements in the function.
416 /// CreateFailBB - Create a basic block to jump to when the stack protector
418 BasicBlock *StackProtector::CreateFailBB() {
419 LLVMContext &Context = F->getContext();
420 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
421 IRBuilder<> B(FailBB);
422 if (Trip.getOS() == llvm::Triple::OpenBSD) {
423 Constant *StackChkFail = M->getOrInsertFunction(
424 "__stack_smash_handler", Type::getVoidTy(Context),
425 Type::getInt8PtrTy(Context), NULL);
427 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
429 Constant *StackChkFail = M->getOrInsertFunction(
430 "__stack_chk_fail", Type::getVoidTy(Context), NULL);
431 B.CreateCall(StackChkFail);
433 B.CreateUnreachable();