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/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/BranchProbabilityInfo.h"
20 #include "llvm/Analysis/EHPersonalities.h"
21 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/StackProtector.h"
24 #include "llvm/CodeGen/TargetPassConfig.h"
25 #include "llvm/IR/Attributes.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/DebugLoc.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/MDBuilder.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/IR/User.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Target/TargetLowering.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Target/TargetSubtargetInfo.h"
52 #define DEBUG_TYPE "stack-protector"
54 STATISTIC(NumFunProtected, "Number of functions protected");
55 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
58 static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
59 cl::init(true), cl::Hidden);
61 char StackProtector::ID = 0;
62 INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
63 "Insert stack protectors", false, true)
64 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
65 INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
66 "Insert stack protectors", false, true)
68 FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
70 StackProtector::SSPLayoutKind
71 StackProtector::getSSPLayout(const AllocaInst *AI) const {
72 return AI ? Layout.lookup(AI) : SSPLK_None;
75 void StackProtector::adjustForColoring(const AllocaInst *From,
76 const AllocaInst *To) {
77 // When coloring replaces one alloca with another, transfer the SSPLayoutKind
78 // tag from the remapped to the target alloca. The remapped alloca should
79 // have a size smaller than or equal to the replacement alloca.
80 SSPLayoutMap::iterator I = Layout.find(From);
81 if (I != Layout.end()) {
82 SSPLayoutKind Kind = I->second;
85 // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
86 // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
87 // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
89 if (I == Layout.end())
90 Layout.insert(std::make_pair(To, Kind));
91 else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
96 void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
97 AU.addRequired<TargetPassConfig>();
98 AU.addPreserved<DominatorTreeWrapperPass>();
101 bool StackProtector::runOnFunction(Function &Fn) {
104 DominatorTreeWrapperPass *DTWP =
105 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
106 DT = DTWP ? &DTWP->getDomTree() : nullptr;
107 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
108 Trip = TM->getTargetTriple();
109 TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
113 Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
114 if (Attr.isStringAttribute() &&
115 Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
116 return false; // Invalid integer string
118 if (!RequiresStackProtector())
121 // TODO(etienneb): Functions with funclets are not correctly supported now.
122 // Do nothing if this is funclet-based personality.
123 if (Fn.hasPersonalityFn()) {
124 EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
125 if (isFuncletEHPersonality(Personality))
130 return InsertStackProtectors();
133 /// \param [out] IsLarge is set to true if a protectable array is found and
134 /// it is "large" ( >= ssp-buffer-size). In the case of a structure with
135 /// multiple arrays, this gets set if any of them is large.
136 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
138 bool InStruct) const {
141 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
142 if (!AT->getElementType()->isIntegerTy(8)) {
143 // If we're on a non-Darwin platform or we're inside of a structure, don't
144 // add stack protectors unless the array is a character array.
145 // However, in strong mode any array, regardless of type and size,
146 // triggers a protector.
147 if (!Strong && (InStruct || !Trip.isOSDarwin()))
151 // If an array has more than SSPBufferSize bytes of allocated space, then we
152 // emit stack protectors.
153 if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
159 // Require a protector for all arrays in strong mode
163 const StructType *ST = dyn_cast<StructType>(Ty);
167 bool NeedsProtector = false;
168 for (StructType::element_iterator I = ST->element_begin(),
169 E = ST->element_end();
171 if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
172 // If the element is a protectable array and is large (>= SSPBufferSize)
173 // then we are done. If the protectable array is not large, then
174 // keep looking in case a subsequent element is a large array.
177 NeedsProtector = true;
180 return NeedsProtector;
183 bool StackProtector::HasAddressTaken(const Instruction *AI) {
184 for (const User *U : AI->users()) {
185 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
186 if (AI == SI->getValueOperand())
188 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
189 if (AI == SI->getOperand(0))
191 } else if (isa<CallInst>(U)) {
193 } else if (isa<InvokeInst>(U)) {
195 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
196 if (HasAddressTaken(SI))
198 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
199 // Keep track of what PHI nodes we have already visited to ensure
200 // they are only visited once.
201 if (VisitedPHIs.insert(PN).second)
202 if (HasAddressTaken(PN))
204 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
205 if (HasAddressTaken(GEP))
207 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
208 if (HasAddressTaken(BI))
215 /// \brief Check whether or not this function needs a stack protector based
216 /// upon the stack protector level.
218 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
219 /// The standard heuristic which will add a guard variable to functions that
220 /// call alloca with a either a variable size or a size >= SSPBufferSize,
221 /// functions with character buffers larger than SSPBufferSize, and functions
222 /// with aggregates containing character buffers larger than SSPBufferSize. The
223 /// strong heuristic will add a guard variables to functions that call alloca
224 /// regardless of size, functions with any buffer regardless of type and size,
225 /// functions with aggregates that contain any buffer regardless of type and
226 /// size, and functions that contain stack-based variables that have had their
228 bool StackProtector::RequiresStackProtector() {
230 bool NeedsProtector = false;
231 for (const BasicBlock &BB : *F)
232 for (const Instruction &I : BB)
233 if (const CallInst *CI = dyn_cast<CallInst>(&I))
234 if (CI->getCalledFunction() ==
235 Intrinsic::getDeclaration(F->getParent(),
236 Intrinsic::stackprotector))
239 if (F->hasFnAttribute(Attribute::SafeStack))
242 // We are constructing the OptimizationRemarkEmitter on the fly rather than
243 // using the analysis pass to avoid building DominatorTree and LoopInfo which
244 // are not available this late in the IR pipeline.
245 OptimizationRemarkEmitter ORE(F);
247 if (F->hasFnAttribute(Attribute::StackProtectReq)) {
248 ORE.emit(OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
249 << "Stack protection applied to function "
250 << ore::NV("Function", F)
251 << " due to a function attribute or command-line switch");
252 NeedsProtector = true;
253 Strong = true; // Use the same heuristic as strong to determine SSPLayout
254 } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
256 else if (HasPrologue)
257 NeedsProtector = true;
258 else if (!F->hasFnAttribute(Attribute::StackProtect))
261 for (const BasicBlock &BB : *F) {
262 for (const Instruction &I : BB) {
263 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
264 if (AI->isArrayAllocation()) {
265 OptimizationRemark Remark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
268 << "Stack protection applied to function "
269 << ore::NV("Function", F)
270 << " due to a call to alloca or use of a variable length array";
271 if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
272 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
273 // A call to alloca with size >= SSPBufferSize requires
275 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
277 NeedsProtector = true;
279 // Require protectors for all alloca calls in strong mode.
280 Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
282 NeedsProtector = true;
285 // A call to alloca with a variable size requires protectors.
286 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
288 NeedsProtector = true;
293 bool IsLarge = false;
294 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
295 Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
296 : SSPLK_SmallArray));
297 ORE.emit(OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
298 << "Stack protection applied to function "
299 << ore::NV("Function", F)
300 << " due to a stack allocated buffer or struct containing a "
302 NeedsProtector = true;
306 if (Strong && HasAddressTaken(AI)) {
308 Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
310 OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken", &I)
311 << "Stack protection applied to function "
312 << ore::NV("Function", F)
313 << " due to the address of a local variable being taken");
314 NeedsProtector = true;
320 return NeedsProtector;
323 /// Create a stack guard loading and populate whether SelectionDAG SSP is
325 static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
327 bool *SupportsSelectionDAGSP = nullptr) {
328 if (Value *Guard = TLI->getIRStackGuard(B))
329 return B.CreateLoad(Guard, true, "StackGuard");
331 // Use SelectionDAG SSP handling, since there isn't an IR guard.
333 // This is more or less weird, since we optionally output whether we
334 // should perform a SelectionDAG SP here. The reason is that it's strictly
335 // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
336 // mutating. There is no way to get this bit without mutating the IR, so
337 // getting this bit has to happen in this right time.
339 // We could have define a new function TLI::supportsSelectionDAGSP(), but that
340 // will put more burden on the backends' overriding work, especially when it
341 // actually conveys the same information getIRStackGuard() already gives.
342 if (SupportsSelectionDAGSP)
343 *SupportsSelectionDAGSP = true;
344 TLI->insertSSPDeclarations(*M);
345 return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
348 /// Insert code into the entry block that stores the stack guard
349 /// variable onto the stack:
352 /// StackGuardSlot = alloca i8*
353 /// StackGuard = <stack guard>
354 /// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
356 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
358 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
359 const TargetLoweringBase *TLI, AllocaInst *&AI) {
360 bool SupportsSelectionDAGSP = false;
361 IRBuilder<> B(&F->getEntryBlock().front());
362 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
363 AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
365 Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
366 B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
368 return SupportsSelectionDAGSP;
371 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
374 /// - The prologue code loads and stores the stack guard onto the stack.
375 /// - The epilogue checks the value stored in the prologue against the original
376 /// value. It calls __stack_chk_fail if they differ.
377 bool StackProtector::InsertStackProtectors() {
378 bool SupportsSelectionDAGSP =
379 EnableSelectionDAGSP && !TM->Options.EnableFastISel;
380 AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
382 for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
383 BasicBlock *BB = &*I++;
384 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
388 // Generate prologue instrumentation if not already generated.
391 SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
394 // SelectionDAG based code generation. Nothing else needs to be done here.
395 // The epilogue instrumentation is postponed to SelectionDAG.
396 if (SupportsSelectionDAGSP)
399 // Set HasIRCheck to true, so that SelectionDAG will not generate its own
400 // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
401 // instrumentation has already been generated.
404 // Generate epilogue instrumentation. The epilogue intrumentation can be
405 // function-based or inlined depending on which mechanism the target is
407 if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
408 // Generate the function-based epilogue instrumentation.
409 // The target provides a guard check function, generate a call to it.
411 LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
412 CallInst *Call = B.CreateCall(GuardCheck, {Guard});
413 llvm::Function *Function = cast<llvm::Function>(GuardCheck);
414 Call->setAttributes(Function->getAttributes());
415 Call->setCallingConv(Function->getCallingConv());
417 // Generate the epilogue with inline instrumentation.
418 // If we do not support SelectionDAG based tail calls, generate IR level
421 // For each block with a return instruction, convert this:
431 // %1 = <stack guard>
432 // %2 = load StackGuardSlot
433 // %3 = cmp i1 %1, %2
434 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
439 // CallStackCheckFailBlk:
440 // call void @__stack_chk_fail()
443 // Create the FailBB. We duplicate the BB every time since the MI tail
444 // merge pass will merge together all of the various BB into one including
445 // fail BB generated by the stack protector pseudo instruction.
446 BasicBlock *FailBB = CreateFailBB();
448 // Split the basic block before the return instruction.
449 BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
451 // Update the dominator tree if we need to.
452 if (DT && DT->isReachableFromEntry(BB)) {
453 DT->addNewBlock(NewBB, BB);
454 DT->addNewBlock(FailBB, BB);
457 // Remove default branch instruction to the new BB.
458 BB->getTerminator()->eraseFromParent();
460 // Move the newly created basic block to the point right after the old
461 // basic block so that it's in the "fall through" position.
462 NewBB->moveAfter(BB);
464 // Generate the stack protector instructions in the old basic block.
466 Value *Guard = getStackGuard(TLI, M, B);
467 LoadInst *LI2 = B.CreateLoad(AI, true);
468 Value *Cmp = B.CreateICmpEQ(Guard, LI2);
470 BranchProbabilityInfo::getBranchProbStackProtector(true);
472 BranchProbabilityInfo::getBranchProbStackProtector(false);
473 MDNode *Weights = MDBuilder(F->getContext())
474 .createBranchWeights(SuccessProb.getNumerator(),
475 FailureProb.getNumerator());
476 B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
480 // Return if we didn't modify any basic blocks. i.e., there are no return
481 // 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 B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
492 if (Trip.isOSOpenBSD()) {
493 Constant *StackChkFail =
494 M->getOrInsertFunction("__stack_smash_handler",
495 Type::getVoidTy(Context),
496 Type::getInt8PtrTy(Context));
498 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
500 Constant *StackChkFail =
501 M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
503 B.CreateCall(StackChkFail, {});
505 B.CreateUnreachable();
509 bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
510 return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());