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/ValueTracking.h"
22 #include "llvm/CodeGen/Analysis.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/IR/Attributes.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/GlobalValue.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/IR/MDBuilder.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 #include <cstdlib>
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "stack-protector"
43 
44 STATISTIC(NumFunProtected, "Number of functions protected");
45 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
46                         " taken.");
47 
48 static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
49                                           cl::init(true), cl::Hidden);
50 
51 char StackProtector::ID = 0;
52 INITIALIZE_PASS(StackProtector, "stack-protector", "Insert stack protectors",
53                 false, true)
54 
55 FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
56   return new StackProtector(TM);
57 }
58 
59 StackProtector::SSPLayoutKind
60 StackProtector::getSSPLayout(const AllocaInst *AI) const {
61   return AI ? Layout.lookup(AI) : SSPLK_None;
62 }
63 
64 void StackProtector::adjustForColoring(const AllocaInst *From,
65                                        const AllocaInst *To) {
66   // When coloring replaces one alloca with another, transfer the SSPLayoutKind
67   // tag from the remapped to the target alloca. The remapped alloca should
68   // have a size smaller than or equal to the replacement alloca.
69   SSPLayoutMap::iterator I = Layout.find(From);
70   if (I != Layout.end()) {
71     SSPLayoutKind Kind = I->second;
72     Layout.erase(I);
73 
74     // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
75     // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
76     // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
77     I = Layout.find(To);
78     if (I == Layout.end())
79       Layout.insert(std::make_pair(To, Kind));
80     else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
81       I->second = Kind;
82   }
83 }
84 
85 bool StackProtector::runOnFunction(Function &Fn) {
86   F = &Fn;
87   M = F->getParent();
88   DominatorTreeWrapperPass *DTWP =
89       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
90   DT = DTWP ? &DTWP->getDomTree() : nullptr;
91   TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
92   HasPrologue = false;
93   HasIRCheck = false;
94 
95   Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
96   if (Attr.isStringAttribute() &&
97       Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
98       return false; // Invalid integer string
99 
100   if (!RequiresStackProtector())
101     return false;
102 
103   ++NumFunProtected;
104   return InsertStackProtectors();
105 }
106 
107 /// \param [out] IsLarge is set to true if a protectable array is found and
108 /// it is "large" ( >= ssp-buffer-size).  In the case of a structure with
109 /// multiple arrays, this gets set if any of them is large.
110 bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
111                                               bool Strong,
112                                               bool InStruct) const {
113   if (!Ty)
114     return false;
115   if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
116     if (!AT->getElementType()->isIntegerTy(8)) {
117       // If we're on a non-Darwin platform or we're inside of a structure, don't
118       // add stack protectors unless the array is a character array.
119       // However, in strong mode any array, regardless of type and size,
120       // triggers a protector.
121       if (!Strong && (InStruct || !Trip.isOSDarwin()))
122         return false;
123     }
124 
125     // If an array has more than SSPBufferSize bytes of allocated space, then we
126     // emit stack protectors.
127     if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
128       IsLarge = true;
129       return true;
130     }
131 
132     if (Strong)
133       // Require a protector for all arrays in strong mode
134       return true;
135   }
136 
137   const StructType *ST = dyn_cast<StructType>(Ty);
138   if (!ST)
139     return false;
140 
141   bool NeedsProtector = false;
142   for (StructType::element_iterator I = ST->element_begin(),
143                                     E = ST->element_end();
144        I != E; ++I)
145     if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
146       // If the element is a protectable array and is large (>= SSPBufferSize)
147       // then we are done.  If the protectable array is not large, then
148       // keep looking in case a subsequent element is a large array.
149       if (IsLarge)
150         return true;
151       NeedsProtector = true;
152     }
153 
154   return NeedsProtector;
155 }
156 
157 bool StackProtector::HasAddressTaken(const Instruction *AI) {
158   for (const User *U : AI->users()) {
159     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
160       if (AI == SI->getValueOperand())
161         return true;
162     } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
163       if (AI == SI->getOperand(0))
164         return true;
165     } else if (isa<CallInst>(U)) {
166       return true;
167     } else if (isa<InvokeInst>(U)) {
168       return true;
169     } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
170       if (HasAddressTaken(SI))
171         return true;
172     } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
173       // Keep track of what PHI nodes we have already visited to ensure
174       // they are only visited once.
175       if (VisitedPHIs.insert(PN).second)
176         if (HasAddressTaken(PN))
177           return true;
178     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
179       if (HasAddressTaken(GEP))
180         return true;
181     } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
182       if (HasAddressTaken(BI))
183         return true;
184     }
185   }
186   return false;
187 }
188 
189 /// \brief Check whether or not this function needs a stack protector based
190 /// upon the stack protector level.
191 ///
192 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
193 /// The standard heuristic which will add a guard variable to functions that
194 /// call alloca with a either a variable size or a size >= SSPBufferSize,
195 /// functions with character buffers larger than SSPBufferSize, and functions
196 /// with aggregates containing character buffers larger than SSPBufferSize. The
197 /// strong heuristic will add a guard variables to functions that call alloca
198 /// regardless of size, functions with any buffer regardless of type and size,
199 /// functions with aggregates that contain any buffer regardless of type and
200 /// size, and functions that contain stack-based variables that have had their
201 /// address taken.
202 bool StackProtector::RequiresStackProtector() {
203   bool Strong = false;
204   bool NeedsProtector = false;
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(),
210                                       Intrinsic::stackprotector))
211           HasPrologue = true;
212 
213   if (F->hasFnAttribute(Attribute::SafeStack))
214     return false;
215 
216   if (F->hasFnAttribute(Attribute::StackProtectReq)) {
217     NeedsProtector = true;
218     Strong = true; // Use the same heuristic as strong to determine SSPLayout
219   } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
220     Strong = true;
221   else if (HasPrologue)
222     NeedsProtector = true;
223   else if (!F->hasFnAttribute(Attribute::StackProtect))
224     return false;
225 
226   for (const BasicBlock &BB : *F) {
227     for (const Instruction &I : BB) {
228       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
229         if (AI->isArrayAllocation()) {
230           // SSP-Strong: Enable protectors for any call to alloca, regardless
231           // of size.
232           if (Strong)
233             return true;
234 
235           if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
236             if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
237               // A call to alloca with size >= SSPBufferSize requires
238               // stack protectors.
239               Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
240               NeedsProtector = true;
241             } else if (Strong) {
242               // Require protectors for all alloca calls in strong mode.
243               Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
244               NeedsProtector = true;
245             }
246           } else {
247             // A call to alloca with a variable size requires protectors.
248             Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
249             NeedsProtector = true;
250           }
251           continue;
252         }
253 
254         bool IsLarge = false;
255         if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
256           Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
257                                                    : SSPLK_SmallArray));
258           NeedsProtector = true;
259           continue;
260         }
261 
262         if (Strong && HasAddressTaken(AI)) {
263           ++NumAddrTaken;
264           Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
265           NeedsProtector = true;
266         }
267       }
268     }
269   }
270 
271   return NeedsProtector;
272 }
273 
274 /// Insert code into the entry block that stores the __stack_chk_guard
275 /// variable onto the stack:
276 ///
277 ///   entry:
278 ///     StackGuardSlot = alloca i8*
279 ///     StackGuard = load __stack_chk_guard
280 ///     call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
281 ///
282 /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
283 /// node.
284 static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
285                            const TargetLoweringBase *TLI, AllocaInst *&AI,
286                            Value *&StackGuardVar) {
287   bool SupportsSelectionDAGSP = false;
288   IRBuilder<> B(&F->getEntryBlock().front());
289 
290   StackGuardVar = TLI->getIRStackGuard(B);
291   if (!StackGuardVar) {
292     /// Use SelectionDAG SSP handling, since there isn't an IR guard.
293     SupportsSelectionDAGSP = true;
294     TLI->insertSSPDeclarations(*M);
295     StackGuardVar = TLI->getSDStackGuard(*M);
296   }
297   assert(StackGuardVar && "Must have stack guard available");
298 
299   PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
300   AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
301   LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
302   B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
303                {LI, AI});
304   return SupportsSelectionDAGSP;
305 }
306 
307 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
308 /// function.
309 ///
310 ///  - The prologue code loads and stores the stack guard onto the stack.
311 ///  - The epilogue checks the value stored in the prologue against the original
312 ///    value. It calls __stack_chk_fail if they differ.
313 bool StackProtector::InsertStackProtectors() {
314   bool SupportsSelectionDAGSP =
315       EnableSelectionDAGSP && !TM->Options.EnableFastISel;
316   AllocaInst *AI = nullptr;       // Place on stack that stores the stack guard.
317   Value *StackGuardVar = nullptr; // The stack guard variable.
318 
319   for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
320     BasicBlock *BB = &*I++;
321     ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
322     if (!RI)
323       continue;
324 
325     if (!HasPrologue) {
326       HasPrologue = true;
327       SupportsSelectionDAGSP &=
328           CreatePrologue(F, M, RI, TLI, AI, StackGuardVar);
329     }
330 
331     if (!SupportsSelectionDAGSP) {
332       // If we do not support SelectionDAG based tail calls, generate IR level
333       // tail calls.
334       //
335       // For each block with a return instruction, convert this:
336       //
337       //   return:
338       //     ...
339       //     ret ...
340       //
341       // into this:
342       //
343       //   return:
344       //     ...
345       //     %1 = load __stack_chk_guard
346       //     %2 = load StackGuardSlot
347       //     %3 = cmp i1 %1, %2
348       //     br i1 %3, label %SP_return, label %CallStackCheckFailBlk
349       //
350       //   SP_return:
351       //     ret ...
352       //
353       //   CallStackCheckFailBlk:
354       //     call void @__stack_chk_fail()
355       //     unreachable
356 
357       // Create the FailBB. We duplicate the BB every time since the MI tail
358       // merge pass will merge together all of the various BB into one including
359       // fail BB generated by the stack protector pseudo instruction.
360       BasicBlock *FailBB = CreateFailBB();
361 
362       // Set HasIRCheck to true, so that SelectionDAG will not generate its own
363       // version.
364       HasIRCheck = true;
365 
366       // Split the basic block before the return instruction.
367       BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
368 
369       // Update the dominator tree if we need to.
370       if (DT && DT->isReachableFromEntry(BB)) {
371         DT->addNewBlock(NewBB, BB);
372         DT->addNewBlock(FailBB, BB);
373       }
374 
375       // Remove default branch instruction to the new BB.
376       BB->getTerminator()->eraseFromParent();
377 
378       // Move the newly created basic block to the point right after the old
379       // basic block so that it's in the "fall through" position.
380       NewBB->moveAfter(BB);
381 
382       // Generate the stack protector instructions in the old basic block.
383       IRBuilder<> B(BB);
384       LoadInst *LI1 = B.CreateLoad(StackGuardVar);
385       LoadInst *LI2 = B.CreateLoad(AI);
386       Value *Cmp = B.CreateICmpEQ(LI1, LI2);
387       auto SuccessProb =
388           BranchProbabilityInfo::getBranchProbStackProtector(true);
389       auto FailureProb =
390           BranchProbabilityInfo::getBranchProbStackProtector(false);
391       MDNode *Weights = MDBuilder(F->getContext())
392                             .createBranchWeights(SuccessProb.getNumerator(),
393                                                  FailureProb.getNumerator());
394       B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
395     }
396   }
397 
398   // Return if we didn't modify any basic blocks. i.e., there are no return
399   // statements in the function.
400   return HasPrologue;
401 }
402 
403 /// CreateFailBB - Create a basic block to jump to when the stack protector
404 /// check fails.
405 BasicBlock *StackProtector::CreateFailBB() {
406   LLVMContext &Context = F->getContext();
407   BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
408   IRBuilder<> B(FailBB);
409   if (Trip.isOSOpenBSD()) {
410     Constant *StackChkFail =
411         M->getOrInsertFunction("__stack_smash_handler",
412                                Type::getVoidTy(Context),
413                                Type::getInt8PtrTy(Context), nullptr);
414 
415     B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
416   } else {
417     Constant *StackChkFail =
418         M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context),
419                                nullptr);
420     B.CreateCall(StackChkFail, {});
421   }
422   B.CreateUnreachable();
423   return FailBB;
424 }
425 
426 bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
427   return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
428 }
429