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/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"
40 STATISTIC(NumFunProtected, "Number of functions protected");
41 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
44 static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
45 cl::init(true), cl::Hidden);
47 char StackProtector::ID = 0;
48 INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
51 FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
52 return new StackProtector(TM);
55 StackProtector::SSPLayoutKind
56 StackProtector::getSSPLayout(const AllocaInst *AI) const {
57 return AI ? Layout.lookup(AI) : SSPLK_None;
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;
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.
74 if (I == Layout.end())
75 Layout.insert(std::make_pair(To, Kind));
76 else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
81 bool StackProtector::runOnFunction(Function &Fn) {
84 DominatorTreeWrapperPass *DTWP =
85 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
86 DT = DTWP ? &DTWP->getDomTree() : nullptr;
87 TLI = TM->getTargetLowering();
89 Attribute Attr = Fn.getAttributes().getAttribute(
90 AttributeSet::FunctionIndex, "stack-protector-buffer-size");
91 if (Attr.isStringAttribute() &&
92 Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
93 return false; // Invalid integer string
95 if (!RequiresStackProtector())
99 return InsertStackProtectors();
102 /// \param [out] IsLarge is set to true if a protectable array is found and
103 /// it is "large" ( >= ssp-buffer-size). In the case of a structure with
104 /// multiple arrays, this gets set if any of them is large.
105 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
107 bool InStruct) const {
110 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
111 if (!AT->getElementType()->isIntegerTy(8)) {
112 // If we're on a non-Darwin platform or we're inside of a structure, don't
113 // add stack protectors unless the array is a character array.
114 // However, in strong mode any array, regardless of type and size,
115 // triggers a protector.
116 if (!Strong && (InStruct || !Trip.isOSDarwin()))
120 // If an array has more than SSPBufferSize bytes of allocated space, then we
121 // emit stack protectors.
122 if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT)) {
128 // Require a protector for all arrays in strong mode
132 const StructType *ST = dyn_cast<StructType>(Ty);
136 bool NeedsProtector = false;
137 for (StructType::element_iterator I = ST->element_begin(),
138 E = ST->element_end();
140 if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
141 // If the element is a protectable array and is large (>= SSPBufferSize)
142 // then we are done. If the protectable array is not large, then
143 // keep looking in case a subsequent element is a large array.
146 NeedsProtector = true;
149 return NeedsProtector;
152 bool StackProtector::HasAddressTaken(const Instruction *AI) {
153 for (const User *U : AI->users()) {
154 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
155 if (AI == SI->getValueOperand())
157 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
158 if (AI == SI->getOperand(0))
160 } else if (isa<CallInst>(U)) {
162 } else if (isa<InvokeInst>(U)) {
164 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
165 if (HasAddressTaken(SI))
167 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
168 // Keep track of what PHI nodes we have already visited to ensure
169 // they are only visited once.
170 if (VisitedPHIs.insert(PN))
171 if (HasAddressTaken(PN))
173 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
174 if (HasAddressTaken(GEP))
176 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
177 if (HasAddressTaken(BI))
184 /// \brief Check whether or not this function needs a stack protector based
185 /// upon the stack protector level.
187 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
188 /// The standard heuristic which will add a guard variable to functions that
189 /// call alloca with a either a variable size or a size >= SSPBufferSize,
190 /// functions with character buffers larger than SSPBufferSize, and functions
191 /// with aggregates containing character buffers larger than SSPBufferSize. The
192 /// strong heuristic will add a guard variables to functions that call alloca
193 /// regardless of size, functions with any buffer regardless of type and size,
194 /// functions with aggregates that contain any buffer regardless of type and
195 /// size, and functions that contain stack-based variables that have had their
197 bool StackProtector::RequiresStackProtector() {
199 bool NeedsProtector = false;
200 if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
201 Attribute::StackProtectReq)) {
202 NeedsProtector = true;
203 Strong = true; // Use the same heuristic as strong to determine SSPLayout
204 } else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
205 Attribute::StackProtectStrong))
207 else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
208 Attribute::StackProtect))
211 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
214 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
216 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
217 if (AI->isArrayAllocation()) {
218 // SSP-Strong: Enable protectors for any call to alloca, regardless
223 if (const ConstantInt *CI =
224 dyn_cast<ConstantInt>(AI->getArraySize())) {
225 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
226 // A call to alloca with size >= SSPBufferSize requires
228 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
229 NeedsProtector = true;
231 // Require protectors for all alloca calls in strong mode.
232 Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
233 NeedsProtector = true;
236 // A call to alloca with a variable size requires protectors.
237 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
238 NeedsProtector = true;
243 bool IsLarge = false;
244 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
245 Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
246 : SSPLK_SmallArray));
247 NeedsProtector = true;
251 if (Strong && HasAddressTaken(AI)) {
253 Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
254 NeedsProtector = true;
260 return NeedsProtector;
263 static bool InstructionWillNotHaveChain(const Instruction *I) {
264 return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
265 isSafeToSpeculativelyExecute(I);
268 /// Identify if RI has a previous instruction in the "Tail Position" and return
269 /// it. Otherwise return 0.
271 /// This is based off of the code in llvm::isInTailCallPosition. The difference
272 /// is that it inverts the first part of llvm::isInTailCallPosition since
273 /// isInTailCallPosition is checking if a call is in a tail call position, and
274 /// we are searching for an unknown tail call that might be in the tail call
275 /// position. Once we find the call though, the code uses the same refactored
276 /// code, returnTypeIsEligibleForTailCall.
277 static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
278 const TargetLoweringBase *TLI) {
279 // Establish a reasonable upper bound on the maximum amount of instructions we
280 // will look through to find a tail call.
281 unsigned SearchCounter = 0;
282 const unsigned MaxSearch = 4;
283 bool NoInterposingChain = true;
285 for (BasicBlock::reverse_iterator I = std::next(BB->rbegin()), E = BB->rend();
286 I != E && SearchCounter < MaxSearch; ++I) {
287 Instruction *Inst = &*I;
289 // Skip over debug intrinsics and do not allow them to affect our MaxSearch
291 if (isa<DbgInfoIntrinsic>(Inst))
294 // If we find a call and the following conditions are satisifed, then we
295 // have found a tail call that satisfies at least the target independent
296 // requirements of a tail call:
298 // 1. The call site has the tail marker.
300 // 2. The call site either will not cause the creation of a chain or if a
301 // chain is necessary there are no instructions in between the callsite and
302 // the call which would create an interposing chain.
304 // 3. The return type of the function does not impede tail call
306 if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
307 if (CI->isTailCall() &&
308 (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
309 returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
313 // If we did not find a call see if we have an instruction that may create
314 // an interposing chain.
316 NoInterposingChain && InstructionWillNotHaveChain(Inst);
318 // Increment max search.
325 /// Insert code into the entry block that stores the __stack_chk_guard
326 /// variable onto the stack:
329 /// StackGuardSlot = alloca i8*
330 /// StackGuard = load __stack_chk_guard
331 /// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
333 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
335 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
336 const TargetLoweringBase *TLI, const Triple &Trip,
337 AllocaInst *&AI, Value *&StackGuardVar) {
338 bool SupportsSelectionDAGSP = false;
339 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
340 unsigned AddressSpace, Offset;
341 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
342 Constant *OffsetVal =
343 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
345 StackGuardVar = ConstantExpr::getIntToPtr(
346 OffsetVal, PointerType::get(PtrTy, AddressSpace));
347 } else if (Trip.getOS() == llvm::Triple::OpenBSD) {
348 StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
349 cast<GlobalValue>(StackGuardVar)
350 ->setVisibility(GlobalValue::HiddenVisibility);
352 SupportsSelectionDAGSP = true;
353 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
356 IRBuilder<> B(&F->getEntryBlock().front());
357 AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
358 LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
359 B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI,
362 return SupportsSelectionDAGSP;
365 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
368 /// - The prologue code loads and stores the stack guard onto the stack.
369 /// - The epilogue checks the value stored in the prologue against the original
370 /// value. It calls __stack_chk_fail if they differ.
371 bool StackProtector::InsertStackProtectors() {
372 bool HasPrologue = false;
373 bool SupportsSelectionDAGSP =
374 EnableSelectionDAGSP && !TM->Options.EnableFastISel;
375 AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
376 Value *StackGuardVar = nullptr; // The stack guard variable.
378 for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
379 BasicBlock *BB = I++;
380 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
386 SupportsSelectionDAGSP &=
387 CreatePrologue(F, M, RI, TLI, Trip, AI, StackGuardVar);
390 if (SupportsSelectionDAGSP) {
391 // Since we have a potential tail call, insert the special stack check
393 Instruction *InsertionPt = nullptr;
394 if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
398 // At this point we know that BB has a return statement so it *DOES*
399 // have a terminator.
400 assert(InsertionPt != nullptr && "BB must have a terminator instruction at "
404 Function *Intrinsic =
405 Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
406 CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt);
409 // If we do not support SelectionDAG based tail calls, generate IR level
412 // For each block with a return instruction, convert this:
422 // %1 = load __stack_chk_guard
423 // %2 = load StackGuardSlot
424 // %3 = cmp i1 %1, %2
425 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
430 // CallStackCheckFailBlk:
431 // call void @__stack_chk_fail()
434 // Create the FailBB. We duplicate the BB every time since the MI tail
435 // merge pass will merge together all of the various BB into one including
436 // fail BB generated by the stack protector pseudo instruction.
437 BasicBlock *FailBB = CreateFailBB();
439 // Split the basic block before the return instruction.
440 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
442 // Update the dominator tree if we need to.
443 if (DT && DT->isReachableFromEntry(BB)) {
444 DT->addNewBlock(NewBB, BB);
445 DT->addNewBlock(FailBB, BB);
448 // Remove default branch instruction to the new BB.
449 BB->getTerminator()->eraseFromParent();
451 // Move the newly created basic block to the point right after the old
452 // basic block so that it's in the "fall through" position.
453 NewBB->moveAfter(BB);
455 // Generate the stack protector instructions in the old basic block.
457 LoadInst *LI1 = B.CreateLoad(StackGuardVar);
458 LoadInst *LI2 = B.CreateLoad(AI);
459 Value *Cmp = B.CreateICmpEQ(LI1, LI2);
460 B.CreateCondBr(Cmp, NewBB, FailBB);
464 // Return if we didn't modify any basic blocks. I.e., there are no return
465 // statements in the function.
472 /// CreateFailBB - Create a basic block to jump to when the stack protector
474 BasicBlock *StackProtector::CreateFailBB() {
475 LLVMContext &Context = F->getContext();
476 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
477 IRBuilder<> B(FailBB);
478 if (Trip.getOS() == llvm::Triple::OpenBSD) {
479 Constant *StackChkFail = M->getOrInsertFunction(
480 "__stack_smash_handler", Type::getVoidTy(Context),
481 Type::getInt8PtrTy(Context), NULL);
483 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
485 Constant *StackChkFail = M->getOrInsertFunction(
486 "__stack_chk_fail", Type::getVoidTy(Context), NULL);
487 B.CreateCall(StackChkFail);
489 B.CreateUnreachable();