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