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 | |
| 18 | #include "llvm/Transforms/Instrumentation.h" |
| 19 | #include "llvm/ADT/Statistic.h" |
| 20 | #include "llvm/ADT/Triple.h" |
| 21 | #include "llvm/Analysis/AliasAnalysis.h" |
Evgeniy Stepanov | a2002b0 | 2015-09-23 18:07:56 +0000 | [diff] [blame] | 22 | #include "llvm/CodeGen/Passes.h" |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 23 | #include "llvm/IR/Constants.h" |
| 24 | #include "llvm/IR/DataLayout.h" |
| 25 | #include "llvm/IR/DerivedTypes.h" |
| 26 | #include "llvm/IR/DIBuilder.h" |
| 27 | #include "llvm/IR/Function.h" |
| 28 | #include "llvm/IR/InstIterator.h" |
| 29 | #include "llvm/IR/Instructions.h" |
| 30 | #include "llvm/IR/IntrinsicInst.h" |
| 31 | #include "llvm/IR/Intrinsics.h" |
| 32 | #include "llvm/IR/IRBuilder.h" |
| 33 | #include "llvm/IR/Module.h" |
| 34 | #include "llvm/Pass.h" |
| 35 | #include "llvm/Support/CommandLine.h" |
| 36 | #include "llvm/Support/Debug.h" |
| 37 | #include "llvm/Support/Format.h" |
| 38 | #include "llvm/Support/MathExtras.h" |
| 39 | #include "llvm/Support/raw_os_ostream.h" |
Evgeniy Stepanov | a2002b0 | 2015-09-23 18:07:56 +0000 | [diff] [blame] | 40 | #include "llvm/Target/TargetLowering.h" |
| 41 | #include "llvm/Target/TargetSubtargetInfo.h" |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 42 | #include "llvm/Transforms/Utils/Local.h" |
| 43 | #include "llvm/Transforms/Utils/ModuleUtils.h" |
| 44 | |
| 45 | using namespace llvm; |
| 46 | |
| 47 | #define DEBUG_TYPE "safestack" |
| 48 | |
| 49 | namespace llvm { |
| 50 | |
| 51 | STATISTIC(NumFunctions, "Total number of functions"); |
| 52 | STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack"); |
| 53 | STATISTIC(NumUnsafeStackRestorePointsFunctions, |
| 54 | "Number of functions that use setjmp or exceptions"); |
| 55 | |
| 56 | STATISTIC(NumAllocas, "Total number of allocas"); |
| 57 | STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas"); |
| 58 | STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas"); |
| 59 | STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads"); |
| 60 | |
| 61 | } // namespace llvm |
| 62 | |
| 63 | namespace { |
| 64 | |
| 65 | /// Check whether a given alloca instruction (AI) should be put on the safe |
| 66 | /// stack or not. The function analyzes all uses of AI and checks whether it is |
| 67 | /// only accessed in a memory safe way (as decided statically). |
| 68 | bool IsSafeStackAlloca(const AllocaInst *AI) { |
| 69 | // Go through all uses of this alloca and check whether all accesses to the |
| 70 | // allocated object are statically known to be memory safe and, hence, the |
| 71 | // object can be placed on the safe stack. |
| 72 | |
| 73 | SmallPtrSet<const Value *, 16> Visited; |
| 74 | SmallVector<const Instruction *, 8> WorkList; |
| 75 | WorkList.push_back(AI); |
| 76 | |
| 77 | // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc. |
| 78 | while (!WorkList.empty()) { |
| 79 | const Instruction *V = WorkList.pop_back_val(); |
| 80 | for (const Use &UI : V->uses()) { |
| 81 | auto I = cast<const Instruction>(UI.getUser()); |
| 82 | assert(V == UI.get()); |
| 83 | |
| 84 | switch (I->getOpcode()) { |
| 85 | case Instruction::Load: |
| 86 | // Loading from a pointer is safe. |
| 87 | break; |
| 88 | case Instruction::VAArg: |
| 89 | // "va-arg" from a pointer is safe. |
| 90 | break; |
| 91 | case Instruction::Store: |
| 92 | if (V == I->getOperand(0)) |
| 93 | // Stored the pointer - conservatively assume it may be unsafe. |
| 94 | return false; |
| 95 | // Storing to the pointee is safe. |
| 96 | break; |
| 97 | |
| 98 | case Instruction::GetElementPtr: |
| 99 | if (!cast<const GetElementPtrInst>(I)->hasAllConstantIndices()) |
| 100 | // GEP with non-constant indices can lead to memory errors. |
| 101 | // This also applies to inbounds GEPs, as the inbounds attribute |
| 102 | // represents an assumption that the address is in bounds, rather than |
| 103 | // an assertion that it is. |
| 104 | return false; |
| 105 | |
| 106 | // We assume that GEP on static alloca with constant indices is safe, |
| 107 | // otherwise a compiler would detect it and warn during compilation. |
| 108 | |
| 109 | if (!isa<const ConstantInt>(AI->getArraySize())) |
| 110 | // However, if the array size itself is not constant, the access |
| 111 | // might still be unsafe at runtime. |
| 112 | return false; |
| 113 | |
| 114 | /* fallthrough */ |
| 115 | |
| 116 | case Instruction::BitCast: |
| 117 | case Instruction::IntToPtr: |
| 118 | case Instruction::PHI: |
| 119 | case Instruction::PtrToInt: |
| 120 | case Instruction::Select: |
| 121 | // The object can be safe or not, depending on how the result of the |
| 122 | // instruction is used. |
| 123 | if (Visited.insert(I).second) |
| 124 | WorkList.push_back(cast<const Instruction>(I)); |
| 125 | break; |
| 126 | |
| 127 | case Instruction::Call: |
| 128 | case Instruction::Invoke: { |
| 129 | // FIXME: add support for memset and memcpy intrinsics. |
| 130 | ImmutableCallSite CS(I); |
| 131 | |
| 132 | // LLVM 'nocapture' attribute is only set for arguments whose address |
| 133 | // is not stored, passed around, or used in any other non-trivial way. |
| 134 | // We assume that passing a pointer to an object as a 'nocapture' |
| 135 | // argument is safe. |
| 136 | // FIXME: a more precise solution would require an interprocedural |
| 137 | // analysis here, which would look at all uses of an argument inside |
| 138 | // the function being called. |
| 139 | ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end(); |
| 140 | for (ImmutableCallSite::arg_iterator A = B; A != E; ++A) |
| 141 | if (A->get() == V && !CS.doesNotCapture(A - B)) |
| 142 | // The parameter is not marked 'nocapture' - unsafe. |
| 143 | return false; |
| 144 | continue; |
| 145 | } |
| 146 | |
| 147 | default: |
| 148 | // The object is unsafe if it is used in any other way. |
| 149 | return false; |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | // All uses of the alloca are safe, we can place it on the safe stack. |
| 155 | return true; |
| 156 | } |
| 157 | |
| 158 | /// The SafeStack pass splits the stack of each function into the |
| 159 | /// safe stack, which is only accessed through memory safe dereferences |
| 160 | /// (as determined statically), and the unsafe stack, which contains all |
| 161 | /// local variables that are accessed in unsafe ways. |
| 162 | class SafeStack : public FunctionPass { |
Evgeniy Stepanov | a2002b0 | 2015-09-23 18:07:56 +0000 | [diff] [blame] | 163 | const TargetMachine *TM; |
| 164 | const TargetLoweringBase *TLI; |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 165 | const DataLayout *DL; |
| 166 | |
| 167 | Type *StackPtrTy; |
| 168 | Type *IntPtrTy; |
| 169 | Type *Int32Ty; |
| 170 | Type *Int8Ty; |
| 171 | |
Evgeniy Stepanov | a2002b0 | 2015-09-23 18:07:56 +0000 | [diff] [blame] | 172 | Value *UnsafeStackPtr = nullptr; |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 173 | |
| 174 | /// Unsafe stack alignment. Each stack frame must ensure that the stack is |
| 175 | /// aligned to this value. We need to re-align the unsafe stack if the |
| 176 | /// alignment of any object on the stack exceeds this value. |
| 177 | /// |
| 178 | /// 16 seems like a reasonable upper bound on the alignment of objects that we |
| 179 | /// might expect to appear on the stack on most common targets. |
| 180 | enum { StackAlignment = 16 }; |
| 181 | |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 182 | /// \brief Find all static allocas, dynamic allocas, return instructions and |
| 183 | /// stack restore points (exception unwind blocks and setjmp calls) in the |
| 184 | /// given function and append them to the respective vectors. |
| 185 | void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas, |
| 186 | SmallVectorImpl<AllocaInst *> &DynamicAllocas, |
| 187 | SmallVectorImpl<ReturnInst *> &Returns, |
| 188 | SmallVectorImpl<Instruction *> &StackRestorePoints); |
| 189 | |
| 190 | /// \brief Allocate space for all static allocas in \p StaticAllocas, |
| 191 | /// replace allocas with pointers into the unsafe stack and generate code to |
| 192 | /// restore the stack pointer before all return instructions in \p Returns. |
| 193 | /// |
| 194 | /// \returns A pointer to the top of the unsafe stack after all unsafe static |
| 195 | /// allocas are allocated. |
Evgeniy Stepanov | a2002b0 | 2015-09-23 18:07:56 +0000 | [diff] [blame] | 196 | Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F, |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 197 | ArrayRef<AllocaInst *> StaticAllocas, |
| 198 | ArrayRef<ReturnInst *> Returns); |
| 199 | |
| 200 | /// \brief Generate code to restore the stack after all stack restore points |
| 201 | /// in \p StackRestorePoints. |
| 202 | /// |
| 203 | /// \returns A local variable in which to maintain the dynamic top of the |
| 204 | /// unsafe stack if needed. |
| 205 | AllocaInst * |
Evgeniy Stepanov | 8685daf | 2015-09-24 01:23:51 +0000 | [diff] [blame] | 206 | createStackRestorePoints(IRBuilder<> &IRB, Function &F, |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 207 | ArrayRef<Instruction *> StackRestorePoints, |
| 208 | Value *StaticTop, bool NeedDynamicTop); |
| 209 | |
| 210 | /// \brief Replace all allocas in \p DynamicAllocas with code to allocate |
| 211 | /// space dynamically on the unsafe stack and store the dynamic unsafe stack |
| 212 | /// top to \p DynamicTop if non-null. |
| 213 | void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr, |
| 214 | AllocaInst *DynamicTop, |
| 215 | ArrayRef<AllocaInst *> DynamicAllocas); |
| 216 | |
| 217 | public: |
| 218 | static char ID; // Pass identification, replacement for typeid. |
Evgeniy Stepanov | a2002b0 | 2015-09-23 18:07:56 +0000 | [diff] [blame] | 219 | SafeStack(const TargetMachine *TM) |
| 220 | : FunctionPass(ID), TM(TM), TLI(nullptr), DL(nullptr) { |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 221 | initializeSafeStackPass(*PassRegistry::getPassRegistry()); |
| 222 | } |
Evgeniy Stepanov | a2002b0 | 2015-09-23 18:07:56 +0000 | [diff] [blame] | 223 | SafeStack() : SafeStack(nullptr) {} |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 224 | |
Hans Wennborg | aa15bff | 2015-09-10 16:49:58 +0000 | [diff] [blame] | 225 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 226 | AU.addRequired<AAResultsWrapperPass>(); |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 227 | } |
| 228 | |
Hans Wennborg | aa15bff | 2015-09-10 16:49:58 +0000 | [diff] [blame] | 229 | bool doInitialization(Module &M) override { |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 230 | DL = &M.getDataLayout(); |
| 231 | |
| 232 | StackPtrTy = Type::getInt8PtrTy(M.getContext()); |
| 233 | IntPtrTy = DL->getIntPtrType(M.getContext()); |
| 234 | Int32Ty = Type::getInt32Ty(M.getContext()); |
| 235 | Int8Ty = Type::getInt8Ty(M.getContext()); |
| 236 | |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 237 | return false; |
| 238 | } |
| 239 | |
Hans Wennborg | aa15bff | 2015-09-10 16:49:58 +0000 | [diff] [blame] | 240 | bool runOnFunction(Function &F) override; |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 241 | }; // class SafeStack |
| 242 | |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 243 | void SafeStack::findInsts(Function &F, |
| 244 | SmallVectorImpl<AllocaInst *> &StaticAllocas, |
| 245 | SmallVectorImpl<AllocaInst *> &DynamicAllocas, |
| 246 | SmallVectorImpl<ReturnInst *> &Returns, |
| 247 | SmallVectorImpl<Instruction *> &StackRestorePoints) { |
Nico Rieck | 7819951 | 2015-08-06 19:10:45 +0000 | [diff] [blame] | 248 | for (Instruction &I : instructions(&F)) { |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 249 | if (auto AI = dyn_cast<AllocaInst>(&I)) { |
| 250 | ++NumAllocas; |
| 251 | |
| 252 | if (IsSafeStackAlloca(AI)) |
| 253 | continue; |
| 254 | |
| 255 | if (AI->isStaticAlloca()) { |
| 256 | ++NumUnsafeStaticAllocas; |
| 257 | StaticAllocas.push_back(AI); |
| 258 | } else { |
| 259 | ++NumUnsafeDynamicAllocas; |
| 260 | DynamicAllocas.push_back(AI); |
| 261 | } |
| 262 | } else if (auto RI = dyn_cast<ReturnInst>(&I)) { |
| 263 | Returns.push_back(RI); |
| 264 | } else if (auto CI = dyn_cast<CallInst>(&I)) { |
| 265 | // setjmps require stack restore. |
| 266 | if (CI->getCalledFunction() && CI->canReturnTwice()) |
| 267 | StackRestorePoints.push_back(CI); |
| 268 | } else if (auto LP = dyn_cast<LandingPadInst>(&I)) { |
| 269 | // Exception landing pads require stack restore. |
| 270 | StackRestorePoints.push_back(LP); |
| 271 | } else if (auto II = dyn_cast<IntrinsicInst>(&I)) { |
| 272 | if (II->getIntrinsicID() == Intrinsic::gcroot) |
| 273 | llvm::report_fatal_error( |
| 274 | "gcroot intrinsic not compatible with safestack attribute"); |
| 275 | } |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | AllocaInst * |
Evgeniy Stepanov | 8685daf | 2015-09-24 01:23:51 +0000 | [diff] [blame] | 280 | SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F, |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 281 | ArrayRef<Instruction *> StackRestorePoints, |
| 282 | Value *StaticTop, bool NeedDynamicTop) { |
| 283 | if (StackRestorePoints.empty()) |
| 284 | return nullptr; |
| 285 | |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 286 | // We need the current value of the shadow stack pointer to restore |
| 287 | // after longjmp or exception catching. |
| 288 | |
| 289 | // FIXME: On some platforms this could be handled by the longjmp/exception |
| 290 | // runtime itself. |
| 291 | |
| 292 | AllocaInst *DynamicTop = nullptr; |
| 293 | if (NeedDynamicTop) |
| 294 | // If we also have dynamic alloca's, the stack pointer value changes |
| 295 | // throughout the function. For now we store it in an alloca. |
| 296 | DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr, |
| 297 | "unsafe_stack_dynamic_ptr"); |
| 298 | |
| 299 | if (!StaticTop) |
| 300 | // We need the original unsafe stack pointer value, even if there are |
| 301 | // no unsafe static allocas. |
| 302 | StaticTop = IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr"); |
| 303 | |
| 304 | if (NeedDynamicTop) |
| 305 | IRB.CreateStore(StaticTop, DynamicTop); |
| 306 | |
| 307 | // Restore current stack pointer after longjmp/exception catch. |
| 308 | for (Instruction *I : StackRestorePoints) { |
| 309 | ++NumUnsafeStackRestorePoints; |
| 310 | |
| 311 | IRB.SetInsertPoint(cast<Instruction>(I->getNextNode())); |
| 312 | Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop; |
| 313 | IRB.CreateStore(CurrentTop, UnsafeStackPtr); |
| 314 | } |
| 315 | |
| 316 | return DynamicTop; |
| 317 | } |
| 318 | |
| 319 | Value * |
Evgeniy Stepanov | a2002b0 | 2015-09-23 18:07:56 +0000 | [diff] [blame] | 320 | SafeStack::moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F, |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 321 | ArrayRef<AllocaInst *> StaticAllocas, |
| 322 | ArrayRef<ReturnInst *> Returns) { |
| 323 | if (StaticAllocas.empty()) |
| 324 | return nullptr; |
| 325 | |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 326 | DIBuilder DIB(*F.getParent()); |
| 327 | |
| 328 | // We explicitly compute and set the unsafe stack layout for all unsafe |
| 329 | // static alloca instructions. We save the unsafe "base pointer" in the |
| 330 | // prologue into a local variable and restore it in the epilogue. |
| 331 | |
| 332 | // Load the current stack pointer (we'll also use it as a base pointer). |
| 333 | // FIXME: use a dedicated register for it ? |
| 334 | Instruction *BasePointer = |
| 335 | IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr"); |
| 336 | assert(BasePointer->getType() == StackPtrTy); |
| 337 | |
| 338 | for (ReturnInst *RI : Returns) { |
| 339 | IRB.SetInsertPoint(RI); |
| 340 | IRB.CreateStore(BasePointer, UnsafeStackPtr); |
| 341 | } |
| 342 | |
| 343 | // Compute maximum alignment among static objects on the unsafe stack. |
| 344 | unsigned MaxAlignment = 0; |
| 345 | for (AllocaInst *AI : StaticAllocas) { |
| 346 | Type *Ty = AI->getAllocatedType(); |
| 347 | unsigned Align = |
| 348 | std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()); |
| 349 | if (Align > MaxAlignment) |
| 350 | MaxAlignment = Align; |
| 351 | } |
| 352 | |
| 353 | if (MaxAlignment > StackAlignment) { |
| 354 | // Re-align the base pointer according to the max requested alignment. |
| 355 | assert(isPowerOf2_32(MaxAlignment)); |
| 356 | IRB.SetInsertPoint(cast<Instruction>(BasePointer->getNextNode())); |
| 357 | BasePointer = cast<Instruction>(IRB.CreateIntToPtr( |
| 358 | IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy), |
| 359 | ConstantInt::get(IntPtrTy, ~uint64_t(MaxAlignment - 1))), |
| 360 | StackPtrTy)); |
| 361 | } |
| 362 | |
| 363 | // Allocate space for every unsafe static AllocaInst on the unsafe stack. |
| 364 | int64_t StaticOffset = 0; // Current stack top. |
| 365 | for (AllocaInst *AI : StaticAllocas) { |
| 366 | IRB.SetInsertPoint(AI); |
| 367 | |
| 368 | auto CArraySize = cast<ConstantInt>(AI->getArraySize()); |
| 369 | Type *Ty = AI->getAllocatedType(); |
| 370 | |
| 371 | uint64_t Size = DL->getTypeAllocSize(Ty) * CArraySize->getZExtValue(); |
| 372 | if (Size == 0) |
| 373 | Size = 1; // Don't create zero-sized stack objects. |
| 374 | |
| 375 | // Ensure the object is properly aligned. |
| 376 | unsigned Align = |
| 377 | std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()); |
| 378 | |
| 379 | // Add alignment. |
| 380 | // NOTE: we ensure that BasePointer itself is aligned to >= Align. |
| 381 | StaticOffset += Size; |
| 382 | StaticOffset = RoundUpToAlignment(StaticOffset, Align); |
| 383 | |
| 384 | Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8* |
| 385 | ConstantInt::get(Int32Ty, -StaticOffset)); |
| 386 | Value *NewAI = IRB.CreateBitCast(Off, AI->getType(), AI->getName()); |
| 387 | if (AI->hasName() && isa<Instruction>(NewAI)) |
| 388 | cast<Instruction>(NewAI)->takeName(AI); |
| 389 | |
| 390 | // Replace alloc with the new location. |
Evgeniy Stepanov | f608111 | 2015-09-30 19:55:43 +0000 | [diff] [blame] | 391 | replaceDbgDeclareForAlloca(AI, BasePointer, DIB, /*Deref=*/true, -StaticOffset); |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 392 | AI->replaceAllUsesWith(NewAI); |
| 393 | AI->eraseFromParent(); |
| 394 | } |
| 395 | |
| 396 | // Re-align BasePointer so that our callees would see it aligned as |
| 397 | // expected. |
| 398 | // FIXME: no need to update BasePointer in leaf functions. |
| 399 | StaticOffset = RoundUpToAlignment(StaticOffset, StackAlignment); |
| 400 | |
| 401 | // Update shadow stack pointer in the function epilogue. |
| 402 | IRB.SetInsertPoint(cast<Instruction>(BasePointer->getNextNode())); |
| 403 | |
| 404 | Value *StaticTop = |
| 405 | IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -StaticOffset), |
| 406 | "unsafe_stack_static_top"); |
| 407 | IRB.CreateStore(StaticTop, UnsafeStackPtr); |
| 408 | return StaticTop; |
| 409 | } |
| 410 | |
| 411 | void SafeStack::moveDynamicAllocasToUnsafeStack( |
| 412 | Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop, |
| 413 | ArrayRef<AllocaInst *> DynamicAllocas) { |
| 414 | DIBuilder DIB(*F.getParent()); |
| 415 | |
| 416 | for (AllocaInst *AI : DynamicAllocas) { |
| 417 | IRBuilder<> IRB(AI); |
| 418 | |
| 419 | // Compute the new SP value (after AI). |
| 420 | Value *ArraySize = AI->getArraySize(); |
| 421 | if (ArraySize->getType() != IntPtrTy) |
| 422 | ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false); |
| 423 | |
| 424 | Type *Ty = AI->getAllocatedType(); |
| 425 | uint64_t TySize = DL->getTypeAllocSize(Ty); |
| 426 | Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize)); |
| 427 | |
| 428 | Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy); |
| 429 | SP = IRB.CreateSub(SP, Size); |
| 430 | |
| 431 | // Align the SP value to satisfy the AllocaInst, type and stack alignments. |
| 432 | unsigned Align = std::max( |
| 433 | std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()), |
| 434 | (unsigned)StackAlignment); |
| 435 | |
| 436 | assert(isPowerOf2_32(Align)); |
| 437 | Value *NewTop = IRB.CreateIntToPtr( |
| 438 | IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))), |
| 439 | StackPtrTy); |
| 440 | |
| 441 | // Save the stack pointer. |
| 442 | IRB.CreateStore(NewTop, UnsafeStackPtr); |
| 443 | if (DynamicTop) |
| 444 | IRB.CreateStore(NewTop, DynamicTop); |
| 445 | |
| 446 | Value *NewAI = IRB.CreateIntToPtr(SP, AI->getType()); |
| 447 | if (AI->hasName() && isa<Instruction>(NewAI)) |
| 448 | NewAI->takeName(AI); |
| 449 | |
| 450 | replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true); |
| 451 | AI->replaceAllUsesWith(NewAI); |
| 452 | AI->eraseFromParent(); |
| 453 | } |
| 454 | |
| 455 | if (!DynamicAllocas.empty()) { |
| 456 | // Now go through the instructions again, replacing stacksave/stackrestore. |
| 457 | for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) { |
| 458 | Instruction *I = &*(It++); |
| 459 | auto II = dyn_cast<IntrinsicInst>(I); |
| 460 | if (!II) |
| 461 | continue; |
| 462 | |
| 463 | if (II->getIntrinsicID() == Intrinsic::stacksave) { |
| 464 | IRBuilder<> IRB(II); |
| 465 | Instruction *LI = IRB.CreateLoad(UnsafeStackPtr); |
| 466 | LI->takeName(II); |
| 467 | II->replaceAllUsesWith(LI); |
| 468 | II->eraseFromParent(); |
| 469 | } else if (II->getIntrinsicID() == Intrinsic::stackrestore) { |
| 470 | IRBuilder<> IRB(II); |
| 471 | Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr); |
| 472 | SI->takeName(II); |
| 473 | assert(II->use_empty()); |
| 474 | II->eraseFromParent(); |
| 475 | } |
| 476 | } |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | bool SafeStack::runOnFunction(Function &F) { |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 481 | DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n"); |
| 482 | |
| 483 | if (!F.hasFnAttribute(Attribute::SafeStack)) { |
| 484 | DEBUG(dbgs() << "[SafeStack] safestack is not requested" |
| 485 | " for this function\n"); |
| 486 | return false; |
| 487 | } |
| 488 | |
| 489 | if (F.isDeclaration()) { |
| 490 | DEBUG(dbgs() << "[SafeStack] function definition" |
| 491 | " is not available\n"); |
| 492 | return false; |
| 493 | } |
| 494 | |
Evgeniy Stepanov | a2002b0 | 2015-09-23 18:07:56 +0000 | [diff] [blame] | 495 | auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); |
| 496 | |
| 497 | TLI = TM ? TM->getSubtargetImpl(F)->getTargetLowering() : nullptr; |
| 498 | |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 499 | { |
| 500 | // Make sure the regular stack protector won't run on this function |
| 501 | // (safestack attribute takes precedence). |
| 502 | AttrBuilder B; |
| 503 | B.addAttribute(Attribute::StackProtect) |
| 504 | .addAttribute(Attribute::StackProtectReq) |
| 505 | .addAttribute(Attribute::StackProtectStrong); |
| 506 | F.removeAttributes( |
| 507 | AttributeSet::FunctionIndex, |
| 508 | AttributeSet::get(F.getContext(), AttributeSet::FunctionIndex, B)); |
| 509 | } |
| 510 | |
| 511 | if (AA->onlyReadsMemory(&F)) { |
| 512 | // XXX: we don't protect against information leak attacks for now. |
| 513 | DEBUG(dbgs() << "[SafeStack] function only reads memory\n"); |
| 514 | return false; |
| 515 | } |
| 516 | |
| 517 | ++NumFunctions; |
| 518 | |
| 519 | SmallVector<AllocaInst *, 16> StaticAllocas; |
| 520 | SmallVector<AllocaInst *, 4> DynamicAllocas; |
| 521 | SmallVector<ReturnInst *, 4> Returns; |
| 522 | |
| 523 | // Collect all points where stack gets unwound and needs to be restored |
| 524 | // This is only necessary because the runtime (setjmp and unwind code) is |
| 525 | // not aware of the unsafe stack and won't unwind/restore it prorerly. |
| 526 | // To work around this problem without changing the runtime, we insert |
| 527 | // instrumentation to restore the unsafe stack pointer when necessary. |
| 528 | SmallVector<Instruction *, 4> StackRestorePoints; |
| 529 | |
| 530 | // Find all static and dynamic alloca instructions that must be moved to the |
| 531 | // unsafe stack, all return instructions and stack restore points. |
| 532 | findInsts(F, StaticAllocas, DynamicAllocas, Returns, StackRestorePoints); |
| 533 | |
| 534 | if (StaticAllocas.empty() && DynamicAllocas.empty() && |
| 535 | StackRestorePoints.empty()) |
| 536 | return false; // Nothing to do in this function. |
| 537 | |
| 538 | if (!StaticAllocas.empty() || !DynamicAllocas.empty()) |
| 539 | ++NumUnsafeStackFunctions; // This function has the unsafe stack. |
| 540 | |
| 541 | if (!StackRestorePoints.empty()) |
| 542 | ++NumUnsafeStackRestorePointsFunctions; |
| 543 | |
Duncan P. N. Exon Smith | e82c286 | 2015-10-13 17:39:10 +0000 | [diff] [blame] | 544 | IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt()); |
Evgeniy Stepanov | 142947e | 2015-10-15 20:50:16 +0000 | [diff] [blame] | 545 | UnsafeStackPtr = TLI->getSafeStackPointerLocation(IRB); |
Peter Collingbourne | de26a91 | 2015-06-22 20:26:54 +0000 | [diff] [blame] | 546 | |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 547 | // The top of the unsafe stack after all unsafe static allocas are allocated. |
Evgeniy Stepanov | a2002b0 | 2015-09-23 18:07:56 +0000 | [diff] [blame] | 548 | Value *StaticTop = moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, Returns); |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 549 | |
| 550 | // Safe stack object that stores the current unsafe stack top. It is updated |
| 551 | // as unsafe dynamic (non-constant-sized) allocas are allocated and freed. |
| 552 | // This is only needed if we need to restore stack pointer after longjmp |
| 553 | // or exceptions, and we have dynamic allocations. |
| 554 | // FIXME: a better alternative might be to store the unsafe stack pointer |
| 555 | // before setjmp / invoke instructions. |
| 556 | AllocaInst *DynamicTop = createStackRestorePoints( |
Evgeniy Stepanov | 8685daf | 2015-09-24 01:23:51 +0000 | [diff] [blame] | 557 | IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty()); |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 558 | |
| 559 | // Handle dynamic allocas. |
| 560 | moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop, |
| 561 | DynamicAllocas); |
| 562 | |
| 563 | DEBUG(dbgs() << "[SafeStack] safestack applied\n"); |
| 564 | return true; |
| 565 | } |
| 566 | |
Hans Wennborg | 083ca9b | 2015-10-06 23:24:35 +0000 | [diff] [blame] | 567 | } // anonymous namespace |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 568 | |
| 569 | char SafeStack::ID = 0; |
Evgeniy Stepanov | a2002b0 | 2015-09-23 18:07:56 +0000 | [diff] [blame] | 570 | INITIALIZE_TM_PASS_BEGIN(SafeStack, "safe-stack", |
| 571 | "Safe Stack instrumentation pass", false, false) |
| 572 | INITIALIZE_TM_PASS_END(SafeStack, "safe-stack", |
| 573 | "Safe Stack instrumentation pass", false, false) |
Peter Collingbourne | 82437bf | 2015-06-15 21:07:11 +0000 | [diff] [blame] | 574 | |
Evgeniy Stepanov | a2002b0 | 2015-09-23 18:07:56 +0000 | [diff] [blame] | 575 | FunctionPass *llvm::createSafeStackPass(const llvm::TargetMachine *TM) { |
| 576 | return new SafeStack(TM); |
| 577 | } |