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/Intrinsics.h"
40 #include "llvm/IR/MDBuilder.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/IR/User.h"
44 #include "llvm/Pass.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
53 #define DEBUG_TYPE "stack-protector"
55 STATISTIC(NumFunProtected, "Number of functions protected");
56 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
59 static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
60 cl::init(true), cl::Hidden);
62 char StackProtector::ID = 0;
64 INITIALIZE_PASS_BEGIN(StackProtector, DEBUG_TYPE,
65 "Insert stack protectors", false, true)
66 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
67 INITIALIZE_PASS_END(StackProtector, DEBUG_TYPE,
68 "Insert stack protectors", false, true)
70 FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
72 StackProtector::SSPLayoutKind
73 StackProtector::getSSPLayout(const AllocaInst *AI) const {
74 return AI ? Layout.lookup(AI) : SSPLK_None;
77 void StackProtector::adjustForColoring(const AllocaInst *From,
78 const AllocaInst *To) {
79 // When coloring replaces one alloca with another, transfer the SSPLayoutKind
80 // tag from the remapped to the target alloca. The remapped alloca should
81 // have a size smaller than or equal to the replacement alloca.
82 SSPLayoutMap::iterator I = Layout.find(From);
83 if (I != Layout.end()) {
84 SSPLayoutKind Kind = I->second;
87 // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
88 // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
89 // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
91 if (I == Layout.end())
92 Layout.insert(std::make_pair(To, Kind));
93 else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
98 void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
99 AU.addRequired<TargetPassConfig>();
100 AU.addPreserved<DominatorTreeWrapperPass>();
103 bool StackProtector::runOnFunction(Function &Fn) {
106 DominatorTreeWrapperPass *DTWP =
107 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
108 DT = DTWP ? &DTWP->getDomTree() : nullptr;
109 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
110 Trip = TM->getTargetTriple();
111 TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
115 Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
116 if (Attr.isStringAttribute() &&
117 Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
118 return false; // Invalid integer string
120 if (!RequiresStackProtector())
123 // TODO(etienneb): Functions with funclets are not correctly supported now.
124 // Do nothing if this is funclet-based personality.
125 if (Fn.hasPersonalityFn()) {
126 EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
127 if (isFuncletEHPersonality(Personality))
132 return InsertStackProtectors();
135 /// \param [out] IsLarge is set to true if a protectable array is found and
136 /// it is "large" ( >= ssp-buffer-size). In the case of a structure with
137 /// multiple arrays, this gets set if any of them is large.
138 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
140 bool InStruct) const {
143 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
144 if (!AT->getElementType()->isIntegerTy(8)) {
145 // If we're on a non-Darwin platform or we're inside of a structure, don't
146 // add stack protectors unless the array is a character array.
147 // However, in strong mode any array, regardless of type and size,
148 // triggers a protector.
149 if (!Strong && (InStruct || !Trip.isOSDarwin()))
153 // If an array has more than SSPBufferSize bytes of allocated space, then we
154 // emit stack protectors.
155 if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
161 // Require a protector for all arrays in strong mode
165 const StructType *ST = dyn_cast<StructType>(Ty);
169 bool NeedsProtector = false;
170 for (StructType::element_iterator I = ST->element_begin(),
171 E = ST->element_end();
173 if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
174 // If the element is a protectable array and is large (>= SSPBufferSize)
175 // then we are done. If the protectable array is not large, then
176 // keep looking in case a subsequent element is a large array.
179 NeedsProtector = true;
182 return NeedsProtector;
185 bool StackProtector::HasAddressTaken(const Instruction *AI) {
186 for (const User *U : AI->users()) {
187 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
188 if (AI == SI->getValueOperand())
190 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
191 if (AI == SI->getOperand(0))
193 } else if (isa<CallInst>(U)) {
195 } else if (isa<InvokeInst>(U)) {
197 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
198 if (HasAddressTaken(SI))
200 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
201 // Keep track of what PHI nodes we have already visited to ensure
202 // they are only visited once.
203 if (VisitedPHIs.insert(PN).second)
204 if (HasAddressTaken(PN))
206 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
207 if (HasAddressTaken(GEP))
209 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
210 if (HasAddressTaken(BI))
217 /// \brief Check whether or not this function needs a stack protector based
218 /// upon the stack protector level.
220 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
221 /// The standard heuristic which will add a guard variable to functions that
222 /// call alloca with a either a variable size or a size >= SSPBufferSize,
223 /// functions with character buffers larger than SSPBufferSize, and functions
224 /// with aggregates containing character buffers larger than SSPBufferSize. The
225 /// strong heuristic will add a guard variables to functions that call alloca
226 /// regardless of size, functions with any buffer regardless of type and size,
227 /// functions with aggregates that contain any buffer regardless of type and
228 /// size, and functions that contain stack-based variables that have had their
230 bool StackProtector::RequiresStackProtector() {
232 bool NeedsProtector = false;
233 for (const BasicBlock &BB : *F)
234 for (const Instruction &I : BB)
235 if (const CallInst *CI = dyn_cast<CallInst>(&I))
236 if (CI->getCalledFunction() ==
237 Intrinsic::getDeclaration(F->getParent(),
238 Intrinsic::stackprotector))
241 if (F->hasFnAttribute(Attribute::SafeStack))
244 // We are constructing the OptimizationRemarkEmitter on the fly rather than
245 // using the analysis pass to avoid building DominatorTree and LoopInfo which
246 // are not available this late in the IR pipeline.
247 OptimizationRemarkEmitter ORE(F);
249 if (F->hasFnAttribute(Attribute::StackProtectReq)) {
251 return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
252 << "Stack protection applied to function "
253 << ore::NV("Function", F)
254 << " due to a function attribute or command-line switch";
256 NeedsProtector = true;
257 Strong = true; // Use the same heuristic as strong to determine SSPLayout
258 } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
260 else if (HasPrologue)
261 NeedsProtector = true;
262 else if (!F->hasFnAttribute(Attribute::StackProtect))
265 for (const BasicBlock &BB : *F) {
266 for (const Instruction &I : BB) {
267 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
268 if (AI->isArrayAllocation()) {
269 auto RemarkBuilder = [&]() {
270 return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
272 << "Stack protection applied to function "
273 << ore::NV("Function", F)
274 << " due to a call to alloca or use of a variable length "
277 if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
278 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
279 // A call to alloca with size >= SSPBufferSize requires
281 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
282 ORE.emit(RemarkBuilder);
283 NeedsProtector = true;
285 // Require protectors for all alloca calls in strong mode.
286 Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
287 ORE.emit(RemarkBuilder);
288 NeedsProtector = true;
291 // A call to alloca with a variable size requires protectors.
292 Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
293 ORE.emit(RemarkBuilder);
294 NeedsProtector = true;
299 bool IsLarge = false;
300 if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
301 Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
302 : SSPLK_SmallArray));
304 return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
305 << "Stack protection applied to function "
306 << ore::NV("Function", F)
307 << " due to a stack allocated buffer or struct containing a "
310 NeedsProtector = true;
314 if (Strong && HasAddressTaken(AI)) {
316 Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
318 return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
320 << "Stack protection applied to function "
321 << ore::NV("Function", F)
322 << " due to the address of a local variable being taken";
324 NeedsProtector = true;
330 return NeedsProtector;
333 /// Create a stack guard loading and populate whether SelectionDAG SSP is
335 static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
337 bool *SupportsSelectionDAGSP = nullptr) {
338 if (Value *Guard = TLI->getIRStackGuard(B))
339 return B.CreateLoad(Guard, true, "StackGuard");
341 // Use SelectionDAG SSP handling, since there isn't an IR guard.
343 // This is more or less weird, since we optionally output whether we
344 // should perform a SelectionDAG SP here. The reason is that it's strictly
345 // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
346 // mutating. There is no way to get this bit without mutating the IR, so
347 // getting this bit has to happen in this right time.
349 // We could have define a new function TLI::supportsSelectionDAGSP(), but that
350 // will put more burden on the backends' overriding work, especially when it
351 // actually conveys the same information getIRStackGuard() already gives.
352 if (SupportsSelectionDAGSP)
353 *SupportsSelectionDAGSP = true;
354 TLI->insertSSPDeclarations(*M);
355 return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
358 /// Insert code into the entry block that stores the stack guard
359 /// variable onto the stack:
362 /// StackGuardSlot = alloca i8*
363 /// StackGuard = <stack guard>
364 /// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
366 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
368 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
369 const TargetLoweringBase *TLI, AllocaInst *&AI) {
370 bool SupportsSelectionDAGSP = false;
371 IRBuilder<> B(&F->getEntryBlock().front());
372 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
373 AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
375 Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
376 B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
378 return SupportsSelectionDAGSP;
381 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
384 /// - The prologue code loads and stores the stack guard onto the stack.
385 /// - The epilogue checks the value stored in the prologue against the original
386 /// value. It calls __stack_chk_fail if they differ.
387 bool StackProtector::InsertStackProtectors() {
388 // If the target wants to XOR the frame pointer into the guard value, it's
389 // impossible to emit the check in IR, so the target *must* support stack
390 // protection in SDAG.
391 bool SupportsSelectionDAGSP =
392 TLI->useStackGuardXorFP() ||
393 (EnableSelectionDAGSP && !TM->Options.EnableFastISel);
394 AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
396 for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
397 BasicBlock *BB = &*I++;
398 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
402 // Generate prologue instrumentation if not already generated.
405 SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
408 // SelectionDAG based code generation. Nothing else needs to be done here.
409 // The epilogue instrumentation is postponed to SelectionDAG.
410 if (SupportsSelectionDAGSP)
413 // Set HasIRCheck to true, so that SelectionDAG will not generate its own
414 // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
415 // instrumentation has already been generated.
418 // Generate epilogue instrumentation. The epilogue intrumentation can be
419 // function-based or inlined depending on which mechanism the target is
421 if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
422 // Generate the function-based epilogue instrumentation.
423 // The target provides a guard check function, generate a call to it.
425 LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
426 CallInst *Call = B.CreateCall(GuardCheck, {Guard});
427 llvm::Function *Function = cast<llvm::Function>(GuardCheck);
428 Call->setAttributes(Function->getAttributes());
429 Call->setCallingConv(Function->getCallingConv());
431 // Generate the epilogue with inline instrumentation.
432 // If we do not support SelectionDAG based tail calls, generate IR level
435 // For each block with a return instruction, convert this:
445 // %1 = <stack guard>
446 // %2 = load StackGuardSlot
447 // %3 = cmp i1 %1, %2
448 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
453 // CallStackCheckFailBlk:
454 // call void @__stack_chk_fail()
457 // Create the FailBB. We duplicate the BB every time since the MI tail
458 // merge pass will merge together all of the various BB into one including
459 // fail BB generated by the stack protector pseudo instruction.
460 BasicBlock *FailBB = CreateFailBB();
462 // Split the basic block before the return instruction.
463 BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
465 // Update the dominator tree if we need to.
466 if (DT && DT->isReachableFromEntry(BB)) {
467 DT->addNewBlock(NewBB, BB);
468 DT->addNewBlock(FailBB, BB);
471 // Remove default branch instruction to the new BB.
472 BB->getTerminator()->eraseFromParent();
474 // Move the newly created basic block to the point right after the old
475 // basic block so that it's in the "fall through" position.
476 NewBB->moveAfter(BB);
478 // Generate the stack protector instructions in the old basic block.
480 Value *Guard = getStackGuard(TLI, M, B);
481 LoadInst *LI2 = B.CreateLoad(AI, true);
482 Value *Cmp = B.CreateICmpEQ(Guard, LI2);
484 BranchProbabilityInfo::getBranchProbStackProtector(true);
486 BranchProbabilityInfo::getBranchProbStackProtector(false);
487 MDNode *Weights = MDBuilder(F->getContext())
488 .createBranchWeights(SuccessProb.getNumerator(),
489 FailureProb.getNumerator());
490 B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
494 // Return if we didn't modify any basic blocks. i.e., there are no return
495 // statements in the function.
499 /// CreateFailBB - Create a basic block to jump to when the stack protector
501 BasicBlock *StackProtector::CreateFailBB() {
502 LLVMContext &Context = F->getContext();
503 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
504 IRBuilder<> B(FailBB);
505 B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
506 if (Trip.isOSOpenBSD()) {
507 Constant *StackChkFail =
508 M->getOrInsertFunction("__stack_smash_handler",
509 Type::getVoidTy(Context),
510 Type::getInt8PtrTy(Context));
512 B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
514 Constant *StackChkFail =
515 M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
517 B.CreateCall(StackChkFail, {});
519 B.CreateUnreachable();
523 bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
524 return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());