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/BranchProbabilityInfo.h"
21 #include "llvm/Analysis/EHPersonalities.h"
22 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/TargetLowering.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/CodeGen/TargetSubtargetInfo.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/DebugLoc.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/IRBuilder.h"
37 #include "llvm/IR/Instruction.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/MDBuilder.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/IR/User.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
54 #define DEBUG_TYPE "stack-protector"
56 STATISTIC(NumFunProtected, "Number of functions protected");
57 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
60 static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
61 cl::init(true), cl::Hidden);
63 char StackProtector::ID = 0;
65 INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
66 "Insert stack protectors", false, true)
67 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
68 INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
69 "Insert stack protectors", false, true)
71 FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
73 void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.addRequired<TargetPassConfig>();
75 AU.addPreserved<DominatorTreeWrapperPass>();
78 bool StackProtector::runOnFunction(Function &Fn) {
81 DominatorTreeWrapperPass *DTWP =
82 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
83 DT = DTWP ? &DTWP->getDomTree() : nullptr;
84 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
85 Trip = TM->getTargetTriple();
86 TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
90 Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
91 if (Attr.isStringAttribute() &&
92 Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
93 return false; // Invalid integer string
95 if (!RequiresStackProtector())
98 // TODO(etienneb): Functions with funclets are not correctly supported now.
99 // Do nothing if this is funclet-based personality.
100 if (Fn.hasPersonalityFn()) {
101 EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
102 if (isFuncletEHPersonality(Personality))
107 return InsertStackProtectors();
110 /// \param [out] IsLarge is set to true if a protectable array is found and
111 /// it is "large" ( >= ssp-buffer-size). In the case of a structure with
112 /// multiple arrays, this gets set if any of them is large.
113 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
115 bool InStruct) const {
118 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
119 if (!AT->getElementType()->isIntegerTy(8)) {
120 // If we're on a non-Darwin platform or we're inside of a structure, don't
121 // add stack protectors unless the array is a character array.
122 // However, in strong mode any array, regardless of type and size,
123 // triggers a protector.
124 if (!Strong && (InStruct || !Trip.isOSDarwin()))
128 // If an array has more than SSPBufferSize bytes of allocated space, then we
129 // emit stack protectors.
130 if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
136 // Require a protector for all arrays in strong mode
140 const StructType *ST = dyn_cast<StructType>(Ty);
144 bool NeedsProtector = false;
145 for (StructType::element_iterator I = ST->element_begin(),
146 E = ST->element_end();
148 if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
149 // If the element is a protectable array and is large (>= SSPBufferSize)
150 // then we are done. If the protectable array is not large, then
151 // keep looking in case a subsequent element is a large array.
154 NeedsProtector = true;
157 return NeedsProtector;
160 bool StackProtector::HasAddressTaken(const Instruction *AI) {
161 for (const User *U : AI->users()) {
162 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
163 if (AI == SI->getValueOperand())
165 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
166 if (AI == SI->getOperand(0))
168 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
169 // Ignore intrinsics that are not calls. TODO: Use isLoweredToCall().
170 if (!isa<DbgInfoIntrinsic>(CI) && !CI->isLifetimeStartOrEnd())
172 } else if (isa<InvokeInst>(U)) {
174 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
175 if (HasAddressTaken(SI))
177 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
178 // Keep track of what PHI nodes we have already visited to ensure
179 // they are only visited once.
180 if (VisitedPHIs.insert(PN).second)
181 if (HasAddressTaken(PN))
183 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
184 if (HasAddressTaken(GEP))
186 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
187 if (HasAddressTaken(BI))
194 /// Search for the first call to the llvm.stackprotector intrinsic and return it
196 static const CallInst *findStackProtectorIntrinsic(Function &F) {
197 for (const BasicBlock &BB : F)
198 for (const Instruction &I : BB)
199 if (const CallInst *CI = dyn_cast<CallInst>(&I))
200 if (CI->getCalledFunction() ==
201 Intrinsic::getDeclaration(F.getParent(), Intrinsic::stackprotector))
206 /// Check whether or not this function needs a stack protector based
207 /// upon the stack protector level.
209 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
210 /// The standard heuristic which will add a guard variable to functions that
211 /// call alloca with a either a variable size or a size >= SSPBufferSize,
212 /// functions with character buffers larger than SSPBufferSize, and functions
213 /// with aggregates containing character buffers larger than SSPBufferSize. The
214 /// strong heuristic will add a guard variables to functions that call alloca
215 /// regardless of size, functions with any buffer regardless of type and size,
216 /// functions with aggregates that contain any buffer regardless of type and
217 /// size, and functions that contain stack-based variables that have had their
219 bool StackProtector::RequiresStackProtector() {
221 bool NeedsProtector = false;
222 HasPrologue = findStackProtectorIntrinsic(*F);
224 if (F->hasFnAttribute(Attribute::SafeStack))
227 // We are constructing the OptimizationRemarkEmitter on the fly rather than
228 // using the analysis pass to avoid building DominatorTree and LoopInfo which
229 // are not available this late in the IR pipeline.
230 OptimizationRemarkEmitter ORE(F);
232 if (F->hasFnAttribute(Attribute::StackProtectReq)) {
234 return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
235 << "Stack protection applied to function "
236 << ore::NV("Function", F)
237 << " due to a function attribute or command-line switch";
239 NeedsProtector = true;
240 Strong = true; // Use the same heuristic as strong to determine SSPLayout
241 } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
243 else if (HasPrologue)
244 NeedsProtector = true;
245 else if (!F->hasFnAttribute(Attribute::StackProtect))
248 for (const BasicBlock &BB : *F) {
249 for (const Instruction &I : BB) {
250 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
251 if (AI->isArrayAllocation()) {
252 auto RemarkBuilder = [&]() {
253 return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
255 << "Stack protection applied to function "
256 << ore::NV("Function", F)
257 << " due to a call to alloca or use of a variable length "
260 if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
261 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
262 // A call to alloca with size >= SSPBufferSize requires
264 Layout.insert(std::make_pair(AI,
265 MachineFrameInfo::SSPLK_LargeArray));
266 ORE.emit(RemarkBuilder);
267 NeedsProtector = true;
269 // Require protectors for all alloca calls in strong mode.
270 Layout.insert(std::make_pair(AI,
271 MachineFrameInfo::SSPLK_SmallArray));
272 ORE.emit(RemarkBuilder);
273 NeedsProtector = true;
276 // A call to alloca with a variable size requires protectors.
277 Layout.insert(std::make_pair(AI,
278 MachineFrameInfo::SSPLK_LargeArray));
279 ORE.emit(RemarkBuilder);
280 NeedsProtector = true;
285 bool IsLarge = false;
286 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
287 Layout.insert(std::make_pair(AI, IsLarge
288 ? MachineFrameInfo::SSPLK_LargeArray
289 : MachineFrameInfo::SSPLK_SmallArray));
291 return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
292 << "Stack protection applied to function "
293 << ore::NV("Function", F)
294 << " due to a stack allocated buffer or struct containing a "
297 NeedsProtector = true;
301 if (Strong && HasAddressTaken(AI)) {
303 Layout.insert(std::make_pair(AI, MachineFrameInfo::SSPLK_AddrOf));
305 return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
307 << "Stack protection applied to function "
308 << ore::NV("Function", F)
309 << " due to the address of a local variable being taken";
311 NeedsProtector = true;
317 return NeedsProtector;
320 /// Create a stack guard loading and populate whether SelectionDAG SSP is
322 static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
324 bool *SupportsSelectionDAGSP = nullptr) {
325 if (Value *Guard = TLI->getIRStackGuard(B))
326 return B.CreateLoad(Guard, true, "StackGuard");
328 // Use SelectionDAG SSP handling, since there isn't an IR guard.
330 // This is more or less weird, since we optionally output whether we
331 // should perform a SelectionDAG SP here. The reason is that it's strictly
332 // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
333 // mutating. There is no way to get this bit without mutating the IR, so
334 // getting this bit has to happen in this right time.
336 // We could have define a new function TLI::supportsSelectionDAGSP(), but that
337 // will put more burden on the backends' overriding work, especially when it
338 // actually conveys the same information getIRStackGuard() already gives.
339 if (SupportsSelectionDAGSP)
340 *SupportsSelectionDAGSP = true;
341 TLI->insertSSPDeclarations(*M);
342 return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
345 /// Insert code into the entry block that stores the stack guard
346 /// variable onto the stack:
349 /// StackGuardSlot = alloca i8*
350 /// StackGuard = <stack guard>
351 /// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
353 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
355 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
356 const TargetLoweringBase *TLI, AllocaInst *&AI) {
357 bool SupportsSelectionDAGSP = false;
358 IRBuilder<> B(&F->getEntryBlock().front());
359 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
360 AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
362 Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
363 B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
365 return SupportsSelectionDAGSP;
368 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
371 /// - The prologue code loads and stores the stack guard onto the stack.
372 /// - The epilogue checks the value stored in the prologue against the original
373 /// value. It calls __stack_chk_fail if they differ.
374 bool StackProtector::InsertStackProtectors() {
375 // If the target wants to XOR the frame pointer into the guard value, it's
376 // impossible to emit the check in IR, so the target *must* support stack
377 // protection in SDAG.
378 bool SupportsSelectionDAGSP =
379 TLI->useStackGuardXorFP() ||
380 (EnableSelectionDAGSP && !TM->Options.EnableFastISel &&
381 !TM->Options.EnableGlobalISel);
382 AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
384 for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
385 BasicBlock *BB = &*I++;
386 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
390 // Generate prologue instrumentation if not already generated.
393 SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
396 // SelectionDAG based code generation. Nothing else needs to be done here.
397 // The epilogue instrumentation is postponed to SelectionDAG.
398 if (SupportsSelectionDAGSP)
401 // Find the stack guard slot if the prologue was not created by this pass
402 // itself via a previous call to CreatePrologue().
404 const CallInst *SPCall = findStackProtectorIntrinsic(*F);
405 assert(SPCall && "Call to llvm.stackprotector is missing");
406 AI = cast<AllocaInst>(SPCall->getArgOperand(1));
409 // Set HasIRCheck to true, so that SelectionDAG will not generate its own
410 // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
411 // instrumentation has already been generated.
414 // Generate epilogue instrumentation. The epilogue intrumentation can be
415 // function-based or inlined depending on which mechanism the target is
417 if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
418 // Generate the function-based epilogue instrumentation.
419 // The target provides a guard check function, generate a call to it.
421 LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
422 CallInst *Call = B.CreateCall(GuardCheck, {Guard});
423 llvm::Function *Function = cast<llvm::Function>(GuardCheck);
424 Call->setAttributes(Function->getAttributes());
425 Call->setCallingConv(Function->getCallingConv());
427 // Generate the epilogue with inline instrumentation.
428 // If we do not support SelectionDAG based tail calls, generate IR level
431 // For each block with a return instruction, convert this:
441 // %1 = <stack guard>
442 // %2 = load StackGuardSlot
443 // %3 = cmp i1 %1, %2
444 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
449 // CallStackCheckFailBlk:
450 // call void @__stack_chk_fail()
453 // Create the FailBB. We duplicate the BB every time since the MI tail
454 // merge pass will merge together all of the various BB into one including
455 // fail BB generated by the stack protector pseudo instruction.
456 BasicBlock *FailBB = CreateFailBB();
458 // Split the basic block before the return instruction.
459 BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
461 // Update the dominator tree if we need to.
462 if (DT && DT->isReachableFromEntry(BB)) {
463 DT->addNewBlock(NewBB, BB);
464 DT->addNewBlock(FailBB, BB);
467 // Remove default branch instruction to the new BB.
468 BB->getTerminator()->eraseFromParent();
470 // Move the newly created basic block to the point right after the old
471 // basic block so that it's in the "fall through" position.
472 NewBB->moveAfter(BB);
474 // Generate the stack protector instructions in the old basic block.
476 Value *Guard = getStackGuard(TLI, M, B);
477 LoadInst *LI2 = B.CreateLoad(AI, true);
478 Value *Cmp = B.CreateICmpEQ(Guard, LI2);
480 BranchProbabilityInfo::getBranchProbStackProtector(true);
482 BranchProbabilityInfo::getBranchProbStackProtector(false);
483 MDNode *Weights = MDBuilder(F->getContext())
484 .createBranchWeights(SuccessProb.getNumerator(),
485 FailureProb.getNumerator());
486 B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
490 // Return if we didn't modify any basic blocks. i.e., there are no return
491 // statements in the function.
495 /// CreateFailBB - Create a basic block to jump to when the stack protector
497 BasicBlock *StackProtector::CreateFailBB() {
498 LLVMContext &Context = F->getContext();
499 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
500 IRBuilder<> B(FailBB);
501 B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
502 if (Trip.isOSOpenBSD()) {
503 Constant *StackChkFail =
504 M->getOrInsertFunction("__stack_smash_handler",
505 Type::getVoidTy(Context),
506 Type::getInt8PtrTy(Context));
508 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
510 Constant *StackChkFail =
511 M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
513 B.CreateCall(StackChkFail, {});
515 B.CreateUnreachable();
519 bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
520 return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
523 void StackProtector::copyToMachineFrameInfo(MachineFrameInfo &MFI) const {
527 for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
528 if (MFI.isDeadObjectIndex(I))
531 const AllocaInst *AI = MFI.getObjectAllocation(I);
535 SSPLayoutMap::const_iterator LI = Layout.find(AI);
536 if (LI == Layout.end())
539 MFI.setObjectSSPLayout(I, LI->second);