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