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 "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"
52 using namespace llvm::safestack;
54 #define DEBUG_TYPE "safestack"
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");
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");
73 /// Rewrite an SCEV expression for a memory access address to an expression that
74 /// represents offset from the given alloca.
76 /// The implementation simply replaces all mentions of the alloca with zero.
77 class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
78 const Value *AllocaPtr;
81 AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
82 : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
84 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
85 if (Expr->getValue() == AllocaPtr)
86 return SE.getZero(Expr->getType());
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
98 const TargetLoweringBase &TL;
107 Value *UnsafeStackPtr = nullptr;
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.
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 };
117 /// \brief Return the value of the stack canary.
118 Value *getStackGuard(IRBuilder<> &IRB, Function &F);
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);
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);
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);
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.
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);
150 /// \brief Generate code to restore the stack after all stack restore points
151 /// in \p StackRestorePoints.
153 /// \returns A local variable in which to maintain the dynamic top of the
154 /// unsafe stack if needed.
156 createStackRestorePoints(IRBuilder<> &IRB, Function &F,
157 ArrayRef<Instruction *> StackRestorePoints,
158 Value *StaticTop, bool NeedDynamicTop);
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);
167 bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
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);
175 SafeStack(Function &F, const TargetLoweringBase &TL, const DataLayout &DL,
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())) {}
183 // Run the transformation on the associated function.
184 // Returns whether the function was changed.
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::getStackGuard(IRBuilder<> &IRB, Function &F) {
335 Value *StackGuardVar = TL.getIRStackGuard(IRB);
338 F.getParent()->getOrInsertGlobal("__stack_chk_guard", StackPtrTy);
339 return IRB.CreateLoad(StackGuardVar, "StackGuard");
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)) {
352 uint64_t Size = getStaticAllocaAllocationSize(AI);
353 if (IsSafeStackAlloca(AI, Size))
356 if (AI->isStaticAlloca()) {
357 ++NumUnsafeStaticAllocas;
358 StaticAllocas.push_back(AI);
360 ++NumUnsafeDynamicAllocas;
361 DynamicAllocas.push_back(AI);
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");
378 for (Argument &Arg : F.args()) {
379 if (!Arg.hasByValAttr())
382 DL.getTypeStoreSize(Arg.getType()->getPointerElementType());
383 if (IsSafeStackAlloca(&Arg, Size))
386 ++NumUnsafeByValArguments;
387 ByValArguments.push_back(&Arg);
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.");
397 if (StackRestorePoints.empty())
400 // We need the current value of the shadow stack pointer to restore
401 // after longjmp or exception catching.
403 // FIXME: On some platforms this could be handled by the longjmp/exception
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);
415 // Restore current stack pointer after longjmp/exception catch.
416 for (Instruction *I : StackRestorePoints) {
417 ++NumUnsafeStackRestorePoints;
419 IRB.SetInsertPoint(I->getNextNode());
420 Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
421 IRB.CreateStore(CurrentTop, UnsafeStackPtr);
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);
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, {});
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())
457 DIBuilder DIB(*F.getParent());
459 StackColoring SSC(F, StaticAllocas);
461 SSC.removeAllMarkers();
463 // Unsafe stack always grows down.
464 StackLayout SSL(StackAlignment);
465 if (StackGuardSlot) {
466 Type *Ty = StackGuardSlot->getAllocatedType();
468 std::max(DL.getPrefTypeAlignment(Ty), StackGuardSlot->getAlignment());
469 SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot),
470 Align, SSC.getFullLiveRange());
473 for (Argument *Arg : ByValArguments) {
474 Type *Ty = Arg->getType()->getPointerElementType();
475 uint64_t Size = DL.getTypeStoreSize(Ty);
477 Size = 1; // Don't create zero-sized stack objects.
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());
485 for (AllocaInst *AI : StaticAllocas) {
486 Type *Ty = AI->getAllocatedType();
487 uint64_t Size = getStaticAllocaAllocationSize(AI);
489 Size = 1; // Don't create zero-sized stack objects.
491 // Ensure the object is properly aligned.
493 std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment());
495 SSL.addObject(AI, Size, Align, SSC.getLiveRange(AI));
499 unsigned FrameAlignment = SSL.getFrameAlignment();
501 // FIXME: tell SSL that we start at a less-then-MaxAlignment aligned location
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))),
513 IRB.SetInsertPoint(BasePointer->getNextNode());
515 if (StackGuardSlot) {
516 unsigned Offset = SSL.getObjectOffset(StackGuardSlot);
517 Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
518 ConstantInt::get(Int32Ty, -Offset));
520 IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
522 // Replace alloc with the new location.
523 StackGuardSlot->replaceAllUsesWith(NewAI);
524 StackGuardSlot->eraseFromParent();
527 for (Argument *Arg : ByValArguments) {
528 unsigned Offset = SSL.getObjectOffset(Arg);
529 Type *Ty = Arg->getType()->getPointerElementType();
531 uint64_t Size = DL.getTypeStoreSize(Ty);
533 Size = 1; // Don't create zero-sized stack objects.
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");
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());
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);
553 uint64_t Size = getStaticAllocaAllocationSize(AI);
555 Size = 1; // Don't create zero-sized stack objects.
557 replaceDbgDeclareForAlloca(AI, BasePointer, DIB, /*Deref=*/false, -Offset);
558 replaceDbgValueForAlloca(AI, BasePointer, DIB, -Offset);
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());
567 Instruction *InsertBefore;
568 if (auto *PHI = dyn_cast<PHINode>(User))
569 InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
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);
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);
590 AI->eraseFromParent();
593 // Re-align BasePointer so that our callees would see it aligned as
595 // FIXME: no need to update BasePointer in leaf functions.
596 unsigned FrameSize = alignTo(SSL.getFrameSize(), StackAlignment);
598 // Update shadow stack pointer in the function epilogue.
599 IRB.SetInsertPoint(BasePointer->getNextNode());
602 IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -FrameSize),
603 "unsafe_stack_static_top");
604 IRB.CreateStore(StaticTop, UnsafeStackPtr);
608 void SafeStack::moveDynamicAllocasToUnsafeStack(
609 Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
610 ArrayRef<AllocaInst *> DynamicAllocas) {
611 DIBuilder DIB(*F.getParent());
613 for (AllocaInst *AI : DynamicAllocas) {
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);
621 Type *Ty = AI->getAllocatedType();
622 uint64_t TySize = DL.getTypeAllocSize(Ty);
623 Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
625 Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
626 SP = IRB.CreateSub(SP, Size);
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);
633 assert(isPowerOf2_32(Align));
634 Value *NewTop = IRB.CreateIntToPtr(
635 IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
638 // Save the stack pointer.
639 IRB.CreateStore(NewTop, UnsafeStackPtr);
641 IRB.CreateStore(NewTop, DynamicTop);
643 Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
644 if (AI->hasName() && isa<Instruction>(NewAI))
647 replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/false);
648 AI->replaceAllUsesWith(NewAI);
649 AI->eraseFromParent();
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);
660 if (II->getIntrinsicID() == Intrinsic::stacksave) {
662 Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
664 II->replaceAllUsesWith(LI);
665 II->eraseFromParent();
666 } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
668 Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
670 assert(II->use_empty());
671 II->eraseFromParent();
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");
684 SmallVector<AllocaInst *, 16> StaticAllocas;
685 SmallVector<AllocaInst *, 4> DynamicAllocas;
686 SmallVector<Argument *, 4> ByValArguments;
687 SmallVector<ReturnInst *, 4> Returns;
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;
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,
701 if (StaticAllocas.empty() && DynamicAllocas.empty() &&
702 ByValArguments.empty() && StackRestorePoints.empty())
703 return false; // Nothing to do in this function.
705 if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
706 !ByValArguments.empty())
707 ++NumUnsafeStackFunctions; // This function has the unsafe stack.
709 if (!StackRestorePoints.empty())
710 ++NumUnsafeStackRestorePointsFunctions;
712 IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
713 UnsafeStackPtr = TL.getSafeStackPointerLocation(IRB);
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);
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);
730 for (ReturnInst *RI : Returns) {
731 IRBuilder<> IRBRet(RI);
732 checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
736 // The top of the unsafe stack after all unsafe static allocas are
739 moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, ByValArguments,
740 Returns, BasePointer, StackGuardSlot);
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());
751 // Handle dynamic allocas.
752 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
755 // Restore the unsafe stack pointer before each return.
756 for (ReturnInst *RI : Returns) {
757 IRB.SetInsertPoint(RI);
758 IRB.CreateStore(BasePointer, UnsafeStackPtr);
761 DEBUG(dbgs() << "[SafeStack] safestack applied\n");
765 class SafeStackLegacyPass : public FunctionPass {
766 const TargetMachine *TM;
769 static char ID; // Pass identification, replacement for typeid..
770 SafeStackLegacyPass(const TargetMachine *TM) : FunctionPass(ID), TM(TM) {
771 initializeSafeStackLegacyPassPass(*PassRegistry::getPassRegistry());
774 SafeStackLegacyPass() : SafeStackLegacyPass(nullptr) {}
776 void getAnalysisUsage(AnalysisUsage &AU) const override {
777 AU.addRequired<TargetLibraryInfoWrapperPass>();
778 AU.addRequired<AssumptionCacheTracker>();
781 bool runOnFunction(Function &F) override {
782 DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
784 if (!F.hasFnAttribute(Attribute::SafeStack)) {
785 DEBUG(dbgs() << "[SafeStack] safestack is not requested"
786 " for this function\n");
790 if (F.isDeclaration()) {
791 DEBUG(dbgs() << "[SafeStack] function definition"
792 " is not available\n");
797 report_fatal_error("Target machine is required");
798 auto *TL = TM->getSubtargetImpl(F)->getTargetLowering();
800 report_fatal_error("TargetLowering instance is required");
802 auto *DL = &F.getParent()->getDataLayout();
803 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
804 auto &ACT = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
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.
815 ScalarEvolution SE(F, TLI, ACT, DT, LI);
817 return SafeStack(F, *TL, *DL, SE).run();
821 } // anonymous namespace
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)
829 FunctionPass *llvm::createSafeStackPass(const llvm::TargetMachine *TM) {
830 return new SafeStackLegacyPass(TM);