1 //===- StackProtector.cpp - Stack Protector Insertion ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
14 //
15 //===----------------------------------------------------------------------===//
16 
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"
50 #include <utility>
51 
52 using namespace llvm;
53 
54 #define DEBUG_TYPE "stack-protector"
55 
56 STATISTIC(NumFunProtected, "Number of functions protected");
57 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
58                         " taken.");
59 
60 static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
61                                           cl::init(true), cl::Hidden);
62 
63 char StackProtector::ID = 0;
64 
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)
70 
71 FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
72 
73 StackProtector::SSPLayoutKind
74 StackProtector::getSSPLayout(const AllocaInst *AI) const {
75   return AI ? Layout.lookup(AI) : SSPLK_None;
76 }
77 
78 void StackProtector::adjustForColoring(const AllocaInst *From,
79                                        const AllocaInst *To) {
80   // When coloring replaces one alloca with another, transfer the SSPLayoutKind
81   // tag from the remapped to the target alloca. The remapped alloca should
82   // have a size smaller than or equal to the replacement alloca.
83   SSPLayoutMap::iterator I = Layout.find(From);
84   if (I != Layout.end()) {
85     SSPLayoutKind Kind = I->second;
86     Layout.erase(I);
87 
88     // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
89     // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
90     // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
91     I = Layout.find(To);
92     if (I == Layout.end())
93       Layout.insert(std::make_pair(To, Kind));
94     else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
95       I->second = Kind;
96   }
97 }
98 
99 void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
100   AU.addRequired<TargetPassConfig>();
101   AU.addPreserved<DominatorTreeWrapperPass>();
102 }
103 
104 bool StackProtector::runOnFunction(Function &Fn) {
105   F = &Fn;
106   M = F->getParent();
107   DominatorTreeWrapperPass *DTWP =
108       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
109   DT = DTWP ? &DTWP->getDomTree() : nullptr;
110   TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
111   Trip = TM->getTargetTriple();
112   TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
113   HasPrologue = false;
114   HasIRCheck = false;
115 
116   Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
117   if (Attr.isStringAttribute() &&
118       Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
119     return false; // Invalid integer string
120 
121   if (!RequiresStackProtector())
122     return false;
123 
124   // TODO(etienneb): Functions with funclets are not correctly supported now.
125   // Do nothing if this is funclet-based personality.
126   if (Fn.hasPersonalityFn()) {
127     EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
128     if (isFuncletEHPersonality(Personality))
129       return false;
130   }
131 
132   ++NumFunProtected;
133   return InsertStackProtectors();
134 }
135 
136 /// \param [out] IsLarge is set to true if a protectable array is found and
137 /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
138 /// multiple arrays, this gets set if any of them is large.
139 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
140                                               bool Strong,
141                                               bool InStruct) const {
142   if (!Ty)
143     return false;
144   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
145     if (!AT->getElementType()->isIntegerTy(8)) {
146       // If we're on a non-Darwin platform or we're inside of a structure, don't
147       // add stack protectors unless the array is a character array.
148       // However, in strong mode any array, regardless of type and size,
149       // triggers a protector.
150       if (!Strong && (InStruct || !Trip.isOSDarwin()))
151         return false;
152     }
153 
154     // If an array has more than SSPBufferSize bytes of allocated space, then we
155     // emit stack protectors.
156     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
157       IsLarge = true;
158       return true;
159     }
160 
161     if (Strong)
162       // Require a protector for all arrays in strong mode
163       return true;
164   }
165 
166   const StructType *ST = dyn_cast<StructType>(Ty);
167   if (!ST)
168     return false;
169 
170   bool NeedsProtector = false;
171   for (StructType::element_iterator I = ST->element_begin(),
172                                     E = ST->element_end();
173        I != E; ++I)
174     if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
175       // If the element is a protectable array and is large (>= SSPBufferSize)
176       // then we are done.  If the protectable array is not large, then
177       // keep looking in case a subsequent element is a large array.
178       if (IsLarge)
179         return true;
180       NeedsProtector = true;
181     }
182 
183   return NeedsProtector;
184 }
185 
186 static bool isLifetimeInst(const Instruction *I) {
187   if (const auto Intrinsic = dyn_cast<IntrinsicInst>(I)) {
188     const auto Id = Intrinsic->getIntrinsicID();
189     return Id == Intrinsic::lifetime_start || Id == Intrinsic::lifetime_end;
190   }
191   return false;
192 }
193 
194 bool StackProtector::HasAddressTaken(const Instruction *AI) {
195   for (const User *U : AI->users()) {
196     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
197       if (AI == SI->getValueOperand())
198         return true;
199     } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
200       if (AI == SI->getOperand(0))
201         return true;
202     } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
203       // Ignore intrinsics that are not calls. TODO: Use isLoweredToCall().
204       if (!isa<DbgInfoIntrinsic>(CI) && !isLifetimeInst(CI))
205         return true;
206     } else if (isa<InvokeInst>(U)) {
207       return true;
208     } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
209       if (HasAddressTaken(SI))
210         return true;
211     } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
212       // Keep track of what PHI nodes we have already visited to ensure
213       // they are only visited once.
214       if (VisitedPHIs.insert(PN).second)
215         if (HasAddressTaken(PN))
216           return true;
217     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
218       if (HasAddressTaken(GEP))
219         return true;
220     } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
221       if (HasAddressTaken(BI))
222         return true;
223     }
224   }
225   return false;
226 }
227 
228 /// Check whether or not this function needs a stack protector based
229 /// upon the stack protector level.
230 ///
231 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
232 /// The standard heuristic which will add a guard variable to functions that
233 /// call alloca with a either a variable size or a size >= SSPBufferSize,
234 /// functions with character buffers larger than SSPBufferSize, and functions
235 /// with aggregates containing character buffers larger than SSPBufferSize. The
236 /// strong heuristic will add a guard variables to functions that call alloca
237 /// regardless of size, functions with any buffer regardless of type and size,
238 /// functions with aggregates that contain any buffer regardless of type and
239 /// size, and functions that contain stack-based variables that have had their
240 /// address taken.
241 bool StackProtector::RequiresStackProtector() {
242   bool Strong = false;
243   bool NeedsProtector = false;
244   for (const BasicBlock &BB : *F)
245     for (const Instruction &I : BB)
246       if (const CallInst *CI = dyn_cast<CallInst>(&I))
247         if (CI->getCalledFunction() ==
248             Intrinsic::getDeclaration(F->getParent(),
249                                       Intrinsic::stackprotector))
250           HasPrologue = true;
251 
252   if (F->hasFnAttribute(Attribute::SafeStack))
253     return false;
254 
255   // We are constructing the OptimizationRemarkEmitter on the fly rather than
256   // using the analysis pass to avoid building DominatorTree and LoopInfo which
257   // are not available this late in the IR pipeline.
258   OptimizationRemarkEmitter ORE(F);
259 
260   if (F->hasFnAttribute(Attribute::StackProtectReq)) {
261     ORE.emit([&]() {
262       return OptimizationRemark(DEBUG_TYPE, "StackProtectorRequested", F)
263              << "Stack protection applied to function "
264              << ore::NV("Function", F)
265              << " due to a function attribute or command-line switch";
266     });
267     NeedsProtector = true;
268     Strong = true; // Use the same heuristic as strong to determine SSPLayout
269   } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
270     Strong = true;
271   else if (HasPrologue)
272     NeedsProtector = true;
273   else if (!F->hasFnAttribute(Attribute::StackProtect))
274     return false;
275 
276   for (const BasicBlock &BB : *F) {
277     for (const Instruction &I : BB) {
278       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
279         if (AI->isArrayAllocation()) {
280           auto RemarkBuilder = [&]() {
281             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAllocaOrArray",
282                                       &I)
283                    << "Stack protection applied to function "
284                    << ore::NV("Function", F)
285                    << " due to a call to alloca or use of a variable length "
286                       "array";
287           };
288           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
289             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
290               // A call to alloca with size >= SSPBufferSize requires
291               // stack protectors.
292               Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
293               ORE.emit(RemarkBuilder);
294               NeedsProtector = true;
295             } else if (Strong) {
296               // Require protectors for all alloca calls in strong mode.
297               Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
298               ORE.emit(RemarkBuilder);
299               NeedsProtector = true;
300             }
301           } else {
302             // A call to alloca with a variable size requires protectors.
303             Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
304             ORE.emit(RemarkBuilder);
305             NeedsProtector = true;
306           }
307           continue;
308         }
309 
310         bool IsLarge = false;
311         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
312           Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
313                                                    : SSPLK_SmallArray));
314           ORE.emit([&]() {
315             return OptimizationRemark(DEBUG_TYPE, "StackProtectorBuffer", &I)
316                    << "Stack protection applied to function "
317                    << ore::NV("Function", F)
318                    << " due to a stack allocated buffer or struct containing a "
319                       "buffer";
320           });
321           NeedsProtector = true;
322           continue;
323         }
324 
325         if (Strong && HasAddressTaken(AI)) {
326           ++NumAddrTaken;
327           Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
328           ORE.emit([&]() {
329             return OptimizationRemark(DEBUG_TYPE, "StackProtectorAddressTaken",
330                                       &I)
331                    << "Stack protection applied to function "
332                    << ore::NV("Function", F)
333                    << " due to the address of a local variable being taken";
334           });
335           NeedsProtector = true;
336         }
337       }
338     }
339   }
340 
341   return NeedsProtector;
342 }
343 
344 /// Create a stack guard loading and populate whether SelectionDAG SSP is
345 /// supported.
346 static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
347                             IRBuilder<> &B,
348                             bool *SupportsSelectionDAGSP = nullptr) {
349   if (Value *Guard = TLI->getIRStackGuard(B))
350     return B.CreateLoad(Guard, true, "StackGuard");
351 
352   // Use SelectionDAG SSP handling, since there isn't an IR guard.
353   //
354   // This is more or less weird, since we optionally output whether we
355   // should perform a SelectionDAG SP here. The reason is that it's strictly
356   // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
357   // mutating. There is no way to get this bit without mutating the IR, so
358   // getting this bit has to happen in this right time.
359   //
360   // We could have define a new function TLI::supportsSelectionDAGSP(), but that
361   // will put more burden on the backends' overriding work, especially when it
362   // actually conveys the same information getIRStackGuard() already gives.
363   if (SupportsSelectionDAGSP)
364     *SupportsSelectionDAGSP = true;
365   TLI->insertSSPDeclarations(*M);
366   return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
367 }
368 
369 /// Insert code into the entry block that stores the stack guard
370 /// variable onto the stack:
371 ///
372 ///   entry:
373 ///     StackGuardSlot = alloca i8*
374 ///     StackGuard = <stack guard>
375 ///     call void @llvm.stackprotector(StackGuard, StackGuardSlot)
376 ///
377 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
378 /// node.
379 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
380                            const TargetLoweringBase *TLI, AllocaInst *&AI) {
381   bool SupportsSelectionDAGSP = false;
382   IRBuilder<> B(&F->getEntryBlock().front());
383   PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
384   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
385 
386   Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
387   B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
388                {GuardSlot, AI});
389   return SupportsSelectionDAGSP;
390 }
391 
392 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
393 /// function.
394 ///
395 ///  - The prologue code loads and stores the stack guard onto the stack.
396 ///  - The epilogue checks the value stored in the prologue against the original
397 ///    value. It calls __stack_chk_fail if they differ.
398 bool StackProtector::InsertStackProtectors() {
399   // If the target wants to XOR the frame pointer into the guard value, it's
400   // impossible to emit the check in IR, so the target *must* support stack
401   // protection in SDAG.
402   bool SupportsSelectionDAGSP =
403       TLI->useStackGuardXorFP() ||
404       (EnableSelectionDAGSP && !TM->Options.EnableFastISel);
405   AllocaInst *AI = nullptr;       // Place on stack that stores the stack guard.
406 
407   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
408     BasicBlock *BB = &*I++;
409     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
410     if (!RI)
411       continue;
412 
413     // Generate prologue instrumentation if not already generated.
414     if (!HasPrologue) {
415       HasPrologue = true;
416       SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
417     }
418 
419     // SelectionDAG based code generation. Nothing else needs to be done here.
420     // The epilogue instrumentation is postponed to SelectionDAG.
421     if (SupportsSelectionDAGSP)
422       break;
423 
424     // Set HasIRCheck to true, so that SelectionDAG will not generate its own
425     // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
426     // instrumentation has already been generated.
427     HasIRCheck = true;
428 
429     // Generate epilogue instrumentation. The epilogue intrumentation can be
430     // function-based or inlined depending on which mechanism the target is
431     // providing.
432     if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
433       // Generate the function-based epilogue instrumentation.
434       // The target provides a guard check function, generate a call to it.
435       IRBuilder<> B(RI);
436       LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
437       CallInst *Call = B.CreateCall(GuardCheck, {Guard});
438       llvm::Function *Function = cast<llvm::Function>(GuardCheck);
439       Call->setAttributes(Function->getAttributes());
440       Call->setCallingConv(Function->getCallingConv());
441     } else {
442       // Generate the epilogue with inline instrumentation.
443       // If we do not support SelectionDAG based tail calls, generate IR level
444       // tail calls.
445       //
446       // For each block with a return instruction, convert this:
447       //
448       //   return:
449       //     ...
450       //     ret ...
451       //
452       // into this:
453       //
454       //   return:
455       //     ...
456       //     %1 = <stack guard>
457       //     %2 = load StackGuardSlot
458       //     %3 = cmp i1 %1, %2
459       //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
460       //
461       //   SP_return:
462       //     ret ...
463       //
464       //   CallStackCheckFailBlk:
465       //     call void @__stack_chk_fail()
466       //     unreachable
467 
468       // Create the FailBB. We duplicate the BB every time since the MI tail
469       // merge pass will merge together all of the various BB into one including
470       // fail BB generated by the stack protector pseudo instruction.
471       BasicBlock *FailBB = CreateFailBB();
472 
473       // Split the basic block before the return instruction.
474       BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
475 
476       // Update the dominator tree if we need to.
477       if (DT && DT->isReachableFromEntry(BB)) {
478         DT->addNewBlock(NewBB, BB);
479         DT->addNewBlock(FailBB, BB);
480       }
481 
482       // Remove default branch instruction to the new BB.
483       BB->getTerminator()->eraseFromParent();
484 
485       // Move the newly created basic block to the point right after the old
486       // basic block so that it's in the "fall through" position.
487       NewBB->moveAfter(BB);
488 
489       // Generate the stack protector instructions in the old basic block.
490       IRBuilder<> B(BB);
491       Value *Guard = getStackGuard(TLI, M, B);
492       LoadInst *LI2 = B.CreateLoad(AI, true);
493       Value *Cmp = B.CreateICmpEQ(Guard, LI2);
494       auto SuccessProb =
495           BranchProbabilityInfo::getBranchProbStackProtector(true);
496       auto FailureProb =
497           BranchProbabilityInfo::getBranchProbStackProtector(false);
498       MDNode *Weights = MDBuilder(F->getContext())
499                             .createBranchWeights(SuccessProb.getNumerator(),
500                                                  FailureProb.getNumerator());
501       B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
502     }
503   }
504 
505   // Return if we didn't modify any basic blocks. i.e., there are no return
506   // statements in the function.
507   return HasPrologue;
508 }
509 
510 /// CreateFailBB - Create a basic block to jump to when the stack protector
511 /// check fails.
512 BasicBlock *StackProtector::CreateFailBB() {
513   LLVMContext &Context = F->getContext();
514   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
515   IRBuilder<> B(FailBB);
516   B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
517   if (Trip.isOSOpenBSD()) {
518     Constant *StackChkFail =
519         M->getOrInsertFunction("__stack_smash_handler",
520                                Type::getVoidTy(Context),
521                                Type::getInt8PtrTy(Context));
522 
523     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
524   } else {
525     Constant *StackChkFail =
526         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
527 
528     B.CreateCall(StackChkFail, {});
529   }
530   B.CreateUnreachable();
531   return FailBB;
532 }
533 
534 bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
535   return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
536 }
537