1 //===-- SafeStack.cpp - Safe Stack 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 splits the stack into the safe stack (kept as-is for LLVM backend)
11 // and the unsafe stack (explicitly allocated and managed through the runtime
12 // support library).
13 //
14 // http://clang.llvm.org/docs/SafeStack.html
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "SafeStackColoring.h"
19 #include "SafeStackLayout.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Analysis/BranchProbabilityInfo.h"
23 #include "llvm/Analysis/ScalarEvolution.h"
24 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DIBuilder.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/InstIterator.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/MDBuilder.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/raw_os_ostream.h"
44 #include "llvm/Target/TargetLowering.h"
45 #include "llvm/Target/TargetSubtargetInfo.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Transforms/Utils/ModuleUtils.h"
49 
50 using namespace llvm;
51 using namespace llvm::safestack;
52 
53 #define DEBUG_TYPE "safestack"
54 
55 enum UnsafeStackPtrStorageVal { ThreadLocalUSP, SingleThreadUSP };
56 
57 static cl::opt<UnsafeStackPtrStorageVal> USPStorage("safe-stack-usp-storage",
58     cl::Hidden, cl::init(ThreadLocalUSP),
59     cl::desc("Type of storage for the unsafe stack pointer"),
60     cl::values(clEnumValN(ThreadLocalUSP, "thread-local",
61                           "Thread-local storage"),
62                clEnumValN(SingleThreadUSP, "single-thread",
63                           "Non-thread-local storage")));
64 
65 namespace llvm {
66 
67 STATISTIC(NumFunctions, "Total number of functions");
68 STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
69 STATISTIC(NumUnsafeStackRestorePointsFunctions,
70           "Number of functions that use setjmp or exceptions");
71 
72 STATISTIC(NumAllocas, "Total number of allocas");
73 STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
74 STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
75 STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
76 STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
77 
78 } // namespace llvm
79 
80 namespace {
81 
82 /// Rewrite an SCEV expression for a memory access address to an expression that
83 /// represents offset from the given alloca.
84 ///
85 /// The implementation simply replaces all mentions of the alloca with zero.
86 class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
87   const Value *AllocaPtr;
88 
89 public:
90   AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
91       : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
92 
93   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
94     if (Expr->getValue() == AllocaPtr)
95       return SE.getZero(Expr->getType());
96     return Expr;
97   }
98 };
99 
100 /// The SafeStack pass splits the stack of each function into the safe
101 /// stack, which is only accessed through memory safe dereferences (as
102 /// determined statically), and the unsafe stack, which contains all
103 /// local variables that are accessed in ways that we can't prove to
104 /// be safe.
105 class SafeStack : public FunctionPass {
106   const TargetMachine *TM;
107   const TargetLoweringBase *TL;
108   const DataLayout *DL;
109   ScalarEvolution *SE;
110 
111   Type *StackPtrTy;
112   Type *IntPtrTy;
113   Type *Int32Ty;
114   Type *Int8Ty;
115 
116   Value *UnsafeStackPtr = nullptr;
117 
118   /// Unsafe stack alignment. Each stack frame must ensure that the stack is
119   /// aligned to this value. We need to re-align the unsafe stack if the
120   /// alignment of any object on the stack exceeds this value.
121   ///
122   /// 16 seems like a reasonable upper bound on the alignment of objects that we
123   /// might expect to appear on the stack on most common targets.
124   enum { StackAlignment = 16 };
125 
126   /// \brief Build a value representing a pointer to the unsafe stack pointer.
127   Value *getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F);
128 
129   /// \brief Return the value of the stack canary.
130   Value *getStackGuard(IRBuilder<> &IRB, Function &F);
131 
132   /// \brief Load stack guard from the frame and check if it has changed.
133   void checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
134                        AllocaInst *StackGuardSlot, Value *StackGuard);
135 
136   /// \brief Find all static allocas, dynamic allocas, return instructions and
137   /// stack restore points (exception unwind blocks and setjmp calls) in the
138   /// given function and append them to the respective vectors.
139   void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
140                  SmallVectorImpl<AllocaInst *> &DynamicAllocas,
141                  SmallVectorImpl<Argument *> &ByValArguments,
142                  SmallVectorImpl<ReturnInst *> &Returns,
143                  SmallVectorImpl<Instruction *> &StackRestorePoints);
144 
145   /// \brief Calculate the allocation size of a given alloca. Returns 0 if the
146   /// size can not be statically determined.
147   uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
148 
149   /// \brief Allocate space for all static allocas in \p StaticAllocas,
150   /// replace allocas with pointers into the unsafe stack and generate code to
151   /// restore the stack pointer before all return instructions in \p Returns.
152   ///
153   /// \returns A pointer to the top of the unsafe stack after all unsafe static
154   /// allocas are allocated.
155   Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
156                                         ArrayRef<AllocaInst *> StaticAllocas,
157                                         ArrayRef<Argument *> ByValArguments,
158                                         ArrayRef<ReturnInst *> Returns,
159                                         Instruction *BasePointer,
160                                         AllocaInst *StackGuardSlot);
161 
162   /// \brief Generate code to restore the stack after all stack restore points
163   /// in \p StackRestorePoints.
164   ///
165   /// \returns A local variable in which to maintain the dynamic top of the
166   /// unsafe stack if needed.
167   AllocaInst *
168   createStackRestorePoints(IRBuilder<> &IRB, Function &F,
169                            ArrayRef<Instruction *> StackRestorePoints,
170                            Value *StaticTop, bool NeedDynamicTop);
171 
172   /// \brief Replace all allocas in \p DynamicAllocas with code to allocate
173   /// space dynamically on the unsafe stack and store the dynamic unsafe stack
174   /// top to \p DynamicTop if non-null.
175   void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
176                                        AllocaInst *DynamicTop,
177                                        ArrayRef<AllocaInst *> DynamicAllocas);
178 
179   bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
180 
181   bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
182                           const Value *AllocaPtr, uint64_t AllocaSize);
183   bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
184                     uint64_t AllocaSize);
185 
186 public:
187   static char ID; // Pass identification, replacement for typeid.
188   SafeStack(const TargetMachine *TM)
189       : FunctionPass(ID), TM(TM), TL(nullptr), DL(nullptr) {
190     initializeSafeStackPass(*PassRegistry::getPassRegistry());
191   }
192   SafeStack() : SafeStack(nullptr) {}
193 
194   void getAnalysisUsage(AnalysisUsage &AU) const override {
195     AU.addRequired<ScalarEvolutionWrapperPass>();
196   }
197 
198   bool doInitialization(Module &M) override {
199     DL = &M.getDataLayout();
200 
201     StackPtrTy = Type::getInt8PtrTy(M.getContext());
202     IntPtrTy = DL->getIntPtrType(M.getContext());
203     Int32Ty = Type::getInt32Ty(M.getContext());
204     Int8Ty = Type::getInt8Ty(M.getContext());
205 
206     return false;
207   }
208 
209   bool runOnFunction(Function &F) override;
210 }; // class SafeStack
211 
212 uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
213   uint64_t Size = DL->getTypeAllocSize(AI->getAllocatedType());
214   if (AI->isArrayAllocation()) {
215     auto C = dyn_cast<ConstantInt>(AI->getArraySize());
216     if (!C)
217       return 0;
218     Size *= C->getZExtValue();
219   }
220   return Size;
221 }
222 
223 bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
224                              const Value *AllocaPtr, uint64_t AllocaSize) {
225   AllocaOffsetRewriter Rewriter(*SE, AllocaPtr);
226   const SCEV *Expr = Rewriter.visit(SE->getSCEV(Addr));
227 
228   uint64_t BitWidth = SE->getTypeSizeInBits(Expr->getType());
229   ConstantRange AccessStartRange = SE->getUnsignedRange(Expr);
230   ConstantRange SizeRange =
231       ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
232   ConstantRange AccessRange = AccessStartRange.add(SizeRange);
233   ConstantRange AllocaRange =
234       ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
235   bool Safe = AllocaRange.contains(AccessRange);
236 
237   DEBUG(dbgs() << "[SafeStack] "
238                << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
239                << *AllocaPtr << "\n"
240                << "            Access " << *Addr << "\n"
241                << "            SCEV " << *Expr
242                << " U: " << SE->getUnsignedRange(Expr)
243                << ", S: " << SE->getSignedRange(Expr) << "\n"
244                << "            Range " << AccessRange << "\n"
245                << "            AllocaRange " << AllocaRange << "\n"
246                << "            " << (Safe ? "safe" : "unsafe") << "\n");
247 
248   return Safe;
249 }
250 
251 bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
252                                    const Value *AllocaPtr,
253                                    uint64_t AllocaSize) {
254   // All MemIntrinsics have destination address in Arg0 and size in Arg2.
255   if (MI->getRawDest() != U) return true;
256   const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
257   // Non-constant size => unsafe. FIXME: try SCEV getRange.
258   if (!Len) return false;
259   return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
260 }
261 
262 /// Check whether a given allocation must be put on the safe
263 /// stack or not. The function analyzes all uses of AI and checks whether it is
264 /// only accessed in a memory safe way (as decided statically).
265 bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
266   // Go through all uses of this alloca and check whether all accesses to the
267   // allocated object are statically known to be memory safe and, hence, the
268   // object can be placed on the safe stack.
269   SmallPtrSet<const Value *, 16> Visited;
270   SmallVector<const Value *, 8> WorkList;
271   WorkList.push_back(AllocaPtr);
272 
273   // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
274   while (!WorkList.empty()) {
275     const Value *V = WorkList.pop_back_val();
276     for (const Use &UI : V->uses()) {
277       auto I = cast<const Instruction>(UI.getUser());
278       assert(V == UI.get());
279 
280       switch (I->getOpcode()) {
281       case Instruction::Load: {
282         if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getType()), AllocaPtr,
283                           AllocaSize))
284           return false;
285         break;
286       }
287       case Instruction::VAArg:
288         // "va-arg" from a pointer is safe.
289         break;
290       case Instruction::Store: {
291         if (V == I->getOperand(0)) {
292           // Stored the pointer - conservatively assume it may be unsafe.
293           DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
294                        << "\n            store of address: " << *I << "\n");
295           return false;
296         }
297 
298         if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getOperand(0)->getType()),
299                           AllocaPtr, AllocaSize))
300           return false;
301         break;
302       }
303       case Instruction::Ret: {
304         // Information leak.
305         return false;
306       }
307 
308       case Instruction::Call:
309       case Instruction::Invoke: {
310         ImmutableCallSite CS(I);
311 
312         if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
313           if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
314               II->getIntrinsicID() == Intrinsic::lifetime_end)
315             continue;
316         }
317 
318         if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
319           if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
320             DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
321                          << "\n            unsafe memintrinsic: " << *I
322                          << "\n");
323             return false;
324           }
325           continue;
326         }
327 
328         // LLVM 'nocapture' attribute is only set for arguments whose address
329         // is not stored, passed around, or used in any other non-trivial way.
330         // We assume that passing a pointer to an object as a 'nocapture
331         // readnone' argument is safe.
332         // FIXME: a more precise solution would require an interprocedural
333         // analysis here, which would look at all uses of an argument inside
334         // the function being called.
335         ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
336         for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
337           if (A->get() == V)
338             if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
339                                                CS.doesNotAccessMemory()))) {
340               DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
341                            << "\n            unsafe call: " << *I << "\n");
342               return false;
343             }
344         continue;
345       }
346 
347       default:
348         if (Visited.insert(I).second)
349           WorkList.push_back(cast<const Instruction>(I));
350       }
351     }
352   }
353 
354   // All uses of the alloca are safe, we can place it on the safe stack.
355   return true;
356 }
357 
358 Value *SafeStack::getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F) {
359   // Check if there is a target-specific location for the unsafe stack pointer.
360   if (TL)
361     if (Value *V = TL->getSafeStackPointerLocation(IRB))
362       return V;
363 
364   // Otherwise, assume the target links with compiler-rt, which provides a
365   // thread-local variable with a magic name.
366   Module &M = *F.getParent();
367   const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
368   auto UnsafeStackPtr =
369       dyn_cast_or_null<GlobalVariable>(M.getNamedValue(UnsafeStackPtrVar));
370 
371   bool UseTLS = USPStorage == ThreadLocalUSP;
372 
373   if (!UnsafeStackPtr) {
374     auto TLSModel = UseTLS ?
375         GlobalValue::InitialExecTLSModel :
376         GlobalValue::NotThreadLocal;
377     // The global variable is not defined yet, define it ourselves.
378     // We use the initial-exec TLS model because we do not support the
379     // variable living anywhere other than in the main executable.
380     UnsafeStackPtr = new GlobalVariable(
381         M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
382         UnsafeStackPtrVar, nullptr, TLSModel);
383   } else {
384     // The variable exists, check its type and attributes.
385     if (UnsafeStackPtr->getValueType() != StackPtrTy)
386       report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
387     if (UseTLS != UnsafeStackPtr->isThreadLocal())
388       report_fatal_error(Twine(UnsafeStackPtrVar) + " must " +
389                          (UseTLS ? "" : "not ") + "be thread-local");
390   }
391   return UnsafeStackPtr;
392 }
393 
394 Value *SafeStack::getStackGuard(IRBuilder<> &IRB, Function &F) {
395   Value *StackGuardVar = nullptr;
396   if (TL)
397     StackGuardVar = TL->getIRStackGuard(IRB);
398   if (!StackGuardVar)
399     StackGuardVar =
400         F.getParent()->getOrInsertGlobal("__stack_chk_guard", StackPtrTy);
401   return IRB.CreateLoad(StackGuardVar, "StackGuard");
402 }
403 
404 void SafeStack::findInsts(Function &F,
405                           SmallVectorImpl<AllocaInst *> &StaticAllocas,
406                           SmallVectorImpl<AllocaInst *> &DynamicAllocas,
407                           SmallVectorImpl<Argument *> &ByValArguments,
408                           SmallVectorImpl<ReturnInst *> &Returns,
409                           SmallVectorImpl<Instruction *> &StackRestorePoints) {
410   for (Instruction &I : instructions(&F)) {
411     if (auto AI = dyn_cast<AllocaInst>(&I)) {
412       ++NumAllocas;
413 
414       uint64_t Size = getStaticAllocaAllocationSize(AI);
415       if (IsSafeStackAlloca(AI, Size))
416         continue;
417 
418       if (AI->isStaticAlloca()) {
419         ++NumUnsafeStaticAllocas;
420         StaticAllocas.push_back(AI);
421       } else {
422         ++NumUnsafeDynamicAllocas;
423         DynamicAllocas.push_back(AI);
424       }
425     } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
426       Returns.push_back(RI);
427     } else if (auto CI = dyn_cast<CallInst>(&I)) {
428       // setjmps require stack restore.
429       if (CI->getCalledFunction() && CI->canReturnTwice())
430         StackRestorePoints.push_back(CI);
431     } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
432       // Exception landing pads require stack restore.
433       StackRestorePoints.push_back(LP);
434     } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
435       if (II->getIntrinsicID() == Intrinsic::gcroot)
436         llvm::report_fatal_error(
437             "gcroot intrinsic not compatible with safestack attribute");
438     }
439   }
440   for (Argument &Arg : F.args()) {
441     if (!Arg.hasByValAttr())
442       continue;
443     uint64_t Size =
444         DL->getTypeStoreSize(Arg.getType()->getPointerElementType());
445     if (IsSafeStackAlloca(&Arg, Size))
446       continue;
447 
448     ++NumUnsafeByValArguments;
449     ByValArguments.push_back(&Arg);
450   }
451 }
452 
453 AllocaInst *
454 SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
455                                     ArrayRef<Instruction *> StackRestorePoints,
456                                     Value *StaticTop, bool NeedDynamicTop) {
457   assert(StaticTop && "The stack top isn't set.");
458 
459   if (StackRestorePoints.empty())
460     return nullptr;
461 
462   // We need the current value of the shadow stack pointer to restore
463   // after longjmp or exception catching.
464 
465   // FIXME: On some platforms this could be handled by the longjmp/exception
466   // runtime itself.
467 
468   AllocaInst *DynamicTop = nullptr;
469   if (NeedDynamicTop) {
470     // If we also have dynamic alloca's, the stack pointer value changes
471     // throughout the function. For now we store it in an alloca.
472     DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
473                                   "unsafe_stack_dynamic_ptr");
474     IRB.CreateStore(StaticTop, DynamicTop);
475   }
476 
477   // Restore current stack pointer after longjmp/exception catch.
478   for (Instruction *I : StackRestorePoints) {
479     ++NumUnsafeStackRestorePoints;
480 
481     IRB.SetInsertPoint(I->getNextNode());
482     Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
483     IRB.CreateStore(CurrentTop, UnsafeStackPtr);
484   }
485 
486   return DynamicTop;
487 }
488 
489 void SafeStack::checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
490                                 AllocaInst *StackGuardSlot, Value *StackGuard) {
491   Value *V = IRB.CreateLoad(StackGuardSlot);
492   Value *Cmp = IRB.CreateICmpNE(StackGuard, V);
493 
494   auto SuccessProb = BranchProbabilityInfo::getBranchProbStackProtector(true);
495   auto FailureProb = BranchProbabilityInfo::getBranchProbStackProtector(false);
496   MDNode *Weights = MDBuilder(F.getContext())
497                         .createBranchWeights(SuccessProb.getNumerator(),
498                                              FailureProb.getNumerator());
499   Instruction *CheckTerm =
500       SplitBlockAndInsertIfThen(Cmp, &RI,
501                                 /* Unreachable */ true, Weights);
502   IRBuilder<> IRBFail(CheckTerm);
503   // FIXME: respect -fsanitize-trap / -ftrap-function here?
504   Constant *StackChkFail = F.getParent()->getOrInsertFunction(
505       "__stack_chk_fail", IRB.getVoidTy(), nullptr);
506   IRBFail.CreateCall(StackChkFail, {});
507 }
508 
509 /// We explicitly compute and set the unsafe stack layout for all unsafe
510 /// static alloca instructions. We save the unsafe "base pointer" in the
511 /// prologue into a local variable and restore it in the epilogue.
512 Value *SafeStack::moveStaticAllocasToUnsafeStack(
513     IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
514     ArrayRef<Argument *> ByValArguments, ArrayRef<ReturnInst *> Returns,
515     Instruction *BasePointer, AllocaInst *StackGuardSlot) {
516   if (StaticAllocas.empty() && ByValArguments.empty())
517     return BasePointer;
518 
519   DIBuilder DIB(*F.getParent());
520 
521   StackColoring SSC(F, StaticAllocas);
522   SSC.run();
523   SSC.removeAllMarkers();
524 
525   // Unsafe stack always grows down.
526   StackLayout SSL(StackAlignment);
527   if (StackGuardSlot) {
528     Type *Ty = StackGuardSlot->getAllocatedType();
529     unsigned Align =
530         std::max(DL->getPrefTypeAlignment(Ty), StackGuardSlot->getAlignment());
531     SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot),
532                   Align, SSC.getFullLiveRange());
533   }
534 
535   for (Argument *Arg : ByValArguments) {
536     Type *Ty = Arg->getType()->getPointerElementType();
537     uint64_t Size = DL->getTypeStoreSize(Ty);
538     if (Size == 0)
539       Size = 1; // Don't create zero-sized stack objects.
540 
541     // Ensure the object is properly aligned.
542     unsigned Align = std::max((unsigned)DL->getPrefTypeAlignment(Ty),
543                               Arg->getParamAlignment());
544     SSL.addObject(Arg, Size, Align, SSC.getFullLiveRange());
545   }
546 
547   for (AllocaInst *AI : StaticAllocas) {
548     Type *Ty = AI->getAllocatedType();
549     uint64_t Size = getStaticAllocaAllocationSize(AI);
550     if (Size == 0)
551       Size = 1; // Don't create zero-sized stack objects.
552 
553     // Ensure the object is properly aligned.
554     unsigned Align =
555         std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
556 
557     SSL.addObject(AI, Size, Align, SSC.getLiveRange(AI));
558   }
559 
560   SSL.computeLayout();
561   unsigned FrameAlignment = SSL.getFrameAlignment();
562 
563   // FIXME: tell SSL that we start at a less-then-MaxAlignment aligned location
564   // (AlignmentSkew).
565   if (FrameAlignment > StackAlignment) {
566     // Re-align the base pointer according to the max requested alignment.
567     assert(isPowerOf2_32(FrameAlignment));
568     IRB.SetInsertPoint(BasePointer->getNextNode());
569     BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
570         IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
571                       ConstantInt::get(IntPtrTy, ~uint64_t(FrameAlignment - 1))),
572         StackPtrTy));
573   }
574 
575   IRB.SetInsertPoint(BasePointer->getNextNode());
576 
577   if (StackGuardSlot) {
578     unsigned Offset = SSL.getObjectOffset(StackGuardSlot);
579     Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
580                                ConstantInt::get(Int32Ty, -Offset));
581     Value *NewAI =
582         IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
583 
584     // Replace alloc with the new location.
585     StackGuardSlot->replaceAllUsesWith(NewAI);
586     StackGuardSlot->eraseFromParent();
587   }
588 
589   for (Argument *Arg : ByValArguments) {
590     unsigned Offset = SSL.getObjectOffset(Arg);
591     Type *Ty = Arg->getType()->getPointerElementType();
592 
593     uint64_t Size = DL->getTypeStoreSize(Ty);
594     if (Size == 0)
595       Size = 1; // Don't create zero-sized stack objects.
596 
597     Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
598                                ConstantInt::get(Int32Ty, -Offset));
599     Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
600                                      Arg->getName() + ".unsafe-byval");
601 
602     // Replace alloc with the new location.
603     replaceDbgDeclare(Arg, BasePointer, BasePointer->getNextNode(), DIB,
604                       /*Deref=*/true, -Offset);
605     Arg->replaceAllUsesWith(NewArg);
606     IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
607     IRB.CreateMemCpy(Off, Arg, Size, Arg->getParamAlignment());
608   }
609 
610   // Allocate space for every unsafe static AllocaInst on the unsafe stack.
611   for (AllocaInst *AI : StaticAllocas) {
612     IRB.SetInsertPoint(AI);
613     unsigned Offset = SSL.getObjectOffset(AI);
614 
615     uint64_t Size = getStaticAllocaAllocationSize(AI);
616     if (Size == 0)
617       Size = 1; // Don't create zero-sized stack objects.
618 
619     replaceDbgDeclareForAlloca(AI, BasePointer, DIB, /*Deref=*/true, -Offset);
620     replaceDbgValueForAlloca(AI, BasePointer, DIB, -Offset);
621 
622     // Replace uses of the alloca with the new location.
623     // Insert address calculation close to each use to work around PR27844.
624     std::string Name = std::string(AI->getName()) + ".unsafe";
625     while (!AI->use_empty()) {
626       Use &U = *AI->use_begin();
627       Instruction *User = cast<Instruction>(U.getUser());
628 
629       Instruction *InsertBefore;
630       if (auto *PHI = dyn_cast<PHINode>(User))
631         InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
632       else
633         InsertBefore = User;
634 
635       IRBuilder<> IRBUser(InsertBefore);
636       Value *Off = IRBUser.CreateGEP(BasePointer, // BasePointer is i8*
637                                      ConstantInt::get(Int32Ty, -Offset));
638       Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name);
639 
640       if (auto *PHI = dyn_cast<PHINode>(User)) {
641         // PHI nodes may have multiple incoming edges from the same BB (why??),
642         // all must be updated at once with the same incoming value.
643         auto *BB = PHI->getIncomingBlock(U);
644         for (unsigned I = 0; I < PHI->getNumIncomingValues(); ++I)
645           if (PHI->getIncomingBlock(I) == BB)
646             PHI->setIncomingValue(I, Replacement);
647       } else {
648         U.set(Replacement);
649       }
650     }
651 
652     AI->eraseFromParent();
653   }
654 
655   // Re-align BasePointer so that our callees would see it aligned as
656   // expected.
657   // FIXME: no need to update BasePointer in leaf functions.
658   unsigned FrameSize = alignTo(SSL.getFrameSize(), StackAlignment);
659 
660   // Update shadow stack pointer in the function epilogue.
661   IRB.SetInsertPoint(BasePointer->getNextNode());
662 
663   Value *StaticTop =
664       IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -FrameSize),
665                     "unsafe_stack_static_top");
666   IRB.CreateStore(StaticTop, UnsafeStackPtr);
667   return StaticTop;
668 }
669 
670 void SafeStack::moveDynamicAllocasToUnsafeStack(
671     Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
672     ArrayRef<AllocaInst *> DynamicAllocas) {
673   DIBuilder DIB(*F.getParent());
674 
675   for (AllocaInst *AI : DynamicAllocas) {
676     IRBuilder<> IRB(AI);
677 
678     // Compute the new SP value (after AI).
679     Value *ArraySize = AI->getArraySize();
680     if (ArraySize->getType() != IntPtrTy)
681       ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
682 
683     Type *Ty = AI->getAllocatedType();
684     uint64_t TySize = DL->getTypeAllocSize(Ty);
685     Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
686 
687     Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
688     SP = IRB.CreateSub(SP, Size);
689 
690     // Align the SP value to satisfy the AllocaInst, type and stack alignments.
691     unsigned Align = std::max(
692         std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()),
693         (unsigned)StackAlignment);
694 
695     assert(isPowerOf2_32(Align));
696     Value *NewTop = IRB.CreateIntToPtr(
697         IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
698         StackPtrTy);
699 
700     // Save the stack pointer.
701     IRB.CreateStore(NewTop, UnsafeStackPtr);
702     if (DynamicTop)
703       IRB.CreateStore(NewTop, DynamicTop);
704 
705     Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
706     if (AI->hasName() && isa<Instruction>(NewAI))
707       NewAI->takeName(AI);
708 
709     replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
710     AI->replaceAllUsesWith(NewAI);
711     AI->eraseFromParent();
712   }
713 
714   if (!DynamicAllocas.empty()) {
715     // Now go through the instructions again, replacing stacksave/stackrestore.
716     for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
717       Instruction *I = &*(It++);
718       auto II = dyn_cast<IntrinsicInst>(I);
719       if (!II)
720         continue;
721 
722       if (II->getIntrinsicID() == Intrinsic::stacksave) {
723         IRBuilder<> IRB(II);
724         Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
725         LI->takeName(II);
726         II->replaceAllUsesWith(LI);
727         II->eraseFromParent();
728       } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
729         IRBuilder<> IRB(II);
730         Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
731         SI->takeName(II);
732         assert(II->use_empty());
733         II->eraseFromParent();
734       }
735     }
736   }
737 }
738 
739 bool SafeStack::runOnFunction(Function &F) {
740   DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
741 
742   if (!F.hasFnAttribute(Attribute::SafeStack)) {
743     DEBUG(dbgs() << "[SafeStack]     safestack is not requested"
744                     " for this function\n");
745     return false;
746   }
747 
748   if (F.isDeclaration()) {
749     DEBUG(dbgs() << "[SafeStack]     function definition"
750                     " is not available\n");
751     return false;
752   }
753 
754   TL = TM ? TM->getSubtargetImpl(F)->getTargetLowering() : nullptr;
755   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
756 
757   ++NumFunctions;
758 
759   SmallVector<AllocaInst *, 16> StaticAllocas;
760   SmallVector<AllocaInst *, 4> DynamicAllocas;
761   SmallVector<Argument *, 4> ByValArguments;
762   SmallVector<ReturnInst *, 4> Returns;
763 
764   // Collect all points where stack gets unwound and needs to be restored
765   // This is only necessary because the runtime (setjmp and unwind code) is
766   // not aware of the unsafe stack and won't unwind/restore it prorerly.
767   // To work around this problem without changing the runtime, we insert
768   // instrumentation to restore the unsafe stack pointer when necessary.
769   SmallVector<Instruction *, 4> StackRestorePoints;
770 
771   // Find all static and dynamic alloca instructions that must be moved to the
772   // unsafe stack, all return instructions and stack restore points.
773   findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
774             StackRestorePoints);
775 
776   if (StaticAllocas.empty() && DynamicAllocas.empty() &&
777       ByValArguments.empty() && StackRestorePoints.empty())
778     return false; // Nothing to do in this function.
779 
780   if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
781       !ByValArguments.empty())
782     ++NumUnsafeStackFunctions; // This function has the unsafe stack.
783 
784   if (!StackRestorePoints.empty())
785     ++NumUnsafeStackRestorePointsFunctions;
786 
787   IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
788   UnsafeStackPtr = getOrCreateUnsafeStackPtr(IRB, F);
789 
790   // Load the current stack pointer (we'll also use it as a base pointer).
791   // FIXME: use a dedicated register for it ?
792   Instruction *BasePointer =
793       IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
794   assert(BasePointer->getType() == StackPtrTy);
795 
796   AllocaInst *StackGuardSlot = nullptr;
797   // FIXME: implement weaker forms of stack protector.
798   if (F.hasFnAttribute(Attribute::StackProtect) ||
799       F.hasFnAttribute(Attribute::StackProtectStrong) ||
800       F.hasFnAttribute(Attribute::StackProtectReq)) {
801     Value *StackGuard = getStackGuard(IRB, F);
802     StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
803     IRB.CreateStore(StackGuard, StackGuardSlot);
804 
805     for (ReturnInst *RI : Returns) {
806       IRBuilder<> IRBRet(RI);
807       checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
808     }
809   }
810 
811   // The top of the unsafe stack after all unsafe static allocas are
812   // allocated.
813   Value *StaticTop =
814       moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, ByValArguments,
815                                      Returns, BasePointer, StackGuardSlot);
816 
817   // Safe stack object that stores the current unsafe stack top. It is updated
818   // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
819   // This is only needed if we need to restore stack pointer after longjmp
820   // or exceptions, and we have dynamic allocations.
821   // FIXME: a better alternative might be to store the unsafe stack pointer
822   // before setjmp / invoke instructions.
823   AllocaInst *DynamicTop = createStackRestorePoints(
824       IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
825 
826   // Handle dynamic allocas.
827   moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
828                                   DynamicAllocas);
829 
830   // Restore the unsafe stack pointer before each return.
831   for (ReturnInst *RI : Returns) {
832     IRB.SetInsertPoint(RI);
833     IRB.CreateStore(BasePointer, UnsafeStackPtr);
834   }
835 
836   DEBUG(dbgs() << "[SafeStack]     safestack applied\n");
837   return true;
838 }
839 
840 } // anonymous namespace
841 
842 char SafeStack::ID = 0;
843 INITIALIZE_TM_PASS_BEGIN(SafeStack, "safe-stack",
844                          "Safe Stack instrumentation pass", false, false)
845 INITIALIZE_TM_PASS_END(SafeStack, "safe-stack",
846                        "Safe Stack instrumentation pass", false, false)
847 
848 FunctionPass *llvm::createSafeStackPass(const llvm::TargetMachine *TM) {
849   return new SafeStack(TM);
850 }
851