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