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