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