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