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