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/ADT/Statistic.h" 19 #include "llvm/ADT/Triple.h" 20 #include "llvm/Analysis/BranchProbabilityInfo.h" 21 #include "llvm/Analysis/ScalarEvolution.h" 22 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 23 #include "llvm/CodeGen/Passes.h" 24 #include "llvm/CodeGen/Passes.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DIBuilder.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/IRBuilder.h" 31 #include "llvm/IR/InstIterator.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/Intrinsics.h" 35 #include "llvm/IR/MDBuilder.h" 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" 43 #include "llvm/Target/TargetLowering.h" 44 #include "llvm/Target/TargetSubtargetInfo.h" 45 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 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 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 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"); 74 STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments"); 75 STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads"); 76 77 } // namespace llvm 78 79 namespace { 80 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> { 86 const Value *AllocaPtr; 87 88 public: 89 AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr) 90 : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {} 91 92 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 93 if (Expr->getValue() == AllocaPtr) 94 return SE.getZero(Expr->getType()); 95 return Expr; 96 } 97 }; 98 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. 104 class SafeStack : public FunctionPass { 105 const TargetMachine *TM; 106 const TargetLoweringBase *TL; 107 const DataLayout *DL; 108 ScalarEvolution *SE; 109 110 Type *StackPtrTy; 111 Type *IntPtrTy; 112 Type *Int32Ty; 113 Type *Int8Ty; 114 115 Value *UnsafeStackPtr = nullptr; 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 125 /// \brief Build a value representing a pointer to the unsafe stack pointer. 126 Value *getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F); 127 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 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, 140 SmallVectorImpl<Argument *> &ByValArguments, 141 SmallVectorImpl<ReturnInst *> &Returns, 142 SmallVectorImpl<Instruction *> &StackRestorePoints); 143 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 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. 154 Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F, 155 ArrayRef<AllocaInst *> StaticAllocas, 156 ArrayRef<Argument *> ByValArguments, 157 ArrayRef<ReturnInst *> Returns, 158 Instruction *BasePointer, 159 AllocaInst *StackGuardSlot); 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 * 167 createStackRestorePoints(IRBuilder<> &IRB, Function &F, 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 178 bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize); 179 180 bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U, 181 const Value *AllocaPtr, uint64_t AllocaSize); 182 bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr, 183 uint64_t AllocaSize); 184 185 public: 186 static char ID; // Pass identification, replacement for typeid. 187 SafeStack(const TargetMachine *TM) 188 : FunctionPass(ID), TM(TM), TL(nullptr), DL(nullptr) { 189 initializeSafeStackPass(*PassRegistry::getPassRegistry()); 190 } 191 SafeStack() : SafeStack(nullptr) {} 192 193 void getAnalysisUsage(AnalysisUsage &AU) const override { 194 AU.addRequired<ScalarEvolutionWrapperPass>(); 195 } 196 197 bool doInitialization(Module &M) override { 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 205 return false; 206 } 207 208 bool runOnFunction(Function &F) override; 209 }; // class SafeStack 210 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 222 bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize, 223 const Value *AllocaPtr, uint64_t AllocaSize) { 224 AllocaOffsetRewriter Rewriter(*SE, AllocaPtr); 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 = 230 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize)); 231 ConstantRange AccessRange = AccessStartRange.add(SizeRange); 232 ConstantRange AllocaRange = 233 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize)); 234 bool Safe = AllocaRange.contains(AccessRange); 235 236 DEBUG(dbgs() << "[SafeStack] " 237 << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ") 238 << *AllocaPtr << "\n" 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, 251 const Value *AllocaPtr, 252 uint64_t AllocaSize) { 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; 258 return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize); 259 } 260 261 /// Check whether a given allocation must be put on the safe 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). 264 bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) { 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; 269 SmallVector<const Value *, 8> WorkList; 270 WorkList.push_back(AllocaPtr); 271 272 // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc. 273 while (!WorkList.empty()) { 274 const Value *V = WorkList.pop_back_val(); 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: { 281 if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getType()), AllocaPtr, 282 AllocaSize)) 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. 292 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr 293 << "\n store of address: " << *I << "\n"); 294 return false; 295 } 296 297 if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getOperand(0)->getType()), 298 AllocaPtr, AllocaSize)) 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)) { 318 if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) { 319 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr 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) 337 if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) || 338 CS.doesNotAccessMemory()))) { 339 DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr 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 357 Value *SafeStack::getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F) { 358 // Check if there is a target-specific location for the unsafe stack pointer. 359 if (TL) 360 if (Value *V = TL->getSafeStackPointerLocation(IRB)) 361 return V; 362 363 // Otherwise, assume the target links with compiler-rt, which provides a 364 // thread-local variable with a magic name. 365 Module &M = *F.getParent(); 366 const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr"; 367 auto UnsafeStackPtr = 368 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(UnsafeStackPtrVar)); 369 370 bool UseTLS = USPStorage == ThreadLocalUSP; 371 372 if (!UnsafeStackPtr) { 373 auto TLSModel = UseTLS ? 374 GlobalValue::InitialExecTLSModel : 375 GlobalValue::NotThreadLocal; 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( 380 M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr, 381 UnsafeStackPtrVar, nullptr, TLSModel); 382 } else { 383 // The variable exists, check its type and attributes. 384 if (UnsafeStackPtr->getValueType() != StackPtrTy) 385 report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type"); 386 if (UseTLS != UnsafeStackPtr->isThreadLocal()) 387 report_fatal_error(Twine(UnsafeStackPtrVar) + " must " + 388 (UseTLS ? "" : "not ") + "be thread-local"); 389 } 390 return UnsafeStackPtr; 391 } 392 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 403 void SafeStack::findInsts(Function &F, 404 SmallVectorImpl<AllocaInst *> &StaticAllocas, 405 SmallVectorImpl<AllocaInst *> &DynamicAllocas, 406 SmallVectorImpl<Argument *> &ByValArguments, 407 SmallVectorImpl<ReturnInst *> &Returns, 408 SmallVectorImpl<Instruction *> &StackRestorePoints) { 409 for (Instruction &I : instructions(&F)) { 410 if (auto AI = dyn_cast<AllocaInst>(&I)) { 411 ++NumAllocas; 412 413 uint64_t Size = getStaticAllocaAllocationSize(AI); 414 if (IsSafeStackAlloca(AI, Size)) 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 } 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 } 450 } 451 452 AllocaInst * 453 SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F, 454 ArrayRef<Instruction *> StackRestorePoints, 455 Value *StaticTop, bool NeedDynamicTop) { 456 assert(StaticTop && "The stack top isn't set."); 457 458 if (StackRestorePoints.empty()) 459 return nullptr; 460 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; 468 if (NeedDynamicTop) { 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"); 473 IRB.CreateStore(StaticTop, DynamicTop); 474 } 475 476 // Restore current stack pointer after longjmp/exception catch. 477 for (Instruction *I : StackRestorePoints) { 478 ++NumUnsafeStackRestorePoints; 479 480 IRB.SetInsertPoint(I->getNextNode()); 481 Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop; 482 IRB.CreateStore(CurrentTop, UnsafeStackPtr); 483 } 484 485 return DynamicTop; 486 } 487 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 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. 511 Value *SafeStack::moveStaticAllocasToUnsafeStack( 512 IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas, 513 ArrayRef<Argument *> ByValArguments, ArrayRef<ReturnInst *> Returns, 514 Instruction *BasePointer, AllocaInst *StackGuardSlot) { 515 if (StaticAllocas.empty() && ByValArguments.empty()) 516 return BasePointer; 517 518 DIBuilder DIB(*F.getParent()); 519 520 // Compute maximum alignment among static objects on the unsafe stack. 521 unsigned MaxAlignment = 0; 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 } 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)); 540 IRB.SetInsertPoint(BasePointer->getNextNode()); 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 547 int64_t StaticOffset = 0; // Current stack top. 548 IRB.SetInsertPoint(BasePointer->getNextNode()); 549 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 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; 576 StaticOffset = alignTo(StaticOffset, Align); 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. 592 for (AllocaInst *AI : StaticAllocas) { 593 IRB.SetInsertPoint(AI); 594 595 Type *Ty = AI->getAllocatedType(); 596 uint64_t Size = getStaticAllocaAllocationSize(AI); 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; 607 StaticOffset = alignTo(StaticOffset, Align); 608 609 replaceDbgDeclareForAlloca(AI, BasePointer, DIB, /*Deref=*/true, -StaticOffset); 610 replaceDbgValueForAlloca(AI, BasePointer, DIB, -StaticOffset); 611 612 // Replace uses of the alloca with the new location. 613 // Insert address calculation close to each use to work around PR27844. 614 std::string Name = std::string(AI->getName()) + ".unsafe"; 615 while (!AI->use_empty()) { 616 Use &U = *AI->use_begin(); 617 Instruction *User = cast<Instruction>(U.getUser()); 618 619 Instruction *InsertBefore; 620 if (auto *PHI = dyn_cast<PHINode>(User)) 621 InsertBefore = PHI->getIncomingBlock(U)->getTerminator(); 622 else 623 InsertBefore = User; 624 625 IRBuilder<> IRBUser(InsertBefore); 626 Value *Off = IRBUser.CreateGEP(BasePointer, // BasePointer is i8* 627 ConstantInt::get(Int32Ty, -StaticOffset)); 628 Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name); 629 630 if (auto *PHI = dyn_cast<PHINode>(User)) { 631 // PHI nodes may have multiple incoming edges from the same BB (why??), 632 // all must be updated at once with the same incoming value. 633 auto *BB = PHI->getIncomingBlock(U); 634 for (unsigned I = 0; I < PHI->getNumIncomingValues(); ++I) 635 if (PHI->getIncomingBlock(I) == BB) 636 PHI->setIncomingValue(I, Replacement); 637 } else { 638 U.set(Replacement); 639 } 640 } 641 642 AI->eraseFromParent(); 643 } 644 645 // Re-align BasePointer so that our callees would see it aligned as 646 // expected. 647 // FIXME: no need to update BasePointer in leaf functions. 648 StaticOffset = alignTo(StaticOffset, StackAlignment); 649 650 // Update shadow stack pointer in the function epilogue. 651 IRB.SetInsertPoint(BasePointer->getNextNode()); 652 653 Value *StaticTop = 654 IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -StaticOffset), 655 "unsafe_stack_static_top"); 656 IRB.CreateStore(StaticTop, UnsafeStackPtr); 657 return StaticTop; 658 } 659 660 void SafeStack::moveDynamicAllocasToUnsafeStack( 661 Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop, 662 ArrayRef<AllocaInst *> DynamicAllocas) { 663 DIBuilder DIB(*F.getParent()); 664 665 for (AllocaInst *AI : DynamicAllocas) { 666 IRBuilder<> IRB(AI); 667 668 // Compute the new SP value (after AI). 669 Value *ArraySize = AI->getArraySize(); 670 if (ArraySize->getType() != IntPtrTy) 671 ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false); 672 673 Type *Ty = AI->getAllocatedType(); 674 uint64_t TySize = DL->getTypeAllocSize(Ty); 675 Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize)); 676 677 Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy); 678 SP = IRB.CreateSub(SP, Size); 679 680 // Align the SP value to satisfy the AllocaInst, type and stack alignments. 681 unsigned Align = std::max( 682 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()), 683 (unsigned)StackAlignment); 684 685 assert(isPowerOf2_32(Align)); 686 Value *NewTop = IRB.CreateIntToPtr( 687 IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))), 688 StackPtrTy); 689 690 // Save the stack pointer. 691 IRB.CreateStore(NewTop, UnsafeStackPtr); 692 if (DynamicTop) 693 IRB.CreateStore(NewTop, DynamicTop); 694 695 Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType()); 696 if (AI->hasName() && isa<Instruction>(NewAI)) 697 NewAI->takeName(AI); 698 699 replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true); 700 AI->replaceAllUsesWith(NewAI); 701 AI->eraseFromParent(); 702 } 703 704 if (!DynamicAllocas.empty()) { 705 // Now go through the instructions again, replacing stacksave/stackrestore. 706 for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) { 707 Instruction *I = &*(It++); 708 auto II = dyn_cast<IntrinsicInst>(I); 709 if (!II) 710 continue; 711 712 if (II->getIntrinsicID() == Intrinsic::stacksave) { 713 IRBuilder<> IRB(II); 714 Instruction *LI = IRB.CreateLoad(UnsafeStackPtr); 715 LI->takeName(II); 716 II->replaceAllUsesWith(LI); 717 II->eraseFromParent(); 718 } else if (II->getIntrinsicID() == Intrinsic::stackrestore) { 719 IRBuilder<> IRB(II); 720 Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr); 721 SI->takeName(II); 722 assert(II->use_empty()); 723 II->eraseFromParent(); 724 } 725 } 726 } 727 } 728 729 bool SafeStack::runOnFunction(Function &F) { 730 DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n"); 731 732 if (!F.hasFnAttribute(Attribute::SafeStack)) { 733 DEBUG(dbgs() << "[SafeStack] safestack is not requested" 734 " for this function\n"); 735 return false; 736 } 737 738 if (F.isDeclaration()) { 739 DEBUG(dbgs() << "[SafeStack] function definition" 740 " is not available\n"); 741 return false; 742 } 743 744 TL = TM ? TM->getSubtargetImpl(F)->getTargetLowering() : nullptr; 745 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 746 747 ++NumFunctions; 748 749 SmallVector<AllocaInst *, 16> StaticAllocas; 750 SmallVector<AllocaInst *, 4> DynamicAllocas; 751 SmallVector<Argument *, 4> ByValArguments; 752 SmallVector<ReturnInst *, 4> Returns; 753 754 // Collect all points where stack gets unwound and needs to be restored 755 // This is only necessary because the runtime (setjmp and unwind code) is 756 // not aware of the unsafe stack and won't unwind/restore it prorerly. 757 // To work around this problem without changing the runtime, we insert 758 // instrumentation to restore the unsafe stack pointer when necessary. 759 SmallVector<Instruction *, 4> StackRestorePoints; 760 761 // Find all static and dynamic alloca instructions that must be moved to the 762 // unsafe stack, all return instructions and stack restore points. 763 findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns, 764 StackRestorePoints); 765 766 if (StaticAllocas.empty() && DynamicAllocas.empty() && 767 ByValArguments.empty() && StackRestorePoints.empty()) 768 return false; // Nothing to do in this function. 769 770 if (!StaticAllocas.empty() || !DynamicAllocas.empty() || 771 !ByValArguments.empty()) 772 ++NumUnsafeStackFunctions; // This function has the unsafe stack. 773 774 if (!StackRestorePoints.empty()) 775 ++NumUnsafeStackRestorePointsFunctions; 776 777 IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt()); 778 UnsafeStackPtr = getOrCreateUnsafeStackPtr(IRB, F); 779 780 // Load the current stack pointer (we'll also use it as a base pointer). 781 // FIXME: use a dedicated register for it ? 782 Instruction *BasePointer = 783 IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr"); 784 assert(BasePointer->getType() == StackPtrTy); 785 786 AllocaInst *StackGuardSlot = nullptr; 787 // FIXME: implement weaker forms of stack protector. 788 if (F.hasFnAttribute(Attribute::StackProtect) || 789 F.hasFnAttribute(Attribute::StackProtectStrong) || 790 F.hasFnAttribute(Attribute::StackProtectReq)) { 791 Value *StackGuard = getStackGuard(IRB, F); 792 StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr); 793 IRB.CreateStore(StackGuard, StackGuardSlot); 794 795 for (ReturnInst *RI : Returns) { 796 IRBuilder<> IRBRet(RI); 797 checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard); 798 } 799 } 800 801 // The top of the unsafe stack after all unsafe static allocas are 802 // allocated. 803 Value *StaticTop = 804 moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, ByValArguments, 805 Returns, BasePointer, StackGuardSlot); 806 807 // Safe stack object that stores the current unsafe stack top. It is updated 808 // as unsafe dynamic (non-constant-sized) allocas are allocated and freed. 809 // This is only needed if we need to restore stack pointer after longjmp 810 // or exceptions, and we have dynamic allocations. 811 // FIXME: a better alternative might be to store the unsafe stack pointer 812 // before setjmp / invoke instructions. 813 AllocaInst *DynamicTop = createStackRestorePoints( 814 IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty()); 815 816 // Handle dynamic allocas. 817 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop, 818 DynamicAllocas); 819 820 // Restore the unsafe stack pointer before each return. 821 for (ReturnInst *RI : Returns) { 822 IRB.SetInsertPoint(RI); 823 IRB.CreateStore(BasePointer, UnsafeStackPtr); 824 } 825 826 DEBUG(dbgs() << "[SafeStack] safestack applied\n"); 827 return true; 828 } 829 830 } // anonymous namespace 831 832 char SafeStack::ID = 0; 833 INITIALIZE_TM_PASS_BEGIN(SafeStack, "safe-stack", 834 "Safe Stack instrumentation pass", false, false) 835 INITIALIZE_TM_PASS_END(SafeStack, "safe-stack", 836 "Safe Stack instrumentation pass", false, false) 837 838 FunctionPass *llvm::createSafeStackPass(const llvm::TargetMachine *TM) { 839 return new SafeStack(TM); 840 } 841