xref: /llvm-project/llvm/lib/CodeGen/StackProtector.cpp (revision 527815f5b087be6b31d0cb21752c581d26769c8a)
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/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"
49 #include <utility>
50 
51 using namespace llvm;
52 
53 #define DEBUG_TYPE "stack-protector"
54 
55 STATISTIC(NumFunProtected, "Number of functions protected");
56 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
57                         " taken.");
58 
59 static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
60                                           cl::init(true), cl::Hidden);
61 
62 char StackProtector::ID = 0;
63 
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)
69 
70 FunctionPass *llvm::createStackProtectorPass() { return new StackProtector(); }
71 
72 void StackProtector::getAnalysisUsage(AnalysisUsage &AU) const {
73   AU.addRequired<TargetPassConfig>();
74   AU.addPreserved<DominatorTreeWrapperPass>();
75 }
76 
77 bool StackProtector::runOnFunction(Function &Fn) {
78   F = &Fn;
79   M = F->getParent();
80   DominatorTreeWrapperPass *DTWP =
81       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
82   DT = DTWP ? &DTWP->getDomTree() : nullptr;
83   TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
84   Trip = TM->getTargetTriple();
85   TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
86   HasPrologue = false;
87   HasIRCheck = false;
88 
89   Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
90   if (Attr.isStringAttribute() &&
91       Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
92     return false; // Invalid integer string
93 
94   if (!RequiresStackProtector())
95     return false;
96 
97   // TODO(etienneb): Functions with funclets are not correctly supported now.
98   // Do nothing if this is funclet-based personality.
99   if (Fn.hasPersonalityFn()) {
100     EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
101     if (isFuncletEHPersonality(Personality))
102       return false;
103   }
104 
105   ++NumFunProtected;
106   return InsertStackProtectors();
107 }
108 
109 /// \param [out] IsLarge is set to true if a protectable array is found and
110 /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
111 /// multiple arrays, this gets set if any of them is large.
112 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
113                                               bool Strong,
114                                               bool InStruct) const {
115   if (!Ty)
116     return false;
117   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
118     if (!AT->getElementType()->isIntegerTy(8)) {
119       // If we're on a non-Darwin platform or we're inside of a structure, don't
120       // add stack protectors unless the array is a character array.
121       // However, in strong mode any array, regardless of type and size,
122       // triggers a protector.
123       if (!Strong && (InStruct || !Trip.isOSDarwin()))
124         return false;
125     }
126 
127     // If an array has more than SSPBufferSize bytes of allocated space, then we
128     // emit stack protectors.
129     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
130       IsLarge = true;
131       return true;
132     }
133 
134     if (Strong)
135       // Require a protector for all arrays in strong mode
136       return true;
137   }
138 
139   const StructType *ST = dyn_cast<StructType>(Ty);
140   if (!ST)
141     return false;
142 
143   bool NeedsProtector = false;
144   for (StructType::element_iterator I = ST->element_begin(),
145                                     E = ST->element_end();
146        I != E; ++I)
147     if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
148       // If the element is a protectable array and is large (>= SSPBufferSize)
149       // then we are done.  If the protectable array is not large, then
150       // keep looking in case a subsequent element is a large array.
151       if (IsLarge)
152         return true;
153       NeedsProtector = true;
154     }
155 
156   return NeedsProtector;
157 }
158 
159 bool StackProtector::HasAddressTaken(const Instruction *AI) {
160   for (const User *U : AI->users()) {
161     const auto *I = cast<Instruction>(U);
162     switch (I->getOpcode()) {
163     case Instruction::Store:
164       if (AI == cast<StoreInst>(I)->getValueOperand())
165         return true;
166       break;
167     case Instruction::PtrToInt:
168       if (AI == cast<PtrToIntInst>(I)->getOperand(0))
169         return true;
170       break;
171     case Instruction::Call: {
172       // Ignore intrinsics that are not calls. TODO: Use isLoweredToCall().
173       const auto *CI = cast<CallInst>(I);
174       if (!isa<DbgInfoIntrinsic>(CI) && !CI->isLifetimeStartOrEnd())
175         return true;
176       break;
177     }
178     case Instruction::Invoke:
179       return true;
180     case Instruction::BitCast:
181     case Instruction::GetElementPtr:
182     case Instruction::Select:
183       if (HasAddressTaken(I))
184         return true;
185       break;
186     case Instruction::PHI: {
187       // Keep track of what PHI nodes we have already visited to ensure
188       // they are only visited once.
189       const auto *PN = cast<PHINode>(I);
190       if (VisitedPHIs.insert(PN).second)
191         if (HasAddressTaken(PN))
192           return true;
193       break;
194     }
195     default:
196       break;
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(B.getInt8PtrTy(), 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 (Function *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(B.getInt8PtrTy(), AI, true, "Guard");
430       CallInst *Call = B.CreateCall(GuardCheck, {Guard});
431       Call->setAttributes(GuardCheck->getAttributes());
432       Call->setCallingConv(GuardCheck->getCallingConv());
433     } else {
434       // Generate the epilogue with inline instrumentation.
435       // If we do not support SelectionDAG based tail calls, generate IR level
436       // tail calls.
437       //
438       // For each block with a return instruction, convert this:
439       //
440       //   return:
441       //     ...
442       //     ret ...
443       //
444       // into this:
445       //
446       //   return:
447       //     ...
448       //     %1 = <stack guard>
449       //     %2 = load StackGuardSlot
450       //     %3 = cmp i1 %1, %2
451       //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
452       //
453       //   SP_return:
454       //     ret ...
455       //
456       //   CallStackCheckFailBlk:
457       //     call void @__stack_chk_fail()
458       //     unreachable
459 
460       // Create the FailBB. We duplicate the BB every time since the MI tail
461       // merge pass will merge together all of the various BB into one including
462       // fail BB generated by the stack protector pseudo instruction.
463       BasicBlock *FailBB = CreateFailBB();
464 
465       // Split the basic block before the return instruction.
466       BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
467 
468       // Update the dominator tree if we need to.
469       if (DT && DT->isReachableFromEntry(BB)) {
470         DT->addNewBlock(NewBB, BB);
471         DT->addNewBlock(FailBB, BB);
472       }
473 
474       // Remove default branch instruction to the new BB.
475       BB->getTerminator()->eraseFromParent();
476 
477       // Move the newly created basic block to the point right after the old
478       // basic block so that it's in the "fall through" position.
479       NewBB->moveAfter(BB);
480 
481       // Generate the stack protector instructions in the old basic block.
482       IRBuilder<> B(BB);
483       Value *Guard = getStackGuard(TLI, M, B);
484       LoadInst *LI2 = B.CreateLoad(B.getInt8PtrTy(), AI, true);
485       Value *Cmp = B.CreateICmpEQ(Guard, LI2);
486       auto SuccessProb =
487           BranchProbabilityInfo::getBranchProbStackProtector(true);
488       auto FailureProb =
489           BranchProbabilityInfo::getBranchProbStackProtector(false);
490       MDNode *Weights = MDBuilder(F->getContext())
491                             .createBranchWeights(SuccessProb.getNumerator(),
492                                                  FailureProb.getNumerator());
493       B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
494     }
495   }
496 
497   // Return if we didn't modify any basic blocks. i.e., there are no return
498   // statements in the function.
499   return HasPrologue;
500 }
501 
502 /// CreateFailBB - Create a basic block to jump to when the stack protector
503 /// check fails.
504 BasicBlock *StackProtector::CreateFailBB() {
505   LLVMContext &Context = F->getContext();
506   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
507   IRBuilder<> B(FailBB);
508   B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
509   if (Trip.isOSOpenBSD()) {
510     FunctionCallee StackChkFail = M->getOrInsertFunction(
511         "__stack_smash_handler", Type::getVoidTy(Context),
512         Type::getInt8PtrTy(Context));
513 
514     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
515   } else {
516     FunctionCallee StackChkFail =
517         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context));
518 
519     B.CreateCall(StackChkFail, {});
520   }
521   B.CreateUnreachable();
522   return FailBB;
523 }
524 
525 bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
526   return HasPrologue && !HasIRCheck && isa<ReturnInst>(BB.getTerminator());
527 }
528 
529 void StackProtector::copyToMachineFrameInfo(MachineFrameInfo &MFI) const {
530   if (Layout.empty())
531     return;
532 
533   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
534     if (MFI.isDeadObjectIndex(I))
535       continue;
536 
537     const AllocaInst *AI = MFI.getObjectAllocation(I);
538     if (!AI)
539       continue;
540 
541     SSPLayoutMap::const_iterator LI = Layout.find(AI);
542     if (LI == Layout.end())
543       continue;
544 
545     MFI.setObjectSSPLayout(I, LI->second);
546   }
547 }
548