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