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