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 #include "llvm/CodeGen/StackProtector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/IR/Attributes.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GlobalValue.h"
29 #include "llvm/IR/GlobalVariable.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
40 #define DEBUG_TYPE "stack-protector"
42 STATISTIC(NumFunProtected, "Number of functions protected");
43 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
46 static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
47 cl::init(true), cl::Hidden);
49 char StackProtector::ID = 0;
50 INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
53 FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
54 return new StackProtector(TM);
57 StackProtector::SSPLayoutKind
58 StackProtector::getSSPLayout(const AllocaInst *AI) const {
59 return AI ? Layout.lookup(AI) : SSPLK_None;
62 void StackProtector::adjustForColoring(const AllocaInst *From,
63 const AllocaInst *To) {
64 // When coloring replaces one alloca with another, transfer the SSPLayoutKind
65 // tag from the remapped to the target alloca. The remapped alloca should
66 // have a size smaller than or equal to the replacement alloca.
67 SSPLayoutMap::iterator I = Layout.find(From);
68 if (I != Layout.end()) {
69 SSPLayoutKind Kind = I->second;
72 // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
73 // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
74 // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
76 if (I == Layout.end())
77 Layout.insert(std::make_pair(To, Kind));
78 else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
83 bool StackProtector::runOnFunction(Function &Fn) {
86 DominatorTreeWrapperPass *DTWP =
87 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
88 DT = DTWP ? &DTWP->getDomTree() : nullptr;
89 TLI = TM->getSubtargetImpl()->getTargetLowering();
91 Attribute Attr = Fn.getAttributes().getAttribute(
92 AttributeSet::FunctionIndex, "stack-protector-buffer-size");
93 if (Attr.isStringAttribute() &&
94 Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
95 return false; // Invalid integer string
97 if (!RequiresStackProtector())
101 return InsertStackProtectors();
104 /// \param [out] IsLarge is set to true if a protectable array is found and
105 /// it is "large" ( >= ssp-buffer-size). In the case of a structure with
106 /// multiple arrays, this gets set if any of them is large.
107 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
109 bool InStruct) const {
112 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
113 if (!AT->getElementType()->isIntegerTy(8)) {
114 // If we're on a non-Darwin platform or we're inside of a structure, don't
115 // add stack protectors unless the array is a character array.
116 // However, in strong mode any array, regardless of type and size,
117 // triggers a protector.
118 if (!Strong && (InStruct || !Trip.isOSDarwin()))
122 // If an array has more than SSPBufferSize bytes of allocated space, then we
123 // emit stack protectors.
124 if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT)) {
130 // Require a protector for all arrays in strong mode
134 const StructType *ST = dyn_cast<StructType>(Ty);
138 bool NeedsProtector = false;
139 for (StructType::element_iterator I = ST->element_begin(),
140 E = ST->element_end();
142 if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
143 // If the element is a protectable array and is large (>= SSPBufferSize)
144 // then we are done. If the protectable array is not large, then
145 // keep looking in case a subsequent element is a large array.
148 NeedsProtector = true;
151 return NeedsProtector;
154 bool StackProtector::HasAddressTaken(const Instruction *AI) {
155 for (const User *U : AI->users()) {
156 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
157 if (AI == SI->getValueOperand())
159 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
160 if (AI == SI->getOperand(0))
162 } else if (isa<CallInst>(U)) {
164 } else if (isa<InvokeInst>(U)) {
166 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
167 if (HasAddressTaken(SI))
169 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
170 // Keep track of what PHI nodes we have already visited to ensure
171 // they are only visited once.
172 if (VisitedPHIs.insert(PN))
173 if (HasAddressTaken(PN))
175 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
176 if (HasAddressTaken(GEP))
178 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
179 if (HasAddressTaken(BI))
186 /// \brief Check whether or not this function needs a stack protector based
187 /// upon the stack protector level.
189 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
190 /// The standard heuristic which will add a guard variable to functions that
191 /// call alloca with a either a variable size or a size >= SSPBufferSize,
192 /// functions with character buffers larger than SSPBufferSize, and functions
193 /// with aggregates containing character buffers larger than SSPBufferSize. The
194 /// strong heuristic will add a guard variables to functions that call alloca
195 /// regardless of size, functions with any buffer regardless of type and size,
196 /// functions with aggregates that contain any buffer regardless of type and
197 /// size, and functions that contain stack-based variables that have had their
199 bool StackProtector::RequiresStackProtector() {
201 bool NeedsProtector = false;
202 if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
203 Attribute::StackProtectReq)) {
204 NeedsProtector = true;
205 Strong = true; // Use the same heuristic as strong to determine SSPLayout
206 } else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
207 Attribute::StackProtectStrong))
209 else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
210 Attribute::StackProtect))
213 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
216 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
218 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
219 if (AI->isArrayAllocation()) {
220 // SSP-Strong: Enable protectors for any call to alloca, regardless
225 if (const ConstantInt *CI =
226 dyn_cast<ConstantInt>(AI->getArraySize())) {
227 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
228 // A call to alloca with size >= SSPBufferSize requires
230 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
231 NeedsProtector = true;
233 // Require protectors for all alloca calls in strong mode.
234 Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
235 NeedsProtector = true;
238 // A call to alloca with a variable size requires protectors.
239 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
240 NeedsProtector = true;
245 bool IsLarge = false;
246 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
247 Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
248 : SSPLK_SmallArray));
249 NeedsProtector = true;
253 if (Strong && HasAddressTaken(AI)) {
255 Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
256 NeedsProtector = true;
262 return NeedsProtector;
265 static bool InstructionWillNotHaveChain(const Instruction *I) {
266 return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
267 isSafeToSpeculativelyExecute(I);
270 /// Identify if RI has a previous instruction in the "Tail Position" and return
271 /// it. Otherwise return 0.
273 /// This is based off of the code in llvm::isInTailCallPosition. The difference
274 /// is that it inverts the first part of llvm::isInTailCallPosition since
275 /// isInTailCallPosition is checking if a call is in a tail call position, and
276 /// we are searching for an unknown tail call that might be in the tail call
277 /// position. Once we find the call though, the code uses the same refactored
278 /// code, returnTypeIsEligibleForTailCall.
279 static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
280 const TargetLoweringBase *TLI) {
281 // Establish a reasonable upper bound on the maximum amount of instructions we
282 // will look through to find a tail call.
283 unsigned SearchCounter = 0;
284 const unsigned MaxSearch = 4;
285 bool NoInterposingChain = true;
287 for (BasicBlock::reverse_iterator I = std::next(BB->rbegin()), E = BB->rend();
288 I != E && SearchCounter < MaxSearch; ++I) {
289 Instruction *Inst = &*I;
291 // Skip over debug intrinsics and do not allow them to affect our MaxSearch
293 if (isa<DbgInfoIntrinsic>(Inst))
296 // If we find a call and the following conditions are satisifed, then we
297 // have found a tail call that satisfies at least the target independent
298 // requirements of a tail call:
300 // 1. The call site has the tail marker.
302 // 2. The call site either will not cause the creation of a chain or if a
303 // chain is necessary there are no instructions in between the callsite and
304 // the call which would create an interposing chain.
306 // 3. The return type of the function does not impede tail call
308 if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
309 if (CI->isTailCall() &&
310 (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
311 returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
315 // If we did not find a call see if we have an instruction that may create
316 // an interposing chain.
318 NoInterposingChain && InstructionWillNotHaveChain(Inst);
320 // Increment max search.
327 /// Insert code into the entry block that stores the __stack_chk_guard
328 /// variable onto the stack:
331 /// StackGuardSlot = alloca i8*
332 /// StackGuard = load __stack_chk_guard
333 /// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
335 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
337 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
338 const TargetLoweringBase *TLI, const Triple &Trip,
339 AllocaInst *&AI, Value *&StackGuardVar) {
340 bool SupportsSelectionDAGSP = false;
341 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
342 unsigned AddressSpace, Offset;
343 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
344 Constant *OffsetVal =
345 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
347 StackGuardVar = ConstantExpr::getIntToPtr(
348 OffsetVal, PointerType::get(PtrTy, AddressSpace));
349 } else if (Trip.getOS() == llvm::Triple::OpenBSD) {
350 StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
351 cast<GlobalValue>(StackGuardVar)
352 ->setVisibility(GlobalValue::HiddenVisibility);
354 SupportsSelectionDAGSP = true;
355 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
358 IRBuilder<> B(&F->getEntryBlock().front());
359 AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
360 LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
361 B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI,
364 return SupportsSelectionDAGSP;
367 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
370 /// - The prologue code loads and stores the stack guard onto the stack.
371 /// - The epilogue checks the value stored in the prologue against the original
372 /// value. It calls __stack_chk_fail if they differ.
373 bool StackProtector::InsertStackProtectors() {
374 bool HasPrologue = false;
375 bool SupportsSelectionDAGSP =
376 EnableSelectionDAGSP && !TM->Options.EnableFastISel;
377 AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
378 Value *StackGuardVar = nullptr; // The stack guard variable.
380 for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
381 BasicBlock *BB = I++;
382 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
388 SupportsSelectionDAGSP &=
389 CreatePrologue(F, M, RI, TLI, Trip, AI, StackGuardVar);
392 if (SupportsSelectionDAGSP) {
393 // Since we have a potential tail call, insert the special stack check
395 Instruction *InsertionPt = nullptr;
396 if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
400 // At this point we know that BB has a return statement so it *DOES*
401 // have a terminator.
402 assert(InsertionPt != nullptr && "BB must have a terminator instruction at "
406 Function *Intrinsic =
407 Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
408 CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt);
411 // If we do not support SelectionDAG based tail calls, generate IR level
414 // For each block with a return instruction, convert this:
424 // %1 = load __stack_chk_guard
425 // %2 = load StackGuardSlot
426 // %3 = cmp i1 %1, %2
427 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
432 // CallStackCheckFailBlk:
433 // call void @__stack_chk_fail()
436 // Create the FailBB. We duplicate the BB every time since the MI tail
437 // merge pass will merge together all of the various BB into one including
438 // fail BB generated by the stack protector pseudo instruction.
439 BasicBlock *FailBB = CreateFailBB();
441 // Split the basic block before the return instruction.
442 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
444 // Update the dominator tree if we need to.
445 if (DT && DT->isReachableFromEntry(BB)) {
446 DT->addNewBlock(NewBB, BB);
447 DT->addNewBlock(FailBB, BB);
450 // Remove default branch instruction to the new BB.
451 BB->getTerminator()->eraseFromParent();
453 // Move the newly created basic block to the point right after the old
454 // basic block so that it's in the "fall through" position.
455 NewBB->moveAfter(BB);
457 // Generate the stack protector instructions in the old basic block.
459 LoadInst *LI1 = B.CreateLoad(StackGuardVar);
460 LoadInst *LI2 = B.CreateLoad(AI);
461 Value *Cmp = B.CreateICmpEQ(LI1, LI2);
462 B.CreateCondBr(Cmp, NewBB, FailBB);
466 // Return if we didn't modify any basic blocks. I.e., there are no return
467 // statements in the function.
474 /// CreateFailBB - Create a basic block to jump to when the stack protector
476 BasicBlock *StackProtector::CreateFailBB() {
477 LLVMContext &Context = F->getContext();
478 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
479 IRBuilder<> B(FailBB);
480 if (Trip.getOS() == llvm::Triple::OpenBSD) {
481 Constant *StackChkFail = M->getOrInsertFunction(
482 "__stack_smash_handler", Type::getVoidTy(Context),
483 Type::getInt8PtrTy(Context), NULL);
485 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
487 Constant *StackChkFail = M->getOrInsertFunction(
488 "__stack_chk_fail", Type::getVoidTy(Context), NULL);
489 B.CreateCall(StackChkFail);
491 B.CreateUnreachable();