1 //===-- SafeStack.cpp - Safe Stack Insertion ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 // http://clang.llvm.org/docs/SafeStack.html
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Instrumentation.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/DIBuilder.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/InstIterator.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Format.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_os_ostream.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
43 #include "llvm/Transforms/Utils/Local.h"
44 #include "llvm/Transforms/Utils/ModuleUtils.h"
48 #define DEBUG_TYPE "safestack"
52 STATISTIC(NumFunctions, "Total number of functions");
53 STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
54 STATISTIC(NumUnsafeStackRestorePointsFunctions,
55 "Number of functions that use setjmp or exceptions");
57 STATISTIC(NumAllocas, "Total number of allocas");
58 STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
59 STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
60 STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
61 STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
67 /// Rewrite an SCEV expression for a memory access address to an expression that
68 /// represents offset from the given alloca.
70 /// The implementation simply replaces all mentions of the alloca with zero.
71 class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
72 const Value *AllocaPtr;
75 AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
76 : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
78 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
79 if (Expr->getValue() == AllocaPtr)
80 return SE.getZero(Expr->getType());
85 /// The SafeStack pass splits the stack of each function into the safe
86 /// stack, which is only accessed through memory safe dereferences (as
87 /// determined statically), and the unsafe stack, which contains all
88 /// local variables that are accessed in ways that we can't prove to
90 class SafeStack : public FunctionPass {
91 const TargetMachine *TM;
92 const TargetLoweringBase *TL;
101 Value *UnsafeStackPtr = nullptr;
103 /// Unsafe stack alignment. Each stack frame must ensure that the stack is
104 /// aligned to this value. We need to re-align the unsafe stack if the
105 /// alignment of any object on the stack exceeds this value.
107 /// 16 seems like a reasonable upper bound on the alignment of objects that we
108 /// might expect to appear on the stack on most common targets.
109 enum { StackAlignment = 16 };
111 /// \brief Build a value representing a pointer to the unsafe stack pointer.
112 Value *getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F);
114 /// \brief Find all static allocas, dynamic allocas, return instructions and
115 /// stack restore points (exception unwind blocks and setjmp calls) in the
116 /// given function and append them to the respective vectors.
117 void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
118 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
119 SmallVectorImpl<Argument *> &ByValArguments,
120 SmallVectorImpl<ReturnInst *> &Returns,
121 SmallVectorImpl<Instruction *> &StackRestorePoints);
123 /// \brief Calculate the allocation size of a given alloca. Returns 0 if the
124 /// size can not be statically determined.
125 uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
127 /// \brief Allocate space for all static allocas in \p StaticAllocas,
128 /// replace allocas with pointers into the unsafe stack and generate code to
129 /// restore the stack pointer before all return instructions in \p Returns.
131 /// \returns A pointer to the top of the unsafe stack after all unsafe static
132 /// allocas are allocated.
133 Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
134 ArrayRef<AllocaInst *> StaticAllocas,
135 ArrayRef<Argument *> ByValArguments,
136 ArrayRef<ReturnInst *> Returns);
138 /// \brief Generate code to restore the stack after all stack restore points
139 /// in \p StackRestorePoints.
141 /// \returns A local variable in which to maintain the dynamic top of the
142 /// unsafe stack if needed.
144 createStackRestorePoints(IRBuilder<> &IRB, Function &F,
145 ArrayRef<Instruction *> StackRestorePoints,
146 Value *StaticTop, bool NeedDynamicTop);
148 /// \brief Replace all allocas in \p DynamicAllocas with code to allocate
149 /// space dynamically on the unsafe stack and store the dynamic unsafe stack
150 /// top to \p DynamicTop if non-null.
151 void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
152 AllocaInst *DynamicTop,
153 ArrayRef<AllocaInst *> DynamicAllocas);
155 bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
157 bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
158 const Value *AllocaPtr, uint64_t AllocaSize);
159 bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
160 uint64_t AllocaSize);
163 static char ID; // Pass identification, replacement for typeid.
164 SafeStack(const TargetMachine *TM)
165 : FunctionPass(ID), TM(TM), TL(nullptr), DL(nullptr) {
166 initializeSafeStackPass(*PassRegistry::getPassRegistry());
168 SafeStack() : SafeStack(nullptr) {}
170 void getAnalysisUsage(AnalysisUsage &AU) const override {
171 AU.addRequired<ScalarEvolutionWrapperPass>();
174 bool doInitialization(Module &M) override {
175 DL = &M.getDataLayout();
177 StackPtrTy = Type::getInt8PtrTy(M.getContext());
178 IntPtrTy = DL->getIntPtrType(M.getContext());
179 Int32Ty = Type::getInt32Ty(M.getContext());
180 Int8Ty = Type::getInt8Ty(M.getContext());
185 bool runOnFunction(Function &F) override;
186 }; // class SafeStack
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());
194 Size *= C->getZExtValue();
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));
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);
213 DEBUG(dbgs() << "[SafeStack] "
214 << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
215 << *AllocaPtr << "\n"
216 << " Access " << *Addr << "\n"
218 << " U: " << SE->getUnsignedRange(Expr)
219 << ", S: " << SE->getSignedRange(Expr) << "\n"
220 << " Range " << AccessRange << "\n"
221 << " AllocaRange " << AllocaRange << "\n"
222 << " " << (Safe ? "safe" : "unsafe") << "\n");
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);
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);
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());
256 switch (I->getOpcode()) {
257 case Instruction::Load: {
258 if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getType()), AllocaPtr,
263 case Instruction::VAArg:
264 // "va-arg" from a pointer is safe.
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");
274 if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getOperand(0)->getType()),
275 AllocaPtr, AllocaSize))
279 case Instruction::Ret: {
284 case Instruction::Call:
285 case Instruction::Invoke: {
286 ImmutableCallSite CS(I);
288 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
289 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
290 II->getIntrinsicID() == Intrinsic::lifetime_end)
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
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)
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");
324 if (Visited.insert(I).second)
325 WorkList.push_back(cast<const Instruction>(I));
330 // All uses of the alloca are safe, we can place it on the safe stack.
334 Value *SafeStack::getOrCreateUnsafeStackPtr(IRBuilder<> &IRB, Function &F) {
335 // Check if there is a target-specific location for the unsafe stack pointer.
337 if (Value *V = TL->getSafeStackPointerLocation(IRB))
340 // Otherwise, assume the target links with compiler-rt, which provides a
341 // thread-local variable with a magic name.
342 Module &M = *F.getParent();
343 const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
344 auto UnsafeStackPtr =
345 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(UnsafeStackPtrVar));
347 if (!UnsafeStackPtr) {
348 // The global variable is not defined yet, define it ourselves.
349 // We use the initial-exec TLS model because we do not support the
350 // variable living anywhere other than in the main executable.
351 UnsafeStackPtr = new GlobalVariable(
352 M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
353 UnsafeStackPtrVar, nullptr, GlobalValue::InitialExecTLSModel);
355 // The variable exists, check its type and attributes.
356 if (UnsafeStackPtr->getValueType() != StackPtrTy)
357 report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
358 if (!UnsafeStackPtr->isThreadLocal())
359 report_fatal_error(Twine(UnsafeStackPtrVar) + " must be thread-local");
361 return UnsafeStackPtr;
364 void SafeStack::findInsts(Function &F,
365 SmallVectorImpl<AllocaInst *> &StaticAllocas,
366 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
367 SmallVectorImpl<Argument *> &ByValArguments,
368 SmallVectorImpl<ReturnInst *> &Returns,
369 SmallVectorImpl<Instruction *> &StackRestorePoints) {
370 for (Instruction &I : instructions(&F)) {
371 if (auto AI = dyn_cast<AllocaInst>(&I)) {
374 uint64_t Size = getStaticAllocaAllocationSize(AI);
375 if (IsSafeStackAlloca(AI, Size))
378 if (AI->isStaticAlloca()) {
379 ++NumUnsafeStaticAllocas;
380 StaticAllocas.push_back(AI);
382 ++NumUnsafeDynamicAllocas;
383 DynamicAllocas.push_back(AI);
385 } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
386 Returns.push_back(RI);
387 } else if (auto CI = dyn_cast<CallInst>(&I)) {
388 // setjmps require stack restore.
389 if (CI->getCalledFunction() && CI->canReturnTwice())
390 StackRestorePoints.push_back(CI);
391 } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
392 // Exception landing pads require stack restore.
393 StackRestorePoints.push_back(LP);
394 } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
395 if (II->getIntrinsicID() == Intrinsic::gcroot)
396 llvm::report_fatal_error(
397 "gcroot intrinsic not compatible with safestack attribute");
400 for (Argument &Arg : F.args()) {
401 if (!Arg.hasByValAttr())
404 DL->getTypeStoreSize(Arg.getType()->getPointerElementType());
405 if (IsSafeStackAlloca(&Arg, Size))
408 ++NumUnsafeByValArguments;
409 ByValArguments.push_back(&Arg);
414 SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
415 ArrayRef<Instruction *> StackRestorePoints,
416 Value *StaticTop, bool NeedDynamicTop) {
417 if (StackRestorePoints.empty())
420 // We need the current value of the shadow stack pointer to restore
421 // after longjmp or exception catching.
423 // FIXME: On some platforms this could be handled by the longjmp/exception
426 AllocaInst *DynamicTop = nullptr;
428 // If we also have dynamic alloca's, the stack pointer value changes
429 // throughout the function. For now we store it in an alloca.
430 DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
431 "unsafe_stack_dynamic_ptr");
434 // We need the original unsafe stack pointer value, even if there are
435 // no unsafe static allocas.
436 StaticTop = IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
439 IRB.CreateStore(StaticTop, DynamicTop);
441 // Restore current stack pointer after longjmp/exception catch.
442 for (Instruction *I : StackRestorePoints) {
443 ++NumUnsafeStackRestorePoints;
445 IRB.SetInsertPoint(I->getNextNode());
446 Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
447 IRB.CreateStore(CurrentTop, UnsafeStackPtr);
453 Value *SafeStack::moveStaticAllocasToUnsafeStack(
454 IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
455 ArrayRef<Argument *> ByValArguments, ArrayRef<ReturnInst *> Returns) {
456 if (StaticAllocas.empty() && ByValArguments.empty())
459 DIBuilder DIB(*F.getParent());
461 // We explicitly compute and set the unsafe stack layout for all unsafe
462 // static alloca instructions. We save the unsafe "base pointer" in the
463 // prologue into a local variable and restore it in the epilogue.
465 // Load the current stack pointer (we'll also use it as a base pointer).
466 // FIXME: use a dedicated register for it ?
467 Instruction *BasePointer =
468 IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
469 assert(BasePointer->getType() == StackPtrTy);
471 for (ReturnInst *RI : Returns) {
472 IRB.SetInsertPoint(RI);
473 IRB.CreateStore(BasePointer, UnsafeStackPtr);
476 // Compute maximum alignment among static objects on the unsafe stack.
477 unsigned MaxAlignment = 0;
478 for (Argument *Arg : ByValArguments) {
479 Type *Ty = Arg->getType()->getPointerElementType();
480 unsigned Align = std::max((unsigned)DL->getPrefTypeAlignment(Ty),
481 Arg->getParamAlignment());
482 if (Align > MaxAlignment)
483 MaxAlignment = Align;
485 for (AllocaInst *AI : StaticAllocas) {
486 Type *Ty = AI->getAllocatedType();
488 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
489 if (Align > MaxAlignment)
490 MaxAlignment = Align;
493 if (MaxAlignment > StackAlignment) {
494 // Re-align the base pointer according to the max requested alignment.
495 assert(isPowerOf2_32(MaxAlignment));
496 IRB.SetInsertPoint(BasePointer->getNextNode());
497 BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
498 IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
499 ConstantInt::get(IntPtrTy, ~uint64_t(MaxAlignment - 1))),
503 int64_t StaticOffset = 0; // Current stack top.
504 IRB.SetInsertPoint(BasePointer->getNextNode());
506 for (Argument *Arg : ByValArguments) {
507 Type *Ty = Arg->getType()->getPointerElementType();
509 uint64_t Size = DL->getTypeStoreSize(Ty);
511 Size = 1; // Don't create zero-sized stack objects.
513 // Ensure the object is properly aligned.
514 unsigned Align = std::max((unsigned)DL->getPrefTypeAlignment(Ty),
515 Arg->getParamAlignment());
518 // NOTE: we ensure that BasePointer itself is aligned to >= Align.
519 StaticOffset += Size;
520 StaticOffset = RoundUpToAlignment(StaticOffset, Align);
522 Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
523 ConstantInt::get(Int32Ty, -StaticOffset));
524 Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
525 Arg->getName() + ".unsafe-byval");
527 // Replace alloc with the new location.
528 replaceDbgDeclare(Arg, BasePointer, BasePointer->getNextNode(), DIB,
529 /*Deref=*/true, -StaticOffset);
530 Arg->replaceAllUsesWith(NewArg);
531 IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
532 IRB.CreateMemCpy(Off, Arg, Size, Arg->getParamAlignment());
535 // Allocate space for every unsafe static AllocaInst on the unsafe stack.
536 for (AllocaInst *AI : StaticAllocas) {
537 IRB.SetInsertPoint(AI);
539 Type *Ty = AI->getAllocatedType();
540 uint64_t Size = getStaticAllocaAllocationSize(AI);
542 Size = 1; // Don't create zero-sized stack objects.
544 // Ensure the object is properly aligned.
546 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
549 // NOTE: we ensure that BasePointer itself is aligned to >= Align.
550 StaticOffset += Size;
551 StaticOffset = RoundUpToAlignment(StaticOffset, Align);
553 Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
554 ConstantInt::get(Int32Ty, -StaticOffset));
555 Value *NewAI = IRB.CreateBitCast(Off, AI->getType(), AI->getName());
556 if (AI->hasName() && isa<Instruction>(NewAI))
557 cast<Instruction>(NewAI)->takeName(AI);
559 // Replace alloc with the new location.
560 replaceDbgDeclareForAlloca(AI, BasePointer, DIB, /*Deref=*/true, -StaticOffset);
561 AI->replaceAllUsesWith(NewAI);
562 AI->eraseFromParent();
565 // Re-align BasePointer so that our callees would see it aligned as
567 // FIXME: no need to update BasePointer in leaf functions.
568 StaticOffset = RoundUpToAlignment(StaticOffset, StackAlignment);
570 // Update shadow stack pointer in the function epilogue.
571 IRB.SetInsertPoint(BasePointer->getNextNode());
574 IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -StaticOffset),
575 "unsafe_stack_static_top");
576 IRB.CreateStore(StaticTop, UnsafeStackPtr);
580 void SafeStack::moveDynamicAllocasToUnsafeStack(
581 Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
582 ArrayRef<AllocaInst *> DynamicAllocas) {
583 DIBuilder DIB(*F.getParent());
585 for (AllocaInst *AI : DynamicAllocas) {
588 // Compute the new SP value (after AI).
589 Value *ArraySize = AI->getArraySize();
590 if (ArraySize->getType() != IntPtrTy)
591 ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
593 Type *Ty = AI->getAllocatedType();
594 uint64_t TySize = DL->getTypeAllocSize(Ty);
595 Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
597 Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
598 SP = IRB.CreateSub(SP, Size);
600 // Align the SP value to satisfy the AllocaInst, type and stack alignments.
601 unsigned Align = std::max(
602 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()),
603 (unsigned)StackAlignment);
605 assert(isPowerOf2_32(Align));
606 Value *NewTop = IRB.CreateIntToPtr(
607 IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
610 // Save the stack pointer.
611 IRB.CreateStore(NewTop, UnsafeStackPtr);
613 IRB.CreateStore(NewTop, DynamicTop);
615 Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
616 if (AI->hasName() && isa<Instruction>(NewAI))
619 replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
620 AI->replaceAllUsesWith(NewAI);
621 AI->eraseFromParent();
624 if (!DynamicAllocas.empty()) {
625 // Now go through the instructions again, replacing stacksave/stackrestore.
626 for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
627 Instruction *I = &*(It++);
628 auto II = dyn_cast<IntrinsicInst>(I);
632 if (II->getIntrinsicID() == Intrinsic::stacksave) {
634 Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
636 II->replaceAllUsesWith(LI);
637 II->eraseFromParent();
638 } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
640 Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
642 assert(II->use_empty());
643 II->eraseFromParent();
649 bool SafeStack::runOnFunction(Function &F) {
650 DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
652 if (!F.hasFnAttribute(Attribute::SafeStack)) {
653 DEBUG(dbgs() << "[SafeStack] safestack is not requested"
654 " for this function\n");
658 if (F.isDeclaration()) {
659 DEBUG(dbgs() << "[SafeStack] function definition"
660 " is not available\n");
664 TL = TM ? TM->getSubtargetImpl(F)->getTargetLowering() : nullptr;
665 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
668 // Make sure the regular stack protector won't run on this function
669 // (safestack attribute takes precedence).
671 B.addAttribute(Attribute::StackProtect)
672 .addAttribute(Attribute::StackProtectReq)
673 .addAttribute(Attribute::StackProtectStrong);
675 AttributeSet::FunctionIndex,
676 AttributeSet::get(F.getContext(), AttributeSet::FunctionIndex, B));
681 SmallVector<AllocaInst *, 16> StaticAllocas;
682 SmallVector<AllocaInst *, 4> DynamicAllocas;
683 SmallVector<Argument *, 4> ByValArguments;
684 SmallVector<ReturnInst *, 4> Returns;
686 // Collect all points where stack gets unwound and needs to be restored
687 // This is only necessary because the runtime (setjmp and unwind code) is
688 // not aware of the unsafe stack and won't unwind/restore it prorerly.
689 // To work around this problem without changing the runtime, we insert
690 // instrumentation to restore the unsafe stack pointer when necessary.
691 SmallVector<Instruction *, 4> StackRestorePoints;
693 // Find all static and dynamic alloca instructions that must be moved to the
694 // unsafe stack, all return instructions and stack restore points.
695 findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
698 if (StaticAllocas.empty() && DynamicAllocas.empty() &&
699 ByValArguments.empty() && StackRestorePoints.empty())
700 return false; // Nothing to do in this function.
702 if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
703 !ByValArguments.empty())
704 ++NumUnsafeStackFunctions; // This function has the unsafe stack.
706 if (!StackRestorePoints.empty())
707 ++NumUnsafeStackRestorePointsFunctions;
709 IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
710 UnsafeStackPtr = getOrCreateUnsafeStackPtr(IRB, F);
712 // The top of the unsafe stack after all unsafe static allocas are allocated.
713 Value *StaticTop = moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas,
714 ByValArguments, Returns);
716 // Safe stack object that stores the current unsafe stack top. It is updated
717 // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
718 // This is only needed if we need to restore stack pointer after longjmp
719 // or exceptions, and we have dynamic allocations.
720 // FIXME: a better alternative might be to store the unsafe stack pointer
721 // before setjmp / invoke instructions.
722 AllocaInst *DynamicTop = createStackRestorePoints(
723 IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
725 // Handle dynamic allocas.
726 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
729 DEBUG(dbgs() << "[SafeStack] safestack applied\n");
733 } // anonymous namespace
735 char SafeStack::ID = 0;
736 INITIALIZE_TM_PASS_BEGIN(SafeStack, "safe-stack",
737 "Safe Stack instrumentation pass", false, false)
738 INITIALIZE_TM_PASS_END(SafeStack, "safe-stack",
739 "Safe Stack instrumentation pass", false, false)
741 FunctionPass *llvm::createSafeStackPass(const llvm::TargetMachine *TM) {
742 return new SafeStack(TM);