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